Lesson 48 · 110 min · advanced
The Parameter-Shift Rule
The parameter-shift rule computes the exact derivative of an expectation value from two further evaluations of the same circuit at shifted parameter values: for a Pauli rotation. This lesson derives the rule from the spectral decomposition of the gate generator. A generator with eigenvalues makes a single sinusoid of frequency , and a sum-to-product identity then gives the general rule . The two-term rule is proved both in the Schrödinger and in the Heisenberg picture. The lesson then shows that the estimator is exact and unbiased under shot noise, extends the rule to parameters that occur in several gates, derives the four-term rule for controlled rotations by solving a linear system, and counts the circuit evaluations a gradient costs.
Prerequisites: Why Backpropagation Fails on Quantum Hardware, Spectral Theorem & Functions of Operators
Objectives and key results
Reduce the derivative with respect to one gate angle to a function by absorbing the gates before and after the parameterised gate into and .
Prove that a generator with eigenvalues makes a single sinusoid , with expressed through the spectral projectors .
Derive the general shift rule , explain the choice , and specialise it to the two-term rule for Pauli rotations in both the Schrödinger and the Heisenberg picture.
Show that the parameter-shift estimator is exact and unbiased under shot noise, compute its variance, and compare it with the bias and variance of finite differences.
Differentiate parameters that occur in several gates with the chain rule, and derive the four-term rule for controlled rotations from the frequencies of their generators.
Implement a parameter-shift gradient that uses exactly circuit evaluations, and count the cost of gradients with controlled rotations.
- theorem · Two-term parameter-shift rule (Pauli rotations)
- identity · Single-frequency form
- theorem · General shift rule
- identity · Heisenberg form of the rule
- formula · Four-term rule for controlled rotations
- formula · Chain rule and cost
The expectation value as a function of one angle#
The previous lesson established two facts. Reverse-mode differentiation is not available on quantum hardware: the intermediate states cannot be read out without tomography, and they cannot be copied. Finite differences are available but poor: the step introduces a bias of order , and shot noise is amplified by a factor in the variance. This lesson shows that the derivative of an expectation value with respect to a gate angle can nevertheless be obtained exactly from circuit evaluations, provided the evaluations are taken at large, fixed shifts of the angle instead of infinitesimal ones. The reason is structural: as a function of one angle, an expectation value is a trigonometric polynomial with very few frequencies, and the derivative of such a function is a finite linear combination of its values.
Definition
Gate-isolated cost function
Let be a parameterised circuit on qubits, a Hermitian observable and . Fix all parameters except the angle of one gate with Hermitian generator , and write , where collects the gates before and the gates after it. The gate-isolated cost function is For a Pauli rotation the generator is .
Absorbing the rest of the circuit into the state and the observable
- Step 1:A circuit is a product of gates in time order; the gate carrying splits it into a part before and a part after. Neither nor depends on when occurs in one gate only.
- Step 2:The adjoint of a product is the product of the adjoints in reverse order: .
- Step 3:Group the factors: the gates before the parameterised gate act on the initial state, the gates after it act on the observable.
- Step 4:is Hermitian, and conjugation by the unitary preserves Hermiticity and eigenvalues. In particular , so .
- Step 5:Every one-parameter gate of the platform has this form. For a Pauli string the generator is Hermitian with .
- Step 6:All other parameters are frozen inside and , so the partial derivative of the full cost function is the ordinary derivative of the one-variable function .
Result
Generators with two eigenvalues#
The dependence of on is fixed by the spectrum of the generator. The spectral theorem of Stage 1 writes a Hermitian operator as a weighted sum of orthogonal projectors, and an operator function such as acts on each projector separately. When has only two eigenvalues, this decomposition makes a single sinusoid.
Expectation values of two-eigenvalue gates are single sinusoids
Let be Hermitian with exactly the two eigenvalues , , and let be the orthogonal projectors onto the eigenspaces, so . Then for every state and Hermitian , all three real. For a Pauli rotation, , and has period .
Proof (8 steps)
- Step 1:Spectral theorem for the Hermitian operator : the eigenspaces of distinct eigenvalues are orthogonal and together span the space.
- Step 2:A function of a Hermitian operator applies the function to each eigenvalue: , here with . The adjoint conjugates the scalar coefficients.
- Step 3:Multiply out the four products. The phases combine as on the diagonal blocks and as on the off-diagonal blocks.
- Step 4:because and are Hermitian, and for every operator .
- Step 5:Take the expectation value in ; the two off-diagonal terms are complex conjugates, and .
- Step 6:Euler's formula and the real part of a product of two complex numbers, .
- Step 7:is Hermitian, so its expectation value is real; and are real by construction.
- Step 8:For a Pauli string , so are the projectors onto the eigenspaces of , on which takes the values . Then .
∎
The shift identity and the general rule#
General parameter-shift rule
Let with . For every and every shift , Consequently, whenever , i.e. , The shift gives , the smallest prefactor and hence the smallest amplification of statistical errors in the two evaluations; there .
Proof (7 steps)
- Step 1:Differentiate term by term; the constant disappears and the chain rule produces the factor .
- Step 2:Addition theorems: in and the even parts cancel in the difference.
- Step 3:Apply both identities with and ; the constant cancels in the difference.
- Step 4:Factor out and compare with the first line: the bracket is .
- Step 5:Divide by . The identity holds exactly, for finite , with no remainder term.
- Step 6:If the two values are estimated independently with variances , the prefactor enters squared. Equality holds exactly when , i.e. ; the smallest positive choice is .
- Step 7:The central difference quotient is the small-shift limit of the rule; for finite it carries the factor , which is its truncation error. The shift rule replaces by the exact factor .
∎
The visualiser draws , the two evaluation points and the secant through them, next to the tangent at . The secant slope is . It differs from the tangent slope by a fixed factor that does not depend on or on the coefficients, and multiplying by recovers the tangent exactly. The first instance shows a Pauli rotation (, ); the second a generator with eigenvalues , such as in , with the small shift , where the secant is already close to the tangent and the correction factor is .
Quick check
The gate has the generator with eigenvalues . Which shift minimises the variance of the shift-rule estimator ? Give in radians.
The two-term rule for Pauli rotations#
For a Pauli rotation the generator has eigenvalues , so , the optimal shift is and the prefactor is . Applied to each parameter of a circuit in which every parameter occupies one Pauli rotation, this is the rule of Mitarai et al. (2018) and Schuld et al. (2019): Because this rule is the workhorse of variational quantum algorithms, we derive it twice more without the spectral detour. First we differentiate the state (Schrödinger picture), then the observable (Heisenberg picture). The second derivation yields an operator identity, which holds for every input state, mixed states included.
Two-term rule in the Schrödinger picture
- Step 1:In the Schrödinger picture the state carries the -dependence and the observable is fixed.
- Step 2:for a fixed operator , here .
- Step 3:Product rule for the bra and the ket. The bra of is , because is Hermitian and complex conjugation turns into .
- Step 4:gives (Euler's formula for an involution), evaluated at .
- Step 5:Rotations about the same axis compose additively: , because the exponents commute.
- Step 6:The bra of is ; expand the product, with the expectation value in .
- Step 7:The terms and are common to both shifts and cancel; the cross terms appear with opposite signs and add.
- Step 8:Compare the third and the seventh line: both are multiples of the same commutator expectation value.
Result
Two-term rule in the Heisenberg picture
Let with , a Pauli string, and let be Hermitian. Then The commutator is itself a difference of two conjugations, . Taking the expectation value in any state, pure or mixed, gives the two-term rule.
Proof (8 steps)
- Step 1:In the Heisenberg picture the observable carries the -dependence and the state is fixed.
- Step 2:commutes with every function of itself, in particular with .
- Step 3:Product rule for the three factors , , ; the middle factor is constant.
- Step 4:The same Euler formula as in the Schrödinger derivation, with for the adjoint.
- Step 5:Expand , using .
- Step 6:Subtract the two signs of the previous line; cancels, and because .
- Step 7:for the one-parameter group , and the adjoint reverses the order.
- Step 8:Substitute line six into line three, conjugate by with line seven and take the expectation value. The identity holds between operators, so it holds for every density matrix as well.
∎
The circuit of the lab's visible test makes the rule concrete. Two rotations prepare a product state and a CNOT correlates the qubits before is measured.
Circuit · 2 qubits
The lab's visible circuit at : on qubit , on qubit , then . The observable is (Pauli word ), and .
The visible lab test: f = cos t1 cos t2
- Step 1:The first column of on each qubit.
- Step 2:, and then has the eigenvalue , which is the eigenvalue of on .
- Step 3:On a product state the expectation value of a product of local operators factorises; .
- Step 4:.
- Step 5:The two-term rule reproduces the analytic partial derivative; the same computation in gives .
- Step 6:The expected value of the visible test, obtained with four evaluations, two per parameter.
Quick check
The parameter of a circuit sits in a single gate. Two runs give and . What is at ?
Exact, and unbiased under shot noise#
On hardware, is not available exactly. Each evaluation is an average over measurement shots. Two kinds of error must be separated: the systematic error of the formula, which remains even with infinitely many shots, and the statistical error of the shot averages. Finite differences suffer from both. The parameter-shift rule has no systematic error at all.
Bias and variance of the shift and difference estimators
Let be the cost of a Pauli rotation (), measured with a Pauli observable (eigenvalues ), and let be the mean of independent single-shot outcomes at angle . (a) The central difference quotient with step satisfies , so its bias is . (b) The parameter-shift estimator is unbiased, , with (c) The central-difference estimator has .
Proof (8 steps)
- Step 1:The shift identity of the general rule with and .
- Step 2:Divide by and expand . The truncation error of finite differences is therefore an exact multiplicative factor for such circuits, and it vanishes only as .
- Step 3:Born rule for an observable with eigenvalues : the probabilities are . Since , .
- Step 4:Linearity of expectation and additivity of variance for independent, identically distributed shots.
- Step 5:Linearity of expectation, followed by the two-term rule, which holds exactly. No step size appears, so no truncation error survives in the expectation.
- Step 6:The two circuit runs are independent, so their variances add, each scaled by . The bound uses .
- Step 7:The same computation with the prefactor in place of : the variance grows like , which is why a small step makes finite differences useless under shot noise.
- Step 8:The example of the previous lesson: , while . With the same shot budget the shift estimator is times less noisy than central differences with .
∎
Quick check
A Pauli observable is measured with shots at each of the two shifted points, where its exact values are and . What is the variance of the parameter-shift estimator ?
Parameters that occur in several gates#
In data re-uploading circuits, in QAOA and in ansätze with tied weights, one trainable parameter feeds several gates, often through an affine map such as . The shift rule applies to gate angles, not directly to parameters. The chain rule connects the two.
Chain rule for repeated parameters
Let a parameter enter Pauli rotations with angles , and let be the expectation value as a function of independent gate angles, so that . Then where shifts the angle of occurrence only. The gradient costs evaluations, and occurrences with can be skipped.
Proof (6 steps)
- Step 1:Give each occurrence its own angle variable; is restricted to the line in angle space.
- Step 2:Multivariate chain rule; is smooth (a trigonometric polynomial) in every angle.
- Step 3:With all other angles fixed, the remaining gates are absorbed into and as in the first derivation, and the single-frequency theorem applies to occurrence alone.
- Step 4:The two-term rule for occurrence . The other occurrences of keep their unshifted angles.
- Step 5:Insert line four into line two. Shifting the gate angle by is the same as shifting by in that one gate.
- Step 6:A single occurrence with scale : the derivative with respect to the parameter is twice the derivative with respect to the gate angle.
∎
Shifting all occurrences at once is wrong
- Step 1:Two rotations about the same axis add their angles, and of is .
- Step 2:Shifting shifts both gate angles, i.e. the total angle by , and . The result is for every , which is wrong.
- Step 3:With independent occurrence angles, each shift moves the total angle by only ; .
- Step 4:The chain rule with , evaluated at , reproduces with four evaluations.
- Step 5:Alternatively, as a function of the circuit is , a generator with eigenvalues , so the general rule with and shift applies (two evaluations). The naive rule used and , where .
Quick check
A parameter appears in on qubit and in on qubit of the same circuit. Which procedure returns exactly?
Controlled rotations and the four-term rule#
A controlled rotation applies to the target when the control is and does nothing otherwise. It is a one-parameter gate, but its generator has three distinct eigenvalues. The two-term rule then fails, and the correct rule needs four evaluations (Anselmetti et al. 2021; Wierichs et al. 2022).
Spectrum and frequencies of a controlled rotation
Let with control qubit first. Then with , whose eigenvalues are (twice), and , and with real coefficients. With , and : , and .
Proof (7 steps)
- Step 1:is block diagonal in the control basis, and the exponential of a block-diagonal matrix is taken block by block: on the control- block.
- Step 2:The control- block contributes the eigenvalue with multiplicity ; the control- block contributes the eigenvalues of .
- Step 3:Spectral decomposition with three projectors summing to , and the operator function applied eigenvalue by eigenvalue.
- Step 4:Multiply out and , as in the two-eigenvalue case.
- Step 5:The frequencies of are the differences of generator eigenvalues. Two different pairs produce the frequency , and arises from the reversed pairs.
- Step 6:Group each term with its reversed partner, which is its complex conjugate because .
- Step 7:As in the two-eigenvalue theorem, with , and with , ; this gives the stated .
∎
Why the two-term rule is wrong for controlled rotations
- Step 1:Split into its frequency components.
- Step 2:The shift identity of the general rule with , applied to each component separately.
- Step 3:The two-term formula is linear in , so it acts on each component with the factor .
- Step 4:The two-term rule overweights the frequency- component by the factor . It is correct only when that component has zero derivative, for example when the control qubit is in a basis state.
Four-term shift rule for controlled rotations
For every controlled Pauli rotation and every , i.e. and . The coefficients are the unique solution of a linear system expressing exactness on the two frequencies .
Proof (8 steps)
- Step 1:Ansatz: a combination of two symmetric differences with unknown coefficients. Symmetric differences remove the constant automatically.
- Step 2:Apply the per-component shift identity to both differences.
- Step 3:for every controlled-rotation cost function if and only if each frequency component is reproduced with weight , because and vary independently with the coefficients .
- Step 4:, , .
- Step 5:Divide the first equation by and the second by . The determinant is non-zero, so the solution exists and is unique.
- Step 6:Add and subtract the two equations, then put on a common denominator.
- Step 7:Numerical values; they satisfy and .
- Step 8:By the spectrum theorem every controlled-rotation cost function has only these components, so the rule is exact. It needs the four evaluations and .
∎
In four-term mode the visualiser draws a controlled-rotation cost function with both frequencies. It marks the four evaluation points and , and compares the four-term estimate with the tangent and with the failing two-term estimate. With the default coefficients (, ) the frequency- component is present, so the two-term value is visibly wrong.
There is an alternative that uses only two-term rules. As a time-ordered circuit, , , , equals . With the control in the two rotations cancel. With the control in , , so the target is rotated by . The parameter now occurs twice, with scales and , and the chain rule again costs four evaluations. More generally, Wierichs et al. (2022) show that a cost function with distinct positive frequencies admits an exact rule with evaluations; the controlled rotation is the case .
Circuit · 2 qubits
at written with two CNOTs: , on qubit , , on qubit . Its unitary equals the controlled rotation exactly.
Cost of a gradient and an implementation#
Number of circuit evaluations per gradient
Let a circuit contain parameterised Pauli rotations and parameterised controlled Pauli rotations. The exact gradient with respect to all parameters by shift rules costs circuit evaluations, and the unshifted value is not among them. In particular, if each of parameters occupies a single Pauli rotation, the cost is exactly evaluations, or shots with shots per evaluation. For comparison, forward differences use evaluations and central differences , both with a systematic error.
Proof (6 steps)
- Step 1:The two-term rule for one occurrence; with repeated parameters the chain rule sums over occurrences, each with its own two evaluations.
- Step 2:The shifted points of different parameters differ in two coordinates, so no evaluation can be shared between parameters.
- Step 3:The four-term rule for one controlled rotation; the points are distinct because and differ modulo , the period of for frequencies and .
- Step 4:Sum over all occurrences.
- Step 5:All rules are combinations of symmetric differences , so the unshifted value never enters. A training loop that also needs the loss value spends one extra evaluation for it, which is not part of the gradient.
- Step 6:Forward differences share between all parameters; both difference schemes are approximations with a step-size bias, unlike the shift rules.
∎
Quick check
An ansatz has parameters in single Pauli rotations and further parameters, each in a single controlled rotation . How many circuit evaluations does one exact gradient by shift rules cost?
The TypeScript cell implements the rule with the simulator's exact expectationValue on a three-qubit circuit with five parameters. It compares the result with central finite differences, counts evaluations, and shows that the general rule with returns the same derivative for every shift . Finally, on a gate it compares the failing two-term rule, the four-term rule and finite differences.
import { FOUR_TERM_C_MINUS, FOUR_TERM_C_PLUS, expectationValue, finiteDifferenceGradient, mulberry32 } from '@/lib/quantum-simulator';
// A three-qubit circuit in which every parameter sits in one Pauli rotation R_P(theta) = exp(-i theta P / 2).
const names = ['a', 'b', 'c', 'd', 'e'];
const rot = (gate: string, q: number, name: string) => ({ kind: 'gate', gate, targets: [q], params: [{ param: name }] });
const cnot = (c: number, t: number) => ({ kind: 'gate', gate: 'CNOT', targets: [c, t] });
const circuit: any = {
version: 1, numQubits: 3, numClbits: 0,
parameters: names.map((name) => ({ name, value: 0 })),
ops: [rot('RY', 0, 'a'), rot('RX', 1, 'b'), cnot(0, 1), rot('RY', 1, 'c'), cnot(1, 2), rot('RX', 2, 'd'), cnot(2, 0), rot('RY', 0, 'e')],
};
const H = [{ coeff: 1, ops: 'ZIZ' }, { coeff: -0.7, ops: 'XYX' }, { coeff: 0.5, ops: 'IZI' }];
let calls = 0;
const f = (theta: number[]): number => {
calls++;
const bindings: Record<string, number> = {};
names.forEach((n, i) => (bindings[n] = theta[i]));
return expectationValue(circuit, H, bindings);
};
const shift = (theta: number[], j: number, s: number) => theta.map((v, k) => (k === j ? v + s : v));
// Parameter-shift gradient: two evaluations per parameter, shifts +-pi/2, prefactor 1/2.
function psrGradient(theta: number[]): number[] {
return theta.map((_, j) => 0.5 * (f(shift(theta, j, Math.PI / 2)) - f(shift(theta, j, -Math.PI / 2))));
}
const rng = mulberry32(48);
const theta = names.map(() => 2 * Math.PI * rng());
const g = psrGradient(theta);
const bindings = Object.fromEntries(names.map((n, i) => [n, theta[i]]));
const fd = finiteDifferenceGradient(circuit, H, { bindings }).gradient;
console.log('theta : ' + theta.map((v) => v.toFixed(4)).join(' '));
console.log('PSR : ' + g.map((v) => v.toFixed(8)).join(' '));
console.log('central FD : ' + names.map((n) => fd[n].toFixed(8)).join(' '));
const dev = Math.max(...names.map((n, i) => Math.abs(g[i] - fd[n])));
console.log('max |PSR - FD| < 1e-8: ' + (dev < 1e-8) + ', evaluate calls: ' + calls + ' = 2P');
// The general rule r / sin(2 r s) [f(theta + s) - f(theta - s)] with r = 1/2 gives the same value for every shift s.
for (const s of [0.1, 1.0, Math.PI / 2, 2.5]) {
const d = (0.5 / Math.sin(s)) * (f(shift(theta, 0, s)) - f(shift(theta, 0, -s)));
console.log('s = ' + s.toFixed(4) + ': df/da = ' + d.toFixed(8));
}
// Controlled rotation CRY(t): generator eigenvalues {0, 0, 1/2, -1/2}, frequencies 1/2 and 1.
const ctrl: any = {
version: 1, numQubits: 2, numClbits: 0, parameters: [{ name: 't', value: 0 }],
ops: [
{ kind: 'gate', gate: 'RY', targets: [0], params: [1.1] },
{ kind: 'gate', gate: 'RX', targets: [1], params: [0.4] },
{ kind: 'gate', gate: 'CRY', targets: [0, 1], params: [{ param: 't' }] },
],
};
const H2 = [{ coeff: 1, ops: 'XZ' }, { coeff: 0.5, ops: 'IZ' }];
const g2 = (t: number) => expectationValue(ctrl, H2, { t });
const t0 = 0.8;
const twoTerm = 0.5 * (g2(t0 + Math.PI / 2) - g2(t0 - Math.PI / 2));
const fourTerm = FOUR_TERM_C_PLUS * (g2(t0 + Math.PI / 2) - g2(t0 - Math.PI / 2))
- FOUR_TERM_C_MINUS * (g2(t0 + 1.5 * Math.PI) - g2(t0 - 1.5 * Math.PI));
const fdT = finiteDifferenceGradient(ctrl, H2, { bindings: { t: t0 } }).gradient.t;
console.log('CRY: two-term ' + twoTerm.toFixed(8) + ', four-term ' + fourTerm.toFixed(8) + ', central FD ' + fdT.toFixed(8));Expected output
theta : 5.3106 3.3600 1.5749 0.4384 2.9134 PSR : -0.58333288 0.49028787 0.27549995 0.06730340 0.51019828 central FD : -0.58333288 0.49028787 0.27549995 0.06730340 0.51019828 max |PSR - FD| < 1e-8: true, evaluate calls: 10 = 2P s = 0.1000: df/da = -0.58333288 s = 1.0000: df/da = -0.58333288 s = 1.5708: df/da = -0.58333288 s = 2.5000: df/da = -0.58333288 CRY: two-term -0.31628747, four-term -0.25008444, central FD -0.25008444
The NumPy cell repeats the checks with explicit matrices: the two-term rule against finite differences, the coefficients from the system, the four-term rule on , and , and the repeated-parameter example, where the naive global shift returns .
import numpy as np
I2 = np.eye(2)
X = np.array([[0, 1], [1, 0]], dtype=complex)
Y = np.array([[0, -1j], [1j, 0]])
Z = np.diag([1.0 + 0j, -1.0])
P0, P1 = np.diag([1.0, 0.0]), np.diag([0.0, 1.0])
def rot(P, t): # R_P(t) = exp(-i t P / 2) = cos(t/2) I - i sin(t/2) P
return np.cos(t / 2) * I2 - 1j * np.sin(t / 2) * P
def crot(P, t): # control qubit 0, target qubit 1 (qubit 0 = most significant)
return np.kron(P0, I2) + np.kron(P1, rot(P, t))
CNOT = np.kron(P0, I2) + np.kron(P1, X)
psi0 = np.array([1, 0, 0, 0], dtype=complex)
# (1) Two-term rule on R_Y(a) (x) R_X(b), CNOT, observable H = Z1 + 0.5 X0 X1.
H = np.kron(I2, Z) + 0.5 * np.kron(X, X)
def f(a, b):
psi = CNOT @ np.kron(rot(Y, a), rot(X, b)) @ psi0
return np.real(np.vdot(psi, H @ psi))
a, b, h = 0.9, -0.4, 1e-6
psr = [0.5 * (f(a + np.pi / 2, b) - f(a - np.pi / 2, b)), 0.5 * (f(a, b + np.pi / 2) - f(a, b - np.pi / 2))]
fd = [(f(a + h, b) - f(a - h, b)) / (2 * h), (f(a, b + h) - f(a, b - h)) / (2 * h)]
print("two-term PSR :", " ".join(f"{g:+.8f}" for g in psr))
print("central FD :", " ".join(f"{g:+.8f}" for g in fd))
print("agree to 1e-8:", bool(np.max(np.abs(np.subtract(psr, fd))) < 1e-8))
# (2) Controlled rotations: frequencies 1/2 and 1, so the two-term rule fails and the four-term rule is exact.
cp = (np.sqrt(2) + 1) / (4 * np.sqrt(2))
cm = (np.sqrt(2) - 1) / (4 * np.sqrt(2))
coef = np.linalg.solve(np.array([[1.0, 1.0], [1.0, -1.0]]), np.array([0.5, 1 / (2 * np.sqrt(2))]))
print(f"c+ = {cp:.10f} c- = {cm:.10f} (2x2 solve: {coef[0]:.10f}, {coef[1]:.10f})")
H2 = np.kron(X, Z) + 0.5 * np.kron(I2, Z)
prep = np.kron(rot(Y, 1.1), rot(X, 0.4))
for name, P in (("CRX", X), ("CRY", Y), ("CRZ", Z)):
def g(t):
psi = crot(P, t) @ np.kron(I2, rot(Y, 0.7)) @ prep @ psi0
return np.real(np.vdot(psi, H2 @ psi))
t = 0.8
two = 0.5 * (g(t + np.pi / 2) - g(t - np.pi / 2))
four = cp * (g(t + np.pi / 2) - g(t - np.pi / 2)) - cm * (g(t + 3 * np.pi / 2) - g(t - 3 * np.pi / 2))
exact = (g(t + h) - g(t - h)) / (2 * h)
print(f"{name}: two-term {two:+.8f} four-term {four:+.8f} central FD {exact:+.8f}")
# (3) A parameter used twice: R_Y(alpha) R_Y(alpha) |0> = R_Y(2 alpha) |0>, F = <Z> = cos(2 alpha).
F = lambda al: np.cos(2 * al)
two_occ = lambda t1, t2: np.cos(t1 + t2) # the same circuit with independent occurrence angles
al = 0.6
naive = 0.5 * (F(al + np.pi / 2) - F(al - np.pi / 2))
chain = sum(0.5 * (two_occ(*(np.array([al, al]) + np.pi / 2 * e)) - two_occ(*(np.array([al, al]) - np.pi / 2 * e)))
for e in np.eye(2))
print(f"repeated parameter: naive shift {round(naive, 12) + 0.0:+.8f} sum over occurrences {chain:+.8f} exact {-2 * np.sin(2 * al):+.8f}")Expected output
two-term PSR : -0.41068688 +0.24206632 central FD : -0.41068688 +0.24206632 agree to 1e-8: True c+ = 0.4267766953 c- = 0.0732233047 (2x2 solve: 0.4267766953, 0.0732233047) CRX: two-term -0.50500255 four-term -0.38816465 central FD -0.38816465 CRY: two-term -0.64278888 four-term -0.49127925 central FD -0.49127925 CRZ: two-term -0.17287827 four-term -0.12224339 central FD -0.12224339 repeated parameter: naive shift +0.00000000 sum over occurrences -1.86407817 exact -1.86407817
The lab asks for exactly this function. It receives a black-box evaluate and must return the gradient using precisely calls; the grader counts the calls.
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
- D. Wierichs, J. Izaac, C. Wang and C. Y.-Y. Lin, General parameter-shift rules for quantum gradients, Quantum 6, 677 (2022).doi:10.22331/q-2022-03-30-677
- G. E. Crooks, Gradients of parameterized quantum gates using the parameter-shift rule and gate decomposition, arXiv:1905.13311 (2019).arxiv.org
- G.-L. R. Anselmetti, D. Wierichs, C. Gogolin and R. M. Parrish, Local, expressive, quantum-number-preserving VQE ansätze for fermionic systems, New Journal of Physics 23, 113010 (2021).doi:10.1088/1367-2630/ac2cb3
Hands-on labs
Gradients with the parameter-shift rule
1 step · auto-gradedOpen labImplement the parameter-shift gradient of a variational circuit using only a black-box
evaluate(params)that returns the exact expectation value . Every parameter sits in a single Pauli rotation , so is exact. The grader checks the values on one visible and four hidden random three-qubit circuits, separately checks that your function callsevaluateexactly times, and finally checks that the values are exact to , which no finite-difference quotient achieves.