About this notebook
Companion to Lecture 7: Formalizing quantum information. Every cell below was executed against the course’s pinned Lean 4 + Mathlib (see
lean/lean-toolchain); each Lean result is exactly what Lean printed. Download the notebook (.ipynb)
Lecture 7 builds a small quantum library, LeanFV.Quantum: states are vectors
Ket n := n → ℂ, gates are matrices, and no-cloning is proved from inner-product
preservation. This notebook uses that library. You will:
- look at the definitions and apply gates to states;
- find out what
#evalanddecidecan and cannot do over ℂ, and why; - prove Pauli identities, including one that is false;
- check the same identities with numpy, and see what “checked numerically” leaves out;
- meet the normalisation trap: the norm Mathlib puts on
Fin 2 → ℂis the wrong one; - use the no-cloning theorem, and draw the inequality at its heart.
import leanmagic
leanmagic.setup(
"import LeanFV.Quantum.NoCloning\n"
"import Mathlib.Analysis.InnerProductSpace.PiL2\n"
"import Mathlib.NumberTheory.Zsqrtd.GaussianInt"
)Lean 4.35.0 ready; header `import LeanFV.Quantum.NoCloning` elaborated.
The header loads the course’s quantum library (which itself imports only the parts of
Mathlib it needs: complex numbers, matrices, the Kronecker product, the unitary group),
plus two extras used below: EuclideanSpace for section 5 and the Gaussian integers
ℤ[i] for section 2. Full import Mathlib would also work, at about four times the start-up
cost.
1. States and gates
Every name lives in the namespace LeanFV.Quantum, so we open it once. open lasts for
this cell and every later one.
open Matrix Complex LeanFV.Quantum
open scoped Kronecker
#check ket0
#print X
#check X_mulVec_ket0✓ Lean accepted this
LeanFV.Quantum.ket0 : Ket (Fin 2)
def LeanFV.Quantum.X : Matrix (Fin 2) (Fin 2) ℂ := !![0, 1; 1, 0]
LeanFV.Quantum.X_mulVec_ket0 : X *ᵥ ket0 = ket1
X *ᵥ ket0 is matrix-times-vector (Matrix.mulVec), and the library proves it is
ket1: the bit flip. Two more of the same kind, proved the same way. ext i says “two
vectors are equal if they agree at every index”, fin_cases i splits into i = 0 and
i = 1, and simp computes each entry.
example : Z *ᵥ ket0 = ket0 := by
ext i
fin_cases i <;> simp [Z, ket0]
example : Y *ᵥ ket0 = I • ket1 := by
ext i
fin_cases i <;> simp [Y, ket0, ket1]✓ Lean accepted this (no messages)
2. What Lean can compute over ℂ
In Lecture 5 the first sanity check for a definition was #eval. Try it on X * X:
#eval X * X✓ Lean accepted this
!![Real.ofCauchy (sorry /- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ... -/) + Real.ofCauchy (sorry /- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... -/)*I, Real.ofCauchy (sorry /- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... -/) + Real.ofCauchy (sorry /- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... -/)*I; Real.ofCauchy (sorry /- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... -/) + Real.ofCauchy (sorry /- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... -/)*I, Real.ofCauchy (sorry /- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ... -/) + Real.ofCauchy (sorry /- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... -/)*I]
Lean did compute something: the identity matrix, with each entry written as
re + im*I. But each real part is printed as Real.ofCauchy (sorry /- 1, 1, 1, … -/). A
real number in Mathlib is an equivalence class of Cauchy sequences of rationals. The
printer shows the first ten terms of one sequence in the class, wrapped in
sorry /- … -/ to flag that this is not a term you could type back in (Mathlib’s source
notes that two sequences for the same number may print differently). You cannot read
off “is this 1?” from the first ten terms. Addition and multiplication of sequences
happen to be computable, so this ran at all. Division does not:
This cell is meant to fail:
#eval (1 : ℝ) / 3✗ rejected, as intended
error, line 1failed to compile definition, consider marking it as 'noncomputable' because it depends on 'Real.instDivInvMonoid', which is 'noncomputable'
noncomputable means Lean has no code to run, only a definition to reason about. Real
division, Real.sqrt and π are all like this. The same limitation stops decide,
which proves a statement by evaluating a yes/no procedure: equality of complex numbers is
decidable only classically (by the law of excluded middle), so there is nothing to
evaluate.
This cell is meant to fail:
example : X * X = 1 := by decide✗ rejected, as intended
error, line 1Tactic `decide` failed to reduce
@decide (X * X = 1) ((X * X).decidableEq 1)
to `true` or `false`.
After unfolding the instances `decidable_of_decidable_of_iff`, `decidable_of_iff`, `Classical.decEq`, `Classical.propDecidable`, `instDecidableEq`, `Finset.decidableDforallFinset`, `Fintype.decidablePiFintype`, `List.decidableBAll`, `decidableEq`, `Multiset.decidableDforallMultiset`, and `Multiset.decidableForallMultiset`, reduction got stuck at
Classical.choice ⋯
Hint: Reduction got stuck on `Classical.choice`, which indicates that a `Decidable` instance is defined using classical reasoning, proving an instance exists rather than giving a concrete construction. The `decide` tactic works by evaluating a decision procedure via reduction, and it cannot make progress with such instances. This can occur due to the `open scoped Classical` command, which enables the instance `Classical.propDecidable`.
Lean’s hint is exact: reduction “got stuck at Classical.choice”. Compare a ring where
equality is computable. The Pauli matrices only use the entries 0, ±1 and ±i, so they
live in the Gaussian integers ℤ[i], whose elements are pairs of integers ⟨a, b⟩ meaning
a + bi. There #eval prints honest values and decide works:
def Yi : Matrix (Fin 2) (Fin 2) GaussianInt := !![0, -⟨0, 1⟩; ⟨0, 1⟩, 0]
#eval Yi * Yi
example : Yi * Yi = 1 := by decide✓ Lean accepted this
!![⟨1, 0⟩, ⟨0, 0⟩; ⟨0, 0⟩, ⟨1, 0⟩]
So the rule of thumb for quantum formalization is: #eval and decide are sanity checks
you can run on an integer or Gaussian-integer copy of your matrices; statements about ℂ are
proved with simp, norm_num and ring, never by evaluation.
3. Proving Pauli identities
The library proves X * X = 1, X * Z = -(Z * X) and X * Y = I • Z. Here is
Y * Z = I • X with the same three-line pattern: rewrite the product of two explicit 2×2
matrices with Matrix.mul_fin_two, then compare entry by entry.
theorem Y_mul_Z : Y * Z = I • X := by
rw [Y, Z, X, mul_fin_two]
ext i j
fin_cases i <;> fin_cases j <;> simp✓ Lean accepted this (no messages)
Lemmas compose. X * Y * Z = i·1 follows from two library lemmas without touching a
single entry: X * Y = I • Z, then pull the scalar out (smul_mul), then Z * Z = 1.
theorem XYZ : X * Y * Z = I • 1 := by
rw [X_mul_Y, smul_mul, Z_mul_Z]✓ Lean accepted this (no messages)
Not every identity you might guess is true. The Paulis do not commute, and proving
that means finding one entry where X * Y and Y * X differ. Entry (0, 0) gives
I = -I, which forces I = 0, which is false.
theorem X_mul_Y_ne : X * Y ≠ Y * X := by
intro h
have h00 := congrFun (congrFun h 0) 0
simp [X, Y, mul_apply, Fin.sum_univ_two] at h00
exact I_ne_zero (by linear_combination h00 / 2)✓ Lean accepted this (no messages)
4. The same identities in numpy
Numerical linear algebra checks the same facts in floating point. This is how you would test a formula before trying to prove it, and it is a good habit (Lecture 5, step 3).
import numpy as np
X = np.array([[0, 1], [1, 0]], dtype=complex)
Y = np.array([[0, -1j], [1j, 0]])
Z = np.array([[1, 0], [0, -1]], dtype=complex)
I2 = np.eye(2)
print("X X = 1 :", np.allclose(X @ X, I2))
print("Y Z = i X :", np.allclose(Y @ Z, 1j * X))
print("X Y Z = i 1 :", np.allclose(X @ Y @ Z, 1j * I2))
print("X Y = Y X :", np.allclose(X @ Y, Y @ X))X X = 1 : True Y Z = i X : True X Y Z = i 1 : True X Y = Y X : False
The answers agree with the proofs. Two differences matter. First, allclose compares up
to a tolerance, which hides rounding. With the Hadamard gate, whose entries involve
1/√2, the product is not exactly the identity in floating point:
H = np.array([[1, 1], [1, -1]]) / np.sqrt(2)
print(H @ H)
print("within tolerance:", np.allclose(H @ H, I2))
print("exactly equal: ", bool((H @ H == I2).all()))[[ 1.00000000e+00 -2.23711432e-17] [-2.23711432e-17 1.00000000e+00]] within tolerance: True exactly equal: False
Second, a numerical check covers the inputs you tried. The next cell tests “unitaries
preserve inner products” on 1,000 random unitaries and state pairs. Lean’s
braket_unitary proves it for every unitary of every size.
rng = np.random.default_rng(0)
def random_unitary(n):
q, r = np.linalg.qr(rng.normal(size=(n, n)) + 1j * rng.normal(size=(n, n)))
return q * (np.diag(r) / abs(np.diag(r)))
worst = 0.0
for _ in range(1000):
U = random_unitary(4)
psi, phi = rng.normal(size=(2, 4)) + 1j * rng.normal(size=(2, 4))
worst = max(worst, abs(np.vdot(U @ psi, U @ phi) - np.vdot(psi, phi)))
print(f"largest |<U psi|U phi> - <psi|phi>| over 1000 trials: {worst:.1e}")largest |<U psi|U phi> - <psi|phi>| over 1000 trials: 7.3e-15
A small number, not zero, and only for 1,000 samples in dimension 4. That is evidence. A proof is a different kind of object: no tolerance and no sampling.
numpy Lean
--------------------------- --------------------------------------
floats, ~16 digits exact complex numbers
tested on the inputs tried proved for all inputs
"close to" (allclose) "equal to" (=)
fast; good for exploring slower; the result is a theorem5. The normalisation trap
A qubit state should have length 1. Here is a natural way to say “ψ has length 1”, and a vector that satisfies it:
example : ‖(fun _ => 1 : Ket (Fin 2))‖ = 1 := by simp✓ Lean accepted this (no messages)
The vector (1, 1) has Euclidean length √2, yet Lean proved its norm is 1. Nothing is
wrong with Lean. Ket (Fin 2) is the plain function type Fin 2 → ℂ, and the norm
Mathlib puts on a function type is the sup norm, max over i of |ψ i|. The statement
was true; it just was not the statement we meant (Lecture 5’s step 4). The library
therefore states normalisation with the inner product, which gives the expected 2:
example : braket (fun _ => 1 : Ket (Fin 2)) (fun _ => 1) = 2 := by
simp [braket, dotProduct]✓ Lean accepted this (no messages)
EuclideanSpace ℂ (Fin 2) is the type that carries the Euclidean norm. Its vectors are
wrapped: WithLp.toLp 2 v turns a plain vector into one. With the wrapper, the norm is
the one physics uses:
example : ‖(WithLp.toLp 2 (fun _ => 1) : EuclideanSpace ℂ (Fin 2))‖ = √2 := by
rw [EuclideanSpace.norm_eq]
simp✓ Lean accepted this (no messages)
This is the trade-off of Lecture 7 in two cells. The plain vector type makes gates easy
(U *ᵥ ψ) and has the wrong norm. EuclideanSpace has the right norm and inner product
built in, and every vector has to be wrapped and unwrapped.
6. Using the no-cloning theorem
Here is the theorem as the library states it. Read the hypotheses: a unitary U, a
normalised blank state s, and two states that U clones.
#check @no_cloning
#print axioms no_cloning✓ Lean accepted this
@no_cloning : ∀ {n : Type u_1} [inst : Fintype n] [inst_1 : DecidableEq n] {U : Matrix (n × n) (n × n) ℂ},
U ∈ unitaryGroup (n × n) ℂ →
∀ {s ψ φ : Ket n}, braket s s = 1 → Clones U s ψ → Clones U s φ → braket ψ φ = 0 ∨ braket ψ φ = 1
'LeanFV.Quantum.no_cloning' depends on axioms: [propext, Classical.choice, Quot.sound]
CNOT clones both ket0 and ket1 onto the blank ket0 (the library proves
CNOT_clones_ket0 and CNOT_clones_ket1). That does not contradict the theorem: their
overlap is 0. But CNOT cannot also clone a state whose overlap with ket0 is 1/2.
The proof feeds the library facts into no_cloning and lets simp compute the overlap.
example : ¬ Clones CNOT ket0 ![1/2, 1/2] := by
intro h
have hz := no_cloning CNOT_mem_unitaryGroup braket_ket0_ket0 CNOT_clones_ket0 h
simp [braket, ket0, dotProduct, Fin.sum_univ_two] at hz✓ Lean accepted this (no messages)
The heart of the proof is one equation. Write z = ⟨ψ|φ⟩. A unitary keeps the overlap of the two inputs ψ⊗s and φ⊗s, which is z. Cloning turns them into ψ⊗ψ and φ⊗φ, whose overlap is z². Both can hold only where z = z².
before U: <psi ⊗ s | phi ⊗ s> = <psi|phi> <s|s> = z
after U: <psi ⊗ psi | phi ⊗ phi> = <psi|phi> <psi|phi> = z^2
U unitary ==> z = z^2 ==> z = 0 or z = 1The picture below makes that concrete with real states ψ = cos θ |0⟩ + sin θ |1⟩ and φ = |0⟩, so z = cos θ runs from 1 down to 0. The dots are computed with numpy: the overlap CNOT actually produces, and the overlap a perfect cloner would need.
import matplotlib.pyplot as plt
ket0 = np.array([1, 0], dtype=complex)
blank = ket0
CNOT = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]], dtype=complex)
thetas = np.linspace(0, np.pi / 2, 13)
z_vals, after_u, clones = [], [], []
for t in thetas:
psi = np.array([np.cos(t), np.sin(t)], dtype=complex)
phi = ket0
z_vals.append(np.vdot(psi, phi).real)
out_psi, out_phi = CNOT @ np.kron(psi, blank), CNOT @ np.kron(phi, blank)
after_u.append(np.vdot(out_psi, out_phi).real)
clones.append(np.vdot(np.kron(psi, psi), np.kron(phi, phi)).real)
zz = np.linspace(0, 1, 200)
fig, ax = plt.subplots(figsize=(6.4, 4.2))
ax.plot(zz, zz, color="#2c5f9e", lw=1.5, label="unitary: overlap stays z")
ax.plot(zz, zz**2, color="#b5523b", lw=1.5, label="perfect clones: overlap z²")
ax.scatter(z_vals, after_u, color="#2c5f9e", s=28, zorder=3, label="CNOT outputs (numpy)")
ax.scatter(z_vals, clones, color="#b5523b", s=28, zorder=3, label="ψ⊗ψ vs φ⊗φ (numpy)")
ax.scatter([0, 1], [0, 1], s=110, facecolors="none", edgecolors="#2c7d54", lw=1.8,
zorder=4, label="z = z²: cloning possible")
ax.set_xlabel("overlap before, z = ⟨ψ|φ⟩")
ax.set_ylabel("overlap after")
ax.set_xlim(-0.03, 1.03)
ax.set_ylim(-0.03, 1.08)
ax.grid(alpha=0.3)
ax.legend(loc="upper left", fontsize=9, frameon=False)
fig.tight_layout()
For overlaps z between 0 and 1, a unitary keeps the overlap at z (CNOT's outputs, blue dots), while perfect copies would have overlap z squared (red dots). The two agree only at z = 0 and z = 1.
The blue dots sit on the line because CNOT is unitary, so it cannot do anything else. Where the blue and red curves differ, CNOT’s output is not a pair of copies. The green circles are the only overlaps where a single unitary could clone both states. The Lean theorem says exactly this, for every unitary and every dimension, not just CNOT and these 13 angles.
Try this
- Prove
Z * Y = -(I • X)in the style of section 3, then derive it fromY_mul_Zinstead (hint:Y * Z = -(Z * Y)is the anticommutation you would need first).- Define
Xi,ZioverGaussianIntlikeYi, and letdecidecheckXi * Yi * Zi = ⟨0, 1⟩ • 1. Then prove the ℂ version with the library lemmas.- Show that CNOT does not clone
 directly: computeCNOT *ᵥ tensor ![1, 1] ket0entry by entry and compare it withtensor ![1, 1] ![1, 1]. Why doesno_cloningnot help here? (Computebraket ket0 ![1, 1].)- In the numpy cell of section 6, replace CNOT by
random_unitary(4)and redraw. Which dots stay on the blue line?