๐ŸŽ‰ 75% of content is free forever โ€” Unlock Premium from $10/mo โ†’
CW
NEWSLIVESearch All Content
๐Ÿ’ผ Servicesโ„น๏ธ Aboutโœ‰๏ธ ContactView Pricing Plansfrom $10

Quantum Compilers

Quantum ComputingQuantum Compilers๐ŸŸข Free Lesson

Quantum Compilation Pipeline

A quantum compiler transforms high-level quantum circuits into hardware-executable instructions:

  1. Frontend parsing: accept quantum program (OpenQASM, QIR)
  2. Optimization: reduce circuit depth and gate count
  3. Transpilation: map to native gate set
  4. Layout/routing: map logical qubits to physical qubits
  5. Scheduling: assign timing and parallelism
  6. Backend code generation: produce pulse-level instructions

Each stage throws away information you cannot easily get back, so the order is fixed. Frontend parsing produces an intermediate representation โ€” OpenQASM 3 or QIR โ€” that all later passes read and write, which is why an intermediate representation with a stable grammar matters more than any single optimiser. Scheduling happens after layout rather than before it, because a gate can only be scheduled at a time when its physical qubits are free and its SWAPs have already been inserted.

Compilation cost itself is usually acceptable: seconds to minutes for circuits of thousands of gates on a laptop. The decision worth making deliberately is when to compile. Compiling once and reusing the result keeps every shot identical and makes the run reproducible; recompiling per shot lets a noise-aware pass pick a different layout as qubit error rates drift through the day, at the price of variance between shots that you then have to model in post-processing.

Gate Synthesis

Gate synthesis decomposes arbitrary unitaries into native gate sets:

For a single qubit, any unitary can be decomposed as:

For two qubits, the KAK decomposition (Cartan decomposition) writes any as:

with at most 3 CNOT gates.

Circuit Optimization

Circuit optimization reduces gate count and depth:

  • Gate cancellation: remove adjacent inverse gates
  • Gate merging: combine multiple gates into one
  • Template matching: replace subcircuits with equivalent shorter ones
  • Algebraic simplification: use gate identities

For example, and .

The highest-yield rules are the boring ones. Two identical single-qubit gates in a row cancel โ€” a Hadamard pair, a CNOT pair, a Pauli pair โ€” because each is its own inverse. Adjacent rotations about the same axis fuse into one rotation, which turns 50 parameter updates into 1 and removes 49 two-quadrature gates worth of phase error. A CNOT with the same control and target cancels. Rotation about commutes across a control, so an sitting between a CNOT's control and the CNOT itself can slide through instead of being re-synthesised.

A worked example shows why these rules compound. A circuit with 1000 consecutive Hadamards on one qubit is the identity: a naive compiler emits 1000 gates at depth 1000, the peephole rule reduces it to 0, and the expected two-qubit error โ€” say per gate โ€” drops from an irrelevant count on a single-qubit string to a genuinely measurable effect once the same logic is wrapped around CNOT pairs. In realistic circuits, adjacent-inverse and rotation-fusing passes typically remove 30 to 60 percent of single-qubit gates before any layout work is done.

PassTriggerSavingWatch out for
Inverse cancellationadjacent self-inverse pair2 gates to 0measurement and reset break commutation
Rotation fusionadjacent same-axis rotations gates to 1keep the angle in to avoid round-off drift
Commutation across a CX controlone less synthesisnever commute across a mid-circuit measurement
Template matchknown subcircuit identityvariableonly if the identity holds for the native basis

Qubit Routing

Qubit routing maps logical qubits to physical qubits with limited connectivity:

  1. Initial placement: assign logical to physical qubits
  2. SWAP insertion: add SWAP gates to enable non-adjacent interactions

The routing problem is NP-hard. Heuristics include:

  • SABRE: look-ahead SWAP routing
  • Graph-based: use hardware connectivity graph
  • Noise-aware: consider error rates when routing

Transpilation Levels

Qiskit provides transpilation levels 0-3:

  • Level 0: no optimization, default layout
  • Level 1: light optimization, trivial layout
  • Level 2: medium optimization, layout by noise
  • Level 3: heavy optimization, full routing and scheduling

Higher levels produce shorter circuits but take longer to compile.

Resource Estimation

Resource estimation counts the resources needed for a quantum algorithm:

  • Qubit count: number of physical qubits
  • Gate count: number of gates (by type)
  • Circuit depth: depth of the circuit
  • T-gate count: number of T gates (costly in fault-tolerant QC)

Resource estimation guides hardware requirements and algorithm design.

Routing Overhead and the Coherence Budget

Routing is where compilation meets physics. On a heavy-hex lattice such as IBM's 127-qubit device, two qubits interact only when they are coupled, so a logical CNOT between distant partners costs a chain of SWAPs, and each SWAP is three CNOTs. The resulting overhead factor is rarely close to 1: circuits that mix many two-qubit gates across a wide register routinely come out 2 to 5 times deeper after routing, and adversarial all-to-all interaction patterns do worse.

The budget being spent is coherence time. With a two-qubit gate near 300 ns and around 200 ยตs, one short path is harmless, but the whole circuit has to finish inside that window: at 500 ns per two-qubit layer including scheduling, 200 ยตs buys roughly 400 two-qubit layers of depth before the state has decayed noticeably. That number, not the logical gate count, is what usually decides whether an algorithm fits on today's hardware.

Three levers move it. A better initial placement cuts long paths before any SWAP is inserted. Reducing the two-qubit count in the optimisation phase shortens everything downstream. And routing that prefers low-error edges over short paths trades a few extra SWAPs for higher fidelity, which is the right trade whenever the fidelity gain outweighs the added exposure time.

LeverTypical effectCost
Noise-aware layout20 to 40 percent lower error per circuitslightly deeper circuits
Shortest-path SWAP chainsfewer inserted SWAPs3 CNOTs per SWAP
Compile once, reusereproducible, auditable runsignores drifting error rates
Recompile per shotfollows the best qubits of the dayshot-to-shot variance to model

Python: Circuit Optimization

python
import numpy as np

def naive_hadamard_circuit(n):
    # n Hadamards -> can be simplified.
    return ['H'] * n

def optimized_hadamard_circuit(n):
    # n Hadamards = I if n is even, H if n is odd.
    return ['H'] if n % 2 else []

def count_gates(circuit):
    return len(circuit)

for n in [10, 100, 1000]:
    naive = naive_hadamard_circuit(n)
    optimized = optimized_hadamard_circuit(n)
    print(f"n={n}: naive={count_gates(naive)}, optimized={count_gates(optimized)}")

Python: Routing Under a Coupling Map

The same file can hold a peephole pass and a shortest-path router, which is enough to see how a non-local CNOT turns into SWAPs:

python
from collections import deque

INVERSE_PAIRS = {
    ("H", "H"), ("X", "X"), ("Y", "Y"), ("Z", "Z"),
    ("S", "Sdg"), ("Sdg", "S"), ("T", "Tdg"), ("Tdg", "T"), ("CX", "CX"),
}

def peephole(gates):
    """Cancel inverse neighbours and fuse adjacent same-axis rotations.
    Each gate is (name, qubits, param)."""
    stack = []
    for name, qs, param in gates:
        if stack:
            pname, pqs, pparam = stack[-1]
            if qs == pqs and (pname, name) in INVERSE_PAIRS:
                stack.pop()
                continue
            if qs == pqs and len(qs) == 1 and pname == name == "Rz":
                stack[-1] = (name, qs, pparam + param)
                continue
        stack.append((name, qs, param))
    return stack

def shortest_path(coupling, src, dst):
    adj = {}
    for u, v in coupling:
        adj.setdefault(u, []).append(v)
        adj.setdefault(v, []).append(u)
    prev = {src: None}
    queue = deque([src])
    while queue:
        u = queue.popleft()
        if u == dst:
            break
        for w in adj.get(u, []):
            if w not in prev:
                prev[w] = u
                queue.append(w)
    path, u = [], dst
    while u is not None:
        path.append(u)
        u = prev[u]
    return path[::-1]

def route(gates, coupling):
    """Insert a SWAP chain wherever a CX spans a non-coupled pair."""
    out = []
    for name, qs, param in gates:
        if name == "CX":
            path = shortest_path(coupling, qs[0], qs[1])
            for i in range(len(path) - 1, 1, -1):
                out.append(("SWAP", (path[i - 1], path[i]), None))
            if len(path) > 2:
                out.append(("CX", (path[0], path[1]), None))
            else:
                out.append(("CX", tuple(qs), None))
        else:
            out.append((name, qs, param))
    return out

line = [(i, i + 1) for i in range(6)]          # 6-qubit line coupling
circuit = [("H", (0,), None), ("Rz", (0,), 0.3), ("Rz", (0,), 0.4),
           ("CX", (0, 5), None), ("CX", (0, 5), None),   # adjacent inverses
           ("H", (5,), None), ("CX", (0, 4), None)]       # spans qubits 0..4

print("before peephole:", len(circuit), "gates")
optimised = peephole(circuit)
print("after peephole:", len(optimised), "gates")
routed = route(optimised, line)
print("after routing:", len(routed), "gates:", [g[0] for g in routed])

The order of those calls is the whole lesson. Peephole reduction first takes seven gates to four: the Hadamard pair and the double CX cancel, and the two rotations fuse into one. Only the surviving CX between qubits 0 and 4 is non-local, so routing adds three SWAPs plus one CX and the circuit ends at seven gates again โ€” but had routing run first, both cancelled CXs would have bought their own SWAP chains and the total would have landed near thirteen. On wider registers the gap between the two orderings grows with the distance the SWAP chains have to travel.

Reading a Transpiler Report

Every serious SDK returns a summary after transpilation, and four lines of it decide whether a job is worth submitting. Compare depth before and after: if the optimiser plus router produced a deeper circuit than you started with, the layout was wrong or the coupling map is too sparse for the interaction pattern, and re-running with an explicit initial layout is the first thing to try. Check the count of two-qubit gates rather than total gates, because single-qubit gates are close to free on superconducting hardware while every CX or CZ carries the dominant error. Check the SWAP count separately: each one costs three two-qubit gates of exposure time with no algorithmic benefit. Finally check that the circuit fits the coherence budget from the previous section โ€” a report showing 400 CX layers on a 200 ยตs device is a rejection, whatever the logical success probability says.

Report lineHealthy signRed flag
Depth after transpileequal or lower than beforelarge increase, or above the coherence limit
Two-qubit gate countdown 30 to 60 percent from the naive circuitunchanged after optimisation level 3
SWAP gatessingle digits for nearest-neighbour structuredozens, indicating a bad layout
Layoutpicked by the noise-aware pass or by youdefault trivial layout on a sparse device

Common Mistakes

Routing before optimising, then wondering why the circuit tripled in depth

Fix: Cancel inverses and fuse rotations first, because every gate you remove is a SWAP chain you never have to insert

Judging a compile by total gate count alone

Fix: Two-qubit gates dominate the error budget, so compare CX or CZ counts and circuit depth instead

Accepting the default trivial layout because it works on a simulator

Fix: Ask for a noise-aware or explicitly chosen initial layout on real hardware, where qubit fidelity varies by more than an order of magnitude across the chip

Key Takeaways

  • A quantum compiler runs six stages in a fixed order: parse to an IR, optimise, synthesise into the native basis, lay out and route, schedule, then emit pulse-level instructions
  • Peephole rules alone routinely remove 30 to 60 percent of single-qubit gates, and cancelling before routing can halve the final two-qubit count
  • Routing on a heavy-hex lattice adds three CNOTs per SWAP, which is why coherence time and not logical gate count is the real budget
  • The compiler must emit each vendor's native basis: Rx, Ry, Rz with CX for IBM, with CZ for Google, with XX for IonQ

Transpilation Algorithms

The SABRE algorithm for qubit routing:

  1. Initial placement: map logical to physical qubits using graph matching
  2. Forward pass: for each gate, find shortest path and insert SWAPs
  3. Backward pass: optimize SWAP insertion
  4. Iterate: repeat until no improvement

The algorithm runs in time where is the gate count and is the qubit count.

Native Gate Sets

Different hardware has different native gate sets:

HardwareSingle-QubitTwo-Qubit
IBMRx, Ry, RzCX (CNOT)
GoogleRx, Ry, RzCZ
IonQRx, Ry, RzXX
RigettiRx, Ry, RzCZ

The transpiler must convert arbitrary gates to these native sets.

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-15

โ€”
โ˜†โ˜†โ˜†โ˜†โ˜†
0 ratings

Rate & Feedback

Need Expert Quantum Computing Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement