Lesson 40 · 90 min · advanced
The SWAP Test
The SWAP test estimates the overlap of two states that are only available as physical copies, without knowing or inverting their preparation circuits. This lesson writes out the controlled-SWAP (Fredkin) gate and proves that it is a self-inverse permutation matrix, derives the acceptance probability by following the state through the circuit, extends the test to -qubit registers with Fredkin gates and to mixed states through the identity , proves Hoeffding's bound for the shot budget and its exponential consequence for concentrated kernels, decomposes the Fredkin gate into two CNOTs and a Toffoli, and identifies the SWAP test as a Hadamard test of the operator SWAP.
Prerequisites: Quantum Kernels & Fidelity Kernels, Toffoli, Reversible Logic & Universality
Objectives and key results
Write the matrix of the Fredkin gate in the basis and prove that it is a self-inverse permutation matrix, hence unitary and Hermitian.
Derive the SWAP-test acceptance probability and by following the state through the circuit.
Implement the test for -qubit registers with Fredkin gates sharing one ancilla, and justify why the same formula holds.
Prove in index notation and deduce for mixed states.
Analyse the estimator : unbiasedness, variance , the Hoeffding shot bound , and the shot cost for concentrated kernels.
Prove the decomposition and count CNOTs for the -qubit test.
Derive the Hadamard test for and and recognise the SWAP test as its special case .
- formula · SWAP-test acceptance probability
- identity · The SWAP trick
- theorem · Estimator and shot budget
- identity · Fredkin decomposition
- formula · Hadamard test
Why a second overlap test?#
The previous lesson defined the fidelity kernel and showed two ways to read it off a quantum computer. The inversion test prepares , applies the inverse circuit and returns the probability of the all-zero outcome, . It is economical, with qubits and twice the depth of , but it makes a strong assumption: we must know a circuit for the second state, and we must be able to run that circuit backwards.
That assumption fails in several situations that matter for quantum machine learning and quantum information. A state can arrive from a quantum sensor, from a quantum memory or over a quantum channel from another processor ("quantum data"); it can be the output of a long physical evolution that we can repeat but not invert; it can be produced by a circuit that contains mid-circuit measurements and postselection, which has no unitary inverse; or two parties may want to compare their states without disclosing how they made them, as in quantum fingerprinting (Buhrman, Cleve, Watrous and de Wolf 2001). In all of these cases we can only ask a source for fresh copies.
The SWAP test works in exactly this setting. It consumes one copy of and one copy of per shot, uses one extra qubit (the ancilla) and a fixed, state-independent circuit, and its single measured bit has the distribution . Its price is qubits instead of , and, as we will prove, about four times as many shots for the same additive precision, and many more for small overlaps.
Definition
The overlap-estimation task
Two sources each emit, on request, a fresh copy of an -qubit state: from the first and from the second (more generally density operators and ). Nothing else is known about the states. The task is to estimate the overlap (fidelity of pure states) to additive precision with failure probability at most , using as few copies (shots) as possible. With and the overlap is the fidelity kernel of the previous lesson.
Quick check
A collaborator sends you, over a quantum link, copies of an unknown two-qubit state . You want for a state that you can prepare yourself. Which statement is correct?
The controlled-SWAP (Fredkin) gate#
Definition
Controlled-SWAP (Fredkin) gate
The Fredkin gate acts on a control qubit and two target qubits and exchanges the targets if and only if the control is : On this platform the gate is written with the control first. With the control as qubit (the most significant bit) the basis is ordered by the index , so the only basis states that move are (index ) and (index ).
Unitary verified: (max deviation 0.0e+0)
The Fredkin gate is a self-inverse permutation matrix
is the permutation matrix of the transposition of the basis indices . Consequently it is real orthogonal, hence unitary (); it is self-inverse (); and it is Hermitian, with eigenvalue on the single vector and eigenvalue on its seven-dimensional orthogonal complement, so .
Proof (8 steps)
- Step 1:Apply the definition to the eight basis states: for (indices –) nothing moves; for the states and have and are fixed, while and .
- Step 2:Column of a matrix is the image of the basis vector , here the basis vector : every column and every row contains exactly one entry , which is the definition of a permutation matrix. This reproduces the displayed matrix: with rows and exchanged.
- Step 3:The sum over picks out ; the last equality holds because is injective. So .
- Step 4:For a real matrix the conjugate transpose is the transpose, so orthogonality is unitarity.
- Step 5:Permutation matrices multiply like the permutations they represent (check on every basis vector).
- Step 6:A transposition undone by itself: applying the Fredkin gate twice restores every basis state. Combining with shows that the gate is Hermitian (equivalently, the matrix is symmetric because ).
- Step 7:Inside the invariant plane spanned by the gate acts as , with eigenvalues . The six fixed basis states and have eigenvalue , so the trace is , the number of fixed points of .
- Step 8:The operator form of the definition: with the control as the leftmost Kronecker factor, places the entry times the block at block position , so the upper-left block acts on and the lower-right block on .
∎
The Fredkin gate was introduced in classical reversible computing (Fredkin and Toffoli 1982). It conserves the number of ones in its input, and always have the same Hamming weight, and together with constant inputs it is universal for reversible Boolean logic: with the output , computes AND, and NOT and FANOUT are obtained similarly. In the SWAP test it plays a purely quantum role: its control is in superposition, so it applies the swap and the identity coherently to the two branches of the ancilla.
Quick check
What is (control qubit is the leftmost bit)?
The acceptance probability#
The SWAP test uses one ancilla (qubit ) and two registers of equal size holding and . It applies a Hadamard to the ancilla, a swap of the two registers controlled by the ancilla, a second Hadamard to the ancilla, and measures the ancilla in the computational basis. Write and ; the only property of the register swap that the proof needs is . For one-qubit states the controlled register swap is a single Fredkin gate; the next section shows how to build it for -qubit registers.
Acceptance probability of the SWAP test
Let be unit vectors and let exchange the two factors of . The circuit applied to produces and measuring the ancilla gives In particular , with if and only if and if and only if .
Proof (11 steps)
- Step 1:Initial state: ancilla in , the two registers loaded with the states to be compared.
- Step 2:on the ancilla, identity on the registers, and distributivity of .
- Step 3:Expand both states in the computational basis, use the defining action and linearity, and refactor the double sum as a product.
- Step 4:The controlled swap leaves the branch alone and swaps the registers in the branch.
- Step 5:Second Hadamard: , ; the factors ; then collect the terms by the ancilla basis state.
- Step 6:Born rule for a measurement of the ancilla alone: the probability of outcome is the squared norm of the projection , i.e. of the register vector multiplying .
- Step 7:Sesquilinearity of the inner product and , so the two cross terms add up to twice the real part.
- Step 8:Inner products of product vectors factorise, . The cross term is real and nonnegative, so its real part is itself.
- Step 9:Insert , into the norm expansion: .
- Step 10:The same computation with flips the sign of the cross term. As a check, .
- Step 11:Cauchy–Schwarz for unit vectors, with equality exactly when ; the lower end is reached exactly for orthogonal states. Since , a single shot can never certify that two states differ.
∎
The SWAP test measures the projector onto the symmetric subspace
For any state of the two registers (entangled or not), the SWAP test accepts with probability where is the orthogonal projector onto the symmetric subspace . Likewise with .
Proof (6 steps)
- Step 1:The first two layers of the theorem, with replaced by an arbitrary register state.
- Step 2:The final Hadamard, collecting the terms by ancilla value as before.
- Step 3:is a permutation matrix of the basis whose permutation is its own inverse; as for the Fredkin gate, such a matrix is real, symmetric and squares to the identity.
- Step 4:Hermitian and idempotent: an orthogonal projector. Its range consists of the vectors with , because . The same algebra applies to , and .
- Step 5:Born rule on the ancilla, then .
- Step 6:For a product input the corollary reproduces the theorem. The formula is linear in the projector , which is what makes the extension to mixed states immediate.
∎
The sampler shows the two one-qubit states on Bloch spheres, , and simulates the SWAP test shot by shot. Its starting configuration is the lab pair against : the exact value is , and the sampled frequency fluctuates around it with standard deviation . Rotate either state and observe that only the angle between the two Bloch vectors matters: for one qubit , so .
Quick check
The SWAP test is run on and . What is ?
Registers of n qubits#
For kernels the states live on qubits. Place the ancilla on qubit , the register holding on qubits and the register holding on qubits (this is the layout of the platform function ). Pair the -th qubit of , , with the -th qubit of , , for . Two lemmas reduce the controlled register swap to Fredkin gates.
A register swap is a product of qubit swaps
for all , where and the factors commute. Hence for all -qubit states.
Proof (4 steps)
- Step 1:A qubit swap exchanges the bits on its two wires and leaves every other wire unchanged.
- Step 2:Operators acting on disjoint sets of qubits commute ( after reordering the wires), so the product does not depend on the order.
- Step 3:Each factor exchanges one bit position, and every position is exchanged exactly once.
- Step 4:Linearity, exactly as in the one-qubit computation of the acceptance theorem.
∎
Controlled products are products of controlled gates
For unitaries on the target qubits and a common control qubit, with , In particular the controlled register swap is the product of the Fredkin gates , which share the ancilla as control.
Proof (4 steps)
- Step 1:The two computational-basis projectors of the control are orthogonal idempotents.
- Step 2:Multiply out with the mixed-product rule ; the cross terms vanish.
- Step 3:Induction on using the two-factor identity.
- Step 4:Apply the lemma to the factorisation of the register swap; a controlled qubit swap is by definition a Fredkin gate.
∎
The SWAP test for n-qubit states
The circuit on qubits, applied to , accepts with probability . It uses qubits, Hadamards and Fredkin gates, and one copy of each state per shot.
Proof (4 steps)
- Step 1:The controlled-product lemma applied to the register-swap factorisation.
- Step 2:The factorisation lemma; this is the only property of the swap used in the acceptance theorem.
- Step 3:The acceptance theorem with .
- Step 4:Count of the circuit elements. All Fredkin gates touch the ancilla, so in this form they run one after another and the controlled swap has depth in Fredkin gates.
∎
Quick check
How many qubits does the SWAP test need to estimate the fidelity kernel of a feature map on qubits?
Mixed states and the SWAP trick#
The SWAP trick
For all , In particular for density operators, and is the purity.
Proof (6 steps)
- Step 1:The swap maps the basis vector to ; its matrix elements are products of Kronecker deltas.
- Step 2:Matrix elements of a Kronecker product between product basis vectors factorise.
- Step 3:The trace is the sum of the diagonal elements in the product basis; insert the resolution of the identity between the two factors.
- Step 4:Insert the two matrix-element formulas: (the first line with the indices renamed) and .
- Step 5:The deltas set and ; the inner sum is the matrix product ; finally cyclicity of the trace.
- Step 6:The two special cases used below. A quadratic function of becomes a linear function of the two-copy state : this is the general mechanism behind estimating nonlinear functionals of quantum states (Ekert et al. 2002).
∎
The SWAP test on mixed states
If the registers hold independent mixed states and (joint input ), the SWAP test accepts with probability and . For pure states , and for two copies of the same state .
Proof (6 steps)
- Step 1:Born rule for a density operator: the circuit maps the input to , and the outcome probability is the trace with the measurement projector. This expression is linear in the register state .
- Step 2:For a pure register state this is the symmetric-projector corollary, rewritten with (cyclicity).
- Step 3:Every density operator has a spectral decomposition with , ; linearity of the first line in carries the pure-state formula over to every mixed register state.
- Step 4:Insert , use , the SWAP trick, and unit traces. .
- Step 5:Spectral decomposition of and linearity of the trace. Each lies in because is positive semidefinite with eigenvalues in , and the weights sum to .
- Step 6:The pure-state theorem is recovered, and two copies of one state reveal its purity, which equals exactly for pure states.
∎
Example: purity of a qubit and a mixed pair
- Step 1:The Bloch formula of the previous lesson with .
- Step 2:A qubit with ; two copies of it pass the SWAP test with probability .
- Step 3:Two valid mixed states: Hermitian, trace , and determinants and , so both eigenvalues are positive.
- Step 4:, the formula of the SWAP trick.
- Step 5:The imaginary parts cancel, as they must for a product of Hermitian matrices under the trace. The NumPy cell at the end of the lesson reproduces from and from the full three-qubit density-matrix simulation.
Result
Quick check
Both registers of a one-qubit SWAP test hold the maximally mixed state . What is ?
From shots to an estimate#
The SWAP-test fidelity estimator
Run the SWAP test times on fresh copies and let be the number of ancilla outcomes ; set and . Then where and (or ). The variance is largest, , for orthogonal states and vanishes only for identical states.
Proof (6 steps)
- Step 1:Each shot uses fresh copies and a fresh ancilla, so the indicators are independent Bernoulli variables with success probability .
- Step 2:Linearity of expectation; variances of independent variables add; .
- Step 3:The estimator is an affine function of ; insert from the acceptance theorem. It is unbiased.
- Step 4:.
- Step 5:, and the difference of squares.
- Step 6:The worst case is , where is a fair coin. A single estimate may fall outside : for near the event has probability close to and gives . Clamping to , as the library routine does, keeps the value in range but introduces a bias near the ends.
∎
Hoeffding’s inequality for Bernoulli averages
Let be independent Bernoulli variables with and . For every ,
Proof (7 steps)
- Step 1:Moment generating function of one Bernoulli variable, and the logarithm of the centred one.
- Step 2:Differentiate; , and .
- Step 3:Quotient rule; the numerator is , so , which is at most because .
- Step 4:Taylor's theorem with the Lagrange remainder (Hoeffding's lemma for Bernoulli variables): .
- Step 5:For the exponential is increasing; Markov's inequality for the nonnegative variable ; independence factorises the expectation of the product.
- Step 6:Hoeffding's lemma for each factor, then minimise the exponent over : the derivative vanishes at .
- Step 7:Union bound over the two tails; the lower tail of is the upper tail of the average of the Bernoulli variables with success probability , to which the same bound applies.
∎
Shot budget of the SWAP test
If then , for every pair of states. For the same guarantee on the inversion test needs only , a factor fewer shots.
Proof (4 steps)
- Step 1:The estimator and its mean differ by twice the error of the Bernoulli average: an error on is an error on .
- Step 2:Hoeffding's inequality with and tolerance .
- Step 3:Take logarithms (monotone) and multiply by , which reverses the inequality.
- Step 4:The inversion test estimates directly as a Bernoulli frequency, so Hoeffding applies with , without the factor .
∎
Worked shot budget: ε = 0.01, δ = 0.05
- Step 1:A guarantee.
- Step 2:Hoeffding's budget for the SWAP test; for the same formula gives .
- Step 3:The inversion test for the same precision and confidence.
- Step 4:The normal approximation with the true variance asks for fewer shots, but it requires knowing and is only asymptotic. Hoeffding's bound holds for every and every pair of states, which is why it is used to plan experiments.
Result
Concentrated kernels cost about 4^n shots with the SWAP test
Suppose the kernel value is exponentially small, , as for the concentrated product-encoding kernels of the previous lesson. (a) A relative precision requires SWAP-test shots, against inversion-test shots. (b) Even distinguishing from with Hoeffding's guarantee requires an additive precision with , hence .
Proof (5 steps)
- Step 1:Square the relative-precision requirement with the SWAP-test variance and solve for .
- Step 2:Multiply numerator and denominator by .
- Step 3:The inversion-test variance vanishes as , while the SWAP-test variance tends to its maximum : a near-zero overlap means a fair coin on the ancilla, the noisiest possible signal.
- Step 4:Hoeffding's budget with a tolerance below the value to be resolved.
- Step 5:The values and : ten qubits already separate the two tests by three orders of magnitude, per kernel entry.
∎
Here the sampler starts from the orthogonal pair () and , so and : every shot is a fair coin, and the estimate has the largest possible standard deviation . Increase the number of shots and watch the error bars shrink like ; about half of the runs produce a negative . Then move back towards : as the variance vanishes and the samples settle on .
The TypeScript cell below uses the platform library: builds the three-qubit test from two one-qubit preparation circuits, returns the exact , the simulator's seeded sampler produces shot estimates for growing , and an explicit generator repeats a Hoeffding-sized experiment times to show how conservative the bound is.
import type { CircuitIR } from '@/lib/quantum-simulator';
import { mulberry32, runCircuit, runStatevector } from '@/lib/quantum-simulator';
import { swapTestCircuit, swapTestProbability } from '@/lib/qml';
// One-qubit preparations: |psi> = RY(pi/3)|0> and |phi> = |0>.
const prepPsi: CircuitIR = { version: 1, numQubits: 1, numClbits: 0, ops: [{ kind: 'gate', gate: 'RY', targets: [0], params: [Math.PI / 3] }] };
const prepPhi: CircuitIR = { version: 1, numQubits: 1, numClbits: 0, ops: [] };
// (1) The SWAP-test circuit: ancilla = qubit 0, |psi> on qubit 1, |phi> on qubit 2, ancilla measured into clbit 0.
const test = swapTestCircuit(1)(prepPsi, prepPhi);
console.log('ops: ' + test.ops.map((op) => (op.kind === 'gate' ? op.gate + '(' + op.targets.join(',') + ')' : op.kind)).join('; '));
// (2) Exact values: F = |<psi|phi>|^2 and P(0) = (1 + F)/2.
const F = runStatevector(prepPsi).fidelity(runStatevector(prepPhi));
const p0 = swapTestProbability(runStatevector(prepPsi), runStatevector(prepPhi));
console.log('F = ' + F.toFixed(12) + ' P(0) = ' + p0.toFixed(12) + ' (1 + F)/2 = ' + ((1 + F) / 2).toFixed(12));
// (3) Shot estimates F_hat = 2 N0/N - 1 from the simulator's seeded sampler, with the standard deviation sqrt((1 - F^2)/N).
for (const shots of [100, 1000, 10000, 100000]) {
const n0 = runCircuit(test, { shots, seed: 40 }).counts?.['0'] ?? 0;
console.log('N = ' + shots + ': N0 = ' + n0 + ' F_hat = ' + ((2 * n0) / shots - 1).toFixed(4) + ' std = ' + Math.sqrt((1 - F * F) / shots).toFixed(4));
}
// (4) Hoeffding: N = ceil(2 ln(2/delta) / eps^2) shots give |F_hat - F| <= eps with probability >= 1 - delta.
const eps = 0.05;
const delta = 0.05;
const N = Math.ceil((2 * Math.log(2 / delta)) / eps ** 2);
const rng = mulberry32(40);
const repetitions = 2000;
let inside = 0;
let worst = 0;
for (let r = 0; r < repetitions; r++) {
let n0 = 0;
for (let s = 0; s < N; s++) if (rng() < p0) n0++;
const err = Math.abs((2 * n0) / N - 1 - F);
worst = Math.max(worst, err);
if (err <= eps) inside++;
}
console.log('Hoeffding N = ' + N + ': ' + inside + ' of ' + repetitions + ' experiments within eps = ' + eps + ' (largest error ' + worst.toFixed(4) + ')');
console.log('normal-approximation N = ' + Math.ceil((1.96 ** 2 * (1 - F * F)) / eps ** 2));
// (5) Orthogonal states |1> and |0>: P(0) = 1/2, where the variance (1 - F^2)/N = 1/N is largest.
const prepOne: CircuitIR = { version: 1, numQubits: 1, numClbits: 0, ops: [{ kind: 'gate', gate: 'X', targets: [0] }] };
console.log('orthogonal states: P(0) = ' + swapTestProbability(runStatevector(prepOne), runStatevector(prepPhi)).toFixed(12));Expected output
ops: RY(1); H(0); CSWAP(0,1,2); H(0); measure F = 0.750000000000 P(0) = 0.875000000000 (1 + F)/2 = 0.875000000000 N = 100: N0 = 86 F_hat = 0.7200 std = 0.0661 N = 1000: N0 = 883 F_hat = 0.7660 std = 0.0209 N = 10000: N0 = 8703 F_hat = 0.7406 std = 0.0066 N = 100000: N0 = 87577 F_hat = 0.7515 std = 0.0021 Hoeffding N = 2952: 2000 of 2000 experiments within eps = 0.05 (largest error 0.0454) normal-approximation N = 673 orthogonal states: P(0) = 0.500000000000
The shot estimates scatter around by about one predicted standard deviation . In the last experiment all repetitions with Hoeffding's shots land within , the largest error being : the guaranteed failure rate is a worst case over all states and all , and for the actual failure rate is far smaller. The normal approximation with the true variance would ask for only shots, but it presupposes the value of that the experiment is supposed to measure.
Quick check
How many SWAP-test shots does Hoeffding's bound require for with probability at least ?
Compiling the Fredkin gate#
Hardware offers one- and two-qubit gates, so the Fredkin gate must be compiled. The cleanest route goes through the Toffoli gate , whose decomposition into six CNOTs, seven gates and two Hadamards was proved in the lesson on the Toffoli gate. Below, has control qubit and target qubit ; in the circuit editor it is .
Fredkin from two CNOTs and a Toffoli
The product is a palindrome, so it reads the same as a matrix product and as a circuit (time order ). In the branch it contains the three-CNOT identity .
Proof (7 steps)
- Step 1:Bit maps of the factors on . All three gates and are permutation matrices of the basis, and a linear map is determined by its values on a basis, so it suffices to show that the composed bit map is for and for .
- Step 2:Qubit is only ever a control. So the product preserves the subspaces and , and we can argue case by case.
- Step 3:With the Toffoli adds and acts as the identity, and because . This is the action of for .
- Step 4:With the Toffoli adds to the target: a CNOT from qubit to qubit .
- Step 5:The three-CNOT SWAP identity, by following the bits: and is associative and commutative.
- Step 6:The two cases combine into the operator form of the Fredkin gate.
- Step 7:Spot check on the two basis states that the Fredkin gate moves, layer by layer.
∎
Circuit · 3 qubits
The decomposition . Its unitary is the Fredkin matrix: the identity except that the rows and columns of and are exchanged.
Two-qubit gate count of the SWAP test
With the six-CNOT Toffoli, one Fredkin gate costs CNOTs (and -type gates), and the SWAP test on -qubit registers costs CNOTs, -type gates and Hadamards. For and the gate set , in which the Toffoli is a primitive, the decomposed test has exactly gates, the gate budget of the lab.
Proof (4 steps)
- Step 1:Count the factors of the decomposition, using the six-CNOT Toffoli circuit.
- Step 2:The CNOTs of the decomposition contribute no single-qubit gates; the Toffoli circuit contributes seven gates and two Hadamards.
- Step 3:The -qubit test consists of Fredkin gates plus the two Hadamards on the ancilla.
- Step 4:When the Toffoli is available as a primitive, as in the lab, the decomposed test has exactly five gates.
∎
Quick check
How many CNOTs does the SWAP test for three-qubit states cost when every Fredkin gate is compiled with the decomposition above and a six-CNOT Toffoli?
The Hadamard test#
The SWAP test is one instance of a more general interferometric primitive. Replace the controlled swap by a controlled version of any unitary and the ancilla measures the real part of the expectation value ; an extra phase gate on the ancilla turns this into the imaginary part. The Hadamard test appears in phase estimation, in the estimation of Jones polynomials (Aharonov, Jones and Landau 2009) and in variational algorithms that need overlaps or gradients that are not expectation values of Hermitian observables.
Hadamard test for the real part
Let be unitary and a unit vector. The circuit on produces , and
Proof (5 steps)
- Step 1:The Hadamard prepares on the ancilla; the controlled unitary acts on the branch only.
- Step 2:, , collected by ancilla value.
- Step 3:Born rule on the ancilla and the expansion .
- Step 4:Unitarity preserves the norm.
- Step 5:The same expansion with ; the ancilla's expectation is the difference of the two probabilities.
∎
Hadamard test for the imaginary part
Insert on the ancilla after the first Hadamard. Then With instead, the sign is reversed: . Running both variants determines the complex number .
Proof (6 steps)
- Step 1:multiplies the amplitude by .
- Step 2:Controlled unitary on the branch, then the final Hadamard as before.
- Step 3:The norm expansion with , , .
- Step 4:Multiplication by rotates the complex plane by and moves the imaginary part onto the real axis.
- Step 5:Insert into the previous line; for , .
- Step 6:With the branch carries , and : the sign convention matters, and the numerical check below confirms it.
∎
The SWAP test is the Hadamard test of SWAP
The SWAP test is the Hadamard test with and input : so the real-part test gives and the imaginary-part variant always gives .
Proof (4 steps)
- Step 1:The controlled unitary of the Hadamard test is the controlled register swap of the SWAP test (controlled-product lemma), and the two circuits coincide gate for gate.
- Step 2:The swap exchanges the factors, and inner products of product vectors factorise.
- Step 3:Expectation values of Hermitian operators are real: . So the imaginary part vanishes even for entangled register states.
- Step 4:The Hadamard-test formula reproduces the acceptance theorem.
∎
Example: U = R_Z(0.8) on the lab state
- Step 1:with .
- Step 2:for diagonal ; Euler's formula: .
- Step 3:Numerical values.
- Step 4:The two Hadamard-test variants. The NumPy cell recovers both numbers from .
Result
Quick check
In the Hadamard test the controlled unitary is (a global phase , controlled by the ancilla). What does the ancilla return?
Worked example: the lab state#
SWAP test of R_Y(π/3)|0⟩ against |0⟩, amplitude by amplitude
- Step 1:First column of at .
- Step 2:The prediction of the acceptance theorem; the remaining steps confirm it amplitude by amplitude.
- Step 3:Kronecker product with the ancilla as the leftmost factor; index , so is index .
- Step 4:on the ancilla copies each amplitude into the half with the factor : and .
- Step 5:The Fredkin gate moves the amplitude of (index ) to (index ); has equal targets and stays.
- Step 6:The final Hadamard combines the amplitudes of each pair of indices into their sum and difference over .
- Step 7:Pairs and : the pair interferes completely constructively and destructively, and the pair has a single nonzero amplitude, at index .
- Step 8:Pair has only the amplitude at index , which enters the output with a minus sign; pair is empty.
- Step 9:All eight amplitudes. Norm check: . It agrees with the theorem: and .
- Step 10:Sum the squared moduli over indices – (ancilla ) and – (ancilla ). The ancilla expectation is the auxiliary quantity checked by the lab.
Result
Circuit · 3 qubits
The lab circuit: prepares on qubit , qubit stays , and is the SWAP test. The statevector shows the five nonzero amplitudes at ; the histogram puts of the weight on ancilla outcome .
- |000⟩0.75
- |001⟩0.0625
- |010⟩0.0625
- |011⟩0
- |100⟩0
- |101⟩0.0625
- |110⟩0.0625
- |111⟩0
The NumPy cell rebuilds everything from bit maps: the Fredkin, CNOT and Toffoli permutation matrices and the decomposition identity; the eight amplitudes after each layer of the lab circuit; the SWAP trick and the mixed-state acceptance probability from a full density-matrix simulation of the three-qubit circuit; both Hadamard-test variants for ; seeded shot estimates; Hoeffding budgets; and the per-entry shot cost of the SWAP and inversion tests for kernel values at relative precision.
import numpy as np
# Basis |c a b> with qubit 0 (the ancilla c) as the most significant bit: index 4c + 2a + b.
def bits(k):
return (k >> 2) & 1, (k >> 1) & 1, k & 1
def perm(f):
"""8 x 8 permutation matrix of the bit map (c, a, b) -> f(c, a, b)."""
P = np.zeros((8, 8))
for k in range(8):
c, a, b = f(*bits(k))
P[4 * c + 2 * a + b, k] = 1.0
return P
CSWAP = perm(lambda c, a, b: (c, b, a) if c else (c, a, b))
CNOT21 = perm(lambda c, a, b: (c, a ^ b, b))
CCX = perm(lambda c, a, b: (c, a, b ^ (c & a)))
print("CSWAP: unitary", np.allclose(CSWAP.T @ CSWAP, np.eye(8)), "| self-inverse", np.allclose(CSWAP @ CSWAP, np.eye(8)),
"| CNOT_21 CCX CNOT_21 = CSWAP", np.allclose(CNOT21 @ CCX @ CNOT21, CSWAP))
# (1) The SWAP test on |psi> = RY(pi/3)|0>, |phi> = |0>: all eight amplitudes after each layer.
H = np.array([[1.0, 1.0], [1.0, -1.0]]) / np.sqrt(2)
H0 = np.kron(H, np.eye(4))
psi = np.array([np.cos(np.pi / 6), np.sin(np.pi / 6)])
phi = np.array([1.0, 0.0])
state = np.kron([1.0, 0.0], np.kron(psi, phi))
for name, U in (("H", H0), ("CSWAP", CSWAP), ("H", H0)):
state = U @ state
print(f"after {name:5s}", " ".join(f"{v:+.6f}" for v in state + 0.0))
F = abs(np.vdot(psi, phi)) ** 2
p0 = float(np.sum(state[:4] ** 2))
print(f"F = {F:.6f} P(0) = {p0:.6f} (1 + F)/2 = {(1 + F) / 2:.6f} P(1) = {1 - p0:.6f}")
# (2) Mixed states: Tr[SWAP (rho x sigma)] = Tr(rho sigma) and P(0) = (1 + Tr(rho sigma))/2.
SWAP = CSWAP[4:, 4:]
rho = np.array([[0.7, 0.2 - 0.1j], [0.2 + 0.1j, 0.3]])
sigma = np.array([[0.4, 0.1j], [-0.1j, 0.6]])
V = H0 @ CSWAP @ H0
out = V @ np.kron(np.diag([1.0, 0.0]), np.kron(rho, sigma)) @ V.conj().T
print(f"Tr[SWAP (rho x sigma)] = {np.trace(SWAP @ np.kron(rho, sigma)).real:.6f} Tr(rho sigma) = {np.trace(rho @ sigma).real:.6f} P(0) = {np.trace(out[:4, :4]).real:.6f}")
# (3) Hadamard test for U = RZ(0.8) on |psi>: P(0) = (1 + Re<psi|U|psi>)/2, with S^dagger: (1 + Im<psi|U|psi>)/2.
U = np.diag([np.exp(-0.4j), np.exp(0.4j)])
CU = np.block([[np.eye(2), np.zeros((2, 2))], [np.zeros((2, 2)), U]])
Hd, Sdg = np.kron(H, np.eye(2)), np.kron(np.diag([1.0, -1.0j]), np.eye(2))
z = np.vdot(psi, U @ psi)
for label, pre, exact in (("Re", np.eye(4), z.real), ("Im", Sdg, z.imag)):
s = Hd @ CU @ pre @ Hd @ np.kron([1.0, 0.0], psi)
print(f"Hadamard test ({label}): 2 P(0) - 1 = {2 * np.sum(np.abs(s[:2]) ** 2) - 1:+.6f} exact = {exact:+.6f}")
# (4) Shots: F_hat = 2 N0/N - 1 with a seeded generator; Hoeffding N >= 2 ln(2/delta)/eps^2.
rng = np.random.default_rng(40)
for N in (100, 1000, 10000, 100000):
n0 = int(np.count_nonzero(rng.random(N) < p0))
print(f"N = {N:6d}: N0 = {n0:5d} F_hat = {2 * n0 / N - 1:+.4f} std = {np.sqrt((1 - F ** 2) / N):.4f}")
for eps in (0.05, 0.01):
print(f"Hoeffding, eps = {eps}, delta = 0.05: N = {int(np.ceil(2 * np.log(2 / 0.05) / eps ** 2))}")
for n in (2, 5, 10, 20):
K = 2.0 ** -n
print(f"K = 2^-{n:<2d}: shots for 10% relative error SWAP test {(1 - K ** 2) / (0.1 * K) ** 2:.3e} inversion test {K * (1 - K) / (0.1 * K) ** 2:.3e}")Expected output
CSWAP: unitary True | self-inverse True | CNOT_21 CCX CNOT_21 = CSWAP True after H +0.612372 +0.000000 +0.353553 +0.000000 +0.612372 +0.000000 +0.353553 +0.000000 after CSWAP +0.612372 +0.000000 +0.353553 +0.000000 +0.612372 +0.353553 +0.000000 +0.000000 after H +0.866025 +0.250000 +0.250000 +0.000000 +0.000000 -0.250000 +0.250000 +0.000000 F = 0.750000 P(0) = 0.875000 (1 + F)/2 = 0.875000 P(1) = 0.125000 Tr[SWAP (rho x sigma)] = 0.440000 Tr(rho sigma) = 0.440000 P(0) = 0.720000 Hadamard test (Re): 2 P(0) - 1 = +0.921061 exact = +0.921061 Hadamard test (Im): 2 P(0) - 1 = -0.194709 exact = -0.194709 N = 100: N0 = 89 F_hat = +0.7800 std = 0.0661 N = 1000: N0 = 883 F_hat = +0.7660 std = 0.0209 N = 10000: N0 = 8737 F_hat = +0.7474 std = 0.0066 N = 100000: N0 = 87315 F_hat = +0.7463 std = 0.0021 Hoeffding, eps = 0.05, delta = 0.05: N = 2952 Hoeffding, eps = 0.01, delta = 0.05: N = 73778 K = 2^-2 : shots for 10% relative error SWAP test 1.500e+03 inversion test 3.000e+02 K = 2^-5 : shots for 10% relative error SWAP test 1.023e+05 inversion test 3.100e+03 K = 2^-10: shots for 10% relative error SWAP test 1.049e+08 inversion test 1.023e+05 K = 2^-20: shots for 10% relative error SWAP test 1.100e+14 inversion test 1.049e+08
In the lab you build the circuit of the worked example. The preparation is locked; you append the SWAP test with at most five gates from , either with a Fredkin gate or with its decomposition. The grader checks the exact ancilla marginal and , and recognises the two classic mistakes: dropping the controlled swap () and dropping the final Hadamard ().
References
- H. Buhrman, R. Cleve, J. Watrous and R. de Wolf, Quantum fingerprinting, Physical Review Letters 87, 167902 (2001).doi:10.1103/PhysRevLett.87.167902
- A. K. Ekert, C. M. Alves, D. K. L. Oi, M. Horodecki, P. Horodecki and L. C. Kwek, Direct estimations of linear and nonlinear functionals of a quantum state, Physical Review Letters 88, 217901 (2002).doi:10.1103/PhysRevLett.88.217901
- J. C. Garcia-Escartin and P. Chamorro-Posada, Swap test and Hong-Ou-Mandel effect are equivalent, Physical Review A 87, 052330 (2013).doi:10.1103/PhysRevA.87.052330
- L. Cincio, Y. Subaşı, A. T. Sornborger and P. J. Coles, Learning the quantum algorithm for state overlap, New Journal of Physics 20, 113022 (2018).doi:10.1088/1367-2630/aae94a
- E. Fredkin and T. Toffoli, Conservative logic, International Journal of Theoretical Physics 21, 219–253 (1982).doi:10.1007/BF01857727
- J. A. Smolin and D. P. DiVincenzo, Five two-bit quantum gates are sufficient to implement the quantum Fredkin gate, Physical Review A 53, 2855 (1996).doi:10.1103/PhysRevA.53.2855
- D. Aharonov, V. Jones and Z. Landau, A polynomial quantum algorithm for approximating the Jones polynomial, Algorithmica 55, 395–421 (2009).doi:10.1007/s00453-008-9168-0
- W. Hoeffding, Probability inequalities for sums of bounded random variables, Journal of the American Statistical Association 58(301), 13–30 (1963).doi:10.1080/01621459.1963.10500830
- M. A. Nielsen and I. L. Chuang, Quantum Computation and Quantum Information, 10th anniversary edition, Cambridge University Press (2010).doi:10.1017/CBO9780511976667
- V. Havlíček, A. D. Córcoles, K. Temme, A. W. Harrow, A. Kandala, J. M. Chow and J. M. Gambetta, Supervised learning with quantum-enhanced feature spaces, Nature 567, 209–212 (2019).doi:10.1038/s41586-019-0980-2
Hands-on labs
Build the SWAP test
1 step · auto-gradedOpen labBuild the SWAP test on three qubits and read the fidelity of two one-qubit states from the ancilla alone: with and the overlap is , so the ancilla must return with probability .