Skip to main content
KetQat

Appearance

Lesson 51 h 15 min

VQE in practice

Measurement budgets, shot noise, optimiser behaviour, barren plateaus and debugging a failing VQE.

After this lesson you can

  • Group Pauli terms into qubit-wise commuting sets and explain when general commuting groups need entangling measurements
  • Derive the variance-optimal shot allocation S_g ∝ σ_g and compute the total shots for a target energy precision
  • Quantify shot noise in an energy estimate and decide when an energy below E_0 is a bug and when it is statistics
  • Derive the parameter-shift rule for rotations generated by Pauli operators and compare it with finite differences
  • State the barren-plateau results with their assumptions and distinguish them from general claims about trainability
  • Find and fix convention, coefficient and gradient bugs in a VQE, and write tests that pin the correct energies

Read first: The variational quantum eigensolver, Measurement and probability

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,

H=−0.4804 II+0.3435 ZI−0.4347 IZ+0.5716 ZZ+0.0910 XX+0.0910 YY,H = -0.4804\,II + 0.3435\,ZI - 0.4347\,IZ + 0.5716\,ZZ + 0.0910\,XX + 0.0910\,YY ,

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 E0=−1.851199E_0 = -1.851199.

Measurement budgets

The estimator and its variance

Write H=c0I+∑iciPiH = c_0 I + \sum_i c_i P_i. 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 gg that can be measured together, and define the group observable Og=∑i∈gciPiO_g = \sum_{i\in g} c_i P_i. One shot in group gg's basis yields one sample of OgO_g: the weighted sum of the ±1\pm1 eigenvalues read off the bits. Its single-shot variance is

σg2=⟨Og2⟩−⟨Og⟩2,\sigma_g^2 = \expval{O_g^2} - \expval{O_g}^2 ,

which includes the covariances between the terms of the group. With SgS_g shots in group gg and independent groups, the energy estimate E^=c0+∑gOˉg\hat E = c_0 + \sum_g \bar O_g is unbiased and has variance

Var⁡(E^)=∑gσg2Sg.\operatorname{Var}(\hat E) = \sum_g \frac{\sigma_g^2}{S_g}.

Grouping

Two Pauli strings qubit-wise commute (QWC) if on every qubit their letters are equal or one of them is II. 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. XXXX and YYYY 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 ∣ci∣\abs{c_i}, then put each into the first group whose members it qubit-wise commutes with. For the testbed this gives three groups: {ZZ,IZ,ZI}\{ZZ, IZ, ZI\}, {XX}\{XX\} and {YY}\{YY\}.

Optimal shot allocation

Given a total budget S=∑gSgS = \sum_g S_g, which split minimises the variance? Minimise ∑gσg2/Sg\sum_g \sigma_g^2/S_g subject to ∑gSg=S\sum_g S_g = S with a Lagrange multiplier λ\lambda:

−σg2Sg2+λ=0  ⟹  Sg=σgλ  ⟹  Sg=S σg∑hσh.-\frac{\sigma_g^2}{S_g^2} + \lambda = 0 \;\Longrightarrow\; S_g = \frac{\sigma_g}{\sqrt\lambda} \;\Longrightarrow\; S_g = S\,\frac{\sigma_g}{\sum_h \sigma_h}.

Substituting back gives the minimum variance and the number of shots needed for a standard error ε\varepsilon:

Var⁡min⁡(E^)=(∑gσg)2S,Sopt(ε)=(∑gσg)2ε2.\operatorname{Var}_{\min}(\hat E) = \frac{\big(\sum_g \sigma_g\big)^2}{S}, \qquad S_{\text{opt}}(\varepsilon) = \frac{\big(\sum_g \sigma_g\big)^2}{\varepsilon^2}.

With equal shots on GG groups instead, Suni(ε)=G∑gσg2/ε2S_{\text{uni}}(\varepsilon) = G\sum_g\sigma_g^2/\varepsilon^2. By the Cauchy–Schwarz inequality (∑gσg)2≤G∑gσg2(\sum_g\sigma_g)^2 \le G\sum_g\sigma_g^2, so the optimal split is never worse, and it helps most when the σg\sigma_g are very unequal.

The catch is that σg\sigma_g 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 σg\sigma_g, or you use the state-independent bound σg≤∑i∈g∣ci∣\sigma_g \le \sum_{i\in g}\abs{c_i}, which gives the worst-case budget S≤(∑i∣ci∣)2/ε2S \le (\sum_i \abs{c_i})^2/\varepsilon^2.

Worked example

At the testbed's exact ground state (as if the VQE had converged perfectly), the exercise's solution gives σ=0.17722\sigma = 0.17722 for {ZZ,IZ,ZI}\{ZZ, IZ, ZI\} and 0.088610.08861 for each of {XX}\{XX\} and {YY}\{YY\}. For a standard error of ε=1.6×10−3\varepsilon = 1.6\times10^{-3} Ha (a commonly used chemical-accuracy target):

allocation total shots
optimal, Sg∝σgS_g \propto \sigma_g 49,072
uniform over the 3 groups 55,206
worst-case bound (∑i∣ci∣)2/ε2(\sum_i\abs{c_i})^2/\varepsilon^2 916,567

Three observations, each specific to this instance. First, the energy operator has zero variance in its own eigenstate, Var⁡(H)=0\operatorname{Var}(H) = 0, yet the measurable groups fluctuate: no single basis measures HH, and the budget comes from the groups. Second, grouping ZIZI with IZIZ 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 σg\sigma_g 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, E^\hat E is a random variable with standard error Var⁡(E^)\sqrt{\operatorname{Var}(\hat E)}. Three practical consequences follow.

  • Estimates below E0E_0 are allowed if they are within a few standard errors. The variational principle bounds the expectation ⟨H⟩\expval H, not an estimate of it. An estimate ten standard errors below E0E_0 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 ∂E/∂θk\partial E/\partial\theta_k. Finite differences with a small step hh divide shot noise by hh, which is disastrous on hardware. For gates generated by Pauli operators there is an exact alternative.

The parameter-shift rule

Let one gate be U(θ)=e−iθP/2U(\theta) = e^{-i\theta P/2} with PP a Pauli string, so P2=IP^2 = I and U(θ)=cos⁡(θ/2) I−isin⁡(θ/2) PU(\theta) = \cos(\theta/2)\,I - i\sin(\theta/2)\,P. Write the circuit as V2U(θ)V1V_2 U(\theta) V_1 and the energy as E(θ)=⟨ϕ∣U(θ)†A U(θ)∣ϕ⟩E(\theta) = \bra{\phi}U(\theta)^\dagger A\,U(\theta)\ket{\phi} with ∣ϕ⟩=V1∣0⟩\ket\phi = V_1\ket0 and A=V2†HV2A = V_2^\dagger H V_2. Expanding the product, every term contains cos⁡2(θ/2)\cos^2(\theta/2), sin⁡2(θ/2)\sin^2(\theta/2) or sin⁡(θ/2)cos⁡(θ/2)\sin(\theta/2)\cos(\theta/2), and the half-angle identities turn these into 11, cos⁡θ\cos\theta and sin⁡θ\sin\theta. Hence

E(θ)=a+bcos⁡θ+csin⁡θE(\theta) = a + b\cos\theta + c\sin\theta

for constants a,b,ca, b, c that depend on everything else in the circuit. Then

E(θ±π2)=a∓bsin⁡θ±ccos⁡θ⟹E(θ+π2)−E(θ−π2)2=−bsin⁡θ+ccos⁡θ=dEdθ.E\big(\theta \pm \tfrac\pi2\big) = a \mp b\sin\theta \pm c\cos\theta \quad\Longrightarrow\quad \frac{E(\theta+\tfrac\pi2) - E(\theta-\tfrac\pi2)}{2} = -b\sin\theta + c\cos\theta = \frac{dE}{d\theta}.

This is exact, not an approximation, and it uses two energy evaluations at shifts of size π/2\pi/2, so shot noise is not amplified by a small step. More generally, [E(θ+s)−E(θ−s)]/(2sin⁡s)=E′(θ)[E(\theta+s) - E(\theta-s)]/(2\sin s) = E'(\theta) for any ss that is not a multiple of π\pi, 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 2m2m energy estimates for mm parameters, and each has its own shot noise. If one shot of the energy at the shifted points has variance σ+2\sigma_+^2 and σ−2\sigma_-^2, and each estimate uses SS shots, one gradient component has variance (σ+2+σ−2)/(4S)(\sigma_+^2 + \sigma_-^2)/(4S).

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 ⟨Z0⟩\expval{Z_0} and a global cost 1−∣⟨0…0∣ψ⟩∣21 - \abs{\braket{0\dots0}{\psi}}^2:

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 nn (layers =n= n) variance, local cost variance, global cost
2 3.1×10−13.1\times10^{-1} 4.5×10−24.5\times10^{-2}
4 1.2×10−11.2\times10^{-1} 4.2×10−34.2\times10^{-3}
6 5.6×10−25.6\times10^{-2} 2.2×10−42.2\times10^{-4}
8 2.3×10−22.3\times10^{-2} 1.8×10−51.8\times10^{-5}
10 1.3×10−21.3\times10^{-2} 1.1×10−61.1\times10^{-6}

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 n=10n = 10 the global gradient has a typical size around 10−310^{-3}, and since one shot of this cost is a 0/1 outcome with standard deviation up to 1/21/2, 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.

  1. Pin energies of basis states. For a computational basis state, only II and ZZ-type terms contribute, so the energy can be added up by hand from the coefficients. For the testbed, ∣01⟩\ket{01} (qubit 0 in ∣0⟩\ket0, qubit 1 in ∣1⟩\ket1) has E=−0.4804+0.3435⋅(+1)−0.4347⋅(−1)+0.5716⋅(−1)=−0.2738E = -0.4804 + 0.3435\cdot(+1) - 0.4347\cdot(-1) + 0.5716\cdot(-1) = -0.2738.
  2. Pin the exact ground energy with a Hamiltonian built a different way (explicit Kronecker products, or another library), not with the same builder.
  3. Check the variational inequality at many random parameters.
  4. Check gradients against central finite differences with exact energies, where the step can be tiny without noise.
  5. Compare with an independent implementation such as the SDK's vqe-ground-state product.

Each test targets a class of bug. A reversed qubit order permutes the basis, which leaves the spectrum, and hence E0E_0, 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 −1.370799-1.370799 for the testbed. The correct value is −1.851199-1.851199. The difference, 0.48040.4804, 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 ∑gσg2/Sg\sqrt{\sum_g\sigma_g^2/S_g}.

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 (∑∣ci∣)2/ε2(\sum\abs{c_i})^2/\varepsilon^2 was 19 times too pessimistic in the worked example.
  • Treating an estimate below E0E_0 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 σg\sigma_g, and allocate shots in proportion to σg\sigma_g, which needs (∑gσg)2/ε2(\sum_g\sigma_g)^2/\varepsilon^2 shots for standard error ε\varepsilon. 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.

Exercises

Run these on your own computer. Each comes with automated checks: python -m pytest test_exercise.py. Nothing you write is sent to KetQat.

Measurement grouping and shot allocation for VQE

advanced · about 1 h 15 min · needs numpy, pytest

Build the measurement side of a VQE: decide which Pauli terms can share shots, how many shots each group gets, how many shots a target precision needs, and check the variance formula against simulated shot noise.

Conventions: Pauli strings act with their first letter on qubit 0, the most significant bit. H2_TESTBED holds the KetQat SDK's two-qubit H2-shaped testbed (approximate coefficients in hartree; not a validated molecular Hamiltonian). The identity term costs no shots.

Functions to implement in starter.py

Function Contract
commutes(p, q) the strings commute as operators (they differ, both non-identity, on an even number of qubits)
qubitwise_commutes(p, q) on every qubit the letters are equal or one is I
greedy_qwc_groups(terms) sort non-identity terms by decreasing ∣c∣\abs{c} (stable), put each into the first group it qubit-wise commutes with entirely, else open a new group
group_standard_deviation(state, group) ⟨O2⟩−⟨O⟩2\sqrt{\expval{O^2} - \expval{O}^2} for O=∑i∈gciPiO = \sum_{i\in g} c_iP_i
optimal_allocation(sigmas, total_shots) real-valued Sg=Sσg/∑hσhS_g = S\sigma_g/\sum_h\sigma_h
estimator_variance(sigmas, shots) ∑gσg2/Sg\sum_g \sigma_g^2/S_g
shots_for_precision(sigmas, epsilon, allocation="optimal") (∑σ)2/ε2(\sum\sigma)^2/\varepsilon^2, or G∑σ2/ε2G\sum\sigma^2/\varepsilon^2 for "uniform"
sample_energy(state, terms, groups, shots_per_group, rng) one shot-noise estimate: per group, rotate into the shared basis, sample, average ∑ici(±1)\sum_i c_i(\pm1); add the identity coefficient exactly

pauli_matrix, group_basis and _rotate_to_basis are provided.

What the checks verify

  • Your commutation rules agree with matrix commutators for all 256 pairs of two-qubit strings, qubit-wise commuting implies commuting, and XXXX, YYYY commute but not qubit-wise.
  • Greedy grouping of the testbed gives {ZZ,IZ,ZI}\{ZZ, IZ, ZI\}, {XX}\{XX\}, {YY}\{YY\}, and grouping a seeded random 4-qubit Hamiltonian partitions it into qubit-wise commuting groups.
  • The optimal allocation has variance (∑σ)2/S(\sum\sigma)^2/S and beats 200 random splits.
  • At the testbed's ground state, HH has zero variance as one operator but the measurable groups do not.
  • 400 seeded simulated energy estimates have a standard deviation within 18% of ∑gσg2/Sg\sqrt{\sum_g\sigma_g^2/S_g} (the sampling error of a standard deviation from 400 samples is about 3.5%), and their mean is within five standard errors of E0E_0.

Run the checks

python -m pytest test_exercise.py

Going further

Measure {XX,YY}\{XX, YY\} together in the Bell basis (apply CX(0→1) then H on qubit 0 before measuring) and recompute the budget with groups {ZZ,IZ,ZI}\{ZZ, IZ, ZI\} and {XX,YY}\{XX, YY\}. Does a larger group save shots here? Explain the answer with the covariance of XXXX and YYYY in the ground state.

Terminal
python -m pip install numpy pytest

starter.py

Python
"""Starter: measurement grouping, variance-based shot allocation and shot noise in VQE.

Conventions: Pauli strings act with their first letter on qubit 0, the most
significant bit of the basis index. A Hamiltonian is a list of (coefficient, label).
The identity string has no shot cost: its contribution is the coefficient itself.
"""

import math

import numpy as np

PAULI = {
    "I": np.eye(2, dtype=complex),
    "X": np.array([[0, 1], [1, 0]], dtype=complex),
    "Y": np.array([[0, -1j], [1j, 0]], dtype=complex),
    "Z": np.array([[1, 0], [0, -1]], dtype=complex),
}

H2_TESTBED = [
    (-0.4804, "II"),
    (0.3435, "ZI"),
    (-0.4347, "IZ"),
    (0.5716, "ZZ"),
    (0.0910, "XX"),
    (0.0910, "YY"),
]


def pauli_matrix(label):
    out = np.array([[1.0 + 0j]])
    for letter in label:
        out = np.kron(out, PAULI[letter])
    return out


def commutes(p, q):
    """True if the Pauli strings commute as operators (an even number of positions where both
    letters are non-identity and different)."""
    raise NotImplementedError


def qubitwise_commutes(p, q):
    """True if on every qubit the letters are equal or at least one is I."""
    raise NotImplementedError


def greedy_qwc_groups(terms):
    """Partition the non-identity terms into qubit-wise commuting groups.

    Visit terms in order of decreasing |coefficient| (ties: input order) and put each into the
    first existing group whose members it qubit-wise commutes with; otherwise open a new group.
    Returns a list of groups, each a list of (coefficient, label).
    """
    raise NotImplementedError


def group_standard_deviation(state, group):
    """Standard deviation of the single-shot estimator of sum_{i in group} c_i <P_i>.

    One shot in the group's shared basis yields sum_i c_i * (eigenvalue of P_i), a random
    variable whose variance is <O^2> - <O>^2 for O = sum_i c_i P_i.
    """
    raise NotImplementedError


def optimal_allocation(sigmas, total_shots):
    """Real-valued shots S_g = total * sigma_g / sum(sigma) that minimise sum sigma_g^2 / S_g."""
    raise NotImplementedError


def estimator_variance(sigmas, shots):
    """Variance of the energy estimate, sum_g sigma_g^2 / S_g (independent groups)."""
    raise NotImplementedError


def shots_for_precision(sigmas, epsilon, allocation="optimal"):
    """Total shots so that the standard error equals epsilon.

    optimal: (sum sigma)^2 / epsilon^2. uniform (equal shots per group, G groups):
    G * sum(sigma^2) / epsilon^2.
    """
    raise NotImplementedError


def _rotate_to_basis(state, basis):
    n = len(basis)
    h = np.array([[1, 1], [1, -1]], dtype=complex) / math.sqrt(2)
    sdg = np.diag([1, -1j])
    psi = state.reshape([2] * n)
    for q, letter in enumerate(basis):
        gate = {"X": h, "Y": h @ sdg}.get(letter)
        if gate is not None:
            psi = np.moveaxis(np.tensordot(gate, np.moveaxis(psi, q, 0), axes=(1, 0)), 0, q)
    return psi.reshape(-1)


def group_basis(group):
    """Shared measurement basis of a qubit-wise commuting group: per qubit the non-I letter (Z if none)."""
    n = len(group[0][1])
    basis = []
    for q in range(n):
        letters = {p[q] for _, p in group if p[q] != "I"}
        assert len(letters) <= 1, "group is not qubit-wise commuting"
        basis.append(letters.pop() if letters else "Z")
    return "".join(basis)


def sample_energy(state, terms, groups, shots_per_group, rng):
    """One shot-noise energy estimate: for each group draw its shots in the shared basis and
    average sum_i c_i * eigenvalue_i; add the identity coefficients exactly."""
    raise NotImplementedError

test_exercise.py

Python
import importlib.util
import os
from pathlib import Path

def _load_target():
    name = os.environ.get("KETQAT_COMMONS_TARGET", "starter")
    path = Path(__file__).with_name(f"{name}.py")
    spec = importlib.util.spec_from_file_location(f"{Path(__file__).parent.name}_{name}", path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

target = _load_target()

import itertools
import math

import numpy as np
import pytest

H2 = target.H2_TESTBED


def matrix(terms):
    return sum(c * target.pauli_matrix(p) for c, p in terms)


def ground_state(terms):
    w, v = np.linalg.eigh(matrix(terms))
    return w[0], v[:, 0]


def test_commutation_rules_agree_with_matrix_commutators():
    for p, q in itertools.product(["".join(t) for t in itertools.product("IXYZ", repeat=2)], repeat=2):
        P, Q = target.pauli_matrix(p), target.pauli_matrix(q)
        assert target.commutes(p, q) == np.allclose(P @ Q, Q @ P), (p, q)
        if target.qubitwise_commutes(p, q):
            assert target.commutes(p, q), "qubit-wise commuting strings must commute"
    assert target.commutes("XX", "YY") and not target.qubitwise_commutes("XX", "YY")


def test_greedy_grouping_of_the_h2_testbed():
    groups = target.greedy_qwc_groups(H2)
    labels = [sorted(p for _, p in g) for g in groups]
    assert labels == [["IZ", "ZI", "ZZ"], ["XX"], ["YY"]]


def test_groups_partition_the_terms_and_are_qubitwise_commuting():
    rng = np.random.default_rng(4)
    labels = sorted({"".join(rng.choice(list("IXYZ"), size=4)) for _ in range(30)} - {"IIII"})
    terms = [(float(c), p) for c, p in zip(rng.normal(size=len(labels)), labels)]
    groups = target.greedy_qwc_groups(terms)
    flat = sorted(p for g in groups for _, p in g)
    assert flat == sorted(labels)
    for g in groups:
        for (_, a), (_, b) in itertools.combinations(g, 2):
            assert target.qubitwise_commutes(a, b)


def test_optimal_allocation_beats_every_other_split():
    sigmas = np.array([0.9, 0.1, 0.35, 0.02])
    total = 10000
    best = target.estimator_variance(sigmas, target.optimal_allocation(sigmas, total))
    assert best == pytest.approx(sigmas.sum() ** 2 / total)
    rng = np.random.default_rng(0)
    for _ in range(200):
        w = rng.dirichlet(np.ones(4))
        assert target.estimator_variance(sigmas, total * w) >= best - 1e-15


def test_shots_for_precision_formulas():
    sigmas = [0.5, 0.2, 0.2]
    eps = 1e-3
    assert target.shots_for_precision(sigmas, eps) == pytest.approx(0.81e6)
    assert target.shots_for_precision(sigmas, eps, "uniform") == pytest.approx(3 * 0.33e6)


def test_ground_state_has_zero_energy_variance_but_not_zero_measurement_cost():
    e0, psi = ground_state(H2)
    nontrivial = [t for t in H2 if t[1] != "II"]
    # As one operator, H has zero variance in its eigenstate...
    assert target.group_standard_deviation(psi, nontrivial) < 1e-7
    # ...but no single basis measures it: the measurable groups fluctuate.
    sigmas = [target.group_standard_deviation(psi, g) for g in target.greedy_qwc_groups(H2)]
    assert sum(sigmas) > 0.1


def test_shot_noise_matches_the_variance_formula():
    rng = np.random.default_rng(2026)
    e0, psi = ground_state(H2)
    groups = target.greedy_qwc_groups(H2)
    sigmas = [target.group_standard_deviation(psi, g) for g in groups]
    shots = np.maximum(1, np.round(target.optimal_allocation(sigmas, 3000))).astype(int)
    repeats = 400
    estimates = np.array([target.sample_energy(psi, H2, groups, shots, rng) for _ in range(repeats)])
    predicted = math.sqrt(target.estimator_variance(sigmas, shots))
    # Sample standard deviation of 400 repeats has ~3.5% relative error; allow 18%.
    assert abs(estimates.std(ddof=1) / predicted - 1) < 0.18
    # The estimator is unbiased: the mean is within 5 standard errors of E0.
    assert abs(estimates.mean() - e0) < 5 * predicted / math.sqrt(repeats)

Debugging a VQE that converges to the wrong answer

advanced · about 1 h · needs numpy, pytest, ketqat[algorithms]

buggy_vqe.py is a complete, tidy VQE for the SDK's two-qubit H2-shaped testbed. It runs, the gradient descent converges smoothly, and it reports

VQE energy: -1.370799

The correct ground energy of this Hamiltonian is −1.851199-1.851199. Your task is to find every defect, fix it in starter.py, and keep the tests passing. Fixing the first defect you find will not be enough: some defects do not change the converged energy at all.

Intended conventions: qubit 0 is the most significant bit of the basis index, the first letter of a Pauli string acts on qubit 0, and RY(θ)=e−iθY/2R_Y(\theta) = e^{-i\theta Y/2}. The testbed coefficients are approximate and are not a validated molecular Hamiltonian; they are used to exercise the algorithm.

How to work

  1. Run python buggy_vqe.py and reproduce the wrong number.
  2. Copy each function from buggy_vqe.py into the matching function in starter.py.
  3. Run the tests. Each failing test points at a class of bug; read its docstring and its expected value, which is always computed independently of your code (by hand, with explicit Kronecker products, by finite differences, or by the KetQat SDK).
  4. Fix one defect at a time and write a three-line log for each: what you observed, why it happened, and which test pins it.

Functions in starter.py

parse_terms, pauli_string_matrix, hamiltonian_matrix, ansatz_state, energy, parameter_shift_gradient and run_vqe, with the same signatures as in buggy_vqe.py. Not every function is broken.

What the checks verify

  • The provided code really fails (so you know the tests can see the defects).
  • The parser keeps every term with its sign.
  • Pauli strings follow the stated qubit order.
  • The energies of the four computational basis states equal the values added up by hand from the coefficients.
  • Your Hamiltonian matrix equals the SDK's own testbed matrix (ketqat_runner.vqe).
  • Your parameter-shift gradient equals central finite differences at seeded random parameters.
  • Your VQE reaches the exact ground energy of a matrix built independently in the test, and the exact_ground_energy of the SDK product [email protected].

Run the checks

python -m pytest test_exercise.py
Terminal
python -m pip install numpy pytest "ketqat[algorithms]"

buggy_vqe.py

Python
"""A small VQE that runs, converges, and is wrong.

This module is given to you as found. It reports an energy for the H2-shaped
testbed in HAMILTONIAN_TEXT, the optimiser converges smoothly, and nothing
crashes. Your job is to find out what is wrong, fix it in starter.py, and pin the
correct behaviour with the tests.

Intended conventions: qubit 0 is the most significant bit of the basis index,
the first letter of a Pauli string acts on qubit 0, and RY(theta) = exp(-i theta Y / 2).
"""

import math

import numpy as np

#: The KetQat SDK's two-qubit H2-shaped testbed (approximate coefficients in hartree;
#: not a validated molecular Hamiltonian), written the way a file export might look.
HAMILTONIAN_TEXT = """
# coefficient  pauli
-0.4804 II
+0.3435 ZI
-0.4347 IZ
+0.5716 ZZ
+0.0910 XX
+0.0910 YY
"""

PAULI = {
    "I": np.eye(2, dtype=complex),
    "X": np.array([[0, 1], [1, 0]], dtype=complex),
    "Y": np.array([[0, -1j], [1j, 0]], dtype=complex),
    "Z": np.array([[1, 0], [0, -1]], dtype=complex),
}


def parse_terms(text):
    """Parse lines "<coefficient> <pauli string>" into [(float, str)]."""
    terms = []
    for line in text.splitlines():
        line = line.strip()
        if not line or line.startswith("#"):
            continue
        coefficient, label = line.split()
        if set(label) == {"I"}:
            # A constant term does not change where the minimum is.
            continue
        terms.append((float(coefficient), label))
    return terms


def pauli_string_matrix(label):
    """Kronecker product of the single-qubit Paulis in the string."""
    out = np.array([[1.0 + 0j]])
    for letter in reversed(label):
        out = np.kron(out, PAULI[letter])
    return out


def hamiltonian_matrix(terms):
    """Dense Hamiltonian sum_i c_i P_i."""
    n = len(terms[0][1])
    H = np.zeros((2**n, 2**n), dtype=complex)
    for c, label in terms:
        H += c * pauli_string_matrix(label)
    return H


def ansatz_state(theta, n, layers):
    """`layers` blocks of [RY on every qubit, CX(q -> q+1) ladder], then a final RY layer."""
    theta = np.asarray(theta, dtype=float)
    state = np.zeros(2**n, dtype=complex)
    state[0] = 1
    p = 0
    for block in range(layers + 1):
        for q in range(n):
            c, s = math.cos(theta[p] / 2), math.sin(theta[p] / 2)
            gate = np.array([[c, -s], [s, c]])
            psi = np.moveaxis(state.reshape([2] * n), q, 0)
            psi = np.tensordot(gate, psi, axes=(1, 0))
            state = np.moveaxis(psi, 0, q).reshape(-1)
            p += 1
        if block < layers:
            for q in range(n - 1):
                idx = np.arange(2**n)
                control = (idx >> (n - 1 - q)) & 1
                flipped = idx ^ (control << (n - 2 - q))
                state = state[flipped]
    return state


def energy(theta, terms, layers):
    """<psi(theta)|H|psi(theta)>."""
    n = len(terms[0][1])
    psi = ansatz_state(theta, n, layers)
    return float(np.vdot(psi, hamiltonian_matrix(terms) @ psi).real)


def parameter_shift_gradient(theta, terms, layers):
    """Gradient by the parameter-shift rule."""
    theta = np.asarray(theta, dtype=float)
    grad = np.zeros_like(theta)
    for k in range(theta.size):
        shift = np.zeros_like(theta)
        shift[k] = math.pi / 4
        grad[k] = (energy(theta + shift, terms, layers) - energy(theta - shift, terms, layers)) / 2
    return grad


def run_vqe(terms, layers, steps=300, learning_rate=0.2, seed=0):
    """Gradient descent from a seeded random start. Returns (lowest energy seen, parameters)."""
    n = len(terms[0][1])
    rng = np.random.default_rng(seed)
    theta = rng.uniform(0, 2 * math.pi, size=n * (layers + 1))
    best = (energy(theta, terms, layers), theta.copy())
    for _ in range(steps):
        theta = theta - learning_rate * parameter_shift_gradient(theta, terms, layers)
        e = energy(theta, terms, layers)
        if e < best[0]:
            best = (e, theta.copy())
    return best


if __name__ == "__main__":
    terms = parse_terms(HAMILTONIAN_TEXT)
    e, theta = run_vqe(terms, layers=1)
    print(f"VQE energy: {e:.6f}")

starter.py

Python
"""Starter: the VQE you will repair.

Start from buggy_vqe.py: copy each function body into the matching function here,
then find and fix what is wrong. Not every function is broken. Keep the intended
conventions: qubit 0 is the most significant bit of the basis index, the first
letter of a Pauli string acts on qubit 0, and RY(theta) = exp(-i theta Y / 2).
Write down each defect you find: what you observed, why it happened, and which
test pins it.
"""

import math

import numpy as np

#: The KetQat SDK's two-qubit H2-shaped testbed (approximate coefficients in hartree;
#: not a validated molecular Hamiltonian), written the way a file export might look.
HAMILTONIAN_TEXT = """
# coefficient  pauli
-0.4804 II
+0.3435 ZI
-0.4347 IZ
+0.5716 ZZ
+0.0910 XX
+0.0910 YY
"""

PAULI = {
    "I": np.eye(2, dtype=complex),
    "X": np.array([[0, 1], [1, 0]], dtype=complex),
    "Y": np.array([[0, -1j], [1j, 0]], dtype=complex),
    "Z": np.array([[1, 0], [0, -1]], dtype=complex),
}


def parse_terms(text):
    """Parse lines "<coefficient> <pauli string>" into [(float, str)]."""
    raise NotImplementedError


def pauli_string_matrix(label):
    """Kronecker product of the single-qubit Paulis in the string."""
    raise NotImplementedError


def hamiltonian_matrix(terms):
    """Dense Hamiltonian sum_i c_i P_i."""
    raise NotImplementedError


def ansatz_state(theta, n, layers):
    """`layers` blocks of [RY on every qubit, CX(q -> q+1) ladder], then a final RY layer."""
    raise NotImplementedError


def energy(theta, terms, layers):
    """<psi(theta)|H|psi(theta)>."""
    raise NotImplementedError


def parameter_shift_gradient(theta, terms, layers):
    """Gradient by the parameter-shift rule."""
    raise NotImplementedError


def run_vqe(terms, layers, steps=300, learning_rate=0.2, seed=0):
    """Gradient descent from a seeded random start. Returns (lowest energy seen, parameters)."""
    raise NotImplementedError

test_exercise.py

Python
import importlib.util
import os
from pathlib import Path

def _load_target():
    name = os.environ.get("KETQAT_COMMONS_TARGET", "starter")
    path = Path(__file__).with_name(f"{name}.py")
    spec = importlib.util.spec_from_file_location(f"{Path(__file__).parent.name}_{name}", path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

target = _load_target()

import math

import numpy as np
import pytest

# Coefficients typed out here, independently of any parser.
C = {"II": -0.4804, "ZI": 0.3435, "IZ": -0.4347, "ZZ": 0.5716, "XX": 0.0910, "YY": 0.0910}


def diagonal_energy(b0, b1):
    """Energy of the basis state |b0 b1> by hand: Z eigenvalue (-1)^b, X and Y terms vanish."""
    z0, z1 = (-1) ** b0, (-1) ** b1
    return C["II"] + C["ZI"] * z0 + C["IZ"] * z1 + C["ZZ"] * z0 * z1


def basis_angles(b0, b1):
    """Parameters of the one-layer ansatz that prepare |b0 b1>: all zero except the final layer."""
    return np.array([0.0, 0.0, math.pi * b0, math.pi * b1])


def terms():
    return target.parse_terms(target.HAMILTONIAN_TEXT)


def load_buggy():
    path = Path(__file__).with_name("buggy_vqe.py")
    spec = importlib.util.spec_from_file_location("buggy_vqe_for_tests", path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


def test_the_provided_code_really_is_wrong():
    buggy = load_buggy()
    t = buggy.parse_terms(buggy.HAMILTONIAN_TEXT)
    assert not np.isclose(buggy.energy(basis_angles(0, 1), t, 1), diagonal_energy(0, 1))


def test_parser_keeps_every_term_with_its_sign():
    parsed = dict((label, c) for c, label in terms())
    assert parsed == pytest.approx(C)


def test_pauli_strings_follow_the_qubit_order():
    assert np.allclose(target.pauli_string_matrix("ZI"), np.diag([1, 1, -1, -1]))
    assert np.allclose(target.pauli_string_matrix("IZ"), np.diag([1, -1, 1, -1]))
    X = np.array([[0, 1], [1, 0]])
    Y = np.array([[0, -1j], [1j, 0]])
    assert np.allclose(target.pauli_string_matrix("XY"), np.kron(X, Y))


@pytest.mark.parametrize("b0,b1", [(0, 0), (0, 1), (1, 0), (1, 1)])
def test_energies_of_basis_states_are_pinned(b0, b1):
    assert target.energy(basis_angles(b0, b1), terms(), 1) == pytest.approx(diagonal_energy(b0, b1), abs=1e-12)


def test_ansatz_prepares_the_basis_states():
    for b0 in (0, 1):
        for b1 in (0, 1):
            psi = target.ansatz_state(basis_angles(b0, b1), 2, 1)
            assert abs(psi[2 * b0 + b1]) == pytest.approx(1)


def test_matrix_matches_the_sdk_testbed():
    vqe = pytest.importorskip("ketqat_runner.vqe")
    sdk_matrix, provenance = vqe.h2_hamiltonian_approximate()
    assert provenance["validated"] is False
    assert np.allclose(target.hamiltonian_matrix(terms()), sdk_matrix, atol=1e-12)


def test_gradient_matches_central_finite_differences():
    rng = np.random.default_rng(8)
    t = terms()
    for _ in range(3):
        theta = rng.uniform(0, 2 * math.pi, size=6)
        g = target.parameter_shift_gradient(theta, t, 2)
        h = 1e-6
        fd = np.array([(target.energy(theta + h * e, t, 2) - target.energy(theta - h * e, t, 2)) / (2 * h) for e in np.eye(6)])
        assert np.allclose(g, fd, atol=1e-6)


def test_vqe_reaches_the_exact_ground_energy():
    t = terms()
    # Independent reference: diagonalise the hand-built matrix.
    I2, X, Y, Z = np.eye(2), np.array([[0, 1], [1, 0]]), np.array([[0, -1j], [1j, 0]]), np.diag([1, -1])
    H = (C["II"] * np.kron(I2, I2) + C["ZI"] * np.kron(Z, I2) + C["IZ"] * np.kron(I2, Z)
         + C["ZZ"] * np.kron(Z, Z) + C["XX"] * np.kron(X, X) + C["YY"] * np.kron(Y, Y))
    e0 = np.linalg.eigvalsh(H)[0]
    e, theta = target.run_vqe(t, layers=1, seed=0)
    assert e >= e0 - 1e-12
    assert e - e0 < 1e-6


@pytest.fixture
def ketqat_home(tmp_path, monkeypatch):
    monkeypatch.setenv("KETQAT_HOME", str(tmp_path / "ketqat-home"))


def test_ground_energy_agrees_with_the_sdk_product(ketqat_home):
    catalog = pytest.importorskip("ketqat_runner.catalog")
    record = catalog.run("[email protected]", seed=7, hamiltonian="h2-approximate", qubits=2, layers=2)
    assert record.status == "succeeded"
    e, _ = target.run_vqe(terms(), layers=1, seed=0)
    assert e == pytest.approx(record.result["exact_ground_energy"], abs=1e-6)

Check your understanding

7 questions. Pass with 70% of the points. Answers are checked on the server; retakes are allowed. Explanations appear once you pass or after three complete attempts.

  1. Using your vqe-measurement-budget solution at the exact ground state of H2_TESTBED, with the greedy qubit-wise commuting groups, compute shots_for_precision(sigmas, 1.6e-3) with the optimal allocation. (Deterministic; no sampling.)

    2 pts

    Computed by running exercise “vqe-measurement-budget” on your computer.

  2. Two measurement groups have single-shot standard deviations σ1=0.3\sigma_1 = 0.3 and σ2=0.1\sigma_2 = 0.1. With a total of 4,000 shots split optimally, how many shots go to group 1?

    1 pt
  3. Can XXXX and YYYY be estimated from the same shots?

    1 pt
  4. Code computes [E(θ+π/4)−E(θ−π/4)]/2[E(\theta + \pi/4) - E(\theta - \pi/4)]/2 and calls it the derivative of an energy that depends on θ\theta through one RY(θ)R_Y(\theta) gate. What does it actually return?

    1 pt
  5. After fixing vqe-debugging, run run_vqe(parse_terms(HAMILTONIAN_TEXT), layers=1, seed=0) and enter the energy. (Deterministic.)

    1 pt

    Computed by running exercise “vqe-debugging” on your computer.

  6. Which defects can leave the converged VQE energy of the testbed unchanged, so that a test of the final energy alone cannot catch them? Select all that apply.

    1 pt

    Select all that apply.

  7. Which statement about barren plateaus is supported by the theorems cited in the lesson?

    1 pt

Sign in with GitHub to check answers and save progress. Reading stays free without an account.

References

  1. Dave Wecker, Matthew B. Hastings, Matthias Troyer (2015). Progress towards practical quantum variational algorithms. Physical Review A 92, 042303. doi:10.1103/PhysRevA.92.042303
  2. Vladyslav Verteletskyi, Tzu-Ching Yen, Artur F. Izmaylov (2020). Measurement optimization in the variational quantum eigensolver using a minimum clique cover. The Journal of Chemical Physics 152, 124114. doi:10.1063/1.5141458
  3. Kosuke Mitarai et al. (2018). Quantum circuit learning. Physical Review A 98, 032309. doi:10.1103/PhysRevA.98.032309
  4. Maria Schuld et al. (2019). Evaluating analytic gradients on quantum hardware. Physical Review A 99, 032331. doi:10.1103/PhysRevA.99.032331
  5. Jarrod R. McClean et al. (2018). Barren plateaus in quantum neural network training landscapes. Nature Communications 9, 4812. doi:10.1038/s41467-018-07090-4
  6. M. Cerezo et al. (2021). Cost function dependent barren plateaus in shallow parametrized quantum circuits. Nature Communications 12, 1791. doi:10.1038/s41467-021-21728-w
  7. Jarrod R. McClean et al. (2016). The theory of variational hybrid quantum-classical algorithms. New Journal of Physics 18, 023023. doi:10.1088/1367-2630/18/2/023023
  8. Abhinav Kandala et al. (2017). Hardware-efficient variational quantum eigensolver for small molecules and quantum magnets. Nature 549, 242-246. doi:10.1038/nature23879
  9. KetQat contributors (2026). KetQat SDK (open source, Apache-2.0), catalog products used at main 2cedabb.