PennyLaneAI / pennylane

PennyLane is a cross-platform Python library for quantum computing, quantum machine learning, and quantum chemistry. Train a quantum computer the same way as a neural network.
https://pennylane.ai
Apache License 2.0
2.27k stars 585 forks source link

[BUG] `qml.PrepSelPrep` does not work correctly with `torch` #6185

Closed KetpuntoG closed 1 week ago

KetpuntoG commented 2 weeks ago

Expected behavior

When using PrepSelPrep in a circuit, differentiation with autograd and torch should give the same result:


import pennylane as qml
from pennylane import numpy as np
import torch

@qml.qnode(qml.device("default.qubit"))
def circuit(coeffs):
    H = qml.ops.LinearCombination(
        coeffs, [qml.Y(0), qml.Y(1) @ qml.Y(2), qml.X(0), qml.X(1) @ qml.X(2)]
    )
    qml.PrepSelPrep(H, control=(3, 4))
    return qml.expval(qml.PauliZ(3) @ qml.PauliZ(4))

params_numpy = np.array([0.4, 0.5, 0.1, 0.3])
params_torch = torch.tensor([0.4, 0.5, 0.1, 0.3])

print(qml.grad(circuit)(params_numpy))
print(torch.autograd.functional.jacobian(circuit, params_torch))

Actual behavior

torch returns gradient 0


numpy: [ 0.41177729 -0.21262357  1.64370435 -0.74256522]

torch: tensor([0., 0., 0., 0.])

Additional information

The manual implementation in Qubitization for PrepSelPrep does appear to be differentiable in torch. It may help to solve the problem if we look at that code

Source code

No response

Tracebacks

No response

System information

Name: PennyLane
Version: 0.39.0.dev3
Summary: PennyLane is a cross-platform Python library for quantum computing, quantum machine learning, and quantum chemistry. Train a quantum computer the same way as a neural network.
Home-page: https://github.com/PennyLaneAI/pennylane
Author: 
Author-email: 
License: Apache License 2.0
Location: /usr/local/lib/python3.10/dist-packages
Requires: appdirs, autograd, autoray, cachetools, networkx, numpy, packaging, pennylane-lightning, requests, rustworkx, scipy, toml, typing-extensions
Required-by: PennyLane_Lightning

Platform info:           Linux-6.1.85+-x86_64-with-glibc2.35
Python version:          3.10.12
Numpy version:           1.26.4
Scipy version:           1.13.1
Installed devices:
- default.clifford (PennyLane-0.39.0.dev3)
- default.gaussian (PennyLane-0.39.0.dev3)
- default.mixed (PennyLane-0.39.0.dev3)
- default.qubit (PennyLane-0.39.0.dev3)
- default.qubit.autograd (PennyLane-0.39.0.dev3)
- default.qubit.jax (PennyLane-0.39.0.dev3)
- default.qubit.legacy (PennyLane-0.39.0.dev3)
- default.qubit.tf (PennyLane-0.39.0.dev3)
- default.qubit.torch (PennyLane-0.39.0.dev3)
- default.qutrit (PennyLane-0.39.0.dev3)
- default.qutrit.mixed (PennyLane-0.39.0.dev3)
- default.tensor (PennyLane-0.39.0.dev3)
- null.qubit (PennyLane-0.39.0.dev3)
- lightning.qubit (PennyLane_Lightning-0.37.0)

Existing GitHub issues

soranjh commented 2 weeks ago

@willjmax Please open a PR to fix this.