The circuit model
Everything so far fits one template, called the circuit model:
- Prepare qubits in .
- Apply a sequence of gates, each acting on one or two (occasionally three) qubits.
- Measure some or all qubits in the computational basis.
- Process the measured bits with an ordinary computer; repeat for many shots.
In a diagram, each horizontal wire is a qubit, time runs left to right, and gates in the same column act on disjoint qubits at the same time. Three numbers describe a circuit's size: its width (number of qubits), its gate count, and its depth (number of columns, i.e. time steps, when gates on disjoint qubits run in parallel). Depth matters on hardware because qubits decay while they wait, as the noise lesson explains. Circuits can also contain measurements in the middle and gates conditioned on their results; teleportation, in the next lesson, uses exactly that. A thorough treatment of the model is in Nielsen and Chuang, Chapter 4.
Here is a width-3, depth-3 circuit with three gates that prepares the Greenberger–Horne–Zeilinger (GHZ) state :
By hand: gives ; the first CX flips qubit 1 on the second branch, giving ; the second CX flips qubit 2 where qubit 1 is 1, giving . Measuring yields 000 or 111, each with probability .
Simulating a circuit with a state vector
A state-vector simulator stores all amplitudes and updates them gate by gate. The naive way to apply a gate on qubit is to build the full matrix and multiply. That costs memory for the matrix alone, which is hopeless beyond a dozen qubits. The standard trick avoids it entirely.
Reshape the vector into a tensor. With our convention (qubit 0 is the most
significant bit), the amplitude of sits at index
. That is exactly how NumPy lays out an array of shape
in memory, so psi.reshape((2,) * n) gives a tensor
whose axis is qubit . No data is copied.
A single-qubit gate is a contraction on one axis. Applying to qubit means
with every other index untouched. A two-qubit gate is a matrix; reshaped
to shape with indices (output of the first qubit, output of the second,
input of the first, input of the second), it contracts with two axes at once.
numpy.einsum writes such contractions directly:
import numpy as np
H = np.array([[1, 1], [1, -1]], dtype=complex) / np.sqrt(2)
CX = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]], dtype=complex)
CX4 = CX.reshape(2, 2, 2, 2) # indices: (out control, out target, in control, in target)
psi = np.zeros(8, dtype=complex)
psi[0] = 1 # |000>
t = psi.reshape(2, 2, 2) # axis j is qubit j (qubit 0 = most significant bit)
t = np.einsum("ai,ijk->ajk", H, t) # H on qubit 0
t = np.einsum("abij,ijk->abk", CX4, t) # CX, control 0, target 1
t = np.einsum("bcjk,ajk->abc", CX4, t) # CX, control 1, target 2
psi = t.reshape(-1)
print(np.round(psi.real, 4)) # [0.7071 0. 0. 0. 0. 0. 0. 0.7071]
# The same circuit with full 8x8 matrices, as an independent check:
I2 = np.eye(2)
U = np.kron(I2, CX) @ np.kron(CX, I2) @ np.kron(H, np.kron(I2, I2))
print(np.allclose(U[:, 0], psi)) # True
counts = np.random.default_rng(5).multinomial(1000, np.abs(psi) ** 2)
print({format(i, "03b"): int(c) for i, c in enumerate(counts) if c})
The last line samples 1000 shots and prints {'000': 515, '111': 485} (NumPy 2.5,
seed 5). Bitstrings are formatted with qubit 0 on the left, matching the index
convention. The exercise asks you to generalise the einsum lines into one
function that applies a -qubit gate to any list of target qubits, in any
order, using numpy.tensordot and numpy.moveaxis.
Cost. A single-qubit gate touches every amplitude once, with a matrix: about complex multiplications. A two-qubit gate costs about . A circuit with gates therefore costs on the order of operations, which is linear in the number of gates and exponential in the number of qubits.
Memory: why simulation hits a wall
Each amplitude is a complex128: two 64-bit floats, 16 bytes. The state of
qubits needs
| Qubits | Roughly | |
|---|---|---|
| 20 | 16,777,216 bytes | 16 MiB: trivial |
| 30 | 17,179,869,184 bytes | 16 GiB: a well-equipped laptop |
| 40 | about bytes | 16 TiB: a large cluster |
| 50 | about bytes | 16 PiB: beyond any single machine's memory |
Every added qubit doubles the memory and the time per gate. Single precision
(complex64) halves the memory, buying exactly one qubit. Three consequences follow.
- Brute-force state-vector simulation stops in the region of a few tens of qubits on any classical hardware, because the requirement grows by a factor of 1024 every ten qubits.
- Structured circuits can be cheaper. Circuits built only from , and CX (Clifford circuits) can be simulated in polynomial time by tracking stabilizers instead of amplitudes (the Gottesman–Knill theorem, Nielsen and Chuang, Section 10.5.4); the error-correction course uses Stim, a simulator of this kind. Tensor-network methods exploit limited entanglement. These are real advantages, but they depend on structure.
- For general circuits no efficient classical simulation method is known. That none exists is widely believed and supported by complexity-theoretic evidence, but it is not proven. Statements of the form "simulating qubits requires memory" describe the state-vector method, not a theorem about all possible classical algorithms.
Sampling versus exact amplitudes
A simulator has something hardware never gives you: the exact amplitudes. Use them. When you test a circuit, compare exact probabilities with the expected ones to tight tolerances, and use sampling only to mimic what an experiment would report. Sampled counts depend on the random generator and seed, and are reproducible only for the same seed and library version; their statistical error is the of the measurement lesson. When you compare two simulators, compare exact quantities first and treat any agreement of sampled counts as a statistical statement.
Checking your simulator against the KetQat SDK
A simulator that agrees with itself proves nothing. The standard way to gain
confidence is to compare it with an independent implementation on a
non-trivial circuit. The open-source KetQat SDK runs a set of catalogued
products locally, each with a declared set of inputs and outputs. Its
grover-search product simulates Grover's search algorithm and reports the exact
success probability from its own state vector.
You do not need to understand Grover's algorithm in depth for this check (the Algorithms course treats it properly). The circuit is: on every qubit, then repetitions of an oracle that flips the sign of the amplitudes of the "marked" basis states, followed by a diffusion step , sign flip of all amplitudes except , . With marked states among , the probability of measuring a marked state after repetitions is with ; this closed form is a theorem proved in the references the product cites. For , one marked state and : , and the success probability is .
Running the product (install the SDK as described in the exercise README):
from ketqat_runner import catalog
record = catalog.run("[email protected]", seed=7, n_qubits=3, marked=[5], shots=1000)
result = record.result
print(record.status, result["iterations"], result["iterations_rule"])
print(result["success_probability"], result["analytic_success_probability"])
print(result["counts"]["101"], "of", result["shots"], "shots landed on the marked state 101")
This printed succeeded 2 floor(pi/4*sqrt(N/M)), then 0.9453124999999998 0.9453124999999999,
then 938 of 1000 shots landed on the marked state 101 (SDK at commit 2cedabb,
NumPy 2.5). The product chose by the rule it reports; the simulated and
analytic probabilities agree to floating-point precision; and the sampled
fraction 0.938 lies about one standard error () below 0.945. Each run also
writes a small JSON record of its inputs and results under $KETQAT_HOME
(default ~/.ketqat), so you can trace any number back to the run that produced it.
In the exercise, your own simulator runs the same circuit gate by gate, and the test compares its success probability with the SDK's for several register sizes and marked sets, to . Two implementations written independently agreeing to that precision on a circuit with dozens of gates is strong evidence that both apply gates in the same order and with the same qubit convention.
Common mistakes
- Mixing up axis order. After
reshape((2,) * n), axis is qubit only because qubit 0 is the most significant bit. With a little-endian convention the axes come out reversed. - Leaving axes in the wrong place.
numpy.tensordotputs the new axes first; move them back to the target positions, or the next gate acts on the wrong qubit. - Building full matrices.
numpy.kronwith identities is fine for checking small cases and disastrous as a simulator. - Comparing sampled counts across tools. Different generators give different counts for the "same" seed. Compare exact probabilities instead.
- Over-reading the memory table. It describes brute-force state vectors, not a proven limit on every classical method.
Summary
- The circuit model: prepare , apply gates, measure, repeat; size is measured by width, depth and gate count.
- A state-vector simulator reshapes amplitudes into an -axis tensor and contracts gates with one or two axes at a time, costing about operations.
- Memory is bytes: 16 GiB at 30 qubits, doubling with every qubit.
- Validate simulators on exact quantities against independent implementations,
such as the KetQat SDK's
grover-searchproduct.
Next, Introductory quantum algorithms uses circuits like these to beat classical query bounds, and to teleport a qubit.