The Quantum Engineer

46. Quantum Transpilation

46.1Hardware Topology

The transpiler's model of the machine: Target objects encoding the coupling map, native gate set with per-qubit (gate, qubits) → (error, duration) entries, timing constraints, and measurement properties. Building topology-aware intuition: draw heavy-hex for n=7,127; find its degree-2 rim; check which qubit pairs share a coupler with good ECR fidelity. Topology decides everything downstream: a circuit is "shallow" only relative to a topology. Also model the dynamics: topologies differ across vendors (lattice vs all-to-all vs reconfigurable neutral atoms), and Part XI's platform chapter explains why — the transpiler sees only the graph, but choosing which graph to buy is a strategic decision made with it.

46.2Swap Insertion

The routing workhorse, implemented honestly: given coupling graph G and a two-qubit gate on non-adjacent (a,b): compute shortest paths, choose a swap sequence minimizing (swaps so far + distance lookahead), apply swaps to the running layout, emit the gate, update the layout map. Beware the classic bugs: forgetting to permute measurements along with the layout (your histogram comes out permuted — always test with output-bit-sensitive circuits), double-swapping (SWAP = 3 CX; adjacent swaps cancel — a peephole pass catches it), and direction-fixing (some couplers are directional; CX(a,b) may need Hadamard-conjugation to CX(b,a) — 1 H on each side, free, and easily forgotten). Benchmark SABRE vs naive shortest-path: the gap is why Qiskit ships the former.

46.3Circuit Depth

Depth as the transpiler's observable: measure before/after each pass; regressions localize broken passes instantly. Depth-reducing passes worth knowing by name: gate parallelism across layers (the layered depth() model), direction-fixing fused with commutation, single-qubit gate resynthesis after routing (routed circuits accumulate串 strings of rotations on each qubit — resynthesize each string as one Euler triple), and Pauli-evolution reordering for chemistry-style circuits (commuting-Pauli blocks can execute in any intra-block order — schedule greedily by topology). Report depth and two-qubit depth separately: on hardware, only the latter costs real error.

46.4Gate Cancellation

The safest optimization class: removing adjacent inverse pairs, sound by inspection. Implementation on the DAG: scan for op; op⁻¹ on the same qubits (X, H, S†·S, CX(a,b)·CX(a,b)), remove, iterate to fixpoint. Power comes from commutation pre-passes: X commutes with CX controls and with Z-rotations — slide it through, meet its twin, cancel both. Self-inverse patterns recur after every routing pass (SWAP·SWAP = I, CX pairs from direction fixing), so run cancellation after routing, not only before — the preset pass managers encode this order, and now you know why. Each rule gets a two-circuit test: input, expected output, Operator equivalence assertion. Boring, sound, and worth 15–30% of real circuits.

46.5Commutation

The algebraic engine under optimization. Two gates commute if their matrices do — then they may be reordered, enabling cancellation, parallel scheduling, and routing freedoms. Implementable pragmatically: Pauli-word gates (Z-rotations, CX, CZ) have clean commutation rules computable in O(1) from their Pauli labels (anticommute on an odd number of overlapping non-I positions ⇒ commute on even); general gates fall back to matrix checks at small width. The payoff ceiling is Pauli-network compilation for quantum chemistry: commuting-block ordering + diagonalization turns naive L-but-deep chemistry circuits into topology-native ones, often 5–10× two-qubit-count reductions (a 2020s result your laptop can reproduce on small ansätze). Commutation is the difference between pattern-matching compilers and algebra-aware ones.

46.6Peephole Optimization

Local rewrite rules, compiler-classic style: match a small subcircuit pattern, replace with an equivalent cheaper one. The quantum twist: equivalence checks are free (matrix equality at width ≤ 3), so a peephole engine can verify its own rules at load time — build the rule table, assert every rewrite's Operator equality in CI, and the unsound-rule bug class vanishes. Rule sources: hand-written (the cancellations of 46.4), enumerated (search all k-gate circuits on ≤2 qubits for equivalences — an afternoon project that finds real rules), or mined from synthesis (46.7's optimal small-block tables). Guard rails: peepholes must respect barriers and measurement boundaries, and only rewrite within the same qubit set.

46.7Synthesis

Bottom-up construction: build optimal small blocks once, reuse everywhere. Optimal 1q runs: every 1-qubit string resynthesizes to ≤ 3 rotations (Euler); optimal 2q blocks: enumerate minimal-CX implementations per target unitary (KAK gives the lower bound; lookup tables make it fast); Toffoli synthesis: 6 CX (3 with ancilla, if clean ancillas are free — the evergreen tradeoff); state preparation: O(2ⁿ) in general but poly for sparse/real-amplitude states (relevant to chemistry initial states). Synthesis tables double as peephole oracles: any subcircuit matching a table key gets the optimal rewrite — the route by which "optimal" propagates upward through a compiler. This is also exactly how the fault-tolerant era compiles (lattice-surgery scheduling = synthesis at the logical layer).

46.8Benchmarking Transpilers

Make claims falsifiable. Protocol: fix a circuit corpus (BenchPress/QASMBench are public), fix hardware targets (real backend snapshots — pin the calibration date), fix the metric stack (two-qubit count, depth, estimated error Σ, and sampled success rate on noisy simulation for n ≤ 20), run each compiler configuration over ≥ 20 seeds, report median and interquartile range — routing and layout are randomized algorithms, and single-run comparisons are noise. Then ablate: your routing vs Qiskit's, your peepholes on/off, level 3 vs your pipeline. You will discover what every compiler engineer learns: default presets are strong, and your wins will be situational — usually topology- or workload-specific. That's fine: situational wins are exactly what production compilation needs.