Chapter 3: Gates, Circuits and Expectation Values¶
Chapter 2 described states and measurements. This chapter describes the verbs: the gates from which every circuit, and therefore every quantum model, is built. You will meet the rotation gates that load data and carry trainable weights, the fixed gates that shape superposition and phase, and the two-qubit gates that create entanglement and compare states. The chapter ends with two tools used constantly later: the rule for reading a circuit's output as a function of its angles, and a dozen lines of NumPy that will simulate every circuit in the book.
3.1 Gates are unitary matrices¶
A gate is a reversible operation on one or more qubits, written as a unitary matrix \(U\) with \(U^\dagger U=I\). Applying it multiplies the state: \(\lvert\psi\rangle\to U\lvert\psi\rangle\). Single-qubit gates are rotations of the Bloch sphere. They move the state around; they never create or destroy probability. Multi-qubit gates make qubits depend on each other, and are the only way to create entanglement. Every gate can be undone by its conjugate transpose \(U^\dagger\); Chapter 7 uses this to compute a kernel.
Order of gates
A circuit is read left to right, but the matrices multiply right to left: applying \(U_1\) first and then \(U_2\) gives the single operator \(U_2U_1\). Getting this backwards is one of the commonest slips in hand calculations (Exercise 3.3).
In machine learning, gates play three roles. Some load the data: their angles are the features. Some are trainable: their angles are weights. And some are fixed structure, such as \(H\) and CNOT, that shape what the model can represent.
3.2 Rotation gates¶
With \(c=\cos\frac\theta2\) and \(s=\sin\frac\theta2\), the three rotation gates are
- \(R_Y\) rotates about the \(y\) axis and has real entries: \(R_Y(\theta)\lvert0\rangle=\cos\frac\theta2\lvert0\rangle+\sin\frac\theta2\lvert1\rangle\). It moves weight between \(\lvert0\rangle\) and \(\lvert1\rangle\) and so directly changes the measured probabilities. It is the workhorse of angle encoding and of trainable weights.
- \(R_X\) rotates about the \(x\) axis. Like \(R_Y\) it changes the probabilities, but it adds a phase \(-i\) to the \(\lvert1\rangle\) component, so its amplitudes are complex. It is an alternative encoding or ansatz layer, usually alternated with \(R_Y\) and \(R_Z\) to reach any direction.
- \(R_Z\) rotates about the \(z\) axis and changes only the relative phase between \(\lvert0\rangle\) and \(\lvert1\rangle\). It is invisible to a \(Z\) measurement on its own; it matters only when a later gate (such as \(H\) or \(R_Y\)) turns phase into probability.
Example 3.1: three rotations on the north pole
(a) \(R_Y(\pi/2)\lvert0\rangle=\cos\frac\pi4\lvert0\rangle+\sin\frac\pi4\lvert1\rangle=\frac{1}{\sqrt2}(\lvert0\rangle+\lvert1\rangle)\), so \(P=(0.5,0.5)\).
(b) \(R_Y(\pi)\lvert0\rangle=\cos\frac\pi2\lvert0\rangle+\sin\frac\pi2\lvert1\rangle=\lvert1\rangle\).
(c) \(R_Z(\varphi)\lvert0\rangle=e^{-i\varphi/2}\lvert0\rangle\), which is \(\lvert0\rangle\) up to a global phase, so \(P(0)\) stays \(1\) whatever \(\varphi\) is.
3.3 Fixed single-qubit gates¶
- \(X\) is the NOT gate: \(X\lvert0\rangle=\lvert1\rangle\), \(X\lvert1\rangle=\lvert0\rangle\). It is a rotation by \(\pi\) about \(x\) and is used to load bits (basis encoding).
- \(H\), the Hadamard gate, creates an equal superposition: \(H\lvert0\rangle=\frac{1}{\sqrt2}(\lvert0\rangle+\lvert1\rangle)=\lvert+\rangle\) and \(H\lvert1\rangle=\lvert-\rangle\). Applying it twice gives back the input. It also switches between the \(Z\) and \(X\) bases, turning phase differences into measurable probability differences.
- Phase gates \(P(\varphi)\) leave \(\lvert0\rangle\) alone and multiply \(\lvert1\rangle\) by \(e^{i\varphi}\). Special cases are \(Z=P(\pi)\) and \(S=P(\pi/2)\). A relative phase is seen only after interference, as in the identity \(HZH=X\).
Rule of thumb
\(R_Y\) and \(X\) change what you measure. \(R_Z\) and \(P\) change phase, and phase needs an \(H\) or another rotation after it to show up.
Example 3.2: phase made visible by interference
Start in \(\lvert0\rangle\), apply \(H\), then \(R_Z(\varphi)\), then \(H\) again, and measure \(Z\).
After the first \(H\): \(\frac1{\sqrt2}(\lvert0\rangle+\lvert1\rangle)\). After \(R_Z(\varphi)\): \(\frac1{\sqrt2}(e^{-i\varphi/2}\lvert0\rangle+e^{i\varphi/2}\lvert1\rangle)\). After the second \(H\) the amplitude of \(\lvert0\rangle\) is \(\frac12(e^{-i\varphi/2}+e^{i\varphi/2})=\cos\frac\varphi2\). So \(P(0)=\cos^2\frac\varphi2\) and \(\langle Z\rangle=\cos\varphi\). The phase that was invisible on its own has become a probability.
3.4 Multi-qubit gates¶
CNOT (controlled-\(X\)) acts as \(\lvert a,b\rangle\to\lvert a,a\oplus b\rangle\): it flips the target qubit when the control is \(1\). With the control as the first qubit,
It is the basic entangling gate: \(H\) on the first qubit followed by CNOT turns \(\lvert00\rangle\) into \(\frac1{\sqrt2}(\lvert00\rangle+\lvert11\rangle)\), in which the two qubits are perfectly correlated. In machine learning it lets features interact: it computes the parity \(x_1\oplus x_2\), which is the heart of the XOR problem (Chapter 11) and of the ZZ feature map (Chapter 5).
Controlled-SWAP (CSWAP, the Fredkin gate) maps \(\lvert1\rangle\lvert a\rangle\lvert b\rangle\to\lvert1\rangle\lvert b\rangle\lvert a\rangle\) and does nothing when the control is \(0\). To swap whole registers apply one CSWAP per pair of qubits. It lets an ancilla qubit compare two states: with a Hadamard before and after, the ancilla's probability of reading \(0\) reveals their overlap (the SWAP test of Chapter 7). On hardware it compiles to several CNOTs and is therefore much more expensive than a single rotation.
3.5 Which gate for which job¶
| Job in a QML model | Gate | Where used |
|---|---|---|
| load a bit | \(X\) | basis encoding |
| load a real feature | \(R_Y(x)\) | angle encoding; most worked problems |
| a trainable weight | \(R_Y(\theta)\), \(R_Z(\theta)\) | variational circuits |
| superposition, change of basis | \(H\) | SWAP test, start of the ZZ map |
| a data-dependent phase | \(P(\varphi)\), \(R_Z(\varphi)\) | ZZ feature map |
| make features interact | CNOT | XOR classifier, ZZ map |
| compare two states | CSWAP with \(H\) | SWAP test |
| load a whole vector | a state-preparation routine | amplitude encoding |
| undo a feature map | \(U^\dagger\), e.g. \(R_Y(-x)\) | inversion test |
| read the answer out | measurement or an expectation estimate | every model |
3.6 A circuit as a function of its angles¶
The output of a variational circuit is the number
Here \(U(x)\) is the fixed encoding that loads the data, \(W(\theta)\) is the ansatz, a layer of rotations whose angles \(\theta\) are the trainable weights plus entangling gates between them, and \(O\) is the observable that is read out, for example \(Z\) on one qubit. The analogy with a neural network is close: the circuit is the layers, \(\theta\) are the weights, and the observable is the output neuron. The design choices are how many layers, which rotations, where the entanglement goes, and which observable.
Sometimes it is easier to push the observable backwards through the circuit than to push the state forwards. Since \(\langle\psi\vert W^\dagger O W\vert\psi\rangle\) is the same number either way, one may compute the conjugated observable \(W^\dagger OW\) and evaluate it in the simpler, earlier state. Two rules are needed in Chapter 11.
Conjugation rules
Through a rotation. On one qubit, \(R_Y(\theta)^\dagger Z\,R_Y(\theta)=\cos\theta\,Z-\sin\theta\,X\).
Proof. With \(R=R_Y(\theta)\) real, \(R^\dagger=R^T\), and \(ZR=\begin{pmatrix}c&-s\\-s&-c\end{pmatrix}\), so \(R^TZR=\begin{pmatrix}c&s\\-s&c\end{pmatrix}\begin{pmatrix}c&-s\\-s&-c\end{pmatrix}=\begin{pmatrix}c^2-s^2&-2cs\\-2cs&s^2-c^2\end{pmatrix}=\begin{pmatrix}\cos\theta&-\sin\theta\\-\sin\theta&-\cos\theta\end{pmatrix}\), which is \(\cos\theta\,Z-\sin\theta\,X\).
Through a CNOT (control qubit \(0\), target qubit \(1\)). \(\mathrm{CNOT}^\dagger Z_1\,\mathrm{CNOT}=Z_0Z_1\) and \(\mathrm{CNOT}^\dagger X_1\,\mathrm{CNOT}=X_1\).
Proof. On a basis state \(\lvert a,b\rangle\), \(Z_1\) after the CNOT reads the eigenvalue \((-1)^{a\oplus b}=(-1)^a(-1)^b\), which is that of \(Z_0Z_1\) on the original state. And \(X_1\) commutes with \(\lvert0\rangle\langle0\rvert\otimes I+\lvert1\rangle\langle1\rvert\otimes X\) because \(X\) commutes with both \(I\) and \(X\).
3.7 A NumPy toolkit¶
The following helpers simulate any circuit in this book exactly. Qubits are ordered as in a bit string, first qubit leftmost, so a two-qubit gate on qubits \((0,1)\) is the Kronecker product in that order.
import numpy as np
from functools import reduce
I2 = np.eye(2)
X = np.array([[0, 1], [1, 0]], dtype=complex)
Z = np.diag([1.0, -1.0]).astype(complex)
H = np.array([[1, 1], [1, -1]], dtype=complex) / np.sqrt(2)
def ry(t):
c, s = np.cos(t / 2), np.sin(t / 2)
return np.array([[c, -s], [s, c]], dtype=complex)
def rz(p):
return np.diag([np.exp(-1j * p / 2), np.exp(1j * p / 2)])
CNOT = np.array([[1, 0, 0, 0], [0, 1, 0, 0],
[0, 0, 0, 1], [0, 0, 1, 0]], dtype=complex) # control = first qubit
def kron(*ms): # tensor product of several operators or states
return reduce(np.kron, ms)
ket0 = np.array([1, 0], dtype=complex)
def probs(psi): # Born rule
return np.abs(psi) ** 2
def expval(psi, O): # <psi|O|psi>, a real number for Hermitian O
return float(np.real(np.vdot(psi, O @ psi)))
def sample(psi, shots, rng): # simulate measurement shots in the computational basis
outcomes = rng.choice(len(psi), size=shots, p=probs(psi) / probs(psi).sum())
return np.bincount(outcomes, minlength=len(psi))
A few lines show the tools at work: the Hadamard-then-CNOT circuit that produces the entangled state of Example 2.2, and the order-of-gates rule.
bell = CNOT @ kron(H, I2) @ kron(ket0, ket0) # H on qubit 0, then CNOT
print(np.round(bell.real, 4)) # [0.7071 0. 0. 0.7071]
print(probs(bell).round(3)) # [0.5 0. 0. 0.5]
# order of gates: first X then H is the matrix H @ X
print(np.round((H @ X @ ket0).real, 4)) # [ 0.7071 -0.7071] = (|0> - |1>)/sqrt2
print(np.round((X @ H @ ket0).real, 4)) # [0.7071 0.7071] = (|0> + |1>)/sqrt2
For an expectation on one qubit of a register, embed the observable with the Kronecker product, for example \(Z\) on the first of two qubits is kron(Z, I2).
3.8 Summary¶
Chapter Summary
- Gates are unitary matrices. A circuit read left to right is a matrix product taken right to left; every gate is undone by \(U^\dagger\).
- \(R_Y(\theta)\) and \(X\) change measured probabilities; \(R_Z(\varphi)\) and \(P(\varphi)\) change phase, which shows only after a later \(H\) or rotation.
- \(H\) makes superpositions and switches between the \(Z\) and \(X\) bases; \(HZH=X\).
- CNOT is the basic entangling gate and computes parity; CSWAP, with Hadamards, compares two states and is expensive on hardware.
- In QML a gate loads data, is a trainable weight, or is fixed structure.
- A model's output is \(f=\langle O\rangle\) in \(W(\theta)U(x)\lvert0\rangle\). Conjugation rules (\(R_Y^\dagger ZR_Y=\cos\theta Z-\sin\theta X\); CNOT sends \(Z_1\) to \(Z_0Z_1\) and fixes \(X_1\)) let you derive closed forms by hand.
3.9 Exercises¶
Exercise 3.1
Compute \(R_Y(\pi/2)\lvert0\rangle\) and \(R_Y(\pi)\lvert0\rangle\), and the measurement probabilities of each.
Answer
\(R_Y(\pi/2)\lvert0\rangle=\frac1{\sqrt2}(\lvert0\rangle+\lvert1\rangle)\) with \(P=(0.5,0.5)\); \(R_Y(\pi)\lvert0\rangle=\lvert1\rangle\) with \(P=(0,1)\).
Exercise 3.2
Verify \(HZH=X\) by matrix multiplication.
Answer
\(ZH=\frac1{\sqrt2}\begin{pmatrix}1&1\\-1&1\end{pmatrix}\), and \(H(ZH)=\frac12\begin{pmatrix}1&1\\1&-1\end{pmatrix}\begin{pmatrix}1&1\\-1&1\end{pmatrix}=\frac12\begin{pmatrix}0&2\\2&0\end{pmatrix}=X\).
Exercise 3.3
Apply \(X\) and then \(H\) to \(\lvert0\rangle\); then apply \(H\) and then \(X\). Are the results the same?
Answer
No. \(X\) then \(H\) gives the matrix \(HX\) and \(HX\lvert0\rangle=H\lvert1\rangle=\frac1{\sqrt2}(\lvert0\rangle-\lvert1\rangle)\). \(H\) then \(X\) gives \(XH\) and \(XH\lvert0\rangle=X\lvert+\rangle=\lvert+\rangle=\frac1{\sqrt2}(\lvert0\rangle+\lvert1\rangle)\). They differ by a relative sign.
Exercise 3.4
Show that a circuit \(H\), \(R_Z(\varphi)\), \(H\) applied to \(\lvert0\rangle\) has \(P(0)=\cos^2(\varphi/2)\). Why is this a "phase to probability" converter?
Answer
See Example 3.2. \(R_Z\) alone changes only a relative phase and a \(Z\) measurement cannot see it; the second Hadamard interferes the two components, and the relative phase \(\varphi\) then determines the probability.
Exercise 3.5
Prove that \(\mathrm{CNOT}\) leaves \(Z_0\) (a \(Z\) on the control) unchanged under conjugation, and that it leaves \(X_1\) unchanged.
Answer
Write \(\mathrm{CNOT}=\lvert0\rangle\langle0\rvert\otimes I+\lvert1\rangle\langle1\rvert\otimes X\). \(Z_0\) is diagonal in the control basis, so it commutes with both projectors, and acts as the identity on the target; hence \(\mathrm{CNOT}^\dagger Z_0\mathrm{CNOT}=Z_0\). \(X_1\) commutes with \(I\) and with \(X\), hence with CNOT. This confirms that only \(Z_1\) (and \(Y_1\)) are altered, as in Section 3.6.
Exercise 3.6
A hardware-efficient ansatz applies \(R_Y\) and \(R_Z\) with independent angles on each of \(n\) qubits in each of \(L\) layers, followed by a fixed entangling block. How many trainable parameters does it have for \(n=4\), \(L=3\)?
Answer
Two angles per qubit per layer: \(2nL=2\cdot4\cdot3=24\).
Exercise 3.7
State which gate you would use to (a) load a classical bit; (b) load a real-valued feature \(x\); (c) let two features influence one another.
Answer
(a) \(X\) on the qubit when the bit is \(1\). (b) \(R_Y(x)\) on one qubit per feature. (c) CNOT (or a controlled phase built from two CNOTs and a rotation).