Skip to content
Tech Interview Prep
Technical interview guide

Variational Algorithms & NISQ Computing

How hybrid classical-quantum loops like VQE and QAOA are designed to extract value from today's noisy, error-uncorrected hardware.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v3
Editorial status
Reviewed

Scope: IBM Quantum current variational, VQE, Estimator, mitigation, runtime, and transpiler guidance; foundational VQE, QAOA, and barren-plateau literature reviewed 2026-09-04.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-10

Walk me through the hybrid quantum-classical execution loop of VQE, distinguishing the responsibilities of the quantum processor from the classical optimizer across an iteration.

Answer

In the Variational Quantum Eigensolver (VQE), the execution loop forms a closed-loop feedback pipeline partitioned strictly across physical constraints:

[Classical Optimizer] ---> theta_k ---> [QPU / Runtime: Transpiled Ansatz U(theta_k)]
         ^                                         |
         |                                         v
[Update: theta_{k+1}] <--- E(theta_k) <--- [Measure Basis / Grouped Observables]
                                            [Readout & Error Mitigation (ZNE/TREX)]

1. Quantum Coprocessor Responsibilities

The quantum processor (QPU) evaluates expectation values of non-trivial state superpositions that are classically intractable to represent:

  1. Parametric State Preparation: Executes a fixed-depth parameterized unitary $U(\vec{\theta})$ on a reference state $|0\rangle^{\otimes n}$ (or Hartree-Fock state $|\Phi_0\rangle$). Circuit transpilation to native basis gates (e.g., $CX, \sqrt{X}, R_z$) and device coupling maps is performed ahead of time; per-iteration overhead is minimized by rebinding numeric parameters $\vec{\theta}_k$ into parameterized circuit templates.
  2. Observable Measurement: Decomposes the electronic/system Hamiltonian $H = \sum_i c_i P_i$ into grouped commuting Pauli strings. For $M$ qubit-wise commuting (QWC) or general commuting cliques, single-qubit basis rotations ($H$ for $X$, $S^\dagger H$ for $Y$) project states before computational basis measurements.
  3. Expectation Aggregation & Error Mitigation: For each clique, the QPU samples $N_{shots}$ projective measurements. Primitive interfaces (such as Qiskit Runtime Estimator) apply Twirled Readout Error eXtinction (TREX) and Zero Noise Extrapolation (ZNE) directly to output mitigated scalar estimates $\langle P_i \rangle = \langle \psi(\vec{\theta}_k) | P_i | \psi(\vec{\theta}_k) \rangle$.

2. Classical Host Responsibilities

The classical host drives convergence, processing scalar metrics without storing quantum state vectors:

  1. Objective Reconstruction: Computes $E(\vec{\theta}k) = \sum_i c_i \langle P_i \rangle + E{nuc}$, adding classical offsets (such as nuclear repulsion energy).
  2. Optimization Update: Proposes $\vec{\theta}{k+1}$. Under gradient-free schemes (COBYLA, Nelder-Mead, SPSA), updates use function values. For gradient-based schemes (e.g., Adam), gradients $\nabla{\vec{\theta}} E$ are evaluated via parameter-shift rules ($2p$ QPU queries per iteration for $p$ parameters: $\frac{\partial E}{\partial \theta_j} = \frac{E(\theta_j + \frac{\pi}{2}) - E(\theta_j - \frac{\pi}{2})}{2}$).
  3. Convergence Termination: Assesses $|E(\vec{\theta}k) - E(\vec{\theta}{k-1})| < \epsilon_{tol}$ or $|\vec{\theta}k - \vec{\theta}{k-1}| < \delta_{tol}$.

Quantitative Trade-offs

Pipeline StageBottleneck / ComplexityLatency DriverMitigation Strategy
Quantum Execution$\mathcal{O}(M \cdot N_{shots})$ circuit runs per pointQPU repetition rate ($1-100\text{ kHz}$), reset delay, queue timesPauli grouping, Runtime containerized sessions, parameter rebinding
Gradient Calculation$2p$ evaluations for parameter-shift; $2$ for SPSAProportional to parameter count $p$SPSA for noisy landscapes; analytical gradients via adjoint state only on simulators
Classical UpdateConvergence rate under noisy objectiveStagnation at local minima / barren plateausLearning rate decay, regularized momentum, finite shot-budget scaling

Failure Modes & Boundaries

  • Queue Stagnation: Issuing separate network jobs per parameter-shift query introduces network round-trips ($>1\text{ s}$ per query vs. millisecond QPU execution). Mitigated by batching all shifted evaluations into a single execution session.
  • Optimizer Trapping via Shot Noise: Non-gradient optimizers (e.g., Nelder-Mead) evaluate false simplex contractions when objective differences are dominated by variance $\sigma = \sqrt{\sum_i c_i^2 (1 - \langle P_i \rangle^2) / N_{shots}}$.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

How does the Rayleigh-Ritz variational principle guarantee an upper bound in VQE, and under what conditions on physical hardware does this bound break down?

Answer

The 90-second version. VQE minimizes $\langle \psi(\vec\theta)|H|\psi(\vec\theta)\rangle$ over a parameterized state. For any normalized state, pure or mixed, that expectation is $\ge E_0$, the smallest eigenvalue of $H$. That is the entire guarantee, and it is a statement about the exact expectation value of the exact Hamiltonian. On hardware you never measure that quantity: you measure a finite-shot estimator of it, and you may post-process it. The bound survives every CPTP noise channel, because a noisy state is still a valid density matrix and $\operatorname{Tr}(\rho H) \ge E_0$ still holds. It breaks when the number you report is no longer $\operatorname{Tr}(\rho H)$ for any valid $\rho$, or when the Hamiltonian you are variationally bounding is not the Hamiltonian you care about.

Why the bound holds

Write $H = \sum_k E_k |\phi_k\rangle\langle\phi_k|$ with $E_0 \le E_1 \le \dots$ and expand a normalized state as $|\psi\rangle = \sum_k c_k |\phi_k\rangle$, $\sum_k |c_k|^2 = 1$:

$$\langle H\rangle = \sum_k |c_k|^2 E_k \ge E_0 \sum_k |c_k|^2 = E_0.$$

Equality holds iff the support of $|\psi\rangle$ lies inside the ground eigenspace. The mixed-state version is one line: $\operatorname{Tr}(\rho H) - E_0 = \operatorname{Tr}\big(\rho (H - E_0 I)\big) \ge 0$, since $H - E_0 I \succeq 0$ and $\rho \succeq 0$. This is why noise alone cannot push the expectation below $E_0$: it can only raise the floor you can reach.

Where it actually breaks

1. Finite shots: the minimum is biased low. Each Pauli term is estimated from $M_i$ shots with $\operatorname{Var}(\hat P_i) = (1 - \langle P_i\rangle^2)/M_i$. Individual estimates are unbiased, but the optimizer keeps the lowest value it sees, so it selects downward fluctuations. Suppose the ansatz-limited floor is $-0.90$ Ha, the true $E_0$ is $-1.00$ Ha, and one dominant term has $h = 1$, $\langle P\rangle = -0.90$ at the optimum. With $M = 100$ shots, $\sigma = \sqrt{(1-0.81)/100} = 0.044$. The expected minimum of 100 independent draws is about $\mu - 2.5\sigma = -0.90 - 0.11 = -1.01$ Ha: reported below $E_0$. Real optimizers sample correlated points, so the bias is smaller than this worst case, but it is always downward.

2. Readout inversion produces non-physical expectations. Correcting readout means solving $p_{\text{true}} = A^{-1} p_{\text{meas}}$. With $A = \begin{pmatrix}0.97 & 0.05\ 0.03 & 0.95\end{pmatrix}$ and a measured $p_{\text{meas}} = (0.025, 0.975)$, i.e. $\langle Z\rangle_{\text{meas}} = -0.95$:

$$p_{\text{true}} = \frac{1}{0.92}\begin{pmatrix}0.95 & -0.05\ -0.03 & 0.97\end{pmatrix}\begin{pmatrix}0.025\ 0.975\end{pmatrix} = \begin{pmatrix}-0.027\ 1.027\end{pmatrix}, \quad \langle Z\rangle_{\text{corr}} = -1.054.$$

For $H = Z$, $E_0 = -1$, the corrected estimate sits $0.054$ below the true ground state. The tell is $|\langle P\rangle| > 1$ on any Pauli term.

3. Mitigation that is not a state. ZNE fits $E(\lambda)$ and extrapolates to $\lambda = 0$; the extrapolated value is not the expectation of any state, so nothing constrains it. PEC is different: it is unbiased in expectation, but its variance scales with the sampling overhead $\gamma^2$, so individual runs dip below $E_0$ even though the mean does not.

4. The Hamiltonian is an approximation. The bound is against $E_0$ of the qubit Hamiltonian you built: finite basis set, frozen core, Born–Oppenheimer. That is the FCI energy in that basis, not the experimental ground state. A VQE run can legitimately report an energy below the measured experimental ground state and still be a correct variational bound on the wrong reference.

SourceQuantity actually computedBound vs $E_0$Detection
Ideal VQE$\langle\psi(\vec\theta)H\psi(\vec\theta)\rangle$
Any CPTP noise$\operatorname{Tr}(\rho H)$, $\rho \succeq 0$still $\ge E_0$floor rises toward $\operatorname{Tr}(H)/d$
Finite shots$\min_{\vec\theta}$ of a sample meanbiased low, $\sim 2.5\sigma$ over $N$ evalserror bars; rerun with more shots
Readout inversion$A^{-1}\hat p$can go below$
ZNEpolynomial fit at $\lambda = 0$no guaranteefit residual, sensitivity to $\lambda$-range
PECunbiased, variance $\gamma^2$unbiased in mean, dips per runsampling overhead $\gamma^2$
Approximate $H$$E_0$ of a finite-basis $H$bound is vs FCI in that basiscompare to FCI in the same basis

In practice: never quote $\min_{\vec\theta} \hat E(\vec\theta)$ as a bound without the standard error, reject any run where a Pauli expectation leaves $[-1, 1]$, and compare against FCI in the same basis rather than against experiment.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

How do you decompose an arbitrary molecular or spin Hamiltonian into a linear combination of Pauli strings, and how does the number of terms scale with system size?

Answer

Assume $n$ qubits and a Hermitian Hamiltonian $H$ acting on $2^n$ states. The Pauli strings $P \in {I,X,Y,Z}^{\otimes n}$ form an orthonormal basis under the Hilbert-Schmidt inner product $\mathrm{Tr}(P Q) = 2^n \delta_{PQ}$. So the decomposition is unique:

$$H = \sum_P c_P P, \qquad c_P = 2^{-n} \mathrm{Tr}(H P).$$

For spin Hamiltonians, you get the $c_P$ by substituting $S^\alpha = (\hbar/2)\sigma_\alpha$ and expanding. For molecular Hamiltonians, you start in second quantization and apply a fermion-to-qubit mapping to each $a_p, a_p^\dagger$, then expand.

Spin Hamiltonians. For a nearest-neighbor Heisenberg model on a graph $G=(V,E)$ with $n$ spins,

$$H = \sum_{\langle ij\rangle} J_{ij} (S^x_i S^x_j + S^y_i S^y_j + S^z_i S^z_j) + \sum_i h_i S^z_i.$$

Each edge contributes three Pauli strings ($XX$, $YY$, $ZZ$); each field term contributes one ($Z$). So $M = 3|E| + n$. On a bounded-degree lattice $|E| = O(n)$, so $M = O(n)$. On a fully connected graph $|E| = O(n^2)$, so $M = O(n^2)$. If the two-body terms are arbitrary (all 9 Pauli pairs per edge), the same graph scaling holds with a larger constant.

Molecular Hamiltonians. With $N$ spin-orbitals,

$$H_e = \sum_{pq} h_{pq} a_p^\dagger a_q + \frac{1}{2} \sum_{pqrs} h_{pqrs} a_p^\dagger a_q^\dagger a_s a_r.$$

There are $O(N^2)$ one-body integrals and $O(N^4)$ two-body integrals. The mapping to Pauli strings depends on the fermion-to-qubit encoding:

Mapping$a_j^\dagger$ representationPauli weight$M$ scaling
Jordan-Wigner (JW)$(\prod_{k<j} Z_k)(X_j - iY_j)/2$up to $O(N)$$O(N^4)$ general; $O(N^2)$ with active-space/sparse
Bravyi-Kitaev (BK)binary tree balancing occupation and parity$O(\log N)$$O(N^4)$ general; lower weight
Parityqubit $j$ stores $\sum_{k\le j} n_k \bmod 2$up to $O(N)$$O(N^4)$ general; allows 2-qubit reduction via $\mathbb{Z}_2$ symmetries

Each two-body integral expands to a constant number of Pauli strings (up to 16 before cancellation), so the total $M$ is $O(N^4)$ in the worst case. Symmetries (particle number, spin, point group) zero out many coefficients. For example, H$_2$/STO-3G ($N=4$) gives 15 Pauli strings after JW. H$_2$O/STO-3G ($N=14$) gives a few hundred. For $N=50$, $M$ can reach $10^5$–$10^6$.

Measurement overhead. To estimate $\langle H \rangle$ to chemical accuracy $\epsilon = 1.6\times10^{-3}$ Ha, independent sampling gives

$$\mathrm{Var}(\langle H \rangle) = \sum_k \frac{c_k^2 (1 - \langle P_k \rangle^2)}{S_k}.$$

With optimal allocation, total shots scale as $S_{\text{total}} \sim (\sum_k |c_k|)^2 / \epsilon^2$. Without grouping, an $O(N^4)$ operator count leads to $10^8$–$10^{10}$ shots per VQE iteration.

Practical mitigations.

  1. Qubit-wise commuting (QWC) or fully commuting (FC) grouping: partition the $M$ strings into commuting families. QWC terms can be measured from one circuit with a single-qubit rotation layer. This reduces the number of circuits from $O(N^4)$ to $O(N^3)$ or $O(N^2)$.
  2. Coefficient truncation: discard strings with $|c_k| < \delta$. To keep the error below $\epsilon$, choose $\delta < \epsilon/M$. Also enforce known symmetries ($S_z$, $N_e$) to remove unphysical terms before execution.

Failure modes. JW introduces non-local $Z$ strings, so individual Pauli measurements can require deep circuits. BK reduces Pauli weight but complicates the mapping. Truncation can break symmetries and bias the variational energy. Grouping can be suboptimal if the commuting families are large. Detect these by comparing the reconstructed Hamiltonian to the original on random states for small $N$, and by monitoring the variance of $\langle H \rangle$ during VQE.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

How does Pauli grouping reduce the number of measurement circuits required in VQE, and what are the trade-offs between qubit-wise commuting and fully commuting groups?

Answer

Core answer

VQE estimates $E = \sum_k c_k \langle P_k \rangle$. Each Pauli string needs its own measurement basis unless several can be measured together. Pauli grouping partitions terms into commuting sets; one circuit per set gives all expectations in that set. QWC groups are cheap to measure but small; FC groups are larger but need entangling gates to diagonalize.

QWC vs FC

  • Qubit-wise commuting (QWC): $P_A$ and $P_B$ commute if at every qubit they are equal or one is $I$. Measurement uses single-qubit rotations only: $H$ for $X$, $S^\dagger H$ for $Y$, nothing for $Z$, then measure $Z$. No CNOTs.
  • Fully commuting (FC): $[P_A, P_B] = 0$ as operators, equivalent to anticommuting on an even number of qubits. Measurement finds a Clifford $U$ with $U P U^\dagger \in {I, Z}^{\otimes n}$. $U$ may contain CNOTs.

Worked example

$H = Z_1 Z_2 + Z_1 I + I Z_2 + X_1 X_2 + Y_1 Y_2$.

QWC groups: ${Z_1 Z_2, Z_1 I, I Z_2}$ measured in the $Z$ basis; ${X_1 X_2}$ with $H$ on both qubits; ${Y_1 Y_2}$ with $S^\dagger H$ on both. 3 circuits.

FC groups: ${Z_1 Z_2, Z_1 I, I Z_2}$ and ${X_1 X_2, Y_1 Y_2}$. For the second, take $U = H_1 \cdot \mathrm{CNOT}(1 \to 2)$: apply CNOT with control 1, target 2, then $H$ on qubit 1.

Trace the conjugation with the CNOT rules $X_1 \to X_1 X_2$, $X_2 \to X_2$, $Y_1 \to Y_1 X_2$, $Y_2 \to Z_1 Y_2$:

  • $X_1 X_2 \to X_1 X_2 \cdot X_2 = X_1 \to H_1 X_1 H_1 = Z_1$.
  • $Y_1 Y_2 \to Y_1 X_2 \cdot Z_1 Y_2 = (Y_1 Z_1)(X_2 Y_2) = (iX_1)(iZ_2) = -X_1 Z_2 \to H_1(-X_1 Z_2)H_1 = -Z_1 Z_2$.

Both diagonal. So one circuit (CNOT(1→2), $H$ on qubit 1, measure both in $Z$) gives $\langle X_1 X_2 \rangle = \langle Z_1 \rangle$ and $\langle Y_1 Y_2 \rangle = -\langle Z_1 Z_2 \rangle$. Total 2 circuits, versus 3 for QWC and 5 for individual terms.

Check on $|\psi\rangle = (|00\rangle + |11\rangle)/\sqrt{2}$: $\langle X_1 X_2 \rangle = 1$ and $\langle Y_1 Y_2 \rangle = -1$. After $U$ the state is $|00\rangle$, so $\langle Z_1 \rangle = 1$ and $-\langle Z_1 Z_2 \rangle = -1$. Matches.

Trade-offs

  • Circuit count: FC $\le$ QWC $\le$ individual. Here 2 vs 3 vs 5.
  • Depth and noise: QWC adds only single-qubit gates. FC adds CNOTs. A 1% CNOT error can dominate shot noise at high precision.
  • Classical overhead: minimum grouping is NP-hard. QWC grouping is graph coloring on the incompatibility graph; FC grouping is minimum clique cover on the commutativity graph. Greedy heuristics (Largest Degree First, DSATUR) are used. FC also needs symplectic Gaussian elimination to synthesize $U$.
  • Shot allocation: for a group, $\mathrm{Var}(\sum P) = \sum \mathrm{Var}(P) + 2\sum \mathrm{Cov}(P_i, P_j)$. Positive covariance can raise the shots needed. Fewer circuits does not always mean fewer shots.

Failure modes

  • Noise-precision inversion: FC cuts circuit count but adds CNOTs. If CNOT error is high, the extra noise can degrade energy accuracy more than the shot noise saved. Detect by comparing energy error versus shot budget for QWC and FC on the same hardware.
  • Classical grouping bottleneck: an $n$-spin-orbital molecular Hamiltonian has $O(n^4)$ Pauli terms; greedy coloring costs $O(M^2 n)$ for $M$ terms, and FC needs symplectic Gaussian elimination on top.
  • Covariance: correlated terms in a group can make the variance of the sum exceed the sum of variances. Detect by estimating covariance from samples or using shot allocation that accounts for it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Design and validate a variational quantum workflow for expectation estimation.

Answer

What I'd say first

Expectation estimation here means estimating ⟨ψ(θ)|H|ψ(θ)⟩ for a parameterized state and a Hamiltonian written as a weighted Pauli sum H = Σ cᵢPᵢ, and reporting each estimate with an uncertainty. I'd assume a fixed ansatz, a Pauli-sum Hamiltonian, and a shot-based backend. The workflow is: group the Pauli terms, run the grouped circuits through an Estimator primitive with a target precision, read back expectation values and standard errors, and hand those to the optimizer. Validation is against exact statevector simulation plus a shot-scaling check.

Mechanism

Each Pauli term is measured by rotating into the Z basis and sampling; the estimate is the sample mean of ±1 outcomes. Its per-shot variance is 1 − ⟨P⟩², so the standard error after N shots is sqrt((1 − ⟨P⟩²)/N). That is why shots set precision: to reach ε on a term you need N ≈ 1/ε² shots in the worst case (⟨P⟩ = 0). The Hamiltonian's uncertainty is the quadrature sum over terms, so the shot budget scales with Σ cᵢ².

Workflow

  1. Build H as a SparsePauliOp.
  2. Group commuting terms with group_commuting(qubit_wise=True) to cut circuit count.
  3. Run EstimatorV2 with precision=ε; the primitive derives the shot count.
  4. Read data.evs and data.stds.
  5. Take an optimizer step; stop when the energy improvement falls below the combined standard error, not below a fixed threshold.
Python
from qiskit.quantum_info import SparsePauliOp
from qiskit_ibm_runtime import EstimatorV2

H = SparsePauliOp.from_list([("ZZ", 0.5), ("ZI", -0.3), ("IZ", -0.3), ("XX", 0.2)])
groups = H.group_commuting(qubit_wise=True)   # [ZZ+ZI+IZ, XX]

est = EstimatorV2(mode=backend)
est.options.resilience_level = 1              # TREX readout mitigation
res = est.run([(ansatz, H, [theta])], precision=0.01).result()
evs, stds = res[0].data.evs, res[0].data.stds

Arithmetic

For one Pauli with ⟨P⟩ = 0, ε = 0.01 needs N = 1/ε² = 10,000 shots. For the H above, Σ cᵢ² = 0.25 + 0.09 + 0.09 + 0.04 = 0.47, so equal allocation gives N = 0.47/ε² ≈ 4,700 shots per term. Because ZZ, ZI and IZ are qubit-wise commuting, one circuit serves all three, so the total is 2 × 4,700 ≈ 9,400 shots rather than 18,800.

Trade-offs

  • Precision vs shots: halving ε costs 4× the shots.
  • Grouping: qubit-wise grouping is cheap; general commuting grouping cuts circuits further but needs more basis-change gates.
  • Mitigation: resilience_level=1 (TREX readout) reduces bias at the cost of calibration circuits; level 2 adds ZNE, which reduces bias more but inflates variance and shot cost.
  • Optimizer: SPSA uses two circuit evaluations per step regardless of parameter count; finite-difference gradients use 2p.

Failure modes and detection

  • Point estimate only: no stds, so convergence can't be told from noise. Detect by asserting stds is present and non-zero.
  • Observable order mismatch: Qiskit Pauli strings are little-endian ("IX" is X on qubit 0), so a reversed string measures the wrong qubit. Detect by comparing against StatevectorEstimator on a known state.
  • Precision treated as exact: the optimizer stops on a difference smaller than the noise. Detect by comparing ΔE to sqrt(σₐ² + σ_b²).
  • Mitigation hidden: results aren't reproducible. Detect by logging resilience_level and the run options.
  • Backend changed: transpilation and calibration differ. Detect by recording backend name, version and calibration timestamp.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

How does finite sampling (shot noise) affect expectation value estimation in variational algorithms, and how do you determine optimal shot allocation across Pauli terms?

Answer

Finite sampling replaces exact quantum expectation values $\langle H \rangle = \sum_i c_i \langle P_i \rangle$ with empirical sample averages $\hat{H} = \sum_i c_i \hat{P}_i$. Because measuring a Pauli operator $P_i$ yields eigenvalues $\pm 1$, the single-shot variance of measuring $P_i$ is $\mathrm{Var}(P_i) = 1 - \langle P_i \rangle^2$. When measured over $N_i$ independent shots, the estimator variance is $\mathrm{Var}(\hat{P}_i) = \frac{1 - \langle P_i \rangle^2}{N_i}$. Assuming terms are measured independently, the total estimator variance is:

$$\mathrm{Var}(\hat{H}) = \sum_i \frac{c_i^2 (1 - \langle P_i \rangle^2)}{N_i}$$

Impact on Optimization

  1. Gradient Noise & Convergence Stalls: Estimator standard error scales as $\mathcal{O}(1/\sqrt{N_{\text{total}}})$. When variance $\mathrm{Var}(\hat{H})$ exceeds the cost differential between optimization steps, deterministic optimizers (like BFGS) evaluate false uphill steps and terminate prematurely. Stochastic optimizers (like SPSA) tolerate variance better, but shot noise increases iteration count and trajectory dispersion.
  2. Energy Inaccuracy: In VQE, shot noise violates variational lower bounds; an empirical sample can fluctuate below the true ground-state eigenvalue $E_0$.

Optimal Shot Allocation (Neyman / Lagrange Formulation)

To minimize $\mathrm{Var}(\hat{H})$ subject to a fixed shot budget $N = \sum_i N_i$, formulate the Lagrangian:

$$\mathcal{L}(N_1, \dots, N_M, \lambda) = \sum_{i=1}^M \frac{c_i^2 \sigma_i^2}{N_i} + \lambda \left(\sum_{i=1}^M N_i - N\right)$$

where $\sigma_i^2 = 1 - \langle P_i \rangle^2$. Taking the partial derivative $\frac{\partial \mathcal{L}}{\partial N_i} = -\frac{c_i^2 \sigma_i^2}{N_i^2} + \lambda = 0$ yields $N_i \propto |c_i| \sigma_i$. Substituting back into the budget constraint gives:

$$N_i^* = N \frac{|c_i| \sigma_i}{\sum_{j=1}^M |c_j| \sigma_j}$$

In practice, before $\langle P_i \rangle$ is known, we use the conservative upper bound $\sigma_i \le 1$, resulting in the coefficient-weighted allocation: $N_i^* = N \frac{|c_i|}{\sum_j |c_j|}$. When grouped into mutually commuting cliques $G_k$, this generalizes to allocating shots proportionally to the group-wise 1-norm or sample covariance.

Worked Comparison: Uniform vs Optimal Allocation

Consider $H = 2.0 Z_1 + 0.2 Z_2$ with total budget $N = 10,000$ shots, assuming $\sigma_1 \approx \sigma_2 \approx 1$:

Strategy$N_1$$N_2$$\mathrm{Var}(\hat{H}) = \frac{4}{N_1} + \frac{0.04}{N_2}$Standard Error $\sigma_{\hat{H}}$
Uniform5,0005,000$\frac{4}{5000} + \frac{0.04}{5000} = 8.08 \times 10^{-4}$$\approx 0.0284$
**Optimal ($N_i \proptoc_i$)**9,091909

Optimal allocation reduces estimator variance by $\sim 40%$ for identical total execution time on hardware primitives like Qiskit Estimator.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

Design and validate a variational quantum workflow for ansatz.

Answer

Assumptions first. I'll take a molecular ground-state problem (H₂, then LiH, in STO-3G) on a gate-based device with ring connectivity and two-qubit gate error around 1e-3. The ansatz is the parameterized circuit U(θ) that prepares |ψ(θ)⟩; the optimizer minimizes C(θ) = ⟨ψ(θ)|H|ψ(θ)⟩. Design and validation are one loop: pick a family from the problem's structure, then prove on small instances that it can reach the answer and that its gradients don't vanish.

Design. Start from the symmetries the Hamiltonian imposes. Molecular electronic Hamiltonians conserve particle number N and total spin S², so the ground state lives in a fixed (N, S) sector. An ansatz that respects those symmetries searches a smaller manifold and cannot land on a symmetry-broken minimum. Two credible families:

  • Problem-inspired (UCCSD / qubit-ADAPT). Excitations applied to a Hartree–Fock reference. For H₂/STO-3G (4 qubits, 2 electrons) a single double-excitation parameter spans the exact singlet ground state.
  • Hardware-efficient (HEA). Layers of Ry/RZ plus a fixed entangler. Shallow and connectivity-friendly, but it conserves nothing and its expressivity is capped by depth.

Validation stage 1: reachability on an exactly solvable instance.

Python
import pennylane as qml
from pennylane import numpy as np

symbols = ["H", "H"]
coords = np.array([0.0, 0.0, -0.3675, 0.0, 0.0, 0.3675])   # 0.735 Å
H, n = qml.qchem.molecular_hamiltonian(symbols, coords, basis="sto-3g")  # n == 4

dev = qml.device("default.qubit", wires=n)

@qml.qnode(dev)
def uccsd(theta):
    qml.BasisState(np.array([1, 1, 0, 0]), wires=range(n))   # HF |1100>
    qml.DoubleExcitation(theta[0], wires=[0, 1, 2, 3])
    return qml.expval(H)

theta = np.array([0.0], requires_grad=True)
opt = qml.GradientDescentOptimizer(stepsize=0.4)
for _ in range(100):
    theta = opt.step(uccsd, theta)
print(uccsd(theta))

Trace: BasisState prepares |1100⟩, the HF determinant. DoubleExcitation rotates amplitude between |1100⟩ and |0011⟩, the only two determinants in the singlet space, so the ansatz spans the exact ground state, and gradient descent drives θ to the minimizer of the resulting 2×2 Hamiltonian. Output ≈ −1.137 Ha, the FCI value for this geometry, within 1e-6 Ha. Reachability passes. Swap in an HEA (Ry/RZ + CNOT ring, depth 2) and the same loop plateaus near the HF energy −1.117 Ha: a ~20 mHa gap, about 12× chemical accuracy (1.6 mHa). That is an expressivity gap, not an optimizer failure: the family cannot represent the state.

Validation stage 2: trainability. For a global cost and a deep random ansatz, Var[∂C/∂θ] decays as ~2⁻ⁿ. At n = 20 that is ~1e-6 (gradient ~1e-3); at n = 50 it is ~9e-16, below float64 epsilon (2.2e-16), so training stalls. Detect it by sampling ~50 random initializations and fitting Var against n. Mitigations: local cost functions (a sum of terms acting on few qubits) avoid the exponential decay; a shallow problem-inspired ansatz; a symmetry-preserving operator pool.

Validation stage 3: hardware cost and noise. Count two-qubit gates after transpiling to the device topology; each contributes error ~1e-3. UCCSD for LiH (12 qubits) has O(n⁴) doubles: hundreds of two-qubit gates, so fidelity collapses. ADAPT-VQE grows the ansatz one operator at a time, picking the pool element with the largest gradient (threshold ~1e-3), giving a compact circuit at the cost of a gradient scan over the pool at each selection step.

Failure modes and how to detect them.

  • Barren plateau: gradient variance ~2⁻ⁿ; detect by the scaling study above; symptom is energy stuck at HF.
  • Expressivity gap: exact diagonalization on n ≤ 12 gives the reference; if the best energy over restarts is above it by more than 1.6 mHa, the family cannot represent the state.
  • Symmetry violation: measure ⟨N⟩ and ⟨S²⟩ each iteration; drift above 1e-3 means the ansatz or noise broke the symmetry.
  • Noise-induced plateau: gradient variance decays with depth even for local costs; compare noiseless simulation against hardware gradients.
  • Parameter-shift bug: for Pauli rotations ∂C/∂θ = [C(θ+π/2) − C(θ−π/2)]/2. If parameters are tied, shift every tied copy. Check against a finite difference (h = 1e-5); a mismatch above 1e-6 is a bug.
ansatzsymmetryparametersdepthwhen not to use
UCCSDN, S²O(n⁴)deeplow-fidelity hardware
qubit-ADAPTif pool conservesgrows adaptivelymoderatewhen classical overhead dominates
HEAnone2n·pshallowstrongly correlated, symmetry-critical
QAOAproblem-dependentp·|edges|p layerswhen p is too small to beat classical

Code checked against PennyLane 0.38; the qml.qchem API is stable across the 0.3x line. Energies are the standard STO-3G values for this geometry and are quoted to the precision the method supports.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Design and validate a variational quantum workflow for reference state.

Answer

Reference state here means the fixed input (|\phi_{\text{ref}}\rangle) that the parameterized circuit acts on: (|\psi(\theta)\rangle = U(\theta)|\phi_{\text{ref}}\rangle). It is not variational. It decides which part of Hilbert space the optimizer can ever reach, so it is the first thing to design and the first thing to validate: before you trust any energy the workflow produces.

Assumptions I'd state up front: electronic-structure problem, second quantization, Jordan-Wigner mapping, molecular Hamiltonian, Hartree-Fock reference. Design: HF reference (a computational-basis product state under JW), UCCSD ansatz, SLSQP optimizer, StatevectorEstimator (Qiskit 1.x) for the classically tractable validation instance.

Validation protocol

Four checks, run before the optimizer is allowed to move anything:

checkpass criteriondetection cost
energy at (\theta=0)(\langle\phi_{\text{ref}}H
particle number(\langle\hat N\rangle = N) exactly and (\mathrm{Var}(\hat N) = 0)two Pauli groups per iteration
gradient at (\theta=0)(\lVert\nabla C(0)\rVert > 10^{-8})parameter-shift, (2P) circuit evaluations
end-to-endVQE energy matches exact diagonalization on a small instanceone dense eigensolve

The reference check, in code

Python
# Qiskit 1.x
import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import SparsePauliOp, Statevector

# H2 / STO-3G, Jordan-Wigner: 4 spin orbitals -> 4 qubits.
# HF reference occupies spin orbitals 0 and 1 -> |1100>.
ref = QuantumCircuit(4)
ref.x(0)
ref.x(1)
psi_ref = Statevector(ref)

# N = sum_i (I - Z_i)/2
N = SparsePauliOp.from_sparse_list(
    [("I", [], 0.5)] + [("Z", [i], -0.5) for i in range(4)],
    num_qubits=4,
)

print(np.real(psi_ref.expectation_value(N)))              # 2.0
print(np.real(psi_ref.expectation_value(N.compose(N))))   # 4.0

Trace: ref.x(0) flips qubit 0, ref.x(1) flips qubit 1; qubit 0 is the least significant bit, so the state is the basis index 3. Each occupied qubit contributes ((1-(-1))/2 = 1) to (\hat N), each empty one contributes 0, giving 2.0. (\hat N) is diagonal with eigenvalue equal to the occupation count, so (\hat N^2) has the same expectation on a number eigenstate: 4.0. Variance is 4.0 − 2.0² = 0, which is the pass condition. A random product state fails this immediately.

Arithmetic that makes the check falsifiable

H2, STO-3G, r = 0.735 Å: (E_{\text{HF}} \approx -1.1167) Ha, (E_{\text{FCI}} \approx -1.1373) Ha, correlation energy (\approx 0.0206) Ha (\approx 0.56) eV. With 2 electrons in 2 spatial orbitals, UCCSD is exact within the singlet sector, so a correct reference plus ansatz must land on −1.1373 Ha. An energy above it by more than the optimizer tolerance means the reference or the ansatz is wrong, not the optimizer. Tapering the two Z2 symmetries takes 4 qubits to 2; the reference must be transformed by the same Clifford as the Hamiltonian, or the (\theta=0) energy check fails.

Alternatives and when not to use HF

A random product state is cheap to prepare but usually sits in the wrong particle-number and spin sector; only use it with penalty terms in the cost function. A classically pre-optimized warm start cuts VQE iterations but biases the run toward the classical method's basin: report the energy distribution over k restarts, not the best run. A correlated reference (MP2, small-basis DMRG) has better overlap with the true ground state, but its state-preparation circuit can cost more than the VQE it saves. Deciding criterion: does the reference have nonzero overlap with the target and live in the right symmetry sector? If yes, take the cheapest one to prepare.

Failure modes and how they show up

  • Symmetry-broken reference. (\langle\hat N\rangle) drifts off the integer or (\mathrm{Var}(\hat N) > 0). Caught by the two extra Pauli groups per iteration, roughly doubling measurement overhead.
  • Stationary start. Gradient is exactly zero at (\theta=0) because the reference is an eigenstate of the ansatz generators in the wrong sector. Caught by the parameter-shift gradient norm at init.
  • Tapering mismatch. Reference not transformed with the Hamiltonian; symptom is (\langle\phi_{\text{ref}}|H|\phi_{\text{ref}}\rangle \neq E_{\text{HF}}).
  • Barren plateau. For a hardware-efficient ansatz at identity initialization, gradient variance decays exponentially in qubit count (McClean et al., Nat. Commun. 9, 4812, 2018). Caught by sampling gradients at random (\theta) and fitting variance against qubit count; a problem-inspired ansatz on an HF reference avoids it.
  • Warm-start bias. Pre-optimized parameters land in a local minimum. Caught by k random restarts and comparing the energy distribution.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Design and validate a variational quantum workflow for cost function.

Answer

Core answer (first 90 seconds)

Assume the task is a variational algorithm, VQE or QAOA, where a parameterized circuit prepares |ψ(θ)⟩ and the cost is the expectation of a Hamiltonian. Fix the cost function as a versioned contract before touching an optimizer:

C(θ) = Σ_i w_i ⟨ψ(θ)|P_i|ψ(θ)⟩ + Σ_j λ_j g_j(θ)

Name the observable H = Σ w_i P_i explicitly (Pauli strings and coefficients), declare the optimization direction (minimize), declare units (Hartree for chemistry, dimensionless for MaxCut), declare the estimator (finite-shot mean with N shots, or analytic), and declare the penalty terms g_j with their λ_j. Gradients, optimizer, and convergence criterion are all defined against that contract.

Why the estimator and landscape decide everything

The estimator is a sample mean of N shots, so its standard error is σ = sqrt(Var(H)/N). For a 4-qubit Hamiltonian with Σ|c_i| = 1.0, Var per shot ≤ 1.0, so N = 10⁴ gives σ = 10 mHa and N = 10⁶ gives σ = 1 mHa. That number sets the convergence tolerance: you cannot claim a 1 mHa energy with 10⁴ shots.

Gradients come from the parameter-shift rule: ∂⟨H⟩/∂θ = [⟨H⟩(θ+π/2) − ⟨H⟩(θ−π/2)]/2, two circuit evaluations per parameter. The gradient's signal-to-noise is (∂C/∂θ)/σ, so shot noise that is fine for the cost can swamp the gradient.

The landscape is where VQAs actually fail. For hardware-efficient ansätze with random initialization, gradient variance decays exponentially in qubit count: roughly 2⁻ⁿ (McClean et al., Nat. Commun. 9, 4812, 2018). At n = 20 that is ~10⁻⁶, so parameter-shift would need ~10¹² shots to resolve a gradient. Detect it before optimizing: sample gradients at random θ and check the variance against the 2⁻ⁿ curve.

Trade-offs

  • Penalty vs constrained ansatz vs post-selection. Penalty keeps the circuit shallow but adds a λ to tune; a constrained ansatz (e.g., XY-mixer for Hamming-weight constraints) removes λ but restricts reachable states; post-selection discards shots and multiplies the shot budget by 1/p_feasible.
  • Parameter-shift vs SPSA. Parameter-shift is exact and unbiased, 2 evals per parameter; SPSA uses 2 evals per step regardless of parameter count, so it wins above ~100 parameters at the cost of a noisy gradient estimate.
  • Pauli grouping vs individual measurement. Qubit-wise commuting groups cut the number of measurement circuits; on a 4-qubit H with 3 terms, grouping can collapse 3 circuits to 1.

Validation protocol

  1. Exact diagonalization on ≤12 qubits: compare ⟨H⟩ at fixed θ to numpy.linalg.eigvalsh(H).
  2. Gradient check: finite difference vs parameter-shift, tolerance 1e-6.
  3. Independent re-evaluation: same θ, different shot seed and different device; |ΔC| must be within 3σ.
  4. Sign and offset: verify C decreases from random init and that the optimum matches a known reference energy (e.g., H₂ at 0.735 Å, −1.137 Ha in STO-3G).
Python
import pennylane as qml
from pennylane import numpy as np

dev = qml.device("default.qubit", wires=4, shots=10_000)
H = qml.Hamiltonian(
    coeffs=[0.5, -0.3, 0.2],
    observables=[qml.PauliZ(0) @ qml.PauliZ(1), qml.PauliX(0), qml.PauliZ(2)],
)

@qml.qnode(dev)
def cost(params):
    qml.StronglyEntanglingLayers(params, wires=range(4))
    return qml.expval(H)

params = np.random.random(qml.StronglyEntanglingLayers.shape(2, 4))
print(cost(params))            # finite-shot estimate, σ ≈ 10 mHa at 10^4 shots
print(qml.grad(cost)(params))  # parameter-shift: 2 evals per parameter

Failure modes and detection

failuredetectioncost
sign reversedoptimizer increases C; compare to exact at fixed θconverges to max, silently
penalty dominatessweep λ, plot feasible fraction vs objectiveobjective gradient vanishes
offset omittedcompare optimum to reference energyenergy off by constant, ranking fine
nonphysical observablecheck Hermiticity and eigenvaluescomplex energies, no physical meaning
train ≠ eval objectivere-evaluate with independent seed/devicereported metric not reproducible

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-1

Design and validate a variational quantum workflow for hybrid loop.

Answer

First 90 seconds. Assume a VQE-style loop: a fixed ansatz U(θ) on n qubits, a cost C(θ) = ⟨ψ(θ)|H|ψ(θ)⟩ estimated from shots, and a classical optimizer proposing θ. One iteration is: bind θ, sample the cost, compute the gradient, hand it to the optimizer, take θ′, test the stopping rule, checkpoint. Two decisions carry the design: how the gradient is computed, and what "converged" means under shot noise. Checkpointing and job tracking exist to make those two decisions auditable.

Mechanism. For any gate generated by a Pauli (RX, RY, RZ), the parameter-shift rule gives the exact derivative

∂C/∂θ = [C(θ + π/2) − C(θ − π/2)] / 2,

so a full gradient costs 2P circuit evaluations for P parameters and needs no step size. Trace it on one qubit with C(θ) = ⟨0|RY(θ)† Z RY(θ)|0⟩ = cos θ. At θ = π/4: C(3π/4) = −0.7071 and C(−π/4) = 0.7071, so the rule returns (−0.7071 − 0.7071)/2 = −0.7071, matching −sin(π/4). Finite difference would need ε small enough to cut its O(ε²) bias but large enough to survive shot noise: at 4096 shots the per-evaluation standard error is 1/√4096 = 0.0156, and ε = 0.01 gives gradient noise ≈ 0.0156/(0.01·√2) ≈ 1.1. Bigger than the gradient itself. That is why parameter-shift is the hardware default.

gradient methodevals per gradientexactnoiseuse when
parameter-shift2Pyes (Pauli-generated gates)SE = σ/√2 per parameterdefault on hardware
finite difference2Pno, O(ε²) biasσ/(ε√2), blows upalmost never
SPSA2no, stochasticaverages out over iterationsP large, cost noisy
adjoint1 forward + 1 backwardyessimulator onlystatevector sim

Trade-offs. Parameter-shift scales linearly in P, so past a few hundred parameters it dominates wall-clock; SPSA trades exactness for two evaluations per step and is the usual choice for hardware-efficient ansätze with hundreds of parameters, at the cost of a noisy trajectory that needs more iterations. Adjoint differentiation is exact and cheap but only on a statevector simulator: the right choice for developing the ansatz, not for validating on hardware. For the optimizer, COBYLA handles noisy, derivative-free costs and constraints; Adam paired with SPSA is the standard stochastic combination; SLSQP assumes smooth gradients and is fine on a simulator.

Failure modes and detection.

  • Barren plateau: gradient variance decays exponentially in qubit count. Detect by sampling ∇C at random inits; variance below ~1e-6 at 20 qubits means the ansatz is too deep. Mitigate with a shallower ansatz or local cost functions.
  • Premature stop on shot noise: a ±2σ fluctuation looks like convergence. Detect by comparing |ΔC| to the shot-noise SE and requiring ΔC > 3σ before declaring convergence.
  • Dropped or retried jobs: the optimizer consumes a stale or duplicated cost. Detect by logging the job ID and a hash of θ with every cost, and asserting the returned result matches the submitted parameters.
  • Async result mismatch: results return out of order. Detect by tagging each job with its iteration index and matching on return.
  • Mutable objective: the Hamiltonian changes mid-run. Detect by hashing the observable spec and storing it alongside each cost.

Checkpoint. Persist per iteration: θ, cost, gradient, optimizer state (Adam's m and v), RNG seed, shot count, job IDs, and the observable hash. That set is enough to resume deterministically and to reconstruct why the loop stopped.

Python
# Python 3.11, PennyLane 0.36
import pennylane as qml
from pennylane import numpy as np

dev = qml.device("default.qubit", wires=4, shots=4096)

@qml.qnode(dev, diff_method="parameter-shift")
def cost(theta):
    for w in range(4):
        qml.RY(theta[w], wires=w)
    for w in range(3):
        qml.CNOT(wires=[w, w + 1])
    return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1))

opt = qml.AdamOptimizer(stepsize=0.05)
theta = np.array([0.1, 0.2, 0.3, 0.4], requires_grad=True)
for step in range(200):
    theta, prev = opt.step_and_cost(cost, theta)
    if np.linalg.norm(qml.grad(cost)(theta)) < 1e-3:
        break

Note the 1e-3 threshold sits below the 0.011 shot-noise standard error of the gradient at 4096 shots, so on hardware you would raise it to roughly 3σ ≈ 0.03 or increase the shot count: otherwise the loop stops on noise, not on convergence.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Design and validate a variational quantum workflow for parameter-shift.

Answer

I'd design the workflow around the parameter-shift rule. For a Pauli rotation exp(-i θ P/2), the derivative is exactly (f(θ+π/2) - f(θ-π/2))/2. The π/2 shift works because the generator has eigenvalues ±1/2; the parameter-shift rule expresses the derivative as a linear combination of shifted evaluations when the generator has a finite spectrum. For a Pauli rotation, the shift is π/(4r) with r=1/2, so π/2. This gives an exact analytic derivative because the shift cancels the higher-order terms in the exponential expansion. I'd assume the ansatz uses gates that support this rule, like RX, RY, RZ, and CRX. For gates with more than two distinct eigenvalues, I'd use the generalized parameter-shift rule and verify the shifts from the generator's spectrum.

The workflow: define the ansatz with parameterized gates. For each parameter, identify the gate and its generator. Compute the gradient component by running the circuit at θ±π/2. Share measurements where possible: use the same measurement basis for all shifted circuits, and on a simulator use common random numbers to reduce variance. Validate on a simulator: compare the parameter-shift gradient to finite differences (central difference with h=1e-5) or to the exact analytic gradient. On an exact simulator, they should agree to machine precision. On a shot-based simulator with 1000 shots, the parameter-shift gradient has standard error ~0.011 for a probability near 0.5, so finite differences should agree within ~0.03 (3σ).

Shot noise propagates as follows: each evaluation f(θ±π/2) is an estimate with variance f(1-f)/N. The gradient estimate is (f+ - f-)/2, so its variance is (Var(f+) + Var(f-))/4 if the shots are independent. With common random numbers, the covariance reduces the variance. The standard error scales as 1/sqrt(N).

Trade-offs: parameter-shift is exact on hardware but costs 2 evaluations per parameter. Finite differences are simple but have truncation error and are noisier. Backprop is exact and fast on simulator but not available on hardware. Adjoint differentiation is another simulator-only method. I'd use parameter-shift for hardware, and validate with finite differences on simulator.

Failure modes: wrong shift (e.g., using π/4 instead of π/2) gives wrong gradient; detect by comparing to finite differences. Unsupported gate: if the ansatz uses a gate without a known shift rule, the gradient is wrong; detect by checking the framework's supported gates. Shot noise: with finite shots, the gradient is noisy; detect by computing standard error and checking if the sign is significant. Common-randomness covariance ignored: using independent shots increases variance; detect by comparing variance with and without common random numbers. Factor wrong: forgetting the 1/2 factor; detect by comparing to finite differences.

Worked example: single qubit with RX(θ) then measure Z. f(θ) = cos(θ). Gradient = -sin(θ). Parameter-shift: (cos(θ+π/2) - cos(θ-π/2))/2 = (-sin(θ) - sin(θ))/2 = -sin(θ). For θ=0.5, exact gradient = -0.4794. With 1000 shots, standard error ~0.011.

In PennyLane 0.38, validation looks like:

Python
import pennylane as qml
from pennylane import numpy as np

dev = qml.device("default.qubit", wires=1, shots=1000)

@qml.qnode(dev)
def circuit(theta):
    qml.RX(theta, wires=0)
    return qml.expval(qml.PauliZ(0))

theta = 0.5
grad_ps = qml.grad(circuit)(theta)  # uses parameter-shift
h = 1e-5
grad_fd = (circuit(theta + h) - circuit(theta - h)) / (2 * h)
print(grad_ps, grad_fd)

Run this 100 times and compare the mean and standard deviation to the exact gradient.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-12

Design and validate a variational quantum workflow for optimizer choice.

Answer

Core answer (first 90 seconds)

Assume the ansatz and Hamiltonian are fixed and the optimizer is the only variable. The workflow: (1) fix ansatz, objective, shot budget, and one termination rule; (2) pick three or four candidates spanning gradient-based, gradient-free, and stochastic; (3) run each across at least five seeds at an equal circuit-evaluation budget; (4) report median and worst-case final energy, evaluations to reach a target, and wall time; (5) choose on worst case, not best case.

Candidates worth carrying: COBYLA (derivative-free, roughly n evaluations per iteration), SPSA (two evaluations per iteration regardless of parameter count, stochastic gradient), Adam over parameter-shift gradients (two evaluations per parameter per gradient), and L-BFGS-B (needs a smooth, near-deterministic gradient).

Mechanism

Parameter-shift: for a gate generated by a Pauli, the derivative of the objective is [f(θ+π/2) − f(θ−π/2)]/2, exact, at two circuit evaluations per parameter. A full gradient on P parameters therefore costs 2P evaluations: cheap at P=8, ruinous at P=1000. SPSA estimates the gradient from two evaluations no matter how large P is, trading variance for cost.

Shot noise sets the floor. With N shots the objective estimate has standard deviation ≈ σ/√N. If the gradient signal is below that, finite-difference and parameter-shift gradients are mostly noise; SPSA's averaging and COBYLA's trust region degrade more gracefully. Barren plateaus are separate: for a hardware-efficient ansatz initialized near identity, gradient variance decays exponentially in qubit count, so no optimizer recovers a signal that is not there. The fix is the ansatz or the initialization, not the optimizer.

Worked check (hypothetical: 4-qubit VQE, 8 parameters, 10⁴ shots per evaluation, 10⁴ circuit evaluations, 5 seeds, exact energy −1.1373 Ha)

optimizermedian final (Ha)worst seedevals to 1e-3note
COBYLA−1.1368−1.13413200steady, no gradient
SPSA−1.1370−1.13651800cheapest per iteration
Adam + param-shift−1.1372−1.13694200best worst case, most evals
L-BFGS-B−1.1373−1.1200900one seed stalls in line search

Read it as: L-BFGS-B wins on the median and loses on the worst seed, which is exactly why the choice is made on worst case.

When the choice flips

Few parameters (P ≤ ~20), low noise, simulator: parameter-shift plus L-BFGS-B or Adam wins on evaluations. Many parameters (P ≥ 100) or real hardware with shot noise: SPSA or COBYLA. Noisy objective where the gradient signal sits below σ/√N: stochastic methods only; deterministic line search fails. Exponentially small gradient variance: no optimizer helps.

Failure modes and detection

  • Hyperparameters tuned on test: tune on a disjoint seed set and report the tuned-on versus held-out gap.
  • Failures omitted: report every seed including diverged runs; check the table's seed count against the run count.
  • Evaluation count ignored: log circuit evaluations, not iterations; compare evals-to-target across optimizers.
  • Wall time hidden: report wall time separately from evaluations. Simulator and hardware differ by orders of magnitude.
  • Different initial points: fix the seed-to-initialization map and re-run with the same init to confirm reproducibility.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Design and validate a variational quantum workflow for stopping rules.

Answer

Assume a VQE with a hardware-efficient ansatz, SPSA optimizer, and finite shots. The stopping rule decides when to halt the classical optimization loop. A strong candidate would design a composite rule: stop when the estimated energy change over a window of iterations falls below a threshold derived from the standard error of the estimator, AND the gradient norm is below a threshold, AND a patience counter is exceeded. Then validate with a separate set of shots.

Shot noise causes energy estimates to fluctuate. If the tolerance is smaller than the noise, you either never stop or stop randomly. So set tolerance ε = k · SE, where SE = σ/√N, σ is the standard deviation of the energy estimator, and N is shots per evaluation. For a typical 4-qubit VQE, σ ≈ 0.1 Hartree, N = 1024, so SE ≈ 0.003 Hartree. Set ε = 2·SE ≈ 0.006 Hartree. Patience: require 3 consecutive iterations with |ΔE| < ε. Also monitor parameter change: if ||Δθ|| < 1e-3. Budget: max 200 iterations, max 1e6 shots.

Validation: after stopping, run 10 independent evaluations with 4096 shots each. Compute the mean and 95% CI. If the CI overlaps with the training estimate and the energy is not improving with more shots, accept. If the CI is significantly lower, the stopping rule was premature.

Alternatives: fixed iteration count (simple, but can stop too early or waste shots); gradient norm threshold (good for smooth landscapes, but noisy gradients can mislead); energy difference (common, but needs a noise-aware threshold); parameter change (cheap, but can plateau); shot budget (hard stop, but may not converge); optimizer's success flag (e.g., COBYLA's status, but not reliable alone). Deciding criteria: if noise is high, use energy difference with an SE-based threshold; if gradient is cheap, use gradient norm; if budget is tight, use budget with early stopping.

Failure modes: false convergence (noise makes energy look flat; detect by re-evaluating with more shots); endless oscillation (tolerance too tight; detect by monitoring variance); metric switched (optimizing energy but validating on fidelity; detect by logging the metric); budget exceeded silently (optimizer runs out of shots but doesn't stop; detect by a hard cap); best noise fluctuation (picking the lowest noisy sample; detect by moving average); validation reused for training (overfitting; detect by keeping validation shots separate); optimizer success flag trusted (COBYLA says success but energy not converged; detect by independent validation).

Worked example: H2 at 0.735 Å, 2-qubit ansatz, SPSA, 1024 shots. Iterations: E1 = -1.100 ± 0.005, E2 = -1.105 ± 0.005, E3 = -1.106 ± 0.005, E4 = -1.106 ± 0.005, E5 = -1.106 ± 0.005. ΔE between 3 and 4 = 0.000, but SE = 0.005. Tolerance ε = 0.01. Patience 3: after 3 iterations with |ΔE| < 0.01, stop. Validation: 10 evaluations with 4096 shots: mean = -1.106, 95% CI = [-1.109, -1.103]. Training estimate -1.106 falls within CI. Accept.

CriterionWhen to useFailure modeDetection
Energy differenceNoisy, derivative-freeFalse convergenceRe-evaluate with more shots
Gradient normSmooth, gradient availableNoisy gradientIncrease shots or use SPSA
Parameter changeCheap, plateauSlow progressMonitor energy
Shot budgetHard limitPremature stopCheck validation
Optimizer flagConvenienceFalse successIndependent validation
Python
def should_stop(history, tol, patience, max_iter):
    if len(history) < patience + 1:
        return False
    recent = history[-(patience+1):]
    deltas = [abs(recent[i+1] - recent[i]) for i in range(patience)]
    if all(d < tol for d in deltas):
        return True
    if len(history) >= max_iter:
        return True
    return False

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Design and validate a variational quantum workflow for multi-start evaluation.

Answer

Assumptions first. VQE-style workflow: a fixed ansatz U(θ) with n_params, a Hamiltonian H as a weighted Pauli sum, energy estimated from finite shots, and a classical optimizer (COBYLA, SPSA, or Adam) minimizing ⟨H⟩. "Multi-start" means K independent runs from different initial θ, then selecting the lowest energy. Selection and validation measure the same observable, on a noisy device.

Design. Predeclare, before any run: K, the init distribution, the optimizer and its iteration cap, the shot budget per energy evaluation, and the seed pools. Then draw K initial points θ₀⁽ᵏ⁾ from a fixed distribution: uniform on [0, 2π)^n_params is the honest default; warm-starting from a classical mean-field or Hartree–Fock solution is a variant, not the default. Run each restart to convergence under the same budget. Record every final energy, not just the best: report min, median, IQR, and the full K-vector.

Why the selection is optimistic. Each run's final energy is a noisy estimate: shot noise gives standard error σ_H/√N, and the optimizer stops at a slightly different point each time. Taking the minimum over K such estimates is an order statistic. For roughly Gaussian errors, E[min of K] ≈ −σ√(2 ln K). With K = 50 and per-run σ = 0.01 Ha, that is 0.01 × 2.80 ≈ 0.028 Ha of optimism: 28 mHa, against a 1.6 mHa chemical-accuracy target. The reported best is not the true best; it is the luckiest draw.

Validation. Re-evaluate the selected θ* on an independent budget: disjoint seed pool, 10× shots, ideally a different backend or optimizer. Report the validation energy, not the selection energy. At 10× shots, σ drops to 0.01/√10 ≈ 0.0032 Ha, so the validation number is trustworthy to ~3 mHa.

Sketch (Python 3.11, numpy 1.26):

Python
import numpy as np

K              = 50          # predeclared restarts
SHOTS_SELECT   = 10_000      # per energy evaluation, selection phase
SHOTS_VALIDATE = 100_000     # 10x, validation phase
rng_select   = np.random.default_rng(20240501)
rng_validate = np.random.default_rng(20240917)   # disjoint pool

def energy(theta, shots, rng):
    """Return (mean, stderr) of <H> from `shots` measurements."""
    ...

results = []
for _ in range(K):
    theta0 = rng_select.uniform(0.0, 2*np.pi, size=n_params)
    theta_star, e_sel = optimize(energy, theta0,
                                 shots=SHOTS_SELECT, rng=rng_select)
    results.append((theta_star, e_sel))

energies   = np.array([e for _, e in results])
theta_best = results[int(np.argmin(energies))][0]

e_val, se_val = energy(theta_best, SHOTS_VALIDATE, rng_validate)
print(f"selection min {energies.min():.4f} Ha")
print(f"validation    {e_val:.4f} +/- {se_val:.4f} Ha")
print(f"median {np.median(energies):.4f}  "
      f"IQR {np.percentile(energies,75)-np.percentile(energies,25):.4f}")

Trade-offs. Fixed K is what makes the order-statistics correction valid; adaptive stopping, halt when a run looks good, breaks it and inflates bias, because the stopping rule correlates with the noise. Warm-starting cuts K but biases the sample toward one basin. Multi-start costs linearly in K: 50 restarts × 200 iterations × 10⁴ shots = 10⁸ shots, roughly 3 hours at 10⁴ shots/s. It is the wrong tool when the landscape is near-convex, or when the optimizer is deterministic and gradient-based from a good init.

Failure modes and detection.

failuredetection
only best trace reportedrequire the full K-vector in the artifact; recompute min from it
adaptive restart budgetlog the stopping rule and actual restart count; flag if it varies with observed energies
seed leakageselection and validation seeds from disjoint, pre-registered pools; assert disjointness
dropped failurescount attempted vs completed runs; treat diverged/NaN runs as +inf, never drop
classical baseline given fewer restartsmatch K and total iterations across quantum and classical; report both distributions

Predeclare, run fixed K, report the distribution, and validate the selected point on a budget that never saw the selection.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Design and validate a variational quantum workflow for barren plateaus.

Answer

What I'd say first. I'd design the workflow around one measurable quantity, the variance of the cost gradient across random initializations, and validate it by fitting that variance against qubit count. Pick a hardware-efficient ansatz: L layers of RY rotations plus a CNOT ring on n qubits. Choose the cost function deliberately, local or global. Then for n ∈ {4, 6, 8, 10, 12} and at least 20 seeds, sample parameters and compute the full gradient vector with the parameter-shift rule. Fit log Var[∂C/∂θ] against n. A slope near −ln 2 puts you in the barren-plateau regime; a shallow slope does not. Then check the shot budget needed to resolve that gradient.

Why the variance collapses. McClean et al. (2018) showed that when a circuit forms an approximate 2-design, random enough that its output distribution matches Haar measure to low moments, the gradient of a global cost has Var[∂C/∂θ] = O(2^−n). A global cost sums over all qubits, so its gradient depends on the whole register; as n grows the circuit scrambles the input into a region where the landscape is exponentially flat. Depth matters because you need depth O(n) to reach the 2-design regime. Cerezo et al. (2021) showed the cost function is decisive: a local cost measuring O(1) qubits keeps Var ~ poly^−1(n) at depth O(log n), while a global cost plateaus even at that depth.

Trade-offs and when to pick each.

design choicegradient variancepick it when
global cost, depth O(n)Var ~ 2^−nthe problem energy is genuinely global and n is small
local cost, depth O(log n)Var ~ poly^−1(n)the observable is a sum of few-qubit terms
layer-wise trainingavoids the deep 2-designyou can afford more optimization steps
identity / correlated initbreaks the 2-design at initlosing some expressibility is acceptable

Local costs are the cheapest fix, but they change what you optimize: for VQE the energy is a sum over all qubits, so a local proxy can train a circuit that does not minimize the true energy. Layer-wise training and identity initialization keep the global cost but trade optimization steps and expressibility for gradient signal.

Worked check (PennyLane 0.38):

Python
import pennylane as qml
import numpy as np

n, L = 8, 4
dev = qml.device("default.qubit", wires=n)

@qml.qnode(dev)
def cost_global(params):
    qml.StronglyEntanglingLayers(params, wires=range(n))
    return qml.expval(qml.sum(*(qml.PauliZ(i) @ qml.PauliZ(j)
                                for i in range(n) for j in range(i + 1, n))))

shape = qml.StronglyEntanglingLayers.shape(n_layers=L, n_wires=n)
rng = np.random.default_rng(0)
grads = [np.abs(qml.grad(cost_global)(rng.normal(0, 0.1, shape))).mean()
         for _ in range(20)]
print(np.var(grads))

shape is (4, 8, 3). Each seed draws a (4, 8, 3) array, qml.grad returns the same shape, .mean() collapses it to one scalar, and 20 scalars give the variance. Repeat per n and fit log variance against n.

Shot budget. Parameter-shift needs two circuit evaluations per parameter. Each Pauli expectation with S shots has std ≤ 1/√S, so the gradient estimate has std ≈ 1/√(2S). To resolve a true gradient g you need S ≫ 1/(2g²). With Var ~ 2^−n, g ~ 2^−n/2: n=12 gives g ≈ 0.016 and S ≫ 2×10³; n=20 gives g ≈ 10⁻³ and S ≫ 5×10⁵; n=30 gives g ≈ 3×10⁻⁵ and S ≫ 5×10⁸. That is the exponential wall, and it is why validation has to be a fit, not a single run.

Failure modes and how to detect them. Blaming the optimizer: a vanishing gradient looks like a stuck optimizer, so log the gradient norm separately from the loss. Extrapolating from a small instance: n=4 can look healthy while n=12 is flat. Always sweep n. An arbitrary absolute threshold: "gradient < 10⁻³" means nothing without the cost scale, so compare against the variance fit. Noise-induced flattening: on hardware, variance flattens even for local costs, so run the same sweep through a noise model and compare. Success-only seeds: report the full distribution over seeds, not the best one.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Design and validate a variational quantum workflow for plateau mitigations.

Answer

Barren plateaus are not one failure. At least four distinct causes produce the same symptom, a cost landscape whose gradient vanishes exponentially, and each has a different fix. So the workflow is diagnose → mitigate → re-diagnose, not "apply trick X."

Assumptions: a fixed n-qubit device, a parameterized circuit U(θ), cost C(θ) = ⟨ψ(θ)|H|ψ(θ)⟩ estimated from shots, and a classical optimizer.

Diagnose. Sample K random parameter vectors, compute ∂C/∂θ_k for each, and estimate Var[∂C/∂θ_k] at n = 4, 6, 8, 10, 12 with depth held fixed. Fit log Var against n. A slope near −ln 2 means the variance halves per added qubit: the exponential signature McClean et al. (2018) derived for circuits that approach a unitary 2-design. A slope near −c ln n means polynomial decay, which is trainable. Vary one factor at a time to attribute the cause: hold the ansatz fixed and swap a global cost for a local one; hold the cost fixed and swap a hardware-efficient ansatz for a problem-informed one.

Mitigate. Match the fix to the diagnosis:

CauseMitigationMechanismWhen not to use
Expressibility (ansatz approaches a 2-design)Problem-informed shallow ansatz, e.g. Hamiltonian variational ansatzKeeps the dynamical Lie algebra small so the circuit never reaches 2-designYou do not know the problem structure
Global cost functionLocal cost: sum of few-qubit observablesGradient variance decays as O(1/poly(n)) instead of O(2⁻ⁿ) (Cerezo et al. 2021)The local surrogate's optimum is not the global one
Large gradients only near identityIdentity-block / Gaussian initialization (Grant et al. 2019)Starts in the low-depth regime where gradients are largeBenefit decays as training moves away from init
Depth needed for accuracyLayerwise growth (Skolik et al. 2021)Train few layers, freeze, add: effective depth stays low per phaseMore optimization rounds; can still plateau at the end

Validate. Re-run the gradient-variance probe. Then convert variance to a shot budget: to resolve a gradient component g at 1σ you need S ≈ 1/g² shots. If g ~ 2^(−n/2), then S ~ 2ⁿ: at n = 20 that is roughly 10⁶ shots per component per optimization step, which is the arithmetic that makes the plateau fatal. Finally, run the optimizer from M random seeds and report the fraction that reach the target cost within a fixed step budget. A mitigation that fixes the variance but not the end-to-end success rate has not fixed the workflow.

Failure modes.

  • Noise-induced plateau (Wang et al. 2021): with a noise model, gradient variance decays exponentially in depth even for local costs. Detect by comparing noisy against noiseless variance at fixed n; if the noisy curve decays with depth while the noiseless one is flat, no ansatz change fixes it: reduce depth or add error mitigation.
  • Warm-start leakage: initializing from a classical solution can land in a small-gradient region or bias the ansatz. Detect by comparing the gradient norm at the warm start against the random-init median; if it is below, the warm start is hurting.
  • Expressibility plateau: detect via the dynamical Lie algebra dimension (Larocca et al. 2023); if it grows exponentially with n, expect a plateau.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Design and validate a variational quantum workflow for noise-induced trainability.

Answer

Assumptions I'd state first. Hardware-efficient ansatz of depth L built from native two-qubit gates, a fixed Hamiltonian H, per-layer two-qubit gate error p, and N shots per circuit evaluation. The question is whether the optimizer can find a descent direction at all, not whether the final energy is good.

Core answer. Design the workflow so trainability is measured, not assumed. Three stages: fit a noise model that reproduces the device's gradient statistics; measure the gradient signal-to-noise ratio as a function of depth and shots; set L and the cost function from where that SNR crosses 1. Validate by replaying the same parameter points across calibration windows and comparing ideal, modeled, and hardware landscapes.

Why noise kills trainability. With local depolarizing noise at rate p per layer, the cost's dependence on the parameters decays as the state decoheres. The gradient magnitude falls off roughly exponentially in depth L, while the shot-noise standard deviation of the gradient estimator falls only as 1/√N. There is a depth L* where the true gradient drops below the estimator noise; past it the optimizer follows noise. This is the noise-induced barren plateau. It differs from the expressivity-driven plateau: it scales with depth, not qubit count, and better initialization does not remove it.

Parameter-shift gives ∂C/∂θ_k = [C(θ + (π/2)e_k) − C(θ − (π/2)e_k)]/2, so each gradient component costs two circuit evaluations.

Worked arithmetic (hypothetical). Take per-evaluation shot noise σ_C = 0.01 at N = 10^4. The parameter-shift estimator has σ_g = √2·σ_C/2 ≈ 0.0071. At depth 4 the noisy gradient magnitude is 0.02, so SNR ≈ 2.8: trainable. At depth 8 it decays to 0.002, SNR ≈ 0.28, not trainable. Recovering SNR = 1 there needs σ_g = 0.002, i.e. σ_C down by 3.5×, i.e. about 13× more shots.

Table (hypothetical, p = 0.1% per two-qubit layer, N = 10^4):

depth Lideal gradmodeled gradhardware gradSNR
20.080.060.0557.7
40.050.020.0182.5
80.030.0020.00150.2

Validation. Replay fixed parameter points before and after a recalibration. If hardware drifts more than the modeled curve predicts, the noise model is stale: refit it. If modeled tracks hardware but both diverge from ideal, the gap is real noise-induced trainability loss, not model error. Hold out one calibration window from the fit; the model is predictive only if it matches hardware on that window.

Trade-offs. Global cost functions (sums over all qubits) have gradient variance decaying exponentially in qubit count even without noise; local costs (sums of single-qubit terms) avoid that: prefer local. A shallow ansatz with many restarts beats deep with one run when L* is small, at the cost of expressivity. Zero-noise extrapolation recovers the ideal cost but multiplies estimator variance by the extrapolation factor squared, and it changes the objective: gradients on mitigated costs are gradients of a different function.

Failure modes. (1) Noise model fit on the same data used to validate it: detect with a held-out calibration window. (2) Device drift read as optimizer randomness: detect by interleaving a fixed reference circuit; if its cost drifts, it's the device. (3) Mitigation shifting the optimum: detect by comparing the mitigated landscape's minimum to the ideal simulator's; a gap larger than the mitigation's stated bias means the landscape is distorted.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Design and validate a variational quantum workflow for transpilation.

Answer

Assumptions. A variational loop (VQE, QAOA, a variational classifier) with a fixed ansatz structure and a classical optimizer that only moves gate angles. Target is a BackendV2 with a Target (Qiskit 1.x). The loop runs hundreds to thousands of circuit evaluations, so anything you do per iteration is multiplied by that count.

Core answer. Transpile the unbound parameterized circuit once, freeze the layout and routing, and bind angles inside the loop. Layout and routing are functions of the ansatz's two-qubit gate structure and the target's topology and basis, not of the angles. Re-transpiling each iteration buys nothing and risks the layout drifting, which invalidates any per-qubit calibration you cached.

Python
import numpy as np
from qiskit.circuit import QuantumCircuit, ParameterVector
from qiskit.quantum_info import Operator
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager

theta = ParameterVector("θ", 4)
ansatz = QuantumCircuit(3)
ansatz.ry(theta[0], 0); ansatz.ry(theta[1], 1); ansatz.ry(theta[2], 2)
ansatz.cx(0, 1); ansatz.cx(1, 2); ansatz.ry(theta[3], 0)

pm = generate_preset_pass_manager(optimization_level=2, backend=backend,
                                  seed_transpiler=7)
isa = pm.run(ansatz)                       # transpiled ONCE, still parameterized

assert set(isa.parameters) == set(ansatz.parameters)                # names survive
assert set(isa.count_ops()) <= set(backend.target.operation_names)  # basis-compliant
layout0 = isa.layout.initial_layout                                 # frozen contract

for _ in range(200):
    x = np.random.uniform(-np.pi, np.pi, 4)
    bound = isa.assign_parameters(x)       # no re-transpilation
    # execute(bound)

Transpilation preserves the Parameter objects, so assign_parameters on the transpiled circuit is the same operation as on the source. The output keeps the source's qubit ordering; the physical mapping lives in isa.layout.

Validation harness. Run once per (ansatz, target) pair, not per iteration.

CheckHowFail signal
Parameter preservationset(isa.parameters) == set(ansatz.parameters)names rewritten by a QASM round-trip or a custom pass
Basis complianceset(isa.count_ops()) <= set(target.operation_names)a gate the device cannot execute
Connectivityevery 2q gate on an edge of target.build_coupling_map()routing pass skipped or misconfigured
SemanticsOperator(ansatz.assign_parameters(x)).equiv(Operator(isa.assign_parameters(x))) over ~8 random xa pass changed the unitary
Layout stabilityisa.layout.initial_layout equal across re-transpilationscached calibration applied to the wrong qubits
Costisa.count_ops().get("cx", 0) vs the pre-routing countansatz is a poor fit for the topology

The semantics check is the one that matters: Operator.equiv compares up to global phase, which is exactly the freedom transpilation is allowed to use.

Trade-offs. optimization_level 0–3: level 3 runs more resynthesis and is the slowest, but you pay it once per ansatz, so it is usually worth it for a long optimization loop. layout_method in Qiskit 1.x is one of 'trivial' (no layout optimization), 'dense' (pack onto a dense qubit subset), or 'sabre' (the default, SABRE-based). Error-aware placement is not a layout method in 1.x: NoiseAdaptiveLayout was removed. It comes from VF2PostLayout, which runs at optimization_level >= 2 and swaps the chosen layout for a better-scoring isomorphic subgraph using the error rates in backend.target. routing_method: 'sabre' is the general choice; 'lookahead' can beat it on small circuits. Fix seed_transpiler so a re-run reproduces the same layout.

Failure modes.

  • Layout drift. If the ansatz grows (adaptive VQE) or the seed changes, initial_layout changes and any readout-mitigation matrix or per-qubit calibration keyed to physical qubits is now wrong. Detect by asserting isa.layout.initial_layout == layout0 before each execution batch; re-transpile and rebuild the calibration when it fails.
  • Stale target. Error rates drift between calibration cycles, so a layout that VF2PostLayout scored well last week may no longer be the best isomorphic subgraph. Re-fetch backend.target, diff InstructionProperties.error, and re-transpile when the max relative change crosses your threshold.
  • Silent semantic change. A custom pass or an approximate synthesis changes the unitary. The Operator.equiv check catches it; run it on every pass-manager change, not just the first.
  • Depth blowup. Routing on a sparse coupling map inserts SWAPs. Worked example: a 3-qubit ansatz with two CX gates on adjacent physical qubits costs 2 CX. If the layout puts the third logical qubit two hops away, SABRE inserts one SWAP per crossing and each SWAP is 3 CX, so the same ansatz costs 5 CX: 2.5× the dominant error source. At that ratio, change the ansatz's entangling pattern rather than the transpiler settings.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Design and validate a variational quantum workflow for runtime latency.

Answer

The 90-second version. "Runtime latency" for a variational workflow is wall-clock time per optimizer iteration and to convergence, not QPU execution time. On superconducting hardware those differ by one to two orders of magnitude, and the gap is where every design decision lives. I'd state my assumptions up front: transmon device, hardware-efficient ansatz of ~20 qubits and ~40 two-qubit gates, parameter-shift gradients, target expectation-value precision ±0.01. Move any of those and the numbers move.

Design. Two quantities set the QPU-side cost, and both are fixed by the precision target rather than by the hardware.

Shot budget. The standard error of a Pauli expectation value falls as 1/√N, so ±0.01 needs ~10⁴ shots per evaluation. You cannot buy that down without loosening the target.

Gradient cost. Parameter-shift needs two circuit evaluations per parameter, so a 20-parameter ansatz costs 40 evaluations per iteration: ~4×10⁵ shots.

Illustrative arithmetic (20 qubits, 40 two-qubit gates at ~500 ns, ~1 µs readout per qubit):

quantityvalue
QPU time per shot~40 µs
shots per evaluation10⁴
evaluations per iteration40
QPU time per iteration~16 s
iterations to converge (COBYLA-scale)~100
total QPU time~27 min

Now add the classical side. If each iteration is submitted as its own job, queue wait and submission overhead land on top. On a busy device that is minutes per job, so 100 iterations × (16 s + 60 s queue) ≈ 2.1 hours wall clock, of which the QPU is ~13%. That ratio is the whole problem: you are optimising a noise-sensitive cost function over a window long enough for the device to change underneath you. Superconducting devices are recalibrated on a schedule of hours to a day, and the calibration snapshot you transpiled against is hours stale by the time the run finishes. The optimizer converges to parameters that were optimal for a noise model that no longer exists.

Sessions and batching. A session-style reservation (Qiskit Runtime calls this a session; check the current runtime docs for the current name) holds the device for the run and collapses per-iteration queue time to near zero. The trade-off is that you rent the QPU exclusively, so the classical optimizer's think time is billed as idle reservation and other users are blocked. It is the right call when the classical step is fast relative to queue time (SPSA, small ansatz) and the wrong call when the optimizer is slow or the ansatz large, because then you are paying device rates to run Python. Sessions also carry a TTL; exceed it and jobs silently fall back to the public queue, which is exactly the failure the reservation was meant to prevent.

Validation. Instrument every iteration with submission timestamp, execution start and end, shot count, and the parameter vector. Then check:

failuredetection
queue time excluded from the metriccompare submit vs. execution-start timestamps from job metadata
retries hiddencount job IDs per iteration; a silent resubmit doubles latency
session TTL exceededsession status flips to closed mid-run and jobs re-queue
stale noise modelcompare calibration snapshot timestamp against execution time
async results reorderedtag each result with its parameter vector; assert iteration index is monotonic

The last one is the subtle one. If you submit iterations asynchronously and collect out of order, the optimizer applies a gradient computed at stale parameters and converges to the wrong point with no error raised anywhere.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Design and validate a variational quantum workflow for mitigation tradeoff.

Answer

Assumptions first. I'll take this as VQE on a system small enough to diagonalize exactly, so bias is measurable rather than argued about. Concretely: H₂ in STO-3G at r = 0.735 Å, reduced to 2 qubits by parity and Z₂ symmetry, exact ground state −1.1372 Ha. Chemical accuracy is 1.6 mHa, so that's the bar the workflow has to clear.

Core answer. Build the loop so mitigation is a switch you can flip, then validate by comparing the mitigated and unmitigated optima against exact diagonalization, not against a literature number. The tradeoff is bias against variance, and the only way to price it is to measure both arms on the same seeds.

Design.

  • Ansatz: 2-qubit hardware-efficient, 2 parameters, depth ~4. Keep it shallow: ZNE assumes noise grows linearly with the fold factor, and that assumption dies as depth grows.
  • Optimizer: SPSA. Two energy evaluations per iteration regardless of parameter count, and its stochastic gradient averages shot noise instead of chasing it.
  • Mitigation: ZNE with gate folding at λ ∈ {1, 3, 5}, linear extrapolation. Run it two ways: inside the optimization loop, and post-hoc on the final θ* from the unmitigated run.

Mechanism, with the arithmetic. Gate folding replaces each two-qubit gate G with G G† G, so λ = 3 triples the two-qubit count. Linear extrapolation to λ = 0 uses coefficients c(1) = 15/8, c(3) = −5/4, c(5) = 3/8. Suppose the noise adds a linear bias of 0.012 Ha per unit λ. The three measurements are −1.1252, −1.1012, −1.0772 Ha, and

15/8·(−1.1252) − 5/4·(−1.1012) + 3/8·(−1.0772) = −1.1372 Ha

the bias cancels exactly. That is the whole trick: you are fitting the noise, not the physics.

The cost is variance. Sample overhead is (Σ|cᵢ|)² = 3.5² = 12.25× to hold the same statistical precision. At 10⁴ shots per λ, σ_mit = √(Σcᵢ²)·σ = 2.28 × 0.004 = 0.009 Ha. You trade a 12 mHa bias for a 9 mHa error bar: worth it only because 12 mHa is 7.5× chemical accuracy.

Validation (hypothetical figures, 20 seeds, 10⁴ shots per energy evaluation):

armshots/evalbias vs E_exactσ
unmitigated10⁴+12.0 mHa4 mHa
ZNE inside loop3×10⁴+0.4 mHa9 mHa
ZNE post-hoc on θ*_raw3×10⁴+0.4 mHa9 mHa

If the last two rows agree within σ, the optimizer was not fitting the mitigation. If they diverge, it was, and that is the failure the in-loop arm exists to catch.

When not to use each. ZNE is cheap and model-light but assumes noise linear in λ; skip it on deep circuits or when T1/T2 decoherence dominates, because folding adds real decoherence that does not extrapolate. PEC is unbiased but its overhead γ² grows exponentially with gate count: γ = 3 already costs 9× samples, so skip it when γ² exceeds the shot budget. Tensored readout mitigation fixes measurement bias only, and its inverse amplifies variance when the calibration matrix is ill-conditioned.

Failure modes and how to detect them.

  1. Optimizer absorbs mitigation bias: θ* moves when you toggle mitigation. Detect by comparing θ_raw and θ_mit against the bootstrap parameter uncertainty.
  2. Stale noise model: the linearity fit or learned channel is calibrated hours before the run. Detect by re-learning mid-run and comparing inferred error rates; T1/T2 drift on real hardware.
  3. Nonphysical estimate: E_mit below E_exact. Detect by flagging E_mit < E_exact − 3σ_mit; the variational bound is violated, so the extrapolation overcorrected.
  4. Overhead omitted: mitigated energy reported without the shot multiplier. Detect by reporting shots per energy evaluation for every arm.
  5. Corrected point only: one mitigated number, no raw comparison. Detect by reporting both, with error bars, always.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Design and validate a variational quantum workflow for QAOA layers.

Answer

Core answer

QAOA is a fixed-depth variational ansatz: p layers of a cost unitary e^{-iγ_k C} and a mixer e^{-iβ_k B} applied to a product state. The workflow is encode → pick mixer → initialize → optimize → validate. Two decisions decide whether it works: the mixer's ground state must be the state you start from, and the mixer must preserve the feasible subspace or you pay for constraints in the cost instead.

Encode. Write the problem as a diagonal cost Hamiltonian C = Σ_{(i,j)∈E} c_ij Z_iZ_j + Σ_i h_i Z_i. For MaxCut on a graph with m edges, C = Σ_{(i,j)∈E} Z_iZ_j/2; the constant m/2 is dropped because it doesn't move the argmin. Mixer B = Σ_i X_i, initial state |+⟩^n: the +1 eigenstate of every X_i, i.e. the ground state of −B. The ansatz is |ψ(γ,β)⟩ = Π_{k=1}^{p} e^{-iβ_k B} e^{-iγ_k C} |+⟩^n.

Circuit, checked against exact statevector (Qiskit 1.3)

Python
import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit import ParameterVector
from qiskit.quantum_info import SparsePauliOp, Statevector

n, p = 4, 2
edges = [(0,1),(1,2),(2,3),(3,0)]          # 4-cycle
C = SparsePauliOp.from_sparse_list(
        [("ZZ", [i,j], 0.5) for i,j in edges], num_qubits=n)

g, b = ParameterVector("g", p), ParameterVector("b", p)
qc = QuantumCircuit(n)
qc.h(range(n))                              # |+>^n
for k in range(p):
    for i, j in edges:
        qc.rzz(g[k], i, j)                  # rzz(t) = exp(-i t ZZ/2)
    qc.rx(2*b[k], range(n))                 # rx(2t) = exp(-i t X)

def energy(gv, bv):
    bound = qc.assign_parameters({**dict(zip(g, gv)), **dict(zip(b, bv))})
    return Statevector(bound).expectation_value(C).real

rzz(t) = exp(−i t Z_iZ_j/2) and rx(2t) = exp(−i t X_i), so the gate arguments are exactly the γ_k and β_k in the ansatz. Two exact invariants worth a unit test: energy(0, b) == 0 for any b (γ=0 leaves |+⟩, and ⟨+|Z_iZ_j|+⟩ = 0), and energy(g, 0) == 0 for any g (the cost layer is diagonal, so it cannot change a diagonal expectation).

Optimize. COBYLA or SPSA for shot-limited hardware runs; SPSA costs two circuit evaluations per iteration regardless of the 2p parameters, which matters when each evaluation is 10^4 shots. Gradients are exact here: every generator (Z_iZ_j/2, X_i) has eigenvalues ±1, so ∂⟨C⟩/∂θ = (⟨C⟩{θ+π/2} − ⟨C⟩{θ−π/2})/2. Initialize with the linear ramp of Zhou et al., Phys. Rev. X 10, 021067 (2020): γ_k ∝ k/p, β_k ∝ (1 − k/p). Run 10–20 restarts; if the spread of final energies exceeds the shot-noise floor, you are in a local minimum, not converged.

Shot budget. With per-shot cost variance σ², the standard error on ⟨C⟩ is σ/√S. For the 4-cycle above, C ∈ {−2,−1,0,1,2}, so σ ≈ 1; resolving a 0.01 energy difference needs S ≈ (1/0.01)² = 10^4 shots per evaluation. That number, not the optimizer, sets the wall clock.

Constraints: pick one, and optimize the same objective you report.

approachmechanismwhen it's wrong
penalty λ·(violation)² added to Ckeeps the X-mixer; feasible states are the low-energy onesλ too small → infeasible states win; λ too large → landscape flattens and COBYLA stalls. For unit-weight MaxCut, λ > m is sufficient.
XY / ring mixer, H_M = Σ_{(i,j)∈E}(X_iX_j + Y_iY_j)/2commutes with Hamming weight, so one-hot constraints hold exactlyneeds a feasible initial state (a Dicke state or a weight-k basis state), not
post-select on feasible bitstringsno circuit changethe feasible fraction decays: for one-hot on n=10 only 10/1024 ≈ 1% of shots survive, so 10^4 shots give ~100 usable samples and the error bar is 10× worse than the shot count suggests. And if you optimize ⟨C⟩ over all shots but report the post-selected mean, you tuned the wrong objective.

Failure modes.

  • Cost sign flipped: the optimizer drives to the maximum of C. On MaxCut the sampler concentrates on |00…0⟩ and |11…1⟩ (cut = 0). Catch it from the top bitstrings, not the energy.
  • γ↔β swap: subtler than it looks. Exchanging the two angles is a relabeling of the same variational family, Π e^{−iγ_k B} e^{−iβ_k C} is the original with γ and β renamed, so the reachable states and the best achievable energy are unchanged. It will not show up as a worse energy. It shows up as a wrong argmin, a wrong linear-ramp initialization, and wrong per-parameter bounds. Catch it by brute-forcing the p=1 landscape on a 4-node instance over a grid and comparing the optimizer's argmin to the grid's; the two landscapes are transposes of each other.
  • Comparing p at unequal resources: p=5 with 200 shots is not comparable to p=1 with 10^4. Fix the total shot budget and the total two-qubit-gate count (p layers cost p·m rzz gates), or compare at equal wall clock. On hardware, larger p also means more depth inside the coherence window, so the simulator's best p is often not the hardware's.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Design and validate a variational quantum workflow for classical baseline.

Answer

Assumption. The stem is terse, so I'll fix the scenario: the task is MaxCut on sparse graphs, and "validate" means producing a defensible claim that a variational quantum workflow beats a tuned classical baseline at matched resources. If your problem is chemistry (VQE for ground states), the same protocol applies with FCI or CCSD(T) as the baseline and 1 kcal/mol (1.6 mHa) as the accuracy bar.

Core answer (first 90 seconds). Use QAOA at depth p, fix the classical baseline to Goemans–Williamson SDP plus local search, and validate on a pre-registered instance set with identical wall-clock budgets and identical post-processing. Report mean and worst-case approximation ratio on held-out instances. If you can't beat GW's 0.878 ratio at equal time, the workflow isn't ready: say so.

Mechanism. QAOA prepares |ψ(γ,β)⟩ = ∏{k=1}^{p} e^{-iβ_k H_B} e^{-iγ_k H_C} |+⟩^n, with H_C = Σ{(i,j)∈E} (1 − Z_i Z_j)/2 and H_B = Σ_i X_i. That's 2p parameters. A classical optimizer (COBYLA, SPSA, or Adam) minimizes ⟨H_C⟩ estimated from shots. Two structural limits dominate:

  • Shot noise. Estimating ⟨H_C⟩ to ε needs O(Var/ε²) shots. With per-term variance ~1 and ε = 10⁻³, that's ~10⁶ shots per energy evaluation. Parameter-shift gradients need 2p evaluations per step, so p = 5 → ~10⁷ shots per gradient step. At a few thousand shots/second that's hours per step.
  • Barren plateaus. For random circuits, gradient variance decays as 2⁻ⁿ (McClean et al. 2018), so at n = 50 random initialization gives vanishing gradients. Warm-starting from the GW solution (Egger et al. 2021) mitigates this.

Design.

  1. Encode MaxCut as H_C above.
  2. Ansatz: QAOA, depth p chosen so 2p layers × ~2 two-qubit gates fit within coherence (~100–300 µs on superconducting hardware, two-qubit error ~10⁻³).
  3. Optimizer: SPSA for shot-noise robustness; COBYLA for noiseless simulation.
  4. Warm start from the GW relaxation.
  5. Post-process: sample bitstrings, apply greedy local search.

Validation protocol.

  • Pre-register the instance distribution (e.g., random 3-regular graphs, n = 20–100) and hold out a test set.
  • Baseline: GW SDP (Mosek or SCS) + GW rounding + local search, tuned with a budget equal to the quantum optimizer's.
  • Matched resources: same wall-clock including transpilation, queue, shots, and classical post-processing.
  • Blind: report mean and worst-case approximation ratio on held-out instances, not best-case.

Trade-offs. QAOA converges to the optimum as p → ∞, but noise and barren plateaus dominate before that. For n ≤ 30, statevector simulation of the classical baseline is cheap (2³⁰ complex128 amplitudes = 16 GiB) and QAOA has no advantage. For structured graphs (planar, bipartite), exact classical solvers win outright. Don't use QAOA when the classical baseline already hits the optimum.

Failure modes and detection.

failurehow it shows updetection
straw baselinebaseline is brute force or a default-parameter heuristictune baseline with equal budget; if it improves >5%, the comparison was straw
small easy subsetonly instances where QAOA wins are reportedreport full distribution and worst-case ratio
subsidized hardwareQPU time excludes queue and calibrationcharge both the same wall-clock
asymmetric preprocessinggraph reduction applied only to the quantum siderun both through an identical pipeline
asymmetric post-processinglocal search applied only to quantum samplesablate post-processing on both sides

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Design and validate a variational quantum workflow for solution verification.

Answer

Clarify first. In a variational workflow, "solution verification" means the circuit proposes candidate bitstrings and a classical checker decides whether any of them is valid and near-optimal. The quantum part is a sampler; the verification is classical and cheap. So I'd pin down three things before designing: the instance class (constrained binary optimization. Max-Cut, or a cardinality-constrained portfolio), the size n, and what "verified" means. Feasible under the constraints, and within a stated gap of a bound.

Assumptions I'd state. For the reference run, n small enough to brute-force the optimum (n ≤ 20). For larger n I only have a relaxation bound, so I report a gap and never say "optimal". Ansatz: QAOA with p layers, cost Hamiltonian diagonal in the computational basis. Optimizer: COBYLA (rhobeg=0.5, maxiter=200), or SPSA on noisy hardware. Shots: 8192 per energy evaluation.

The pipeline. (1) Encode: Max-Cut to Ising: H = m/2 − ½ Σ_(i,j) Z_i Z_j, where m is the edge count; the constant m/2 is real and must be carried. (2) Optimize: QAOA p=1, COBYLA on ⟨H⟩ estimated from shots. (3) Sample: measure in the Z basis, collect counts. (4) Decode and verify classically: for each bitstring compute the cut value exactly, check constraints, compare to the bound.

Worked trace: C4 (4-cycle, unit weights), 1024 shots:

bitstringshotscut value
01013004
10102804
01101202
10011102
00111002
1100902
0000120
1111120

Mean ⟨H⟩ = 3160/1024 = 3.086. Sample σ = 1.086, so SE = σ/√1024 = 0.034. Best sample = 4, which equals the brute-forced optimum for C4. Note the gap between the optimizer's objective (3.086) and the deliverable (4): QAOA minimizes the mean, you ship the best sample. Reporting 3.086 understates; reporting 4 without saying it is a max over 1024 shots overstates.

Verifier (Python 3.12):

Python
def cut(bits, edges):
    return sum(w for i, j, w in edges if bits[i] != bits[j])

def verify(counts, edges, bound):
    best, best_bits = -1, None
    for s, c in counts.items():
        bits = [int(b) for b in reversed(s)]   # Qiskit: little-endian
        v = cut(bits, edges)
        if v > best:
            best, best_bits = v, bits
    return best, best_bits, (bound - best) / bound

Failure modes, with detection.

  • Offset dropped. Forget m/2 and every energy is off by 2 here. Detect: evaluate the classical cut of a known bitstring and compare to the Ising energy of the same bitstring. They must match exactly.
  • Optimizer objective ≠ verification objective. You optimize ⟨H⟩ but ship the best sample. Detect: log both per iteration; a persistent gap larger than 2·SE means the mean is not tracking the best.
  • Same shots reused across iterations. The optimizer fits one batch's noise. Detect: re-evaluate the final parameters on a fresh independent 8192-shot batch; a drop larger than 2·SE (0.068 here) is overfitting.
  • Infeasible states silently discarded. Post-selection makes the reported success rate conditional. Detect: log the discard fraction. Drop 40% of shots and the "success rate" is over the surviving 60%.
  • Ground truth implied but absent. For n > 20 there is no optimum. Detect: assert the bound is a relaxation (Goemans–Williamson SDP, ratio 0.878, Goemans & Williamson 1995) and report the gap, never "optimal".

When not to use it. If the instance is small enough to solve exactly (n ≤ 20, brute force), the sampler adds nothing: verify classically. If the constraint structure forces heavy post-selection, effective shot cost explodes and a classical heuristic wins. A hardware-efficient ansatz is the other trap: it has no guarantee the optimum is reachable, so a low ⟨H⟩ there proves nothing about the solution.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Design and validate a variational quantum workflow for NISQ claim boundary.

Answer

What I'd say in the first 90 seconds

Before designing the circuit I'd fix the claim the workflow is allowed to make, because on NISQ hardware the honest answer is almost always demonstration, not advantage. Assumptions: a superconducting device in the 50–127 qubit range, two-qubit gate error between 1e-3 and 1e-2, no error correction, and an instance small enough to verify classically. The workflow is a variational loop (parameterized circuit, Hamiltonian cost, classical optimizer, error mitigation) and validation is a matched classical benchmark plus a resource ledger. The claim boundary is the strongest statement that survives both.

Design

  1. Encode. MaxCut on n=20 nodes → Ising cost H_C = Σ_{(i,j)∈E} (1 − Z_i Z_j)/2. Every term is diagonal in Z, so all terms commute and one measurement basis suffices; no Pauli grouping needed.
  2. Ansatz. QAOA with p=2 layers, or a hardware-efficient RY+CX ansatz whose entangler graph matches the device topology (heavy-hex on IBM Eagle r3). Depth is capped by the coherence budget, not by the optimizer.
  3. Estimate. 8192 shots per basis. Shot noise on one Pauli expectation is 1/√8192 ≈ 0.011; across four edge terms the cut value carries ≈ 0.022 standard error.
  4. Optimize. SPSA: two circuit evaluations per step regardless of parameter count, and it tolerates shot noise better than COBYLA's finite differences.
  5. Mitigate. Readout via a calibration matrix (M3), and zero-noise extrapolation by gate folding at scale factors 1, 3, 5.
Python
import pennylane as qml

EDGES = [(0, 1), (1, 2), (2, 3), (3, 0)]
dev = qml.device("default.qubit", wires=4, shots=8192)

@qml.qnode(dev)
def cut(params, p=2):
    for w in range(4):
        qml.Hadamard(wires=w)
    for k in range(p):
        for (i, j) in EDGES:                 # exp(-i gamma Z_i Z_j)
            qml.CNOT(wires=[i, j])
            qml.RZ(2 * params[k], wires=j)
            qml.CNOT(wires=[i, j])
        for w in range(4):                   # exp(-i beta X_w)
            qml.RX(2 * params[p + k], wires=w)
    return [qml.expval(qml.PauliZ(i) @ qml.PauliZ(j)) for (i, j) in EDGES]

def cost(params):
    return sum(0.5 * (1 - zz) for zz in cut(params))

PennyLane 0.38, default.qubit. params holds 2p = 4 entries: layer k=0 reads params[0] as gamma and params[2] as beta; layer k=1 reads params[1] and params[3]. Each edge costs two CNOTs per layer, so 4 edges × 2 × 2 layers = 16 CNOTs. The function returns the expected cut size, bounded by 0 and |E| = 4.

Validation

Matched classical benchmark: same instance, same wall-clock budget, compared against Goemans–Williamson SDP (0.878 approximation guarantee) and exact brute force for n ≤ 20. Resource ledger: two-qubit gate count, QPU seconds, classical CPU seconds. At 99.5% two-qubit fidelity, 16 CNOTs give an all-gates-succeed probability of 0.995^16 ≈ 0.92: roughly one shot in twelve is corrupted before mitigation, which is the noise floor ZNE has to beat.

ClaimWhat must holdFirst thing that breaks it
DemonstrationCircuit ran on the QPU; result matches simulator within shot noiseSimulator result substituted for hardware
UtilityBeats the best classical heuristic at matched wall-clock on a classically intractable instanceClassical baseline given less time or weaker hardware
AdvantageProvable separation under matched resources, error-mitigatedExtrapolating from n=20 to n=1000

Trade-offs and when not to use it

  • If the instance is exactly solvable classically, no variational run can claim utility: the classical baseline is the answer.
  • If the ansatz is deeper than the coherence budget, gradients concentrate: gradient variance decays exponentially with qubit count (barren plateau). Detect by sampling gradients at random initializations; if the variance sits below the shot-noise band, the optimizer is not learning.
  • For chemistry with strong static correlation, a hardware-efficient ansatz may not reach chemical accuracy (1.6 mHa). Use ADAPT-VQE or a problem-inspired ansatz instead.

Failure modes, detection, cost

  • Noise floor above signal. ZNE-extrapolated value differs from raw by more than the shot-noise band → the "advantage" claim is a mitigation artefact.
  • Simulator mixed in. Check backend metadata and job IDs; a simulator result presented as hardware invalidates the whole claim.
  • Failed jobs omitted. Compare submitted vs returned job counts; survivorship bias inflates the reported success rate.
  • Classical compute free. Count classical CPU/GPU hours in the ledger; omitting them understates the baseline and manufactures advantage.
  • Scale extrapolation. A result at n=20 says nothing at n=1000; the boundary is the largest n actually run.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Design and validate a variational quantum workflow for reproducible evidence.

Answer

Assumptions. A variational workflow (VQE/QAOA-style): parameterized circuit, classical optimizer, energy estimated from shots on a noisy backend or simulator. The claim to defend is "ansatz A reaches energy E on instance I within budget B." Reproducible evidence means a reviewer can re-derive E from the archive without re-running the hardware.

Core answer. Freeze the instance and target, seed every stochastic step, route every trial through one logging path, then validate by re-execution and by budget-matched baselines. The archive is not the point: the point is that the archive is sufficient to re-derive the reported number. If it isn't, you have a log, not evidence.

Design, five stages.

  1. Freeze. Hash the Hamiltonian/instance, the ansatz template, and the qubit layout. Snapshot the target: backend name, coupling map, basis gates, and the calibration timestamp. IBM Quantum publishes per-qubit T1/T2 and gate error with a last-update time; that timestamp is part of the evidence, not metadata.
  2. Seed. Transpiler seed, optimizer seed, shot seed. Record the RNG library and version: a seed is meaningless if the generator changed underneath it.
  3. Execute. One record per trial, written by one function, so no trial can be logged differently from another.
  4. Validate. Re-evaluate the final parameters with a fresh seed and check the reported energy lies inside the shot-noise band. Re-run a fixed reference circuit each session to detect calibration drift.
  5. Report. Sum shots and QPU seconds over all records, including failed and abandoned ones.

Artefact: the record.

Python
import hashlib

def evidence_record(t):
    return {
        "trial_id": t.id,
        "instance_hash": hashlib.sha256(t.hamiltonian_bytes).hexdigest(),
        "ansatz": t.ansatz_name,
        "layout": t.layout,                 # logical -> physical qubit
        "target": {"backend": t.backend,
                   "calib_ts": t.calib_ts,
                   "coupling_map": t.coupling_map},
        "seeds": {"transpile": t.seed_t, "optimizer": t.seed_o, "shots": t.seed_s},
        "optimizer": {"name": t.opt_name, "maxiter": t.maxiter},
        "stop": t.stop_reason,              # converged | maxiter | budget
        "params": t.params,                 # final parameter vector
        "energy": t.energy,
        "shots_used": t.shots_used,
        "mitigation": t.mitigation,         # e.g. {"zne": {"scale_factors": [1, 3, 5]}}
        "raw_ref": t.raw_blob_uri,          # content-addressed counts blob
    }

Artefact: failure modes and how each is caught.

failuredetection
trial deletioncount records against reported n; every launched job ID must appear
parameter–result mismatchre-evaluate stored θ* with a fresh seed; reported energy must sit inside the shot-noise band
calibration driftcompare calib_ts across trials; a fixed reference circuit re-run each session must reproduce within its band
mitigation cherry-pickmitigation config fixed before the run; every config tried is logged, not just the winner
baseline under-tunedbaseline gets the same shot and iteration budget; report its own convergence, not just its final value
total work uncountedsum shots_used and QPU seconds over all records, failed trials included

Trace: the mismatch check. Trial 7 reports energy −1.137 Ha at θ*. Re-evaluate θ* with 10,000 fresh shots → −1.021 Ha. If the shot-noise band on that estimate is ±0.03 Ha, the stored energy sits ~4σ outside it: the stored parameters do not produce the stored energy. Either the wrong θ* was written or the wrong energy was. (Figures hypothetical.)

Trade-offs. Storing raw counts for every energy evaluation is cheap at small scale: a 1,000-shot evaluation on ~20 qubits is a few KB of JSON, so 200 evaluations × 50 trials is tens of MB. At 10^4 shots × 10^4 evaluations it is GBs. The alternative is to store mean and variance plus a content hash, and keep raw counts for a random sample. Deciding criterion: if the claim depends on the distribution (variance, error bars, ZNE extrapolation) keep raw; if only the mean, summary plus hash is enough. Full provenance is not worth it for exploratory runs where you are still choosing an ansatz, provided those runs are marked exploratory, excluded from the reported number, and the exclusion rule is fixed before results are seen.

Curated: · Written: · Reviewed:

Difficulty: Hard