Skill Tracer
Skills › Scientific Agent Skills › qiskit › transpilation.md

transpilation.md

333 lines · skills/qiskit/references/transpilation.md at 5f2bc03

Open on GitHub
1# Target-Aware Transpilation
2
3Transpilation rewrites an abstract circuit into an **instruction set architecture (ISA) circuit** that satisfies a specific backend `Target`:
4
5- only supported instructions,
6- valid qubit operands and connectivity,
7- backend timing and control-flow constraints,
8- an explicit virtual-to-physical qubit layout.
9
10IBM Runtime V2 primitives require ISA circuits. They do not perform layout, routing, and basis translation automatically.

Target-Aware Transpilation

Transpilation rewrites an abstract circuit into an instruction set architecture (ISA) circuit that satisfies a specific backend Target:

  • only supported instructions,
  • valid qubit operands and connectivity,
  • backend timing and control-flow constraints,
  • an explicit virtual-to-physical qubit layout.

IBM Runtime V2 primitives require ISA circuits. They do not perform layout, routing, and basis translation automatically.

Raw lines 1 to 11
12## Recommended Entry Point
14Use a preset staged pass manager:
16```python
17from qiskit.transpiler import generate_preset_pass_manager
19pass_manager = generate_preset_pass_manager(
20 backend=backend,
21 optimization_level=1,
22 seed_transpiler=17,
24isa_circuit = pass_manager.run(circuit)
25```
27The pass manager can be reused for circuits targeting the same backend snapshot:
29```python
30isa_circuits = pass_manager.run(circuits)
31```
33`qiskit.transpile()` remains a convenient wrapper, but a pass manager is easier to reuse, inspect, and customize.

Recommended Entry Point

Use a preset staged pass manager:

from qiskit.transpiler import generate_preset_pass_manager

pass_manager = generate_preset_pass_manager(
    backend=backend,
    optimization_level=1,
    seed_transpiler=17,
)
isa_circuit = pass_manager.run(circuit)

The pass manager can be reused for circuits targeting the same backend snapshot:

isa_circuits = pass_manager.run(circuits)

qiskit.transpile() remains a convenient wrapper, but a pass manager is easier to reuse, inspect, and customize.

Raw lines 12 to 34
35## The BackendV2 Target
37`backend.target` is the source of supported operations and constraints:
39```python
40print("backend:", backend.name)
41print("qubits:", backend.num_qubits)
42print("operations:", sorted(backend.operation_names))
43print("coupling map:", backend.coupling_map)
44print("target:", backend.target)
45```
47Do not use these removed or legacy BackendV1 access patterns:
49```python
50# Do not use in Qiskit 2.x code:
51# backend.configuration().basis_gates
52# backend.properties()
53# BackendProperties
54```
56For a synthetic target:
58```python
59from qiskit.transpiler import CouplingMap, Target
61target = Target.from_configuration(
62 basis_gates=["cz", "sx", "rz"],
63 coupling_map=CouplingMap.from_line(5),
65pass_manager = generate_preset_pass_manager(
66 target=target,
67 optimization_level=1,
68 seed_transpiler=17,
70isa_circuit = pass_manager.run(circuit)
71```
73Prefer one coherent `backend` or `target`. Combining a backend with separate `basis_gates` or `coupling_map` inputs creates competing sources of truth and is discouraged.

The BackendV2 Target

backend.target is the source of supported operations and constraints:

print("backend:", backend.name)
print("qubits:", backend.num_qubits)
print("operations:", sorted(backend.operation_names))
print("coupling map:", backend.coupling_map)
print("target:", backend.target)

Do not use these removed or legacy BackendV1 access patterns:

# Do not use in Qiskit 2.x code:
# backend.configuration().basis_gates
# backend.properties()
# BackendProperties

For a synthetic target:

from qiskit.transpiler import CouplingMap, Target

target = Target.from_configuration(
    basis_gates=["cz", "sx", "rz"],
    coupling_map=CouplingMap.from_line(5),
)
pass_manager = generate_preset_pass_manager(
    target=target,
    optimization_level=1,
    seed_transpiler=17,
)
isa_circuit = pass_manager.run(circuit)

Prefer one coherent backend or target. Combining a backend with separate basis_gates or coupling_map inputs creates competing sources of truth and is discouraged.

Raw lines 35 to 74
75## Preset Optimization Levels
77| Level | Typical intent |
78|---:|---|
79| 0 | Minimal transformation needed to satisfy the target |
80| 1 | Light optimization with relatively low compilation cost |
81| 2 | More optimization and search |
82| 3 | Heavier optimization and search; highest classical cost |
84Higher does not guarantee a better experimental result. Compare levels using the same circuit, target snapshot, and seed:
86```python
87compiled = {}
88for level in (0, 1, 2, 3):
89 manager = generate_preset_pass_manager(
90 backend=backend,
91 optimization_level=level,
92 seed_transpiler=17,
93 )
94 compiled[level] = manager.run(circuit)
95```
97Start with levels 1 and 3 for a bounded comparison. Evaluate target-native two-qubit operations, depth, estimated duration when available, and downstream result quality.

Preset Optimization Levels

LevelTypical intent
0Minimal transformation needed to satisfy the target
1Light optimization with relatively low compilation cost
2More optimization and search
3Heavier optimization and search; highest classical cost

Higher does not guarantee a better experimental result. Compare levels using the same circuit, target snapshot, and seed:

compiled = {}
for level in (0, 1, 2, 3):
    manager = generate_preset_pass_manager(
        backend=backend,
        optimization_level=level,
        seed_transpiler=17,
    )
    compiled[level] = manager.run(circuit)

Start with levels 1 and 3 for a bounded comparison. Evaluate target-native two-qubit operations, depth, estimated duration when available, and downstream result quality.

Raw lines 75 to 98
99## Transpiler Stages
101A preset `StagedPassManager` has six conceptual stages:
1031. **init**: validate and synthesize high-level operations.
1042. **layout**: map virtual qubits to physical qubits.
1053. **routing**: add routing operations to satisfy connectivity.
1064. **translation**: convert to target-supported instructions.
1075. **optimization**: simplify and resynthesize the target circuit.
1086. **scheduling**: apply hardware-aware timing passes when configured.
110Qiskit 2.x scheduling does not restore `qiskit.pulse`; that module was removed.
112Inspect the generated manager:
114```python
115print(pass_manager)
116print(pass_manager.property_set)
117```
119The property set is primarily a pass-development and debugging interface; do not build long-term application logic around undocumented keys.

Transpiler Stages

A preset StagedPassManager has six conceptual stages:

  1. init: validate and synthesize high-level operations.
  2. layout: map virtual qubits to physical qubits.
  3. routing: add routing operations to satisfy connectivity.
  4. translation: convert to target-supported instructions.
  5. optimization: simplify and resynthesize the target circuit.
  6. scheduling: apply hardware-aware timing passes when configured.

Qiskit 2.x scheduling does not restore qiskit.pulse; that module was removed.

Inspect the generated manager:

print(pass_manager)
print(pass_manager.property_set)

The property set is primarily a pass-development and debugging interface; do not build long-term application logic around undocumented keys.

Raw lines 99 to 120
121## Layouts and Observables
123Transpilation can permute logical qubits. Estimator observables must be mapped to the final physical layout:
125```python
126from qiskit.quantum_info import SparsePauliOp
128observable = SparsePauliOp.from_list([("ZZ", 1.0)])
129isa_circuit = pass_manager.run(circuit)
130isa_observable = observable.apply_layout(isa_circuit.layout)
131```
133Submit the mapped observable:
135```python
136pub = (isa_circuit, isa_observable, parameter_values)
137```
139Do not manually guess the permutation from a circuit drawing. Use `isa_circuit.layout`.
141For a list of observables:
143```python
144isa_observables = [
145 observable.apply_layout(isa_circuit.layout)
146 for observable in observables
148```

Layouts and Observables

Transpilation can permute logical qubits. Estimator observables must be mapped to the final physical layout:

from qiskit.quantum_info import SparsePauliOp

observable = SparsePauliOp.from_list([("ZZ", 1.0)])
isa_circuit = pass_manager.run(circuit)
isa_observable = observable.apply_layout(isa_circuit.layout)

Submit the mapped observable:

pub = (isa_circuit, isa_observable, parameter_values)

Do not manually guess the permutation from a circuit drawing. Use isa_circuit.layout.

For a list of observables:

isa_observables = [
    observable.apply_layout(isa_circuit.layout)
    for observable in observables
]
Raw lines 121 to 149
150## Parameterized Workloads
152Transpile the parameterized circuit once:
154```python
155parameterized_isa = pass_manager.run(parameterized_circuit)
156isa_observable = observable.apply_layout(parameterized_isa.layout)
158for values in optimizer_values:
159 pub = (parameterized_isa, isa_observable, [values])
160 result = estimator.run([pub], precision=0.03).result()[0]
161```
163This avoids repeated layout and routing. Retranspile only when the circuit structure, target, selected backend feature set, or compilation strategy changes.

Parameterized Workloads

Transpile the parameterized circuit once:

parameterized_isa = pass_manager.run(parameterized_circuit)
isa_observable = observable.apply_layout(parameterized_isa.layout)

for values in optimizer_values:
    pub = (parameterized_isa, isa_observable, [values])
    result = estimator.run([pub], precision=0.03).result()[0]

This avoids repeated layout and routing. Retranspile only when the circuit structure, target, selected backend feature set, or compilation strategy changes.

Raw lines 150 to 164
165## Initial Layouts
167Use an explicit layout only when calibration analysis or a reproducibility requirement justifies it:
169```python
170pass_manager = generate_preset_pass_manager(
171 backend=backend,
172 optimization_level=2,
173 initial_layout=[3, 5, 8],
174 seed_transpiler=17,
176```
178An explicit layout bypasses the preset layout-selection logic. Confirm every physical qubit and interaction is supported by the target.

Initial Layouts

Use an explicit layout only when calibration analysis or a reproducibility requirement justifies it:

pass_manager = generate_preset_pass_manager(
    backend=backend,
    optimization_level=2,
    initial_layout=[3, 5, 8],
    seed_transpiler=17,
)

An explicit layout bypasses the preset layout-selection logic. Confirm every physical qubit and interaction is supported by the target.

Raw lines 165 to 179
180## Approximate Synthesis
182`approximation_degree` trades unitary fidelity for potentially cheaper circuits:
184```python
185pass_manager = generate_preset_pass_manager(
186 backend=backend,
187 optimization_level=3,
188 approximation_degree=0.99,
189 seed_transpiler=17,
191```
193Treat approximation as an experimental parameter. Compare ideal-unitary error, native two-qubit count, and hardware outcome. Do not describe `0.99` as a universal one-percent error bound for the whole algorithm.

Approximate Synthesis

approximation_degree trades unitary fidelity for potentially cheaper circuits:

pass_manager = generate_preset_pass_manager(
    backend=backend,
    optimization_level=3,
    approximation_degree=0.99,
    seed_transpiler=17,
)

Treat approximation as an experimental parameter. Compare ideal-unitary error, native two-qubit count, and hardware outcome. Do not describe 0.99 as a universal one-percent error bound for the whole algorithm.

Raw lines 180 to 194
195## Reproducibility
197Set the transpiler seed explicitly:
199```python
200pass_manager = generate_preset_pass_manager(
201 backend=backend,
202 optimization_level=3,
203 seed_transpiler=17,
205```
207Qiskit 2.5 also supports `QISKIT_TRANSPILER_SEED`, but an explicit argument is clearer in reproducible code.
209Record:
211- Qiskit version,
212- backend name and target/calibration timestamp if available,
213- optimization level,
214- seed,
215- all non-default pass-manager arguments,
216- input and output QPY artifacts,
217- output layout and structural metrics.
219A fixed seed stabilizes stochastic compiler choices; it does not freeze changing backend calibration data or package behavior across releases.

Reproducibility

Set the transpiler seed explicitly:

pass_manager = generate_preset_pass_manager(
    backend=backend,
    optimization_level=3,
    seed_transpiler=17,
)

Qiskit 2.5 also supports QISKIT_TRANSPILER_SEED, but an explicit argument is clearer in reproducible code.

Record:

  • Qiskit version,
  • backend name and target/calibration timestamp if available,
  • optimization level,
  • seed,
  • all non-default pass-manager arguments,
  • input and output QPY artifacts,
  • output layout and structural metrics.

A fixed seed stabilizes stochastic compiler choices; it does not freeze changing backend calibration data or package behavior across releases.

Raw lines 195 to 220
221## Analyze Compiled Circuits
223```python
224def two_qubit_instruction_count(circuit):
225 return sum(
226 len(item.qubits) == 2
227 for item in circuit.data
228 )
230print("logical depth:", circuit.depth())
231print("ISA depth:", isa_circuit.depth())
232print("ISA size:", isa_circuit.size())
233print("ISA operations:", isa_circuit.count_ops())
234print("two-qubit instructions:", two_qubit_instruction_count(isa_circuit))
235print("layout:", isa_circuit.layout)
236```
238Count all two-qubit instructions rather than only `cx`; current targets may use `cz`, `ecr`, `rzz`, or other operations.
240Circuit metrics are proxies. Calibration-aware quality depends on which physical qubits and operations were selected.

Analyze Compiled Circuits

def two_qubit_instruction_count(circuit):
    return sum(
        len(item.qubits) == 2
        for item in circuit.data
    )

print("logical depth:", circuit.depth())
print("ISA depth:", isa_circuit.depth())
print("ISA size:", isa_circuit.size())
print("ISA operations:", isa_circuit.count_ops())
print("two-qubit instructions:", two_qubit_instruction_count(isa_circuit))
print("layout:", isa_circuit.layout)

Count all two-qubit instructions rather than only cx; current targets may use cz, ecr, rzz, or other operations.

Circuit metrics are proxies. Calibration-aware quality depends on which physical qubits and operations were selected.

Raw lines 221 to 241
242## Verify ISA Compatibility
244Runtime rejects circuits that do not satisfy the target. A practical preflight is:
2461. Compile using the exact backend.
2472. Confirm the compiled width fits `backend.num_qubits`.
2483. Inspect every instruction name and qubit tuple against `backend.target`.
2494. Submit only the pass-manager output.
251For advanced validation, use target APIs rather than a hardcoded basis list.

Verify ISA Compatibility

Runtime rejects circuits that do not satisfy the target. A practical preflight is:

  1. Compile using the exact backend.
  2. Confirm the compiled width fits backend.num_qubits.
  3. Inspect every instruction name and qubit tuple against backend.target.
  4. Submit only the pass-manager output.

For advanced validation, use target APIs rather than a hardcoded basis list.

Raw lines 242 to 252
253## Fake Backends and Aer
255Test target-aware compilation without consuming QPU time:
257```python
258from qiskit.transpiler import generate_preset_pass_manager
259from qiskit_ibm_runtime.fake_provider import FakeSherbrooke
261fake_backend = FakeSherbrooke()
262pass_manager = generate_preset_pass_manager(
263 backend=fake_backend,
264 optimization_level=1,
265 seed_transpiler=17,
267isa_circuit = pass_manager.run(circuit)
268```
270Fake-backend availability can change between Runtime releases. List the installed fake-provider exports rather than assuming an old tutorial backend exists.
272For an Aer noise model derived from a real backend:
274```python
275from qiskit_aer import AerSimulator
277noisy_simulator = AerSimulator.from_backend(backend)
278simulator_pass_manager = generate_preset_pass_manager(
279 backend=noisy_simulator,
280 optimization_level=1,
281 seed_transpiler=17,
283simulator_circuit = simulator_pass_manager.run(circuit)
284```
286An Aer model is an approximation of the calibration data used to create it; it is not a faithful predictor of every QPU effect.

Fake Backends and Aer

Test target-aware compilation without consuming QPU time:

from qiskit.transpiler import generate_preset_pass_manager
from qiskit_ibm_runtime.fake_provider import FakeSherbrooke

fake_backend = FakeSherbrooke()
pass_manager = generate_preset_pass_manager(
    backend=fake_backend,
    optimization_level=1,
    seed_transpiler=17,
)
isa_circuit = pass_manager.run(circuit)

Fake-backend availability can change between Runtime releases. List the installed fake-provider exports rather than assuming an old tutorial backend exists.

For an Aer noise model derived from a real backend:

from qiskit_aer import AerSimulator

noisy_simulator = AerSimulator.from_backend(backend)
simulator_pass_manager = generate_preset_pass_manager(
    backend=noisy_simulator,
    optimization_level=1,
    seed_transpiler=17,
)
simulator_circuit = simulator_pass_manager.run(circuit)

An Aer model is an approximation of the calibration data used to create it; it is not a faithful predictor of every QPU effect.

Raw lines 253 to 287
288## Dynamic Circuits and Fractional Gates
290Backend capabilities can depend on how the backend is requested:
292```python
293backend = service.backend(
294 backend_name,
295 use_fractional_gates=True,
297```
299Fractional-gate support and dynamic-control support have evolved across Runtime versions. The actual service keyword is `use_fractional_gates=True`; the fractional-gates guide currently contains a `fractional_gates=True` typo. Parameterized `rzz` angles must satisfy the returned target bounds (currently `[0, pi/2]` in the Runtime validator); parameter values outside the range are not repaired by compiling the symbolic circuit once. Inspect the returned target and current feature-compatibility documentation instead of assuming both are available for every backend and option combination.
301If a circuit uses `if_else`, `while_loop`, `switch_case`, `for_loop`, or classical expressions:
303- confirm the operations are present in `backend.operation_names`,
304- compile against that returned backend object,
305- check mitigation and fractional-gate compatibility,
306- test the full branch behavior.

Dynamic Circuits and Fractional Gates

Backend capabilities can depend on how the backend is requested:

backend = service.backend(
    backend_name,
    use_fractional_gates=True,
)

Fractional-gate support and dynamic-control support have evolved across Runtime versions. The actual service keyword is use_fractional_gates=True; the fractional-gates guide currently contains a fractional_gates=True typo. Parameterized rzz angles must satisfy the returned target bounds (currently [0, pi/2] in the Runtime validator); parameter values outside the range are not repaired by compiling the symbolic circuit once. Inspect the returned target and current feature-compatibility documentation instead of assuming both are available for every backend and option combination.

If a circuit uses if_else, while_loop, switch_case, for_loop, or classical expressions:

  • confirm the operations are present in backend.operation_names,
  • compile against that returned backend object,
  • check mitigation and fractional-gate compatibility,
  • test the full branch behavior.
Raw lines 288 to 307
308## Custom Pass Managers
310Customize only after measuring a limitation in preset output:
312```python
313from qiskit.transpiler import PassManager
314from qiskit.transpiler.passes import RemoveBarriers
316cleanup = PassManager([RemoveBarriers()])
317cleaned = cleanup.run(circuit)
318```
320For target-aware custom pipelines, use `StagedPassManager` or modify a generated preset stage. Every custom transformation must preserve circuit semantics, parameters, control flow, and global phase as appropriate.
322Write regression tests based on operator/state equivalence for small circuits and application-level outputs for larger circuits.

Custom Pass Managers

Customize only after measuring a limitation in preset output:

from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import RemoveBarriers

cleanup = PassManager([RemoveBarriers()])
cleaned = cleanup.run(circuit)

For target-aware custom pipelines, use StagedPassManager or modify a generated preset stage. Every custom transformation must preserve circuit semantics, parameters, control flow, and global phase as appropriate.

Write regression tests based on operator/state equivalence for small circuits and application-level outputs for larger circuits.

Raw lines 308 to 323
324## Common Failures
326- **Circuit not ISA-compatible**: submit the pass-manager output, not the abstract input.
327- **Wrong expectation value**: map the observable through `isa_circuit.layout`.
328- **Too many routing operations**: compare layout methods, seeds, initial layouts, and circuit connectivity.
329- **Compilation is slow**: lower the optimization level or reduce repeated transpilation.
330- **BackendV1 attribute error**: replace `configuration()` and `properties()` access with BackendV2 target and direct attributes.
331- **Unknown instruction**: inspect the exact backend target; do not use a generic basis copied from another device.
332- **Dynamic-circuit rejection**: verify target control-flow operations and incompatible backend feature flags.
333- **Non-reproducible comparison**: fix the seed and backend snapshot, and store all compiler settings.

Common Failures

  • Circuit not ISA-compatible: submit the pass-manager output, not the abstract input.
  • Wrong expectation value: map the observable through isa_circuit.layout.
  • Too many routing operations: compare layout methods, seeds, initial layouts, and circuit connectivity.
  • Compilation is slow: lower the optimization level or reduce repeated transpilation.
  • BackendV1 attribute error: replace configuration() and properties() access with BackendV2 target and direct attributes.
  • Unknown instruction: inspect the exact backend target; do not use a generic basis copied from another device.
  • Dynamic-circuit rejection: verify target control-flow operations and incompatible backend feature flags.
  • Non-reproducible comparison: fix the seed and backend snapshot, and store all compiler settings.
Raw lines 324 to 333