Hands-on lab · 1 step
Gradients with the parameter-shift rule
Implement 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 calls evaluate exactly times, and finally checks that the values are exact to , which no finite-difference quotient achieves.
Step 1: Implement parameterShiftGradient
Complete the TypeScript function
parameterShiftGradient(evaluate: (params: number[]) => number, params: number[]): number[]
What evaluate does. evaluate(p) runs a fixed unitary circuit on with the parameter values p and returns the exact expectation value of a fixed observable (a real combination of Pauli strings). p must be an array with one finite number per parameter; entry p[j] is bound to the circuit's -th declared parameter. A wrong length or a non-finite entry throws. Every call is counted, as each call would be a separate circuit execution on hardware.
What to return. An array grad of length params.length with grad[j] at params. Every parameter-dependent gate is a Pauli rotation with , and each parameter appears in exactly one gate, so
where is the -th unit vector: only entry is shifted.
Call budget. Exactly two calls of evaluate per parameter, i.e. exactly calls in total. The unshifted value is not needed. Do not modify params; work on copies.
Tests. Every test calls your function with the arguments (evaluate, params). The values check compares your gradient with the exact one; the calls check runs the same problems again and also requires exactly calls; the exact check (tests exact-visible and exact-random-1 to exact-random-4) runs them once more with the absolute tolerance . The shift rule is exact up to floating-point rounding, so it passes all three; central finite differences with a small step also use calls but fail exact.
- visible and calls-visible: the circuit , , with , for which . At
params = [0.4, 1.1]the gradient is (absolute tolerance ), using calls. - random-1 to random-4 and calls-random-1 to calls-random-4 (hidden): random three-qubit circuits of , , rotations interleaved with CNOTs, with respectively 7, 7, 7, 8 parameters and an observable that is a Pauli string or a sum of two weighted Pauli strings (absolute tolerance ). Only their arguments are sent to your browser; the expected gradients stay on the server.