Skip to main content
KetQat

Appearance

Lesson 755 min

Introductory quantum algorithms

Deutsch–Jozsa, Bernstein–Vazirani and teleportation: what they compute and what they do not prove.

After this lesson you can

  • Define the query model precisely, including bit oracles, phase oracles and what is counted
  • Derive phase kickback and use it to turn a bit oracle into a phase oracle
  • Execute and analyse the Deutsch–Jozsa and Bernstein–Vazirani algorithms and compare their query counts with deterministic and bounded-error classical algorithms
  • Explain why these results are oracle (query) separations and not practical speed-ups
  • Derive the teleportation protocol and show, by computing Bob's state before the classical bits arrive, that it does not transmit information faster than light
  • Verify a hand simulation of teleportation against the KetQat SDK quantum-teleportation product

Read first: Quantum circuits and simulation

The query model

The first quantum algorithms were not designed to factor numbers or simulate molecules. They were designed to answer a cleaner question: can a quantum computer learn a property of a black-box function with fewer evaluations than any classical computer? To make "fewer" precise we fix a model.

A function f:{0,1}n→{0,1}f:\{0,1\}^n\to\{0,1\} is available only through an oracle, a gate we may apply but not look inside. Because gates must be reversible, the oracle writes f(x)f(x) into an extra target qubit instead of overwriting the input:

Uf∣x⟩∣y⟩=∣x⟩∣y⊕f(x)⟩.U_f\ket{x}\ket{y} = \ket{x}\ket{y\oplus f(x)} .

This bit oracle permutes basis states, so it is unitary. The cost of an algorithm is its number of queries, i.e. applications of UfU_f. Everything else (other gates, classical processing, the time to build UfU_f) is not counted. The classical counterpart may evaluate ff on inputs of its choice, and each evaluation is one query. We compare query counts, and we must also say what kind of classical algorithm we compare with: deterministic and always correct, or randomised with bounded error (correct with probability at least, say, 2/3). Background: Nielsen and Chuang, Sections 1.4 and 6.1.

Phase kickback

Set the target to ∣−⟩=(∣0⟩−∣1⟩)/2\ket- = (\ket0 - \ket1)/\sqrt2. If f(x)=0f(x) = 0 nothing happens. If f(x)=1f(x) = 1 the target becomes (∣1⟩−∣0⟩)/2=−∣−⟩(\ket1 - \ket0)/\sqrt2 = -\ket-. Either way,

Uf∣x⟩∣−⟩=(−1)f(x)∣x⟩∣−⟩.U_f\ket{x}\ket{-} = (-1)^{f(x)}\ket{x}\ket{-}.

The target is unchanged and the value of ff has been "kicked back" as a sign on the input register. Discarding the target, one query implements the phase oracle Of∣x⟩=(−1)f(x)∣x⟩O_f\ket x = (-1)^{f(x)}\ket x. On a superposition of inputs, the phase oracle marks every term with its own sign in a single query; interference then turns these signs into a measurable answer. Kickback is also why controlled gates make global phases matter: a phase that is global for the target becomes a relative phase on the control.

A tool: Hadamards on nn qubits

For a basis state ∣x⟩\ket x on nn qubits,

H⊗n∣x⟩=12n∑z∈{0,1}n(−1)x⋅z∣z⟩,x⋅z=∑ixizi mod 2.H^{\otimes n}\ket{x} = \frac{1}{\sqrt{2^n}}\sum_{z\in\{0,1\}^n}(-1)^{x\cdot z}\ket z, \qquad x\cdot z = \sum_i x_i z_i \bmod 2 .

For one qubit this is H∣x⟩=(∣0⟩+(−1)x∣1⟩)/2H\ket x = (\ket0 + (-1)^x\ket1)/\sqrt2; the general case is the tensor product of nn such factors. In particular H⊗n∣0n⟩H^{\otimes n}\ket{0^n} is the uniform superposition, and the amplitude of ∣0n⟩\ket{0^n} in H⊗n∣ϕ⟩H^{\otimes n}\ket\phi is the uniform average of the amplitudes of ∣ϕ⟩\ket\phi, scaled by 2n\sqrt{2^n}.

Deutsch–Jozsa

Problem (a promise problem). We are promised that ff is either constant (the same value on all 2n2^n inputs) or balanced (0 on exactly half of the inputs, 1 on the other half). Decide which.

Algorithm. Apply H⊗nH^{\otimes n} to ∣0n⟩\ket{0^n}, query the phase oracle once, apply H⊗nH^{\otimes n} again, and measure.

Quantum circuit on 3 wires (x0, x1, x2). step 1: H on x0; H on x1; H on x2. step 2: O_f on x0, x1, x2. step 3: H on x0; H on x1; H on x2. step 4: measure x0; measure x1; measure x2.x0x1x2HHHO_fHHH
Deutsch–Jozsa on three input qubits (phase-oracle form)

Analysis. After the first layer and the oracle the state is 2−n/2∑x(−1)f(x)∣x⟩2^{-n/2}\sum_x(-1)^{f(x)}\ket x. By the Hadamard identity, the amplitude of ∣0n⟩\ket{0^n} after the second layer is

a0=12n∑x(−1)f(x).a_0 = \frac{1}{2^n}\sum_{x}(-1)^{f(x)} .

If ff is constant, every term has the same sign and ∣a0∣=1\abs{a_0} = 1: the outcome is 0n0^n with certainty. If ff is balanced, half the terms are +1+1 and half −1-1, so a0=0a_0 = 0: the outcome is never 0n0^n. So one query decides the problem with certainty. This is the algorithm of Deutsch and Jozsa (1992) in the improved single-query form of Cleve, Ekert, Macchiavello and Mosca (1998).

Classical comparison, stated carefully.

  • Deterministic, always correct: 2n−1+12^{n-1} + 1 queries are necessary and sufficient in the worst case. Sufficient: among 2n−1+12^{n-1}+1 distinct inputs a balanced function must show both values. Necessary: an adversary can answer 0 to the first 2n−12^{n-1} queries, and then both the constant-0 function and a balanced function that is 0 exactly on the queried inputs are still possible. The exercise confirms both halves by brute force for n=2,3n = 2, 3.
  • Randomised, bounded error: query kk independent uniformly random inputs and answer "constant" if all values agree. A constant function is never misclassified; a balanced one gives all-equal answers with probability 2⋅2−k=21−k2\cdot2^{-k} = 2^{1-k}. Two queries already give error at most 1/21/2, and ten give error below 0.0020.002, independently of nn.

So the exponential gap (1 query versus 2n−1+12^{n-1}+1) holds only against exact deterministic classical algorithms. Against randomised algorithms that may err with small probability, the advantage is a constant number of queries.

Worked example

Take n=3n = 3 and ff equal to 1 only on input 011011. This ff is neither constant nor balanced, so the promise fails, but the formula still applies: a0=(7−1)/8=3/4a_0 = (7 - 1)/8 = 3/4 and the probability of measuring 000000 is 9/16=0.56259/16 = 0.5625. With the promise in force the outcome is always 0 or 1, never in between.

Bernstein–Vazirani

Problem. f(x)=s⋅x mod 2f(x) = s\cdot x \bmod 2 for an unknown string s∈{0,1}ns\in\{0,1\}^n. Find ss.

Algorithm. The same circuit as Deutsch–Jozsa. After the oracle the state is 2−n/2∑x(−1)s⋅x∣x⟩=H⊗n∣s⟩2^{-n/2}\sum_x(-1)^{s\cdot x}\ket x = H^{\otimes n}\ket s, so the final H⊗nH^{\otimes n} (which is its own inverse) returns exactly ∣s⟩\ket s. One query reveals all nn bits of ss with certainty (Bernstein and Vazirani, 1997).

Classical comparison. Each classical query returns one bit, and ss is one of 2n2^n possibilities. A deterministic algorithm needs exactly nn queries (querying the unit vectors eie_i returns sis_i; with fewer than nn answers at least two strings remain consistent). A randomised algorithm that succeeds with probability at least 2/3 still needs Ω(n)\Omega(n) queries, by an information-counting argument. The gap is therefore 11 versus Θ(n)\Theta(n): a linear separation, not an exponential one. (Bernstein and Vazirani also defined a recursive version of the problem with a larger gap; we do not cover it.)

import numpy as np
from functools import reduce

n = 3
H = np.array([[1, 1], [1, -1]]) / np.sqrt(2)
Hn = reduce(np.kron, [H] * n)
zero = np.eye(2 ** n)[0]

def dj_p_zero(f_values):
    oracle = np.diag([(-1.0) ** v for v in f_values])     # phase oracle from kickback
    return abs((Hn @ oracle @ Hn @ zero)[0]) ** 2

print(round(dj_p_zero([1, 1, 1, 1, 1, 1, 1, 1]), 12))     # constant: 1.0
print(round(dj_p_zero([0, 1, 1, 0, 1, 0, 0, 1]), 12))     # balanced (parity): 0.0

s = 0b101                                                  # Bernstein-Vazirani with hidden s = 101
f_bv = [bin(s & x).count("1") % 2 for x in range(2 ** n)]
out = Hn @ np.diag([(-1.0) ** v for v in f_bv]) @ Hn @ zero
print(format(int(np.argmax(abs(out) ** 2)), "03b"), round(abs(out[s]) ** 2, 12))   # 101 1.0

What these results do and do not show

Deutsch–Jozsa and Bernstein–Vazirani are theorems about query complexity in an oracle model. They show that interference can extract a global property of a function from fewer evaluations than classical evaluation allows. They do not show a practical speed-up on any problem anyone needs solved, for three reasons.

  1. The oracle is assumed, not built. In practice someone must implement UfU_f as a circuit. If you are given that circuit, you can often read the answer off it classically: for Bernstein–Vazirani, a circuit computing s⋅xs\cdot x essentially contains ss.
  2. The classical baseline matters. The Deutsch–Jozsa gap disappears (up to a constant) against randomised classical algorithms with small error.
  3. Query counts are not running time. Real cost includes gates, error correction and the classical control around them.

Their value is conceptual: they are the smallest complete examples of the pattern "superpose, query in phase, interfere", which reappears in Simon's algorithm, phase estimation and Shor's algorithm (the Algorithms course covers these, with their own precise conditions).

Quantum teleportation

Teleportation answers a different question: Alice holds a qubit in an unknown state ∣ψ⟩=α∣0⟩+β∣1⟩\ket\psi = \alpha\ket0 + \beta\ket1, and Alice and Bob share one Bell pair ∣Φ+⟩\ket{\Phi^+}. Using only local operations and two classical bits, can Bob end up holding ∣ψ⟩\ket\psi? Yes (Bennett et al., 1993); the protocol was first demonstrated with photons by Bouwmeester et al. (1997).

Quantum circuit on 3 wires (q0, q1, q2). step 1: H on q1. step 2: CNOT, control q1, target q2. step 3: barrier. step 4: CNOT, control q0, target q1. step 5: H on q0. step 6: measure q0; measure q1. step 7: Pauli fix on q2.q0q1q2HHPauli fix
Teleportation: q0 is the message, q1 and q2 share |Φ+⟩; after Alice measures, Bob applies X if m1 = 1, then Z if m0 = 1

The first two gates prepare the Bell pair (in practice it is distributed in advance). Derivation. Write the three-qubit state as (α∣0⟩+β∣1⟩)⊗(∣00⟩+∣11⟩)/2(\alpha\ket0 + \beta\ket1)\otimes(\ket{00} + \ket{11})/\sqrt2. Alice's CX from qubit 0 to qubit 1 gives

12[α∣0⟩(∣00⟩+∣11⟩)+β∣1⟩(∣10⟩+∣01⟩)],\tfrac{1}{\sqrt2}\big[\alpha\ket0(\ket{00} + \ket{11}) + \beta\ket1(\ket{10} + \ket{01})\big],

and her HH on qubit 0 gives, after regrouping by the values m0m1m_0m_1 of her two qubits,

12[∣00⟩(α∣0⟩+β∣1⟩)+∣01⟩(α∣1⟩+β∣0⟩)+∣10⟩(α∣0⟩−β∣1⟩)+∣11⟩(α∣1⟩−β∣0⟩)].\tfrac12\Big[\ket{00}(\alpha\ket0 + \beta\ket1) + \ket{01}(\alpha\ket1 + \beta\ket0) + \ket{10}(\alpha\ket0 - \beta\ket1) + \ket{11}(\alpha\ket1 - \beta\ket0)\Big].

Each of Alice's four outcomes has probability 1/41/4, whatever α\alpha and β\beta are, and leaves Bob with Xm1Zm0∣ψ⟩X^{m_1}Z^{m_0}\ket\psi. Alice sends m0m1m_0m_1 to Bob over an ordinary channel; Bob applies XX if m1=1m_1 = 1 and then ZZ if m0=1m_0 = 1, which undoes Xm1Zm0X^{m_1}Z^{m_0} exactly. His qubit is now ∣ψ⟩\ket\psi, with fidelity 1 on every branch.

What teleportation does not do.

  • It does not send information faster than light. Before the two bits arrive, Bob does not know which branch occurred, so his qubit is described by the average over branches: 14∑m0,m1Xm1Zm0∣ψ⟩⟨ψ∣Zm0Xm1=I/2\tfrac14\sum_{m_0,m_1}X^{m_1}Z^{m_0}\ketbra\psi\psi Z^{m_0}X^{m_1} = I/2 for every ∣ψ⟩\ket\psi (averaging over I,X,Z,XZI, X, Z, XZ maps every Bloch vector to the centre). Nothing Bob can measure depends on ∣ψ⟩\ket\psi until the classical message, limited by the speed of light, arrives.
  • It does not copy. Alice's qubits end in ∣m0⟩∣m1⟩\ket{m_0}\ket{m_1}, which carry no trace of α,β\alpha, \beta; the original is destroyed, consistent with no-cloning.
  • It does not move matter or energy, and it consumes a Bell pair per qubit: one shared Bell pair plus two classical bits buy one transmitted qubit.

Checking the protocol with the KetQat SDK

The SDK's quantum-teleportation product computes all four branches exactly and reports, for each, the probability, Bob's correction, and the fidelity with and without it:

from ketqat_runner import catalog

record = catalog.run("[email protected]", seed=11, theta=2.0, phi=1.0, shots=1000)
result = record.result
for branch in result["branches"]:
    print(branch["outcome"], branch["probability"], branch["correction"],
          round(branch["fidelity"], 9), round(branch["fidelity_without_correction"], 4))
print(result["average_fidelity_without_correction"], result["counts"])

For the input with Bloch angles θ=2.0\theta = 2.0, φ=1.0\varphi = 1.0 this printed (SDK commit 2cedabb, NumPy 2.5) probability 0.25 and fidelity 1.0 for all four outcomes, uncorrected fidelities 1.0, 0.2414, 0.1732 and 0.5855 for outcomes 00, 01, 10 and 11, an average uncorrected fidelity of exactly 0.5, and seeded counts 242, 276, 226 and 256. The uncorrected values have a simple explanation: on branch m0m1m_0m_1 Bob holds Xm1Zm0∣ψ⟩X^{m_1}Z^{m_0}\ket\psi, whose fidelity with ∣ψ⟩\ket\psi is the square of a Bloch component, rx2r_x^2, rz2r_z^2 or ry2r_y^2. For this input rx2=(sin⁡2cos⁡1)2≈0.2414r_x^2 = (\sin2\cos1)^2 \approx 0.2414. The exercise asks you to reproduce every one of these numbers with your own NumPy simulation and to confirm that Bob's state before the bits arrive is I/2I/2.

Common mistakes

  • Quoting "exponential speed-up" for Deutsch–Jozsa without the conditions. The gap is against exact deterministic algorithms in the query model; against bounded-error randomised algorithms it is a constant.
  • Counting the wrong thing. Query complexity counts oracle calls only.
  • Forgetting the target in ∣−⟩\ket-. With the target in ∣0⟩\ket0 the bit oracle writes f(x)f(x) into the target and entangles it with the input; no phase is kicked back.
  • Thinking teleportation is instantaneous. Bob's qubit is useless until the two classical bits arrive.
  • Applying Bob's corrections in the wrong pairing. m1m_1 (Alice's half of the pair) controls XX, m0m_0 (the message qubit) controls ZZ.

Summary

  • In the query model, cost is the number of oracle calls; phase kickback turns a bit oracle with target ∣−⟩\ket- into a phase oracle.
  • Deutsch–Jozsa: 1 query, exact, versus 2n−1+12^{n-1}+1 for deterministic exact classical algorithms but O(1)O(1) for bounded-error randomised ones.
  • Bernstein–Vazirani: 1 query versus Θ(n)\Theta(n) classical queries.
  • These are oracle separations, not practical speed-ups.
  • Teleportation transfers an unknown qubit using one Bell pair and two classical bits; Bob's state is I/2I/2 until the bits arrive, so no faster-than-light signalling.

The two exercises implement the oracle algorithms with a brute-force check of the classical bound, and teleportation checked branch by branch against the KetQat SDK. Next, Noise, limitations and modern hardware asks what happens when gates are not perfect.

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.

Phase kickback, Deutsch–Jozsa and Bernstein–Vazirani

intermediate · about 45 min · needs numpy

You will build oracles for a Boolean function f:{0,1}n→{0,1}f:\{0,1\}^n\to\{0,1\}, verify phase kickback, and run the Deutsch–Jozsa and Bernstein–Vazirani algorithms as exact state-vector computations. You will also check the classical query count that the Deutsch–Jozsa comparison refers to.

A function is given as f_values, a list of length 2n2^n with f_values[x] =f(x)= f(x), where the integer xx encodes the bitstring x0x1…xn−1x_0x_1\dots x_{n-1} with x0x_0 most significant (the course convention).

Functions to implement (in starter.py)

Function Contract
bit_oracle(f_values) The 2n+1×2n+12^{n+1}\times2^{n+1} permutation matrix Uf∣x⟩∣y⟩=∣x⟩∣y⊕f(x)⟩U_f\ket{x}\ket{y} = \ket{x}\ket{y\oplus f(x)}, with the target yy as the last (least significant) qubit.
phase_oracle(f_values) The 2n×2n2^n\times2^n diagonal matrix Of∣x⟩=(−1)f(x)∣x⟩O_f\ket x = (-1)^{f(x)}\ket x.
deutsch_jozsa(f_values) Simulate H⊗nH^{\otimes n}, OfO_f, H⊗nH^{\otimes n} on ∣0n⟩\ket{0^n}. Return (verdict, p_zero) where p_zero is the probability of measuring all zeros and verdict is "constant" if p_zero > 0.5, else "balanced".
bernstein_vazirani(s, n) Build the phase oracle of f(x)=s⋅x mod 2f(x) = s\cdot x \bmod 2, run H⊗nH^{\otimes n}, OfO_f, H⊗nH^{\otimes n} on ∣0n⟩\ket{0^n}, and return the measured string as an integer (the most probable outcome; it has probability 1).
classical_dj_worst_case_queries(n) The number of queries a deterministic classical algorithm needs in the worst case to decide constant vs balanced with certainty: 2n−1+12^{n-1}+1.

What the checks verify

  • bit_oracle is a permutation matrix, hence unitary, and with the target in ∣−⟩\ket- it acts as (−1)f(x)∣x⟩∣−⟩(-1)^{f(x)}\ket x\ket- on every input: phase kickback.
  • deutsch_jozsa answers correctly for both constant functions and all 70 balanced functions on 3 bits, with p_zero exactly 1 or 0, and for arbitrary functions p_zero equals (2−n∑x(−1)f(x))2\big(2^{-n}\sum_x(-1)^{f(x)}\big)^2, the formula derived in the lesson.
  • bernstein_vazirani recovers every hidden string ss for n=1,…,6n = 1,\dots,6.
  • For n=2n = 2 and 33 a brute-force search confirms that 2n−12^{n-1} queries can leave both a constant and a balanced function consistent with the answers, while 2n−1+12^{n-1}+1 always suffice.

Run the checks

python -m pip install numpy
python -m pytest test_exercise.py
Terminal
python -m pip install numpy

starter.py

Python
"""Phase kickback, Deutsch-Jozsa and Bernstein-Vazirani (KetQat Commons, Foundations).

f_values[x] = f(x) for x = 0 .. 2**n - 1, with x_0 the most significant bit.
"""
import numpy as np


def bit_oracle(f_values):
    """Return U_f|x>|y> = |x>|y XOR f(x)> as a 2^(n+1) x 2^(n+1) matrix (target y is the last qubit)."""
    raise NotImplementedError


def phase_oracle(f_values):
    """Return the diagonal matrix O_f|x> = (-1)^f(x) |x>."""
    raise NotImplementedError


def deutsch_jozsa(f_values):
    """Return (verdict, p_zero) from H^n O_f H^n |0^n>; verdict is "constant" if p_zero > 0.5 else "balanced"."""
    raise NotImplementedError


def bernstein_vazirani(s, n):
    """Return the integer measured after H^n O_f H^n |0^n> for f(x) = s . x mod 2."""
    raise NotImplementedError


def classical_dj_worst_case_queries(n):
    """Return the worst-case number of classical queries to decide constant vs balanced with certainty."""
    raise NotImplementedError

test_exercise.py

Python
"""Checks for the oracle-algorithms 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()

import itertools

import numpy as np
import pytest

RNG = np.random.default_rng(1992)
MINUS = np.array([1, -1]) / np.sqrt(2)


def _balanced_functions(n):
    N = 2 ** n
    for ones in itertools.combinations(range(N), N // 2):
        f = [0] * N
        for x in ones:
            f[x] = 1
        yield f


def test_bit_oracle_is_a_permutation_and_kicks_back_phase():
    for n in (1, 2, 3):
        f = list(RNG.integers(0, 2, size=2 ** n))
        U = target.bit_oracle(f)
        assert U.shape == (2 ** (n + 1),) * 2
        assert np.allclose(U @ U.T, np.eye(2 ** (n + 1))) and set(np.unique(U)) <= {0, 1}
        for x in range(2 ** n):
            ket_x = np.eye(2 ** n)[x]
            out = U @ np.kron(ket_x, MINUS)
            assert np.allclose(out, (-1) ** f[x] * np.kron(ket_x, MINUS))
            # on |x>|0> it writes f(x) into the target
            assert np.allclose(U @ np.kron(ket_x, [1, 0]), np.kron(ket_x, np.eye(2)[f[x]]))


def test_phase_oracle_matches_kickback():
    f = [0, 1, 1, 0, 1, 0, 0, 0]
    assert np.allclose(np.diag(target.phase_oracle(f)), [1, -1, -1, 1, -1, 1, 1, 1])


def test_deutsch_jozsa_on_all_three_bit_promise_functions():
    for f in ([0] * 8, [1] * 8):
        verdict, p = target.deutsch_jozsa(f)
        assert verdict == "constant" and np.isclose(p, 1)
    count = 0
    for f in _balanced_functions(3):
        verdict, p = target.deutsch_jozsa(f)
        assert verdict == "balanced" and np.isclose(p, 0, atol=1e-12)
        count += 1
    assert count == 70


def test_deutsch_jozsa_probability_formula_for_any_function():
    for n in (1, 2, 3, 4):
        for _ in range(10):
            f = list(RNG.integers(0, 2, size=2 ** n))
            expected = (sum((-1) ** v for v in f) / 2 ** n) ** 2
            assert np.isclose(target.deutsch_jozsa(f)[1], expected)


@pytest.mark.parametrize("n", [1, 2, 3, 4, 5, 6])
def test_bernstein_vazirani_recovers_every_string(n):
    for s in range(2 ** n):
        assert target.bernstein_vazirani(s, n) == s


@pytest.mark.parametrize("n", [2, 3])
def test_classical_worst_case_query_count(n):
    q = target.classical_dj_worst_case_queries(n)
    N = 2 ** n
    balanced = list(_balanced_functions(n))
    # An adversary answers 0 to every query. After q - 1 = N/2 queries (any set of inputs),
    # the constant-0 function and some balanced function are both still consistent.
    for queried in itertools.combinations(range(N), q - 1):
        assert any(all(f[x] == 0 for x in queried) for f in balanced)
    # After q = N/2 + 1 queries no balanced function can answer 0 everywhere, so the answers decide.
    for queried in itertools.combinations(range(N), q):
        assert not any(all(f[x] == 0 for x in queried) for f in balanced)

Teleportation by hand, checked against the KetQat SDK

intermediate · about 45 min · needs numpy, ketqat[algorithms]

You will simulate the teleportation protocol branch by branch with NumPy, compute what Bob holds before and after his correction, and compare every number with the KetQat SDK's quantum-teleportation product. You will also compute Bob's state before the two classical bits reach him, which is the calculation behind "teleportation does not send information faster than light".

Setup and labels

Three qubits in the course convention (qubit 0 most significant):

  • qubit 0: the message ∣ψ⟩=cos⁡θ2∣0⟩+eiφsin⁡θ2∣1⟩\ket\psi = \cos\frac\theta2\ket0 + e^{i\varphi}\sin\frac\theta2\ket1 (Alice);
  • qubit 1: Alice's half of ∣Φ+⟩\ket{\Phi^+};
  • qubit 2: Bob's half of ∣Φ+⟩\ket{\Phi^+}.

Alice applies CX0→1\mathrm{CX}_{0\to1}, then HH on qubit 0, then measures qubits 0 and 1, obtaining bits m0m_0 (qubit 0) and m1m_1 (qubit 1). The outcome label is the string f"{m0}{m1}". Bob applies XX if m1=1m_1 = 1, then ZZ if m0=1m_0 = 1.

The SDK product uses the same physical roles and the same outcome labels ("m0 is the message qubit's bit, m1 is Alice's half"); internally it stores amplitudes little-endian, which does not affect any number you compare.

Functions to implement (in starter.py)

Function Contract
message_state(theta, phi) The length-2 complex vector of ∣ψ⟩\ket\psi.
alice_final_state(theta, phi) The 8-component state after Alice's CX and HH, before measurement.
teleport_branches(theta, phi) A dict from outcome "00", "01", "10", "11" to a dict with keys probability, fidelity (with ∣ψ⟩\ket\psi after Bob's correction) and fidelity_without_correction. Fidelity of Bob's pure state ∣χ⟩\ket\chi is ∣⟨ψ∣χ⟩∣2\abs{\braket{\psi}{\chi}}^2.
bob_density_matrix_before_bits(theta, phi) Bob's 2×22\times2 reduced density matrix after Alice has measured, averaged over her outcomes (Bob does not yet know them), i.e. ∑kPr⁡[k] ∣χk⟩⟨χk∣\sum_k \Pr[k]\,\ketbra{\chi_k}{\chi_k} with the uncorrected branch states ∣χk⟩\ket{\chi_k}.

What the checks verify

  • Every outcome has probability exactly 1/41/4 and fidelity 1 after correction, for random inputs and the six axis states.
  • Without correction, the probability-weighted fidelity is exactly 1/21/2.
  • Your per-branch probabilities and uncorrected fidelities agree with catalog.run("[email protected]", theta=..., phi=...) to 10−910^{-9} for several inputs (the product computes them with its own simulator).
  • Bob's state before the bits arrive is I/2I/2 for every input: his local statistics carry no information about ∣ψ⟩\ket\psi.

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 test points KETQAT_HOME at a temporary directory, so SDK run records are not left in your home directory.

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

starter.py

Python
"""Teleportation by hand, checked against the KetQat SDK (KetQat Commons, Foundations).

Qubit 0: message, qubit 1: Alice's half of |Phi+>, qubit 2: Bob's half. Qubit 0 is the most significant bit.
"""
import numpy as np

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


def message_state(theta, phi):
    """Return cos(theta/2)|0> + e^{i phi} sin(theta/2)|1>."""
    raise NotImplementedError


def alice_final_state(theta, phi):
    """Return the 3-qubit state after CX(0->1) and H on qubit 0, applied to |psi> (x) |Phi+>."""
    raise NotImplementedError


def teleport_branches(theta, phi):
    """Return {"m0m1": {"probability", "fidelity", "fidelity_without_correction"}} for the four outcomes."""
    raise NotImplementedError


def bob_density_matrix_before_bits(theta, phi):
    """Return Bob's 2x2 density matrix averaged over Alice's outcomes, before any correction."""
    raise NotImplementedError

test_exercise.py

Python
"""Checks for the teleportation-check 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()

import numpy as np
import pytest

RNG = np.random.default_rng(1993)
AXIS_STATES = [(0, 0), (np.pi, 0), (np.pi / 2, 0), (np.pi / 2, np.pi), (np.pi / 2, np.pi / 2), (np.pi / 2, 3 * np.pi / 2)]


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


def _inputs():
    return AXIS_STATES + [(RNG.uniform(0, np.pi), RNG.uniform(0, 2 * np.pi)) for _ in range(30)]


def test_message_state_is_normalised_bloch_form():
    psi = target.message_state(1.0, 0.5)
    assert np.allclose(psi, [np.cos(0.5), np.exp(0.5j) * np.sin(0.5)])


def test_alice_state_is_a_normalised_three_qubit_state():
    for theta, phi in _inputs():
        state = target.alice_final_state(theta, phi)
        assert state.shape == (8,) and np.isclose(np.linalg.norm(state), 1)


def test_every_branch_has_probability_quarter_and_unit_fidelity():
    for theta, phi in _inputs():
        branches = target.teleport_branches(theta, phi)
        assert sorted(branches) == ["00", "01", "10", "11"]
        for b in branches.values():
            assert np.isclose(b["probability"], 0.25)
            assert np.isclose(b["fidelity"], 1.0)


def test_without_correction_the_average_fidelity_is_one_half():
    # Analytic: sum_k (1/4) |<psi|P_k|psi>|^2 over P_k in {I, X, Z, XZ} = (1 + x^2 + y^2 + z^2) / 4 = 1/2.
    for theta, phi in _inputs():
        branches = target.teleport_branches(theta, phi)
        avg = sum(b["probability"] * b["fidelity_without_correction"] for b in branches.values())
        assert np.isclose(avg, 0.5)


@pytest.mark.parametrize("theta, phi", [(1.0, 0.5), (0.3, 4.0), (2.5, 1.2), (np.pi / 2, 0.0)])
def test_branches_agree_with_ketqat_sdk(theta, phi):
    from ketqat_runner import catalog

    record = catalog.run("[email protected]", seed=7, theta=theta, phi=phi, shots=100)
    assert record.status == "succeeded"
    sdk = {b["outcome"]: b for b in record.result["branches"]}
    mine = target.teleport_branches(theta, phi)
    for outcome in ("00", "01", "10", "11"):
        assert abs(mine[outcome]["probability"] - sdk[outcome]["probability"]) < 1e-9
        assert abs(mine[outcome]["fidelity"] - sdk[outcome]["fidelity"]) < 1e-9
        assert abs(mine[outcome]["fidelity_without_correction"] - sdk[outcome]["fidelity_without_correction"]) < 1e-9


def test_bob_learns_nothing_before_the_bits_arrive():
    for theta, phi in _inputs():
        rho = target.bob_density_matrix_before_bits(theta, phi)
        assert np.allclose(rho, np.eye(2) / 2)

Check your understanding

8 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. A bit oracle Uf∣x⟩∣y⟩=∣x⟩∣y⊕f(x)⟩U_f\ket x\ket y = \ket x\ket{y\oplus f(x)} is applied to ∣x⟩∣−⟩\ket x\ket-. What is the result?

    1 pt
  2. For n=4n = 4 input bits, how many queries does a deterministic classical algorithm need in the worst case to decide, with certainty, whether a promised constant-or-balanced function is constant or balanced?

    1 pt
  3. A randomised classical algorithm for Deutsch–Jozsa queries k=5k = 5 independent, uniformly random inputs and answers "constant" if all five values agree. If ff is balanced, what is the probability that it answers wrongly?

    1 pt
  4. Run deutsch_jozsa([0, 0, 0, 1, 0, 0, 0, 0]) with your exercise code. Enter p_zero.

    1 pt

    Computed by running exercise “oracle-algorithms” on your computer.

  5. Which statement about Deutsch–Jozsa is accurate?

    1 pt
  6. How do quantum and classical query counts compare for Bernstein–Vazirani with an nn-bit hidden string?

    1 pt
  7. With your teleport_branches(1.0, 0.5) from the teleportation exercise, what is the fidelity_without_correction of outcome "10"?

    1 pt

    Computed by running exercise “teleportation-check” on your computer.

  8. Select every true statement about teleportation.

    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
  2. David Deutsch, Richard Jozsa (1992). Rapid solution of problems by quantum computation. Proceedings of the Royal Society of London A 439, 553-558. doi:10.1098/rspa.1992.0167
  3. Richard Cleve et al. (1998). Quantum algorithms revisited. Proceedings of the Royal Society A 454, 339-354. doi:10.1098/rspa.1998.0164
  4. Ethan Bernstein, Umesh Vazirani (1997). Quantum complexity theory. SIAM Journal on Computing 26(5), 1411-1473. doi:10.1137/S0097539796300921
  5. Charles H. Bennett et al. (1993). Teleporting an unknown quantum state via dual classical and Einstein-Podolsky-Rosen channels. Physical Review Letters 70, 1895-1899. doi:10.1103/PhysRevLett.70.1895
  6. Dik Bouwmeester et al. (1997). Experimental quantum teleportation. Nature 390, 575-579. doi:10.1038/37539