QuantumCore

Lesson 40 · 90 min · advanced

The SWAP Test

Loading progress…

The SWAP test estimates the overlap ∣⟨ψ∣ϕ⟩∣2\lvert\langle\psi\vert\phi\rangle\rvert^2 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 P(0)=12(1+∣⟨ψ∣ϕ⟩∣2)P(0)=\frac12\big(1+\lvert\langle\psi\vert\phi\rangle\rvert^2\big) by following the state through the circuit, extends the test to nn-qubit registers with nn Fredkin gates and to mixed states through the identity Tr[SWAP(ρ⊗σ)]=Tr(ρσ)\mathrm{Tr}\big[\mathrm{SWAP}(\rho\otimes\sigma)\big]=\mathrm{Tr}(\rho\sigma), proves Hoeffding's bound N≥2ln⁡(2/δ)/ε2N\ge2\ln(2/\delta)/\varepsilon^2 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 8×88\times8 matrix of the Fredkin gate in the basis ∣c a b⟩\lvert c\,a\,b\rangle and prove that it is a self-inverse permutation matrix, hence unitary and Hermitian.

  • Derive the SWAP-test acceptance probability P(0)=12(1+∣⟨ψ∣ϕ⟩∣2)P(0)=\frac12\big(1+\lvert\langle\psi\vert\phi\rangle\rvert^2\big) and P(1)=12(1−∣⟨ψ∣ϕ⟩∣2)P(1)=\frac12\big(1-\lvert\langle\psi\vert\phi\rangle\rvert^2\big) by following the state through the circuit.

  • Implement the test for nn-qubit registers with nn Fredkin gates sharing one ancilla, and justify why the same formula holds.

  • Prove Tr[SWAP(ρ⊗σ)]=Tr(ρσ)\mathrm{Tr}\big[\mathrm{SWAP}(\rho\otimes\sigma)\big]=\mathrm{Tr}(\rho\sigma) in index notation and deduce P(0)=12(1+Tr(ρσ))P(0)=\frac12\big(1+\mathrm{Tr}(\rho\sigma)\big) for mixed states.

  • Analyse the estimator F^=2P^(0)−1\hat F=2\hat P(0)-1: unbiasedness, variance (1−F2)/N(1-F^2)/N, the Hoeffding shot bound N≥2ln⁡(2/δ)/ε2N\ge2\ln(2/\delta)/\varepsilon^2, and the 4n4^n shot cost for concentrated kernels.

  • Prove the decomposition CSWAP0;1,2=CNOT2→1 CCX0,1→2 CNOT2→1\mathrm{CSWAP}_{0;1,2}=\mathrm{CNOT}_{2\to1}\,\mathrm{CCX}_{0,1\to2}\,\mathrm{CNOT}_{2\to1} and count 8n8n CNOTs for the nn-qubit test.

  • Derive the Hadamard test for Re⟨ψ∣U∣ψ⟩\mathrm{Re}\langle\psi\vert U\vert\psi\rangle and Im⟨ψ∣U∣ψ⟩\mathrm{Im}\langle\psi\vert U\vert\psi\rangle and recognise the SWAP test as its special case U=SWAPU=\mathrm{SWAP}.

formula · SWAP-test acceptance probability
P(0)=14∥∣ψϕ⟩+∣ϕψ⟩∥2=12(1+∣⟨ψ∣ϕ⟩∣2),P(1)=12(1−∣⟨ψ∣ϕ⟩∣2)P(0)=\tfrac14\big\lVert\lvert\psi\phi\rangle+\lvert\phi\psi\rangle\big\rVert^2=\tfrac12\big(1+\lvert\langle\psi\vert\phi\rangle\rvert^2\big),\qquad P(1)=\tfrac12\big(1-\lvert\langle\psi\vert\phi\rangle\rvert^2\big)
identity · The SWAP trick
Tr[SWAP (ρ⊗σ)]=Tr(ρσ) ⇒ P(0)=12(1+Tr(ρσ))\mathrm{Tr}\big[\mathrm{SWAP}\,(\rho\otimes\sigma)\big]=\mathrm{Tr}(\rho\sigma)\ \Rightarrow\ P(0)=\tfrac12\big(1+\mathrm{Tr}(\rho\sigma)\big)
theorem · Estimator and shot budget
F^=2P^(0)−1,E[F^]=F,Var[F^]=4P0(1−P0)N=1−F2N,N≥2ln⁡(2/δ)ε2⇒P(∣F^−F∣≤ε)≥1−δ\hat F=2\hat P(0)-1,\quad\mathbb E[\hat F]=F,\quad\mathrm{Var}[\hat F]=\frac{4P_0(1-P_0)}N=\frac{1-F^2}N,\qquad N\ge\frac{2\ln(2/\delta)}{\varepsilon^2}\Rightarrow P\big(\lvert\hat F-F\rvert\le\varepsilon\big)\ge1-\delta
identity · Fredkin decomposition
CSWAP0;1,2=CNOT2→1 CCX0,1→2 CNOT2→1(8 CNOTs with a 6-CNOT Toffoli)\mathrm{CSWAP}_{0;1,2}=\mathrm{CNOT}_{2\to1}\,\mathrm{CCX}_{0,1\to2}\,\mathrm{CNOT}_{2\to1}\qquad(8\ \text{CNOTs with a 6-CNOT Toffoli})
formula · Hadamard test
P(0)=12(1+Re⟨ψ∣U∣ψ⟩),P(0)∣S†=12(1+Im⟨ψ∣U∣ψ⟩)P(0)=\tfrac12\big(1+\mathrm{Re}\langle\psi\vert U\vert\psi\rangle\big),\qquad P(0)\big\vert_{S^\dagger}=\tfrac12\big(1+\mathrm{Im}\langle\psi\vert U\vert\psi\rangle\big)

Why a second overlap test?#

The previous lesson defined the fidelity kernel K(x,x′)=∣⟨ϕ(x)∣ϕ(x′)⟩∣2K(x,x')=\lvert\langle\phi(x)\vert\phi(x')\rangle\rvert^2 and showed two ways to read it off a quantum computer. The inversion test prepares ∣ϕ(x)⟩=U(x)∣0n⟩\lvert\phi(x)\rangle=U(x)\lvert0^n\rangle, applies the inverse circuit U(x′)†U(x')^\dagger and returns the probability of the all-zero outcome, P(0n)=∣⟨0n∣U(x′)†U(x)∣0n⟩∣2=K(x,x′)P(0^n)=\lvert\langle0^n\vert U(x')^\dagger U(x)\vert0^n\rangle\rvert^2=K(x,x'). It is economical, with nn qubits and twice the depth of UU, 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 ∣ψ⟩\lvert\psi\rangle and one copy of ∣ϕ⟩\lvert\phi\rangle per shot, uses one extra qubit (the ancilla) and a fixed, state-independent circuit, and its single measured bit has the distribution P(0)=12(1+∣⟨ψ∣ϕ⟩∣2)P(0)=\frac12\big(1+\lvert\langle\psi\vert\phi\rangle\rvert^2\big). Its price is 2n+12n+1 qubits instead of nn, 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 nn-qubit state: ∣ψ⟩\lvert\psi\rangle from the first and ∣ϕ⟩\lvert\phi\rangle from the second (more generally density operators ρ\rho and σ\sigma). Nothing else is known about the states. The task is to estimate the overlap (fidelity of pure states) F=∣⟨ψ∣ϕ⟩∣2∈[0,1],or in generalTr(ρσ)∈[0,1],F=\lvert\langle\psi\vert\phi\rangle\rvert^2\in[0,1],\qquad\text{or in general}\qquad\mathrm{Tr}(\rho\sigma)\in[0,1], to additive precision ε\varepsilon with failure probability at most δ\delta, using as few copies (shots) NN as possible. With ∣ψ⟩=∣ϕ(x)⟩\lvert\psi\rangle=\lvert\phi(x)\rangle and ∣ϕ⟩=∣ϕ(x′)⟩\lvert\phi\rangle=\lvert\phi(x')\rangle the overlap is the fidelity kernel K(x,x′)K(x,x') of the previous lesson.

Quick check

A collaborator sends you, over a quantum link, 10410^4 copies of an unknown two-qubit state ∣ϕ⟩\lvert\phi\rangle. You want ∣⟨ψ∣ϕ⟩∣2\lvert\langle\psi\vert\phi\rangle\rvert^2 for a state ∣ψ⟩\lvert\psi\rangle that you can prepare yourself. Which statement is correct?

Select one answer

The controlled-SWAP (Fredkin) gate#

Definition

Controlled-SWAP (Fredkin) gate

The Fredkin gate CSWAPc;a,b\mathrm{CSWAP}_{c;a,b} acts on a control qubit cc and two target qubits a,ba,b and exchanges the targets if and only if the control is 11: CSWAP ∣c a b⟩={∣c a b⟩,c=0,∣c b a⟩,c=1,CSWAP=∣0⟩⟨0∣⊗I4+∣1⟩⟨1∣⊗SWAP.\mathrm{CSWAP}\,\lvert c\,a\,b\rangle=\begin{cases}\lvert c\,a\,b\rangle,&c=0,\\\lvert c\,b\,a\rangle,&c=1,\end{cases}\qquad\mathrm{CSWAP}=\lvert0\rangle\langle0\rvert\otimes I_4+\lvert1\rangle\langle1\rvert\otimes\mathrm{SWAP}. On this platform the gate is written CSWAP(c,a,b)\mathrm{CSWAP}(c,a,b) with the control first. With the control as qubit 00 (the most significant bit) the basis ∣c a b⟩\lvert c\,a\,b\rangle is ordered by the index 4c+2a+b4c+2a+b, so the only basis states that move are ∣101⟩\lvert101\rangle (index 55) and ∣110⟩\lvert110\rangle (index 66).

CSWAP0;1,2=(1000000001000000001000000001000000001000000000100000010000000001)=(I400SWAP),SWAP=(1000001001000001)\mathrm{CSWAP}_{0;1,2}=\begin{pmatrix}1&0&0&0&0&0&0&0\\0&1&0&0&0&0&0&0\\0&0&1&0&0&0&0&0\\0&0&0&1&0&0&0&0\\0&0&0&0&1&0&0&0\\0&0&0&0&0&0&1&0\\0&0&0&0&0&1&0&0\\0&0&0&0&0&0&0&1\end{pmatrix}=\begin{pmatrix}I_4&0\\0&\mathrm{SWAP}\end{pmatrix},\qquad\mathrm{SWAP}=\begin{pmatrix}1&0&0&0\\0&0&1&0\\0&1&0&0\\0&0&0&1\end{pmatrix}
CSWAP in the basis |c a b⟩ with qubit 0 = control8×8

Unitary verified: U†U=IU^\dagger U = I (max deviation 0.0e+0)

Proposition

The Fredkin gate is a self-inverse permutation matrix

CSWAP\mathrm{CSWAP} is the permutation matrix PπP_\pi of the transposition π=(5 6)\pi=(5\ 6) of the basis indices {0,…,7}\{0,\dots,7\}. Consequently it is real orthogonal, hence unitary (CSWAP†CSWAP=I8\mathrm{CSWAP}^\dagger\mathrm{CSWAP}=I_8); it is self-inverse (CSWAP2=I8\mathrm{CSWAP}^2=I_8); and it is Hermitian, with eigenvalue −1-1 on the single vector 12(∣101⟩−∣110⟩)\frac1{\sqrt2}\big(\lvert101\rangle-\lvert110\rangle\big) and eigenvalue +1+1 on its seven-dimensional orthogonal complement, so Tr CSWAP=6\mathrm{Tr}\,\mathrm{CSWAP}=6.

Proof (8 steps)
  1. Step 1:
    CSWAP∣k⟩=∣π(k)⟩,π(5)=6,  π(6)=5,  π(k)=k  (k∉{5,6})\mathrm{CSWAP}\lvert k\rangle=\lvert\pi(k)\rangle,\qquad\pi(5)=6,\ \ \pi(6)=5,\ \ \pi(k)=k\ \ (k\notin\{5,6\})
    Apply the definition to the eight basis states: for c=0c=0 (indices 00–33) nothing moves; for c=1c=1 the states ∣100⟩\lvert100\rangle and ∣111⟩\lvert111\rangle have a=ba=b and are fixed, while ∣101⟩↦∣110⟩\lvert101\rangle\mapsto\lvert110\rangle and ∣110⟩↦∣101⟩\lvert110\rangle\mapsto\lvert101\rangle.
  2. Step 2:
    (Pπ)jk=⟨j∣Pπ∣k⟩=δj,π(k)(P_\pi)_{jk}=\langle j\vert P_\pi\vert k\rangle=\delta_{j,\pi(k)}
    Column kk of a matrix is the image of the basis vector ∣k⟩\lvert k\rangle, here the basis vector ∣π(k)⟩\lvert\pi(k)\rangle: every column and every row contains exactly one entry 11, which is the definition of a permutation matrix. This reproduces the displayed matrix: I8I_8 with rows 55 and 66 exchanged.
  3. Step 3:
    (Pπ⊤Pπ)kl=∑j=07δj,π(k) δj,π(l)=δπ(k),π(l)=δkl(P_\pi^{\top}P_\pi)_{kl}=\sum_{j=0}^{7}\delta_{j,\pi(k)}\,\delta_{j,\pi(l)}=\delta_{\pi(k),\pi(l)}=\delta_{kl}
    The sum over jj picks out j=π(k)j=\pi(k); the last equality holds because π\pi is injective. So Pπ⊤Pπ=I8P_\pi^\top P_\pi=I_8.
  4. Step 4:
    Pπ∈R8×8 ⇒ Pπ†=Pπ‾ ⊤=Pπ⊤ ⇒ Pπ†Pπ=I8P_\pi\in\mathbb R^{8\times8}\ \Rightarrow\ P_\pi^\dagger=\overline{P_\pi}^{\,\top}=P_\pi^\top\ \Rightarrow\ P_\pi^\dagger P_\pi=I_8
    For a real matrix the conjugate transpose is the transpose, so orthogonality is unitarity.
  5. Step 5:
    PσPτ∣k⟩=Pσ∣τ(k)⟩=∣σ(τ(k))⟩ ⇒ PσPτ=Pσ∘τP_\sigma P_\tau\lvert k\rangle=P_\sigma\lvert\tau(k)\rangle=\lvert\sigma(\tau(k))\rangle\ \Rightarrow\ P_\sigma P_\tau=P_{\sigma\circ\tau}
    Permutation matrices multiply like the permutations they represent (check on every basis vector).
  6. Step 6:
    π∘π=id ⇒ CSWAP2=Pπ∘π=Pid=I8 ⇒ CSWAP−1=CSWAP=CSWAP†\pi\circ\pi=\mathrm{id}\ \Rightarrow\ \mathrm{CSWAP}^2=P_{\pi\circ\pi}=P_{\mathrm{id}}=I_8\ \Rightarrow\ \mathrm{CSWAP}^{-1}=\mathrm{CSWAP}=\mathrm{CSWAP}^\dagger
    A transposition undone by itself: applying the Fredkin gate twice restores every basis state. Combining CSWAP−1=CSWAP\mathrm{CSWAP}^{-1}=\mathrm{CSWAP} with CSWAP−1=CSWAP†\mathrm{CSWAP}^{-1}=\mathrm{CSWAP}^\dagger shows that the gate is Hermitian (equivalently, the matrix is symmetric because π=π−1\pi=\pi^{-1}).
  7. Step 7:
    CSWAP 12(∣101⟩∓∣110⟩)=12(∣110⟩∓∣101⟩)=∓12(∣101⟩∓∣110⟩)\mathrm{CSWAP}\,\tfrac1{\sqrt2}\big(\lvert101\rangle\mp\lvert110\rangle\big)=\tfrac1{\sqrt2}\big(\lvert110\rangle\mp\lvert101\rangle\big)=\mp\tfrac1{\sqrt2}\big(\lvert101\rangle\mp\lvert110\rangle\big)
    Inside the invariant plane spanned by ∣101⟩,∣110⟩\lvert101\rangle,\lvert110\rangle the gate acts as XX, with eigenvalues ±1\pm1. The six fixed basis states and 12(∣101⟩+∣110⟩)\frac1{\sqrt2}(\lvert101\rangle+\lvert110\rangle) have eigenvalue +1+1, so the trace is 7⋅1+1⋅(−1)=67\cdot1+1\cdot(-1)=6, the number of fixed points of π\pi.
  8. Step 8:
    ∣0⟩⟨0∣⊗I4+∣1⟩⟨1∣⊗SWAP=(1000)⊗I4+(0001)⊗SWAP=(I400SWAP)\lvert0\rangle\langle0\rvert\otimes I_4+\lvert1\rangle\langle1\rvert\otimes\mathrm{SWAP}=\begin{pmatrix}1&0\\0&0\end{pmatrix}\otimes I_4+\begin{pmatrix}0&0\\0&1\end{pmatrix}\otimes\mathrm{SWAP}=\begin{pmatrix}I_4&0\\0&\mathrm{SWAP}\end{pmatrix}
    The operator form of the definition: with the control as the leftmost Kronecker factor, A⊗BA\otimes B places the entry ArcA_{rc} times the block BB at block position (r,c)(r,c), so the upper-left block acts on c=0c=0 and the lower-right block on c=1c=1.

∎

The Fredkin gate was introduced in classical reversible computing (Fredkin and Toffoli 1982). It conserves the number of ones in its input, ∣c a b⟩\lvert c\,a\,b\rangle and CSWAP∣c a b⟩\mathrm{CSWAP}\lvert c\,a\,b\rangle always have the same Hamming weight, and together with constant inputs it is universal for reversible Boolean logic: with b=0b=0 the output a′=a cˉa'=a\,\bar c, b′=a cb'=a\,c 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 CSWAP0;1,2 ∣110⟩\mathrm{CSWAP}_{0;1,2}\,\lvert110\rangle (control qubit 00 is the leftmost bit)?

Select one answer

The acceptance probability#

The SWAP test uses one ancilla (qubit 00) and two registers of equal size holding ∣ψ⟩\lvert\psi\rangle and ∣ϕ⟩\lvert\phi\rangle. 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 ∣ψϕ⟩=∣ψ⟩⊗∣ϕ⟩\lvert\psi\phi\rangle=\lvert\psi\rangle\otimes\lvert\phi\rangle and ∣ϕψ⟩=∣ϕ⟩⊗∣ψ⟩\lvert\phi\psi\rangle=\lvert\phi\rangle\otimes\lvert\psi\rangle; the only property of the register swap that the proof needs is SWAP∣ψϕ⟩=∣ϕψ⟩\mathrm{SWAP}\lvert\psi\phi\rangle=\lvert\phi\psi\rangle. For one-qubit states the controlled register swap is a single Fredkin gate; the next section shows how to build it for nn-qubit registers.

Theorem

Acceptance probability of the SWAP test

Let ∣ψ⟩,∣ϕ⟩∈Cd\lvert\psi\rangle,\lvert\phi\rangle\in\mathbb C^d be unit vectors and let SWAP\mathrm{SWAP} exchange the two factors of Cd⊗Cd\mathbb C^d\otimes\mathbb C^d. The circuit H0⋅(∣0⟩⟨0∣⊗I+∣1⟩⟨1∣⊗SWAP)⋅H0H_0\cdot\big(\lvert0\rangle\langle0\rvert\otimes I+\lvert1\rangle\langle1\rvert\otimes\mathrm{SWAP}\big)\cdot H_0 applied to ∣0⟩∣ψ⟩∣ϕ⟩\lvert0\rangle\lvert\psi\rangle\lvert\phi\rangle produces 12∣0⟩(∣ψϕ⟩+∣ϕψ⟩)+12∣1⟩(∣ψϕ⟩−∣ϕψ⟩),\tfrac12\lvert0\rangle\big(\lvert\psi\phi\rangle+\lvert\phi\psi\rangle\big)+\tfrac12\lvert1\rangle\big(\lvert\psi\phi\rangle-\lvert\phi\psi\rangle\big), and measuring the ancilla gives P(0)=14∥∣ψϕ⟩+∣ϕψ⟩∥2=12(1+∣⟨ψ∣ϕ⟩∣2),P(1)=12(1−∣⟨ψ∣ϕ⟩∣2).P(0)=\tfrac14\big\lVert\lvert\psi\phi\rangle+\lvert\phi\psi\rangle\big\rVert^2=\tfrac12\big(1+\lvert\langle\psi\vert\phi\rangle\rvert^2\big),\qquad P(1)=\tfrac12\big(1-\lvert\langle\psi\vert\phi\rangle\rvert^2\big). In particular 12≤P(0)≤1\frac12\le P(0)\le1, with P(0)=1P(0)=1 if and only if ∣ϕ⟩=eiα∣ψ⟩\lvert\phi\rangle=e^{i\alpha}\lvert\psi\rangle and P(0)=12P(0)=\frac12 if and only if ⟨ψ∣ϕ⟩=0\langle\psi\vert\phi\rangle=0.

Proof (11 steps)
  1. Step 1:
    ∣Ψ0⟩=∣0⟩⊗∣ψ⟩⊗∣ϕ⟩=∣0⟩∣ψϕ⟩\lvert\Psi_0\rangle=\lvert0\rangle\otimes\lvert\psi\rangle\otimes\lvert\phi\rangle=\lvert0\rangle\lvert\psi\phi\rangle
    Initial state: ancilla in ∣0⟩\lvert0\rangle, the two registers loaded with the states to be compared.
  2. Step 2:
    ∣Ψ1⟩=(H⊗I)∣Ψ0⟩=12(∣0⟩+∣1⟩)∣ψϕ⟩=12(∣0⟩∣ψϕ⟩+∣1⟩∣ψϕ⟩)\lvert\Psi_1\rangle=(H\otimes I)\lvert\Psi_0\rangle=\tfrac1{\sqrt2}\big(\lvert0\rangle+\lvert1\rangle\big)\lvert\psi\phi\rangle=\tfrac1{\sqrt2}\big(\lvert0\rangle\lvert\psi\phi\rangle+\lvert1\rangle\lvert\psi\phi\rangle\big)
    H∣0⟩=12(∣0⟩+∣1⟩)H\lvert0\rangle=\frac1{\sqrt2}(\lvert0\rangle+\lvert1\rangle) on the ancilla, identity on the registers, and distributivity of ⊗\otimes.
  3. Step 3:
    SWAP∣ψϕ⟩=∑i,jψiϕj SWAP∣i⟩∣j⟩=∑i,jψiϕj∣j⟩∣i⟩=(∑jϕj∣j⟩)⊗(∑iψi∣i⟩)=∣ϕψ⟩\mathrm{SWAP}\lvert\psi\phi\rangle=\sum_{i,j}\psi_i\phi_j\,\mathrm{SWAP}\lvert i\rangle\lvert j\rangle=\sum_{i,j}\psi_i\phi_j\lvert j\rangle\lvert i\rangle=\Big(\sum_j\phi_j\lvert j\rangle\Big)\otimes\Big(\sum_i\psi_i\lvert i\rangle\Big)=\lvert\phi\psi\rangle
    Expand both states in the computational basis, use the defining action SWAP∣i⟩∣j⟩=∣j⟩∣i⟩\mathrm{SWAP}\lvert i\rangle\lvert j\rangle=\lvert j\rangle\lvert i\rangle and linearity, and refactor the double sum as a product.
  4. Step 4:
    ∣Ψ2⟩=12(∣0⟩∣ψϕ⟩+∣1⟩ SWAP∣ψϕ⟩)=12(∣0⟩∣ψϕ⟩+∣1⟩∣ϕψ⟩)\lvert\Psi_2\rangle=\tfrac1{\sqrt2}\big(\lvert0\rangle\lvert\psi\phi\rangle+\lvert1\rangle\,\mathrm{SWAP}\lvert\psi\phi\rangle\big)=\tfrac1{\sqrt2}\big(\lvert0\rangle\lvert\psi\phi\rangle+\lvert1\rangle\lvert\phi\psi\rangle\big)
    The controlled swap ∣0⟩⟨0∣⊗I+∣1⟩⟨1∣⊗SWAP\lvert0\rangle\langle0\rvert\otimes I+\lvert1\rangle\langle1\rvert\otimes\mathrm{SWAP} leaves the ∣0⟩\lvert0\rangle branch alone and swaps the registers in the ∣1⟩\lvert1\rangle branch.
  5. Step 5:
    ∣Ψ3⟩=12(∣0⟩+∣1⟩)∣ψϕ⟩+12(∣0⟩−∣1⟩)∣ϕψ⟩=12∣0⟩(∣ψϕ⟩+∣ϕψ⟩)+12∣1⟩(∣ψϕ⟩−∣ϕψ⟩)\lvert\Psi_3\rangle=\tfrac12\big(\lvert0\rangle+\lvert1\rangle\big)\lvert\psi\phi\rangle+\tfrac12\big(\lvert0\rangle-\lvert1\rangle\big)\lvert\phi\psi\rangle=\tfrac12\lvert0\rangle\big(\lvert\psi\phi\rangle+\lvert\phi\psi\rangle\big)+\tfrac12\lvert1\rangle\big(\lvert\psi\phi\rangle-\lvert\phi\psi\rangle\big)
    Second Hadamard: H∣0⟩=12(∣0⟩+∣1⟩)H\lvert0\rangle=\frac1{\sqrt2}(\lvert0\rangle+\lvert1\rangle), H∣1⟩=12(∣0⟩−∣1⟩)H\lvert1\rangle=\frac1{\sqrt2}(\lvert0\rangle-\lvert1\rangle); the factors 12⋅12=12\frac1{\sqrt2}\cdot\frac1{\sqrt2}=\frac12; then collect the terms by the ancilla basis state.
  6. Step 6:
    P(0)=∥(⟨0∣⊗I)∣Ψ3⟩∥2=14∥∣ψϕ⟩+∣ϕψ⟩∥2P(0)=\big\lVert(\langle0\rvert\otimes I)\lvert\Psi_3\rangle\big\rVert^2=\tfrac14\big\lVert\lvert\psi\phi\rangle+\lvert\phi\psi\rangle\big\rVert^2
    Born rule for a measurement of the ancilla alone: the probability of outcome 00 is the squared norm of the projection (∣0⟩⟨0∣⊗I)∣Ψ3⟩(\lvert0\rangle\langle0\rvert\otimes I)\lvert\Psi_3\rangle, i.e. of the register vector multiplying ∣0⟩\lvert0\rangle.
  7. Step 7:
    ∥u+v∥2=⟨u∣u⟩+⟨v∣v⟩+⟨u∣v⟩+⟨v∣u⟩=∥u∥2+∥v∥2+2 Re⟨u∣v⟩\lVert u+v\rVert^2=\langle u\vert u\rangle+\langle v\vert v\rangle+\langle u\vert v\rangle+\langle v\vert u\rangle=\lVert u\rVert^2+\lVert v\rVert^2+2\,\mathrm{Re}\langle u\vert v\rangle
    Sesquilinearity of the inner product and ⟨v∣u⟩=⟨u∣v⟩‾\langle v\vert u\rangle=\overline{\langle u\vert v\rangle}, so the two cross terms add up to twice the real part.
  8. Step 8:
    ∥∣ψϕ⟩∥=∥ψ∥ ∥ϕ∥=1,⟨ψϕ∣ϕψ⟩=⟨ψ∣ϕ⟩⟨ϕ∣ψ⟩=⟨ψ∣ϕ⟩⟨ψ∣ϕ⟩‾=∣⟨ψ∣ϕ⟩∣2\lVert\lvert\psi\phi\rangle\rVert=\lVert\psi\rVert\,\lVert\phi\rVert=1,\qquad\langle\psi\phi\vert\phi\psi\rangle=\langle\psi\vert\phi\rangle\langle\phi\vert\psi\rangle=\langle\psi\vert\phi\rangle\overline{\langle\psi\vert\phi\rangle}=\lvert\langle\psi\vert\phi\rangle\rvert^2
    Inner products of product vectors factorise, ⟨a⊗b∣c⊗d⟩=⟨a∣c⟩⟨b∣d⟩\langle a\otimes b\vert c\otimes d\rangle=\langle a\vert c\rangle\langle b\vert d\rangle. The cross term is real and nonnegative, so its real part is itself.
  9. Step 9:
    P(0)=14(1+1+2∣⟨ψ∣ϕ⟩∣2)=12(1+∣⟨ψ∣ϕ⟩∣2)P(0)=\tfrac14\big(1+1+2\lvert\langle\psi\vert\phi\rangle\rvert^2\big)=\tfrac12\big(1+\lvert\langle\psi\vert\phi\rangle\rvert^2\big)
    Insert u=∣ψϕ⟩u=\lvert\psi\phi\rangle, v=∣ϕψ⟩v=\lvert\phi\psi\rangle into the norm expansion: ∥u+v∥2=2+2∣⟨ψ∣ϕ⟩∣2\lVert u+v\rVert^2=2+2\lvert\langle\psi\vert\phi\rangle\rvert^2.
  10. Step 10:
    P(1)=14∥∣ψϕ⟩−∣ϕψ⟩∥2=14(2−2∣⟨ψ∣ϕ⟩∣2)=12(1−∣⟨ψ∣ϕ⟩∣2)P(1)=\tfrac14\big\lVert\lvert\psi\phi\rangle-\lvert\phi\psi\rangle\big\rVert^2=\tfrac14\big(2-2\lvert\langle\psi\vert\phi\rangle\rvert^2\big)=\tfrac12\big(1-\lvert\langle\psi\vert\phi\rangle\rvert^2\big)
    The same computation with v↦−vv\mapsto-v flips the sign of the cross term. As a check, P(0)+P(1)=1P(0)+P(1)=1.
  11. Step 11:
    0≤∣⟨ψ∣ϕ⟩∣2≤1 ⇒ 12≤P(0)≤10\le\lvert\langle\psi\vert\phi\rangle\rvert^2\le1\ \Rightarrow\ \tfrac12\le P(0)\le1
    Cauchy–Schwarz for unit vectors, with equality ∣⟨ψ∣ϕ⟩∣=1\lvert\langle\psi\vert\phi\rangle\rvert=1 exactly when ∣ϕ⟩=eiα∣ψ⟩\lvert\phi\rangle=e^{i\alpha}\lvert\psi\rangle; the lower end is reached exactly for orthogonal states. Since P(0)≥12P(0)\ge\frac12, a single shot can never certify that two states differ.

∎

Corollary

The SWAP test measures the projector onto the symmetric subspace

For any state ∣χ⟩\lvert\chi\rangle of the two registers (entangled or not), the SWAP test accepts with probability P(0)=⟨χ∣Πsym∣χ⟩,Πsym=12(I+SWAP),P(0)=\langle\chi\vert\Pi_{\mathrm{sym}}\vert\chi\rangle,\qquad\Pi_{\mathrm{sym}}=\tfrac12\big(I+\mathrm{SWAP}\big), where Πsym\Pi_{\mathrm{sym}} is the orthogonal projector onto the symmetric subspace {∣v⟩:SWAP∣v⟩=∣v⟩}\{\lvert v\rangle:\mathrm{SWAP}\lvert v\rangle=\lvert v\rangle\}. Likewise P(1)=⟨χ∣Πanti∣χ⟩P(1)=\langle\chi\vert\Pi_{\mathrm{anti}}\vert\chi\rangle with Πanti=12(I−SWAP)\Pi_{\mathrm{anti}}=\frac12(I-\mathrm{SWAP}).

Proof (6 steps)
  1. Step 1:
    ∣0⟩∣χ⟩ →H0 12(∣0⟩+∣1⟩)∣χ⟩ →C-SWAP 12(∣0⟩∣χ⟩+∣1⟩ SWAP∣χ⟩)\lvert0\rangle\lvert\chi\rangle\ \xrightarrow{H_0}\ \tfrac1{\sqrt2}\big(\lvert0\rangle+\lvert1\rangle\big)\lvert\chi\rangle\ \xrightarrow{\text{C-SWAP}}\ \tfrac1{\sqrt2}\big(\lvert0\rangle\lvert\chi\rangle+\lvert1\rangle\,\mathrm{SWAP}\lvert\chi\rangle\big)
    The first two layers of the theorem, with ∣ψϕ⟩\lvert\psi\phi\rangle replaced by an arbitrary register state.
  2. Step 2:
    →H0 ∣0⟩ 12(I+SWAP)∣χ⟩+∣1⟩ 12(I−SWAP)∣χ⟩=∣0⟩ Πsym∣χ⟩+∣1⟩ Πanti∣χ⟩\xrightarrow{H_0}\ \lvert0\rangle\,\tfrac12\big(I+\mathrm{SWAP}\big)\lvert\chi\rangle+\lvert1\rangle\,\tfrac12\big(I-\mathrm{SWAP}\big)\lvert\chi\rangle=\lvert0\rangle\,\Pi_{\mathrm{sym}}\lvert\chi\rangle+\lvert1\rangle\,\Pi_{\mathrm{anti}}\lvert\chi\rangle
    The final Hadamard, collecting the terms by ancilla value as before.
  3. Step 3:
    SWAP†=SWAP,SWAP2=I\mathrm{SWAP}^\dagger=\mathrm{SWAP},\qquad\mathrm{SWAP}^2=I
    SWAP\mathrm{SWAP} is a permutation matrix of the basis ∣i⟩∣j⟩\lvert i\rangle\lvert j\rangle whose permutation (i,j)↦(j,i)(i,j)\mapsto(j,i) is its own inverse; as for the Fredkin gate, such a matrix is real, symmetric and squares to the identity.
  4. Step 4:
    Πsym†=Πsym,Πsym2=14(I+2 SWAP+SWAP2)=14(2I+2 SWAP)=Πsym\Pi_{\mathrm{sym}}^\dagger=\Pi_{\mathrm{sym}},\qquad\Pi_{\mathrm{sym}}^2=\tfrac14\big(I+2\,\mathrm{SWAP}+\mathrm{SWAP}^2\big)=\tfrac14\big(2I+2\,\mathrm{SWAP}\big)=\Pi_{\mathrm{sym}}
    Hermitian and idempotent: an orthogonal projector. Its range consists of the vectors with SWAP∣v⟩=∣v⟩\mathrm{SWAP}\lvert v\rangle=\lvert v\rangle, because Πsym∣v⟩=∣v⟩  ⟺  SWAP∣v⟩=∣v⟩\Pi_{\mathrm{sym}}\lvert v\rangle=\lvert v\rangle\iff\mathrm{SWAP}\lvert v\rangle=\lvert v\rangle. The same algebra applies to Πanti\Pi_{\mathrm{anti}}, and Πsym+Πanti=I\Pi_{\mathrm{sym}}+\Pi_{\mathrm{anti}}=I.
  5. Step 5:
    P(0)=∥Πsym∣χ⟩∥2=⟨χ∣Πsym†Πsym∣χ⟩=⟨χ∣Πsym∣χ⟩P(0)=\big\lVert\Pi_{\mathrm{sym}}\lvert\chi\rangle\big\rVert^2=\langle\chi\vert\Pi_{\mathrm{sym}}^\dagger\Pi_{\mathrm{sym}}\vert\chi\rangle=\langle\chi\vert\Pi_{\mathrm{sym}}\vert\chi\rangle
    Born rule on the ancilla, then Π†Π=Π2=Π\Pi^\dagger\Pi=\Pi^2=\Pi.
  6. Step 6:
    ∣χ⟩=∣ψϕ⟩:⟨ψϕ∣Πsym∣ψϕ⟩=12(1+⟨ψϕ∣ϕψ⟩)=12(1+∣⟨ψ∣ϕ⟩∣2)\lvert\chi\rangle=\lvert\psi\phi\rangle:\quad\langle\psi\phi\vert\Pi_{\mathrm{sym}}\vert\psi\phi\rangle=\tfrac12\big(1+\langle\psi\phi\vert\phi\psi\rangle\big)=\tfrac12\big(1+\lvert\langle\psi\vert\phi\rangle\rvert^2\big)
    For a product input the corollary reproduces the theorem. The formula is linear in the projector ∣χ⟩⟨χ∣\lvert\chi\rangle\langle\chi\rvert, which is what makes the extension to mixed states immediate.

∎

The sampler shows the two one-qubit states on Bloch spheres, ∣ψ⟩=cos⁡θ2∣0⟩+eiφsin⁡θ2∣1⟩\lvert\psi\rangle=\cos\frac\theta2\lvert0\rangle+e^{i\varphi}\sin\frac\theta2\lvert1\rangle, and simulates the SWAP test shot by shot. Its starting configuration is the lab pair θA=π3\theta_A=\frac\pi3 against ∣0⟩\lvert0\rangle: the exact value is P(0)=12(1+cos⁡2π6)=78P(0)=\frac12\big(1+\cos^2\frac\pi6\big)=\frac78, and the sampled frequency fluctuates around it with standard deviation P(0)(1−P(0))/N\sqrt{P(0)(1-P(0))/N}. Rotate either state and observe that only the angle between the two Bloch vectors matters: for one qubit ∣⟨ψ∣ϕ⟩∣2=12(1+r⃗⋅r⃗ ′)\lvert\langle\psi\vert\phi\rangle\rvert^2=\frac12(1+\vec r\cdot\vec r\,'), so P(0)=34+14 r⃗⋅r⃗ ′P(0)=\frac34+\frac14\,\vec r\cdot\vec r\,'.

Quick check

The SWAP test is run on ∣ψ⟩=∣+⟩=12(∣0⟩+∣1⟩)\lvert\psi\rangle=\lvert+\rangle=\frac1{\sqrt2}(\lvert0\rangle+\lvert1\rangle) and ∣ϕ⟩=∣0⟩\lvert\phi\rangle=\lvert0\rangle. What is P(0)P(0)?

tolerance ±0.000001

Registers of n qubits#

For kernels the states live on nn qubits. Place the ancilla on qubit 00, the register AA holding ∣ψ⟩\lvert\psi\rangle on qubits 1,…,n1,\dots,n and the register BB holding ∣ϕ⟩\lvert\phi\rangle on qubits n+1,…,2nn+1,\dots,2n (this is the layout of the platform function swapTestCircuit\mathtt{swapTestCircuit}). Pair the ii-th qubit of AA, ai=1+ia_i=1+i, with the ii-th qubit of BB, bi=1+n+ib_i=1+n+i, for i=0,…,n−1i=0,\dots,n-1. Two lemmas reduce the controlled register swap to nn Fredkin gates.

Lemma

A register swap is a product of qubit swaps

SWAPA,B∣x⟩A∣y⟩B=∣y⟩A∣x⟩B\mathrm{SWAP}_{A,B}\lvert x\rangle_A\lvert y\rangle_B=\lvert y\rangle_A\lvert x\rangle_B for all x,y∈{0,1}nx,y\in\{0,1\}^n, where SWAPA,B=∏i=0n−1SWAPai,bi\mathrm{SWAP}_{A,B}=\prod_{i=0}^{n-1}\mathrm{SWAP}_{a_i,b_i} and the factors commute. Hence SWAPA,B∣ψ⟩∣ϕ⟩=∣ϕ⟩∣ψ⟩\mathrm{SWAP}_{A,B}\lvert\psi\rangle\lvert\phi\rangle=\lvert\phi\rangle\lvert\psi\rangle for all nn-qubit states.

Proof (4 steps)
  1. Step 1:
    SWAPai,bi ∣x0⋯xi⋯xn−1⟩A∣y0⋯yi⋯yn−1⟩B=∣x0⋯yi⋯xn−1⟩A∣y0⋯xi⋯yn−1⟩B\mathrm{SWAP}_{a_i,b_i}\,\lvert x_0\cdots x_i\cdots x_{n-1}\rangle_A\lvert y_0\cdots y_i\cdots y_{n-1}\rangle_B=\lvert x_0\cdots y_i\cdots x_{n-1}\rangle_A\lvert y_0\cdots x_i\cdots y_{n-1}\rangle_B
    A qubit swap exchanges the bits on its two wires and leaves every other wire unchanged.
  2. Step 2:
    SWAPai,biSWAPaj,bj=SWAPaj,bjSWAPai,bi(i≠j)\mathrm{SWAP}_{a_i,b_i}\mathrm{SWAP}_{a_j,b_j}=\mathrm{SWAP}_{a_j,b_j}\mathrm{SWAP}_{a_i,b_i}\qquad(i\ne j)
    Operators acting on disjoint sets of qubits commute ((P⊗I)(I⊗Q)=P⊗Q=(I⊗Q)(P⊗I)(P\otimes I)(I\otimes Q)=P\otimes Q=(I\otimes Q)(P\otimes I) after reordering the wires), so the product does not depend on the order.
  3. Step 3:
    ∏i=0n−1SWAPai,bi ∣x⟩A∣y⟩B=∣y0⋯yn−1⟩A∣x0⋯xn−1⟩B=∣y⟩A∣x⟩B\prod_{i=0}^{n-1}\mathrm{SWAP}_{a_i,b_i}\,\lvert x\rangle_A\lvert y\rangle_B=\lvert y_0\cdots y_{n-1}\rangle_A\lvert x_0\cdots x_{n-1}\rangle_B=\lvert y\rangle_A\lvert x\rangle_B
    Each factor exchanges one bit position, and every position is exchanged exactly once.
  4. Step 4:
    SWAPA,B∣ψ⟩∣ϕ⟩=∑x,yψxϕy∣y⟩∣x⟩=∣ϕ⟩∣ψ⟩\mathrm{SWAP}_{A,B}\lvert\psi\rangle\lvert\phi\rangle=\sum_{x,y}\psi_x\phi_y\lvert y\rangle\lvert x\rangle=\lvert\phi\rangle\lvert\psi\rangle
    Linearity, exactly as in the one-qubit computation of the acceptance theorem.

∎

Lemma

Controlled products are products of controlled gates

For unitaries U1,…,UnU_1,\dots,U_n on the target qubits and a common control qubit, with C(U)=∣0⟩⟨0∣⊗I+∣1⟩⟨1∣⊗UC(U)=\lvert0\rangle\langle0\rvert\otimes I+\lvert1\rangle\langle1\rvert\otimes U, C(Un⋯U1)=C(Un)⋯C(U1).C(U_n\cdots U_1)=C(U_n)\cdots C(U_1). In particular the controlled register swap is the product of the nn Fredkin gates CSWAP0;ai,bi\mathrm{CSWAP}_{0;a_i,b_i}, which share the ancilla as control.

Proof (4 steps)
  1. Step 1:
    P0=∣0⟩⟨0∣, P1=∣1⟩⟨1∣:P02=P0,P12=P1,P0P1=P1P0=0P_0=\lvert0\rangle\langle0\rvert,\ P_1=\lvert1\rangle\langle1\rvert:\qquad P_0^2=P_0,\quad P_1^2=P_1,\quad P_0P_1=P_1P_0=0
    The two computational-basis projectors of the control are orthogonal idempotents.
  2. Step 2:
    C(U) C(V)=P02⊗I+P0P1⊗V+P1P0⊗U+P12⊗UV=P0⊗I+P1⊗UV=C(UV)C(U)\,C(V)=P_0^2\otimes I+P_0P_1\otimes V+P_1P_0\otimes U+P_1^2\otimes UV=P_0\otimes I+P_1\otimes UV=C(UV)
    Multiply out with the mixed-product rule (A⊗B)(C⊗D)=AC⊗BD(A\otimes B)(C\otimes D)=AC\otimes BD; the cross terms vanish.
  3. Step 3:
    C(Un⋯U1)=C(Un) C(Un−1⋯U1)=⋯=C(Un)⋯C(U1)C(U_n\cdots U_1)=C(U_n)\,C(U_{n-1}\cdots U_1)=\cdots=C(U_n)\cdots C(U_1)
    Induction on nn using the two-factor identity.
  4. Step 4:
    C(SWAPA,B)=C(∏iSWAPai,bi)=∏i=0n−1C(SWAPai,bi)=∏i=0n−1CSWAP0;ai,biC\big(\mathrm{SWAP}_{A,B}\big)=C\Big(\prod_i\mathrm{SWAP}_{a_i,b_i}\Big)=\prod_{i=0}^{n-1}C\big(\mathrm{SWAP}_{a_i,b_i}\big)=\prod_{i=0}^{n-1}\mathrm{CSWAP}_{0;a_i,b_i}
    Apply the lemma to the factorisation of the register swap; a controlled qubit swap is by definition a Fredkin gate.

∎

Corollary

The SWAP test for n-qubit states

The circuit H(0); CSWAP(0,1,n+1); CSWAP(0,2,n+2); … ; CSWAP(0,n,2n); H(0)H(0);\ \mathrm{CSWAP}(0,1,n+1);\ \mathrm{CSWAP}(0,2,n+2);\ \dots;\ \mathrm{CSWAP}(0,n,2n);\ H(0) on 2n+12n+1 qubits, applied to ∣0⟩∣ψ⟩∣ϕ⟩\lvert0\rangle\lvert\psi\rangle\lvert\phi\rangle, accepts with probability P(0)=12(1+∣⟨ψ∣ϕ⟩∣2)P(0)=\frac12\big(1+\lvert\langle\psi\vert\phi\rangle\rvert^2\big). It uses 2n+12n+1 qubits, 22 Hadamards and nn Fredkin gates, and one copy of each state per shot.

Proof (4 steps)
  1. Step 1:
    ∏i=0n−1CSWAP0;1+i,1+n+i=∣0⟩⟨0∣⊗I+∣1⟩⟨1∣⊗SWAPA,B\prod_{i=0}^{n-1}\mathrm{CSWAP}_{0;1+i,1+n+i}=\lvert0\rangle\langle0\rvert\otimes I+\lvert1\rangle\langle1\rvert\otimes\mathrm{SWAP}_{A,B}
    The controlled-product lemma applied to the register-swap factorisation.
  2. Step 2:
    SWAPA,B∣ψ⟩∣ϕ⟩=∣ϕ⟩∣ψ⟩\mathrm{SWAP}_{A,B}\lvert\psi\rangle\lvert\phi\rangle=\lvert\phi\rangle\lvert\psi\rangle
    The factorisation lemma; this is the only property of the swap used in the acceptance theorem.
  3. Step 3:
    P(0)=12(1+∣⟨ψ∣ϕ⟩∣2)P(0)=\tfrac12\big(1+\lvert\langle\psi\vert\phi\rangle\rvert^2\big)
    The acceptance theorem with d=2nd=2^n.
  4. Step 4:
    #qubits=1+n+n=2n+1,#CSWAP=n,#H=2\#\text{qubits}=1+n+n=2n+1,\qquad\#\mathrm{CSWAP}=n,\qquad\#H=2
    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 nn in Fredkin gates.

∎

Quick check

How many qubits does the SWAP test need to estimate the fidelity kernel of a feature map on n=4n=4 qubits?

tolerance ±0.5

Mixed states and the SWAP trick#

Lemma

The SWAP trick

For all A,B∈Cd×dA,B\in\mathbb C^{d\times d}, Tr[SWAP (A⊗B)]=Tr(AB).\mathrm{Tr}\big[\mathrm{SWAP}\,(A\otimes B)\big]=\mathrm{Tr}(AB). In particular Tr[SWAP(ρ⊗σ)]=Tr(ρσ)\mathrm{Tr}\big[\mathrm{SWAP}(\rho\otimes\sigma)\big]=\mathrm{Tr}(\rho\sigma) for density operators, and Tr[SWAP(ρ⊗ρ)]=Tr(ρ2)\mathrm{Tr}\big[\mathrm{SWAP}(\rho\otimes\rho)\big]=\mathrm{Tr}(\rho^2) is the purity.

Proof (6 steps)
  1. Step 1:
    SWAP=∑i,j=0d−1∣j i⟩⟨i j∣ ⇒ ⟨k l∣SWAP∣i j⟩=⟨k l∣j i⟩=δkj δli\mathrm{SWAP}=\sum_{i,j=0}^{d-1}\lvert j\,i\rangle\langle i\,j\rvert\ \Rightarrow\ \langle k\,l\vert\mathrm{SWAP}\vert i\,j\rangle=\langle k\,l\vert j\,i\rangle=\delta_{kj}\,\delta_{li}
    The swap maps the basis vector ∣i j⟩=∣i⟩⊗∣j⟩\lvert i\,j\rangle=\lvert i\rangle\otimes\lvert j\rangle to ∣j i⟩\lvert j\,i\rangle; its matrix elements are products of Kronecker deltas.
  2. Step 2:
    ⟨i j∣A⊗B∣k l⟩=⟨i∣A∣k⟩⟨j∣B∣l⟩=Aik Bjl\langle i\,j\vert A\otimes B\vert k\,l\rangle=\langle i\vert A\vert k\rangle\langle j\vert B\vert l\rangle=A_{ik}\,B_{jl}
    Matrix elements of a Kronecker product between product basis vectors factorise.
  3. Step 3:
    Tr[SWAP(A⊗B)]=∑i,j⟨i j∣SWAP(A⊗B)∣i j⟩=∑i,j∑k,l⟨i j∣SWAP∣k l⟩ ⟨k l∣A⊗B∣i j⟩\mathrm{Tr}\big[\mathrm{SWAP}(A\otimes B)\big]=\sum_{i,j}\langle i\,j\vert\mathrm{SWAP}(A\otimes B)\vert i\,j\rangle=\sum_{i,j}\sum_{k,l}\langle i\,j\vert\mathrm{SWAP}\vert k\,l\rangle\,\langle k\,l\vert A\otimes B\vert i\,j\rangle
    The trace is the sum of the diagonal elements in the product basis; insert the resolution of the identity ∑k,l∣k l⟩⟨k l∣=I\sum_{k,l}\lvert k\,l\rangle\langle k\,l\rvert=I between the two factors.
  4. Step 4:
    =∑i,j,k,lδil δjk Aki Blj=\sum_{i,j,k,l}\delta_{il}\,\delta_{jk}\,A_{ki}\,B_{lj}
    Insert the two matrix-element formulas: ⟨i j∣SWAP∣k l⟩=δilδjk\langle i\,j\vert\mathrm{SWAP}\vert k\,l\rangle=\delta_{il}\delta_{jk} (the first line with the indices renamed) and ⟨k l∣A⊗B∣i j⟩=AkiBlj\langle k\,l\vert A\otimes B\vert i\,j\rangle=A_{ki}B_{lj}.
  5. Step 5:
    =∑i,jAji Bij=∑i(∑jBijAji)=∑i(BA)ii=Tr(BA)=Tr(AB)=\sum_{i,j}A_{ji}\,B_{ij}=\sum_i\Big(\sum_jB_{ij}A_{ji}\Big)=\sum_i(BA)_{ii}=\mathrm{Tr}(BA)=\mathrm{Tr}(AB)
    The deltas set k=jk=j and l=il=i; the inner sum is the matrix product BABA; finally cyclicity of the trace.
  6. Step 6:
    A=ρ, B=σ: Tr[SWAP(ρ⊗σ)]=Tr(ρσ);A=B=ρ: Tr[SWAP(ρ⊗ρ)]=Tr(ρ2)A=\rho,\ B=\sigma:\ \mathrm{Tr}\big[\mathrm{SWAP}(\rho\otimes\sigma)\big]=\mathrm{Tr}(\rho\sigma);\qquad A=B=\rho:\ \mathrm{Tr}\big[\mathrm{SWAP}(\rho\otimes\rho)\big]=\mathrm{Tr}(\rho^2)
    The two special cases used below. A quadratic function of ρ\rho becomes a linear function of the two-copy state ρ⊗ρ\rho\otimes\rho: this is the general mechanism behind estimating nonlinear functionals of quantum states (Ekert et al. 2002).

∎

Theorem

The SWAP test on mixed states

If the registers hold independent mixed states ρ\rho and σ\sigma (joint input ρ⊗σ\rho\otimes\sigma), the SWAP test accepts with probability P(0)=12(1+Tr(ρσ)),P(1)=12(1−Tr(ρσ)),P(0)=\tfrac12\big(1+\mathrm{Tr}(\rho\sigma)\big),\qquad P(1)=\tfrac12\big(1-\mathrm{Tr}(\rho\sigma)\big), and 0≤Tr(ρσ)≤10\le\mathrm{Tr}(\rho\sigma)\le1. For pure states Tr(ρσ)=∣⟨ψ∣ϕ⟩∣2\mathrm{Tr}(\rho\sigma)=\lvert\langle\psi\vert\phi\rangle\rvert^2, and for two copies of the same state P(0)=12(1+Tr ρ2)P(0)=\frac12\big(1+\mathrm{Tr}\,\rho^2\big).

Proof (6 steps)
  1. Step 1:
    P(0)=Tr[(∣0⟩⟨0∣⊗I) V(∣0⟩⟨0∣⊗ω)V†],V=H0 C(SWAP) H0P(0)=\mathrm{Tr}\Big[\big(\lvert0\rangle\langle0\rvert\otimes I\big)\,V\big(\lvert0\rangle\langle0\rvert\otimes\omega\big)V^\dagger\Big],\qquad V=H_0\,C(\mathrm{SWAP})\,H_0
    Born rule for a density operator: the circuit maps the input ∣0⟩⟨0∣⊗ω\lvert0\rangle\langle0\rvert\otimes\omega to V(⋅)V†V(\cdot)V^\dagger, and the outcome probability is the trace with the measurement projector. This expression is linear in the register state ω\omega.
  2. Step 2:
    ω=∣χ⟩⟨χ∣:P(0)=⟨χ∣Πsym∣χ⟩=Tr(Πsym ∣χ⟩⟨χ∣)\omega=\lvert\chi\rangle\langle\chi\rvert:\quad P(0)=\langle\chi\vert\Pi_{\mathrm{sym}}\vert\chi\rangle=\mathrm{Tr}\big(\Pi_{\mathrm{sym}}\,\lvert\chi\rangle\langle\chi\rvert\big)
    For a pure register state this is the symmetric-projector corollary, rewritten with ⟨χ∣M∣χ⟩=Tr(M∣χ⟩⟨χ∣)\langle\chi\vert M\vert\chi\rangle=\mathrm{Tr}(M\lvert\chi\rangle\langle\chi\rvert) (cyclicity).
  3. Step 3:
    ω=∑mqm∣χm⟩⟨χm∣ ⇒ P(0)=∑mqm Tr(Πsym∣χm⟩⟨χm∣)=Tr(Πsym ω)\omega=\sum_mq_m\lvert\chi_m\rangle\langle\chi_m\rvert\ \Rightarrow\ P(0)=\sum_mq_m\,\mathrm{Tr}\big(\Pi_{\mathrm{sym}}\lvert\chi_m\rangle\langle\chi_m\rvert\big)=\mathrm{Tr}\big(\Pi_{\mathrm{sym}}\,\omega\big)
    Every density operator has a spectral decomposition with qm≥0q_m\ge0, ∑mqm=1\sum_mq_m=1; linearity of the first line in ω\omega carries the pure-state formula over to every mixed register state.
  4. Step 4:
    ω=ρ⊗σ:P(0)=12 Tr(ρ⊗σ)+12 Tr[SWAP(ρ⊗σ)]=12 Trρ Trσ+12 Tr(ρσ)=12(1+Tr(ρσ))\omega=\rho\otimes\sigma:\quad P(0)=\tfrac12\,\mathrm{Tr}(\rho\otimes\sigma)+\tfrac12\,\mathrm{Tr}\big[\mathrm{SWAP}(\rho\otimes\sigma)\big]=\tfrac12\,\mathrm{Tr}\rho\,\mathrm{Tr}\sigma+\tfrac12\,\mathrm{Tr}(\rho\sigma)=\tfrac12\big(1+\mathrm{Tr}(\rho\sigma)\big)
    Insert Πsym=12(I+SWAP)\Pi_{\mathrm{sym}}=\frac12(I+\mathrm{SWAP}), use Tr(A⊗B)=TrA TrB\mathrm{Tr}(A\otimes B)=\mathrm{Tr}A\,\mathrm{Tr}B, the SWAP trick, and unit traces. P(1)=1−P(0)P(1)=1-P(0).
  5. Step 5:
    ρ=∑kpk∣ek⟩⟨ek∣:Tr(ρσ)=∑kpk⟨ek∣σ∣ek⟩∈[0,1]\rho=\sum_kp_k\lvert e_k\rangle\langle e_k\rvert:\quad\mathrm{Tr}(\rho\sigma)=\sum_kp_k\langle e_k\vert\sigma\vert e_k\rangle\in[0,1]
    Spectral decomposition of ρ\rho and linearity of the trace. Each ⟨ek∣σ∣ek⟩\langle e_k\vert\sigma\vert e_k\rangle lies in [0,1][0,1] because σ\sigma is positive semidefinite with eigenvalues in [0,1][0,1], and the weights pk≥0p_k\ge0 sum to 11.
  6. Step 6:
    ρ=∣ψ⟩⟨ψ∣, σ=∣ϕ⟩⟨ϕ∣:Tr(ρσ)=⟨ψ∣ϕ⟩⟨ϕ∣ψ⟩=∣⟨ψ∣ϕ⟩∣2;σ=ρ: P(0)=12(1+Tr ρ2)\rho=\lvert\psi\rangle\langle\psi\rvert,\ \sigma=\lvert\phi\rangle\langle\phi\rvert:\quad\mathrm{Tr}(\rho\sigma)=\langle\psi\vert\phi\rangle\langle\phi\vert\psi\rangle=\lvert\langle\psi\vert\phi\rangle\rvert^2;\qquad\sigma=\rho:\ P(0)=\tfrac12\big(1+\mathrm{Tr}\,\rho^2\big)
    The pure-state theorem is recovered, and two copies of one state reveal its purity, which equals 11 exactly for pure states.

∎

Derivation

Example: purity of a qubit and a mixed pair

  1. Step 1:
    ρ=12(I+r⃗⋅σ⃗) ⇒ Tr ρ2=12(1+∣r⃗∣2)\rho=\tfrac12\big(I+\vec r\cdot\vec\sigma\big)\ \Rightarrow\ \mathrm{Tr}\,\rho^2=\tfrac12\big(1+\lvert\vec r\rvert^2\big)
    The Bloch formula Tr(ρρ′)=12(1+r⃗⋅r⃗ ′)\mathrm{Tr}(\rho\rho')=\frac12(1+\vec r\cdot\vec r\,') of the previous lesson with ρ′=ρ\rho'=\rho.
  2. Step 2:
    r⃗=(0,0,0.6):Tr ρ2=12(1+0.36)=0.68,P(0)=12(1+0.68)=0.84\vec r=(0,0,0.6):\quad\mathrm{Tr}\,\rho^2=\tfrac12(1+0.36)=0.68,\qquad P(0)=\tfrac12(1+0.68)=0.84
    A qubit with ρ=diag(0.8,0.2)\rho=\mathrm{diag}(0.8,0.2); two copies of it pass the SWAP test with probability 0.840.84.
  3. Step 3:
    ρ=(0.70.2−0.1i0.2+0.1i0.3),  σ=(0.40.1i−0.1i0.6)\rho=\begin{pmatrix}0.7&0.2-0.1i\\0.2+0.1i&0.3\end{pmatrix},\ \ \sigma=\begin{pmatrix}0.4&0.1i\\-0.1i&0.6\end{pmatrix}
    Two valid mixed states: Hermitian, trace 11, and determinants 0.21−0.05=0.16>00.21-0.05=0.16>0 and 0.24−0.01=0.23>00.24-0.01=0.23>0, so both eigenvalues are positive.
  4. Step 4:
    Tr(ρσ)=∑i,jρijσji=0.7⋅0.4+(0.2−0.1i)(−0.1i)+(0.2+0.1i)(0.1i)+0.3⋅0.6\mathrm{Tr}(\rho\sigma)=\sum_{i,j}\rho_{ij}\sigma_{ji}=0.7\cdot0.4+(0.2-0.1i)(-0.1i)+(0.2+0.1i)(0.1i)+0.3\cdot0.6
    Tr(ρσ)=∑ijρijσji\mathrm{Tr}(\rho\sigma)=\sum_{ij}\rho_{ij}\sigma_{ji}, the formula of the SWAP trick.
  5. Step 5:
    =0.28+(−0.01−0.02i)+(−0.01+0.02i)+0.18=0.44,P(0)=12(1+0.44)=0.72=0.28+(-0.01-0.02i)+(-0.01+0.02i)+0.18=0.44,\qquad P(0)=\tfrac12(1+0.44)=0.72
    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 0.440.44 from Tr[SWAP(ρ⊗σ)]\mathrm{Tr}[\mathrm{SWAP}(\rho\otimes\sigma)] and P(0)=0.72P(0)=0.72 from the full three-qubit density-matrix simulation.

Result

P(0)=12(1+Tr(ρσ))=0.72for the pair above,P(0)=12(1+Tr ρ2)=0.84for two copies of diag(0.8,0.2)\boxed{P(0)=\tfrac12\big(1+\mathrm{Tr}(\rho\sigma)\big)=0.72\quad\text{for the pair above},\qquad P(0)=\tfrac12\big(1+\mathrm{Tr}\,\rho^2\big)=0.84\quad\text{for two copies of }\mathrm{diag}(0.8,0.2)}

Quick check

Both registers of a one-qubit SWAP test hold the maximally mixed state ρ=σ=12I\rho=\sigma=\frac12I. What is P(0)P(0)?

tolerance ±0.000001

From shots to an estimate#

Theorem

The SWAP-test fidelity estimator

Run the SWAP test NN times on fresh copies and let N0N_0 be the number of ancilla outcomes 00; set P^(0)=N0/N\hat P(0)=N_0/N and F^=2P^(0)−1\hat F=2\hat P(0)-1. Then E[F^]=F,Var[F^]=4P0(1−P0)N=1−F2N≤1N,\mathbb E[\hat F]=F,\qquad\mathrm{Var}[\hat F]=\frac{4P_0(1-P_0)}N=\frac{1-F^2}N\le\frac1N, where P0=12(1+F)P_0=\frac12(1+F) and F=∣⟨ψ∣ϕ⟩∣2F=\lvert\langle\psi\vert\phi\rangle\rvert^2 (or Tr ρσ\mathrm{Tr}\,\rho\sigma). The variance is largest, 1/N1/N, for orthogonal states and vanishes only for identical states.

Proof (6 steps)
  1. Step 1:
    Bs=1{shot s returns 0},P(Bs=1)=P0,N0=∑s=1NBsB_s=\mathbf 1\{\text{shot }s\text{ returns }0\},\quad P(B_s=1)=P_0,\quad N_0=\sum_{s=1}^NB_s
    Each shot uses fresh copies and a fresh ancilla, so the indicators are independent Bernoulli variables with success probability P0P_0.
  2. Step 2:
    E[P^(0)]=1N∑sE[Bs]=P0,Var[P^(0)]=1N2∑sVar[Bs]=P0(1−P0)N\mathbb E[\hat P(0)]=\frac1N\sum_s\mathbb E[B_s]=P_0,\qquad\mathrm{Var}[\hat P(0)]=\frac1{N^2}\sum_s\mathrm{Var}[B_s]=\frac{P_0(1-P_0)}N
    Linearity of expectation; variances of independent variables add; Var[Bs]=E[Bs2]−E[Bs]2=P0−P02\mathrm{Var}[B_s]=\mathbb E[B_s^2]-\mathbb E[B_s]^2=P_0-P_0^2.
  3. Step 3:
    E[F^]=2 E[P^(0)]−1=2P0−1=(1+F)−1=F\mathbb E[\hat F]=2\,\mathbb E[\hat P(0)]-1=2P_0-1=(1+F)-1=F
    The estimator is an affine function of P^(0)\hat P(0); insert P0=12(1+F)P_0=\frac12(1+F) from the acceptance theorem. It is unbiased.
  4. Step 4:
    Var[F^]=Var[2P^(0)−1]=4 Var[P^(0)]=4P0(1−P0)N\mathrm{Var}[\hat F]=\mathrm{Var}[2\hat P(0)-1]=4\,\mathrm{Var}[\hat P(0)]=\frac{4P_0(1-P_0)}N
    Var[aX+b]=a2Var[X]\mathrm{Var}[aX+b]=a^2\mathrm{Var}[X].
  5. Step 5:
    4P0(1−P0)=4⋅1+F2⋅1−F2=(1+F)(1−F)=1−F24P_0(1-P_0)=4\cdot\frac{1+F}2\cdot\frac{1-F}2=(1+F)(1-F)=1-F^2
    1−P0=12(1−F)1-P_0=\frac12(1-F), and the difference of squares.
  6. Step 6:
    F∈[0,1] ⇒ 0≤1−F2≤1,Var[F^]=0  ⟺  F=1F\in[0,1]\ \Rightarrow\ 0\le1-F^2\le1,\qquad\mathrm{Var}[\hat F]=0\iff F=1
    The worst case is F=0F=0, where P0=12P_0=\frac12 is a fair coin. A single estimate may fall outside [0,1][0,1]: for FF near 00 the event N0<N/2N_0<N/2 has probability close to 12\frac12 and gives F^<0\hat F<0. Clamping to [0,1][0,1], as the library routine swapTestEstimate\mathtt{swapTestEstimate} does, keeps the value in range but introduces a bias near the ends.

∎

Lemma

Hoeffding’s inequality for Bernoulli averages

Let B1,…,BNB_1,\dots,B_N be independent Bernoulli variables with P(Bs=1)=pP(B_s=1)=p and Bˉ=1N∑sBs\bar B=\frac1N\sum_sB_s. For every t>0t>0, P(Bˉ−p≥t)≤e−2Nt2,P(∣Bˉ−p∣≥t)≤2e−2Nt2.P\big(\bar B-p\ge t\big)\le e^{-2Nt^2},\qquad P\big(\lvert\bar B-p\rvert\ge t\big)\le2e^{-2Nt^2}.

Proof (7 steps)
  1. Step 1:
    E[esB]=(1−p)e0+p es=1−p+p es,L(s)=ln⁡E[es(B−p)]=−sp+ln⁡(1−p+pes)\mathbb E\big[e^{sB}\big]=(1-p)e^{0}+p\,e^{s}=1-p+p\,e^{s},\qquad L(s)=\ln\mathbb E\big[e^{s(B-p)}\big]=-sp+\ln\big(1-p+pe^s\big)
    Moment generating function of one Bernoulli variable, and the logarithm of the centred one.
  2. Step 2:
    L(0)=0,L′(s)=−p+pes1−p+pes=−p+q(s),L′(0)=0L(0)=0,\qquad L'(s)=-p+\frac{pe^s}{1-p+pe^s}=-p+q(s),\qquad L'(0)=0
    Differentiate; q(s)=pes1−p+pes∈[0,1]q(s)=\frac{pe^s}{1-p+pe^s}\in[0,1], and q(0)=pq(0)=p.
  3. Step 3:
    L′′(s)=q′(s)=pes(1−p+pes)−pes⋅pes(1−p+pes)2=q(s)(1−q(s))≤14L''(s)=q'(s)=\frac{pe^s(1-p+pe^s)-pe^s\cdot pe^s}{(1-p+pe^s)^2}=q(s)\big(1-q(s)\big)\le\tfrac14
    Quotient rule; the numerator is pes(1−p)pe^s(1-p), so q′=q(1−q)q'=q(1-q), which is at most 14\frac14 because u(1−u)=14−(u−12)2u(1-u)=\frac14-(u-\frac12)^2.
  4. Step 4:
    L(s)=L(0)+sL′(0)+s22L′′(ξ)≤s28(some ξ between 0 and s)L(s)=L(0)+sL'(0)+\tfrac{s^2}2L''(\xi)\le\frac{s^2}8\qquad(\text{some }\xi\text{ between }0\text{ and }s)
    Taylor's theorem with the Lagrange remainder (Hoeffding's lemma for Bernoulli variables): E[es(B−p)]≤es2/8\mathbb E[e^{s(B-p)}]\le e^{s^2/8}.
  5. Step 5:
    P(Bˉ−p≥t)=P(esN(Bˉ−p)≥esNt)≤e−sNt E[∏s′=1Nes(Bs′−p)]=e−sNt∏s′=1NE[es(Bs′−p)]P\big(\bar B-p\ge t\big)=P\big(e^{sN(\bar B-p)}\ge e^{sNt}\big)\le e^{-sNt}\,\mathbb E\Big[\prod_{s'=1}^Ne^{s(B_{s'}-p)}\Big]=e^{-sNt}\prod_{s'=1}^N\mathbb E\big[e^{s(B_{s'}-p)}\big]
    For s>0s>0 the exponential is increasing; Markov's inequality P(X≥a)≤E[X]/aP(X\ge a)\le\mathbb E[X]/a for the nonnegative variable esN(Bˉ−p)e^{sN(\bar B-p)}; independence factorises the expectation of the product.
  6. Step 6:
    ≤exp⁡(−sNt+Ns28) → s=4t  exp⁡(−4Nt2+2Nt2)=e−2Nt2\le\exp\Big(-sNt+\frac{Ns^2}8\Big)\ \xrightarrow{\ s=4t\ }\ \exp\big(-4Nt^2+2Nt^2\big)=e^{-2Nt^2}
    Hoeffding's lemma for each factor, then minimise the exponent −sNt+Ns2/8-sNt+Ns^2/8 over ss: the derivative −Nt+Ns/4-Nt+Ns/4 vanishes at s=4ts=4t.
  7. Step 7:
    P(∣Bˉ−p∣≥t)≤P(Bˉ−p≥t)+P((1−Bˉ)−(1−p)≥t)≤2e−2Nt2P\big(\lvert\bar B-p\rvert\ge t\big)\le P\big(\bar B-p\ge t\big)+P\big((1-\bar B)-(1-p)\ge t\big)\le2e^{-2Nt^2}
    Union bound over the two tails; the lower tail of Bˉ\bar B is the upper tail of the average of the Bernoulli variables 1−Bs1-B_s with success probability 1−p1-p, to which the same bound applies.

∎

Theorem

Shot budget of the SWAP test

If N ≥ 2ln⁡(2/δ)ε2,N\ \ge\ \frac{2\ln(2/\delta)}{\varepsilon^2}, then P(∣F^−F∣≤ε)≥1−δP\big(\lvert\hat F-F\rvert\le\varepsilon\big)\ge1-\delta, for every pair of states. For the same guarantee on K^=N0/N\hat K=N_0/N the inversion test needs only N≥ln⁡(2/δ)2ε2N\ge\frac{\ln(2/\delta)}{2\varepsilon^2}, a factor 44 fewer shots.

Proof (4 steps)
  1. Step 1:
    ∣F^−F∣=∣(2P^(0)−1)−(2P0−1)∣=2 ∣P^(0)−P0∣\lvert\hat F-F\rvert=\big\lvert\big(2\hat P(0)-1\big)-\big(2P_0-1\big)\big\rvert=2\,\big\lvert\hat P(0)-P_0\big\rvert
    The estimator and its mean differ by twice the error of the Bernoulli average: an error ε\varepsilon on F^\hat F is an error ε/2\varepsilon/2 on P^(0)\hat P(0).
  2. Step 2:
    P(∣F^−F∣>ε)≤P(∣P^(0)−P0∣≥ε2)≤2exp⁡(−2Nε24)=2e−Nε2/2P\big(\lvert\hat F-F\rvert>\varepsilon\big)\le P\Big(\big\lvert\hat P(0)-P_0\big\rvert\ge\frac\varepsilon2\Big)\le2\exp\Big(-2N\frac{\varepsilon^2}4\Big)=2e^{-N\varepsilon^2/2}
    Hoeffding's inequality with p=P0p=P_0 and tolerance t=ε/2t=\varepsilon/2.
  3. Step 3:
    2e−Nε2/2≤δ  ⟺  −Nε22≤ln⁡δ2  ⟺  N≥2ln⁡(2/δ)ε22e^{-N\varepsilon^2/2}\le\delta\iff-\frac{N\varepsilon^2}2\le\ln\frac\delta2\iff N\ge\frac{2\ln(2/\delta)}{\varepsilon^2}
    Take logarithms (monotone) and multiply by −2/ε2<0-2/\varepsilon^2<0, which reverses the inequality.
  4. Step 4:
    P(∣K^−K∣≥ε)≤2e−2Nε2≤δ  ⟺  N≥ln⁡(2/δ)2ε2=14⋅2ln⁡(2/δ)ε2P\big(\lvert\hat K-K\rvert\ge\varepsilon\big)\le2e^{-2N\varepsilon^2}\le\delta\iff N\ge\frac{\ln(2/\delta)}{2\varepsilon^2}=\frac14\cdot\frac{2\ln(2/\delta)}{\varepsilon^2}
    The inversion test estimates KK directly as a Bernoulli frequency, so Hoeffding applies with t=εt=\varepsilon, without the factor 22.

∎

Derivation

Worked shot budget: ε = 0.01, δ = 0.05

  1. Step 1:
    ln⁡2δ=ln⁡40=3.688879…\ln\frac2\delta=\ln40=3.688879\ldots
    A 95 %95\,\% guarantee.
  2. Step 2:
    N≥2⋅3.688879(0.01)2=73777.6 ⇒ N=73778N\ge\frac{2\cdot3.688879}{(0.01)^2}=73777.6\ \Rightarrow\ N=73778
    Hoeffding's budget for the SWAP test; for ε=0.05\varepsilon=0.05 the same formula gives N=2952N=2952.
  3. Step 3:
    Ninv≥3.6888792⋅(0.01)2=18444.4 ⇒ Ninv=18445N_{\mathrm{inv}}\ge\frac{3.688879}{2\cdot(0.01)^2}=18444.4\ \Rightarrow\ N_{\mathrm{inv}}=18445
    The inversion test for the same precision and confidence.
  4. Step 4:
    F=34:1.961−F2N≤0.01  ⟺  N≥1.962⋅0.437510−4=16807F=\tfrac34:\quad1.96\sqrt{\frac{1-F^2}N}\le0.01\iff N\ge\frac{1.96^2\cdot0.4375}{10^{-4}}=16807
    The normal approximation with the true variance (1−F2)/N(1-F^2)/N asks for fewer shots, but it requires knowing FF and is only asymptotic. Hoeffding's bound holds for every NN and every pair of states, which is why it is used to plan experiments.

Result

ε=0.01, δ=0.05:NSWAP=73778,Ninv=18445\boxed{\varepsilon=0.01,\ \delta=0.05:\qquad N_{\mathrm{SWAP}}=73778,\qquad N_{\mathrm{inv}}=18445}
Corollary

Concentrated kernels cost about 4^n shots with the SWAP test

Suppose the kernel value is exponentially small, F≈2−nF\approx2^{-n}, as for the concentrated product-encoding kernels of the previous lesson. (a) A relative precision Var[F^]≤εrF\sqrt{\mathrm{Var}[\hat F]}\le\varepsilon_rF requires N≥1−F2εr2F2≈4nεr2N\ge\frac{1-F^2}{\varepsilon_r^2F^2}\approx\frac{4^n}{\varepsilon_r^2} SWAP-test shots, against N≥1−Fεr2F≈2nεr2N\ge\frac{1-F}{\varepsilon_r^2F}\approx\frac{2^n}{\varepsilon_r^2} inversion-test shots. (b) Even distinguishing FF from 00 with Hoeffding's guarantee requires an additive precision ε=c 2−n\varepsilon=c\,2^{-n} with c<1c<1, hence N≥2ln⁡(2/δ) 4n/c2N\ge2\ln(2/\delta)\,4^n/c^2.

Proof (5 steps)
  1. Step 1:
    1−F2N≤εrF  ⟺  N≥1−F2εr2F2\sqrt{\frac{1-F^2}N}\le\varepsilon_rF\iff N\ge\frac{1-F^2}{\varepsilon_r^2F^2}
    Square the relative-precision requirement with the SWAP-test variance and solve for NN.
  2. Step 2:
    F=2−n:1−4−nεr2 4−n=4n−1εr2F=2^{-n}:\quad\frac{1-4^{-n}}{\varepsilon_r^2\,4^{-n}}=\frac{4^n-1}{\varepsilon_r^2}
    Multiply numerator and denominator by 4n4^n.
  3. Step 3:
    F(1−F)N≤εrF  ⟺  N≥1−Fεr2F=2n−1εr2(F=2−n)\sqrt{\frac{F(1-F)}N}\le\varepsilon_rF\iff N\ge\frac{1-F}{\varepsilon_r^2F}=\frac{2^n-1}{\varepsilon_r^2}\quad(F=2^{-n})
    The inversion-test variance K(1−K)/NK(1-K)/N vanishes as K→0K\to0, while the SWAP-test variance (1−F2)/N(1-F^2)/N tends to its maximum 1/N1/N: a near-zero overlap means a fair coin on the ancilla, the noisiest possible signal.
  4. Step 4:
    ε=c 2−n:N≥2ln⁡(2/δ)c2 4−n=2ln⁡(2/δ)c2 4n\varepsilon=c\,2^{-n}:\quad N\ge\frac{2\ln(2/\delta)}{c^2\,4^{-n}}=\frac{2\ln(2/\delta)}{c^2}\,4^n
    Hoeffding's budget with a tolerance below the value to be resolved.
  5. Step 5:
    n=10, εr=0.1:NSWAP≈1.05×108,Ninv≈1.02×105n=10,\ \varepsilon_r=0.1:\quad N_{\mathrm{SWAP}}\approx1.05\times10^8,\qquad N_{\mathrm{inv}}\approx1.02\times10^5
    The values (410−1)/0.01(4^{10}-1)/0.01 and (210−1)/0.01(2^{10}-1)/0.01: ten qubits already separate the two tests by three orders of magnitude, per kernel entry.

∎

Here the sampler starts from the orthogonal pair ∣1⟩\lvert1\rangle (θA=π\theta_A=\pi) and ∣0⟩\lvert0\rangle, so F=0F=0 and P(0)=12P(0)=\frac12: every shot is a fair coin, and the estimate F^=2P^(0)−1\hat F=2\hat P(0)-1 has the largest possible standard deviation 1/N1/\sqrt N. Increase the number of shots and watch the error bars shrink like N−1/2N^{-1/2}; about half of the runs produce a negative F^\hat F. Then move θA\theta_A back towards 00: as F→1F\to1 the variance (1−F2)/N(1-F^2)/N vanishes and the samples settle on P(0)=1P(0)=1.

The TypeScript cell below uses the platform library: swapTestCircuit\mathtt{swapTestCircuit} builds the three-qubit test from two one-qubit preparation circuits, swapTestProbability\mathtt{swapTestProbability} returns the exact P(0)P(0), the simulator's seeded sampler produces shot estimates for growing NN, and an explicit mulberry32\mathtt{mulberry32} generator repeats a Hoeffding-sized experiment 20002000 times to show how conservative the bound is.

TypeScriptrunnable
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 F=0.75F=0.75 by about one predicted standard deviation (1−F2)/N\sqrt{(1-F^2)/N}. In the last experiment all 20002000 repetitions with Hoeffding's N=2952N=2952 shots land within ε=0.05\varepsilon=0.05, the largest error being 0.04540.0454: the guaranteed failure rate δ=5 %\delta=5\,\% is a worst case over all states and all NN, and for F=34F=\frac34 the actual failure rate is far smaller. The normal approximation with the true variance would ask for only ⌈1.962(1−F2)/ε2⌉=673\lceil1.96^2(1-F^2)/\varepsilon^2\rceil=673 shots, but it presupposes the value of FF that the experiment is supposed to measure.

Quick check

How many SWAP-test shots does Hoeffding's bound require for ∣F^−F∣≤0.05\lvert\hat F-F\rvert\le0.05 with probability at least 0.950.95?

tolerance ±0.5

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 CCXc1,c2→t∣xc1,xc2,xt⟩=∣xc1,xc2,xt⊕xc1xc2⟩\mathrm{CCX}_{c_1,c_2\to t}\lvert x_{c_1},x_{c_2},x_t\rangle=\lvert x_{c_1},x_{c_2},x_t\oplus x_{c_1}x_{c_2}\rangle, whose decomposition into six CNOTs, seven T/T†T/T^\dagger gates and two Hadamards was proved in the lesson on the Toffoli gate. Below, CNOT2→1\mathrm{CNOT}_{2\to1} has control qubit 22 and target qubit 11; in the circuit editor it is CNOT(2,1)\mathrm{CNOT}(2,1).

Theorem

Fredkin from two CNOTs and a Toffoli

CSWAP0;1,2=CNOT2→1  CCX0,1→2  CNOT2→1.\mathrm{CSWAP}_{0;1,2}=\mathrm{CNOT}_{2\to1}\;\mathrm{CCX}_{0,1\to2}\;\mathrm{CNOT}_{2\to1}. The product is a palindrome, so it reads the same as a matrix product and as a circuit (time order CNOT(2,1); CCX(0,1,2); CNOT(2,1)\mathrm{CNOT}(2,1);\ \mathrm{CCX}(0,1,2);\ \mathrm{CNOT}(2,1)). In the branch c=1c=1 it contains the three-CNOT identity SWAP1,2=CNOT2→1CNOT1→2CNOT2→1\mathrm{SWAP}_{1,2}=\mathrm{CNOT}_{2\to1}\mathrm{CNOT}_{1\to2}\mathrm{CNOT}_{2\to1}.

Proof (7 steps)
  1. Step 1:
    CNOT2→1: (c,a,b)↦(c, a⊕b, b),CCX0,1→2: (c,a,b)↦(c, a, b⊕ca)\mathrm{CNOT}_{2\to1}:\ (c,a,b)\mapsto(c,\,a\oplus b,\,b),\qquad\mathrm{CCX}_{0,1\to2}:\ (c,a,b)\mapsto(c,\,a,\,b\oplus ca)
    Bit maps of the factors on ∣c a b⟩\lvert c\,a\,b\rangle. All three gates and CSWAP\mathrm{CSWAP} 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 (c,a,b)↦(c,a,b)(c,a,b)\mapsto(c,a,b) for c=0c=0 and (c,b,a)(c,b,a) for c=1c=1.
  2. Step 2:
    c is unchanged by every factorc\ \text{is unchanged by every factor}
    Qubit 00 is only ever a control. So the product preserves the subspaces c=0c=0 and c=1c=1, and we can argue case by case.
  3. Step 3:
    c=0:(a,b)→CNOT2→1(a⊕b, b)→ CCX = I (a⊕b, b)→CNOT2→1(a⊕b⊕b, b)=(a, b)c=0:\quad(a,b)\xrightarrow{\mathrm{CNOT}_{2\to1}}(a\oplus b,\,b)\xrightarrow{\ \mathrm{CCX}\ =\ I\ }(a\oplus b,\,b)\xrightarrow{\mathrm{CNOT}_{2\to1}}(a\oplus b\oplus b,\,b)=(a,\,b)
    With c=0c=0 the Toffoli adds ca=0ca=0 and acts as the identity, and CNOT2→12=I\mathrm{CNOT}_{2\to1}^2=I because b⊕b=0b\oplus b=0. This is the action of CSWAP\mathrm{CSWAP} for c=0c=0.
  4. Step 4:
    c=1:CCX0,1→2∣c=1: (a,b)↦(a, b⊕a)=CNOT1→2c=1:\quad\mathrm{CCX}_{0,1\to2}\big\vert_{c=1}:\ (a,b)\mapsto(a,\,b\oplus a)=\mathrm{CNOT}_{1\to2}
    With c=1c=1 the Toffoli adds 1⋅a=a1\cdot a=a to the target: a CNOT from qubit 11 to qubit 22.
  5. Step 5:
    (a,b)→CNOT2→1(a⊕b, b)→CNOT1→2(a⊕b, b⊕a⊕b)=(a⊕b, a)→CNOT2→1(a⊕b⊕a, a)=(b, a)(a,b)\xrightarrow{\mathrm{CNOT}_{2\to1}}(a\oplus b,\,b)\xrightarrow{\mathrm{CNOT}_{1\to2}}\big(a\oplus b,\,b\oplus a\oplus b\big)=(a\oplus b,\,a)\xrightarrow{\mathrm{CNOT}_{2\to1}}\big(a\oplus b\oplus a,\,a\big)=(b,\,a)
    The three-CNOT SWAP identity, by following the bits: x⊕x=0x\oplus x=0 and ⊕\oplus is associative and commutative.
  6. Step 6:
    CNOT2→1 CCX0,1→2 CNOT2→1=∣0⟩⟨0∣⊗I4+∣1⟩⟨1∣⊗SWAP1,2=CSWAP0;1,2\mathrm{CNOT}_{2\to1}\,\mathrm{CCX}_{0,1\to2}\,\mathrm{CNOT}_{2\to1}=\lvert0\rangle\langle0\rvert\otimes I_4+\lvert1\rangle\langle1\rvert\otimes\mathrm{SWAP}_{1,2}=\mathrm{CSWAP}_{0;1,2}
    The two cases combine into the operator form of the Fredkin gate.
  7. Step 7:
    ∣101⟩↦∣111⟩↦∣110⟩↦∣110⟩,∣110⟩↦∣110⟩↦∣111⟩↦∣101⟩\lvert101\rangle\mapsto\lvert111\rangle\mapsto\lvert110\rangle\mapsto\lvert110\rangle,\qquad\lvert110\rangle\mapsto\lvert110\rangle\mapsto\lvert111\rangle\mapsto\lvert101\rangle
    Spot check on the two basis states that the Fredkin gate moves, layer by layer.

∎

Circuit · 3 qubits

Quantum circuit on 3 qubitsX on q1 controlled by q2; X on q2 controlled by q0, q1; X on q1 controlled by q2q0q1q2

The decomposition CNOT(2,1); CCX(0,1,2); CNOT(2,1)\mathrm{CNOT}(2,1);\ \mathrm{CCX}(0,1,2);\ \mathrm{CNOT}(2,1). Its unitary is the Fredkin matrix: the identity except that the rows and columns of ∣101⟩\lvert101\rangle and ∣110⟩\lvert110\rangle are exchanged.

U=(1000000001000000001000000001000000001000000000100000010000000001)U = \begin{pmatrix} 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 \end{pmatrix}
Proposition

Two-qubit gate count of the SWAP test

With the six-CNOT Toffoli, one Fredkin gate costs 88 CNOTs (and 77 TT-type gates), and the SWAP test on nn-qubit registers costs 8n8n CNOTs, 7n7n TT-type gates and 2n+22n+2 Hadamards. For n=1n=1 and the gate set {H,CNOT,CCX}\{H,\mathrm{CNOT},\mathrm{CCX}\}, in which the Toffoli is a primitive, the decomposed test has exactly 55 gates, the gate budget of the lab.

Proof (4 steps)
  1. Step 1:
    #CNOT(CSWAP)=2⏟CNOT2→1 twice+6⏟CCX=8\#\mathrm{CNOT}(\mathrm{CSWAP})=\underbrace{2}_{\mathrm{CNOT}_{2\to1}\ \text{twice}}+\underbrace{6}_{\mathrm{CCX}}=8
    Count the factors of the decomposition, using the six-CNOT Toffoli circuit.
  2. Step 2:
    #T-type(CSWAP)=7,#H(CSWAP)=2\#T\text{-type}(\mathrm{CSWAP})=7,\qquad\#H(\mathrm{CSWAP})=2
    The CNOTs of the decomposition contribute no single-qubit gates; the Toffoli circuit contributes seven T/T†T/T^\dagger gates and two Hadamards.
  3. Step 3:
    n CSWAP:8n CNOT,7n T-type,2n+2 Hn\ \mathrm{CSWAP}:\quad8n\ \mathrm{CNOT},\quad7n\ T\text{-type},\quad2n+2\ H
    The nn-qubit test consists of nn Fredkin gates plus the two Hadamards on the ancilla.
  4. Step 4:
    n=1, gate set {H,CNOT,CCX}:H; CNOT; CCX; CNOT; H = 5 gatesn=1,\ \text{gate set }\{H,\mathrm{CNOT},\mathrm{CCX}\}:\quad H;\ \mathrm{CNOT};\ \mathrm{CCX};\ \mathrm{CNOT};\ H\ =\ 5\ \text{gates}
    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?

tolerance ±0.5

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 UU and the ancilla measures the real part of the expectation value ⟨ψ∣U∣ψ⟩\langle\psi\vert U\vert\psi\rangle; 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.

Theorem

Hadamard test for the real part

Let UU be unitary and ∣ψ⟩\lvert\psi\rangle a unit vector. The circuit H0⋅(∣0⟩⟨0∣⊗I+∣1⟩⟨1∣⊗U)⋅H0H_0\cdot\big(\lvert0\rangle\langle0\rvert\otimes I+\lvert1\rangle\langle1\rvert\otimes U\big)\cdot H_0 on ∣0⟩∣ψ⟩\lvert0\rangle\lvert\psi\rangle produces 12∣0⟩(I+U)∣ψ⟩+12∣1⟩(I−U)∣ψ⟩\frac12\lvert0\rangle(I+U)\lvert\psi\rangle+\frac12\lvert1\rangle(I-U)\lvert\psi\rangle, and P(0)=12(1+Re⟨ψ∣U∣ψ⟩),P(1)=12(1−Re⟨ψ∣U∣ψ⟩),E[Z0]=Re⟨ψ∣U∣ψ⟩.P(0)=\tfrac12\big(1+\mathrm{Re}\langle\psi\vert U\vert\psi\rangle\big),\qquad P(1)=\tfrac12\big(1-\mathrm{Re}\langle\psi\vert U\vert\psi\rangle\big),\qquad\mathbb E[Z_0]=\mathrm{Re}\langle\psi\vert U\vert\psi\rangle.

Proof (5 steps)
  1. Step 1:
    ∣0⟩∣ψ⟩→H012(∣0⟩∣ψ⟩+∣1⟩∣ψ⟩)→C(U)12(∣0⟩∣ψ⟩+∣1⟩U∣ψ⟩)\lvert0\rangle\lvert\psi\rangle\xrightarrow{H_0}\tfrac1{\sqrt2}\big(\lvert0\rangle\lvert\psi\rangle+\lvert1\rangle\lvert\psi\rangle\big)\xrightarrow{C(U)}\tfrac1{\sqrt2}\big(\lvert0\rangle\lvert\psi\rangle+\lvert1\rangle U\lvert\psi\rangle\big)
    The Hadamard prepares ∣+⟩\lvert+\rangle on the ancilla; the controlled unitary acts on the ∣1⟩\lvert1\rangle branch only.
  2. Step 2:
    →H012∣0⟩(∣ψ⟩+U∣ψ⟩)+12∣1⟩(∣ψ⟩−U∣ψ⟩)\xrightarrow{H_0}\tfrac12\lvert0\rangle\big(\lvert\psi\rangle+U\lvert\psi\rangle\big)+\tfrac12\lvert1\rangle\big(\lvert\psi\rangle-U\lvert\psi\rangle\big)
    H∣0⟩=12(∣0⟩+∣1⟩)H\lvert0\rangle=\frac1{\sqrt2}(\lvert0\rangle+\lvert1\rangle), H∣1⟩=12(∣0⟩−∣1⟩)H\lvert1\rangle=\frac1{\sqrt2}(\lvert0\rangle-\lvert1\rangle), collected by ancilla value.
  3. Step 3:
    P(0)=14∥∣ψ⟩+U∣ψ⟩∥2=14(∥ψ∥2+∥Uψ∥2+2 Re⟨ψ∣U∣ψ⟩)P(0)=\tfrac14\big\lVert\lvert\psi\rangle+U\lvert\psi\rangle\big\rVert^2=\tfrac14\Big(\lVert\psi\rVert^2+\lVert U\psi\rVert^2+2\,\mathrm{Re}\langle\psi\vert U\vert\psi\rangle\Big)
    Born rule on the ancilla and the expansion ∥u+v∥2=∥u∥2+∥v∥2+2 Re⟨u∣v⟩\lVert u+v\rVert^2=\lVert u\rVert^2+\lVert v\rVert^2+2\,\mathrm{Re}\langle u\vert v\rangle.
  4. Step 4:
    ∥Uψ∥2=⟨ψ∣U†U∣ψ⟩=⟨ψ∣ψ⟩=1 ⇒ P(0)=14(2+2 Re⟨ψ∣U∣ψ⟩)=12(1+Re⟨ψ∣U∣ψ⟩)\lVert U\psi\rVert^2=\langle\psi\vert U^\dagger U\vert\psi\rangle=\langle\psi\vert\psi\rangle=1\ \Rightarrow\ P(0)=\tfrac14\big(2+2\,\mathrm{Re}\langle\psi\vert U\vert\psi\rangle\big)=\tfrac12\big(1+\mathrm{Re}\langle\psi\vert U\vert\psi\rangle\big)
    Unitarity preserves the norm.
  5. Step 5:
    P(1)=14∥∣ψ⟩−U∣ψ⟩∥2=12(1−Re⟨ψ∣U∣ψ⟩),E[Z0]=P(0)−P(1)=Re⟨ψ∣U∣ψ⟩P(1)=\tfrac14\big\lVert\lvert\psi\rangle-U\lvert\psi\rangle\big\rVert^2=\tfrac12\big(1-\mathrm{Re}\langle\psi\vert U\vert\psi\rangle\big),\qquad\mathbb E[Z_0]=P(0)-P(1)=\mathrm{Re}\langle\psi\vert U\vert\psi\rangle
    The same expansion with v↦−vv\mapsto-v; the ancilla's ZZ expectation is the difference of the two probabilities.

∎

Theorem

Hadamard test for the imaginary part

Insert S†=diag(1,−i)S^\dagger=\mathrm{diag}(1,-i) on the ancilla after the first Hadamard. Then P(0)=12(1+Im⟨ψ∣U∣ψ⟩),P(1)=12(1−Im⟨ψ∣U∣ψ⟩).P(0)=\tfrac12\big(1+\mathrm{Im}\langle\psi\vert U\vert\psi\rangle\big),\qquad P(1)=\tfrac12\big(1-\mathrm{Im}\langle\psi\vert U\vert\psi\rangle\big). With S=diag(1,i)S=\mathrm{diag}(1,i) instead, the sign is reversed: P(0)=12(1−Im⟨ψ∣U∣ψ⟩)P(0)=\frac12\big(1-\mathrm{Im}\langle\psi\vert U\vert\psi\rangle\big). Running both variants determines the complex number ⟨ψ∣U∣ψ⟩\langle\psi\vert U\vert\psi\rangle.

Proof (6 steps)
  1. Step 1:
    S†12(∣0⟩+∣1⟩)=12(∣0⟩−i∣1⟩)S^\dagger\tfrac1{\sqrt2}\big(\lvert0\rangle+\lvert1\rangle\big)=\tfrac1{\sqrt2}\big(\lvert0\rangle-i\lvert1\rangle\big)
    S†S^\dagger multiplies the ∣1⟩\lvert1\rangle amplitude by −i-i.
  2. Step 2:
    →C(U)12(∣0⟩∣ψ⟩−i ∣1⟩U∣ψ⟩)→H012∣0⟩(∣ψ⟩−iU∣ψ⟩)+12∣1⟩(∣ψ⟩+iU∣ψ⟩)\xrightarrow{C(U)}\tfrac1{\sqrt2}\big(\lvert0\rangle\lvert\psi\rangle-i\,\lvert1\rangle U\lvert\psi\rangle\big)\xrightarrow{H_0}\tfrac12\lvert0\rangle\big(\lvert\psi\rangle-iU\lvert\psi\rangle\big)+\tfrac12\lvert1\rangle\big(\lvert\psi\rangle+iU\lvert\psi\rangle\big)
    Controlled unitary on the ∣1⟩\lvert1\rangle branch, then the final Hadamard as before.
  3. Step 3:
    P(0)=14∥∣ψ⟩−iU∣ψ⟩∥2=14(1+1+2 Re⟨ψ∣(−iU)∣ψ⟩)P(0)=\tfrac14\big\lVert\lvert\psi\rangle-iU\lvert\psi\rangle\big\rVert^2=\tfrac14\Big(1+1+2\,\mathrm{Re}\langle\psi\vert(-iU)\vert\psi\rangle\Big)
    The norm expansion with u=∣ψ⟩u=\lvert\psi\rangle, v=−iU∣ψ⟩v=-iU\lvert\psi\rangle, ∥v∥=1\lVert v\rVert=1.
  4. Step 4:
    z=⟨ψ∣U∣ψ⟩=x+iy:Re(−iz)=Re(−ix+y)=y=Im zz=\langle\psi\vert U\vert\psi\rangle=x+iy:\quad\mathrm{Re}(-iz)=\mathrm{Re}(-ix+y)=y=\mathrm{Im}\,z
    Multiplication by −i-i rotates the complex plane by −90∘-90^\circ and moves the imaginary part onto the real axis.
  5. Step 5:
    P(0)=12(1+Im⟨ψ∣U∣ψ⟩),P(1)=14∥∣ψ⟩+iU∣ψ⟩∥2=12(1−Im⟨ψ∣U∣ψ⟩)P(0)=\tfrac12\big(1+\mathrm{Im}\langle\psi\vert U\vert\psi\rangle\big),\qquad P(1)=\tfrac14\big\lVert\lvert\psi\rangle+iU\lvert\psi\rangle\big\rVert^2=\tfrac12\big(1-\mathrm{Im}\langle\psi\vert U\vert\psi\rangle\big)
    Insert into the previous line; for P(1)P(1), Re(iz)=−Im z\mathrm{Re}(iz)=-\mathrm{Im}\,z.
  6. Step 6:
    S: 12(∣0⟩+i∣1⟩) ⇒ P(0)=12(1+Re(iz))=12(1−Im z)S:\ \tfrac1{\sqrt2}\big(\lvert0\rangle+i\lvert1\rangle\big)\ \Rightarrow\ P(0)=\tfrac12\big(1+\mathrm{Re}(iz)\big)=\tfrac12\big(1-\mathrm{Im}\,z\big)
    With SS the branch carries +i+i, and Re(iz)=−y\mathrm{Re}(iz)=-y: the sign convention matters, and the numerical check below confirms it.

∎

Corollary

The SWAP test is the Hadamard test of SWAP

The SWAP test is the Hadamard test with U=SWAPA,BU=\mathrm{SWAP}_{A,B} and input ∣ψ⟩∣ϕ⟩\lvert\psi\rangle\lvert\phi\rangle: Re ⟨ψϕ∣SWAP∣ψϕ⟩=∣⟨ψ∣ϕ⟩∣2,Im ⟨ψϕ∣SWAP∣ψϕ⟩=0,\mathrm{Re}\,\langle\psi\phi\vert\mathrm{SWAP}\vert\psi\phi\rangle=\lvert\langle\psi\vert\phi\rangle\rvert^2,\qquad\mathrm{Im}\,\langle\psi\phi\vert\mathrm{SWAP}\vert\psi\phi\rangle=0, so the real-part test gives P(0)=12(1+∣⟨ψ∣ϕ⟩∣2)P(0)=\frac12\big(1+\lvert\langle\psi\vert\phi\rangle\rvert^2\big) and the imaginary-part variant always gives P(0)=12P(0)=\frac12.

Proof (4 steps)
  1. Step 1:
    C(SWAPA,B)=∏iCSWAP0;ai,biC(\mathrm{SWAP}_{A,B})=\prod_i\mathrm{CSWAP}_{0;a_i,b_i}
    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.
  2. Step 2:
    ⟨ψϕ∣SWAP∣ψϕ⟩=⟨ψϕ∣ϕψ⟩=⟨ψ∣ϕ⟩⟨ϕ∣ψ⟩=∣⟨ψ∣ϕ⟩∣2\langle\psi\phi\vert\mathrm{SWAP}\vert\psi\phi\rangle=\langle\psi\phi\vert\phi\psi\rangle=\langle\psi\vert\phi\rangle\langle\phi\vert\psi\rangle=\lvert\langle\psi\vert\phi\rangle\rvert^2
    The swap exchanges the factors, and inner products of product vectors factorise.
  3. Step 3:
    SWAP†=SWAP ⇒ ⟨χ∣SWAP∣χ⟩∈R for every ∣χ⟩\mathrm{SWAP}^\dagger=\mathrm{SWAP}\ \Rightarrow\ \langle\chi\vert\mathrm{SWAP}\vert\chi\rangle\in\mathbb R\ \text{for every}\ \lvert\chi\rangle
    Expectation values of Hermitian operators are real: ⟨χ∣A∣χ⟩‾=⟨χ∣A†∣χ⟩=⟨χ∣A∣χ⟩\overline{\langle\chi\vert A\vert\chi\rangle}=\langle\chi\vert A^\dagger\vert\chi\rangle=\langle\chi\vert A\vert\chi\rangle. So the imaginary part vanishes even for entangled register states.
  4. Step 4:
    P(0)=12(1+Re⟨ψϕ∣SWAP∣ψϕ⟩)=12(1+∣⟨ψ∣ϕ⟩∣2)P(0)=\tfrac12\big(1+\mathrm{Re}\langle\psi\phi\vert\mathrm{SWAP}\vert\psi\phi\rangle\big)=\tfrac12\big(1+\lvert\langle\psi\vert\phi\rangle\rvert^2\big)
    The Hadamard-test formula reproduces the acceptance theorem.

∎

Derivation

Example: U = R_Z(0.8) on the lab state

  1. Step 1:
    ∣ψ⟩=RY(π3)∣0⟩=32∣0⟩+12∣1⟩,U=RZ(0.8)=diag(e−0.4i,e0.4i)\lvert\psi\rangle=R_Y(\tfrac\pi3)\lvert0\rangle=\tfrac{\sqrt3}2\lvert0\rangle+\tfrac12\lvert1\rangle,\qquad U=R_Z(0.8)=\mathrm{diag}\big(e^{-0.4i},e^{0.4i}\big)
    RZ(θ)=e−iθZ/2R_Z(\theta)=e^{-i\theta Z/2} with θ=0.8\theta=0.8.
  2. Step 2:
    ⟨ψ∣U∣ψ⟩=34e−0.4i+14e0.4i=cos⁡0.4−i2sin⁡0.4\langle\psi\vert U\vert\psi\rangle=\tfrac34e^{-0.4i}+\tfrac14e^{0.4i}=\cos0.4-\tfrac i2\sin0.4
    ⟨ψ∣U∣ψ⟩=∑k∣ψk∣2Ukk\langle\psi\vert U\vert\psi\rangle=\sum_k\lvert\psi_k\rvert^2U_{kk} for diagonal UU; Euler's formula: 34(cos⁡0.4−isin⁡0.4)+14(cos⁡0.4+isin⁡0.4)\frac34(\cos0.4-i\sin0.4)+\frac14(\cos0.4+i\sin0.4).
  3. Step 3:
    Re=cos⁡0.4=0.921061,Im=−12sin⁡0.4=−0.194709\mathrm{Re}=\cos0.4=0.921061,\qquad\mathrm{Im}=-\tfrac12\sin0.4=-0.194709
    Numerical values.
  4. Step 4:
    PRe(0)=12(1+0.921061)=0.960530,PS†(0)=12(1−0.194709)=0.402645P_{\mathrm{Re}}(0)=\tfrac12(1+0.921061)=0.960530,\qquad P_{S^\dagger}(0)=\tfrac12(1-0.194709)=0.402645
    The two Hadamard-test variants. The NumPy cell recovers both numbers from 2P(0)−12P(0)-1.

Result

⟨ψ∣RZ(0.8)∣ψ⟩=0.921061−0.194709 i\boxed{\langle\psi\vert R_Z(0.8)\vert\psi\rangle=0.921061-0.194709\,i}

Quick check

In the Hadamard test the controlled unitary is U=−IU=-I (a global phase −1-1, controlled by the ancilla). What does the ancilla return?

Select one answer

Worked example: the lab state#

Derivation

SWAP test of R_Y(π/3)|0⟩ against |0⟩, amplitude by amplitude

  1. Step 1:
    ∣ψ⟩=RY(π3)∣0⟩=cos⁡π6∣0⟩+sin⁡π6∣1⟩=32∣0⟩+12∣1⟩,∣ϕ⟩=∣0⟩\lvert\psi\rangle=R_Y(\tfrac\pi3)\lvert0\rangle=\cos\tfrac\pi6\lvert0\rangle+\sin\tfrac\pi6\lvert1\rangle=\tfrac{\sqrt3}2\lvert0\rangle+\tfrac12\lvert1\rangle,\qquad\lvert\phi\rangle=\lvert0\rangle
    First column of RY(θ)=(cos⁡θ2−sin⁡θ2sin⁡θ2cos⁡θ2)R_Y(\theta)=\begin{pmatrix}\cos\frac\theta2&-\sin\frac\theta2\\\sin\frac\theta2&\cos\frac\theta2\end{pmatrix} at θ=π3\theta=\frac\pi3.
  2. Step 2:
    F=∣⟨ψ∣ϕ⟩∣2=cos⁡2π6=34,P(0)=12(1+34)=78F=\lvert\langle\psi\vert\phi\rangle\rvert^2=\cos^2\tfrac\pi6=\tfrac34,\qquad P(0)=\tfrac12\big(1+\tfrac34\big)=\tfrac78
    The prediction of the acceptance theorem; the remaining steps confirm it amplitude by amplitude.
  3. Step 3:
    ∣Ψ0⟩=∣0⟩∣ψ⟩∣0⟩=32∣000⟩+12∣010⟩=(32,0,12,0,0,0,0,0)⊤\lvert\Psi_0\rangle=\lvert0\rangle\lvert\psi\rangle\lvert0\rangle=\tfrac{\sqrt3}2\lvert000\rangle+\tfrac12\lvert010\rangle=\big(\tfrac{\sqrt3}2,0,\tfrac12,0,0,0,0,0\big)^{\top}
    Kronecker product with the ancilla as the leftmost factor; index 4c+2a+b4c+2a+b, so ∣010⟩\lvert010\rangle is index 22.
  4. Step 4:
    ∣Ψ1⟩=64∣000⟩+24∣010⟩+64∣100⟩+24∣110⟩=(64,0,24,0,64,0,24,0)⊤\lvert\Psi_1\rangle=\tfrac{\sqrt6}4\lvert000\rangle+\tfrac{\sqrt2}4\lvert010\rangle+\tfrac{\sqrt6}4\lvert100\rangle+\tfrac{\sqrt2}4\lvert110\rangle=\big(\tfrac{\sqrt6}4,0,\tfrac{\sqrt2}4,0,\tfrac{\sqrt6}4,0,\tfrac{\sqrt2}4,0\big)^{\top}
    HH on the ancilla copies each amplitude into the c=1c=1 half with the factor 12\frac1{\sqrt2}: 32⋅12=64≈0.612372\frac{\sqrt3}2\cdot\frac1{\sqrt2}=\frac{\sqrt6}4\approx0.612372 and 12⋅12=24≈0.353553\frac12\cdot\frac1{\sqrt2}=\frac{\sqrt2}4\approx0.353553.
  5. Step 5:
    ∣Ψ2⟩=64∣000⟩+24∣010⟩+64∣100⟩+24∣101⟩=(64,0,24,0,64,24,0,0)⊤\lvert\Psi_2\rangle=\tfrac{\sqrt6}4\lvert000\rangle+\tfrac{\sqrt2}4\lvert010\rangle+\tfrac{\sqrt6}4\lvert100\rangle+\tfrac{\sqrt2}4\lvert101\rangle=\big(\tfrac{\sqrt6}4,0,\tfrac{\sqrt2}4,0,\tfrac{\sqrt6}4,\tfrac{\sqrt2}4,0,0\big)^{\top}
    The Fredkin gate moves the amplitude of ∣110⟩\lvert110\rangle (index 66) to ∣101⟩\lvert101\rangle (index 55); ∣100⟩\lvert100\rangle has equal targets and stays.
  6. Step 6:
    H0: ∣0 ab⟩↦12(∣0 ab⟩+∣1 ab⟩),∣1 ab⟩↦12(∣0 ab⟩−∣1 ab⟩)H_0:\ \lvert0\,ab\rangle\mapsto\tfrac1{\sqrt2}\big(\lvert0\,ab\rangle+\lvert1\,ab\rangle\big),\quad\lvert1\,ab\rangle\mapsto\tfrac1{\sqrt2}\big(\lvert0\,ab\rangle-\lvert1\,ab\rangle\big)
    The final Hadamard combines the amplitudes of each pair of indices (k,k+4)(k,k+4) into their sum and difference over 2\sqrt2.
  7. Step 7:
    ∣000⟩: 12(64+64)=32,∣100⟩: 12(64−64)=0,∣010⟩,∣110⟩: 12⋅24=14\lvert000\rangle:\ \tfrac1{\sqrt2}\big(\tfrac{\sqrt6}4+\tfrac{\sqrt6}4\big)=\tfrac{\sqrt3}2,\quad\lvert100\rangle:\ \tfrac1{\sqrt2}\big(\tfrac{\sqrt6}4-\tfrac{\sqrt6}4\big)=0,\quad\lvert010\rangle,\lvert110\rangle:\ \tfrac1{\sqrt2}\cdot\tfrac{\sqrt2}4=\tfrac14
    Pairs (0,4)(0,4) and (2,6)(2,6): the pair (0,4)(0,4) interferes completely constructively and destructively, and the pair (2,6)(2,6) has a single nonzero amplitude, at index 22.
  8. Step 8:
    ∣001⟩: 12⋅24=14,∣101⟩: −12⋅24=−14,∣011⟩,∣111⟩: 0\lvert001\rangle:\ \tfrac1{\sqrt2}\cdot\tfrac{\sqrt2}4=\tfrac14,\qquad\lvert101\rangle:\ -\tfrac1{\sqrt2}\cdot\tfrac{\sqrt2}4=-\tfrac14,\qquad\lvert011\rangle,\lvert111\rangle:\ 0
    Pair (1,5)(1,5) has only the amplitude at index 55, which enters the c=1c=1 output with a minus sign; pair (3,7)(3,7) is empty.
  9. Step 9:
    ∣Ψ3⟩=(32, 14, 14, 0, 0, −14, 14, 0)⊤≈(0.866025, 0.25, 0.25, 0, 0, −0.25, 0.25, 0)⊤\lvert\Psi_3\rangle=\big(\tfrac{\sqrt3}2,\ \tfrac14,\ \tfrac14,\ 0,\ 0,\ -\tfrac14,\ \tfrac14,\ 0\big)^{\top}\approx(0.866025,\,0.25,\,0.25,\,0,\,0,\,-0.25,\,0.25,\,0)^{\top}
    All eight amplitudes. Norm check: 34+4⋅116=1\frac34+4\cdot\frac1{16}=1. It agrees with the theorem: 12(∣ψϕ⟩+∣ϕψ⟩)=32∣00⟩+14∣10⟩+14∣01⟩\frac12(\lvert\psi\phi\rangle+\lvert\phi\psi\rangle)=\frac{\sqrt3}2\lvert00\rangle+\frac14\lvert10\rangle+\frac14\lvert01\rangle and 12(∣ψϕ⟩−∣ϕψ⟩)=14∣10⟩−14∣01⟩\frac12(\lvert\psi\phi\rangle-\lvert\phi\psi\rangle)=\frac14\lvert10\rangle-\frac14\lvert01\rangle.
  10. Step 10:
    P(0)=34+116+116=78=0.875,P(1)=116+116=18,⟨Z0⟩=78−18=34P(0)=\tfrac34+\tfrac1{16}+\tfrac1{16}=\tfrac78=0.875,\qquad P(1)=\tfrac1{16}+\tfrac1{16}=\tfrac18,\qquad\langle Z_0\rangle=\tfrac78-\tfrac18=\tfrac34
    Sum the squared moduli over indices 00–33 (ancilla 00) and 44–77 (ancilla 11). The ancilla expectation ⟨Z0⟩=2P(0)−1=F\langle Z_0\rangle=2P(0)-1=F is the auxiliary quantity checked by the lab.

Result

P(0)=78,P(1)=18,F^=2P(0)−1=34=cos⁡2π6\boxed{P(0)=\tfrac78,\qquad P(1)=\tfrac18,\qquad\hat F=2P(0)-1=\tfrac34=\cos^2\tfrac\pi6}

Circuit · 3 qubits

Quantum circuit on 3 qubitsRY(π/3) on q1; H on q0; SWAP on q1, q2 controlled by q0; H on q0q0q1q2RY(π/3)HH

The lab circuit: RY(π/3)R_Y(\pi/3) prepares ∣ψ⟩\lvert\psi\rangle on qubit 11, qubit 22 stays ∣ϕ⟩=∣0⟩\lvert\phi\rangle=\lvert0\rangle, and H(0); CSWAP(0,1,2); H(0)H(0);\ \mathrm{CSWAP}(0,1,2);\ H(0) is the SWAP test. The statevector shows the five nonzero amplitudes 32,14,14,−14,14\frac{\sqrt3}2,\frac14,\frac14,-\frac14,\frac14 at ∣000⟩,∣001⟩,∣010⟩,∣101⟩,∣110⟩\lvert000\rangle,\lvert001\rangle,\lvert010\rangle,\lvert101\rangle,\lvert110\rangle; the histogram puts 78\frac78 of the weight on ancilla outcome 00.

∣ψ⟩=32∣000⟩+14∣001⟩+14∣010⟩−14∣101⟩+14∣110⟩\lvert\psi\rangle = \tfrac{\sqrt{3}}{2}\lvert 000\rangle + \tfrac{1}{4}\lvert 001\rangle + \tfrac{1}{4}\lvert 010\rangle - \tfrac{1}{4}\lvert 101\rangle + \tfrac{1}{4}\lvert 110\rangle
  • |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 0.720.72 from a full density-matrix simulation of the three-qubit circuit; both Hadamard-test variants for U=RZ(0.8)U=R_Z(0.8); seeded shot estimates; Hoeffding budgets; and the per-entry shot cost of the SWAP and inversion tests for kernel values K=2−nK=2^{-n} at 10 %10\,\% relative precision.

Pythonrunnable
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 RY(1,π/3)R_Y(1,\pi/3) is locked; you append the SWAP test with at most five gates from {H,CSWAP,CNOT,CCX}\{H,\mathrm{CSWAP},\mathrm{CNOT},\mathrm{CCX}\}, either with a Fredkin gate or with its decomposition. The grader checks the exact ancilla marginal (78,18)\big(\frac78,\frac18\big) and ⟨Z0⟩=34\langle Z_0\rangle=\frac34, and recognises the two classic mistakes: dropping the controlled swap (⟨Z0⟩=1\langle Z_0\rangle=1) and dropping the final Hadamard (⟨Z0⟩=0\langle Z_0\rangle=0).

References

  1. H. Buhrman, R. Cleve, J. Watrous and R. de Wolf, Quantum fingerprinting, Physical Review Letters 87, 167902 (2001).doi:10.1103/PhysRevLett.87.167902
  2. 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
  3. 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
  4. 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
  5. E. Fredkin and T. Toffoli, Conservative logic, International Journal of Theoretical Physics 21, 219–253 (1982).doi:10.1007/BF01857727
  6. 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
  7. 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
  8. 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
  9. M. A. Nielsen and I. L. Chuang, Quantum Computation and Quantum Information, 10th anniversary edition, Cambridge University Press (2010).doi:10.1017/CBO9780511976667
  10. 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-graded

    Build the SWAP test on three qubits and read the fidelity of two one-qubit states from the ancilla alone: with ∣ψ⟩=RY(π/3)∣0⟩\lvert\psi\rangle=R_Y(\pi/3)\lvert0\rangle and ∣ϕ⟩=∣0⟩\lvert\phi\rangle=\lvert0\rangle the overlap is F=∣⟨ψ∣ϕ⟩∣2=cos⁡2π6=34F=\lvert\langle\psi\vert\phi\rangle\rvert^2=\cos^2\frac\pi6=\frac34, so the ancilla must return 00 with probability P(0)=12(1+F)=78P(0)=\frac12(1+F)=\frac78.

    Open lab