Skip to main content
KetQat

Appearance

Lesson 650 min

Quantum circuits and simulation

The circuit model, state-vector simulation and its exponential cost, and running circuits locally.

After this lesson you can

  • Describe a computation in the circuit model and state its width, depth and gate count
  • Apply single- and two-qubit gates to an n-qubit state vector by reshaping it into a tensor, without forming 2^n x 2^n matrices
  • Compute the memory a state vector needs (16 bytes per amplitude) and explain what this implies for classical simulation
  • Sample measurement outcomes from a simulated state with a fixed seed and report them as bitstrings in a stated qubit order
  • Validate a home-made simulator against an independent implementation, the KetQat SDK grover-search product

Read first: Multiple qubits and entanglement

The circuit model

Everything so far fits one template, called the circuit model:

  1. Prepare nn qubits in ∣0⋯0⟩\ket{0\cdots0}.
  2. Apply a sequence of gates, each acting on one or two (occasionally three) qubits.
  3. Measure some or all qubits in the computational basis.
  4. 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 (∣000⟩+∣111⟩)/2(\ket{000} + \ket{111})/\sqrt2:

Quantum circuit on 3 wires (q0, q1, q2). step 1: H on q0. step 2: CNOT, control q0, target q1. step 3: CNOT, control q1, target q2. step 4: measure q0; measure q1; measure q2.q0q1q2H
Preparing a three-qubit GHZ state

By hand: HH gives (∣000⟩+∣100⟩)/2(\ket{000} + \ket{100})/\sqrt2; the first CX flips qubit 1 on the second branch, giving (∣000⟩+∣110⟩)/2(\ket{000} + \ket{110})/\sqrt2; the second CX flips qubit 2 where qubit 1 is 1, giving (∣000⟩+∣111⟩)/2(\ket{000} + \ket{111})/\sqrt2. Measuring yields 000 or 111, each with probability 1/21/2.

Simulating a circuit with a state vector

A state-vector simulator stores all 2n2^n amplitudes and updates them gate by gate. The naive way to apply a gate UU on qubit qq is to build the full 2n×2n2^n\times2^n matrix I⊗⋯⊗U⊗⋯⊗II\otimes\cdots\otimes U\otimes\cdots\otimes I and multiply. That costs 4n4^n 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 ∣q0q1…qn−1⟩\ket{q_0q_1\dots q_{n-1}} sits at index ∑jqj2n−1−j\sum_j q_j 2^{n-1-j}. That is exactly how NumPy lays out an array of shape (2,2,…,2)(2, 2, \dots, 2) in memory, so psi.reshape((2,) * n) gives a tensor ψq0q1…qn−1\psi_{q_0q_1\dots q_{n-1}} whose axis jj is qubit jj. No data is copied.

A single-qubit gate is a contraction on one axis. Applying UU to qubit qq means

ψ…qq′…′=∑qqUqq′qq ψ…qq…,\psi'_{\dots q_q'\dots} = \sum_{q_q} U_{q_q' q_q}\, \psi_{\dots q_q\dots},

with every other index untouched. A two-qubit gate is a 4×44\times4 matrix; reshaped to shape (2,2,2,2)(2,2,2,2) 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 kk-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 2×22\times2 matrix: about 2n+12^{n+1} complex multiplications. A two-qubit gate costs about 2n+22^{n+2}. A circuit with GG gates therefore costs on the order of G⋅2nG\cdot2^n 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 nn qubits needs

M(n)=16⋅2n bytes.M(n) = 16\cdot 2^n \text{ bytes}.
Qubits nn M(n)M(n) Roughly
20 16,777,216 bytes 16 MiB: trivial
30 17,179,869,184 bytes 16 GiB: a well-equipped laptop
40 about 1.76×10131.76\times10^{13} bytes 16 TiB: a large cluster
50 about 1.80×10161.80\times10^{16} 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 HH, SS 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 nn qubits requires 2n2^n 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 p(1−p)/N\sqrt{p(1-p)/N} 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: HH on every qubit, then kk repetitions of an oracle that flips the sign of the amplitudes of the "marked" basis states, followed by a diffusion step H⊗nH^{\otimes n}, sign flip of all amplitudes except ∣0⋯0⟩\ket{0\cdots0}, H⊗nH^{\otimes n}. With MM marked states among N=2nN = 2^n, the probability of measuring a marked state after kk repetitions is sin⁡2((2k+1)θ)\sin^2\big((2k+1)\theta\big) with sin⁡θ=M/N\sin\theta = \sqrt{M/N}; this closed form is a theorem proved in the references the product cites. For n=3n = 3, one marked state and k=2k = 2: sin⁡θ=1/8\sin\theta = 1/\sqrt8, and the success probability is 121/128=0.9453125121/128 = 0.9453125.

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 k=2k = 2 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 (≈0.007\approx0.007) 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 10−910^{-9}. 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 jj is qubit jj 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.tensordot puts the new axes first; move them back to the target positions, or the next gate acts on the wrong qubit.
  • Building full matrices. numpy.kron with 2n×2n2^n\times2^n 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 ∣0⋯0⟩\ket{0\cdots0}, apply gates, measure, repeat; size is measured by width, depth and gate count.
  • A state-vector simulator reshapes 2n2^n amplitudes into an nn-axis tensor and contracts gates with one or two axes at a time, costing about G⋅2nG\cdot2^n operations.
  • Memory is 16⋅2n16\cdot2^n 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-search product.

Next, Introductory quantum algorithms uses circuits like these to beat classical query bounds, and to teleport a qubit.

Exercises

Run these on your own computer. Each comes with automated checks: python -m pytest test_exercise.py. Nothing you write is sent to KetQat.

Build a state-vector simulator and check it against the KetQat SDK

intermediate · about 1 h · needs numpy, ketqat[algorithms]

You will write a small but genuine state-vector simulator: it applies gates on any subset of qubits by reshaping the state, never by building a 2n×2n2^n\times2^n matrix. You then use it to run Grover's search on a few qubits and compare the success probability with the open-source KetQat SDK's grover-search product, an independent implementation.

Ordering convention. Qubit 0 is the most significant bit: the amplitude of ∣q0q1…qn−1⟩\ket{q_0q_1\dots q_{n-1}} is at index ∑jqj2 n−1−j\sum_j q_j 2^{\,n-1-j}, and state.reshape((2,) * n) puts qubit jj on axis jj. Bitstrings are written with qubit 0 on the left. A kk-qubit gate acting on targets = [t0, t1, ...] uses the same convention internally: t0 is the most significant bit of the gate's index. (The SDK's Grover product also prints bitstrings most significant qubit first.)

Functions to implement (in starter.py)

Function Contract
zero_state(n) The complex vector ∣0⋯0⟩\ket{0\cdots0} of length 2n2^n.
apply_gate(state, gate, targets) Return a new state with the 2k×2k2^k\times2^k unitary gate applied to the qubits listed in targets (distinct, any order). Use reshape + numpy.tensordot or numpy.einsum; do not build the full 2n×2n2^n\times2^n matrix.
probabilities(state) Outcome probabilities ∣ψx∣2\abs{\psi_x}^2 as a real array.
sample_counts(state, shots, seed) A dict from bitstring (qubit 0 first, e.g. "011") to count, containing only non-zero counts. Use rng = numpy.random.default_rng(seed) and rng.multinomial(shots, probabilities(state)).
memory_bytes(n) Bytes needed to store an nn-qubit state in complex128: 16⋅2n16\cdot2^n, as a Python int.
grover_success_probability(n, marked, iterations) Run Grover's search with your simulator: HH on every qubit, then iterations times [oracle: multiply the amplitudes of the marked basis states by −1-1; diffusion: HH on every qubit, multiply every amplitude except that of ∣0⋯0⟩\ket{0\cdots0} by −1-1, HH on every qubit]. Return the total probability of the marked states.

The oracle and the "flip all but ∣0⋯0⟩\ket{0\cdots0}" step are diagonal, so you may apply them by multiplying the state vector element-wise; every HH must go through apply_gate.

What the checks verify

  • apply_gate agrees with the full Kronecker-product matrix (built independently in the test) for random one-, two- and three-qubit unitaries on random targets of a 5-qubit random state, including targets given in decreasing order.
  • A Hadamard and a chain of CX gates produce the GHZ state (∣000⟩+∣111⟩)/2(\ket{000}+\ket{111})/\sqrt2, and its counts contain only "000" and "111".
  • sample_counts is reproducible for a fixed seed and its counts sum to shots.
  • memory_bytes matches 16⋅2n16\cdot2^n (e.g. 16 GiB at n=30n=30).
  • grover_success_probability matches the analytic value sin⁡2((2k+1)θ)\sin^2\big((2k+1)\theta\big), sin⁡θ=M/N\sin\theta = \sqrt{M/N}, and the success_probability reported by catalog.run("[email protected]", ...) from the KetQat SDK, to 10−910^{-9}.

Run the checks

python -m pip install numpy "ketqat[algorithms] @ git+https://github.com/ketqat/ketqat-sdk@2cedabbd814fd199b1989c8ceb1e9efa1744c2c0#subdirectory=python"
python -m pytest test_exercise.py

The SDK writes a small run record for every product run under $KETQAT_HOME (default ~/.ketqat). The test points KETQAT_HOME at a temporary directory, so nothing is left behind.

Terminal
python -m pip install numpy "ketqat[algorithms]"

starter.py

Python
"""A small state-vector simulator (KetQat Commons, Foundations).

Ordering: qubit 0 is the most significant bit; state.reshape((2,) * n) puts qubit j on axis j.
"""
import numpy as np

H = np.array([[1, 1], [1, -1]], dtype=complex) / np.sqrt(2)


def zero_state(n):
    """Return |0...0> on n qubits as a complex vector of length 2**n."""
    raise NotImplementedError


def apply_gate(state, gate, targets):
    """Return a new state with the 2^k x 2^k gate applied to the qubits in targets (targets[0] = gate MSB)."""
    raise NotImplementedError


def probabilities(state):
    """Return |amplitude|^2 for every basis state."""
    raise NotImplementedError


def sample_counts(state, shots, seed):
    """Return {bitstring: count} (qubit 0 leftmost, non-zero counts only) from rng.multinomial."""
    raise NotImplementedError


def memory_bytes(n):
    """Return 16 * 2**n, the bytes of an n-qubit complex128 state vector."""
    raise NotImplementedError


def grover_success_probability(n, marked, iterations):
    """Run Grover search with this simulator and return the total probability of the marked states."""
    raise NotImplementedError

test_exercise.py

Python
"""Checks for the statevector-simulator exercise. Run: python -m pytest test_exercise.py"""
import importlib.util
import os
from pathlib import Path

def _load_target():
    name = os.environ.get("KETQAT_COMMONS_TARGET", "starter")
    path = Path(__file__).with_name(f"{name}.py")
    spec = importlib.util.spec_from_file_location(f"{Path(__file__).parent.name}_{name}", path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

target = _load_target()

from functools import reduce

import numpy as np
import pytest

RNG = np.random.default_rng(42)
H = np.array([[1, 1], [1, -1]]) / np.sqrt(2)
CX = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])


@pytest.fixture(autouse=True)
def _isolated_ketqat_home(tmp_path, monkeypatch):
    monkeypatch.setenv("KETQAT_HOME", str(tmp_path / "ketqat-home"))


def _random_unitary(d):
    m = RNG.normal(size=(d, d)) + 1j * RNG.normal(size=(d, d))
    q, r = np.linalg.qr(m)
    return q * (np.diag(r) / abs(np.diag(r)))


def _full_matrix(gate, targets, n):
    """Independent construction: permute qubits so targets come first, kron with identity, permute back."""
    k = len(targets)
    rest = [q for q in range(n) if q not in targets]
    order = list(targets) + rest
    big = np.kron(gate, np.eye(2 ** (n - k)))
    # P maps the original basis index to the permuted one.
    dim = 2 ** n
    P = np.zeros((dim, dim))
    for i in range(dim):
        bits = [(i >> (n - 1 - q)) & 1 for q in range(n)]
        j = reduce(lambda acc, b: 2 * acc + b, [bits[q] for q in order], 0)
        P[j, i] = 1
    return P.T @ big @ P


def test_zero_state():
    s = target.zero_state(3)
    assert s.shape == (8,) and s[0] == 1 and np.count_nonzero(s) == 1


@pytest.mark.parametrize("targets", [[0], [4], [2], [0, 1], [3, 1], [4, 0], [2, 0, 3], [4, 3, 1]])
def test_apply_gate_matches_full_matrix(targets):
    n = 5
    psi = RNG.normal(size=2 ** n) + 1j * RNG.normal(size=2 ** n)
    psi /= np.linalg.norm(psi)
    gate = _random_unitary(2 ** len(targets))
    expected = _full_matrix(gate, targets, n) @ psi
    got = target.apply_gate(psi.copy(), gate, targets)
    assert np.allclose(got, expected)


def test_ordering_convention():
    X = np.array([[0, 1], [1, 0]])
    s = target.apply_gate(target.zero_state(3), X, [0])
    assert np.isclose(abs(s[4]), 1)  # |100> is index 4
    s = target.apply_gate(target.apply_gate(target.zero_state(2), X, [1]), CX, [1, 0])  # control q1, target q0
    assert np.isclose(abs(s[3]), 1)  # |01> -> |11>


def test_ghz_and_counts():
    s = target.apply_gate(target.zero_state(3), H, [0])
    s = target.apply_gate(s, CX, [0, 1])
    s = target.apply_gate(s, CX, [1, 2])
    assert np.allclose(s, np.array([1, 0, 0, 0, 0, 0, 0, 1]) / np.sqrt(2))
    assert np.allclose(target.probabilities(s).sum(), 1)
    counts = target.sample_counts(s, 1000, seed=3)
    assert set(counts) <= {"000", "111"} and sum(counts.values()) == 1000
    assert counts == target.sample_counts(s, 1000, seed=3)


def test_memory_bytes():
    assert target.memory_bytes(1) == 32
    assert target.memory_bytes(30) == 16 * 1024 ** 3
    assert target.memory_bytes(40) == 16 * 1024 ** 4


@pytest.mark.parametrize("n, marked, k", [(3, [5], 2), (4, [3, 12], 1), (4, [3, 12], 3), (5, [3, 17], 3), (6, [0], 6)])
def test_grover_matches_analytic_value(n, marked, k):
    theta = np.arcsin(np.sqrt(len(marked) / 2 ** n))
    assert np.isclose(target.grover_success_probability(n, marked, k), np.sin((2 * k + 1) * theta) ** 2)


@pytest.mark.parametrize("n, marked, k", [(3, [5], 2), (4, [6], 2), (5, [3, 17], 3), (6, [1, 2, 40], 4)])
def test_grover_matches_ketqat_sdk(n, marked, k):
    from ketqat_runner import catalog

    record = catalog.run("[email protected]", seed=1, n_qubits=n, marked=marked, iterations=k, shots=10)
    assert record.status == "succeeded"
    assert record.result["iterations"] == k
    assert abs(target.grover_success_probability(n, marked, k) - record.result["success_probability"]) < 1e-9

Check your understanding

6 questions. Pass with 70% of the points. Answers are checked on the server; retakes are allowed. Explanations appear once you pass or after three complete attempts.

  1. How much memory, in GiB (2302^{30} bytes), does a complex128 state vector of 34 qubits occupy?

    1 pt
  2. A 5-qubit GHZ state is prepared by HH on qubit 0 followed by the chain CX0→1,CX1→2,CX2→3,CX3→4\mathrm{CX}_{0\to1}, \mathrm{CX}_{1\to2}, \mathrm{CX}_{2\to3}, \mathrm{CX}_{3\to4}, applied in that order. What is the depth of this circuit (not counting measurements)?

    1 pt
  3. With this course's convention, psi.reshape((2,) * n) turns an nn-qubit state into a tensor. Which axis belongs to qubit 0?

    1 pt
  4. Run your grover_success_probability(4, [6], 2) from the exercise. Enter the result.

    1 pt

    Computed by running exercise “statevector-simulator” on your computer.

  5. You want to check your simulator against another implementation on the same circuit. What is the most informative comparison?

    1 pt
  6. Select every true statement.

    1 pt

    Select all that apply.

Sign in with GitHub to check answers and save progress. Reading stays free without an account.

References

  1. Michael A. Nielsen, Isaac L. Chuang (2010). Quantum Computation and Quantum Information (10th Anniversary Edition). Cambridge University Press. doi:10.1017/CBO9780511976667