• Algorithms

SWAP Test

The SWAP test is a quantum circuit that estimates the overlap (fidelity) between two unknown quantum states using a single ancilla qubit and a controlled-SWAP gate.

The SWAP test circuit uses three registers: one ancilla qubit initialized to |0>, and two data registers holding the states |psi> and |phi> to be compared. The circuit applies a Hadamard gate to the ancilla, then a controlled-SWAP (Fredkin) gate that swaps the two data registers conditioned on the ancilla being |1>, and finally another Hadamard on the ancilla before measurement. The sequence is compact and does not require knowledge of |psi> or |phi>, making it applicable whenever the states can be prepared as black boxes or quantum oracle calls.

After the two Hadamard gates and the controlled-SWAP, measuring the ancilla qubit in the computational basis yields outcome 0 with probability P(0) = 1/2 + 1/2 |<psi|phi>|^2 and outcome 1 with probability P(1) = 1/2 - 1/2 |<psi|phi>|^2. Repeating the circuit k times and counting 0 outcomes gives an unbiased estimator of the fidelity F = |<psi|phi>|^2 with standard error of order 1/sqrt(k). When |psi> = |phi>, the ancilla is always 0; when they are orthogonal, both outcomes are equally likely. The test is destructive in the sense that each run consumes one copy of each state, so estimating F to precision epsilon requires O(1/epsilon^2) state preparations.

In quantum machine learning, the SWAP test is the canonical method for evaluating quantum kernel functions. A quantum kernel K(x, x’) = |<phi(x)|phi(x’)>|^2 between data points x and x’ mapped to quantum states |phi(x)> and |phi(x’)> can be estimated directly by running the SWAP test on the two feature states. This enables quantum support vector machines and other kernel methods without ever classically accessing the exponentially large feature space. The inner product can also be measured more efficiently on some hardware using the Hadamard test variant, which requires only one extra qubit and half the circuit depth.

Hardware implementation of the SWAP test is challenging because the controlled-SWAP gate decomposes into three CNOT gates, adding significant depth and error accumulation on near-term devices. For small systems or systems with native multi-qubit gates, this is manageable, but for high-dimensional feature states the gate count grows with system size. An alternative approach on hardware with mid-circuit measurement and feed-forward is to replace the controlled-SWAP with a sequence of Bell measurements, reducing the ancilla overhead. The SWAP test also underlies quantum fingerprinting, a communication complexity protocol that allows two parties to compare n-bit strings using only O(log n) qubits of quantum communication, an exponential reduction over classical deterministic protocols.