Skip to content

Commit

Permalink
QNSPSA bugfix (#4421)
Browse files Browse the repository at this point in the history
* qnspsa bugfix

* Update doc/releases/changelog-dev.md

* Update tests/optimize/test_qnspsa.py

Co-authored-by: Matthew Silverman <[email protected]>

---------

Co-authored-by: Matthew Silverman <[email protected]>
  • Loading branch information
albi3ro and timmysilv authored Aug 2, 2023
1 parent e9fb43b commit c6865ea
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
3 changes: 3 additions & 0 deletions doc/releases/changelog-dev.md
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,9 @@
`Tensor.sparse_matrix()`, it is recommended to use the `wire_order` keyword argument over `wires`.
[(#4424)](https://github.com/PennyLaneAI/pennylane/pull/4424)

* Replace `op.adjoint` with `qml.adjoint` in `QNSPSAOptimizer`.
[(#4421)](https://github.com/PennyLaneAI/pennylane/pull/4421)

* Replace deprecated `jax.ad` by `jax.interpreters.ad`.
[(#4403)](https://github.com/PennyLaneAI/pennylane/pull/4403)

Expand Down
2 changes: 1 addition & 1 deletion pennylane/optimize/qnspsa.py
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@ def _get_overlap_tape(self, cost, args1, args2, kwargs):
op_forward = self._get_operations(cost, args1, kwargs)
op_inv = self._get_operations(cost, args2, kwargs)

new_ops = op_forward + [op.adjoint() for op in reversed(op_inv)]
new_ops = op_forward + [qml.adjoint(op) for op in reversed(op_inv)]
return qml.tape.QuantumScript(new_ops, [qml.probs(wires=cost.tape.wires.labels)])

@staticmethod
Expand Down
17 changes: 17 additions & 0 deletions tests/optimize/test_qnspsa.py
Original file line number Diff line number Diff line change
Expand Up @@ -418,3 +418,20 @@ def test_blocking(self, finite_diff_step, seed):
# blocking should stop params from updating from this minimum
new_params, _ = opt.step_and_cost(qnode, params)
assert np.allclose(new_params, params)


def test_template_no_adjoint():
"""Test that qnspsa iterates when the operations do not have a custom adjoint."""

num_qubits = 2
dev = qml.device("default.qubit", wires=num_qubits)

@qml.qnode(dev)
def cost(params):
qml.RandomLayers(weights=params, wires=range(num_qubits), seed=42)
return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1))

params = np.random.normal(0, np.pi, (2, 4))
opt = qml.QNSPSAOptimizer(stepsize=5e-2)
assert opt.step_and_cost(cost, params) # just checking it runs without error
assert not qml.RandomLayers.has_adjoint

0 comments on commit c6865ea

Please sign in to comment.