-
Notifications
You must be signed in to change notification settings - Fork 39
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Implement Grover's Algorithm using Lightning-Qubit's C++ API #980
Open
jzaia18
wants to merge
19
commits into
PennyLaneAI:master
Choose a base branch
from
jzaia18:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 7 commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
0337eb3
Get build system working to compile against C++ API
jzaia18 1a78bf0
Fully working implementation of Grover's
jzaia18 906974e
Introduce extra large 3rd oracle
jzaia18 d8e57f7
Merge branch 'PennyLaneAI:master' into master
jzaia18 48dea6c
Implement identical algo to C++ impl with python+pennylane
jzaia18 3b54a2a
Add benchmarking code to both C++ and python impls
jzaia18 5203b82
Merge branch 'master' into master
AmintorDusko 1d658fb
Change result extraction to use functional programming style
jzaia18 5057894
Improve application of oracles by condensing into 1 function
jzaia18 8875449
Merge branch 'master' of github.com:jzaia18/pennylane-lightning
jzaia18 aa94a18
Add custom directory to format target, and format files
jzaia18 915ff6d
Merge branch 'master' into master
AmintorDusko e466e97
Fix comment rot on oracle function
jzaia18 65a3eef
Merge branch 'master' of github.com:jzaia18/pennylane-lightning
jzaia18 8bd1f93
Fix type mismatch caused by attempt to unpack tensor as a numpy object
jzaia18 0066b3b
Change loop over grover repetitions to forward iterations
jzaia18 ff86a5e
Refactor macros for oracle definitions into global consts
jzaia18 ca6634c
Condense creation of results vector into a single STL function call, …
jzaia18 a5ecaa0
Formatting changes to Python impl to please code-coverage plugin
jzaia18 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
project(lightning_demo LANGUAGES CXX) | ||
add_executable(lq_grover main.cpp) | ||
target_include_directories(lq_grover PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) | ||
target_link_libraries(lq_grover lightning_qubit | ||
lightning_qubit_observables | ||
lightning_qubit_measurements | ||
lightning_qubit_gates | ||
lightning_gates | ||
lq_gates_kernel_map | ||
lq_gates_register_kernels_x64 | ||
) | ||
|
||
# Unsure if this is the best way to include the necessary gate implementations | ||
target_include_directories(lq_grover PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../pennylane_lightning/core/src/simulators/lightning_qubit/gates/cpu_kernels/) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,130 @@ | ||
import numpy as np | ||
import pennylane as qml | ||
|
||
# Define oracles | ||
ORACLE1_QUBITS = 6 | ||
ORACLE1_EXPECTED = [1, 1, 0, 1, 0] | ||
|
||
ORACLE2_QUBITS = 10 | ||
ORACLE2_EXPECTED = [1, 0, 1, 0, 1, 0, 1, 0, 1] | ||
|
||
ORACLE3_QUBITS = 17 | ||
ORACLE3_EXPECTED = [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1] | ||
|
||
ORACLES = [(ORACLE1_QUBITS, ORACLE1_EXPECTED), | ||
(ORACLE2_QUBITS, ORACLE2_EXPECTED), | ||
(ORACLE3_QUBITS, ORACLE3_EXPECTED)] | ||
|
||
|
||
def grovers_setup(num_qubits: int): | ||
''' | ||
Setup up a circuit for iterations of Grover's search | ||
|
||
Places a circuit into uniform superposition. Additionally, places the | ||
ancilla qubit for the oracle in the |-> state such that it can | ||
apply phase kickback. | ||
|
||
:param num_qubits: The number of qubits in the circuit | ||
''' | ||
qml.X(num_qubits-1) | ||
for i in range(num_qubits): | ||
qml.Hadamard(wires=i) | ||
|
||
def grovers_mirror(num_qubits): | ||
''' | ||
Apply the "Grover's Mirror" reflection to the active circuit | ||
|
||
Performs a reflection across the vector which represents the uniform | ||
superposition. This is used for amplitude-amplification for Grover's | ||
algorithm. | ||
|
||
:param num_qubits: The number of qubits in the circuit | ||
''' | ||
for i in range(num_qubits-1): | ||
qml.Hadamard(wires=i) | ||
|
||
qml.MultiControlledX(wires=range(num_qubits), | ||
control_values=[False]*(num_qubits-1)) | ||
|
||
for i in range(num_qubits-1): | ||
qml.Hadamard(wires=i) | ||
|
||
def run_grovers(oracle, num_qubits): | ||
''' | ||
Overall function for running Grover's algorithm on a chosen oracle | ||
|
||
Run Grover's algorithm from start to finish. Prepares a state, and | ||
repeats state selection and amplitude-amplification for sqrt(N) iterations | ||
(where N = 2^(# of non-ancilla qubits)). This implementation assumes that | ||
the oracle always picks precisly 1 state (rather than an arbitrary number). | ||
|
||
:param oracle: A black-box function that acts on a created statevector | ||
:param num_qubits: The number of qubits in the circuit the oracle acts | ||
on (includes the ancilla) | ||
''' | ||
grovers_setup(num_qubits) | ||
|
||
reps = int(np.sqrt(2**(num_qubits-1))) | ||
for _ in range(reps): | ||
oracle() | ||
grovers_mirror(num_qubits) | ||
|
||
return [qml.expval(qml.PauliZ(i)) for i in range(num_qubits-1)] | ||
|
||
def run_experiment(oracle, num_qubits) -> None: | ||
''' | ||
Run Grover's algorithm and evaluates results | ||
|
||
Run Grover's algorithm from start to finish, and finds the expected | ||
measurement outcome. | ||
|
||
:param oracle: A black-box function that acts on a created statevector | ||
:param num_qubits: The number of qubits in the circuit the oracle acts | ||
on (includes the ancilla) | ||
''' | ||
dev = qml.device('lightning.qubit', wires=num_qubits) | ||
|
||
|
||
circ = qml.QNode(run_grovers, dev) | ||
|
||
expvals = circ(oracle, num_qubits) | ||
results = [int(val.numpy() < 0) for val in expvals] | ||
|
||
print(results) | ||
|
||
def gen_oracle(i): | ||
''' | ||
Create an oracle function which selects the state given by the global const | ||
|
||
:param i: The index of the globally defined pair of constants to use | ||
''' | ||
num_qubits = ORACLES[i][0] | ||
control_vals = ORACLES[i][1] | ||
def oracle(): | ||
qml.MultiControlledX(wires=range(num_qubits), | ||
control_values=control_vals) | ||
return (oracle, num_qubits) | ||
|
||
|
||
if __name__ == '__main__': | ||
import cProfile | ||
import time | ||
|
||
# Dummy run to let the interpreter run all functions once | ||
run_experiment(*gen_oracle(0)) | ||
|
||
def main(): | ||
times = [] | ||
# Run all experiments | ||
for i in range(len(ORACLES)): | ||
print('Expecting:', ORACLES[i][1]) | ||
print('Got:') | ||
start_time = time.time() | ||
run_experiment(*gen_oracle(i)) | ||
times.append(time.time() - start_time) | ||
print() | ||
|
||
for i in range(len(times)): | ||
print(f'Time to run oracle {i+1}: {int(1000*times[i])}ms') | ||
|
||
cProfile.run('main()', sort='cumtime') |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The use of
.numpy()
suggests that you are running your code with Torch or Tensorflow, for example. Is this the case?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It shouldn't be. The python virtualenv I'm using does not have tensorflow nor torch installed. The return type I was getting from running the circuit was a list of
pennylane.numpy.tensor.tensor
. All of these tensors are 0-dimensional so I used.numpy()
to convert these to a scalar value.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If I take your python file
grover.py
and run, as it is, in a fresh environment with Python 3.10, where I only installed requirements-dev.txt, I'm getting the following error message:Would you know why?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
After you make all sensible updates, could you please re-run your benchmarks in a new and fresh environment?
Please let us know about your results.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Okay, I'm seeing this too. It seems the issue was that I originally installed my dependencies from
requirements.txt
instead ofrequirements-dev.txt
. It seems there are only a few differences, but namely the dev version installs Pennylane from source, so this is almost certainly related to that. Fixed in 8bd1f93