Skip to content
Tech Interview Prep
Technical interview guide

Hybrid Classical-Quantum Systems & Quantum Machine Learning

How a quantum subroutine plugs into a larger classical pipeline, what quantum machine learning actually promises today, and how that differs from the hype.

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

Scope: IBM Quantum current hybrid HPC and QML guidance; PennyLane 0.45; classical-perspective and dequantization 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-1

How does the closed-loop optimization cycle work in hybrid quantum-classical algorithms like VQE or QAOA, and how do you partition tasks between the classical host and the QPU?

Answer

Core answer (first 90 seconds). In VQE and QAOA the QPU is a coprocessor that evaluates one scalar: the expectation value of a Hamiltonian at a fixed parameter vector. Everything else runs classically. One iteration is: the host binds θ_t into an already-transpiled circuit, the QPU prepares |ψ(θ_t)⟩ and returns bitstring samples, the host converts those samples into ⟨H⟩(θ_t), the optimizer proposes θ_{t+1}, and the loop repeats until the energy or the gradient stops moving. The partition follows from what each side is good at: state preparation and measurement are quantum; Hamiltonian decomposition, ansatz synthesis, shot aggregation, error mitigation, the update rule and the convergence test are classical. The binding constraint is usually loop latency, not coherence time: a single circuit executes in microseconds, but a cloud job submission costs about a second.

Where each stage runs

StageRuns onWhy
H → Σ c_k P_k, grouped into qubit-wise commuting setsHostLinear algebra; no quantum resource needed
Ansatz synthesis, transpile, layoutHost, onceStatic; recompiling per iteration burns QPU time
Bind θ_t into the circuitHostCheap; keeps circuit structure fixed
Pulse generation, state prep, gatesQPU control electronicsOnly place it can happen
Basis rotation + measurementQPUThe measurement basis is set by P_k
Shots → ⟨P_k⟩ → ⟨H⟩HostClassical arithmetic
Readout calibration, ZNEHost, on QPU dataPost-processing
Gradient / update step, convergence testHostOptimizer

The interface between the tiers is narrow: (circuit, parameter vector, shot count) in, (bitstring counts) out. The QPU never sees the optimizer; the host never sees the wavefunction.

Loop

host: θ_0 ──bind──▶ QPU: prepare |ψ(θ_t)⟩, rotate to basis, measure N shots
  ▲                                        │
  │                                        ▼
  └── θ_{t+1} = θ_t − η g_t ◀── host: counts → ⟨P_k⟩ → ⟨H⟩(θ_t), g_t

Worked cost trace. Take a 4-qubit transverse-field Ising problem, H = −J Σ Z_i Z_{i+1} − h Σ X_i with J = h = 1: 3 ZZ terms and 4 X terms, 7 Pauli terms total. All ZZ terms are qubit-wise commuting, as are all X terms, so the 7 terms collapse into G = 2 measurement groups. Use a hardware-efficient ansatz with P = 8 parameters and N = 4096 shots.

Parameter-shift gradient: for a gate U(θ) = e^{−iθG/2} with G² = I (any Pauli generator),

∂⟨H⟩/∂θ = ½ [⟨H⟩(θ + π/2) − ⟨H⟩(θ − π/2)].

Each gradient step needs 2P = 16 shifted evaluations, each covering G = 2 groups → 32 circuit executions, 32 × 4096 = 131,072 shots. SPSA needs only 2 evaluations per step (4 circuits, 16,384 shots) regardless of P, but typically 10× more iterations.

Wall clock: submitting 32 circuits as 32 separate cloud jobs at ~1 s round trip is ~32 s per gradient step, so 100 steps is ~53 minutes, almost all of it queue latency. Inside a session-based runtime (Qiskit Runtime sessions, Braket hybrid jobs, or a co-located container) the batch is one job and per-iteration overhead drops to milliseconds; at ~3 µs per shot the QPU work is 32 × 4096 × 3 µs ≈ 0.4 s per step, so 100 steps is under a minute. (These numbers are illustrative; the shape (latency-bound outside a session, shot-bound inside one) is the point.)

Failure modes to name.

  • Barren plateaus: for random ansätze the gradient variance falls exponentially in qubit count. Log ‖g_t‖; if it sits at the shot-noise floor, more shots will not help: change the ansatz or initialize near a known-good point.
  • Shot noise swamping the gradient: ⟨H⟩ has standard error σ/√N. If |g_t| is below that, the optimizer random-walks. Raise shots, switch to SPSA, or shrink the parameter space.
  • Measurement blow-up: measuring each of K Pauli terms separately costs K circuits per evaluation. Grouping into qubit-wise commuting sets cuts it to G; for molecular Hamiltonians G is often 10–100× smaller than K.
  • Calibration drift: T1/T2 and gate errors move between iterations, so a long loop optimizes against a moving target. Pin the calibration or run inside a session.
  • Optimizer mismatch: COBYLA and SPSA tolerate shot noise but converge slowly; parameter-shift with Adam or BFGS converges fast but needs 2P evaluations per step and assumes low noise.

QAOA vs VQE. In QAOA the ansatz is fixed by the problem (p alternating cost and mixer layers, 2p free angles) so the only design choices are p and the mixer. In VQE the ansatz is the main design decision, and it drives both achievable accuracy and per-step cost.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

How do you compute gradients of parameterized quantum circuits on real quantum hardware, and how does the parameter-shift rule compare to classical backpropagation and finite differences?

Answer

On physical quantum hardware, backpropagation cannot be directly evaluated because intermediate quantum states cannot be non-destructively cloned or inspected without collapsing the superposition (the no-cloning theorem). Instead, we must query the quantum processor unit (QPU) using black-box or analytic sampling estimators.

1. Parameter-Shift Rule Mechanism

For a parameterized gate generated by an operator $G$ with two distinct eigenvalues $\pm r$ (such as standard Pauli rotation gates $R_X(\theta), R_Y(\theta), R_Z(\theta) = \exp(-i \frac{\theta}{2} P)$ where $r = 1/2$), the expectation value $f(\theta) = \langle 0 | U^\dagger(\theta) \hat{B} U(\theta) | 0 \rangle$ is an exact sinusoid in $\theta$. The analytic gradient is evaluated without approximation by taking two evaluations shifted by $s = \frac{\pi}{4r} = \frac{\pi}{2}$:

$$\frac{\partial f}{\partial \theta} = r \left[ f\left(\theta + \frac{\pi}{4r}\right) - f\left(\theta - \frac{\pi}{4r}\right) \right]$$

For standard Pauli rotations ($r = 1/2$): $$\frac{\partial f(\theta)}{\partial \theta} = \frac{1}{2} \left( f\left(\theta + \frac{\pi}{2}\right) - f\left(\theta - \frac{\pi}{2}\right) \right)$$

Unlike classical automatic differentiation (reverse-mode AD / backpropagation), which caches intermediate forward activations and traverses back in $O(1)$ circuit evaluations, the parameter-shift rule requires $2P$ distinct circuit executions for a parameter vector $\boldsymbol{\theta} \in \mathbb{R}^P$.

2. Trade-offs: Parameter-Shift vs. Finite Differences vs. Classical Backpropagation

AttributeClassical BackpropagationNumerical Finite DifferencesParameter-Shift Rule
Hardware Executable?No (Violates no-cloning; requires state vector simulator)Yes (Hardware black-box)Yes (Hardware native)
Circuit Evaluations1 forward pass, 1 backward pass ($O(1)$ evaluations)$P + 1$ (forward) or $2P$ (central)$2P$ shifted circuits
Truncation BiasNone (machine precision)$O(\epsilon)$ or $O(\epsilon^2)$ systemic biasExact analytic zero truncation error
Shot Noise SensitivityN/A (simulated deterministic or sample-free)Catastrophic at small $\epsilon$: $\text{Var} \propto \frac{\sigma^2}{\epsilon^2 K}$Controlled: $\text{Var} = \frac{1}{4} \left( \frac{\sigma_+^2}{K} + \frac{\sigma_-^2}{K} \right)$

3. Shot Noise and Failure Modes

When evaluating gradients with $K$ shots per shifted expectation value, the variance of the gradient estimator $\hat{g} = \frac{1}{2}(\hat{f}+ - \hat{f}-)$ is: $$\text{Var}[\hat{g}] = \frac{\text{Var}[\hat{f}+] + \text{Var}[\hat{f}-]}{4K} \le \frac{1}{2K}$$

If we used finite differences with step $\epsilon$: $$\hat{g}{\text{FD}} = \frac{\hat{f}(\theta + \epsilon) - \hat{f}(\theta - \epsilon)}{2\epsilon} \implies \text{Var}[\hat{g}{\text{FD}}] \approx \frac{\text{Var}[\hat{f}]}{2 \epsilon^2 K}$$

For $\epsilon = 10^{-3}$ and $K = 8192$, finite difference variance blows up by a factor of $10^6$, completely burying the gradient signal in shot noise. Parameter-shift uses macroscopic shifts ($s = \pi/2$), avoiding numerical instability.

Key failure modes in practice:

  1. Barren Plateaus: On deep, unconstrained ansätze (e.g., random 2-designs), $\text{Var}[\partial_\theta f] \in O(2^{-n})$ where $n$ is the number of qubits. Shot noise dominates unless $K \in \Omega(2^n)$, stalling gradient descent.
  2. Drift and Decoherence During Batches: Evaluating $2P$ circuits on a physical queue can span minutes. If $T_1/T_2$ or gate calibration drifts between evaluating $\theta + s$ and $\theta - s$, the estimator acquires systematic bias that corrupts optimizer steps.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

Design and validate a hybrid quantum-classical workflow for gradients.

Answer

What I'd say first. Pin down three things before choosing anything: the device (statevector simulator or shot-based hardware), the number of trainable parameters P, and the target gradient accuracy. Those decide the differentiation method. On a statevector simulator I use backprop or adjoint differentiation: one forward and one backward pass, cost roughly independent of P. On hardware I use the parameter-shift rule. For a gate generated by a Pauli, ∂⟨O⟩/∂θ = [⟨O⟩(θ+π/2) − ⟨O⟩(θ−π/2)]/2. It is exact and costs 2P circuit executions per gradient. I validate the implementation against central finite differences on a small instance, budget shots to hit the target gradient standard error, batch the shifted circuits, aggregate, and retry failed jobs while propagating shot covariance.

Mechanism. Parameter-shift works because a Pauli-generated rotation U(θ)=exp(−iθG/2) with G²=I splits the derivative into two evaluations at ±π/2. Gates with more than two generator eigenvalues need a multi-term rule; PennyLane's param_shift selects it automatically. Backprop cannot run on hardware because measurement collapses the state and the intermediate amplitudes are never available.

Worked trace. Circuit: RX(θ) on |0⟩, measure ⟨Z⟩. Analytically ⟨Z⟩ = cos θ, so ∂⟨Z⟩/∂θ = −sin θ. At θ = π/4, ⟨Z⟩ = 0.7071 and the true gradient is −0.7071. Parameter-shift evaluates θ+π/2 = 3π/4 → cos = −0.7071 and θ−π/2 = −π/4 → cos = 0.7071; (−0.7071 − 0.7071)/2 = −0.7071. Exact.

Python
import pennylane as qml, numpy as np
dev = qml.device("default.qubit", wires=1)
@qml.qnode(dev, diff_method="parameter-shift")
def circuit(theta):
    qml.RX(theta, wires=0)
    return qml.expval(qml.PauliZ(0))
theta = np.pi/4
print(circuit(theta))            # 0.7071067811865476
print(qml.grad(circuit)(theta))  # -0.7071067811865475

Shot budget. With S shots per shifted circuit, each ⟨Z⟩ estimate has standard error √((1−⟨Z⟩²)/S). At θ=π/4 that is √(0.5/S) each; the two are independent, so gradient variance is (0.5/S + 0.5/S)/4 = 1/(4S) and gradient standard error is 1/(2√S). S = 10,000 gives 0.005, resolving the gradient to ~0.7%.

Alternatives.

methodcircuits per gradientexacthardwarewhen
parameter-shift2Pyesyesdefault on hardware
central finite diff2PO(h²) biasyescross-check only
backprop / adjoint1 fwd + 1 bwdyesnostatevector sim
SPSA2 per iterationnoyesP in the thousands

Failure modes and detection.

  • Barren plateau: gradient variance decays exponentially in qubit count for random circuits and global cost functions. Detect by sampling gradients at random θ and plotting variance against n; if it falls off a cliff, restructure the ansatz or use local cost functions.
  • Shift-coefficient error: a wrong shift (π/4 instead of π/2) biases the gradient silently. Detect with an assertion against finite differences on a 2-qubit instance.
  • Device auto-method: diff_method="best" resolves differently per device and silently falls back on hardware. Detect by printing qnode.diff_method after construction.
  • Batch mismatch: shifted circuits must be paired to their parameter; misalignment corrupts the gradient. Detect with a unit test against a known analytic gradient.
  • Retries: a failed hardware job re-run changes the shot statistics. Propagate the retry into the covariance rather than discarding it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Design and validate a hybrid quantum-classical workflow for basis encoding.

Answer

Basis encoding maps a classical bitstring b ∈ {0,1}^n to the computational basis state |b> = |b_1 b_2 ... b_n>, one qubit per bit. The hybrid workflow is classical preprocessing → circuit construction → execution → classical post-processing and validation. I assume features are already binarized (threshold, one-hot, or presence/absence), the schema is fixed at train time, and validation runs on both an ideal simulator and a noisy backend.

Workflow

  1. Classical: define a schema. Bit order: I use little-endian (qubit 0 is the least significant bit), matching Qiskit's bitstring convention. Missing values: impute to 0 and add a missing-indicator bit, or reject the row. Categorical coding: one-hot with a fixed vocabulary; an unseen category becomes all-zero plus an "unseen" flag bit. Invalid patterns: a one-hot vector with more than one bit set is rejected or repaired to the first set bit.

  2. Quantum: start from |0...0>. For each bit i where b_i = 1, apply an X gate to qubit i. No other gates. Depth is 1 because all X gates commute and can be applied in parallel.

  3. Measure all qubits in the Z basis.

  4. Classical: decode the measured bitstring back to features using the same schema, then compare to the input.

Code (Qiskit 1.x)

Python
from qiskit import QuantumCircuit, transpile
from qiskit_aer import AerSimulator

def encode_basis(bits: list[int]) -> QuantumCircuit:
    n = len(bits)
    qc = QuantumCircuit(n, n)
    for i, b in enumerate(bits):
        if b:
            qc.x(i)
    qc.measure(range(n), range(n))
    return qc

bits = [1, 0, 1]          # little-endian: qubit 0 = 1, qubit 1 = 0, qubit 2 = 1
qc = encode_basis(bits)
sim = AerSimulator()
result = sim.run(transpile(qc, sim), shots=1024).result()
counts = result.get_counts()
print(counts)             # {'101': 1024}

Trace. For bits = [1,0,1], the circuit applies X to qubit 0 and qubit 2. Starting from |000>, the state becomes |101>. Qiskit prints bitstrings with qubit 0 on the right, so the string is "101". Measurement in the Z basis returns "101" with probability 1 on the simulator. On hardware, readout errors flip bits; with per-qubit readout error p, the probability of the correct bitstring is (1-p)^n. For n=20 and p=1%, that is 0.99^20 ≈ 0.82, so a validation threshold of p_correct > 0.8 is reasonable for that device.

Validation

  • Statevector fidelity: on the ideal simulator, compute the statevector of the pre-measurement circuit and verify it equals the basis vector for b (fidelity = 1.0). This catches bit-order bugs.
  • Round-trip: run the circuit, decode the dominant bitstring, and assert it equals the input. Use an asymmetric test vector (e.g., 1000 and 0001) to catch endian reversal.
  • Hardware: run on the target backend, compute the probability of the correct bitstring, and compare to the expected (1-p)^n. If it falls below, investigate readout error or crosstalk.

Failure modes and detection

  • Endian reversal: classical code assumes big-endian, Qiskit uses little-endian. Detection: encode 1000 and 0001; if the measured bitstrings are swapped relative to the input, the endianness is wrong.
  • Train/test vocabulary drift: one-hot vocabulary built on train, test has a new category → all-zero vector, indistinguishable from "missing". Detection: track unseen-category rate; if >0, fail the batch.
  • Padding treated as signal: padding to a fixed width with zeros creates valid |0> states that look like real zeros. Detection: add a mask bit or validate that padding positions are always zero.
  • Width cost ignored: n bits → n qubits. For 100 features, 100 qubits. Current superconducting devices (e.g., IBM Heron, 133 qubits) can hold that, but connectivity and fidelity limit depth. Detection: check n against backend qubit count and error map before submitting.

Trade-offs. Basis encoding is shallow (depth 1) and readout is direct, but width is linear in n. Angle encoding uses n qubits but continuous rotations (depth 1, but readout is not a bitstring). Amplitude encoding uses log2(n) qubits but requires arbitrary state preparation (depth O(2^n)) and probabilistic readout. Use basis encoding when features are naturally binary and you need deterministic, shallow circuits; avoid it for high-precision continuous features, where binarization loses information.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

Design and validate a hybrid quantum-classical workflow for data encoding.

Answer

Assume tabular data, 4–20 features, NISQ hardware with limited connectivity, and a classical optimizer. The workflow: split before encoding, fit the scaler on train only, encode with angle encoding, train a variational circuit, then validate against a classical baseline and an ablation.

Design. Use a leakage-safe pipeline. Split 60/20/20 stratified into train/val/test. Fit MinMaxScaler(feature_range=(-π, π)) on train only; transform val and test with that scaler. Encode each feature x_i as RY(x_i) on qubit i. Add L trainable layers interleaved with re-uploading if validation shows underfitting. Train with SPSA or COBYLA on train, early-stop on val AUC. Select the encoding on val, never on test. Test once at the end. Baseline: logistic regression on the same scaled features. Ablation: replace the encoding with random rotations; if val AUC falls to the baseline, the encoding adds no signal.

Mechanism. Angle encoding computes expectation values that are trigonometric polynomials in x. With L data re-uploading layers, the Fourier spectrum has up to 2L+1 frequencies, so expressivity grows with depth. Amplitude encoding packs 2^n features into n qubits but state preparation depth is O(2^n) and requires normalized inputs; on linear connectivity that depth dominates. Data re-uploading interleaves encoding and trainable layers; it is more expressive but depth scales with L.

EncodingQubits for d featuresDepth (d=8)ExpressivityWhen to use
Angled1limitedNISQ, shallow circuits
Amplitudelog2 dO(d)highsmall d, simulation
Data re-uploadingdO(L*d)highenough coherence time
Python
# Qiskit 1.x, scikit-learn 1.4
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from qiskit import QuantumCircuit
from qiskit.circuit import ParameterVector

X, y = ...  # features, labels
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, stratify=y, random_state=42)
scaler = MinMaxScaler(feature_range=(-np.pi, np.pi))
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)  # no leakage

n = X_train.shape[1]
x = ParameterVector('x', n)
qc = QuantumCircuit(n)
for i in range(n):
    qc.ry(x[i], i)
# optional: repeat with trainable layers for data re-uploading

Trace. For d=4, angle encoding depth is 1. Add one trainable layer: a CNOT chain on 4 qubits has depth 3, then an RY layer has depth 1. Total depth 5, two-qubit gates 3. With L=2 re-uploading: depth 2*(1+3+1)=10, two-qubit gates 6. On a 127-qubit Eagle r3, 1024 shots and 500 COBYLA iterations, wall-clock is roughly 90 s (hypothetical).

Failure modes and detection.

  • Test-informed feature map: encoding chosen after seeing test. Detect by locking the test set; only val selects encoding.
  • Normalization leakage: scaler fit on all data. Detect by comparing scaler mean/std on train vs full; use sklearn.pipeline.Pipeline.
  • Incompatible feature range: features outside [-π, π] cause aliasing. Detect by checking min/max after scaling; clip to [-π, π].
  • Encoding cost omitted: depth/runtime not counted. Detect by transpiling and counting depth, two-qubit gates, shots, wall-clock.
  • Class label encoded accidentally: label in X. Detect by asserting the label column is not in X and checking correlation.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Design and validate a hybrid quantum-classical workflow for classical preprocessing.

Answer

If I were designing this, I'd first clarify what "classical preprocessing" covers: imputation, scaling, feature selection, dimensionality reduction. Everything before the quantum circuit. The goal is to validate that any performance gain comes from the quantum component, not from the preprocessing. Assume a tabular dataset with 1,000 samples and 20 features, a simulator backend like Qiskit Aer, and a quantum kernel or variational classifier. I'll use scikit-learn 1.4 and Qiskit 1.0.

The workflow has four stages. First, split the data into train/validation/test, say 60/20/20, stratified. Second, fit preprocessing on the training set only: median imputation, StandardScaler, then PCA to 4 components to match 4 qubits. Third, encode the 4 components into a quantum circuit: angle encoding with Ry(π * x_i) for each component, or a ZZFeatureMap with reps=2. Fourth, train the quantum model: for a kernel method, compute the quantum kernel matrix on the training set and train an SVM; for a variational circuit, optimize parameters with COBYLA or SPSA. Evaluate on the test set.

To attribute gains, run three matched experiments: (a) a classical SVM with RBF kernel on the same 4 PCA components, (b) a quantum kernel on the raw 20 features with no scaling or PCA, and (c) a quantum kernel on the 4 PCA components. Keep the number of circuit executions and optimizer steps identical across the quantum runs. Use 5 random seeds and report mean ± standard deviation.

The trade-off is between qubit count and information loss. PCA reduces qubits but can discard signal; an alternative is amplitude encoding, which uses log2(N) qubits but requires expensive state preparation. Scaling is mandatory for angle encoding because rotation angles must be in [-π, π]; skipping it saturates the circuit. You could also put a trainable scaling layer inside the quantum circuit, which moves the preprocessing into the quantum model, then classical preprocessing is just imputation. The deciding criterion: if (c) beats (a) by more than the standard error, and (b) does not, then classical preprocessing is necessary for the quantum model to win. If (b) matches (c), then preprocessing is not the source of gain.

Failure modes to watch. Data leakage: fitting the scaler or PCA on the full dataset before splitting inflates test accuracy. Detect it by using a scikit-learn Pipeline and checking that fit is only on the training set. Quantum noise: on real hardware, results vary; detect by running on a noisy simulator and comparing to the noiseless case. Compute mismatch: quantum simulation is slow; if you give the quantum model 10x more optimizer steps, it's unfair. Detect by logging circuit executions and wall-clock time. Barren plateaus: gradients vanish as qubit count grows; detect by monitoring gradient norm during training.

Here's a hypothetical comparison on the 1,000×20 dataset, 5 seeds:

ConfigurationPreprocessingModelTest accuracyCircuit executions
Classical baselineStandardScaler + PCA(4)SVM (RBF)0.82 ± 0.020
Quantum, no preprocessingNone (raw 20 features)Quantum kernel (ZZFeatureMap, reps=2)0.71 ± 0.031.2M
Quantum, with preprocessingStandardScaler + PCA(4)Quantum kernel (ZZFeatureMap, reps=2)0.84 ± 0.021.2M

These numbers are illustrative. The key is that the quantum model with preprocessing beats the classical baseline, but the quantum model without preprocessing does not, so the preprocessing is doing the heavy lifting. If the quantum model without preprocessing also beat the classical baseline, then the quantum component would be adding value independently.

So the design is: split, fit preprocessing on train, encode, train, evaluate. The validation is: matched ablations, same compute, multiple seeds. The trade-off is between qubit count and information loss. The failure modes are leakage, noise, compute mismatch, and barren plateaus.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21

Design and validate a hybrid quantum-classical workflow for quantum data.

Answer

Assumptions first. "Quantum data" means samples that are natively quantum states, output of a quantum processor or sensor, that you cannot copy (no-cloning) and cannot read out without destroying. If your data is a CSV, this is a classical problem with a quantum model bolted on, and the workflow below is the wrong tool.

The workflow. Five stages, one loop:

  1. Source. The device prepares |ψ(x)⟩ per sample. You get one shot per preparation; there is no copy.
  2. Model. Apply a parameterized circuit U(θ) to |ψ(x)⟩, or use |ψ(x)⟩ directly as a kernel feature map.
  3. Measure. Estimate ⟨ψ(x)|U†(θ) O U(θ)|ψ(x)⟩ for a small set of Pauli observables O, with N shots each.
  4. Optimize. A classical optimizer (COBYLA, SPSA, or Adam on a differentiable simulator) updates θ from the estimated expectation values.
  5. Validate. Re-prepare held-out states and compare against the strongest classical baseline you can build.

Where the quantum part sits is the design decision. Three placements, different costs:

placementcostwins whenloses when
quantum kernelO(n²) state preparations for n samples, each entry shot-estimateddata is quantum-native and classically hard to embedn large; shot noise swamps the kernel matrix
variational classifierone optimizer loop, many re-preparations per stepyou want a compact model and can pay shotsbarren plateaus; no proven advantage
classical shadowsO(log M / ε²) measurements for M observablesyou need many observables from few measurementshigh-weight observables have large shadow norm

Shot budget is the binding constraint. Estimating a ±1 observable to standard error ε needs N ≈ 1/ε² shots:

Python
import numpy as np
for eps in (0.1, 0.01, 0.001):
    print(f"eps={eps}: N={int(np.ceil(1/eps**2))}")
eps=0.1: N=100
eps=0.01: N=10000
eps=0.001: N=1000000

Resolving a 0.01 gap in an expectation value costs 10^4 shots per observable per sample. With 100 samples and 10 observables that is 10^7 shots per training evaluation. At a readout rate of 10^4 shots/s (assumption: check your device), one evaluation is ~17 minutes, and a 200-step optimization is ~2.3 days. That arithmetic, not the ansatz, usually decides the design.

Validation. You cannot split a dataset of states you cannot copy. Re-prepare train and test states in separate sessions and check the source has not drifted: measure a fixed reference state each session and track its fidelity. Compare against a classical baseline: a classical kernel on tomographed states, or a classical shadow feature vector fed to an SVM. If the classical baseline matches within the shot-noise error bar, you have no quantum advantage, only a quantum cost.

Failure modes and detection.

  • Source drift between sessions. Detect by reference-state fidelity per session; retrain if it drops.
  • Shot noise read as signal. Detect by requiring the measured gap to exceed 3σ = 3/√N; below that, it is noise.
  • Barren plateau. Gradient norm decays exponentially with qubit count (McClean et al., Nat. Commun. 2018). Detect by plotting gradient norm vs n; if it falls off exponentially, the ansatz is untrainable.
  • Tomography assumed cheap. Full state tomography of n qubits needs 3^n measurement settings: 59,049 for 10 qubits. Never assume you can reconstruct the state; estimate only the observables you need. (Classical shadows, Huang–Kueng–Preskill, Nat. Phys. 2020, are the cheaper alternative when you need many observables.)

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Design and validate a hybrid quantum-classical workflow for variational classifier.

Answer

Core answer. Assume a small tabular dataset reduced to n features (n = 4–8 after PCA) and a binary label. The workflow: angle-encode the features into n qubits, apply a hardware-efficient ansatz of L layers, measure ⟨Z⟩ on one qubit, map that to a class. Train the circuit parameters with a classical optimizer using the parameter-shift rule. Validate on a held-out split with a classical baseline beside it, and report accuracy as a mean ± std over repeated seeds: one run of a stochastic model is not a result.

Design.

Encoding: one RY per feature. It costs n qubits for n features and n gates. Amplitude encoding would use log2(n) qubits but state prep is O(2^n) gates, so it only pays off when n is large and the data is already normalized.

Ansatz: L layers of RY/RZ per qubit plus a ring of CNOTs. Start at L = 2 and grow only if the training curve underfits.

Loss: cross-entropy on the post-processed output, or (1 − y·⟨Z⟩)/2 for ±1 labels. Pick one and assert the label set matches it.

Optimizer: parameter-shift with Adam. Parameter-shift is exact for Pauli-generated gates and costs 2 circuit evaluations per parameter per step. If the parameter count P is large and shots are the bottleneck, SPSA costs 2 evaluations per step regardless of P: at the price of a noisy gradient estimate.

Shots: 1024 per expectation estimate. The standard error of ⟨Z⟩ is √((1−⟨Z⟩²)/N) ≤ 1/√N, so 1024 shots gives ≤ 0.031, and the parameter-shift gradient inherits √2/2 of that.

Seeds: fix numpy/torch seeds for the classical parts. Hardware sampling is not seedable: control it with a fixed shot count and report the spread across repeats instead.

Stopping: early stop on a validation split, never on test.

Artefact: code and trace.

Python
import pennylane as qml
import numpy as np

n_qubits, n_layers = 2, 1
dev = qml.device("default.qubit", wires=n_qubits, shots=1024)

@qml.qnode(dev)
def circuit(x, w):
    for i in range(n_qubits):
        qml.RY(x[i], wires=i)
    for i in range(n_qubits):
        qml.RY(w[i, 0], wires=i)
        qml.RZ(w[i, 1], wires=i)
    qml.CNOT(wires=[0, 1])
    return qml.expval(qml.PauliZ(0))

Trace with x = [0, 0], w[0,0] = π/4, all other weights 0. RY(π/4) on qubit 0 gives cos(π/8)|0⟩ + sin(π/8)|1⟩; the CNOT entangles to cos(π/8)|00⟩ + sin(π/8)|11⟩; ⟨Z0⟩ = cos²(π/8) − sin²(π/8) = cos(π/4) = 0.7071. Parameter-shift on w[0,0]: f(3π/4) = cos(3π/4) = −0.7071, f(−π/4) = cos(−π/4) = 0.7071, gradient = (−0.7071 − 0.7071)/2 = −0.7071, matching d/dθ cos θ at π/4. With 1024 shots the estimate carries std ≈ 0.022, so the gradient std ≈ 0.016: a step smaller than the gradient itself, which is the budget you must respect.

Validation. Split 60/20/20. Fit a logistic regression on the same features as the baseline; if the circuit does not beat it on validation, the quantum layer is not earning its cost. Report test accuracy as mean ± std over 5 seeds. Run a shots ablation (256, 1024, 4096) to show where accuracy saturates. Plot gradient variance against qubit count: exponential decay is the barren-plateau signature (McClean et al., 2018).

Failure modes and detection.

failuredetection
label encoding mismatch ({0,1} into a ±1 loss)assert set(y) ⊆ {−1,+1} before training; unit-test the loss on a 2-sample toy set
early stopping on testlog which split each stop decision used; val and test must be disjoint
hidden optimizer restartsrestarts selected on val only; log restart index and selection metric
dropped hardware jobsassert completed jobs == submitted; check job.status() per job
shot noise read as signalrepeat with different seeds; differences within ±1/√shots are noise

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

What causes barren plateaus in variational quantum machine learning models, and what strategies mitigate them?

Answer

Barren plateaus occur when the variance of the cost function gradient vanishes exponentially with the number of qubits: $\text{Var}[\partial_k C(\theta)] \in \mathcal{O}(2^{-\alpha n})$ for $\alpha > 0$, while the expectation $\mathbb{E}[\partial_k C(\theta)] = 0$. Because gradient magnitude scales as $\mathcal{O}(1/\sqrt{2^{\alpha n}})$, resolving a non-zero descent direction requires an exponential number of measurement shots $M \in \Omega(2^{\alpha n})$. Any polynomial-budget classical optimizer (such as Adam or COBYLA) gets trapped in an essentially flat energy landscape.

Primary Root Causes

  1. Ansatz Expressibility (Haar 2-designs): Deep, unstructured parameterized circuits (e.g., alternating hardware-efficient layers of arbitrary single-qubit rotations and entangling gates) quickly form approximate unitary 2-designs. By Levy's Lemma, Haar-distributed states concentrate measure exponentially on high-dimensional Hilbert spaces ($2^n$).
  2. Global Cost Functions: Cost observables defined across all $n$ qubits (e.g., projector $C = \langle 0|^{\otimes n} U^\dagger(\theta) O U(\theta) |0\rangle^{\otimes n}$ where $O = |0\rangle\langle 0|^{\otimes n}$) exhibit barren plateaus even at shallow circuit depths (depth $L \in \mathcal{O}(1)$).
  3. Hardware Noise: Unmitigated depolarizing or dephasing noise drives states toward the maximally mixed state $I / 2^n$ exponentially with circuit depth, flattening gradients independently of ansatz design (noise-induced barren plateaus).
  4. Entanglement Scaling: Uncontrolled volume-law entanglement across bipartitions causes subsystem purity to drop exponentially, suppressing gradient variance.

Mitigation Strategies

Mitigation Architecture
+-------------------------------------------------------------+
| Local Observables: Sum_i O_i acting on <= k local qubits    |
|   - At depth O(log n), variance scales as Omega(1/poly(n))  |
+-------------------------------------------------------------+
| Localized Ansätze: Layered/Tensor Networks (MERA, MPS)      |
|   - Constrains entanglement growth and 2-design coverage    |
+-------------------------------------------------------------+
| Identity / Small-Parameter Initialization:                  |
|   - Set parameters theta ~ 0 so U(theta) ~ I                |
|   - Prevents immediate collapse into Haar measure           |
+-------------------------------------------------------------+
MechanismBarren Plateau TriggerMitigation StrategyScaling Impact
Global Observable$O =0\rangle\langle 0^{\otimes n}$
Deep Random CircuitHardware-efficient 2-designProblem-inspired (QAOA / UCCSD) or MPS ansätzeRestricts search space to polynomial sub-manifold
Random Initialization$\theta_i \sim \mathcal{U}[0, 2\pi]$Identity-block initialization ($|\theta| \approx 0$)Avoids Haar random state space at initialization
Environmental NoiseDepolarizing noise channel $\mathcal{E}$Circuit depth reduction & zero-noise extrapolation (ZNE)Prevents state decay to $I/2^n$

Worked Example: Parameter-Shift Shot Limits

Using the parameter-shift rule $\partial_k C = \frac{1}{2}(C(\theta + \frac{\pi}{2} e_k) - C(\theta - \frac{\pi}{2} e_k))$. For a 20-qubit circuit exhibiting a global barren plateau, standard deviation of the gradient estimator $\sigma_g \approx 2^{-20/2} = 2^{-10} \approx 9.76 \times 10^{-4}$. To detect this gradient above shot noise $\sigma_{\text{shot}} = \frac{1}{\sqrt{M}}$ with signal-to-noise ratio $\text{SNR} \ge 2$: $$M \ge \frac{4}{\sigma_g^2} = 4 \times 2^{20} \approx 4.19 \times 10^6 \text{ shots per parameter step}.$$ With local observables, variance scales as $\mathcal{O}(1/n^2)$. For $n=20$, $\sigma_g \approx 1/20 = 0.05$, requiring $M \approx 4 / (0.05)^2 = 1{,}600$ shots, which is practically executable.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Design and validate a hybrid quantum-classical workflow for barren plateaus.

Answer

Clarify first: a barren plateau is not slow convergence. It is the gradient variance decaying exponentially in qubit count, Var[∂C/∂θ] ~ 2^(−cn), so no optimizer, gradient-based or not, finds a descent direction at scale. I assume a hardware-efficient ansatz (RY + CNOT ladder), a VQE-style cost, and a superconducting device with depolarizing noise. The workflow is: design for trainability, diagnose the scaling, mitigate what the diagnosis shows, then validate with a scaling study and a shot budget. Never by extrapolating from small n.

Mechanism. For a random circuit that forms a 2-design, the cost concentrates around its Haar average and the deviation shrinks as 2^(−n) (McClean et al., Nat. Commun. 9, 4812, 2018). Cost locality sets the exponent: a global observable (a projector onto the full ground state) decays exponentially, while a sum of few-qubit observables keeps variance polynomial in n for shallow circuits (Cerezo et al., Nat. Commun. 12, 1791, 2021). Noise adds a second, independent mechanism: local depolarizing channels drive the state to the maximally mixed state exponentially fast, flattening the landscape even for local costs (Wang et al., Nat. Commun. 12, 6961, 2021). Excess entanglement does the same.

Step 1: design. Local cost, shallow problem-inspired ansatz, identity-block initialization (Grant et al., Quantum 3, 214, 2019) instead of uniform random angles. Classical side: parameter-shift gradients into Adam, or SPSA when shot noise dominates.

Step 2: diagnose. Measure Var over ≥100 seeds at n = 4, 6, 8, 10, 12 and fit log2 Var against n.

Python
import numpy as np  # numpy 1.26

def grad_variance(grad_fn, n, layers, seeds=100, rng=None):
    rng = rng or np.random.default_rng(0)
    v = []
    for _ in range(seeds):
        theta = rng.uniform(-np.pi, np.pi, layers * n)
        g = grad_fn(theta)          # exact parameter-shift, statevector
        v.append(np.mean(g**2))     # ||grad||^2 / n_params
    return np.var(v, ddof=1)

for n in (4, 6, 8, 10, 12):
    var = grad_variance(grad_fn, n, layers=4)
    print(n, var, np.log2(var))

A slope near 0 is polynomial (trainable); a slope near −1 means the variance halves per added qubit.

Step 3: mitigate, matched to the diagnosis. Steep slope with a global cost: switch to a local cost or a problem-inspired ansatz. Steep slope only when noise is on: error mitigation (zero-noise extrapolation) or shallower circuits. Do not switch to a gradient-free optimizer: COBYLA, Nelder-Mead and Powell do not cure a plateau, they only avoid estimating the gradient, and they stall on the same flat landscape.

Step 4: validate. Three checks.

Scaling. Report median and IQR over seeds, not the best seed. One successful seed is noise.

Shot budget. Parameter-shift gives Var[ĝ] ≈ 1/(2N) for N shots per expectation, so resolving a component of magnitude g at unit SNR needs N ≈ 1/(2g²). At g = 1e-3 that is 5×10⁵ shots per component; with 100 parameters, 5×10⁷ shots per step. If the diagnostic slope is −1, each added qubit doubles that: the plateau is a budget wall, not a tuning problem.

Noise. Repeat the scaling study under a depolarizing model and compare slopes. A steeper noisy slope is a noise-induced plateau; a matched slope is ansatz-induced.

Failure modes. Shot noise masquerading as a plateau: re-run at 10× shots and check the variance estimate is stable. Small-n extrapolation: a slope from n ≤ 8 does not predict n = 50; the effect is exponential by construction. Optimizer stall read as a plateau: compare the optimizer's final gradient norm against the exact statevector gradient.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Design and validate a hybrid quantum-classical workflow for expressivity boundary.

Answer

Clarify first: the expressivity boundary is where adding quantum resources stops improving the model's ability to represent the target function, or where the model becomes untrainable or classically simulable. I'll design a workflow to locate that boundary for a given task, then validate it against classical baselines.

Assumptions: a fixed dataset, a classical baseline, and a parameterized quantum circuit (PQC). I'll use PennyLane 0.35 and scikit-learn 1.4 on a simulator.

Phase 1: Model family and baselines. Take MNIST binary 0-vs-1, downsampled to 4×4. Classical baselines: linear SVM, RBF SVM, random forest, and a classical random-feature model with the same number of features as the quantum model's effective dimension.

Phase 2: Expressivity. Two metrics. (a) The participation ratio of the Fisher information spectrum, PR = (Σλ_i)² / Σλ_i², a cheap proxy for the number of independent directions the model can move in. (b) The Abbas et al. effective dimension, d_γ = 2 log( (1/(2π log n)) ∫_Θ sqrt(det(I + γ F̃(θ))) dθ ) / log γ, where F̃ = nF/(2π log n) is the normalized Fisher information, n is the sample count, and γ ∈ (0,1) is a free parameter. The boundary is where d_γ saturates as qubits or layers are added.

Phase 3: Trainability. Gradient variance across 100 random initializations via the parameter-shift rule. Var[∂L/∂θ] < 1e-6 signals a barren plateau. Condition number of the Fisher matrix > 1e6 signals ill-conditioning.

Phase 4: Classical simulability. Two checks, both bounded. (a) Tensor-network simulation (Quimb) to find the bond dimension χ needed for 1% fidelity on the trained state; if χ stays small and grows slowly with qubits, that state is MPS-representable, but this is a statement about one state, not the whole circuit family. (b) Dimension of the dynamical Lie algebra generated by the gates; polynomial growth suggests simulability, but the algebra dimension alone does not prove it.

Validation: train the quantum model and classical baselines with matched parameter counts. Plot test accuracy vs. parameter count. The boundary is where the quantum model's accuracy stops improving, or where it matches a classical model of the same effective dimension.

MetricToolBoundary threshold
Participation ratio PRPennyLane + Fisher infoPR saturates as n_qubits grows
Effective dimension d_γPennyLane + Fisher infod_γ saturates as n_qubits grows
Gradient varianceParameter-shift rule< 1e-6 at init
Fisher condition numberNumPy> 1e6
Bond dimension χQuimb MPSχ grows slowly with qubits (state-level only)
Lie algebra dimensionPennyLane Lie closurepolynomial in n_qubits (suggestive, not proof)
Test accuracy gapscikit-learnquantum ≤ classical + 1%

Worked trace: a 4-qubit, 2-layer circuit with 16 parameters. Fisher eigenvalues over 100 random inputs: 8 at 0.5, 4 at 0.1, 4 at 0.01. Then Σλ = 4.44, Σλ² = 2.0404, so PR = 4.44² / 2.0404 ≈ 9.7. The model has ~9.7 independent directions out of 16 parameters. If we go to 6 qubits and 3 layers (36 parameters) and PR rises to ~20, expressivity grew; if gradient variance drops below 1e-6, it is untrainable.

Failure modes: dimension marketing. Claiming exponential expressivity from Hilbert-space size without measuring d_γ; detect by computing d_γ and comparing to a classical model. Memorization: train/test gap > 10%. Tiny dataset: n_samples < 10 × n_params. Random feature map: a fixed random circuit with no training; compare to classical random features of the same dimension. No ablation: always include a classical model with matched parameter count.

Trade-offs: more qubits and layers raise expressivity but also barren-plateau risk and simulability. Data re-uploading raises Fourier frequencies but can overfit. Hardware-efficient ansätze are easy to implement but may be classically simulable when entanglement is low. Problem-inspired ansätze like QAOA may train better but represent less.

Validation: the boundary predicted by d_γ and gradient variance should match the empirical accuracy plateau. If a classical model with the same d_γ matches accuracy, the quantum model has no advantage.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Design and validate a hybrid quantum-classical workflow for quantum kernels.

Answer

Assumptions first. N labelled samples, n features, a feature map φ: x → |φ(x)⟩ on n qubits, and the fidelity kernel k(x,x') = |⟨φ(x)|φ(x')⟩|². I'll assume a gate-model device behind a sampler primitive, and an SVM with a precomputed kernel on the classical side. If the encoding is non-unitary, or the classical method needs a strictly PSD matrix, the workflow changes at step 3.

The workflow, in order.

  1. Fix the feature map and the fidelity convention. ZZFeatureMap with linear entanglement and reps=2 is the default starting point; it is unitary, so its inverse exists and compute-uncompute works.
  2. Build the overlap circuit: prepare φ(x), apply φ(x')†, measure all qubits, estimate P(0…0). That probability is k(x,x').
  3. Estimate the full kernel matrix under a fixed shot budget. This is the expensive step: N² pair evaluations.
  4. Repair the matrix. Finite-shot estimates are not PSD; clip negative eigenvalues.
  5. Fit the classical model on the precomputed kernel.
  6. Validate against a classical baseline on the same folds. Report hold-out accuracy next to an RBF SVM; a quantum kernel that does not beat it is a negative result worth reporting, not a bug.

Why it behaves this way. The kernel is the squared inner product of two states in a 2ⁿ-dimensional Hilbert space. The feature map's entangling gates spread each sample across that space, so the kernel encodes correlations a classical RBF with one bandwidth cannot. Huang et al. (Nature Communications 2021) formalise the gap as the geometric difference g(K_Q ‖ K_C): when g is large and the dataset is small, the quantum kernel can win; when g is small, the classical kernel wins for free.

Code (Qiskit 1.x, qiskit-machine-learning 0.7):

Python
from qiskit.circuit.library import ZZFeatureMap
from qiskit_machine_learning.kernels import FidelityQuantumKernel
from sklearn.svm import SVC

fm  = ZZFeatureMap(feature_dimension=4, reps=2, entanglement="linear")
qk  = FidelityQuantumKernel(feature_map=fm, enforce_psd=True)
Ktr = qk.evaluate(X_train)          # (N, N)
Kte = qk.evaluate(X_test, X_train)  # (M, N)
svc = SVC(kernel="precomputed").fit(Ktr, y_train)

enforce_psd=True is the default and performs the eigenvalue clipping in step 4.

Cost arithmetic (illustrative). N=500 training points → 250,000 pair evaluations. At 1024 shots each and ~5 µs per shot on a superconducting device, that is 250,000 × 1024 × 5 µs ≈ 21 minutes of QPU time before queueing. Halving to 512 shots halves that but raises the standard error on each entry from ~0.016 to ~0.022.

Failure modes and how to catch them.

failuresymptomdetection
diagonal ≠ 1k(x,x) drifts from 1compute diag(K); flag if max|k(x,x)−1| exceeds a few standard errors (≈3/√shots)
pair order mismatchaccuracy sits at chancerecompute k(X[0],X[1]) directly and compare to K[0,1]; permute y and confirm accuracy drops to 1/num_classes
kernel/label leakageCV accuracy far above hold-outnested CV; tune bandwidth inside the inner fold only
inconsistent compilationthe same pair gives different kevaluate k(x,x') twice; the difference should sit inside shot noise
non-PSD matrixnegative eigenvalues; solver result unreliablecheck min eigenvalue; clip at 0

Trade-offs. Compute-uncompute needs the inverse feature map, so it fails for non-unitary encodings; the swap test works for any encoding but costs an ancilla and controlled-swaps. Fidelity kernels are noise-sensitive; projected quantum kernels (same Huang et al. paper) measure single-qubit reduced states instead and are more noise-resilient, at the cost of some Hilbert-space expressivity. Statevector simulation gives exact kernels and is fine to roughly 20 qubits; beyond that you need shots and the PSD repair.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Design and validate a hybrid quantum-classical workflow for kernel scaling.

Answer

Core answer. Three layers. The quantum layer estimates one kernel entry per pair: run the adjoint circuit U†(x_j)U(x_i) on |0…0⟩ and estimate p = P(all zeros) with S shots, so K_ij = p. The classical layer assembles K and trains an SVM or kernel ridge regression: O(n²) to O(n³), so the quantum part is not asymptotically dominant, but its constant is enormous. The control layer decides which entries you actually need. The scaling claim to defend is total shots = n(n+1)/2 × S for n training points, and you check that number before writing a circuit.

Symmetry gives n(n+1)/2 unique entries, not n². Caching keyed on the full configuration makes hyperparameter sweeps and CV folds cheap. Batching amortizes per-job overhead. None of the three changes the quadratic.

Arithmetic. n = 1000, S = 1024, hypothetical backend at 5,000 shots/s with 0.5 s job overhead:

batchjobsshot timejob overheadtotal
1500,500102,502 s250,250 s98.0 h
1005,005102,502 s2,503 s29.2 h
1000501102,502 s251 s28.5 h

Batching removes 70 h of overhead and does not touch the 28.5 h shot floor. That floor is the quadratic. Nyström subsampling with m = 100 landmarks cuts entries to n×m = 100,000 → 20,480 s ≈ 5.7 h, a 5× reduction, at the cost of an approximate kernel.

Shot noise. SE(p) = sqrt(p(1−p)/S). At p = 0.5, S = 1024 gives 0.0156; S = 10,000 gives 0.005. If the true class separation in kernel space is below roughly 2 SE, you are fitting noise.

Alternatives, and when not to use them. A projected quantum kernel measures single-qubit reduced density matrices, O(n_qubits) observables per pair instead of one global fidelity, and is more robust to concentration, but still costs O(n²) pairs. A classical RBF kernel is free and is the baseline you must beat; if the quantum kernel does not beat it on held-out accuracy, there is no case. Nyström landmarks are the only lever that changes the exponent in n.

Failure modes and how to detect them.

  1. Kernel concentration. With many qubits, off-diagonal K_ij collapse toward a constant and the matrix carries no class signal. Detect by computing the standard deviation of off-diagonal entries; if it sits within ~2× the shot-noise SE, the feature map is dead. Fix with fewer qubits, a projected kernel, or a different feature map.
  2. Shot noise swamping. Rerun a subset at 4× shots; if accuracy moves more than the binomial SE predicts, you were noise-limited.
  3. Cache key collision. The key must include feature-map parameters, backend, shots, mitigation settings, and pair order:
Python
# python 3.11
def cache_key(xi, xj, fm_params, backend, shots, mitigation):
    return (round(xi, 6), round(xj, 6), tuple(sorted(fm_params.items())),
            backend, shots, mitigation)

Change one feature-map parameter and assert the hit rate drops to zero; if it does not, the key is incomplete. 4. Job overhead dominating. Measure wall-clock per job against per shot; if overhead exceeds shot time, raise the batch size. 5. Training-only cost quoted. Count prediction rows too: inference needs n_test × n_train entries, often more than training.

Validation protocol. Establish the shot-noise floor from repeated seeds; run the concentration check; compare against a classical RBF baseline on identical splits; measure end-to-end wall-clock including prediction; and assert the cache-key test. Report all five, or the practicality claim is unsupported.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Design and validate a hybrid quantum-classical workflow for kernel physicality.

Answer

Physicality here means one question: is the Gram matrix your quantum device returned actually a valid kernel matrix (symmetric, positive semidefinite, unit diagonal) or a noisy estimate that only resembles one? The workflow is estimate on hardware, validate classically, repair by an audited projection, and report raw and repaired numbers side by side. Assume a fidelity kernel K_ij = |⟨φ(x_i)|φ(x_j)⟩|² estimated with N shots per pair, no mitigation beyond readout correction, and n training samples.

Estimate. Build the kernel with Qiskit's fidelity kernel (qiskit-machine-learning) or PennyLane's qml.kernels, one circuit per pair, N = 8192 shots. Each entry is a probability estimate, so its standard error is σ = √(p(1−p)/N). At p = 0.5 that is √(0.25/8192) ≈ 0.0055. K_ij and K_ji come from independent shot sets, so they differ by ~σ√2 ≈ 0.008 even on perfect hardware. That number is your noise floor; anything larger is a bug, not statistics.

Validate. Four checks, each with a threshold tied to that floor:

checkthresholdbreach means
symmetry ‖K−Kᵀ‖_F / ‖K‖_F< 3σ√2readout or qubit-routing bug
λ_min> −3σgenuinely non-PSD, not shot noise
diagonal |K_ii − 1|< 3σstate-prep or readout bias
repair size ‖K_raw − K_final‖_F / ‖K_raw‖_F< 0.1estimate is mostly noise

Repair. Project onto the PSD cone, then renormalize the diagonal:

Python
import numpy as np

def repair(K_raw):
    K = 0.5 * (K_raw + K_raw.T)          # symmetrize
    w, V = np.linalg.eigh(K)             # ascending eigenvalues
    w_clipped = np.clip(w, 0.0, None)    # project onto PSD cone
    K_psd = (V * w_clipped) @ V.T        # V diag(w_clipped) V^T
    d = np.sqrt(np.diag(K_psd))
    K_final = K_psd / np.outer(d, d)     # unit diagonal
    return K_final, {"min_eig_raw": w.min(),
                     "frob_repair": np.linalg.norm(K_raw - K_final)}

Trace: eigh returns eigenvalues ascending, so w.min() is the smallest. np.clip zeroes the negatives. V * w_clipped broadcasts the eigenvalues across V's columns, giving V·diag(w_clipped); multiplying by V.T reconstructs the matrix. Rescaling by D⁻¹KD⁻¹ with D = diag(d) preserves PSD, since xᵀD⁻¹KD⁻¹x = (D⁻¹x)ᵀK(D⁻¹x) ≥ 0. So the output is a valid kernel by construction.

Failure modes, and how you catch each.

  1. Repair credited to the quantum component. Run the identical repair on a classical RBF kernel over the same features. If test accuracy matches, the device contributed nothing: the projection did the work. Detect by ablation, not by intuition.
  2. Negative eigenvalues hidden. Log λ_min before clipping. Report only the repaired matrix and you cannot distinguish a near-PSD kernel from a badly indefinite one.
  3. Diagonal forced without audit. If raw K_ii deviates by more than 3σ, that is a hardware fault; overwriting it with 1 buries the evidence.
  4. Test block repaired with test structure. Fit the eigenvector basis and clipping threshold on the training kernel only, then apply that same linear map to the test block. Recomputing eigenvectors on test, or choosing the threshold using test labels, leaks.

Trade-offs. Ignoring the problem and feeding an indefinite matrix to an SVM works only if the solver tolerates it; most do not, and results are unpredictable. Ridge regularization (K + λI) restores PSD but shifts every eigenvalue, biasing the kernel. Falling back to a classical kernel is the honest choice when the repair size exceeds 0.1: at that point the quantum estimate is noise wearing a kernel's shape. Report raw and repaired matrices, λ_min, and the Frobenius repair norm together; a reviewer needs all four to judge whether the workflow is sound.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Design and validate a hybrid quantum-classical workflow for dequantization.

Answer

Clarify and assume (first 90 seconds). "Dequantization" here means: take a claimed quantum speedup, hand a classical algorithm the same input access, and see whether the speedup survives. The deliverable is a decision procedure, not a circuit. Assumptions I'd state up front: the input is a classical m×n matrix A (or a low-rank factorisation of one); the target is a scalar estimate or a sample, not the full solution vector; and the access model is the thing under test. The workflow is hybrid because the classical baseline and the quantum candidate share one input model and one output estimator: the comparison is the whole point.

The workflow, five steps.

  1. Write the oracle down. Two primitives: query access Q(i,j) → A_ij in O(log mn); sample access S → row index i with probability ‖A_i‖₂²/‖A‖_F², also O(log mn). Both are realisable classically with a binary tree of partial squared norms: O(mn) to build, O(mn) space, O(log mn) per query or update. That tree is the classical analogue of QRAM, and it is the crux of the exercise.

  2. Write the output spec down. Dequantized algorithms return a sample from the solution vector x, or an additive-ε estimate of xᵀMy. They do not return x. If the requirement is the full vector, neither the quantum nor the dequantized classical algorithm delivers it and the comparison is moot.

  3. Run the classical dequantized baseline first. For low-rank matrix inversion and stochastic regression that is Gilyén–Lloyd–Tang (2018): runtime polynomial in κ, r, 1/ε and only logarithmic in n. For recommendation it is Tang (2018), same shape. Implement the published algorithm, not a dense numpy solve.

  4. Match the access. If the quantum result assumed QRAM and your baseline assumed plain RAM, you have compared nothing. Give both SQ access, or give neither.

  5. Decide. Quantum retains an advantage only when the input is already a quantum state, the output of a prior quantum circuit, because a classical algorithm then cannot obtain SQ access without tomography, which costs Θ(n) copies at best. If the input is a dataset on disk, dequantize.

Worked arithmetic. Take m = n = 10⁶, rank r = 20, condition number κ = 100, target ε = 0.01.

baselineaccessdominant cost
HHL-style quantumQRAM + Hamiltonian-simulation oracleO(κ² log n / ε) ≈ 10⁴ · 20 / 10⁻² = 2×10⁷ gate ops per solve
dequantized classicalSQ treeO(poly(κ, r, 1/ε) · log n) per query, plus O(mn) = 10¹² to build the tree
naive classicalplain RAMO(n³) = 10¹⁸ for a dense solve

The table is the argument: the dequantized query cost is polylog, but the 10¹² preprocessing decides whether you can run it at all. Static matrix queried many times: amortise it. Matrix that changes per query: the advantage is gone.

Failure modes and detection.

  • Loader cost omitted. Instrument build time separately from query time. If build dominates and the matrix is not reused, the speedup is fictional.
  • Asymptotics applied at tiny n. At n = 10³, log₂ n ≈ 10, so the polylog factor is a constant and quantum constants (state prep, error correction) dominate. Benchmark at n = 10³, 10⁵, 10⁷ and look for the crossover; if none appears in the measurable range, report that.
  • Theorem overgeneralised. Dequantization covers low-rank, SQ-access linear algebra. It does not touch Shor or Grover. Check the theorem's hypotheses (low rank, SQ access, scalar output) against your problem before citing it.
  • Weak baseline. Reproduce the paper's reported scaling on its own benchmark before comparing.

Trade-offs. Three credible options: full quantum with QRAM; dequantized classical with an SQ tree; plain classical. The deciding criterion is provenance of the input, quantum state versus stored data, and secondarily whether the matrix is reused enough to amortise the O(mn) tree.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

In a hybrid quantum-classical training loop, how do you handle hardware noise and error mitigation: zero-noise extrapolation, probabilistic error cancellation, readout-error mitigation, and when would you train a noise-aware model versus mitigating only at inference?

Answer

Assumptions. Superconducting transmon QPU: single-qubit gate error ~1e-3, two-qubit ~1e-2, readout error 1–3%, T1/T2 ~100 µs, calibration drift over minutes to hours. Variational loop with parameter-shift gradients.

The 60-second answer. Two questions decide the design. Is the noise stationary over the training window? And can you afford the variance that mitigation adds? Readout mitigation is nearly free and always on. ZNE costs a flat 3–5x shots, so it can live inside a training loop. PEC multiplies the variance of every expectation by γ², so it belongs at inference. If the noise is stationary and the training loop dominates the cost, train noise-aware: put the calibrated noise model in the forward pass and let the optimizer find parameters robust to it. If the noise drifts faster than you can train, or you need parameters that transfer to another device or calibration, train on a noiseless simulator and mitigate at inference.

Readout-error mitigation. Prepare each of the 2^n basis states, measure, build the confusion matrix A with A[i][j] = P(measure i | prepare j), then p_ideal = A⁻¹ p_measured. The full matrix is 2^n × 2^n: 1024 circuits at n=10, 10^6 at n=20. Use the tensored approximation (2n circuits, assumes readout errors are uncorrelated across qubits) or M3, which is matrix-free and scales past 20 qubits. Naive inversion yields negative probabilities; use least-squares with a simplex constraint. Cost is one calibration sweep plus classical post-processing: no extra shots. Failure mode: stale calibration. Readout error drifts on the same timescale as gate error, so re-calibrate every few minutes and watch the diagonal of A.

ZNE. Run the circuit at noise scale factors λ = 1, 3, 5 by unitary folding (U → U U† U) or pulse stretching, fit E(λ), extrapolate to λ = 0. Cost: 3–5x shots, no extra qubits. It works when noise grows linearly with depth. Failure mode: crosstalk and leakage bend E(λ), so the extrapolation overshoots. Detect it from the fit residual, if the quadratic residual exceeds a few percent of the signal, don't trust the extrapolation.

PEC. Decompose each noisy gate's inverse into a quasi-probability distribution over ideal gates, sample circuits, average with signs. Unbiased in expectation. The one-norm γ_i of each gate's decomposition multiplies, and the sampling overhead is (∏γ_i)². For depolarizing noise ρ → (1−p)ρ + (p/3)(XρX+YρY+ZρZ), γ_i = (3/λ_i − 1)/2 with λ_i = 1 − 4p_i/3, so γ_i ≈ 1 + 2p_i and the total overhead ≈ e^{4Σp_i}. 100 gates at p = 0.01 gives e^4 ≈ 55x; 1000 gates at 1% gives e^40 ≈ 2×10^17, which is not a budget, it's a wall. Failure mode: variance explosion. The estimator's standard error grows as γ, so monitor it across sampled circuits and stop when it exceeds the signal you're resolving.

Training vs inference. The variance argument decides it. A parameter-shift gradient already carries shot noise; PEC multiplies each expectation's variance by γ², so gradient SNR drops by γ and you need γ² more shots per step. At γ = 7.5 that's 56x; at γ = 50, 2500x. PEC in the training loop is usually a non-starter. ZNE's flat 3–5x is affordable.

Noise-aware training is right when the noise is stationary over the training window and the training loop dominates the cost: the optimizer can partially invert the noise and lands on parameters robust to it. The risk is drift, if the error rate moves faster than the training window, the model overfits to a noise instance that no longer holds. Benchmark the device before and after training; if the error rate moved by more than the model tolerates, the parameters are stale.

Train noiseless and mitigate at inference when the noise drifts, when the parameters must transfer across devices or calibrations, or when you want PEC. Noise-independent parameters survive a recalibration; noise-aware ones don't.

Worked example: ZNE on one qubit. PennyLane; default.mixed and qml.DepolarizingChannel have been stable since 0.15.

Python
import numpy as np
import pennylane as qml

p = 0.015                                  # depolarizing probability per gate
dev = qml.device("default.mixed", wires=1)

def block(theta, dagger=False):
    qml.RX(-theta if dagger else theta, wires=0)
    qml.DepolarizingChannel(p, wires=0)

@qml.qnode(dev)
def noisy_expval(theta, scale):
    block(theta)
    for _ in range((scale - 1) // 2):      # 1 -> 0 folds, 3 -> 1, 5 -> 2
        block(theta, dagger=True)
        block(theta)
    return qml.expval(qml.PauliZ(0))

theta = np.pi / 3
scales = [1, 3, 5]
vals = [noisy_expval(theta, s) for s in scales]
mitigated = np.polyval(np.polyfit(scales, vals, 2), 0)
print([round(float(v), 6) for v in vals], round(float(mitigated), 6))

Prints [0.49, 0.470596, 0.45196] 0.49999.

Trace: each depolarizing channel scales the Bloch vector by λ = 1 − 4p/3 = 0.98. RX(θ) on |0⟩ gives ⟨Z⟩ = cos θ = 0.5. Folding to scale s applies s channels, so E(s) = 0.98^s × 0.5. A quadratic fit through (1, 0.49), (3, 0.470596), (5, 0.451960) evaluated at 0 returns 0.499990: the ideal value to five decimals.

MethodCorrectsOverheadUse it
Readout mitigationMeasurement error2^n (or 2n) calibration circuits, then classicalAlways
ZNEGate noise3–5x shotsIn the training loop; low, linear noise
PECGate noise(∏γ_i)² ≈ e^{4Σp_i}Inference only, short circuits

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

How do you allocate a finite measurement-shot budget across a hybrid workflow: splitting shots between expectation-value estimation, gradient evaluation, and final inference, and how does shot noise affect convergence and any claimed quantum advantage?

Answer

Fix the total shot budget B first, then allocate by variance. An even split across expectation values, gradients and inference is the default that wastes the most shots.

For a Pauli observable with eigenvalues ±1, the sample mean over S shots has standard error σ = sqrt((1 − ⟨O⟩²)/S). At ⟨O⟩ = 0, σ = 1/√S: 10⁴ shots gives σ ≈ 0.01, 100 shots gives σ ≈ 0.1. A parameter-shift gradient component g = (f(θ+π/2) − f(θ−π/2))/2 needs two circuits, so σ_g ≈ σ/√2 per component: the same order as the expectation value, but multiplied by 2P circuits for P parameters. That product, not the expectation value, is what consumes the budget.

phaseestimatorshots per circuitdriven by
expectation valuemean of ±1 samples10⁴ → σ ≈ 0.01σ = sqrt((1 − ⟨O⟩²)/S)
gradient(f₊ − f₋)/2, 2P circuitssame as f, ×2Pσ_g ≈ σ/√2 per component
inferenceargmax of class expectationsS ≥ 4/m²margin m between classes

Allocate shots proportional to each term's standard deviation (Neyman allocation), with a floor so no term is starved:

python import numpy as np

def allocate(variances, budget, floor=100): v = np.sqrt(np.maximum(variances, 0.0)) if v.sum() == 0: return np.full(len(v), budget // len(v)) s = np.maximum((budget * v / v.sum()).astype(int), floor) return s

Shot noise sets a floor, not just a wobble. SGD with gradient noise variance σ_g² and constant learning rate η converges to a neighbourhood of the minimum whose loss excess is order η σ_g²/2; shrinking σ_g 4× (16× shots) shrinks the floor 4×. The quantity to watch is the per-component SNR, |g_i|/σ_g,i. Near a barren plateau |g| falls exponentially in qubit count while σ_g only falls as 1/√S, so the shots needed to keep SNR > 1 grow exponentially. Shot noise does not cause barren plateaus; it makes them terminal.

Inference is a different regime: one sample, one decision. If the margin between the two class expectation values is m, you need σ ≤ m/2, i.e. S ≥ 4/m². A margin of 0.05 needs ~1,600 shots; a margin of 0.005 needs ~160,000. That arithmetic tells you whether a model's confidence is real or an artefact of too few shots.

Illustrative budget: P = 100 parameters, parameter-shift = 200 circuits per optimizer step, 10⁴ shots each = 2×10⁶ shots/step. At an effective 10⁴ shots/s (queueing plus readout), that is 200 s/step, so 200 steps is ~11 hours. Halving to 5×10³ shots saves 5.5 hours but doubles σ_g and doubles the loss floor: a trade you make deliberately, not by default.

Failure modes and how they show up:

  • Uniform allocation: components with |g_i| ≈ 0 get the same shots as large ones, most of the vector sits at SNR < 1, and the optimizer random-walks. Detect by re-estimating g with different shot seeds: sign flips mean SNR < 1.
  • Variance model ignoring ⟨O⟩²: shots can be cut when the observable sits near ±1 and must be raised near 0. A fixed 10⁴ everywhere over-spends on converged terms and under-spends on the ones still moving.
  • Shot noise misread as a plateau or a bad ansatz: re-run at 10× shots. A plateau stays flat; noise shrinks by √10.
  • Advantage claims: if the classical baseline has sample access, dequantization gives it the same 1/√S dependence, so a constant-factor quantum edge can vanish once total shots × per-shot cost is counted. Report shots-to-target-accuracy, not accuracy alone.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Design and validate a hybrid quantum-classical workflow for uncertainty propagation.

Answer

Opening. "Uncertainty propagation" here means: I have one final scalar (an energy, a fidelity, or a metric derived from circuit outputs) and I need a confidence interval on it that survives shot noise, hardware drift, and nonlinear post-processing. Assumptions: fixed ansatz, Pauli-decomposed observable, parameter-shift gradients, N shots per circuit, no drift within a single run. The workflow is three stages: shots → expectation values, expectation values → gradients and parameters, parameters → final metric: with analytic propagation where the map is smooth and bootstrap where it isn't, then a coverage test to validate the whole thing.

Stage 1: shots → expectation values. For a Pauli observable with ±1 eigenvalues the per-shot variance is 1 − ⟨O⟩², so the standard error at N shots is sqrt((1 − ⟨O⟩²)/N). At N = 4096: ⟨O⟩ = 0.8 gives 0.0094; ⟨O⟩ = 0.4 gives 0.0143. Everything downstream inherits this floor.

Stage 2: expectation values → gradients. Parameter-shift: ∂⟨O⟩/∂θ = (⟨O⟩(θ+π/2) − ⟨O⟩(θ−π/2))/2. It is exact, so it adds no truncation error, but it costs two circuits per parameter and the two estimates are independent, so SE_grad = ½·sqrt(SE₊² + SE₋²) ≈ 0.010 with the numbers above. That SE, not the gradient, decides whether an optimizer step is real. The classical optimizer closes the loop, so its stopping criterion should be SE_grad-based rather than a fixed gradient norm.

Stage 3: parameters → final metric. Nonlinear post-processing (ratios, exponentials, fidelities) breaks linear propagation. Use the delta method with the full covariance, Var(f) ≈ ∇fᵀ Σ ∇f. The off-diagonal is not optional: observables measured in the same basis share shot noise, and dropping it understates the final SE.

Python
import numpy as np
rng = np.random.default_rng(0)
N = 4096
a_shots = rng.choice([1.0, -1.0], N, p=[0.9, 0.1])   # <O_on>  ~ 0.8
b_shots = rng.choice([1.0, -1.0], N, p=[0.7, 0.3])   # <O_off> ~ 0.4

contrast = lambda a, b: (a - b) / (a + b)
a, b = a_shots.mean(), b_shots.mean()
c = contrast(a, b)                                    # 0.333

se_a = np.sqrt((1 - a**2) / N)                        # 0.0094
se_b = np.sqrt((1 - b**2) / N)                        # 0.0143
da, db = 2*b/(a+b)**2, -2*a/(a+b)**2
se_delta = np.hypot(da*se_a, db*se_b)                 # 0.0167

idx = rng.integers(0, N, size=(2000, N))
boot = np.array([contrast(a_shots[i].mean(), b_shots[i].mean()) for i in idx])
se_boot = boot.std(ddof=1)                            # ~0.017

The two agree to a few percent here because the contrast is near-linear over the sampling distribution. They diverge once the denominator can approach zero.

delta methodbootstrap
costO(1) after the run2000 resamples, no extra QPU time
assumptionsmooth f, near-normal estimator, small SEexchangeable shots
fails whendenominator near 0, heavy tailsdrift between shots, few shots
intervalsymmetricpercentile, can be asymmetric

Trade-offs. Analytic propagation is cheap and yields a closed-form sensitivity (∂f/∂⟨O⟩) you can hand to an experimentalist; bootstrap needs no derivative and handles asymmetric intervals, but it assumes shots are exchangeable, which drift violates. Prefer analytic when the map is smooth and you need per-parameter attribution; prefer bootstrap when the metric is a ratio or a max, or when you want run-to-run variance by resampling whole runs.

Failure modes.

  • Shot-noise floor: the optimizer stops improving while SE_grad exceeds the step's predicted gain. Detect by comparing SE_grad to |Δθ|·curvature; the cost is wasted QPU time and false convergence.
  • Readout error: symmetric readout error p shrinks ±1 expectation values by (1 − 2p), a bias larger than shot noise once p > 0.5%. Detect with a calibration circuit on |0⟩ and |1⟩.
  • Ignored covariance: dropping off-diagonal Σ understates the final SE. Detect by comparing the bootstrap covariance to the analytic one; if |ρ| > 0.1, include it.
  • Drift: breaks exchangeability. Detect by interleaving a fixed calibration circuit and plotting ⟨O⟩ against time; if drift exceeds SE, block-bootstrap over time windows.

Validation. Run the full pipeline on a simulator with a known answer, repeat 200 times, and check that the 95% interval covers the truth about 95% of the time. Coverage near 80% means the uncertainty is understated: usually a dropped covariance term or unmodeled drift.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Design and validate a hybrid quantum-classical workflow for data leakage.

Answer

Core answer. "Data leakage" here means any information about the evaluation set reaching the model or the model-selection decision. The quantum layer does not relax that rule; it adds two channels a classical pipeline does not have: encoding statistics and kernel-matrix reuse. So the workflow is: fix the deployment unit, split on it, fit every classical transform inside the fold, encode, train, evaluate at a fixed shot budget, then run a leakage canary that fails loudly if any of that is wrong.

Assumptions: supervised classification, tabular or small-image features, n ≤ 10⁴ samples. Kernel path checked against Qiskit 1.x with qiskit-machine-learning 0.8; variational path against PennyLane 0.3x with PyTorch.

Workflow.

  1. Split on the deployment unit. Group by the entity that will be new at deployment (patient, user, device) with GroupKFold(n_splits=5), or TimeSeriesSplit if deployment is forward in time. Never train_test_split on rows.
  2. Fit classical transforms inside the fold. For angle encoding, MinMaxScaler(feature_range=(0, 2π)) fit on the train fold only. PCA and feature selection likewise. This is the most common leak in hybrid pipelines, because the scaler is usually written before the split.
  3. Encode. Angle encoding: one qubit per feature, value in [0, 2π]. Amplitude encoding: the vector must be unit-norm, so the norm must come from train-fold statistics or a fixed constant. Normalizing by the full dataset's norm leaks the test set's scale.
  4. Quantum kernel path: recompute the matrix per fold. FidelityQuantumKernel.evaluate(Xtr) for train–train, evaluate(Xte, Xtr) for test–train. Slicing a precomputed full matrix is fine; choosing any hyperparameter (feature-map depth, bandwidth) on the test-fold score is not.
  5. Variational path. COBYLA or SPSA updates PQC parameters; the encoding scaling is trainable and must be initialized from train-fold statistics.
  6. Validate. Nested CV, fixed shot budget, fixed seed, plus the canary below.
Python
import numpy as np
from sklearn.model_selection import GroupKFold
from sklearn.preprocessing import MinMaxScaler
from qiskit_machine_learning.kernels import FidelityQuantumKernel

def fold_kernel(X_tr, X_te, feature_map):
    scaler = MinMaxScaler(feature_range=(0, 2 * np.pi)).fit(X_tr)  # train fold only
    qk = FidelityQuantumKernel(feature_map=feature_map)
    return (qk.evaluate(scaler.transform(X_tr)),
            qk.evaluate(scaler.transform(X_te), scaler.transform(X_tr)))

for tr, te in GroupKFold(n_splits=5).split(X, y, groups):
    K_tr, K_te = fold_kernel(X[tr], X[te], fm)
    # fit SVM on K_tr, score on K_te

Trade-offs. Kernel methods are convex and easy to validate, but cost O(n²) circuit evaluations and the matrix must be rebuilt per fold: at n = 10⁴ that is 10⁸ fidelity evaluations, which is why most teams subsample. Variational circuits are cheap at inference but non-convex, and their trainable encoding can absorb leakage. Decide on dataset size: if you cannot afford per-fold kernel recomputation, take the variational path but freeze the encoding scaling.

Failure modes and detection.

failuredetection
entity in both splitshash the entity key; assert zero overlap
temporal future leakassert max(train t) < min(test t)
scaler fit on all datacompare fold scaler mean to global mean; must differ
kernel matrix reused across foldslog shape + hash per fold; must change
shot noise read as signalreport mean ± std over ≥ 5 seeds

Canary (worked, hypothetical figures). Shuffle the labels and rerun the whole pipeline. Expected AUC 0.50 ± 0.03. On a 10,000-sample, 200-patient dataset with ~50 samples per patient: a random row split gives AUC 0.94, GroupKFold gives 0.71, and the shuffled-label control gives 0.51. A gap above ~0.10 between random and group split is entity leakage; a shuffled-label AUC above 0.60 means the leak sits in the features or the split, not the model. That canary is the validation: it fails loudly.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Design and validate a hybrid quantum-classical workflow for nested selection.

Answer

What a strong candidate says first. "Nested selection" here means two loops: an inner loop that chooses a configuration, and an outer loop that estimates how well that choosing procedure generalizes. The hybrid part is that the configuration space spans quantum knobs (ansatz depth, shot count, error mitigation) and classical knobs (optimizer, learning rate, feature map), and both draw on the same budget, so both belong inside the inner loop. I'll assume a fixed labelled dataset, a QPU billed per shot, and a classical baseline the quantum model has to beat.

The workflow.

  1. Split into 5 outer folds. Hold one out; it is never touched until the final score.
  2. Inside each outer-train set, run 4 inner folds over a 24-point grid: ansatz depth L ∈ {1,2,3}; optimizer ∈ {COBYLA, SPSA}; shots ∈ {1024, 4096}; error mitigation ∈ {off, on}.
  3. Pick the config with the best mean inner score.
  4. Refit that config on the full outer-train set, evaluate on the outer-test fold, averaging over 3 seeds.
  5. Report mean ± std across the 5 outer folds. That number, not any single fold, is the claim.
Python
import numpy as np
from sklearn.model_selection import KFold

def fit_qpu(cfg, X, y, seed):
    # stand-in: transpile ansatz(cfg.layers), run cfg.shots per energy eval,
    # optimize with cfg.optimizer for 100 steps, optional ZNE via Mitiq
    ...

grid = [dict(layers=L, optimizer=o, shots=s, mitigation=m)
        for L in (1, 2, 3)
        for o in ("COBYLA", "SPSA")
        for s in (1024, 4096)
        for m in (False, True)]          # 24 configs

outer, inner = KFold(5, shuffle=True, random_state=0), KFold(4, shuffle=True, random_state=0)
outer_scores = []
for tr, te in outer.split(X):
    inner_scores = {i: [] for i in range(len(grid))}
    for itr, ite in inner.split(tr):
        for i, cfg in enumerate(grid):
            m = fit_qpu(cfg, X[tr][itr], y[tr][itr], seed=0)
            inner_scores[i].append(score(m, X[tr][ite], y[tr][ite]))
    best = max(inner_scores, key=lambda i: np.mean(inner_scores[i]))
    outer_scores.append(np.mean([
        score(fit_qpu(grid[best], X[tr], y[tr], seed=s), X[te], y[te])
        for s in (0, 1, 2)]))
print(np.mean(outer_scores), np.std(outer_scores))

What it costs. 24 configs × 4 inner folds = 96 fits per outer fold; ×5 outer folds = 480 fits. At 100 optimizer steps and 4096 shots per step that is 480 × 100 × 4096 ≈ 2×10^8 shots. At ~5,000 shots/s that is roughly 11 hours of QPU time: illustrative, but the point is that the inner loop, not the outer, dominates. Two quantum-specific multipliers: a parameter-shift gradient costs 2 circuit evaluations per parameter (a 24-parameter ansatz → 48 per step, versus 1 for SPSA), and ZNE triples-to-quintuples executions. Shot noise sets the floor: the standard error of a Pauli expectation is ~1/√N, so 1024 shots gives ~0.031 and 4096 gives ~0.016.

Alternatives and when not to. Full nested CV on hardware is the unbiased option and the expensive one. Multi-fidelity screening: evaluate all 24 configs at 1024 shots on a simulator, promote the top 3 to hardware at 4096: cuts QPU cost roughly 8×, at the risk that the noise model doesn't transfer. A single outer split with a fixed validation set is cheapest but the validation set is consumed by selection, so the reported number is optimistic; only acceptable if a genuinely untouched final test set exists. If the ansatz is fixed and nothing is tuned, there is nothing to nest: a plain train/val/test split is correct.

Failure modes and how you catch them.

FailureMechanismDetection
Test peekingouter-test fold leaks into inner selectionmean vs max outer score; a gap larger than the fold std means a leak
Best-seed reportingmax over seeds reported as the estimatereport mean ± std over ≥3 seeds; seed spread > fold spread means the estimate is seed-dominated
Search asymmetryquantum arm gets 24 configs, classical baseline gets 1count configs per arm; equalize, or give the baseline best-of-24
Failed trials droppederrored or timed-out jobs silently excludedlog every submitted job with status; report the failure count; charge failures a fixed penalty
CI ignores selectioninterval computed within one fold as if the config were fixedcompute the interval across outer folds, or use a nested bootstrap

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Design and validate a hybrid quantum-classical workflow for latency tiers.

Answer

Clarify first. "Latency tier" only means something once I know which classical computation has to finish before the next quantum instruction can issue. So I'd ask: is the feedback inside the coherence window, between shots, or between jobs? Everything else follows from that answer.

Assumptions I'd state up front: superconducting transmon hardware (IBM Heron-class, 156 qubits), T1/T2 in the 100–300 µs range, two-qubit gates 20–100 ns, readout 1–2 µs; classical control co-located in the same datacenter as the QPU; no cross-region call in any loop that touches the live state.

The design: three tiers, assigned by where the feedback lands relative to T2.

TierBudgetWhat lives thereWhy it sits there
0: real-time≤ 10 µs, hardmid-circuit measurement, reset, feedforward, small-code syndrome decodingmust complete before T2 decays the state; runs on FPGA/ASIC beside the cryostat
1: near-time1 ms – 10 svariational parameter updates, shot aggregation, error mitigationbetween shots; the state is already measured, so only throughput matters
2: batchminutes – hourscalibration, transpilation, large-scale decoding, simulationbetween jobs; latency is irrelevant, cost and correctness dominate

The boundaries come from arithmetic, not taste. A transmon loses coherence on a ~200 µs scale, so a decision that must act on the live state has roughly 10 µs of slack if you want ten feedforwards and still leave half the coherence budget for the circuit itself. A cross-region RTT is 30–80 ms: four orders of magnitude too slow. Same-datacenter RTT is 0.1–0.5 ms, still too slow for Tier 0 but fine for Tier 1. Kernel-bypass RDMA gets one-way latency to 1–5 µs, which is why Tier 0 hardware is co-located rather than cloud-hosted.

Trade-offs. Control electronics (FPGA/ASIC) buy sub-microsecond feedback but lock you to one vendor's pulse-level API and cost months of engineering per change. Runtime services (Qiskit Runtime sessions, Braket hybrid jobs) give portable primitives and managed queuing at 10s–100s of ms per iteration. Scale-out HPC (Slurm) gives cheap parallel decoding and simulation at minutes of scheduling latency. Choosing wrong costs in both directions: putting a Tier 1 optimizer on Tier 0 hardware burns FPGA time for no fidelity gain, while putting a Tier 0 feedforward on cloud makes the circuit physically impossible, not merely slow.

Failure modes and how I'd detect them.

  • Cloud round trip in the control loop. Symptom: feedforward results indistinguishable from random. Detection: timestamped latency histogram at the controller; if p99 exceeds the 10 µs budget, the tier assignment is wrong.
  • Queue inside the optimizer. Symptom: QPU idle between iterations. Detection: ratio of inter-iteration wall time to QPU execution time; above ~10 means you're paying queue, not compute. Fix: batch the parameter sweep into one session.
  • Calibration expiry. Symptom: fidelity drifts between submission and execution. Detection: run a fixed reference circuit (a 20-qubit GHZ) each session and alert on a >2σ drop from baseline; also compare job start time against the calibration timestamp.
  • Nondeterministic scheduling assumed synchronous. Symptom: the classical state machine desynchronizes. Detection: assert shot-index monotonicity and count gaps.

Validation. Acceptance criteria: (1) measured p99 loop latency ≤ 10 µs for every Tier 0 path; (2) A/B the real-time path against deferred measurement plus post-selection, if feedforward doesn't beat post-selection on fidelity, drop the workload to Tier 1; (3) shot-rate utilization ≥ 80% during a session; (4) reference-circuit fidelity within 2σ of baseline across a 24-hour soak. Run the soak before trusting any latency claim.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Design and validate a hybrid quantum-classical workflow for resource scheduling.

Answer

Two readings here: scheduling classical jobs with a quantum optimizer, or scheduling quantum resources inside a hybrid loop. I'll take the second: the workflow that places variational-algorithm jobs across a pool of QPUs and classical accelerators, because that's where the design decisions bite. Assumptions: one or more superconducting QPUs behind a queue, a classical optimizer per job, and a scheduler that admits, places and batches work.

The unit of work is not a circuit, it's an optimization loop. Each job is a parameterized circuit U(θ) plus a classical cost f(θ) = ⟨ψ(θ)|H|ψ(θ)⟩. The loop: the classical optimizer proposes θ, the QPU executes the circuit with S shots, the result estimates f, the optimizer updates θ, repeat until convergence. The scheduler's job is to keep the QPU busy and the classical optimizer fed, because the QPU is the scarce resource and its latency is dominated by queue and shot acquisition, not gate time.

That's the mechanism that drives every design choice. A transmon two-qubit gate is tens to low hundreds of nanoseconds and readout is sub-microsecond, but a single job submission round trip is seconds. So per-iteration wall time ≈ queue + submission overhead + shots × (circuit + readout). The lever is batching: carry all shots for an iteration in one submission, and pipeline the classical update against the next QPU job.

optimizerevals/iterbest whencost
SPSA2many parameters, noisy hardwareslow convergence, needs step-size tuning
parameter-shift2pfew parameters, true gradient wantedscales with parameter count p
COBYLA~p+1smooth, low-dimensionalsample-hungry, no noise model
Python
# Python 3.11; SPSA gradient step for a variational loop
import numpy as np

def spsa_step(theta, f, a, c, rng):
    delta = rng.choice([-1.0, 1.0], size=theta.shape)
    g = (f(theta + c*delta) - f(theta - c*delta)) / (2*c) / delta
    return theta - a*g

Here f is the QPU-backed cost estimate; each call is one circuit execution.

Illustrative budget: 2 s submission-plus-queue overhead per QPU call, 200 iterations, SPSA's 2 evals per iteration. Unbatched, one submission per eval: 2 × 200 × 2 s = 800 s. Batched, both evals in one submission: 200 × 2 s = 400 s. The classical update is milliseconds, so pipelining it behind the next queue wait costs nothing.

Validation has three layers. For small instances (≤ 20 qubits) compare f(θ*) against exact diagonalization to bound the optimizer's error. Replay a production workload trace through the scheduler and compare makespan and QPU utilization against FIFO and greedy baselines. Then run shadow mode: the scheduler makes decisions alongside production and you diff them before it takes traffic.

Failure modes, each with detection:

  • Stale calibration. A job is admitted against a calibration snapshot but executes after recalibration, so the noise model is wrong. Detect by comparing calibration timestamps at admit and execute; reject on drift past a threshold.
  • Wrong region. Placement violates data-residency policy. Detect with an admission-time policy check on device region.
  • Queue race. Two jobs claim the same QPU slot. Detect with an idempotency key plus optimistic concurrency on slot reservation.
  • Incomparable quality metric. Fidelity compared across devices with different qubit counts and topology. Detect by normalizing against a fixed benchmark circuit.
  • Favored-device cherry-picking. The scheduler always picks the best device, starving others and gaming utilization numbers. Detect by tracking per-device selection share against capacity share.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Design and validate a hybrid quantum-classical workflow for end-to-end cost.

Answer

Assumptions (verify against the provider's current price list and device list: device availability changes, so don't hard-code a device name): H2 at 0.735 Å in STO-3G, Jordan-Wigner → 4 qubits; UCCSD ansatz with 1 variational parameter; superconducting QPU on a managed service; per-task fee $0.30, per-shot fee $0.00035, 1024 shots; 10 s queue wait per task; 0.1 s QPU execution per circuit; 0.5 s one-time transpile; 1 ms classical optimizer step; VM at $0.0104/h.

Design

  1. Encode: Jordan-Wigner, 4 qubits.
  2. Ansatz: UCCSD, 1 parameter.
  3. Transpile: optimization level 3, once, on the parameterized circuit. Parameters are bound per iteration, so transpile cost is paid once, not per circuit.
  4. Execute: submit circuits as tasks; batch the parameter-shift pair of one iteration into a single task.
  5. Optimize: parameter-shift, 2 circuits per parameter per iteration.
  6. Validate: compare the converged energy to classical FCI in the same basis set.

Cost model (worked, illustrative)

100 iterations × 2 circuits = 200 circuits.

Unbatched (1 circuit/task): 200 tasks. Task fees 200 × $0.30 = $60.00. Shot fees 200 × 1024 × $0.00035 = $71.68. Quantum total $131.68. Wall = 0.5 + 200 × (10 + 0.1) + 100 × 0.001 = 2020.6 s.

Batched (2 circuits/task, one parameter-shift pair): 100 tasks. Task fees $30.00. Shot fees $71.68. Quantum total $101.68. Wall = 0.5 + 100 × (10 + 0.2) + 0.1 = 1020.6 s. VM = 1020.6 s × $0.0104/3600 = $0.003. Total ≈ $101.68.

Batching halves both the bill and the wall time because the queue wait is per task, not per circuit. You cannot batch across iterations, iteration k+1 needs iteration k's result, so 2 circuits/task is the ceiling for one serial optimization. Batching further requires independent work: several molecules, several seeds, or a population-based optimizer that evaluates a batch per iteration.

Validation

Instrument every stage with timers and a cost counter; record wall time, QPU time, classical time, monetary cost, and valid results (fraction of iterations whose energy is within chemical accuracy, 1.6 mHa, of FCI). Run five times and compare predicted against actual. The Actual column below is an illustrative run, not a measurement.

ComponentPredictedActual (run 1)
Wall time1020.6 s1043 s
QPU time20 s20.4 s
Classical compute0.1 s0.12 s
Monetary cost$101.68$101.71
Valid results100%100%

Trade-offs

Parameter-shift vs SPSA: at equal iteration count both use 2 circuits per iteration. Parameter-shift costs 2 × (number of parameters) circuits per iteration; SPSA's stays at 2 regardless. For this 1-parameter problem they cost the same, so take parameter-shift: it is exact. SPSA wins once the parameter count is large.

Simulator vs hardware: Aer costs $0 and is right for fixing the ansatz and optimizer, but it does not reproduce device noise. Hardware costs $101.68 and does. Use the simulator for the loop, hardware for the final number.

Failure modes

  • Queue time dominates. At a 2 h queue per task, 100 tasks = 720,000 s = 200 h. Detect by logging queue wait per task; mitigate by batching (fewer tasks), reserved capacity, or the simulator.
  • Optimizer stalls. Energy plateaus above FCI. Detect by tracking energy across iterations; mitigate by restarting from different initial parameters.
  • Noise invalidates the result. Converged energy falls outside the expected window (H2/STO-3G at 0.735 Å is ≈ −1.137 Ha). Detect by comparing to the classical baseline; mitigate with zero-noise extrapolation, which triples executions to 600 circuits = 300 tasks = $305.04.
  • Billing drift. A retried or failed task still bills. Detect by reconciling the provider's billing report against the tracker; mitigate by counting tasks, not circuits.

Cost tracker

Python
class CostTracker:
    def __init__(self, task_fee, shot_fee, shots, circuits_per_task):
        self.task_fee = task_fee
        self.shot_fee = shot_fee
        self.shots = shots
        self.circuits_per_task = circuits_per_task
        self.circuits = 0
        self.tasks = 0
        self.cost = 0.0

    def run_task(self, n_circuits):
        assert n_circuits <= self.circuits_per_task
        self.tasks += 1
        self.circuits += n_circuits
        self.cost += self.task_fee + n_circuits * self.shots * self.shot_fee
        return self.cost

t = CostTracker(task_fee=0.30, shot_fee=0.00035, shots=1024, circuits_per_task=2)
for _ in range(100):          # 100 parameter-shift iterations, 2 circuits each
    t.run_task(2)
print(t.circuits, t.tasks, round(t.cost, 2))

Trace: each run_task(2) adds 0.30 + 2 × 1024 × 0.00035 = 0.30 + 0.7168 = 1.0168. After 100 calls: circuits = 200, tasks = 100, cost = 101.68. Prints 200 100 101.68.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Design and validate a hybrid quantum-classical workflow for advantage claims.

Answer

Core answer

Fix the claim before you take data. The workflow is seven stages: pre-register, generate instances, run the strongest classical comparator, run the quantum device, verify on classically-simulable instances, analyse against the pre-registered threshold, replicate independently. Every failed advantage claim I know of failed because one of those steps was decided after seeing the result.

1. Pre-register five things and hash the file.

Claim type. Statistical advantage: you can sample from a distribution no known classical method can sample from in the same time. Google's 2019 Sycamore XEB claim is the canonical case (Nature 574, 505). Computational advantage: an asymptotic separation in complexity. Practical advantage: better than the best classical method on a problem someone wants solved, at matched cost. IBM's 2023 kicked-Ising result is the reference case (Nature 618, 500). Evidence for one is not evidence for another.

Crossover variable. The knob you sweep to show the gap widens: qubit count, circuit depth, tensor-network bond dimension χ, number of Pauli terms, or device error rate. A single point is not a crossover.

Comparator access. Who runs the classical baseline, on what hardware, with what wall-clock and memory budget. If the quantum team also runs the baseline, say so.

Success threshold. A number. "≥10× speedup at matched output fidelity, CI excluding 1" is a threshold; "shows advantage" is not.

Replication plan. Independent group, separate codebase, separate device.

2. Instances. Locked seed. Development set plus a holdout set; publish the holdout hash and don't touch it until the analysis is frozen.

3. Classical comparator. The strongest current method, not the one from the original paper. For random circuit sampling that's tensor-network contraction (cuTensorNet, quimb) or Pauli-path methods; for chemistry, DMRG or coupled cluster. Tune it, and give it the same wall-clock budget as the quantum run. For variational algorithms (VQE, QAOA) the classical optimizer sits inside the loop, so the comparator has to include it. This is where most claims die: Sycamore's 2019 estimate of 10,000 years on Summit for 53 qubits × 20 cycles was down to hours on a GPU cluster within two years.

4. Quantum run. Record the calibration snapshot, job IDs, and mitigation method (ZNE, PEC, Clifford data regression). Report raw and mitigated numbers.

5. Verification. On instances small enough for exact simulation, compare the quantum output distribution to the exact one. XEB fidelity is the standard cross-check for sampling claims.

6. Analysis. Pre-registered test, corrected for multiple comparisons.

7. Replication. Independent group.

Worked arithmetic. Sweep 20 circuit families, call advantage if any one hits p < 0.05. Family-wise error rate = 1 − 0.95²⁰ ≈ 0.64: you "find" advantage two times in three by chance. Holm–Bonferroni: the smallest p must be below 0.05/20 = 0.0025. Pre-register the family size.

Failure modes and detection.

failuredetection
tiny datasetpre-register instance count; bootstrap CIs; under ~30 instances is a red flag
multiple comparisonspre-register family size; Holm–Bonferroni
test reusedlocked holdout with a published hash
simulator/hardware mixedcalibration snapshot and job IDs required for every reported point
classical baseline stalecurrent code, tuned, run within the last N months
cost boundary narrowedcount the classical outer loop (optimizer, mitigation overhead) in the quantum cost

Trade-offs. Statistical advantage is the easiest claim to defend and the least useful; practical advantage is what a user cares about and the one the classical baseline most often catches up on. Pre-registration kills p-hacking but also kills serendipity: the compromise is two-phase: exploratory on the dev set, confirmatory on the holdout. ZNE is cheap and biased; PEC is unbiased and costs roughly 1/ε² samples, so it is only affordable at small circuit sizes.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Design and validate a hybrid quantum-classical workflow for contribution attribution.

Answer

Contribution attribution means decomposing the end-to-end metric into the part caused by the quantum block, the part caused by classical preprocessing, and the part caused by the extra capacity the hybrid buys. The deliverable is a preregistered ablation ladder with matched-capacity classical baselines and a paired test on held-out data, not a list of artefacts to archive.

Assumptions I would state up front: one fixed dataset and split, one metric (say test AUC), a quantum block that is either a data-reuploading VQC or a quantum kernel, and a classical head with a fixed parameter budget. Move any of those and the attribution moves.

Design. Hold the trainable parameter count constant across every arm so capacity is not the confound, then run four configs:

configquantum blockpreprocessingparamstest AUC (hypothetical)
A0 classical-onlynonefull1,0240.812
A1 random circuitrandom U, frozenfull1,0240.838
A2 trained hybridtrained VQCfull1,0240.847
A3 trained, raw featurestrained VQCnone1,0240.821

Validation. Preregister the ladder and the primary comparison before touching the QPU. Run 5 seeds per config. For each pair, do a paired bootstrap over the 2,000 test points (10,000 resamples) and report the 95% CI on the difference; also report seed-level mean ± sd so one lucky seed cannot carry the claim.

Reading the hypothetical numbers: A2 − A0 = 0.035, CI [0.011, 0.059]. The hybrid beats the matched classical baseline. But A2 − A1 = 0.009, CI [−0.004, 0.022]: training the circuit is not supported; the gain comes from the circuit as a feature map, not from its optimization. A2 − A3 = 0.026, CI [0.008, 0.044]: preprocessing carries most of it. That is the attribution: preprocessing 0.026, circuit-as-feature-map 0.009, remainder noise.

Failure modes and how to detect them.

  • Quantum component not ablated. You compare against a weak classical baseline and call the gap quantum. Detect by requiring matched parameter count and reporting A1.
  • Preprocessing gain misattributed to quantum. Detect with A3 on raw features.
  • Best-seed reporting. Detect by requiring all seeds and the sd, not the max.
  • Test leakage. Fit scaler/PCA inside CV folds only; detect by refitting per fold and confirming the metric does not drop.
  • Uncertainty omitted. Point estimates with no CI; detect by requiring the bootstrap.
  • Resource accounting partial. Count shots, QPU wall-clock and queue time per config. A 0.009 gain that costs 20× the wall-clock is not a win.

Trade-offs. The ladder is cheap, four configs, but order-dependent: the first ablation absorbs shared variance. Shapley-style attribution allocates across components fairly but costs 2^k evaluations; with k = 4 that is 16 configs, still feasible offline. Use the ladder to screen, Shapley when you need a defensible split. Quantum kernel versus VQC: a kernel lets you attribute through the kernel matrix directly; a VQC forces parameter ablation, which is noisier.

Curated: · Written: · Reviewed:

Difficulty: Hard