Transpilation Optimizations with SABRE
Usage estimate: under one minute on a Heron r2 processor (NOTE: This is an estimate only. Your runtime might vary.)
Background
Transpilation is a critical step in Qiskit that converts quantum circuits into forms compatible with specific quantum hardware. It involves two key stages: qubit layout (mapping logical qubits to physical qubits on the device) and gate routing (ensuring multi-qubit gates respect device connectivity by inserting SWAP gates as needed).
SABRE (SWAP-Based Bidirectional heuristic search algorithm) is a powerful optimization tool for both layout and routing. It is especially effective for large-scale circuits (100+ qubits) and devices with complex coupling maps, like the IBM® Heron, where the exponential growth in possible qubit mappings demands efficient solutions.
Why use SABRE?
SABRE minimizes the number of SWAP gates and reduces circuit depth, improving circuit performance on real hardware. Its heuristic-based approach makes it ideal for advanced hardware and large, complex circuits. Recent improvements introduced in the LightSABRE algorithm further optimize SABRE’s performance, offering faster runtimes and fewer SWAP gates. These enhancements make it even more effective for large-scale circuits.
What you’ll learn
This tutorial is divided into two parts:
- Learn to use SABRE with Qiskit patterns for advanced optimization of large circuits.
- Leverage qiskit_serverless to maximize SABRE’s potential for scalable and efficient transpilation.
You will:
- Optimize SABRE for circuits with 100+ qubits, surpassing default transpilation settings like
optimization_level=3. - Explore LightSABRE enhancements that improve runtime and reduce gate counts.
- Customize key SABRE parameters (
swap_trials,layout_trials,max_iterations,heuristic) to balance circuit quality and transpilation runtime.
Requirements
Before starting this tutorial, be sure you have the following installed:
- Qiskit SDK v1.0 or later, with visualization support
- Qiskit Runtime v0.28 or later (
pip install qiskit-ibm-runtime) - Serverless (
pip install qiskit-ibm-catalog qiskit_serverless)
Setup
# Added by doQumentation — installs packages not in the Binder environment
%pip install -q qiskit-serverless
from qiskit import QuantumCircuit
from qiskit.quantum_info import SparsePauliOp
from qiskit_ibm_catalog import QiskitServerless, QiskitFunction
from qiskit_ibm_runtime import QiskitRuntimeService
from qiskit_ibm_runtime import EstimatorOptions
from qiskit_ibm_runtime import EstimatorV2 as Estimator
from qiskit.transpiler import CouplingMap
from qiskit.transpiler.passes import SabreLayout, SabreSwap
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
import matplotlib.pyplot as plt
import numpy as np
import time
Part I. Using SABRE with Qiskit patterns
SABRE can be used in Qiskit to optimize quantum circuits by handling both the qubit layout and gate routing stages. In this section, we’ll guide you through the minimal example of using SABRE with Qiskit patterns, with the primary focus on step 2 of optimization.
To run SABRE, you need:
- A DAG (Directed Acyclic Graph) representation of your quantum circuit.
- The coupling map from the backend, which specifies how qubits are physically connected.
- The SABRE pass, which applies the algorithm to optimize the layout and routing.
For this part, we’ll focus on the SabreLayout pass. It performs both layout and routing trials, working to find the most efficient initial layout while minimizing the number of SWAP gates needed. Importantly, SabreLayout, just by itself, internally optimizes both the layout and routing by storing the solution that adds the least number of SWAP gates. Note that when using just SabreLayout, we cannot change the heuristic of SABRE, but we are able to customize the number of layout_trials.
Step 1: Map classical inputs to a quantum problem
A GHZ (Greenberger-Horne-Zeilinger) circuit is a quantum circuit that prepares an entangled state where all qubits are either in the |0...0⟩ or |1...1⟩ state. The GHZ state for qubits is mathematically represented as:
It is constructed by applying:
- A Hadamard gate to the first qubit to create superposition.
- A series of CNOT gates to entangle the remaining qubits with the first.
For this example, we intentionally construct a star-topology GHZ circuit instead of a linear-topology one. In the star topology, the first qubit acts as the "hub," and all other qubits are entangled directly with it using CNOT gates. This choice is deliberate because, while the linear topology GHZ state can theoretically be implemented in depth on a linear coupling map without any SWAP gates, SABRE would trivially find an optimal solution by mapping a 100-qubit GHZ circuit to a subgraph of the backend's heavy-hex coupling map.
The star topology GHZ circuit poses a significantly more challenging problem. Although it can still theoretically be executed in depth without SWAP gates, finding this solution requires identifying an optimal initial layout, which is much harder due to the non-linear connectivity of the circuit. This topology serves as a better test case for evaluating SABRE, as it demonstrates how configuration parameters impact layout and routing performance under more complex conditions.

Notably:
- The HighLevelSynthesis tool can produce the optimal depth solution for the star topology GHZ circuit without introducing SWAP gates, like shown in the image above.
- Alternatively, the StarPrerouting pass can reduce the depth further by guiding SABRE's routing decisions, though it may still introduce some SWAP gates. However, StarPrerouting increases runtime and requires integration into the initial transpilation process.
For the purposes of this tutorial, we exclude both HighLevelSynthesis and StarPrerouting to isolate and highlight the direct impact of SABRE configuration on runtime and circuit depth. By measuring the expectation value for each qubit pair, we analyze:
- How well SABRE reduces SWAP gates and circuit depth.
- The effect of these optimizations on the fidelity of the executed circuit, where deviations from indicate loss of entanglement.!
# set seed for reproducibility
seed = 42
num_qubits = 110
# Create GHZ circuit
qc = QuantumCircuit(num_qubits)
qc.h(0)
for i in range(1, num_qubits):
qc.cx(0, i)
qc.measure_all()
Next, we will map the operators of interest to evaluate the behavior of the system. Specifically, we will use ZZ operators between qubits to examine how the entanglement degrades as the qubits become farther apart. This analysis is critical because inaccuracies in the expectation values for distant qubits can reveal the impact of noise and errors in the circuit execution. By studying these deviations, we gain insight into how well the circuit preserves entanglement under different SABRE configurations and how effectively SABRE minimizes the impact of hardware constraints.
# ZZII...II, ZIZI...II, ... , ZIII...IZ
operator_strings = [
"Z" + "I" * i + "Z" + "I" * (num_qubits - 2 - i)
for i in range(num_qubits - 1)
]
print(operator_strings)
print(len(operator_strings))
operators = [SparsePauliOp(operator) for operator in operator_strings]
['ZZIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII', 'ZIZIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII', 'ZIIZIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII', 'ZIIIZIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII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IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIZIIIII', 'ZIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIZIIII', 'ZIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIZIII', 'ZIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIZII', 'ZIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIZI', 'ZIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIZ']
109
Step 2: Optimize problem for quantum hardware execution
In this step, we focus on optimizing the circuit layout for execution on a specific quantum hardware device with 127 qubits. This is the main focus of the tutorial, as we perform SABRE optimizations and transpilation to achieve the best circuit performance. Using the SabreLayout pass, we determine an initial qubit mapping that minimizes the need for SWAP gates during routing. By passing the coupling_map of the target backend, SabreLayout adapts the layout to the device's connectivity constraints.
We will use generate_preset_pass_manager with optimization_level=3 for the transpilation process and customize the SabreLayout pass with different configurations. The goal is to find a setup that produces a transpiled circuit with the lowest size and/or depth, demonstrating the impact of SABRE optimizations.
Why Are Circuit Size and Depth Important?
- Lower size (gate count): Reduces the number of operations, minimizing opportunities for errors to accumulate.
- Lower depth: Shortens the overall execution time, which is critical for avoiding decoherence and maintaining quantum state fidelity.
By optimizing these metrics, we improve the circuit’s reliability and execution accuracy on noisy quantum hardware. Select the backend.
service = QiskitRuntimeService()
# backend = service.least_busy(
# operational=True, simulator=False, min_num_qubits=127
# )
backend = service.backend("ibm_boston")
print(f"Using backend: {backend.name}")
Using backend: ibm_boston
To evaluate the impact of different configurations on circuit optimization, we will create three pass managers, each with unique settings for the SabreLayout pass. These configurations help analyze the trade-off between circuit quality and transpilation time.
Key parameters
max_iterations: The number of forward-backward routing iterations to refine the layout and reduce routing costs.layout_trials: The number of random initial layouts tested, selecting the one that minimizes SWAP gates.swap_trials: The number of routing trials for each layout, refining gate placement for better routing.
Increase layout_trials and swap_trials to perform more thorough optimization, at the cost of increased transpilation time.
Configurations in this tutorial
-
pm_1: Default settings withoptimization_level=3.max_iterations=4layout_trials=20swap_trials=20
-
pm_2: Increases the number of trials for better exploration.max_iterations=4layout_trials=200swap_trials=200
-
pm_3: Extendspm_2by increasing the number of iterations for further refinement.max_iterations=8layout_trials=200swap_trials=200
By comparing the results of these configurations, we aim to determine which achieves the best balance between circuit quality (for example, size and depth) and computational cost.
# Get the coupling map from the backend
cmap = CouplingMap(backend().configuration().coupling_map)
# Create the SabreLayout passes for the custom configurations
sl_2 = SabreLayout(
coupling_map=cmap,
seed=seed,
max_iterations=4,
layout_trials=200,
swap_trials=200,
)
sl_3 = SabreLayout(
coupling_map=cmap,
seed=seed,
max_iterations=8,
layout_trials=200,
swap_trials=200,
)
# Create the pass managers, need to first create then configure the SabreLayout passes
pm_1 = generate_preset_pass_manager(
optimization_level=3, backend=backend, seed_transpiler=seed
)
pm_2 = generate_preset_pass_manager(
optimization_level=3, backend=backend, seed_transpiler=seed
)
pm_3 = generate_preset_pass_manager(
optimization_level=3, backend=backend, seed_transpiler=seed
)
Now we can configure the SabreLayout pass in the custom pass managers. To do this we know that for the default generate_preset_pass_manager on optimization_level=3, the SabreLayout pass is at index 2, as SabreLayout occurs after SetLayout and VF2Laout passes. We can access this pass and modify its parameters.
pm_2.layout.replace(index=2, passes=sl_2)
pm_3.layout.replace(index=2, passes=sl_3)
With each pass manager configured, we will now execute the transpilation process for each. To compare results, we will track key metrics, including the transpilation time, the depth of the circuit (measured as the two-qubit gate depth), and the total number of gates in the transpiled circuits
# Transpile the circuit with each pass manager and measure the time
t0 = time.time()
tqc_1 = pm_1.run(qc)
t1 = time.time() - t0
t0 = time.time()
tqc_2 = pm_2.run(qc)
t2 = time.time() - t0
t0 = time.time()
tqc_3 = pm_3.run(qc)
t3 = time.time() - t0
# Obtain the depths and the total number of gates (circuit size)
depth_1 = tqc_1.depth(lambda x: x.operation.num_qubits == 2)
depth_2 = tqc_2.depth(lambda x: x.operation.num_qubits == 2)
depth_3 = tqc_3.depth(lambda x: x.operation.num_qubits == 2)
size_1 = tqc_1.size()
size_2 = tqc_2.size()
size_3 = tqc_3.size()
# Transform the observables to match the backend's ISA
operators_list_1 = [op.apply_layout(tqc_1.layout) for op in operators]
operators_list_2 = [op.apply_layout(tqc_2.layout) for op in operators]
operators_list_3 = [op.apply_layout(tqc_3.layout) for op in operators]
# Compute improvements compared to pass manager 1 (default)
depth_improvement_2 = ((depth_1 - depth_2) / depth_1) * 100
depth_improvement_3 = ((depth_1 - depth_3) / depth_1) * 100
size_improvement_2 = ((size_1 - size_2) / size_1) * 100
size_improvement_3 = ((size_1 - size_3) / size_1) * 100
time_increase_2 = ((t2 - t1) / t1) * 100
time_increase_3 = ((t3 - t1) / t1) * 100
print(
f"Pass manager 1 (4,20,20) : Depth {depth_1}, Size {size_1}, Time {t1:.4f} s"
)
print(
f"Pass manager 2 (4,200,200): Depth {depth_2}, Size {size_2}, Time {t2:.4f} s"
)
print(f" - Depth improvement: {depth_improvement_2:.2f}%")
print(f" - Size improvement: {size_improvement_2:.2f}%")
print(f" - Time increase: {time_increase_2:.2f}%")
print(
f"Pass manager 3 (8,200,200): Depth {depth_3}, Size {size_3}, Time {t3:.4f} s"
)
print(f" - Depth improvement: {depth_improvement_3:.2f}%")
print(f" - Size improvement: {size_improvement_3:.2f}%")
print(f" - Time increase: {time_increase_3:.2f}%")
Pass manager 1 (4,20,20) : Depth 439, Size 2346, Time 0.5775 s
Pass manager 2 (4,200,200): Depth 395, Size 2070, Time 3.9927 s
- Depth improvement: 10.02%
- Size improvement: 11.76%
- Time increase: 591.43%
Pass manager 3 (8,200,200): Depth 375, Size 1873, Time 2.3079 s
- Depth improvement: 14.58%
- Size improvement: 20.16%
- Time increase: 299.67%
The results demonstrate that increasing the number of trials (layout_trials and swap_trials) can significantly improve circuit quality by reducing both depth and size. However, this improvement often comes at the cost of increased runtime due to the additional computation required to explore more potential layouts and routing paths.
Increasing the max_iterations can further enhance optimization by refining the layout through more forward-backward routing cycles. In this case, increasing max_iterations resulted in the most significant reduction in circuit depth and size, even reducing runtime compared to pm_2, likely by streamlining subsequent optimization stages. It’s important to note, however, that the effectiveness of increasing max_iterations can vary significantly depending on the circuit. While more iterations may yield better layout and routing choices, they provide no guarantees and depend heavily on the circuit’s structure and the complexity of the connectivity constraints
# Plot the results of the metrics
times = [t1, t2, t3]
depths = [depth_1, depth_2, depth_3]
sizes = [size_1, size_2, size_3]
pm_names = [
"pm_1 (4 iter, 20 trials)",
"pm_2 (4 iter, 200 trials)",
"pm_3 (8 iter, 200 trials)",
]
colors = plt.cm.viridis(np.linspace(0.2, 0.8, len(pm_names)))
# Create a figure with three subplots
fig, axs = plt.subplots(3, 1, figsize=(6, 9), sharex=True)
axs[0].bar(pm_names, times, color=colors)
axs[0].set_ylabel("Time (s)", fontsize=12)
axs[0].set_title("Transpilation Time", fontsize=14)
axs[0].grid(axis="y", linestyle="--", alpha=0.7)
axs[1].bar(pm_names, depths, color=colors)
axs[1].set_ylabel("Depth", fontsize=12)
axs[1].set_title("Circuit Depth", fontsize=14)
axs[1].grid(axis="y", linestyle="--", alpha=0.7)
axs[2].bar(pm_names, sizes, color=colors)
axs[2].set_ylabel("Size", fontsize=12)
axs[2].set_title("Circuit Size", fontsize=14)
axs[2].set_xticks(range(len(pm_names)))
axs[2].set_xticklabels(pm_names, fontsize=10, rotation=15)
axs[2].grid(axis="y", linestyle="--", alpha=0.7)
# Add some spacing between subplots
plt.tight_layout()
plt.show()
Step 3: Execute using Qiskit primitives
In this step, we use the Estimator primitive to calculate the expectation values for the ZZ operators, evaluating the entanglement and execution quality of the transpiled circuits. To align with typical user workflows, we submit the job for execution and apply error suppression using dynamical decoupling, a technique that mitigates decoherence by inserting gate sequences to preserve qubit states. Additionally, we specify a resilience level to counteract noise, with higher levels providing more accurate results at the cost of increased processing time. This approach assesses the performance of each pass manager configuration under realistic execution conditions.
options = EstimatorOptions()
options.resilience_level = 2
options.dynamical_decoupling.enable = True
options.dynamical_decoupling.sequence_type = "XY4"
# Create an Estimator object
estimator = Estimator(backend, options=options)
# Submit the circuit to Estimator
job_1 = estimator.run([(tqc_1, operators_list_1)])
job_1_id = job_1.job_id()
print(job_1_id)
job_2 = estimator.run([(tqc_2, operators_list_2)])
job_2_id = job_2.job_id()
print(job_2_id)
job_3 = estimator.run([(tqc_3, operators_list_3)])
job_3_id = job_3.job_id()
print(job_3_id)
d5k0qs7853es738dab6g
d5k0qsf853es738dab70
d5k0qsf853es738dab7g
# Run the jobs
result_1 = job_1.result()[0]
print("Job 1 done")
result_2 = job_2.result()[0]
print("Job 2 done")
result_3 = job_3.result()[0]
print("Job 3 done")
Job 1 done
Job 2 done
Job 3 done
Step 4: Post-process and return result in desired classical format
Once the job completes, we analyze the results by plotting the expectation values for each qubit. In an ideal simulation, all values should be 1, reflecting perfect entanglement across the qubits. However, due to noise and hardware constraints, the expectation values typically decrease as i increases, revealing how entanglement degrades over distance.
In this step, we compare the results from each pass manager configuration to the ideal simulation. By examining the deviation of