Chapter 6: Variational Quantum Algorithms for Many-Body Systems#
This chapter develops the variational quantum eigensolver from the variational methods, qubit encodings and measurement circuits of the preceding chapters. We distinguish ansatz restrictions, optimization error, symmetry leakage and sampling uncertainty; derive parameter-shift rules with their spectral and parameter-sharing assumptions; and compare generic and physically motivated ansatz families on the same Lipkin, pairing, Hubbard and Heisenberg benchmarks used for phase estimation. ADAPT-VQE illustrates circuit construction and gradient traps. A self-contained introduction to QAOA develops the QUBO mapping, adiabatic motivation and small MaxCut examples. Excited-state targeting is outlined, and the closing section on the relation to machine learning leads over to the second part of the notes. NumPy programs and an executed notebook reproduce the numerical checks and make the limits of dense simulation explicit.
# Put every BookPrograms/chapter*/ and BookPrograms/common/ on sys.path
import sys, pathlib
root = pathlib.Path.cwd().resolve()
while not (root / 'BookPrograms').is_dir() and root.parent != root:
root = root.parent
sys.path[:0] = sorted(str(p) for p in (root / 'BookPrograms').iterdir() if p.is_dir())
import numpy as np
Introduction#
Phase estimation in Chapter 5 resolves energies on a grid whose spacing decreases exponentially with the number of control qubits, but the coherent evolution time grows inversely with the target precision. The variational quantum eigensolver, VQE [Peruzzo2014,McClean2016], uses a different organization of resources: repeatedly prepare a trial state, estimate its energy, and improve its parameters with a classical optimizer. Short circuits can make this approach attractive when long coherent evolutions are costly. This is a trade-off, not a guarantee of accurate results or of an advantage over classical methods.
The resource question of Chapter 1 remains the organizing principle: preparation, evolution, measurement and errors must be assessed together. The chapter joins four threads already developed in the book. Chapter 2 supplies state preparation, density matrices and joint measurement statistics, including the one-qubit variational example of Section A first Hamiltonian: the two-level system. Chapter 3 supplies the variational principle, reference states, symmetries and classical benchmarks, and in its last two sections (Sections From fermions to qubits and From Pauli sums to circuits and measurements) the qubit Hamiltonians, excitation circuits and Pauli measurement schemes. Chapter 5 supplies the same four model problems and the connection between a trial state’s ground-space overlap and spectral measurement. We use these conventions and benchmarks throughout. From Chapter 4 we need little: the product formula used below is already derived in Section The Baker–Campbell–Hausdorff expansion and Trotter splitting, and the adiabatic motivation for QAOA, the subject of Section Time-dependent Hamiltonians and adiabatic preparation, is restated in Section The ansatz and where it comes from.
Three choices govern a VQE calculation. The ansatz determines the reachable states and their symmetries. The measurement scheme determines which expectation value is estimated, at what statistical cost. The optimizer determines which part of the reachable family is actually found. We separate these choices rather than interpreting convergence as evidence that all three are satisfactory. In particular, replacing joint correlators by products of one-qubit averages evaluates the energy of a different, uncorrelated state. The parameter-shift rule also requires care when a generator has more than two eigenvalues or an angle occurs in several gates.
Sections Two small Hamiltonians, worked through and The model Hamiltonians compare generic and
physically motivated ansätze on the earlier Hamiltonians. Section Letting the algorithm choose the circuit: ADAPT-VQE
lets the circuit grow from a pool of operators and illustrates both a
compact success and a false convergence. Section A second variational algorithm: QAOA
extends the same variational machinery to combinatorial optimization
and briefly distinguishes it from machine learning. The programs in
LectureMaterial/BookPrograms/chapter6/ use exact state-vector energies for the
optimization benchmarks; the separate measurement experiment uses finite
shots. Exact matrix exponentiation and exact reference states are
explicit simulator conveniences, not hardware resource estimates.
The variational principle on a circuit#
The foundation is the Rayleigh–Ritz inequality used by the variational methods of Chapter 3 (Section The variational characterization). Projective coupled cluster is an important exception: its energy need not be a variational upper bound. For a Hamiltonian \(\hat{H}\) with ground-state energy \(E_0\) and any normalized state \(\vert\psi\rangle\),
with equality if and only if \(\vert\psi\rangle\) is a ground state. The proof is one line in the eigenbasis: with \(\vert\psi\rangle=\sum_jc_j\vert\phi_j\rangle\) and \(\hat{H}\vert\phi_j\rangle=E_j\vert\phi_j\rangle\),
since every \(E_j\ge E_0\) and the weights sum to one. Nothing about this is quantum-computational; it is a statement about weighted averages. What changes on a quantum computer is which states are available. Restricting \(\vert\psi\rangle\) to a family \(\vert\psi(\vec{\theta})\rangle\) labeled by real parameters turns Eq. (6.1) into a minimization,
where the minimum denotes the ideal optimum within the family. A practical optimizer returns some \(\vec{\theta}_*\), for which \(E(\vec{\theta}_*)\ge E_{\mathrm{VQE}}\ge E_0\) when energies are evaluated exactly and the search stays in the intended sector. The family is generated by a parametrized circuit acting on a reference state that is easy to prepare,
A circuit with \(\bigO(nd)\) gates can have a compact classical description while preparing a state whose expectation values are expensive to evaluate classically. The possible advantage concerns that evaluation, not the existence of a compact parametrization. Classical variational Monte Carlo, tensor networks and other structured families also avoid storing all \(2^n\) amplitudes. Many shallow circuits remain classically tractable, so compactness and entanglement alone establish no computational advantage. The small examples here compare physical mechanisms and accuracy; they are all readily simulated classically.
Two remarks about Eq. (6.3) are worth making at once, because the whole chapter turns on them. The first is what the bound is worth. It says that the answer lies above \(E_0\); it does not say that it lies close. If the family contains nothing near the ground state, the optimizer converges beautifully to a number that is simply too high, and its convergence tells us nothing about the quality of the answer. This is the difficulty of every variational method in this book, since a Hartree–Fock calculation also converges and also converges to the wrong energy, and the remedies are the same: enlarge the family and watch whether the number moves, compare families of different structure, and check against exact results wherever the system is small enough to allow it. For the same Hamiltonian and target sector, a lower exact variational energy is closer to the ground energy. This does not order the fidelities or errors of other observables. If the gap above the ground eigenspace is \(\Delta>0\), its projector \(P_0\) satisfies
This follows by bounding every excited-state contribution in Eq. (6.2) below by \(\Delta\); a small or unknown gap limits the certification available from the energy alone.
For a physical mixed state, \(\mathrm{Tr}(\rho\hat H)\ge E_0\) follows from \(\rho\ge0\) and \(\mathrm{Tr}\rho=1\). State-preparation noise alone therefore preserves the global bound, but can break a target-sector restriction. A finite-shot estimate \(\hat E\) is a random variable and can fall below \(E_0\), even when it is unbiased. Biased readout, inconsistent measurements or error-mitigated estimates need not obey the bound either. Selecting the lowest noisy value during optimization introduces selection bias; a final energy should be measured with fresh data and reported with its uncertainty. The below-ground QPE estimates in Table 5.5 instead arise from the finite spectral grid.
The loop. As executed, the algorithm is the following.
Choose an ansatz \(U(\vec{\theta})\), a reference \(\vert\Phi_0\rangle\) and initial parameters \(\vec{\theta}^{(0)}\).
On the quantum device, prepare \(\vert\psi(\vec{\theta})\rangle\) and measure enough Pauli strings, enough times, to reconstruct \(E(\vec{\theta})=\langle\psi(\vec{\theta})\vert\hat{H}\vert\psi(\vec{\theta})\rangle\).
On the classical device, use \(E\) and, if available, its gradient to propose \(\vec{\theta}^{(k+1)}\).
Stop using stated optimization and statistical criteria; check the sector and remeasure the final state independently. A flat energy history alone is not a certificate of accuracy.
Steps 2 and 3 alternate hundreds or thousands of times, and Fig. 6.1 draws the division of labour. Step 2 is where the quantum computer earns its place. Repeated measurements can dominate the cost, but state preparation, gate depth and classical optimization must also be counted. Most of this chapter is about how much step 2 costs, how it can go wrong, and how the ansatz of step 1 decides whether the loop is worth running at all.

Figure 6.1: The hybrid loop. The quantum device does one thing, the preparation and measurement of \(\vert\psi(\vec{\theta})\rangle\), and does it many times per iteration; the classical device assembles the energy from the string expectation values and proposes the next parameters.
The reader has met this loop twice already. Section A first Hamiltonian: the two-level system minimized the energy of a two-level system over the Bloch angles of a one-qubit state, Eq. (2.100), and Section A first variational circuit: unitary coupled cluster for the pairing model minimized the seventeen-string pairing Hamiltonian over the four angles of the pair-excitation circuit of Eq. (3.90), reproducing the unitary coupled-cluster energies of Table 3.15 digit for digit. Both were VQE calculations with the expectation value taken exactly on the simulator. What this chapter adds is the general machinery, the ansätze that are not tied to one model, the statistics of the readout and the gradients, and the systematic application to the models.
The ansatz#
The circuit \(U(\vec{\theta})\) is built from parametrized rotations and fixed entangling gates. The rotations are the exponentials of the Pauli matrices of Eq. (2.86),
and since \(X^2=Y^2=Z^2=I\) each closes on two terms, \(R_a(\theta)=\cos(\theta/2)\,I-i\sin(\theta/2)\,\sigma_a\), Eq. (2.85). The same is true of the Pauli rotations \(e^{-i\theta P/2}\) of Eq. (3.81) for any string \(P\). This innocuous identity is responsible for the parameter-shift rule of Section Gradients on a quantum computer: when an angle occurs in just one such gate and all other gates are fixed, the energy is a trigonometric polynomial of degree one in that angle, and such a polynomial can be differentiated exactly by evaluating it at two shifted points.
One qubit is a sphere#
For a single qubit the general normalized state, up to a phase, is the Bloch-sphere state of Eq. (2.36), \(\cos(\theta/2)\vert 0\rangle+e^{i\phi}\sin(\theta/2)\vert 1\rangle\), two angles for two real degrees of freedom. A product of two rotations,
reaches every one-qubit state, and for a Hamiltonian with real matrix elements the single rotation \(R_y(\theta)\vert 0\rangle\) already suffices, since the ground state of a real symmetric matrix can be chosen real. For a one-qubit Hamiltonian the ansatz is therefore exact: the variational minimum is the true ground state, and any residual in an exact simulation comes from optimization and roundoff. Shot noise and device errors add other contributions in an experiment. Section Two small Hamiltonians, worked through starts with this transparent test case.
The hardware-efficient ansatz#
The workhorse of the near-term literature [Kandala2017] places a pair of rotations on every qubit and follows them with a fixed layer of entangling gates, repeating the pattern \(L\) times,
applied to \(\vert 0\cdots0\rangle\) and read from right to left. With a ladder of CNOT gates as \(U_{\mathrm{ent}}\), control \(q\) and target \(q+1\) for \(q=0,\dots,n-2\), this uses \(2nL\) parameters and \((n-1)(L-1)\) two-qubit gates; Fig. 6.2 shows two layers on three qubits. It is called hardware-efficient because it is built from whatever gates the machine executes natively and respects whatever connectivity it has, and its main limitation is that nothing in it knows anything about the Hamiltonian. It does not in general conserve particle number or the desired spin symmetries, and is not guaranteed to contain any state resembling the ground state. It is a generic family that happens to be cheap.

Figure 6.2: The hardware-efficient ansatz of Eq. (6.8) with \(L=2\) layers on three qubits: \(R_y\) and \(R_z\) on every qubit, a CNOT ladder, a second layer of rotations, and the readout. Twelve parameters and two CNOT gates. Omitting the final entangling layer defines the ansatz convention used here; moving a layer into the measurement would change the measured observables and potentially their cost.
Two consequences follow, and both appear in the calculations of Section The model Hamiltonians. The optimization landscape has many local minima, so that restarts from several random initializations are not a refinement but a necessity, and all the hardware-efficient results below are the best of four starts (two for the eight-qubit Hubbard model). And as \(n\) and \(L\) grow the landscape flattens: for a sufficiently random circuit the gradient of the energy has zero mean and a variance that decays exponentially with the number of qubits. This is the barren plateau of Section Barren plateaus. A third consequence is specific to many-body physics and is the one the tables below make most vividly. The Hamiltonians of Section The four models on a qubit register act on a register that contains every particle number at once, and the physical ground state is the lowest state of one sector. A circuit that does not conserve the particle number is free to leave the sector, and if the register has a lower eigenvalue elsewhere, as the pairing and Hubbard Hamiltonians of Table 5.6 do, optimization may find it and report an energy that is not the energy of the system one wanted.
Ansätze that know the physics#
The alternative is to build the circuit from the Hamiltonian. The unitary coupled-cluster ansatz of Section Unitary coupled cluster,
starts from the reference determinant and applies particle-hole excitations, so it conserves the particle number by construction, has parameters that are recognizable amplitudes, and connects directly to the excitation hierarchy of classical coupled cluster. Truncated unitary and projective coupled cluster are different approximations; their energies need not coincide. Its circuit form is the Trotterized product of Eq. (3.60), one Pauli rotation per string of each excitation, and Section A first variational circuit: unitary coupled cluster for the pairing model compared the full exponential with a one-step ordered product. Re-optimization can compensate some changes in the family, but equality of their best energies is not a general theorem. Every circuit of this kind has the form
with Hermitian generators \(G_k\) that are sums of Pauli strings and a
reference that is a computational basis state or another easily prepared
state, the first generator acting first. The pair excitation of
Eq. (3.88) is \(G=-\frac12(Y_iX_a-X_iY_a)\); the
fermionic single excitation of Eq. (3.83) is the
same with the Jordan–Wigner string in between; a double excitation
\(a^{\dagger}_ra^{\dagger}_ta_qa_p-\mathrm{h.c.}\) with four distinct modes maps to eight strings. The
class PauliRotationAnsatz in vqe.py implements
Eq. (6.10) for any list of generators, applying each
exponential through the spectral decomposition of its matrix, which is
exact and fast at the sizes of this book, and it can also emit the
circuit of Section The exponential of a Pauli string for a computational-basis
reference and generators whose strings commute. Other references need
a separate preparation circuit, and a noncommuting sum needs an explicit
synthesis or product formula. The code rejects unsupported circuit
conversions instead of silently changing the state. The script checks that it reproduces the pair-excitation
circuit of Fig. 3.7 to machine precision.
A second physically motivated family uses the Hamiltonian itself as the generator. The Hamiltonian-variational ansatz [Wecker2015] splits \(\hat{H}=\sum_g\hat{H}_g\) into implementable pieces and alternates them with one angle per piece and layer. A piece may consist of commuting strings, or may require further synthesis. In chronological layer order,
The rightmost factor acts first. With all angles equal to \(\Delta t\), this is a product-formula approximation to time evolution. An adiabatic schedule requires the appropriate initial ground state, interpolation and gap conditions; it is not supplied by the ansatz alone. A symmetry \(Q\) is preserved when \([\hat H_g,Q]=0\) for each piece. The weaker condition \([\hat H,Q]=0\) does not imply that an arbitrary splitting preserves \(Q\). Likewise, one layer’s parameter count does not specify its gate cost. For the Hubbard example the full hopping exponential is applied exactly as a dense matrix; its Pauli strings do not all commute. The Heisenberg example uses the odd and even bond sums. These choices conserve the relevant symmetries of the supplied reference states.
Unitary coupled cluster organizes the generators by excitations from a reference determinant. The Hamiltonian-variational family organizes them by terms of the Hamiltonian. Either requires a reference and a reachable family appropriate to the target sector. A generic product of qubit rotations is spin mean field; it is not a general fermionic Hartree–Fock determinant. The orbital-rotation construction of Section Reference states and fermionic rotations is needed for the latter.
Between the generic and the physical families lie the adaptive schemes, which grow a circuit of the form of Eq. (6.10) one generator at a time, choosing at each step, from a pool of candidates, the one with the largest energy gradient. They produce compact, problem-specific circuits at the price of many extra measurements during the construction, and they are the subject of Section Letting the algorithm choose the circuit: ADAPT-VQE. Symmetry is the thread through all of this. An ansatz that conserves the quantities the Hamiltonian conserves searches a smaller space and may be easier to optimize, and cannot leave that sector in the ideal circuit; an ansatz that breaks a symmetry the Hamiltonian respects, as the CNOT ladder breaks the permutation symmetry of the Lipkin model, must recover the desired symmetry through optimization, with no guarantee that a particular run will do so.
Measuring the energy#
Everything so far has been written as though \(\langle\psi\vert\hat{H}\vert\psi\rangle\) were simply available. It is not. We use computational-basis readout after local basis rotations. Each measurement generally changes the state, so we repeat preparation for each independent sample. More general measurement protocols are possible. Section Measuring a Pauli sum set out how the expectation value of a Pauli sum is assembled from such readouts, and we recall the result before adding what the variational loop needs from it. With \(\hat{H}=\sum_\alpha h_\alpha P_\alpha\),
so the problem reduces to one number per string, and the identity string needs no measurement at all. A string of \(Z\)’s is read directly: the eigenvalue on the observed bit string is the parity \((-1)^{\sum_qb_q}\) over the qubits the string acts on, and its average over the shots estimates \(\langle P\rangle\). A qubit carrying \(X\) is preceded by a Hadamard, since \(HZH=X\), and a qubit carrying \(Y\) by \(S^{\dagger}\) and then \(H\), since \(HS^{\dagger}\,Y\,SH=Z\); Fig. 6.3 shows the three circuits, which applied qubit by qubit suffice for every string and hence for every Hamiltonian. Strings that commute qubit by qubit share the rotation and the shots, so the number of distinct circuits is the number of such groups, Table 3.21, and not the number of strings. Table 6.1 checks the recipe on a random two-qubit state, with the outcome distribution taken exactly rather than sampled: the rotated-and-averaged parity agrees with the matrix element to machine precision for every string tried.

Figure 6.3: Measuring \(Z\), \(X\) and \(Y\) on one qubit. The meter always reads the computational basis; the observable is selected by what precedes it. For a string, the circuits are applied qubit by qubit and the parity of the outcome bits on the support of the string is averaged.
string |
rotation and readout |
\(\langle\psi\vert P\vert\psi\rangle\) |
difference |
|---|---|---|---|
\(ZI\) |
\(-0.300445\) |
\(-0.300445\) |
\(1\times10^{-16}\) |
\(XI\) |
\(-0.020521\) |
\(-0.020521\) |
\(9\times10^{-17}\) |
\(YI\) |
\(-0.414294\) |
\(-0.414294\) |
\(2\times10^{-16}\) |
\(XX\) |
\(0.577375\) |
\(0.577375\) |
\(2\times10^{-16}\) |
\(YY\) |
\(0.919859\) |
\(0.919859\) |
\(4\times10^{-16}\) |
\(ZZ\) |
\(-0.573748\) |
\(-0.573748\) |
\(1\times10^{-16}\) |
\(XZ\) |
\(-0.599067\) |
\(-0.599067\) |
\(1\times10^{-16}\) |
\(YX\) |
\(-0.078774\) |
\(-0.078774\) |
\(8\times10^{-17}\) |
Table 6.1: The rotation recipe checked against direct evaluation on a
random two-qubit state. The second column is what hardware does, the
rotations of Fig. 6.3 followed by a readout of both
qubits and an average of the parity, here over the exact outcome
distribution; the third is the matrix element. Produced by
vqe_measurement.py.
Shot noise, and what it costs the loop#
Each shot returns \(\pm1\), so the estimator of \(\langle P\rangle\) from \(N\) shots is a sample mean of bounded variables, unbiased, with variance
and a standard error at most \(1/\sqrt{N}\). When the strings are measured independently the errors add in quadrature,
where the bound assumes a total budget \(N\) divided optimally among the strings in the manner of Section Measuring a Pauli sum, and \(\Lambda=\sum_{\alpha\ne I}\vert h_\alpha\vert\) is the Pauli \(1\)-norm of the traceless part, the same quantity that set the time step of phase estimation in Eq. (5.34). The scaling is the point. For independently sampled strings, coefficient-proportional allocation gives the sufficient worst-case budget for root-mean-square error \(\epsilon\),
shots. This is an upper-bound prescription, not a necessary cost for every state or measurement scheme. With grouped measurements define the single-shot group value \(S_g=\sum_{\alpha\in g}h_\alpha p_\alpha\). Independent groups give
The covariance terms matter. For a total budget \(N_{\rm tot}\), \(N_g\propto\sqrt{v_g}\) minimizes the variance, up to integer allocation. This is the grouped version of Section Measuring a Pauli sum.
Table 6.2 uses \(N\) shots per setting, hence \(3N\) preparations for its three settings. It reports the empirical spread of \(200\) independent energy estimates for a fixed state with energy \(0.330283\). The fluctuations in the estimated spread are visible; the scaled values are not all within \(5\%\) of each other. Figure 6.4 compares them with the exact group-variance prediction \(\sigma_E\sqrt N=0.912576\) from Eq. (6.16). At fixed nonzero single-shot variance, independent sampling gives the \(N^{-1/2}\) standard-error law. Better grouping and allocation improve its prefactor. Coherent amplitude estimation uses a different access model and should not be compared by shot count alone.
shots per setting \(N\) |
standard error |
\(\times\sqrt{N}\) |
bias |
|---|---|---|---|
\(10\) |
\(0.2649\) |
\(0.84\) |
\(-0.0031\) |
\(100\) |
\(0.0948\) |
\(0.95\) |
\(+0.0150\) |
\(1000\) |
\(0.0276\) |
\(0.87\) |
\(+0.0015\) |
\(10000\) |
\(0.0102\) |
\(1.02\) |
\(-0.0008\) |
Table 6.2: Shot noise in the energy of a fixed two-qubit trial state of
the two-mode Hamiltonian (\(E=0.330283\), \(\Lambda=2.175\), three
measurement settings), over \(200\) independent repetitions of the whole
measurement. The third column is the second scaled by \(\sqrt{N}\) and is
subject to sampling fluctuations; the last column is the empirical bias
of the finite set of repetitions, not the bias of the estimator. Produced by vqe_measurement.py.

Figure 6.4: The standard error of the sampled energy of Table 6.2 against the number of shots per measurement setting, on doubly logarithmic axes. The dashed line is the \(N^{-1/2}\) law with the exact covariance-inclusive prefactor of Eq. (6.16), with no fitted parameter. Produced by vqe_measurement.py.
The bound also explains why measurement reduction matters. For example, \(\Lambda=10^3\) Hartree and \(\epsilon=1.6\times10^{-3}\) Hartree give a sufficient worst-case budget of about \(3.9\times10^{11}\) preparations for one energy. Actual costs depend on variances, grouping, the precision needed at intermediate steps and confidence requirements; a high-probability bound also depends on the failure probability. This number is not a prediction for every molecule. Noise also affects optimization: very small finite-difference steps and deterministic line searches can be unreliable, but stochastic finite differences remain possible, as SPSA illustrates.
Why single-qubit marginals do not determine the energy#
Here is a shortcut that looks reasonable and is wrong. Reading all \(n\) qubits gives, in particular, the one-qubit statistics \(\langle Z_0\rangle,\dots,\langle Z_{n-1}\rangle\), and it is tempting to build the energy out of those, treating a two-qubit term as a product,
In general this equality is false even with exact statistics; increasing the number of shots cannot restore a correlation that was discarded.
Theorem 6.1 (Marginals do not determine correlators)
There exist states \(\rho\) and \(\rho'\) on two qubits with identical single-qubit reduced density matrices, and an observable \(\hat{H}\) with \(\mathrm{Tr}(\rho\hat{H})\ne\mathrm{Tr}(\rho'\hat{H})\). Consequently the expectation value of \(\hat{H}\) is not a function of the single-qubit measurement statistics.
Proof
Take \(\hat{H}=Z\otimes Z\) and the two Bell states of Eq. (2.63), \(\vert\Phi^+\rangle=(\vert 00\rangle+\vert 11\rangle)/\sqrt2\) and \(\vert\Psi^+\rangle=(\vert 01\rangle+\vert 10\rangle)/\sqrt2\). Both have the maximally mixed reduced density matrices \(\rho_0=\rho_1=I/2\) of Section Reduced density matrices of entangled states, so every single-qubit observable, \(X\), \(Y\) and \(Z\) on either qubit, has the same expectation value, zero, in the two states, and hence so does any function of them. Yet \(\langle\Phi^+\vert Z\otimes Z\vert\Phi^+\rangle=+1\) and \(\langle\Psi^+\vert Z\otimes Z\vert\Psi^+\rangle=-1\).
The mechanism is not an artifact of a contrived example. The single-qubit statistics of a state are precisely the content of its reduced density matrices, and a reduced density matrix is obtained by tracing out the other qubit, Eq. (2.56), an operation whose entire purpose is to discard correlations. Asking for \(\langle Z_0Z_1\rangle\) from \(\langle Z_0\rangle\) and \(\langle Z_1\rangle\) is asking to recover what was deliberately thrown away. For a product state it holds for all local observables. An entangled state may satisfy it for a particular pair of observables, and a separable mixed state may violate it through classical correlations. For example, \((|00\rangle\langle00|+|11\rangle\langle11|)/2\) has zero local \(Z\) means and unit \(ZZ\) expectation.
There is nevertheless a precise meaning to the reconstructed energy. If every local average comes from the same physical reduced state \(\rho_q\), then factorizing every Pauli string gives
The tensor product is a normalized positive density matrix. Thus the reconstruction is the energy of a different, generally mixed, product state and cannot violate the global variational bound. It may violate a target-sector bound because the product of marginals need not remain in a fixed-particle-number sector. Noisy or inconsistent estimates of local states require separate treatment.
What it does to a VQE calculation. Take \(\hat{H}=Z\otimes Z\) with the one-parameter family
Every state in it has \(\langle Z_0Z_1\rangle=1\), since both basis states present have even parity, so the true landscape is flat, \(E_{\mathrm{true}}(\theta)=1\). The marginals are \(\langle Z_0\rangle=\langle Z_1\rangle=\cos^2\theta-\sin^2\theta=\cos2\theta\), so the reconstruction of Eq. (6.17) reports
an oscillating function with minima at \(\theta=\pi/4\) and \(3\pi/4\) where it reports \(0\) for a quantity whose value is \(1\). Figure 6.5 draws the two. The error of the reconstruction, \(1-\cos^22\theta=\sin^22\theta\), is exactly the square of the concurrence \(\vert\sin2\theta\vert\) of the state, so the two curves touch only at the three parameter values \(0,\pi/2,\pi\) representing two distinct product states and separate most widely at the Bell states, which sit at the bottom of the fictitious wells; and the slope of the dashed curve points, on every descending branch, toward the maximally entangled state. An optimizer handed this landscape is not merely misinformed. It is driven toward the configuration on which the readout is at its worst, and the more successfully it optimizes the larger the error it accumulates, while every diagnostic the classical half of the loop can see says that the run is going well.

Figure 6.5: The two energy landscapes of \(Z\otimes Z\) over the family of Eq. (6.19): the true energy, which is flat, and the marginal reconstruction of Eq. (6.20). The circles mark the spurious minima at the Bell states. Produced by vqe_measurement.py.
Table 6.3 compares the two objectives on the two-level pairing Hamiltonian of Eq. (3.79), whose ground energy is \(-0.618034\). Joint readout reaches that value. The marginal objective reaches \(-0.5\) and here selects a product state whose true energy is also \(-0.5\). Agreement at this particular optimum does not repair the incorrect objective: Eq. (6.20) already shows its bias on entangled states. The product-state restriction loses the correlation energy. The code differentiates the reconstructed objective numerically on the noiseless simulator; a two-term shift of the entire nonlinear product of local averages is not its derivative.
Local readout of both qubits on the same preparation is sufficient; an entangling measurement is unnecessary. Preserve the paired outcomes, multiply them shot by shot and then average. For a general Pauli string, measure its nonidentity support after the required basis rotations and average its parity. Measuring all register qubits is convenient, but qubits on which the string is the identity are not required.
energy |
|
|---|---|
exact ground state |
\(-0.618034\) |
VQE, joint readout |
\(-0.618034\) |
VQE, marginal reconstruction (reported) |
\(-0.500000\) |
true energy of the state it prepared |
\(-0.500000\) |
Table 6.3: VQE on the two-level pairing Hamiltonian of
Eq. (3.79) with joint and with marginal readout,
hardware-efficient ansatz with two layers, identical starting
parameters. The marginal objective evaluates the product of reduced states;
in this run its optimum is a product state, so its reported and actual
energies agree while both miss the correlation energy. Produced by vqe_measurement.py.
Gradients on a quantum computer#
The classical half of the loop wants derivatives. On a classical computer one differentiates the code; here the energy is accessible only through measurement, and the obvious substitute, the finite difference
is a poor one for a reason that has nothing to do with quantum mechanics. It has a truncation error \(\bigO(h^2)\) that wants \(h\) small, and it subtracts two noisy numbers whose difference is \(\bigO(h)\) while their errors are not, so that with shot noise \(\sigma\) on each energy the standard deviation of the derivative estimate is \(\sigma/(\sqrt2h)\) for independent energy errors. Balancing this with an \(\bigO(h^2)\) bias gives \(h\propto\sigma^{1/3}\) and root-mean-square error of order \(\sigma^{2/3}\), with constants set by the higher derivatives. The parameter-shift rule [Mitarai2018,Schuld2019] avoids finite-difference bias for gates satisfying its spectral hypotheses. For a two-eigenvalue generator it uses two energies separated by a finite shift; more general spectra can require additional evaluations.
The parameter-shift rule#
The rule is a statement about the generators of the gates, not about the Hamiltonian, which enters only through the requirement that \(E(\vec{\theta})\) be measurable at all. This is the usual source of confusion and is worth stating first.
Theorem 6.2 (Two-term parameter-shift rule)
Let \(E(\theta)=\langle\psi\vert U^{\dagger}(\theta)\hat{H}U(\theta)\vert\psi\rangle\) with \(U(\theta)=e^{-i\theta G}\), \(\hat{H}\) and \(G\) Hermitian, and let \(G\) have exactly two distinct eigenvalues \(\pm r\), \(r>0\). Then
Proof
Because \(G\) has only the eigenvalues \(\pm r\) one has \(G^2=r^2I\), and the projectors onto its two eigenspaces are \(\Pi_\pm=\frac12(I\pm G/r)\), with \(\Pi_\pm^2=\Pi_\pm\), \(\Pi_+\Pi_-=0\), \(\Pi_++\Pi_-=I\) and \(G=r(\Pi_+-\Pi_-)\). The exponential therefore has the spectral form,
the same closing on two terms as in Eq. (2.85). Substituting into \(E(\theta)\) gives four terms, two of which carry no \(\theta\) and two of which carry \(e^{\pm2ir\theta}\); collecting them, and using that \(E\) is real,
with \(A=\langle\psi\vert\Pi_+\hat{H}\Pi_++\Pi_-\hat{H}\Pi_-\vert\psi\rangle\), \(B=2\,\mathrm{Re}\langle\psi\vert\Pi_+\hat{H}\Pi_-\vert\psi\rangle\) and \(C=-2\,\mathrm{Im}\langle\psi\vert\Pi_+\hat{H}\Pi_-\vert\psi\rangle\). The energy is a pure sinusoid of frequency \(2r\), three unknowns and no more, so that \(E'(\theta)=-2rB\sin(2r\theta)+2rC\cos(2r\theta)\). Evaluating Eq. (6.24) at \(\theta\pm s\) with \(s=\pi/(4r)\), so that \(2rs=\pi/2\) and the shifted cosines and sines exchange places, \(E(\theta+s)-E(\theta-s)=2[-B\sin(2r\theta)+C\cos(2r\theta)]\), which is \(E'(\theta)/r\).
The standard case is \(G=P/2\) with \(P\) a Pauli string, the rotations of Eq. (6.6) and the Pauli rotations of Eq. (3.81), so that \(r=1/2\), \(s=\pi/2\) and
all other parameters held fixed and \(\theta_k\) occurring in one gate.
For eigenvalues \(g_-<g_+\), subtracting \((g_++g_-)/2\) times the identity
only changes a global phase, so the theorem applies with
\(r=(g_+-g_-)/2\). If one parameter occurs in several gates, differentiate
each occurrence and sum by the chain rule, or use the frequencies of the
whole dependence. Shifting all occurrences together with the single-gate
rule is generally wrong. In particular, the shared-angle product ansatz
can contain frequencies \(1,\ldots,n\) and uses a \(2n\)-evaluation rule. Equation (6.25)
looks like Eq. (6.21) with \(h=\pi/2\), and it is
essential to see why it is a different kind of object. The shift is not
small and there is no truncation error to trade against noise: the
identity is exact for every \(\theta\). What makes it work is that
Eq. (6.24) has three unknown constants, so that three
evaluations determine the function completely and two determine its
derivative; the rule is interpolation of an exactly known form, not
approximation of an unknown one. On hardware this is worth a great
deal, because the two terms are of order one and well separated and
their difference does not amplify the noise. A gradient with \(P\)
parameters costs \(2P\) energies, each of them the shots of
Section Shot noise, and what it costs the loop, and this is where the expense of VQE lives.
Two checks in gradients.py make the theorem concrete. Fitting
\(A\), \(B\), \(C\) to three energies of a two-qubit, two-layer
hardware-efficient state as a function of one \(R_y\) angle and predicting
the energy at \(25\) other angles reproduces it to \(9\times10^{-16}\),
which confirms the functional form and not merely the derivative; and
the shift rule agrees with a converged finite difference to
\(3\times10^{-11}\), the residual being the finite difference’s own error.
When two terms are not enough#
The hypothesis of Theorem 6.2 is not decorative. Consider
with eigenvalues \(-1,0,+1\). What the energy sees are the differences of eigenvalues, now \(0,\pm1,\pm2\), so that Eq. (6.24) becomes a two-frequency polynomial
with two distinct frequencies. The standard two-term rule passes the frequency-one terms but annihilates the frequency-two terms, so it cannot give the general derivative. The failure is not graceful. For the generator of Eq. (6.26) acting on \(\vert{+}{+}\rangle\) with \(\hat{H}=0.7\,XI+0.4\,IX+0.5\,XX+0.3\,YZ\) at \(\theta=0.6\) the true derivative is \(-1.087126\) and the two-term rule returns \(-0.621107\), a number of the right sign and the wrong size, which an optimizer would follow without complaint. The remedy is the generalized rule for \(R\) frequencies \(1,2,\ldots,R\) [Wierichs2022],
which reduces to Eq. (6.25) at \(R=1\) and at \(R=2\)
recovers \(-1.087126\) to \(10^{-8}\). The cost is \(2R\) evaluations per parameter. For frequencies
\(\omega,2\omega,\ldots,R\omega\), replace each shift by \(x_\mu/\omega\)
and multiply the weights by \(\omega\). This is not an academic example: the pair-excitation
generator \(-\frac12(Y_iX_a-X_iY_a)\) of Eq. (3.88), and
unit-coefficient fermionic excitations between distinct configurations,
have the spectrum
\(\{-1,0,+1\}\), since the anti-Hermitian excitation operator squares to
minus a projector. Applied to the four pair excitations of the circuit
of Eq. (3.90) the two-term rule is wrong by
\(1.3\times10^{-2}\) while the four-term rule agrees with the finite
difference to \(3\times10^{-10}\), which is why the class VQE
asks every ansatz, parameter by parameter, which rule applies: two
terms for the rotations of the hardware-efficient family, four for the
excitation generators. For an unrecognized spectrum the implementation
uses a finite difference only for noiseless energies and rejects that
fallback when shots are enabled; SPSA remains available. This distinction
matters for the Hamiltonian-variational examples. Another valid approach
is to decompose a generator into gates and differentiate each occurrence
of the tied angle separately. Giving each Pauli string an independent
angle changes the variational family and may break the symmetries of the
original excitation operator.
Optimizers#
With gradients available the classical half of the loop is ordinary
numerical optimization, and the programs of this chapter use three
methods. Plain gradient descent, \(\vec{\theta}\leftarrow\vec{\theta}-\eta\nabla E\),
is robust, slow, and easy to reason about, and it is what the
convergence histories below show. The BFGS quasi-Newton method of
common/optimize.py, already used for the coupled-cluster
amplitudes of Chapter 3, converges in a small fraction
of the iterations when the energies are exact, which is the case on a
simulator and is what every table of Section The model Hamiltonians uses;
on hardware its line searches are fragile because they compare energies
that differ by less than the shot noise. On the two-mode Hamiltonian
from the same start, gradient descent needs \(5101\) energy evaluations
to reach the minimum, BFGS \(204\).
The third is a stochastic gradient approximation. Simultaneous perturbation stochastic approximation, SPSA [Spall1992], estimates the whole gradient from two energies whatever the number of parameters, by perturbing all of them at once along a random direction \(\vec{\Delta}\) with entries \(\pm1\),
with step sizes \(a_k\) and \(c_k\) that decay slowly with the iteration count. The estimate is unbiased for the gradient up to \(\bigO(c_k^2)\) and very noisy, and the noise averages out over the iterations in the way that stochastic gradient descent tolerates. Against the \(2P\) energies of a parameter-shift gradient this is a large saving when \(P\) is large, and the right currency for the comparison is the number of energy evaluations rather than the number of iterations, since each evaluation is the shots of Section Shot noise, and what it costs the loop. Figure 6.6 makes the comparison on the four-qubit pairing Hamiltonian of Eq. (3.78) with a three-layer hardware-efficient ansatz, \(24\) parameters, both methods from the same start: after \(2941\) evaluations the parameter-shift descent has reached \(-0.162\), and SPSA after \(1801\) has reached \(-0.599\), on a landscape whose lowest point is the register minimum \(-0.779\). The comparison is not universal, since it depends on the learning rates, the number of parameters and the noise, and this demonstration uses exact energies. SPSA uses two evaluations for the gradient and one additional evaluation for monitoring each step; the plot also includes the initial energy. A comparison under shot noise requires repeated runs and an explicit total-shot budget.

Figure 6.6: Gradient descent with parameter-shift gradients against SPSA on the four-qubit pairing Hamiltonian with a three-layer hardware-efficient ansatz (\(24\) parameters), from the same starting point, against the number of energy evaluations. The dashed line is the lowest eigenvalue of the register. Produced by gradients.py.
Barren plateaus#
Random circuit ensembles can exhibit concentration of their gradients [McClean2018]. Under suitable assumptions on the ensemble, observable normalization and circuit portions surrounding a parameter, the mean vanishes and the variance behaves as
The typical gradient size is the square root of this variance, \(2^{-cn/2}\). For \(c=1\) and \(n=50\) this is about \(3\times10^{-8}\), whereas the variance is about \(9\times10^{-16}\). Resolving such a gradient with an order-one single-shot variance can require order \(2^{cn}\) shots. A small finite-difference step does not solve this statistical problem.
The unitary-design argument is a statement about a specified random ensemble, not about every expressive circuit. Local costs, circuit depth, symmetries, initialization and noise all matter; classical optimization also has vanishing-gradient problems. Figure 6.7 shows \(300\) random samples at each of \(n=2,\ldots,8\), with depth \(L=n\) and observable \(Z_0Z_1\). The variance decreases from about \(0.19\) to \(0.0019\); a fit for \(n\ge4\) has slope \(-0.99\) in \(\log_2\) variance. This finite-size observation illustrates concentration but does not establish asymptotic scaling. Physically motivated ansätze and suitable initializations can help, without a general guarantee. QPE contains no variational optimization, but its input-state preparation can inherit these problems if VQE is used for that step.

Figure 6.7: The variance of one gradient component of the hardware-efficient ansatz with a CNOT ring and \(L=n\) layers, for the observable \(Z_0Z_1\), over \(300\) random parameter vectors, against the number of qubits. The dashed line uses the slope fitted for \(n\ge4\), anchored at the \(n=2\) variance. Produced by gradients.py.
Two small Hamiltonians, worked through#
We return to the two systems of Section Two small Hamiltonians, worked through, now solved variationally. Reusing them is deliberate: the comparison of Section Phase estimation and VQE weighed against each other is between two algorithms on one problem, not between two problems.
One qubit: the tapered pairing Hamiltonian#
The tapered one-qubit form of the two-level pairing model, Eq. (3.80), \(\hat{H}=\frac12I+Z-\frac12X\), has the ground state \(E_-=\frac12-\frac{\sqrt5}{2}=-0.618034\). The matrix is real, so the single rotation \(R_y(\theta)\vert 0\rangle=\cos(\theta/2)\vert 0\rangle+\sin(\theta/2)\vert 1\rangle\) suffices, and its energy is
minimized where \(\tan\theta=-\frac12\) on the branch with \(\cos\theta<0\). The program finds \(-0.6180339887\) at \(\theta=-3.6052\) (equivalently \(2.6779\) modulo \(2\pi\)), that is \(\tan\theta=-0.5000\), with an error of order \(10^{-16}\): the ansatz is exact, so the residual reflects numerical optimization and floating-point roundoff in this noiseless simulation. Compare Table 5.4, where phase estimation with ten control qubits reached \(1.5\times10^{-3}\), limited by the grid \(2\pi/(t2^m)\) of its energy register. VQE is not quantizing the answer at all. On a single qubit, with an exact ansatz and no shot noise, the energy is more accurate in these simulations. This is not a resource-matched hardware comparison: state preparation, shots, coherent evolution and confidence have not been assigned a common cost.
Two qubits: the two-mode Hamiltonian#
The two-mode Hamiltonian of Eq. (3.71) is where the first real lesson appears. Its register holds the spectrum \(\{0,\ 0.916905,\ 2.083095,\ 3.5\}\), and the physical problem of Section A worked example: two modes is the one-particle sector, whose ground state is \(0.916905\); the register minimum, zero, is the vacuum \(\vert 00\rangle\) with no particle at all. Table 6.4 shows what the two kinds of ansatz make of this. The hardware-efficient circuit, with one layer or two, converges without difficulty to \(0.000000\) and \(\langle\hat{N}\rangle=0\): it has found the ground state of the register, which is the correct answer to the question it was asked and the wrong answer to the question we meant. The number-conserving ansatz, the single fermionic rotation of Eq. (3.83) applied to \(\vert 10\rangle\) with one parameter, cannot leave the sector and finds \(0.916905\) at \(\theta=-0.2702\), the value of Section Reference states and fermionic rotations, to machine precision. The point generalizes to every fermionic Hamiltonian in an orbital encoding, since the register contains every particle number and the ground state of the full Fock space is rarely the state one wants; the remedies are an ansatz that conserves the number, a penalty term \(\mu(\hat{N}-N)^2\) with \(\mu\) large enough to lift all lower competing sectors, or a symmetry-adapted encoding that removes the other sectors, as the two-level tapered example of Section Tapering a discrete symmetry does. A generic parity taper does not fix the full particle number. The ground state of the one-particle sector is entangled, a superposition of \(\vert 10\rangle\) and \(\vert 01\rangle\), and the single excitation gate reaches it with four CNOT gates and one angle; and its exact expectation equals the sector ground energy up to roundoff, consistent with Eq. (6.1), in contrast to the \(m=5\), \(7\) and \(8\) rows of Table 5.5, which lie below it.
ansatz |
parameters |
\(E_{\mathrm{VQE}}\) |
\(\langle\hat{N}\rangle\) |
|---|---|---|---|
hardware-efficient, \(1\) layer |
\(4\) |
\(0.000000\) |
\(0\) |
hardware-efficient, \(2\) layers |
\(8\) |
\(0.000000\) |
\(0\) |
single excitation from \(\vert 10\rangle\) |
\(1\) |
\(0.916905\) |
\(1\) |
Table 6.4: VQE on the two-mode Hamiltonian of Eq. (3.71),
whose register spectrum is \(\{0, 0.916905, 2.083095, 3.5\}\) and whose
one-particle ground state is \(0.916905\). The hardware-efficient ansatz
leaves the sector and finds the vacuum; the number-conserving single
excitation finds the physical ground state. Produced by
vqe_models.py.
The model Hamiltonians#
We now run VQE on the four systems that Section The model Hamiltonians on a quantum computer fed
to phase estimation, with the Hamiltonians, couplings and exact energies
of Table 5.6: the Lipkin model with \(N=4\) in the doublet
encoding of Eq. (3.73), \(E_0=-4.212877\); the pairing
model with four levels and two pairs in the compact encoding of
Eq. (3.78), \(E_0=0.635548\); the four-site Hubbard
ring at \(U=4t\) with four particles and \(S_z=0\) in the spin-major
Jordan–Wigner encoding of Section The four models on a qubit register, eight qubits,
\(E_0=-2.102748\); and the four-site Heisenberg ring, \(E_0=-2\). The
programs take the Hamiltonians from qpe_models.py of
Chapter 5, so that the two chapters agree by construction
on what is being solved. The energies are evaluated exactly on the
simulator, and every fixed-ansatz result is the best of four random restarts (two for
the eight-qubit Hubbard model) of
BFGS, with parameter-shift gradients where implemented and noiseless
finite differences otherwise; the question of shot noise is
separated out, since its effect is the one already quantified in
Section Shot noise, and what it costs the loop and its interaction with the optimizer is
taken up in the exercises.
The hardware-efficient ansatz#
Table 6.5 is the generic ansatz applied without thought to all four models, at one, two and three layers. It is read against two reference values: the lowest eigenvalue of the whole register, which is what an unconstrained minimization is entitled to find, and the exact ground-state energy of the physical sector, which is what we want. The last column is the overlap of the optimized state with the exact sector ground state, the quantity that Table 5.9 showed to govern the success of a subsequent phase-estimation run.
model |
\(L\) |
param. |
CNOT |
\(E_{\mathrm{VQE}}\) |
register min. |
sector \(E_0\) |
\(\vert\langle E_0\vert\psi\rangle\vert^2\) |
|---|---|---|---|---|---|---|---|
Lipkin, \(N=4\) |
\(1\) |
\(8\) |
\(0\) |
\(-4.000000\) |
\(-4.212877\) |
\(-4.212877\) |
\(0.9358\) |
\(2\) |
\(16\) |
\(3\) |
\(-4.105370\) |
\(-4.212877\) |
\(-4.212877\) |
\(0.9726\) |
|
\(3\) |
\(24\) |
\(6\) |
\(-4.211395\) |
\(-4.212877\) |
\(-4.212877\) |
\(0.9998\) |
|
pairing, \(L=4\) |
\(1\) |
\(8\) |
\(0\) |
\(-0.500000\) |
\(-0.779164\) |
\(0.635548\) |
\(0.0000\) |
\(2\) |
\(16\) |
\(3\) |
\(-0.622012\) |
\(-0.779164\) |
\(0.635548\) |
\(0.0000\) |
|
\(3\) |
\(24\) |
\(6\) |
\(-0.779164\) |
\(-0.779164\) |
\(0.635548\) |
\(0.0000\) |
|
Hubbard ring |
\(1\) |
\(16\) |
\(0\) |
\(-1.527864\) |
\(-3.418551\) |
\(-2.102748\) |
\(0.0067\) |
\(2\) |
\(32\) |
\(7\) |
\(-2.000000\) |
\(-3.418551\) |
\(-2.102748\) |
\(0.0000\) |
|
Heisenberg ring |
\(1\) |
\(8\) |
\(0\) |
\(-1.000000\) |
\(-2.000000\) |
\(-2.000000\) |
\(0.3333\) |
\(2\) |
\(16\) |
\(3\) |
\(-1.619494\) |
\(-2.000000\) |
\(-2.000000\) |
\(0.7994\) |
|
\(3\) |
\(24\) |
\(6\) |
\(-1.914214\) |
\(-2.000000\) |
\(-2.000000\) |
\(0.9714\) |
Table 6.5: The hardware-efficient ansatz on the four models, best of four
random restarts of BFGS (two for Hubbard). Parameters and CNOT counts, the variational
energy, the lowest eigenvalue of the register, the exact energy of the
physical sector, and the overlap of the optimized state with the sector
ground state. Produced by vqe_models.py.
The table is a catalog of what can go wrong, and each row is instructive. The one-layer rows have no entangling gate at all, so they are mean-field calculations, product states optimized over their angles: for the Lipkin model the result, \(-4\), is the Hartree–Fock energy of Section Stability and the Lipkin model with an overlap \(0.9358\) that is exactly the overlap of the reference state in Table 5.9, because at this coupling the mean field is the reference; for the Heisenberg ring it is the Néel energy \(-1\) with the Néel overlap \(1/3\). Adding layers helps the Lipkin and Heisenberg models, and at three layers their errors are about \(1.5\times10^{-3}\) and \(8.6\times10^{-2}\) with overlaps of \(0.9998\) and \(0.97\), good enough to make either an excellent input for phase estimation. Neither is exact, and the Lipkin error is the characteristic one: the exact ground state is symmetric under every permutation of the four qubits, the CNOT ladder singles out a direction along the chain, and the symmetric state can only be represented by coordinated values of \(24\) parameters. The observed error does not by itself distinguish a restriction of the ansatz from an optimizer that has not found its global minimum. The pairing rows are the failure of Section Two qubits: the two-mode Hamiltonian at full size. The physical ground state, \(0.635548\), is the lowest state with two pairs; the register also contains the sectors with zero, one, three and four pairs, and the lowest eigenvalue of all of them is \(-0.779164\) in the one-pair sector. The ansatz has no reason to stay at two pairs, so with three layers it finds \(-0.779164\) exactly, with zero overlap with the state we wanted, and the “error” of \(-1.4\) in the comparison table below is not an error of the optimizer at all. The Hubbard rows fail in the same way and more slowly: the register minimum \(-3.418551\) lies in another particle-number sector, the two-layer circuit with \(32\) parameters and \(7\) CNOT gates reaches \(-2.000000\) with no overlap with the four-particle ground state, and adding layers enlarges the unconstrained search space without restoring the target particle number. The lesson is the one stated in Section Ansätze that know the physics. The runs terminated under the numerical stopping criteria; this does not certify a global minimum or the correct sector. Particle-number statistics, symmetry checks and comparisons across ansätze remain useful when exact reference energies are unavailable.
Ansätze that know the physics#
Table 6.6 repeats the calculation with the circuits of Section Ansätze that know the physics, chosen for each model from what Chapter 3 knows about it.
model |
ansatz |
param. |
\(E_{\mathrm{VQE}}\) |
error |
\(\vert\langle E_0\vert\psi\rangle\vert^2\) |
|---|---|---|---|---|---|
Lipkin, \(N=4\) |
mean field, one \(R_y\) angle |
\(1\) |
\(-4.00000000\) |
\(2.1\times10^{-1}\) |
\(0.935763\) |
HVA, \(1\) layer |
\(3\) |
\(-4.21238352\) |
\(4.9\times10^{-4}\) |
\(0.999939\) |
|
HVA, \(2\) layers |
\(6\) |
\(-4.21287670\) |
\(<10^{-14}\) |
\(1.000000\) |
|
pairing, \(L=4\) |
four pair excitations (UCCD) |
\(4\) |
\(0.63698698\) |
\(1.4\times10^{-3}\) |
\(0.999822\) |
all six pair transfers |
\(6\) |
\(0.63554847\) |
\(<10^{-14}\) |
\(1.000000\) |
|
Hubbard ring |
HVA, \(1\) layer, \(U_0=0.01t\) |
\(2\) |
\(-1.97671868\) |
\(1.3\times10^{-1}\) |
\(0.988473\) |
HVA, \(2\) layers |
\(4\) |
\(-2.10274848\) |
\(<10^{-14}\) |
\(1.000000\) |
|
Heisenberg ring |
HVA, \(1\) layer, from singlets |
\(2\) |
\(-2.00000000\) |
\(<10^{-14}\) |
\(1.000000\) |
Table 6.6: Ansätze built from the physics of each model, best of four
random restarts (two for the eight-qubit Hubbard ring): the number of
parameters, the variational energy, its error, and the overlap of the
optimized state with the exact ground state. HVA is the
Hamiltonian-variational ansatz of Eq. (6.11). Produced by
vqe_models.py.
For the Lipkin model the Hamiltonian of Eq. (3.73)
has three groups of internally commuting strings, its \(Z\), \(XX\) and
\(YY\) parts, which do not commute with one another, so a layer of
the Hamiltonian-variational ansatz is three angles; the generators are
built from the collective quasispin operators and commute with the
permutations of the qubits, so the ansatz lives in the symmetric
subspace from the start, and two layers, six parameters, give the exact
energy where \(24\) hardware-efficient parameters gave \(10^{-3}\). One
layer already has an overlap of \(0.99994\). For the pairing model the
four pair excitations from the reference \(\vert 1100\rangle\) are the
one-step unitary coupled-cluster circuit of Eq. (3.90),
and the energy \(0.63698698\) is the UCCD value of Table 3.23,
reproduced here by the general PauliRotationAnsatz rather than
by the hand-built circuit of Section A first variational circuit: unitary coupled cluster for the pairing model; it misses the
exact answer by \(1.4\times10^{-3}\) in the reported optimization. Four real parameters cannot cover all
normalized real states of the six-dimensional two-pair space, but this
dimension count alone does not prove that the particular ground state
is unreachable. Adding the two remaining pair transfers, between the two occupied
and between the two empty levels, which are not excitations of the
reference but rotations within it once the first four have acted, gives
a circuit of six angles that is exact. The Hubbard ring illustrates the
other requirement of the Hamiltonian-variational ansatz, a reference
with the right symmetries. The Néel determinant of
Table 5.9 has an overlap of \(0.24\) and, being a
product state, is not an eigenstate of the hopping term; the natural
alternative is the ground state of the non-interacting ring, but at
\(U=0\) and half filling that state is six-fold degenerate in the full \(N=4\) sector and four-fold degenerate
when \(S_z=0\) is also imposed. Its members have different overlaps with
the interacting ground state; an arbitrary eigensolver basis vector is
not a uniquely defined reference. The program takes instead the ground state at
\(U=0.01t\), a weakly interacting state approaching the combination selected by
degenerate perturbation theory, with an overlap of \(0.8509\), and alternates the on-site and the
hopping terms: one layer gives \(-1.9767\), two layers with four angles
give \(-2.10274848\) to numerical precision. The reference was obtained
by exact diagonalization and the two exponentials by dense matrices.
A scalable preparation of that reference and synthesis of the hopping
unitary are additional requirements for a hardware implementation. The Heisenberg ring is the most striking
row. The reference is the product of two singlets on the bonds \((0,1)\)
and \((2,3)\), the ground state of the even-bond half of the Hamiltonian,
and one layer of the odd and the even bond groups, two angles, gives the
exact ground state \(-2\); Section Letting the algorithm choose the circuit: ADAPT-VQE will show that a
single well-chosen operator suffices. Figure 6.8
shows gradient-descent histories at three HVA layers for Lipkin and
Hubbard, two HVA layers for Heisenberg, and six pair transfers for pairing, and it is worth noticing that the Lipkin
curve stalls at \(5\times10^{-4}\), the value of the one-layer ansatz: plain
descent from this start stalls, whereas BFGS with restarts finds a lower
energy. A flat history alone does not prove that the stationary point
is a local minimum.

Figure 6.8: Gradient-descent histories from random starts: three HVA layers for Lipkin and Hubbard, two for Heisenberg, and six pair transfers for pairing. These include deeper circuits than those tabulated. Gradients use shift rules where supported and noiseless finite differences otherwise. The Lipkin curve stalls near the one-layer energy. Produced by vqe_models.py.
Phase estimation and VQE weighed against each other#
Table 6.7 puts the results of this chapter and the last side by side: the error of phase estimation with ten control qubits and the exact evolution operator, from Table 5.7, against the best hardware-efficient and physically motivated variational energies. These are numerical accuracy comparisons, not equal-resource benchmarks: QPE uses a finite clock and exact evolution, while VQE uses exact expectation values and dense simulation of its generators.
model |
QPE, \(m=10\) |
VQE, hardware-efficient |
VQE, physics |
|---|---|---|---|
Lipkin, \(N=4\) |
\(5.9\times10^{-3}\) |
\(+1.5\times10^{-3}\) |
\(<10^{-14}\) |
pairing, \(L=4\) |
\(7.3\times10^{-3}\) |
\(-1.4\) (wrong sector) |
\(<10^{-14}\) |
Hubbard ring |
\(1.7\times10^{-2}\) |
\(+1.0\times10^{-1}\) |
\(<10^{-14}\) |
Heisenberg ring |
\(1.3\times10^{-3}\) |
\(+8.6\times10^{-2}\) |
\(0\) |
Table 6.7: The four models: the error of phase estimation with \(m=10\)
control qubits and exact evolution (Table 5.7), the
signed error of the best hardware-efficient energy of
Table 6.5, and the error of the best physically motivated
ansatz of Table 6.6. The negative hardware-efficient
entry for the pairing model is a minimum in the wrong particle-number
sector, not a violation of the variational principle. Produced by
vqe_models.py.
For an eigenstate input and the signed, nonaliasing phase convention of Chapter 5, standard QPE assigns probability at least \(4/\pi^2\) to the nearest phase-grid point. A trial state contributes its spectral weights to the outcome distribution. Ground-space overlap is therefore one factor in success, and finite-clock leakage is another. Poor overlap need not be exponentially small for every correlated system, and a strong peak can belong to the wrong eigenstate. An identity-shift or phase-aliasing mistake can also look plausible. QPE is not self-certifying simply because its ideal resolution is known.
With a spectral scale \(\Lambda\) and fixed confidence, a basic phase estimation construction uses \(\bigO(\log(\Lambda/\epsilon))\) control qubits and total evolution time of order \(1/\epsilon\); converting this into a gate count requires a Hamiltonian-simulation algorithm and error budget. Independent-shot VQE energy estimation has a sufficient worst-case cost \(\bigO(\Lambda^2/\epsilon^2)\) per energy under the sampling assumptions of Section Shot noise, and what it costs the loop. It also needs an optimization budget and control of ansatz error. Repetition reduces sampling noise, not arbitrary device bias or ansatz error. Comparing these expressions alone cannot determine a hardware crossover, and the exact-simulator energies in the table do not establish noise tolerance or quantum advantage.
VQE can nevertheless provide useful input states for QPE. The three-layer Lipkin overlap \(0.9998\) is the probability weight of the ground component, not the probability of a particular finite-clock bit string. Even an exact eigenstate normally produces several clock outcomes unless its phase is exactly representable. Conditioning on one outcome generally filters a superposition of eigenstates rather than projecting exactly onto one; Section The state you start from gives the finite-resolution conditional state. Resolved spectral weights, repeated outcomes and known gap information can strengthen the assessment of a variational state. The combined method still requires both successful preparation and affordable coherent evolution; the scaling of those requirements is central to the assessment in [Lee2023].
Excited states. Variational quantum deflation [Higgott2019] replaces \(\hat H\) by \(\hat H+\mu|E_0\rangle\langle E_0|\). For an exact, nondegenerate ground state, \(\mu>E_1-E_0\) makes the first excited eigenspace the ground eigenspace of this modified operator. An approximate ground state perturbs this argument, a degenerate ground space requires all of its components to be deflated, and the search ansatz must be able to reach the desired excited symmetry sector. If \(|\psi_j\rangle=U_j|0\cdots0\rangle\), the overlap with a trial state \(U(\vec\theta)|0\cdots0\rangle\) is the all-zero probability after \(U_j^\dagger U(\vec\theta)\). Quantum subspace expansion instead measures Hamiltonian and overlap matrices in a selected excitation space and solves a generalized eigenvalue problem [McClean2017QSE]; Section Non-orthogonal bases and the generalized eigenvalue problem shows how the conditioning of the overlap matrix and the noise of the measured matrix elements limit such methods.
There is a useful warning in the Lipkin example. The three HVA pieces preserve promotion parity, so their action on \(|0000\rangle\) stays even. The first excited state of the \(J=2\) multiplet at the stated coupling is odd, with energy about \(-2.986068\). Deflating the even ground state while keeping that ansatz cannot find it. One can optimize from an odd symmetric reference or enlarge the generator set. Exercise 6.8 makes this reachability check part of the calculation.
Letting the algorithm choose the circuit: ADAPT-VQE#
Every ansatz of Section The model Hamiltonians was chosen by hand from what we knew about the model, and the tables show how much that choice matters. The adaptive variational quantum eigensolver of Grimsley, Economou, Barnes and Mayhall [Grimsley2019], ADAPT-VQE, makes the choice part of the algorithm. One supplies a reference state and a pool of Hermitian generators \(\{G_j\}\), and the circuit of Eq. (6.10) is grown one generator at a time.
The algorithm. Start from \(\vert\psi\rangle=\vert\Phi_0\rangle\) with an empty circuit. At every step, for every generator in the pool, measure the derivative of the energy with respect to a new angle inserted at the end of the current circuit and evaluated at zero,
where \(\vert\psi\rangle\) is the current optimized state. If the largest \(\vert\)gradient\(\vert\) is below a threshold, stop. Otherwise append \(e^{-i\theta G_j}\) for the generator with the largest gradient, with \(\theta=0\) as its starting value, re-optimize all the angles of the circuit by the VQE loop, and repeat. On hardware the commutator of Eq. (6.32) is a Pauli sum whose expectation value is measured like any other. A pool scan requires the expectations of all these commutators, whose numbers of strings, grouping and covariances can differ substantially from those of \(\hat H\). Shared measurements may be reused. Thus the scan cost is not simply one ordinary energy measurement per generator. The method often produces compact circuits, but it does not guarantee the shortest circuit or convergence to the ground state. A small pool gradient only excludes a first-order decrease along the available directions; the Lipkin example below illustrates the limitation. Generator normalization matters when comparing gradient magnitudes.
The class
AdaptVQE in adapt_vqe.py does all of this on the
simulator.
import numpy as np
from qpe_models import book_models
from vqe_models import pair_generator
from adapt_vqe import AdaptVQE
H = {name: H for name, H, E0, psi, sector in book_models()}["pairing, $L=4$"]
pool = [pair_generator(4, i, a) for i in range(4) for a in range(i + 1, 4)] # six pair transfers
labels = [f"P{i}{a}" for i in range(4) for a in range(i + 1, 4)]
adapt = AdaptVQE(H, "1100", pool, labels)
theta, E = adapt.run(max_ops=8, tol=1e-6, verbose=True)
print(adapt.chosen, E) # five operators, E = 0.63554847
step 1: added P02 (|grad| = 1.00e+00), E = 0.93844719
step 2: added P03 (|grad| = 1.11e+00), E = 0.88724986
step 3: added P12 (|grad| = 1.12e+00), E = 0.73887005
step 4: added P13 (|grad| = 1.27e+00), E = 0.63698698
step 5: added P23 (|grad| = 1.14e-02), E = 0.63554847
stop: pool_gradient_threshold; max pool gradient 2.86e-10
['P02', 'P03', 'P12', 'P13', 'P23'] 0.6355484735755967
The run prints, step by step, the operator chosen, its gradient and the re-optimized energy.
Pools. The pool is where the physics enters, and three kinds are used below. For a fermionic system the natural pool is the set of spin-conserving singles and doubles, \(i(a^{\dagger}_qa_p-\mathrm{h.c.})\) and \(i(a^{\dagger}_ra^{\dagger}_ta_qa_p-\mathrm{h.c.})\), in the Jordan–Wigner encoding, which is the pool of the original fermionic ADAPT-VQE and is what unitary coupled cluster would use all at once; for the pairing model in the compact encoding it is the six pair transfers \(-\frac12(Y_iX_a-X_iY_a)\) between all pairs of levels. For a spin model one can use the qubit pool of [Tang2021], the individual Pauli strings of low weight, which are cheaper to exponentiate than the fermionic operators and give up the particle-number conservation; or operators built from the symmetries of the model, the collective quasispin operators of the Lipkin model or, for the Heisenberg ring, the bond spin currents \(X_iY_j-Y_iX_j\) and the scalar chiralities \(\vec{S}_i\cdot(\vec{S}_j\times\vec{S}_k)\). One condition is common to all of them and easy to get wrong. The Hamiltonians of this book are real symmetric matrices and their ground states can be chosen real, and a real reference state has, for any real generator \(G\), a gradient that vanishes identically, since \(\langle\psi\vert[G,\hat{H}]\vert\psi\rangle\) is the difference of a real number and its transpose. A pool of real generators, strings with an even number of \(Y\)’s, therefore supplies no first-order direction from a real reference, and the algorithm stops at step zero reporting convergence. Every generator below is imaginary, a string with an odd number of \(Y\)’s or a real combination of such strings, so that \(e^{-i\theta G}\) is a real orthogonal matrix and the state stays real while gradients can be nonzero. This choice alone does not ensure that the pool is sufficient or equally normalized. The same reality is what made the single excitation of Eq. (3.83) a combination of \(YX\) and \(XY\) strings and the pair excitation of Eq. (3.88) likewise.
model |
reference, pool |
pool |
ops |
\(E_{\mathrm{ADAPT}}\) |
error |
\(\vert\langle E_0\vert\psi\rangle\vert^2\) |
|---|---|---|---|---|---|---|
pairing, \(L=4\) |
\(\vert 1100\rangle\), six pair transfers |
\(6\) |
\(5\) |
\(0.63554847\) |
\(<10^{-14}\) |
\(1.000000\) |
Lipkin, \(N=4\) |
\(\vert 0000\rangle\), qubit pool |
\(28\) |
\(7\) |
\(-4.21287670\) |
\(<10^{-13}\) |
\(1.000000\) |
\(\vert 0000\rangle\), collective \((2)\) |
\(2\) |
\(1\) |
\(-4.21240735\) |
\(4.7\times10^{-4}\) |
\(0.999942\) |
|
\(\vert 0000\rangle\), collective \((3)\) |
\(3\) |
\(2\) |
\(-4.21287670\) |
\(<10^{-14}\) |
\(1.000000\) |
|
Heisenberg ring |
singlet covering, currents and chiralities |
\(8\) |
\(1\) |
\(-2.00000000\) |
\(<10^{-14}\) |
\(1.000000\) |
Néel \(\vert 0101\rangle\), same pool |
\(8\) |
\(3\) |
\(-2.00000000\) |
\(<10^{-14}\) |
\(1.000000\) |
|
Hubbard ring |
\(U_0=0.01t\) ground state, singles and doubles |
\(162\) |
\(12\) |
\(-2.09135394\) |
\(1.1\times10^{-2}\) |
\(0.997668\) |
Table 6.8: ADAPT-VQE on the four models: the pool, its size, the number of
operators in the final circuit, the energy, its error and the overlap
with the exact ground state. The gradient threshold is \(10^{-6}\); the
Hubbard run is stopped at twelve operators. Produced by
adapt_vqe.py.

Figure 6.9: The energy error of ADAPT-VQE against the number of operators in the circuit, for the runs of Table 6.8. Errors below \(10^{-13}\) are drawn at that value. Produced by adapt_vqe.py.
Results. Table 6.8 and Fig. 6.9 collect the runs. For the pairing model the algorithm chooses, in order, the four excitations from the occupied levels \(0\) and \(1\) to the empty levels \(2\) and \(3\), with gradients of order one, and after these four it is at \(0.63698698\), which is exactly the UCCD energy of Table 6.6: it has rebuilt the unitary coupled-cluster circuit by itself. The fifth operator, the transfer between the empty levels \(2\) and \(3\), has a gradient of \(1.1\times10^{-2}\), small but not zero, and it takes the energy to the exact value; the sixth, between the occupied levels, is then never needed, since every remaining gradient is below \(10^{-6}\). For the Lipkin model the qubit pool of the \(28\) one- and two-qubit strings with one \(Y\) needs seven operators, all of them \(X_pY_q\) or \(Y_pX_q\) type, and it is exact, so that the number-breaking strings have not hurt here; the collective pool with three operators needs two, the third-order \(i(J_+^2J_z-J_zJ_-^2)\) first with a gradient of \(16\) and then \(i(J_+^2-J_-^2)\), and is exact. The collective pool with two operators is the instructive failure. It contains \(i(J_+-J_-)\), which changes the quasispin projection by one, and \(i(J_+^2-J_-^2)\), which changes it by two; the Hamiltonian of Eq. (3.73) conserves the parity of \(m\), so that the first operator has a gradient that vanishes by symmetry in every state the second one can reach from the reference, and the second, once optimized, has a gradient that vanishes because it is at its own minimum. After one operator every gradient in the pool is zero, the algorithm reports convergence, and the energy is \(4.7\times10^{-4}\) too high, the exact ground state in the three-dimensional even-parity subspace needing two real angles that one operator cannot supply. This is the gradient trap: a zero gradient means only that no operator of the pool, applied once, lowers the energy to first order, and a pool that is too small, or whose operators are forbidden by a symmetry from connecting the current state to the target, produces a confident and wrong convergence. It is the adaptive version of the quiet failure of Section Phase estimation and VQE weighed against each other, and the remedy is the same, checking reachability, adding useful directions and testing for stationary traps. Lie-algebraic controllability of a pool does not by itself guarantee that this greedy first-order procedure avoids traps.
The Heisenberg ring is the success of the section. From the Néel state the algorithm takes the two bond currents on \((0,1)\) and \((2,3)\), which rotate the two Néel bonds into singlets, and then a scalar chirality on three adjacent sites (the run chooses \(3,0,1\)), three operators, and is exact. From the singlet covering it needs only the chirality: a single operator with a single angle takes the product of two singlets to the exact ground state of the ring, \(-2\), to machine precision. The ground state of the four-site Heisenberg ring is a specific superposition of the two singlet coverings, and the chirality generator, which acts within the singlet space as a rotation between suitable linear combinations of the coverings, is the operator that connects them; no hardware-efficient circuit of Table 6.5 came within \(8\times10^{-2}\) of what one well-chosen generator does exactly. The Hubbard ring is the honest case. From the weak-coupling reference with the full pool of \(162\) spin-conserving singles and doubles, the algorithm chooses twelve doubles, with the gradients printed by the program, and after twelve it is \(1.1\times10^{-2}\) above the exact energy with an overlap of \(0.9977\), still improving. Operator count is not circuit depth: synthesizing these generators and preparing the weak-coupling reference must be costed separately. The implemented pool also includes transfers with overlapping mode indices, for which the four-distinct-mode eight-string count does not apply. The two-layer Hamiltonian-variational ansatz of Table 6.6 was exact with four parameters, because its generators, the whole hopping term and the whole interaction, are the right collective operators for this problem in the way that the chirality was for the Heisenberg ring; a pool of individual excitations rebuilds them one piece at a time. That is the general trade-off of the adaptive method, and it is worth stating plainly: ADAPT-VQE removes the need to guess an ansatz, and replaces it with the need to guess a pool.
A second variational algorithm: QAOA#
The variational loop of Fig. 6.1 does not care where the Hamiltonian came from. This last section applies it to a Hamiltonian that is diagonal in the computational basis and encodes a combinatorial optimization problem, so that its ground eigenspace is spanned by optimal bit strings and the “energy” is the cost of a candidate solution. The algorithm that does this, the quantum approximate optimization algorithm of Farhi, Goldstone and Gutmann [Farhi2014], is a VQE with a fixed and very particular ansatz, alternating exponentials of the cost Hamiltonian and of a transverse field, and it is included here for three reasons. It is the form in which variational quantum computing is most often encountered outside physics; its ansatz is motivated by a product formula for adiabatic evolution, the Trotterized path of Section Time-dependent Hamiltonians and adiabatic preparation with optimized step lengths; and it is the bridge to quantum machine learning, the subject of Part II, where Chapter 10 develops the algorithm in full.
From a combinatorial problem to a Hamiltonian#
A large class of combinatorial problems can be written as quadratic unconstrained binary optimization, QUBO: minimize
over the \(2^n\) bit strings, with a real matrix \(\matr{Q}\) that holds the problem; since \(x_i^2=x_i\) the diagonal carries the linear terms. Constraints are added as penalties, and the reduction of a problem to this form is a craft of its own. The substitution \(x_i=(1-s_i)/2\) with \(s_i=\pm1\) turns Eq. (6.33) into a classical Ising energy,
and replacing \(s_i\) by the Pauli matrix \(Z_i\), whose eigenvalue on \(\vert x_i\rangle\) is \((-1)^{x_i}=s_i\), gives the cost Hamiltonian
a Pauli sum of weight at most two, diagonal in the computational basis, with \(\hat{H}_C\vert\vec{x}\rangle=(C(\vec{x})-c)\vert\vec{x}\rangle\). The ground eigenspace of \(\hat{H}_C\) is spanned by the optimal bit strings, and the many-body problem has become a spin glass. Table 6.9 carries the two-variable example \(\matr{Q}=\begin{pmatrix}1&-2\\-2&1\end{pmatrix}\) through: \(J_{01}=-1\), \(h_0=h_1=\frac12\), \(c=0\), so that \(\hat{H}_C=-Z_0Z_1+\frac12(Z_0+Z_1)\), and its diagonal reproduces \(\vec{x}^T\matr{Q}\vec{x}\) bit string by bit string, with the minimum \(-2\) at \(\vec{x}=(1,1)\).
\(\vec{x}\) |
\((s_0,s_1)\) |
\(\vec{x}^T\matr{Q}\vec{x}\) |
\(\langle\vec{x}\vert\hat{H}_C\vert\vec{x}\rangle\) |
|---|---|---|---|
\(00\) |
\((+1,+1)\) |
\(0\) |
\(0\) |
\(01\) |
\((+1,-1)\) |
\(1\) |
\(1\) |
\(10\) |
\((-1,+1)\) |
\(1\) |
\(1\) |
\(11\) |
\((-1,-1)\) |
\(-2\) |
\(-2\) |
Table 6.9: The QUBO with \(Q_{00}=Q_{11}=1\), \(Q_{01}=Q_{10}=-2\) and its
Ising form \(\hat{H}_C=-Z_0Z_1+\frac12(Z_0+Z_1)\), evaluated on every bit
string. Produced by qaoa_basics.py.
The standard example, used for the rest of the section, is MaxCut: given a graph with vertices \(V\) and edges \(E\), partition the vertices into two sets so that as many edges as possible cross the partition. With \(z_i=\pm1\) marking the side of vertex \(i\), an edge \((i,j)\) is cut when \(z_i\ne z_j\), that is when \((1-z_iz_j)/2=1\), so that the number of cut edges is the eigenvalue of
on \(\vert\vec{z}\rangle\), and MaxCut is the search for the largest eigenvalue of \(\hat{H}_C\), a maximization; the two conventions differ by a sign and we keep the maximization, as the literature does. MaxCut is NP-hard, and the Goemans–Williamson semidefinite relaxation with randomized rounding has an expected approximation guarantee of about \(0.87856\) on graphs with nonnegative edge weights [GoemansWilliamson1995].
The ansatz and where it comes from#
The QAOA state of depth \(p\) is
with \(2p\) real parameters, and the algorithm maximizes \(F_p(\vec{\gamma},\vec{\beta})=\langle\vec{\gamma},\vec{\beta}\vert\hat{H}_C\vert\vec{\gamma},\vec{\beta}\rangle\) by the loop of Fig. 6.1, then samples the optimized state in the computational basis and keeps the best bit string seen. The two exponentials are the phase separator and the mixer. The first is diagonal, \(e^{-i\gamma\hat{H}_C}\vert\vec{z}\rangle=e^{-i\gamma C(\vec{z})}\vert\vec{z}\rangle\), and imprints on every bit string a phase proportional to its cost; for MaxCut it is one \(e^{i\gamma Z_iZ_j/2}\) per edge, a CNOT, an \(R_z(-\gamma)\) and a CNOT, the gadget of Fig. 3.5, and all the edges commute so that their order is immaterial. With direct edge connectivity, disjoint-edge scheduling uses the edge-chromatic number of interaction rounds (between the maximum degree and one more for simple graphs); CNOT decomposition and routing add further depth. The second is a product of single-qubit rotations \(e^{-i\beta X_q}=R_x(2\beta)\) that turn the phases into amplitudes; without it nothing would ever change the outcome probabilities, which are uniform in \(\vert{+}\rangle^{\otimes n}\). Figure 6.10 shows one layer for a single edge. The state is periodic up to a global phase in \(\gamma\) with period \(2\pi\) when all cost differences are integers, and in \(\beta\) with period \(\pi\), and the function \(F_p\) inherits the symmetries of the graph, so that the angle domain is periodic. Its dimension is still \(2p\), and periodicity does not imply easy optimization. Weighted costs generally do not share the \(2\pi\) period in \(\gamma\).

Figure 6.10: One QAOA layer for MaxCut on a single edge: the uniform superposition, the phase separator \(e^{-i\gamma(I-Z_0Z_1)/2}\) as a CNOT, \(R_z(-\gamma)\), CNOT (up to a global phase), the mixer \(R_x(2\beta)\) on both qubits, and the readout. For a graph the phase separator is one such gadget per edge; for depth \(p\) the two blocks are repeated with their own angles.
The adiabatic motivation [Farhi2000] starts with the ground state \(|+\rangle^{\otimes n}\) of \(-\hat H_M\) and interpolates toward the maximizers of \(\hat H_C\) using
Adiabatic following requires control of the relevant spectral gap and schedule, including treatment of a degenerate final optimum. A first-order product formula for a step of duration \(\Delta t\) is \(e^{+i(1-s_l)\Delta t\hat H_M}e^{+is_l\Delta t\hat H_C}\). Thus Eq. (6.37) contains the discretized schedule with \(\beta_l=-(1-s_l)\Delta t\) and \(\gamma_l=-s_l\Delta t\). The minus signs follow from the maximization convention. QAOA frees these angles for optimization; they need not follow an adiabatic schedule.
Define \(F_p^\star=\max_{\vec\gamma,\vec\beta}F_p\). Appending a layer with zero angles embeds the depth-\(p\) family into depth \(p+1\), hence \(F_{p+1}^\star\ge F_p^\star\). Local optimizers need not find this global optimum or produce a monotone sequence. For a fixed finite instance, the family can approach the optimal cost through sufficiently slow, finely discretized evolution [Farhi2014]; this gives no efficient rate in system size or depth.
For MaxCut the product-formula commutator is
This is an evolution error when approximating a prescribed schedule. As a variational circuit the finite product defines its own family; re-optimization may improve its energy but does not make that family equal to the continuous-evolution family or remove all approximation error. This is the same distinction made for factorized UCC in Section Trotterized unitary coupled cluster. The QAOA construction is also an HVA with cost and mixer pieces, with their signs absorbed into the angles.
What can be computed by hand, and what the program finds#
At \(p=1\) the expectation value of one edge term can be computed in closed form, and the calculation is short enough to be worth doing. For a single edge the operator \(Z_0Z_1\) is carried through the mixer in the Heisenberg picture, \(e^{i\beta X}Ze^{-i\beta X}=\cos2\beta\,Z+\sin2\beta\,Y\) on each qubit, so that \(Z_0Z_1\to\cos^22\beta\,Z_0Z_1+\sin2\beta\cos2\beta\,(Z_0Y_1+Y_0Z_1)+\sin^22\beta\,Y_0Y_1\); then through the phase separator, where \(Z_0Z_1\) and \(Y_0Y_1\) commute with \(Z_0Z_1\) and have zero expectation in \(\vert{+}{+}\rangle\), while \(e^{-i\gamma Z_0Z_1/2}\) conjugating \(Z_0Y_1\) gives \(\cos\gamma\,Z_0Y_1-\sin\gamma\,X_1\), whose expectation in \(\vert{+}{+}\rangle\) is \(-\sin\gamma\), and the same for \(Y_0Z_1\). Together,
which the program verifies against the simulator on a grid of \(13\times11\) angles to \(7\times10^{-16}\), and whose maximum, \(F_1=1\) at \(\gamma=\pi/2\), \(\beta=\pi/8\), solves the one-edge problem exactly. On a graph the same calculation gives, for an edge \((u,v)\) that belongs to no triangle and whose end points have degrees \(d_u\) and \(d_v\), \(\langle C_{uv}\rangle=\frac12+\frac14\sin4\beta\sin\gamma\,(\cos^{d_u-1}\gamma+\cos^{d_v-1}\gamma)\), because every other edge at \(u\) contributes a factor \(\cos\gamma\) when the phase separator is carried through; for a cycle with \(n\ge4\), \(d=2\) at every vertex,
with maximum \(3n/4\), which the program also verifies. For an even cycle, \(C_{\max}=n\) and the ratio \(3/4\) of the optimum at \(p=1\) is the number Farhi, Goldstone and Gutmann computed in the original paper, and it is below the Goemans–Williamson guarantee. An odd cycle has \(C_{\max}=n-1\), so its ratio is \(3n/[4(n-1)]\). A triangle is excluded from the derivation. The cycle comparison is illustrative: its optimum is easy to find classically, and two small graphs do not establish performance on difficult families.
graph |
\(p\) |
\(F_p\) |
\(F_p/C_{\max}\) |
\(P(\text{optimal cut})\) |
|---|---|---|---|---|
ring \(C_4\) |
\(1\) |
\(3.0000\) |
\(0.7500\) |
\(0.5312\) |
\(2\) |
\(4.0000\) |
\(1.0000\) |
\(1.0000\) |
|
\(3\) |
\(4.0000\) |
\(1.0000\) |
\(1.0000\) |
|
prism, \(6\) vertices |
\(1\) |
\(5.9392\) |
\(0.8485\) |
\(0.4008\) |
\(2\) |
\(6.6029\) |
\(0.9433\) |
\(0.7209\) |
|
\(3\) |
\(6.8780\) |
\(0.9826\) |
\(0.9233\) |
Table 6.10: QAOA for MaxCut on the four-vertex ring (\(C_{\max}=4\)) and on
the six-vertex prism graph, two triangles joined by three edges
(\(C_{\max}=7\)): the optimized expectation value \(F_p\), the
approximation ratio \(F_p/C_{\max}\), and the probability that a sample
of the optimized state is an optimal cut, for depths \(p=1,2,3\), best of
ten random starts. Produced by qaoa_basics.py.
Table 6.10 and Figs. 6.11 and 6.12 show what the program finds. On the ring, \(p=1\) gives \(3/4\) as the formula says, and the landscape of Fig. 6.11 is the function of Eq. (6.41), smooth and periodic with its maxima where \(\sin4\beta\sin2\gamma=1\); \(p=2\) is exact, \(F_2=4\), and the optimized state is a superposition of the two optimal cuts and nothing else. The four-vertex ring is a bipartite graph, and a depth of two suffices for it in the same way that two layers of the Hamiltonian-variational ansatz sufficed for the Hubbard ring. The six-vertex prism graph, which has triangles and is not bipartite, illustrates gradual concentration with depth: the ratio climbs from \(0.85\) at \(p=1\) through \(0.94\) to \(0.98\) at \(p=3\), and the probability of sampling one of the six optimal cuts from \(0.40\) to \(0.92\), so that after three layers one shot succeeds with probability about \(0.923\), and \(M\) independent shots succeed at least once with probability \(1-(1-0.923)^M\); Fig. 6.12 shows the six optimal strings rising out of the distribution as \(p\) grows. What is being bought with depth is concentration, and Fig. 6.12 is the picture to keep in mind: the algorithm does not compute the cut, it prepares a distribution from which the cut is likely to be drawn. The measurement uses a single computational-basis setting because \(\hat H_C\) is diagonal. Both \(\gamma_l\) and \(\beta_l\) multiply sums of commuting operators with multiple spectral gaps; use a suitable generalized shift or differentiate the individual gate occurrences with tied angles. The program uses noiseless finite differences and ten random starts, not a hardware gradient experiment. Trainability depends on depth, graph, initialization and noise, rather than following a universal barren-plateau rule. Assessing practical advantage requires classical baselines, total optimization cost and sampling confidence beyond these small examples.

Figure 6.11: The \(p=1\) landscape \(F_1(\gamma,\beta)\) of QAOA for MaxCut on the four-vertex ring, Eq. (6.41), over one period in each angle; the star is the optimum found by the program, \(F_1=3\). Produced by qaoa_basics.py.

Figure 6.12: Output distributions of the optimized QAOA state for MaxCut on the six-vertex prism graph at depths \(p=1\), \(2\) and \(3\), over the \(64\) bit strings; the six optimal cuts are drawn in red. Produced by qaoa_basics.py.
Perspectives: variational circuits as machine-learning models#
QAOA is where the methods of Part I touch quantum machine learning, and it is worth seeing why before Part II takes up the subject. Read Eq. (6.37) once more. The matrix \(\matr{Q}\) of the QUBO is data: it could be the adjacency matrix of a graph, a covariance matrix of a portfolio, the couplings of a Hopfield network, or a distance matrix between samples, and the circuit is a parametrized function of that data whose parameters are trained by minimizing a cost. Optimizing each instance separately is variational optimization, not by itself machine learning; learning requires a specified data distribution, training objective and assessment of generalization. The general form, of which QAOA and VQE are both instances, is a parametrized circuit \(U(\vec{x},\vec{\theta})\) in which some gates carry the input \(\vec{x}\) and others the trainable parameters, and an output \(f(\vec{x};\vec{\theta})=\langle 0\vert U^{\dagger}\hat{O}U\vert 0\rangle\) for some observable \(\hat{O}\), the hybrid model of Eq. (8.1); the training loop is the loop of Fig. 6.1 with a loss function in the place of the energy, the gradients come from the same parameter-shift rule, and the difficulties are the same shot noise and the same barren plateaus, which in this setting are made worse by the need to evaluate the circuit on every sample of a training set. The data can also enter the way it enters QAOA, through the Hamiltonian whose exponential is the first layer, in which case the circuit’s output is a feature map \(\vec{x}\mapsto\vert\phi(\vec{x})\rangle\), and the overlap \(\vert\langle\phi(\vec{x})\vert\phi(\vec{x}')\rangle\vert^2\), measurable by the same method as the deflation overlap of Section Phase estimation and VQE weighed against each other, is a kernel that can be handed to a classical support-vector machine [Havlicek2019,Schuld2019kernel], as Chapter 9 does. Finally, the optimized QAOA state sampled in the computational basis is a generative model over bit strings, a Born machine, when trained to fit a target distribution. Ordinary MaxCut QAOA maximizes expected cut value and does not fit an arbitrary target distribution. The reviews [Biamonte2017,Cerezo2021] set out the field. Its questions, which models can be trained without barren plateaus, which kernels cannot be evaluated classically, and whether any of it has an advantage over classical learning on classical data, are the questions of Chapters 8 to 12; the questions of this part, whether a variational circuit can prepare the ground state of a many-body Hamiltonian that no classical method can reach, share their tools and not their answers, and the reader who has followed this chapter has what is needed to read either literature.
Summary#
VQE optimizes the expectation value of a Hamiltonian over a circuit family. Its exact energy obeys the variational bound; a finite-shot estimate has uncertainty, and a target-sector bound requires staying in that sector. Joint correlators are obtained by rotating the nonidentity support of each Pauli string, retaining the outcomes from each preparation, and averaging parities. For \(Y\), the chronological order is \(S^\dagger\) followed by \(H\), so the total basis-change unitary is \(HS^\dagger\). Products of local means instead evaluate the product of reduced states. Group covariance and shot allocation determine the measurement variance.
The two-term parameter-shift rule applies to a single occurrence of a two-eigenvalue generator; additional spectral gaps and shared parameters require appropriate generalized rules or the chain rule. SPSA estimates a gradient from two perturbed energies, with monitoring counted separately. Barren plateaus concern specified circuit ensembles and cost functions, not all variational families.
On the four benchmark Hamiltonians, physically motivated ansätze attain much lower target-sector errors than the tested generic circuits. The pairing and Hubbard examples show why minimizing energy without checking the particle sector can answer the wrong physical question. These dense simulations verify energies and overlaps, but do not establish efficient reference preparation or hardware implementation of collective generators. ADAPT-VQE can discover compact useful sequences, yet pool gradients may vanish away from the ground state. Excited-state searches also require explicit symmetry and reachability checks.
QPE and VQE address different resource constraints and can be combined: VQE prepares a trial state, while QPE resolves its spectral content at a cost in coherent evolution. Neither method automatically certifies all parts of that calculation. QAOA applies a related product ansatz to a classical cost Hamiltonian; its optimized expectation, probability of an optimal sample and total computational cost are distinct performance measures.
Exercises#
The variational principle on a circuit. (a) Prove Eq. (6.1) and show that equality holds if and only if \(\vert\psi\rangle\) lies in the ground-state eigenspace. (b) Show that the ansatz of Eq. (6.7) reaches every pure state of one qubit up to a global phase, and that \(R_y\) alone reaches every real state. Derive Eq. (6.31) and its minimum. (c) The hardware-efficient ansatz with \(L\) layers on \(n\) qubits has \(2nL\) parameters, while a general state has \(2^{n+1}-2\) real degrees of freedom. At what \(L\) do the counts match, and why does matching them not imply that the ansatz reaches every state? (d) Show that if a noisy device prepares a mixed state \(\rho\) instead of \(\vert\psi\rangle\langle\psi\vert\), then \(\mathrm{Tr}(\rho\hat{H})\ge E_0\) still holds. Which property of \(\rho\) does the work? (e) Explain why the two-layer hardware-efficient result of Table 6.4 is correct and nevertheless useless, and propose two ways of obtaining \(0.916905\): add a sufficiently strong number penalty, or replace the ansatz by number-conserving gates acting on a one-particle reference. Explain why changing only the reference of an unrestricted ansatz is insufficient. Test both approaches with
vqe.py.Measurement. (a) Verify \(HZH=X\) and \(HS^{\dagger}YSH=Z\) by direct multiplication. (b) Write down the measurement circuit for the string \(X\otimes Y\otimes Z\otimes I\) and the classical post-processing that turns an outcome bit string into \(\pm1\). (c) Derive Eq. (6.13) and show that the variance vanishes when \(\vert\psi\rangle\) is an eigenstate of \(P\). (d) Partition the strings of the Lipkin Hamiltonian of Eq. (3.73) into qubit-wise commuting groups by hand and compare with Table 3.21. (e) Reproduce Table 6.2 with
vqe_measurement.py, extend it to \(10^5\) shots, fit the standard error to \(aN^{-b}\) and check \(b=1/2\). Then repeat the whole VQE optimization of Table 6.5 for the Heisenberg ring with the energies drawn from \(10^2\), \(10^3\) and \(10^4\) shots per setting (the argumentshotsofVQE), using SPSA, and plot the converged energy against the shot count. At what shot count does the ansatz error dominate the statistical error?The marginal trap. (a) Compute the reduced density matrices of \(\vert\Phi^+\rangle\) and \(\vert\Psi^+\rangle\) and confirm the claim in the proof of Theorem 6.1. (b) Derive Eq. (6.20) and show that the error of the reconstruction equals the squared concurrence of the state. (c) Show that \(\langle Z_0Z_1\rangle=\langle Z_0\rangle\langle Z_1\rangle\) for every product state, and construct an entangled state for which it holds accidentally. What does the existence of such states imply about detecting the error empirically? (d) Run the marginal readout of
vqe_measurement.pyon the Lipkin Hamiltonian with the three-layer hardware-efficient ansatz and report both the energy the optimizer believes and the true energy of the state it prepared. Can the reported number lie below the global \(E_0\) when the marginals are exact and physical? Prove Eq. (6.18), and distinguish the global bound from a fixed-sector bound. Differentiate the nonlinear reconstruction with a valid rule, not the ordinary two-term VQE shift.The parameter-shift rule. (a) Fill in the algebra between Eq. (6.23) and Eq. (6.24), obtaining the coefficients \(A\), \(B\), \(C\). (b) Show that three evaluations at points giving an invertible interpolation matrix determine the three coefficients, and hence that the rule is exact interpolation. (c) For \(G=\frac12(Z_0+Z_1)\) derive Eq. (6.27) and work out exactly which frequency components the two-term rule of Eq. (6.25) sees and which it loses. (d) Verify that Eq. (6.28) reduces to Eq. (6.25) at \(R=1\), and derive it at \(R=2\) by differentiating Eq. (6.27) and solving for the four shifted energies. (e) Show that the pair-excitation generator \(-\frac12(Y_iX_a-X_iY_a)\) has the eigenvalues \(\{-1,0,0,+1\}\) and explain, from the structure of Eq. (3.89), why it must. (f) Estimate the number of shots for one gradient of a \(20\)-qubit, five-layer hardware-efficient ansatz on a Hamiltonian with \(500\) strings in \(30\) groups at \(10^4\) shots per group, and for the same gradient with SPSA.
Barren plateaus. (a) Reproduce Fig. 6.7 with
gradients.pyand extend it to \(n=10\). (b) Repeat with a fixed number of layers, \(L=2\), and with the Heisenberg ring Hamiltonian in place of \(Z_0Z_1\); which of the two changes the slope? (c) Repeat with the Hamiltonian-variational ansatz of the Heisenberg ring at \(L=n\) from the singlet covering, sampling the angles from \([-\pi,\pi]\) and then from \([-0.1,0.1]\), and explain the difference. (d) Argue from Eq. (6.13) how many shots are needed to resolve a gradient of variance \(2^{-n}\), and at what \(n\) this exceeds \(10^{12}\).Ansätze that know the physics. (a) Show that each of the three Lipkin HVA generators is permutation symmetric and preserves promotion parity. Starting from \(|0000\rangle\), identify the reachable even sector inside \(J=2\). Count the independent real amplitudes of a normalized real state there. Explain why counting angles alone does not prove that a circuit covers that space. (b) Compare the ordered four-excitation and six-transfer pairing circuits. Compute their tangent ranks at the reference and at generic parameter values, and test their best energies numerically. Explain why a tangent count at one point cannot prove global reachability or non-reachability. (c) Count the free four-site Hubbard ground-state degeneracy at \(N=4\) and then at \(N_\uparrow=N_\downarrow=2\): the answers are six and four, respectively. Diagonalize the interaction in the degenerate free space and compare its selected state with the \(U=0.01t\) reference and its \(0.8509\) overlap with the \(U=4t\) ground state. (d) Show that the singlet covering is the ground state of the even-bond Heisenberg Hamiltonian and express the full ring ground state as a linear combination of the two singlet coverings.
ADAPT-VQE. (a) Derive Eq. (6.32) and show that \(i[G,\hat{H}]\) is Hermitian, so that the gradient is a measurable expectation value. (b) Prove that for a real reference state, a real symmetric Hamiltonian and a real symmetric generator the gradient vanishes identically, and that for an imaginary generator (an odd number of \(Y\)’s) \(e^{-i\theta G}\) is a real orthogonal matrix. (c) Explain the gradient trap of the two-operator collective pool in Table 6.8 from the parity of the quasispin projection, and determine how the third operator supplies a useful direction. Distinguish first-order gradients from the space generated by repeated operator products and commutators. (d) Show that the scalar chirality \(\vec{S}_0\cdot(\vec{S}_1\times\vec{S}_2)\) is an imaginary Hermitian operator, write it as a sum of six Pauli strings, and verify with
adapt_vqe.pythat one angle takes the singlet covering to the exact ground state of the ring. (e) Run the Hubbard case ofadapt_vqe.pyto \(24\) operators and plot the error against the number of operators and against the number of CNOT gates after specifying a decomposition and connectivity. Count the actual Pauli terms: only a double excitation with four distinct indices has the standard eight-string form. Include reference preparation and distinguish operator count, gate count and depth. Compare with the four-parameter Hamiltonian-variational ansatz.Excited states and symmetry. (a) For an exact nondegenerate ground state, prove the deflation condition \(\mu>E_1-E_0\). Discuss an approximate deflated state and a degenerate ground space. (b) Show why the Lipkin HVA from \(|0000\rangle\) cannot reach the first odd-parity excited state. Optimize the odd sector from the symmetric one-promotion state \(\frac12(|1000\rangle+|0100\rangle+|0010\rangle+|0001\rangle)\) and compare with \(-2.986068\). (c) Deflate the even ground state and find the next even state, choosing the penalty from the even-sector gap and checking that the ansatz can reach the target. Compare both parity sectors with Fig. 5.10. (d) Explain the circuit for overlap measurement and the extra costs of deflating several states.
QAOA. (a) Derive Eq. (6.34) and check it on the example of Table 6.9. (b) Show that \(e^{-i\gamma(I-Z_0Z_1)/2}\) is, up to a global phase, the CNOT–\(R_z(-\gamma)\)–CNOT gadget of Fig. 6.10, and that \(e^{-i\beta X}=R_x(2\beta)\). (c) Carry out the Heisenberg-picture calculation of Eq. (6.40) in full, and extend it to an edge of a triangle-free graph with degrees \(d_u\) and \(d_v\). (d) Derive Eq. (6.38)–(6.39), and show that \(F_{p+1}^\star\ge F_p^\star\) for global optima, and explain why locally optimized results need not be monotone. (e) Encode the graph-coloring or the number-partitioning problem as a QUBO, build its cost Hamiltonian with
qaoa_basics.pyand run QAOA at \(p=1,2,3\). (f) Show that the QAOA state of Eq. (6.37) is the Hamiltonian-variational ansatz of Eq. (6.11) for \(-\hat{H}_C-\hat{H}_M\), and run thePauliRotationAnsatzofvqe.pyon the ring MaxCut Hamiltonian to confirm that it reproduces Table 6.10.Comparing the two algorithms. (a) For a target accuracy \(\epsilon\), estimate the number of measurements VQE needs and the circuit depth phase estimation needs, both as functions of \(\Lambda\) and \(\epsilon\), for \(\Lambda=10\) and \(\Lambda=10^3\). State which additional assumptions about preparation, gate synthesis, repetition rates and confidence are needed to define a resource crossover. (b) Table 5.5 contains phase-estimation results below the exact energy. Explain why this is not an error and why an exact expectation value cannot do so, whereas a finite-shot VQE estimate can. Propose an uncertainty report for each method. (c) Take the three-layer hardware-efficient state of the Lipkin model from Table 6.5 as the trial state of the
PhaseEstimationclass of Chapter 5 with \(m=8\) control qubits, and compare the probability of reading the ground-state bits with the entries of Table 5.9. Repeat with the two-layer pairing state, and explain the result. (d) Both algorithms need something they cannot supply themselves, a state with a large overlap and an expressive ansatz. Argue that these are the same difficulty in different clothes, and identify one respect in which they are not. (e) Write a paragraph, of the kind that would appear in a paper, stating what has and has not been demonstrated by the calculations of Chapters 5 and 6 on the four models.
Programs for this chapter#
Every number and figure in this chapter comes from the programs in
LectureMaterial/BookPrograms/chapter6/, which build on the shared
modules of Chapters 2 and 3
(statevector, circuit, gates, pauli,
models, optimize, jordanwigner), on
mapped_models.py and pauli_circuits.py of
Chapter 3, and on qpe_models.py of
Chapter 5 for the model Hamiltonians. All of them are
imported by the notebook
LectureMaterial/Notebooks/chapter6/chapter6.ipynb, and all
run on numpy and matplotlib alone.
vqe.pyThe three ansatz classesHardwareEfficientof Eq. (6.8),ProductStateandPauliRotationAnsatzof Eq. (6.10); the classVQEwith exact or sampled energies, the parameter-shift gradients of Eqs. (6.25) and (6.28), gradient descent, BFGS and the SPSA of Eq. (6.29); andrun_restarts. As a script it checks the ansätze against the circuits of Section From Pauli sums to circuits and measurements, the shift rules against finite differences, and the three optimizers on the two-mode Hamiltonian. A few seconds.vqe_measurement.pyThe rotation recipe of Table 6.1, the shot-noise experiment of Table 6.2 and Fig. 6.4, the Bell-state counterexample of Theorem 6.1, the landscapes of Fig. 6.5 and the marginal VQE run of Table 6.3. About ten seconds.gradients.pyThe trigonometric form of Eq. (6.24) fitted and tested, the two-term rule against finite differences, the three-eigenvalue generator of Eq. (6.26) and the four-term rulegeneral_shift, the barren plateau of Fig. 6.7 and the SPSA comparison of Fig. 6.6. About fifteen seconds.vqe_models.pyThe excitation generatorspair_generator,single_generatorandhva_generators, the overlap with the exact sector ground state, and the calculations of Tables 6.4, 6.5, 6.6 and 6.7 and Fig. 6.8. About one minute, the eight-qubit Hubbard runs dominating.adapt_vqe.pyThe classAdaptVQEwith the pool gradients of Eq. (6.32), the operator poolslipkin_pools,heisenberg_poolandhubbard_pool, and the runs of Table 6.8 and Fig. 6.9. About fifteen seconds.qaoa_basics.pyqubo_to_ising,ising_hamiltonianandmaxcut_hamiltonian, Eqs. (6.34)–(6.36); the classQAOAimplementing Eq. (6.37) with the optimization over \((\vec{\gamma},\vec{\beta})\); the checks of Table 6.9 and of Eqs. (6.40) and (6.41); Table 6.10, Fig. 6.11 and Fig. 6.12. About five seconds.validation.pyIndependent checks of shared-parameter and complex-state derivatives, the product-marginal identity, grouped shot variance, circuit compilation, symmetry-sector degeneracies, the Lipkin excited-state obstruction, ADAPT stopping reasons and weighted QAOA periodicity. A few seconds.
Running the programs of this chapter#
Each cell below runs one of the programs listed above as a script and shows the figures it writes to BookFigures/.
import runpy, time
from IPython.display import Image, display
t0 = time.time()
runpy.run_path(str(root / 'BookPrograms' / 'chapter6/vqe.py'), run_name='__main__')
for png in sorted((root / 'BookFigures' / 'chapter6').glob('*.png')):
if png.stat().st_mtime >= t0:
display(Image(str(png)))
PauliRotationAnsatz reproduces the pair-excitation circuit of chapter 3
four-term rule for the pair-excitation generators (eigenvalues -1, 0, 1): |shift - fd| = 3.2e-10
two-term rule on the same generators: |wrong - fd| = 1.31e-02
two-term rule for the R_y / R_z rotations of the hardware-efficient ansatz agrees with finite differences
gradient_descent: E = 0.00000000 (exact 0.00000000), 5101 energy evaluations
bfgs: E = 0.00000000 (exact 0.00000000), 204 energy evaluations
spsa: E = 0.00072291 (exact 0.00000000), 901 energy evaluations
VQE checks passed
import runpy, time
from IPython.display import Image, display
t0 = time.time()
runpy.run_path(str(root / 'BookPrograms' / 'chapter6/vqe_measurement.py'), run_name='__main__')
for png in sorted((root / 'BookFigures' / 'chapter6').glob('*.png')):
if png.stat().st_mtime >= t0:
display(Image(str(png)))
=== The rotation recipe on a random two-qubit state (Table 6.rotationcheck)
string rotation + read-out <psi|P|psi> difference
ZI -0.300445 -0.300445 0e+00
XI -0.020521 -0.020521 8e-17
YI -0.414294 -0.414294 2e-16
XX 0.577375 0.577375 1e-16
YY 0.919859 0.919859 4e-16
ZZ -0.573748 -0.573748 2e-16
XZ -0.599067 -0.599067 0e+00
YX -0.078774 -0.078774 8e-17
=== Shot noise in the energy of a fixed trial state of the two-mode Hamiltonian (Table 6.shots)
exact energy 0.330283, Pauli 1-norm of the traceless part 2.175, 3 measurement settings
shots per setting standard error x sqrt(N) bias
exact grouped standard-error prefactor sigma*sqrt(N): 0.912576
10 0.2649 0.84 -0.0031
100 0.0948 0.95 +0.0150
1000 0.0276 0.87 +0.0015
10000 0.0102 1.02 -0.0008
=== Marginals do not determine correlators (Theorem 7.marginal)
|Phi+>: <X_q>, <Y_q>, <Z_q> = [0. 0. 0. 0. 0. 0.], <Z Z> = +1
|Psi+>: <X_q>, <Y_q>, <Z_q> = [0. 0. 0. 0. 0. 0.], <Z Z> = -1
=== A VQE run with marginal read-out on the two-level pairing Hamiltonian, hardware-efficient ansatz (Table 6.marginal)
exact ground state -0.618034
VQE, joint read-out -0.618034
VQE, marginal reconstruction (reported) -0.500000
true energy of the state it prepared -0.500000
measurement checks passed
import runpy, time
from IPython.display import Image, display
t0 = time.time()
runpy.run_path(str(root / 'BookPrograms' / 'chapter6/gradients.py'), run_name='__main__')
for png in sorted((root / 'BookFigures' / 'chapter6').glob('*.png')):
if png.stat().st_mtime >= t0:
display(Image(str(png)))
=== E(theta_k) = A + B cos(theta_k) + C sin(theta_k) for an R_y rotation (Eq. 6.trigpoly)
A = 0.633345, B = -0.548706, C = 0.468971; largest deviation of the fitted form on 25 other points 7.2e-16
=== two-term rule against finite differences (h = 1e-5): largest difference 1.1e-11
=== A generator with three eigenvalues: G = (Z_0 + Z_1)/2
eigenvalues of G: [-1. 0. 0. 1.]
true derivative -1.087126; two-term rule -0.621107; four-term rule (R = 2) -1.087126
the pair-excitation generators of chapter 3 have the same spectrum, and VQE uses the four-term rule for them
=== Barren plateau: Var[dE/dtheta_1] for the hardware-efficient ansatz with L = n layers (Fig. 6.barren)
n = 2: variance 1.95e-01, mean -0.017
n = 3: variance 9.25e-02, mean +0.025
n = 4: variance 2.87e-02, mean +0.010
n = 5: variance 1.61e-02, mean +0.018
n = 6: variance 8.05e-03, mean -0.003
n = 7: variance 3.80e-03, mean -0.004
n = 8: variance 1.88e-03, mean +0.003
slope of log2(variance) against n for n >= 4: -0.99 (an exponential decay 2^(-c n))
=== SPSA against parameter-shift gradient descent on the four-qubit pairing Hamiltonian, HEA with 3 layers (Fig. 6.spsa)
parameter shift: 2941 energy evaluations, final energy -0.162266 (lowest eigenvalue of the register -0.779164)
SPSA: 1801 energy evaluations, final energy -0.599486 (lowest eigenvalue of the register -0.779164)
gradient checks passed
import runpy, time
from IPython.display import Image, display
t0 = time.time()
runpy.run_path(str(root / 'BookPrograms' / 'chapter6/vqe_models.py'), run_name='__main__')
for png in sorted((root / 'BookFigures' / 'chapter6').glob('*.png')):
if png.stat().st_mtime >= t0:
display(Image(str(png)))
=== The tapered one-qubit pairing Hamiltonian H = I/2 + Z - X/2 with the R_y ansatz
VQE -0.6180339887, exact -0.6180339887, error -2.2e-16, angle -3.605240 (tan(theta) = -0.5000, expected -1/2 up to the branch)
=== The two-mode Hamiltonian of Eq. (3.twoqubitH): hardware-efficient ansatz against the single excitation
ansatz params E_VQE <N>
hardware-efficient, 1 layer 4 0.000000 0.00
hardware-efficient, 2 layers 8 0.000000 0.00
single excitation from |10> 1 0.916905 1.00
spectrum of the register [0. 0.916905 2.083095 3.5 ]; one-particle ground state 0.916905; the single excitation gives theta = -0.2702
=== The four models with the hardware-efficient ansatz, best of four restarts (Table 6.hea)
model layers params CNOTs E_VQE register min sector E0 |<E0|psi>|^2
Lipkin, $N=4$ 1 8 0 -4.000000 -4.212877 -4.212877 0.9358
Lipkin, $N=4$ 2 16 3 -4.105370 -4.212877 -4.212877 0.9726
Lipkin, $N=4$ 3 24 6 -4.211395 -4.212877 -4.212877 0.9998
pairing, $L=4$ 1 8 0 -0.500000 -0.779164 0.635548 0.0000
pairing, $L=4$ 2 16 3 -0.622012 -0.779164 0.635548 0.0000
pairing, $L=4$ 3 24 6 -0.779164 -0.779164 0.635548 0.0000
Hubbard ring 1 16 0 -1.527864 -3.418551 -2.102748 0.0067
Hubbard ring 2 32 7 -2.000000 -3.418551 -2.102748 0.0000
Heisenberg ring 1 8 0 -1.000000 -2.000000 -2.000000 0.3333
Heisenberg ring 2 16 3 -1.619494 -2.000000 -2.000000 0.7994
Heisenberg ring 3 24 6 -1.914214 -2.000000 -2.000000 0.9714
=== Ansätze that know the physics (Table 6.physics)
model ansatz params E_VQE exact E0 error |<E0|psi>|^2
Lipkin, $N=4$ mean field, one R_y angle 1 -4.00000000 -4.21287670 2.1e-01 0.935763
Lipkin, $N=4$ Hamiltonian-variational, 1 layer 3 -4.21238352 -4.21287670 4.9e-04 0.999939
Lipkin, $N=4$ Hamiltonian-variational, 2 layers 6 -4.21287670 -4.21287670 1.9e-14 1.000000
Lipkin, $N=4$ Hamiltonian-variational, 3 layers 9 -4.21287670 -4.21287670 2.9e-14 1.000000
pairing, $L=4$ four pair excitations (UCCD) 4 0.63698698 0.63554847 1.4e-03 0.999822
pairing, $L=4$ all six pair transfers 6 0.63554847 0.63554847 -2.2e-16 1.000000
Hubbard reference: the U = 0.01 ground state, overlap with the U = 4 ground state 0.8509
Hubbard ring Hamiltonian-variational, 1 layer 2 -1.97671868 -2.10274848 1.3e-01 0.988473
Hubbard ring Hamiltonian-variational, 2 layers 4 -2.10274848 -2.10274848 -4.0e-15 1.000000
Hubbard ring Hamiltonian-variational, 3 layers 6 -2.10274848 -2.10274848 -5.3e-15 1.000000
Heisenberg ring Hamiltonian-variational, 1 layer 2 -2.00000000 -2.00000000 -1.3e-15 1.000000
Heisenberg ring Hamiltonian-variational, 2 layers 4 -2.00000000 -2.00000000 -2.2e-15 1.000000
=== The four models: phase estimation (m = 10, Table 5.qpemodels) against the best variational energies
model QPE error HEA error physics error physics overlap
Lipkin, $N=4$ 5.9e-03 +1.5e-03 1.9e-14 1.000000
pairing, $L=4$ 7.3e-03 -1.4e+00 -2.2e-16 1.000000
Hubbard ring 1.7e-02 +1.0e-01 -5.3e-15 1.000000
Heisenberg ring 1.3e-03 +8.6e-02 -2.2e-15 1.000000
model VQE checks passed
import runpy, time
from IPython.display import Image, display
t0 = time.time()
runpy.run_path(str(root / 'BookPrograms' / 'chapter6/adapt_vqe.py'), run_name='__main__')
for png in sorted((root / 'BookFigures' / 'chapter6').glob('*.png')):
if png.stat().st_mtime >= t0:
display(Image(str(png)))
=== Pairing model, L = 4, two pairs: pool of the six pair transfers
step 1: added P02 (|grad| = 1.00e+00), E = 0.93844719
step 2: added P03 (|grad| = 1.11e+00), E = 0.88724986
step 3: added P12 (|grad| = 1.12e+00), E = 0.73887005
step 4: added P13 (|grad| = 1.27e+00), E = 0.63698698
step 5: added P23 (|grad| = 1.14e-02), E = 0.63554847
stop: pool_gradient_threshold; max pool gradient 2.86e-10
=== Lipkin model: the qubit pool and the collective pool
Lipkin, qubit pool:
step 1: added X0Y1 (|grad| = 6.67e-01), E = -4.02758751
step 2: added X0Y2 (|grad| = 7.61e-01), E = -4.06438040
step 3: added X0Y3 (|grad| = 8.87e-01), E = -4.11604788
step 4: added Y1X2 (|grad| = 6.85e-01), E = -4.14536972
step 5: added X1Y3 (|grad| = 7.74e-01), E = -4.18379887
step 6: added Y2X3 (|grad| = 6.76e-01), E = -4.21279162
step 7: added Y0X1 (|grad| = 1.83e-03), E = -4.21287670
stop: pool_gradient_threshold; max pool gradient 2.25e-10
Lipkin, collective pool (2):
step 1: added i(J+^2 - J-^2) (|grad| = 8.00e+00), E = -4.21240735
stop: pool_gradient_threshold; max pool gradient 5.52e-09
Lipkin, collective pool (3):
step 1: added i(J+^2 Jz - Jz J-^2) (|grad| = 1.60e+01), E = -4.20782513
step 2: added i(J+^2 - J-^2) (|grad| = 4.87e-01), E = -4.21287670
stop: pool_gradient_threshold; max pool gradient 3.35e-08
=== Heisenberg ring: spin currents and scalar chiralities
Heisenberg, from singlets:
step 1: added chirality 012 (|grad| = 7.50e-01), E = -2.00000000
stop: pool_gradient_threshold; max pool gradient 2.54e-12
Heisenberg, from Neel:
step 1: added current 01 (|grad| = 2.00e+00), E = -1.20710678
step 2: added current 23 (|grad| = 2.00e+00), E = -1.50000000
step 3: added chirality 012 (|grad| = 7.50e-01), E = -2.00000000
stop: pool_gradient_threshold; max pool gradient 4.40e-11
=== Hubbard ring: fermionic singles and doubles from the weak-coupling reference (12 operators)
pool of 162 generators
step 1: added double 15->16 (|grad| = 9.97e-01), E = -1.15043153
step 2: added double 27->37 (|grad| = 1.06e+00), E = -1.31383705
step 3: added double 04->34 (|grad| = 1.06e+00), E = -1.47058160
step 4: added double 26->27 (|grad| = 9.54e-01), E = -1.59031480
step 5: added double 05->15 (|grad| = 8.78e-01), E = -1.70285902
step 6: added double 16->26 (|grad| = 7.84e-01), E = -1.78474359
step 7: added double 34->37 (|grad| = 7.33e-01), E = -1.85727638
step 8: added double 04->05 (|grad| = 7.58e-01), E = -1.93582926
step 9: added double 14->37 (|grad| = 3.64e-01), E = -2.00587258
step 10: added double 25->37 (|grad| = 3.80e-01), E = -2.07772333
step 11: added double 24->27 (|grad| = 2.47e-01), E = -2.08719613
step 12: added double 07->16 (|grad| = 2.40e-01), E = -2.09135394
stop: operator_limit; max pool gradient 1.47e-01
=== Summary (Table 6.adapt)
model / pool pool ops E_ADAPT error |<E0|psi>|^2
pairing, six pair transfers 6 5 0.63554847 0.0e+00 1.000000
Lipkin, qubit pool 28 7 -4.21287670 1.2e-14 1.000000
Lipkin, collective pool (2) 2 1 -4.21240735 4.7e-04 0.999942
Lipkin, collective pool (3) 3 2 -4.21287670 7.1e-15 1.000000
Heisenberg, from singlets 8 1 -2.00000000 -1.3e-15 1.000000
Heisenberg, from Neel 8 3 -2.00000000 0.0e+00 1.000000
Hubbard, fermionic pool 162 12 -2.09135394 1.1e-02 0.997668
ADAPT-VQE checks passed
import runpy, time
from IPython.display import Image, display
t0 = time.time()
runpy.run_path(str(root / 'BookPrograms' / 'chapter6/qaoa_basics.py'), run_name='__main__')
for png in sorted((root / 'BookFigures' / 'chapter6').glob('*.png')):
if png.stat().st_mtime >= t0:
display(Image(str(png)))
=== QUBO x^T Q x with Q = [[1, -2], [-2, 1]] -> Ising (Table 6.qubo)
J_01 = -1.0, h = {0: 0.5, 1: 0.5}, constant = 0.0; H_C = {'ZZ': -1.0, 'ZI': 0.5, 'IZ': 0.5}
x = (0, 0): x^T Q x = +0.0, H_C(z) + const = +0.0
x = (0, 1): x^T Q x = +1.0, H_C(z) + const = +1.0
x = (1, 0): x^T Q x = +1.0, H_C(z) + const = +1.0
x = (1, 1): x^T Q x = -2.0, H_C(z) + const = -2.0
=== One edge, p = 1: <Z_0 Z_1> = -sin(4 beta) sin(gamma)
largest deviation from the formula over a 13 x 11 grid: 7.8e-16
optimum F = 1.000000 at gamma = 1.5708, beta = 0.3927 (the cut of one edge is 1: the single edge is solved exactly at p = 1)
=== QAOA for MaxCut (Table 6.qaoa)
graph C_max p F_p ratio P(optimal cut) gamma, beta
ring $C_4$ 4 1 3.0000 0.7500 0.5313 (5.498, 1.178)
ring $C_4$ 4 2 4.0000 1.0000 1.0000 (4.712, 5.498, 1.178, 0.785)
ring $C_4$ 4 3 4.0000 1.0000 1.0000 (4.410, 4.874, 2.213, 1.147, 2.413, 0.723)
prism graph, 6 vertices 7 1 5.9392 0.8485 0.4008 (2.571, 0.348)
prism graph, 6 vertices 7 2 6.6029 0.9433 0.7209 (5.781, 2.225, 1.092, 1.857)
prism graph, 6 vertices 7 3 6.8780 0.9826 0.9233 (2.733, 2.284, 2.097, 2.077, 1.228, 0.169)
ring, p = 1: largest deviation from F_1 = 2 + sin(4 beta) sin(2 gamma): 4.8e-15
ring, p = 1: largest F on the grid 2.9945 (optimiser 3.0000)
QAOA checks passed
import runpy, time
from IPython.display import Image, display
t0 = time.time()
runpy.run_path(str(root / 'BookPrograms' / 'chapter6/validation.py'), run_name='__main__')
for png in sorted((root / 'BookFigures' / 'chapter6').glob('*.png')):
if png.stat().st_mtime >= t0:
display(Image(str(png)))
Analytic shared-angle, complex-phase and propagated-state gradients passed
Product-marginal identity, variational bound and grouped covariance passed
Circuit compilation and invalid-input checks passed
Hubbard degeneracies [6, 4]; first Lipkin J=2 excitation -2.98606798 has odd parity
ADAPT threshold, operator-limit and empty-pool statuses passed
Weighted QAOA optimum 0.09999999999999996 ; nonsymmetric QUBO mappings passed
All chapter-6 independent validation checks passed