Skip to content
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

Custom return type #2813

Merged
merged 2 commits into from
Jul 18, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pennylane/interfaces/autograd.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ def _execute(
if isinstance(r[0][0], dict):
# This happens when measurement type is Counts and shot vector is passed
continue
except (IndexError, KeyError):
except (TypeError, IndexError, KeyError):
pass
r = np.hstack(r) if r.dtype == np.dtype("object") else r
res[i] = np.tensor(r)
Expand Down
30 changes: 29 additions & 1 deletion tests/devices/test_custom_return_obj.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,13 +62,28 @@ class DeviceSupporingSpecialObservable(DefaultQubit):
short_name = "default.qubit.specialobservable"
observables = DefaultQubit.observables.union({"SpecialObservable"})

@classmethod
def capabilities(cls):
capabilities = super().capabilities().copy()
capabilities.update(
provides_jacobian=True,
)
return capabilities

def expval(self, observable, **kwargs):
if self.analytic and isinstance(observable, SpecialObservable):
val = super().expval(qml.PauliZ(wires=0), **kwargs)
return SpecialObject(val)

return super().expval(observable, **kwargs)

def jacobian(self, tape):
# we actually let pennylane do the work of computing the
# jacobian for us but return it as a device jacobian
gradient_tapes, fn = qml.gradients.param_shift(tape)
tape_jacobian = fn(qml.execute(gradient_tapes, self, None))
return tape_jacobian

dev = DeviceSupporingSpecialObservable(wires=1, shots=None)

# force diff_method='parameter-shift' because otherwise
Expand All @@ -87,7 +102,20 @@ def reference_qnode(x):
assert isinstance(out, np.ndarray)
assert isinstance(out.item(), SpecialObject)
assert np.isclose(out.item().val, reference_qnode(0.2))
reference_jac = qml.jacobian(reference_qnode)(np.array(0.2, requires_grad=True)),

assert np.isclose(
reference_jac,
qml.jacobian(qnode)(np.array(0.2, requires_grad=True)).item().val,
qml.jacobian(reference_qnode)(np.array(0.2, requires_grad=True)),
)

# now check that also the device jacobian works with a custom return type
@qml.qnode(dev, diff_method="device")
def device_gradient_qnode(x):
qml.RY(x, wires=0)
return qml.expval(SpecialObservable(wires=0))

assert np.isclose(
reference_jac,
qml.jacobian(device_gradient_qnode)(np.array(0.2, requires_grad=True)).item().val,
)