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

Raise an error if gradient of QNode returning qml.sample() is computed #2556

Open
eddddddy opened this issue May 10, 2022 · 0 comments
Open
Labels
enhancement ✨ New feature or request

Comments

@eddddddy
Copy link
Contributor

Feature details

Right now PennyLane allows computing the gradient of QNodes that returns qml.sample(). This is illustrated by the below code:

def print_sample_grad():
    dev = qml.device('default.qubit', wires=1, shots=10)

    @qml.qnode(dev, diff_method='parameter-shift')
    def circuit(x):
        qml.RX(x[0], wires=0)
        return qml.sample(wires=0)

    x = np.array([0.1])

    print('samples:', circuit(x))
    print('sample gradients:', qml.jacobian(circuit)(x))
>>> print_sample_grad()
samples: [0 0 0 0 0 0 0 0 0 0]
sample gradients: [[-0.5]
 [ 0.5]
 [ 0.5]
 [ 0. ]
 [ 0.5]
 [ 0.5]
 [-0.5]
 [ 0.5]
 [ 0. ]
 [ 0.5]]

This is unintuitive behaviour since the gradient of a sample doesn't really make any sense.

Instead of silently failing and producing nonsensical gradients, an error should be raised if the user tries to compute the gradient of a QNode that returns a sample. Ideally, the forward pass would still be supported.

Implementation

No response

How important would you say this feature is?

1: Not important. Would be nice to have.

Additional information

No response

@eddddddy eddddddy added the enhancement ✨ New feature or request label May 10, 2022
timmysilv added a commit that referenced this issue Feb 22, 2024
**Context:**
Autograd allows the differentiation of integers, although this doesn't
entirely make sense (see #2556). On top of this, our docstring for
`qml.sample` currently suggests that it _is_ possible, when it should
really just point the user elsewhere.

**Description of the Change:**
- Update the docstring of `qml.sample` to suggest the use of expval
instead
- Add tests to show that autograd allows computing the jacobian of a
circuit which returns samples, whereas jax (for example) does not

**Benefits:**
More useful docs

**Possible Drawbacks:**
We are testing something that shouldn't exist just because Autograd said
it should exist

**Related GitHub Issues:**
Fixes #4840
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement ✨ New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant