Lesson 38: IBM Qiskit II: Transpilation, Noise and Real Hardware¶
38.1 Learning Outcomes¶
By the end of this hour a student will be able to:
- Transpile circuits for a target backend and interpret depth and gate counts.
- Read a coupling map and understand the cost of routing.
- Build noise models (depolarising, thermal relaxation, readout error).
- Apply error-mitigation techniques: readout correction, zero-noise extrapolation, dynamical decoupling.
- Submit jobs to real IBM Quantum hardware and interpret the results.
38.2 Transpilation in Qiskit¶
Basic usage¶
from qiskit import QuantumCircuit, transpile
from qiskit_ibm_runtime.fake_provider import FakeManilaV2
backend = FakeManilaV2() # 5-qubit simulated device with real calibration data
qc = QuantumCircuit(3)
qc.h(0); qc.cx(0, 1); qc.cx(0, 2)
for level in range(4):
tqc = transpile(qc, backend, optimization_level=level)
print(f"level {level}: depth={tqc.depth():3d} "
f"CX={tqc.count_ops().get('cx', 0):3d} total={sum(tqc.count_ops().values()):3d}")
Typical output.
level 0: depth= 15 CX= 4 total= 19
level 1: depth= 13 CX= 4 total= 17
level 2: depth= 13 CX= 4 total= 17
level 3: depth= 11 CX= 2 total= 13
Level 3 halved the CNOT count. On hardware where CNOT error is \(\sim10^{-2}\) and single-qubit error \(\sim10^{-4}\), that is the difference between a usable and an unusable result.
Coupling maps¶
print(backend.coupling_map)
# [[0,1],[1,0],[1,2],[2,1],[2,3],[3,2],[3,4],[4,3]]
FakeManila is a line: 0 — 1 — 2 — 3 — 4. A CNOT between qubits 0 and 4 requires 3 SWAPs (9
CNOTs) plus the target CNOT.
Topology comparison across vendors.
| Device family | Topology | Avg degree | SWAP overhead |
|---|---|---|---|
| IBM Falcon/Eagle | heavy-hex | ~2.5 | high |
| IBM Heron | heavy-hex + tunable couplers | ~2.5 | high |
| Google Sycamore | 2-D grid | 4 | medium |
| IonQ / Quantinuum | all-to-all | \(n-1\) | zero |
| Rigetti | octagonal lattice | ~3 | medium |
Trapped-ion machines have far slower gates (µs–ms versus ns) but all-to-all connectivity. For circuits with long-range interactions — chemistry, QAOA on dense graphs — they frequently beat superconducting devices despite the speed disadvantage, because they avoid the SWAP explosion.
Inspecting the transpiled circuit¶
tqc = transpile(qc, backend, optimization_level=3, seed_transpiler=42)
print("depth :", tqc.depth())
print("size :", tqc.size()) # total gate count
print("ops :", tqc.count_ops())
print("layout :", tqc.layout.initial_layout) # logical -> physical mapping
print("basis gates:", backend.operation_names)
Always set seed_transpiler — routing uses a stochastic algorithm (SABRE), so results vary
between runs. Reproducibility requires the seed.
38.3 Noise Models¶
The three dominant error channels¶
(a) Depolarising error. With probability \(p\), replace the state with the maximally mixed state:
(b) Thermal relaxation (\(T_1\), \(T_2\)).
| Parameter | Meaning | Typical (superconducting) |
|---|---|---|
| \(T_1\) | amplitude damping: \(\lvert 1\rangle\to\lvert 0\rangle\) | 100–300 µs |
| \(T_2\) | dephasing: loss of phase coherence | 100–200 µs |
| \(t_{\text{gate}}\) | single-qubit gate time | ~35 ns |
| \(t_{\text{CX}}\) | two-qubit gate time | 200–500 ns |
Constraint: \(T_2 \le 2T_1\) always.
(c) Readout (measurement) error. \(\Pr[\text{read }1\mid\text{state }0]\) and vice versa, typically \(1\)–\(5\%\) — often the largest single error source, and also the easiest to correct.
Building a custom noise model¶
from qiskit_aer import AerSimulator
from qiskit_aer.noise import (NoiseModel, depolarizing_error,
thermal_relaxation_error, ReadoutError)
noise = NoiseModel()
# 1-qubit depolarising
noise.add_all_qubit_quantum_error(depolarizing_error(1e-3, 1), ['sx', 'x', 'rz'])
# 2-qubit depolarising
noise.add_all_qubit_quantum_error(depolarizing_error(1e-2, 2), ['cx', 'ecr'])
# thermal relaxation (T1 = 100us, T2 = 80us, gate time 300ns)
T1, T2, tg = 100e-6, 80e-6, 300e-9
noise.add_all_qubit_quantum_error(thermal_relaxation_error(T1, T2, tg), ['cx'])
# readout error: P(1|0) = 2%, P(0|1) = 4%
noise.add_all_qubit_readout_error(ReadoutError([[0.98, 0.02],
[0.04, 0.96]]))
sim = AerSimulator(noise_model=noise)
Using a real device's noise profile¶
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime.fake_provider import FakeSherbrooke
backend = FakeSherbrooke() # 127-qubit Eagle, real calibration data
sim = AerSimulator.from_backend(backend) # noise model built automatically
This is the single most useful debugging tool in Qiskit. It reproduces the actual device's \(T_1\), \(T_2\), gate errors and readout errors, so you can predict hardware behaviour without queueing.
38.4 Error Mitigation¶
Mitigation is not correction. Error correction (L10) removes errors using redundant encoding and needs many physical qubits per logical one. Error mitigation leaves the errors in place and statistically post-processes them away — it costs extra shots, not extra qubits, which is why it is the NISQ-era tool.
Readout error mitigation (M3 / measurement calibration)¶
Measure a calibration matrix \(A\) where \(A_{ij} = \Pr[\text{read }i\mid\text{prepared }j]\), then invert:
Cheapest and most effective mitigation available — it costs \(2^{n}\) (or, with the M3 tensored approach, only \(2n\)) calibration circuits and routinely recovers several percent of accuracy.
Zero-noise extrapolation (ZNE)¶
Idea. Deliberately amplify the noise by a factor \(\lambda = 1, 2, 3, \ldots\), measure the observable at each level, and extrapolate back to \(\lambda = 0\).
Noise amplification by gate folding: replace each gate \(G\) by \(G\,G^\dagger\,G\) (which equals \(G\) ideally) to triple the noise while leaving the ideal result unchanged.
Cost: 3–5× more shots. Benefit: typically recovers 50–90 % of the noise-free value for shallow circuits.
Dynamical decoupling (DD)¶
Insert sequences of pulses (e.g. \(X\)–\(X\) or the XY4 sequence) into idle periods. The pulses average away low-frequency dephasing, echoing out the environment's slow noise.
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import ALAPScheduleAnalysis, PadDynamicalDecoupling
from qiskit.circuit.library import XGate
pm = PassManager([ALAPScheduleAnalysis(durations),
PadDynamicalDecoupling(durations, [XGate(), XGate()])])
qc_dd = pm.run(tqc)
Free in shots — it only fills idle time — and typically improves fidelity by 10–30 % on circuits with significant idling.
Using mitigation via the Runtime Estimator¶
from qiskit_ibm_runtime import QiskitRuntimeService, EstimatorV2
service = QiskitRuntimeService()
backend = service.least_busy(operational=True, simulator=False)
estimator = EstimatorV2(mode=backend)
estimator.options.resilience_level = 2 # 0=none, 1=readout(TREX), 2=ZNE
estimator.options.dynamical_decoupling.enable = True
estimator.options.default_shots = 8192
| Resilience level | Techniques | Overhead |
|---|---|---|
| 0 | none | 1× |
| 1 | readout mitigation (TREX) + twirling | ~1.5× |
| 2 | + zero-noise extrapolation | ~3–5× |
38.5 Running on Real Hardware¶
from qiskit_ibm_runtime import QiskitRuntimeService, SamplerV2
service = QiskitRuntimeService(channel="ibm_quantum", token="YOUR_TOKEN")
backend = service.least_busy(operational=True, simulator=False, min_num_qubits=5)
print("Using:", backend.name)
tqc = transpile(qc, backend, optimization_level=3)
sampler = SamplerV2(mode=backend)
job = sampler.run([tqc], shots=4096)
print("Job ID:", job.job_id()) # save it -- queues can be hours
result = job.result()
print(result[0].data.c.get_counts())
Practical checklist.
- Transpile for the specific backend — a circuit compiled for one device will not run on another.
- Save the job ID. Queue times range from minutes to hours; retrieve later with
service.job(job_id). - Check calibration data (
backend.properties()) — qubit quality varies by a factor of 5 across a chip and changes daily. - Start small. Debug on
FakeBackendfirst; hardware time is a scarce shared resource.
38.6 Solved Problems¶
Problem 1 — Transpilation cost across optimisation levels¶
A 5-qubit GHZ circuit is transpiled for a linear-topology device. Compute the expected CNOT counts and fidelities at each optimisation level, given CNOT error \(10^{-2}\).
Solution.
Logical circuit. \(H\) on \(q_0\), then CNOT(\(0,1\)), CNOT(\(0,2\)), CNOT(\(0,3\)), CNOT(\(0,4\)) — 4 CNOTs, but three of them are non-adjacent on a line.
Level 0 (naive routing). Distances from \(q_0\): 1, 2, 3, 4. CNOTs to \(q_2\): 1 SWAP + 1 CNOT = 4. To \(q_3\): 2 SWAPs + 1 = 7. To \(q_4\): 3 SWAPs + 1 = 10.
Level 3 (SABRE routing + a smarter GHZ construction). The transpiler recognises that a GHZ state can be built as a chain: CNOT(\(0,1\)), CNOT(\(1,2\)), CNOT(\(2,3\)), CNOT(\(3,4\)) — all nearest-neighbour, no SWAPs at all.
Fidelities.
Improvement: error rate falls from 19.8 % to 3.9 % — a 5× reduction.
The general lesson. GHZ has two equivalent constructions — star (all CNOTs from \(q_0\)) and chain. They are mathematically identical but differ 5.5× in cost on a line. Design your circuits for the hardware graph; do not rely on the transpiler to undo a bad choice.
(Note the chain version has depth 4 rather than depth 1 for the star's parallel CNOTs — a depth-versus-CNOT-count trade-off. On a line, CNOT count wins.)
Problem 2 — Predicting circuit fidelity¶
A transpiled circuit has 45 single-qubit gates, 28 CNOTs, and 5 measurements. Given \(\epsilon_{1q} = 3\times10^{-4}\), \(\epsilon_{2q} = 8\times10^{-3}\), \(\epsilon_{\text{ro}} = 2\times10^{-2}\), estimate the total fidelity and identify the dominant error source.
Solution.
Assuming independent errors, the total success probability is the product:
Single-qubit contribution.
Two-qubit contribution.
Readout contribution.
Total.
Error budget.
| Source | Error contribution | Share of total error |
|---|---|---|
| Single-qubit gates | 1.34 % | 4.1 % |
| Two-qubit gates | 20.1 % | 61.4 % |
| Readout | 9.6 % | 34.5 % |
| Total | 28.8 % | 100 % |
Priorities that follow directly.
- Reduce CNOT count —
optimization_level=3, better topology matching, algorithmic restructuring. Highest leverage. - Apply readout mitigation — the second-largest source, and the cheapest to fix (a calibration matrix costs \(2n\) circuits and recovers nearly all of the 9.6 %).
- Ignore single-qubit gate count — optimising it is not worth the effort at 4 %.
This error-budget analysis should precede any hardware run. It tells you whether the experiment is worth attempting at all: below \(F \approx 0.3\) the signal is generally unrecoverable.
Problem 3 — Readout error mitigation, worked¶
A 1-qubit experiment should give \(\Pr[0] = 0.7\). The device has \(\Pr[1|0] = 0.05\) and \(\Pr[0|1] = 0.08\). Compute the measured distribution, then recover the ideal one by matrix inversion.
Solution.
Calibration matrix. Column \(j\) = the distribution observed when state \(j\) was prepared:
Forward: the measured distribution.
The bias. We measure \(\Pr[0] = 0.689\) instead of \(0.700\) — an error of \(-0.011\), or 1.6 % relative.
Inverse: recovering the truth.
Perfect recovery in the noiseless-statistics limit.
Two practical caveats.
- Shot noise is amplified. \(A^{-1}\) has entries larger than 1, so statistical fluctuations in \(\vec p_{\text{meas}}\) are magnified. The amplification factor is \(\|A^{-1}\| \approx 1.15\) here; for worse readout (\(\epsilon = 20\%\)) it can exceed 2.
- Negative probabilities can appear. With shot noise, \(A^{-1}\vec p\) may contain small negative
entries. The standard fix is a constrained least-squares projection onto the probability
simplex — which is what Qiskit's M3 and
mthreeimplement.
Scaling. Full \(2^{n}\times2^{n}\) calibration is infeasible beyond ~10 qubits. M3 exploits the fact that readout errors are largely uncorrelated between qubits, using a tensor-product model that needs only \(2n\) calibration circuits and scales to hundreds of qubits.
Problem 4 — Zero-noise extrapolation by hand¶
An observable is measured at noise scale factors \(\lambda = 1, 2, 3\) giving \(\langle O\rangle\) values \(0.62\), \(0.48\), \(0.37\). Extrapolate to \(\lambda = 0\) using (a) linear and (b) quadratic fits. The exact value is \(0.80\).
Solution.
(a) Linear fit \(\langle O\rangle = a + b\lambda\) by least squares over \(\lambda = 1,2,3\).
Linear estimate: 0.740. Error from the true 0.80: \(-0.060\) (7.5 % low).
(b) Quadratic fit through all three points exactly, \(y = a + b\lambda + c\lambda^{2}\):
Subtracting consecutive equations:
Subtracting again: \(2c = 0.03 \Rightarrow c = 0.015\). Then \(b = -0.14 - 0.045 = -0.185\), and \(a = 0.62 - b - c = 0.62 + 0.185 - 0.015 = \mathbf{0.790}\).
Quadratic estimate: 0.790. Error: \(-0.010\) (1.25 % low).
Comparison.
| Method | Estimate | Error | Improvement over raw |
|---|---|---|---|
| Raw (\(\lambda=1\)) | 0.620 | \(-0.180\) | — |
| Linear ZNE | 0.740 | \(-0.060\) | 3.0× |
| Quadratic ZNE | 0.790 | \(-0.010\) | 18× |
| Exact | 0.800 | — | — |
Why quadratic did better here. The data curves — the successive drops are \(0.14\) then \(0.11\), not equal — so noise decay is closer to exponential than linear, and the quadratic captures more of that curvature.
Two cautions.
- Higher-order fits amplify shot noise. With \(n\) points and an order-\((n-1)\) polynomial the fit interpolates exactly, including the noise. In practice use more scale factors than fit parameters.
- Exponential extrapolation \(\langle O\rangle = A e^{-\Gamma\lambda} + B\) often fits better,
since depolarising noise decays multiplicatively. Qiskit's
resilience_level=2and Mitiq both offer it.
Cost. 3 scale factors means 3× the shots, plus the folded circuits are up to 3× deeper.
Problem 5 — Planning a hardware experiment end to end¶
Design a complete experiment to run a 4-qubit QAOA Max-Cut instance on IBM hardware, with all decisions justified.
Solution.
Step 1 — Define the problem. 4-vertex cycle graph \(C_4\) (edges 0-1, 1-2, 2-3, 3-0). Brute-force optimum: \(C_{\max} = 4\) (bipartite; colour alternate vertices).
Step 2 — Estimate resources.
At \(\epsilon_{\text{CX}} = 10^{-2}\): \(F \approx 0.99^{8} = 0.923\) — comfortably feasible.
Step 3 — Choose a backend.
backend = service.least_busy(operational=True, simulator=False, min_num_qubits=5)
Check backend.properties() and select the 4 physical qubits with the lowest CNOT error using
initial_layout. Prefer a device whose coupling map contains a 4-cycle (heavy-hex does not
contain 4-cycles, so one SWAP will be needed — budget for it).
Step 4 — Optimise parameters classically first. Simulate the 4-qubit circuit exactly on a laptop (\(2^4 = 16\) amplitudes) and grid-search \((\gamma,\beta)\) over \([0,\pi]\times[0,\pi/2]\). Never burn hardware time on parameter optimisation when the instance is classically simulable.
Step 5 — Transpile.
tqc = transpile(qc, backend, optimization_level=3,
initial_layout=[best_qubits], seed_transpiler=42)
print(tqc.depth(), tqc.count_ops())
Step 6 — Configure mitigation.
sampler = SamplerV2(mode=backend)
sampler.options.dynamical_decoupling.enable = True # free
sampler.options.twirling.enable_gates = True # Pauli twirling
job = sampler.run([tqc], shots=8192)
Use the Sampler, not the Estimator, because we want the bitstring distribution — the best sampled cut is the answer, and QAOA's value comes from the best sample, not the mean.
Step 7 — Post-process.
counts = job.result()[0].data.c.get_counts()
best = max(counts, key=lambda b: cut_value(b, edges))
print("best cut found:", cut_value(best, edges), "of", 4)
Also apply classical local search to the top-20 sampled bitstrings — single-bit flips often improve a near-optimal sample to the true optimum at negligible cost.
Step 8 — Report honestly.
| Metric | Value |
|---|---|
| Best cut found | 4 / 4 ✓ |
| \(\Pr[\text{optimal}]\) from sampling | ~35 % |
| \(\langle C\rangle\) (mean cut) | ~3.1 |
| Approximation ratio \(\langle C\rangle/C_{\max}\) | 0.78 |
| Simulator (noiseless) \(\langle C\rangle\) | 3.4 |
| Noise cost | 0.3 in mean cut value |
| Classical brute force | 4/4 in microseconds |
The honest conclusion to write in the report. "The 4-qubit QAOA circuit executed successfully on hardware and found the optimal cut in 35 % of shots, with a mean cut value 9 % below the noiseless simulation. This validates the implementation and quantifies the hardware noise. It does not demonstrate quantum advantage: the instance is solved exactly by classical brute force in microseconds."
38.7 Practice Problems¶
- A circuit has 60 CNOTs at \(\epsilon = 5\times10^{-3}\). Estimate the fidelity. [Ans: 0.741]
- Compute the SWAP overhead for CNOT(\(q_1,q_5\)) on a line. [Ans: 3 SWAPs = 9 CNOTs + 1]
- Invert \(A = \begin{pmatrix}0.97&0.03\\0.03&0.97\end{pmatrix}\) and mitigate \(\vec p = (0.6,0.4)\). [Ans: \((0.6064, 0.3936)\)]
- Linear ZNE on \((1,0.70),(2,0.55),(3,0.42)\): extrapolate to 0. [Ans: 0.8367]
- Why is \(T_2 \le 2T_1\)?
- Which mitigation technique costs no extra shots? [Ans: dynamical decoupling]
- Build the error budget for 100 single-qubit gates, 40 CNOTs and 3 measurements at the rates in Problem 2.
38.8 Summary¶
- Transpilation does gate translation, layout, routing and optimisation;
optimization_level=3typically halves the CNOT count. Always setseed_transpilerfor reproducibility. - Coupling maps determine SWAP cost; trapped-ion machines' all-to-all connectivity often beats faster superconducting devices on connectivity-heavy circuits.
- Noise models combine depolarising, thermal relaxation (\(T_1\), \(T_2\)) and readout errors;
AerSimulator.from_backend()reproduces a real device exactly. - Error mitigation ≠ correction: it costs shots, not qubits. Readout mitigation (cheapest, matrix inversion / M3), ZNE (3–5× shots, extrapolate noise to zero), dynamical decoupling (free — fills idle time).
- CNOTs and readout dominate the error budget; single-qubit gates are usually negligible. Compute the budget before running.
- On hardware: transpile for the specific backend, save the job ID, check calibration data, debug on
FakeBackendfirst, optimise parameters classically when the instance is simulable, and report implementation validation honestly rather than claiming advantage.
Next lesson: L39 — Google Cirq.
Practise now: unit4-platforms-lab.html → Transpiler Lab: pick a coupling map, watch SWAPs get
inserted, and see fidelity change as you vary the optimisation level and error rates.