Lesson 47 · 95 min · advanced
Why Backpropagation Fails on Quantum Hardware
Classical neural networks are trained by reverse-mode automatic differentiation (backpropagation), which returns the whole gradient for a constant multiple of the cost of one forward pass by storing every intermediate value and propagating adjoints backwards. This lesson shows why that algorithm cannot run on a quantum processor: the intermediate states and the adjoint states are vectors of amplitudes that the device never outputs, measurement destroys them, and the no-cloning theorem forbids keeping a copy. A counting argument (sphere packing, Holevo's bound and Fano's inequality) proves that reading out one state to precision needs circuit runs. A simulator, in contrast, can backpropagate: the adjoint method computes in time and memory. On hardware the gradient must be estimated from expectation values; the lesson derives the shot-noise variance and the Taylor bias of central finite differences, the MSE-optimal step for , and the unbiased parameter-shift estimator with variance .
Prerequisites: Variational Quantum Circuits: Architecture, Supervised Learning & Gradient Descent
Objectives and key results
State the reverse-mode recursion , identify what it stores, and translate it to a circuit, where the intermediates are the states .
Explain the three hardware obstructions (samples only, measurement collapse, no-cloning) and prove that estimating an arbitrary -qubit pure state to precision needs at least copies.
Derive the adjoint method with , , and its cost time, memory.
Derive the variance and the bias of the central finite-difference estimator, and the MSE-optimal step with minimal MSE .
Show that the parameter-shift estimator is unbiased with variance , whose MSE decays as .
- theorem · Counting bound for reading out a state
- formula · Adjoint method
- formula · Central finite differences under shot noise
- formula · MSE-optimal finite-difference step
- formula · Parameter-shift estimator
What backpropagation needs#
The previous lesson ended with a training loop in which the quantum processor supplies the derivatives of the model output, two circuit evaluations per weight. A classical network with a million weights is never trained that way: backpropagation delivers all million partial derivatives for the price of roughly one extra forward pass. It is natural to ask whether a variational circuit, which is a composition of linear maps just like the layers of a network, can be differentiated in the same way. This lesson answers the question in three parts. First it states precisely what reverse-mode differentiation stores and reuses. Then it proves that a quantum processor cannot provide those quantities, while a classical simulator can (the adjoint method). Finally it quantifies the alternative available on hardware, estimating derivatives from noisy expectation values, and compares finite differences with the parameter-shift rule.
Definition
Reverse-mode automatic differentiation
Let be fixed and for , with a scalar loss . Reverse mode first runs the forward pass, computing and storing (the tape). It then runs the backward pass: starting from the adjoint (a row vector) it computes Backpropagation in neural networks is this algorithm applied to a layered network.
Correctness and cost of reverse mode
The backward recursion returns the exact gradient . It performs one vector–Jacobian product per stage, so its cost is a constant multiple of the forward pass, independent of the number of parameters, and it needs every stored intermediate at the moment stage is processed.
Proof (5 steps)
- Step 1:enters only through ; chain rule for the composition .
- Step 2:The chain rule once more; each Jacobian is evaluated at the intermediate value of its own stage.
- Step 3:Peel off one factor at a time: multiplying from the left keeps every intermediate a row vector, never a matrix.
- Step 4:Substitute the definition of into the first line.
- Step 5:A vector–Jacobian product of stage costs a bounded multiple of evaluating (the cheap-gradient principle, Griewank and Walther). The Jacobians depend on , which must therefore be stored on the tape or recomputed.
∎
Reverse mode applied to a circuit
- Step 1:A circuit of gates is a composition of stages whose intermediates are the states .
- Step 2:Every parameterised gate is generated by a Hermitian ; for the generator is .
- Step 3:The stage maps are linear, , and the loss is the quadratic form of : the adjoint is a bra of dimension , propagated backwards through the gates.
- Step 4:The derivative of a quadratic form; the adjoint-method theorem below gives the proof.
Result
Why a quantum processor cannot run the backward pass#
A quantum processor applies the gates to a physical register, but it never outputs the state. What it returns, run after run, is a bit string drawn from the Born distribution, after which the register is in a computational basis state and the superposition is gone. Three facts, each proved earlier in the course, stand between the hardware and the tape of reverse mode.
- Only samples are observable. A run of an -qubit circuit ending in a measurement yields one outcome, at most classical bits. Amplitudes appear only through outcome frequencies.
- Measurement collapses the state. After the outcome is recorded, the post-measurement state is ; reading the register destroys the intermediate that the backward pass needs.
- States cannot be copied. One might try to duplicate , measure one copy and continue the circuit with the other. The theorem of the lesson The No-Cloning Theorem rules this out.
No-cloning (recalled)
There is no unitary on and fixed state with for every state . Consequently a circuit cannot store a copy of for later use while continuing to compute with it. (Proved in the lesson The No-Cloning Theorem; Wootters and Zurek, Dieks.)
Proof (4 steps)
- Step 1:Assume such a exists and apply it to two arbitrary states.
- Step 2:Take the inner product of the two equations; on the left, and inner products of product states factorise on the right.
- Step 3:, and has the solutions and .
- Step 4:Two states that are neither equal nor orthogonal give a contradiction, so no universal cloner exists.
∎
Each attempt to learn something about therefore consumes one run of the first gates. How many runs does it take to learn the state well enough to use it as data? The answer is a counting argument: many states are far apart, each run carries few bits, so many runs are needed. The two lemmas construct the many far-apart states; the theorem does the counting. Throughout, the distance between pure states is the Euclidean distance up to a global phase, , which satisfies the triangle inequality.
States with nonnegative amplitudes
Let and . For define . Then is a unit vector and for all .
Proof (5 steps)
- Step 1:The basis is orthonormal.
- Step 2:Expand the squared norm of a difference of unit vectors; the real part is maximal, equal to the modulus, for the optimal phase.
- Step 3:All amplitudes are real and nonnegative, so the overlap equals its modulus.
- Step 4:For such states the optimal phase is : the phase-invariant distance is the plain Euclidean one.
- Step 5:The coordinates of are those of ; the extra coordinate only adds a square.
∎
Many well-separated points
For every the set contains points whose pairwise distances all exceed .
Proof (5 steps)
- Step 1:Choose points greedily, each farther than from all previous ones. The balls of radius around them are disjoint and lie in the bounded set , so the process stops after finitely many points: the set is maximal.
- Step 2:Maximality: a point of at distance more than from every could still be added.
- Step 3:Subadditivity of volume; a ball of radius in has volume , with the unit ball.
- Step 4:The unit ball is the union of the reflections of by sign changes of coordinates, which are congruent and overlap only on coordinate hyperplanes, a set of volume zero.
- Step 5:Combine the last two lines.
∎
Reading out an n-qubit state needs exponentially many copies
Let and . Suppose a procedure receives copies of an unknown -qubit pure state , measures them in any way (one at a time, adaptively, or jointly), and outputs a classical description of a unit vector with with probability at least , for every . Then For this is .
Proof (8 steps)
- Step 1:The packing lemma with . By the orthant lemma the states satisfy for .
- Step 2:Feed the procedure a uniformly random packing state; is its complete classical record (an adaptive scheme is one measurement on the copies), and rounds its output to the nearest packing state.
- Step 3:Triangle inequality for . Hence .
- Step 4:Fano's inequality with the binary entropy , and for the uniform distribution.
- Step 5:Data-processing inequality: is a function of .
- Step 6:Holevo's bound for the ensemble (Nielsen and Chuang, Theorem 12.1). Each is pure, so , and the entropy of any state of qubits is at most bits.
- Step 7:Chain the inequalities and insert with .
- Step 8:is equivalent to . With a fixed the bound becomes .
∎
For and an error-free procedure () the counting bound evaluates to at least copies for and copies for (the NumPy cell at the end prints the table), and reverse mode would need such a readout for every intermediate state and every adjoint state of every training step.
Quick check
Why can a quantum processor not keep the tape that reverse-mode differentiation reuses in its backward pass?
Simulators can backpropagate: the adjoint method#
A statevector simulator holds as an array of complex numbers, so nothing prevents reverse mode there. Storing the whole tape costs such arrays, but the circuit is unitary: any intermediate can be recovered from a later one by applying inverse gates. The adjoint method exploits this and keeps only a constant number of vectors.
Adjoint differentiation of an expectation value
Let with , (a fixed gate is a stage without parameter), and . Define and . Then and both sequences are generated backwards from and by and .
Proof (6 steps)
- Step 1:Differentiate the absolutely convergent exponential series term by term; commutes with its own exponential.
- Step 2:Product rule: only the factor depends on .
- Step 3:, and since the first term is the complex conjugate of the second.
- Step 4:and ; is the definition of .
- Step 5:Unitarity : the forward states are recovered by undoing one gate at a time, so they need not be stored.
- Step 6:For , . For a Pauli rotation the generator is ; this is the formula used in the code cell.
∎
Cost of the adjoint method
For a circuit of gates, each acting on a bounded number of qubits, and an observable with Pauli terms, the adjoint method computes and all partial derivatives in time with three statevectors, i.e. memory. Storing the tape instead needs amplitudes, memory, and evaluating the parameter-shift rule on the simulator needs simulations, time.
Proof (5 steps)
- Step 1:A -qubit gate updates the groups of amplitudes once each.
- Step 2:Forward pass gate by gate; a Pauli string permutes the amplitudes and multiplies them by phases.
- Step 3:Each iteration costs a constant number of operations, in total, and holds only , and the scratch vector .
- Step 4:A complex double occupies bytes, so one -qubit statevector takes bytes MiB.
- Step 5:Each of the shifted circuits is a complete simulation; the adjoint method replaces them by a single backward sweep.
∎
The TypeScript cell implements the theorem on a random three-qubit circuit with twelve rotation angles and a three-term observable. It performs one forward pass, sets , and walks backwards through the gates, reading off before undoing gate on both vectors. The result agrees with the engine's parameter-shift gradient to machine precision, after gate applications instead of full circuit simulations.
import { Statevector, expectationValue, mulberry32, parameterShiftGradient } from '@/lib/quantum-simulator';
// A random 3-qubit circuit: two layers of R_Y, R_Z rotations (12 trainable angles) and a CNOT chain.
const n = 3;
const rng = mulberry32(47);
const H = [
{ coeff: 0.7, ops: 'ZZI' },
{ coeff: -0.4, ops: 'IXY' },
{ coeff: 0.25, ops: 'YIZ' },
];
type Gate = { kind: 'rot'; axis: 'X' | 'Y' | 'Z'; q: number; name: string } | { kind: 'cnot'; c: number; t: number };
const gates: Gate[] = [];
const values: Record<string, number> = {};
for (let layer = 0; layer < 2; layer++) {
for (let q = 0; q < n; q++) {
for (const axis of ['Y', 'Z'] as const) {
const name = 't' + gates.length;
values[name] = 2 * Math.PI * rng() - Math.PI;
gates.push({ kind: 'rot', axis, q, name });
}
}
for (let q = 0; q < n - 1; q++) gates.push({ kind: 'cnot', c: q, t: q + 1 });
}
const names = Object.keys(values);
// The same circuit as Circuit IR, for the engine's expectation value and parameter-shift gradient.
const ir = {
version: 1 as const,
numQubits: n,
numClbits: 0,
parameters: names.map((name) => ({ name, value: values[name] })),
ops: gates.map((g) =>
g.kind === 'rot'
? { kind: 'gate' as const, gate: ('R' + g.axis) as 'RX' | 'RY' | 'RZ', targets: [g.q], params: [{ param: g.name }] }
: { kind: 'gate' as const, gate: 'CNOT' as const, targets: [g.c, g.t] },
),
};
// U_k (sign +1) and U_k^dagger (sign -1): R_P(theta)^dagger = R_P(-theta), CNOT^dagger = CNOT.
let gateApplications = 0;
function apply(sv: Statevector, g: Gate, sign: 1 | -1): void {
gateApplications++;
if (g.kind === 'rot') sv.applyGate(('R' + g.axis) as 'RX' | 'RY' | 'RZ', [g.q], [sign * values[g.name]]);
else sv.applyGate('X', [g.t], [], [g.c]);
}
// H|psi> = sum_k c_k P_k |psi>, one Pauli string at a time.
function applyH(sv: Statevector): Statevector {
const out = new Float64Array(sv.amps.length);
for (const term of H) {
const t = sv.clone();
for (let q = 0; q < n; q++) if (term.ops[q] !== 'I') t.applyGate(term.ops[q] as 'X' | 'Y' | 'Z', [q]);
for (let i = 0; i < out.length; i++) out[i] += term.coeff * t.amps[i];
}
return new Statevector(n, out);
}
// Forward pass: phi = |psi_P>. Backward pass: lambda = H|psi_P>, then undo one gate at a time.
const phi = Statevector.zero(n);
for (const g of gates) apply(phi, g, 1);
const lambda = applyH(phi);
const value = phi.inner(lambda).re;
const adjoint: Record<string, number> = {};
for (let k = gates.length - 1; k >= 0; k--) {
const g = gates[k];
if (g.kind === 'rot') {
// df/dtheta_k = 2 Re <lambda_k| (-i P/2) |phi_k> = Im <lambda_k| P |phi_k>
const mu = phi.clone().applyGate(g.axis, [g.q]);
adjoint[g.name] = lambda.inner(mu).im;
}
apply(phi, g, -1);
apply(lambda, g, -1);
}
const psr = parameterShiftGradient(ir, H);
const maxDiff = Math.max(...names.map((p) => Math.abs(adjoint[p] - psr.gradient[p])));
console.log('P = ' + names.length + ' parameters, f = ' + value.toFixed(6) + ' (engine: ' + expectationValue(ir, H).toFixed(6) + ')');
console.log('adjoint gradient: [' + names.slice(0, 4).map((p) => adjoint[p].toFixed(6)).join(', ') + ', ...]');
console.log('parameter shift: [' + names.slice(0, 4).map((p) => psr.gradient[p].toFixed(6)).join(', ') + ', ...]');
console.log('max |adjoint - parameter shift| < 1e-12: ' + (maxDiff < 1e-12));
console.log('adjoint: 1 forward + 1 backward pass, ' + gateApplications + ' gate applications, 3 statevectors in memory');
console.log('parameter shift: ' + psr.evaluations + ' circuit evaluations = 2P + 1');Expected output
P = 12 parameters, f = -0.579687 (engine: -0.579687) adjoint gradient: [0.386988, -0.206896, -0.122747, -0.000161, ...] parameter shift: [0.386988, -0.206896, -0.122747, -0.000161, ...] max |adjoint - parameter shift| < 1e-12: true adjoint: 1 forward + 1 backward pass, 48 gate applications, 3 statevectors in memory parameter shift: 25 circuit evaluations = 2P + 1
| statevector simulator | quantum processor | |
|---|---|---|
| state after gate | an array of amplitudes | a physical register, read only by sampling |
| copies | free | forbidden (no-cloning) |
| adjoint | computed and reused for all | never available as data |
| gradient cost | time, memory | circuits, each repeated times |
| scaling in | exponential memory | polynomial in per run |
The two settings fail in opposite ways. The simulator has every amplitude but pays for each vector; the hardware runs large circuits but reveals almost nothing per run.
Quick check
A simulator differentiates a -qubit circuit with rotation gates. How does the memory of the adjoint method compare with storing the tape of all intermediate states?
Finite differences under shot noise#
Hardware gives access to the function only through noisy estimates. The most obvious way to estimate a derivative from function values is a difference quotient. For the rest of the lesson the observable is a Pauli string, every evaluation uses fresh shots, and different evaluations are independent.
Definition
Shot estimate and central finite-difference estimator
For an angle the evaluation is the mean of independent outcomes of the circuit at angle ; by the shot-noise theorem of the lesson on variational circuits, and . The central finite-difference estimator with step is built from two independent evaluations. Write .
Variance and bias of central finite differences
(a) . (b) If is five times continuously differentiable and , then with . (c) .
Proof (6 steps)
- Step 1:Linearity of expectation and unbiasedness of each evaluation.
- Step 2:For independent : , here with .
- Step 3:Taylor's theorem with the Lagrange form of the remainder.
- Step 4:The even-order terms cancel; the odd ones double, and .
- Step 5:Divide by and bound each fifth derivative by .
- Step 6:Expand ; the cross term has expectation zero.
∎
A sum of shifted squared sines
For all real and : .
Proof (3 steps)
- Step 1:Double-angle formula .
- Step 2:Apply it with and add.
- Step 3:Addition theorem ; the sine terms cancel.
∎
Finite differences for f = cos θ
- Step 1:The one-qubit model of the lab; .
- Step 2:Part (a) of the theorem and the lemma.
- Step 3:.
- Step 4:Power series of ; the leading term matches because for .
- Step 5:At the variance is exactly for every ; this is part (a) of the lab.
- Step 6:With the estimate is essentially pure noise; the truncation error is negligible.
Result
The duel above uses the lab setting: , , . The finite-difference histogram is centred on but spreads over several units, while the parameter-shift histogram is a narrow spike. Noise in each evaluation is of order , independent of ; dividing the difference by amplifies it fifty-fold. Bringing the standard deviation down to the parameter-shift level of would take times as many shots, per evaluation.
Quick check
For at with shots per evaluation, what is the variance of the central finite-difference estimator with ?
The bias–variance trade-off and the optimal step#
Small steps amplify noise as ; large steps incur a truncation bias of order . The mean squared error balances the two, and its minimiser depends on the shot budget.
The MSE-optimal step and the law
- Step 1:Part (c) of the theorem with the bias of part (b); .
- Step 2:; the first-order terms cancel in the sum.
- Step 3:Keep the leading order of each term.
- Step 4:Differentiate and multiply by (assuming and ).
- Step 5:is strictly convex on and tends to at both ends, so the stationary point is the unique minimiser.
- Step 6:Insert : at the optimum the squared bias is half the variance.
- Step 7:Substitute and collect powers.
Result
The optimal step for f = cos θ
- Step 1:, , : the optimal step does not depend on .
- Step 2:The step is large, about , far from the "small " of calculus.
- Step 3:and .
- Step 4:Exact bias and variance of the previous derivation.
- Step 5:Numerical minimisation of the exact MSE (NumPy cell). The asymptotic formula misses the exact minimiser by .
Result
At the finite-difference histogram is narrow but visibly shifted: its mean is instead of , a bias of , comparable to its standard deviation . No step size does better than an MSE of about with shots, and because the optimum scales as rather than , extra shots help finite differences less than they help an unbiased estimator.
Quick check
For , what is the asymptotically MSE-optimal finite-difference step when every evaluation uses shots (four decimals)?
An unbiased alternative: the parameter-shift estimator#
Finite differences treat as an arbitrary smooth function. A Pauli rotation produces a very special one: the next lesson proves that for every angle of a gate , whatever the rest of the circuit is. For such functions two evaluations at the finite shifts give the derivative exactly.
Bias and variance of the parameter-shift estimator
Let be the expectation value of a Pauli observable and with independent -shot evaluations. Then and For the variance is , and the MSE equals the variance, decaying as .
Proof (5 steps)
- Step 1:and .
- Step 2:Linearity of expectation; the constant cancels. No Taylor expansion is involved, so there is no truncation error.
- Step 3:Independence of the two evaluations and the shot-noise variance ; each bracket is at most .
- Step 4:for both shifted evaluations.
- Step 5:Part (b) of the lab.
∎
Finite differences against parameter shift at θ = π/4, N = 1000
- Step 1:At both noise brackets equal ; only the squared prefactors and differ.
- Step 2:Even the best step leaves finite differences seven times worse at equal cost: both use two evaluations of shots per parameter.
- Step 3:Shots per evaluation that the optimal finite difference needs, by the asymptotic formula, to match parameter shift with shots: about times more.
- Step 4:The gap widens without bound as the shot budget grows.
Result
The default duel () shows the intermediate regime: the finite-difference spread is ten times that of parameter shift and its bias is still small. Vary and watch the optimal-step marker move as . The TypeScript cell reproduces the three regimes with the engine's shot sampler (seeded, repetitions of each estimator), and the NumPy cell evaluates every formula of this lesson exactly, including the exact binomial variance of one evaluation, the MSE minimiser and the counting bound.
import { estimatePauliExpectation, mulberry32, runStatevector, type Statevector } from '@/lib/quantum-simulator';
// f(theta) = <Z> = cos(theta) for R_Y(theta)|0>; one evaluation = mean of N shots (+1 for outcome 0, -1 for 1).
const theta = Math.PI / 4;
const N = 1000; // shots per evaluation
const R = 2000; // repetitions of each gradient estimate
const Z = { coeff: 1, ops: 'Z' };
const prepare = (angle: number): Statevector =>
runStatevector({ version: 1, numQubits: 1, numClbits: 0, ops: [{ kind: 'gate', gate: 'RY', targets: [0], params: [angle] }] });
const evaluate = (state: Statevector, rng: () => number): number => estimatePauliExpectation(state, Z, N, rng).mean;
function summarise(samples: number[]): { mean: number; variance: number; mse: number } {
const mean = samples.reduce((s, x) => s + x, 0) / samples.length;
const variance = samples.reduce((s, x) => s + (x - mean) ** 2, 0) / (samples.length - 1);
const mse = samples.reduce((s, x) => s + (x + Math.sin(theta)) ** 2, 0) / samples.length; // true f'(theta) = -sin(theta)
return { mean, variance, mse };
}
// Central finite differences [f(theta + h) - f(theta - h)] / (2h) for three step sizes.
console.log("true derivative f'(pi/4) = " + (-Math.sin(theta)).toFixed(6));
for (const h of [0.01, 0.1, 0.456]) {
const plus = prepare(theta + h);
const minus = prepare(theta - h);
const rng = mulberry32(47);
const g: number[] = [];
for (let r = 0; r < R; r++) g.push((evaluate(plus, rng) - evaluate(minus, rng)) / (2 * h));
const s = summarise(g);
const exactMean = (-Math.sin(theta) * Math.sin(h)) / h;
const exactVar = (Math.sin(theta + h) ** 2 + Math.sin(theta - h) ** 2) / (4 * h * h * N);
const exactMse = (exactMean + Math.sin(theta)) ** 2 + exactVar;
console.log('FD h = ' + h.toFixed(3) + ': mean ' + s.mean.toFixed(4) + ' (exact ' + exactMean.toFixed(4) + '), variance ' + s.variance.toExponential(3) + ' (exact ' + exactVar.toExponential(3) + '), MSE ' + s.mse.toExponential(3) + ' (exact ' + exactMse.toExponential(3) + ')');
}
// Parameter shift (1/2)[f(theta + pi/2) - f(theta - pi/2)]: unbiased, variance cos^2(theta) / (2N).
const plus = prepare(theta + Math.PI / 2);
const minus = prepare(theta - Math.PI / 2);
const rng = mulberry32(47);
const g: number[] = [];
for (let r = 0; r < R; r++) g.push(0.5 * (evaluate(plus, rng) - evaluate(minus, rng)));
const s = summarise(g);
const exactVar = Math.cos(theta) ** 2 / (2 * N);
console.log('PSR : mean ' + s.mean.toFixed(4) + ' (exact ' + (-Math.sin(theta)).toFixed(4) + '), variance ' + s.variance.toExponential(3) + ' (exact ' + exactVar.toExponential(3) + '), MSE ' + s.mse.toExponential(3) + ' (exact ' + exactVar.toExponential(3) + ')');
console.log('optimal FD step h* = (9/N)^(1/6) = ' + Math.pow(9 / N, 1 / 6).toFixed(5));Expected output
true derivative f'(pi/4) = -0.707107 FD h = 0.010: mean -0.6730 (exact -0.7071), variance 2.477e+0 (exact 2.500e+0), MSE 2.477e+0 (exact 2.500e+0) FD h = 0.100: mean -0.6992 (exact -0.7059), variance 2.404e-2 (exact 2.500e-2), MSE 2.409e-2 (exact 2.500e-2) FD h = 0.456: mean -0.6820 (exact -0.6829), variance 1.151e-3 (exact 1.202e-3), MSE 1.782e-3 (exact 1.790e-3) PSR : mean -0.7071 (exact -0.7071), variance 2.565e-4 (exact 2.500e-4), MSE 2.564e-4 (exact 2.500e-4) optimal FD step h* = (9/N)^(1/6) = 0.45608
import numpy as np
from math import lgamma, log, log2, ceil
theta, N = np.pi / 4, 1000
def var_fd(t, h, n):
return (np.sin(t + h) ** 2 + np.sin(t - h) ** 2) / (4 * h * h * n)
def bias_fd(t, h):
return -np.sin(t) * (np.sin(h) / h - 1)
def mse_fd(t, h, n):
return bias_fd(t, h) ** 2 + var_fd(t, h, n)
def var_psr(t, n):
return (np.sin(t + np.pi / 2) ** 2 + np.sin(t - np.pi / 2) ** 2) / (4 * n)
# (1) sin^2(t+h) + sin^2(t-h) = 1 - cos(2t) cos(2h) on a grid
grid = np.linspace(-3.0, 3.0, 61)
gap = max(abs(np.sin(t + h) ** 2 + np.sin(t - h) ** 2 - (1 - np.cos(2 * t) * np.cos(2 * h))) for t in grid for h in grid)
print("identity sin^2(t+h) + sin^2(t-h) = 1 - cos2t cos2h holds:", gap < 1e-12)
# (2) one evaluation: exact binomial sums for f_hat = 2k/N - 1, k ~ Bin(N, (1 + cos phi)/2)
phi = theta + 0.01
p = (1 + np.cos(phi)) / 2
logpmf = np.array([lgamma(N + 1) - lgamma(k + 1) - lgamma(N - k + 1) + k * log(p) + (N - k) * log(1 - p) for k in range(N + 1)])
pmf = np.exp(logpmf)
vals = 2 * np.arange(N + 1) / N - 1
mean = float(pmf @ vals)
var = float(pmf @ (vals - mean) ** 2)
print(f"one evaluation at pi/4 + 0.01: E = {mean:.6f}, cos = {np.cos(phi):.6f}, N Var = {N * var:.6f}, sin^2 = {np.sin(phi) ** 2:.6f}")
# (3) the lab values
print(f"Var FD (h = 0.01) = {var_fd(theta, 0.01, N):.6f}, Var PSR = {var_psr(theta, N):.6e}, ratio = {var_fd(theta, 0.01, N) / var_psr(theta, N):.1f}")
# (4) bias, variance and MSE of central differences against the step size
for h in (0.01, 0.1, 0.3, 0.456, 1.0):
print(f"h = {h:5.3f}: bias = {bias_fd(theta, h):+.3e}, f'''h^2/6 = {np.sin(theta) * h * h / 6:.3e}, Var = {var_fd(theta, h, N):.3e}, MSE = {mse_fd(theta, h, N):.3e}")
# (5) the MSE-optimal step: asymptotic formula against the exact minimiser on a fine grid
h_star = (9 / N) ** (1 / 6)
hs = np.linspace(0.30, 0.60, 300001)
h_min = hs[np.argmin(mse_fd(theta, hs, N))]
print(f"h* = (9/N)^(1/6) = {h_star:.5f}, MSE(h*) = {mse_fd(theta, h_star, N):.4e}; exact minimiser {h_min:.4f}, MSE = {mse_fd(theta, h_min, N):.4e}")
print(f"asymptotic MSE* = (3/4) 9^(-1/3) sin^2(theta) N^(-2/3) = {0.75 * 9 ** (-1 / 3) * np.sin(theta) ** 2 * N ** (-2 / 3):.4e}, PSR MSE = {var_psr(theta, N):.4e}")
# (6) FD needs N^(-2/3), PSR N^(-1): shots for the FD optimum to match PSR with 1000 shots
c = 0.75 * 9 ** (-1 / 3) * np.sin(theta) ** 2
n_fd = (c / var_psr(theta, N)) ** 1.5
print(f"asymptotic shots per FD evaluation to reach the PSR MSE at N = 1000: {n_fd:.0f}")
# (7) tomography counting bound with p_e = 0: copies >= ((2^n - 1) log2(1/(6 eps)) - 1) / n for eps = 0.01
for n in (1, 5, 10, 20, 50):
print(f"n = {n:2d}: at least {ceil(((2 ** n - 1) * log2(1 / (6 * 0.01)) - 1) / n):.4g} copies")Expected output
identity sin^2(t+h) + sin^2(t-h) = 1 - cos2t cos2h holds: True one evaluation at pi/4 + 0.01: E = 0.700000, cos = 0.700000, N Var = 0.509999, sin^2 = 0.509999 Var FD (h = 0.01) = 2.500000, Var PSR = 2.500000e-04, ratio = 10000.0 h = 0.010: bias = +1.179e-05, f'''h^2/6 = 1.179e-05, Var = 2.500e+00, MSE = 2.500e+00 h = 0.100: bias = +1.178e-03, f'''h^2/6 = 1.179e-03, Var = 2.500e-02, MSE = 2.500e-02 h = 0.300: bias = +1.056e-02, f'''h^2/6 = 1.061e-02, Var = 2.778e-03, MSE = 2.889e-03 h = 0.456: bias = +2.425e-02, f'''h^2/6 = 2.451e-02, Var = 1.202e-03, MSE = 1.790e-03 h = 1.000: bias = +1.121e-01, f'''h^2/6 = 1.179e-01, Var = 2.500e-04, MSE = 1.282e-02 h* = (9/N)^(1/6) = 0.45608, MSE(h*) = 1.7904e-03; exact minimiser 0.4585, MSE = 1.7902e-03 asymptotic MSE* = (3/4) 9^(-1/3) sin^2(theta) N^(-2/3) = 1.8028e-03, PSR MSE = 2.5000e-04 asymptotic shots per FD evaluation to reach the PSR MSE at N = 1000: 19365 n = 1: at least 4 copies n = 5: at least 25 copies n = 10: at least 416 copies n = 20: at least 2.128e+05 copies n = 50: at least 9.14e+13 copies
Quick check
For at with shots per evaluation, what is the variance of the parameter-shift estimator?
References
- K. Mitarai, M. Negoro, M. Kitagawa and K. Fujii, Quantum circuit learning, Physical Review A 98, 032309 (2018).doi:10.1103/PhysRevA.98.032309
- M. Schuld, V. Bergholm, C. Gogolin, J. Izaac and N. Killoran, Evaluating analytic gradients on quantum hardware, Physical Review A 99, 032331 (2019).doi:10.1103/PhysRevA.99.032331
- T. Jones and J. Gacon, Efficient calculation of gradients in classical simulations of variational quantum algorithms, arXiv:2009.02823 (2020).arxiv.org
- A. S. Holevo, Bounds for the quantity of information transmitted by a quantum communication channel, Problems of Information Transmission 9(3), 177–183 (1973).
- M. A. Nielsen and I. L. Chuang, Quantum Computation and Quantum Information, 10th anniversary edition, Cambridge University Press (2010), Chapters 2, 8 and 12.doi:10.1017/CBO9780511976667
- W. K. Wootters and W. H. Zurek, A single quantum cannot be cloned, Nature 299, 802–803 (1982).doi:10.1038/299802a0
- D. Dieks, Communication by EPR devices, Physics Letters A 92(6), 271–272 (1982).doi:10.1016/0375-9601(82)90084-6
- A. Griewank and A. Walther, Evaluating Derivatives: Principles and Techniques of Algorithmic Differentiation, 2nd edition, SIAM (2008).doi:10.1137/1.9780898717761
- T. M. Cover and J. A. Thomas, Elements of Information Theory, 2nd edition, Wiley (2006), Section 2.10 (Fano’s inequality).doi:10.1002/047174882X
- J. Haah, A. W. Harrow, Z. Ji, X. Wu and N. Yu, Sample-optimal tomography of quantum states, arXiv:1508.01797 (2015).arxiv.org
- R. O’Donnell and J. Wright, Efficient quantum tomography, arXiv:1508.01907 (2015).arxiv.org
- A. Abbas et al., On quantum backpropagation, information reuse, and cheating measurement collapse, arXiv:2305.13362 (2023).arxiv.org
Hands-on labs
Shot-noise variance of gradient estimators
1 step · auto-gradedOpen labCompare the two gradient estimators available on quantum hardware for of the state : the central finite difference with step and the parameter-shift rule. Both use two circuit evaluations of shots; you compute the exact shot-noise variance of each and see a factor between them.