Skip to content
Tech Interview Prep
Technical interview guide

Quantum Programming Frameworks

The practical toolchain a quantum software engineer works in day to day (Qiskit, Cirq, and PennyLane) and the difference between simulators and real hardware backends.

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

Scope: Qiskit current; Cirq current; PennyLane 0.45; Amazon Braket current; OpenQASM 3; QIR current documentation reviewed 2026-09-04.

Interview Q&A

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

Curated: · Written: · Reviewed:

25 questions

Q&A-1

How do core quantum programming frameworks (e.g., Qiskit, Cirq, PennyLane) differ in their circuit representations, execution models, and target hardware abstractions?

Answer

The 90-second answer. All three build circuits from gates on wires; they disagree about what a circuit is. Qiskit treats it as a program to compile: QuantumCircuit is a mutable instruction list on virtual qubits, the transpiler lowers it to a DAGCircuit, and a Target supplies the coupling map, native basis, durations and error rates of one device. Cirq treats it as a schedule: a Circuit is an ordered list of Moments, each a set of operations on mutually disjoint qubits, so concurrency is explicit from construction. PennyLane treats it as a function: a QNode records ops onto a QuantumTape inside a classical autodiff graph, and the framework's core competence is analytic gradients, not device compilation. Compiler, scheduler, autodiff engine.

Representation.

  • Qiskit: QuantumCircuit holds (operation, qubits, clbits) instructions; DAGCircuit is the transpiler IR (qiskit.converters.circuit_to_dag). No time offsets until a scheduling pass adds them. Control flow is native: IfElseOp, WhileLoopOp, SwitchCaseOp (1.0), Store (1.1).
  • Cirq: Moment enforces disjointness: cirq.Moment(cirq.X(q0), cirq.Y(q0)) raises. cirq.Circuit inserts with InsertStrategy.EARLIEST by default, packing each op into the earliest moment whose qubits are free. That is why Cirq circuits read like hardware schedules.
  • PennyLane: QuantumTape is a linear record of ops plus measurements; QNode binds it to a device and a diff method. Since 0.36, qml.capture.enable() traces QNodes into PLxPR, a JAXPR-like IR, so JAX can compile the whole hybrid loop.

Execution.

  • Qiskit: SamplerV2/EstimatorV2 with PUBs: (circuit,), (circuit, parameter_values), (circuit, observables, parameter_values). SamplerV2 returns BitArrays, EstimatorV2 returns evs/stds. Qiskit 1.0 removed qiskit.opflow and QuantumInstance; 2.0 removed BackendV1 and assemble().
  • Cirq: cirq.Simulator for state vectors, cirq.Sampler for shots, cirq.Study for sweeps; cirq_google reaches Google's Engine. cirq.google moved to cirq_google in Cirq 1.0, and ClassicallyControlledOperation was replaced by CircuitOperation.with_classical_controls.
  • PennyLane: qml.device("default.qubit") (exact statevector), "lightning.qubit" (C++), "default.mixed" (density matrix). diff_method="parameter-shift" costs two circuit executions per parameter for a single-parameter rotation; "adjoint" costs one extra circuit regardless of parameter count but needs measurements at the end.

Worked example: why the representation decides the cost. Route a CX between qubits 0 and 2 on a line coupling map 0–1–2. Track target bits over GF(2), where CX(i,j) does x_j ^= x_i:

start     (x0, x1, x2)
CX(0,1)   (x0, x1^x0, x2)
CX(1,2)   (x0, x1^x0, x2^x1^x0)
CX(0,1)   (x0, x1, x2^x1^x0)
CX(1,2)   (x0, x1, x2^x0)   == CX(0,2)

One long-range CX becomes four native CX gates. IBM's heavy-hex lattice (max degree 3, e.g. the 127-qubit Eagle) puts typical qubit pairs several hops apart, so SabreSwap: the default routing method since Qiskit Terra 0.20: spends its budget picking a layout that keeps that multiplier down. Cirq's GridQubit sidesteps it by making you place qubits on the grid up front; PennyLane mostly doesn't care, because its target is a simulator or a plugin.

QiskitCirqPennyLane
Core objectQuantumCircuit → DAGCircuitCircuit of MomentsQuantumTape in a QNode
Qubit idvirtual Qubit in a QuantumRegisterGridQubit, LineQubit, NamedQubitinteger/string wires
Device modelTarget (basis, coupling map, durations, error rates)Device/GridDevice (geometry, moment validation)backend plugin (Device/DeviceV2)
Optimised forcompilation, dynamic circuits, error mitigationpulse/moment scheduling, noise modellingvariational algorithms, gradients

Failure modes.

  1. Layout blowup. Each long-range CX costs at least 4 CX gates (the identity above), so an all-to-all Qiskit circuit transpiled onto heavy-hex can see two-qubit gate counts multiply several-fold, and depth grows faster than gate count once SWAPs serialize. Compare count_ops() and depth() before and after transpile(); don't eyeball the drawing.
  2. Re-transpiling inside a variational loop. Calling transpile() per optimizer step re-runs layout and routing. Transpile once and bind parameters later, or pass a parameter array through an EstimatorV2 PUB.
  3. Cirq moment explosion. InsertStrategy.NEW, or ops added in a bad order, gives one moment per gate: a 100-gate circuit reports depth 100 and the scheduler has nothing to pack. Check len(circuit.moments) against len(list(circuit.all_operations())).
  4. Gradient cost. Parameter-shift on a 100-parameter ansatz is 200 circuit executions per gradient: fine on default.qubit, fatal on hardware.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

In Qiskit, what is the architectural difference between the Sampler and Estimator primitives, and how do you choose between them for near-term quantum algorithms?

Answer

The 90-second answer

Both primitives take a circuit and a shot budget. They differ in what they hand back and where the statistics get collapsed.

Sampler returns measurement outcomes: a BitArray of bitstrings, or counts derived from it. You get the raw sample. Estimator returns a real number: the expectation value of a Hermitian observable you supply as a SparsePauliOp, plus a standard error.

That difference decides the choice. If your algorithm's cost function is $\langle\psi(\theta)|H|\psi(\theta)\rangle$ (VQE, a variational classifier's mean loss, a time-evolved observable) use Estimator. If your algorithm consumes bitstrings: QAOA's candidate solutions, Grover's marked state, anything where the shape of the distribution is the answer: use Sampler.

The reason it matters beyond convenience: to get $\langle H\rangle$ out of Sampler you must choose measurement bases yourself, group commuting Pauli terms, split shots across groups, and recombine. Estimator does that inside the primitive, where it can also apply error mitigation to the estimate. Doing it by hand in Python forfeits the shot allocation and the mitigation, and shot allocation is where most of the variance in a VQE run actually comes from.

Assumptions, and what would flip the decision

Qiskit 1.x with primitives V2 (BaseSamplerV2 / BaseEstimatorV2). V1 is a different API: V1's Sampler returned a QuasiDistribution, V2 returns a BitArray. If your observable is a single Pauli term, the grouping advantage disappears and Sampler plus manual reduction is competitive. If a classical post-processing step needs the full distribution, Estimator cannot give it to you at any shot count.

How Estimator does the work

You pass state preparation only: no terminal measurements, because the primitive appends its own basis rotations and measurements. It partitions the observable into qubit-wise-commuting groups, appends the basis change per group ($H$ for $X$, $S^\dagger H$ for $Y$), runs shots per group, and combines the per-group means weighted by the Pauli coefficients. The standard error it returns comes from those per-group shot counts, so that is the number to watch when tuning precision.

SamplerV2EstimatorV2
PUB shape(circuit, params)(circuit, observables, params)
Circuit ends inexplicit measurestate preparation only
ReturnsBitArray / counts$\langle H\rangle \in \mathbb{R}$ + standard error
Basis choiceyoursprimitive's, from the observable
Readout erroruncorrected in the bitstringsfolded into the estimate

Failure modes

  • Handing Estimator a circuit that already ends in measurements: it appends its own, so strip them first.
  • Computing $\langle H\rangle$ from Sampler counts without M3 or a calibration-matrix inversion gives a biased estimate: readout error is not corrected in the returned bitstrings.
  • Setting shots explicitly on Estimator means you own the precision; leaving it to the default precision target lets the primitive pick the shot count.
  • A poor commuting-group partition inflates the shot cost, sometimes by an order of magnitude on a 20-qubit Hamiltonian.

Worked example

Python
from qiskit.circuit import QuantumCircuit
from qiskit.quantum_info import SparsePauliOp
from qiskit.primitives import StatevectorEstimator, StatevectorSampler

qc = QuantumCircuit(2)
qc.h(0)                       # (|00> + |10>)/sqrt(2); qubit 1 stays |0>

obs = SparsePauliOp.from_list([("ZZ", 0.5), ("ZX", 0.5)])
est = StatevectorEstimator()
print(est.run([(qc, obs)]).result()[0].data.evs)

qc_m = qc.copy()
qc_m.measure_all()
samp = StatevectorSampler()
print(samp.run([qc_m], shots=1024).result()[0].data.meas.get_counts())

Trace. Qubit 0 is in $|+\rangle$, qubit 1 in $|0\rangle$. $\langle ZZ\rangle = \langle Z_0\rangle\langle Z_1\rangle = 0 \cdot 1 = 0$; $\langle ZX\rangle = \langle Z_1\rangle\langle X_0\rangle = 1 \cdot 1 = 1$. Weighted: $0.5 \cdot 0 + 0.5 \cdot 1 = 0.5$, so the first print is [0.5] (one observable, so a length-1 array). measure_all() adds a 2-bit register named meas; the state gives outcomes 00 and 10 with probability 1/2 each, so the second print is roughly {'00': 512, '10': 512}: the exact split depends on the seed.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

How does Cirq use Moments and Operations to represent quantum circuits, and how does this explicit time-slice structure differ from gate-queue representations?

Answer

Core answer (first 90 seconds)

A Cirq Circuit is a sequence of Moments. A Moment is a set of Operations that act on disjoint qubits, and an Operation is a Gate bound to specific qubits. The schedule, which gates share a time slice, is the data structure itself, not something a later pass derives. len(circuit) is the number of moments, i.e. the depth in time slices.

The invariant: no two operations in a moment may share a qubit. cirq.Moment([cirq.X(q0), cirq.H(q0)]) raises ValueError at construction. A moment may be empty, and an empty moment is meaningful: it is a time slice where nothing happens, which is how Cirq expresses idle time without a delay instruction.

Contrast with gate queues

A gate-queue representation (Qiskit's QuantumCircuit instruction list, OpenQASM 2) is a flat ordered list of instructions. Concurrency is implicit: either the executor runs an instruction as soon as its qubits are free (ASAP), or a scheduling pass assigns time slots. Qiskit does this in transpile(..., scheduling_method='asap'|'alap'); OpenQASM 3 added delay/durationof to express timing that OpenQASM 2 could not. In Cirq you make that decision while building the circuit.

Worked example

Python
import cirq

q0, q1 = cirq.LineQubit.range(2)
c = cirq.Circuit()

c.append(cirq.H(q0), strategy=cirq.InsertStrategy.NEW)
c.append(cirq.H(q1), strategy=cirq.InsertStrategy.EARLIEST)
c.append(cirq.CNOT(q0, q1), strategy=cirq.InsertStrategy.EARLIEST)

print(c)
print(len(c))

Trace:

  • c starts with zero moments.
  • H(q0) with NEW allocates a fresh moment at the end: moment 0 = [H(q0)].
  • H(q1) with EARLIEST scans from the front; moment 0 holds H(q0) on q0, q1 is free, so it joins moment 0: [H(q0), H(q1)].
  • CNOT(q0, q1) with EARLIEST finds both qubits busy in moment 0, so it creates moment 1.

Output:

0: ───H───@───
          │
1: ───H───X───

len(c) is 2.

Insertion strategies

  • EARLIEST: slide the operation back to the first moment where all its qubits are free. It never commutes past an operation on the same qubit.
  • NEW: always allocate a fresh moment at the end.
  • NEW_THEN_INLINE: allocate a new moment, then route subsequent appends inline into it.
  • INLINE: append into the last moment, raising ValueError if the qubits collide.
Cirq Moment modelGate queue / DAG (Qiskit QuantumCircuit, OpenQASM 2)
Circuit isSequence[Moment]; the schedule is the data structureflat instruction list; the schedule is derived later
Concurrencyexplicit, fixed at constructionimplicit; ASAP/ALAP pass or DAG topological order
Same-qubit collisionrejected when the Moment is builtallowed; ordering is list position
Idle timean empty Moment, or a qubit absent from oneneeds an explicit delay (OpenQASM 3) or is inferred
Depthlen(circuit) directlycomputed after scheduling

Failure modes

  1. Depth inflation. Appending 20 single-qubit gates on 20 distinct qubits with NEW yields a 20-moment circuit; with EARLIEST it is 1 moment. Check len(circuit) after a build loop.
  2. EARLIEST moving a gate you meant to keep late. A dynamical-decoupling echo pulse intended to sit after a two-qubit gate can slide into an earlier free moment, breaking the symmetry around that gate. Pin it with NEW, or diff circuit.moments before and after the append.
  3. Device validation. A moment can be structurally valid (disjoint qubits) and still illegal for the target: device.validate_circuit(circuit) raises ValueError when a moment schedules operations the hardware cannot run simultaneously, such as two two-qubit gates sharing a coupler. This surfaces at build/validate time rather than at run time.

Cirq's design targets hardware where a control system drives a fixed set of qubits per clock cycle, so keeping the time slice explicit keeps the circuit close to the pulse schedule.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

How do Qiskit transpilation passes (specifically basis gate translation, routing, and optimization levels) impact circuit depth and fidelity on noisy quantum backends?

Answer

Assume a fixed-coupling superconducting backend: native two-qubit gate ECR (or CZ), two-qubit error 0.5–1%, single-qubit error 0.03–0.1%, and RZ implemented as a virtual frame change (zero error, zero duration). Under those assumptions, routing is the dominant cost, basis translation sets a floor you cannot optimize below, and the optimization level buys depth at the price of compile time and determinism.

Basis translation sets the floor. Your abstract gates are rewritten into the backend's native set: typically {id, rz, sx, x, ecr}. RZ is free; SX and X are cheap; ECR is the gate that costs you. A SWAP is not native: it becomes 3 ECRs plus single-qubit corrections. A Toffoli becomes roughly 6 two-qubit gates. This step is deterministic for a given synthesis method, so you cannot optimize your way out of it: you can only pick a better synthesis (for example a different synthesis_method in UnitarySynthesis). Circuits heavy in multi-controlled gates pay their depth here.

Routing is usually the dominant cost. Layout assigns virtual qubits to physical ones; routing inserts SWAPs whenever a two-qubit gate spans a non-adjacent pair. On a line Q0–Q1–Q2, a CNOT between Q0 and Q2 costs:

StepOperationTwo-qubit gates
1SWAP Q2 onto Q13
2CNOT Q0, Q11
3SWAP Q1 back to Q23
Total7

Generalising: a naive swap-and-restore router pays 6(d−1)+1 two-qubit gates for a gate between qubits at distance d. Fidelity multiplies per gate, so F ≈ (1−e)^n. At e = 0.008, that block drops from 0.992 for a single gate to 0.992^7 ≈ 0.945. Depth and error both grow with qubit distance, and error compounds exponentially in the two-qubit count, which is why the two-qubit count, not depth(), is the number to watch.

Optimization levels trade compile time and determinism for depth.

  • Level 0: trivial layout, no optimization. It still routes, so the output runs: a debugging baseline, not a deployment choice.
  • Level 1: trivial layout plus light local optimization. Cancelling adjacent inverse gates, merging rotation angles.
  • Level 2: SABRE for both layout and routing, plus commutation analysis and gate consolidation.
  • Level 3: SABRE with more randomized trials and higher-effort two-qubit unitary synthesis, keeping the best result. Non-deterministic, and markedly slower to compile.

SABRE is connectivity-driven, not noise-driven: it minimises SWAP count against the coupling map, not error rates. To steer around a qubit with bad T1, add a noise-aware layout pass or a custom pass manager.

Measure it on your own circuit (Qiskit 1.x):

Python
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import GenericBackendV2

backend = GenericBackendV2(
    num_qubits=5,
    basis_gates=["id", "rz", "sx", "x", "ecr"],
    coupling_map=[[0, 1], [1, 2], [2, 3], [3, 4]],
    seed=42,
)

qc = QuantumCircuit(5)
qc.h(0)
for i in range(4):
    qc.cx(i, i + 1)   # nearest-neighbour: no routing needed
qc.cx(0, 4)           # spans the line: routing required
qc.measure_all()

for level in range(4):
    tqc = transpile(qc, backend, optimization_level=level, seed_transpiler=42)
    print(level, tqc.depth(), dict(tqc.count_ops()))

Read the ecr count out of count_ops() and plug it into (1−e)^n. Hypothetical figures for a 5-qubit, 10-CNOT circuit on a line, at e = 0.008:

LevelDepthTwo-qubit gatesSuccess prob.
045300.786
132220.838
225180.865
322160.879

The trade-off is not "always level 3". Level 3's two-qubit resynthesis is heuristic and randomized, so on some circuits it returns a different decomposition that is no shorter, and two runs can disagree. Lower depth also does not guarantee higher fidelity: a layout that avoids a hot qubit can beat a shorter circuit routed straight through it.

What would change the answer: all-to-all connectivity removes routing, leaving basis translation as the floor. Two-qubit error an order of magnitude lower makes depth matter less than calibration drift. A circuit shallow enough that routing adds one or two SWAPs makes levels 1 and 3 nearly identical, and I would take the deterministic one.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

How does Cirq enforce hardware constraints through its Device classes, and how do you validate or map a circuit onto a specific superconducting layout such as Sycamore?

Answer

Cirq splits this into two objects. cirq.Device is a validator and metadata source: it never rewrites your circuit. Mapping onto a real layout is the job of cirq.transformers, and the contract is transform-then-validate: device.validate_circuit(circuit) raises ValueError if anything violates the target.

What Device enforces

A cirq.Device exposes metadata (qubit_set, gateset, nx_graph), validate_operation, validate_moment, validate_circuit, and duration_of. cirq_google.Sycamore is the static 54-GridQubit layout; cirq_google.SycamoreGate is the native two-qubit gate and is legal only on the pairs the device enumerates. Validation is eager: a Circuit(device=d) validates every append, so a bad gate fails at construction, not at submission.

python import cirq, cirq_google from cirq.transformers import route_circuit_cqc, optimize_for_target_gateset

device = cirq_google.Sycamore q = sorted(device.metadata.qubit_set)[:3]

c = cirq.Circuit(device=device) c.append(cirq.H(q[0])) c.append(cirq_google.SycamoreGate().on(q[0], q[2]))

ValueError: (q0, q2) is not a valid Sycamore pair

device-free build, then map, then validate once

raw = cirq.Circuit(cirq.CNOT(q[0], q[1]), cirq.CNOT(q[1], q[2])) routed = route_circuit_cqc(raw, device.metadata.nx_graph) mapped = optimize_for_target_gateset(routed, gateset=cirq_google.SycamoreGateset()) device.validate_circuit(mapped)

route_circuit_cqc inserts SWAPs so every two-qubit interaction is local; optimize_for_target_gateset decomposes into SycamoreGate, PhasedXZGate, MeasurementGate and WaitGate. Neither pass knows about fidelity: they satisfy topology and gate set only.

The surface an interviewer wants to see named

SurfaceEnforcesFails how
metadata.qubit_setlegal qubitsunknown qubit → ValueError
metadata.gatesetnative gatesnon-native gate rejected
validate_operationgate on a legal pairSycamoreGate on an uncoupled pair
validate_momentdisjoint qubit supportoverlapping ops in one moment
duration_ofns per operationfeeds alignment and scheduling
validate_circuitall of the aboveraises before you submit

What routing costs, in numbers

Take 12 two-qubit interactions on non-adjacent pairs. Each SWAP is 3 SycamoreGates plus single-qubit corrections, so routing adds 36 two-qubit gates. At the 2019 Sycamore calibration of roughly 0.6% error per two-qubit gate, fidelity from those gates alone is $0.994^{36} \approx 0.80$: about 20% lost to routing, before decoherence. Layout choice, not just validity, decides the result.

Failure modes

  • Static class versus calibration device. cirq_google.Sycamore carries no error rates. engine.get_processor('sycamore').get_device() returns a SerializableDevice with a calibration snapshot: per-qubit $T_1$, readout error, gate durations. Validating against the static class passes circuits the live device will run badly.
  • Valid but bad subgraph. Routing can land on coupled qubits that are the worst on the chip. Sycamore shipped 54 qubits; the 2019 supremacy run used 53 because one was out of spec. Pull calibration and weight the layout.
  • Moment validation is not timing validation. validate_moment checks disjointness, not duration alignment. Two operations of different length in one moment pass validation and still need cirq.align_left/align_right before pulse-level scheduling.
  • Eager validation cost. A 10k-operation circuit built with device= validates on every append. Build device-free, validate once.

Use cirq.UNCONSTRAINED_DEVICE for abstract or simulation work; pay for validation only when the target is real.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Design and validate a quantum software workflow for global phase.

Answer

What I'd say first

Global phase is the scalar e^{iφ} in front of a whole unitary. On a standalone state it is unobservable: U and e^{iφ}U give the same density matrix ρ = U|ψ⟩⟨ψ|U†, so no measurement distinguishes them. It stops being unobservable the moment U sits on a controlled branch or inside a composition, because then e^{iφ} multiplies only part of the Hilbert space and becomes a relative phase. So the workflow separates two questions: "equal up to phase?" for standalone modules, and "exactly equal?" for controlled embeddings.

Assumptions: qubit unitaries, no mid-circuit measurement in the equivalence checks, Python 3.11 with Qiskit 1.x or Cirq 1.x for the library helpers.

The workflow

  1. Declare the convention. Each gate/circuit module carries metadata, phase_exact or phase_free, and the tests read it. A phase_free module may not be embedded in a controlled block without an explicit phase fix.
  2. Standalone equivalence, phase-insensitive. Compare with process fidelity F = |Tr(U†V)|²/d² (F = 1 means equal up to phase), or Qiskit's Operator.equiv, or Cirq's allclose_up_to_global_phase.
  3. Controlled embedding, phase-sensitive. Build controlled-U and controlled-V explicitly and compare exactly: Qiskit's Operator.equals, or entrywise with a tolerance. This is the test that catches a dropped phase.
  4. Phase arithmetic. Compare phases as wrapped differences, never by subtracting raw np.angle values.

Why it matters: worked example

U = T = diag(1, e^{iπ/4}); V = the π/8 gate = diag(e^{-iπ/8}, e^{iπ/8}) = e^{-iπ/8}U. Standalone: F = |Tr(U†V)|²/4 = |2e^{-iπ/8}|²/4 = 1, so they are the same operation.

Controlled (control first, basis |00⟩,|01⟩,|10⟩,|11⟩):

  • controlled-U = diag(1, 1, 1, e^{iπ/4})
  • controlled-V = diag(1, 1, e^{-iπ/8}, e^{iπ/8})

The entrywise ratio controlled-V·controlled-U† = diag(1, 1, e^{-iπ/8}, e^{-iπ/8}) is not a constant, so they are not equal up to global phase. The difference is exactly a phase gate P(-π/8) on the control qubit: a physical, measurable operation.

Python
import numpy as np                      # Python 3.11, numpy 1.26
T = np.diag([1, np.exp(1j*np.pi/4)])
V = np.diag([np.exp(-1j*np.pi/8), np.exp(1j*np.pi/8)])
I2 = np.eye(2); Z = np.zeros((2, 2), complex)
ctrl = lambda U: np.block([[I2, Z], [Z, U]])
CU, CV = ctrl(T), ctrl(V)
print(np.allclose(CU, CV))              # False
print(np.round(np.diag(CV @ CU.conj().T), 6))
# [1.+0.j, 1.+0.j, 0.92388-0.382683j, 0.92388-0.382683j]

Trade-offs

Phase-insensitive comparison is cheap and tolerant of numerical drift, but blind by construction: it passes a wrong controlled circuit. Phase-sensitive comparison catches that case but fails on legitimate float drift, so it needs an explicit tolerance. A third option, closer to hardware, conjugates by Hadamards and measures the relative phase on the control; use it as the end-to-end check, not the unit test.

Failure modes and detection

failuredetection
phase always discarded: every test uses equivadd a controlled-embedding test using equals
relative phase mistaken for global: RZ(θ) assumed equal to P(θ), but RZ(θ) = e^{-iθ/2}P(θ)compare controlled-RZ against controlled-P
controlled conversion untestedassert the controlled matrix against a hand-built diag
phase wrap: np.angle returns (-π, π], so a 2π difference reads as ~0compare abs(((a-b+π) mod 2π) - π) < tol

Tolerances

Set them explicitly: 1e-8 absolute on matrix entries for exact comparisons, 1e-6 on process fidelity. Reduce phases to (-π, π] before exponentiating: np.exp(1j*phi) with phi near 1e16 has no significant digits left.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14

Design and validate a quantum software workflow for bit ordering.

Answer

The 90-second answer

Bit ordering breaks because three orders coexist and only one is visible in the output. Qiskit indexes qubits 0..n-1 and treats qubit 0 as the least significant bit of the statevector index, but get_counts() returns bitstrings whose leftmost character is the highest-index classical bit. A 3-qubit circuit with X on qubit 0 and a full measurement returns '001', not '100'. Nothing in that string says which convention produced it, and '000' and '111' are correct under every convention, which is exactly why symmetric test states hide the bug.

My workflow: one canonical order, two conversion points, one asymmetric test.

Design

Canonical order is a tuple[int, ...] of length n where index i is logical qubit i. Everything between the SDK and the consumer speaks that. Two adapters, and only two:

Python
# Qiskit 1.x: get_counts() keys are ordered highest classical bit first.
def to_logical(key: str) -> tuple[int, ...]:
    return tuple(int(b) for b in reversed(key))

def from_logical(bits: tuple[int, ...]) -> str:
    return "".join(str(b) for b in reversed(bits))

to_logical("001") == (1, 0, 0): qubit 0 measured 1. The round trip from_logical(to_logical(k)) == k is an invariant you assert in a unit test.

Width is carried explicitly, never inferred. int("001", 2) is 1; the leading zero is gone and no later code recovers it. So the canonical type carries n alongside the bits, and every adapter asserts len(key) == n.

Validation

The test that catches everything is a single asymmetric basis state:

Python
from qiskit import QuantumCircuit, transpile
from qiskit_aer import AerSimulator

n = 3
qc = QuantumCircuit(n, n)
qc.x(0)                      # only logical qubit 0 is |1>
qc.measure(range(n), range(n))

backend = AerSimulator()
counts = backend.run(transpile(qc, backend), shots=100).result().get_counts()
assert counts == {"001": 100}, counts

Trace: X on qubit 0 gives |001> in Qiskit's little-endian statevector. Measurement writes q0->c0, q1->c1, q2->c2. The key is c2 c1 c0, so '001'. '001' is not a palindrome, so a reversed adapter yields '100' and the assert fires. Run the same circuit with X on qubit 2 and assert '100': that pins both ends.

Then re-run the identical assertion on the transpiled circuit and on hardware. transpile() attaches a TranspileLayout at circuit.layout; initial_layout maps virtual to physical qubits and final_layout records the permutation routing introduced. The counts keys are still expressed in the original classical register, so the assertion must not change. If you apply final_layout to the counts as well, you reverse twice and the key flips: the most common production miss, and it only appears once routing actually runs, i.e. on a backend with a coupling map, not on a fully connected simulator.

Trade-offs

Three credible options. (1) Normalize at the boundary, as above: one place to be wrong, works across SDKs, costs a copy per result. (2) Keep provider order end to end and document it: zero conversion code, but every consumer must know the convention, and it breaks the moment a second SDK or a classical service enters. (3) Convert to int immediately: convenient for arithmetic, but you must carry n separately or you lose leading zeros. Pick (1) when more than one SDK or more than one consumer is in play; (2) is fine for a single-SDK notebook that never leaves the page. Cirq sidesteps the string entirely by making qubits objects and returning arrays indexed by the qubit list you passed; Braket defines its own string order. Pin either with the same asymmetric test rather than trusting recall.

Failure modes and detection

  • Double reversal: adapter applied on both read and write. Symptom: key is the exact reverse of expected. Detected by the asymmetric assert.
  • Leading zero lost: int(key) then re-rendered. Symptom: key length < n. Detected by len(key) == n.
  • Multiple classical registers: Qiskit concatenates by classical bit index, highest first, so the last-created register's bits are leftmost. Symptom: correct length, halves swapped. Detected by a two-register variant of the asymmetric test.
  • Histogram keys as integers: sorted(counts) and sorted(counts, key=int) disagree, and '01' and '1' collide. Keep keys as zero-padded strings.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Design and validate a quantum software workflow for custom gates.

Answer

I'd start by clarifying the target: which SDK and hardware, and whether the custom gate is defined as a unitary matrix or as a subcircuit. I'll assume Qiskit 1.0 and an IBM Eagle processor with basis gates {ecr, rz, sx, x}. The workflow has four stages: define, validate the definition, map to the target, and validate the mapped circuit.

Define. Store the gate as a versioned artifact. In Qiskit, use UnitaryGate for a matrix, or a Gate subclass with a definition circuit. Pin the SDK version (e.g., qiskit==1.0.2) and keep the definition in version control. Name it uniquely, e.g., my_lib.my_gate.v1, to avoid collisions.

Validate the definition. Check unitarity: U @ U.conj().T ≈ I. For a parameterized gate, test known parameter values (e.g., angle=0 gives identity). If the gate is defined as a circuit, compare its operator to the intended unitary using Operator.equiv with rtol=1e-8, atol=1e-8. This catches parameter convention errors (radians vs turns) and global phase issues if you also compare controlled versions.

Map to the target. Use transpile with the target's basis_gates and optimization_level=3. Qiskit will synthesize the unitary into the basis. If the gate is already native, skip synthesis. For parameterized gates, bind parameters before transpiling.

Validate the mapped circuit. Compare the original and transpiled operators up to global phase: Operator(qc).equiv(Operator(transpiled), rtol=1e-8, atol=1e-8). For larger circuits, use process fidelity or randomized benchmarking. Check ancilla cleanup: if synthesis uses ancillas, simulate with Statevector and verify ancillas are |0> and unentangled. Check resource overhead: gate count and depth.

Here's a worked example. A custom two-qubit unitary (a SWAP gate) is defined and transpiled to Eagle basis.

Python
from qiskit import QuantumCircuit, transpile
from qiskit.circuit.library import UnitaryGate
from qiskit.quantum_info import Operator
import numpy as np

U = np.array([[1,0,0,0],[0,0,1,0],[0,1,0,0],[0,0,0,1]], dtype=complex)
custom = UnitaryGate(U, label="my_swap")
qc = QuantumCircuit(2)
qc.append(custom, [0,1])
transpiled = transpile(qc, basis_gates=['ecr','rz','sx','x'], optimization_level=3)
assert Operator(qc).equiv(Operator(transpiled), rtol=1e-8, atol=1e-8)
print(transpiled.count_ops())

The trace: original unitary is a permutation. Transpiled circuit uses 3 ECR gates and several single-qubit rotations. Operator equivalence holds to 1e-8. Gate count: 3 ECR, plus single-qubit gates; depth increases from 1 to roughly 15. If the two-qubit gate error is 1e-3, the added error is roughly 3e-3, which may be acceptable.

Trade-offs. Alternatives: use a native gate if the target supports it (e.g., if the custom gate is already in the basis, no synthesis). Or use a different synthesis method (e.g., Qiskit's UnitaryGate.definition vs transpile). Deciding criterion: required fidelity vs circuit depth overhead. When not to use: if the gate is not unitary (e.g., measurement-based), or if synthesis produces >10x gate count compared to a native decomposition.

Failure modes.

  • Name collision: two gates with same name but different definitions. Detection: unit tests comparing operator equivalence for all gates in a library. Cost: silent wrong results.
  • Parameter convention mismatch: e.g., angle in radians vs turns. Detection: test with known parameters (angle=0 gives identity). Cost: wrong unitary.
  • Ancilla not cleaned: leftover entanglement. Detection: simulate with Statevector and check ancilla qubits are |0> and unentangled. Cost: incorrect results, decoherence.
  • Global phase: if the gate is used in a controlled context, global phase matters. Detection: compare controlled versions. Cost: wrong relative phase.
  • Target basis mismatch: transpiler may not support the gate. Detection: check transpiled circuit's basis gates. Cost: compilation failure or unexpected depth.
  • Approximation error hidden: synthesis approximates, but error not reported. Detection: compute process fidelity between original and transpiled. Cost: accumulated error. Set a threshold: process fidelity > 0.9999 or operator norm difference < 1e-6. For NISQ, aim for approximation error < 1e-5 if two-qubit gate error is 1e-3.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

Design and validate a quantum software workflow for parameters.

Answer

What I'd say first. "Parameters" here means the symbolic angles in a parameterized circuit (Parameter/ParameterVector in Qiskit, or the tensor arguments of a QNode in PennyLane) that get bound to numbers before execution. I'll assume Qiskit 1.x for the symbolic layer, one backend, and a sweep of ~10³ points, since that is what decides the design. The workflow is three stages: define symbolically, bind numerically, validate by differential test. Evaluate the same circuit two independent ways and compare. The symbolic layer is where the bugs live, because it fails silently.

1. Define. Build with ParameterVector, then freeze the canonical order once.

Python
# Qiskit 1.x
import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit import ParameterVector
from qiskit.quantum_info import Statevector

theta = ParameterVector("theta", 2)
qc = QuantumCircuit(1)
qc.rx(theta[0], 0)
qc.rz(theta[1], 0)

params = list(qc.parameters)   # canonical order; never rebuild it from names

2. Bind. Bind by Parameter object, not by name, and assert the circuit is fully bound.

Python
values = np.array([0.3, 0.7], dtype=np.float64)
bound = qc.assign_parameters(dict(zip(params, values)))
assert len(bound.parameters) == 0        # partial bind fails here, not at the backend

For a sweep, don't loop: SamplerV2.run([(qc, np.array([[0.1, 0.2], [0.3, 0.4]]))]) submits one job with an (N, 2) array. Transpile the parameterized circuit once and bind after; the alternative, bind then transpile, costs N transpiles and only wins if a pass can fold the now-numeric angles.

3. Validate. Two checks, both cheap:

  • Differential: build the same circuit with literal floats and compare statevectors. np.allclose(Statevector(bound).data, Statevector(ref).data, atol=1e-12).
  • Expression: evaluate each ParameterExpression at ~5 random points against a NumPy/sympy reference. Qiskit simplifies as it builds (x - x collapses to 0), so compare values, not expr == p.

Failure modes and how each is caught.

failuremechanismdetection
same-name collisiontwo Parameter("theta") are distinct objects; a name-keyed dict binds one and leaves the other symboliclen(bound.parameters) == 0 fails
degrees vs radiansrx/qml.RX take radians; a degrees value is off by 180/π ≈ 57.3golden test: rx(π/2) on |0⟩ gives P(1) = 0.5; passing 90 gives ≈ 0.72
float downcastnp.float32(0.1) - 0.1 = 1.49e-9; 20 layers compound it past a 1e-8 toleranceassert values.dtype == np.float64 before bind
partial binda dict missing a key leaves that parameter symbolicsame len(bound.parameters) == 0 assert
wrong simplificationthe expression tree rewrites as it builds5-point numeric comparison to a reference
list ordera positional list binds in circuit.parameters order, not gate-append orderbind by dict, or assert list(qc.parameters) == params

Alternatives. Qiskit's symbolic layer lets you build once and bind many times, and lets the transpiler optimize once, but its expression tree supports only a restricted set of operations, so an unsupported operation raises rather than evaluating. PennyLane binds numbers at QNode call time and gives you gradients (parameter-shift, backprop) but no symbolic tree, so the "unrepresentable expression" class of bug does not exist there. Pick Qiskit for large fixed-circuit sweeps, PennyLane when you need qml.grad. If the sweep is a single point, skip the symbolic layer and build the numeric circuit.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Design and validate a quantum software workflow for native serialization.

Answer

What a strong candidate says in the first two minutes

"Native serialization" means the framework's own binary format, for Qiskit that is QPY, as opposed to interchange text like OpenQASM 3 or QIR. I'd use it on the hot path inside one service, and never as the only copy of anything that has to outlive the framework version that wrote it.

Assumptions I'd state before designing: Qiskit 1.x on both writer and reader, Python 3.11, the payload is circuits plus their calibrations and parameter bindings, artifacts live in object storage, and the reader is a worker that also accepts uploads from users. That last point is what makes this a security question as much as a format question: a loader is a parser fed untrusted bytes.

The workflow

  1. Write path. Serialize with QPY, hash the bytes, and store a manifest next to the blob: QPY version, Qiskit version, SHA-256, byte length, manifest schema version. The manifest is the index; the blob is opaque.
  2. Read path. Verify the checksum before parsing, reject blobs over a size cap, then parse in a worker with no network and no credentials.
  3. Boundary rule. Anything crossing to another SDK, or archived past the framework's support window, is exported to OpenQASM 3 or QIR at write time and stored alongside the QPY blob.
Python
# Qiskit 1.2, Python 3.11
import hashlib, io, qiskit
from qiskit import QuantumCircuit, qpy

def save(circuit: QuantumCircuit, path: str) -> dict:
    buf = io.BytesIO()
    qpy.dump(circuit, buf)              # native QPY, not pickle
    blob = buf.getvalue()
    open(path, "wb").write(blob)
    return {"path": path, "bytes": len(blob),
            "sha256": hashlib.sha256(blob).hexdigest(),
            "qiskit": qiskit.__version__}

def load(path: str, manifest: dict) -> QuantumCircuit:
    blob = open(path, "rb").read()
    if hashlib.sha256(blob).hexdigest() != manifest["sha256"]:
        raise ValueError("checksum mismatch")   # never reaches the parser
    return qpy.load(io.BytesIO(blob))[0]        # load returns a list

Trace: save writes the blob, then hashes the same bytes it wrote, so the manifest can only describe what is on disk. load reads, hashes, compares, and only then calls qpy.load. A corrupted byte fails at the comparison; a file written by a newer QPY than the installed Qiskit supports fails inside qpy.load with an error naming the unsupported version: an explicit failure, not a silent misparse.

Choosing the format

formatkeepslosesuse for
QPY (native)custom gates, calibrations, control flow, parameter expressionsanything outside Qiskithot path, same-version service to service
OpenQASM 3gates, parameters, most control flowcalibrations; some instructions make the exporter raise QASM3ExporterErrortool boundaries, human review
QIRLLVM-level IR for compiler toolchainsQiskit-specific objectshanding off to a non-Qiskit compiler
pickleeverything, including class identityversion stability; unpickling untrusted bytes executes arbitrary codenever on the artifact path

Validation

A golden corpus of roughly 200 circuits: parameterized, custom gates, if_else control flow, classical registers, delays, calibrations: round-trips in CI; small ones are compared by unitary, large ones by circuit equality plus counts. A version matrix writes with 1.0 and reads with 1.2 and 2.0. A fuzzer mutates bytes and asserts the loader raises rather than hangs or allocates without bound. A nightly canary loads the oldest artifact in the archive.

Failure modes and how they surface

  • Newer file, older reader. Loader raises on the version; alert on that error string, and keep one reader service on the newest Qiskit.
  • Custom gate class not importable in the worker. The loader must reconstruct the class by qualified name, so a gate defined in a notebook round-trips in-process and fails in the worker. Detection: the corpus includes a gate defined in an installed package, and CI asserts the reader image imports it.
  • Pickle sneaking onto the artifact path. Someone calls pickle.dump(circuit). Detection: a lint rule plus a loader that rejects the \x80 pickle opcode prefix before parsing.
  • Manifest schema drift. Old readers cannot parse a new manifest. Version the manifest and ignore unknown fields.
  • Archive rot. A QPY file becomes unreadable once its version leaves the support window. Detection: the nightly canary; mitigation: re-encode the archive to the current QPY version on a schedule, or fall back to the stored OpenQASM 3.

Trade-off

Native fidelity buys you calibrations, custom gates and exact parameter expressions; it costs you portability and couples the artifact to a framework version. If the artifact must be read by a non-Qiskit tool or survive a decade, native is the wrong primary format: export at write time and treat QPY as a cache.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Design and validate a quantum software workflow for OpenQASM intent.

Answer

Core answer (first 90 seconds). "Intent" is the semantics the OpenQASM source declares: which gates act on which qubits, the timing directives, the classical control flow, and the measurements. The workflow's job is to prove the executed program preserves that intent, not merely that it parses. Assume OpenQASM 3.0 with stdgates.inc, a Qiskit 1.x front end (qiskit.qasm3), and a named target backend. Five stages: (1) pin the language version and the feature subset you accept; (2) parse to an AST and keep it. The AST is the intent record; (3) lower to the IR (QuantumCircuit); (4) diff the IR against the AST-derived intent; (5) execute and compare against a reference simulation. Stages 1–4 are cheap and catch silent loss; stage 5 catches what only shows up at runtime.

The failure that motivates the whole design is a parser that accepts a construct and drops it. OpenQASM 3 implementations support subsets of the language, so acceptance is not preservation. The checks that matter:

constructhow intent is lostdetectionconsequence
delay[100ns] q[1];importer accepts, drops the instruction"delay" not in qc.count_ops() or qc.duration is Noneschedule wrong; results shift on calibrated hardware
gate name collides with stdgates.inclater definition silently winshash each gate body, compare to sourcewrong unitary, no error raised
if (c==1) x q[0];condition dropped, gate applied unconditionallyinstruction.operation.condition is Nonewrong branch, wrong distribution
include "stdgates.inc";file not found, parser substitutes or errorsresolve includes against a pinned, checksummed file setnondeterministic builds
angle literal 1.5707963267948966parsed as float32round-trip the literal, compare bit patterns~1e-7 rad error: below gate error, but breaks exact unitary tests
Python
# Qiskit 1.1, Python 3.11
from qiskit import qasm3
from qiskit.qasm3 import QASM3ImporterError

src = """OPENQASM 3.0;
include "stdgates.inc";
qubit[2] q; bit[2] c;
h q[0];
delay[100ns] q[1];
c[0] = measure q[0];"""

try:
    qc = qasm3.loads(src)
except QASM3ImporterError as e:
    print("rejected:", e)          # intent preserved by refusal
else:
    ops = qc.count_ops()
    assert "delay" in ops, f"timing dropped: {ops}"
    assert qc.duration is not None, "duration lost"

If the pinned importer does not implement delay, loads raises QASM3ImporterError and the workflow records a rejection: that is intent preserved by refusal. If it accepts the program, the assertions are the check: a missing delay in count_ops() or a None duration means the timing intent was silently dropped.

Trade-offs. Structural diff (gate counts, qubit mapping, conditions) is O(gates) and catches everything in the table. Unitary comparison against a reference is decisive for semantic changes structural diff misses, but the matrix is 2^n × 2^n: practical to about 12–15 qubits, so use it only on the sub-circuits that carry custom gates. Round-tripping (export then re-import) tests the exporter too, but conflates two bugs; prefer AST-to-IR diff and keep round-trip as a separate regression. Validate intent on a simulator, where noise cannot masquerade as intent loss; use hardware only to confirm calibration.

Failure modes beyond the table. Measurement bit ordering: OpenQASM indexes c[0] to the first declared bit, Qiskit's classical register is little-endian. Check qc.cregs mapping explicitly. Qubit index remapping during transpilation: compare the pre- and post-transpile layout so a permutation is not read as a gate change. Both are detected by asserting on the IR, not by eyeballing a histogram.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Design and validate a quantum software workflow for QIR role.

Answer

What I'd say first. QIR is LLVM IR with quantum conventions layered on: opaque %Qubit and %Result types, __quantum__qis__* intrinsics for gates and measurement, and __quantum__rt__* functions for allocation, release, and result recording. A workflow is four stages (emit, validate, lower, execute) and the profile is the contract tying them together. I pick the profile from the target first: Base Profile is straight-line circuits with statically known qubits and terminal measurement; Adaptive Profile adds mid-circuit measurement, classical control flow, and dynamic allocation. Choose wrong and the module validates fine, then the target rejects it at load.

Design.

  1. Emit. From Q# via the QDK compiler, or programmatically with pyqir. The emitter stamps a module flag qir_profiles = base_profile or adaptive_profile, and the entry point carries requiredQubits / requiredResults attributes.
  2. Validate statically. Parse with pyqir, then check: the module flag matches the target's supported profile; only profile-legal intrinsics appear (no __quantum__rt__qubit_allocate in Base Profile); every __quantum__qis__* symbol is in the runtime's declared set; the LLVM verifier passes.
  3. Lower. Run LLVM optimization passes, then target lowering to the device gate set. Re-validate the lowered module: lowering is where profile violations usually appear.
  4. Execute and check. Run on qir-runner for semantics, or on the target; compare against a reference simulator on golden vectors.

Snippet (Adaptive Profile, Bell pair):

LLVM
%Qubit = type opaque
%Result = type opaque
declare void @__quantum__qis__h__body(%Qubit*)
declare void @__quantum__qis__cnot__body(%Qubit*, %Qubit*)
declare %Result* @__quantum__qis__mz__body(%Qubit*, %Result*)
declare %Qubit* @__quantum__rt__qubit_allocate()
declare void @__quantum__rt__qubit_release(%Qubit*)
declare void @__quantum__rt__result_record_output(%Result*, i8*)

define void @Bell() #0 {
  %q0 = call %Qubit* @__quantum__rt__qubit_allocate()
  %q1 = call %Qubit* @__quantum__rt__qubit_allocate()
  call void @__quantum__qis__h__body(%Qubit* %q0)
  call void @__quantum__qis__cnot__body(%Qubit* %q0, %Qubit* %q1)
  %r0 = call %Result* @__quantum__qis__mz__body(%Qubit* %q0, %Result* null)
  %r1 = call %Result* @__quantum__qis__mz__body(%Qubit* %q1, %Result* null)
  call void @__quantum__rt__result_record_output(%Result* %r0, i8* null)
  call void @__quantum__rt__result_record_output(%Result* %r1, i8* null)
  call void @__quantum__rt__qubit_release(%Qubit* %q0)
  call void @__quantum__rt__qubit_release(%Qubit* %q1)
  ret void
}
attributes #0 = { "requiredQubits"="2" "requiredResults"="2" }
!llvm.module.flags = !{!0}
!0 = !{i32 1, !"qir_profiles", !"adaptive_profile"}

Trace: the validator reads the module flag, sees adaptive_profile, and permits the two qubit_allocate calls. It checks requiredQubits=2 against the two allocations. It resolves h, cnot, mz, result_record_output against the runtime. Any of those failing is a load-time reject, not a runtime surprise.

Failure modes and detection.

  • LLVM version mismatch: producer emits IR for a newer LLVM than the consumer's verifier accepts → parse/verify error at load. Pin the LLVM version in CI and run the verifier on every emitted module.
  • Unsupported profile: module flag says adaptive_profile, target supports only base_profile → reject at load. Detect with the profile check in step 2.
  • Opaque runtime call: a __quantum__qis__* symbol the runtime doesn't implement → link error or abort. Detect by diffing the module's declared intrinsics against the runtime's symbol table.
  • Endianness: result-record integer encoding differs between little- and big-endian hosts → wrong decoded results. Detect with golden vectors run on both.
  • Stale debug metadata: !dbg references to inlined-away values fail the LLVM verifier. Detect with -verify-each during lowering.

Trade-off. Base Profile is cheaper to validate and maps to hardware with no classical feed-forward; Adaptive Profile buys mid-circuit measurement and control at the cost of a runtime that must support dynamic allocation and a target that can do conditional gates. If the target can't do feed-forward, don't emit Adaptive: you'll validate fine and fail at load.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Design and validate a quantum software workflow for semantic round trips.

Answer

Let me clarify the goal: a semantic round trip means exporting a quantum circuit to an interchange format and importing it back, then proving the imported circuit has the same action on states and classical registers as the original. I'll assume the source and sink are Qiskit 1.0, the interchange format is OpenQASM 3.0, and we have a second independent parser (e.g., pytket's QASM parser) to use as an oracle.

The workflow has three parts. First, a feature-complete test suite. Second, a semantic oracle that compares circuits without relying on text or shallow shape. Third, a validation harness that runs the oracle and reports the first differing operation.

For the test suite, I generate circuits that exercise: parameterized gates (e.g., RZ(theta) with theta as a Parameter), global phase (set via QuantumCircuit.global_phase), relative phase (e.g., controlled-Z), custom gates (defined as a subcircuit and exported as a gate definition), measurements, conditions (if (c==1) X), reset, and asymmetric order (X then Z vs Z then X). Each circuit is small enough to compute its unitary or simulate exactly.

The semantic oracle depends on the circuit type. For pure quantum circuits (no measurement, condition, or reset), I compare unitaries up to global phase using Qiskit's Operator.equiv, which defaults to rtol=1e-5, atol=1e-8. For circuits with classical control flow, I simulate both the original and the round-tripped circuit on a fixed set of input states (e.g., all computational basis states for small qubit counts) with a fixed seed, and compare the resulting statevectors and classical registers. I use a different parser for the oracle than the one under test to avoid correlated bugs.

Text equality is too strict because whitespace, gate naming, and parameter formatting differ. Shallow shape equality is too weak because the same gate count can hide different parameters or order. Unitary equivalence up to global phase is the right semantic check for pure circuits.

Here's the key trap: global phase is invisible to a standalone unitary comparison because Operator.equiv ignores it. To catch global phase loss, I wrap the circuit in a controlled operation. For example:

Python
from qiskit import QuantumCircuit, qasm3
from qiskit.quantum_info import Operator
import numpy as np

qc = QuantumCircuit(1)
qc.rz(np.pi/2, 0)
qc.global_phase = np.pi/4

qasm_str = qasm3.dumps(qc)
qc_rt = qasm3.loads(qasm_str)

print(Operator(qc).equiv(Operator(qc_rt)))  # True even if global phase lost
qc_ctrl = qc.control(1)
qc_rt_ctrl = qc_rt.control(1)
print(Operator(qc_ctrl).equiv(Operator(qc_rt_ctrl)))  # False if global phase lost

If the exporter drops the global phase, the controlled comparison returns False because the relative phase between the |10> and |11> states changes.

Trade-offs: exact unitary comparison with tolerance 1e-8 is right for exact round trips. If the target format uses approximate synthesis, I relax to 1e-6 and document that. Using an independent parser as oracle costs extra setup but catches bugs where the same parser is both exporter and importer. When the target format cannot represent a feature, the round trip must fail explicitly, not silently drop it.

Failure modes and detection:

  • Unsupported feature dropped: check that the gate set and qubit count match before and after; if a gate is missing, fail.
  • Same parser as oracle: use a second parser (e.g., pytket) to import the QASM and compare.
  • Approximate tolerance loose: tighten tolerance until failures appear; if they do, the round trip is not exact.
  • Measurement ignored: compare classical registers after simulation; if they differ, fail.
  • Metadata mistaken for semantics: strip gate names, register names, and diagram layout before comparison.

A table of checks:

This workflow validates semantic round trips by construction: it tests the features that matter, uses an independent oracle, and catches the specific failure modes that production review must cover.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Design and validate a quantum software workflow for semantic custody.

Answer

Clarify first. "Semantic custody" isn't a standard term, so I'd pin it down before designing anything: it's the property that the meaning of the source program (the unitary it specifies, up to a stated equivalence class) survives every transformation, and that each transformation leaves an artifact making the claim checkable after the fact. Assumptions I'd state up front: gate-model superconducting target, Qiskit 1.x with qiskit-ibm-runtime, circuits up to ~20 qubits, no mid-circuit feedforward in v1.

The workflow: five stages, each gated by a check.

stageartifact writtencheck that gates the next stage
ingestsource SHA-256, declared semantics (observable set, equivalence class), Qiskit + QPY versionsource parses; declared semantics present
capabilitybackend.target snapshot + timestamp, required-gate diffevery required op ∈ target.operation_names
transformISA circuit, QPY dump, pass list, initial/final layout, seed_transpilerOperator.from_circuit(isa).equiv(ref) within ε
validateequivalence report, depth and two-qubit count vs budgetboth pass
executejob ID, raw counts, calibration snapshot, executed-circuit hashhash matches the validated ISA circuit

The load-bearing check is unitary equivalence, and it has a hard size limit. After transpiling, compare the reference circuit against the ISA circuit with Operator.from_circuit, which uses the layout the transpiler attached to map physical qubits back to logical ones:

Python
# Qiskit 1.x
from qiskit.quantum_info import Operator
ref = Operator(qc.remove_final_measurements(inplace=False))
got = Operator.from_circuit(isa.remove_final_measurements(inplace=False))
assert ref.equiv(got, rtol=1e-8), "semantic drift"

Dense Operator costs 16·4ⁿ bytes: 16.8 MB at 10 qubits, 268 MB at 12, 4.3 GB at 14. So this check is real to 12 qubits and dead at 14. Past that, switch to Clifford/stabilizer simulation (Aer's method="stabilizer" scales to thousands of qubits for Clifford circuits) or sample K random input states, simulate the ideal classically, and compare output distributions. For circuits with mid-circuit measurement, unitary equivalence doesn't apply at all: compare the classical control-flow graph instead.

Trade-offs. Fail-closed is right for unsupported gates and for layout, but wrong for approximate synthesis: snapping rz angles to a discrete grid is a bounded error you want to accept, so the policy is "exact within a recorded ε", not "exact". Two cases where silent degradation is defensible: optimization level 3 dropping a barrier (semantics preserved, unless the barrier was there for crosstalk, so mark it preserve), and noise-adaptive layout remapping logical to physical qubits (unitary preserved, noise profile changed, so the layout belongs in the artifact, not just the log).

Failure modes and how each is caught.

  • Silent fallback: a gate the target lacks gets left in and rejected at submit. Detect by asserting set(isa.count_ops()) ⊆ set(backend.target.operation_names) before submission.
  • Bit reversal: Qiskit writes bitstrings with the leftmost character as the highest-index classical bit. Prepare qc.x(0); qc.measure_all() on 2 qubits: correct output is {'01': 1024}, not {'10': 1024}. Run this as a canary on every new provider.
  • Parameter drift: hash the bound parameter dict at calibration and at execution; a mismatch means the circuit you validated isn't the circuit you ran.
  • Unsupported control: QIR's base profile has no if, so a circuit with if_else compiles but fails at the target. Check the target's control-flow ops explicitly.
  • Result coercion: Sampler v1 returns a QuasiDistribution that can carry negative or >1 values; coercing it to a probability dict silently drops that. Assert the return type and that probabilities sum to 1 within tolerance.
  • Version loss: QPY written by a newer Qiskit won't load in an older one. Pin the Qiskit version in the artifact and refuse to load a newer QPY format.
  • Blind retry: resubmitting a job that already reached RUNNING doubles shots and biases the estimate. Retry only submission-time failures (429, connection reset), never a job that started.

Validation is re-running the check on the executed circuit. Store the ISA circuit's hash with the job ID and the calibration snapshot; if the hash of what the backend reports differs, the result is void regardless of how good the counts look.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Design and validate a quantum software workflow for statevector simulation.

Answer

What I'd say first

Before picking anything I'd pin three things: the circuit class (Clifford-only, or with T gates), the qubit count, and what the simulation is for. A correctness oracle for a small circuit, or a stand-in for hardware. Those decide the method, and the method decides whether the workflow is feasible at all.

For a general circuit up to roughly 30 qubits I'd use a statevector simulator: Qiskit Aer's AerSimulator(method="statevector") or Cirq's cirq.Simulator(). I'd treat it as an oracle only for cases I can bound, and above that I'd switch method rather than buy RAM.

Why the bound sits where it does

A statevector is 2^n complex amplitudes. At complex128 that's 16 bytes each, so memory is 2^(n+4) bytes:

qubitsamplitudesstatevector (complex128)density matrix
201.05 × 10^616 MiB16 TiB
253.36 × 10^7512 MiB16 PiB
301.07 × 10^916 GiB16 EiB
341.72 × 10^10256 GiB—

Every gate touches all 2^n amplitudes, so a g-gate circuit is O(g·2^n) time and memory bandwidth is the real bottleneck: one single-qubit gate on 30 qubits streams 16 GiB. Aer's precision="single" halves the footprint at the cost of accuracy; its GPU device option moves that streaming to HBM.

Choosing the method

  • Clifford-only circuits: stabilizer simulation, polynomial in qubit count, exact. Aer method="stabilizer", Cirq CliffordSimulator. It cannot handle T gates.
  • Shallow, low-entanglement circuits: matrix product state, Aer method="matrix_product_state". Cost tracks the bond dimension χ, which tracks entanglement; a deep circuit with volume-law entanglement is worse than statevector.
  • Noise: density matrix, 4^n entries. 16 TiB at 20 qubits. Only for tiny circuits.

The validation workflow

  1. Bit order. Prepare |1⟩ on qubit 0 with an X gate and read the nonzero index. Qiskit is little-endian, so the index is 1; Cirq's final_state is big-endian over its qubit order, so it is 2^(n-1). Cross-tool comparison needs an explicit reversal.
  2. Global phase. Statevectors are equal up to a global phase, so compare fidelity |⟨ψ|φ⟩|², never elementwise.
  3. Measurement. Compare probabilities |a_i|², or sample N shots and check the empirical distribution against exact with a standard error of √(p(1−p)/N). Asserting that a single shot equals an amplitude is the classic wrong test.
  4. Independent oracle. For Clifford circuits, cross-check statevector against stabilizer. For n ≤ 12, cross-check against a dense matrix multiply of the full unitary.

Failure modes and how I'd catch them

  • Memory blowup: compute 2^(n+4) before launching, not after the OOM.
  • Collapse misread: reading the statevector after a measurement instruction gives the collapsed branch; use save_statevector before the measurement.
  • Shared compiler bug: if both simulators run the same transpiler, agreement proves nothing. Route one path through a different toolchain.
  • Hardware comparison: hardware can only validate coarse statistics, never exact amplitudes. Noise and shot counts dominate.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Design and validate a quantum software workflow for noise simulators.

Answer

Clarify, then assume. The workflow depends on what the simulator is for. I'll assume a superconducting transmon device, a circuit-level noise model built from daily calibration (per-qubit T1/T2, √X/X/CZ error, readout P(1|0) and P(0|1)), and a goal of predicting the outcome distribution of a benchmark circuit, a QEC memory experiment or an RB-style circuit, well enough to rank hardware or tune a decoder. If the goal is decoder training data instead, the validation target becomes logical error rate per round, and the pipeline below is unchanged except at the gate.

Core answer: five stages, each with a gate.

  1. Ingest calibration → noise model. Pull the latest calibration snapshot, timestamp it, and build the model. In Qiskit Aer: NoiseModel.from_backend(backend), or explicit depolarizing_error / thermal_relaxation_error composition. Store the calibration timestamp and a hash of the model in the result metadata: that timestamp is the thing that goes stale.
  2. Pick the method by size and structure. This is the design decision; the table below is the rule.
  3. Run with fixed seeds. Every stochastic method takes a seed. Trajectory results reproduce only if seed, shot count, and noise-model hash are all recorded.
  4. Validate on held-out circuits. Circuits that were not used to fit any parameter.
  5. Gate. Accept only if the predicted distribution matches hardware within the shot-count error bar.

Method selection: the scaling that decides it.

methodstate sizememorypractical nwhen
statevector2^n amplitudes16·2^n B~30 (16 GiB)noiseless reference, or the base for trajectories
density matrix4^n entries16·4^n B~10–12exact noise, small circuits, coherent errors
trajectory (statevector + sampled noise)2^n per shot16·2^n B~30, cost × shotsstochastic Pauli noise, many qubits
stabilizer (Stim)O(n) per shottinythousands of qubitsClifford-only circuits, QEC sampling
MPS / tensor network (Aer, Cirq+qsim)bond dim χO(n·χ²)depends on entanglementlow-entanglement, 1D circuits

Arithmetic: complex128 is 16 bytes. A density matrix at n=10 is 16·4^10 = 16 MiB; at n=15 it is 16 GiB; at n=20 it is 16 TiB, off the table. Statevector at n=30 is 16 GiB. So density-matrix buys exactness at roughly five fewer qubits than statevector. Trajectory cost is N shots with statistical error on a probability of about 1/√N: 1% needs N ≈ 10^4, 0.1% needs N ≈ 10^6. That is the trade: trajectory is cheap in memory, expensive in shots.

Python
from qiskit_aer.noise import NoiseModel
from qiskit_aer import AerSimulator

nm  = NoiseModel.from_backend(backend)   # snapshot at calibration time
sim = AerSimulator(method="density_matrix", noise_model=nm)
res = sim.run(circ, shots=10_000, seed_simulator=1234).result()

Validation protocol. Fit the noise model on day-D calibration, then validate on a disjoint set of circuits: different qubit pairs, different depths. Compare predicted against measured outcome distributions with a chi-square or total-variation test at the shot count's error bar. Preserve seeds and the noise-model hash so a rerun reproduces bit-for-bit.

Failure modes and how each is detected.

  • Stale calibration: model built from a snapshot older than the hardware run. Detect by asserting the calibration timestamp is within a fixed window of the run and logging both.
  • Independent-error assumption: single-qubit depolarizing applied where hardware has correlated CZ errors. Detect by comparing predicted against measured two-qubit correlators; the gap grows with depth.
  • Readout double-applied: readout error added in the noise model and again by measurement mitigation. Detect by checking the mitigation flag; predicted P(1) drifts by exactly the readout error.
  • Leakage projected away: transmon leakage to |2⟩ truncated to a qubit. Detect by predicted error saturating below measured at high depth.
  • Fit/test reuse: the same circuits tuned and validated. Detect by holding out by circuit family, not by shot.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Design and validate a quantum software workflow for dynamic control.

Answer

Assumptions. Superconducting transmon backend with mid-circuit measurement and feed-forward (IBM Eagle r3 / Heron class), Qiskit 1.x as the SDK, OpenQASM 3 as the interchange. On trapped-ion or neutral-atom targets the same pipeline holds but the support matrix is different, so read it from the target rather than assuming.

Core answer. Build the workflow as four layers and validate each layer against the one below it, never trusting the layer above.

  1. Source: Qiskit's if_test, while_loop, for_loop and switch context managers, or OpenQASM 3 if/while/for.
  2. IR: Qiskit's ControlFlowOp subclasses (IfElseOp, WhileLoopOp, ForLoopOp, SwitchCaseOp). These keep each branch as a nested circuit instead of flattening it, which is what makes the next layer possible.
  3. Transpile: target-aware, driven by BackendV2.target, so an op the device cannot run fails at compile time instead of at job submission.
  4. Execute: runtime primitives; the feed-forward itself happens on the control electronics, not in the program.

Validation runs at three fidelities and asserts on correlations, not marginals. A dropped conditional leaves the marginal distribution of the final qubit unchanged in half the cases, so a marginal test passes while the circuit is broken.

Worked trace. q0: H, measure → c0. q1: if c0==1, X. q2: if c0==0, X. Measure q1→c1, q2→c2.

  • Ideal: c1 = c0, c2 = 1−c0. So P(c1=1) = 0.5 and c1⊕c2 = 1 always.
  • Condition dropped (no X ever fires): c1 = c2 = 0. P(c1=1) = 0, c1⊕c2 = 0.
  • Stale bit (c0 read before the measurement, defaults to 0): c1 = 0, c2 = 1. P(c1=1) = 0, c1⊕c2 = 1.

Three distinct signatures from one circuit. At 4096 shots the standard error on a 0.5 probability is √(0.25/4096) ≈ 0.0078, so a 3σ band is ±0.023; a total-variation-distance gate of 0.05 sits at roughly 6σ and will not fire on noise alone.

Trade-offs.

decisionoption Aoption Bdeciding criterion
loop boundunroll at compile time (ForLoopOp with a classical constant)native while_loopIs the bound known classically? Unrolling lets the transpiler optimise across iterations and needs no backend support; a measurement-dependent bound forces native control flow.
simulationStim (Clifford, polynomial)Aer statevector (exact, 2ⁿ)Any non-Clifford gate? Then Stim is out and you pay 2ⁿ.
feed-forwardhardware conditionalpost-select on measurement outcomesk mid-circuit measurements means post-selection keeps 2⁻ᵏ of shots: k=10 keeps 1 in 1024.

Failure modes and how each is caught.

failuresymptomdetection
condition droppedconditional never fires; P(c1=1)=0count_ops() before and after transpile must still list if_else; then the correlation test above
branch explosionop count grows ~2ⁿ with nested switchplot op count against nesting depth; a straight line on a log axis is the tell
stale bitconditional reads a clbit measured later, or neverwalk circuit.dag(): the Measure node writing that clbit must precede the IfElseOp node
unsupported looptranspile error, or job rejected at submissiontarget.instruction_supported("while_loop") before you build the pass manager
latency dominatesconditional error climbs as the gap between measurement and if growssweep identity delays between the two and fit error against delay; the slope is the effective bit lifetime

Stim's rec[-1] targets give you the same feedback semantics in a stabiliser simulator, but its REPEAT block is compile-time only: it will not catch a runtime-loop bug, so keep Aer in the loop for anything with a measurement-dependent bound.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Design and validate a quantum software workflow for PennyLane QNode.

Answer

Core answer

Clarify three things before writing any QNode: which device (simulator or hardware), which autodiff interface (autograd/torch/jax), and whether shots are analytic (shots=None) or sampled. Those three decide the gradient method, and the gradient method decides whether your training loop is exact or approximate.

Design: never leave diff_method at its default "best". Pin it explicitly. On default.qubit with shots=None, "best" resolves to backprop; add shots=1000 and it silently falls back to parameter-shift. Pin the device, the plugin version, and the interface, then assert the resolved method at construction.

Validate: expand the tape, count trainable params, and check the gradient against a finite-difference reference.

Worked trace (PennyLane 0.39, autograd interface)

Python
import pennylane as qml
import numpy as np

dev = qml.device("default.qubit", wires=2, shots=None)

@qml.qnode(dev, diff_method="parameter-shift", interface="autograd")
def circuit(x, y):
    qml.RX(x, wires=0)
    qml.CNOT(wires=[0, 1])
    qml.RY(y, wires=1)
    return qml.expval(qml.PauliZ(1))

x = np.array(0.3, requires_grad=True)
y = np.array(0.7, requires_grad=True)

The circuit evaluates to cos(x)cos(y) = 0.7307 at (0.3, 0.7). Parameter-shift runs four circuits (x±π/2 at fixed y, then y±π/2 at fixed x) and combines each pair as (f(+π/2) − f(−π/2))/2. That returns exactly [−0.2260, −0.6154], matching the analytic −sin(x)cos(y), −cos(x)sin(y). Finite-diff with h=1e-5 agrees to ~4 decimals but is approximate; parameter-shift is exact for RX/RY because their generators have eigenvalues ±1/2.

Inspect before trusting the method:

Python
tape = qml.workflow.construct_tape(circuit)(x, y)
print(tape.trainable_params)   # [0, 1]
print(circuit.diff_method)     # 'parameter-shift'

Trade-offs

methodgradient costexacthardwareconstraint
backprop1 fwd + 1 bwdyesnoshots=None, simulator
parameter-shift2 circuits/paramyesyes2p executions
finite-diff2 circuits/paramnoyesstep-size error
adjoint~1 fwd + 1 bwdyesnoreversible, no mid-circuit measure

Pick backprop for simulator training loops: cheapest and exact. Pick parameter-shift when the target is hardware or you need shots. Use adjoint only for large state-vector sims with reversible circuits.

Failure modes

  • Auto-selected method changes: "best" flips from backprop to parameter-shift the moment shots become finite. Detect by asserting circuit.diff_method after construction, not before.
  • Backprop on hardware: hardware devices don't expose the state vector, so backprop is impossible; construction raises. Detect at QNode build time, not at the first optimizer step.
  • Trainable-param detection: non-differentiable args (data) are excluded from tape.trainable_params, so the gradient vector shrinks. Detect by comparing len(tape.trainable_params) to the params you expect to update.
  • Shots semantics: shots=None is analytic; finite shots add sampling noise to every gradient estimate. Detect by running the same gradient twice and checking variance.
  • Plugin incompatibility: a third-party device may not implement the method you pinned (adjoint needs no mid-circuit measurement). Detect by constructing the QNode against the real plugin, not a mock.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Design and validate a quantum software workflow for gradient portability.

Answer

Portability here means one thing: the same training loop produces the same gradient whether it runs on a statevector simulator or a shot-based QPU. Assume a variational circuit with P trainable rotation parameters, an expectation-value objective, and two targets: default.qubit and a remote QPU. The core answer: portability is a property of the gradient contract, not the code. Pin the differentiation method per device, validate the gradient numerically against a high-precision reference, and count cost in circuit executions. Let the framework pick the method silently and you get finite differences on hardware without ever noticing.

Design: four stages

  1. Declare the circuit once, parameterised, and keep the diff method as a policy keyed by device: never a literal inside the QNode.
  2. Resolve the method at construction and assert it. qnode.diff_method must equal the policy entry; this is what catches a "best"-style resolution quietly landing on finite differences.
  3. Gradient contract test on the simulator: analytic gradient versus central finite difference at ε = 1e-6, tolerance 1e-6.
  4. Resource accounting: record the transformed circuits and count executions, because that is what the QPU bills you for.
Python
import pennylane as qml
from pennylane import numpy as pnp

DIFF_POLICY = {
    "default.qubit":   "backprop",        # exact, one backward pass
    "lightning.qubit": "adjoint",         # exact, statevector resident
    "qiskit.remote":   "parameter-shift", # exact, 2 executions per parameter
}

def circuit(params):
    for w, p in enumerate(params):
        qml.RY(p, wires=w)
    qml.CNOT(wires=[0, 1])
    return qml.expval(qml.PauliZ(0))

def build(dev):
    method = DIFF_POLICY[dev.name]
    qnode = qml.QNode(circuit, dev, diff_method=method)
    assert qnode.diff_method == method, f"silent fallback to {qnode.diff_method}"
    return qnode

params = pnp.array([0.3, -1.1, 0.7, 2.0], requires_grad=True)
sim = build(qml.device("default.qubit", wires=4))
g = qml.grad(sim)(params)                       # analytic
e = pnp.eye(4)
ref = pnp.array([(sim(params + 1e-6*e[i]) - sim(params - 1e-6*e[i])) / 2e-6
                 for i in range(4)])
assert pnp.allclose(g, ref, atol=1e-6)

What each method costs

methodruns onexactexecutions per gradientstate memory
backpropstatevector simyes1 fwd + 1 bwdO(2^n)
adjointstatevector simyes1 fwd + 1 bwdO(2^n)
parameter-shiftsim + QPUyes2P (Pauli rotations)O(1)
finite-diffsim + QPUno, O(ε²) bias2PO(1)
SPSAsim + QPUstochastic2 per stepO(1)

Validate against shot noise, not against zero

P = 4, shots = 4096. Each ⟨Z⟩ estimate has variance ≤ 1/4096 ≈ 2.4e-4, std ≈ 0.016. The parameter-shift gradient (f₊ − f₋)/2 has variance σ²/2 ≈ 1.2e-4, std ≈ 0.011. Central finite difference at ε = 0.01 has variance σ²/(2ε²) ≈ 1.2, std ≈ 1.1: a hundred times worse, and still biased by O(ε²) = 1e-4. So the hardware validation tolerance is 3σ ≈ 0.033: a hardware gradient outside that band is a bug, not shot noise.

Trade-offs and failure modes

Choose backprop or adjoint when the statevector fits in memory and P is large: cost is independent of P. Choose parameter-shift on hardware or when the state is too big: exact, but 2P executions. Choose SPSA when P is in the thousands and a noisy direction is acceptable. Never ship finite differences as a production gradient.

  • Silent method downgrade. diff_method="best" resolves to finite-diff on a QPU. Detect by asserting the resolved method at construction.
  • Hidden gradient work. A classical head detached from the quantum gradient. Detect by comparing the loss gradient norm against a finite-difference probe of the whole model.
  • Unsupported higher order. Backprop gives a Hessian free on the simulator; on hardware you need param_shift_hessian at O(P²) executions. Detect by running the Hessian check on the simulator, then counting executions on hardware.
  • Shot covariance ignored. Reusing one set of shots across Pauli terms in a Hamiltonian correlates the gradient components, so summing variances overstates the error. Detect by comparing the empirical gradient covariance over repeated runs to the diagonal-only estimate.
  • Interface dtype cast. JAX defaults to float32 unless jax_enable_x64 is set, so a float64 parameter truncates silently. Detect by asserting the parameter dtype at the QNode boundary.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Design and validate a quantum software workflow for Braket task.

Answer

What I'd say first

Three assumptions before designing anything: one AWS account in one region, circuits submitted from Python with amazon-braket-sdk, and results read back from S3 rather than held in memory. The constraint that shapes the whole design is that CreateQuantumTask is asynchronous and takes no client token you can replay: the SDK object you get back is not a durable record. Your own store has to be the source of truth for what was submitted, what it cost, and whether it finished.

The workflow

Submit → persist → poll → fetch → validate → attribute cost. The submit step writes the dedupe key and the task record in the same call path, because a crash between them is exactly how you get billed twice.

Python
import boto3, hashlib, time
from braket.aws import AwsDevice

REGION = "us-west-1"
braket = boto3.client("braket", region_name=REGION)
ddb = boto3.resource("dynamodb", region_name=REGION).Table("braket_tasks")

def submit(circuit, device_arn, s3_prefix, shots=1000, tags=None):
    assert device_arn.split(":")[3] == REGION, "device region != client region"
    key = hashlib.sha256(
        (str(circuit) + device_arn + str(shots)).encode()).hexdigest()
    if (prev := ddb.get_item(Key={"dedupe_key": key}).get("Item")):
        return prev["task_arn"]
    task = AwsDevice(device_arn).run(
        circuit, s3_location=s3_prefix, shots=shots, tags=tags or {})
    ddb.put_item(Item={
        "dedupe_key": key, "task_arn": task.arn, "device_arn": device_arn,
        "shots": shots, "action_schema": "braket.ir.jaqcd.program/1",
        "output_s3": f"{s3_prefix}/{task.id}", "status": "CREATED",
        "cost_tags": tags or {}})
    return task.arn

def wait(arn, sla_s=900):
    deadline = time.time() + sla_s
    while time.time() < deadline:
        t = braket.get_quantum_task(quantumTaskArn=arn)
        if t["status"] in ("COMPLETED", "FAILED", "CANCELLED"):
            return t
        time.sleep(5)
    braket.cancel_quantum_task(quantumTaskArn=arn)
    raise TimeoutError(arn)

The ARN is arn:aws:braket:<region>:<account>:quantum-task/<uuid>: the region is embedded, which is why the assert can be a one-liner. On COMPLETED, read results.json from the task's output prefix; on FAILED, read failureReason and never touch S3. Tags become cost allocation tags in Cost Explorer once activated, which is the only way to attribute spend per experiment.

Simulator or QPU

criterionSV1 (state vector)QPU
qubit ceiling34device-specific, roughly 20–36
noisenonereal; needs mitigation
billingper minute of wall clockper task plus per shot
latencysecondsqueue of minutes to hours
use it foralgorithm correctness, regression testsnoise characterisation, final validation

Deciding rule: if the question is "is my circuit right", the simulator answers it for free and deterministically. If the question is "does this hardware give me the distribution I need", only the QPU answers it, and you pay per shot for the privilege, so you tune on SV1 and spend QPU shots on the final run. DM1 (17 qubits) is the one to reach for when you need noise modelled rather than absent.

Failure modes and how you catch them

failuredetection
duplicate submitno idempotency token on the API; dedupe on (circuit, device, shots) before submit, and reconcile task count against your table nightly
region mismatchdevice ARN region vs client region, asserted at startup; surfaces as a validation error at submit otherwise
S3 permissionstask reaches COMPLETED but the read 403s; the task role needs s3:PutObject on the output prefix and your reader needs s3:GetObject: prove it with a 1-shot task in CI
stuck QUEUEDpoll GetQuantumTask; alert when QUEUED exceeds your SLA, then CancelQuantumTask
partial resultstatus FAILED with failureReason set and no results.json; treat FAILED as terminal
credentials loggedgrep logs for X-Amz-Security-Token; never enable boto3 debug logging in the submit path

Validating the workflow itself

Run a Bell circuit, 1000 shots, on SV1. measurementCounts must have keys only in {"00", "11"}. Each count is Binomial(1000, 0.5), so σ = √(1000·0.25) ≈ 15.8 and a 3σ band is 500 ± 47. Assert 453 ≤ n ≤ 547. A key of "01" or "10" means the CNOT or the qubit mapping is wrong: that is the check that catches a mis-wired circuit before it reaches a QPU.

Then kill the submit process after CreateQuantumTask returns but before the DynamoDB write, and re-run it. You get two ARNs and two bills. That is the concrete demonstration of why the dedupe key exists, and it is the test I would put in CI.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Design and validate a quantum software workflow for device capability.

Answer

Assumptions, then the answer. IBM Quantum hardware, Qiskit 1.2 with qiskit-ibm-runtime 0.30, one pinned instance, a circuit you will run repeatedly. The workflow is five steps: resolve the backend, snapshot its capability, compile against that snapshot, validate the compiled circuit against the same snapshot, and submit the validated object with the snapshot's fingerprint recorded against the job id.

A backend name is not a contract. ibm_brisbane is a 127-qubit Eagle device today; its calibration changes daily and the name can be retired. The executable contract is BackendV2.target: the supported operations, which qubits each acts on, and per-qubit duration and error. Everything downstream reads the snapshot, never the name.

Python
# Qiskit 1.2, qiskit-ibm-runtime 0.30
import hashlib, json
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit.quantum_info import Operator
from qiskit_ibm_runtime import QiskitRuntimeService, SamplerV2

service = QiskitRuntimeService()
backend = service.backend("ibm_brisbane", instance="my-instance")  # pin the instance
assert backend.status().operational

target = backend.target
snapshot = {
    "name": backend.name,
    "num_qubits": backend.num_qubits,
    "ops": sorted(target.operation_names),
    "edges": sorted(target.build_coupling_map().get_edges()),
    "dt": backend.dt,
}
fingerprint = hashlib.sha256(
    json.dumps(snapshot, sort_keys=True, default=str).encode()).hexdigest()[:16]

pm = generate_preset_pass_manager(backend=backend, optimization_level=3,
                                  seed_transpiler=42)
isa = pm.run(circuit)          # ISA: target ops on target qubits only

# validate the exact object you will submit
assert set(isa.count_ops()) <= set(target.operation_names) | {"barrier"}
ref = circuit.remove_final_measurements(inplace=False)
assert Operator.from_circuit(isa.remove_final_measurements(inplace=False)).equiv(
    Operator(ref), rtol=1e-8)

job = SamplerV2(mode=backend).run([(isa,)], shots=4096)
job_store[job.job_id()] = fingerprint   # bind the capability doc to the artifact

Validation. Two checks, both on the exact object you submit. ISA compliance: every op in isa.count_ops() must appear in target.operation_names, plus barrier, which the transpiler may leave behind. Semantic equivalence: strip measurements from both circuits and compare unitaries with Operator.from_circuit, which maps the transpiled circuit back through its layout to the original qubit ordering; equiv compares up to global phase, which is what you want, since the hardware does not preserve it. If either assert fires you have a compile bug, not a hardware problem.

Failure modes and how you catch them.

failuredetection
stale snapshotre-fetch backend.target and compare the fingerprint before submit; a 1-hour TTL suffices because calibration is daily, and inside a Session the device does not change
wrong instance or regionpin instance= at service.backend(...), then assert job.backend().name == snapshot["name"] after submission
retired deviceservice.backends(operational=True, simulator=False) before resolving; backend.status().operational is the cheap pre-check
shot capSamplerV2 defaults to 1024 shots per PUB; the provider documents a per-PUB maximum, and the runtime rejects an over-cap PUB at submission, not at compile time
verbatim feature assumedthe transpiler will not decompose an AnnotatedOperation, so confirm the annotated op is in target.operation_names or the job fails at submission
recompile after validationhash the ISA circuit and submit that object; any pass running after the assert means the validated circuit is not the executed one

Trade-offs. Caching the snapshot costs one API call per TTL and buys a stable compile target; skipping it costs a failed job, or worse, results you attribute to the algorithm. Pinning a backend buys reproducibility across runs; service.least_busy(operational=True, simulator=False) buys queue time and gives up comparability. optimization_level=3 spends compile time to cut two-qubit depth, which dominates error on a 127-qubit device: drop to 1 only for a tight inner loop where compile time is the bottleneck. A Session reserves the device across iterations and removes re-queueing between them, at the cost of holding hardware you may not be using.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Design and validate a quantum software workflow for result normalization.

Answer

What I'd say first (60–120s). Assume Qiskit 1.x primitives: SamplerV2 returns a PrimitiveResult of PubResults whose .data is a DataBin holding a BitArray; EstimatorV2 returns evs and stds; Aer's sampler and M3-style mitigation return quasi-probabilities that can be negative. The workflow is five steps: keep the raw result immutable, tag it by kind, normalize each kind into one canonical shape with its own invariants, validate those invariants, then emit the normalized view alongside provenance. The tag is the whole point: counts, quasi-probabilities, expectations and statevectors have different invariants, so collapsing them into one "probability dict" is a lie for at least three of them.

Steps. (1) Ingest: store the raw PrimitiveResult (or its serialization) with a content hash; never mutate it. (2) Classify: dispatch on kind, not on shape. (3) Normalize: each variant exposes to_normalized(). (4) Validate: assert the kind's invariants. (5) Emit: normalized view + provenance record (backend, shots, mitigation method, transpile seed).

Python
from dataclasses import dataclass
from typing import Union, Mapping
import numpy as np

@dataclass(frozen=True)
class Counts:
    counts: Mapping[str, int]; shots: int; provenance: dict

@dataclass(frozen=True)
class Quasi:
    probs: Mapping[str, float]; provenance: dict

@dataclass(frozen=True)
class Expectation:
    evs: np.ndarray; stds: np.ndarray; provenance: dict

Result = Union[Counts, Quasi, Expectation]

def normalize(r: Result) -> dict:
    if isinstance(r, Counts):
        total = sum(r.counts.values())
        assert total == r.shots, f"counts sum {total} != shots {r.shots}"
        return {"kind": "distribution",
                "probs": {k: v / r.shots for k, v in r.counts.items()},
                "shots": r.shots, "provenance": r.provenance}
    if isinstance(r, Quasi):
        s = sum(r.probs.values())
        assert abs(s - 1.0) < 1e-6, f"quasi sums to {s}"
        return {"kind": "distribution", "probs": dict(r.probs), "shots": None,
                "negativity": sum(-v for v in r.probs.values() if v < 0),
                "provenance": r.provenance}
    if isinstance(r, Expectation):
        return {"kind": "expectation", "evs": r.evs, "stds": r.stds,
                "provenance": r.provenance}
    raise TypeError(r)

Trace. normalize(Counts({'00': 2048, '11': 2048}, shots=4096, provenance={})) → total 4096 equals shots, returns probs={'00': 0.5, '11': 0.5}, shots=4096. normalize(Quasi({'00': 0.90, '01': 0.06, '10': 0.06, '11': -0.02}, provenance={})) → sum is 1.00, passes, returns shots=None and negativity=0.02. normalize(Expectation(evs=[0.87], stds=[0.02], provenance={})) → returns kind='expectation' and no shots key at all: that missing key is the structural guard against casting an expectation to a count.

Why clipping biases the estimate. Take the quasi above. Clipping negatives to zero gives {0.90, 0.06, 0.06, 0}, which sums to 1.02; renormalizing yields P(00)=0.882. The mitigated estimate was 0.90, so silent clipping moves the headline number by 1.8 percentage points and hides the 0.02 negative mass that was the mitigation's own uncertainty signal. Keep the negatives, report negativity, and let the consumer decide.

Trade-off: eager vs lazy normalization. Eager (normalize at the runner) gives one canonical shape, validates once, and makes downstream code uniform, but it discards kind-specific fields and pays conversion cost for results nobody reads. Lazy (normalize at the consumer) preserves fidelity and costs nothing unused, but every consumer re-implements the conversion and they drift. Decide on consumer count and whether raw is retained anyway: with three or more consumers and raw already stored, normalize eagerly; with one consumer or a one-off analysis, stay lazy. It is not worth a tagged union when the raw object is already the interface: inside a single Qiskit script, PubResult.data is fine.

kindsourceinvariantnever do
countsBitArray.get_counts()sum == shotstreat as probabilities without dividing
quasiAer sampler / M3sum ≈ 1, may be negativeclip then renormalize silently
expectationEstimatorV2 evs/stds|evs| ≤ 1 per Pauli termmultiply by shots to get counts
statevectorStatevector / Aernorm == 1, complexcast to float or JSON without real+imag

Failure modes to detect. Counts summing above shots means a merge double-counted: assert on ingest. A shots field appearing on an expectation means someone cast it: reject at the schema. A statevector round-tripped through JSON losing its imaginary part shows up as a norm below 1: check the norm after deserialization. Dropped mitigation metadata is invisible until you cannot reproduce a number, so hash the provenance into the normalized record. Set default_shots explicitly on SamplerV2 rather than relying on the fallback, so the shots invariant is checkable.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21

Design and validate a quantum software workflow for job idempotency.

Answer

Core answer (first 90 seconds). Assume the provider bills per task or per QPU-second, that a submit can time out after the provider has already accepted the work, and that the client can crash between the HTTP call and writing the response. Then idempotency is not a retry policy: it is a durable record of intent plus a reconciliation step that runs before any resubmit.

Concretely: derive a client-side idempotency key from the canonical job spec, write an INTENT row keyed by it, submit, then persist the provider's job ID onto that row. Every retry path reads the row first. If the row has a job ID, poll it. If it has none, query the provider for a job carrying the key as a tag before submitting again. Only a confirmed absence justifies a second submit.

What the key is computed over. Canonical JSON (sorted keys, no whitespace) of: provider, backend name, shots, the circuit in a stable serialization (QASM 3 or the provider's IR), transpiler optimization level and seed, and parameter bindings. SHA-256 it.

Python
import hashlib, json

def key(spec: dict) -> str:
    blob = json.dumps(spec, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(blob.encode()).hexdigest()

Same spec gives the same key; changing shots or the seed gives a new one, which is correct because it is a different job. Add a schema-version field so a change to the canonicalization cannot silently collide with keys already in the store.

Provider-side idempotency, where it exists. Amazon Braket's CreateQuantumTask takes a jobToken; replaying a request with the same token returns the original task instead of creating a second one. Use it when available: it closes the submit/persist race entirely. IBM Quantum's Qiskit Runtime primitives do not accept a client-supplied idempotency token; the service returns a job ID and you must persist it yourself, so the INTENT row is the only protection in that window.

Reconciliation. States: INTENT → SUBMITTED → RUNNING → TERMINAL (DONE | ERROR | CANCELLED). An orphan is an INTENT row with no job ID older than the submit deadline. Distinguish it from a completed job by querying the provider by tag; if the provider cannot search by tag, you cannot prove absence, so escalate to a human rather than resubmit. Guard against status regression with a monotonic state: once TERMINAL, ignore a later RUNNING report from a lagging list API.

Trace of the timeout-after-accept case:

t (s)clientproviderstore row K
0.0write INTENT—INTENT
0.1POST submitaccepts, job JINTENT
0.9read timeoutJ queuedINTENT
1.0retry: read K—INTENT, no job id
1.1query by tag Kreturns JSUBMITTED J
1.2poll JDONETERMINAL

Trade-offs. Three credible designs: (1) at-least-once submit with dedupe downstream (simplest, but you pay for duplicates; (2) provider idempotency token) exactly-once submit, only where the API offers it; (3) client-side key plus reconciliation. Works everywhere, but leaves the submit/persist race. Pick (2) when the provider has it and QPU time is billed per task; pick (3) otherwise. Do not build any of this for a one-off exploratory session where a duplicate costs cents and the state store is more operational surface than the waste it prevents.

Failure modes and detection. Duplicate QPU cost: count distinct provider job IDs per key, alert on more than one. Orphan: INTENT rows older than the deadline. Concurrent retry: two workers on one key. Take a lease with a conditional write and alert on lease contention. Eventual consistency: get-job reports DONE while list-jobs still reports RUNNING. Trust the point read.

Validation. Fault-inject the two windows: kill the process after the provider accepts but before the row is updated, then replay the request and assert exactly one provider job exists. Follow with a soak test at an injected timeout rate.

Hypothetical arithmetic: 2,000 jobs/day, 15 s of QPU each, 4% timeout-after-accept. Naive resubmit duplicates 80 jobs, about 1,200 s/day of paid QPU time, roughly 20 minutes, for zero extra results.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Design and validate a quantum software workflow for credentials.

Answer

Assumptions. Eight engineers, hybrid variational workloads, Amazon Braket for QPU access, results landing in S3, nightly CI plus laptops. On IBM instead, the only structural change is that the credential is a long-lived API key rather than an IAM role: everything below still applies, and the local account file becomes your top leak vector.

The workflow, four layers.

  1. Identity. No long-lived keys. CI authenticates with GitHub OIDC, and the role's trust policy is the whole control:
JSON
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": {"Federated": "arn:aws:iam::123456789012:oidc-provider/token.actions.githubusercontent.com"},
    "Action": "sts:AssumeRoleWithWebIdentity",
    "Condition": {
      "StringEquals": {"token.actions.githubusercontent.com:aud": "sts.amazonaws.com"},
      "StringLike":   {"token.actions.githubusercontent.com:sub": "repo:org/repo:ref:refs/heads/main"}
    }
  }]
}

sub is the load-bearing condition. Drop it and any repository on GitHub can assume the role. Laptops use IAM Identity Center SSO. STS defaults to 3600 s; set DurationSeconds: 900 for CI.

  1. Task role. Braket assumes a role you pass at submission to write results, so its trust policy must allow braket.amazonaws.com to assume it. Scope the permissions to one prefix:
JSON
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Action": "s3:PutObject",
    "Resource": "arn:aws:s3:::amazon-braket-us-east-1-123456789012/tasks/*"
  }]
}

No GetObject, no s3:*, no "*".

  1. Results bucket. Block Public Access on, SSE-KMS, bucket policy denying aws:SecureTransport: false, 30-day lifecycle expiry.

  2. Egress and logs. Build hosts sit in a subnet with no internet gateway; provider endpoints go through a proxy with an explicit allowlist. Logs are structured JSON and pass a redactor that drops any key matching (?i)(token|api[_-]?key|secret|authorization) before emit.

Validating it. A design without a test is a claim.

Trace: the OIDC exchange. The runner mints a JWT and trades it for a session:

$ curl -sH "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \
    "$ACTIONS_ID_TOKEN_REQUEST_URL&audience=sts.amazonaws.com" | jq -r .value > oidc.jwt

# middle segment of oidc.jwt, base64url-decoded:
{ "aud": "sts.amazonaws.com",
  "sub": "repo:org/repo:ref:refs/heads/main",
  "ref": "refs/heads/main",
  "iat": 1730000000, "exp": 1730000300 }

$ aws sts assume-role-with-web-identity \
    --role-arn arn:aws:iam::123456789012:role/braket-ci \
    --role-session-name GitHubActions \
    --web-identity-token file://oidc.jwt \
    --duration-seconds 900
{ "Credentials": { "Expiration": "2024-10-27T03:48:20Z", ... } }

GitHub controls the JWT lifetime, so don't build logic on the exact value. The session you get back is what CI actually uses, and it dies 900 s after the call.

Negative IAM test. Submit a task with a role that can be assumed but lacks s3:PutObject. Braket accepts the task and it lands FAILED with an S3 access-denied reason when it writes results; a ValidationException at submission means Braket rejected the role up front. Either is a pass. A task that reaches COMPLETED means your scoping is decorative.

Canary credential. Commit a notebook with a fake IBM Cloud API key in an output cell. CI's gitleaks run must fail. Run it weekly: a scanner that silently stopped matching is worse than none.

Rotation drill. Revoke the CI role mid-run by attaching a deny-all inline policy; STS sessions aren't individually revocable, but the deny applies to live sessions on the next authorization call. In-flight tasks finish server-side under the task role. The next submission fails AccessDenied; if you instead let the 900 s session lapse, it's ExpiredToken. Time from revoke to green build is your rotation MTTR.

Egress test. From the build subnet, curl a non-allowlisted host. Expect a timeout, not a 200.

Failure modes.

  • Secrets in task parameters. Braket persists task parameters and they're readable through the API. Pass a DB password as a hybrid-job parameter and it's stored. Scan task parameters for high-entropy strings.
  • Overly broad S3. s3:* on * is what people reach for. Catch it with IAM Access Analyzer and aws iam simulate-principal-policy in CI.
  • Local config archived. The Qiskit account file is plaintext JSON and gets swept into laptop backups and Docker build contexts. Exclude it in .dockerignore and the backup policy, and scan backups for it.
  • Exception dumps. A traceback printing request headers leaks Authorization: Bearer .... Unit-test the log scrubber against a fixture traceback containing a fake bearer token.

Trade-offs. OIDC removes the long-lived key but makes your build depend on GitHub's OIDC provider; keep a break-glass role. A proxy allowlist covers every provider with one rule but adds a hop and a single point of failure; per-provider VPC endpoints avoid that where the service supports them. Fifteen-minute sessions shrink blast radius but break any local script that polls a job longer than that: Braket polls server-side so it's fine, a hand-rolled poller isn't.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Design and validate a quantum software workflow for version pinning.

Answer

Assumptions up front: a Qiskit + IBM-style stack (qiskit, qiskit-ibm-runtime, qiskit-aer), Python 3.11. The structure transfers to Cirq/cirq-google or PennyLane; only the package names change.

Core answer (first 90 seconds)

Pin everything that changes the circuit or the numbers, and record everything you can't pin. That's three layers:

  1. Environment: exact package versions plus hashes.
  2. Compilation contract: transpiler version, seed, optimization level, and the target's basis gates and coupling map.
  3. Execution context: backend name, calibration snapshot, shots, provider API version.

A lockfile freezes layer 1 only. Layers 2 and 3 live on the provider's machine and move under you, so you record them and re-validate on a cadence instead of pretending they're pinned. The rule: pin software, record hardware, re-baseline on a schedule.

The workflow

1. Lock the environment. pip-compile --generate-hashes (pip-tools) or uv lock writes exact versions with SHA-256 hashes. Pin qiskit==1.2.4, not qiskit>=1.2. Install with pip install --require-hashes -r requirements.txt so a drifted or tampered wheel fails at install, not mid-experiment.

qiskit==1.2.4 \
    --hash=sha256:9f2c... \
qiskit-ibm-runtime==0.29.0 \
    --hash=sha256:41ab...

2. Freeze the compilation contract. Transpilation is not deterministic across versions: transpile(circuit, backend, optimization_level=3, seed_transpiler=42) can yield a different circuit when the pass manager changes. Record the seed, the optimization level, and the backend's basis_gates and coupling_map at compile time. Serialize the transpiled circuit to OpenQASM 3 (or QIR) and commit it, so the artifact you ran is the artifact you can re-run.

3. Record the execution context. Backend name, calibration timestamp, shots, and provider API version go in a manifest beside the lockfile. IBM publishes per-qubit T1/T2 and gate/readout errors that change every calibration cycle; a job submitted today runs on today's calibration, not the one you benchmarked against.

Validation gates

  • Install gate: hash mismatch fails CI.
  • Golden-circuit gate: run a fixed 4-qubit GHZ circuit, compare the measured distribution to a stored baseline with a statistical tolerance (worked example: total variation distance < 0.05 at 4096 shots). Catches silent default changes and transpiler drift.
  • Round-trip gate: serialize → deserialize → assert circuit equality. Catches serializer incompatibility.
  • Canary job: submit one small job to the real backend before the batch; a BackendNotFound stops the run.

Trade-offs

Strict pinning buys reproducibility and costs transpiler improvements and calibration freshness. Don't pin when you're probing hardware capability, or when a backend is being retired and you must migrate anyway. Re-baseline monthly or on any provider SDK minor release.

Failure modes and detection

failurehow it shows updetection
transitive plugin driftqiskit-aer bumps a numpy boundhash mismatch at install
deprecated API removedQiskit 1.0 (Feb 2024) removed qiskit.execute()ImportError in CI
target retiredIBM retired the ibmq_* systemsBackendNotFound on submit
serializer incompatibilityOpenQASM 2 can't express mid-circuit measurementround-trip test fails
silent default changeshots or optimization level default shiftsgolden-circuit TVD exceeds tolerance

Curated: · Written: · Reviewed:

Difficulty: Medium