Top 100 Quantum Software Engineer Interview Questions and Answers
The questions most likely to come up in your Quantum Software Engineer interview, ranked by likelihood, with senior-level answers that cover what the interviewer is listening for.
Curated: · Written: · Reviewed:
Q&A-106Start from the basics: what is a qubit, and how do superposition, entanglement and measurement differ from what a classical bit can do?
A strong candidate answers in three moves: the definition, the one thing that separates a qubit from a bit, and a worked two-qubit example.
A classical bit holds one of two values and you can read it without changing it. A qubit is a unit vector in a two-dimensional complex vector space, written |ψ⟩ = α|0⟩ + β|1⟩ with α, β ∈ ℂ and |α|² + |β|² = 1. |0⟩ and |1⟩ are the computational basis states: the outcomes of a Z-basis measurement. The amplitudes are complex; the probabilities are their squared moduli. That distinction is not pedantry: α = 1/√2 and α = (1+i)/2 both give P(0) = 1/2 under a Z measurement, but they are different states, and the relative phase between them is what a Hadamard or a second rotation turns into a measurable difference.
| state | amplitudes | P(0) | P(1) | Bloch vector |
|---|---|---|---|---|
| |0⟩ | α=1, β=0 | 1 | 0 | (0, 0, 1) |
| |1⟩ | α=0, β=1 | 0 | 1 | (0, 0, −1) |
| |+⟩ | α=β=1/√2 | 1/2 | 1/2 | (1, 0, 0) |
| |i⟩ | α=1/√2, β=i/√2 | 1/2 | 1/2 | (0, 1, 0) |
Superposition is not a hidden value. A classical bit in a sealed envelope is 0 or 1 with 50% odds; |+⟩ has no definite Z value, and measuring X instead returns +1 with certainty. Which basis you measure in decides whether the state looks random or definite: that is the operational content of superposition.
The Bloch sphere makes this concrete: every pure single-qubit state is a unit vector (sinθ cosφ, sinθ sinφ, cosθ) with α = cos(θ/2), β = e^{iφ} sin(θ/2). Global phase is unobservable; φ is not. Mixed states sit inside the sphere, radius < 1.
Entanglement is a joint property: a two-qubit state is entangled when it cannot be factored as |a⟩ ⊗ |b⟩. Take |Φ+⟩ = (|00⟩ + |11⟩)/√2. Each qubit alone is maximally mixed, its reduced density matrix is I/2, yet the outcomes are perfectly correlated. Simulating 1000 shots:
import numpy as np
psi = np.array([1, 0, 0, 1]) / np.sqrt(2) # |00> + |11>
p = np.abs(psi) ** 2 # [0.5, 0, 0, 0.5]
rng = np.random.default_rng(0)
counts = np.bincount(rng.choice(4, size=1000, p=p), minlength=4)
print(counts) # ~[500, 0, 0, 500] for keys 00, 01, 10, 11
Measure both qubits in X instead and you get the same perfect correlation. That second basis is the point: a shared classical random variable fixed at preparation can reproduce the Z correlation but not both, which is what CHSH turns into an inequality.
Measurement is projective and non-unitary. Measuring Z on α|0⟩ + β|1⟩ returns 0 with probability |α|² and leaves the state |0⟩; the amplitudes are gone. You cannot copy the state first, no-cloning, so one shot is all you get, and statistics come from repeating the preparation.
The follow-up is always whether the correlation is a channel. It is not. Alice's measurement gives her a random bit and updates the joint state, but Bob's marginal is I/2 before and after; his local statistics do not move. Learning the correlation requires comparing classical records, which is why teleportation spends two classical bits.
Curated: · Written: · Reviewed: —
Q&A-101A colleague says a quantum computer evaluates every answer at once and picks the right one. What actually makes the right answer come out?
The 90-second version. No algorithm reads out all 2^n answers: measurement returns one bitstring, sampled with probability |a|². What a quantum algorithm does is arrange that every computational path leading to a wrong outcome arrives with amplitudes that cancel, and every path leading to the right outcome arrives in phase. That is interference, and it is the whole source of the speedup. The "tries all answers at once" story describes the state preparation, not the algorithm: after the oracle the register does hold all 2^n values of f(x), but in relative phases you cannot read. Interference converts those phases into a bias in the one measurement you get.
Deutsch-Jozsa, with the arithmetic. n = 1, f: {0,1} → {0,1}. Prepare |0⟩|1⟩, Hadamard both: (|0⟩+|1⟩)/√2 ⊗ (|0⟩−|1⟩)/√2. The oracle |x⟩|y⟩ → |x⟩|y⊕f(x)⟩ kicks the phase back onto the input register, |x⟩ → (−1)^f(x)|x⟩, so that register is a₀|0⟩ + a₁|1⟩ with a_x = (−1)^f(x)/√2. Final Hadamard on that qubit:
| outcome | amplitude | constant f | balanced f |
|---|---|---|---|
| 0 | (a₀+a₁)/√2 | ±1 | 0 |
| 1 | (a₀−a₁)/√2 | 0 | ±1 |
Two paths reach outcome 0: the |0⟩ path and the |1⟩ path, and they add. Constant f makes them add to 1; balanced f makes them cancel to exactly 0. One query decides it, where the best deterministic classical algorithm needs 2^(n−1)+1 queries in the worst case.
Grover, same mechanism, different geometry. N = 4, one marked item, uniform amplitudes 1/2. The oracle flips the marked amplitude's sign: (1/2, 1/2, 1/2, −1/2). Diffusion reflects every amplitude about the mean, a → 2ā − a, with ā = 1/4: the marked entry goes to 2(1/4) − (−1/2) = 1, the other three to 2(1/4) − 1/2 = 0. One iteration, exact answer, probability 1. In general the marked amplitude is sin((2k+1)θ) with sinθ = √(M/N), which is why the speedup is √N and not N: each iteration rotates the amplitude vector by a fixed angle, and you cannot rotate past the target.
Why classical probability cannot do this. A probability vector is non-negative, and every classical operation is a stochastic matrix, which maps non-negative vectors to non-negative vectors. Two paths to the same outcome can only add. Quantum amplitudes are signed, in general complex, and the measured probability is |Σ paths|², so paths can subtract. That is the entire difference, and it is why the classical analogue of "evaluate f on all inputs" is a randomized algorithm that returns a uniformly random answer.
Failure modes. Interference lives in relative phase, so dephasing (T2, not T1) is what kills these circuits; a global phase is unobservable and harmless. A sign error in the oracle inverts the pattern: Deutsch-Jozsa then returns the wrong answer with certainty, which is why I validate the oracle on a known constant and a known balanced instance before trusting a run. And interference is not free speedup: it only helps where the problem's structure gives you a pattern to cancel against, which is why there is no generic quantum speedup for arbitrary search.
Curated: · Written: · Reviewed: —
Q&A-2A colleague describes a qubit in superposition as secretly being 0 or 1 with equal odds. What is wrong with that?
The odds are right; the picture behind them is wrong. A superposition is a complex amplitude vector, and the relative phase between amplitudes is physical. A probability distribution over 0 and 1 has nowhere to put that phase.
Take |+⟩ = (|0⟩ + |1⟩)/√2. Measure in the Z basis and you get 0 half the time, 1 half the time: identical to a coin flip. That is the only place the two stories agree. Now apply a Hadamard and measure again. H|+⟩ = |0⟩, so the coherent state returns 0 with probability 1. The coin flip stays at 50/50.
| Preparation | P(0) in Z | P(0) in X |
|---|---|---|
| |+⟩ | 0.50 | 1.00 |
| ½|0⟩⟨0| + ½|1⟩⟨1| | 0.50 | 0.50 |
In density-matrix terms the difference is the off-diagonal entries. The coherent state is ρ = [[½, ½], [½, ½]]; the classical mixture is ρ = [[½, 0], [0, ½]]. Those off-diagonals are the coherences, and they are exactly what interference-based algorithms consume. Grover's diffusion step, the QFT in Shor's algorithm, Deutsch–Jozsa: all of them work by arranging amplitudes to add or cancel. You cannot cancel probabilities.
Where the colleague's intuition is safe: if you only ever measure in one fixed basis and never apply a basis change, the two descriptions give identical predictions, and treating the qubit as an unknown classical bit is a fine bookkeeping shortcut. That is the ensemble interpretation: the state describes statistics over many identically prepared runs, not a definite value per run. It stays consistent as long as you do not ask about single-shot counterfactuals.
The other intuition people reach for is "it's both at once." That is usable when reasoning about correlations before measurement: a control qubit in |+⟩ entangled with a target gives you both branches in the joint state, and that is how you read a phase-kickback circuit. It breaks the moment you assume both branches are independently readable. You cannot observe both, and no-cloning means you cannot copy the unknown state to try.
The failure mode worth naming is decoherence. Coupling to the environment kills the off-diagonal terms on a timescale T2, and the state becomes an effective classical mixture in the pointer basis. That is the one regime where "secretly 0 or 1" is approximately true, but it is a physical process with a rate, not a description of superposition itself. If you believed superposition were always ignorance, you would predict that a Hadamard on a decohered qubit still returns 0 deterministically. It does not; it returns 50/50, and that is how T2 is measured.
The strongest form of the argument is Bell. If the qubit carried a definite value, a local hidden-variable model would bound the CHSH correlator at 2. Entangled-photon and superconducting-qubit experiments reach S ≈ 2.8, close to the Tsirelson bound of 2√2 ≈ 2.83. No local definite-value story reproduces that.
So the colleague's picture is a valid shortcut for one-basis statistics and a wrong model of the state. The test that separates them is a basis change.
Curated: · Written: · Reviewed:
Q&A-5Does the no-cloning theorem stop you from preparing two qubits in the same state?
I would treat no-cloning and what it does not forbid as a claim that has to survive being recomputed from the raw counts.
No-cloning forbids a single unitary that copies an arbitrary unknown state, because such a map cannot be linear. It says nothing about preparing two qubits from the same known classical description, which is what a state-preparation routine does every time it runs.
Concretely, distinguish the three cases explicitly in design discussions: re-preparing from a description is free, copying a basis state with a CNOT works for basis states only, and duplicating an unknown state is impossible.
The reason for that specificity is a failure I have seen: A protocol design assumed a received unknown state could be duplicated so one copy could be measured and the other kept; the implementation used a CNOT, which entangles rather than copies, and the retained qubit was maximally mixed with fidelity 0.5 to the original.
What a CNOT does to two inputs.
| Input | Output | Copy achieved |
|---|---|---|
| zero state | both zero | yes |
| plus state | Bell pair | no |
I would not consider it settled without evidence: Apply the proposed copy operation to a state in the X basis and check the reduced state of each output rather than testing on basis states only.
A CNOT copies labels, not states.
Curated: · Written: · Reviewed:
Q&A-9Can you draw your two entangled qubits on Bloch spheres?
Where candidates lose the interview on the Bloch sphere and its limits is treating an exact-state result as a device result.
You can draw their reduced states, but those two pictures do not contain the joint state. The Bloch representation is complete for one qubit and loses exactly the correlations that make a multi-qubit state interesting.
Concretely, use Bloch pictures for single-qubit calibration and gate tuning, and switch to joint quantities such as parity expectations, a density matrix or a witness the moment more than one qubit is in scope.
The reason for that specificity is a failure I have seen: A debugging session drew both halves of a Bell pair at the origin of their Bloch spheres, concluded the qubits were dead, and replaced a working calibration with one that produced a genuinely mixed state at fidelity 0.61.
Same local pictures, different joint states.
| Joint state | Bloch vector A | Entangled |
|---|---|---|
| Bell pair | origin | yes |
| classical mixture of 00 and 11 | origin | no |
I would not consider it settled without evidence: Show that two very different joint states can give identical single-qubit Bloch vectors before relying on the picture for a multi-qubit diagnosis.
Two spheres are not a two-qubit state.
Curated: · Written: · Reviewed:
Q&A-7When is a statevector the wrong object to describe your qubits?
The 90-second answer. A statevector is the wrong object the moment the state stops being pure. Three cases cover nearly everything you hit in practice: you want the state of one qubit inside an entangled register; the state is an ensemble. You are averaging over shots, or over a stochastic error model; or the qubits have leaked information into an environment you are not tracking. In all three the right object is a density matrix ρ: Hermitian, positive semidefinite, trace one. The cheap discriminator is purity, Tr(ρ²): exactly 1 for a pure state, strictly less for a mixed one.
But "use a density matrix" is not the whole answer, because ρ costs 4ⁿ complex entries against 2ⁿ for a statevector. That 2ⁿ blow-up is the reason most noisy-circuit work does not use one.
Why the statevector fails. A statevector is a rank-1 density matrix, |ψ⟩⟨ψ|. The partial trace of a pure bipartite state is generally mixed, so the moment you ask about a subsystem of an entangled register you have left the statevector's domain. Noise channels are CPTP maps that take a pure state to a mixed one; if you discard the environment, the reduced state is mixed even though the joint state is pure. And a classical ensemble of pure states: "the qubit is |0⟩ with probability p": is mixed by construction.
The trade-off. Density-matrix simulation is exponentially more expensive, and for noisy circuits the statevector is often still the right choice:
| n | statevector (16·2ⁿ B) | density matrix (16·4ⁿ B) |
|---|---|---|
| 20 | 17 MB | 18 TB |
| 25 | 537 MB | 18 PB |
| 30 | 17 GB | 18 EB |
So ρ caps out around n ≈ 15 on a 32 GB node while a statevector reaches n ≈ 30. Two methods keep the cheaper cost:
- Quantum trajectories (Monte Carlo wavefunction). Sample the noise, evolve a pure statevector per shot, average the observables. Cost is O(K·2ⁿ) for K shots, with statistical error falling as 1/√K. You get the measurement statistics without ever forming ρ.
- Stabilizer / Pauli-frame simulation. For Clifford circuits with Pauli noise, a tableau simulator such as Stim tracks the state in O(n²) time and memory per gate and samples shots exactly: this is how surface-code decoding datasets are generated at scale.
Reach for the density matrix when you need the exact unconditional state, or a nonlinear functional of it (purity, entanglement entropy, fidelity to a target) and n is small enough to afford it.
Checking it. Purity and the partial trace are a few lines:
import numpy as np
def purity(rho):
return np.real(np.trace(rho @ rho))
psi = np.zeros(4, dtype=complex)
psi[0] = psi[3] = 1 / np.sqrt(2) # Bell state
rho = np.outer(psi, psi.conj())
print(purity(rho)) # 1.0
m = rho.reshape(2, 2, 2, 2) # (i0, i1, j0, j1)
rho0 = np.trace(m, axis1=1, axis2=3) # trace out qubit 1
print(purity(rho0)) # 0.5
Failure modes. The one I have actually seen: a noise study renormalized its output back to a unit vector after each channel application. That silently projects every mixed state onto a pure one, and the decoherence curve stayed flat at fidelity 0.99 for 40 gate layers. The same class of bug appears when a reduced state is reported as a ket, or when fidelity is computed against a statevector that was never mixed. Detect it by asserting purity falls as noise is applied, and by cross-checking a trajectory average against ρ for n ≤ 12, where both are affordable.
Curated: · Written: · Reviewed:
Q&A-6How many qubits can you simulate exactly on a 256 GB machine?
33 qubits, with a dense statevector in double precision. 34 qubits needs 2^38 bytes = 274.9 GB (256 GiB), which is the whole machine with nothing left for the OS, the runtime, or the buffers a gate application needs. So the practical ceiling is 33, and even that is tight.
The arithmetic: a statevector stores 2^n complex amplitudes, and a complex128 is 16 bytes (two float64).
- 2^33 × 16 = 2^37 bytes = 137.4 GB (128 GiB): fits.
- 2^34 × 16 = 2^38 bytes = 274.9 GB (256 GiB): does not fit, and would not fit even on a 256 GiB box, because the process needs more than the array.
| Qubits | Amplitudes | Statevector (complex128) | Density matrix (4^n × 16 B) |
|---|---|---|---|
| 16 | 6.6e4 | 1.0 MB | 68.7 GB |
| 17 | 1.3e5 | 2.1 MB | 274.9 GB |
| 30 | 1.07e9 | 17.2 GB | 1.8e19 B (18 EB) |
| 33 | 8.59e9 | 137.4 GB | 1.2e21 B |
| 34 | 1.72e10 | 274.9 GB | 4.7e21 B |
Two things follow from that table. First, if you need a density matrix, the natural representation for a noisy simulation, the limit drops to 16 qubits (68.7 GB); 17 qubits is 274.9 GB and out. Second, the wall is hard: there is no graceful degradation, you get an allocation failure or the OOM killer, not a slower run.
What actually bites at 33 qubits is bandwidth, not capacity. Every gate layer reads and writes the full 137 GB. At a realistic 100 GB/s of memory bandwidth that is ~2.7 s per layer, so a 100-layer circuit is minutes of pure memory traffic. If you see the run slow to a crawl rather than fail, you are swapping, and the fix is fewer qubits, not more patience.
Alternatives when 33 is not enough, each with its own exactness caveat:
- Stabilizer simulation is exact for Clifford circuits and handles thousands of qubits in kilobytes, because it tracks the Pauli frame instead of amplitudes. It is useless the moment a non-Clifford gate (T, arbitrary rotation) appears.
- Tensor networks are exact for low-entanglement circuits and can reach 50+ qubits, but the cost is set by the bond dimension you cap, and the result is only exact if the cap is not truncating.
- Single precision (complex64, 8 bytes) doubles the width to 34 qubits at 137 GB, at the cost of accumulated rounding error over deep circuits. Worth it only for shallow ones.
- Distributed statevector across N nodes buys log2(N) qubits, but every non-local gate becomes an all-to-all communication step.
Before scheduling a run, compute 2^n × 16 (or 4^n × 16) and compare it to the machine's real free memory, not its nameplate. A 33-qubit job wants roughly 1.5× the array size in headroom, so on a 256 GB box it is the last width that runs comfortably.
Curated: · Written: · Reviewed:
Q&A-8Each qubit of your Bell pair looks maximally mixed. Was the state prepared badly?
No. A maximally mixed qubit is what maximal entanglement looks like from one side. For |Φ⁺⟩ = (|00⟩+|11⟩)/√2, tracing out B gives ρ_A = I/2, so every single-qubit measurement returns 50/50 in any basis. That marginal is identical to a fair coin, and identical to the classical mixture (|00⟩⟨00| + |11⟩⟨11|)/2. Marginals cannot separate those cases, so they cannot judge the preparation.
Judge the joint state instead. Two measurement families do that, and they answer different questions.
| Measurement | Settings | What it gives |
|---|---|---|
| ZZ and XX parity | 2 | Witness: ⟨ZZ⟩+⟨XX⟩ > 1 certifies entanglement, and the sign pair identifies which Bell state |
| XX, YY, ZZ | 3 | Fidelity F = (1 + ⟨XX⟩ − ⟨YY⟩ + ⟨ZZ⟩)/4 |
Deciding criteria. If the question is "is this pair entangled at all?", two parity measurements suffice: for any separable state ⟨ZZ⟩+⟨XX⟩ ≤ 1 (Cauchy–Schwarz on the Bloch vectors of a product state, extended by convexity), so a measured sum above 1 is a certificate. If the question is "how good is it?": a fidelity number for a spec, or a comparison against a threshold like 0.99 for a fault-tolerance budget: you need the third basis. ZZ and XX alone only lower-bound F at (⟨XX⟩+⟨ZZ⟩)/4, which is weak.
Worked numbers. ⟨XX⟩ = 0.98, ⟨ZZ⟩ = 0.98, ⟨YY⟩ = −0.96 gives F = (1 + 0.98 + 0.96 + 0.98)/4 = 0.98. Drop YY and the same data guarantees only F ≥ 0.49: below the 0.5 separable ceiling, so it certifies nothing about fidelity even though the witness sum 1.96 > 1 still certifies entanglement.
Failure modes:
- Testing qubits one at a time. An acceptance test that measured each qubit separately, saw 50/50 on both, and rejected the device would have discarded a pair with joint fidelity 0.94. A perfect Bell pair and a fully depolarized pair give the same marginals.
- One basis only. ZZ alone cannot separate |Φ⁺⟩ from the classical mixture (both give ⟨ZZ⟩ = 1); XX alone cannot separate |Φ⁺⟩ from |Ψ⁺⟩ (both give ⟨XX⟩ = 1). You need both.
- Basis misalignment. A rotated XX basis lowers ⟨XX⟩ and mimics decoherence. Calibrate the joint basis with the same pulse sequence used for the data.
- Readout error. A 2% per-qubit readout error pulls measured ⟨ZZ⟩ to (1 − 2·0.02)² ≈ 0.92 and shows up as infidelity. Correct for it before quoting F.
Curated: · Written: · Reviewed:
Q&A-10How do you decide whether a two-qubit pure state is entangled?
The 60-second answer. Write the state in the computational basis as |ψ⟩ = a|00⟩ + b|01⟩ + c|10⟩ + d|11⟩ and pack the amplitudes into the 2×2 coefficient matrix M = [[a, b], [c, d]]. The state is a product |ψ_A⟩⊗|ψ_B⟩ exactly when det M = ad − bc = 0. If ad − bc ≠ 0 it is entangled, and the concurrence C = 2|ad − bc| says how much. For two qubits there is only one nontrivial cut (qubit 1 vs qubit 2), so that single number is the whole answer.
Why the determinant decides it. If |ψ⟩ = (α|0⟩+β|1⟩)⊗(γ|0⟩+δ|1⟩), then a = αγ, b = αδ, c = βγ, d = βδ, so ad − bc = αγβδ − αδβγ = 0. Conversely, ad = bc forces M to have rank 1, so M = uvᵀ and |ψ⟩ = (u₀|0⟩+u₁|1⟩)⊗(v₀|0⟩+v₁|1⟩). The rank of M is the Schmidt rank: 1 means product, 2 means entangled.
The reduced-state test is the same fact. ρ_A = MM†, and tr(ρ_A²) = 1 − C²/2. So tr(ρ_A²) = 1 iff C = 0 iff separable: the reduced state is pure exactly when the whole state factors.
Worked example. Bell state |Φ⁺⟩ = (|00⟩+|11⟩)/√2: a = d = 1/√2, b = c = 0, so ad − bc = 1/2 and C = 1. Maximally entangled. ρ_A = MM† = I/2, tr(ρ_A²) = 1/2 < 1. Product state |0⟩⊗|+⟩ = (|00⟩+|01⟩)/√2: a = b = 1/√2, c = d = 0, so ad − bc = 0 and C = 0. ρ_A = diag(1, 0), tr(ρ_A²) = 1.
Which test to use. For two qubits every test is O(1), so pick the cheapest: the determinant is four amplitudes and one subtraction of two products, doable by hand. Reduced-state purity needs forming MM† and squaring it, roughly a dozen flops. Schmidt rank via SVD of the 2×2 M is overkill here but is the version that generalizes: across a cut of dimension d it costs O(d³), as does reduced-state purity, while the determinant only exists for 2×2.
Where the criterion breaks. It holds for pure states only. A mixed two-qubit state can be entangled with no pure-state determinant to check: the Werner state ρ = p|Φ⁺⟩⟨Φ⁺| + (1−p)I/4 is entangled for p > 1/3. For mixed states use concurrence via Wootters' formula, C = max(0, λ₁−λ₂−λ₃−λ₄) with λᵢ the square roots of the eigenvalues of ρρ̃, or the PPT/Peres–Horodecki criterion, which is necessary and sufficient for 2×2 and 2×3 systems but not beyond. Finally, threshold the arithmetic: a state that should be product can give ad − bc ≈ 1e-16 in floating point, so treat |ad − bc| below a small epsilon as zero rather than reporting spurious entanglement.
Curated: · Written: · Reviewed:
Q&A-26Your two qubits agree on every measurement. Is that entanglement?
Depends on what "every measurement" means, and that ambiguity is the question.
If the qubits agree along every axis (Z, X, and everything between) that is a maximally entangled state, not merely an entangled one. Only |Φ⁺⟩ = (|00⟩+|11⟩)/√2, up to local rotations, gives perfect agreement for every measurement direction. No separable state does that.
If they agree in the measurements you actually ran, and those were all along one axis, you have shown correlation, not entanglement. The separable mixture ρ = ½|00⟩⟨00| + ½|11⟩⟨11| gives perfect Z agreement and zero X agreement. The two preparations are indistinguishable in Z alone.
Mechanism. A Z measurement on the mixture returns 00 or 11 with equal probability, so the outcomes always match. Rotate both qubits by 45° and the mixture's two branches become independent coin flips: the agreement evaporates. The Bell state is a coherent superposition, not a mixture: rotating both qubits rotates the whole state, and the correlation survives. That coherence is what the mixture lacks, and it is what the second basis detects.
The operational test. Measure parity in at least two mutually unbiased bases. A clean quantitative version: for any separable two-qubit state, Σ over i∈{x,y,z} of ⟨σ_i⊗σ_i⟩² ≤ 1. A Bell state gives 3. Anything above 1 is entangled: a witness, not a complete test.
The device-independent test is CHSH: S = E(a,b) − E(a,b′) + E(a′,b) + E(a′,b′). Local hidden-variable models cap |S| ≤ 2; a Bell state reaches 2√2 ≈ 2.83 at the optimal angles (0° and 90° on one side, 45° and 135° on the other), where each correlator is ±1/√2 ≈ ±0.707.
| Preparation | ⟨ZZ⟩ | ⟨XX⟩ | CHSH S |
|---|---|---|---|
| Bell pair | +1 | +1 | 2.83 |
| Classical mixture | +1 | 0 | ≤ 2 |
| Werner state, p = 0.5 | +0.5 | +0.5 | 1.41 |
Failure modes. Photon loss forces the fair-sampling assumption: you only count coincidences, so undetected pairs can fake the correlation; closing the detection loophole needs high-efficiency detectors. The locality loophole needs the basis choice to be spacelike separated from the other measurement. Basis drift and dark counts shift the measured S, so a real result is reported with error bars, not a bare number. And the Werner row is the trap: at p = 0.5 the state is entangled (p > 1/3) yet violates neither CHSH nor the witness, so a null result never proves separability.
Trade-offs. CHSH is device-independent but needs loophole closure and many trials, and only certifies above p = 1/√2 ≈ 0.707. The Σ⟨σ_i⊗σ_i⟩² witness is cheap, three settings, but state-dependent and incomplete. Full state tomography reconstructs ρ and gives concurrence or negativity, but assumes trusted devices and costs many measurements.
So: agreement in one basis is a correlation. Agreement in every basis is a Bell state, but you cannot measure every basis, so you run two or three MUBs, compute S or the witness, and report the number with its error bars.
Curated: · Written: · Reviewed:
Q&A-25Can you send two classical bits by transmitting one qubit?
Yes: provided Alice and Bob already share a Bell pair. Alice encodes two classical bits into her half of the pair and sends that single qubit to Bob, who recovers both bits with certainty. That is superdense coding. Without the shared pair the answer is no: the Holevo bound caps one qubit at one classical bit of accessible information, and no measurement on that qubit alone extracts more.
Mechanism. The pair starts in |Φ+> = (|00> + |11>)/√2, Alice holding qubit A, Bob qubit B. Alice encodes her two bits by applying one of four Pauli operations to A alone:
| Bits | Operation on A | Resulting Bell state |
|---|---|---|
| 00 | I | (|00> + |11>)/√2 |
| 01 | X | (|10> + |01>)/√2 |
| 10 | Z | (|00> − |11>)/√2 |
| 11 | Z then X | (|10> − |01>)/√2 |
The four results are the four Bell states, and they are mutually orthogonal. Orthogonal states are perfectly distinguishable, so Bob can identify which one he holds in a single measurement, and each outcome maps to one of the four bit strings. A local operation on one qubit has moved the pair between four globally distinguishable states.
Decoding is a fixed two-gate circuit: CNOT with A as control and B as target, then Hadamard on A, then measure both qubits in the computational basis.
Trace for the 11 case. Alice applies Z to A first. Z leaves |0> alone and sends |1> to −|1>, so the |00> term is unchanged and the |11> term flips sign: the pair becomes (|00> − |11>)/√2. She then applies X to A, which swaps |0> and |1>: |00> → |10> and |11> → |01>, giving (|10> − |01>)/√2. Bob's CNOT flips B only when A is 1, so |10> → |11> and |01> → |01>, leaving (|11> − |01>)/√2 = ((|1> − |0>)/√2) ⊗ |1> = −|−>|1>. Hadamard on A sends |−> to |1>, so the state is −|11>. Both qubits measure 1 and Bob reads 11. The other three cases land on 00, 01 and 10 the same way.
Trade-offs. Count qubits end to end and the advantage disappears: one qubit to distribute the pair, one to transmit, two qubits for two bits. What superdense coding buys is scheduling, not compression. The entanglement can be generated and stored when the channel is quiet, and the lossy transmission happens later, on demand, in one shot. It also means only the encoded qubit has to survive the noisy link; the pair can be purified beforehand.
Failure modes. The scheme is only as good as the pair. Decoherence between distribution and use degrades the state toward a mixture, Bob's four outcomes stop being orthogonal, and his error rate rises, so measure pair fidelity (CHSH or Bell-state tomography) and pair generation rate, and bound throughput by those rather than by the qubit channel. Bell-state measurement is the second limit: with linear optics and no ancillas you can distinguish only two of the four Bell states, so a photonic implementation either halves the rate or needs extra photons and feed-forward. Detection is direct: send known bit strings and compare the decoded error rate against measured pair fidelity.
Put numbers on it. If the entanglement source yields usable pairs at 1.2 kHz while the classical channel runs at 10 MHz, the scheme is four orders of magnitude slower than simply sending the bits: the pair rate, not the qubit transmission, is the ceiling.
Curated: · Written: · Reviewed:
Q&A-24What does teleportation actually move, and what does it require?
Quantum teleportation moves an unknown quantum state, the complex amplitudes of a qubit, from one physical qubit to another. It does not move the particle itself. The original qubit's state is destroyed in the process (no-cloning), and the receiving qubit must already be entangled with the sender's qubit.
Requirements per qubit teleported:
- One pre-shared Bell pair (maximally entangled pair of qubits).
- Two classical bits sent from sender to receiver.
- Local operations: a Bell measurement at the sender, and one of four Pauli corrections (I, X, Z, XZ) at the receiver, chosen by the two classical bits.
The sender measures the unknown qubit and their half of the Bell pair in the Bell basis, obtaining two classical bits. They send those bits to the receiver. Until the bits arrive, the receiver's qubit is in a maximally mixed state: it carries no information about the original. The bits are on the critical path; teleportation is not faster-than-light.
When is teleportation worth it versus direct transport? Direct transport sends the physical qubit through a quantum channel. For short distances and low loss, direct transport is simpler: no entanglement distribution, no classical channel, no correction gates. But loss scales exponentially with distance. Telecom fiber runs about 0.2 dB/km, so 100 km costs 20 dB: a transmission probability of about 10^-2, i.e. roughly 1% of photons survive. At 1000 km the same fiber costs 200 dB, about 10^-20. Teleportation, combined with quantum repeaters, can extend range: you create entanglement between distant nodes via entanglement swapping, then teleport. The cost is one Bell pair and two classical bits per qubit, plus the infrastructure to distribute and purify entanglement.
Gate teleportation is a variant: instead of moving a state, you teleport a gate onto a state using a resource state. For example, a T gate can be applied by teleporting a magic state and applying a correction. This is used in fault-tolerant quantum computing, where non-Clifford gates are expensive.
When the entanglement cost is not justified: if you have a short, low-loss link and only need to move a few qubits, direct transport wins. If you need to move many qubits, the entanglement budget (one Bell pair per qubit) and classical bandwidth (2 bits per qubit) may dominate. Also, if you cannot distribute entanglement reliably, teleportation is impossible.
A concrete failure mode: a distributed design assumed teleportation removed the classical channel, so its latency model omitted the round trip. Measured end-to-end, the protocol was bounded by a 40 ms classical hop that the design had priced at zero. (Hypothetical figures.) Detection: trace the protocol including the classical transmission and the receiver's conditional corrections, and time it.
Resource table per qubit teleported:
| Resource | Quantity | Consumed |
|---|---|---|
| Bell pair | 1 | yes |
| classical bits | 2 | yes |
| original qubit state | 1 | destroyed |
The classical bits are on the critical path.
Curated: · Written: · Reviewed:
Q&A-34A stakeholder asks whether entanglement gives you an instantaneous channel. What do you say?
Short answer: no. Entanglement correlates outcomes; it does not carry a message. Alice's local statistics are identical no matter what Bob does, so nothing Bob does is detectable at Alice's end until he tells her over a classical channel, and that channel is bounded by c. To a stakeholder: the correlation is real, but it is only visible when you compare notes, and comparing notes is a classical round trip.
Why, in one calculation. Take |Φ+> = (|00> + |11>)/√2, Alice holding A, Bob holding B. Alice's reduced state is ρ_A = Tr_B|Φ+><Φ+| = I/2. That is the whole argument: the reduced state is maximally mixed and does not depend on B's basis, so every measurement Alice makes returns 0 or 1 with probability 1/2.
Bob's choice changes only the joint record. Rewrite the state in the X basis (|0> = (|+>+|->)/√2, |1> = (|+>-|->)/√2):
|Φ+> = (|++> + |-->)/√2
So Bob measuring X also gets 50/50, and Alice's marginal is still I/2. The correlation is real but conditional on comparing bases:
| Alice measures | Bob measures | Alice's marginal | Bob's marginal | Joint |
|---|---|---|---|---|
| Z | Z | 50/50 | 50/50 | always equal |
| X | X | 50/50 | 50/50 | always equal |
| Z | X | 50/50 | 50/50 | independent |
The last row is the point. Bob's basis choice is invisible in Alice's data; it only becomes visible when the two lists are brought together, which costs a classical round trip.
The "collapse" is bookkeeping. In the formalism, measuring B projects A. In relativistic QFT, spacelike-separated measurements commute, there is no observable ordering, so no experiment can distinguish "A collapsed first" from "B collapsed first". No-signalling is a theorem, not a limitation of current hardware.
When an entanglement-based design is worth it, and when it isn't. The deciding question is whether the protocol's security or capability rests on the quantum correlations themselves, or whether entanglement is just being used as a shared random seed.
Worth it:
- QKD, especially device-independent QKD, where the security proof depends on a Bell-inequality violation that no classical shared key can reproduce.
- Distributing entanglement for a quantum network or distributed quantum computation, where the resource is the entanglement, not a classical bit.
- Clock synchronization, where entanglement-based protocols can beat classical two-way time transfer in some loss regimes.
Not worth it:
- Any classical payload over an authenticated classical channel. Entanglement adds distribution hardware (sources, detectors, repeaters) and no latency benefit, because the classical comparison is still required.
- Using entanglement as a shared random seed. A PRF or a pre-shared key is cheaper and has no distribution loss.
Costs to weigh: at 1550 nm, telecom fibre loses about 0.2 dB/km, so 100 km costs ~20 dB and roughly 1% of photons survive; rates fall exponentially with distance, which is why repeaters or satellites enter the picture. Detector dark counts and timing jitter set the error floor.
Failure mode. A design that budgets a zero-latency control channel on shared entanglement collapses the moment the classical comparison step is added back: the control loop is still bounded by the classical round trip, and the architecture work is wasted. Detect it early by asking, for every "instantaneous" link, which classical message the receiver needs before it can act on what it measured. If there is one, the link is not instantaneous.
Curated: · Written: · Reviewed:
Q&A-1Your three-qubit circuit excites qubit 0 and the histogram key reads 001. Is that right?
In Qiskit, yes. In Cirq, no, and the circuit diagram cannot tell you which one you are looking at.
Qiskit prints the key as a classical-register bitstring, most-significant clbit first, and by default clbit i is wired to qubit i. Qubit 0 is therefore the rightmost character, so 001 means qubit 0 excited. Cirq's measure returns columns in the order you passed the qubits, so qubit 0 is leftmost and 001 means qubit 2 excited. Same circuit, same key, opposite answer.
Qiskit 1.x, checked against qiskit-aer:
from qiskit import QuantumCircuit, transpile
from qiskit_aer import AerSimulator
from qiskit.quantum_info import Statevector
qc = QuantumCircuit(3)
qc.x(0)
print(Statevector.from_instruction(qc).probabilities_dict())
# {'001': 1.0} <- index 1 = 2**0, qubit 0 is the LSB
qc.measure_all()
counts = AerSimulator().run(transpile(qc, AerSimulator()), shots=1024).result().get_counts()
print(counts)
# {'001': 1024}
Cirq, same physical circuit:
import cirq
q = cirq.LineQubit.range(3)
c = cirq.Circuit(cirq.X(q[0]), cirq.measure(*q, key='m'))
res = cirq.Simulator().run(c, repetitions=1024)
print(res.measurements['m'][0])
# [1 0 0] <- column 0 is q[0], so the string is '100'
| Excited qubit | Qiskit key (qubit 0 rightmost) | Cirq / wire-order key (qubit 0 leftmost) |
|---|---|---|
| 0 | 001 | 100 |
| 1 | 010 | 010 |
| 2 | 100 | 001 |
Note the middle row: qubit 1 is the fixed point of the mirror, which is exactly why a symmetric fixture proves nothing.
The failure mode. The key follows the clbit index, not the qubit index. qc.measure(0, 2) puts qubit 0's outcome in the leftmost position, so the same physical result prints 100. And the bug is silent: for a GHZ state or a uniform superposition the mirrored key is the same key, so cross-framework comparisons look fine. For a single-excitation state the entire histogram lands on the wrong key and nothing raises: you get a plausible-looking distribution that disagrees with the reference on every shot.
What I would actually do.
- Pin the convention once, in a helper that converts framework output to your internal order at the boundary where results leave the framework, not at each call site.
- Assert it with an asymmetric fixture: excite exactly qubit 0 of a three-qubit register and assert the printed key, the statevector index, and the clbit mapping against values worked out by hand.
{'001': shots}in Qiskit,[1 0 0]in Cirq. - When comparing a device histogram to a reference from another stack, mirror one of them explicitly and re-check that the fidelity moves, if it does not move, your fixture was symmetric and the test is worthless.
If you cannot say which end of the key qubit 0 sits on, you do not yet know whether 001 is right.
Curated: · Written: · Reviewed:
Q&A-3A compiler emits a block equal to minus your intended unitary. Does it matter?
This is an area where the ideal circuit and the circuit that executes global phase versus relative phase are different programs.
Global phase is unobservable on its own, so the block is a legitimate replacement anywhere it is applied directly. It stops being legitimate the moment the block is placed under a control, because the phase then becomes relative between the two branches and changes the interference the enclosing algorithm relies on.
Concretely, record global phase explicitly on any circuit object that may later be controlled, and test synthesized blocks in the controlled form they will be used in rather than standalone.
The reason for that specificity is a failure I have seen: A synthesized block equal to minus the target passed every standalone equivalence check, then produced a phase-estimation result off by exactly one bin because the controlled version differed from the intended one by a Z on the control.
Where the harmless phase becomes visible.
| Use | U vs minus U | Observable difference |
|---|---|---|
| applied directly | equivalent | 0 |
| under a control | not equivalent | phase estimation off by 1 bin |
I would not consider it settled without evidence: Compare the full unitary including phase for any block destined for a controlled construction, not the measurement distribution.
Phase that is global today is relative tomorrow.
Curated: · Written: · Reviewed:
Q&A-12Your hardware only measures in the computational basis. How do you measure an X observable?
Measuring X on a Z-only device means rotating the state so X becomes Z, then reading out. H X H = Z, so ⟨X⟩ equals the Z-basis expectation of the Hadamard-rotated state. For a Pauli string, apply the basis change qubit by qubit (H where the term has X, S† then H where it has Y, nothing where it has Z) then measure every qubit in Z and multiply the ±1 outcomes.
Assumptions: single-qubit gates are calibrated; the observable is a Pauli string or a sum of them; readout is Z-only. If the device exposes X/Y readout directly through firmware, the same rotation happens inside the instrument and you skip the explicit gate.
| Observable | Gate before Z readout | Shots shared with |
|---|---|---|
| Z | none | other Z terms |
| X | H | other X terms |
| Y | S† then H | other Y terms |
Worked example. Take H = 0.5·X0X1 + 0.5·Z0Z1 on |+⟩|+⟩. Exact: ⟨X0X1⟩ = 1, ⟨Z0Z1⟩ = 0, so ⟨H⟩ = 0.5. Drop the basis change and measure both terms as Z0Z1: the X term reads 0 instead of 1, and the estimate comes out 0. Wrong by 0.5, with no error flag. That is the failure mode: an X term evaluated in Z contributes near zero and the energy looks plausible.
# Qiskit 1.x, AerSimulator
from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator
import numpy as np
qc = QuantumCircuit(2, 2)
qc.ry(np.pi / 2, [0, 1]) # prepare |+>|+>
qc.h([0, 1]) # basis change for X0 X1
qc.measure([0, 1], [0, 1])
counts = AerSimulator().run(qc, shots=4000).result().get_counts()
# {'00': 4000}
# parity mean = (n00 - n01) / 4000 = 1 = <X0 X1>
Trace: |00⟩ → ry(π/2) on each qubit → |+⟩|+⟩ → H on each → |00⟩ → measure → '00' every shot. Parity = +1, matching ⟨X0X1⟩ = 1. Delete the h([0, 1]) line and the same circuit measures Z0Z1 on |+⟩|+⟩, giving parity mean 0: the X term silently reads zero.
Shot noise sets the resolution. A single-qubit Z measurement returns ±1, so the standard error of the mean after N shots is at most 1/√N. Resolving ⟨X⟩ to ±0.01 needs N ≈ 10⁴ shots for that term.
Trade-offs. Grouping qubit-wise commuting terms lets one rotated circuit serve several terms: a 20-term Hamiltonian that splits into 4 groups costs 4 circuits instead of 20, a 5× shot saving. The cost is depth: the group's basis change is the union of its members' rotations, so qubits that were identity in one term pick up an H. When the device is gate-limited rather than shot-limited, when the terms are already all-Z (grouping adds nothing), or when the number of groups approaches the number of terms, grouping costs more than it saves and you measure term by term.
Classical shadows estimate many Pauli observables from one randomized-measurement dataset. They win when you need hundreds of observables and can spend more shots per observable; they lose to a direct rotated measurement when you need one or two terms to high precision.
Failure modes and detection. Forgetting the rotation gives the 0.5 error above. Using S instead of S† for Y flips the sign of the imaginary part. A qubit-order mismatch between circuit and bitstring flips parities on the wrong qubits. Before trusting a full Hamiltonian, measure a term whose exact value you know on a small instance and require agreement within the shot-noise interval.
Curated: · Written: · Reviewed:
Q&A-19Explain how a controlled operation writes information into the control qubit's phase.
Core. A controlled operation writes into the control's phase when the target sits in an eigenstate of the operation being controlled. Write the controlled gate as C-U: it applies U to the target only on the control's |1⟩ branch. If U|ψ⟩ = e^{iφ}|ψ⟩, then
C-U (α|0⟩ + β|1⟩)_C ⊗ |ψ⟩_T = (α|0⟩ + β e^{iφ}|1⟩)_C ⊗ |ψ⟩_T.
The target comes out exactly as it went in; the eigenvalue e^{iφ} has moved onto the |1⟩ amplitude of the control. That relative phase is the kickback, and it is observable only if the control is in superposition: otherwise it is a global phase.
Trace. Two qubits, control C in |+⟩, target T in |−⟩, gate CNOT. |−⟩ is the −1 eigenstate of X, so φ = π.
Start: (1/√2)(|0⟩+|1⟩)_C ⊗ (1/√2)(|0⟩−|1⟩)_T.
CNOT flips T only when C = 1:
- |0⟩_C branch: target untouched → (1/√2)|0⟩_C ⊗ (1/√2)(|0⟩−|1⟩)_T
- |1⟩_C branch: target flips → (1/√2)|1⟩_C ⊗ (1/√2)(|1⟩−|0⟩)_T = −(1/√2)|1⟩_C ⊗ (1/√2)(|0⟩−|1⟩)_T
Sum: (1/√2)(|0⟩−|1⟩)_C ⊗ (1/√2)(|0⟩−|1⟩)_T = |−⟩_C|−⟩_T.
Control went |+⟩ → |−⟩; target unchanged. Measuring the control in the X basis returns |−⟩ with certainty: that is the phase read out.
Alternatives and when to pick them.
| Approach | What carries the answer | Pick when |
|---|---|---|
| Phase kickback | control's relative phase | the answer must interfere with the control (phase estimation, Grover's oracle, Deutsch–Jozsa) |
| Read the target | target's measured value | you want U applied to a known input |
| Intrinsic CPhase/CZ | phase already on the control's |1⟩ branch | U is diagonal in the computational basis |
| Measure + feedforward | classical phase | eigenstate unknown or expensive, eigenvalue ±1 |
Deciding question for the first row: where does the answer need to appear? If it is the target's value, prepare a basis state and measure it: no eigenstate, no kickback. If U is diagonal, there is no eigenstate to prepare and no target to disturb; the gate already is the phase. If the eigenstate is expensive or unknown, measure the target and apply a classically-controlled phase, at the cost of a mid-circuit measurement and feedforward latency.
Failure modes. Target not in an eigenstate → the gate entangles instead of kicking back. Prepare |+⟩_C|0⟩_T and CNOT gives (|00⟩+|11⟩)/√2: both marginals are maximally mixed, no relative phase anywhere. Detect by checking the target's reduced density matrix equals the state you prepared, and that the control still shows X-basis interference. Control not in superposition → the phase is global and unobservable; detect by a control Bloch vector with no x or y component. Dephasing on either qubit destroys the relative phase; detect by watching the control's interference fringe contrast decay with delay.
Curated: · Written: · Reviewed:
Q&A-13Why can a quantum circuit not contain an AND gate as written classically?
A quantum circuit can't contain a classical AND because AND is not invertible, and every gate in a closed quantum circuit is unitary: hence invertible.
Two ways to see it. Counting: AND maps four input pairs to two outputs, with 00, 01 and 10 all landing on 0. A unitary on two qubits is a bijection on the four computational basis states, so no 2-qubit unitary computes AND. Linearity: a unitary acts linearly on amplitudes, so U(α|00⟩+β|11⟩) = αU|00⟩+βU|11⟩. AND is a nonlinear function of the bit values, so it can't be a gate.
The resolution is to make the map injective by carrying the inputs through and writing the result somewhere new. That's the Toffoli (CCNOT): |a,b,c⟩ → |a,b,c⊕(a∧b)⟩. With c=0 it computes AND into the target while leaving a and b intact.
Trace, starting from |a,b,anc,out⟩ = |1,1,0,0⟩:
- Toffoli(a,b,anc): |1,1,1,0⟩
- CNOT(anc,out): |1,1,1,1⟩
- Toffoli(a,b,anc) again: |1,1,0,1⟩
The ancilla is back to |0⟩ and out holds a∧b. Step 3 is the uncompute; without it the ancilla stays entangled with the inputs.
That last point is where the choice of construction matters.
| Construction | Qubits | Ancilla clean | When to use |
|---|---|---|---|
| Toffoli into ancilla, no uncompute | 3 | no | ancilla used once, never reused coherently |
| Compute–copy–uncompute | 4 | yes | output needed as a bit, ancilla reused later |
| Phase kickback (compute, phase, uncompute) | 3 | yes | AND feeds a phase, e.g. a Grover oracle |
| Measure ancilla, classically control | 3 | n/a | only when the measurement commutes with the rest |
The cost is real: compute–copy–uncompute is two Toffolis plus a CNOT, roughly double the gates of the irreversible version, and the extra qubit is the price of reversibility. Phase kickback drops the output register when you only need the parity to steer a phase: that's why Grover oracles are usually written that way.
Failure mode to name: a dirty ancilla. If you compute AND into an ancilla and never uncompute, the ancilla is entangled with the input register. Inside a phase oracle that entanglement destroys the interference the algorithm depends on: you get a flat output distribution that looks exactly like hardware noise. Detect it by checking the ancilla's reduced state is |0⟩⟨0| (or that its marginal is pure) after running the oracle on a uniform superposition; if it isn't, you have a missing uncompute.
Curated: · Written: · Reviewed:
Q&A-23Why does forgetting to uncompute scratch qubits break an algorithm rather than just waste them?
Leftover scratch stays entangled with the register holding the superposition. That entanglement makes the branches distinguishable, so the relative phases that amplitude amplification and phase estimation depend on no longer interfere. You get a mixture, not a superposition, and the algorithm's guarantee no longer holds: a correctness bug, not an efficiency one.
Mechanism. A reversible subroutine is compute / use / uncompute. Compute writes f(x) into an ancilla, so the joint state is Σ_x α_x |x⟩|f(x)⟩. Skip the uncompute and the ancilla is a record of f(x). Tracing it out leaves the register in a mixture: the coherences ⟨x|ρ|x'⟩ with f(x) ≠ f(x') are gone. Grover's diffusion operator is the reflection 2|s⟩⟨s| − I, and it only amplifies if those coherences are present. Acting on a mixture, the reflection no longer produces the interference the algorithm relies on.
Worked example. Two qubits: data q0, ancilla q1. Oracle = CNOT(q0,q1) to compute f(x)=x, then Z on q1 to apply the phase. Start |+⟩|0⟩ = (|00⟩+|10⟩)/√2.
Clean (CNOT, Z, CNOT): |+⟩|0⟩ → (|00⟩+|11⟩)/√2 → (|00⟩−|11⟩)/√2 → (|00⟩−|10⟩)/√2 = |−⟩|0⟩. Final H on q0: H|−⟩ = |1⟩. So q0 = |1⟩ with probability 1.
Dirty (CNOT, Z, no uncompute): |+⟩|0⟩ → (|00⟩+|11⟩)/√2 → (|00⟩−|11⟩)/√2. Final H on q0: (|00⟩−|11⟩)/√2 → [|00⟩+|10⟩−|01⟩+|11⟩]/2. P(q0=0) = 1/2, P(q0=1) = 1/2.
| Oracle | P(q0=1) |
|---|---|
| uncomputed | 1.0 |
| ancilla left dirty | 0.5 |
The ancilla holds f(x), so the two branches of q0 no longer interfere; the deterministic answer becomes a coin flip.
What uncomputation costs. Every gate in compute is mirrored by its inverse, so the subroutine's gate count and depth roughly double. On hardware where two-qubit gates dominate the error budget that is a direct fidelity cost: at 0.1% error per two-qubit gate, 100 gates succeed 90% of the time and 200 gates 82%. Ways to pay less:
- Borrowed ancillas. A qubit elsewhere in the algorithm that is in an unknown state can serve as scratch, provided the uncompute restores it exactly. You don't need |0⟩, you need "returned to what it was". The constraint is that you can't use it as a control for operations that assume |0⟩.
- Bennett's compute-copy-uncompute. Compute f into scratch, CNOT the answer into an output register, then uncompute the scratch. You keep the answer and get the scratch back clean; you pay recomputation instead of space.
- Phase kickback. If the compute circuit is ancilla-free, a target in |−⟩ absorbs the phase (−1)^{f(x)} and no compute/uncompute pair is needed. The catch is that ancilla-free circuits for general f can be much larger.
- Peephole cancellation. Adjacent compute/uncompute pairs cancel, and compilers remove them: Q#'s
within/applyblocks andAdjfunctors exist for exactly this. If the pair only produces a phase, it can often be fused into the next operation.
You can skip uncompute when the ancilla is part of the output: classical reversible circuits, or a measurement whose result is used classically. In a coherent quantum algorithm you cannot.
Detecting it. Assert in simulation that the scratch register returns to |0⟩ with probability one on a superposition input, not just on basis states. The superposition input is what the algorithm actually runs on, and it is where the interference failure shows up. The symptom in the wild is a flat output distribution that looks like device noise.
Curated: · Written: · Reviewed:
Q&A-22Your algorithm needs a clean ancilla halfway through. Reset or allocate?
The 90-second answer
If the ancilla is reused inside the shot (syndrome extraction in a QEC cycle, any mid-circuit loop) you reset. The code block has fixed width; allocating a fresh qubit per round would blow the layout. If the ancilla is used once and you have idle width, allocate: a qubit that has never been touched sits in |0> with no reset error and no reset latency, and the only cost is the extra qubit and whatever routing it forces.
The decision rule: compare the reset's residual excitation times the number of reuses against the routing overhead the extra width introduces. Both are measurable on the target device; neither is a constant you can look up.
What reset actually costs
Active reset on superconducting hardware is measure-then-correct: read the qubit, and if it came back |1>, drive an X. That inherits the readout error and adds feedback latency: typically a few hundred nanoseconds to a couple of microseconds per reset, on top of the readout window. Residual excitation after reset commonly lands in the 0.1–1% range and is device- and calibration-dependent, so measure it rather than trusting a datasheet number.
A fresh qubit avoids all of that. Its |0> is the ground state; thermal excitation at dilution-fridge temperatures is negligible for a transmon. What you pay is width: more qubits means more crosstalk, worse connectivity, and more SWAPs to bring the ancilla next to its partners. On a heavy-hex lattice that routing cost can exceed the reset cost outright.
The failure mode: compounding
Reset error compounds multiplicatively across reuses. If a routine resets the same ancilla k times per shot, the probability the ancilla was clean every time is (1 − p_reset)^k.
| Reset error p | Reuses k | Clean-run probability |
|---|---|---|
| 0.2% | 12 | 0.998^12 = 0.98 |
| 2% | 12 | 0.98^12 = 0.78 |
(Hypothetical figures, arithmetic shown.) At 2% the detection statistics are unusable, roughly one shot in five has a corrupted ancilla somewhere, and nothing in the syndrome data flags it. That is the trap: the reset looks like a no-op in the circuit diagram, so nobody budgets for its error.
How to detect it
Characterize the reset directly: prepare the ancilla, reset it, then measure it immediately, over thousands of shots, and report the residual |1> population. Do this per qubit, not per device: reset fidelity varies across the chip. Then propagate that number through the reuse count before trusting any syndrome statistics.
When not to reset
Single-use ancilla with spare width: allocate. Reset only wins when width is the binding constraint, or when the fresh qubit's routing cost exceeds the reset's time-plus-error. And if you do reset, budget the latency: k resets per shot at ~1 µs each is k microseconds off your coherence budget.
Curated: · Written: · Reviewed:
Q&A-11After you measure one qubit of a register mid-circuit, what happens to the rest?
Short answer. A projective measurement projects the whole register onto the subspace consistent with the outcome, then renormalizes. Any qubit that was entangled with the measured one changes state; a qubit that was in a product state with it does not. On hardware you get a classical bit, and the register is in whatever state the projection left it in, if later gates depend on the outcome, you have to branch on that bit.
Mechanism. For outcome m the update is |ψ⟩ → (P_m ⊗ I)|ψ⟩ / √p_m, with p_m = ⟨ψ|P_m|ψ⟩. The projector touches only the measured qubit, but it acts on the full register, so both the normalization and the post-state are global. An instrument (Kraus) description gives you the outcome and the conditional state together. A density-matrix simulator gives you the average Σ_m p_m ρ_m, which is the right object only if you never look at the bit.
Bell pair. |Φ⁺⟩ = (|00⟩+|11⟩)/√2, measure A:
| Outcome on A | Probability | State of B |
|---|---|---|
| 0 | 0.50 | |0⟩ |
| 1 | 0.50 | |1⟩ |
B's marginal was I/2 before and is I/2 after. What changed is that the correlation with A is gone.
GHZ trace. |GHZ⟩ = (|000⟩+|111⟩)/√2, measure q1.
- P₀|GHZ⟩ = |000⟩/√2, so p(0) = 1/2 and the post-state is |000⟩.
- P₁|GHZ⟩ = |111⟩/√2, so p(1) = 1/2 and the post-state is |111⟩.
q0 and q2 were never touched and are still a Bell pair, but now in a product state with q1. Measuring the middle qubit of GHZ does not destroy the outer pair's entanglement; measuring one half of a Bell pair does destroy the other's coherence. Which one you get depends on what the measured qubit was entangled with, not on the fact that you measured.
Worked example (hypothetical numbers). Three data qubits in a uniform superposition over 8 states, ancilla a = q0 ⊕ q1, marked state |110⟩. Measure a without uncomputing it:
- a = 0 (p = 1/2): data is uniform over {|000⟩, |001⟩, |110⟩, |111⟩}; |110⟩ now has conditional probability 1/4.
- a = 1 (p = 1/2): data is uniform over {|010⟩, |011⟩, |100⟩, |101⟩}; |110⟩ is gone.
A circuit that ignores the bit is running two different algorithms and averaging them: 1/2 × 1/4 + 1/2 × 0 = 1/8, the same as before the measurement, but with a hard zero on half the shots and any further amplitude amplification reflecting off the wrong subspace.
Trade-offs.
- Defer the measurement vs mid-circuit. Deferring keeps the qubit coherent and keeps you inside the unitary toolbox. Mid-circuit measurement is what you need for feed-forward: teleportation, repeat-until-success, syndrome extraction in QEC, dynamic circuits. The cost is that readout is the slowest single-qubit operation (hundreds of ns to a few µs) and its error is usually the dominant per-qubit error on superconducting hardware, and it drags the classical control path into the critical path.
- Reuse the ancilla vs allocate a fresh one. Reuse needs a reset, and reset is imperfect: thermalization leaves residual |1⟩ population, so a reused ancilla is not the same resource as a fresh one. Fresh ancillas cost qubits, which matters on devices with limited connectivity.
- Trajectory vs density matrix in simulation. Sample trajectories if you branch on the bit; use the density matrix if you discard it.
Failure modes.
- Measuring an ancilla that is still entangled with the data. Detected by comparing the conditional statevector after the measurement against the state the rest of the circuit assumes, or by replacing the measurement with a no-op and watching the success probability move.
- Assuming the outcome is deterministic. Detected by a histogram of the ancilla bit across shots.
- Reusing a measured qubit without reset. The next gate sees the collapsed state, not |0⟩; detected by tomography on the reused qubit before the next gate.
Curated: · Written: · Reviewed:
Q&A-20A circuit measures a qubit and applies a gate conditioned on the result. Can you avoid the measurement?
Yes, but only under conditions you should state before you rely on it. The deferred measurement principle: a computational-basis measurement followed by a unitary classically conditioned on the outcome is equivalent to the coherently controlled unitary followed by the same measurement. The conditions are that the measurement is in the computational basis, the conditioned operation is unitary, and nothing else consumes the outcome: no reset, no second measurement, no later basis choice driven by the bit.
Why it works. The classical bit is just the control qubit's value in the computational basis. A controlled unitary acts as the identity on the control's |0> and |1> components, so it commutes with measuring the control. For control C and target T, M_C ∘ (U controlled on C) = (U controlled on C) ∘ M_C. The joint distribution over all final measurement outcomes is identical.
Trace it. q0 = |+>, q1 = |0>.
Measured form: H on q0 gives (|00> + |10>)/√2. Measure q0: outcome 0 with probability 1/2, post-state |00>, no X; outcome 1 with probability 1/2, post-state |10>, X on q1 gives |11>. Ensemble: 1/2|00> + 1/2|11>, diagonal.
Deferred form: H on q0 gives (|00> + |10>)/√2. CX(0,1) gives (|00> + |11>)/√2. Measure q0: outcome 0 with probability 1/2, q1 = |0>; outcome 1 with probability 1/2, q1 = |1>. Same ensemble.
The difference is the state before the final measurement: the deferred circuit holds the Bell state (|00>+|11>)/√2, the measured circuit holds a classical mixture. If you never measure q0, they are not equivalent: the deferred one has entanglement the other does not. That is exactly why the principle earns its keep: it shows mid-circuit measurement adds no computational power over coherent control, and it is what a statevector simulator does instead of branching on outcomes.
Where it breaks.
- Non-unitary conditioned operations. Reset, a second measurement, or a feed-forward that changes a later measurement's basis cannot be deferred. Syndrome extraction in QEC is the canonical case: measure the ancilla, reset it, reuse it.
- Ancilla cost. Every deferred measurement needs a qubit held coherent until the end. Deferring 20 syndrome rounds needs 20 live ancillas, not one reused.
- Coherence budget. The deferred circuit is longer. On a superconducting device with T2 of order 100 µs and two-qubit gates of 100–500 ns, 20 rounds of roughly 1 µs each spend about a fifth of the coherence budget: hypothetical numbers, but the shape is right.
- Readout and feedback. The measured form pays readout error (roughly 1–2% per mid-circuit measurement on current hardware) and feedback latency (hundreds of nanoseconds); the deferred form pays neither, but pays in depth and qubits.
| Form | Live ancillas | Coherent window | Control error |
|---|---|---|---|
| Deferred | one per deferred measurement | extended to end of circuit | none: no readout |
| Mid-circuit | none; reset and reuse | one round | readout ~1–2% plus feedback latency |
What to do. Simulate the deferred form to establish the intended distribution, then run the dynamic form on the target and compare success rate and duration. Deferring is the right default for reasoning and for statevector simulation; on hardware, measure mid-circuit when the conditioned operation is non-unitary or when ancillas and coherence are the binding constraint.
Curated: · Written: · Reviewed:
Q&A-21What does a device need to support before you can write a dynamic circuit?
A device needs three things, and they form a chain: mid-circuit measurement, classical registers the control electronics can read, and conditional gates that fire within the coherence time of the qubits still waiting. The first two are usually advertised; the third is where submissions fail.
Mid-circuit measurement means measuring a qubit partway through the circuit without ending the shot. Classical registers must be readable by the control stack, not just by the host collecting results at the end: the condition has to be evaluated on the device. Conditional gates (feed-forward) let the pulse sequence branch on that register in real time. That is a hardware property: the control system must decide and dispatch a pulse based on a bit that did not exist when the job was compiled. No compiler setting substitutes for it.
| Capability | What it means | If absent |
|---|---|---|
| Mid-circuit measurement | measure a qubit, keep the rest of the circuit running | only terminal measurement; nothing to branch on |
| Readable classical register | result routed to control electronics | condition can't be evaluated on device; compiler falls back to post-selection |
| Conditional gates | control stack branches and dispatches a pulse in real time | no adaptive operation |
| Feed-forward latency < T2 | loop closes before waiting qubits decohere | conditional gate lands on decohered qubits |
| Mid-circuit reset | qubit returned to |0⟩ and reused | needed for qubit reuse, not for every dynamic circuit |
Qiskit 1.x expresses the requirement directly:
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
qc = QuantumCircuit(qr, cr)
qc.h(0)
qc.measure(0, 0) # mid-circuit measurement
with qc.if_test((cr, 1)): # feed-forward on the classical bit
qc.x(1)
Trace: H puts q0 in an equal superposition. The measurement collapses it and writes cr[0] = 0 or 1 with probability 1/2 each. If cr[0] = 1, X flips q1. So q1 ends in |1⟩ half the time and |0⟩ half the time: the branch is real, not a post-hoc filter. (Checked against Qiskit 1.0+, where if_test replaced the older c_if.)
The binding constraint is the latency budget. The loop is measurement + classical routing + branch decision + pulse dispatch, and it must close well inside T2 of every qubit still holding state. Take a hypothetical device with T2 = 60 µs on the waiting qubit. A 0.5 µs loop retains exp(-0.5/60) ≈ 0.99 of its coherence; a 4 µs loop retains exp(-4/60) ≈ 0.94. That ~5-point gap is paid before any gate error, and it compounds across every round of feed-forward.
Failure modes worth naming: latency exceeding T2 (the conditional gate lands on decohered qubits. Detect by comparing device fidelity to a simulator that treats feed-forward as instantaneous); mid-circuit measurement without a readable register (the compiler silently defers to post-selection, which discards shots and can cost exponential overhead across repeated rounds); measurement crosstalk disturbing idle neighbours; and reset error accumulating when a qubit is reused.
Not every circuit needs this. The deferred-measurement principle says classically-controlled quantum operations can often be pushed to the end. You need dynamic circuits when you want to reuse a qubit (measure + reset), when post-selection would throw away too many shots, or for real-time feedback such as active reset.
Curated: · Written: · Reviewed:
Q&A-18Why do Z rotations often cost nothing on superconducting hardware?
On superconducting hardware a Z rotation is not a pulse. The qubit is driven in a rotating frame set by the phase of the microwave reference, and shifting that phase by φ before the next pulse is algebraically identical to having applied Rz(φ). The control stack updates a number, so the gate takes 0 ns and adds no decoherence or gate error. An arbitrary single-qubit rotation therefore compiles to two calibrated half-pulses for the X/Y part plus three virtual Z rotations.
Mechanism. Rz(φ) = diag(e^(−iφ/2), e^(iφ/2)). A drive pulse with phase θ implements a rotation about an axis in the XY plane at angle θ. Changing θ by φ rotates that axis, which is exactly conjugation by Rz(φ). Because the frame phase is a software variable carried between pulses, the compiler folds each Z into the phase of the next pulse and emits nothing.
Decomposition of one arbitrary single-qubit rotation:
| Component | Count | Duration each |
|---|---|---|
| virtual Z | 3 | 0 ns |
| calibrated half-pulse | 2 | 20 ns |
Frame tracking, step by step. Start with frame phase 0. Apply Rz(π/2): frame becomes π/2, no pulse emitted. Apply a half-pulse: it goes out with phase π/2. Apply Rz(π): frame becomes 3π/2. Apply the second half-pulse: it goes out with phase 3π/2. Two pulses total; three Z's absorbed into their phases.
When a physical Z is the right call. Virtual Z is free only if the compiler tracks the frame through the whole circuit. Three cases break that:
- A Z immediately before a Z-basis measurement commutes with the measurement, so it is a no-op on the outcome and can be dropped rather than tracked.
- A control stack without per-pulse phase updates cannot fold the Z into the next pulse, so the Z becomes a real operation with real duration and error.
- Architectures with a different native gate set (trapped ions, for instance) implement Z physically, and the same circuit costs time there.
For calibrating or benchmarking the Z operation itself you need a physical implementation to measure, since a frame change leaves no pulse to characterize.
Failure mode. An optimization pass that minimizes raw instruction count can delete virtual Z's and substitute physical pulses, cutting the reported gate count while increasing scheduled duration. Detect it by comparing scheduled duration and two-qubit count before and after the pass, not the raw instruction count.
Curated: · Written: · Reviewed:
Q&A-14Your device offers a fixed basis set. What does that cost your arbitrary rotations?
The 60-second answer. A fixed basis set turns every arbitrary rotation into a compiled sequence, and you pay per rotation, logarithmically in precision. For Clifford+T, an Rz(θ) whose angle is not a multiple of π/4 costs about 3·log2(1/ε) T gates: 30 at ε=1e-3, 60 at ε=1e-6, 100 at ε=1e-10. Each extra bit of precision costs 3 T gates. Because T gates are the expensive resource in a fault-tolerant machine: magic-state distillation makes one T cost on the order of 10²–10³ Clifford gates, depending on the target error: the bill scales with the number of rotations in the circuit, not with the number of qubits. And the synthesis error is coherent, so it adds in amplitude: N rotations each off by ε can be off by Nε, not √N·ε.
Why the log, and why 3. The Clifford+T group is dense in SU(2), so approximation is possible; the question is how fast the achievable set fills up. Counting distinct unitaries reachable with n T gates gives a lower bound of 3·log2(1/ε) − O(1), and Ross–Selinger synthesis meets it up to an additive constant. The general-purpose Solovay–Kitaev bound is worse: O(log^c(1/ε)) with c ≈ 3.97 in the standard analysis, which is why you use a basis-specific synthesizer rather than a generic one. Angles that are multiples of π/4 are exact: Rz(π/4) is one T gate, Rz(π/2) is S, Rz(π) is Z, with zero approximation error.
Turning the tolerance into a budget. The mistake is picking ε per gate. Pick it from the circuit's total error budget, and pick it differently depending on whether the synthesis errors add coherently or with random relative phase:
import math
def per_rotation_eps(n_rot, eps_total, coherent=True):
return eps_total / n_rot if coherent else eps_total / math.sqrt(n_rot)
def t_count(eps): # Ross-Selinger: 3*log2(1/eps) + O(1)
return math.ceil(3 * math.log2(1 / eps))
for n in (100, 10_000):
for coherent in (True, False):
eps = per_rotation_eps(n, 1e-2, coherent)
print(n, "coherent" if coherent else "random", f"{eps:.2e}", t_count(eps))
100 coherent 1.00e-04 40
100 random 1.00e-03 30
10000 coherent 1.00e-06 60
10000 random 1.00e-04 40
For a 1e-2 total budget, 10,000 rotations need ε=1e-6 per rotation if the errors are coherent and only 1e-4 if they are effectively random: 60 T gates versus 40, a 50% cost difference on the dominant resource. Assuming the optimistic case without justification is how a circuit quietly misses its target.
What changes the answer. If the device has native continuous rotations, the cost moves elsewhere. On superconducting transmons, Rz is a virtual frame change: exact, zero duration, zero error, so arbitrary Z rotations are free and the cost is the √X pulses needed to change the rotation axis. Trapped ions offer native R(θ,φ) directly, at the price of two-qubit gates in the 10–100 µs range instead of tens of nanoseconds. Ancilla-assisted synthesis reduces the T-count constant at the cost of an ancilla and classical feed-forward. And a fixed basis set forces synthesis at compile time, so variational algorithms that update parameters every iteration pay the full synthesis cost per iteration.
Failure modes. Coherent synthesis error does not average out under repetition and is not converted to Pauli error by the compiler, so it survives into the algorithm's output; in phase estimation it is amplified by the inverse of the eigenvalue gap. Over-tightening ε wastes T gates on precision the algorithm cannot use. Detection is direct: compare the synthesized unitary to the target in operator norm per rotation, sum the norms across the circuit, and check that sum against the algorithm's budget before running anything. Randomized benchmarking will not give you this number, because it reports a Pauli-twirled error rate that hides the coherent part.
Curated: · Written: · Reviewed:
Q&A-27You measure a CHSH value of 2.05. Have you violated the local bound?
This is an area where the ideal circuit and the circuit that executes the CHSH bound and the statistics behind it are different programs.
Not yet: the local bound is 2 and the quantum maximum is about 2.828, so the whole window is 0.83 wide and the error bar decides. With 8,192 trials per setting the standard error on S is about 0.022, which puts 2.05 a little over two standard errors above the bound.
Concretely, compute the standard error from the four correlators and the trial counts, fix the number of trials before the run, and report S with its interval rather than as a point value.
The reason for that specificity is a failure I have seen: A result reported a violation at S equal to 2.03 from 1,024 trials per setting, where the standard error was 0.063; the same apparatus reproduced 1.98 on the next run and the claim was withdrawn.
The same S at two trial counts.
| Trials per setting | Standard error on S | S = 2.05 is |
|---|---|---|
| 1,024 | 0.063 | noise |
| 8,192 | 0.022 | marginal |
| 65,536 | 0.008 | a violation |
I would not consider it settled without evidence: State S, the per-setting trial count and the standard error together, and require several standard errors of margin above 2.
A violation is a distance measured in standard errors.
Curated: · Written: · Reviewed:
Q&A-28Your Bell test discards trials where a detector did not fire. What does that cost the claim?
Discarding non-detections makes the analysed set conditional on an event, a detection, that a local model can correlate with the measurement setting. That is the cost: the violation stops being a statement about the pairs the source emitted and becomes a statement about the subset that happened to fire. A local hidden-variable model with a detection strategy tuned to the settings reproduces the same post-selected statistics, so the test no longer rules out local realism unless you assume fair sampling: that the detected subset is representative of the emitted pairs.
Fair sampling can be dropped only above a detection-efficiency threshold, and the threshold depends on the state:
| State | Inequality | Efficiency threshold η |
|---|---|---|
| maximally entangled | CHSH, Garg–Mermin (1974) | 2(√2 − 1) ≈ 82.8% |
| non-maximally entangled | Eberhard (1993) | 2/3 ≈ 66.7% |
The arithmetic: 2(√2 − 1) = 2 × 0.41421 = 0.82843. A maximally entangled photon test at 70% efficiency cannot drop fair sampling; the same 70% clears Eberhard's bound if the state is deliberately non-maximally entangled. That is the lever the 2015 experiments pulled.
Three experiments in 2015 closed the detection loophole together with locality and freedom of choice: Hensen et al. (Delft, electron spins separated by 1.3 km), Giustina et al. (Vienna, photons), and Shalm et al. (NIST, photons). The photon tests used Eberhard's scheme, non-maximally entangled states, to bring the required efficiency down to what their detectors could reach. Before 2015, a Bell violation either assumed fair sampling or left the detection loophole open.
Concretely, report:
- trials attempted, trials discarded, and the reason for each discard class (no detection at A, no detection at B, no coincidence);
- the detection efficiency η and which threshold it is compared against;
- whether the reported S is post-selected or computed over all attempted trials with non-detections counted as outcomes.
Hypothetical: 100,000 attempted pairs at η = 0.70 gives 70,000 coincidences and 30,000 discards. A post-selected analysis uses 70% of the data; a loophole-free analysis has to account for all 100,000.
The failure mode is a denominator swap: reporting S over coincidences while calling the result loophole-free. Those are different questions. Below the relevant threshold the honest label is "violation conditional on fair sampling".
The discarded trials are part of the result; the denominator is part of the claim.
Curated: · Written: · Reviewed:
Q&A-29You need to certify a GHZ state on five qubits. Do you run tomography?
I would treat entanglement witnesses versus full tomography as a claim that has to survive being recomputed from the raw counts.
Tomography needs 3 to the n measurement settings, 243 at five qubits, and reconstructs far more than the claim requires. A fidelity witness certifies genuine multipartite entanglement from two settings whenever the estimated fidelity exceeds one half.
Concretely, fix the witness before looking at the data, since choosing the witness that happens to violate its bound on the observed counts is the same error as choosing a hypothesis after seeing the sample.
The reason for that specificity is a failure I have seen: A team ran 243 tomography settings at 4,096 shots each, about a million executions and nine hours of device time, to establish a claim that two settings and 8,192 shots would have supported.
Certifying a five-qubit GHZ state.
| Method | Settings | Shots | Device time |
|---|---|---|---|
| full tomography | 243 | 995,328 | ~9 h |
| fidelity witness | 2 | 8,192 | ~4 min |
I would not consider it settled without evidence: Estimate the witness from its preregistered settings and report the fidelity with its confidence interval against the one-half bound.
Measure the claim, not the whole state.
Curated: · Written: · Reviewed:
Q&A-30Why does tomography stop being an option so quickly?
The useful question for the cost of state tomography is what the hardware does that the simulator never showed.
The number of parameters in a density matrix grows as 4 to the n and the number of measurement settings as 3 to the n, so the shot budget grows exponentially in qubits while the useful conclusion usually does not. At ten qubits it is 59,049 settings.
Concretely, reserve tomography for one and two qubit characterization, and use randomized measurement techniques, witnesses or direct fidelity estimation for anything wider, stating the estimator and its assumptions.
The reason for that specificity is a failure I have seen: A characterization plan budgeted tomography for an eight-qubit register, discovered it needed 6,561 settings at 2,048 shots, over 13 million executions, and abandoned characterization entirely rather than switching estimator.
Tomography settings by width.
| Qubits | Settings | Real parameters |
|---|---|---|
| 2 | 9 | 16 |
| 5 | 243 | 1,024 |
| 10 | 59,049 | 1,048,576 |
I would not consider it settled without evidence: Compute the settings and shots the chosen estimator requires at the target width before committing device time.
Pick the estimator that scales with the question.
Curated: · Written: · Reviewed:
Q&A-31A vendor quotes 99.9 percent fidelity. What did they measure?
What a strong candidate says first
Ask what object the number describes and which protocol produced it. "Fidelity" is not one measurement. State fidelity compares one prepared state against a target; process fidelity characterizes a gate as a channel over all inputs; randomized benchmarking (RB) reports a Clifford-averaged average gate fidelity. A vendor quoting 99.9 percent has picked one of these, on some subset of qubits, in some calibration window, and that number does not transfer to your circuit.
Then ask the question that actually decides it: does the vendor's protocol exercise the error channel my workload is dominated by?
Three numbers that all read as fidelity
| Quantity | Illustrative value | Applies to | Protocol |
|---|---|---|---|
| single-qubit average gate | 99.9% | one qubit | RB |
| two-qubit average gate | 99.2% | one coupled pair | RB / interleaved RB |
| state prep and measurement | 98.5% | readout chain | prep + measurement |
Values are illustrative; real devices vary per qubit and drift between calibrations.
When to take the vendor's number, and when to re-measure
Re-measuring costs lab time and yields a number that is itself stale by the time you use it: calibration drift means your measurement and theirs are both snapshots. So the decision is not "always re-measure"; it is whether the vendor's protocol matches your workload.
Adopt the figure when your circuit is shallow enough that gate error is not the dominant term (readout or state prep dominates); when you are screening vendors before committing engineering time; when the vendor's protocol is the one your workload actually runs, for instance the same Clifford-randomized workload; or when the quoted number is conservative against your own spot checks, so it is a lower bound on what you will get.
Re-measure when your error budget is dominated by a gate type the vendor did not characterize; when you need a specific gate's error rather than a Clifford average, which interleaved RB or cycle benchmarking gives you; when the number will be written into a contract or a hardware requirement; or when the vendor's qubit subset and calibration window differ from the ones you will be allocated.
The failure this prevents
A design assumed a quoted 99.9 percent single-qubit figure applied to two-qubit operations. The two-qubit error was 0.8 percent. A circuit with 200 two-qubit gates: 0.992^200 = 0.20, so 20 percent success, against the 82 percent the team expected from 0.999^200. The headline was correct and irrelevant.
What to record
Reproduce the vendor's protocol on the qubits your circuit will use, and record the calibration timestamp alongside the number. A fidelity without its protocol is a rumour.
Curated: · Written: · Reviewed:
Q&A-32Randomized benchmarking gives an excellent number and your algorithm still fails. Why?
What a strong candidate says first
Randomized benchmarking measures the average error of a gate set under random Clifford sequences. That number is real, but it is an average over an ensemble your workload may not belong to. RB's random sequences twirl coherent errors (over-rotations, crosstalk, a miscalibrated pulse) into effective depolarizing noise. Depolarizing errors add in probability, so they accumulate linearly with depth. Coherent errors add in amplitude, so they accumulate quadratically. A structured circuit that repeats the same gate on the same qubit keeps the error on one axis, and the amplification RB averaged away comes back.
Mechanism
Model a per-gate over-rotation as U = exp(-iθZ/2) with θ = 0.007 rad. Under RB, each gate's error axis is randomized by the surrounding Cliffords, so the per-gate infidelity is θ²/4 ≈ 1.2e-5 and n gates give ≈ n·1.2e-5. In a circuit that repeats the gate, the rotations add: total angle nθ, infidelity ≈ (nθ/2)². The ratio of observed to RB-predicted error is n.
| Repetitions n | RB-predicted (linear) | Observed (coherent) |
|---|---|---|
| 10 | 1.2e-4 | 1.2e-3 |
| 50 | 6.1e-4 | 3.1e-2 |
At 50 repetitions the device still reports 99.8% average gate fidelity, but the repeated-gate circuit has drifted 0.35 rad and lost about 3% fidelity.
Alternatives and when to use them
- Interleaved RB: insert the gate of interest between random Cliffords. Isolates that gate's error, but the random context still twirls coherent error, so it reports the same averaged number: use it to attribute error to a gate, not to see coherent buildup.
- Cycle benchmarking: measure a fixed repeating cycle (the actual gate pattern) rather than random sequences. Preserves coherent accumulation within the cycle, so it sees the structured error. Use when your workload is a repeated cycle.
- Gate set tomography: reconstructs the full process matrix, so it separates coherent from stochastic error directly. Expensive (many sequences, hours), use when you need the error's axis, not just its size.
- Purity benchmarking / unitarity: gives the incoherent fraction; if unitarity is high but RB error is nonzero, the error is coherent. Cheap add-on.
Detection
Sweep depth on the repeated-gate sequence and fit error against n. A linear fit means depolarizing error and the RB number transfers. A quadratic fit means coherent error and the RB number does not transfer. That is the check.
Curated: · Written: · Reviewed:
Q&A-33When is it legitimate to apply a readout correction matrix to your counts?
Short answer. Legitimate when two things hold: the readout channel is a nuisance you characterized independently of the data you are correcting, and the claim is about the state you prepared. Not legitimate when the measurement model is part of the hypothesis: a loophole-free Bell test, a test of the detector itself, or any result whose violation appears only after correction. The question to ask is not "is the matrix accurate" but "does the conclusion survive without it".
Mechanism. Readout error is a classical channel. Characterize it with an assignment matrix A, where A_ij = P(measure i | prepare j), estimated by preparing each computational basis state and counting. The corrected distribution is p = A⁻¹m. Because A is estimated from finite shots and can be ill-conditioned, use constrained least squares or maximum likelihood with p ≥ 0 and Σp = 1 rather than raw inversion, and propagate the uncertainty: the corrected value always carries a larger error bar than the raw one.
Worked trace (hypothetical figures). One qubit, 10,000 shots per calibration state. A = [[0.97, 0.06], [0.03, 0.94]], columns indexed by prepared state. An experiment returns raw counts (8600, 1400), so m = (0.860, 0.140). Solving A p = m: determinant 0.91, p₀ = (0.94·0.860 − 0.06·0.140)/0.91 = 0.879, p₁ = 0.121. The correction moves the |0⟩ population from 0.860 to 0.879.
Statistical error: raw σ(p₀) = √(0.86·0.14/10000) = 0.0035. Corrected σ = √((0.94² + 0.06²)·1204)/(0.91·10000) = 0.0036. Barely worse, because A is well conditioned. That is the good case.
Failure modes.
- Drift. Suppose the true matrix at run time had drifted to A′ = [[0.94, 0.09], [0.06, 0.91]]: a 3-point change in P(1|0), the kind you get from a two-level system, a temperature shift, or crosstalk from a neighbouring qubit driven during the run. The same true state (0.879, 0.121) then measures as (0.837, 0.163), and correcting with the stale A reports 0.854. Bias 0.025: seven times the 0.0036 statistical error. The result is calibration-limited, not statistics-limited.
- State-dependent readout. Leakage to |2⟩, or T₁ decay during a long readout pulse, makes the error depend on the state being measured. A single assignment matrix cannot represent that.
- Correlated readout. Crosstalk between qubits makes the full 2ⁿ matrix intractable; correcting qubit-by-qubit assumes an independence that may not hold.
- Ill-conditioning. As A approaches singular, the inverse amplifies noise; corrected error bars can exceed the effect you are claiming.
- Negative probabilities. Naive inversion returning negative counts is a sign the correction is doing more work than the data supports.
What to do instead. Design the readout error down: heralded readout, repeated QND measurement, or SPAM-robust protocols such as randomized measurements: rather than correcting it away. When you do correct, publish raw counts, the matrix, its timestamp, and the corrected result, and re-measure the matrix often enough to bound drift. If the correction moves the result by more than the statistical error bar, say so; the honest statement is "raw 0.860, corrected 0.879, calibration-limited at the 0.02 level", not "0.879".
Curated: · Written: · Reviewed:
Q&A-15Which number would you ask for first when comparing two implementations of the same algorithm?
Ask for the two-qubit gate count after transpilation to the target device.
Assumptions: both implementations compute the same function, and you are comparing them on hardware you actually intend to run on (or a simulator model of it). If the target is a fault-tolerant machine executing logical qubits, the currency changes: noted at the end.
Why that number rather than abstract gate count or circuit depth: on current superconducting and trapped-ion devices, two-qubit gates dominate the error budget. Typical calibration figures are single-qubit error around 1e-4 to 1e-3 and two-qubit error around 5e-3 to 1e-2, roughly an order of magnitude apart. Forty two-qubit gates at 0.7% each succeed about 76% of the time; four hundred single-qubit gates at 0.05% each still succeed about 82%. The two-qubit count is what moves the answer.
Abstract counts also hide routing. A design that looks cheap in source form can be expensive once the transpiler maps it onto a limited connectivity graph.
Worked example, hypothetical device with 0.7% two-qubit error and a line topology:
| Design | Abstract CNOTs | Routed CNOTs | Estimated success |
|---|---|---|---|
| A | 12 | 39 | 0.76 |
| B | 16 | 18 | 0.88 |
Design A leans on 12 long-range interactions. After routing to a line it needs 39 CNOTs against B's 18. On abstract counts A looks better (0.92 against 0.89); on routed counts B wins. That inversion is why the transpiled number is the first one to ask for.
Pair it with the device's current two-qubit error rate so the count converts into an expected success probability, and ask for the transpiler settings, optimization level and seed, because counts shift between runs.
Failure modes and what to check:
- The product-of-fidelities estimate is an upper bound. It ignores crosstalk between simultaneously driven pairs, leakage out of the computational subspace, measurement error, and decoherence over the longer schedule. A 39-CNOT circuit also spends more wall-clock time in T1/T2.
- Count and depth both matter. On a sparse coupling graph, 39 CNOTs may serialize; ask for the routed depth alongside the count.
- Qubit assignment matters. The transpiler can place gates on low-fidelity qubits, so check the per-qubit error map rather than the device average.
- For a variational algorithm, shots times iterations can dominate the total error budget more than the per-circuit count.
- For a fault-tolerant target, ask for logical T-count or magic-state count instead; physical CNOT count is not the currency there.
How to settle it: transpile both candidates with the same optimization level and seed, compare routed two-qubit counts and estimated success, then confirm with a noisy simulation or a short hardware run. Source-level metrics are not evidence.
Curated: · Written: · Reviewed:
Q&A-4You need a probability estimated to one percent. How many shots do you budget?
My answer to the Born rule and shot noise starts from the resource count rather than from the asymptotic claim.
A measured probability is a binomial estimate, so its standard error is the square root of p times one minus p over the shot count. One percent absolute accuracy near p equal to one half needs about 2,500 shots, and one tenth of a percent needs 250,000.
Concretely, derive the shot count from the accuracy the decision requires, then state the resulting confidence interval next to every reported probability instead of quoting the point estimate alone.
The reason for that specificity is a failure I have seen: A team declared a circuit fix successful because a probability moved from 0.512 to 0.523 over 1,024 shots, a difference well inside the 0.016 standard error, and the change was later shown to have no effect at all.
Shots against accuracy near p = 0.5.
| Shots | Standard error | Useful for |
|---|---|---|
| 1,024 | 0.016 | coarse checks |
| 4,096 | 0.008 | routine comparison |
| 250,000 | 0.001 | calibration-grade claims |
I would not consider it settled without evidence: Recompute the standard error from the shot count and require the observed change to exceed several times that interval before it is called a change.
Quote the interval or the number means nothing.
Curated: · Written: · Reviewed:
Q&A-105How do you decide how many shots a circuit needs?
Shots are a statistical budget, not a quality dial. First I write down what the run has to decide and what precision that decision needs, then I compare the sampling error at the planned shot count against every non-sampling error in the stack. If sampling isn't the dominant term, more shots converge you to the wrong number with tighter error bars.
For a Pauli observable P with eigenvalues ±1 measured in its eigenbasis, the estimate is a mean of N Bernoulli draws:
SE(⟨P⟩) = sqrt((1 − ⟨P⟩²)/N).
Worst case ⟨P⟩ = 0 gives SE = 1/sqrt(N). Halving the error costs 4× the shots.
| target SE on ⟨P⟩ | shots (worst case) |
|---|---|
| 0.1 | 100 |
| 0.03 | ~1,100 |
| 0.01 | 10,000 |
| 0.003 | ~111,000 |
import numpy as np
def shots_for_pauli(expectation, target_se):
# Var(<P>) = (1 - <P>^2)/N for P with eigenvalues +-1
return int(np.ceil((1 - expectation**2) / target_se**2))
For a Hamiltonian H = Σ cᵢPᵢ measured in M commuting groups, variances add: Var = Σᵢ cᵢ²(1 − ⟨Pᵢ⟩²)/Nᵢ, and the shot-optimal split across groups is Nᵢ ∝ |cᵢ|·sqrt(1 − ⟨Pᵢ⟩²). So the honest answer for an energy is a per-group allocation, not one number.
Then the part that actually decides the question: is sampling what's limiting you? Run the circuit at N and at 4N shots. If the mean moves by more than the error bar shrank, you have systematic error, not shot noise. The usual culprits:
- Readout bias. 2% asymmetric readout error puts roughly a 0.02 bias on ⟨Z⟩: larger than the 0.01 SE you bought with 10,000 shots. Correct the readout matrix before spending shots.
- Drift. T1, qubit frequency and crosstalk move over minutes. More shots average over a drifting parameter. Split the shots into ten batches and compare batch means against the sqrt(N_batch) prediction; excess scatter is drift, and the fix is shorter runs or interleaved calibration, not more shots.
- Correlated noise. Leakage and cosmic-ray events give heavy tails, so the multinomial SE underestimates. A chi-square test of the histogram against the multinomial prediction catches it.
- Biased estimator. Ratio estimators and small-probability estimates carry O(1/N) bias that can exceed the statistical error when p is tiny.
I increase shots when the decision margin is only a few SE wide, the device is stable across the run, and the estimator is unbiased. Otherwise I change the estimator:
- Group commuting Paulis so one set of shots serves several terms: cuts total shots by the group count.
- Classical shadows when many observables are needed from one state: O(log M) measurement settings instead of one per observable.
- Amplitude estimation when the circuit is small enough to afford the extra depth: error scales as 1/N rather than 1/sqrt(N).
- Parameter-shift versus SPSA for gradients: 2 evaluations per parameter versus 2 total, trading gradient noise for shot count.
For an A-versus-B comparison I size shots to separate the difference at about 3 SE of the difference, and interleave A and B so drift cancels. And I report the shot count alongside the result: an expectation value without its error bar isn't a result.
Curated: · Written: · Reviewed: —
Q&A-36What happens if you run Deutsch-Jozsa on a function that is neither constant nor balanced?
Before trusting anything about the promise in Deutsch-Jozsa I would write down what a wrong answer would look like.
The algorithm returns an answer anyway, and the answer is meaningless. Its all-zeros outcome probability is the squared magnitude of the average of minus one to the f of x, so a function that is zero on three quarters of its inputs returns all zeros about 25 percent of the time and is reported as constant.
Concretely, treat the promise as an input precondition the caller must establish, and either verify it separately or use an algorithm that does not require it.
The reason for that specificity is a failure I have seen: A demonstration wrapped Deutsch-Jozsa around an unverified predicate; on inputs outside the promise it reported constant 1 run in 4 and the results were used to justify a design decision that was wrong.
Outcome probability against the function.
| Function | P(all zeros) | Reported |
|---|---|---|
| constant | 1.00 | constant |
| balanced | 0.00 | balanced |
| 75% zeros | 0.25 | constant 1 run in 4 |
I would not consider it settled without evidence: Feed the implementation a function outside the promise and confirm the output is unusable rather than merely noisy.
A promise is an assumption, not a check.
Curated: · Written: · Reviewed:
Q&A-38You do not know how many items are marked. How do you run Grover?
I would answer unknown solution counts in amplitude amplification by separating what the mathematics guarantees from what the device delivers.
The fixed schedule is unusable because it depends on M, and guessing wrong rotates past the optimum. The standard answers are quantum counting to estimate M first, or an exponentially increasing randomized schedule that finds a solution in expected order square root of N over M queries without knowing M.
Concretely, pick the randomized schedule when a single solution suffices and counting when the number itself is the answer, and specify the zero-solution behaviour separately.
The reason for that specificity is a failure I have seen: A search assumed one marked item on an instance that had four; 804 iterations is exactly twice the 402 that four solutions require, so the amplitude landed back at a trough and the marked items were returned about once in a million shots, which was read as hardware noise.
Fixed schedule for M = 1 on other instances.
| Actual M | Optimal iterations | Run at 804 |
|---|---|---|
| 1 | 804 | 1.00 |
| 4 | 402 | 0.000001 |
| 0 | none | undefined output |
I would not consider it settled without evidence: Run the chosen strategy against instances with 1, 4 and 0 solutions and confirm the reported success rate in each case.
Unknown M is a different algorithm, not a tuning problem.
Curated: · Written: · Reviewed:
Q&A-37How many Grover iterations do you run over a million candidates?
The number: 804 iterations. For N = 2²⁰ ≈ 1.05 million and one marked item, the optimum is k = round((π/4)·√(N/M) − ½) = round(0.7854 × 1024 − 0.5) = 804. The exact form matters more than the approximation: the rotation angle is θ = arcsin(√(M/N)), and after k iterations the state has rotated by (2k+1)θ, so you want (2k+1)θ = π/2. That is where the −½ comes from.
Why it is a maximum, not a limit. Grover is a rotation in the two-dimensional subspace spanned by the good and bad superpositions. Each iteration rotates by 2θ, so the success probability is sin²((2k+1)θ): it rises to 1 at π/2 and falls back. There is no plateau to sit on, and no "run a few more to be safe".
| Iterations | Success probability |
|---|---|
| 400 | 0.50 |
| 804 | 0.9999998 |
| 1,608 | 5×10⁻¹¹ |
Check it yourself.
import math
N, M = 2**20, 1
theta = math.asin(math.sqrt(M / N))
k = round((math.pi / 4) / theta - 0.5) # (2k+1)*theta = pi/2
p = math.sin((2 * k + 1) * theta) ** 2
print(k, p) # 804 0.9999998
Trade-offs: the part that decides the design.
Known M vs unknown M. The formula needs M. If you do not have it: (a) quantum counting (Brassard–Høyer–Tapp) runs phase estimation on the Grover operator to estimate M, at roughly the cost of the search itself, then you run the right k; (b) exponential search (Boyer–Brassard–Høyer–Tapp 1998) tries k = 1, 2, 4, 8, … measuring after each, landing within a constant factor of the known-M optimum without ever knowing M; (c) fixed-point quantum search (Yoder–Low–Chuang 2014) converges monotonically to error δ at the cost of a log(1/δ) factor in iterations. Take (b) when M is unknown and you want one answer, (a) when you need M itself.
Partial iterations. You do not have to reach π/2. Since p = sin²((2k+1)θ), k(p) ≈ (2/π)·arcsin(√p)·k_opt: half the iterations buys about half the success probability. That is only worth it if you have a reason to stop early, because for a fixed iteration budget one run at k_opt beats two runs at k_opt/2: 1 − 0.5² = 0.75 against ≈1.
Large M. When M is a non-trivial fraction of N, θ is not small and the small-angle form π/4·√(N/M) breaks down. At M = N/4, θ = π/6 and a single iteration already gives certainty; for M > N/4 just measure directly, because the first rotation overshoots.
Oracle cost. Each iteration is one oracle call plus one diffusion. If the oracle is a deep circuit (a hash preimage check, say) the constant per iteration can eat the quadratic. The speedup is in query count, not wall clock.
When Grover is the wrong tool. Unstructured search is the only setting where it is provably optimal (Bennett–Bernstein–Brassard–Vazirani 1997: Ω(√N) queries). If the problem has structure, classical algorithms can beat √N: SAT solvers, meet-in-the-middle, lattice reduction. If a classical heuristic already returns the solution with probability p, amplitude amplification on that biased start needs O(1/√p) iterations, which can be far below √N. And if you need all M solutions rather than one sample, the cost is Θ(√(NM)): the quadratic speedup is per-sample.
Failure mode. The one I have seen: doubling "to be safe". At 1,608 iterations the rotation lands at 3217θ ≈ π, and sin² ≈ 5×10⁻¹¹: 8,192 shots return nothing. Detect it by plotting success against k on a small instance (N = 2¹⁰, M = 1, k_opt = 25) and confirming the peak sits where the formula predicts.
Curated: · Written: · Reviewed:
Q&A-39Where does the cost of a Grover search actually go?
The 60-second answer. Query complexity counts oracle invocations; it is not the cost. The cost is the compiled two-qubit gate count of the full schedule (oracle plus diffuser, per iteration, times the iteration count) and in a fault-tolerant estimate, the T-count and the surface-code volume that T-count forces. For N = 2^20 the optimal iteration count is ⌊(π/4)√N⌋ = 804. That number is where the accounting starts, not where it ends.
Assumptions: the oracle is a classical predicate you must synthesize into a reversible circuit, not handed to you as a black box; you are estimating fault-tolerant cost; N = 2^20.
Where the gates go. Each iteration is one oracle call plus one diffuser. The diffuser is a phase flip on |0…0⟩, i.e. an n-controlled Z. For n = 20 the standard decomposition uses 2(n−2) = 36 Toffolis; at 6 CNOTs each that is ~216 CNOTs before the oracle is counted at all. The oracle is usually at least as expensive again, because a reversible predicate must compute the predicate into an ancilla and then uncompute it to free the workspace: you pay twice for the same logic. So ~432 two-qubit gates per iteration is a reasonable planning figure, and 804 × 432 ≈ 350,000 two-qubit gates for the whole search.
Why the query count misleads. 804 sounds tractable. 350,000 two-qubit gates at a 0.5% per-gate error rate gives an expected 1,750 faults; the probability of a clean run is e^−1750, i.e. zero. The query count hid four orders of magnitude of physical work.
Which currency to report, and when.
| Metric | Right when | Blind spot |
|---|---|---|
| Query count | Oracle is a true black box; comparing algorithmic scaling | Ignores oracle synthesis entirely |
| Two-qubit gate count | Near-term feasibility, depth-limited hardware | Ignores T-count and magic-state cost |
| T-count | Fault-tolerant resource estimate | Ignores Clifford overhead and routing |
| Physical qubits × time | Hardware budget, comparing architectures | Depends on code distance and error rate |
Deciding criterion: what are you comparing? If it is two algorithms sharing the same oracle, query count is fine and gate count is noise. If it is "can this run on hardware," query count is the wrong currency and you must compile.
Failure mode. The one I have seen: a proposal quoted 804 queries as the cost of the search. Compiled against the real predicate, the schedule was ~350,000 two-qubit gates. The number that decided feasibility was never in the query count.
What would change my answer. If the oracle is genuinely given as a black box by the problem statement (proving a lower bound, or comparing two algorithms that share it) then query count is the correct currency and compiling it is wasted effort. In the fault-tolerant regime, two-qubit gate count is itself a proxy: the T-count and the code distance it forces dominate, and a circuit with fewer CNOTs but more T gates can be the more expensive one.
Curated: · Written: · Reviewed:
Q&A-40How would you describe Grover to someone who is not searching a list?
Grover's algorithm is amplitude amplification. The list search everyone learns is one instance. The general statement: given any procedure A that prepares a state, and any way to recognise the states you want, you can raise the probability of seeing a wanted state from p to near 1 in about (π/4)/√p iterations.
Each iteration: apply A†, reflect about |0⟩ (flip the sign of every amplitude except the all-zeros state), apply A, then reflect about the good subspace (flip the sign of the marked states). Two reflections, one preparation and its inverse. The composition is a rotation in the two-dimensional plane spanned by "good" and "bad", by angle 2θ where sin θ = √p. After k iterations the success probability is sin²((2k+1)θ).
Search is the case A = H^⊗n, p = M/N, oracle = the marking function. Nothing in the mechanism needs a list. A could be a state-prep circuit for a SAT assignment, a subroutine that samples a collision, a quantum-walk step, or a routine that prepares a feasible solution to a constrained optimisation problem. If you can prepare and you can check, you can amplify.
When it wins: p is small, the oracle is cheap, and A is cheap enough that you can afford A and A† per iteration. When it does not: p is already close to 1 (the rotation overshoots. You can pass the target and come back down, so zero iterations is optimal), the oracle costs more than re-running A, or you cannot implement A† at all, since amplification needs the inverse.
The failure mode I would flag first is cost accounting. The "quadratic speedup" is in oracle calls, not in wall clock. Amplification multiplies whatever A costs by the iteration count, and each iteration runs A and A†.
Worked example, p = 0.04. θ = arcsin(0.2) = 0.2014 rad. Optimal k = round(π/(4θ) − 1/2) = round(3.900 − 0.5) = 3 iterations. Success after 3: sin²(7 × 0.2014) = sin²(1.4095) = 0.974.
| Approach | Preparation runs | Success |
|---|---|---|
| classical repetition | 90 | 0.974 |
| amplitude amplification, 3 iterations | 6 | 0.974 |
Classical: 1 − 0.96^90 = 0.974. Amplification: 3 iterations × (A + A†) = 6 preparation runs. The gain is 90/6 = 15×, not 1/p = 25×. If A is a deep circuit, that 15× can disappear into the constant factor.
One-line version: Grover turns a procedure that succeeds with small probability into one that succeeds almost surely, at a cost of about 1/√p repetitions of that procedure and its inverse, and list search is just the case where the procedure is a uniform superposition.
Self-assessment
Key points / rubric:
- State that Grover is amplitude amplification, not just list search.
- Describe the iteration: A†, reflection about |0⟩, A, reflection about good subspace.
- Give the rotation picture and the success probability formula.
- Explain when it helps and when it does not (cost of A and A†, p near 1).
- Flag that the speedup is in oracle calls, not wall clock.
- Provide a concrete worked example with numbers.
What interviewers look for:
- Can you generalise beyond the textbook list search?
- Do you understand the mechanism (reflections, rotation) rather than just the O(√N) result?
- Do you account for the cost of state preparation and its inverse?
- Can you identify failure modes (overshooting, expensive A, no A†)?
- Do you give a concrete example with correct arithmetic?
Weak-answer patterns:
- Reciting "Grover searches an unsorted list in O(√N)" without mentioning amplitude amplification.
- Claiming a quadratic speedup in wall-clock time.
- Ignoring the cost of A and A†.
- Forgetting that the number of iterations must be chosen carefully; too many reduces success.
- No worked example or incorrect arithmetic.
Follow-up questions:
- How does amplitude amplification relate to quantum walks?
- What happens if there are multiple marked states?
- How do you choose the number of iterations if p is unknown?
- Can you use amplitude amplification when A is not unitary?
- How does this compare to classical random sampling?
Curated: · Written: · Reviewed:
Q&A-41Grover returns a candidate. What do you do with it?
Measure the register, get a candidate x, then evaluate f(x) classically. That one evaluation is the answer to the question. Grover hands you a candidate, not a proof.
Why it is mandatory: the oracle is a unitary O|x⟩ = (−1)^{f(x)}|x⟩. A black box. You cannot read the marked set out of it or ask it which items it flagged. And the output is probabilistic: after k iterations P(success) = sin²((2k+1)θ), with θ = arcsin√(M/N). You pick k to push that near 1; the circuit never guarantees it. The only way to know whether the candidate is a solution is to evaluate f on it yourself.
Worked trace. N = 4 items, one marked (index 3). θ = arcsin(1/2) = 30°, optimal k = round(π/(4θ) − ½) = 1.
import numpy as np
N_QUBITS, MARKED = 2, 3 # N = 4 items, one marked
N = 1 << N_QUBITS
def f(x): # the predicate the oracle encodes
return x == MARKED
def grover(k):
psi = np.full(N, 1/np.sqrt(N))
for _ in range(k):
psi[MARKED] *= -1 # oracle: flip the marked amplitude
psi = 2*psi.mean() - psi # diffusion about the mean
return psi
for k in (1, 2):
psi = grover(k)
print(f"k={k} amplitudes={np.round(psi,3)} P(marked)={psi[MARKED]**2:.3f}")
Output:
k=1 amplitudes=[ 0. 0. 0. 1.] P(marked)=1.000
k=2 amplitudes=[-0.5 -0.5 -0.5 0.5] P(marked)=0.250
Hand trace of k=1: start [½, ½, ½, ½]; oracle flips index 3 → [½, ½, ½, −½]; mean = ¼; diffusion ψ_x ← 2·¼ − ψ_x → [0, 0, 0, 1]. Measure → 3, verify f(3) = True.
k=2 (overshoot): oracle → [0, 0, 0, −1]; mean = −¼; diffusion → [−½, −½, −½, ½]. P(3) = 0.25. Three runs in four you measure a non-solution, and verification is what catches it.
Cost. N = 2^20, M = 1: θ = arcsin(2⁻¹⁰) ≈ 9.7656×10⁻⁴, k = round(π/(4θ) − ½) = 804.
| k | (2k+1)θ | P(solution) |
|---|---|---|
| 0 | 0.00098 | 9.5×10⁻⁷ |
| 402 | 0.786 | 0.50 |
| 804 | 1.5713 | 0.9999998 |
| 1608 | 3.1416 | 8.8×10⁻¹¹ |
One verification call against 804 oracle calls is 0.12% overhead. Verification costs roughly 1/√N of the search, so wherever Grover is worth running it is noise. It stops being free when N is small: N = 100, √N = 10, one check is 10% of the run. But if f is so expensive you cannot afford one extra call, Grover's √N speedup is already the wrong tool.
Failure modes.
- Overshoot. Doubling k from 804 to 1608 drives (2k+1)θ to π and P(solution) to 8.8×10⁻¹¹. More iterations destroy your odds. Verification catches it in one evaluation.
- Inverted comparison in the oracle marks the complement. Every candidate is wrong; without verification the error surfaces downstream weeks later.
- M = 0. Grover returns a near-uniform sample; verification rejects it and you learn M = 0 instead of trusting a hit.
- Unknown M. You cannot set k. Run quantum counting (Brassard, Høyer, Tapp) to estimate M first, then set k. A failed verification with a k you believe optimal points at the oracle, not the schedule.
The measured state has collapsed, so you cannot re-measure it: re-run from a fresh state preparation.
When I would skip it. Only when the predicate is approximate, a heuristic score or sampling target, and a wrong hit is cheap. For a correctness-critical result, never. Verification is one evaluation; the alternative is a silent wrong answer.
Self-assessment
Key points a strong answer hits:
- Measure, then classically evaluate f on the candidate. Verification is mandatory, not optional.
- The oracle is a black-box unitary; the output is probabilistic, sin²((2k+1)θ).
- Verification costs roughly 1/√N of the search.
- Failure modes: overshoot, inverted oracle, M = 0, unknown M.
- Re-run from fresh state preparation; quantum counting when M is unknown.
What interviewers look for:
- Do you know Grover is probabilistic and the oracle is opaque?
- Can you quantify the verification cost instead of hand-waving it?
- Do you name concrete failure modes and how you would detect them?
- Do you know when verification is not free: small N, expensive f?
Weak-answer patterns:
- "Measure and you are done": treats the candidate as a guaranteed solution.
- "Re-measure the register": ignores collapse.
- "Just run more iterations to be sure": the overshoot trap.
- No numbers: no k, no success probability, no overhead figure.
- Confusing the oracle with a readable function.
Follow-up questions:
- How do you choose k when M is unknown?
- What happens if you run 2k iterations?
- How would you detect an oracle that marks the complement?
- When is verification not worth its cost?
- How does this change for amplitude estimation rather than search?
Curated: · Written: · Reviewed:
Q&A-35Which multi-qubit entangled state would you choose if one qubit may be lost?
Choose W when a qubit can be lost and the survivors still have to do something. GHZ is the wrong default for that job: lose one qubit and the rest are left in a classical mixture with zero entanglement, so a protocol that assumed a shared entangled resource keeps running on nothing.
Assumptions: loss is the dominant error, the identity of the lost qubit is known (heralded erasure, or erasure conversion), and the surviving qubits must remain usable without re-preparing the whole state.
Why the two states differ
Take three qubits and trace one out.
|GHZ> = (|000> + |111>)/√2. Trace out qubit 3. The remaining pair is (|00><00| + |11><11|)/2: a 50/50 classical mixture. Concurrence 0.
|W> = (|001> + |010> + |100>)/√3. Trace out qubit 3. The |001> branch leaves |00> on the pair; the |010> and |100> branches leave |01> and |10>. So
ρ₁₂ = (1/3)|00><00| + (2/3)|Ψ+><Ψ+|, with |Ψ+> = (|01> + |10>)/√2.
Concurrence 2/3. The pair is still entangled. Among three-qubit states, W is the one that leaves the most entanglement in a surviving pair: that is the whole content of "loss-robust".
| State | Survivors after one loss | Concurrence | Max CHSH |
|---|---|---|---|
| GHZ | `( | 00><00 | + |
| W | `(1/3) | 00><00 | + (2/3) |
The second row is the part people miss. The survivors are entangled, but 1.89 < 2, so they cannot violate CHSH. W buys you a working pair, not a device-independent one.
Trade-offs
W's residual entanglement is weaker than a fresh Bell pair (2/3 against 1), and W is worse than GHZ for anything needing the full N-party correlation: GHZ maximally violates Mermin-type N-party inequalities and gives Heisenberg-limited phase estimation, 1/N scaling against the 1/√N standard quantum limit. If the protocol needs that, pick GHZ and handle loss by encoding rather than by state choice: the [[4,1,2]] code (Grassl, Beth, Pellizzari, PRA 56, 33, 1997) corrects one erasure and keeps the logical qubit alive.
Failure modes
- GHZ with undetected loss. The protocol keeps running on a classical mixture and returns wrong answers with no error signal. Catch it by checking the stabilizers: the
X⊗X⊗XandZ⊗Z⊗Zparities fail as soon as a qubit is gone. - W with loss. It survives, but the residual pair sits below the CHSH threshold, so any self-testing or device-independent step fails. Catch it by measuring the concurrence of the survivors, not just their presence.
- Confusing loss with decoherence. W's advantage is specific to loss. Under local depolarizing noise the ranking can flip, so loss-robust does not mean noise-robust. If loss is unheralded you cannot distinguish a lost qubit from a measurement error, and neither state helps.
Curated: · Written: · Reviewed:
Q&A-42The QFT is often called exponentially faster than the FFT. Is it?
No, not as a transform. The QFT and the FFT compute the same linear map, the DFT on 2^n amplitudes, but they are not comparable objects. The QFT is exponentially cheaper in gates and exponentially more expensive to read. The exponential speedup people quote is real only inside an algorithm that consumes the transformed state and emits one classical answer.
The gate counts. On n qubits the exact QFT is n Hadamard gates plus one controlled-phase rotation per pair j<k: n(n−1)/2 rotations, n(n+1)/2 gates total. At n=20 that is 210 gates. The FFT on 2^20 = 1,048,576 points costs about (n/2)·2^n = 10·2^20 ≈ 1.05×10^7 complex multiplications. The QFT is ~5×10^4 cheaper to run. That ratio is the whole basis of the "exponentially faster" claim.
Why it doesn't survive contact with the output. The QFT's output is a quantum state: 2^n complex amplitudes you cannot look at. Recovering them takes full state tomography: 4^n − 1 Pauli measurements, each needing O(1/ε²) shots for accuracy ε. At n=20 that is 4^20 ≈ 1.1×10^12 measurement settings, about 10^5 times the cost of just running the classical FFT. The gate saving is paid back, with interest, the moment you want the vector.
Where the speedup is real. Inside an algorithm that consumes the transformed state and emits one classical value. Phase estimation is the canonical case: m ancilla qubits, an inverse QFT costing O(m²) gates, and one measurement that returns m classical bits of the eigenvalue. Nothing is tomographed; interference does the extraction. Shor's algorithm is this pattern: the published resource estimate for RSA-2048 is ~20 million physical qubits and 8 hours (Gidney & Ekerå, Quantum 5, 433, 2021), on roughly 4,000 logical qubits, with the QFT a small slice of the gate budget.
Approximate QFT. Rotations below a threshold angle 2π/2^m are dropped, keeping only pairs with |k−j| ≤ m. That gives O(nm) gates instead of O(n²); m = O(log n) keeps the approximation error negligible for the algorithms that use it (Coppersmith, 1994). At n=20, m=7 gives 20 + 140 = 160 gates against 210 exact: a modest saving, and the reason real circuits quote O(n log n).
Failure mode. A team swaps an FFT for a QFT in a signal-processing pipeline, then finds the downstream step needs the transformed vector rather than one scalar, and pays the tomography cost. Detection is cheap and belongs at design time: count the classical numbers the algorithm must output. More than O(1) and the QFT buys nothing; exactly one (a phase, a period, a factor) and the speedup is real and the tomography never appears.
| Transform | Cost to run | Output you can read |
|---|---|---|
| FFT, 2^n points | ~n·2^{n−1} complex mults | all 2^n amplitudes |
| QFT, n qubits | n(n+1)/2 gates | one sampled outcome |
| QFT + tomography | + 4^n − 1 Pauli measurements | all 2^n amplitudes |
Curated: · Written: · Reviewed:
Q&A-43How many ancilla qubits does phase estimation need?
The short answer. For the standard QFT-based phase estimation, the ancilla (precision) register needs
t = n + ⌈log₂(2 + 1/(2ε))⌉
qubits to return the phase to n bits with success probability at least 1 − ε. For a coin-flip success probability (ε = 0.5) that is t = n + 2, so 8 bits of precision costs 10 ancillas and 16 bits costs 18.
Why that count. The t ancillas are the readout register. Hadamards put them in a uniform superposition, controlled-U^(2^j) writes the phase into their relative phases, and the inverse QFT turns that into a t-bit binary fraction. The register width sets the resolution: the estimate is the phase rounded to a multiple of 2^-t, so two eigenvalues closer than 2^-t cannot be told apart. The n bits are the precision the downstream decision needs; the extra ⌈log₂(2 + 1/(2ε))⌉ qubits exist so the rounding lands in the correct bin with probability 1 − ε instead of being aliased into a neighbour.
The cost that actually bites. Ancillas are cheap; the controlled-U applications are not. Applying controlled-U^(2^j) for j = 0 … t−1 means 2^j executions of controlled-U each, so the total is
Σ_{j=0}^{t-1} 2^j = 2^t − 1.
Each extra ancilla doubles that. The ancilla count is therefore a budget decision, not a rounding detail.
| Precision n | Ancillas t (ε = 0.5) | Controlled-U applications |
|---|---|---|
| 8 | 10 | 1,023 |
| 16 | 18 | 262,143 |
Going from 8 to 16 bits multiplies the controlled-U count by 256.
The alternative to raise. Iterative (semi-classical) phase estimation uses a single ancilla qubit. It measures one bit of the phase at a time, feeding the previous result back as a classical rotation before measuring the next, so it needs mid-circuit measurement and classical feed-forward, and it runs the controlled-U circuit t times instead of holding t qubits. Kitaev's original formulation is the same idea. Choose it when qubits are the scarce resource and coherence or repetition rate is not; choose the standard register when you want the answer in one shot and the device has the width.
Failure modes. Under-provisioning t aliases the phase: you recover the true phase modulo 2^-t and can silently pick the wrong eigenvalue. Detect it by checking the estimate against a classically known eigenvalue, or by running with t+1 and seeing whether the answer moves. Over-provisioning is the opposite failure: a design that asked for 16 bits "for margin" where 8 sufficed multiplied the controlled-U count by 256 and blew the coherence budget. The check is arithmetic: compute 2^t − 1 from the precision you actually need and compare it against the device's coherence time divided by the duration of one controlled-U.
Curated: · Written: · Reviewed:
Q&A-44Which part of Shor's algorithm actually runs on the quantum computer?
Only the order-finding subroutine runs on the quantum computer. The rest of Shor's algorithm is a classical wrapper.
Assume N is an odd composite that is not a prime power. Pick a random a with 1 < a < N. If gcd(a,N) > 1, you already have a factor and never touch the quantum computer. Otherwise you need the multiplicative order of a modulo N: the smallest r > 0 with a^r ≡ 1 (mod N).
The quantum part is phase estimation on the unitary U|y> = |a y mod N>. The circuit performs controlled modular exponentiation and an inverse quantum Fourier transform. Measurement yields a bitstring that estimates s/r for some integer s. That is the only quantum work. Everything after is classical: continued fractions turn the measured phase into r, then you check r is even and a^{r/2} ≠ -1 (mod N). If both hold, gcd(a^{r/2} - 1, N) and gcd(a^{r/2} + 1, N) give nontrivial factors. If not, retry with a new a. For a random a, the success probability is at least 1/2, so the expected number of bases is at most 2.
Alternatives and deciding criteria. Classically, you can find the order with baby-step giant-step in O(√r) modular multiplications, which is exponential in log N. Quantum order finding is polynomial in log N. So the quantum subroutine is worth running only when you have fault-tolerant qubits and N is large enough that classical order finding is infeasible. For small N, or when N has small factors, trial division or ECM finds factors without any quantum call. For RSA-sized N today, classical GNFS is the practical alternative because fault-tolerant hardware does not exist at the required scale. Within the quantum subroutine, you can use QFT-based phase estimation or iterative phase estimation. Iterative uses one ancilla and classical feedback, reducing qubit count at the cost of more repetitions; QFT-based uses more ancillas but fewer measurements. The deciding criterion is whether you are qubit-limited or depth-limited.
Failure modes. If r is odd, or a^{r/2} ≡ -1 (mod N), the classical extraction fails; detect by checking those conditions and retry. If phase estimation returns a bad s/r (for example s = 0 or s sharing a factor with r), continued fractions may not recover r; detect by verifying a^r ≡ 1 (mod N). If the modular exponentiation circuit is wrong, order finding returns garbage; the classical verification catches it. Without error correction, quantum errors make the measured phase random.
Here is the classical driver. Only the call to quantum_order_finder is quantum.
def shor(N):
while True:
a = random.randrange(2, N)
g = gcd(a, N)
if g > 1:
return g
r = quantum_order_finder(a, N) # only quantum call
if r % 2 == 1:
continue
x = pow(a, r // 2, N)
if x == N - 1:
continue
return gcd(x - 1, N), gcd(x + 1, N)
| Step | Runs on | What it does | Failure mode |
|---|---|---|---|
| Choose a | classical | random 1 < a < N, gcd(a,N)=1 | gcd > 1 gives factor immediately |
| Order finding | quantum | phase estimation on U | y> = |
| Recover r | classical | continued fractions on measured phase | r odd or a^{r/2} ≡ -1; retry |
| Extract factors | classical | gcd(a^{r/2} ± 1, N) | trivial factors; retry |
The quantum computer is a subroutine inside a classical loop.
Curated: · Written: · Reviewed:
Q&A-45Phase estimation gives you a noisy phase. How do you get an integer order from it?
The 90-second answer. Phase estimation returns an m-bit approximation φ of s/r, where r is the order of a mod N and s is some integer. Run the continued-fraction expansion (CFE) of φ. Among its convergents, take the one whose denominator q satisfies q < N; that q is your candidate order. Verify it: compute a^q mod N. If that is 1, you have r. If not, the sample was bad: discard it and run phase estimation again. Discarding samples is the algorithm working, not a bug.
Why CFE recovers r. The measured φ satisfies |φ − s/r| ≤ 2^−m. Legendre's theorem says that if |φ − s/r| < 1/(2r²), then s/r appears as a convergent of φ. Since r < N, it suffices that 2^−m < 1/(2N²), i.e. m ≥ 2⌈log₂N⌉ + 1. The qubit count is chosen to make the error small enough that the true fraction is guaranteed to be a convergent. The denominator bound q < N then picks it out: convergents with q ≥ N are too large to be the order.
Worked trace. N = 15, a = 7. The order is r = 4 (7⁴ = 2401 ≡ 1 mod 15). Take m = 9, so φ is a multiple of 2^−9. Suppose phase estimation returns φ = 0.25390625 = 130/512, close to the true s/r = 1/4.
CFE of 130/512:
512 = 3·130 + 122
130 = 1·122 + 8
122 = 15·8 + 2
8 = 4·2 + 0
So 130/512 = [0; 3, 1, 15, 4]. Convergents:
| Convergent | Value | Denominator |
|---|---|---|
| [0] | 0/1 | 1 |
| [0;3] | 1/3 | 3 |
| [0;3,1] | 1/4 | 4 |
| [0;3,1,15] | 16/63 | 63 |
| [0;3,1,15,4] | 65/256 | 256 |
The largest denominator below N = 15 is 4. Candidate r = 4. Check 7⁴ mod 15 = 1. ✓
Trade-offs. Two knobs. More qubits (larger m) shrinks the error so CFE almost always succeeds, but each run costs a deeper circuit. Fewer qubits means more discarded samples and more phase-estimation runs. The standard choice m = 2⌈log₂N⌉ + 1 sits where the error bound is just satisfied. You can also skip CFE and round φ to the nearest fraction with denominator < N, but rounding alone can land on the wrong denominator when φ is near a boundary; CFE is what gives the guarantee.
Failure modes and detection. Three ways a sample fails, all caught by the same check a^q ≡ 1 mod N:
- Error too large: φ is closer to a wrong convergent, so q ≠ r. Happens when m is too small or the run is unlucky.
- gcd(s, r) = d > 1: CFE returns r/d, a proper divisor of the order. The probability that gcd(s, r) = 1 is φ(r)/r, so this is common.
- s = 0: φ = 0, CFE gives denominator 1.
In every case, verify and retry. The expected number of phase-estimation runs is O(1): a constant number of retries suffices with high probability.
Curated: · Written: · Reviewed:
Q&A-46A paper factors 21 on a small device. What does that tell you about RSA?
Almost nothing about RSA's security, unless the circuit scales with the number's bit length. The tell is whether the modular exponentiation was compiled with knowledge of the factors.
Shor's algorithm's cost is dominated by the modular exponentiation: the controlled multiplication of a quantum register by a^x mod N. If you already know the period (equivalently, the factors), you can replace that generic circuit with a small constant one that just emits the right output. The 2012 photonic experiment that factored 21 (Martín-López et al.) used 5 qubits and a compiled modular exponentiation. It demonstrates control and readout of a small quantum system, not the arithmetic that makes RSA hard.
| Implementation | Qubits | Runs on unknown input |
|---|---|---|
| compiled with known period | 5 | no |
| generic modular arithmetic | ~2n+3 logical | yes |
For 21 (n = 5 bits), a generic circuit needs on the order of 2n+3 ≈ 13 logical qubits: small, but the point is the scaling, not the constant. For RSA-2048, Gidney and Ekerå's 2021 estimate puts it at roughly 20 million physical qubits running for 8 hours, with error correction. That gap, 5 qubits versus 20 million, is what the demo does not close.
So the questions I would ask: does the qubit count grow with the modulus? Would the circuit run on an input whose factors were unknown? If either answer is no, the paper is a hardware milestone, not a cryptanalytic one.
A demonstration that needs the answer has not computed it.
Curated: · Written: · Reviewed:
Q&A-47What would it actually take to factor RSA-2048?
The short answer. Breaking RSA-2048 means running Shor's algorithm on a fault-tolerant quantum computer. The best current published estimate is Gidney and Ekerå (Quantum 5, 433, 2021): about 20 million physical qubits for roughly 8 hours, assuming a 0.1% (1e-3) physical error rate, a 1 µs surface-code cycle, and code distance 27. A 2025 construction (Gidney, arXiv:2505.15917) trades time for space and reports under a million physical qubits at a runtime on the order of a week. There is no classical shortcut: GNFS on a 2048-bit modulus is estimated at roughly 2^110 operations.
Why those numbers. Shor's algorithm reduces factoring to period-finding, which is dominated by modular exponentiation: about 2n modular multiplications of n-bit numbers for n=2048. Each modular multiplication is built from Toffoli gates, so the Toffoli count scales roughly as n²: on the order of a billion to a few billion Toffoli gates. That count is the whole problem. Every Toffoli consumes a distilled magic state, and the magic-state factories, not the arithmetic, dominate the physical qubit budget: in the 2021 design most of the 20 million qubits sit in factories producing T states at the rate the arithmetic consumes them.
Code distance follows from the error budget. A distance-d surface code uses 2d²−1 physical qubits per logical qubit and suppresses the logical error rate roughly as (p/p_th)^((d+1)/2). With p=1e-3 and a threshold near 1e-2, d=27 gives a logical error rate per cycle around 10^-14; over the ~3×10^10 cycles in an 8-hour run that is a ~10^-4 chance of a logical failure. d=27 costs 2·27²−1 = 1457 physical qubits per logical qubit, so 20 million physical qubits is only about 13,700 logical qubits: the factories are most of them.
Estimates and their assumptions.
| Estimate | Physical qubits | Runtime | Assumptions |
|---|---|---|---|
| Fowler et al. 2012 | ~10^9 | — | surface code, p≈1e-3 |
| Gidney–Ekerå 2021 | ~2×10^7 | ~8 h | p=1e-3, 1 µs cycle, d=27 |
| Gidney 2025 | <10^6 | ~1 week | p=1e-3, 1 µs cycle |
Trade-offs. Space and time are interchangeable: you can buy runtime with fewer factories (the 2025 result) or buy speed with more (the 2021 result). Physical error rate is the highest-leverage assumption: drop p from 1e-3 to 1e-4 and the required distance falls, cutting physical qubits per logical qubit sharply. Factory design matters too: different distillation protocols and injection schemes change the qubits-per-T-state cost. And the operational question is usually harvest-now-decrypt-later: an adversary records ciphertext today and decrypts when a machine exists, so what matters is whether your data's lifetime exceeds time-to-CRQC, not the estimate alone.
What actually breaks. If the physical error rate is at or above threshold (~1%), increasing distance makes things worse, not better: the estimate collapses. Leakage out of the computational subspace and correlated errors (cosmic rays, control crosstalk) violate the independent-noise assumption the threshold model rests on. Real-time decoding at a 1 µs cycle is a hard classical problem; a decoder that can't keep up stalls the machine. And a run that fails just fails: you detect it by classically multiplying the returned factors, not by any internal signal.
What to quote. Any estimate with its assumptions attached: error rate, cycle time, code distance, factory design, arithmetic circuit. If someone hands you a qubit count with no error rate and no cycle time, ask for those two numbers first; they move the answer more than anything else.
Curated: · Written: · Reviewed:
Q&A-48Does a quantum computer halve every key length?
No. The premise folds two different quantum attacks into one, and only one of them is a halving, and even that one halves the security level, not the key length.
Shor's algorithm halves nothing. It solves factoring and discrete log in polynomial time, so RSA-2048 and ECDH P-256 aren't weakened, they're gone. Key size doesn't rescue them: RSA-4096 falls to the same algorithm with a larger polynomial. Grover's algorithm is the one that halves, and it applies to unstructured search: brute-forcing a symmetric key, inverting a hash. It turns a 2^n search into roughly 2^(n/2) oracle queries. AES-128's key stays 128 bits long; what drops from 128 to about 64 is the work factor an attacker needs.
| Primitive | Classical security | Quantum attack | Post-quantum security |
|---|---|---|---|
| RSA-2048 | ~112 bits | Shor | broken |
| ECDH P-256 | ~128 bits | Shor | broken |
| AES-128 | 128 bits | Grover | ~64 bits |
| AES-256 | 256 bits | Grover | ~128 bits |
| SHA-256 preimage | 256 bits | Grover | ~128 bits |
| SHA-256 collision | 128 bits | BHT | ~85 bits |
That last row matters: collision resistance doesn't halve, it drops to about 2^(n/3) under Brassard–Høyer–Tapp, putting SHA-256 collisions near 2^85. "Halve everything" is wrong even inside the symmetric world.
Grover also needs an oracle, a known plaintext/ciphertext pair or a hash target, to recognize the right key when it sees it. No verification predicate, no search.
Then the caveats on the 2^64 figure itself. It's an oracle-query count, not a wall clock. Each Grover iteration evaluates the full cipher as a reversible circuit, so the gate count sits far above 2^64, and the whole run has to stay coherent: that's the error-correction bill, and it's the reason 2^64 queries is not a 2^64-time attack. Grover parallelizes badly too: k independent searches cut the iteration count by sqrt(k), not k, so total work is unchanged and you buy only a sqrt(k) wall-clock improvement. Zalka showed this in 1999. The quadratic speedup is also optimal for unstructured search (BBHT), so nobody is going to find a better generic attack on AES: that assumption is safe to build on.
What this means for a migration plan: the urgent work is key establishment and long-lived signatures, because traffic recorded today can be decrypted once a cryptographically relevant machine exists. Symmetric primitives are a parameter review, move to AES-256 and SHA-384 where the margin matters, not a replacement programme. Doubling the key restores the security level exactly, which is why the symmetric side is cheap and the public-key side is not.
The failure mode to watch for: a plan that spends two quarters swapping symmetric primitives while ECDH key establishment stays classical. Detection is mechanical: inventory the protocol, tag each primitive "broken by Shor" or "halved by Grover", and check that the Shor-broken ones have owners and dates. If the symmetric items have dates and the key-establishment items don't, the sequencing is backwards.
Curated: · Written: · Reviewed:
Q&A-49Why would you migrate key establishment before any quantum computer exists?
The 90-second answer
Assume the question is about confidentiality of data with a long secrecy lifetime, not about signatures. The reason to migrate key establishment now is harvest-now-decrypt-later: an adversary records TLS sessions today and decrypts them once a cryptographically relevant quantum computer (CRQC) exists. Shor's algorithm breaks the key exchange (ECDHE, finite-field DH) protecting those sessions, so the exposure window opens at capture, not at the machine's arrival. If the data must stay secret for 25 years and a CRQC plausibly lands in 10-15, ciphertext captured today is already compromised in the future. Signatures are a different problem: forging one needs the machine, so there is no harvest-now-forge-later equivalent for a one-time authentication.
So migrate key establishment for long-lived confidential data first, and let the trigger be the data's secrecy lifetime, not the estimated CRQC date.
Mechanism and what to migrate to
Shor breaks RSA, DH, ECDH and ECDSA. Grover only halves symmetric strength, so AES-256 and SHA-384 stay fine: bulk encryption needs no change. The replacement for key establishment is ML-KEM (FIPS 203, from CRYSTALS-Kyber), standardized August 2024. NIST IR 8547 (initial public draft) targets deprecating RSA/ECDH by 2030 and disallowing them after 2035; CNSA 2.0 requires ML-KEM-1024 for national security systems.
Trade-offs a real migration faces
- Hybrid vs pure PQC. Deploy X25519MLKEM768 (the IETF TLS hybrid group, on by default in Chrome since 2024) rather than pure ML-KEM. Hybrid keeps classical security if ML-KEM is later broken and is the only way to interoperate with peers that don't yet speak PQC. The cost is bytes.
- Performance. ML-KEM-768 encapsulation runs in tens of microseconds: CPU is not the problem. Bandwidth is: the ML-KEM-768 encapsulation key is 1184 bytes and the ciphertext 1088 bytes, against 32 bytes for X25519. That adds roughly 1.2 KB to each side of the handshake.
- Interoperability. The oversized ClientHello is the real failure mode: Chrome's 2023 Kyber experiment broke connections through middleboxes and servers that mishandled a ClientHello spanning multiple TCP segments. Certificate-based auth is worse, an ML-DSA-44 signature is 2420 bytes, and CA and HSM support lags.
When not to migrate yet
Skip key-establishment migration for data whose secrecy lifetime is shorter than the migration horizon (session auth, ephemeral tokens), for systems being decommissioned before ~2035, and for embedded devices with no update path where you would wait for a hardware refresh. Inventory them anyway.
What breaks, and what replaces it
| Primitive | Broken by | Replacement | Note |
|---|---|---|---|
| ECDH / DH (key establishment) | Shor | ML-KEM-768 (FIPS 203) | hybrid X25519MLKEM768 in TLS |
| RSA / ECDSA (signatures) | Shor | ML-DSA (FIPS 204) | larger certs, CA support lagging |
| AES-128 | Grover (halved) | AES-256 | no urgency |
| SHA-256 | Grover (halved) | SHA-384 | no urgency |
A cryptographic inventory (where keys live, how long each protected item must stay secret) is what sequences the work. The capture is the event that starts the clock.
Curated: · Written: · Reviewed:
Q&A-50How do you decide whether your migration is late without predicting a date?
You don't need a date for the quantum computer to decide whether you're late. You need three numbers and one comparison.
X is the confidentiality lifetime of your data: how long it must stay secret. Y is how long your migration actually takes. Z is when a cryptographically relevant quantum computer arrives. You are late when X + Y > Z. Since Z is unknown, compare against the earliest horizon you're willing to defend, Z_low. If X + Y exceeds Z_low, you are late under the pessimistic scenarios and should act. If X + Y sits below Z_low, you are not late under any scenario in the range, and you monitor. The date never enters the decision; only the lower bound of the horizon does.
The work is in X and Y, because both are usually underestimated.
Y is not the protocol change. It is the slowest component that has to move: firmware signing chains on deployed hardware, certificate re-issuance across a large estate, vendor dependencies you don't control. Measure Y from that component. If you cannot enumerate every place a key is used, your Y is a lower bound, not an estimate, and a lower bound on Y is the dangerous direction.
Worked example, with the horizon assumed rather than predicted:
| X: data lifetime | Y: migration | X + Y | Z_low assumed | Verdict |
|---|---|---|---|---|
| 25 | 7 | 32 | 10 | Late under every horizon |
| 5 | 3 | 8 | 10 | Not late; 2-year margin |
| 1 | 2 | 3 | 10 | Not late; agility still worth it |
Two responses compete with "start migrating now."
Invest in crypto-agility instead of accelerating the migration. If Y is dominated by hardware you cannot reflash, starting earlier does not shorten Y: the firmware still ships on its own cycle. What shortens the next migration is agility: hybrid key exchange, a crypto abstraction layer, an inventory of where keys live. Pick this when Y is hardware-bound.
Act on vendor signals instead of computing the sum. NIST standards and vendor roadmaps are real, but they lag: by the time a signal is unambiguous, the remaining Z may be shorter than Y. Use signals to sanity-check Z_low, not to trigger the decision.
The framework misleads in three cases. When X is near zero (session keys, ephemeral data) the sum is dominated by Y, and "not late" is true about exposure but wrong about priority; you still need agility. When Y is unknown because you have no crypto inventory, you cannot compute the sum, and unknown Y should be treated as late, because you cannot bound it. When Z_low is itself contested and the plausible range spans an order of magnitude, the verdict flips with the endpoint you pick; then decide on cost asymmetry, where migrating early costs churn and wasted effort and exposure costs irreversibly.
A plan I reviewed assumed 18 months because it counted server-side changes. The firmware signing chain on deployed hardware took 5 years. The real Y put the estate past every horizon the risk team had accepted.
Show the three numbers and the subtraction rather than asserting readiness, and re-run when an input changes (a new data class, a longer retention requirement, a vendor slipping) not on a calendar.
Curated: · Written: · Reviewed:
Q&A-51Which post-quantum algorithms do you deploy, and how do you choose?
Core answer (first 90 seconds). Assume you control the TLS terminator and the firmware-signing pipeline, and the deadline comes from policy, NIST IR 8547 deprecates RSA and ECC after 2030 and disallows them after 2035, rather than from a cryptanalytic break. You don't choose algorithms on cryptographic taste; you deploy the finalized standards: ML-KEM (FIPS 203) for key encapsulation, ML-DSA (FIPS 204) or SLH-DSA (FIPS 205) for signatures. The decision you actually make is the parameter set and where the byte growth lands.
| Scheme | Public key | Signature / ciphertext | Signing cost |
|---|---|---|---|
| X25519 / Ed25519 (classical) | 32 B | 64 B | ~0.05 ms |
| ML-KEM-768 | 1184 B | 1088 B ciphertext | n/a (encaps is fast) |
| ML-DSA-65 | 1952 B | 3309 B | ~0.1–0.3 ms |
| SLH-DSA-SHA2-128s | 32 B | 7856 B | hundreds of ms |
ML-DSA vs SLH-DSA. Both sign; pick per use. ML-DSA is lattice-based, fast to sign and verify, moderate signature size, larger public key. SLH-DSA is hash-based: its security rests only on hash preimage resistance, so it is the conservative choice if you distrust lattice assumptions, but signing is orders of magnitude slower and signatures run 7–50 KB. Put ML-DSA on the hot path (TLS certificate signatures, session auth). Put SLH-DSA where signatures are rare and you want assumption diversity: root CA, firmware release signing, long-lived code signing. Do not put SLH-DSA on a per-request path.
Hybrid is the interim default. X25519MLKEM768 (a 32-byte X25519 share plus a 1184-byte ML-KEM-768 share, 1216 bytes total) is what Chrome, Firefox and OpenSSL 3.5 negotiate by default. It keeps classical security if ML-KEM falls to new lattice cryptanalysis, at the cost of a bigger ClientHello. For signatures the equivalent hedge is a hybrid certificate, e.g. ECDSA plus ML-DSA.
When not to migrate. Don't migrate a system whose data has no harvest-now-decrypt-later exposure and whose stack can't carry the bytes: short-lived telemetry, an embedded device you can't reflash, a protocol with a fixed handshake buffer. Defer those, record the compensating control, and revisit when the stack can be updated: rather than shipping a handshake that fails in the field.
Failure mode. A rollout that swapped only the key exchange hit an embedded TLS stack with a fixed 4 KB handshake buffer; the ClientHello carrying the ML-KEM share no longer fit, the fleet could not be updated remotely, and 40,000 units needed a field visit. Detect it before rollout by running the chosen parameter set end to end against the real stack and the smallest device in the fleet, not against a reference implementation.
Curated: · Written: · Reviewed:
Q&A-52Why combine a classical and a post-quantum key exchange rather than switching outright?
The 90-second answer. You can't switch outright because the traffic you send today is decryptable later. An adversary recording TLS sessions now can decrypt them once a cryptographically relevant quantum computer exists: harvest-now-decrypt-later. So you want ML-KEM in the handshake as soon as it is usable. But ML-KEM (FIPS 203, finalised August 2024) is a young standard with young implementations, and its security rests on Module-LWE, an assumption with far less field time than the discrete-log problem behind X25519. A hybrid derives the session secret from both, so the session is secure if either holds. You get quantum resistance without betting the estate on the newer scheme being flawless.
How it is carried. In TLS 1.3 (RFC 8446) the key exchange rides in the key_share extension and the group is chosen from supported_groups. The hybrid group is X25519MLKEM768 (codepoint 0x11EC, draft-ietf-tls-ecdhe-mlkem); the earlier deployment used X25519Kyber768Draft00 (0x6399). The client sends both shares, the server replies with both, and the two shared secrets are concatenated and fed to HKDF-Extract. A flaw in one component's output does not compromise the other as long as the combiner is sound, which is why the combination belongs in the KDF, not in a wrapper around the transport.
What it costs. Sizes, from the specs:
| Component | Public / encapsulation key | Ciphertext |
|---|---|---|
| X25519 | 32 B | 32 B |
| ML-KEM-768 | 1184 B | 1088 B |
So the client's key_share grows by 1184 − 32 = 1152 bytes and the server's by 1088 − 32 = 1056 bytes. That ~1.2 KB is the real cost. The CPU cost is not: ML-KEM-768 encapsulation and decapsulation are on the order of tens of microseconds on a modern core, comparable to X25519, so you are paying bandwidth, not cycles.
Failure modes.
- Oversized ClientHello. The extra ~1.2 KB pushes the ClientHello past limits in some middleboxes and TLS terminators. Chrome's rollout of X25519Kyber768 (default from Chrome 124, April 2024) hit exactly this: a small fraction of connections failed until the offending boxes were fixed. This is the argument for negotiating the group rather than mandating it: a client that does not offer it falls back to X25519 with no flag day.
- Silent downgrade. If an attacker strips the hybrid group from
supported_groups, you get a classical-only session and never notice. Log the negotiated group per session so an incident can tell which traffic is affected. - Combiner bugs. If the implementation feeds only one secret into the KDF, you have the cost of a hybrid and the security of the weaker half. Test that both secrets are required.
Rollback. Because the group is negotiated, you can disable the hybrid by config if a flaw lands, without touching clients. That is the property that survives the next surprise.
Curated: · Written: · Reviewed:
Q&A-104Trotter error shrinks with more steps and circuit depth grows with them. On a noisy device, how do you choose the step count?
There's an optimum, and on today's hardware it's usually small. You're minimizing two errors that move in opposite directions: Trotter discretization, which falls as you add steps, and gate noise, which grows with the depth those steps add. The right r is the one that minimizes their sum, not the largest r that fits.
First-order Trotter, e^{-iHt} ≈ (∏j e^{-iH_j t/r})^r, has operator error ≈ (1/2) Σ{j<k} ||[H_j,H_k]|| t²/r. Write that as C t²/r: halving the error doubles the depth. Second-order symmetric Suzuki steps give O(t³/r²) at roughly twice the gates per step, so they win once your accuracy target is tight enough to pay for them.
Noise: with per-two-qubit-gate error p and L two-qubit gates per step, circuit infidelity is ≈ r L p for small p. Total ≈ C t²/r + r L p. Setting the derivative to zero gives r* = sqrt(C t² / (L p)). The 1/sqrt(p) is the part people miss: a noisier device wants fewer steps, not more.
Illustrative numbers: C t² = 0.1, L = 20, p = 1e-3.
- r=1: 0.100 + 0.020 = 0.120
- r=2: 0.050 + 0.040 = 0.090
- r=3: 0.033 + 0.060 = 0.093
- r=4: 0.025 + 0.080 = 0.105
Optimum near r=2. Doubling to r=4 "to be safe" costs 17% more total error. That's the tradeoff in one line.
In practice you don't trust C. Sweep r on the noiseless simulator to get the Trotter curve alone, then sweep on hardware to find where the noise floor bites. The energy-vs-r curve should fall, flatten, then rise; you operate at the minimum. If you can't afford a sweep, run r and 2r and Richardson-extrapolate, but only if you're in the asymptotic regime, which for small r you usually aren't.
Qiskit 1.x:
from qiskit.circuit.library import PauliEvolutionGate
from qiskit.synthesis import LieTrotter, SuzukiTrotter
from qiskit.quantum_info import SparsePauliOp
H = SparsePauliOp.from_list([("ZZ", 0.5), ("XX", 0.3), ("ZI", 0.2)])
first = PauliEvolutionGate(H, time=1.0, synthesis=LieTrotter(reps=2))
second = PauliEvolutionGate(H, time=1.0, synthesis=SuzukiTrotter(order=2, reps=2))
Two things people get wrong. Trotter error is coherent: it's a unitary you didn't want, so it biases the expectation value systematically and does not average out with more shots. And the error that matters is the one in the observable you're measuring, not the operator norm; if the commutator term is small on your state, you can take larger steps than the norm bound suggests.
When L is large and the terms are small, qDRIFT randomizes the term order and its error bound depends on (Σ_j ||H_j||)² rather than the commutator norms, which can beat deterministic Trotter at the same gate count. And in the fault-tolerant regime this calculus is wrong: you pay in T gates and magic states, and you take r large enough that Trotter error sits below the logical error rate.
Curated: · Written: · Reviewed: —
Q&A-53A device advertises T1 of 120 microseconds. What does that let you build?
The short answer
T1 = 120 µs is a relaxation time constant, not a gate count. It says an excited qubit's probability of still being excited falls to 1/e ≈ 37% after 120 µs: equivalently, about 63% of the population has decayed by then. What you can build is bounded by how many gates fit inside that window with acceptable error, and on a superconducting transmon that is a few hundred two-qubit gates at best, usually fewer once T2 and gate fidelity are counted.
The arithmetic
Two-qubit gates on current transmon hardware run around 300 ns. So:
| Circuit duration | Fraction of T1 | Survival e^(−t/T1) | Two-qubit gates at 300 ns |
|---|---|---|---|
| 12 µs | 0.1 | 0.90 | 40 |
| 30 µs | 0.25 | 0.78 | 100 |
| 60 µs | 0.5 | 0.61 | 200 |
| 120 µs | 1.0 | 0.37 | 400 |
That is per qubit, and it is only relaxation. Dephasing (T2) usually cuts the budget further: on transmons T2 ≤ 2·T1 by theory and in practice often lands near T1 or below. Gate infidelity adds on top: at 1e-3 error per two-qubit gate, 100 gates already costs about 10% fidelity before coherence enters.
So the honest reading: 120 µs buys a shallow circuit, tens to low hundreds of two-qubit gates, not a deep one.
What that lets you build
- Variational circuits: VQE or QAOA on 4–12 qubits with depth in the tens. These are designed around shallow ansätze precisely because coherence is the wall.
- State preparation and small algorithms: GHZ, small QFT, Bernstein–Vazirani, Grover on a handful of qubits.
- Benchmarking and characterization: randomized benchmarking, cross-entropy benchmarking, tomography on few qubits.
- Error-mitigated runs: zero-noise extrapolation or probabilistic error cancellation on circuits of roughly 50–100 gates, where the sampling overhead is still affordable.
What it does not let you build
Anything needing thousands of sequential two-qubit gates: full QFT on 20+ qubits, deep chemistry circuits with Trotter steps in the hundreds, Shor's algorithm at cryptographically relevant sizes. Those need coherence times two to four orders of magnitude longer, or error correction.
Alternatives when 120 µs is the constraint
- Dynamical decoupling (XY4, CPMG) on idle qubits extends effective T2 during the circuit: free depth if your compiler inserts it.
- Error mitigation trades sampling cost for effective depth. PEC overhead grows exponentially in gate count, so it helps at 50–100 gates, not 1000.
- Circuit compilation: reduce SWAPs, route to the best-connected qubits, use native gates. A 30% depth reduction is often cheaper than a better device.
- If the algorithm needs more depth than the device allows, the answer is a different backend or a simulator for small instances, not a clever workaround.
Failure mode to watch
Coherence is per qubit, not per chip. A device datasheet quoting 120 µs is quoting the best qubit. The qubits your router picks may have T1 of 40 µs and T2 of 25 µs, which is roughly 80 two-qubit gates. I have seen a workload projected against a 140 µs best-qubit T2 land at a third of the expected success rate because the actual layout used qubits near 45 µs. Read T1 and T2 for the physical qubits in the chosen layout, from the same calibration record as the run.
Curated: · Written: · Reviewed:
Q&A-58Your qubits idle for long stretches. What can you do without changing the algorithm?
Insert dynamical decoupling (DD) into the idle windows: a train of π pulses that refocuses low-frequency dephasing. It is suppression, not correction: no logical state is protected, the qubit just accumulates less phase error while it waits. It is also not the only lever. If the scheduler is leaving qubits idle, better qubit mapping, gate scheduling, or reusing idle qubits for mid-circuit measurement and reset can shrink the idle window itself, and that is usually cheaper than adding pulses.
Why an echo works. A qubit's phase relative to the drive drifts as φ = ∫ ω(t) dt, where ω(t) is the noise-induced frequency offset. A π pulse about X flips the sign of the accumulated phase. Split an idle interval into two halves with a π pulse in the middle: the second half accumulates the opposite sign, so a constant offset cancels exactly. Real noise is not constant, it has a correlation time τ_c, and cancellation is good only while the pulse spacing τ stays below τ_c, so the noise looks quasi-static across each interval. For 1/f flux noise in transmons, τ_c is typically microseconds to tens of microseconds, which is why DD spacings of ~1 µs or less are common. If τ exceeds τ_c, the pulses refocus nothing and only add error.
Sequences differ in what they cancel and how they tolerate pulse error:
| Sequence | Pulses | Cancels |
|---|---|---|
| XpXm | 2 | static offset, first order |
| CPMG | N, equal spacing | static + first order, robust to one-axis pulse error |
| XY4 | 4 | static + first order, robust to pulse-area error on both axes |
| XY8 | 8 | same, better for low-frequency 1/f noise |
Compilers can insert these for you: Qiskit's transpiler has a PadDynamicalDecoupling pass, with XY4Sequence, XpXmSequence and CPMGSequence in qiskit.circuit.library.
Whether it helps is arithmetic. Take a hypothetical transmon with T2* = 30 µs and echo T2 = 100 µs, and an idle window of 100 µs. Without DD the free-induction decay is exp(-(100/30)²) ≈ 1.5e-5: the qubit is effectively gone. With DD spacing well under τ_c, the decay is governed by T2: exp(-100/100) ≈ 0.37. That is the whole case for DD: it converts a T2* decay into a T2 decay.
The failure mode is the opposite regime. Each π pulse has finite fidelity, on good hardware on the order of 1e-3 error per single-qubit gate, so a train of 100 pulses adds ~10% error before it suppresses anything. DD also drives leakage to |2⟩ and can crosstalk into neighbouring qubits, so it must not run on qubits being measured or read out. A poorly chosen spacing (τ > τ_c) or a sequence applied to a circuit with little idle time adds pulse error with no refocusing benefit.
Detect it by measuring, not assuming: compare the workload's fidelity with and without the sequence on the same qubits in the same calibration window, and check the idle fraction from the schedule. If idle time is comparable to or shorter than T2*, DD is a net loss; if it is many times T2*, it is the cheapest win available without touching the algorithm.
Curated: · Written: · Reviewed:
Q&A-57You transpiled yesterday and submit today. What can go wrong?
A transpiled circuit is not a portable program. It is a physical layout (specific qubit indices, native gates, and inserted SWAPs) chosen to minimise error against the backend's calibration at the moment you transpiled. Submit it a day later and you are running yesterday's layout on today's device. If the calibration moved, the layout is stale: the qubits you picked may no longer be the best, the routing may no longer be the shortest, and a qubit may have been taken offline entirely.
So: re-transpile against the backend immediately before submit, or cache the ISA circuit together with the calibration timestamp it was built against and re-transpile whenever that timestamp changes.
What transpilation actually consumes
transpile(circuit, backend=backend) reads the backend's coupling map, per-qubit and per-gate error rates, readout errors, T1/T2, and gate durations, then picks an initial layout and a routing. Every one of those inputs is a snapshot. The output references physical qubits by index; nothing in it re-checks the device at execution time.
What changes overnight
| Change | Effect on yesterday's layout |
|---|---|
| Coupler disabled for maintenance | Routing SWAPs now take a worse path, or the job fails validation |
| Two-qubit gate error on a chosen pair rises | Layout is no longer the low-error choice |
| T1/T2 on a chosen qubit falls | Idle qubits decohere through a longer effective circuit |
| Readout error rises | Measurement bias grows; mitigation calibrated to old rates is wrong |
| Backend version or gate set changes | Cached ISA circuit may not validate at all |
Why the damage is silent
The job usually still returns counts. You get a worse distribution, not an error, so the failure looks like an algorithm problem. Illustrative arithmetic: a circuit with 40 two-qubit gates at 0.99 fidelity each has expected success ≈ 0.99^40 ≈ 0.67. If the chosen pair degrades to 0.97, that becomes 0.97^40 ≈ 0.30: less than half, with no warning.
Detection and fix
from qiskit import transpile
def isa_for_now(circuit, backend, cached=None):
# Calibration the cached ISA circuit was built against.
# API differs by backend version: BackendV1 exposes
# backend.properties().last_update_date; BackendV2 backends
# expose properties() only if the provider supplies them.
now = backend.properties().last_update_date
if cached is None or cached["calibration_ts"] != now:
isa = transpile(circuit, backend=backend,
optimization_level=3,
seed_transpiler=1234)
return isa, now
return cached["isa"], cached["calibration_ts"]
Record calibration_ts and the backend version alongside every result. If you cannot re-transpile, at least compare the timestamp the layout was built against with the one at execution.
Trade-offs
Re-transpiling costs wall-clock time (seconds to minutes for large circuits) and, with a stochastic seed, changes the layout between runs, which breaks run-to-run comparability. For an A/B comparison, fix seed_transpiler and initial_layout so only the variable under test moves, but still re-validate that the pinned qubits are healthy before each submission. Pinning a layout for weeks is the trap: it is exactly the cached-circuit failure above.
Failure modes to name
- Silent degradation: counts return, fidelity drops, algorithm blamed.
- Job rejection: layout references a qubit no longer in the coupling map.
- Miscalibrated mitigation: readout-error mitigation built from stale rates.
- Broken comparability: layout changed between runs, so the delta is hardware, not code.
A layout is only valid for the calibration it was chosen under.
Curated: · Written: · Reviewed:
Q&A-54Two devices report the same error rate and one runs your circuit far worse. What could differ?
The number on the datasheet is almost always a randomized-benchmarking average: error per Clifford or per gate. RB inserts random Clifford gates, which twirl whatever the physical error is into an effective stochastic Pauli channel. That twirling is the problem: it erases the distinction between a stochastic error and a coherent one, and those two accumulate completely differently.
A stochastic error adds in probability: after N gates the infidelity is ≈ N·p. A coherent error: a systematic over-rotation, a miscalibrated pulse, crosstalk that adds a fixed small rotation: adds in amplitude: after N gates the state has been rotated by N·ε, so the infidelity goes as sin²(Nε/2), which is ≈ N²·ε²/6 for small angles. Same RB number, quadratic instead of linear growth.
Worked example. Both devices report p = 1e-3 per gate. Device A is stochastic. Device B has a coherent over-rotation of ε = √(6p) = 0.0775 rad (4.4°), which has the same average gate infidelity ε²/6 = 1e-3 under the average-gate-infidelity convention.
| Depth N | A: stochastic N·p | B: coherent sin²(Nε/2) |
|---|---|---|
| 10 | 0.010 | 0.14 |
| 20 | 0.020 | 0.49 |
| 30 | 0.030 | 0.84 |
At depth 30 the coherent device is essentially wrong while the stochastic one sits at 3%. That is "same error rate, far worse circuit."
Other things that differ
- Crosstalk and context dependence. RB runs one qubit (or one isolated pair) at a time. A real circuit runs neighbours simultaneously; ZZ coupling and frequency collisions make the error rate depend on what the neighbours are doing. The RB number is a best case.
- Leakage. Errors that push population to |2⟩ or outside the qubit subspace are not captured by a two-level RB analysis, and they accumulate.
- Idling decoherence. RB gates are back-to-back with no idle time. A real circuit has qubits waiting through T1/T2 while others are gated; the reported gate error says nothing about that.
- What the number measures. Readout error, SPAM, or a per-layer versus per-gate convention can dominate the reported figure.
- Compilation and routing. Same native gate fidelity, different connectivity → different SWAP overhead → different depth. The device with worse connectivity runs the same logical circuit deeper.
- Calibration drift. The number is a snapshot; the device may have drifted since it was measured.
How to tell them apart
Run the same gate (or a structured circuit) repeatedly and plot infidelity against depth, then fit against the linear prediction N·p from the RB number. Superlinear growth means coherent.
# same gate repeated N times, measure survival probability
for N in [1, 5, 10, 20, 30, 50]:
infid = 1 - run_circuit([gate] * N, shots=4000)
# fit infid vs N: slope ~ p (stochastic) or curvature ~ N^2 (coherent)
Confirm with interleaved RB, purity benchmarking, or gate-set tomography. Randomized compiling (Pauli-twirling the circuit) converts coherent errors into stochastic ones, if the circuit then matches the RB prediction, the error was coherent.
What to do
Recalibrate the systematic rotation; apply randomized compiling so the linear model holds; avoid scheduling the crosstalk pair together. More shots do not fix a coherent error: it is a bias, not noise.
Curated: · Written: · Reviewed:
Q&A-55Your gates benchmark well individually and the circuit still fails. What do you check next?
What a strong candidate says first. Isolated benchmarks and the circuit are different experiments, so the first move is to name what the circuit adds and order the checks by cost. "Fails" also needs pinning: is the output distribution wrong (a coherent or leakage error), or is fidelity just below the threshold you budgeted (an incoherent budget miss)? Those point at different checks.
The circuit differs from the isolated benchmark in four ways: gates run in parallel (crosstalk), qubits that aren't being addressed still decohere (spectators), the run takes longer (drift, T1/T2), and every result passes through readout (SPAM). Isolated RB holds the first three fixed and subtracts the fourth.
Order the checks cheapest-first.
- Readout. Measure the assignment matrix. It is minutes of work and it is the one error that is not a gate at all. At 2% readout error per qubit, a 5-qubit circuit carries ~10% SPAM before any gate fires.
- Drift. Re-run the isolated benchmark immediately before and after the circuit run. If the isolated number moved, the circuit did not fail: the calibration did.
- Parallel pattern. Run simultaneous RB or a layer-fidelity measurement on the exact parallel layer the circuit uses. This is the only check that isolates crosstalk.
The discriminator. Compare the measured layer error to the independent sum of the isolated gate errors. The gap is context error, and how it scales tells you which of the four it is:
| How the excess scales | Cause | Check |
|---|---|---|
| with number of simultaneous pairs | crosstalk | simultaneous RB on the exact layer |
| with circuit duration, not parallelism | decoherence, drift | isolated RB before/after; idle-qubit RB |
| constant offset, independent of both | readout, leakage | assignment matrix; leakage RB ( |
Worked arithmetic (illustrative). Four CZ gates at 0.3% isolated error each. Independent sum per layer: 1 − 0.997⁴ = 1.19%. Measured layer error: 2.1%. Gap 0.9 points per layer. Over 20 layers: naive budget 1 − 0.9881²⁰ = 21% failure; measured 1 − 0.979²⁰ = 35%. That gap is what "benchmarks well, circuit fails" looks like, and it is crosstalk-shaped because it scales with the pair count.
Trade-offs and mitigation. Serializing the layer removes crosstalk but adds depth: four parallel CZ become four sequential, three extra gate times per layer. At ~40 ns per CZ against a T2 of order 100 µs that is 120 ns, cheap. It stops being cheap when the circuit already sits near the coherence limit, or when the extra depth breaks a latency budget. The alternatives are detuning the offending pair apart during the layer, or having the scheduler choose a different pairing. Both cost calibration time and constrain the compiler.
Failure modes to name. RB is leakage-blind: a gate that leaks to |2> can look fine in RB and poison the circuit; measure |2> population directly. Simultaneous RB on a pattern the circuit does not use tells you nothing. And a single "crosstalk" number hides that only one pair in the layer is bad: measure per-pair.
Curated: · Written: · Reviewed:
Q&A-16Your algorithm assumes all-to-all connectivity and the device is a lattice. What does that cost?
Assume the device is a lattice: nearest-neighbour two-qubit gates only, qubit degree 2 on a line, up to 3 on IBM's heavy-hex coupling map, up to 4 on a Google-style grid, and on the order of 1% two-qubit gate error on current superconducting hardware. My algorithm assumed any pair could interact. On that device every non-adjacent interaction becomes routing, and routing is SWAPs. One SWAP is exactly 3 CX gates (plus single-qubit gates if CX is directional), so a single long-range two-qubit gate between qubits d hops apart costs roughly 3(d-1) extra two-qubit gates if one qubit walks to its partner.
The part that matters is that the penalty does not stay a constant factor. Take n qubits on a sqrt(n) x sqrt(n) grid and one layer in which every qubit interacts with an arbitrary partner. At least n/2 of those pairs straddle the grid's bisection, and that cut is only about sqrt(n) edges wide, so at least n/2 SWAPs, 3n/2 two-qubit gates, have to cross it, and since each edge carries one SWAP at a time the depth is at least sqrt(n)/2 SWAPs, which is 1.5*sqrt(n) two-qubit gate layers. A fully-connected interaction pattern therefore costs depth that grows as sqrt(n) with machine size, on top of the gate-count blowup. All-to-all is a hardware bill, not a free abstraction.
Worked example, 5-qubit line, 12-CX circuit at depth 18. Illustrative figures, not a device benchmark: at 1% per two-qubit gate, the 27 extra CX gates the trivial layout inserts leave 0.99^27 = 0.76, losing about 24% of shots; at 1.5% per gate it is 0.985^27 = 0.67, a third.
| Layout | SWAPs | CX | Depth |
|---|---|---|---|
| trivial (default) | 9 | 39 | 45 |
| interaction-aware | 2 | 18 | 24 |
Each SWAP contributes 3 CX and, where it cannot overlap other routing, 3 layers of depth: 18 + 27 = 45 for the trivial layout, 18 + 6 = 24 for the other.
Reproduce it by transpiling the same circuit twice onto the target coupling map. Qiskit 1.x:
from qiskit import transpile
from qiskit.transpiler import CouplingMap
coupling = CouplingMap.from_line(5) # degree-2 device model
basis = ["rz", "sx", "x", "cx"]
def cost(layout):
t = transpile(circuit, coupling_map=coupling, basis_gates=basis,
layout_method=layout, routing_method="sabre",
optimization_level=1, seed_transpiler=7)
return t.count_ops().get("cx", 0), t.depth()
print(cost("trivial"), cost("sabre"))
Three levers move the number, in this order of payoff: picking the layout from the algorithm's interaction graph, rewriting the algorithm to a lattice-native interaction pattern, and using hardware with all-to-all connectivity (trapped ions, neutral-atom arrays that shuttle). The third is not free either: it trades routing for slower two-qubit gates and qubit transport time.
Failure modes I would watch for: depth rising past the qubits' coherence budget while idle qubits decohere during the waits; SWAPs scheduled in parallel on neighbouring pairs hitting crosstalk; a router leaving a permutation in place so a later gate costs more rather than less; and reported depth being an upper bound the device does not hit at its quoted fidelity. Detect all of them by transpiling the same circuit under both layouts on the real coupling map, comparing CX count and depth, then running both on hardware and comparing measured fidelity: never the compiler's estimate alone.
Curated: · Written: · Reviewed:
Q&A-103Your circuit's two-qubit gates act on pairs that are not adjacent in the device's coupling map. How do you choose the initial layout, and when would you route by hand instead of taking the transpiler's default?
The first 90 seconds
Mapping splits into two decisions: the initial layout, which logical qubit sits on which physical qubit, and routing, inserting SWAPs when a two-qubit gate's operands aren't adjacent in the coupling map. The transpiler default (SABRE-style layout plus swap insertion) is the right starting point for a one-off circuit. I override it in three cases: the circuit has a repeated block I can amortize a hand-picked layout over, the algorithm has a natural subgraph embedding, or calibration data shows the default layout is landing gates on the worst CX pairs.
What routing actually costs
On a CX-native device, one SWAP = 3 CX. So routing costs (number of SWAPs) × 3 extra CX, plus the depth those add to the critical path. On a device with a native iSWAP-family gate, a SWAP is one gate up to single-qubit phases, and the arithmetic changes by 3×.
For a random circuit on an L×L grid, the average Manhattan distance between two random qubits is about 2L/3, so a random two-qubit gate needs roughly that many SWAPs: about 2√N extra CX per gate on an N-qubit grid. That is why a circuit that looks cheap on paper gets expensive on a lattice.
Worked trace: five qubits in a line 0–1–2–3–4, and I need CX(q0, q4). The router does SWAP(3,4), SWAP(2,3), SWAP(1,2), then CX(0,1): 9 + 1 = 10 CX over 4 layers, against 1 CX in 1 layer if the pair were adjacent.
The detail that matters: those SWAPs do not have to be uncomputed. A router tracks the permutation and relabels the final measurements: classically free. Undoing them costs another 9 CX for nothing. If you hand-route, keep the permutation map and apply it to the classical register at the end.
Default or custom
| Situation | Do this |
|---|---|
| One-off shallow circuit | Accept default layout and routing |
| Repeated block (Trotter step × 50) | Transpile once, reuse the layout; routing cost amortizes |
| Algorithm has a natural subgraph (1D chain, star) | Seed initial_layout to that subgraph |
| Default layout lands on bad CX pairs | Noise-aware layout, re-checked after recalibration |
Failure modes
- Optimizing CX count while depth blows up. On a device with T2 in the tens of microseconds, a depth-200 circuit can decohere even with fewer gates. Read both numbers off the transpiled circuit, not just the operation counts.
- Stale calibration. A layout chosen because pair (3,4) had the best CX yesterday is a guess today; calibration drifts on the order of hours. Re-run layout selection per calibration cycle, or pin a layout you have validated and accept the loss.
- Stochastic transpilation. Different seeds give different depths: often 10–30% apart on the same circuit. Run a handful of seeds, keep the best, and record which one.
- Forgotten measurement relabeling. Hand-route without applying the permutation and your histogram is a permutation of the right answer, which reads as a plausible wrong result.
If pushed further
Routing is a graph-embedding problem with no exact polynomial solution at scale; SABRE is a heuristic that is good enough most of the time. The judgement call is whether the circuit's structure gives you information the heuristic does not have. If it does not, take the default and spend your effort elsewhere.
Curated: · Written: · Reviewed: —
Q&A-17How do you tell whether a circuit is too deep for a device before you run it?
What a strong candidate says first
"Too deep" only means something against a target and a success bar, so pin those down first: which device, which physical qubits after routing, and whether you need one correct bitstring or an expectation value averaged over shots. Then compare the circuit's scheduled duration on that device against the coherence times of the qubits it actually touches. Gate count and circuit.depth() are the wrong metric: depth() counts layers, so it scores a CX and a single-qubit rotation the same, and it has no idea that a routed SWAP is three CXs.
The screen is duration over T2. Idle coherence decays as exp(-t/T2), so at duration = T2 you are at 0.37 amplitude, and at 2x T2 you are at 0.14. Below roughly 0.2x T2, decoherence is not what is killing you; gate error is.
Getting the number
from qiskit import transpile
from qiskit_ibm_runtime import QiskitRuntimeService
backend = QiskitRuntimeService().backend("ibm_brisbane") # BackendV2
isa = transpile(circuit, backend=backend,
optimization_level=3,
scheduling_method="alap", # required for isa.duration
seed_transpiler=7)
duration_s = isa.duration * backend.dt # dt = seconds per sample
used = {isa.find_bit(q).index for q in isa.qubits}
t2 = {q: backend.target.qubit_properties[q].t2 for q in used}
print(duration_s, min(t2.values()), duration_s / min(t2.values()))
Checked against Qiskit 1.x with qiskit-ibm-runtime. isa.duration is in units of backend.dt; without scheduling_method it is None. Read T2 from the same backend.target you transpiled against: calibration drifts, and T2 varies several-fold across qubits on one device, so a number from last week's record or from a different qubit is not evidence.
Two circuits, near-identical gate count
| Circuit | CX | Scheduled duration | Min T2 used | duration/T2 | exp(-t/T2) |
|---|---|---|---|---|---|
| A | 400 | 18 us | 90 us | 0.20 | 0.82 |
| B | 420 | 210 us | 90 us | 2.33 | 0.10 |
B is the one that fails, and nothing in its gate count says so. This is the failure I have seen: a 400-gate circuit accepted on gate count, routing stretched its critical path to 210 us against a T2 of 90 us, the counts came back flat, and three days went into hunting a logic bug that was decoherence.
Where the screen is too crude
Total duration assumes every qubit idles for the whole window. A qubit that is gated throughout has its decoherence folded into the gate error rates instead, so the ratio is an upper bound on the damage, not the damage. The refinement is per-qubit idle time: walk the scheduled circuit and sum the gaps for each qubit. A qubit that waits 180 us of a 210 us window for its partner in a long-range CX sits at exp(-180/90) = 0.135 even though the circuit's own gates are fine.
Two more ways it misleads:
- T2 from a Ramsey experiment (T2*) is usually shorter than the echo T2 a vendor reports, because it includes low-frequency drift. Comparing against T2* makes a workable circuit look hopeless. Use the same quantity the calibration record publishes.
- The scheduled duration includes the terminal measurements. The state you care about is fixed before them, so the coherence-relevant window ends at the last gate.
When duration is not the whole story
Duration screens decoherence; it says nothing about accumulated gate error. Multiply the per-gate errors from backend.target["cx"][(i, j)].error along the critical path, then multiply by the idle factor: that product is your expected success probability, and it is the number to compare against your bar. If you need one correct bitstring out of 2^50, 1% per-shot fidelity is fatal; if you are estimating an expectation value over 10^5 shots, it may be fine.
If the estimate is borderline, do not guess: measure it cheaply. Insert a delay sweep into the circuit and watch the signal decay, or append the inverse of the circuit and check the return probability. Either costs one job and gives you the effective coherence of this circuit on this device, which is what you actually wanted.
Curated: · Written: · Reviewed:
Q&A-56Why is leakage worse for error correction than an ordinary bit flip?
Core answer. A bit flip is an error the code is built to see: it stays inside the two-level computational subspace, it shows up in the stabilizer syndrome, and it is corrected on the round it happens. Leakage leaves that subspace: population sits in |2> or higher, so it is not a Pauli error, the decoder's model does not contain it, and nothing corrects it that round. It then persists for many rounds and spreads through two-qubit gates, so one leakage event becomes a correlated, time-correlated fault. The threshold theorem assumes faults are independent and local; leakage breaks both assumptions at once.
Why each property matters.
-
Outside the code's alphabet. Stabilizer codes are defined on qubits, and syndrome extraction measures Pauli operators. A leaked qubit can return a trivial syndrome (looks like no error) or a random one, so the decoder either ignores it or mis-corrects. A decoder cannot correct an error its model excludes.
-
Persists across rounds. A bit flip is reset by the correction each cycle. Leakage is not: in a transmon the leaked level decays at roughly twice the |1>→|0> rate, so with T1 ≈ 100 µs and a 50 ns two-qubit gate, leaked population survives on the order of 10³ gate times unless something actively removes it. Every round it survives is another round it can spread.
-
Spreads. A leaked control in |2> driving a CZ can move population into the partner's |2> level, because the |1>–|2> transition of one qubit is near-resonant with the |0>–|1> transition of the other. One leakage event becomes two, then four. A distance-d code only promises to correct ⌊(d−1)/2⌋ independent faults per logical operator.
| Property | Bit flip (Pauli) | Leakage |
|---|---|---|
| Inside computational subspace | yes | no ( |
| Visible in syndrome | deterministically | often not, or random |
| Lifetime | corrected each round | until decay, ~10³ gate times |
| Spreads via two-qubit gates | no | yes |
| Fits threshold model | yes (independent faults) | no (correlated, time-correlated) |
Trade-offs: three places to attack it.
- At the source: pulse shaping (DRAG) and tunable couplers cut leakage per gate. Cheapest per cycle, no decoder change, but it lowers the rate rather than removing it and constrains gate calibration.
- Detect and remove: a leakage detection unit maps |2> onto an ancilla flag, and a leakage reduction unit swaps the population back. The only option that stops accumulation, but it adds gates and cycle time, and the LRU is itself a new noise source.
- Leakage-aware decoding: feed the flag into the decoder (correlated / Pauli+-style decoding) so a leaked qubit is treated as an erasure rather than a Pauli error. No extra cycle time, but it needs the detection flag to exist and only helps if leakage is detected.
Deciding criteria: measured leakage per gate, whether syndrome extraction already produces a flag, and cycle-time budget. If leakage per gate is below ~10⁻⁴ and gates are short, source-level mitigation may be enough. If it accumulates over hundreds of rounds, you need detection plus removal.
Failure modes and how to see them. The signature is a logical error rate that stalls as you add rounds: more distance buys nothing because the dominant fault is correlated and outside the model. Detect it by measuring leakage population per qubit per round and checking it is reset rather than accumulating. Illustrative numbers from a distance-5 experiment: 1.1% logical error per cycle with no leakage handling, 0.32% with LRUs. Treat as illustrative, not a benchmark.
Curated: · Written: · Reviewed:
Q&A-61How can a code detect an error without measuring the logical state?
A stabilizer code detects errors by measuring the stabilizer generators, never the logical operators. The surface code is the one people actually build, so I'll use it.
The code space is the simultaneous +1 eigenspace of a set of commuting Pauli operators: the generators. An error E is detected because it anticommutes with at least one generator S. Measuring S returns +1 when the state sits in S's +1 eigenspace and −1 when E has flipped it. That −1 is a syndrome bit. Every generator commutes with every logical operator, so measuring generators cannot change the logical amplitudes: the syndrome reports that an error occurred without revealing or disturbing the encoded value.
Concretely, the 3-qubit repetition code. Generators S1 = Z1Z2 and S2 = Z2Z3; logical states |000> and |111>; logical X = X1X2X3. Start in |000>: both generators return +1, syndrome (0,0). Apply X1. X1 anticommutes with S1 but commutes with S2, so S1 → −1, S2 → +1, syndrome (1,0), which points at qubit 1; applying X1 corrects it. Now apply the logical X1X2X3: it commutes with both generators, syndrome (0,0), invisible. That is the distance doing its job: the code corrects one error and cannot see a weight-3 logical operator by construction.
One round is not enough, because the extraction circuit is itself noisy and a single round cannot separate a data error from a measurement error: both flip a syndrome bit. You repeat extraction and match syndromes across rounds in a space-time graph. For a distance-d code (d is the code distance, the minimum weight of an undetectable logical operator) you repeat on the order of d times, because a chain of d measurement errors can mimic a logical error.
| Rounds | Distinguishes data vs measurement error | When it's the right choice |
|---|---|---|
| 1 | no | measurement far more reliable than gates; detection only |
| ~d (d = code distance) | yes | fault-tolerant correction |
Real numbers: Google's 2023 surface-code experiment (Nature 614, 676) ran d=3 and d=5 surface codes and measured a logical error per cycle of roughly 3.0% at d=3 and 2.9% at d=5, giving Λ ≈ 2.14. Each increase of distance by 2 roughly halves the logical error rate. A d=3 surface code uses 9 data qubits plus 8 ancillas, 17 physical qubits per logical qubit.
When fewer rounds suffice: if measurement fidelity is much higher than gate fidelity (trapped ions), or if you only need detection rather than correction, you can cut rounds. Flag qubits detect hook errors from weight-4 stabilizer measurement with fewer rounds than naive repetition. If only one error type matters, a repetition code is cheaper than a full surface code.
Failure modes. A measurement error read as a data error makes the decoder apply the wrong correction and inject a logical fault; you catch it by syndrome changes that no single error chain explains. A hook error, one fault in a weight-4 measurement circuit propagating to a weight-2 data error, cuts the effective distance; circuit-level noise simulation or flag qubits expose it. And errors in the normalizer, the logical operators themselves, are undetectable by design; that is what the distance bounds.
What interviewers look for
- You explain the stabilizer formalism: commuting generators, +1 eigenspace, anticommutation as the detection mechanism.
- You state clearly that generators commute with logical operators, so measurement does not collapse the logical state.
- You trace a concrete example (repetition code) showing a correctable error and an undetectable logical operator.
- You know why one round is insufficient and how distance sets the number of rounds.
- You can name real numbers and a specific experiment.
- You mention failure modes: measurement errors, hook errors, normalizer errors.
Weak-answer patterns
- Saying "measure the logical state and compare": that destroys the superposition and defeats the purpose.
- Confusing stabilizer measurement with logical measurement.
- Hand-waving about error correction without distance or rounds.
- Claiming a single round suffices for fault tolerance.
- Ignoring measurement errors or hook errors.
Follow-up questions
- How do you choose the number of rounds for a given physical error rate?
- What is a hook error, and how do flag qubits help?
- How does the surface code handle both X and Z errors?
- What is the threshold, and how does it depend on the decoder?
- How do you decode syndromes in real time?
- What happens if a measurement error occurs in the final round?
Curated: · Written: · Reviewed:
Q&A-62How many physical qubits does one logical qubit cost?
What a strong candidate says first. There is no single number, and a plan built on one is a plan built on a guess. For the rotated surface code, the default choice, one logical qubit costs 2d²−1 physical qubits: 49 at d=5, 241 at d=11, 1249 at d=25. The distance isn't picked, it's derived: p_L ≈ 0.03 (p/p_th)^((d+1)/2), with p_th ≈ 0.57% for the standard circuit-level depolarizing model (Fowler et al., PRA 86, 032324, 2012). So the answer is: give me p, p_th and the target p_L, and I'll compute d and the bill.
Mechanism. A distance-d rotated patch is d² data qubits with d²−1 measure qubits interleaved, so 2d²−1 total. Distance d means the lightest undetectable error chain has weight d, and the decoder fails only when roughly d/2 errors line up: hence exponential suppression in d. The useful consequence: going from d to d+2 multiplies p_L by p/p_th. Call that Λ. Willow's measured Λ = 2.14 (Google Quantum AI, Nature, Dec 2024) therefore says the hardware runs at p/p_th ≈ 0.47, near half threshold, which is why each two units of distance buys only 2.14×. To get Λ = 10 you need p = p_th/10.
Arithmetic. Take p = 0.1%, p_th = 0.57%, so p/p_th = 0.175, and a target of 1e-10 per round.
| d | physical qubits (2d²−1) | p_L per round, p/p_th = 0.175 | p_L per round, p/p_th = 0.47 |
|---|---|---|---|
| 5 | 49 | 1.6e-4 | 3.1e-3 |
| 11 | 241 | 8.7e-7 | 3.2e-4 |
| 17 | 577 | 4.7e-9 | 3.4e-5 |
| 25 | 1249 | 4.5e-12 | 1.6e-6 |
| 51 | 5201 | — | 8.9e-11 |
d=21 gives 1.5e-10, just over target; d=23 gives 2.6e-11, so 1057 qubits. Round up to d=25 for margin and you get 1249. Now rerun at Willow-like p/p_th = 0.47: the same 1e-10 target needs d=51, or 5201 qubits. A 2.7× change in physical error rate moves the bill 5×.
What the patch count leaves out. Three things, all of which bite:
- Rounds. A lattice-surgery logical operation runs ~d rounds, so per-operation error is ~d × p_L(round). At d=25 that is 25 × 4.5e-12 ≈ 1.1e-10.
- Routing. Lattice surgery needs ancilla patches between data patches; on a 2D grid with nearest-neighbour coupling the routing area is a real fraction of the machine.
- Magic states. Non-Clifford gates need distillation, and factories usually dominate. Gidney & Ekerå's estimate for factoring RSA-2048 in 8 hours is 20 million physical qubits (Quantum 5, 433, 2021); the data patches are only part of that.
Alternatives. The surface code is not the only price list. Bravyi et al. (Nature 627, 778, 2024) give a [[144,12,12]] qLDPC code: 144 physical qubits for 12 logical qubits at distance 12, i.e. 12 physical per logical, against 287 for a d=12 surface patch. The catch is connectivity: the checks are long-range, so it needs a hardware topology the surface code doesn't, and its per-round logical error at small distance is worse. Color codes trade a higher threshold for harder decoding. A repetition code is cheaper but protects one basis only, so it isn't a logical qubit.
Failure mode. A resource plan that assumed 100 physical qubits per logical qubit. At p = 0.1% and a 1e-10 target the real number is ~1000–1250, so the machine was sized about 10× too small. The check is mechanical: write down p, p_th, target p_L, d, and 2d²−1, and confirm each follows from the one before. If a plan quotes qubits-per-logical without p and p_th beside it, it isn't a plan.
Curated: · Written: · Reviewed:
Q&A-63Your device's error rate is below a quoted threshold. Are you fault-tolerant?
No, not by that fact alone. A device error rate below a quoted threshold is not evidence of fault tolerance, because the threshold belongs to a complete scheme under a stated noise model, not to a device.
The threshold belongs to a scheme, not a device
The threshold theorem is a statement about a fault-tolerant scheme: an error-correcting code, a decoder, a syndrome extraction circuit, state preparation and measurement, and the factories that produce magic states. All under a noise model that assumes faults are largely independent and local. The number it produces is specific to that combination. The commonly quoted ~1% figure for surface codes is a circuit-level depolarizing result; swap in a different decoder, a code with different distance scaling, or correlated noise, and the threshold moves, often by an order of magnitude.
So the first move is to match the quoted threshold to your setup: which code, which decoder, which noise model, and whether the threshold was derived for circuit-level noise or only for a phenomenological model that treats measurement and gate errors as independent per-operation events.
Distance scaling is the only direct test
The independence assumption is what breaks first in hardware. Correlated errors: crosstalk between neighbouring qubits, a shared readout line or resonator coupling many qubits to one amplifier, leakage out of the computational subspace that propagates through two-qubit gates, calibration drift: violate it. Under correlated noise the effective threshold can fall below the device's per-gate error rate, and increasing distance makes things worse rather than better. A device with 0.1% two-qubit gate error can still be above threshold if correlated errors across a shared readout line dominate; the measured logical error then rises with distance.
The direct test is distance scaling. Build the same logical circuit at distances d and d+2 (ideally d+4 as well), measure logical error per round, and check that it falls. Define Λ = p_L(d) / p_L(d+2); below threshold means Λ > 1, and the size of Λ tells you how much headroom you have. A single distance tells you nothing.
| Code distance | Logical error per round, independent noise | Logical error per round, correlated noise |
|---|---|---|
| 3 | 0.9% | 0.9% |
| 5 | 0.35% | 1.2% |
(Illustrative figures, not measured.) At d=3 the two models are indistinguishable; they separate only at d=5, where the correlated case rises instead of falling. That is the signature of being above threshold despite a low physical error rate.
Resolving that difference costs shots. The standard error on a measured rate p with n shots is sqrt(p(1-p)/n). For p ≈ 0.01 and a target standard error of 0.1 percentage points, n ≈ 0.01 × 0.99 / (0.001)² ≈ 10,000 shots per distance. Fewer than that and the two curves overlap inside their error bars.
Two further failure modes are worth naming. Real-time decoding has to keep up with the syndrome rate; if the decoder falls behind, the effective threshold drops regardless of the device. And a threshold is asymptotic: finite-size behaviour at small distance can look above threshold even when the asymptotic value is not, which is why two distances are a minimum and three are better.
Fault tolerance is a property of the whole stack: code, decoder, control electronics, and the noise model you are willing to defend, not of a single error-rate number.
Curated: · Written: · Reviewed:
Q&A-64Your decoder is accurate but slow. Why is that fatal rather than merely inconvenient?
A decoder slower than the syndrome round period is fatal because the backlog grows without bound: the decoder is a consumer whose service rate is below the arrival rate, so it never catches up, and the Pauli frame is never current at the moment a logical measurement or conditional operation needs it. Accuracy is irrelevant if the correction arrives after the state it was computed for has already decohered further.
Mechanism. The control system emits one syndrome round per fixed period: on the order of a microsecond for superconducting hardware, slower for trapped-ion and neutral-atom platforms. Each round has to be decoded and its correction folded into the Pauli frame before the next logical operation. If decoding takes 2 µs per round against a 1 µs period, the queue grows by 1 µs per round: 1 ms after a thousand rounds, and unbounded after that. The frame then lags the physical state by the whole backlog, so any feed-forward correction is applied to a state that has moved on. The logical qubit's effective lifetime is capped by decoding latency, not by code distance.
Arithmetic. Backlog after N rounds = N × (t_decode − t_round). At t_decode = 2 µs and t_round = 1 µs, N = 1000 gives 1 ms of backlog. If the physical qubits' T2 is ~100 µs (illustrative; superconducting T2 is tens to hundreds of microseconds), the frame is ten coherence times stale and the correction is meaningless.
Alternatives, and when slow is acceptable.
| Approach | Latency | Accuracy cost | Use when |
|---|---|---|---|
| Buffer and decode in bursts | amortized, but queue latency diverges as utilization → 1 | none | offline replay of stored syndromes |
| Sliding-window decoding | ~round period | truncation error at window edges | real-time, moderate distance |
| Union-Find / near-linear decoders | µs-scale | slightly worse than MWPM at low distance | real-time on FPGA |
| Lookup tables | ns | only small codes | small distance, high rate |
| Full MWPM offline | ms-scale | best | calibration, threshold estimation |
Buffering is the tempting non-answer: it works only if the decoder is faster than the round rate on average, and even then a bursty decoder at 90% utilization has queue latency that blows up. It is the right tool for offline analysis, where the whole syndrome history is available and no deadline applies.
Failure modes. (1) Unbounded backlog: detected as monotonically growing queue depth. (2) Stale frame: the logical measurement returns a wrong value with no error flag, which is worse than a detected failure. (3) Decoder timeout: the control system drops rounds, silently reducing effective code distance. Detect all three by measuring the decoder latency distribution (p50 and p99) against the round period, not the mean, and by checking that conditional logical operations actually complete.
The test is whether a conditional logical operation succeeds; if it does not, the decoder is too slow regardless of how accurate it is.
Curated: · Written: · Reviewed:
Q&A-65A result claims a logical qubit beat a physical one. What do you ask?
The first minute
Four questions, in this order:
- Which physical qubit is the baseline: the median on the die, the best, or the best at matched duration and matched task?
- Is the logical number per cycle of error correction, and is the physical number per cycle too, or per gate?
- Memory only, or does it include logical operations?
- How many shots, and how many logical failures?
Then: show me the logical error rate beside the best physical qubit's error over the same duration and the same task. If it isn't below that, the claim is a baseline choice, not a result.
Why the baseline decides the answer
Physical error rates across one die commonly spread by 3× or more. A distance-3 surface-code patch is 9 data qubits and 8 ancillas, and its logical error is set by its worst constituent qubits and by the decoder, not by the best qubit on the chip. So the logical number can never track the best qubit's number, and comparing against the median is close to free.
One experiment, two baselines (hypothetical figures):
| Baseline | Error per cycle | Logical memory | Break-even? |
|---|---|---|---|
| Median physical qubit | 0.9% | 0.5% | yes |
| Best physical qubit, same duration | 0.28% | 0.5% | no: 1.8× worse |
| Best physical qubit, same duration, logical ops included | 0.28% | not measured | unclaimed |
The same logical 0.5% is a win against 0.9% and a loss against 0.28%. Nothing about the experiment changed.
Units and task
A logical error rate per cycle covers d rounds of stabilizer measurement, each containing two-qubit gates, measurement and reset. A physical error rate quoted per two-qubit gate has a different denominator. Ask for the physical qubit's error per cycle over the same wall-clock window, idling and measurement included: that is the number the logical rate has to beat.
Memory is the easy case: repeated stabilizer measurement, no logical gates. Logical operations need lattice surgery or transversal gates plus magic-state distillation, and distillation consumes many physical qubits and cycles per logical gate. A memory break-even says nothing about a computation. Ask whether any logical gate was executed; if not, treat it as a memory result.
Statistics
Ask for raw counts. At 10⁴ shots, a logical error rate of 0.5% has a standard error near 0.07 percentage points: a 95% interval of roughly 0.36% to 0.64%. The best physical qubit at 0.28% over the same shots gives roughly 0.18% to 0.38%. The gap is about 2.5 standard errors: real, not comfortable. A 1.1× claim at that shot count is noise. Ask for 10⁵ shots before believing anything under 2×.
Failure modes and how I'd catch them
- Median baseline presented as "the physical qubit". Detect: ask for the baseline qubit's identity and its error per cycle.
- Per-gate physical against per-cycle logical. Detect: ask for the physical number over the same duration, measurement and reset included.
- Memory-only result described as a logical qubit. Detect: ask whether any logical gate ran.
- Calibration drift between the two measurements. Detect: ask whether both were taken in the same calibration window; drift between calibrations can exceed the effect.
- No error bars. Detect: ask for shots and logical failures, then recompute the interval.
What settles it
One sentence: logical error per cycle below the best physical qubit's error per cycle, same chip, same calibration window, same duration, same task, with intervals that don't overlap. Anything less is a baseline choice.
Curated: · Written: · Reviewed:
Q&A-66Why do non-Clifford gates dominate a fault-tolerant resource estimate?
Direct answer. In a stabilizer code the Clifford gates are the cheap ones and the non-Clifford gates are the expensive ones, so a fault-tolerant estimate is dominated by whatever the algorithm needs to make its gate set universal: almost always T gates. The reason is structural, not an implementation detail: the Eastin–Knill theorem says no quantum error-correcting code can implement a universal gate set transversally. Clifford gates can be done transversally or by lattice surgery on the surface code, so they cost a bounded number of physical operations per logical operation. T gates cannot, so they are injected as magic states, and those states must be distilled from many noisy copies before they are good enough to use.
Mechanism. A T gate is applied by preparing a magic state |T⟩ = (|0⟩ + e^{iπ/4}|1⟩)/√2, then consuming it with a Clifford-only gadget (CNOT, measurement, conditional correction). The state itself is the expensive part. Raw magic states carry the same error rate as the physical hardware, so they are distilled: the 15-to-1 Reed–Muller protocol (Bravyi–Kitaev, 2005) takes 15 input states of error p and produces one output state with error ≈ 35p³. That cubic suppression is why distillation works, and why it costs so much: each round multiplies the state count by 15, and reaching the target logical error rate usually needs two rounds, so 225 noisy input states per usable T state.
Worked example (illustrative figures). Take a circuit with 2.4 × 10⁹ T gates. At 225 input states per output, the factory must produce and consume ~5.4 × 10¹¹ raw magic states over the run. If the factory holds 1,600,000 physical qubits and the data block holds 320,000, the split is:
| Component | Physical qubits | Share |
|---|---|---|
| logical data | 320,000 | 17% |
| distillation factories | 1,600,000 | 83% |
The factories are five times the data block. Counting total gates instead of T gates hides this: the Clifford gates are numerous but cheap, and the T gates are few but each one drags a factory behind it.
Failure modes. Counting total gates and concluding the circuit is modest: the T count is what sets the factory footprint and the runtime. Ignoring T depth: a circuit with few T gates but deep T layers serializes on factory throughput, and the runtime is set by the factory, not the data block. Assuming the factory footprint shrinks with better hardware alone: it shrinks with lower input error (fewer distillation rounds) and better code distance, not with raw qubit count.
When this doesn't apply. Clifford-only circuits (stabilizer simulation, some error-correction subroutines) need no factories. Near-term devices without error correction are outside this analysis entirely. And T count can be reduced algorithmically (QROM, phase-estimation reformulations, or trading T gates for Clifford gates) which is often cheaper than building a bigger factory.
What to report. T count and T depth, separately from the Clifford count, plus the factory-to-data qubit ratio.
Curated: · Written: · Reviewed:
Q&A-59Zero-noise extrapolation improves your expectation value. What did it cost?
Assume a fixed circuit, a shot-noise-limited device and a single Pauli observable. ZNE buys a smaller bias and pays in shots: the extrapolated value is a fixed linear combination of the runs at each noise factor, so its variance is a weighted sum of their variances, and the weights are larger than one in absolute value. The second cost is a modelling assumption the reported error bar does not cover.
Where the variance comes from
Noise scaling by unitary folding: each fold appends the inverse of a preceding block, leaving the ideal unitary unchanged while multiplying the gate count: produces runs at noise factors lambda = 1, 2, 3. Each run returns y_i with shot noise. The extrapolation fits y(lambda) = a + blambda and reports a. With three points that fit is a fixed linear combination: a = 3y1 - 3y2 + y3. Check it on any line: 3(a + b) - 3*(a + 2b) + (a + 3b) = a.
The three runs are independent, so Var(a) = 9Var(y1) + 9Var(y2) + 1*Var(y3). A Pauli observable has per-shot variance at most 1, so Var(y_i) <= 1/n_i and, with equal shot counts, Var(a) <= 19/n. Nineteen times the variance is 4.4 times the standard error. That multiplier comes from the coefficients, not from the hardware, and it is the number an interviewer wants.
The arithmetic
| Run | Noise factors | Shots | Standard error |
|---|---|---|---|
| unmitigated | 1 | 100,000 | 1/sqrt(100000) = 0.0032 |
| mitigated, equal split | 1, 2, 3 | 3 x 100,000 | sqrt(19/100000) = 0.014 |
| mitigated, matched error bar | 1, 2, 3 | 4,900,000 total | 0.0032 |
| unmitigated at that budget | 1 | 4,900,000 | 1/sqrt(4900000) = 0.00045 |
Row three is the honest price: matching the unmitigated error bar takes 49 times the shots. That 49 is (sum of |c_i|)^2, from giving each noise factor shots proportional to |c_i| = (3, 3, 1); splitting them equally costs 57x instead. Row four is why the comparison must be at equal total shot budget: spent on the unmitigated circuit, the same 4.9 million shots give an interval seven times tighter.
The coefficients are a design choice. A two-point linear Richardson extrapolation from lambda = 1 and 3 uses c = (1.5, -0.5), so sum of c_i^2 is 2.5 rather than 19: wider spacing is cheaper, at the price of knowing nothing about curvature. Adding a third factor and cancelling a quadratic term costs more again.
What the interval does not cover
Shot-noise amplification is the visible cost; the invisible one is the model. If the true bias is not linear in lambda, the residual lands in the reported value and not in the interval.
- Check the fit residuals at the sampled noise factors against the per-point error bars. A residual of several sigma means the model is wrong, and a wider interval does not repair a wrong model.
- Refit with an exponential, or with the decay rate left free, and compare. If the two extrapolated values differ by more than the quoted interval, model error dominates shot noise.
- Hold out a noise factor: fit on lambda = 1 and 2, predict the measurement at 3. If the prediction misses by more than its own error bar, lambda is not proportional to the actual noise and extrapolating to zero lands off target.
Report the mitigated value with its interval, the total shots consumed, the noise factors and the fit model. A mitigated number whose interval is narrower than the unmitigated one at the same shot count means the fit's noise was never propagated.
Curated: · Written: · Reviewed:
Q&A-60A stakeholder asks whether mitigation gets you to fault tolerance. What do you say?
No. Mitigation makes one number more accurate on a circuit you can already run; fault tolerance is a property of an encoded qubit that keeps getting better as you add hardware. They are not two points on the same road.
The one-sentence version for the stakeholder: mitigation reduces the bias in an expectation value, it never produces a logical qubit, and its cost grows exponentially with circuit volume, so it cannot be a path to fault tolerance.
Mechanism. Probabilistic error cancellation is the clearest case. You characterise the noise, then sample circuits weighted by quasi-probabilities that cancel it in expectation. The sampling overhead is e^(2γN), where γ is the per-gate noise rate and N the gate count (Temme, Bravyi and Gambetta, 2017). That exponent is the whole story. At γ = 10⁻³ and N = 10⁴ gates you need about 5×10⁸ shots; at N = 10⁶ the exponent is 2000 and the shot budget is not finite in any useful sense. Zero-noise extrapolation is cheaper per circuit, but it only extrapolates a curve: it does not change the scaling, and it inherits whatever the noise model gets wrong.
Correction is a different object. A distance-d surface code with physical error p below threshold (roughly 1%) suppresses the logical error per cycle as (p/p_th)^((d+1)/2), at a cost of roughly d² physical qubits per logical qubit, plus magic-state distillation for non-Clifford gates. Google's Willow surface-code experiment (Nature, December 2024) reported the logical error per cycle falling from ~0.3% at distance 3 to ~0.14% at distance 5: below threshold, meaning more qubits bought fewer logical errors. That direction is the thing mitigation cannot produce.
| Technique | Produces a logical qubit | Overhead |
|---|---|---|
| suppression (dynamical decoupling, Pauli twirling) | no | small, constant |
| mitigation (PEC, ZNE, CDR) | no | exponential in circuit volume (PEC: e^(2γN)) |
| correction (surface code + distillation) | yes | ~d² physical per logical, bounded below threshold |
Failure mode I have seen. A roadmap drew mitigation as the incremental step before fault tolerance. At the circuit volumes the application needed, the sampling overhead passed 10⁸ shots and the plan had no reachable milestone. The tell is always the same: nobody wrote down the shot budget at the target volume.
Detection. Run two mitigation methods on the same circuit. If ZNE and PEC disagree beyond their error bars, the noise model is wrong and the mitigated number is wrong with no warning. Mitigation has no self-check; a logical qubit does.
What I would ask for before calling it settled: the mitigation overhead at the target circuit volume, and whether the shot budget stays finite. If it does not, the answer is no.
Mitigation buys accuracy on small circuits, not scale.
Curated: · Written: · Reviewed:
Q&A-67Walk through what actually happens in one iteration of VQE.
One VQE iteration is three steps: prepare a state from the current parameters, estimate the energy by sampling, hand that scalar to a classical optimizer that returns the next parameters. The interesting parts are how the estimate is built and what the optimizer does with a noisy scalar.
Assume a fixed ansatz U(θ) with p parameters, a Hamiltonian H = Σᵢ cᵢPᵢ over Pauli strings, and a shot budget N per circuit.
Prepare. Bind θ into the ansatz and run it on |0…0⟩. One circuit execution, deterministic given θ.
Measure. You cannot measure H directly. You measure each Pauli string Pᵢ in its eigenbasis, insert single-qubit rotations so Pᵢ becomes a Z-type measurement, and average the ±1 outcomes. Terms that qubit-wise commute share a basis and therefore one circuit: Z₀Z₁ and Z₂ both measure in the Z basis, so one circuit yields both. X₀X₁ needs H gates on qubits 0 and 1, a second circuit. The energy estimate is Σᵢ cᵢ·(mean of Pᵢ outcomes).
The estimator is unbiased but noisy. For a single Pauli with eigenvalues ±1, Var(⟨Pᵢ⟩) = (1 − ⟨Pᵢ⟩²)/N, so standard error ~1/√N. Energy variance is Σᵢ cᵢ²·Varᵢ, so a term with a large coefficient dominates the error budget: spend shots there.
Update. The optimizer receives E(θ) and proposes θ′. Gradient-free methods (COBYLA, Nelder-Mead) consume the scalar directly. Gradient-based methods use the parameter-shift rule: ∂E/∂θₖ = [E(θ + (π/2)eₖ) − E(θ − (π/2)eₖ)]/2, exact for gates generated by a Pauli with eigenvalues ±1. No finite differences. That costs 2p circuit evaluations per iteration; SPSA gets a stochastic gradient from 2 evaluations regardless of p.
Worked trace: 4 qubits, H = 0.5·Z₀Z₁ + 0.3·X₀X₁ + 0.2·Z₂, p = 6, N = 10⁴ shots per circuit. Grouping gives 2 circuits per energy evaluation. Parameter-shift gradient: 2 × 6 = 12 evaluations × 2 circuits = 24 circuit executions, 240,000 shots for one iteration. At ~5 µs/shot readout-dominated, roughly 1.2 s of device time per iteration, before queue.
Trade-offs that decide the design:
- Shots per evaluation vs iterations. A fixed total shot budget split as N per iteration and K iterations gives energy error ~1/√N and a final parameter error that also depends on K. Fewer, larger evaluations beat many noisy ones when the optimizer is gradient-based, because the gradient is a difference of two noisy scalars.
- Gradient-based vs gradient-free. Parameter shift is exact but scales 2p evaluations per step; SPSA is 2 per step at the cost of a noisy direction. For p in the hundreds, SPSA or a grouped/commuting gradient usually wins.
- Grouping strategy. Qubit-wise commuting grouping is cheap to compute; full commuting grouping (via a clique cover on the commutation graph) needs fewer circuits but more classical work per iteration.
Failure modes to watch:
- Barren plateaus. For deep, randomly initialized hardware-efficient ansätze, gradient variance falls exponentially in qubit count (McClean et al., 2018), so the optimizer stalls near the start. Detect by logging ‖∇E‖ against iteration; if it sits at the shot-noise floor, more shots will not help.
- Shot-noise floor. If the true gradient magnitude is below ~1/√N, the optimizer random-walks. Compare the measured gradient to the estimator's standard error before trusting a step.
- Ansatz expressibility vs trainability. A more expressive ansatz can reach lower energies but is harder to optimize; the two pull against each other and the balance is empirical.
Instrument shots, circuit count, and wall time per evaluation alongside the iteration count: an iteration is not a fixed unit of work.
Curated: · Written: · Reviewed:
Q&A-68Why not use the most expressive ansatz you can fit on the device?
Answer in the first minute. Expressibility is not free; you pay for it in trainability. An ansatz expressive enough to reach most of the Hilbert space behaves like a random unitary, and gradients of a cost function over random circuits concentrate exponentially around zero as you add qubits. You end up with a landscape that has no usable slope: a barren plateau. The practical rule: restrict the ansatz to the subspace the problem actually occupies, and measure the gradient scaling before you commit device time.
Why it happens. For C(θ) = ⟨ψ(θ)|H|ψ(θ)⟩, if the circuit forms (or approximates) a 2-design at sufficient depth, then over random parameters E[∂C/∂θ_k] = 0 and Var[∂C/∂θ_k] decays exponentially in the number of qubits. McClean et al. (2018) established this for random circuits: the cost function concentrates around its mean over the Haar measure, and a concentrated function has a vanishing derivative. Two knobs matter more than raw expressibility:
- Cost-function locality. Global cost functions (a projector onto one target state) barren-plateau exponentially; local cost functions (a sum of few-qubit observables) can avoid it: Cerezo et al. (2021).
- Depth and entanglement. Even local cost functions go barren past a depth threshold (entanglement-induced barren plateaus), and noise flattens the landscape further (noise-induced barren plateaus, Wang et al. 2021). The noise-induced case does not improve with more shots.
What to do instead.
- Use a problem-informed, symmetry-preserving ansatz: gates that conserve particle number and spin for a molecular Hamiltonian, or the Hamiltonian's own terms (Hamiltonian variational ansatz) for a spin model. This cuts the reachable subspace down to the physically relevant one.
- Prefer local cost functions.
- Keep circuits shallow; use layerwise training or identity-block initialization.
- Verify before you commit: sample gradient variance at random parameters for increasing width and depth. Exponential decay means a barren plateau: change the ansatz, not the optimizer.
Worked example (illustrative figures). A 20-qubit hardware-efficient ansatz at 12 layers, random initialization:
| Ansatz (20 qubits, 12 layers) | Var[∂C/∂θ] at random init |
|---|---|
| problem-informed, symmetry-preserving | ~1e-2 |
| hardware-efficient, random | ~1e-6 |
With gradient standard deviation ~1e-3, 400 optimizer steps at learning rate 0.01 move the energy by roughly 4e-3: below the shot noise of a single energy evaluation at a few thousand shots. The optimizer is not failing; there is no signal to follow.
If you cannot show the gradient variance decaying sub-exponentially with width, you do not yet know whether the ansatz trains, and the device will tell you the expensive way.
Curated: · Written: · Reviewed:
Q&A-69Your optimizer makes no progress on a 20-qubit circuit. Is it the optimizer?
Usually not. For a 20-qubit circuit deep enough to approximate a random unitary, the gradient variance decays exponentially with qubit count. At 20 qubits, typical gradient components are around 10^-3, which requires on the order of 10^6 shots per component to distinguish from zero. The landscape is flat, not badly navigated. No optimizer can fix that.
But the answer depends on the circuit. If it's a shallow, problem-inspired ansatz, the optimizer might be the issue. So diagnose before you blame the optimizer.
The mechanism is the barren plateau. For random parameterized quantum circuits, the expected gradient vanishes exponentially. The variance of the gradient across random initializations scales as O(1/2^n) for global cost functions. At 20 qubits, 2^-20 ≈ 1e-6. That's the variance, so the typical gradient magnitude is its square root, about 1e-3. This is a property of the landscape, not the optimizer.
How to diagnose: sample random parameters, compute the gradient via the parameter-shift rule, and take the variance across samples. Do this for increasing qubit counts. If the variance decays exponentially, it's a barren plateau. If it doesn't, then look at the optimizer. In simulation you can compute exact gradients; if they are zero, it's not the optimizer. On hardware, shot noise can mask small gradients, but the underlying issue is the same.
Here's the arithmetic for a global cost function and deep random circuits:
| Qubits | Gradient variance (2^-n) | Typical gradient | Shots to resolve |
|---|---|---|---|
| 8 | 3.9e-3 | 6.3e-2 | ~250 |
| 20 | 9.5e-7 | 9.8e-4 | ~1e6 |
The exponential scaling is for global cost functions. Local cost functions can have polynomial or even constant variance for shallow circuits, so the table is the worst case. Depth matters. A 20-qubit circuit with depth 100 can still be barren. A 20-qubit circuit with depth 5 might not be. So the first question is: how deep is your circuit?
A common pattern: a team cycles through four optimizers over three weeks on a plateaued 20-qubit ansatz. The gradient variance is 1e-6 throughout. No optimizer could have helped. They needed to change the circuit, not the optimizer.
If the gradient variance is not exponentially small, then check the optimizer: learning rate, initialization, local minima. For shallow circuits, optimizers like Adam, SPSA, or COBYLA can work. But for deep random circuits, no optimizer helps. Changing the optimizer does not change the landscape.
Mitigations that actually work: shallower problem-informed circuits, local cost observables, layerwise initialization. These change the landscape. So the next step is to measure gradient variance against qubit count. If it decays exponentially, it's a barren plateau. If not, then it's the optimizer.
Curated: · Written: · Reviewed:
Q&A-70How many shots does one VQE energy evaluation take?
There is no fixed number. One VQE energy evaluation costs as many shots as the target accuracy and the Hamiltonian's coefficient structure require. For H = Σ_i c_i P_i measured term by term with optimal allocation,
N = (Σ_i |c_i|)² / ε²
with ε the target accuracy in hartree. A 12-qubit molecular Hamiltonian with Σ|c_i| ≈ 20 Ha evaluated to chemical accuracy (ε = 1.6 mHa) needs N = 20² / (1.6×10⁻³)² ≈ 1.6×10⁸ shots.
Where the formula comes from: a Pauli expectation ⟨P_i⟩ estimated from N_i shots has variance at most 1/N_i, so the energy estimator has variance Σ c_i²/N_i. Minimizing that under Σ N_i = N puts N_i ∝ |c_i| and leaves a standard deviation of Σ|c_i|/√N. Setting that equal to ε gives the expression above. Giving every term the same number of shots is worse by a factor of M, the number of terms, because small-coefficient terms consume shots they do not need.
Grouping. Pauli strings that commute can be measured in one circuit. Partitioning the Hamiltonian into commuting sets and allocating shots within each set proportionally to coefficient magnitude typically cuts the total by one to two orders of magnitude, since one shot now informs several terms. For the example above that is the difference between 1.6×10⁸ and roughly 10⁷ shots.
Failure mode: a fixed shot budget. Budget 8,192 shots per energy evaluation on that Hamiltonian and the energy standard deviation is Σ|c_i|/√N = 20/√8192 ≈ 0.22 Ha, about 140× chemical accuracy. The optimizer then fits noise: the energy surface is flat within the error bars and the "converged" geometry is arbitrary. Detect it before the run by computing Σ|c_i|/√N and comparing to ε; a ratio above ~1 means the run cannot resolve the answer.
| Strategy | Shots for ε = 1.6 mHa |
|---|---|
| Optimal per-term allocation | 1.6×10⁸ |
| Commuting groups, proportional allocation | ~10⁷ |
Before submitting a job, compute Σ|c_i| from the Hamiltonian, fix ε, and check N against the shot budget and queue time. If N is out of reach, shrink the active space or use a lower-variance estimator rather than quietly relaxing ε.
Curated: · Written: · Reviewed:
Q&A-71You want exact gradients on hardware. What do they cost?
Exact gradients on hardware means the parameter-shift rule, and its price is circuit evaluations: two per parameter per gradient step, each carrying its own shot budget. For a P-parameter ansatz at S shots per estimate, one gradient step costs 2·P·S shots. At P = 200 and S = 10⁶ that is 4×10⁸ shots for a single step, before the optimizer has moved anywhere.
Why two evaluations. For a gate U(θ) = exp(−iθG/2) whose generator G has eigenvalues ±1 (every Pauli rotation RX, RY, RZ, and any exp(−iθP/2) with P² = I) the expectation f(θ) = ⟨ψ|U†OU|ψ⟩ is a pure sinusoid in θ, so
∂f/∂θ = [ f(θ + π/2) − f(θ − π/2) ] / 2
holds exactly. No step size to tune, no O(ε²) truncation bias. The two shifted circuits are the same ansatz with one parameter moved, so the price is two full evaluations per parameter. Gates whose generator has more than two distinct eigenvalues need the four-term rule (four evaluations per parameter); gates with no such structure need the stochastic parameter-shift rule, which is more expensive again.
What that buys against the alternatives.
| Method | Evaluations per step | Shots at S = 10⁶, P = 200 |
|---|---|---|
| Parameter-shift | 2P = 400 | 4×10⁸ |
| Four-term rule | 4P = 800 | 8×10⁸ |
| Finite differences | 2P = 400 | 4×10⁸, plus O(ε²) bias and shot noise ÷ ε |
| SPSA | 2 | 2×10⁶ |
| Simulator adjoint | one backward pass | 0 hardware shots |
SPSA is the honest comparison: two evaluations per step regardless of P, at the cost of a noisy gradient estimate whose variance grows with P, so it needs more steps and a decaying learning rate. Finite differences look the same price as parameter-shift but are strictly worse: biased, and the shot noise is divided by the step size ε. Adjoint differentiation is free but only exists on a simulator; on hardware there is no backprop.
Failure modes. The shot budget is the one that kills runs. A 200-parameter optimization at 10⁶ shots per estimate spends 4×10⁸ shots per step; at a hardware throughput of 10⁴–10⁵ shots/s that is roughly 1–11 hours per step, and a run needing hundreds of steps is not schedulable. The second is a gradient noise floor: each estimate has standard error σ/√S, so a gradient component built from two of them has standard error σ√(2/S), and once the true gradient falls below that the optimizer random-walks instead of converging. Detect both by logging shots consumed per step and the empirical variance of the gradient components across steps; if the gradient norm sits at the noise floor, more steps will not help.
What to do. Price a gradient step before choosing the optimizer: 2·P·S shots, times the number of steps you expect. If that exceeds the budget, either reduce P (ansatz design, not optimizer tuning), reduce S and accept a noisier gradient, or switch to SPSA and spend the savings on more steps. State which you used: a run reported as "converged" without the gradient method and shot budget is not reproducible.
Curated: · Written: · Reviewed:
Q&A-72You have a fixed shot budget and forty measurement groups. How do you split it?
Split the fixed budget (N) across the 40 groups as (n_i = N \frac{|c_i|\sigma_i}{\sum_j |c_j|\sigma_j}), where (c_i) is the coefficient of group (i) in the Hamiltonian and (\sigma_i) is the per-shot standard deviation of that group's estimator. If you have no pilot data, use (\sigma_i=1) for Pauli groups (their single-shot variance is (1-\langle H_i\rangle^2 \le 1)) and allocate proportional to (|c_i|). Enforce a floor (n_i \ge n_{\min}) so the variance estimates stay usable.
Let (H=\sum_i c_i H_i). Estimate each (\langle H_i\rangle) by the sample mean over (n_i) shots. Then (\operatorname{Var}(\hat H)=\sum_i c_i^2\sigma_i^2/n_i). Minimize subject to (\sum_i n_i=N). Lagrange: (-c_i^2\sigma_i^2/n_i^2+\lambda=0), so (n_i\propto |c_i|\sigma_i). The square root is the whole point: variance falls as (1/n), so the marginal value of a shot is (c_i^2\sigma_i^2/n_i^2). That is why the weight is (|c_i|\sigma_i), not (|c_i|\sigma_i^2). If a group is itself a sum of Pauli terms, fold their coefficients into (\sigma_i); the formula is unchanged.
Hypothetical arithmetic for two groups, (N=10^6), (\sigma_i=1); the same formula applies to all 40.
| group | (c_i) | weight | (n_i) | variance contribution |
|---|---|---|---|---|
| 1 | 0.5 | 0.5 | 833,333 | 3.0e-7 |
| 2 | 0.1 | 0.1 | 166,667 | 6.0e-8 |
| total | 1,000,000 | 3.6e-7 |
Uniform would give 500,000 each and total variance 5.2e-7, so the weighted split cuts the standard error by about 17% here.
Uniform is the right default when the (|c_i|\sigma_i) are within a small factor, when you have no reliable (\sigma_i), or when per-group overhead dominates. Adaptive allocation (pilot shots, estimate (\sigma_i), reallocate) beats static when (\sigma_i) vary widely, but the pilot consumes budget and noisy (\sigma_i) at low shot counts can make the weights worse than uniform. Forty groups means forty circuits; if state preparation, compilation, or readout overhead per group is large, merging groups can save more than the optimal shot split. Weighted allocation is not worth it when the shot savings are smaller than the extra calibration and compilation cost.
Correlated sampling error: if groups share shots or readout crosstalk, the total variance has covariance terms and the independent formula underestimates. Detect it by measuring covariance between group estimators on the same shots. Noisy variance estimates: the sample variance has relative error roughly (\sqrt{2/(n_i-1)}) for Gaussian data; at (n_i=100) that is about 14%, enough to swing the weights. Detect it by comparing predicted (V=\sum_i c_i^2\sigma_i^2/n_i) to observed variance across repeated runs, or by bootstrap. Fix with pilot shots, a floor (n_i), or conservative (\sigma_i=1). Group overhead: detect by timing per-group overhead against shot cost; if overhead exceeds the shot savings, merge groups.
Curated: · Written: · Reviewed:
Q&A-73Your QAOA run returns bitstrings that violate the problem's constraints. What happened?
Nothing is broken in the sampler. You encoded the constraint as a penalty term in the cost Hamiltonian, and a penalty is a soft bias, not a projection: the optimized state still carries amplitude on infeasible bitstrings, and sampling reports them faithfully.
Assumptions this rests on: a standard QAOA circuit whose cost unitary is built from the objective plus λ·penalty, a transverse-field mixer, a hard constraint (cardinality or one-hot), and no post-selection before you looked at the results. If any of those is false, say you already use a constraint-preserving mixer, the diagnosis changes.
Why it happens. H_C = H_obj + λ·H_pen. The cost unitary e^(−iγH_C) is a continuous phase rotation: it changes the relative phases of basis states, it does not delete the infeasible ones. The mixer e^(−iβH_X) is a product of single-qubit X rotations, which connects every computational basis state to every other. So amplitude flows into the infeasible subspace on every layer, and the penalty only suppresses it through interference. With finite λ and finite depth p, that suppression is partial.
Measure this before anything else: the feasible fraction of your samples, and the objective computed over feasible samples only. An approximation ratio computed over all samples is not a number about your problem.
Worked example (illustrative figures). A run reported ratio 0.88. 41% of the sampled bitstrings violated the cardinality constraint. Restricted to feasible samples, the ratio was 0.62.
| Sample set | Fraction of shots | Approximation ratio |
|---|---|---|
| all samples | 1.00 | 0.88 |
| feasible only | 0.59 | 0.62 |
Same run, two readings. The 0.88 came from infeasible strings scoring well on the penalized objective, not from the optimizer solving the problem.
The three fixes, and what each costs.
- Raise λ. Cheap, but past a point the landscape flattens: the penalty dominates H_C, gradients shrink, and the optimizer stalls. Sweep λ and watch both the feasible fraction and the feasible-only objective; the useful range is where both are still moving.
- Constraint-preserving mixer. For a cardinality constraint, an XY-mixer on a ring or complete graph keeps the state inside the fixed-Hamming-weight subspace by construction, so infeasible bitstrings have exactly zero amplitude. This is the structural fix; it costs a different mixer and a re-derived circuit.
- Post-selection. Discard infeasible shots. Fine for one constraint, but the feasible fraction falls roughly exponentially in the number of independent constraints, so with several you spend shots to get almost nothing.
Failure modes to name. λ too small: infeasible strings dominate the sample and the reported objective is meaningless. λ too large: flat landscape, poor convergence. Post-selection on many constraints: the feasible fraction collapses and your shot budget buys few usable samples. Reporting a single ratio without the feasible fraction: you cannot tell which of these you are in.
Detect it by logging, per run, the feasible fraction, the objective over feasible samples, and the penalty's contribution to the energy. If the penalty contribution is comparable to the objective, λ is doing the work and the "solution" is an artefact of the penalty.
Curated: · Written: · Reviewed:
Q&A-74What do you compare your QAOA result against?
I would answer choosing a classical baseline for a variational claim by separating what the mathematics guarantees from what the device delivers.
Against a tuned classical heuristic given the same wall-clock budget, and against the trivial bound the problem already guarantees. Comparing to a random assignment, or to an untuned solver, measures effort rather than capability.
Concretely, fix the baseline, its tuning budget and the instance set before running, and give the classical side compute comparable to the quantum side's device and queue time.
The reason for that specificity is a failure I have seen: A QAOA result on max-cut reported a 0.71 approximation ratio as evidence of promise; a random assignment guarantees 0.5 and a standard classical heuristic reached 0.93 on the same instances in under a second.
Same instances, three methods.
| Method | Approximation ratio | Time |
|---|---|---|
| random assignment | 0.50 | 0 s |
| QAOA depth 3 | 0.71 | 6 h |
| tuned heuristic | 0.93 | 0.8 s |
I would not consider it settled without evidence: Report the quantum result, the trivial bound and a tuned classical solver on identical instances with their runtimes.
A baseline nobody tuned is not a baseline.
Curated: · Written: · Reviewed:
Q&A-75How do you keep a quantum benchmark honest?
A benchmark is honest when the number you report is the number the protocol would have produced before you looked at the data. On quantum hardware that means three things, in order: fix the protocol, keep the full ledger, and put a timestamp and an error bar on the result.
Fix the protocol before the first shot: the instance set (which qubits, which circuits), the metric (success probability, heavy-output probability, fidelity), the baseline, the stopping rule, and the analysis. Write it in the repo with a timestamp. Choose any of those after seeing results and you are reporting the maximum over a family of analyses, with the family hidden.
Keep the full ledger: every instance attempted, every restart, every dropped run with its reason. The headline is a row in that ledger, not a replacement for it.
Timestamp and error bar: superconducting qubits drift. T1, T2 and gate error move on the scale of hours, so a benchmark run after a recalibration is a different machine. Report the calibration state and wall-clock time, and give an interval, not a point estimate.
Why selection bias is the default here
Quantum benchmarking is stochastic twice over. The hardware is noisy, so one shot is a coin flip; and variational or pulse-level methods add an optimizer whose convergence is itself random. A run that "converged" is a lucky draw from the optimizer's distribution. Keep the converged runs and drop the rest and you have conditioned on the outcome: you report E[success | converged], not E[success]. The same move shows up as picking the best 8 of 31 qubits, or stopping when the curve looks good. Note also that the benchmark measures the compiled, calibrated circuit, not the ideal unitary: the ideal circuit and the executed circuit are different programs, and the gap is where the dishonesty hides.
Trade-offs
Preregistration is not free. It is rigid, slow, and wrong for exploratory work where you do not yet know which metric matters. Three lighter alternatives, in increasing cost:
- Use a standard protocol. Randomized benchmarking, cross-entropy benchmarking (XEB), mirror circuits and Quantum Volume each ship a fixed procedure, so the protocol is the preregistration. Randomized benchmarking is built to be insensitive to state-prep and measurement (SPAM) error; XEB and mirror circuits are not, so report SPAM separately. Mirror circuits (Proctor et al., PRL 2022) and the Quantum Economic Development Consortium (QED-C) application benchmarks are the usual pick when you want an application-shaped number rather than an average gate fidelity.
- Hold out a test set. Tune on one instance set, report on another you never touched.
- Independent replication. Someone else runs your protocol on their machine.
Preregister when you are choosing the metric, the subset, or the stopping rule: that is where the forking paths are. Running a standard protocol end to end, a timestamped ledger and an interval are usually enough.
Failure modes and how you catch them
- Garden of forking paths: many defensible analyses, one reported. Diff the preregistered plan against the analysis script.
- HARKing: hypothesis stated after results. Check the timestamp on the plan.
- Drift: benchmark and calibration separated in time. Re-run the same protocol and check the intervals overlap.
- SPAM inflation: prep and measurement error folded into the number. Report it separately from the gate number.
Worked example (illustrative figures)
A study reports 0.94 over 8 instances. The protocol ran 31; the 23 dropped are the ones where the optimizer did not converge.
| Population | Instances | Success rate |
|---|---|---|
| reported subset | 8 | 0.94 |
| all attempted | 31 | 0.42 |
The reported subset is the top of the distribution, not the mean. Even on its own terms it is fragile: with n=8 and p=0.94, the standard error is sqrt(0.94·0.06/8) = 0.084, so the 95% interval is 0.94 ± 1.96·0.084 = [0.78, 1.00]. A point estimate without that interval is not a result.
Curated: · Written: · Reviewed:
Q&A-86Your variational loop needs 100,000 circuit executions. Which modality?
Superconducting. The loop is throughput-bound, and transmon two-qubit gates are roughly three orders of magnitude faster than trapped-ion MS gates: hundreds of nanoseconds against hundreds of microseconds. Across 100,000 executions that ratio is the whole answer.
What you multiply is per-execution wall clock, not gate fidelity:
t_exec ≈ depth × t_2q + t_readout + t_reset
Worked example, hypothetical numbers, depth-100 ansatz, 100,000 shots:
| transmon | trapped ion | |
|---|---|---|
| t_2q | 300 ns | 300 µs |
| circuit (depth 100) | 30 µs | 30 ms |
| readout + reset | 5 µs | 1 ms |
| t_exec | ~35 µs | ~31 ms |
| 100,000 shots | ~3.5 s device time | ~52 min device time |
Both totals are small enough that job overhead dominates in practice: 100,000 separate submissions at 100 ms round trip is 2.8 hours regardless of modality. Batch shots into as few jobs as the SDK allows: on superconducting that lever is bigger than the modality choice itself.
The caveat that can flip the verdict is connectivity. Trapped ions couple all-to-all; transmons on a heavy-hex or linear layout need SWAPs to route. If the ansatz's two-qubit interactions are dense, routing can inflate the two-qubit count by more than the 1000× gate-time gap. Compare depth after routing, not logical depth. A 100-layer ansatz that compiles to 100 layers on ions and 2,000 on transmons is a trapped-ion problem.
Failure modes, and how each one shows up:
- Calibration drift on the transmon. T1, T2 and two-qubit error drift over hours, and a variational loop runs for hours. Run a fixed reference circuit every N iterations and track its energy; a step outside the shot-noise band means recalibrate, not add shots. Without that monitor you optimize against a moving objective and the energy you report is meaningless.
- Shot starvation. 100,000 shots split across 500 iterations is 200 shots per gradient estimate. The energy plateaus because the gradient is noise, not because you converged. Distinguish them by watching gradient variance alongside the energy trace: flat energy with flat variance is starvation, flat energy with shrinking variance is convergence.
- Budget exhaustion on the ion trap. Project remaining iterations × t_exec against the deadline before you start. This failure is silent: you simply stop mid-optimization holding a half-converged parameter set.
Pick trapped ion when the ansatz is shallow, needs all-to-all connectivity, and the shot count is small enough that per-gate fidelity outweighs gates per second. At 100,000 executions with a routed depth in the hundreds, it isn't.
Curated: · Written: · Reviewed:
Q&A-92Your annealing results are noisy and inconsistent. What tuning parameter do you check?
Chain strength. That is the first parameter to check, and it explains most "noisy and inconsistent" annealing results.
Mechanism: minor embedding maps one logical variable onto a chain of physical qubits coupled to each other by a chain coupling. That coupling has to be strong enough to keep the chain ferromagnetically aligned, and weak enough not to swamp the problem couplings. Those two requirements pull in opposite directions, and the window between them is what you are tuning.
Too weak: chains break. A sample with a broken chain does not correspond to any assignment of the logical variables: the physical qubits in the chain ended up in different states. The sampler still returns it, and the default chain_break_method (majority vote) silently repairs it into a logical assignment the annealer never sampled. That is where "inconsistent" comes from: the objective values you are comparing are partly manufactured.
Too strong: the chain couplings dominate the problem couplings. The energy landscape flattens, differences between logical assignments shrink relative to the chain term, and the hardware's precision limits start to matter. D-Wave documents integrated control errors on coupling values as a percentage of the programmed value, so a chain strength of 8 makes the absolute error on the problem couplings 8x what it is at chain strength 1. Small problem couplings get lost in that error.
How to check it: sweep chain strength, and for each value record the mean chain break fraction alongside the best objective. The break fraction is the diagnostic; the objective alone is not.
import numpy as np
from dwave.system import DWaveSampler, EmbeddingComposite
sampler = EmbeddingComposite(DWaveSampler())
for cs in [0.5, 1.0, 2.0, 4.0, 8.0]:
ss = sampler.sample(bqm, num_reads=1000, chain_strength=cs)
cbf = ss.record.chain_break_fraction
print(f"cs={cs:4.1f} mean_break={cbf.mean():.3f} best={ss.first.energy:.1f}")
(Python 3.11, Ocean SDK dwave-system; chain_break_fraction is a per-sample field on the returned sampleset. If you leave chain_strength unset, Ocean falls back to uniform_torque_compensation, which scales with chain length and the largest problem bias: a reasonable starting point, but a heuristic, not a measurement.)
Illustrative sweep for a 40-variable MaxCut on Advantage, chains of length 4-6 (figures made up to show the shape, not measured):
| chain_strength | mean break fraction | best energy |
|---|---|---|
| 0.5 | 0.34 | -118.2 |
| 1.0 | 0.11 | -124.7 |
| 2.0 | 0.02 | -131.4 |
| 4.0 | 0.00 | -129.8 |
| 8.0 | 0.00 | -122.1 |
Read it left to right: at 0.5 a third of the samples are invalid, so their energies are not comparable; the objective improves as breaks disappear; past 4.0 breaks are already zero and the objective gets worse, which is the flattened landscape. The usable setting is the smallest chain strength that drives the break fraction to zero, not the largest.
If chain strength does not explain the variance, check in this order: the embedding (long chains need higher chain strength and are more fragile. Re-embed with a shorter chain length), the anneal time (the default 20 µs schedule is short; a longer anneal helps problems with small gaps), and num_reads (run-to-run variance at fixed settings is expected; report the distribution, not the best sample).
What to report with every result: chain strength, mean chain break fraction, the repair rule used for broken chains, and the number of reads. A best objective quoted without the break fraction is not a result you can defend.
Curated: · Written: · Reviewed:
Q&A-97Your dataset has 500 features. How do you get it into a quantum state?
The encoding you pick is decided by what the algorithm does with the data, not by the feature count. Two encodings cover almost every proposal, and they trade qubits against preparation depth in opposite directions.
Assumptions: 500 real-valued features per sample, a gate-based device, no fault tolerance, and an algorithm that reads the state more than once. Otherwise nothing is worth preparing.
Angle (rotation) encoding. One feature per qubit: apply RY(θ_i) with θ_i = x_i scaled into [-π, π] on qubit i. That is 500 qubits, and depth 1 if the device can address every qubit in parallel. The resulting state is a product state, so it lives in a 500-dimensional subspace of a 2^500-dimensional Hilbert space: no exponential compression. That is fine for variational classifiers and quantum kernel methods, where the feature map is the whole point.
Amplitude encoding. Pack the 500 features into the amplitudes of 9 qubits: 2^9 = 512 amplitudes, so pad with 12 zeros. Now the state is a genuine 500-dimensional vector inside a 512-dimensional space. The catch is preparation. Preparing an arbitrary 9-qubit state costs on the order of 2^9 gates in the worst case; Grover-Rudolph reaches polynomial depth only for distributions you can integrate efficiently, and QRAM gives O(log N) depth but does not exist at fault-tolerant scale.
| Encoding | Qubits | Prep depth | Compression |
|---|---|---|---|
| amplitude | 9 | ~2^9 worst case; polylog with QRAM or structure | exponential |
| angle | 500 | 1 with all-to-all; routing-limited otherwise | none |
Worked arithmetic: 500 features become 9 qubits, 512 amplitudes, 12 padding zeros. If the algorithm claims a speedup over a classical O(N) pass, the prep circuit's ~512-gate depth is charged against that claim. For a single query, preparation dominates and you lose. For HHL-style algorithms that query the state O(log N) times, preparation amortizes: that is the only regime where amplitude encoding pays for itself.
Two failure modes are worth naming. First, a proposal claims exponential advantage from amplitude-encoding 500 features into 9 qubits and reports only the model circuit. Compile the state preparation for the actual data and report its depth and two-qubit gate count next to the model's; if prep depth is comparable to or larger than the model depth, the advantage is gone. Second, dequantization: if the data has classically samplable structure (low rank, or an access model you can simulate) the same algorithm runs classically with polynomial overhead, and the quantum version is not faster.
Angle encoding is the right default for near-term variational work. Amplitude encoding only pays when the algorithm queries the state many times and the data has structure you can exploit during preparation. Report qubit count, prep depth and prep gate count together; the model circuit alone is not evidence.
Curated: · Written: · Reviewed:
Q&A-98You want a quantum kernel model on 1,000 training samples. What does that cost?
The number first. 1,000 samples give 499,500 distinct pairs: the Gram matrix is symmetric and the diagonal is 1 for a normalized feature map, so you never compute it. At 4,096 shots per entry that is 2.05e9 circuit executions. On a device sustaining 10,000 shots/s, that is 57 hours of QPU time, before error mitigation, before compilation, and with every entry carrying ~0.8% shot noise.
Each entry comes from the compute-uncompute circuit: prepare U(x_i)|0^n>, apply U(x_j)†, measure P(0^n) = |<psi(x_i)|psi(x_j)>|^2. One circuit per shot, 499,500 distinct circuits.
import math
n, shots, rate = 1000, 4096, 10_000 # rate = sustained shots/s
pairs = n * (n - 1) // 2 # 499_500
total = pairs * shots # 2_045_952_000
print(total / rate / 3600) # 56.8 hours
print(0.5 / math.sqrt(shots)) # 0.0078 -> ~0.8% per entry
| Samples | Pairs | Shots @ 4,096 | QPU hours @ 10k shots/s |
|---|---|---|---|
| 1,000 | 499,500 | 2.05e9 | 57 |
| 10,000 | 49,995,000 | 2.05e11 | 5,688 (~237 days) |
What the 57 hours excludes.
- Compilation. 499,500 distinct circuits, each transpiled and scheduled. At 100 ms per circuit that is ~14 h of classical CPU, serial unless you parallelize the transpiler.
- Error mitigation. Zero-noise extrapolation at three noise levels triples the shots to ~171 h. Probabilistic error cancellation costs exponential in circuit depth, so it is not a constant multiplier.
- Precision is quadratic. Shot noise on a probability estimate is
0.5/sqrt(S). Getting 0.1% instead of 0.8% needs 250,000 shots per entry: 61× the shots, ~3,470 h.
The failure mode that bites. Shot noise perturbs each entry by ~0.8%, and a perturbed Gram matrix is not positive semi-definite. The SVM quadratic program assumes PSD; you either add λI or clip negative eigenvalues, and both bias the kernel you were trying to measure. Detect it by checking the smallest eigenvalue of the assembled matrix before fitting, if it is negative by more than the shot-noise scale, the fit is meaningless.
The comparison that decides it. An RBF kernel on the same 1,000 samples builds its Gram matrix in ~10 ms and the SVM fit is O(n³) ≈ 1e9 flops, seconds end to end. The quantum route is ~2×10⁴× the wall-clock at 4,096 shots. That gap is only worth paying if the feature map is not classically simulable: Huang et al. (Nature Communications, 2021) formalize the test as the geometric difference g(K_Q || K_C), and Liu, Arunachalam and Temme (Nature Physics, 2021) construct a separation where it is provably large. For Pauli or IQP-style feature maps, classical shadows estimate the same kernel in polynomial time, and the gap closes.
So: price the Gram matrix from the sample count before proposing the method, state the shot budget and the noise model for the entries, and if you cannot say why this kernel is hard to simulate classically, use the classical one.
Curated: · Written: · Reviewed:
Q&A-99Your estimated kernel matrix has negative eigenvalues. What do you do?
The 90-second answer. Diagnose before you repair. A kernel matrix is PSD by construction when the kernel is valid, so negative eigenvalues mean one of two things: floating-point error, or a kernel that is not actually PSD. Compare λ_min to λ_max. If |λ_min| is at round-off level, roughly 1e-8·λ_max in float64, symmetrize and clip; nothing is wrong. If λ_min is a real fraction of λ_max, the kernel is indefinite, the dual QP is no longer convex, and the solver may still hand you a vector that is not the optimum of the problem you meant to solve. Anything that calls Cholesky fails outright. Repair, and select the repair's strength inside cross-validation, never against the test split.
Diagnose.
import numpy as np
K = np.array([[1.0, 1.1, 1.1],
[1.1, 1.0, 1.1],
[1.1, 1.1, 1.0]])
K = (K + K.T) / 2 # symmetrize first
w, V = np.linalg.eigh(K) # ascending
print(w) # [-0.1 -0.1 3.2]
print(w.min() / w.max()) # -0.03125
w_clip = np.clip(w, 0.0, None)
K_psd = (V * w_clip) @ V.T
print(np.diag(K_psd)) # [1.0667 1.0667 1.0667]
λ_min/λ_max = -0.031 is not round-off. This kernel is genuinely indefinite. Note what clipping did to the diagonal: k(x,x) went from 1.0 to 1.0667, so a normalized kernel is no longer normalized, and the margin geometry the SVM was fitted against has shifted.
Repair options.
| Repair | Cost | Evaluable on new points? | What it changes |
|---|---|---|---|
| Symmetrize (K+Kᵀ)/2 | O(n²) | yes | fixes asymmetry only, not the sign |
| Eigenvalue clip | O(n³) | no: you get a matrix, not a function | breaks k(x,x)=1; no feature map to evaluate |
| Diagonal jitter K+εI | O(n) | yes | shrinks the fit; ε must exceed |λ_min| |
| Nearest PSD in Frobenius norm | O(n³) | no | equals clipping (Higham 1988) |
| Re-derive from a valid kernel | depends | yes | the honest fix when the kernel itself is invalid |
On the jitter: adding εI shifts every eigenvalue by ε, so ε = 0.1 on the matrix above gives eigenvalues 0, 0, 3.3. Still singular, Cholesky still fails. You need ε strictly greater than 0.1.
Where the indefiniteness comes from decides which repair is honest. A learned similarity, a distance-based kernel built on a non-Euclidean metric, or a kernel evaluated over imputed entries can all be indefinite at the source. Clipping hides that; re-deriving from a valid kernel fixes it.
Failure modes.
- Clipping the training Gram matrix and then trying to score test points. You cannot clip the test block independently: it is not square, and clipping it alone breaks the joint PSD structure. Clipping the joint (n+m)×(n+m) matrix mixes test rows into the training kernel, which is a leak. If you clip, you have committed to a transductive setup.
- Jitter too small. Cholesky needs strictly positive eigenvalues, so ε = |λ_min| exactly still fails.
- Tuning the repair on the test split. Illustrative, not measured: a ridge picked against the test set reports 0.87, and the same pipeline under nested cross-validation reports 0.71. The gap is the repair, not the model.
- Silent wrong answers. A solver that never calls Cholesky returns a solution to a non-convex problem without complaint. The Cholesky error is your only cheap detector.
What I would report. The measured λ_min/λ_max ratio, the repair method and its parameter, and evidence that the parameter was chosen inside nested cross-validation. The repair is part of the estimator, so it belongs in the model description, not in a preprocessing footnote.
Curated: · Written: · Reviewed:
Q&A-100Your hybrid model beats the classical baseline. How do you show the quantum part did it?
The 90-second version. "The quantum part did it" is a claim that the quantum stage contributes accuracy beyond a classical model of matched capacity and matched tuning budget on the same preprocessed inputs. I'd test that with a preregistered ablation: fix the preprocessing, the data splits, and the classical head, then swap only the quantum stage for classical surrogates. Report uncertainty over data splits, not over shots: shot noise is a measurement detail; split variance is what decides whether the effect is real.
Why the control has to be matched. A hybrid pipeline has at least four sources of accuracy: the preprocessing, the feature map, the quantum-estimated quantities, and the classical model on top. Replacing the quantum stage with a random feature map of the same dimension tests whether the gain is just dimensionality: a higher-dimensional feature space often helps regardless of where it came from. Adding a tuned classical kernel on the same inputs tests whether the gain is just tuning. If either surrogate matches the hybrid, the quantum stage is not the owner of the gain.
A worked trace. A team reported a 6-point held-out gain over their classical baseline (0.75 → 0.81). The ablation:
| Pipeline | Held-out accuracy | Gain over baseline |
|---|---|---|
| quantum kernel | 0.81 | +6 |
| random feature map, same dimension | 0.80 | +5 |
| tuned classical kernel | 0.81 | +6 |
The random feature map recovered 5 of the 6 points; the tuned classical kernel recovered all of them. The quantum stage's marginal contribution was zero within split variance. (Figures are illustrative.)
Deciding criteria. I'd call the quantum stage responsible only if three things hold. First, the hybrid beats the best classical surrogate by more than the spread across data splits: as a rule of thumb, the gap should exceed about two standard deviations of the split-to-split variation. Second, the gap survives when the classical surrogate gets the same tuning budget: same search space, same number of trials. Third, the gap holds or grows as you scale the problem, rather than shrinking toward zero.
When a hybrid is still justified. Even with no accuracy edge, the quantum stage can be worth keeping if it reduces sample complexity, fewer labelled examples for the same accuracy, if it encodes structure a classical kernel cannot cheaply represent, such as a physically motivated Hamiltonian, or if the quantum resource is cheaper at the sizes you actually run. Those are separate claims and need their own ablations: a sample-complexity curve, not a single accuracy number.
Failure modes to name. Shot noise reported as split variance inflates significance. Tuning asymmetry (the quantum kernel tuned, the classical baseline left at defaults) manufactures a gain. Kernel concentration at large qubit counts flattens the feature map so the quantum kernel behaves like a constant. And leakage: if the quantum stage saw the test split during feature-map selection, the ablation will look clean and be wrong.
Curated: · Written: · Reviewed:
Q&A-96Which parts of a hybrid workload run near the QPU and which do not?
Core answer
Split the workload by the latency budget each stage has to hit, not by what it computes. Three tiers:
- Real-time (in-circuit) feedback: the decision has to be made and a conditional pulse applied before the qubits decohere. This runs on the control electronics: FPGAs/ASICs in the rack next to the cryostat, not on a host CPU. Examples: a mid-circuit measurement feeding a conditional X, or a surface-code decoder returning a Pauli-frame correction.
- Near-time: parameter updates, calibration, error-mitigation fitting. Milliseconds. Runs on a classical host in the same datacenter as the QPU, e.g. a Qiskit Runtime session or an Amazon Braket Hybrid Job container.
- Offline: circuit construction, transpilation, shot post-processing, decoder training. Seconds to hours. Runs anywhere: batch cluster, laptop, cloud.
Why the boundary sits where it does
The budget for tier 1 is set by coherence. A fixed-frequency transmon has T2 around 100 µs; a two-qubit gate is 200–500 ns. If the feedback decision leaves the FPGA, you pay the host round trip: PCIe plus kernel plus driver plus userspace, tens of microseconds at best, and a datacenter Ethernet hop adds tens to hundreds more. Trace it: measure (≈1 µs digitization) → ship samples to host (10–50 µs) → host decides (1–10 µs) → ship pulse back (10–50 µs) → play. That is 20–100 µs, i.e. 20–100% of T2, per feedback event. On the FPGA the same loop is a few hundred nanoseconds.
For a surface code the constraint is tighter: the syndrome-extraction cycle is ~1 µs, and the decoder must return a correction within that cycle or syndromes queue up. A 50 µs host round trip is 50 cycles of backlog: the decoder falls behind, the Pauli frame is stale, and the logical error rate degrades. That is why real-time decoding is an FPGA/ASIC problem.
Table
| Stage | Budget | Where it runs | What breaks if misplaced |
|---|---|---|---|
| Mid-circuit measurement → conditional pulse | < 1 µs | FPGA on control stack | Conditional fires after decoherence; result is noise |
| Surface-code decoding | ≤ 1 syndrome cycle (~1 µs) | FPGA/ASIC at the cryostat | Syndrome backlog, stale Pauli frame, higher logical error rate |
| Variational parameter update | ms | Host in same DC (Qiskit Runtime session, Braket Hybrid Job) | RTT dominates iteration; run time scales with network, not circuit |
| Calibration / error-mitigation fit | s | Host, same DC | Acceptable; only costs wall-clock |
| Transpilation, shot post-processing, decoder training | s–hr | Anywhere, batch cluster | Nothing, unless it holds a QPU reservation idle |
Trade-offs and when near-QPU is wrong
The alternative to the split is to put everything on the FPGA: lowest latency, but you are writing Verilog for what is often a Python-shaped algorithm, and you cannot iterate. The other extreme, everything on the host, is fine for tier 3 and fatal for tier 1.
Near-QPU placement is wrong when the stage is latency-insensitive and parallel. Training a neural-network decoder, or post-processing 10^6 shots, does not care whether it sits next to the QPU; co-locating it burns QPU-adjacent capacity and, on runtimes that bill a session, holds the device reserved while a CPU job runs. Push it to a batch cluster. Similarly, if a near-time loop's per-iteration classical work exceeds the circuit execution time, the QPU idles between iterations: measure both and move the work, or batch the iterations.
Failure modes to check
- Decoder latency > syndrome cycle → backlog. Detect by logging decoder wall time per cycle against the cycle clock.
- Parameter-update loop dominated by RTT. Detect by comparing per-iteration wall clock to circuit execution time; if the ratio is >2, the network is the bottleneck.
- Conditional feedback that works in a local prototype but not in the deployed topology. Measure per-stage latency and data volume in the real rack-to-host path, not on a laptop.
Curated: · Written: · Reviewed:
Q&A-95A QPU task returns after your classical optimizer has moved on. What have you got?
You have a stale result: a gradient (or energy) evaluated at a parameter vector the optimizer has already replaced. It is a correctness problem, not a latency one. Nothing throws. The loop applies it, the trajectory bends, and the run fails later for reasons that look like hardware noise.
Why it's silent. The update is θ_{k+1} = θ_k − lr·g(θ_k). A result from iteration k−d carries g(θ_{k−d}), which has the same shape and magnitude as the gradient you wanted: it just points from the wrong place. No NaN, no exception, no shot-count anomaly. What you have is gradient descent with a delay, and the stability bound on the step size tightens as the delay grows: a learning rate tuned for zero delay can diverge once results land a few iterations late. On a narrow valley, the delayed gradient walks the optimizer across the valley instead of down it.
Make every result self-identifying. Carry a request id through the loop so a result you didn't ask for is unaddressable, not merely rejected.
completed = {} # request_id -> result, written by the QPU callback thread
next_id = 0
def submit(theta):
global next_id
rid = next_id
next_id += 1
qpu.submit(theta, request_id=rid) # result lands in completed[rid] later
return rid
def collect(rid, timeout=2.0):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
if rid in completed:
return completed.pop(rid).grad
time.sleep(0.01)
return None # timed out; completed[rid] may still arrive later
for k in range(iters):
rid = submit(theta)
g = collect(rid)
if g is None:
continue # skip: no update this iteration
theta = theta - lr * g
Trace it. Iteration 5 submits rid=5 at t=0.0 into a QPU queue three deep; the round trip is ~1.2 s. collect(5) returns None at t=2.0 s, so the loop skips the update. Iteration 6 submits rid=6 at t=2.0 s. The rid=5 result completes at t=2.6 s and lands in completed[5], where nothing reads it, because collect(6) only looks for rid 6. Now change one line, drain completed in arrival order instead, and at k=6 you apply rid=5's gradient, evaluated at θ_5, to θ_6. With lr=0.05 that is a 0.015 displacement in a direction that was correct one step ago. Small per step, but it is systematic lag, not noise, and it accumulates.
Decide the policy explicitly rather than letting whichever branch runs first decide for you:
| Policy on a late result | Optimizer sees | Cost |
|---|---|---|
| apply whatever arrives | g(θ_{k−d}) used at θ_k | silent trajectory corruption |
| match on id, skip | no update this iteration | one wasted QPU batch |
| match on id, retry | fresh g(θ_k) | QPU queue time; livelocks if the step is always faster than the round trip |
| abort the run | nothing | lose the whole run |
Skip is the right default when a QPU batch costs seconds of queue time and the optimizer tolerates a missing step: reuse the previous gradient, or shrink the step. Retry is right when the QPU is fast and the timeout is a rare outlier. Abort is right when a corrupted trajectory costs more than the run.
Failure modes. A retry storm saturates the QPU queue and makes every subsequent result later, which is how a 2% timeout rate becomes 40%. Ids that reset on process restart can match a result from the previous run: persist a monotonic counter or use a UUID. A timeout does not cancel the QPU job, so the guard belongs on the apply path, not just the wait. And completed grows with every abandoned result; prune entries below next_id - window.
Detection. Log the timeout rate per iteration. Above a few percent, the optimizer step is outrunning the QPU round trip, and the fix is more shots per submission or several parameter sets in flight, not retrying harder. In test, inject a delayed response and assert the loop discards it.
Curated: · Written: · Reviewed:
Q&A-94Your circuits take 70 milliseconds each. How long is the experiment?
The execution time is 70 ms per circuit times the number of circuits. If the experiment is 1,000 circuits, that's 70 seconds of device time. The wall-clock time is usually much larger, because queueing dominates: on shared hardware a job waits minutes to hours before it runs.
Assumptions that decide the answer:
- Circuit count N. Execution = 0.07 N seconds.
- Whether the N circuits are submitted as one batched job or N separate jobs.
- The provider's queue policy and whether session or reservation mode is available.
Arithmetic for N = 1,000:
| Submission | Execution | Jobs | Queue per job | Queue total | Wall clock |
|---|---|---|---|---|---|
| Batched | 70 s | 1 | 40 min | 40 min | ~41 min |
| One job per circuit | 70 s | 1,000 | 40 min | 667 h | ~28 days |
| Session mode | 70 s | 1 | 2 h | 2 h | ~2 h 1 min |
The 40 min and 2 h figures are illustrative queue waits; substitute your provider's observed numbers. The point is the ratio: 70 s of execution can sit behind 40 min of queue, a 34× overhead, or behind 667 h, a 34,000× overhead.
A failure I have seen: a variational loop submitted one job per iteration. 300 iterations at 40 min queue each = 200 h of queue. Execution was 300 × 70 ms = 21 s. Wall clock was ~8.3 days. The fix is to batch circuits into as few jobs as the provider allows and use session mode for iterative workloads.
Detection: record queue time and execution time separately for every task. If wall clock is orders of magnitude above 0.07 N seconds, the bottleneck is scheduling, not the device. Report both numbers with the result.
So: if you mean 1,000 circuits, the experiment is 70 seconds of execution and, on a shared device without batching, about a month of wall clock. With batching, about 41 minutes.
Curated: · Written: · Reviewed:
Q&A-93A neutral-atom platform advertises hundreds of atoms. What can it run?
Short answer: "hundreds of atoms" is an analog-Hamiltonian-simulation number. Gate-model circuits on the same hardware run on tens of qubits, not hundreds. Establish which mode a scaling claim refers to before you believe it.
Why the two numbers differ
Neutral-atom arrays entangle through Rydberg blockade: a laser excites atoms to a high principal quantum number (n ≈ 50–100), and two atoms inside the blockade radius, roughly 5–10 µm at n ≈ 70, cannot both be excited. That radius is set by the laser and the van der Waals coefficient, not by wiring.
Analog mode exploits this directly. A global laser addresses every atom at once; the Hamiltonian is defined by atom geometry (loaded from an SLM or tweezer array) plus global Rabi frequency Ω(t) and detuning Δ(t). No per-site addressing, no routing, no SWAPs. That is why 256 atoms is routine: QuEra's Aquila, available on AWS Braket, is a 256-atom analog machine, and Pasqal quotes analog registers in the hundreds.
Gate mode needs single-site control. Each qubit needs its own focused beam for rotations, and a two-qubit gate requires the pair to sit inside the blockade radius: in a static array that means shuttling atoms with tweezers or accepting long-range couplings at worse fidelity. Single-site addressing is slower and lossier, and atom loss of roughly 1–2% per rearrangement or imaging cycle caps circuit depth. Reported two-qubit fidelities sit near 99.5% and single-qubit near 99.9%; a 100-gate circuit compounds that.
| Platform | Analog | Gate model |
|---|---|---|
| QuEra Aquila | 256 atoms, analog only | none offered |
| Pasqal | hundreds of atoms | separate gate mode, smaller register |
| Atom Computing | — | 1,180 atoms, error-correction focus |
The failure mode
A team sized a variational circuit for 256 qubits because the vendor page said 256 atoms. The gate-mode register was a fraction of that and the ansatz did not fit. Detection: compile the actual circuit for the target mode and count physical qubits after routing and ancilla before committing.
What to verify
Ask the vendor for the mode, the register size in that mode, and the two-qubit fidelity at that size. Then compile a representative workload in that mode and check it fits.
Curated: · Written: · Reviewed:
Q&A-90Can you run your gate-model circuit on a quantum annealer?
The 90-second version. No, not for a general circuit. A quantum annealer is a different computational model, not a slower gate machine. It does exactly one thing: find low-energy configurations of a quadratic binary objective. If your circuit computes such an objective, you can hand the problem over; if it computes anything else, there is no known efficient encoding. The honest answer is "no, unless your circuit is already an optimization problem."
Why the mapping fails. A gate-model device applies a sequence of unitaries to a register and you sample the output bitstring distribution. A D-Wave annealer implements a transverse-field Ising Hamiltonian, H(s) = A(s)·Σ σˣᵢ + B(s)·H_problem, where H_problem is diagonal in the computational basis, and evolves from a uniform superposition to H_problem over an anneal time you set. That Hamiltonian is stoquastic, non-positive off-diagonal entries in the computational basis, so it cannot represent an arbitrary unitary. There is no gate set to compile to and no circuit depth. The output is a set of low-energy samples of H_problem, not the output distribution of a program.
What does map. Problems already phrased as minimizing E(x) = xᵀQx with x ∈ {0,1}ⁿ: MaxCut, graph coloring, number partitioning, SAT, portfolio optimization. If your circuit computes one of those, hand the QUBO to the annealer.
Worked example: MaxCut on a triangle. Maximizing the cut is minimizing E(x) = 2(x₁x₂ + x₁x₃ + x₂x₃) − 2(x₁ + x₂ + x₃). Enumerate all eight assignments:
| x₁x₂x₃ | cut edges | E |
|---|---|---|
| 000 | 0 | 0 |
| 001 | 2 | −2 |
| 010 | 2 | −2 |
| 011 | 2 | −2 |
| 100 | 2 | −2 |
| 101 | 2 | −2 |
| 110 | 2 | −2 |
| 111 | 0 | 0 |
Minimum E = −2, i.e. cut value 2, which is the true MaxCut of a triangle. Six of the eight assignments achieve it: any non-constant labeling cuts exactly two edges.
The same QUBO in dimod (Python 3, dimod 0.12):
import dimod
Q = {(0, 1): 2, (0, 2): 2, (1, 2): 2, # quadratic terms
(0, 0): -2, (1, 1): -2, (2, 2): -2} # linear terms
bqm = dimod.BinaryQuadraticModel.from_qubo(Q)
ss = dimod.ExactSolver().sample(bqm)
print(ss.first.energy) # -2.0
ExactSolver enumerates all 2³ assignments; the lowest energy is −2.0, matching the table. On hardware you'd swap ExactSolver for EmbeddingComposite(DWaveSampler()) and read the best of num_reads samples.
Hardware numbers. D-Wave Advantage: Pegasus topology, ~5,000 qubits, 15 couplers per qubit. Advantage2: Zephyr, 20 couplers per qubit. Anneal time is programmable from 0.5 µs to 2000 µs, default 20 µs; you typically request thousands of reads (num_reads=1000) and keep the lowest-energy sample. A dense QUBO needs minor embedding: each logical variable becomes a chain of physical qubits, and a fully connected n-variable problem has n(n−1)/2 couplings, so chain length grows with n and a few hundred dense variables can consume the chip.
Failure modes. Chain breaks: the physical qubits in a chain disagree; D-Wave reports chain_break_fraction and you majority-vote, but a high fraction means the embedding is too tight. Gap collapse: the minimum spectral gap between ground and first excited state shrinks, often exponentially, for hard instances, so a fixed anneal time returns the ground state with low probability; you detect it by the success probability over many reads, not by any hardware error. And the classical baseline: always compare against simulated annealing or a MIP solver (Gurobi, CPLEX) on the same QUBO and the same wall-clock budget, because for most QUBOs of practical size the classical solver wins.
If you want the Ising ground state on a gate machine, that's QAOA: alternate cost and mixer unitaries for p layers, then sample. It targets the same objective with a different model.
Self-assessment
Key points a strong answer hits
- Names the model mismatch: an annealer is an Ising/QUBO sampler, not a universal gate machine.
- States the stoquastic constraint: why an arbitrary unitary can't be represented.
- Says what does map: objectives already in QUBO/Ising form.
- Gives a concrete objective and its optimum (the triangle MaxCut above).
- Mentions minor embedding and chain breaks as the practical cost of mapping.
- Compares against a classical baseline before claiming any advantage.
- Knows QAOA is the gate-model counterpart to annealing.
What interviewers look for Whether you can state the boundary of the model precisely instead of hand-waving "quantum is quantum"; whether you know the output is a set of samples, not a program's output distribution; whether you'd benchmark against classical solvers before claiming speedup.
Weak-answer patterns
- "Yes, you can compile any circuit to an annealer": false; there is no gate set.
- Treating the annealer as a universal quantum computer.
- Quoting qubit counts as if they were gate-model qubits (5,000 annealer qubits ≠ 5,000 logical qubits).
- Claiming quantum speedup with no classical baseline.
- Confusing QAOA (gate model) with annealing.
Follow-up questions
- What's the difference between QAOA and annealing on the same QUBO?
- How does minor embedding change the effective problem size?
- Why is the transverse-field Ising Hamiltonian stoquastic, and what does that forbid?
- How would you detect gap collapse on real hardware?
- When would you pick an annealer over a MIP solver?
Curated: · Written: · Reviewed:
Q&A-91Your QUBO has 100 densely connected variables. How many physical qubits?
Short answer: not 100. For a dense 100-variable QUBO on an annealer, expect a few thousand physical qubits, and the exact number is whatever the embedder returns for that device's working graph. The advertised qubit count is a bound on the hardware, not on your problem.
Assumptions I'd state first: the QUBO is genuinely dense, every pair of the 100 variables has a nonzero coupling, and the target is an annealer whose hardware graph is sparse (Chimera or Pegasus). If either is false the answer changes, and I'd check both before quoting a number.
Why. An annealer can only couple qubits that are physically adjacent. A logical variable whose couplings exceed the hardware degree gets split into a chain of physical qubits locked together by strong ferromagnetic couplers so they act as one variable. In a dense problem every variable couples to all 99 others, so every chain has to reach every other chain. On Chimera a unit cell offers only four qubits per side, so chains grow roughly linearly with the clique size: that is where the multiplier comes from. Physical qubits ≈ logical variables × mean chain length.
Worked example (illustrative numbers). 100 variables, embedder returns chains averaging 38 qubits:
| Quantity | Value |
|---|---|
| logical variables | 100 |
| mean chain length | 38 |
| physical qubits | ~3,800 |
That is 38× the problem. It does not fit a 2,048-qubit Chimera device at all. On a Pegasus device with ~5,000 qubits the same clique embeds with shorter chains, but chain breaks become the thing you measure.
The alternatives, and when each wins.
- Different hardware graph. Pegasus has higher degree than Chimera, so the same clique embeds with shorter chains and fewer physical qubits. Choose it when embedding overhead is the binding constraint.
- Reduce density. Dense QUBOs are often dense only because of a penalty term or a quadratization of higher-order interactions. If the real interaction graph is sparse, embedding is cheap. Check the graph before assuming density.
- Decomposition. Split into subproblems, solve each, stitch. Use it when the embedding does not fit and the problem has exploitable structure; the cost is losing any global-optimality claim and spending more shots.
- Gate model. QAOA needs no minor embedding, but a dense 100-variable problem needs all-to-all connectivity, which no current gate device has natively: you pay in SWAP networks instead. It wins when the interaction graph already matches the device's connectivity.
- Classical. At 100 dense variables, a classical heuristic is the baseline to beat. If it is fast and good enough, the annealer has to justify itself.
Failure mode. Quoting the advertised qubit count as the problem size. Detection: run the embedder, report physical qubits used and the maximum chain length, and measure chain-break fraction in the returned samples. Long chains break more, and broken chains silently corrupt the answer.
What I'd say: compute the embedding first, report overhead and chain-length distribution with any result, and treat the advertised count as hardware capacity, not problem capacity.
Curated: · Written: · Reviewed:
Q&A-89One device leads on quantum volume and another on a speed metric. Which do you pick?
The 90-second answer
Neither, on those numbers alone. Quantum volume and a speed metric are defined by different protocols with different compilation allowances, so a device can lead on one and trail on the other without either score being wrong. Use published scores to build a shortlist; decide from your own compiled workload on each target, at the accuracy and confidence your result needs.
Why the two scores aren't comparable
Quantum volume is a single-number protocol: it fixes a square circuit (width equal to depth) and reports the largest one a device runs with a passing heavy-output probability. It measures the whole stack: qubits, connectivity, gate fidelity, readout, and the compiler that maps the circuit onto the device. A speed metric (executions per hour, or CLOPS-style throughput) counts how many shots of some circuit the system returns per unit time. Different circuit, different compilation freedom, different denominator.
The trap: a benchmark that permits full-circuit optimization measures the compiler as much as the hardware. A vendor can lead a throughput number by compiling a shallow, hardware-native circuit, while its quantum-volume number reflects a deep, connectivity-constrained one. Neither number is a lie; they answer different questions.
What to do instead
- Shortlist from published scores: they are cheap and they bound what is plausible.
- Take your actual circuit, compile it for each target with that vendor's SDK, and measure end to end: transpiled depth, two-qubit gate count, shots needed to reach your target statistical error, and wall clock per shot batch.
- Compare on your metric, not theirs.
Worked example (hypothetical figures)
Two devices, each leading one column:
| Device | Quantum volume | Executions per hour |
|---|---|---|
| A | 128 | 900 |
| B | 32 | 3,600 |
A variational workload needs 200,000 executions.
- Device A: 200,000 / 900 = 222 h ≈ 9.3 days.
- Device B: 200,000 / 3,600 = 56 h ≈ 2.3 days.
Picking A on quantum volume costs about 7 days of wall clock. That is the failure mode: the quantum-volume leader is 4× slower per shot, and on a shot-hungry workload the throughput gap dominates.
Failure modes to name
- Compiler-optimized throughput: the speed number does not survive your transpilation. Detect by re-measuring after compiling your circuit.
- Quantum volume without your topology: the protocol's square circuit may not match your connectivity. Detect by comparing transpiled two-qubit depth.
- Shot-count mismatch: a device with lower error per gate may need fewer shots, flipping the ranking. Detect by computing shots-to-target-error, not raw throughput.
Bottom line
Benchmarks shortlist; workloads decide. Reproduce the vendor protocol or replace it with your own workload measurement before ranking devices.
Curated: · Written: · Reviewed:
Q&A-88A vendor announces twice as many qubits. What have they told you?
What they told you
A number of physical qubits on one device, or, if it's a roadmap slide, a target they intend to reach. Neither is a capability claim. Usable width is roughly min(qubits that pass calibration on the day, qubits the compiler can route your circuit across without blowing the depth budget).
The numbers that decide whether the extra qubits are usable
- Connectivity. Ask for the coupling map, not the count. A heavy-hex lattice has qubits of degree 2 or 3, so a 20-qubit workload that fits inside one neighbourhood needs no SWAPs, while the same workload placed across a sparse region pays routing on every layer.
- Median two-qubit gate error. This is the dominant term. A 127-qubit device at 1% two-qubit error is worse for a 20-qubit circuit than a 65-qubit device at 0.3%.
- Readout error and T1/T2 relative to gate time. The coherence budget is T2 divided by the two-qubit gate duration. At T2 = 100 µs and a 300 ns gate you have on the order of 300 gate times of coherence, but at 1% error per gate you are out of signal after roughly 100 gates regardless of how long the qubits live.
- Calibration yield. Announced width is the fab number. What matters is how many qubits pass calibration the day you run.
Also pin down physical versus logical. If the vendor says "logical qubits", ask for the code distance and the logical error rate per cycle; one distance-3 logical qubit is not one qubit of the same kind as a physical one.
Ask for the workload-shaped result
Compile a representative circuit (yours, or a published benchmark of similar width and depth) to both targets. Compare success probability at fixed shots, and wall time including compilation and queueing. That is the only comparison that survives contact with the transpiler.
Worked example (illustrative figures)
A team swapped a 65-qubit device for a 127-qubit one on a 20-qubit workload. Calibration on the larger chip left the workload's qubits spread across a sparse region, so the compiler inserted SWAPs:
| Device | Physical qubits | Routed 2Q gates | Success prob (1024 shots) |
|---|---|---|---|
| 65q | 65 | 84 | 0.62 |
| 127q | 127 | 131 | 0.41 |
Same circuit, same shots, worse answer. The extra 62 qubits bought nothing and cost 47 additional two-qubit gates, each contributing its own error.
Failure modes to name
- Routing overhead. Depth grows with SWAP count, and success probability falls roughly exponentially in routed two-qubit gate count.
- Crosstalk. Denser couplers and simultaneous drives can degrade neighbours; detect it by comparing isolated against simultaneous randomized benchmarking.
- Yield. A 127-qubit device with 90 calibrated qubits is a 90-qubit device for your purposes.
- Compiler placement. Different transpiler seeds give different routing; pin the seed and the transpiler version and report both.
How I'd settle it
Run the same circuit on both targets at fixed shots and report success probability with a confidence interval, plus routed two-qubit gate count, transpiler version and seed. If the new device wins on that, the qubit count was a real capability increase. Until then it is a resource count.
Curated: · Written: · Reviewed:
Q&A-87How much does device topology matter to your algorithm choice?
Short answer: topology matters as much as gate error, and for any algorithm dense in long-range interactions it can matter more. The comparison that decides it is not "which device has better two-qubit fidelity" but "what does my interaction graph cost to embed in each coupling map." Topology enters as a multiplier on two-qubit gate count, and gate count enters exponentially into success probability.
Why. A two-qubit gate needs the two qubits physically adjacent. If the algorithm's interaction graph has an edge between non-adjacent qubits, the compiler inserts SWAPs, three CNOTs each, to bring them together, or decomposes the interaction over a longer path. So routed gate count ≈ (interaction count) + 3 × (SWAPs), and the SWAP count scales with the average pairwise distance in the coupling map. All-to-all coupling: zero SWAPs. A 2D lattice (heavy-hex is degree 3): every non-adjacent pair pays.
Worked example (hypothetical figures, chosen to be self-consistent). 12 qubits, all-to-all interaction graph: every one of the C(12,2) = 66 pairs interacts once.
- All-to-all device: K12 edge-colours into 11 matchings of 6, so 66 two-qubit gates, no routing.
- 2D lattice: a SWAP-based router emits 216 CNOTs. 66 interactions plus 150 routing CNOTs (50 SWAPs).
| Topology | Two-qubit gates | Per-gate fidelity | Success ≈ f^n |
|---|---|---|---|
| all-to-all (ion trap) | 66 | 0.994 | 0.67 |
| 2D lattice (superconducting) | 216 | 0.997 | 0.52 |
The lattice has the better gate (0.997 vs 0.994) and still loses, because 216 gates at 0.997 is worse than 66 at 0.994. Break-even: the lattice needs per-gate error below 1.8×10⁻³ (fidelity > 0.9982) to match a 0.994 ion trap. A 3.3× tighter gate than it has. This ignores readout and idle decoherence; include them and the lattice looks worse, not better.
When topology doesn't matter. If the algorithm is already local: a nearest-neighbour Trotter circuit on a line, QAOA on a graph that matches the hardware: routing overhead is near zero and you should pick on fidelity, coherence and qubit count instead. Shallow circuits also dilute the penalty: the exponential only bites once the routed count is in the hundreds. And all-to-all is not free: those devices typically pay in crosstalk, slower gates, or fewer qubits.
Topology can also change which algorithm you pick. A locality-friendly variant with 20% more gates but zero routing can beat the dense version on a lattice device, even though it loses on an all-to-all one.
Failure modes I'd watch for.
- Choosing hardware on headline two-qubit fidelity without transpiling. A 3× routed count erases a 2× fidelity advantage; the arithmetic above is the check.
- Trusting one transpiler run. SWAP count depends on the initial layout and the router; transpile across several seeds and take the distribution, not the best number.
- Treating the interaction graph as fixed. It is a property of the algorithm and its encoding: swapping Jordan-Wigner for a locality-preserving fermionic encoding can cut the routed count on a lattice device by a large factor.
What I'd do. Transpile the workload to each candidate coupling map, compare routed two-qubit counts, multiply per-gate fidelities, and only then compare devices. If the lattice loses, reformulate toward locality before ruling the hardware out.
# Qiskit 1.x
from qiskit import transpile
from qiskit.transpiler import CouplingMap
qc = build_algorithm() # 12 qubits, all-to-all interaction graph
for name, cm in [("all-to-all", CouplingMap.from_full(12)),
("2D lattice", CouplingMap.from_grid(3, 4))]:
t = transpile(qc, coupling_map=cm, basis_gates=["cx", "u"],
optimization_level=3, seed_transpiler=0)
print(name, t.count_ops().get("cx", 0))
Curated: · Written: · Reviewed:
Q&A-76Two frameworks both offer an expectation-value primitive. Are they the same thing?
No. They share a name and a shape (circuit in, observable in, number out) and differ in four places that change the number you get back. Assume hardware-backed estimation on a superconducting device, not a statevector simulator; on a simulator the question mostly evaporates.
The three you'll meet: Qiskit Runtime's EstimatorV2, Cirq's cirq.work.measure_observables, and PennyLane's qml.expval.
| Framework | Primitive | Readout mitigation default | Uncertainty returned |
|---|---|---|---|
| Qiskit Runtime | EstimatorV2 | on: resilience_level=1 applies measurement twirling + TREX | yes, data.stds alongside data.evs |
| Cirq | cirq.work.measure_observables | off: you pass readout_calibrations yourself | yes, mean/variance/stddev per observable |
| PennyLane | qml.expval | off: qml.mitigate_with_zne is opt-in | no: the value only |
(Checked against qiskit-ibm-runtime 0.2x, cirq 1.x, pennylane 0.3x.)
Two more axes. Grouping: Qiskit Runtime groups commuting observables before it submits, so you get one number per observable without asking. Cirq bins commuting Pauli strings into measurement groups itself. PennyLane hands you one value per observable and leaves grouping to qml.transforms.split_non_commuting. Shot budget: Qiskit takes a target precision (standard error) per pub, with default_precision/default_shots as the fallback; Cirq takes repetitions per group; PennyLane takes shots per circuit. Same word, three meanings.
When each default is right. Qiskit's on-by-default mitigation is the right choice when you're on real hardware with ~1–3% readout error and you want a defensible number without hand-rolling calibration circuits. It costs extra calibration circuits per job, and TREX assumes readout error is uncorrelated across qubits: crosstalk or leakage breaks that assumption and the "corrected" value can land further from the truth than the raw one. Cirq's explicit calibration is right when you need to control exactly which calibration circuits run, or when you're comparing against a simulator and want mitigation out of the way. PennyLane's analytic default (shots=None) is right for algorithm development, where you want the exact expectation and no sampling.
The failure mode. Comparing a mitigated number to an unmitigated one and calling it a device problem. Illustrative example: same 4-qubit circuit, same Pauli observable, 4096 shots each. Stack A reports −0.734 with mitigation on; Stack B reports −0.672 with it off. The gap is 0.062. The standard error on a Pauli expectation at 4096 shots is at most 1/√4096 = 0.0156, so two independent estimates differ by ~0.022 at 1σ: the gap is roughly 3σ. That is not shot noise, and it is not physics either; it is the mitigation setting.
What I'd do before believing a cross-stack difference. Pin the observable, the circuit, and the shot count; disable mitigation on both (resilience_level=0 in Qiskit, no readout_calibrations in Cirq); require agreement within shot noise. Only then turn mitigation back on and compare like with like. Compare estimators before comparing results.
Self-assessment
Key points a strong answer hits
- Names the actual primitives (
EstimatorV2,measure_observables,qml.expval) not "Qiskit and Cirq". - States the shared contract (circuit + observable → expectation value) and says that the contract is where the similarity ends.
- Covers at least two of the four axes: mitigation default, uncertainty reporting, grouping, shot/precision semantics.
- Says which default is right for which situation, rather than listing options.
- Gives a concrete procedure for comparing across stacks instead of eyeballing two numbers.
What interviewers look for
- Whether you know the defaults, not just the API surface. The default is what silently changes your result.
- Whether you separate "different number" from "different device".
- Whether you can name the assumption mitigation rests on (uncorrelated readout error) and what breaks it.
- Whether you'd design the comparison (pin inputs, disable mitigation, budget the shot noise) before drawing a conclusion.
Weak-answer patterns
- "They're the same, both compute ⟨ψ|O|ψ⟩." True of the math, useless about the tooling.
- Listing API differences without saying which one moves the number.
- Treating a mitigated and an unmitigated value as comparable.
- Quoting a cross-stack gap with no shot-noise budget attached.
- Assuming
shotsmeans the same thing in all three frameworks.
Follow-up questions
- What does TREX assume, and how would you detect that the assumption is violated on your device?
- You disable mitigation on both stacks and they still disagree by 5σ. What now?
- How would you get an uncertainty estimate out of PennyLane?
- When is grouping commuting observables a bad idea?
- Why does
shots=Nonechange the character of the answer, not just its precision?
Curated: · Written: · Reviewed:
Q&A-77You export a circuit to OpenQASM and import it elsewhere. What do you check?
Assume the producer is Qiskit 1.x or 2.x and the wire format is OpenQASM 2.0 unless the consumer advertises 3.0 support: 2.0 is the lowest common denominator and the one that loses the most. If the circuit contains measurement or reset it is not unitary, and that changes which check you run.
Three checks, in order. Did every construct survive. Is the semantics preserved up to global phase. Did the consumer fail loudly on anything it could not represent. The third is the one people skip and the one that matters: a converter that drops a construct and hands back a valid circuit is worse than one that raises, because the failure is now downstream of you.
For the first check, diff the instruction set, not the gate count. qasm2.dumps will not emit a global phase at all, OpenQASM 2 has no syntax for it, so a circuit with global_phase = 0.7 comes back with global_phase = 0.0 and no warning. OpenQASM 3 added gphase for exactly this, but support is per-consumer.
For the second, compare unitaries when the circuit is unitary and small enough to materialise. Operator.equiv is exact and compares up to global phase, but it builds the full 2^n × 2^n matrix, so it is practical to about 12 qubits (4096 × 4096, roughly 270 MB) and dead at 20. Above that, compare statevectors on a fixed input with Statevector.equiv: 2^n amplitudes, fine to about 25 qubits. When the circuit has measurement, or is bigger still, sample instead, but sample in more than one basis: a Z-rotation error is invisible in computational-basis counts.
from qiskit import QuantumCircuit, qasm2
from qiskit.quantum_info import Operator
qc = QuantumCircuit(2, name="fixture")
qc.h(0)
qc.cx(0, 1)
qc.rz(0.3, 1) # asymmetric: breaks the |00>+|11> symmetry
qc.global_phase = 0.7
back = qasm2.loads(qasm2.dumps(qc))
print(Operator(qc).equiv(Operator(back))) # True
print(Operator(qc).global_phase, Operator(back).global_phase) # 0.7 0.0
Trace: dumps writes OPENQASM 2.0; include "qelib1.inc"; qreg q[2]; h q[0]; cx q[0],q[1]; rz(0.3) q[1];. No statement carries the phase. loads rebuilds the circuit with global_phase = 0. equiv compares up to global phase, so it returns True and tells you nothing about the loss. Reading global_phase off both operators is what catches it. That matters when the circuit is later used as a controlled block, where the phase stops being unobservable.
Third check: qiskit.qasm2.loads defaults to strict=True and raises on gates outside the standard set; strict=False accepts them. Vendor gates like rzz and ecr are outside that set, so strict import rejects circuits a lenient one swallows. That is the cost of strictness: you have to decompose to standard gates first, which changes the gate count and, on real hardware, the noise profile. Pay it. A rejected import is a five-minute fix; a silently substituted gate is a wrong result.
Failure modes worth naming. Global phase dropped, as above. Endianness: QASM 2 q[0] is the first wire and Qiskit indexes statevectors little-endian, so a big-endian consumer reverses every bitstring. An asymmetric fixture catches it, a uniform superposition hides it. And if(c==1) feed-forward, which QASM 2 restricts to whole-register equality and a consumer may ignore entirely, running the conditional gate unconditionally.
| Construct | OpenQASM 2 | OpenQASM 3 | Silent loss |
|---|---|---|---|
| global phase | no syntax | gphase | yes |
custom gate definition | yes | def | only if consumer ignores it |
| arbitrary unitary | no, decompose | box (opaque) | yes, if decomposed wrong |
delay / timing | no | yes | yes |
classical if | whole-register equality | general expressions | yes |
mid-circuit measure | yes | yes | no |
Sources: OpenQASM 2.0 spec (arXiv:1707.03429), OpenQASM 3 spec (arXiv:2104.14722), Qiskit qiskit.qasm2 documentation.
Curated: · Written: · Reviewed:
Q&A-78Your dynamic circuit behaves differently after export. Where do you look?
Start with what "export" means, because the answer changes. Serializing to OpenQASM 2 or 3 is a text transform; transpiling to a backend ISA also permutes qubits and rewrites the gate set. I'd look in three places, in this order: the classical-bit mapping, whether the target supports mid-circuit measurement and feed-forward at all, and the qubit permutation from routing. The classical-bit mapping comes first because it's the one that fails silently: the exported circuit parses, runs, and looks correct.
Why it breaks: a conditional is written against a named classical bit. In QASM 2 that's if(c1==1) on creg c1[1]; in QASM 3 it's if (c[1] == 1). Hardware returns one flat bitstring per shot, so exporters map named registers onto offsets in that flat register. Merge creg c0[1]; creg c1[1]; into bit[2] c; and c1[0] becomes c[1]. A converter that keeps the old index now branches on a different qubit's measurement.
Here's the transform, by hand:
Source (QASM 2):
qreg q[2];
creg c0[1];
creg c1[1];
h q[0];
measure q[0] -> c0[0];
measure q[1] -> c1[0];
if(c1==1) x q[0];
After flattening to one register (QASM 3):
qubit[2] q;
bit[2] c;
h q[0];
c[0] = measure q[0];
c[1] = measure q[1];
if (c[0] == 1) x q[0]; // was c1[0]; now reads q[0]'s own result
The branch was meant to fire on q[1]'s outcome and now fires on q[0]'s. Nothing else in the text changed.
The other two places, and how to tell them apart:
| Symptom in the exported circuit | Likely cause | Check |
|---|---|---|
| Conditional gone from the text | Target lacks mid-circuit measurement / feed-forward | Backend's supported operations |
| Conditional present, reads a different bit | Register flattening / reindexing | Diff clbit indices, source vs export |
| Conditional present, right bit, wrong qubit | Routing permutation | Compare the final layout |
| Fires at the wrong point | Measurement reordering, dropped reset/delay | Instruction order in the exported text |
If the conditional is missing from the exported text entirely, it's not a mapping bug: the target doesn't implement mid-circuit measurement plus feed-forward, or requires it enabled, or only allows it on a subset of qubits. Check the backend's supported operations before touching the converter. If the conditional is present and reads the right bit but targets the wrong qubit, it's routing: transpilation to the coupling map permutes qubits, and the conditional follows the logical qubit to whatever physical qubit it landed on. Compare the final layout. If it's present, right bit, right qubit, but fires at the wrong point, look at instruction order: exporters may append or reorder final measurements, delay has no QASM 2 equivalent and is dropped, and reset is dropped by targets that don't support it. Any of which changes a circuit that depends on mid-circuit state.
The deciding test is the exported text itself. Diff the classical-bit indices and the instruction order against the source. If the conditional survived, it's a mapping or routing bug; if it didn't, it's a support bug.
To confirm, force each branch. Run the exported circuit on a simulator with the condition forced true and then false, and assert the gate fires on the intended measurement outcome. On hardware the symptom is a success rate that drops while the circuit diagram is unchanged, which is exactly why the exported text, not the diagram, is where you look.
Curated: · Written: · Reviewed:
Q&A-79Does it matter that your rotation angles are serialized to six decimal places?
Short answer: per gate, no. Across a circuit, it depends on whether the truncation is biased.
One rotation rounded to six decimals is off by at most 5e-7 rad. Two-qubit gate errors on current superconducting hardware run around 1e-3, so a single gate's serialization error sits three orders of magnitude below the noise floor. Nobody should lose sleep over one rotation.
The question is what thousands of them do together. Two regimes:
- Unbiased rounding (round-to-nearest): each angle is off by a random ±5e-7. The errors add as a random walk, so the total phase error after N gates is about √N · 5e-7.
- Biased truncation (floor, or a serializer that drops digits): every angle is off in the same direction by up to 1e-6. Errors add linearly: N · 1e-6.
For a circuit whose observable is phase-sensitive, say ⟨X⟩ = cos(Σθ) on a chain of Rz gates, the error in the estimate is bounded by the phase error, since |d cos/dθ| ≤ 1.
| N rotations | δ per gate | unbiased Δ ≈ √N·δ | biased Δ ≈ N·δ |
|---|---|---|---|
| 10 | 5e-7 | 1.6e-6 | 5e-6 |
| 1,000 | 5e-7 | 1.6e-5 | 5e-4 |
| 12,000 | 5e-7 | 5.5e-5 | 6e-3 |
| 12,000 (floor) | 1e-6 | — | 1.2e-2 |
So the same "six decimals" is harmless at 1,000 gates and worth roughly 1% of your answer at 12,000 if the truncation is biased. That 1% is the kind of error that sits inside your error bars and outside the accuracy your conclusion needs.
Why it stays invisible. The circuit is still unitary. No gate fails, no fidelity check trips, the simulator runs. The only symptom is that the number you get back is slightly wrong, and it is wrong in a way that looks like hardware noise. Interleaving entangling gates scrambles the phase and partially cancels the error, but you cannot rely on that: the bound above is the worst case, and a circuit built to accumulate a phase (phase estimation, QAOA angle sweeps) sits close to it.
What I would do. Keep parameters at full double precision, or symbolic, until binding. If you must serialize to six decimals for file size, use round-to-nearest rather than floor: that alone turns linear accumulation into a random walk. Then verify on the largest circuit in the workload:
import numpy as np
rng = np.random.default_rng(7)
theta = rng.uniform(-np.pi, np.pi, 12_000)
def expectation(angles):
# |+> through a chain of Rz(angles); <X> = cos(sum(angles))
return np.cos(angles.sum())
full = expectation(theta)
rounded = expectation(np.round(theta, 6)) # unbiased
floored = expectation(np.floor(theta * 1e6) / 1e6) # biased
The gap between full and rounded is your rounding budget; the gap to floored is what a biased serializer costs you.
When it does not matter. If your target precision is 1e-3, typical for NISQ hardware, six decimals is fine up to a few thousand gates even with floor. It matters when the circuit is long, when the answer is a phase, or when you are comparing two runs that differ only in how the parameters were written out.
Curated: · Written: · Reviewed:
Q&A-80Your submission times out but the provider may have accepted it. What now?
What a strong candidate says first
Don't resubmit. A timeout is an ambiguous outcome: the provider may have accepted the request and lost the response, or may never have seen it. Resubmitting turns an unknown into a probable duplicate.
The first move is to ask the provider what it knows, using an identifier you control rather than one the provider assigned. If you sent an idempotency key or client token with the request, query by it: the provider either has a task under that key or it doesn't, and that answer is authoritative. If you didn't send one, reconcile by a natural key: a hash of the task payload, or the business identifier (order ID, job name) that makes this submission unique. List recent tasks matching that key and compare.
Only when that check comes back empty do you resubmit, and you resubmit with the same key, so a race between your query and a late-arriving original still collapses to one task.
The alternatives, and when each is right
| Approach | What it gives you | Where it breaks |
|---|---|---|
Provider idempotency header (Stripe Idempotency-Key, AWS ClientToken) | Provider dedupes server-side; retrying is safe | Key must exist before the first attempt; Stripe documents a 24-hour retention window, so a retry after that creates a second task |
| Natural-key dedupe on your side | Works with providers that have no idempotency support | Needs a stable key; payloads carrying timestamps or random fields break it |
| Reconciliation job | Catches duplicates after the fact, including ones you never retried | Eventually consistent; you may already have paid twice |
| Blind retry | Trivial to write | Duplicates and double billing on every transient error |
Criteria: if the provider supports idempotency keys, use them and retry freely. If it doesn't, you need a natural key plus a reconciliation sweep, and you accept a window where duplicates are possible.
Failure modes
- Duplicate tasks billed twice. Detect by counting tasks per idempotency key and alerting when any key has more than one.
- Duplicate results treated as independent samples. This is the quiet one: two identical rows averaged into a metric read as two observations. Detect by deduping on the natural key before aggregation.
- Reusing a key for a different payload. Stripe rejects a key reused with different parameters rather than silently returning the first result, which means the key must be derived from the payload, not from a counter.
- Key expiry. A retry past the provider's retention window is a new request. Detect by timestamping the original attempt and refusing to retry past the window without a fresh reconciliation.
Verification
Inject a timeout after the provider accepts, kill the connection after the write commits, and confirm the client recovers the existing task instead of creating a second. That is the only test that exercises the ambiguous path.
Curated: · Written: · Reviewed:
Q&A-81How do you avoid discovering a device restriction from a failed job?
Query the live target at submission time, check the circuit against it locally, and only submit if it passes. The check costs one target fetch and one transpile, sub-second, and it is the only thing standing between you and a rejection that arrives after the queue.
What the target actually carries. A BackendV2 exposes backend.target: basis gates, coupling map, qubit count, and the operation set the device currently accepts. That operation set is the part people miss. It is not just x, cx, measure: control-flow ops show up there as if_else and while_loop when the device supports dynamic circuits, and vanish when the provider disables them for maintenance. Target.instruction_supported(name, qargs=...) answers both "does this backend accept it" and "does it accept it on these qubits". Job-level limits (shots per job, circuits per job) sit on the backend object rather than the target, and are worth reading in the same pass.
from qiskit import QuantumCircuit, transpile
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService()
backend = service.backend("ibm_brisbane") # fetched now, not at process start
target = backend.target
qc = QuantumCircuit(3, 3)
qc.h(0)
qc.measure(0, 0)
with qc.if_test((qc.clbits[0], 1)): # mid-circuit feed-forward
qc.x(1)
qc.measure(1, 1)
if not target.instruction_supported("if_else"):
raise RuntimeError("target has no if_else: dynamic circuits unavailable")
if not target.instruction_supported("if_else", qargs=(1,)):
raise RuntimeError("if_else not supported on qubit 1")
isa = transpile(qc, backend=backend, optimization_level=1, seed_transpiler=7)
assert "if_else" in isa.count_ops(), "transpiler dropped the feed-forward"
On a backend whose target lists if_else, all three checks pass and isa is a circuit the provider will accept. On one where maintenance has disabled it, the first check raises in milliseconds, before anything enters the queue. The count_ops assertion covers the other direction: a pass manager that rewrites the circuit into something legal but not what you meant.
Where each check fails.
| Check | Runs | Time to failure | What a miss costs |
|---|---|---|---|
target snapshot + instruction_supported | local | ~0.2 s | nothing |
transpile to ISA | local | ~1 s | nothing |
| provider validation | provider, post-queue | 20–90 min (illustrative) | queue position, resubmit |
| job failure mid-execution | provider | minutes–hours | shots, queue position |
Alternatives, and when each wins. Transpiling alone is free and catches basis gates and connectivity, but the pass manager has no opinion on whether the provider will accept mid-circuit measurement today: that is a policy flag on the target, not a routing problem. Submitting and catching the error catches everything, including restrictions the target cannot express, and is the right call when jobs are cheap and the queue is short. Pinning a backend and circuit pair that worked last week is fastest and breaks silently at the next maintenance window. The deciding criterion is the ratio: a failed job costs queue time times batch size, the pre-flight check costs one target fetch. When that ratio is above one, check first.
Failure modes. A BackendV2 you fetched at process start goes stale: maintenance flips if_else off, your cached target still says yes, and the check passes. Re-fetch immediately before submit, or compare the fresh target's operation names against the snapshot you validated. A check that passes locally can still be rejected because the restriction is per-instance: your instance may not have access to that backend at all, which the target does not encode. List service.backends(instance=...) for the instance you will submit to. And a local check cannot see a maintenance window that opens after you submit; for that, catch the provider error, re-fetch the target, re-transpile, and resubmit rather than retrying the same circuit.
Curated: · Written: · Reviewed:
Q&A-82What runs in CI for a quantum codebase, and what does not?
The 90-second answer. Three tiers run on every pull request, and all three are offline: ideal statevector simulation, noisy simulation, and transpilation against a fake backend. Hardware runs on a schedule and on deploy, never on a branch. The rule that places an assertion is cost per check: a statevector assertion costs milliseconds, a QPU job costs queue time plus metered device time, so only assertions that require a device go there.
| Tier | Runtime per check | Catches |
|---|---|---|
| Ideal statevector | ms | gate ordering, phase conventions, ancilla cleanup |
| Noisy simulator | s | mitigation and post-selection logic, readout handling |
| Fake backend transpile | ms–s | routing, coupling-map violations, gate-set translation |
| Provider simulator | s | credential handling, PUB serialization, primitive options |
| Hardware canary | min | provider defaults, calibration drift, real readout error |
Sizing the simulator tiers. Statevector memory is 2^n amplitudes at 16 bytes each (complex128): 20 qubits is 16 MiB, 25 is 512 MiB, 30 is 16 GiB. Density-matrix simulation is 4^n × 16 bytes: 10 qubits is 16 MiB, 12 is 256 MiB, 14 is 4 GiB. So cap statevector tests at 25 qubits and density-matrix tests at 12, which keeps a standard 8 GB runner comfortable. Clifford-only circuits are the exception: a stabilizer simulator is polynomial in qubits and gates, so those tests can run at thousands of qubits and belong in CI.
Structural assertions are deterministic; ratio assertions are not. This is the distinction that keeps the suite from going flaky.
# Qiskit 1.x, qiskit-aer
from qiskit import QuantumCircuit, transpile
from qiskit_aer import AerSimulator
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
sim = AerSimulator(seed_simulator=7)
counts = sim.run(transpile(qc, sim), shots=1024).result().get_counts()
Trace: H puts q0 in (|0⟩+|1⟩)/√2, CX entangles it into (|00⟩+|11⟩)/√2, both qubits are measured. counts therefore has exactly two keys, '00' and '11', summing to 1024; '01' and '10' never appear. That key-set assertion is the one to make: it fails immediately if the CX is dropped or misordered, and it cannot flake. The split between the two keys is Binomial(1024, 0.5), standard deviation √(1024 × 0.25) = 16 counts, so an unseeded run lands in 512 ± 48 at three sigma. Asserting exactly 512 fails about 2.5% of the time. Either seed the simulator, or assert the band, not the exact count.
What stays out. Hardware in the pull-request path, because queue time is shared and unbounded and a branch pipeline inherits it; the failure mode is a pipeline whose p95 duration is set by someone else's backlog, which ends with the team disabling the quantum tests. Variational loops (VQE, QAOA parameter sweeps) stay out because they produce a distribution, not a pass/fail, and take minutes to hours. Full device characterization and calibration stay out. Anything above the memory caps above stays out. And any tier needing an API token stays out of fork-triggered runs, because GitHub Actions does not pass secrets to pull_request workflows from forks: that tier runs on push and schedule instead.
Failure modes and how you see them. A flaky statistical assertion gets retried, then ignored; track flake rate per test and fix by seeding or widening the band. A provider tier that silently skips on every fork PR means serialization regressions land unnoticed; track skip rate and add a same-repo merge-queue run. A pinned noise model drifts away from the live device; a scheduled job diffs NoiseModel.from_backend against the snapshot. A backend's coupling map or gate set changes under you; a scheduled job diffs backend.target against the stored snapshot and fails loudly. The hardware canary asserts even parity on a Bell pair above a threshold taken from a baseline run, and alerts when that fraction drops: that is the only check that sees real readout error.
Curated: · Written: · Reviewed:
Q&A-83How do you assert on a sampled distribution without a flaky test?
To assert on a sampled distribution without a flaky test, set a tolerance based on the standard error (SE) of the statistic, not on exact counts. For a probability estimate from N independent samples, SE = sqrt(p(1-p)/N). With N=4096, SE ≤ 0.0078 (since max at p=0.5 gives sqrt(0.25/4096) ≈ 0.0078). So a tolerance of 3 SE is about 2.3 percentage points. Assert that the observed proportion is within k SE of the expected, where k is chosen to balance false positives and detection power. Seed the random sampler and record the seed so failures are reproducible.
Exact counts fail because they have variance: even a correct implementation will produce different counts each run. Widening the tolerance arbitrarily reduces power. For example, a suite that asserted counts within ±20 failed roughly one run in six; the team widened to ±200, at which point it stopped detecting a real 8% regression. The following table compares strategies at 4,096 shots:
| Assertion | Flaky | Detects 8% regression |
|---|---|---|
| exact counts | yes | yes |
| ±5 percentage points | no | no |
| 3 standard errors | no | yes |
The mechanism: the central limit theorem makes the sample proportion approximately normal for large N, so k SE gives a confidence interval. Choose k based on the desired false positive rate. For a single assertion, k=3 gives ~0.3% false positive rate. For multiple assertions, adjust with Bonferroni or similar. The test should be validated by injecting a regression of the size that matters and confirming the test fails.
Failure modes: If samples are not independent (e.g., correlated shots), the SE formula underestimates variance. If N is small, the normal approximation may not hold; use exact binomial tests or bootstrap. If the distribution is not binomial, use the appropriate variance estimator. Also, if the sampler is not seeded, failures are not reproducible.
This applies to any sampled distribution: quantum circuits, randomized algorithms, Monte Carlo simulations. The key is to derive the tolerance from the sample size and variance, not to guess.
Curated: · Written: · Reviewed:
Q&A-84Why is pinning the SDK not enough to reproduce a run?
Pinning the SDK fixes the source-level API you write against. It does not fix the circuit that actually runs. On hardware you never execute your QuantumCircuit; you execute the transpiled, ISA-form circuit, and that object is a function of more inputs than the version string.
What actually determines the executed circuit:
- Transpiler version and pass-manager defaults. A minor release can change routing or layout heuristics.
optimization_levelandseed_transpiler. Level 3 with a different seed picks a different layout.- The backend target snapshot: coupling map, basis gates, and per-qubit calibration. IBM backends recalibrate daily, so the same source transpiled a week apart can differ.
- Provider API schema: how the primitive serializes parameters and results.
Two runs with the same pinned SDK can therefore execute different circuits.
Alternatives, and when each is right:
-
Pin the whole toolchain in a container. Pin
qiskit,qiskit-aer, the provider package,numpy, and the image digest. This reproduces transpilation deterministically, but not the backend: a live device's calibration drifts, so re-transpiling next month against the same pinned stack still yields a different circuit. Good for simulator work, insufficient for hardware. -
Store the transpiled circuit itself. Serialize the ISA circuit with QPY and keep it with the result. This is the only option that reproduces the exact executed object without re-running the compiler. Cost: QPY is versioned. A file written by Qiskit 1.2 may not load in 1.0, so record the writing version too, and expect to re-transpile if you upgrade.
-
Hybrid, which is what I'd do: pin the toolchain for the source, and store the QPY of the transpiled circuit plus the backend target snapshot and job ID. The QPY is the ground truth; the pinned stack lets you regenerate and diff if the QPY is unreadable.
from qiskit import transpile, qpy
from qiskit_ibm_runtime import QiskitRuntimeService
backend = QiskitRuntimeService().backend("ibm_brisbane")
isa = transpile(circuit, backend=backend,
optimization_level=3, seed_transpiler=1234)
with open("run.qpy", "wb") as f:
qpy.dump(isa, f) # store this next to the result
Failure modes and detection:
- Silent layout change: same source, newer transpiler, more two-qubit gates, lower fidelity. Detect by diffing CNOT counts between the stored and regenerated circuits.
- Backend drift: the stored circuit is fine but the device's calibration moved, so re-running gives different results. Detect by comparing the calibration timestamp in the stored target snapshot against the run date.
- QPY incompatibility: load fails after an upgrade. Detect at load time; mitigate by keeping the writing version.
Illustrative example (numbers made up to show the shape):
| Release | CNOTs after transpile | Success |
|---|---|---|
| pinned | 96 | 0.71 |
| newer | 117 | 0.58 |
Same source, same seed, different transpiler release.
Verification: re-run the stored QPY on a simulator and confirm it reproduces the recorded counts, then confirm the hardware job ID and calibration window match. If the QPY reproduces and the hardware result does not, the drift is in the device, not your code. Keep the artifact that ran, not just the source that produced it.
Curated: · Written: · Reviewed:
Q&A-85Which seeds does a quantum experiment need to record?
Record every seed that feeds a random draw, not just the one that looks like "the" seed. In a Qiskit/Aer stack that is three: the simulator's shot-and-noise seed (seed_simulator), the transpiler's routing seed (seed_transpiler, or SabreSwap(seed=...)), and the optimizer's initialization seed (your own RNG, e.g. np.random.default_rng(seed)). Record the RNG type and the framework versions next to the integers, because np.random.seed(42) (legacy RandomState) and np.random.default_rng(42) (Generator) produce different streams from the same number.
import numpy as np
from qiskit import transpile
from qiskit_aer import AerSimulator
rng = np.random.default_rng(7) # optimizer init
isa = transpile(circuit, backend=backend, seed_transpiler=11)
res = AerSimulator().run(isa, shots=4096, seed_simulator=23).result()
| Draw | Control | Effect if unrecorded |
|---|---|---|
| shot + noise sampling | seed_simulator (Aer) | counts differ run to run |
| routing / layout | seed_transpiler, SabreSwap(seed=) | different physical gate sequence, so different noisy counts |
| optimizer init | your RNG, e.g. np.random.default_rng(seed) | different start, possibly a different local minimum |
Why all three matter. seed_simulator fixes only the sampling of the final distribution; it does not fix the distribution itself. seed_transpiler fixes the layout and the SWAP insertion order, so a different value gives a different physical gate sequence. On an ideal noiseless simulator that still yields the same distribution and the same counts; once a noise model or a device is involved, the sampled error locations differ and the counts diverge even with an identical seed_simulator. The optimizer seed fixes the starting point of a variational loop, and a different start can converge to a different local minimum, so the final energy changes.
The trade-off is fixed seeds versus averaging over seeds, and it depends on the claim. For "this circuit produces this distribution," fix the seeds and record them; one run is the experiment. For "this algorithm reaches energy E," a single seed is one sample, and reporting the best of many seeds overstates performance. Average over a recorded set of seeds and report the mean and spread. A lucky initialization seed is a real bias in variational work, so a claim about the algorithm needs several seeds, not the best one.
A concrete failure: a variational run reached a promising energy that could not be repeated, because the optimizer's initial parameters came from an unseeded generator. Twenty restarts from other starts averaged 0.08 hartree worse (hypothetical figures). The detection is to re-run from the recorded seeds on the same versions and compare the full trajectory, energies per iteration, not just the final value; matching only the endpoint can hide a different path.
One caveat on scope: Qiskit Runtime's Sampler and Estimator primitives do not expose a seed, and real hardware is not reproducible, so seeds cover only the classical parts (transpilation, parameter initialization). Record them anyway, and treat a result whose seeds are missing as an observation rather than a reproducible experiment.
Curated: · Written: · Reviewed:
Q&A-107Write and run a Bell-state circuit in Qiskit or Cirq. Walk me through the gates, what the simulator returns, and what changes on hardware.
I'll use Qiskit 1.x and assume we're on a simulator first, then a real device.
The circuit is two gates: Hadamard on qubit 0, then CNOT with control 0 and target 1. Measure both qubits.
from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
sim = AerSimulator()
result = sim.run(qc, shots=1024).result()
print(result.get_counts())
The simulator returns something like {'00': 512, '11': 498}: only those two keys, roughly equal. The 01 and 10 keys are absent or at numerical noise level (exactly zero on a statevector simulator). That's the signature: the qubits are perfectly correlated. If you see 01 and 10 at ~25% each, you either forgot the CNOT or put the H on the wrong qubit.
Why 1024 shots? It's the Qiskit default and gives a standard error of about 1.6% on a 50/50 split: sqrt(0.25/1024) ≈ 0.0156. For a first look that's fine. If you need to resolve a 1% deviation from ideal, you need ~10,000 shots or more.
Transpilation is where the simulator and hardware diverge. On a statevector simulator with no coupling map, transpile may leave H and CX as-is or decompose to the backend's basis gates. On real hardware, the backend's basis set is typically rz, sx, x, cx. The H becomes rz(pi/2) sx rz(pi/2) or similar. The CX stays a CX if qubits 0 and 1 are physically adjacent; if not, the transpiler inserts SWAPs, which are three CXs each. That's a 3x or 7x increase in two-qubit gate count for a two-qubit circuit: on a 2-qubit circuit it's trivial, but the same effect on a 50-qubit circuit is the difference between fitting in coherence time and not.
On hardware, the ideal distribution smears. Typical superconducting numbers: CX error ~0.5–1%, readout error ~1–3% per qubit. So instead of {'00': 512, '11': 512}, you might see {'00': 470, '11': 460, '01': 50, '10': 44}. The 01 and 10 counts come from gate errors and readout misassignment. The 00/11 imbalance comes from asymmetric readout error: qubit 0 might read 1 as 0 more often than the reverse.
The Bell state is a fixed point of depolarizing noise in the sense that it stays a mixture of Bell states, so the correlated peaks survive but with reduced contrast. You can quantify that with a parity measurement: the fraction of shots where the two bits agree. Ideal is 1.0; hardware might give 0.93. That's a useful single number to track across calibrations.
To go further, you'd run a CHSH inequality test. Measure in the four bases (ZZ, ZX, XZ, XX) and compute S. Ideal is 2√2 ≈ 2.828; a value above 2 certifies entanglement. On hardware, S around 2.5–2.7 is typical for a decent device. That's the real check that you built a Bell state, not just a correlated classical mixture.
Failure modes to watch: forgetting to measure both qubits (you get no counts), measuring only one (you see 50/50 on that qubit alone, which looks like no entanglement), or running on hardware without checking the calibration, if T1 has dropped or the CX is miscalibrated, you get a mess.
Curated: · Written: · Reviewed: —
Q&A-108A colleague wants to run a deep, fault-tolerant algorithm on today's hardware. What does the NISQ era actually constrain, and how does that change the design?
Assume a superconducting device today: T1 ≈ 100 µs, T2 ≈ 80 µs, two-qubit gate time ≈ 50 ns, two-qubit gate error ≈ 1e-3, readout error ≈ 1e-2. The NISQ constraint is that there is no fault tolerance. Every gate and every idle moment adds error, and we cannot correct it. So the design goal shifts from "minimize gate count asymptotically" to "minimize depth and total error per run."
The hard limit is coherence. A circuit of depth d with gate time t_g takes roughly d·t_g. If that approaches T2, the state decoheres before you finish. With T2 = 80 µs and t_g = 50 ns, you have a raw budget of ~1600 gate times, but errors accumulate: with per-gate error p, success probability ≈ (1-p)^N. For p = 1e-3 and N = 1000 gates, that's ~37%. For N = 5000, ~0.7%. Practical circuits today are tens to a few hundred gates deep, not thousands.
That rules out deep fault-tolerant algorithms like full Shor or deep phase estimation. It favors shallow variational circuits: VQE, QAOA, and other parameterized circuits with a few layers. The ansatz depth is chosen to fit the coherence budget, and the classical optimizer handles the rest. The trade-off is that shallow circuits may not be expressive enough to represent the target state, and the optimization landscape can have barren plateaus.
Error mitigation is the bridge. It does not correct errors; it reduces their bias in expectation values. Three common techniques:
- Readout error mitigation: calibrate a confusion matrix and invert it on the counts. Costs extra calibration circuits and can amplify statistical noise.
- Zero-noise extrapolation (ZNE): run the circuit at several noise levels (e.g., by gate folding) and extrapolate to zero noise. Costs 3–5× shots.
- Dynamical decoupling: insert pulse sequences on idle qubits to refocus dephasing. Costs no extra shots but requires calibration.
None of these give you a logical qubit. Error correction does: it encodes one logical qubit in many physical qubits, measures stabilizers to detect errors, and corrects them. It requires physical error rates below a threshold (~1e-2 for surface code) and thousands of physical qubits per logical qubit. Today's devices are at or above threshold and have too few qubits, so QEC is not available for algorithm design.
| Regime | Physical error | Qubits per logical | Depth budget | Algorithm style | | NISQ | 1e-3 – 1e-2 | N/A | ~100s of gates | Shallow variational + mitigation | | Fault-tolerant | < 1e-2 (below threshold) | 1000s | unlimited | Deep circuits, QEC |
Failure modes: mitigation can hide errors that are not stochastic, e.g., leakage or correlated errors; ZNE assumes noise scales smoothly, which fails for non-Markovian noise. Readout mitigation can produce negative probabilities. Dynamical decoupling can introduce errors if the pulse sequence is not calibrated.
So the design rule: estimate your depth budget from T2 and gate error, pick a shallow ansatz that fits, and use mitigation to squeeze out bias. If you need thousands of gates, you need fault tolerance, which means waiting for better hardware.
Curated: · Written: · Reviewed: —
Q&A-102Two vendors pitch you their flagship QPU. How do you compare them objectively for your workload?
First question back: compare them for what? A device that wins a headline benchmark can lose on your circuit, so I fix the workload first (say a 20-qubit, 40-layer ansatz with mid-circuit measurement) then pick metrics that bound whether it runs.
Quantum volume is the standard starting point and it is a real measurement, not marketing. For width n you generate random circuits of n qubits and n layers of SU(4) gates, simulate them classically, and measure the heavy-output probability: the mass the device puts on the half of bitstrings with above-median ideal probability. Haar-random circuits give ≈0.85 ideally; the pass criterion is a mean above 2/3 at 2σ confidence over many circuits. QV = 2^n for the largest n that passes.
Three assumptions make it narrower than it looks. The model circuit is all-to-all, so on a heavy-hex lattice the transpiler inserts SWAPs and the compiled depth is far above n: you are measuring routing as much as gates. It is square, so it says nothing about a shallow-wide or deep-narrow circuit. And it doubles per qubit, so QV 64 vs QV 128 hides whether the extra qubit is good or the existing ones improved.
That is why one fidelity number cannot rank devices. Randomized benchmarking's error-per-Clifford is an average over a gate set, on isolated qubits, with no crosstalk, no leakage, no spectator errors and no readout. A device can post 99.9% two-qubit RB and still fail your circuit because parallel gates interfere.
What I check instead:
- Layer fidelity / EPLG. Run simultaneous two-qubit gates across a whole layer and measure the process fidelity of that layer. This captures crosstalk, which isolated RB cannot. Error per layered gate is EPLG = 1 − LF^(1/d) for a d-qubit layer.
- CLOPS. Circuit layer operations per second: how many QV-like layers the stack executes per second, including the classical round trip. It tells you whether a 10,000-iteration variational loop is minutes or days. CLOPS_h includes parameter updates; plain CLOPS does not.
- Application-level benchmarks. The QED-C suite (QFT, phase estimation, amplitude estimation, Hamiltonian simulation) or, better, your own circuit at your width and depth.
- Operational facts. Connectivity, native gate set, readout fidelity, T1/T2, calibration cadence, queue time, per-shot cost.
| Metric | Measures | Misses |
|---|---|---|
| Quantum volume | largest square random circuit passing the heavy-output test | topology cost, non-square shapes, per-qubit detail |
| Two-qubit RB | average error per Clifford, isolated pair | crosstalk, leakage, readout |
| Layer fidelity | fidelity of a full parallel layer | circuit-specific structure |
| CLOPS | throughput including classical overhead | accuracy |
| Application benchmark | end-to-end success on a real circuit | generality |
The arithmetic that decides most cases is layer fidelity compounding. At LF = 0.99 per layer, 0.99^100 ≈ 0.37 after 100 layers; at LF = 0.999, 0.999^100 ≈ 0.90. So a 100-layer circuit needs roughly 0.999 per layer to stay above 90%. For a 100-qubit layer with LF = 0.5, EPLG = 1 − 0.5^(1/100) ≈ 0.0069, about 0.7% error per qubit per layer.
Failure modes to watch: a vendor quoting QV from a calibration date weeks before your run; QV measured with all-to-all compilation while your circuit is routed; CLOPS quoted without parameter updates when your loop updates them. The detection is the same in each case: re-run the benchmark yourself on both machines, same transpiler settings, same shots, same day, and record the calibration timestamp next to the number.
So my answer to the vendors is a table of my own circuit's success probability and wall-clock per iteration on each device, dated, and that decides it.
Curated: · Written: · Reviewed: —