-
Notifications
You must be signed in to change notification settings - Fork 627
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
Add support for arbitrary linear combination gradient recipes #909
Conversation
Codecov Report
@@ Coverage Diff @@
## master #909 +/- ##
==========================================
- Coverage 97.89% 97.88% -0.02%
==========================================
Files 147 147
Lines 10069 10100 +31
==========================================
+ Hits 9857 9886 +29
- Misses 212 214 +2
Continue to review full report at Codecov.
|
Thanks @antalszava! I think this is going in the right direction, but I think it needs to be even more general than this. For example, rather than thinking about positive shifts and negative shifts, we want to simply provide a framework for defining gradient recipes that are arbitrary linear combinations. For example, say a gate has the gradient recipe grad_recipe = [(0.1, 5), (-0.65, -pi), (1.2, 0.2)] That is, the grad recipe should be of the form Question: we could go even further, and support grad recipes of the form # corresponds to 0.1*f(x+5) - 0.65*f(2x-pi) + 1.2*f(0.2)
grad_recipe = [(0.1, 1, 5), (-0.65, 2, -pi), (1.2, 0, 0.2)] Another question: Do we want the grad recipe to be a function? For example, if a gradient recipe has a degree of freedom, we could easily represent this: # corresponds to [f(x+s) - f(x-s)] / 2sin(s)
grad_recipe = lambda s: [(1/(2*sin(s)), 1, s), (1/(2*sin(s)), 1, -s)] |
for c, res in zip(coeffs, results): | ||
shifted = np.array(res) | ||
# stat += c * shifted | ||
np.add(stat, c * shifted, out=stat, casting="unsafe") |
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 workaround proposed by numpy/numpy#7225 (comment).
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.
🤔 I'm guessing this is because c
has a dtype that is causing casting issues?
Would it be better to simply cast/ensure that c
and shifted
are the correct dtype?
Hi @josh146, thanks for the suggestions! Eventually went with
After checking with Tom and Juan Miguel, this would be motivated by works with quantum channels. There, we'd like to have the ability to specify something like Notes on the current version:
Updating the docstrings, the documentation as well as revisiting parts of the code for refactoring purposes remain as TODO (thought first it's worth for you to see if this would something that fits our case). |
The coverage report of the files where there was addition/deletion:
The missing lines do not seem to be affected by this PR and Codecov doesn't seem to list where the drop would have occured. |
The following specific case holds for example for qubit operations that are | ||
generated by one of the Pauli matrices and results in an overall positive and | ||
negative shift: |
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.
Very nice way of putting this! I find it very clear to read and understand.
Co-authored-by: Tom Bromley <[email protected]>
… into multiple_shifts
Thanks so much for the comments @trbromley! Updated the formulae and further docs based on your suggestions. Thanks, @josh146 for merging the qubit case in here! |
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.
💯
.github/CHANGELOG.md
Outdated
* Updated how gradient recipes are stored for operations, allowing for | ||
gradient recipe definitions involving custom multipliers and with more than | ||
two terms. | ||
[(#909)](https://github.com/PennyLaneAI/pennylane/pull/909) |
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.
* Updated how gradient recipes are stored for operations, allowing for | |
gradient recipe definitions involving custom multipliers and with more than | |
two terms. | |
[(#909)](https://github.com/PennyLaneAI/pennylane/pull/909) | |
* Updated how parameter-shift gradient recipes are defined for operations, allowing for | |
gradient recipes that are specified as an arbitrary number of terms. | |
[(#909)](https://github.com/PennyLaneAI/pennylane/pull/909) | |
Previously, `Operation.grad_recipe` was restricted to two-term parameter-shift formulas. | |
With this change, the gradient recipe now contains elements of the form | |
$[c_i, a_i, s_i]$, resulting in a gradient recipe of | |
$$\frac{\partial}{\partial\phi_k}f(\phi_k) = \sum_{i} c_i * f(a_i * \phi_k+s_i).$$ | |
As this is a breaking change, all custom operations with defined gradient recipes must be | |
updated to continue working with PennyLane 0.13. Note though that if `grad_recipe = None`, the | |
default gradient recipe remains unchanged, and corresponds to the two terms $[c_0, a_0, s_0]=[1/2, 1, \pi/2]$ | |
and $[c_1, a_1, s_1]=[-1/2, 1, -\pi/2]$ for every parameter. |
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.
Thought it was best to add some more details! Might have to double check that the math renders correctly.
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.
Thanks! Checked and updated.
Update: enclosing with $$
didn't seem to work, added it with <img src="https://render.githubusercontent.com/render/math?math=">
.
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.
Awesome work, thanks @antalszava 💯
Co-authored-by: Tom Bromley <[email protected]>
… into multiple_shifts
…aneAI#909) * Have positive and negative multiplier and shift values * No print * Formatting * 3 element terms for grad_recipes; qubit okay; CV draft * CV for tape mode * Comments * Remove unused * Formatting * Solve casting by specifying dtype at creation * No casting needed for shifted * Update module docstring and Operation.grad_recipe docstring * Development guide update * Wording * Adding tests; adding error raised for unsupported logic for tape second-order CV case * No f strings * Update pennylane/qnodes/cv.py Co-authored-by: Josh Izaac <[email protected]> * Update pennylane/tape/tapes/cv_param_shift.py * Simplify using np.dot in CV param shift tape * Update tests/qnodes/test_qnode_cv.py Co-authored-by: Josh Izaac <[email protected]> * get_parameter_shift in tape mode as per Josh's suggestion; use that * Changelog * Update tests/tape/tapes/test_cv_param_shift.py Co-authored-by: Josh Izaac <[email protected]> * Update .github/CHANGELOG.md Co-authored-by: Tom Bromley <[email protected]> * merge in changes from 915 * Update pennylane/operation.py Co-authored-by: Tom Bromley <[email protected]> * Update grad recipe formulae as per Tom's suggestions * Update other formula in comment * CHANGELOG * Add rendering img url approach * Plus * Update pennylane/operation.py Co-authored-by: Tom Bromley <[email protected]> * Applying review suggestions * Update doc/development/plugins.rst * Update pennylane/operation.py * equation formatting fixes Co-authored-by: Josh Izaac <[email protected]> Co-authored-by: Tom Bromley <[email protected]>
* Test for comparing different devices with the default device * Update test_compare_default_qubit.py with the suggestions of Pennylane team * Test for comparing different devices with the default device * Update test_compare_default_qubit.py with the suggestions of Pennylane team * Enable tape mode in tests (#859) * backup * add fixture * polish * polish2 * Update tests/templates/test_integration.py * add execution property to Device class for tracking the number of device executions over a QNodes lifetime (#853) * add execution property to Device class for tracking the number of device executions over a QNodes lifetime, add unit tests for tracking device executions * reformat files with black, update execution to num_executions, reformat existing exceptions, update num_executions docstring * Fix typo in test_device_executions docstring Co-authored-by: Nathan Killoran <[email protected]> * move _num_executions counter to execute() method for _device and _qubit_device, move corresponding unit tests to appropriate locations * update CHANGELOG.md to include num_executions * Add Anthony Hayes to list of contributers in CHANGEOG.md Co-authored-by: Maria Schuld <[email protected]> Co-authored-by: Nathan Killoran <[email protected]> Co-authored-by: Tom Bromley <[email protected]> * Adds handling of single-qubit Paulis and all-identity Pauli to PauliRot operation. (#860) * Fix PauliRot to work for single-qubit case with int-specified wire. * Fix matrix construction for all-identity Pauli. * Ensure PauliRot decomposition handles all-identity case. * Adds tests for single-qubit PauliRot matrix, and identity decomp. * Updated changelog. * Removed single-qubit matrix test since this was not the original single-qubit issue. * Added PR link to changelog. * Run black formatting. * Run black through command line. * Update .github/CHANGELOG.md Co-authored-by: antalszava <[email protected]> * Reverted stuff that was reformatted by emacs black. * Fixes decomposition to also handle integer wires. * Update codecov.yml * Fixed eigvals to work for all-identity case, and updated tests. Co-authored-by: Olivia Di Matteo <[email protected]> Co-authored-by: antalszava <[email protected]> Co-authored-by: Josh Izaac <[email protected]> * Updating collections and VQECost to work in tape mode (#863) * backup * add fixture * polish * polish2 * Update tests/templates/test_integration.py * [WIP] Updating collections to work in tape mode * more * black and linting * skip test with race condition * Add VQECost support * add more tests * update changelog * Update pennylane/collections/map.py * Update pennylane/tape/__init__.py * suggested changes * suggested changes Co-authored-by: Maria Schuld <[email protected]> * Build many-body observables in PL-QChem using FermionOperator data structure (#854) * Modify the 'observable' function to build PL observables from a list of FermionOperators * Modify unit tests for the 'observable' function * Modify functions 'one_particle' and 'two_particle' to build FermionOperators * Modify unit tests for 'one_particle' function * Polish 'one_particle' and 'two_particle' functions * Modify unit test for the 'two_particle' and 'one_particle' functions * Add missing contribution due to core orbitals to the 'two_particle' function * Modify unit tests for 'two_particle' function * Update 'CHANGELOG.md' * Remove trailing spaces * Update 'CHANGELOG.md' * Polish docstrings * Apply suggestions from code review * Polsih the docstring of 'observable' * Adds basic resource estimation to quantum tapes. (#862) * Adds resource estimation and depth to quantum tape. (Untested.) * Fixed depth calculation to include only observables. Added tests. * Add new feature to changelog. * Run black. * Change accessing of graph to satisfy CodeFactor. * Update pennylane/tape/circuit_graph.py Co-authored-by: Nathan Killoran <[email protected]> * Update pennylane/tape/circuit_graph.py Co-authored-by: Josh Izaac <[email protected]> * Update pennylane/tape/tapes/tape.py Co-authored-by: Josh Izaac <[email protected]> * Added usage examples to code doc strings. * Fixed typo. * Replaced truncated graph by operation subgraph. * Full replacement of truncated graph with operation graph. * Change default values of depth to None, adjust tests. * Update .github/CHANGELOG.md Co-authored-by: Josh Izaac <[email protected]> * Update pennylane/tape/circuit_graph.py Co-authored-by: Josh Izaac <[email protected]> * Update pennylane/tape/circuit_graph.py Co-authored-by: Josh Izaac <[email protected]> * Switch from properties to methods for resource estimation. * Update pennylane/tape/circuit_graph.py Co-authored-by: Josh Izaac <[email protected]> Co-authored-by: Olivia Di Matteo <[email protected]> Co-authored-by: Nathan Killoran <[email protected]> Co-authored-by: Josh Izaac <[email protected]> * Updating qnn.TorchLayer to work in tape mode (#865) * backup * add fixture * polish * polish2 * Update tests/templates/test_integration.py * [WIP] Updating collections to work in tape mode * more * black and linting * skip test with race condition * Add VQECost support * add more tests * Updating qnn.TorchLayer to work in tape mode * update changelog * fixes * fixes * Apply suggestions from code review Co-authored-by: Tom Bromley <[email protected]> Co-authored-by: Maria Schuld <[email protected]> Co-authored-by: Tom Bromley <[email protected]> Co-authored-by: Nathan Killoran <[email protected]> * Updating qnn.KerasLayer to work in tape mode (#869) * Update qnn.keras for tape mode * Add tape mode evaluate * Work on tests * Update qnode * Tests working * Update changelog * Fix weird behaviour * Remove extra attribute * Add support for backprop * Apply suggestions from code review Co-authored-by: Josh Izaac <[email protected]> * Apply suggestions * merge master Co-authored-by: Nathan Killoran <[email protected]> Co-authored-by: Josh Izaac <[email protected]> * Make caching compatible with batch execution (#851) * dummy change * rewrite num_diff method internally * undo dummy change needed to open pr * more * use deep copy * rewrite param shift method * more * more * backup * polish param shift method * docs * backup * typos * backup * make postprocessing of finite diff depend on order * fix operation copies * backup * attempt to fix tests * fixing tests * temporarily fix copying * finish param shift var * blacking the code * blacking the code * pylint * fix black * fix black * test black * black * fix function naming * all bugs fixed but inverse * Revert "fix function naming" This reverts commit c8eb906. * struggling with tape construction using inverse gates * try to get reversible to work * reversible tape working * refactor cv param shift (expval) method * remove middle functions in cv param shift -> now variance test failing to call them * port CV var * linting * basic rewrite of jacobian loop * rewrite jacobian loop * test jacobian tape passing * working parameter shift tests * CV tests passing * reversible tape working * all tests passing * linting * use a flat tape list * black * add batch_execute functions to device and qubit_device * black * backup * docstrings * remove deepcopying (#845) * polish * docstrings * polishing * linting * Update pennylane/operation.py Co-authored-by: Nathan Killoran <[email protected]> * Update pennylane/operation.py Co-authored-by: Nathan Killoran <[email protected]> * Update pennylane/tape/tapes/qubit_param_shift.py Co-authored-by: Nathan Killoran <[email protected]> * Update pennylane/tape/tapes/reversible.py Co-authored-by: Nathan Killoran <[email protected]> * make tests pass * add test for batch_execute * polish * polish2 * skip tests if interface not imported * fix test * Update pennylane/_device.py Co-authored-by: Josh Izaac <[email protected]> * update copy semantics * Josh review * Update pennylane/tape/tapes/reversible.py Co-authored-by: Nathan Killoran <[email protected]> * more * suggested changes * suggested changes * Update pennylane/tape/tapes/reversible.py Co-authored-by: Nathan Killoran <[email protected]> * suggested changes * added copying tests * more copying tests * another test * Update pennylane/tape/tapes/reversible.py * Update pennylane/tape/tapes/cv_param_shift.py Co-authored-by: Nathan Killoran <[email protected]> * backup * reset fix implemented, still 4 cache tests not passing * backup * improve tests * Use caching in device * polisg * Add argument * Update devs * Fix jacobian tape * Fix tests * Remove extra test * Only allow caching in tape mode * Update test docstring * Move * Update tests * Prevent use in backprop mode * Update changelog * Update TODO * Update docstring * Apply black * Fix test * Apply black * Remove tests and update docstrings * Update changelog * Minor improvements * Remove unused import * Remove mention of caching in changelog * Apply suggestions from code review Co-authored-by: Nathan Killoran <[email protected]> * Update changelog * Rename caching to cache in qubit device * Rename caching to cache * Remove extra methods * Update docstrings * Apply suggestion * Remove extra caching line Co-authored-by: Maria Schuld <[email protected]> Co-authored-by: Josh Izaac <[email protected]> Co-authored-by: Nathan Killoran <[email protected]> Co-authored-by: antalszava <[email protected]> * Add the sqrt X gate (#871) * Add the sqrt X (SX) gate Issue #868 * Add inverse and fix docs spacing inverse still isn't testing correctly * fixing matrix vrs _matrix * edit changelog * edit changelog * grammar fix Co-authored-by: Josh Izaac <[email protected]> * another typo Co-authored-by: antalszava <[email protected]> * switch decomposition order * Update .github/CHANGELOG.md Co-authored-by: Tom Bromley <[email protected]> * Update .github/CHANGELOG.md Co-authored-by: Tom Bromley <[email protected]> * Apply suggestions from code review Co-authored-by: antalszava <[email protected]> Co-authored-by: Josh Izaac <[email protected]> * add to default_mixed, test default_qubit, test decomposition * Update .github/CHANGELOG.md Co-authored-by: Josh Izaac <[email protected]> Co-authored-by: antalszava <[email protected]> Co-authored-by: Tom Bromley <[email protected]> * Small update in DisplacementEmbedding docstring (#879) * Update displacement.py * Update pennylane/templates/embeddings/displacement.py Co-authored-by: Josh Izaac <[email protected]> Co-authored-by: Maria Schuld <[email protected]> Co-authored-by: Josh Izaac <[email protected]> * Update the templates quickstart (#880) * default_qubit to use the hard-coded inverses (#872) * default_qubit to use the hard-coded inverses Issue #870 * Add to changelog Co-authored-by: antalszava <[email protected]> Co-authored-by: Tom Bromley <[email protected]> * Add representation to MeasurementProcess (#883) * add repr method * fix a test * polish * Update pennylane/tape/measure.py Co-authored-by: Josh Izaac <[email protected]> * Update pennylane/tape/measure.py Co-authored-by: Josh Izaac <[email protected]> * Use dense matrices in mottonen state preparation (#864) * backup * refactor * refactor complete * add angle equation * polish * polish * simplify code more * black * polish equation * Update pennylane/templates/state_preparations/mottonen.py * Update pennylane/templates/state_preparations/mottonen.py * Update pennylane/templates/state_preparations/mottonen.py * reverse wires * docstrings * backup * update qasm * make all test run * docstring polish * backup * make tests pass * black * typo * one more typo * delete unused import * Update pennylane/templates/state_preparations/mottonen.py Co-authored-by: Olivia Di Matteo <[email protected]> * Update pennylane/templates/state_preparations/mottonen.py Co-authored-by: Olivia Di Matteo <[email protected]> * Update pennylane/templates/state_preparations/mottonen.py Co-authored-by: Olivia Di Matteo <[email protected]> * polish * Update pennylane/templates/state_preparations/mottonen.py Co-authored-by: Olivia Di Matteo <[email protected]> * Update tests/templates/test_state_preparations.py Co-authored-by: Nathan Killoran <[email protected]> * Update pennylane/templates/state_preparations/mottonen.py Co-authored-by: Nathan Killoran <[email protected]> * Update pennylane/templates/state_preparations/mottonen.py Co-authored-by: Josh Izaac <[email protected]> * speed up theta * black * Update pennylane/templates/state_preparations/mottonen.py Co-authored-by: Olivia Di Matteo <[email protected]> * black * update changelog Co-authored-by: Olivia Di Matteo <[email protected]> Co-authored-by: Nathan Killoran <[email protected]> Co-authored-by: Josh Izaac <[email protected]> * Update jacobian_tape.py (#891) * AngleEmbedding fewer features than qubits temp func (#881) * Test for AngleEmbedding where there are fewer features than qubits * Adjust * Temp func for no shape check broadcast * Docstring * TODO * format * just limit wires * black * check_shape Returns in docstring Co-authored-by: Maria Schuld <[email protected]> * Fixes bug where binary operations on PennyLane tensors results in an incorrect requires_grad attribute (#889) * Fixes bug where binary operations on PennyLane tensors resulted in an incorrect requires_grad attribute * linting * linting * more * more * more * more * final bug quashing * remove prints * suggested changes Co-authored-by: Maria Schuld <[email protected]> * Support returning commuting observables on the same wire (#882) * Prevent multiple observables on one wire * Add test * Add to changelog * Update changelog * Prevent variances as well * Fix test * Fix test * Fix typo * Update changelog * Prevent sampling on same wire * Add prototype version * Add test * Remove constant * Integrate expand in qubit device * Add to expand_tape * Revert qnode changes * Update naming * Only expand when needed * Remove test from qnode * Add to test * Correct changelog * Update changelog * Remove strict checks * Add comment * Add error * Update tests * Prevent expanding in qnode if using qubit device: * Run black * Revert qubit device * Move functionality to qnode * Move tests * Update tests * Update spacing * Run black * Fix tests * Revert qubit dev * Only expand observables if they share a wire * Only expand observables that share a wire * Fix tests * Apply isort * Fix isort * Apply suggestions from code review * parametrize test * Fix CI checks: * Actually fix CI * Update test * Factor out to a method * Fix test * Remove new line * Minor updates * Change variable name * Update docstring * Add hardware-efficient particle-conserving ansatz U1 (#875) * Add the ParticleConservingU1 template * Add checks to 'ParticleConservingU1' template * Add check to 'ParticleConservingU1' template * Import the new template and add it to the documentation * Remove trailing space * Fix typo in the docstring * Add functions to generate initial parameters for the 'ParticleConservingU1' template * Remove trailing whitespaces * Add unit test for ParticleConservingU1 template * Add comments in the unit test * Polish unit test * Complete unit test 'test_particle_conserving_u1_operations' * Remove qchem dependency from the unit test * Add test 'test_particle_conserving_u1_exceptions' * Add test 'test_integration' * Remove print line * Add functions 'particle_conserving_u1_normal' and 'particle_conserving_u1_uniform' to INIT_KWARGS_SHAPES in 'test_init.py' * Add unit tests for the functions 'particle_conserving_u1_uniform' and 'particle_conserving_u1_normal' * Improve unit tests for 'particle_conserving_u1_uniform` and particle_conserving_u1_normal' * Polish docstrings * Add 'ParticleConservingU1' template to the integration tests * Improve on the docstrings * Remove trailing space * Improve on the docstrings and update 'CHANGELOG.md' * Polish docstrings * Reduce size of figures in the docstring * Reduce size of image in the docstring * Scale image * Add link to PL's operations page * Polish docstring * Apply suggestions from code review Co-authored-by: Maria Schuld <[email protected]> * Apply suggestions from code review * Remove 'check_type' import * Adjust size of figure * Adjust thumbnail image size * Adjust aspect ratio of thumbnail figure * Scale thumbnail * Add new thumbnail * Apply suggestions from code review Co-authored-by: Maria Schuld <[email protected]> * Apply suggestions from code review * Increase slightly the size of the figures * Adjust size of the figures * Apply suggestions from code review Co-authored-by: ixfoduap <[email protected]> * Apply suggestions from code review * Apply suggestions from code review * Add new function to test the decomposition of U1ex * Polish 'test_decomposition_u1ex' * Apply suggestions from code review Co-authored-by: antalszava <[email protected]> Co-authored-by: ixfoduap <[email protected]> * Apply suggestions from code review * Fix identation in the docstring * Polish docstring * Polish docstring Co-authored-by: Maria Schuld <[email protected]> Co-authored-by: ixfoduap <[email protected]> Co-authored-by: antalszava <[email protected]> * Unwrap tensor in random_layer (#893) * Unwrap in random_layer if necessary; add test * Docstring, default.qubit * Test unwrapped gradient; update docstring * Docstring * Add qml.density_matrix QNode return with partial trace capabilities (#878) * First implementation of density matrix for the default_qubit device * Update with first tests. * Black formatting. * Correct default.qubit, add default.mixed and add tests. * Unecessary enable tape removed * Update pennylane/_qubit_device.py Co-authored-by: Josh Izaac <[email protected]> * Update pennylane/_qubit_device.py Co-authored-by: Josh Izaac <[email protected]> * Update pennylane/_qubit_device.py Co-authored-by: Josh Izaac <[email protected]> * Update pennylane/devices/default_mixed.py Co-authored-by: Josh Izaac <[email protected]> * Update tests/tape/test_tape_measure.py Co-authored-by: Josh Izaac <[email protected]> * Update pennylane/devices/default_mixed.py Co-authored-by: Josh Izaac <[email protected]> * Update tests/tape/test_tape_measure.py Co-authored-by: Josh Izaac <[email protected]> * Update tests/tape/test_tape_measure.py Co-authored-by: Josh Izaac <[email protected]> * Update tests/tape/test_tape_measure.py Co-authored-by: Josh Izaac <[email protected]> * Changes from review * Add test for all wires (density matrix) * Better coverage * Update changelod.md * Update from second review. * Blank line changelog * Update changelog * Update .github/CHANGELOG.md Co-authored-by: Josh Izaac <[email protected]> * Update from third review * Update pennylane/tape/measure.py Co-authored-by: Tom Bromley <[email protected]> * Update pennylane/devices/default_mixed.py Co-authored-by: Tom Bromley <[email protected]> * Update pennylane/devices/default_qubit.py Co-authored-by: Tom Bromley <[email protected]> * Add density_matrix to tape.__init__ Co-authored-by: Josh Izaac <[email protected]> Co-authored-by: antalszava <[email protected]> Co-authored-by: Tom Bromley <[email protected]> * Adding functions for agnostic tensor manipulations (#886) * [WIP] Adding a container class for unified array manipulations * linting * fix docs * add tests * linting * add autograd tests * add autograd tests * add torch tests * add tf tests * full coverage * docstring * Apply suggestions from code review * changes * Change to functional approach * add more docstrings * fix docs * linting * coverage * finish tests * Apply suggestions from code review Co-authored-by: Nathan Killoran <[email protected]> * fix typos * Apply suggestions from code review Co-authored-by: Nathan Killoran <[email protected]> * bug fix * Apply suggestions from code review Co-authored-by: Nathan Killoran <[email protected]> Co-authored-by: Maria Schuld <[email protected]> * Update pennylane/tensorbox/tensorbox.py Co-authored-by: Nathan Killoran <[email protected]> * suggested changes * suggested changes * change * update changelog Co-authored-by: Nathan Killoran <[email protected]> Co-authored-by: Maria Schuld <[email protected]> * Add tensor unwrapping in BaseQNode for keyword arguments (#903) * Fix in BaseQNode * Add staticmethod for unwrapping (codefactor); remove import * Change to check that spots init_state difference earlier * CHANGELOG * Update * Use recorder to check gates used * Test docstrings * Fix gradient in tape mode when measurements are independent of a parameter (#901) * Fix batch execution for parameters that are independent of observable * Add test * Remove extra indent * Fixes #709 (#899) * Fixes #709 * Conform to PEP8 * Fixes formatting using black * * Added a conditional test for a GPU enabled environment * Added changelog/contribution. * Fixed also for the tape mode * Fixes a condition to run a CUDA related test * Fixes a bug in test * Update .github/CHANGELOG.md Co-authored-by: Tom Bromley <[email protected]> * Update tests/qnn/test_qnn_torch.py Co-authored-by: Tom Bromley <[email protected]> * Update tests/qnn/test_qnn_torch.py Co-authored-by: Tom Bromley <[email protected]> * Update tests/qnn/test_qnn_torch.py Co-authored-by: Tom Bromley <[email protected]> * Indentation correction Co-authored-by: Josh Izaac <[email protected]> Co-authored-by: Tom Bromley <[email protected]> * Followup #899 (#906) Fixes CUDA test * Fixes bug in the QAOA _diagonal_terms function to take into account the queuing refactor (#905) * Fixes bug in the QAOA _diagonal_terms function to take into account the queuing refactor * update changelog * Update .github/CHANGELOG.md Co-authored-by: Tom Bromley <[email protected]> Co-authored-by: Tom Bromley <[email protected]> * Allow PennyLane to rescan and refresh available plugin devices within the same Python runtime (#907) * Fix entrypoint colab bug * more * more * final * linting * doc fix * Apply suggestions from code review * suggested changes Co-authored-by: antalszava <[email protected]> * Add decomposition for CRot gate (#908) * Add decomposition * Add test * Update decomposition * Update changelog * Add more parameter options * Support in non tape mode * Update test to accommodate tape mode * Add comment * Add hardware-efficient particle-conserving ansatz U2 (#876) * Add the ParticleConservingU2 template * VQECost can optimize observables using the grouping module (#902) * First attempt * Add first version * Add test * Add to test * Add to tests * Run black * Remove trailing whitespace * Add to documentation * Add to changelog * Minor corrections * Prevent calculation of the metric tensor in optimize mode * Add test * Apply checks * Minor update * Move to new feature * Apply suggestions from code review Co-authored-by: Josh Izaac <[email protected]> * Add mention of grouping module in changelog * Apply suggestiosn * Fix error in example * Update .github/CHANGELOG.md * Update .github/CHANGELOG.md * Fix changelog Co-authored-by: Josh Izaac <[email protected]> * Rename VQECost to ExpvalCost (#913) * Rename VQECost to ExpvalCost * Add VQECost as deprecated * Add to changelog * Update PR number * Revert changes to changelog * Change a to an * Add pylint exception * Remove VQECost from docs * Reintroduce docstring * Support returning the metric tensor of ExpvalCost in tape mode (#911) * First attempt * Support old qnode in tape mode * Add test * Switch to disabling and re-enabling tape * Try with tests * Make warnings appear for users * Fix test * Remove the _wires arg * Remove reference to VQECost * Add to changelog * Rename * Fix CI checks * Apply suggestions from code review Co-authored-by: Josh Izaac <[email protected]> * Add hard-coded expected val Co-authored-by: Josh Izaac <[email protected]> * Modify qml.grad so that it stores and makes accessible the value of the intermediate forward pass (#914) * Modify qml.grad so that it stores and makes accessible the value of the intermediate forward pass * fix * linting * fix docs * add tests * update changelog * Update pennylane/__init__.py * suggested changes * Update pennylane/__init__.py Co-authored-by: Theodor <[email protected]> Co-authored-by: Theodor <[email protected]> * Remove mention of travis (#917) * Define the generator for the MultiRZ operation (#912) * [WIP] Define the generator for the MultiRZ operation * Save recalculating generator * Apply black * Add test * Add to changelog Co-authored-by: trbromley <[email protected]> Co-authored-by: Tom Bromley <[email protected]> * Support for MultiRZ and CRot in default.qubit.tf (#921) * Adding MultiRZ default.tensor.tf func * Add tests; docstrings; update * String compare * Temporarily remove CRot support so that it gets decomposed * Formatting * Fix * Integration tests for parametrized gates taking a tf variable * Update pennylane/devices/tf_ops.py Co-authored-by: Josh Izaac <[email protected]> * Changelog Co-authored-by: Josh Izaac <[email protected]> * Fixes bug in tape.set_parameters() (#923) * Fixes bug in tape.set_parameters() * add test * re add test * suggested changes * Allow optimizers to return cost function output via opt step (#916) * Modify qml.grad so that it stores and makes accessible the value of the intermediate forward pass * fix * linting * fix docs * add tests * update changelog * Update pennylane/__init__.py * suggested changes * Update pennylane/__init__.py Co-authored-by: Theodor <[email protected]> * Move grad and jacobian * Fix optimizers * Fix for user-defined gradients * Run black * Fix pylint issues * Remove autograd functions from docs * Apply suggestions from code review Co-authored-by: Josh Izaac <[email protected]> * Simplify compute_gradient * Raise error in step_and_cost for gradient-free opts * Remove step_and_cost from rotosolve/-select * Add simple tests * update changelog * Revert changes * Add example to changelog * Apply suggestions from code review Co-authored-by: Tom Bromley <[email protected]> * Apply suggestions from code review Co-authored-by: Tom Bromley <[email protected]> * Update step calculations * Fix tests * Add rotosolve/-select * Apply suggestions from code review Co-authored-by: Josh Izaac <[email protected]> * Apply suggestions from code review Co-authored-by: Tom Bromley <[email protected]> * Update docstring * Fix docstrings Co-authored-by: Josh Izaac <[email protected]> Co-authored-by: Tom Bromley <[email protected]> * Add support for arbitrary linear combination gradient recipes (#909) * Have positive and negative multiplier and shift values * No print * Formatting * 3 element terms for grad_recipes; qubit okay; CV draft * CV for tape mode * Comments * Remove unused * Formatting * Solve casting by specifying dtype at creation * No casting needed for shifted * Update module docstring and Operation.grad_recipe docstring * Development guide update * Wording * Adding tests; adding error raised for unsupported logic for tape second-order CV case * No f strings * Update pennylane/qnodes/cv.py Co-authored-by: Josh Izaac <[email protected]> * Update pennylane/tape/tapes/cv_param_shift.py * Simplify using np.dot in CV param shift tape * Update tests/qnodes/test_qnode_cv.py Co-authored-by: Josh Izaac <[email protected]> * get_parameter_shift in tape mode as per Josh's suggestion; use that * Changelog * Update tests/tape/tapes/test_cv_param_shift.py Co-authored-by: Josh Izaac <[email protected]> * Update .github/CHANGELOG.md Co-authored-by: Tom Bromley <[email protected]> * merge in changes from 915 * Update pennylane/operation.py Co-authored-by: Tom Bromley <[email protected]> * Update grad recipe formulae as per Tom's suggestions * Update other formula in comment * CHANGELOG * Add rendering img url approach * Plus * Update pennylane/operation.py Co-authored-by: Tom Bromley <[email protected]> * Applying review suggestions * Update doc/development/plugins.rst * Update pennylane/operation.py * equation formatting fixes Co-authored-by: Josh Izaac <[email protected]> Co-authored-by: Tom Bromley <[email protected]> * Adding controlled rotation gradients (#915) * Have positive and negative multiplier and shift values * No print * Formatting * 3 element terms for grad_recipes; qubit okay; CV draft * CV for tape mode * Comments * Remove unused * Formatting * Solve casting by specifying dtype at creation * No casting needed for shifted * Update module docstring and Operation.grad_recipe docstring * Development guide update * Wording * Adding tests; adding error raised for unsupported logic for tape second-order CV case * No f strings * adding CX gradient recipe * Update pennylane/qnodes/cv.py Co-authored-by: Josh Izaac <[email protected]> * Update pennylane/tape/tapes/cv_param_shift.py * more * more * more tests * fix typo * Apply suggestions from code review Co-authored-by: antalszava <[email protected]> * Simplify using np.dot in CV param shift tape * Update tests/qnodes/test_qnode_cv.py Co-authored-by: Josh Izaac <[email protected]> * get_parameter_shift in tape mode as per Josh's suggestion; use that * Changelog * Update tests/tape/tapes/test_cv_param_shift.py Co-authored-by: Josh Izaac <[email protected]> * Use get_parameter_shift in qubit param shift * Specify the shift kwarg * Further docstrings * CHANGELOG * Update .github/CHANGELOG.md Co-authored-by: Tom Bromley <[email protected]> * Apply suggestions from code review Co-authored-by: Tom Bromley <[email protected]> * merge in changes from 915 * suggested changes * black Co-authored-by: antalszava <[email protected]> Co-authored-by: Tom Bromley <[email protected]> * Support multiple devices with ExpvalCost (#927) * Fix multiple devices in ExpvalCost in tape mode * Extend test to non-tape mode * Fix typo * Apply suggestions * Applied suggestions * Fix CI * Update pennylane/vqe/vqe.py Co-authored-by: Josh Izaac <[email protected]> Co-authored-by: Josh Izaac <[email protected]> * Fix incorrect exception message for unknown interfaces (#930) * Fix incorrect exception message for unknown interfaces * changelog * Update qchem._terms_to_qubit_operator function to handle tensors with identities (#928) * QChem _terms_to_qubit_operator identity cases * Formatting Co-authored-by: Josh Izaac <[email protected]> * Pin pyscf<1.7.4 to allow scipy>=1.5 in QChem (#926) * Remove the pinning for scipy and add pinning for pyscf * Update requirements.txt * Update requirements.txt * Update requirements.txt * Update requirements.txt * Pin pyscf==1.7.2 Co-authored-by: Josh Izaac <[email protected]> * Update requirements.txt * Update changelog for the next release (#932) * Update changelog for the next release * Update CHANGELOG.md * Apply suggestions from code review Co-authored-by: Nathan Killoran <[email protected]> * suggested changes * reword tricks Co-authored-by: Nathan Killoran <[email protected]> * Improve the reliability of multi-threaded QNodeCollection execution by adding thread locking during queuing (#918) * Fixes #910 * Added re-entrant lock guard before/after with block of QuantumTape. * Fixes a PyTorch test failure caused by numerical precision. * Modified the change log * Fixes typo * Remove dependency to template circuits from parallel test * Added enable/disable tape mode guard for QNodeCollection test * Added fixture param for the problematic test * Update .github/CHANGELOG.md Co-authored-by: Josh Izaac <[email protected]> * Update tests/tape/tapes/test_qnode.py Co-authored-by: Josh Izaac <[email protected]> * Fixed potential deadlock because of exception in QuantumTape * Fixed unused variable error * Assert if QNodeCollection instantiation does not throw * Update tests/tape/tapes/test_qnode.py Co-authored-by: Josh Izaac <[email protected]> Co-authored-by: Josh Izaac <[email protected]> * Update docstrings (#934) * Update readme (#933) * Update readme * Update readme * Update readme * Update readme * Update readme * Update readme * Update readme * Update readme * Update readme * Update readme * more * more * more * more * more * more * more * more * more * more * more * more * test * test * more * Apply suggestions from code review Co-authored-by: Nathan Killoran <[email protected]> * Update README.md Co-authored-by: Nathan Killoran <[email protected]> * add new readme * add new readme * remove old readme * Added gif * remove file * update gif * crop gif * Apply suggestions from code review Co-authored-by: Tom Bromley <[email protected]> * revert images Co-authored-by: Josh Izaac <[email protected]> Co-authored-by: Tom Bromley <[email protected]> * Bump version number to v0.13 (#935) * Bump version number to v0.13 * Apply suggestions from code review Co-authored-by: antalszava <[email protected]> * fixes Co-authored-by: antalszava <[email protected]> * typo * fix missing images * Bump version number to v0.14-dev (#939) * Bump version number to v0.14-dev * fix * Solving issues with black using the standard black l-100. Also, I used isort to sort the libraries. * CI * fix * Apply suggestions from code review Co-authored-by: Tom Bromley <[email protected]> * Update pennylane/devices/tests/test_compare_default_qubit.py Co-authored-by: Tom Bromley <[email protected]> * Apply suggestions from code review Co-authored-by: Tom Bromley <[email protected]> * Update CHANGELOG.md Co-authored-by: antalszava <[email protected]> Co-authored-by: Maria Schuld <[email protected]> Co-authored-by: anthayes92 <[email protected]> Co-authored-by: Nathan Killoran <[email protected]> Co-authored-by: Tom Bromley <[email protected]> Co-authored-by: Olivia Di Matteo <[email protected]> Co-authored-by: Olivia Di Matteo <[email protected]> Co-authored-by: Josh Izaac <[email protected]> Co-authored-by: agran2018 <[email protected]> Co-authored-by: Christina Lee <[email protected]> Co-authored-by: ixfoduap <[email protected]> Co-authored-by: rmoyard <[email protected]> Co-authored-by: Shumpei Kobayashi <[email protected]> Co-authored-by: soranjh <[email protected]> Co-authored-by: Theodor <[email protected]> Co-authored-by: trbromley <[email protected]>
Context:
The "gradient recipe" of a gate parameter stores the coefficient (
c
) and the shift (s
) used to compute the partial derivative of an expectation value using the parameter shift rule (∂f(x) = c*(f(x+s) -f(x-s))
). TheOperation.grad_recipe
attribute is used for this. It turns out, that certain gates require more advanced gradient recipes for computing analytic gradients.While calculating the gradients that involve quantum circuits containing quantum channels, we'd further require that the gate parameter is not only shifted by a scalar constant but also scaled (at times with a scaling factor of 0, such that we only evaluate using the constant shift).
Bearing these points in mind, it would be good for a gradient recipe to have the ability to:
Description of the Change:
The gradient recipe has been changed so that it can support computations like
∂f(x) = Σi c_i f(a_i x + b_i)
. This is even more flexible, as it allows us to represent terms that do not depend onx
(1.2*f(0.2)
):Notes on the changes:
grad_recipe
immutable (tuple
), each element of thegrad_recipe
represents the recipe for a gate parameter; immutability was added as the original recipe is not mutated, but queried for further computation.grad_recipe
nested lists. Each list that is nested describes a term in the sum making up∂f(x)
and is of the form of[coefficient, scaling factor, shift]
.The reason why lists are used is that we may potentially be post-processing the multiplier and the shift values in non-tape mode:
pennylane/pennylane/operation.py
Line 644 in 6d489ea
Therefore, it made sense to choose a mutable collection rather than a
tuple
.grad_recipe = ([[multiplier, a, shift], [-multiplier, a, -shift]], None)
, with[[multiplier, a, shift], [-multiplier, a, -shift]]
being the recipe for the first,None
being the recipe for the second parameter.Benefits:
Possible Drawbacks:
Related GitHub Issues:
N/A
TODO:
grad_recipe
attributes to have containpos_multiplier, pos_shift, neg_multiplier, neg_shift
get_parameter_shift
NotImplementedError
is raised