Parameter-Shift Gradient in PennyLane
Differentiate f(θ) = ⟨Z⟩ = cos θ after R_X(θ) with the parameter-shift rule; compare with a manual shift and the analytic −sin θ.
For a gate of the form $e^{-i\theta P/2}$ with $P$ a Pauli operator, the exact rule $$\frac{\partial f}{\partial\theta}=\frac{f(\theta+\pi/2)-f(\theta-\pi/2)}{2}$$ holds. It is not a finite-difference approximation but an exact equality; so it can be used on hardware by evaluating the circuit twice per parameter. diff_method="parameter-shift" requests this method explicitly.
Requirements: pip install pennylane. The code runs on your machine or in Colab, not inside WordPress.
Code
import pennylane as qml
from pennylane import numpy as np
dev = qml.device("default.qubit", wires=1)
@qml.qnode(dev, diff_method="parameter-shift")
def f(theta):
qml.RX(theta, wires=0)
return qml.expval(qml.PauliZ(0))
theta = np.array(0.7, requires_grad=True)
grad = qml.grad(f)(theta)
manual = (f(theta + np.pi / 2) - f(theta - np.pi / 2)) / 2
print("f(theta) =", round(float(f(theta)), 6), "| cos(theta) =", round(float(np.cos(theta)), 6))
print("parameter-shift grad =", round(float(grad), 6))
print("manual shift =", round(float(manual), 6))
print("analytic -sin(theta) =", round(float(-np.sin(theta)), 6))
Line-by-line code explanation
| Line | Explanation |
|---|---|
| 1-2 | Imports. |
| 4 | A one-qubit device. |
| 7 | A quantum node that uses parameter shift for differentiation. |
| 8-10 | The function: RX(θ) then ⟨Z⟩ = cos θ. |
| 13 | A differentiable parameter. |
| 14 | The gradient from PennyLane. |
| 15 | The gradient by hand with two shifts of ±π/2. |
| 16 | Compare f with the value cos θ. |
| 17-19 | Print the three gradients. |
Expected output (from an actual run)
f(theta) = 0.764842 | cos(theta) = 0.764842 parameter-shift grad = -0.644218 manual shift = -0.644218 analytic -sin(theta) = -0.644218
The output is deterministic (an exact device without shots).
Try it yourself
Related topics
References
- K. Mitarai; M. Negoro; M. Kitagawa; K. Fujii (2018). Quantum circuit learning. Phys. Rev. A 98:032309 doi:10.1103/PhysRevA.98.032309
- Xanadu (2025). Parameter-shift rules. PennyLane Glossary pennylane.ai
- Xanadu (2025). PennyLane Documentation. PennyLane docs.pennylane.ai
