Part III · Keeping Quanta Alive · Chapter 13
NISQ and Variational Circuits
Fault tolerance is expensive, and it is not here yet. So what can a few dozen noisy qubits actually do today? The answer is a bargain: let the quantum machine do the one thing it does natively — prepare and measure an enormous state — and let an ordinary classical optimizer steer it.
Sources: Preskill 2018 · Peruzzo et al. 2014 · Farhi et al. 2014 · Jacquier et al., QML in Finance
Part III has spent its chapters on a hard truth: error correction works, but it is expensive — thousands of physical qubits and deep, coherent circuits for a single protected logical operation. That machine is coming, not arrived. This chapter asks what the machines we have now — noisy, shallow, uncorrected — are good for, and gives the era's defining answer: variational algorithms. A short parametrized circuit prepares a trial state; the device measures a single number, an energy or a cost; and a classical optimizer adjusts the circuit's knobs to push that number down. The whole scheme rests on one theorem you can prove in three lines — that a measured energy can never beat the true ground energy — and by the end you will have a Variational Quantum Eigensolver hitting the exact ground energy of a spin chain to machine precision, and a QAOA circuit whose Max-Cut answer climbs with every layer you add.
What this chapter covers
- 13.1The NISQ era. Preskill's coinage: tens to hundreds of noisy qubits, shallow circuits, no error correction — and the hybrid quantum/classical loop built to fit inside those limits.
- 13.2The variational principle. The one theorem the whole chapter leans on: ⟨ψ(θ)|H|ψ(θ)⟩ ≥ E₀ for every θ, with equality only at the ground state. Three lines in the eigenbasis.
- 13.3VQE. A hardware-efficient ansatz U(θ), the energy read by sampling, and a classical optimizer that finds the ground state by minimizing it. Shot noise is the price of measurement.
- 13.4QAOA and Max-Cut. Encode a combinatorial cost as a diagonal Hamiltonian, alternate cost and mixer unitaries for p layers, and optimize (γ, β). The approximation ratio improves with depth.
- 13.5The honest scorecard. No proven speedup, barren plateaus, and noise that caps the depth. Why these are the honest best we can do before fault tolerance — and why the verdict is still open.
- 13.6The Lab. VQE driven to the exact ground energy of a transverse-field Ising chain, and QAOA for Max-Cut whose ratio climbs with every layer, reaching 0.965 by p = 3 from independent cold starts. The variational floor, probed everywhere and holding to round-off.
13.1The NISQ era
F · FormalismIn 2018 John Preskill gave the present moment a name: NISQ, for Noisy Intermediate-Scale Quantum. The three words are a specification. Noisy: gates and qubits carry the errors of Chapter 4, and there is no error correction to sweep them away. Intermediate-scale: tens to a few hundred qubits — too many to simulate trivially on a laptop, too few and too faulty to run the fault-tolerant algorithms of Part II at useful sizes. The deep, coherent circuits that Shor and phase estimation demand would accumulate error long before they finished. So the NISQ question is sharp: what can you compute with a circuit only a few layers deep, whose every run is a little bit wrong?
The era's answer is to stop asking the quantum computer to do the whole job. Split the work. Let the quantum device do the one thing it is uniquely good at — hold a state in a -dimensional space and give you a measurement statistic from it — and hand everything else to a classical computer sitting beside it. The quantum circuit is kept shallow (so noise stays tolerable) and parametrized by a handful of gate angles . The classical machine reads out a number, decides how to change , and asks for another run. This back-and-forth is the variational pattern, and it is the organizing idea of the whole chapter.
13.2The variational principle
F · FormalismEverything rests on a fact about Hermitian operators so simple it is almost a definition. Let be a Hamiltonian with eigenstates and real eigenvalues ordered , so that is the ground energy. Any normalized state expands in that eigenbasis,
Its expected energy is then a probability-weighted average of the eigenvalues,
where the inequality just replaces every by the smallest one, . That is the whole variational principle: no state has an expected energy below the ground energy, and equality holds if and only if all the weight sits on the ground level (a ground state). Turn it into an algorithm and it reads: take any family of states you can prepare, and minimize over . Whatever minimum you reach is a rigorous upper bound on , and if your family is rich enough to contain the ground state, the bound is tight. You cannot cheat downward — the floor is inviolable — so the only failure mode is stopping short, above the floor.
This is exactly the guarantee a NISQ machine needs. It does not require the circuit to be deep, or exact, or noiseless to be safe: any state it manages to prepare gives an honest bound. The quantum device's job is just to evaluate for whatever the classical optimizer proposes.
13.3The Variational Quantum Eigensolver
F · FormalismC · ConceptsThe Variational Quantum Eigensolver (VQE) is the variational principle wired into a loop. Three pieces. First, an ansatz: a parametrized circuit that prepares the trial state . A hardware-efficient ansatz uses only the gates the device runs well — layers of single-qubit rotations interleaved with entangling CNOTs:
Second, the energy evaluation: to get the device prepares and measures . A Hamiltonian is a sum of Pauli terms; you estimate each term's expectation by sampling in the right basis and add them up. Third, the classical optimizer: it takes and returns a better , closing the loop. The three fit together as one hybrid machine:
Because measurement is sampling, the energy comes with shot noise: a finite number of shots gives a noisy estimate of each expectation, with a statistical error that shrinks only as . The estimate is unbiased — it converges to the true — but every evaluation the optimizer sees is jittered, which is one of the practical frictions of the method (the lab quantifies it as a clean 5 check).
Before the many-qubit machinery, feel the principle on a single qubit. Take and a two-angle ansatz . The energy landscape is drawn below as a slice at your chosen ; the red floor is the exact . Steer the angles and watch the curve ride above that floor everywhere, kissing it only when the trial state lines up with the true ground state:
One-qubit energy landscape ⟨H(θ, φ)⟩
H = Z + 0.6 X + 0.4 Y · ansatz R_Z(φ) R_Y(θ)|0⟩ · exact E₀ = −‖(1, 0.6, 0.4)‖
The blue curve is a slice of the energy landscape at your chosen φ. It rides above the red floor E₀ everywhere — no setting of θ ever beats the ground energy, which is the variational bound at work. Its lowest point (gold dashes) only sinks all the way to E₀ at two settings of φ, half a turn apart: φ ≈ 0.59 and φ ≈ 3.73. Both pick out the same plane through the Bloch sphere — the one holding the field vector — entered from opposite sides, so the touching θ flips sign between them; at either, the slice contains the true ground state. Steer both angles to drive the green dot onto the red line: that is a converged VQE run in miniature.
That is VQE in one qubit. The lab does the same thing on a 3-qubit chain: a 12-angle ansatz, gradient descent, and a measured energy that settles onto the exact ground line from above and never below.
13.4QAOA and Max-Cut
F · FormalismC · ConceptsThe same variational skeleton solves a different kind of problem. The Quantum Approximate Optimization Algorithm (QAOA) targets combinatorial optimization — problems where you seek the best assignment of bits. The showcase is Max-Cut: given a graph, split its nodes into two sets so as to cut as many edges as possible. Encode the objective as a diagonal cost Hamiltonian whose eigenvalue on a bitstring is that string's cut value,
since is when spins and disagree (the edge is cut) and when they agree. Maximizing maximizes the expected number of cut edges. QAOA builds its trial state by starting from the uniform superposition and alternating two unitaries for rounds — the cost unitary and a mixer built from :
(Mind the ordering: the factor stands rightmost, next to the initial state, so it acts first; each later layer multiplies on the left — exactly the order in which the lab applies them.) The cost unitary is diagonal — it stamps a phase on each basis state proportional to its cut value — while the mixer is a layer of one-qubit -rotations that spreads amplitude between bitstrings. A classical optimizer tunes the angles to maximize . The quality of the answer is the approximation ratio
where is the true optimum (found by brute force in the lab, for a small graph). Two facts make the dial of interest. First, layers contain as a special case — set the last layer's and the extra round is the identity — so the optimal ratio can only rise with depth. Second, as QAOA can approach the exact optimum. Note what the first fact is about: the optima. Whether a finite optimizer actually finds them at every depth is a separate, empirical question — so the lab optimizes each from independent random starts and measures the climb, rather than seeding each depth from the last (which would make the climb true by construction). Measured that way, the ratio still rises with and clears the random-guessing baseline at the very first layer. The catch, of course, is that larger means a deeper circuit — precisely what NISQ noise makes costly to run.
13.5The honest scorecard
F · FormalismNow the sober accounting the book has promised at every turn. Variational algorithms are the flagship of the NISQ era, and it is tempting to read their flexibility as a guarantee of advantage. It is not. Here is where things actually stand.
No proven speedup. Unlike Shor's factoring or Hamiltonian simulation, neither VQE nor QAOA has a proof that it beats the best classical algorithm on a problem of practical interest. For many instances, classical methods — from clever heuristics to tensor-network and other simulation techniques — keep pace or win. Whether these methods ever deliver a decisive advantage is a genuinely open question, not a settled win.
Barren plateaus. As the number of qubits and the ansatz depth grow, the energy landscape can flatten exponentially: gradients vanish across almost all of parameter space, and the optimizer has no slope to follow. This barren-plateau phenomenon (which Chapter 16 studies in earnest) can make a generic hardware-efficient ansatz untrainable at scale — the very expressiveness that lets it reach any state is what buries the gradient.
Noise caps the depth. Deeper circuits express more, and QAOA's ratio improves with — but on real NISQ hardware each extra layer injects more error, until the signal drowns. Depth is exactly the resource the era is short of. Shot noise compounds it: resolving a small energy difference to steer the optimizer can demand enormous numbers of measurements.
None of this makes the approach worthless. It makes it honest: variational circuits are the best we know how to do on the hardware we have, before fault tolerance arrives to lift the depth limit. They may yet find a niche of real advantage; they may turn out to be a bridge we walk across and leave behind. The book's stance is to run them, measure them, and refuse to overclaim — which is exactly what the lab does next.
13.6The Lab — VQE and QAOA from scratch
P · PracticeThe lab builds both algorithms on a real state-vector simulator with a hand-written classical optimizer — no quantum SDK. For VQE the trial state is a hardware-efficient ansatz: because and CNOT are real and is real, the whole search stays in the reals, which is all a real symmetric Hamiltonian's ground state needs:
1/// Prepare |ψ(θ)⟩ = U(θ)|0…0⟩ for the hardware-efficient ansatz:2/// an initial R_Y layer, then L blocks of [CNOT ladder, R_Y layer].3/// Parameter count = n·(L+1).4fn ansatz_state(theta: &[f64], n: usize, l: usize) -> Vec<f64> {5 let dim = 1usize << n;6 let mut s = vec![0.0; dim];7 s[0] = 1.0;8 let mut idx = 0;9 for q in 0..n {10 apply_ry(&mut s, n, q, theta[idx]);11 idx += 1;12 }13 for _ in 0..l {14 for q in 0..n - 1 {15 apply_cnot(&mut s, n, q, q + 1);16 }17 for q in 0..n {18 apply_ry(&mut s, n, q, theta[idx]);19 idx += 1;20 }21 }22 s23}
The optimizer is gradient descent, and the gradient is not a finite difference but the parameter-shift rule (derived in Chapter 16): for a rotation gate generated by a Pauli, the exact derivative is a difference of two energies evaluated at shifted angles — themselves ordinary circuit runs. Every one of those shifted evaluations is a legitimate sampled , and so must obey the variational bound:
1/// The parameter-shift rule for an R_Y(θ)=exp(-iθY/2) gate (generator Y/2 with2/// eigenvalues ±½): ∂⟨H⟩/∂θ_k = ½[E(θ+½π e_k) - E(θ-½π e_k)], EXACT — no finite3/// step, no truncation. Every energy evaluated here is a genuine sampled θ and4/// so is fed through `eval`, which tracks the variational-bound minimum.5fn param_shift_grad(theta: &[f64], eval: &mut dyn FnMut(&[f64]) -> f64) -> Vec<f64> {6 let shift = std::f64::consts::FRAC_PI_2;7 let mut g = vec![0.0; theta.len()];8 let mut t = theta.to_vec();9 for k in 0..theta.len() {10 let orig = t[k];11 t[k] = orig + shift;12 let ep = eval(&t);13 t[k] = orig - shift;14 let em = eval(&t);15 t[k] = orig;16 g[k] = 0.5 * (ep - em);17 }18 g19}
QAOA reuses the same simulator with a diagonal cost unitary and an -rotation mixer, optimized this time by a hand-written Nelder–Mead simplex over the angles:
1/// Apply the cost unitary e^{-iγ H_C}, H_C = Σ (1 - Z_iZ_j)/2. Up to a global2/// phase this multiplies every basis state by e^{-iγ} once per CUT edge.3fn apply_cost(state: &mut [C], n: usize, edges: &[(usize, usize)], gamma: f64) {4 for (k, amp) in state.iter_mut().enumerate() {5 let cut = cut_value(k, n, edges) as f64;6 *amp *= C::from_polar(1.0, -gamma * cut);7 }8}910/// Apply the mixer e^{-iβ H_M}, H_M = Σ X_i, as e^{-iβ X} on each qubit:11/// e^{-iβX} = cos β · I - i sin β · X.12fn apply_mixer(state: &mut [C], n: usize, beta: f64) {13 let co = C::new(beta.cos(), 0.0);14 let si = C::new(0.0, -beta.sin()); // -i sin β15 // …16}
A bench of referees runs and writes its verdicts to JSON, which the panel below reads live — nothing is hardcoded, down to the number of checks. Most of the bench grades the machinery route against route, so that no check compares a computation with itself: the gate loops against a dense Kronecker-built unitary, the closed form against the exponential of its generator, the parameter-shift gradient against Richardson-extrapolated finite differences, the QAOA circuit against dense matrix exponentials of (13.4) and (13.5), and itself computed twice — once by a library eigensolver, once by a hand-written matrix-free power iteration. Only because of that last pair does the variational-floor referee mean anything: comes from the dense Hamiltonian, from the matrix-free route, and over every angle the optimizer touched plus 40,000 random ones, the deepest excursion below is a round-off-sized number of either sign — a few parts in , which is what an inequality honestly looks like in floating point, never a meaningful breach (the panel shows your run's value):
1// --- Referee 6: the variational floor, across two independent routes -----2// E(θ) comes from the dense Hamiltonian; E₀ comes from the matrix-free power3// iteration. As a theorem the difference cannot be negative for a normalized4// state, so what this referee actually gates is that BOTH routes are right5// and the ansatz stays normalized — and the value it reports is honest6// double-precision noise, of order 1e-15 and of either sign, not an exact 0.7assert!(min_bound_gap.is_finite());8referees.push(Referee {9 name: "Variational floor min(E_dense(θ) − E₀_free) ≥ −round-off".into(),10 value: min_bound_gap,11 tol: -8e-15,12 pass: min_bound_gap >= -8e-15,13});
The rest follow: VQE reaches the exact ground energy to machine precision — the panel shows your run's and gap; the shot-noise estimate at 50,000 shots per measurement setting (2 settings, so 100,000 circuit runs in all) lands well within 5 of the exact energy, where is the exact per-setting standard deviation of the two summed observables, computed from the state itself — and a second referee confirms that this is neither inflated nor optimistic by checking over hundreds of random angles; QAOA's Max-Cut approximation ratio, each depth optimized from 120 independent random starts, climbs across to 0.965, comfortably above the random baseline of 0.60 (both numbers are your run's, read from the JSON); and the last two referees certify Exercise 5's triangle closed form and its ratio-1 optimum against the brute-force simulator:
cargo run --release in Rust-QML/ch13-vqe)Run it yourself with cargo run --release in Rust-QML/ch13-vqe. This is the last lab of Part III. We have kept quanta alive two ways now — by correcting their errors (the expensive, future way) and by designing algorithms shallow enough to survive the errors we cannot yet correct (the pragmatic, present way). What both share is a loop: prepare, measure, adjust, repeat. In VQE and QAOA the “adjust” was a classical optimizer chasing a lower energy. In Part IV it becomes something with a grander name — learning — and the circuits we have just trained turn out to be the first machine-learning models built from amplitudes.
13.7Exercises
1. (F) Starting from the eigenbasis expansion (13.1), fill in every step of (13.2) to prove . Then state precisely when equality holds, and explain what the condition means when the ground level is degenerate (several eigenstates share ).
2. (C) In the one-qubit explorer, fix at a value far from either of its optima and sweep : record the lowest energy the slice reaches and confirm it stays above . Now tune to drive the slice minimum down onto the red line. You should find two values of that do it, half a turn apart. Compute both from the slice minimum , explain why they select the same plane through the Bloch sphere, and check that the touching flips sign between them.
3. (C) From the QAOA panel, read the approximation ratios at . Verify each is at least the previous one. Then be precise about what that verifies: the argument of §13.4 guarantees monotonicity of the optima, but the lab optimizes each depth from independent random starts, so the climb you read off is a measurement of the optimizer finding them — it could fail, and the referee reports its margin. Explain why the alternative (seeding each depth with the previous optimum plus a zero layer) would make the check pass even with a broken circuit, and why the lab keeps that warm-started chain only as a diagnostic.
4. (P) Change the Max-Cut graph in the lab (add an edge, or add a node). Re-run and confirm that updates, the ratio is still monotone in , and it still beats the random baseline . Does a denser graph need a larger to reach the same ratio?
5. (F, hard) Work out QAOA at on a triangle (three nodes, three edges, ), using the lab's conventions: the cost unitary stamps per cut edge, and the mixer applies to each qubit. Show that the expected cut is , maximize it over , and compare the resulting approximation ratio to the classical random-assignment value of . You should find a surprise: the optimum already saturates — approximation ratio 1 from a single layer. (Hint: work in the basis, use , and evaluate each edge's by commuting the Paulis through the two unitaries. The lab's last two referees certify both the closed form and the saturated optimum numerically — check your algebra against your machine.)
The bridge → Chapter 14: Learning from Data
Where you stand. You can run a NISQ machine: the variational principle guarantees any state's measured energy is an honest upper bound on the ground energy, VQE drives a hardware-efficient ansatz down to the exact E₀ of a spin chain, and QAOA's Max-Cut ratio climbs with depth even when every depth starts cold — all verified route against route, with the deepest dip below the ⟨H(θ)⟩ ≥ E₀ floor a signed few parts in 10¹⁵ (double-precision round-off, not a breach), and the losses (no proven speedup, barren plateaus, noise) stated plainly.
The open question. A variational circuit is a parametrized function whose knobs you tune to minimize a cost — which is precisely the shape of a machine-learning model trained on a loss. So what is learning, really? Before dressing it in amplitudes, we ought to understand it where it was born: classically, as fitting a function to data and hoping it generalizes.
What comes next. Part IV opens with learning stripped to its classical essentials — models, loss functions, gradient descent, generalization and overfitting — so that when we hand the model a quantum feature space and quantum parameters, we know exactly which part is new and which part is the same old optimization loop you just built.