|q⟩ Bad Qubits

advanced · Programming · Advanced VQE & Ansatz Design

Gradient Measurement

To train a VQE you need the gradient of the energy with respect to every circuit parameter. On a classical simulator you could differentiate the state vector directly, but on real hardware you only ever get expectation values from measurements. The question this lesson answers is: how do you obtain an exact analytic gradient using only circuit evaluations?

Why finite differences fail

The naive approach is the finite-difference estimate

EθkE(θk+ε)E(θkε)2ε.\frac{\partial E}{\partial\theta_k} \approx \frac{E(\theta_k + \varepsilon) - E(\theta_k - \varepsilon)}{2\varepsilon}.

This has two problems on a quantum device. A small ε\varepsilon makes the numerator a difference of two nearly equal noisy numbers — the shot noise blows up as 1/ε1/\varepsilon. A large ε\varepsilon introduces O(ε2)O(\varepsilon^2) truncation bias. There is no good middle ground.

The parameter-shift rule

For gates of the form U(θ)=eiθP/2U(\theta) = e^{-i\theta P/2} with a Pauli generator PP (so P2=IP^2 = I, which covers RX,RY,RZR_X, R_Y, R_Z), the gradient is given exactly by the same circuit evaluated at two macroscopically shifted points:

Eθk=12[E(θk+π2)E(θkπ2)].\frac{\partial E}{\partial\theta_k} = \frac{1}{2}\Bigl[\,E\bigl(\theta_k + \tfrac{\pi}{2}\bigr) - E\bigl(\theta_k - \tfrac{\pi}{2}\bigr)\Bigr].

This is not an approximation. Because the eigenvalues of P/2P/2 are ±12\pm\tfrac{1}{2}, the energy as a function of θk\theta_k is a pure sinusoid acosθk+bsinθk+ca\cos\theta_k + b\sin\theta_k + c, and a sinusoid's derivative is recovered exactly from samples a quarter-period apart. The shift is a fixed π/2\pi/2, so each evaluation is a normal-magnitude expectation value — no division by a tiny ε\varepsilon, no truncation bias.

A concrete check

Take the simplest case: a single qubit in 0|0\rangle, apply RY(θ)R_Y(\theta), and measure ZZ. Since RY(θ)0=cos(θ/2)0+sin(θ/2)1R_Y(\theta)|0\rangle = \cos(\theta/2)|0\rangle + \sin(\theta/2)|1\rangle,

E(θ)=Z=cos2 ⁣θ2sin2 ⁣θ2=cosθ.E(\theta) = \langle Z\rangle = \cos^2\!\tfrac{\theta}{2} - \sin^2\!\tfrac{\theta}{2} = \cos\theta.

The true derivative is sinθ-\sin\theta. Apply the shift rule:

12[cos(θ+π2)cos(θπ2)]=12[sinθsinθ]=sinθ.\frac{1}{2}\bigl[\cos(\theta + \tfrac{\pi}{2}) - \cos(\theta - \tfrac{\pi}{2})\bigr] = \frac{1}{2}\bigl[-\sin\theta - \sin\theta\bigr] = -\sin\theta. \checkmark

The two-evaluation recipe reproduces the analytic gradient exactly.

Try it

Implement E(θ)=cosθE(\theta) = \cos\theta for the RYR_Y-then-ZZ circuit, then return the parameter-shift estimate of the gradient at θ=0.8\theta = 0.8 radians. The grader checks your returned number against the exact value sin(0.8)-\sin(0.8).

Run your code to see the quantum state.

Sign in on the full site to ask questions and join the discussion.