From a working loop to a trustworthy one
The lesson on the variational quantum eigensolver computed energies from exact state vectors, optimised them with BFGS and compared the result with exact diagonalisation. A VQE on real hardware has none of those comforts. Every energy is a statistical estimate, the number of shots is the dominant cost, the optimiser sees a noisy function, and there is usually no exact answer to compare against. This lesson covers the four things that decide whether a practical VQE result can be trusted: how many measurements it needs, how noise enters the energy, how gradients are obtained, and how to test the implementation so that a converged but wrong answer gets caught.
Throughout, the running example is the SDK's two-qubit H2-shaped testbed,
in hartree, with the first letter on qubit 0 (the most significant bit). As the SDK's provenance note says, these coefficients are approximate and not a validated molecular Hamiltonian (KetQat SDK); they are used here to study the algorithm, not to report chemistry. Its exact ground energy is .
Measurement budgets
The estimator and its variance
Write . A measurement setting (a choice of basis on every qubit) lets you estimate several Pauli expectations from the same shots, provided all of them are diagonal in that basis. Partition the non-identity terms into groups that can be measured together, and define the group observable . One shot in group 's basis yields one sample of : the weighted sum of the eigenvalues read off the bits. Its single-shot variance is
which includes the covariances between the terms of the group. With shots in group and independent groups, the energy estimate is unbiased and has variance
Grouping
Two Pauli strings qubit-wise commute (QWC) if on every qubit their letters are equal or one of them is . A QWC group can be measured with single-qubit rotations only: on each qubit rotate into the eigenbasis of the one non-identity letter that appears there. Two strings commute as operators when they differ (both non-identity, different letters) on an even number of qubits. and commute, since they differ on two qubits, but they do not commute qubit-wise. Measuring them together needs an entangling basis change, here a rotation to the Bell basis. General commuting groups are fewer and larger, at the price of extra two-qubit gates before measurement, which on noisy hardware adds error.
Finding the minimum number of groups is a minimum clique cover problem, NP-hard in general, so practical tools use heuristics (Verteletskyi, Yen and Izmaylov 2020). A simple greedy rule, used in the exercise: sort terms by , then put each into the first group whose members it qubit-wise commutes with. For the testbed this gives three groups: , and .
Optimal shot allocation
Given a total budget , which split minimises the variance? Minimise subject to with a Lagrange multiplier :
Substituting back gives the minimum variance and the number of shots needed for a standard error :
With equal shots on groups instead, . By the Cauchy–Schwarz inequality , so the optimal split is never worse, and it helps most when the are very unequal.
The catch is that depends on the state you are measuring, which is what you are trying to learn. In practice you spend a pilot batch of shots to estimate the , or you use the state-independent bound , which gives the worst-case budget .
Worked example
At the testbed's exact ground state (as if the VQE had converged perfectly), the exercise's solution gives for and for each of and . For a standard error of Ha (a commonly used chemical-accuracy target):
| allocation | total shots |
|---|---|
| optimal, | 49,072 |
| uniform over the 3 groups | 55,206 |
| worst-case bound | 916,567 |
Three observations, each specific to this instance. First, the energy operator has zero variance in its own eigenstate, , yet the measurable groups fluctuate: no single basis measures , and the budget comes from the groups. Second, grouping with did not reduce the shot count here: in this ground state both terms are perfectly correlated, so their standard deviations simply add. Grouping always reduces the number of distinct circuits, but whether it reduces shots depends on the covariances. Third, the worst-case bound is about 19 times larger than the state-specific optimum, which is why pilot estimates of pay off.
These numbers are for a two-qubit toy. For molecules, the number of Pauli terms grows roughly as the fourth power of the number of orbitals, and analyses of realistic problems found measurement counts that could make VQE impractically slow without better measurement strategies (Wecker, Hastings and Troyer 2015).
Shot noise in the energy
With a finite budget, is a random variable with standard error . Three practical consequences follow.
- Estimates below are allowed if they are within a few standard errors. The variational principle bounds the expectation , not an estimate of it. An estimate ten standard errors below is a bug; one standard error below is statistics.
- Comparisons need error bars. Two parameter settings whose energies differ by less than about two combined standard errors cannot be ranked reliably, so an optimiser driven by noisy energies wanders near the optimum instead of converging. Use larger shot counts as the optimisation proceeds.
- The reported energy should be re-measured. Selecting the lowest of many noisy estimates biases the result downwards (the "winner's curse"). Re-estimate the final parameters with a fresh, large batch of shots.
Optimisers and gradients
Gradient-free methods (Nelder–Mead, COBYLA, coordinate descent as in the SDK product, SPSA) need only energy evaluations. They are simple and robust to some noise but can need many evaluations as the number of parameters grows.
Gradient-based methods need . Finite differences with a small step divide shot noise by , which is disastrous on hardware. For gates generated by Pauli operators there is an exact alternative.
The parameter-shift rule
Let one gate be with a Pauli string, so and . Write the circuit as and the energy as with and . Expanding the product, every term contains , or , and the half-angle identities turn these into , and . Hence
for constants that depend on everything else in the circuit. Then
This is exact, not an approximation, and it uses two energy evaluations at shifts of size , so shot noise is not amplified by a small step. More generally, for any that is not a multiple of , which is worth remembering when you meet code that uses a different shift: the divisor must match the shift. The rule is due to Mitarai and coauthors (Mitarai et al. 2018) and was generalised by Schuld and coauthors (Schuld et al. 2019). A full gradient costs energy estimates for parameters, and each has its own shot noise. If one shot of the energy at the shifted points has variance and , and each estimate uses shots, one gradient component has variance .
Barren plateaus
Gradients can also be small for a structural reason. McClean and coauthors proved that if a parameterised circuit is random enough (formally, if it forms an approximate unitary 2-design over the qubits), then the variance of each gradient component, over random initialisations, decays exponentially with the number of qubits (McClean et al. 2018). Since the mean gradient is zero, a typical gradient is then exponentially small, and resolving it needs exponentially many shots: a barren plateau. Cerezo and coauthors showed that the choice of cost function matters even for shallow circuits: costs that compare the whole state with a target ("global" costs) have barren plateaus even for shallow circuits, while costs built from few-qubit observables ("local" costs) keep polynomially large gradients for circuits of logarithmic depth, under the assumptions of their theorems (Cerezo et al. 2021).
These are theorems with assumptions. They do not say every ansatz has a barren plateau, and the absence of a barren plateau does not guarantee that optimisation succeeds; local minima and noise remain. A quick numerical experiment shows the effect. Using the hardware-efficient ansatz from the introductory lesson with as many CNOT ladders as qubits, the snippet below draws 200 random parameter vectors and computes the parameter-shift derivative with respect to the first angle, for a local cost and a global cost :
import math
import numpy as np
def ansatz(theta, n, layers):
state, idx, p = np.eye(2**n)[0], np.arange(2**n), 0
for block in range(layers + 1):
for q in range(n):
c, s = math.cos(theta[p] / 2), math.sin(theta[p] / 2)
psi = np.moveaxis(state.reshape([2] * n), q, 0)
psi = np.stack([c * psi[0] - s * psi[1], s * psi[0] + c * psi[1]])
state, p = np.moveaxis(psi, 0, q).reshape(-1), p + 1
if block < layers:
for q in range(n - 1):
state = state[idx ^ (((idx >> (n - 1 - q)) & 1) << (n - 2 - q))]
return state
def costs(theta, n, layers):
psi = ansatz(theta, n, layers)
z0 = 1 - 2 * ((np.arange(2**n) >> (n - 1)) & 1)
return np.sum(psi**2 * z0), 1 - psi[0] ** 2 # local <Z_0>, global 1 - |<0|psi>|^2
rng = np.random.default_rng(0)
for n in (2, 4, 6, 8, 10):
shift = np.zeros(n * (n + 1)); shift[0] = math.pi / 2
grads = []
for _ in range(200):
th = rng.uniform(0, 2 * math.pi, size=n * (n + 1))
plus, minus = costs(th + shift, n, n), costs(th - shift, n, n)
grads.append([(plus[0] - minus[0]) / 2, (plus[1] - minus[1]) / 2])
v = np.var(grads, axis=0)
print(n, f"{v[0]:.1e}", f"{v[1]:.1e}")
| qubits (layers ) | variance, local cost | variance, global cost |
|---|---|---|
| 2 | ||
| 4 | ||
| 6 | ||
| 8 | ||
| 10 |
This is a numerical observation for one ansatz, one parameter and 200 samples (each variance is uncertain by roughly 10%), not a proof. Still, the pattern matches the theory: the global cost's gradient variance falls by about an order of magnitude for every two qubits added, the local cost's far more slowly. At the global gradient has a typical size around , and since one shot of this cost is a 0/1 outcome with standard deviation up to , resolving that gradient's sign takes hundreds of thousands of shots per energy evaluation.
Debugging a VQE
A VQE bug rarely crashes. The code runs, the optimiser converges smoothly, and the reported energy is plausible. The defence is a set of tests whose expected values are computed independently of the code under test.
- Pin energies of basis states. For a computational basis state, only and -type terms contribute, so the energy can be added up by hand from the coefficients. For the testbed, (qubit 0 in , qubit 1 in ) has .
- Pin the exact ground energy with a Hamiltonian built a different way (explicit Kronecker products, or another library), not with the same builder.
- Check the variational inequality at many random parameters.
- Check gradients against central finite differences with exact energies, where the step can be tiny without noise.
- Compare with an independent implementation such as the SDK's
vqe-ground-stateproduct.
Each test targets a class of bug. A reversed qubit order permutes the basis, which leaves the spectrum, and hence , unchanged: a test that checks only the converged energy cannot see it, but a basis-state energy can. A dropped identity term shifts every energy by its coefficient and leaves the optimal parameters unchanged: only a comparison with an absolute reference catches it. A wrong gradient rule may still converge, just more slowly, so only a gradient test catches it.
In the debugging exercise you receive buggy_vqe.py, which reports a converged energy of
for the testbed. The correct value is . The difference, , is exactly the
magnitude of the identity coefficient, a strong clue. But fixing that bug alone is not enough: the
code contains two more defects that do not change the converged energy and are invisible to a test
that only looks at it.
Exercises
vqe-measurement-budget. Implement commutation tests, greedy QWC grouping, group standard
deviations, the optimal allocation, the shot formulas and a shot-noise energy sampler. The checks
compare your commutation rules with matrix commutators, your grouping of the testbed with the
expected three groups, your optimal allocation against 200 random splits, and the empirical
standard deviation of 400 simulated energy estimates against .
vqe-debugging. Repair the provided VQE. The tests pin the parser, the qubit order, the four
basis-state energies (by hand), the Hamiltonian matrix (against the SDK's own construction), the
gradient (against finite differences), the converged energy (against an independently built matrix
and the SDK product), and confirm that the provided code really fails them. Keep a short log of
each defect: the symptom, the cause, and the test that pins it.
Common mistakes
- Budgeting shots per Pauli term instead of per measurement group, and ignoring covariances inside a group.
- Using worst-case variances when a pilot estimate is cheap. The bound was 19 times too pessimistic in the worked example.
- Treating an estimate below as automatically wrong, or automatically fine. Compare the gap with the standard error.
- Finite-difference gradients on hardware. Use the parameter-shift rule, and make sure shift and divisor match.
- Citing barren plateaus as a universal law. The theorems have assumptions: randomness of the circuit, the form of the cost, the depth.
- Testing only the final energy. Bugs that permute qubits or shift by a constant are invisible to it.
Summary
The cost of a practical VQE is dominated by measurements. Group commuting terms, estimate each group's single-shot standard deviation , and allocate shots in proportion to , which needs shots for standard error . Energies are statistical estimates, so comparisons and the variational bound must be read with error bars. The parameter-shift rule gives exact gradients from two shifted energies, and barren-plateau theorems explain why gradients can vanish exponentially for random, deep or globally defined costs. Finally, a VQE must be tested against independently computed values at several points, not just at its converged energy, because the most common bugs converge to plausible numbers. The next lesson applies the same variational machinery to combinatorial optimisation with QAOA.