← Back

What a Quantum Transpiler Really Does

An analysis of the process that turns a logical circuit into instructions executable by a specific quantum device: gate decomposition, qubit mapping, routing, SWAP insertion, optimization and scheduling.

Transpiler
What is a quantum transpiler

From Logical Circuit to Hardware: How a Quantum Computer Compiles

When we draw a quantum circuit, we usually work with an ideal model. We have perfectly connected qubits, we apply any gate we need, and we assume all operations have a similar cost. Basically, the same thing we do when programming in any language, except that here we program with gates.

The circuit clearly expresses the algorithm we want to run, but not necessarily something a specific quantum device can understand, especially given the different quantum computer implementation technologies that currently exist.

Before reaching the hardware, the circuit must go through a process of quantum compilation, often also called transpilation. During this process, the original circuit is rewritten to fit the instruction set, connectivity, timing and physical characteristics of the chosen target device.

The result can look very different from the initial circuit. It may contain more gates, use other physical qubits, incorporate SWAP operations and have a considerably greater depth, in addition to everything needed for error correction.

However, both circuits must represent, up to the allowed approximations, the same logical transformation.

This difference between logical equivalence and physical efficiency is one of the keys of quantum software engineering, and I always make the same comparison, with all due caveats: when we compile a program written in C# or Rust, for example, at the end of the chain from compilation to execution everything is translated into an assembly-language application that the (classical, of course) computer finally runs, and before getting there, the compiler or the runtime has performed an enormous number of optimizations behind the scenes that the programmer (comfortable with their high-level code) never even finds out about.

The goal of this article is to introduce the fundamental concepts of a quantum transpiler.

The logical circuit is not yet an executable program

A logical circuit describes a sequence of operations on logical qubits. For example:

q0: ──H────■────
           │
q1: ───────X────

This circuit prepares an entangled state using a Hadamard gate and a CNOT. From a mathematical point of view, the description is sufficient: first HH is applied to q0q_0, and then a CNOT controlled by q0q_0 and targeting q1q_1.

However, to run the circuit on a real device we must answer several questions:

  • Does the hardware support a native Hadamard gate?
  • How is the CNOT physically implemented?
  • Which physical qubits will be used?
  • Are those qubits directly connected?
  • What error rates do they have?
  • How long does each operation take?
  • Can several gates be executed simultaneously?
  • Are there control constraints or crosstalk between nearby qubits?

A quantum backend only accepts circuits that comply with its instruction set architecture, or ISA. This means using the gates supported by the device and respecting its connectivity constraints.

Compilation is therefore a combination of translation, optimization and constraint solving.

This is a sector that is currently under heavy development as the capabilities of quantum computers advance.

The stages of quantum compilation

Although each platform uses its own terminology, the compilation flow can be understood through the following stages (and if you ever learned to program in assembly at some point in your career, it won’t surprise you much):

Logical circuit
      │
      ▼
Gate decomposition
      │
      ▼
Qubit mapping
      │
      ▼
Routing and SWAP insertion
      │
      ▼
Optimization
      │
      ▼
Scheduling
      │
      ▼
Executable instructions

These stages are not always applied just once, nor do they follow a strictly linear flow. A routing decision may introduce new gates, which forces the decomposition to be repeated and opens new optimization opportunities. Modern compilers organize these transformations through sequences of passes, loops and conditional decisions.

Gate decomposition

The first problem is translating the abstract gates of the circuit into the device’s native gate set.

An algorithm may contain operations such as:

  • Hadamard.
  • CNOT.
  • Toffoli.
  • SWAP.
  • Arbitrary rotations.
  • Gates controlled by several qubits.
  • Operations defined by the programmer.

Hardware, however, usually provides a much smaller set of elementary instructions. Therefore, a logical gate must be expressed as a sequence of gates the device can implement.

By way of comparison, and with all due caveats, any algebraic operation ends up reduced to the elementary arithmetic operations (add, subtract, divide and multiply).

For example, a SWAP gate can be decomposed into three CNOTs:

q0: ──■────X────■──
      │    │    │
q1: ──X────■────X──

The logical relation can be written as:

SWAP⁡(a,b)=CNOT⁡(a,b)CNOT⁡(b,a)CNOT⁡(a,b)\operatorname{SWAP}(a,b) = \operatorname{CNOT}(a,b) \operatorname{CNOT}(b,a) \operatorname{CNOT}(a,b)

This decomposition is exact in the ideal model, but it is not free on a physical device. If every two-qubit gate introduces noise, replacing one abstract operation with several native gates increases the probability of error.

Approximate decomposition

Some arbitrary rotations cannot be expressed exactly with a finite set of gates. In those cases, the compiler generates an approximation:

U≈GmGm−1⋯G2G1U \approx G_m G_{m-1}\cdots G_2G_1

, where each GiG_i belongs to the available gate set.

Increasing the precision of the approximation usually increases the number of gates as well. This creates an engineering decision:

  • A longer sequence approximates the ideal operation better.
  • A shorter sequence accumulates less physical noise.

The best mathematical solution is not always the best experimental solution.

Mapping logical qubits to physical qubits

A logical qubit is the one we actually use to perform an operation, but for it to work correctly, it is supported by a set of other qubits dedicated to correcting errors, among other tasks; depending on the nature of the quantum computer, this ratio can be 1 to 5 or even 1 to 9 (that is, for each useful logical qubit there are another 9 that support it).

The identifiers q0q_0, q1q_1 or q2q_2 in a circuit are abstractions. The device has specific physical qubits, each with different characteristics.

The assignment, known as qubit mapping or qubit placement, establishes a correspondence:

π:QL→QP\pi : Q_L \rightarrow Q_P

, where QLQ_L is the set of logical qubits and QPQ_P the set of physical qubits.

For example:

logical q0 → physical Q7
logical q1 → physical Q8
logical q2 → physical Q12

This assignment directly influences the final circuit because physical qubits can differ in a number of factors, such as:

  • Gate fidelity.
  • Readout error rate.
  • Relaxation and decoherence times.
  • Connectivity with other qubits.
  • Gate duration.
  • Quality of two-qubit operations.

A simple strategy might select the qubits with the best individual fidelities. However, those qubits may be far from each other and require many routing operations. Another strategy might choose a highly connected region of the processor, even if some of its qubits are noisier.

The mapping problem is therefore not about finding the “best qubits” in isolation. It is about finding the best physical region for the circuit’s interaction pattern.

The device connectivity graph

In an abstract circuit we assume any qubit can interact with any other. On many real devices, two-qubit gates can only be executed between certain pairs.

This constraint is represented by a coupling graph:

GH=(V,E)G_H = (V,E)

, where:

  • Each vertex v∈Vv\in V represents a physical qubit.
  • Each edge (u,v)∈E(u,v)\in E indicates that the hardware allows a direct interaction between those qubits.

Consider this linear topology:

Q0 ─── Q1 ─── Q2 ─── Q3

A gate between Q0Q_0 and Q1Q_1 can be executed directly. A gate between Q0Q_0 and Q3Q_3 cannot.

If the circuit requires that interaction, the compiler must change the location of the quantum states or use an equivalent construction compatible with the available connectivity.

This is where the routing problem begins.

Routing and SWAP gate insertion

Routing determines how to move logical states across the physical topology so that every two-qubit operation can be executed between connected qubits.

Suppose the assignment:

q0 → Q0
q1 → Q3

and a logical gate:

CNOT⁡(q0,q1)\operatorname{CNOT}(q_0,q_1)

Since Q0Q_0 and Q3Q_3 are not adjacent, the compiler may insert SWAP operations:

Initial state:

q0        q1
 │         │
Q0 ─ Q1 ─ Q2 ─ Q3

After routing:

     q0    q1
      │     │
Q0 ─ Q1 ─ Q2 ─ Q3

Each SWAP exchanges the states held by two physical qubits. It is important to understand that the qubits are not physically “moved”. What changes is the correspondence between logical states and physical positions.

If initially:

π(q0)=Q0,π(q1)=Q3\pi(q_0)=Q_0,\qquad \pi(q_1)=Q_3

, after swapping Q0Q_0 and Q1Q_1, we get:

π′(q0)=Q1,π′(q1)=Q3\pi'(q_0)=Q_1,\qquad \pi'(q_1)=Q_3

The compiler must keep this correspondence up to date for the rest of the circuit.

The real cost of a SWAP

A SWAP can be represented with three CNOTs. Therefore, inserting five SWAPs could introduce up to fifteen additional two-qubit operations before further optimizations.

This cost matters because two-qubit operations are usually more delicate than single-qubit ones. Routing can turn a small logical circuit into a much deeper physical circuit.

Global routing versus local decisions

A naive strategy might always select the shortest path to bring the two qubits of the next gate closer. However, this local decision can be harmful for later operations.

Consider the sequence:

CNOT⁡(q0,q3),CNOT⁡(q0,q2),CNOT⁡(q0,q1)\operatorname{CNOT}(q_0,q_3), \quad \operatorname{CNOT}(q_0,q_2), \quad \operatorname{CNOT}(q_0,q_1)

Moving q0q_0 toward q3q_3 may solve the first interaction, but move it away from the other qubits. A decision that seems optimal for the current operation can increase the total cost of the circuit.

A routing algorithm must balance different goals:

  • Number of SWAP gates.
  • Added depth.
  • Total duration.
  • Estimated fidelity.
  • Available parallelism.
  • Quality of the physical links.
  • Cost of future operations.

Compilation strategies may use solver-based methods, heuristics and machine learning techniques. Their objective functions may consider gate count, duration, fidelity and compilation scalability.

Optimization of the physical circuit

After decomposing gates and inserting routing operations, the circuit contains opportunities for simplification.

Common optimizations include:

Cancellation of inverse gates

If a gate is followed by its inverse:

UU†=IU U^\dagger = I

, both can be removed, since applying them has no effect at all (it’s as if the expression x = 28*2 + 2 - 2 were optimized to x = 28*2).

For a self-inverse gate such as XX:

XX=IXX=I

The following fragment performs no transformation:

──X──X──

Merging rotations

Two consecutive rotations around the same axis can be combined:

Rz(α)Rz(β)=Rz(α+β)R_z(\alpha)R_z(\beta)=R_z(\alpha+\beta)

Therefore:

──Rz(α)──Rz(β)──

can be transformed into:

──Rz(α+β)──

Reordering operations

Independent or commuting gates can be rearranged to:

  • Expose cancellations.
  • Reduce depth.
  • Increase parallelism.
  • Make routing easier.
  • Group compatible operations.

Eliminating unnecessary SWAPs

It is not always necessary to return each logical state to its original physical position. If the circuit ends with measurements, the compiler can keep the final permutation and reinterpret the classical results.

For example, if at the end:

logical q0 → physical Q4
logical q1 → physical Q2

it may be cheaper to measure Q4Q_4 and Q2Q_2 and reorder the classical bits afterwards than to insert new SWAPs.

Hardware-dependent optimization

Two algebraically equivalent sequences can have very different physical costs. A hardware-aware compiler may prefer:

  • Links with lower error.
  • More favorable control directions.
  • Calibrated native gates.
  • Shorter sequences.
  • Regions with better experimental metrics.

For this reason, optimizing only the total number of gates is not enough.

Scheduling: when each operation runs

Once the physical sequence of instructions has been determined, we still need to decide when each one will run. Scheduling assigns a start time to each operation:

s:O→R≥0s: O \rightarrow \mathbb{R}_{\geq 0}

, where OO represents the set of operations in the circuit.

The assignment must respect several constraints.

Logical dependencies

If a gate uses the quantum result produced by another, it cannot start before the previous operation finishes:

s(oj)≥s(oi)+d(oi)s(o_j) \geq s(o_i)+d(o_i)

where d(oi)d(o_i) is the duration of oio_i.

Resource exclusion

Two operations that use the same qubit at the same time cannot overlap:

qubits(oi)∩qubits(oj)≠∅⇒oi and oj do not overlap\text{qubits}(o_i)\cap\text{qubits}(o_j)\neq\varnothing \Rightarrow o_i\text{ and }o_j\text{ do not overlap}

Physical constraints

The device may impose additional limitations related to:

  • Shared control electronics.
  • Measurement operations.
  • Qubit reset.
  • Synchronization.
  • Timing alignment.
  • Crosstalk between nearby operations.

Scheduling turns a logical sequence into a temporal program.

Time →      0      1      2      3

Q0          H      ├─CNOT─┤     M
Q1          X      ├─CNOT─┤     M
Q2          ├─Rz───────────┤     M

Logical depth counts layers, but physical duration must account for the fact that not all gates take the same time.

Logical depth and execution time are not equivalent

The depth of a circuit is normally defined as the length of the longest path of dependent operations:

D(C)=max⁡p∈P(C)∣p∣D(C)=\max_{p\in P(C)} |p|

This measure is useful, but it does not necessarily reflect real time.

Consider two circuits:

Circuit A:
Layer 1: H
Layer 2: CNOT
Layer 3: H

Circuit B:
Layer 1: Rz
Layer 2: Rz
Layer 3: Rz

Both have depth three. However, the durations of their operations may differ:

TA=d(H)+d(CNOT⁡)+d(H)T_A=d(H)+d(\operatorname{CNOT})+d(H) TB=3d(Rz)T_B=3d(R_z)

If certain rotations are implemented through reference frame updates rather than physical pulses, the time difference can be even greater.

A more representative metric is the duration of the critical path:

T(C)=max⁡p∈P(C)∑g∈pd(g)T(C)=\max_{p\in P(C)} \sum_{g\in p} d(g)

Therefore:

same depth⇏same duration\text{same depth} \not\Rightarrow \text{same duration}

and also:

lower depth⇏lower error\text{lower depth} \not\Rightarrow \text{lower error}

Why two equivalent circuits can behave differently

Two circuits C1C_1 and C2C_2 are equivalent if they implement the same transformation, possibly ignoring a global phase:

UC1=eiϕUC2U_{C_1}=e^{i\phi}U_{C_2}

This mathematical equivalence does not imply physical equivalence.

Different number of gates

One decomposition may use fewer operations than another:

Ng(C1)≠Ng(C2)N_g(C_1)\neq N_g(C_2)

Different depth

A circuit may allow several gates to run in parallel:

D(C1)<D(C2)D(C_1)<D(C_2)

even if both have a similar number of operations.

Different routing cost

One formulation may fit the device’s connectivity graph while another requires numerous SWAPs:

NSWAP(C1)≪NSWAP(C2)N_{\mathrm{SWAP}}(C_1)\ll N_{\mathrm{SWAP}}(C_2)

Different estimated fidelity

As a simplified approximation, if each operation gig_i has a success probability fif_i, the total fidelity can be estimated by:

F(C)≈∏ifiF(C)\approx\prod_i f_i

This expression does not capture all the effects of real noise, but it shows something important: adding gates reduces the accumulated probability of running the circuit correctly.

Different duration

Even two circuits with the same depth may use operations with different times:

T(C1)≠T(C2)T(C_1)\neq T(C_2)

Different exposure to decoherence

A qubit that stays idle while waiting for other operations remains exposed to noise. For this reason, the gaps introduced by scheduling also matter.

A simple example

Suppose three logical qubits and three physical qubits with linear connectivity:

Q0 ─── Q1 ─── Q2

The logical circuit contains:

q0: ──H────■────
           │
q1: ───────┼────
           │
q2: ───────X────

The two-qubit operation connects q0q_0 with q2q_2.

Assignment A

q0 → Q0
q1 → Q1
q2 → Q2

The interaction between q0q_0 and q2q_2 is not direct. The compiler must introduce routing.

One possibility is:

SWAP(Q0,Q1)
CNOT(Q1,Q2)

The correspondence after the SWAP is:

q0 → Q1
q1 → Q0
q2 → Q2

Assignment B

q0 → Q1
q1 → Q0
q2 → Q2

Now q0q_0 and q2q_2 are adjacent and the CNOT can run directly.

Both cases start from the same logical circuit. However, a better initial assignment avoids a SWAP and, with it, several additional physical operations.

This is why mapping and routing must be analyzed together.

There is no single objective function

When a circuit is said to be “optimized”, it is worth asking: optimized with respect to what?

A compiler may try to minimize:

min⁡Ngates\min N_{\text{gates}}

or:

min⁡D(C)\min D(C)

It may also minimize:

min⁡T(C)\min T(C)

, or maximize an estimate of fidelity:

max⁡F(C)\max F(C)

Another possibility is to use a combined function:

min⁡(αN2q+βD+γT+δE)\min \left( \alpha N_{\mathrm{2q}} +\beta D +\gamma T +\delta E \right)

, where:

  • N2qN_{\mathrm{2q}} is the number of two-qubit gates;
  • DD is the depth;
  • TT is the estimated duration;
  • EE is the expected error;
  • α,β,γ,δ\alpha,\beta,\gamma,\delta represent the relative importance of each objective.

Reducing depth may require using noisier links. Minimizing SWAPs may concentrate too many operations on a group of qubits. Choosing the qubits with the best fidelities may increase routing distances.

Quantum compilation is, to a large extent, a multi-objective optimization problem, similar to what high-level language compilers solve.

Some interesting metrics we should compare

To evaluate two compiled circuits, looking at the final drawing is not enough. It is worth comparing:

Size

S(C)=total number of operationsS(C)=\text{total number of operations}

Depth

D(C)=number of dependent layersD(C)=\text{number of dependent layers}

Two-qubit gates

N2q(C)N_{2q}(C)

This is usually an especially relevant metric because these operations drive a large part of the routing and the accumulated error.

Added SWAPs

NSWAP(C)N_{\mathrm{SWAP}}(C)

It measures the cost introduced by physical connectivity.

Estimated duration

T(C)T(C)

It depends on the real durations of the instructions and on the scheduling.

Fidelity or expected error

An approximation based on the known properties of the device can be used, keeping in mind that physical noise is not always independent or stationary.

Quality of the result

Finally, the experimental distribution should be compared with the ideal result using a metric appropriate for the experiment.

None of these indicators, considered in isolation, fully describes the quality of the compilation.

Key takeaways

The circuit a quantum developer writes is a logical description, not the final physical program.

To run it, the compiler must:

  1. Decompose the operations into gates compatible with the device.
  2. Assign logical qubits to physical qubits.
  3. Resolve connectivity constraints.
  4. Insert SWAPs when necessary.
  5. Simplify and reorganize the circuit.
  6. Schedule each instruction in time.
  7. Generate a representation compatible with the target hardware.

Every decision changes the physical cost of execution. A poor mapping can produce costly routing. Routing can introduce numerous two-qubit gates. Decomposition can increase depth. Scheduling can add waiting time, and all these transformations can amplify the effect of noise.

That is why two mathematically equivalent circuits can show radically different depths, durations and error rates.

Quantum compilation is not a secondary stage sitting between the algorithm and the device. It is the process that determines whether an elegant logical formulation can become a physically viable experiment. For a quantum software engineer, understanding this transformation is as important as knowing the algorithm itself.

Some references

If you are especially interested in this topic, which sees very high activity in quantum computing, here are some references: