QuantumCore

Lesson 47 · 95 min · advanced

Why Backpropagation Fails on Quantum Hardware

Loading progress…

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 ∣ψk⟩\lvert\psi_k\rangle and the adjoint states are vectors of 2n2^n 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 ε\varepsilon needs Ω(2nlog⁡(1/ε)/n)\Omega\big(2^n\log(1/\varepsilon)/n\big) circuit runs. A simulator, in contrast, can backpropagate: the adjoint method computes ∂k⟨H⟩=2 Re⟨λk∣(−iGk)∣ϕk⟩\partial_k\langle H\rangle=2\,\mathrm{Re}\langle\lambda_k\vert(-iG_k)\vert\phi_k\rangle in O(P 2n)O(P\,2^n) time and O(2n)O(2^n) 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 h∗=(9/N)1/6h^\ast=(9/N)^{1/6} for f=cos⁡θf=\cos\theta, and the unbiased parameter-shift estimator with variance cos⁡2θ/(2N)\cos^2\theta/(2N).

Prerequisites: Variational Quantum Circuits: Architecture, Supervised Learning & Gradient Descent

Objectives and key results
  • State the reverse-mode recursion xˉk−1=xˉk ∂Fk/∂xk−1\bar x_{k-1}=\bar x_k\,\partial F_k/\partial x_{k-1}, identify what it stores, and translate it to a circuit, where the intermediates are the states ∣ψk⟩∈C2n\lvert\psi_k\rangle\in\mathbb C^{2^n}.

  • Explain the three hardware obstructions (samples only, measurement collapse, no-cloning) and prove that estimating an arbitrary nn-qubit pure state to precision ε\varepsilon needs at least [(1−pe)(2n−1)log⁡216ε−1]/n\big[(1-p_e)(2^n-1)\log_2\frac1{6\varepsilon}-1\big]/n copies.

  • Derive the adjoint method ∂k⟨H⟩=2 Re⟨λk∣(−iGk)∣ϕk⟩\partial_k\langle H\rangle=2\,\mathrm{Re}\langle\lambda_k\vert(-iG_k)\vert\phi_k\rangle with ∣ϕk−1⟩=Uk†∣ϕk⟩\lvert\phi_{k-1}\rangle=U_k^\dagger\lvert\phi_k\rangle, ∣λk−1⟩=Uk†∣λk⟩\lvert\lambda_{k-1}\rangle=U_k^\dagger\lvert\lambda_k\rangle, and its cost O(P 2n)O(P\,2^n) time, O(2n)O(2^n) memory.

  • Derive the variance (1−f+2)+(1−f−2)4h2N\frac{(1-f_+^2)+(1-f_-^2)}{4h^2N} and the bias f′′′(θ)6h2+O(h4)\frac{f'''(\theta)}6h^2+O(h^4) of the central finite-difference estimator, and the MSE-optimal step h∗∝N−1/6h^\ast\propto N^{-1/6} with minimal MSE ∝N−2/3\propto N^{-2/3}.

  • Show that the parameter-shift estimator is unbiased with variance (1−f(θ+π2)2)+(1−f(θ−π2)2)4N\frac{(1-f(\theta+\frac\pi2)^2)+(1-f(\theta-\frac\pi2)^2)}{4N}, whose MSE decays as N−1N^{-1}.

theorem · Counting bound for reading out a state
N ≥ (1−pe) (2n−1)log⁡216ε−1n=Ω(2nlog⁡(1/ε)n)copiesN\ \ge\ \frac{(1-p_e)\,(2^n-1)\log_2\frac{1}{6\varepsilon}-1}{n}=\Omega\Big(\frac{2^n\log(1/\varepsilon)}{n}\Big)\quad\text{copies}
formula · Adjoint method
∂⟨H⟩∂θk=2 Re⟨λk∣(−iGk)∣ϕk⟩,∣ϕk−1⟩=Uk†∣ϕk⟩,∣λk−1⟩=Uk†∣λk⟩,∣λP⟩=H∣ϕP⟩\frac{\partial\langle H\rangle}{\partial\theta_k}=2\,\mathrm{Re}\langle\lambda_k\vert(-iG_k)\vert\phi_k\rangle,\qquad\lvert\phi_{k-1}\rangle=U_k^\dagger\lvert\phi_k\rangle,\quad\lvert\lambda_{k-1}\rangle=U_k^\dagger\lvert\lambda_k\rangle,\quad\lvert\lambda_P\rangle=H\lvert\phi_P\rangle
formula · Central finite differences under shot noise
Var[g^FD]=(1−f+2)+(1−f−2)4h2N,E[g^FD]−f′(θ)=f′′′(θ)6h2+O(h4)\mathrm{Var}[\hat g_{\mathrm{FD}}]=\frac{(1-f_+^2)+(1-f_-^2)}{4h^2N},\qquad\mathbb E[\hat g_{\mathrm{FD}}]-f'(\theta)=\frac{f'''(\theta)}{6}h^2+O(h^4)
formula · MSE-optimal finite-difference step
h∗=(9σ2(f′′′)2N)1/6,MSE(h∗)=34 9−1/3σ4/3∣f′′′∣2/3N−2/3;f=cos⁡θ: h∗=(9/N)1/6h^\ast=\Big(\frac{9\sigma^2}{(f''')^2N}\Big)^{1/6},\qquad\mathrm{MSE}(h^\ast)=\frac34\,9^{-1/3}\sigma^{4/3}\lvert f'''\rvert^{2/3}N^{-2/3};\qquad f=\cos\theta:\ h^\ast=(9/N)^{1/6}
formula · Parameter-shift estimator
g^PSR=12[f^(θ+π2)−f^(θ−π2)],E[g^PSR]=f′(θ),Var[g^PSR]=(1−f(θ+π2)2)+(1−f(θ−π2)2)4N\hat g_{\mathrm{PSR}}=\tfrac12\big[\hat f(\theta+\tfrac\pi2)-\hat f(\theta-\tfrac\pi2)\big],\qquad\mathbb E[\hat g_{\mathrm{PSR}}]=f'(\theta),\qquad\mathrm{Var}[\hat g_{\mathrm{PSR}}]=\frac{(1-f(\theta+\frac\pi2)^2)+(1-f(\theta-\frac\pi2)^2)}{4N}

What backpropagation needs#

The previous lesson ended with a training loop in which the quantum processor supplies the derivatives ∂f/∂θj\partial f/\partial\theta_j 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 x0∈Rm0x_0\in\mathbb R^{m_0} be fixed and xk=Fk(xk−1;θk)∈Rmkx_k=F_k(x_{k-1};\theta_k)\in\mathbb R^{m_k} for k=1,…,Pk=1,\dots,P, with a scalar loss L(θ)=ℓ(xP)L(\theta)=\ell(x_P). Reverse mode first runs the forward pass, computing and storing x0,…,xPx_0,\dots,x_P (the tape). It then runs the backward pass: starting from the adjoint xˉP=∇ℓ(xP)\bar x_P=\nabla\ell(x_P) (a row vector) it computes xˉk−1=xˉk ∂Fk∂xk−1∣xk−1,∂L∂θk=xˉk ∂Fk∂θk∣xk−1,k=P,…,1.\bar x_{k-1}=\bar x_k\,\frac{\partial F_k}{\partial x_{k-1}}\Big\rvert_{x_{k-1}},\qquad\frac{\partial L}{\partial\theta_k}=\bar x_k\,\frac{\partial F_k}{\partial\theta_k}\Big\rvert_{x_{k-1}},\qquad k=P,\dots,1 . Backpropagation in neural networks is this algorithm applied to a layered network.

Proposition

Correctness and cost of reverse mode

The backward recursion returns the exact gradient ∇θL\nabla_\theta L. It performs one vector–Jacobian product per stage, so its cost is a constant multiple of the forward pass, independent of the number PP of parameters, and it needs every stored intermediate xk−1x_{k-1} at the moment stage kk is processed.

Proof (5 steps)
  1. Step 1:
    ∂L∂θk=∇ℓ(xP) ∂xP∂xk ∂xk∂θk\frac{\partial L}{\partial\theta_k}=\nabla\ell(x_P)\,\frac{\partial x_P}{\partial x_k}\,\frac{\partial x_k}{\partial\theta_k}
    θk\theta_k enters LL only through xk=Fk(xk−1;θk)x_k=F_k(x_{k-1};\theta_k); chain rule for the composition xk↦xk+1↦⋯↦xPx_k\mapsto x_{k+1}\mapsto\dots\mapsto x_P.
  2. Step 2:
    ∂xP∂xk=JP JP−1⋯Jk+1,Jj=∂Fj∂xj−1∣xj−1\frac{\partial x_P}{\partial x_k}=J_P\,J_{P-1}\cdots J_{k+1},\qquad J_j=\frac{\partial F_j}{\partial x_{j-1}}\Big\rvert_{x_{j-1}}
    The chain rule once more; each Jacobian is evaluated at the intermediate value of its own stage.
  3. Step 3:
    xˉk:=∇ℓ(xP) JP⋯Jk+1 ⇒ xˉP=∇ℓ(xP),xˉk−1=xˉk Jk\bar x_k:=\nabla\ell(x_P)\,J_P\cdots J_{k+1}\ \Rightarrow\ \bar x_P=\nabla\ell(x_P),\quad\bar x_{k-1}=\bar x_k\,J_k
    Peel off one factor at a time: multiplying from the left keeps every intermediate a row vector, never a matrix.
  4. Step 4:
    ∂L∂θk=xˉk ∂Fk∂θk∣xk−1\frac{\partial L}{\partial\theta_k}=\bar x_k\,\frac{\partial F_k}{\partial\theta_k}\Big\rvert_{x_{k-1}}
    Substitute the definition of xˉk\bar x_k into the first line.
  5. Step 5:
    cost(∇θL)=∑k=1Pcost(xˉk↦xˉkJk) ≤ c⋅cost(L)\text{cost}(\nabla_\theta L)=\sum_{k=1}^P\text{cost}(\bar x_k\mapsto\bar x_kJ_k)\ \le\ c\cdot\text{cost}(L)
    A vector–Jacobian product of stage kk costs a bounded multiple of evaluating FkF_k (the cheap-gradient principle, Griewank and Walther). The Jacobians depend on xk−1x_{k-1}, which must therefore be stored on the tape or recomputed.

∎

Derivation

Reverse mode applied to a circuit

  1. Step 1:
    ∣ψ0⟩=∣0n⟩,∣ψk⟩=Uk(θk)∣ψk−1⟩,f(θ)=⟨ψP∣H∣ψP⟩\lvert\psi_0\rangle=\lvert0^n\rangle,\qquad\lvert\psi_k\rangle=U_k(\theta_k)\lvert\psi_{k-1}\rangle,\qquad f(\theta)=\langle\psi_P\vert H\vert\psi_P\rangle
    A circuit of PP gates is a composition of stages whose intermediates are the states ∣ψk⟩∈C2n\lvert\psi_k\rangle\in\mathbb C^{2^n}.
  2. Step 2:
    Uk(θk)=e−iθkGk,∂Uk∂θk=−iGkUkU_k(\theta_k)=e^{-i\theta_kG_k},\qquad\frac{\partial U_k}{\partial\theta_k}=-iG_kU_k
    Every parameterised gate is generated by a Hermitian GkG_k; for RP(θ)=e−iθP/2R_P(\theta)=e^{-i\theta P/2} the generator is G=P/2G=P/2.
  3. Step 3:
    xˉk ⟷ ⟨λk∣=⟨ψP∣H UP⋯Uk+1\bar x_k\ \longleftrightarrow\ \langle\lambda_k\vert=\langle\psi_P\vert H\,U_P\cdots U_{k+1}
    The stage maps are linear, Jk=UkJ_k=U_k, and the loss is the quadratic form of HH: the adjoint is a bra of dimension 2n2^n, propagated backwards through the gates.
  4. Step 4:
    ∂f∂θk=2 Re ⟨λk∣(−iGk)∣ψk⟩\frac{\partial f}{\partial\theta_k}=2\,\mathrm{Re}\,\langle\lambda_k\vert(-iG_k)\vert\psi_k\rangle
    The derivative of a quadratic form; the adjoint-method theorem below gives the proof.

Result

reverse mode needs, for every k, the 2n complex amplitudes of ∣ψk⟩ and of ∣λk⟩\boxed{\text{reverse mode needs, for every }k,\ \text{the }2^n\text{ complex amplitudes of }\lvert\psi_k\rangle\text{ and of }\lvert\lambda_k\rangle}

Why a quantum processor cannot run the backward pass#

A quantum processor applies the gates UkU_k 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.

  1. Only samples are observable. A run of an nn-qubit circuit ending in a measurement yields one outcome, at most nn classical bits. Amplitudes appear only through outcome frequencies.
  2. Measurement collapses the state. After the outcome bb is recorded, the post-measurement state is ∣b⟩\lvert b\rangle; reading the register destroys the intermediate ∣ψk⟩\lvert\psi_k\rangle that the backward pass needs.
  3. States cannot be copied. One might try to duplicate ∣ψk⟩\lvert\psi_k\rangle, measure one copy and continue the circuit with the other. The theorem of the lesson The No-Cloning Theorem rules this out.
Theorem

No-cloning (recalled)

There is no unitary VV on H⊗H\mathcal H\otimes\mathcal H and fixed state ∣s⟩\lvert s\rangle with V(∣ψ⟩⊗∣s⟩)=∣ψ⟩⊗∣ψ⟩V\big(\lvert\psi\rangle\otimes\lvert s\rangle\big)=\lvert\psi\rangle\otimes\lvert\psi\rangle for every state ∣ψ⟩\lvert\psi\rangle. Consequently a circuit cannot store a copy of ∣ψk⟩\lvert\psi_k\rangle for later use while continuing to compute with it. (Proved in the lesson The No-Cloning Theorem; Wootters and Zurek, Dieks.)

Proof (4 steps)
  1. Step 1:
    V(∣ψ⟩∣s⟩)=∣ψ⟩∣ψ⟩,V(∣φ⟩∣s⟩)=∣φ⟩∣φ⟩V(\lvert\psi\rangle\lvert s\rangle)=\lvert\psi\rangle\lvert\psi\rangle,\quad V(\lvert\varphi\rangle\lvert s\rangle)=\lvert\varphi\rangle\lvert\varphi\rangle
    Assume such a VV exists and apply it to two arbitrary states.
  2. Step 2:
    ⟨ψ∣φ⟩⟨s∣s⟩=⟨ψ∣φ⟩2\langle\psi\vert\varphi\rangle\langle s\vert s\rangle=\langle\psi\vert\varphi\rangle^2
    Take the inner product of the two equations; V†V=IV^\dagger V=I on the left, and inner products of product states factorise on the right.
  3. Step 3:
    ⟨ψ∣φ⟩=⟨ψ∣φ⟩2 ⇒ ⟨ψ∣φ⟩∈{0,1}\langle\psi\vert\varphi\rangle=\langle\psi\vert\varphi\rangle^2\ \Rightarrow\ \langle\psi\vert\varphi\rangle\in\{0,1\}
    ⟨s∣s⟩=1\langle s\vert s\rangle=1, and z=z2z=z^2 has the solutions 00 and 11.
  4. Step 4:
    ∣ψ⟩=∣0⟩, ∣φ⟩=∣+⟩:⟨0∣+⟩=12∉{0,1}\lvert\psi\rangle=\lvert0\rangle,\ \lvert\varphi\rangle=\lvert+\rangle:\quad\langle0\vert+\rangle=\tfrac1{\sqrt2}\notin\{0,1\}
    Two states that are neither equal nor orthogonal give a contradiction, so no universal cloner exists.

∎

Each attempt to learn something about ∣ψk⟩\lvert\psi_k\rangle therefore consumes one run of the first kk 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, D(ψ,φ)=min⁡α∥ψ−eiαφ∥D(\psi,\varphi)=\min_\alpha\lVert\psi-e^{i\alpha}\varphi\rVert, which satisfies the triangle inequality.

Lemma

States with nonnegative amplitudes

Let d=2n−1d=2^n-1 and K={x∈Rd: xi≥0, ∥x∥≤1}K=\{x\in\mathbb R^d:\ x_i\ge0,\ \lVert x\rVert\le1\}. For x∈Kx\in K define ∣ψ(x)⟩=1−∥x∥2 ∣0⟩+∑i=1dxi∣i⟩\lvert\psi(x)\rangle=\sqrt{1-\lVert x\rVert^2}\,\lvert0\rangle+\sum_{i=1}^dx_i\lvert i\rangle. Then ∣ψ(x)⟩\lvert\psi(x)\rangle is a unit vector and D(ψ(x),ψ(y))≥∥x−y∥D\big(\psi(x),\psi(y)\big)\ge\lVert x-y\rVert for all x,y∈Kx,y\in K.

Proof (5 steps)
  1. Step 1:
    ∥ψ(x)∥2=1−∥x∥2+∑i=1dxi2=1\lVert\psi(x)\rVert^2=1-\lVert x\rVert^2+\sum_{i=1}^dx_i^2=1
    The basis {∣i⟩}\{\lvert i\rangle\} is orthonormal.
  2. Step 2:
    ∥ψ−eiαφ∥2=2−2 Re(eiα⟨ψ∣φ⟩) ⇒ D(ψ,φ)2=2−2∣⟨ψ∣φ⟩∣\lVert\psi-e^{i\alpha}\varphi\rVert^2=2-2\,\mathrm{Re}\big(e^{i\alpha}\langle\psi\vert\varphi\rangle\big)\ \Rightarrow\ D(\psi,\varphi)^2=2-2\lvert\langle\psi\vert\varphi\rangle\rvert
    Expand the squared norm of a difference of unit vectors; the real part is maximal, equal to the modulus, for the optimal phase.
  3. Step 3:
    ⟨ψ(x)∣ψ(y)⟩=1−∥x∥21−∥y∥2+∑ixiyi ≥ 0\langle\psi(x)\vert\psi(y)\rangle=\sqrt{1-\lVert x\rVert^2}\sqrt{1-\lVert y\rVert^2}+\sum_ix_iy_i\ \ge\ 0
    All amplitudes are real and nonnegative, so the overlap equals its modulus.
  4. Step 4:
    D(ψ(x),ψ(y))2=2−2⟨ψ(x)∣ψ(y)⟩=∥ψ(x)−ψ(y)∥2D\big(\psi(x),\psi(y)\big)^2=2-2\langle\psi(x)\vert\psi(y)\rangle=\lVert\psi(x)-\psi(y)\rVert^2
    For such states the optimal phase is α=0\alpha=0: the phase-invariant distance is the plain Euclidean one.
  5. Step 5:
    ∥ψ(x)−ψ(y)∥2=(1−∥x∥2−1−∥y∥2)2+∥x−y∥2 ≥ ∥x−y∥2\lVert\psi(x)-\psi(y)\rVert^2=\big(\sqrt{1-\lVert x\rVert^2}-\sqrt{1-\lVert y\rVert^2}\big)^2+\lVert x-y\rVert^2\ \ge\ \lVert x-y\rVert^2
    The coordinates 1,…,d1,\dots,d of ψ(x)\psi(x) are those of xx; the extra coordinate only adds a square.

∎

Lemma

Many well-separated points

For every 0<δ≤120<\delta\le\frac12 the set KK contains M≥(2δ)−dM\ge(2\delta)^{-d} points whose pairwise distances all exceed δ\delta.

Proof (5 steps)
  1. Step 1:
    ∥xi−xj∥>δ ⇒ B(xi,δ2)∩B(xj,δ2)=∅\lVert x_i-x_j\rVert>\delta\ \Rightarrow\ B(x_i,\tfrac\delta2)\cap B(x_j,\tfrac\delta2)=\varnothing
    Choose points greedily, each farther than δ\delta from all previous ones. The balls of radius δ2\frac\delta2 around them are disjoint and lie in the bounded set {∥x∥≤1+δ2}\{\lVert x\rVert\le1+\frac\delta2\}, so the process stops after finitely many points: the set {x1,…,xM}\{x_1,\dots,x_M\} is maximal.
  2. Step 2:
    K⊆⋃m=1MBˉ(xm,δ)K\subseteq\bigcup_{m=1}^M\bar B(x_m,\delta)
    Maximality: a point of KK at distance more than δ\delta from every xmx_m could still be added.
  3. Step 3:
    vol(K)≤M δd vol(Bd)\mathrm{vol}(K)\le M\,\delta^d\,\mathrm{vol}(B^d)
    Subadditivity of volume; a ball of radius δ\delta in Rd\mathbb R^d has volume δd vol(Bd)\delta^d\,\mathrm{vol}(B^d), with BdB^d the unit ball.
  4. Step 4:
    vol(K)=2−d vol(Bd)\mathrm{vol}(K)=2^{-d}\,\mathrm{vol}(B^d)
    The unit ball is the union of the 2d2^d reflections of KK by sign changes of coordinates, which are congruent and overlap only on coordinate hyperplanes, a set of volume zero.
  5. Step 5:
    M ≥ 2−dδd=(2δ)−dM\ \ge\ \frac{2^{-d}}{\delta^d}=(2\delta)^{-d}
    Combine the last two lines.

∎

Theorem

Reading out an n-qubit state needs exponentially many copies

Let 0<ε<160<\varepsilon<\frac16 and 0≤pe<10\le p_e<1. Suppose a procedure receives NN copies of an unknown nn-qubit pure state ∣ψ⟩\lvert\psi\rangle, measures them in any way (one at a time, adaptively, or jointly), and outputs a classical description of a unit vector ψ^\hat\psi with D(ψ^,ψ)≤εD(\hat\psi,\psi)\le\varepsilon with probability at least 1−pe1-p_e, for every ∣ψ⟩\lvert\psi\rangle. Then N ≥ (1−pe) (2n−1)log⁡216ε−1n.N\ \ge\ \frac{(1-p_e)\,(2^n-1)\log_2\frac1{6\varepsilon}-1}{n}. For ε≤136\varepsilon\le\frac1{36} this is N=Ω(2nlog⁡(1/ε)/n)N=\Omega\big(2^n\log(1/\varepsilon)/n\big).

Proof (8 steps)
  1. Step 1:
    {x1,…,xM}⊂K,∥xm−xm′∥>3ε,M≥(6ε)−d,ψm=ψ(xm)\{x_1,\dots,x_M\}\subset K,\quad\lVert x_m-x_{m'}\rVert>3\varepsilon,\quad M\ge(6\varepsilon)^{-d},\qquad\psi_m=\psi(x_m)
    The packing lemma with δ=3ε≤12\delta=3\varepsilon\le\frac12. By the orthant lemma the states satisfy D(ψm,ψm′)>3εD(\psi_m,\psi_{m'})>3\varepsilon for m≠m′m\ne m'.
  2. Step 2:
    X∼Unif{1,…,M},ρX=(∣ψX⟩⟨ψX∣)⊗N →measure Y ⟶ X^=arg min⁡mD(ψ^(Y),ψm)X\sim\mathrm{Unif}\{1,\dots,M\},\qquad\rho_X=\big(\lvert\psi_X\rangle\langle\psi_X\rvert\big)^{\otimes N}\ \xrightarrow{\text{measure}}\ Y\ \longrightarrow\ \hat X=\operatorname*{arg\,min}_mD\big(\hat\psi(Y),\psi_m\big)
    Feed the procedure a uniformly random packing state; YY is its complete classical record (an adaptive scheme is one measurement on the NN copies), and X^\hat X rounds its output to the nearest packing state.
  3. Step 3:
    D(ψ^,ψX)≤ε ⇒ D(ψ^,ψm)≥D(ψX,ψm)−D(ψ^,ψX)>2ε  (m≠X) ⇒ X^=XD(\hat\psi,\psi_X)\le\varepsilon\ \Rightarrow\ D(\hat\psi,\psi_m)\ge D(\psi_X,\psi_m)-D(\hat\psi,\psi_X)>2\varepsilon\ \ (m\ne X)\ \Rightarrow\ \hat X=X
    Triangle inequality for DD. Hence Pr⁡(X^≠X)≤pe\Pr(\hat X\ne X)\le p_e.
  4. Step 4:
    I(X;X^)=H(X)−H(X∣X^) ≥ log⁡2M−(1+pelog⁡2M)=(1−pe)log⁡2M−1I(X;\hat X)=H(X)-H(X\vert\hat X)\ \ge\ \log_2M-\big(1+p_e\log_2M\big)=(1-p_e)\log_2M-1
    Fano's inequality H(X∣X^)≤h(pe)+pelog⁡2MH(X\vert\hat X)\le h(p_e)+p_e\log_2M with the binary entropy h≤1h\le1, and H(X)=log⁡2MH(X)=\log_2M for the uniform distribution.
  5. Step 5:
    I(X;X^) ≤ I(X;Y)I(X;\hat X)\ \le\ I(X;Y)
    Data-processing inequality: X^\hat X is a function of YY.
  6. Step 6:
    I(X;Y) ≤ S(1M∑mρm)−1M∑mS(ρm) ≤ log⁡2dim⁡(H⊗N)=nNI(X;Y)\ \le\ S\Big(\frac1M\sum_m\rho_m\Big)-\frac1M\sum_mS(\rho_m)\ \le\ \log_2\dim\big(\mathcal H^{\otimes N}\big)=nN
    Holevo's bound for the ensemble {1M,ρm}\{\frac1M,\rho_m\} (Nielsen and Chuang, Theorem 12.1). Each ρm\rho_m is pure, so S(ρm)=0S(\rho_m)=0, and the entropy of any state of nNnN qubits is at most nNnN bits.
  7. Step 7:
    nN ≥ (1−pe)log⁡2M−1 ≥ (1−pe) (2n−1)log⁡216ε−1nN\ \ge\ (1-p_e)\log_2M-1\ \ge\ (1-p_e)\,(2^n-1)\log_2\tfrac1{6\varepsilon}-1
    Chain the inequalities and insert log⁡2M≥dlog⁡216ε\log_2M\ge d\log_2\frac1{6\varepsilon} with d=2n−1d=2^n-1.
  8. Step 8:
    ε≤136 ⇒ 16ε≥ε−1/2 ⇒ log⁡216ε≥12log⁡21ε\varepsilon\le\tfrac1{36}\ \Rightarrow\ \tfrac1{6\varepsilon}\ge\varepsilon^{-1/2}\ \Rightarrow\ \log_2\tfrac1{6\varepsilon}\ge\tfrac12\log_2\tfrac1\varepsilon
    6ε≤ε1/26\varepsilon\le\varepsilon^{1/2} is equivalent to ε1/2≤16\varepsilon^{1/2}\le\frac16. With a fixed pe<1p_e<1 the bound becomes Ω(2nlog⁡(1/ε)/n)\Omega\big(2^n\log(1/\varepsilon)/n\big).

∎

For ε=0.01\varepsilon=0.01 and an error-free procedure (pe=0p_e=0) the counting bound evaluates to at least 416416 copies for n=10n=10 and 9.14×10139.14\times10^{13} copies for n=50n=50 (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 ∣ψ1⟩,…,∣ψP⟩\lvert\psi_1\rangle,\dots,\lvert\psi_P\rangle that reverse-mode differentiation reuses in its backward pass?

Select one answer

Simulators can backpropagate: the adjoint method#

A statevector simulator holds ∣ψk⟩\lvert\psi_k\rangle as an array of 2n2^n complex numbers, so nothing prevents reverse mode there. Storing the whole tape costs PP 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.

Theorem

Adjoint differentiation of an expectation value

Let U(θ)=UP⋯U1U(\theta)=U_P\cdots U_1 with Uk=e−iθkGkU_k=e^{-i\theta_kG_k}, Gk=Gk†G_k=G_k^\dagger (a fixed gate is a stage without parameter), and f(θ)=⟨0∣U†HU∣0⟩f(\theta)=\langle0\vert U^\dagger HU\vert0\rangle. Define ∣ϕk⟩=Uk⋯U1∣0⟩\lvert\phi_k\rangle=U_k\cdots U_1\lvert0\rangle and ∣λk⟩=Uk+1†⋯UP†H∣ϕP⟩\lvert\lambda_k\rangle=U_{k+1}^\dagger\cdots U_P^\dagger H\lvert\phi_P\rangle. Then ∂f∂θk=2 Re ⟨λk∣(−iGk)∣ϕk⟩=2 Im ⟨λk∣Gk∣ϕk⟩,\frac{\partial f}{\partial\theta_k}=2\,\mathrm{Re}\,\langle\lambda_k\vert(-iG_k)\vert\phi_k\rangle=2\,\mathrm{Im}\,\langle\lambda_k\vert G_k\vert\phi_k\rangle, and both sequences are generated backwards from ∣ϕP⟩\lvert\phi_P\rangle and ∣λP⟩=H∣ϕP⟩\lvert\lambda_P\rangle=H\lvert\phi_P\rangle by ∣ϕk−1⟩=Uk†∣ϕk⟩\lvert\phi_{k-1}\rangle=U_k^\dagger\lvert\phi_k\rangle and ∣λk−1⟩=Uk†∣λk⟩\lvert\lambda_{k-1}\rangle=U_k^\dagger\lvert\lambda_k\rangle.

Proof (6 steps)
  1. Step 1:
    ∂∂θke−iθkGk=∑m≥1m(−iGk)mθkm−1m!=−iGk e−iθkGk\frac{\partial}{\partial\theta_k}e^{-i\theta_kG_k}=\sum_{m\ge1}\frac{m(-iG_k)^m\theta_k^{m-1}}{m!}=-iG_k\,e^{-i\theta_kG_k}
    Differentiate the absolutely convergent exponential series term by term; GkG_k commutes with its own exponential.
  2. Step 2:
    ∂∣ϕP⟩∂θk=UP⋯Uk+1 (−iGk) Uk⋯U1∣0⟩=Vk (−iGk)∣ϕk⟩,Vk=UP⋯Uk+1\frac{\partial\lvert\phi_P\rangle}{\partial\theta_k}=U_P\cdots U_{k+1}\,(-iG_k)\,U_k\cdots U_1\lvert0\rangle=V_k\,(-iG_k)\lvert\phi_k\rangle,\qquad V_k=U_P\cdots U_{k+1}
    Product rule: only the factor UkU_k depends on θk\theta_k.
  3. Step 3:
    ∂f∂θk=⟨∂kϕP∣H∣ϕP⟩+⟨ϕP∣H∣∂kϕP⟩=2 Re ⟨ϕP∣H∣∂kϕP⟩\frac{\partial f}{\partial\theta_k}=\langle\partial_k\phi_P\vert H\vert\phi_P\rangle+\langle\phi_P\vert H\vert\partial_k\phi_P\rangle=2\,\mathrm{Re}\,\langle\phi_P\vert H\vert\partial_k\phi_P\rangle
    f=⟨ϕP∣H∣ϕP⟩f=\langle\phi_P\vert H\vert\phi_P\rangle, and since H=H†H=H^\dagger the first term is the complex conjugate of the second.
  4. Step 4:
    ⟨ϕP∣HVk=(Vk†H∣ϕP⟩)†=⟨λk∣ ⇒ ∂f∂θk=2 Re ⟨λk∣(−iGk)∣ϕk⟩\langle\phi_P\vert HV_k=\big(V_k^\dagger H\lvert\phi_P\rangle\big)^\dagger=\langle\lambda_k\vert\ \Rightarrow\ \frac{\partial f}{\partial\theta_k}=2\,\mathrm{Re}\,\langle\lambda_k\vert(-iG_k)\vert\phi_k\rangle
    (AB)†=B†A†(AB)^\dagger=B^\dagger A^\dagger and H†=HH^\dagger=H; Vk†=Uk+1†⋯UP†V_k^\dagger=U_{k+1}^\dagger\cdots U_P^\dagger is the definition of ∣λk⟩\lvert\lambda_k\rangle.
  5. Step 5:
    Vk−1=VkUk ⇒ ∣λk−1⟩=Uk†∣λk⟩,∣ϕk−1⟩=Uk†Uk∣ϕk−1⟩=Uk†∣ϕk⟩V_{k-1}=V_kU_k\ \Rightarrow\ \lvert\lambda_{k-1}\rangle=U_k^\dagger\lvert\lambda_k\rangle,\qquad\lvert\phi_{k-1}\rangle=U_k^\dagger U_k\lvert\phi_{k-1}\rangle=U_k^\dagger\lvert\phi_k\rangle
    Unitarity Uk†Uk=IU_k^\dagger U_k=I: the forward states are recovered by undoing one gate at a time, so they need not be stored.
  6. Step 6:
    Re(−iz)=Im z ⇒ ∂f∂θk=2 Im ⟨λk∣Gk∣ϕk⟩=Gk=P/2Im ⟨λk∣P∣ϕk⟩\mathrm{Re}(-iz)=\mathrm{Im}\,z\ \Rightarrow\ \frac{\partial f}{\partial\theta_k}=2\,\mathrm{Im}\,\langle\lambda_k\vert G_k\vert\phi_k\rangle\overset{G_k=P/2}{=}\mathrm{Im}\,\langle\lambda_k\vert P\vert\phi_k\rangle
    For z=a+ibz=a+ib, −iz=b−ia-iz=b-ia. For a Pauli rotation RP(θ)R_P(\theta) the generator is P/2P/2; this is the formula used in the code cell.

∎

Proposition

Cost of the adjoint method

For a circuit of PP gates, each acting on a bounded number of qubits, and an observable with KK Pauli terms, the adjoint method computes ff and all PP partial derivatives in time O((P+K) 2n)O\big((P+K)\,2^n\big) with three statevectors, i.e. O(2n)O(2^n) memory. Storing the tape instead needs (P+1) 2n(P+1)\,2^n amplitudes, O(P 2n)O(P\,2^n) memory, and evaluating the parameter-shift rule on the simulator needs 2P+12P+1 simulations, O(P2 2n)O(P^2\,2^n) time.

Proof (5 steps)
  1. Step 1:
    one gate on ∣ϕ⟩∈C2n: O(2n)\text{one gate on }\lvert\phi\rangle\in\mathbb C^{2^n}:\ O(2^n)
    A kk-qubit gate updates the 2n−k2^{n-k} groups of 2k2^k amplitudes once each.
  2. Step 2:
    ∣ϕP⟩: P⋅O(2n),∣λP⟩=∑j=1KcjPj∣ϕP⟩: K⋅O(2n)\lvert\phi_P\rangle:\ P\cdot O(2^n),\qquad\lvert\lambda_P\rangle=\sum_{j=1}^Kc_jP_j\lvert\phi_P\rangle:\ K\cdot O(2^n)
    Forward pass gate by gate; a Pauli string permutes the amplitudes and multiplies them by phases.
  3. Step 3:
    k=P,…,1:  ∣μ⟩=Gk∣ϕk⟩,  Im⟨λk∣μ⟩,  ∣ϕk−1⟩=Uk†∣ϕk⟩,  ∣λk−1⟩=Uk†∣λk⟩k=P,\dots,1:\ \ \lvert\mu\rangle=G_k\lvert\phi_k\rangle,\ \ \mathrm{Im}\langle\lambda_k\vert\mu\rangle,\ \ \lvert\phi_{k-1}\rangle=U_k^\dagger\lvert\phi_k\rangle,\ \ \lvert\lambda_{k-1}\rangle=U_k^\dagger\lvert\lambda_k\rangle
    Each iteration costs a constant number of O(2n)O(2^n) operations, O(P 2n)O(P\,2^n) in total, and holds only ϕ\phi, λ\lambda and the scratch vector μ\mu.
  4. Step 4:
    tape: (P+1) 2n amplitudes;n=20, P=1000: 1001×16 MiB≈15.6 GiB vs. 3×16 MiB\text{tape}:\ (P+1)\,2^n\ \text{amplitudes};\qquad n=20,\ P=1000:\ 1001\times16\,\text{MiB}\approx15.6\,\text{GiB}\ \text{vs.}\ 3\times16\,\text{MiB}
    A complex double occupies 1616 bytes, so one 2020-qubit statevector takes 220⋅162^{20}\cdot16 bytes =16=16 MiB.
  5. Step 5:
    (2P+1)⋅O((P+K) 2n)=O(P2 2n) for K=O(P)(2P+1)\cdot O\big((P+K)\,2^n\big)=O\big(P^2\,2^n\big)\ \text{for}\ K=O(P)
    Each of the 2P+12P+1 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 ∣λP⟩=H∣ϕP⟩\lvert\lambda_P\rangle=H\lvert\phi_P\rangle, and walks backwards through the gates, reading off ∂kf=Im⟨λk∣Pk∣ϕk⟩\partial_kf=\mathrm{Im}\langle\lambda_k\vert P_k\vert\phi_k\rangle before undoing gate kk on both vectors. The result agrees with the engine's parameter-shift gradient to machine precision, after 4848 gate applications instead of 2525 full circuit simulations.

TypeScriptrunnable
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 simulatorquantum processor
state after gate kkan array of 2n2^n amplitudesa physical register, read only by sampling
copiesfreeforbidden (no-cloning)
adjoint ⟨λk∣\langle\lambda_k\rvertcomputed and reused for all kknever available as data
gradient costO(P 2n)O(P\,2^n) time, O(2n)O(2^n) memory2P2P circuits, each repeated NN times
scaling in nnexponential memorypolynomial in nn per run

The two settings fail in opposite ways. The simulator has every amplitude but pays 2n2^n for each vector; the hardware runs large circuits but reveals almost nothing per run.

Quick check

A simulator differentiates a 2525-qubit circuit with P=500P=500 rotation gates. How does the memory of the adjoint method compare with storing the tape of all intermediate states?

Select one answer

Finite differences under shot noise#

Hardware gives access to the function f(θ)=⟨H⟩θf(\theta)=\langle H\rangle_\theta 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 NN fresh shots, and different evaluations are independent.

Definition

Shot estimate and central finite-difference estimator

For an angle φ\varphi the evaluation f^(φ)=1N∑s=1Nzs\hat f(\varphi)=\frac1N\sum_{s=1}^Nz_s is the mean of NN independent outcomes zs∈{±1}z_s\in\{\pm1\} of the circuit at angle φ\varphi; by the shot-noise theorem of the lesson on variational circuits, E[f^(φ)]=f(φ)\mathbb E[\hat f(\varphi)]=f(\varphi) and Var[f^(φ)]=1−f(φ)2N\mathrm{Var}[\hat f(\varphi)]=\frac{1-f(\varphi)^2}N. The central finite-difference estimator with step h>0h>0 is g^FD(h)=f^(θ+h)−f^(θ−h)2h,\hat g_{\mathrm{FD}}(h)=\frac{\hat f(\theta+h)-\hat f(\theta-h)}{2h}, built from two independent evaluations. Write f±=f(θ±h)f_\pm=f(\theta\pm h).

Theorem

Variance and bias of central finite differences

(a) Var[g^FD]=(1−f+2)+(1−f−2)4h2N\mathrm{Var}[\hat g_{\mathrm{FD}}]=\dfrac{(1-f_+^2)+(1-f_-^2)}{4h^2N}. (b) If ff is five times continuously differentiable and M5=max⁡∣ξ−θ∣≤h∣f(5)(ξ)∣M_5=\max_{\lvert\xi-\theta\rvert\le h}\lvert f^{(5)}(\xi)\rvert, then E[g^FD]−f′(θ)=f′′′(θ)6h2+R\mathbb E[\hat g_{\mathrm{FD}}]-f'(\theta)=\frac{f'''(\theta)}6h^2+R with ∣R∣≤M5120h4\lvert R\rvert\le\frac{M_5}{120}h^4. (c) MSE=E[(g^FD−f′(θ))2]=bias2+Var\mathrm{MSE}=\mathbb E\big[(\hat g_{\mathrm{FD}}-f'(\theta))^2\big]=\mathrm{bias}^2+\mathrm{Var}.

Proof (6 steps)
  1. Step 1:
    E[g^FD]=f+−f−2h\mathbb E[\hat g_{\mathrm{FD}}]=\frac{f_+-f_-}{2h}
    Linearity of expectation and unbiasedness of each evaluation.
  2. Step 2:
    Var[g^FD]=Var[f^(θ+h)]+Var[f^(θ−h)]4h2=(1−f+2)+(1−f−2)4h2N\mathrm{Var}[\hat g_{\mathrm{FD}}]=\frac{\mathrm{Var}[\hat f(\theta+h)]+\mathrm{Var}[\hat f(\theta-h)]}{4h^2}=\frac{(1-f_+^2)+(1-f_-^2)}{4h^2N}
    For independent X,YX,Y: Var[aX+bY]=a2VarX+b2VarY\mathrm{Var}[aX+bY]=a^2\mathrm{Var}X+b^2\mathrm{Var}Y, here with a=−b=12ha=-b=\frac1{2h}.
  3. Step 3:
    f(θ±h)=∑j=04(±h)jj!f(j)(θ)+(±h)5120f(5)(ξ±),∣ξ±−θ∣<hf(\theta\pm h)=\sum_{j=0}^4\frac{(\pm h)^j}{j!}f^{(j)}(\theta)+\frac{(\pm h)^5}{120}f^{(5)}(\xi_\pm),\qquad\lvert\xi_\pm-\theta\rvert<h
    Taylor's theorem with the Lagrange form of the remainder.
  4. Step 4:
    f+−f−=2hf′(θ)+h33f′′′(θ)+h5120(f(5)(ξ+)+f(5)(ξ−))f_+-f_-=2hf'(\theta)+\frac{h^3}3f'''(\theta)+\frac{h^5}{120}\big(f^{(5)}(\xi_+)+f^{(5)}(\xi_-)\big)
    The even-order terms cancel; the odd ones double, and 23!=13\frac{2}{3!}=\frac13.
  5. Step 5:
    f+−f−2h−f′(θ)=f′′′(θ)6h2+h4240(f(5)(ξ+)+f(5)(ξ−))⏟R,∣R∣≤2M5240h4=M5120h4\frac{f_+-f_-}{2h}-f'(\theta)=\frac{f'''(\theta)}6h^2+\underbrace{\frac{h^4}{240}\big(f^{(5)}(\xi_+)+f^{(5)}(\xi_-)\big)}_{R},\qquad\lvert R\rvert\le\frac{2M_5}{240}h^4=\frac{M_5}{120}h^4
    Divide by 2h2h and bound each fifth derivative by M5M_5.
  6. Step 6:
    E[(g^−f′)2]=(Eg^−f′)2+E[(g^−Eg^)2]\mathbb E\big[(\hat g-f')^2\big]=\big(\mathbb E\hat g-f'\big)^2+\mathbb E\big[(\hat g-\mathbb E\hat g)^2\big]
    Expand g^−f′=(g^−Eg^)+(Eg^−f′)\hat g-f'=(\hat g-\mathbb E\hat g)+(\mathbb E\hat g-f'); the cross term has expectation zero.

∎

Lemma

A sum of shifted squared sines

For all real θ\theta and hh:  sin⁡2(θ+h)+sin⁡2(θ−h)=1−cos⁡2θ cos⁡2h\ \sin^2(\theta+h)+\sin^2(\theta-h)=1-\cos2\theta\,\cos2h.

Proof (3 steps)
  1. Step 1:
    sin⁡2u=12(1−cos⁡2u)\sin^2u=\tfrac12\big(1-\cos2u\big)
    Double-angle formula cos⁡2u=1−2sin⁡2u\cos2u=1-2\sin^2u.
  2. Step 2:
    sin⁡2(θ+h)+sin⁡2(θ−h)=1−12[cos⁡(2θ+2h)+cos⁡(2θ−2h)]\sin^2(\theta+h)+\sin^2(\theta-h)=1-\tfrac12\big[\cos(2\theta+2h)+\cos(2\theta-2h)\big]
    Apply it with u=θ±hu=\theta\pm h and add.
  3. Step 3:
    cos⁡(a+b)+cos⁡(a−b)=2cos⁡acos⁡b ⇒ sin⁡2(θ+h)+sin⁡2(θ−h)=1−cos⁡2θcos⁡2h\cos(a+b)+\cos(a-b)=2\cos a\cos b\ \Rightarrow\ \sin^2(\theta+h)+\sin^2(\theta-h)=1-\cos2\theta\cos2h
    Addition theorem cos⁡(a±b)=cos⁡acos⁡b∓sin⁡asin⁡b\cos(a\pm b)=\cos a\cos b\mp\sin a\sin b; the sine terms cancel.

∎

Derivation

Finite differences for f = cos θ

  1. Step 1:
    f(φ)=⟨0∣RY(φ)†ZRY(φ)∣0⟩=cos⁡φ,1−f(φ)2=sin⁡2φf(\varphi)=\langle0\vert R_Y(\varphi)^\dagger ZR_Y(\varphi)\vert0\rangle=\cos\varphi,\qquad1-f(\varphi)^2=\sin^2\varphi
    The one-qubit model of the lab; RY(φ)∣0⟩=cos⁡φ2∣0⟩+sin⁡φ2∣1⟩R_Y(\varphi)\lvert0\rangle=\cos\frac\varphi2\lvert0\rangle+\sin\frac\varphi2\lvert1\rangle.
  2. Step 2:
    Var[g^FD]=sin⁡2(θ+h)+sin⁡2(θ−h)4h2N=1−cos⁡2θcos⁡2h4h2N\mathrm{Var}[\hat g_{\mathrm{FD}}]=\frac{\sin^2(\theta+h)+\sin^2(\theta-h)}{4h^2N}=\frac{1-\cos2\theta\cos2h}{4h^2N}
    Part (a) of the theorem and the lemma.
  3. Step 3:
    E[g^FD]=cos⁡(θ+h)−cos⁡(θ−h)2h=−sin⁡θ sin⁡hh\mathbb E[\hat g_{\mathrm{FD}}]=\frac{\cos(\theta+h)-\cos(\theta-h)}{2h}=-\sin\theta\,\frac{\sin h}h
    cos⁡(a+b)−cos⁡(a−b)=−2sin⁡asin⁡b\cos(a+b)-\cos(a-b)=-2\sin a\sin b.
  4. Step 4:
    bias=−sin⁡θ(sin⁡hh−1)=sin⁡θ(h26−h4120+…)\mathrm{bias}=-\sin\theta\Big(\frac{\sin h}h-1\Big)=\sin\theta\Big(\frac{h^2}6-\frac{h^4}{120}+\dots\Big)
    Power series of sin⁡hh\frac{\sin h}h; the leading term matches f′′′6h2\frac{f'''}6h^2 because f′′′=sin⁡θf'''=\sin\theta for f=cos⁡θf=\cos\theta.
  5. Step 5:
    θ=π4: cos⁡2θ=0 ⇒ Var[g^FD]=14h2N=h=0.01, N=100014⋅10−4⋅103=2.5\theta=\tfrac\pi4:\ \cos2\theta=0\ \Rightarrow\ \mathrm{Var}[\hat g_{\mathrm{FD}}]=\frac1{4h^2N}\overset{h=0.01,\,N=1000}{=}\frac1{4\cdot10^{-4}\cdot10^3}=2.5
    At θ=π4\theta=\frac\pi4 the variance is exactly 14h2N\frac1{4h^2N} for every hh; this is part (a) of the lab.
  6. Step 6:
    2.5≈1.581 ≫ ∣f′(π4)∣=12≈0.7071,bias≈1.18×10−5\sqrt{2.5}\approx1.581\ \gg\ \lvert f'(\tfrac\pi4)\rvert=\tfrac1{\sqrt2}\approx0.7071,\qquad\mathrm{bias}\approx1.18\times10^{-5}
    With h=0.01h=0.01 the estimate is essentially pure noise; the truncation error is negligible.

Result

f=cos⁡θ:Var[g^FD]=1−cos⁡2θcos⁡2h4h2N,bias=−sin⁡θ(sin⁡hh−1)\boxed{f=\cos\theta:\quad\mathrm{Var}[\hat g_{\mathrm{FD}}]=\frac{1-\cos2\theta\cos2h}{4h^2N},\qquad\mathrm{bias}=-\sin\theta\Big(\frac{\sin h}{h}-1\Big)}

The duel above uses the lab setting: θ=π4\theta=\frac\pi4, h=0.01h=0.01, N=1000N=1000. The finite-difference histogram is centred on −0.7071-0.7071 but spreads over several units, while the parameter-shift histogram is a narrow spike. Noise in each evaluation is of order N−1/2≈0.03N^{-1/2}\approx0.03, independent of hh; dividing the difference by 2h=0.022h=0.02 amplifies it fifty-fold. Bringing the standard deviation down to the parameter-shift level of 0.01580.0158 would take 10410^4 times as many shots, 10710^7 per evaluation.

Quick check

For f=cos⁡θf=\cos\theta at θ=π4\theta=\frac\pi4 with N=1000N=1000 shots per evaluation, what is the variance of the central finite-difference estimator with h=0.1h=0.1?

tolerance ±0.0001

The bias–variance trade-off and the optimal step#

Small steps amplify noise as h−2h^{-2}; large steps incur a truncation bias of order h2h^2. The mean squared error balances the two, and its minimiser depends on the shot budget.

Derivation

The MSE-optimal step h∗h^\ast and the N−2/3N^{-2/3} law

  1. Step 1:
    MSE(h)=(f′′′6h2+O(h4))2+(1−f+2)+(1−f−2)4h2N\mathrm{MSE}(h)=\Big(\frac{f'''}6h^2+O(h^4)\Big)^2+\frac{(1-f_+^2)+(1-f_-^2)}{4h^2N}
    Part (c) of the theorem with the bias of part (b); f′′′=f′′′(θ)f'''=f'''(\theta).
  2. Step 2:
    (1−f+2)+(1−f−2)=2σ2+O(h2),σ2=1−f(θ)2(1-f_+^2)+(1-f_-^2)=2\sigma^2+O(h^2),\qquad\sigma^2=1-f(\theta)^2
    f±2=f2±2hff′+O(h2)f_\pm^2=f^2\pm2hff'+O(h^2); the first-order terms cancel in the sum.
  3. Step 3:
    MSE(h)≈A(h)=(f′′′)236h4+σ22h2N\mathrm{MSE}(h)\approx A(h)=\frac{(f''')^2}{36}h^4+\frac{\sigma^2}{2h^2N}
    Keep the leading order of each term.
  4. Step 4:
    A′(h)=(f′′′)29h3−σ2h3N=0  ⟺  h6=9σ2(f′′′)2NA'(h)=\frac{(f''')^2}9h^3-\frac{\sigma^2}{h^3N}=0\iff h^6=\frac{9\sigma^2}{(f''')^2N}
    Differentiate and multiply by h3>0h^3>0 (assuming f′′′≠0f'''\ne0 and σ≠0\sigma\ne0).
  5. Step 5:
    A′′(h)=(f′′′)23h2+3σ2h4N>0A''(h)=\frac{(f''')^2}3h^2+\frac{3\sigma^2}{h^4N}>0
    AA is strictly convex on (0,∞)(0,\infty) and tends to ∞\infty at both ends, so the stationary point is the unique minimiser.
  6. Step 6:
    (f′′′)236h∗4=(f′′′)2h∗636 h∗2=σ24Nh∗2 ⇒ A(h∗)=3σ24Nh∗2\frac{(f''')^2}{36}h^{\ast4}=\frac{(f''')^2h^{\ast6}}{36\,h^{\ast2}}=\frac{\sigma^2}{4Nh^{\ast2}}\ \Rightarrow\ A(h^\ast)=\frac{3\sigma^2}{4Nh^{\ast2}}
    Insert h∗6h^{\ast6}: at the optimum the squared bias is half the variance.
  7. Step 7:
    A(h∗)=3σ24N((f′′′)2N9σ2)1/3=34 9−1/3 σ4/3∣f′′′∣2/3 N−2/3A(h^\ast)=\frac{3\sigma^2}{4N}\Big(\frac{(f''')^2N}{9\sigma^2}\Big)^{1/3}=\frac34\,9^{-1/3}\,\sigma^{4/3}\lvert f'''\rvert^{2/3}\,N^{-2/3}
    Substitute h∗−2=((f′′′)2N/(9σ2))1/3h^{\ast-2}=\big((f''')^2N/(9\sigma^2)\big)^{1/3} and collect powers.

Result

h∗=(9σ2(f′′′)2N)1/6∝N−1/6,min⁡hMSE≈34 9−1/3σ4/3∣f′′′∣2/3N−2/3\boxed{h^\ast=\Big(\frac{9\sigma^2}{(f''')^2N}\Big)^{1/6}\propto N^{-1/6},\qquad\min_h\mathrm{MSE}\approx\frac34\,9^{-1/3}\sigma^{4/3}\lvert f'''\rvert^{2/3}N^{-2/3}}
Derivation

The optimal step for f = cos θ

  1. Step 1:
    σ2=sin⁡2θ,f′′′(θ)=sin⁡θ ⇒ h∗=(9sin⁡2θsin⁡2θ N)1/6=(9N)1/6\sigma^2=\sin^2\theta,\quad f'''(\theta)=\sin\theta\ \Rightarrow\ h^\ast=\Big(\frac{9\sin^2\theta}{\sin^2\theta\,N}\Big)^{1/6}=\Big(\frac9N\Big)^{1/6}
    f′=−sin⁡f'=-\sin, f′′=−cos⁡f''=-\cos, f′′′=sin⁡f'''=\sin: the optimal step does not depend on θ\theta.
  2. Step 2:
    N=1000:h∗=0.0091/6=eln⁡(0.009)/6≈0.45608N=1000:\quad h^\ast=0.009^{1/6}=e^{\ln(0.009)/6}\approx0.45608
    The step is large, about 26∘26^\circ, far from the "small hh" of calculus.
  3. Step 3:
    min⁡hMSE≈34 9−1/3sin⁡2θ N−2/3≈0.36056sin⁡2θ N−2/3=θ=π/41.8028×10−3\min_h\mathrm{MSE}\approx\tfrac34\,9^{-1/3}\sin^2\theta\,N^{-2/3}\approx0.36056\sin^2\theta\,N^{-2/3}\overset{\theta=\pi/4}{=}1.8028\times10^{-3}
    σ4/3∣f′′′∣2/3=sin⁡2θ\sigma^{4/3}\lvert f'''\rvert^{2/3}=\sin^2\theta and N−2/3=0.01N^{-2/3}=0.01.
  4. Step 4:
    θ=π4:  MSE(h)=12(sin⁡hh−1)2+14h2N\theta=\tfrac\pi4:\ \ \mathrm{MSE}(h)=\tfrac12\Big(\frac{\sin h}h-1\Big)^2+\frac1{4h^2N}
    Exact bias and variance of the previous derivation.
  5. Step 5:
    arg min⁡hMSE(h)≈0.4585,MSE=1.7902×10−3;MSE(0.45608)=1.7904×10−3\operatorname*{arg\,min}_h\mathrm{MSE}(h)\approx0.4585,\quad\mathrm{MSE}=1.7902\times10^{-3};\qquad\mathrm{MSE}(0.45608)=1.7904\times10^{-3}
    Numerical minimisation of the exact MSE (NumPy cell). The asymptotic formula misses the exact minimiser by 0.5%0.5\%.

Result

f=cos⁡θ, N=1000:h∗=(9/N)1/6≈0.45608,min⁡hMSE≈1.79×10−3  (θ=π4)\boxed{f=\cos\theta,\ N=1000:\quad h^\ast=(9/N)^{1/6}\approx0.45608,\qquad\min_h\mathrm{MSE}\approx1.79\times10^{-3}\ \ (\theta=\tfrac\pi4)}

At h=0.456h=0.456 the finite-difference histogram is narrow but visibly shifted: its mean is −0.6829-0.6829 instead of −0.7071-0.7071, a bias of 0.0240.024, comparable to its standard deviation 0.0350.035. No step size does better than an MSE of about 1.79×10−31.79\times10^{-3} with 10001000 shots, and because the optimum scales as N−2/3N^{-2/3} rather than N−1N^{-1}, extra shots help finite differences less than they help an unbiased estimator.

Quick check

For f=cos⁡θf=\cos\theta, what is the asymptotically MSE-optimal finite-difference step h∗h^\ast when every evaluation uses N=106N=10^6 shots (four decimals)?

tolerance ±0.001

An unbiased alternative: the parameter-shift estimator#

Finite differences treat ff as an arbitrary smooth function. A Pauli rotation produces a very special one: the next lesson proves that f(θ)=a+bcos⁡θ+csin⁡θf(\theta)=a+b\cos\theta+c\sin\theta for every angle of a gate RP(θ)=e−iθP/2R_P(\theta)=e^{-i\theta P/2}, whatever the rest of the circuit is. For such functions two evaluations at the finite shifts ±π2\pm\frac\pi2 give the derivative exactly.

Proposition

Bias and variance of the parameter-shift estimator

Let f(θ)=a+bcos⁡θ+csin⁡θf(\theta)=a+b\cos\theta+c\sin\theta be the expectation value of a Pauli observable and g^PSR=12[f^(θ+π2)−f^(θ−π2)]\hat g_{\mathrm{PSR}}=\frac12\big[\hat f(\theta+\frac\pi2)-\hat f(\theta-\frac\pi2)\big] with independent NN-shot evaluations. Then E[g^PSR]=f′(θ)\mathbb E[\hat g_{\mathrm{PSR}}]=f'(\theta) and Var[g^PSR]=(1−f(θ+π2)2)+(1−f(θ−π2)2)4N ≤ 12N.\mathrm{Var}[\hat g_{\mathrm{PSR}}]=\frac{\big(1-f(\theta+\frac\pi2)^2\big)+\big(1-f(\theta-\frac\pi2)^2\big)}{4N}\ \le\ \frac1{2N}. For f=cos⁡θf=\cos\theta the variance is cos⁡2θ2N\frac{\cos^2\theta}{2N}, and the MSE equals the variance, decaying as N−1N^{-1}.

Proof (5 steps)
  1. Step 1:
    f(θ±π2)=a+bcos⁡(θ±π2)+csin⁡(θ±π2)=a∓bsin⁡θ±ccos⁡θf\big(\theta\pm\tfrac\pi2\big)=a+b\cos\big(\theta\pm\tfrac\pi2\big)+c\sin\big(\theta\pm\tfrac\pi2\big)=a\mp b\sin\theta\pm c\cos\theta
    cos⁡(u±π2)=∓sin⁡u\cos(u\pm\frac\pi2)=\mp\sin u and sin⁡(u±π2)=±cos⁡u\sin(u\pm\frac\pi2)=\pm\cos u.
  2. Step 2:
    E[g^PSR]=12[f(θ+π2)−f(θ−π2)]=−bsin⁡θ+ccos⁡θ=f′(θ)\mathbb E[\hat g_{\mathrm{PSR}}]=\tfrac12\big[f(\theta+\tfrac\pi2)-f(\theta-\tfrac\pi2)\big]=-b\sin\theta+c\cos\theta=f'(\theta)
    Linearity of expectation; the constant aa cancels. No Taylor expansion is involved, so there is no truncation error.
  3. Step 3:
    Var[g^PSR]=14[Varf^(θ+π2)+Varf^(θ−π2)]=(1−f+π/22)+(1−f−π/22)4N\mathrm{Var}[\hat g_{\mathrm{PSR}}]=\tfrac14\Big[\mathrm{Var}\hat f(\theta+\tfrac\pi2)+\mathrm{Var}\hat f(\theta-\tfrac\pi2)\Big]=\frac{(1-f_{+\pi/2}^2)+(1-f_{-\pi/2}^2)}{4N}
    Independence of the two evaluations and the shot-noise variance 1−f2N\frac{1-f^2}N; each bracket is at most 11.
  4. Step 4:
    f=cos⁡: f(θ±π2)=∓sin⁡θ ⇒ Var[g^PSR]=2cos⁡2θ4N=cos⁡2θ2Nf=\cos:\ f\big(\theta\pm\tfrac\pi2\big)=\mp\sin\theta\ \Rightarrow\ \mathrm{Var}[\hat g_{\mathrm{PSR}}]=\frac{2\cos^2\theta}{4N}=\frac{\cos^2\theta}{2N}
    1−sin⁡2θ=cos⁡2θ1-\sin^2\theta=\cos^2\theta for both shifted evaluations.
  5. Step 5:
    θ=π4, N=1000:Var[g^PSR]=1/22000=2.5×10−4\theta=\tfrac\pi4,\ N=1000:\quad\mathrm{Var}[\hat g_{\mathrm{PSR}}]=\frac{1/2}{2000}=2.5\times10^{-4}
    Part (b) of the lab.

∎

Derivation

Finite differences against parameter shift at θ = π/4, N = 1000

  1. Step 1:
    Var[g^FD(h)]Var[g^PSR]=1/(4h2N)1/(4N)=h−2=h=0.01104\frac{\mathrm{Var}[\hat g_{\mathrm{FD}}(h)]}{\mathrm{Var}[\hat g_{\mathrm{PSR}}]}=\frac{1/(4h^2N)}{1/(4N)}=h^{-2}\overset{h=0.01}{=}10^4
    At θ=π4\theta=\frac\pi4 both noise brackets equal 1N\frac1N; only the squared prefactors 14h2\frac1{4h^2} and 14\frac14 differ.
  2. Step 2:
    min⁡hMSEFDMSEPSR=1.7902×10−32.5×10−4≈7.2\frac{\min_h\mathrm{MSE}_{\mathrm{FD}}}{\mathrm{MSE}_{\mathrm{PSR}}}=\frac{1.7902\times10^{-3}}{2.5\times10^{-4}}\approx7.2
    Even the best step leaves finite differences seven times worse at equal cost: both use two evaluations of NN shots per parameter.
  3. Step 3:
    0.36056⋅12 NFD−2/3=14⋅1000 ⇒ NFD≈193650.36056\cdot\tfrac12\,N_{\mathrm{FD}}^{-2/3}=\frac1{4\cdot1000}\ \Rightarrow\ N_{\mathrm{FD}}\approx19365
    Shots per evaluation that the optimal finite difference needs, by the asymptotic formula, to match parameter shift with 10001000 shots: about 1919 times more.
  4. Step 4:
    min⁡hMSEFDMSEPSR∝N−2/3N−1=N1/3\frac{\min_h\mathrm{MSE}_{\mathrm{FD}}}{\mathrm{MSE}_{\mathrm{PSR}}}\propto\frac{N^{-2/3}}{N^{-1}}=N^{1/3}
    The gap widens without bound as the shot budget grows.

Result

MSEPSR=cos⁡2θ2N∝N−1vs.min⁡hMSEFD≈0.36sin⁡2θ N−2/3\boxed{\mathrm{MSE}_{\mathrm{PSR}}=\frac{\cos^2\theta}{2N}\propto N^{-1}\qquad\text{vs.}\qquad\min_h\mathrm{MSE}_{\mathrm{FD}}\approx0.36\sin^2\theta\,N^{-2/3}}

The default duel (h=0.1h=0.1) shows the intermediate regime: the finite-difference spread is ten times that of parameter shift and its bias is still small. Vary NN and watch the optimal-step marker move as N−1/6N^{-1/6}. The TypeScript cell reproduces the three regimes with the engine's shot sampler (seeded, 20002000 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.

TypeScriptrunnable
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
Pythonrunnable
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 f=cos⁡θf=\cos\theta at θ=0\theta=0 with N=100N=100 shots per evaluation, what is the variance of the parameter-shift estimator?

tolerance ±0.00001

References

  1. K. Mitarai, M. Negoro, M. Kitagawa and K. Fujii, Quantum circuit learning, Physical Review A 98, 032309 (2018).doi:10.1103/PhysRevA.98.032309
  2. 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
  3. T. Jones and J. Gacon, Efficient calculation of gradients in classical simulations of variational quantum algorithms, arXiv:2009.02823 (2020).arxiv.org
  4. A. S. Holevo, Bounds for the quantity of information transmitted by a quantum communication channel, Problems of Information Transmission 9(3), 177–183 (1973).
  5. 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
  6. W. K. Wootters and W. H. Zurek, A single quantum cannot be cloned, Nature 299, 802–803 (1982).doi:10.1038/299802a0
  7. D. Dieks, Communication by EPR devices, Physics Letters A 92(6), 271–272 (1982).doi:10.1016/0375-9601(82)90084-6
  8. A. Griewank and A. Walther, Evaluating Derivatives: Principles and Techniques of Algorithmic Differentiation, 2nd edition, SIAM (2008).doi:10.1137/1.9780898717761
  9. 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
  10. J. Haah, A. W. Harrow, Z. Ji, X. Wu and N. Yu, Sample-optimal tomography of quantum states, arXiv:1508.01797 (2015).arxiv.org
  11. R. O’Donnell and J. Wright, Efficient quantum tomography, arXiv:1508.01907 (2015).arxiv.org
  12. 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-graded

    Compare the two gradient estimators available on quantum hardware for f(θ)=⟨Z⟩=cos⁡θf(\theta)=\langle Z\rangle=\cos\theta of the state RY(θ)∣0⟩R_Y(\theta)\lvert0\rangle: the central finite difference with step h=0.01h=0.01 and the parameter-shift rule. Both use two circuit evaluations of N=1000N=1000 shots; you compute the exact shot-noise variance of each and see a factor h−2=104h^{-2}=10^4 between them.

    Open lab