Quantum Computing Master Course — 147. Transpilation Fundamentals
Lesson 147: Transpilation Fundamentals
Smartyfy Quantum Computing Master Course
Objectives and prerequisites
Explain circuit compilation stages, inspect a basis-translated circuit, and verify ideal operator equivalence without confusing it with physical performance. Prerequisites are gate decompositions, layout and routing, matrix multiplication, and global phase. The Qiskit example targets the official 2.5.2 documentation reference; it was not executed because the SDK was absent. The independent decomposition check was executed locally.
Compilation changes representation while preserving a specification
Transpilation rewrites a quantum circuit for a target gate set, connectivity, or optimization objective. It may decompose gates, choose an initial placement, insert routing operations, simplify instructions, and schedule timing. The intended equivalence must be stated: an ideal unitary up to global phase, a measurement distribution with a mapped output, or a more general dynamic behavior are different specifications.
A device target can include more than a coupling graph. It can specify supported operations on particular qubit tuples, durations, errors, and timing constraints. A circuit expressed in a permitted gate vocabulary is not automatically valid for every device using that vocabulary. Connectivity and instruction placement still matter.
| Stage | Main change | Verification concern |
|---|---|---|
| Layout | Map logical qubits to positions | Preserve the mapping record |
| Routing | Make interactions compatible with connectivity | Track final permutations and overhead |
| Basis translation | Replace operations with supported gates | Check decomposition and phase |
| Optimization and scheduling | Reduce cost and assign compatible timing | Check objective, constraints and ideal behavior |
A deliberately limited local example
Take the unmeasured circuit H(0), CX(0,1). Translate it to the basis rz, sx, x, cx with a fixed optimization level and compiler seed. We do not supply a coupling map or backend target, so the example investigates basis translation without imposing device routing or timing constraints. No remote hardware information is requested.
from qiskit import QuantumCircuit, transpile
from qiskit.quantum_info import Operator
original = QuantumCircuit(2)
original.h(0)
original.cx(0,1)
compiled = transpile(original, basis_gates=['rz','sx','x','cx'],
optimization_level=1, seed_transpiler=147)
assert Operator(original).equiv(Operator(compiled))
assert set(compiled.count_ops()) <= {'rz','sx','x','cx'}
print('Operations:', compiled.count_ops())
print('Depth:', compiled.depth())
print('Global phase:', compiled.global_phase)
The snippet asks Operator.equiv to compare the complete two-qubit operators up to one global phase. It also checks that every remaining operation belongs to the requested basis. Exact output gate counts and depth are intentionally not invented: they depend on the SDK implementation and were not observed in this environment.
A seed helps reproduce heuristic choices in a fixed software environment, but does not guarantee identical compiled circuits across all versions or machines. Record the input circuit, target constraints, seed, optimization settings, actual version, and output circuit when executing the example.
Worked Hadamard decomposition with phase
Define Rz(φ) = diag(exp(−iφ/2), exp(iφ/2)). Define SX as one half times the matrix with rows [1+i, 1−i] and [1−i, 1+i]. SX squares to X and includes the conventional phase used by this gate definition.
Apply Rz(π/2), then SX, then Rz(π/2). The resulting operator is Rz(π/2) SX Rz(π/2), because column vectors are acted on by the rightmost matrix first. Direct multiplication gives exp(−iπ/4)H. Therefore H = exp(iπ/4) Rz(π/2) SX Rz(π/2).
The global phase must be accounted for in an exact matrix representation, even though a standalone final-state measurement cannot detect it. A compiler may record such a phase separately rather than insert a physical gate. Omitting it from a raw entry-by-entry matrix comparison would falsely report inequality.
Executed independent operator check
Save Lesson 141’s first code block as local_statevector141.py beside this script before running it.
from math import pi
from cmath import exp
from local_statevector141 import apply_one, apply_cx, H
SX = [[(1+1j)/2,(1-1j)/2],[(1-1j)/2,(1+1j)/2]]
RZ = [[exp(-1j*pi/4),0],[0,exp(1j*pi/4)]]
phase = exp(1j*pi/4)
for column in range(4):
v = [complex(i==column) for i in range(4)]
expected = apply_cx(apply_one(v,H,0),0,1)
actual = apply_one(v,RZ,0)
actual = apply_one(actual,SX,0)
actual = apply_one(actual,RZ,0)
actual = apply_cx(actual,0,1)
actual = [phase*a for a in actual]
assert all(abs(a-b)<1e-12 for a,b in zip(actual,expected))
print('All four operator columns match with one common phase correction')
This test applies the original and decomposed two-qubit circuits to all four basis columns and uses the same phase correction for every column. All comparisons passed. Using a separate phase for each column would be insufficient, because it could hide a relative phase that changes superposed inputs.
The test verifies one analytical decomposition, not the unexecuted compiler’s output. It gives a concrete expected identity that explains why the requested basis can represent the Hadamard part of the example. SDK runtime validation remains a separate task in an environment where that package is available.
Equivalence after routing requires layout awareness
If a later example supplies connectivity constraints, the final physical circuit may include a nontrivial layout. Comparing its raw operator with the logical circuit without applying the recorded permutation can fail even when the compiler is correct. Conversely, ignoring an undocumented permutation can cause a real output interpretation error.
Use a layout-aware comparison method appropriate to the installed SDK, or explicitly map input and output coordinates before comparing. The official Operator interface includes methods for circuit conversion that can account for layouts, but their exact options should be checked for the selected version. The no-routing example above deliberately avoids this extra issue.
Measurements, reset, and classically conditioned operations do not generally form one unitary matrix on the original qubits. Their equivalence requires comparing channels, instruments, or specified classical output behavior. Do not remove such instructions merely to make an operator comparison pass unless that reduced circuit is the intended object of the test.
Optimization quality is a separate question
Two compiled circuits can be ideally equivalent but have different depth, two-qubit count, duration, and noise exposure. A smaller instruction count is not automatically a shorter schedule or lower physical error. A virtual phase update and a slow entangling pulse do not have equal cost merely because both occupy one instruction slot.
Higher optimization effort is not a guarantee of a better result for every target or cost objective. Heuristics may trade compiler time for a different decomposition or layout. Compare the quantities that matter for the workload and retain the compiled artifact, rather than describing an optimization level as an intrinsic hardware improvement.
Approximate synthesis introduces another distinction. If approximation is allowed, an exact-equivalence assertion may be inappropriate; a declared operator or output error tolerance is needed. The example here requests ordinary exact basis translation and uses only a floating-point tolerance for the mathematical check.
Four exercises with worked solutions
-
What common phase relates the three-gate Rz–SX–Rz sequence to H?
Solution. The sequence equals exp(−iπ/4)H. Multiplying it by exp(iπ/4) gives H exactly under the declared matrices.
-
Why test all four columns with one phase rather than four independent phases?
Solution. A unitary’s global phase is common to every input. Input-dependent phases become relative phases on superpositions and can change observable behavior.
-
Does a basis-only target prove the circuit fits a particular coupling graph?
Solution. No. It constrains operation names but does not specify which physical pairs support them. Connectivity must be supplied and checked separately.
-
Why can ideal equivalence coexist with different noisy results?
Solution. Different decompositions and schedules expose the hardware to different physical operations, durations, and correlations. The ideal unitary comparison deliberately omits those noise mechanisms.
Five explained multiple-choice questions
-
Basis translation primarily changes: A. The desired logical input distribution. B. The measurement interpretation without a map. C. The gate representation used to implement the specified operation. D. The mathematical dimension of every circuit.
Answer: C. It replaces operations with supported primitives while preserving the declared behavior.
-
The Rz–SX–Rz sequence in this lesson equals: A. H exactly with no common phase. B. exp(iπ/4)H. C. ZH with a relative sign. D. exp(−iπ/4)H.
Answer: D. Direct multiplication yields the stated negative quarter-pi common phase.
-
Operator.equiv is appropriate here because the compared objects are: A. Arbitrary noisy channels with classical outcomes. B. Unmeasured unitary circuits in the same input-output ordering. C. Histograms with finite sampling uncertainty. D. Physical calibration records from different days.
Answer: B. The chosen specification is ideal operator equivalence up to one global phase.
-
A routed circuit requires checking: A. The final layout as well as its logical action. B. Only whether it has fewer instructions. C. Only its initial diagram orientation. D. Only native-basis membership, without checking the final permutation.
Answer: A. Routing can permute where logical information resides.
-
Higher optimization level guarantees: A. Minimum possible physical runtime. B. Zero hardware noise. C. More compilation effort according to its strategy, without a universal best-output guarantee. D. Identical output circuits across all SDK releases.
Answer: C. Heuristic optimization depends on target, version, and chosen cost objective.
Pitfalls and summary
State the target and equivalence notion, preserve global phase and layouts, and separate ideal correctness from physical cost. Inspect the actual compiled circuit rather than inferring its properties from an optimization label or an unexecuted example.
Primary sources and further study
These sources support the definitions and context. The numerical examples, exercises, and explanations here were prepared for this lesson. Research papers are optional advanced reading.