Quantum Programming and Simulation

Chapter 10
Compilation, Transpilation and Hardware Execution

Diploma in Quantum Computing
Quantum Programming and Simulation   •   Diploma

Compilation, Transpilation and Hardware Execution

Introduction

A quantum algorithm is usually designed at a logical level, using abstract qubits and gates such as Hadamard, controlled-NOT, phase rotations and measurement. A real quantum processor, however, has a fixed number of physical qubits, a restricted native gate set, limited qubit connectivity, finite coherence times and hardware-dependent error rates. The process of converting a logical circuit into an executable hardware program is therefore central to quantum programming.

This chapter examines compilation, transpilation and execution as a complete workflow. Compilation is treated broadly as the transformation from a high-level quantum program to an executable representation. Transpilation commonly refers to rewriting a circuit into the gate set, connectivity and operational conventions of a target platform. The workflow includes gate decomposition, qubit placement, routing, scheduling, optimization, job submission and result analysis.

A useful distinction is that a simulator executes a mathematical model of a circuit, whereas a quantum processor executes physical operations subject to noise and operational constraints. Comparing the two requires more than checking whether the most frequent bit string is identical; it requires attention to distributions, statistical uncertainty, calibration data and hardware metrics.

Learning objectives

By the end of this chapter, a student should be able to:

  1. Explain the roles of compilation and transpilation in a quantum software stack.
  2. Decompose abstract gates into a target processor’s native operations.
  3. Describe qubit placement, routing and the effect of connectivity constraints.
  4. Explain scheduling, circuit depth, parallelism and coherence limitations.
  5. Identify common circuit optimizations and their risks.
  6. Submit jobs safely to cloud quantum processors and manage credentials and queues.
  7. Compare simulator and hardware results using suitable statistical and hardware metrics.
  8. Evaluate a compiled circuit and justify practical execution choices.

1. From logical circuits to executable programs

A logical circuit specifies an algorithm independently of a particular processor. Its qubits are ideal mathematical systems, and its gates may come from a universal library. A hardware circuit must satisfy several additional conditions:

  • every gate must be supported directly or decomposable into supported gates;
  • every two-qubit operation must act on a permitted pair of physical qubits;
  • measurements and resets must follow the device interface;
  • operations must be placed in time without violating dependencies;
  • the circuit should be sufficiently short and simple to limit errors.

The transformation can be represented as:

Quantum compilation flow Logical circuitabstract gates Transpilerdecompose and map Scheduled circuitnative operations Processor or simulatorcounts and metrics constraints: gate set • topology • timing • calibration Results must be interpreted with statistical and hardware context.
Quantum compilation flow from algorithm to hardware results
Figure: Quantum compilation flow from algorithm to hardware results

Figure: The transformation from an abstract quantum circuit to an executable job and measured results.

A compiler may also perform classical processing, such as evaluating parameters, allocating memory and preparing measurement instructions. In practice, the boundary between compiler and transpiler varies between software frameworks. The important idea is that the resulting circuit must preserve the intended logical action, subject to approximation choices and hardware limitations.

2. Gate decomposition and native gate sets

A native gate set is the collection of operations implemented directly, or nearly directly, by a processor. Typical native operations include single-qubit rotations, a phase-like gate and one entangling gate. The exact set differs between technologies and vendors.

A gate not in the native set is replaced by an equivalent sequence. For example, a controlled-Z operation can be related to a controlled-NOT operation by basis changes on the target qubit:

CZ = (I ⊗ H) CNOT (I ⊗ H)

Here, I is the single-qubit identity, H is the Hadamard gate, ⊗ denotes the tensor product, and the rightmost operation acts first under the usual circuit convention. This identity assumes ideal gates and the same qubit ordering on both sides.

A general single-qubit unitary can be written, up to a global phase, as:

U(θ, φ, λ) = Rz(φ) Ry(θ) Rz(λ)

The angles θ, φ and λ are real rotation angles in radians. This decomposition is useful because many platforms implement rotations about selected axes efficiently. Global phase is physically unobservable for an isolated state, but relative phases must be preserved.

Decomposition involves trade-offs. A mathematically equivalent circuit may differ in gate count, entangling-gate count, depth and sensitivity to calibration. Since two-qubit gates are often less reliable than single-qubit gates, a transpiler generally tries to reduce entangling operations, but not at the cost of violating the algorithm’s required connectivity or introducing excessive depth.

3. Qubit placement and routing

3.1 Logical and physical qubits

A logical qubit is a position in the algorithm. A physical qubit is an available device qubit with particular calibration data. A placement, or initial layout, is a mapping from logical qubits to physical qubits. If logical qubit qi is assigned to physical qubit pj, the mapping can be written as π(qi)=pj.

Good placement keeps frequently interacting logical qubits close on the device and may select physical qubits with lower error rates. Placement is an optimization problem because interaction patterns change throughout a circuit.

3.2 Coupling graphs

Hardware connectivity is represented by a coupling graph G=(V,E). The vertices V represent physical qubits and an edge (u,v)∈E indicates that a two-qubit operation is permitted between those qubits. Some processors have directed couplings for particular gates; in that case, direction must also be respected or corrected with additional basis operations.

If a logical two-qubit gate acts on q1 and q2, their assigned physical qubits must be adjacent in the coupling graph. If they are not adjacent, routing is required.

3.3 Routing with SWAP operations

A common routing method inserts SWAP gates. A SWAP exchanges the states of two adjacent physical qubits. It can be decomposed into three controlled-NOT operations:

SWAP(a,b) = CNOT(a,b) CNOT(b,a) CNOT(a,b)

The order is read according to the circuit convention. This identity assumes ideal CNOT operations and appropriate control-target orientation. Inserting a SWAP increases both gate count and depth, so routing is often a major source of hardware error.

For example, consider a linear device 0—1—2—3. If logical qubits A and D are initially placed on physical qubits 0 and 3, a direct two-qubit gate between them is impossible. A compiler may move A or D through the chain using SWAPs until the two states occupy adjacent sites. Alternative placements may reduce the number of required SWAPs. The best choice depends on all interactions, not only the first one.

Routing algorithms may be heuristic, search-based or optimization-based. They commonly balance:

  • the number of inserted SWAPs;
  • estimated gate error;
  • circuit depth;
  • preservation of useful existing mappings;
  • qubit readout and coherence quality.

4. Scheduling, depth and coherence

After decomposition and routing, operations must be assigned start times. Gates that act on disjoint qubits may sometimes execute in parallel, whereas gates sharing a qubit must obey dependencies. The scheduled circuit has a duration determined by gate durations, control electronics and synchronization requirements.

Circuit depth is the number of sequential layers under a specified layering convention. It is not necessarily equal to total gate count. Two circuits can have the same number of gates but different depths if one exposes more parallelism.

A simple coherence constraint is that the execution time should be small relative to the relevant coherence times. If a qubit remains involved for time t and has relaxation time T1, a common idealized survival factor for energy relaxation is approximately:

P1(t) = e-t/T1

Here t and T1 have the same time unit, and the expression describes a simplified exponential model. Dephasing introduces additional effects, often characterized by T2; real devices may require calibration-based noise models rather than this approximation.

Scheduling also matters for measurement. Readout operations may be simultaneous or sequential depending on hardware, and simultaneous activity can create crosstalk. A schedule should therefore be evaluated using actual timing and calibration information, not depth alone.

5. Circuit optimization

Optimization rewrites a circuit while preserving its intended operation or measurement statistics. Common transformations include:

  • cancelling adjacent inverse gates, such as X X = I;
  • combining consecutive rotations about the same axis;
  • removing redundant barriers when they do not express a required timing constraint;
  • commuting gates through independent operations;
  • simplifying classical controls and parameter expressions;
  • choosing a better qubit layout;
  • reducing or restructuring routing operations.

Optimization must respect non-commutation. For example, rotations about different axes generally cannot be freely reordered. An optimization that is valid for a unitary circuit may also be invalid if it changes measurement timing, reset behavior, mid-circuit classical control or noise-sensitive scheduling assumptions.

There is no universally best optimization level. Aggressive rewriting can reduce gate count but increase compilation time, obscure debugging and sometimes select a longer route on a particular device. Professional practice is to preserve the original circuit, record transpiler settings and compare the compiled circuit’s metrics with the intended circuit.

6. A practical compilation workflow

A robust workflow consists of the following stages:

  1. Specify the algorithm. Define inputs, outputs, measurements and acceptable approximation.
  2. Validate logically. Test the circuit on small ideal simulations and known cases.
  3. Select a target. Choose a simulator or processor according to qubit count, connectivity, native gates, queue conditions and calibration quality.
  4. Inspect constraints. Record supported gates, coupling map, measurement behavior and timing rules.
  5. Transpile. Apply layout, decomposition, routing, scheduling and optimization.
  6. Inspect the result. Check logical-to-physical mapping, depth, two-qubit count and estimated duration.
  7. Run a baseline. Execute an ideal or noise-aware simulator using the same compiled circuit when possible.
  8. Submit hardware jobs. Use secure credentials, a selected backend and an appropriate shot count.
  9. Monitor and retrieve. Record job identifiers, queue status, timestamps and software versions.
  10. Compare and interpret. Separate statistical sampling variation from hardware-induced error.

A minimal pseudocode pattern is:

circuit = build_logical_circuit()
assert validate(circuit)
compiled = transpile(circuit, backend=target, optimization_level=k)
report(compiled.depth, compiled.two_qubit_count, compiled.layout)
sim_result = run_simulator(compiled, shots=N)
job = submit(compiled, backend=target, shots=N)
result = retrieve(job.id)
compare(sim_result, result)

The exact function names vary by framework. The methodological principles are portable.

7. Cloud execution, credentials and queues

Cloud quantum services expose processors through an account and job-management system. A safe execution procedure includes:

  • creating an account through an authorized channel;
  • storing API tokens in environment variables or a secrets manager rather than source code;
  • granting only necessary permissions;
  • selecting the intended project, workspace or account context;
  • checking service status and backend availability;
  • submitting a small test job before a large experiment;
  • recording the job identifier and circuit metadata;
  • deleting or rotating credentials if exposure is suspected.

A queue is a scheduling system, not a guarantee of immediate execution. Waiting time can depend on service tier, machine availability, calibration periods, maintenance and competing jobs. A job may have states such as submitted, queued, running, completed, cancelled or failed. Programs should handle retries carefully: resubmitting blindly can duplicate experiments and incur additional cost.

Shot count affects both precision and resource usage. If an event has true probability p and is sampled independently N times, the estimated frequency has standard deviation:

σp = √(p(1-p)/N)

This is a binomial sampling result. It assumes independent identically distributed shots and concerns sampling uncertainty only; it does not include systematic hardware bias. Since p is usually unknown, it may be estimated from the observed frequency.

8. Simulator and hardware results

An ideal simulator predicts the distribution produced by the mathematical circuit. A hardware processor produces samples affected by gate errors, readout errors, decoherence, crosstalk, leakage, calibration drift and control imperfections. A noise-aware simulator can model some of these effects but is only as accurate as its noise model.

Comparison should use the same compiled circuit, measurement convention, shot count where practical and bit-order interpretation. Useful measures include:

8.1 Total variation distance

For discrete distributions P and Q, total variation distance is:

DTV(P,Q) = 1/2 ∑x |P(x)-Q(x)|

The sum is over all measured outcomes. The value lies between 0 and 1. It is zero for identical distributions. With finite samples, the empirical value also contains sampling error.

8.2 Hellinger distance

A frequently used distributional measure is:

H(P,Q) = (1/√2) √(∑x (√P(x)-√Q(x))²)

The distributions must be normalized and non-negative. This metric is sensitive to differences across low-probability outcomes and is bounded between 0 and 1 under this convention.

8.3 Success probability and expectation values

For an algorithm with a defined set of successful outcomes S, success probability is:

Psuccess = ∑x∈S P(x)

If a measured observable has outcomes associated with values ox, its expectation is:

⟨O⟩ = ∑x ox P(x)

These measures are meaningful only when the success criterion, outcome encoding and observable are specified.

8.4 Hardware metrics

Important metrics include:

MetricMeaningWhy it matters
Qubit countNumber of available physical qubitsLimits problem size, but does not alone indicate quality
ConnectivityPermitted two-qubit interactionsDetermines routing overhead
Gate errorEstimated probability or infidelity for an operationIndicates operation reliability
Readout errorProbability of reporting an incorrect measured stateAffects observed counts
T₁ and T₂Relaxation and dephasing timesIndicate sensitivity to elapsed execution time
Gate durationTime required for an operationInfluences decoherence and scheduling
Queue delayTime before execution beginsAffects experimental throughput
Two-qubit count and depthCompiled circuit costUseful predictors of accumulated error

Metrics are calibration-dependent and should be recorded with timestamps. A headline metric such as quantum volume or a vendor’s fidelity estimate should not replace task-specific benchmarking.

9. Worked example: comparing ideal and hardware distributions

Suppose an ideal two-qubit circuit predicts outcomes 00 and 11 with probabilities 0.50 each. A hardware run with 1,000 shots produces 460 counts for 00, 40 for 01, 30 for 10 and 470 for 11. The empirical hardware distribution is therefore:

Q = (0.46, 0.04, 0.03, 0.47), while the ideal distribution is P = (0.50, 0, 0, 0.50) in the order 00, 01, 10, 11.

The total variation distance is:

DTV(P,Q) = 1/2 (|0.50-0.46| + |0-0.04| + |0-0.03| + |0.50-0.47|)
= 1/2 (0.04 + 0.04 + 0.03 + 0.03)
= 0.07

Thus the empirical distributions differ by 0.07 under this metric. The hardware success probability, taking 00 and 11 as successful outcomes, is 0.46 + 0.47 = 0.93. The result suggests both loss of probability from the ideal successful outcomes and appearance of undesired outcomes. It does not, by itself, identify whether the cause is gate error, readout error, decoherence or another mechanism.

The sampling standard deviation for a probability near 0.5 with 1,000 shots is approximately:

σp = √(0.5×0.5/1000) ≈ 0.0158

The observed deviations of approximately 0.03–0.04 are larger than one sampling standard deviation, although a formal statistical conclusion requires a specified test and treatment of all outcomes.

10. Illustrative case: mapping a three-qubit algorithm

Background

A teaching laboratory uses a three-qubit entangling circuit that prepares a correlated state and measures all qubits. The logical circuit contains several single-qubit gates and two CNOT gates between logical qubits A–B and B–C.

Problem

The selected processor has physical connectivity 0—1—2, but calibration data show that physical qubit 1 has relatively high readout error. The student must choose a mapping and compare simulator and hardware results.

Analysis

The interaction graph of the algorithm is also a chain, so no SWAP is needed if A, B and C are placed on 0, 1 and 2 in that order. However, placing B on the central physical qubit exposes it to the higher readout error. Moving B to an endpoint would require either a different ordering or routing operations. The student therefore compares two strategies:

  • Mapping 1: A→0, B→1, C→2; zero routing overhead but poorer central readout.
  • Mapping 2: B→0, A→1, C→2; one interaction may require routing because the logical interaction pattern no longer matches the physical chain.

Approach

The student transpiles both alternatives at the same optimization level, records native gate counts, depth and estimated duration, and runs each compiled circuit on an ideal simulator and with the same number of hardware shots. The student also records calibration timestamps and reads the actual measurement error estimates.

Outcome

Mapping 1 has fewer two-qubit operations and lower depth. Mapping 2 reduces exposure of the logical central qubit to the poor readout location but introduces additional routing. If Mapping 2 produces a worse distribution despite better readout placement, the added two-qubit operations may dominate. If Mapping 1 has strong evidence of readout bias and Mapping 2 is only slightly deeper, Mapping 2 may be preferable. The correct decision is empirical and task-specific rather than based on qubit count alone.

Learning points

The case demonstrates that placement is a multi-objective decision. Connectivity, gate error, readout quality, duration and algorithmic interaction structure must be considered together. A reproducible report should include the original circuit, compiled circuit, mapping, backend, calibration time, optimization settings, shot count and comparison metric.

11. Challenges, limitations and responsible practice

Compilation is not lossless in the engineering sense: although the ideal unitary may be preserved, every additional physical operation creates opportunities for error. Noise-aware compilation can improve expected performance but depends on incomplete and changing calibration data. Approximate synthesis can shorten circuits while deliberately introducing bounded approximation error; such a choice must be documented.

Results can also be misinterpreted. A high success rate on an easy circuit does not establish general hardware advantage. Post-selection, measurement-error mitigation and other corrections may improve reported results but can increase variance, computational cost or interpretive complexity. Mitigation should never be presented as raw hardware performance.

Responsible cloud use includes protecting credentials, respecting provider terms, avoiding unnecessary high-shot jobs and reporting resource consumption. Experimental records should support reproducibility without exposing private tokens or confidential data. When quantum workloads involve sensitive classical inputs, data governance and jurisdictional requirements remain applicable even if the quantum processor is remote.

12. Contemporary developments and best practices

Modern toolchains increasingly combine compiler heuristics with calibration-aware placement, pulse-level scheduling, dynamic circuits and error mitigation. Some systems expose intermediate representations so that researchers can inspect transformations rather than treating transpilation as a black box. Machine-learning methods are also being explored for layout and routing, but they must be validated against deterministic baselines and changing hardware conditions.

Best practice is to:

  1. compile for the actual target rather than assuming abstract gates are native;
  2. inspect the final mapping and count entangling gates;
  3. compare alternative layouts when the circuit is connectivity-sensitive;
  4. use the same compiled circuit for simulator baselines;
  5. record backend, calibration, software version, settings and shot count;
  6. distinguish sampling uncertainty from systematic hardware error;
  7. protect credentials and make cloud jobs reproducible;
  8. treat hardware metrics as time-dependent evidence, not permanent labels.

Chapter Summary

Compilation and transpilation transform logical quantum circuits into programs compatible with a particular simulator or processor. The transformation includes native-gate decomposition, qubit placement, routing through coupling graphs, scheduling and optimization. Physical connectivity can require SWAP gates, which increase depth and error exposure. Scheduling determines parallelism and execution duration, while coherence times help explain why long circuits are vulnerable.

Cloud execution requires secure credentials, backend selection, queue monitoring, job identifiers and careful record keeping. Simulator results describe an ideal or modeled distribution; hardware results include statistical sampling and physical noise. Total variation distance, Hellinger distance, success probability and expectation values provide useful comparison tools, provided their assumptions and definitions are explicit. Practical decisions should consider connectivity, gate and readout errors, T₁, T₂, duration, depth, queue conditions and calibration time.

Key Terms

Compilation: Transformation of a quantum program into an executable representation.

Transpilation: Rewriting a circuit for a target gate set, topology and hardware interface.

Native gate: An operation directly supported by a quantum processor.

Gate decomposition: Replacement of an abstract operation by an equivalent native sequence.

Logical qubit: An algorithmic qubit independent of a specific device location.

Physical qubit: A hardware qubit with device-specific properties.

Layout: Mapping between logical and physical qubits.

Coupling graph: Graph describing permitted physical interactions.

Routing: Insertion of operations to satisfy connectivity constraints.

SWAP gate: Operation that exchanges the states of two qubits.

Circuit depth: Number of sequential operation layers under a specified convention.

Scheduling: Assignment of operations to execution times.

Coherence time: Characteristic time over which quantum information remains usable.

Readout error: Error in converting a final quantum state into a classical result.

Shot: One execution and measurement of a circuit.

Queue: System that orders submitted cloud jobs for execution.

Total variation distance: Half the summed absolute difference between two distributions.

Calibration: Measurement and estimation of current hardware operating parameters.

Crosstalk: Unwanted influence of operations on nearby or simultaneous qubits.

Error mitigation: Technique intended to reduce the impact of errors in reported results without full error correction.

Review Questions

Short Answer Questions

  1. Why must a logical circuit be transpiled before execution on most quantum processors?
  2. What is the purpose of a coupling graph?
  3. How does a SWAP operation help with routing?
  4. Distinguish circuit depth from total gate count.
  5. Why should backend calibration timestamps be recorded?

Long Answer Questions

  1. Explain the complete workflow from a logical circuit to a cloud hardware result.
  2. Discuss how gate decomposition and native gate sets influence circuit performance.
  3. Explain the trade-off between choosing a high-quality qubit layout and minimizing routing operations.
  4. Compare ideal simulation, noise-aware simulation and hardware execution.
  5. Describe secure and reproducible practices for submitting quantum jobs through a cloud service.

Analytical / Application Questions

  1. A processor has linear connectivity 0—1—2—3, and two logical qubits requiring a CNOT are initially mapped to 0 and 3. Propose a routing strategy and explain its cost.
  2. An ideal distribution is (0.5, 0, 0, 0.5), while hardware counts from 1,000 shots are (460, 40, 30, 470). Calculate the total variation distance and interpret the result.
  3. Two layouts are available: Layout A has lower depth but uses a qubit with poor readout fidelity; Layout B has one additional SWAP but better readout fidelity. Design an experiment to decide which layout is preferable, specifying the measurements and records required.

Multiple Choice Questions with Answers

Question 1

What is the primary purpose of transpilation?

A. To convert measurement results into probabilities

B. To adapt a logical circuit to a target gate set and hardware topology

C. To increase the number of logical qubits

D. To remove the need for calibration

Correct Answer: B. To adapt a logical circuit to a target gate set and hardware topology

Question 2

Which structure represents permitted physical two-qubit interactions?

A. A coupling graph

B. A probability histogram

C. A queue identifier

D. A calibration timestamp

Correct Answer: A. A coupling graph

Question 3

How many ideal CNOT gates are commonly used to decompose a SWAP gate?

A. One

B. Two

C. Three

D. Four

Correct Answer: C. Three

Question 4

What is a likely consequence of inserting additional SWAP gates?

A. Reduced routing overhead

B. Increased gate count and possible error exposure

C. Automatic elimination of readout error

D. Guaranteed shorter execution time

Correct Answer: B. Increased gate count and possible error exposure

Question 5

Which metric measures the difference between two discrete probability distributions using half the summed absolute differences?

A. Total variation distance

B. Relaxation time

C. Circuit depth

D. Readout fidelity

Correct Answer: A. Total variation distance

Question 6

For 1,000 independent shots and probability p = 0.5, what is the approximate binomial standard deviation of the estimated probability?

A. 0.00158

B. 0.0158

C. 0.158

D. 1.58

Correct Answer: B. 0.0158

Question 7

Which information is especially important for reproducing a hardware experiment?

A. Only the final most frequent bit string

B. Backend, calibration time, transpiler settings and shot count

C. Only the processor's total qubit count

D. The queue length without the circuit

Correct Answer: B. Backend, calibration time, transpiler settings and shot count

Question 8

What does T₁ primarily characterize in the simplified discussion of coherence?

A. Energy relaxation time

B. Readout duration

C. Queue waiting time

D. Number of native gates

Correct Answer: A. Energy relaxation time

Question 9

Why can simulator and hardware distributions differ?

A. Hardware results are affected by noise and finite sampling

B. Simulators always use fewer qubits

C. Hardware never performs measurements

D. Logical gates cannot be represented mathematically

Correct Answer: A. Hardware results are affected by noise and finite sampling

Question 10

Which practice is safest for a cloud API credential?

A. Embedding it directly in a public source file

B. Sharing it in a circuit comment

C. Storing it in a protected environment variable or secrets manager

D. Printing it in experiment reports

Correct Answer: C. Storing it in a protected environment variable or secrets manager

Quantum Programming and Simulation
Chapter 10 of 15