Algorithmresearch
SABRE
Also called SWAP-based bidirectional heuristic search.
Li, Ding and Xie's qubit mapper. It adds one SWAP at a time by a lookahead score over the front layer, and finds the initial mapping by forward and backward passes.
- Solves
- Qubit mapping
- Time
- O(N (N + m)) distancesO(g (l + N) N D (N + e)) one passO(N D (N + e)) one search step
- Space
- O(N^2 + g) total
- Where
- D = the largest degree of the coupling graph; N = the number of physical qubits; e = the size of the extended set; g = the number of gates; l = the limit of SWAPs in a row before the release valve; m = the number of coupling edges; n = the number of logical qubits
- Model
- Word RAM
- Properties
- randomizednot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Gushu Li, Yufei Ding, Yuan Xie, 2019
SABRE (SWAP-based BidiREctional heuristic search) is a heuristic for qubit mapping, by Gushu Li, Yufei Ding and Yuan Xie (ASPLOS 2019). It takes a quantum circuit and a coupling graph and inserts SWAP gates so that every two-qubit gate runs on coupled physical qubits. It walks the dependence graph of the circuit, runs every gate it can, and when it is stuck adds the one SWAP that most lowers a score: the mean distance of the gates that are waiting, plus a smaller weight times the mean distance of the next gates. It finds a good initial mapping by running the same search forward over the circuit, then backward over the reversed circuit, and taking the final mapping as the new start. Each step looks only at SWAPs next to waiting qubits, not at whole mappings, so it scales to large devices.
In plain words
You have people at seats around a table, a script of conversations in order, and the rule that only neighbors can talk. SABRE reads the script and lets every conversation happen whose two people are neighbors and whose earlier lines are done. When nobody waiting can talk, it tries each exchange of seats between a waiting person and a neighbor, and picks the one that brings the waiting pairs closest, with a small bonus for bringing the next few pairs closer as well. Then it repeats.
To choose the first seating, it plays the whole script once from a random seating, then plays it backward from where everyone ended up. The seating at the end of the backward run is good for the start of the script, so it is used for the real run.
The problem
Given a circuit on logical qubits and a connected coupling graph on physical qubits, find an initial mapping and a sequence of gates and SWAPs on the edges of that runs the circuit, with few SWAPs. The problem page defines it, shows that it is NP-complete, and defines SWAP as three CNOTs.
The algorithm
The search works on the dependence DAG of the circuit: gate depends on gate if is the last gate before on one of 's qubits. The front layer is the set of gates whose predecessors have all run. The extended set is the next two-qubit gates after in the DAG. is the distance of and in , so SWAPs bring two qubits next to each other. With the current mapping, the score of a candidate SWAP (Equation 2 of the paper) is
where is the mapping after the SWAP on , , and is for a qubit not in a recent SWAP and rises by for each recent one, so the search favors SWAPs on other qubits, which can run at the same time.
SABRE(C, G, trials, traversals)- 1
compute the distance matrix D of G by breadth-first search from every vertex - 2
for each trial: choose a random initial mapping π - 3
run SWAP-SEARCH on C from π, then on the reverse of C from the final mapping, and so on for traversals − 1 passes; π is the last final mapping - 4
run SWAP-SEARCH on C from π; keep the output with the fewest SWAPs and its initial mapping π - 5
return the best output, its initial mapping and its final mapping SWAP-SEARCH(C, π)- 6
F ← the gates of C with no predecessor - 7
while F is not empty: - 8
if some gate of F is ready (one qubit, or its two qubits adjacent under π): run every ready gate, move to F the successors whose predecessors have all run, reset the decay, and continue - 9
if l SWAPs in a row have run no gate: move one qubit of the closest gate of F along a shortest path until the gate is ready (the release valve), and continue - 10
E ← the first e two-qubit gates after F in the DAG - 11
for each SWAP on an edge of G that touches a qubit of a gate in F: compute its score H - 12
apply the SWAP of least score to π (ties at random), emit it, and raise the decay of its two qubits
The reverse traversal. A circuit read backward has the same dependences reversed, and the mapping at the end of a forward pass suits the last gates. A backward pass from it ends in a mapping that suits the first gates, and it has seen the whole circuit on the way. The paper runs three passes (forward, backward, forward), five times from different random mappings, and keeps the best.
The release valve. The paper does not show that SWAP-SEARCH ends, and the score can choose SWAPs that run no gate; LightSABRE (2024) reports such cases and adds a release valve. The code adds a rule of this kind on line L9. After SWAPs in a row with no gate run ( by default), it walks one qubit of the closest waiting gate along a shortest path, which makes that gate ready. This bounds the SWAPs, and the proof uses it. In the random tests, it never fired with the default limit.
The code. It follows Algorithm 1 and Equation 2, with , and as in the paper, and resets the decay after a gate runs or every 5 SWAPs. One-qubit gates are kept in the DAG and run as soon as they reach . It uses breadth-first search for instead of Floyd-Warshall, since the graph has no weights. It builds the extended set again at each step, which costs ; a real tool keeps it up to date.
Example
Take the line , logical qubits on , and the circuit , then . No gate is ready: at distance 2, and . The candidate SWAPs touch or :
| SWAP | term | term with | |
|---|---|---|---|
| , to | 1 | 2 | |
| , to | 1 | 2.5 | |
| , to | 3 | 4 |
SABRE picks , runs on , then needs one more SWAP for : 2 SWAPs. Without lookahead () the first two SWAPs tie at 1, and the second one leads to 3 SWAPs. Neither is the best: the interaction graph is the path , which fits on the line with in the middle, so the right initial mapping needs no SWAP. The forward pass ends with in the middle of and , for example on , so the backward pass starts from a mapping with no SWAP needed, and the full SABRE returns an output with 0 SWAPs. The test file checks all of this.
Correctness
The proof file proves three things for the code. First, every pass ends, with at most SWAPs for two-qubit gates, because of the release valve. Second, every two-qubit gate of the output, SWAPs included, acts on an edge of , and every gate of runs exactly once, after its predecessors. Third, the output is equivalent to up to the final permutation: with the map that puts each logical qubit on its physical qubit and the free physical qubits in , the output satisfies . The proof uses two facts: a gate on logical qubits under is the same gate on 's physical qubits, and a SWAP on only changes the mapping. Any order of the gates that respects the DAG gives the same operation, because gates that change places share no qubit and commute. Nothing is proved about the number of SWAPs beyond the upper bound.
Proof: SABRE ends and its output is equivalent to the input circuitfull
This file proves, for the code of this page, that every pass of SWAP-SEARCH ends with a bounded number of SWAPs, that every two-qubit operation of its output acts on a coupling edge, and that the output computes the input circuit up to the initial and final permutations. Nothing here is about how many SWAPs SABRE uses compared with the optimum.
Setting. The input is a circuit on logical qubits , each gate on one or two qubits, and a connected coupling graph on physical qubits with . A mapping is an injective . Gate depends on if and is the last gate before on one of 's qubits; this gives the DAG. is the number of two-qubit gates, is the distance in , and is the limit of the release valve.
Termination
Lemma 1 (SWAPs touch occupied qubits). Every candidate SWAP of line L11 is an edge of with at least one end that holds a logical qubit.
Proof. Line L11 takes the edges of where for a qubit of a gate in . ∎
Lemma 2 (when SWAPs happen, F holds only waiting two-qubit gates). Whenever lines L9 to L12 run, every gate of is a two-qubit gate whose qubits are at distance at least 2.
Proof. Line L8 runs before them in the same iteration and runs every ready gate. If any gate of were ready, L8 would have run it and gone to the next iteration. A one-qubit gate is always ready. ∎
Theorem 3 (every pass ends). SWAP-SEARCH ends after at most gate runs and at most SWAPs.
Proof. Each gate enters once, when its last predecessor runs, and leaves it once, when it runs; so there are gate runs. Call a stall a maximal run of iterations in which no gate runs. During a stall, the counter of SWAPs in a row grows by one at each L12. When it reaches , line L9 takes the gate of of least distance (Lemma 2), and moves along a shortest path: each SWAP is on an edge with , and such a exists on every shortest path. After SWAPs, and are adjacent, and since no other gate ran, the gate is still in , so the next L8 runs it. So every stall has at most SWAPs and ends with a gate run. By Lemma 2, holds a two-qubit gate during each stall, and this gate or another two-qubit gate runs at its end, so there are at most stalls. While is not empty and no stall is going on, line L8 runs a gate in each iteration. So the loop ends after at most iterations of L8 and SWAPs. ∎
SABRE runs SWAP-SEARCH a fixed number of times (trials times traversals), so it ends as well.
The output is valid
Lemma 4 (order). The gates of run in an order that is a linear extension of the DAG, each exactly once.
Proof. A gate enters only when its count of predecessors not yet run reaches 0, so it runs after all of them. By Theorem 3 and the end condition , every gate enters and leaves , so every gate runs exactly once. ∎
Lemma 5 (edges). Every SWAP of the output is on an edge of , and every two-qubit gate of runs on physical qubits joined by an edge.
Proof. SWAPs come from line L11 (Lemma 1) or from the shortest-path walk of L9, which uses edges of . Line L8 runs a two-qubit gate on only when , that is, when they are joined by an edge. ∎
The output is equivalent
Take the state space of the physical qubits. For a mapping , let be the linear map from the logical qubits to the physical qubits that puts logical qubit on physical qubit and the other physical qubits in :
For a gate on logical qubits , write for it on the logical register and for the same gate on the physical qubits , in the same order.
Lemma 6 (gates move through the mapping). .
Proof. is a relabeling of tensor factors followed by adding factors in . Under it, the factors of become the factors of , so a gate on before the map is the same gate on after it, and the added factors are not touched. ∎
Lemma 7 (a SWAP only changes the mapping). Let be an edge and the transposition of and . Then .
Proof. exchanges the values of qubits and in every basis state. Applied to , the value that was on (logical if , or 0 if is free) moves to , and the other way round, so the result puts logical qubit on and keeps the free qubits in . That is , and both sides are linear. ∎
This is the same update the code makes in apply_swap, so after each SWAP the variable layout is . Lemma 7 also holds for SWAP written as three CNOTs, since the CNOT page proves that .
Lemma 8 (reordering). Let be the order in which the gates of run. Then as operators.
Proof. By Lemma 4, is a linear extension of the DAG, and so is the original order. Any two linear extensions of a partial order are joined by a series of exchanges of two adjacent elements that are not comparable (bubble sort one into the other: when two adjacent gates are out of order with respect to the target, the target puts them in the other order, so neither precedes the other in the partial order). Two gates not comparable in the DAG share no qubit, since two gates on a common qubit are joined by the chain of gates on that qubit. Gates on disjoint qubits commute. So each exchange keeps the product, and the two products are equal. ∎
Theorem 9 (equivalence up to the final permutation). Let be the output of SWAP-SEARCH from , with final mapping , as an operator on the physical qubits. Then
Proof. Write the output as operations , with mappings , where is the mapping after . Let be the product, in run order, of the gates of among . We show by induction on . For both sides are . If is a SWAP on , then , , and Lemma 7 gives . If runs gate on , the code emits it on , the mapping does not change, and Lemma 6 gives . At , is the product of all gates of in run order, which equals by Lemma 8. ∎
So the output, started with logical qubit on and the free qubits in , ends with the state that produces, with logical qubit on and the free qubits back in . A measurement of logical qubit reads physical qubit . This holds for every pass, including the backward ones, since a backward pass is SWAP-SEARCH on the reversed circuit; SABRE returns the output of a forward pass, so it is the circuit .
What the tests check
The test file checks the statements of Lemmas 4 and 5 on random circuits on lines, stars, grids and trees, and checks Theorem 9 directly: for CNOT and X circuits it compares the output, with each SWAP expanded into three CNOTs, against on every basis state, which decides the equality since both sides map basis states to basis states; for circuits with H, T and CNOT it compares every column of the two operators by state vector simulation. It also checks the bound of Theorem 3 with several limits , including , where the search is the plain walk along shortest paths.
Complexity
Breadth-first search from each vertex gives in . In a search step, holds at most two-qubit gates, so there are at most candidate SWAPs, and each costs to score: per step. Each run of SWAPs between two gate runs has at most SWAPs, and there are at most runs, so a pass costs in the worst case. The paper argues that a gate needs at most about the diameter of in SWAPs, for a 2D grid, which gives its bound of ; that argument assumes every SWAP makes progress, which the score does not promise without a rule like the release valve. Space is for and for the DAG.
Properties
What is proved. Each pass ends with at most SWAPs; every two-qubit operation of the output is on a coupling edge; and the output equals the input circuit up to the initial and final permutations. The proof file has the details.
What is cited. Li, Ding and Xie (Section V) test on the 20-qubit IBM Q20 Tokyo coupling graph against BKA, the layered A* method of Zulehner, Paler and Wille. On small benchmarks, SABRE finds mappings with no or few added gates: the added gates fall by 91% or vanish, against BKA. On large ones, it adds about 10% fewer gates on average, and runs where BKA runs out of memory. With the decay parameter, the depth of the output varies by about 8% against the number of gates.
What is measured. On 150 random circuits of 5 to 8 gates on devices of 4 or 5 qubits (seed 0), SABRE with 5 trials and 3 passes uses the fewest possible SWAPs, by an exhaustive breadth-first search over every initial mapping, on 147, and one more than that on the other 3. Every output passes a check that each two-qubit gate is on an edge and that the gates run in a legal order, and the outputs agree with the input circuit on every basis state, for CNOT and X circuits after the SWAPs are expanded into three CNOTs, and for H, T and CNOT circuits by state vectors. On 30 random circuits of 40 gates on a grid (seed 7), three passes instead of one cut the total SWAPs from 505 to 397, 21% fewer. On 3,000 random circuits on random trees with extra edges, with in , in and in , no pass ever made SWAPs in a row, so the release valve never fired; the tests do not show that the plain score can cycle, only that the code ends either way.
Variants and improvements
- Fidelity and time. Later versions weigh each coupling by its error rate or gate time, so the distance in is a cost, not a hop count.
- LightSABRE (Zou, Treinish, Hartman, Ivrii and Lishman, 2024), the version in Qiskit, speeds up the search, runs many trials, and adds a release valve for the cases where the original score makes no progress. It reports 18.9% fewer SWAPs than the original SABRE on the same benchmarks.
- Bridges and commutation. Some routers also use bridge gates or move commuting gates into the front layer, so fewer SWAPs are needed.
- Exact or layered search. For small circuits, an exact method by satisfiability finds the fewest SWAPs, and A* search per layer, as in Zulehner, Paler and Wille, finds the best SWAPs for each layer of gates. SABRE trades these guarantees for speed.
When to use it
Use SABRE, or a descendant of it, as the default router for circuits of tens to thousands of qubits on a sparse coupling graph. Run several trials and keep the best, since the result depends on the random start and on ties. For a circuit small enough, run an exact method to know how far the heuristic is from the best.
Pitfalls
- No termination proof in the paper. The score can prefer SWAPs that run no gate; a router should have a rule that forces progress.
- The final mapping. The output ends in a different mapping than it starts; the measured bits must be read from the final places, or the compiler must add SWAPs to undo it.
- Random ties. Two runs with different seeds can give different SWAP counts; report the seed and the number of trials.
- Even number of passes. The last pass must be forward, over the real circuit, or the output runs the circuit backward.
- Directed couplings. On a device with one-way CNOTs, a CNOT in the wrong direction needs four Hadamard gates, which the plain score does not count.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sabre-qubit-mapping/. The authors are listed in prov/2MX74V.jsonl.
"""SABRE qubit mapping, after Li, Ding and Xie (ASPLOS 2019).
A circuit is a list of gates on logical qubits 0..n-1. A gate is a tuple
(name, qubits), with one or two qubits, for example ("cx", (0, 2)). The
device is N physical qubits 0..N-1 and a list of undirected coupling edges.
A layout is a list: layout[a] is the physical qubit of logical qubit a.
The output of a pass is a list of operations on physical qubits:
("gate", i, (p,) or (p, q)) runs gate i of the input circuit, and
("swap", (p, q)) exchanges the states of p and q.
Besides the paper, the search has a release valve: after `limit` SWAPs in a
row with no gate run, it routes the closest gate of the front layer along a
shortest path. Without it the heuristic can cycle; with it every pass ends.
"""
import random
from collections import deque
def distances(n_phys, edges):
"""All-pairs shortest path lengths of the coupling graph, by BFS."""
adj = [[] for _ in range(n_phys)]
for p, q in edges:
adj[p].append(q)
adj[q].append(p)
dist = []
for s in range(n_phys):
d = [None] * n_phys
d[s] = 0
queue = deque([s])
while queue:
u = queue.popleft()
for v in adj[u]:
if d[v] is None:
d[v] = d[u] + 1
queue.append(v)
if any(x is None for x in d):
raise ValueError("the coupling graph must be connected")
dist.append(d)
return adj, dist
def dependence_dag(gates):
"""Successors and the number of predecessors of every gate."""
last = {}
succ = [[] for _ in gates]
npred = [0] * len(gates)
for i, (_, qs) in enumerate(gates):
preds = {last[a] for a in qs if a in last}
for j in preds:
succ[j].append(i)
npred[i] = len(preds)
for a in qs:
last[a] = i
return succ, npred
def swap_search(gates, layout, n_phys, adj, dist, rng, ext_size=20, weight=0.5,
delta=0.001, decay_reset=5, limit=None):
"""One traversal of the circuit. Return (operations, final layout)."""
layout = list(layout)
owner = [None] * n_phys # owner[p] is the logical qubit on p, or None
for a, p in enumerate(layout):
owner[p] = a
if limit is None:
limit = 10 * n_phys
succ, npred = dependence_dag(gates)
npred = list(npred)
front = [i for i in range(len(gates)) if npred[i] == 0] # @line L6
ops = []
decay = [1.0] * n_phys
steps = 0 # search steps since the last reset of the decay
stalled = 0 # SWAPs since the last gate was run
def apply_swap(p, q):
a, b = owner[p], owner[q]
owner[p], owner[q] = b, a
if a is not None:
layout[a] = q
if b is not None:
layout[b] = p
ops.append(("swap", (p, q)))
def gate_dist(i, lay):
a, b = gates[i][1]
return dist[lay[a]][lay[b]]
while front: # @line L7
ready = [i for i in front if len(gates[i][1]) == 1 or gate_dist(i, layout) == 1]
if ready: # @line L8
for i in ready:
front.remove(i)
ops.append(("gate", i, tuple(layout[a] for a in gates[i][1])))
for j in succ[i]:
npred[j] -= 1
if npred[j] == 0:
front.append(j)
decay = [1.0] * n_phys
steps = 0
stalled = 0
continue
if stalled >= limit: # @line L9
# release valve: walk one qubit of the closest gate toward the other
i = min(front, key=lambda g: (gate_dist(g, layout), g))
a, b = gates[i][1]
while dist[layout[a]][layout[b]] > 1:
p = layout[a]
q = min(v for v in adj[p] if dist[v][layout[b]] == dist[p][layout[b]] - 1)
apply_swap(p, q)
stalled = 0
continue
# the extended set: the first two-qubit gates after the front layer
ext = [] # @line L10
seen = set(front)
left = {j: npred[j] for j in range(len(gates))}
queue = deque(front)
while queue and len(ext) < ext_size:
i = queue.popleft()
for j in succ[i]:
left[j] -= 1
if left[j] == 0 and j not in seen:
seen.add(j)
queue.append(j)
if len(gates[j][1]) == 2:
ext.append(j)
if len(ext) == ext_size:
break
cands = set()
for i in front:
for a in gates[i][1]:
p = layout[a]
for q in adj[p]:
cands.add((min(p, q), max(p, q)))
best, best_score = [], None
for p, q in sorted(cands): # @line L11
lay = list(layout)
a, b = owner[p], owner[q]
if a is not None:
lay[a] = q
if b is not None:
lay[b] = p
h = sum(gate_dist(i, lay) for i in front) / len(front)
if ext:
h += weight * sum(gate_dist(i, lay) for i in ext) / len(ext)
h *= max(decay[p], decay[q])
if best_score is None or h < best_score - 1e-12:
best, best_score = [(p, q)], h
elif abs(h - best_score) <= 1e-12:
best.append((p, q))
p, q = rng.choice(best)
apply_swap(p, q) # @line L12
stalled += 1
steps += 1
if steps % decay_reset == 0:
decay = [1.0] * n_phys
else:
decay[p] += delta
decay[q] += delta
return ops, layout
def swap_count(ops):
return sum(1 for op in ops if op[0] == "swap")
def sabre(n_log, gates, n_phys, edges, seed=0, trials=5, traversals=3, **kw):
"""Return (operations, initial layout, final layout) with the fewest SWAPs."""
if n_log > n_phys:
raise ValueError("more logical than physical qubits")
if traversals % 2 == 0:
raise ValueError("the number of traversals must be odd, so the last one is forward")
rng = random.Random(seed)
adj, dist = distances(n_phys, edges) # @line L1
reverse = list(reversed(gates))
best = None
for _ in range(trials):
layout = rng.sample(range(n_phys), n_log) # @line L2
for t in range(traversals - 1): # @line L3
# forward, backward, forward, ...: the final layout of one pass
# is the initial layout of the next
_, layout = swap_search(gates if t % 2 == 0 else reverse, layout, n_phys, adj, dist, rng, **kw)
start = layout
ops, final = swap_search(gates, start, n_phys, adj, dist, rng, **kw) # @line L4
if best is None or swap_count(ops) < swap_count(best[0]):
best = (ops, start, final)
return best # @line L5
def to_three_cnots(ops):
"""Expand every SWAP into three CNOTs, the middle one reversed."""
out = []
for op in ops:
if op[0] == "swap":
p, q = op[1]
out += [("cx", (p, q)), ("cx", (q, p)), ("cx", (p, q))]
else:
out.append(op)
return out
test_sabre_qubit_mapping.py 339 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sabre-qubit-mapping/. The authors are listed in prov/2MX74V.jsonl.
import cmath
import itertools
import math
import random
from collections import deque
from sabre_qubit_mapping import (
dependence_dag,
distances,
sabre,
swap_count,
swap_search,
to_three_cnots,
)
# ---------- devices and circuits ----------
def line(n):
return [(i, i + 1) for i in range(n - 1)]
def star(n):
return [(0, i) for i in range(1, n)]
def grid(r, c):
e = []
for i in range(r):
for j in range(c):
v = i * c + j
if j + 1 < c:
e.append((v, v + 1))
if i + 1 < r:
e.append((v, v + c))
return e
def tree(rng, n):
return [(i, rng.randrange(i)) for i in range(1, n)]
def random_circuit(rng, n, g, one_qubit=("h",)):
out = []
for _ in range(g):
if n == 1 or rng.random() < 0.25:
out.append((rng.choice(one_qubit), (rng.randrange(n),)))
else:
out.append(("cx", tuple(rng.sample(range(n), 2))))
return out
# ---------- checks ----------
def check_routing(gates, edges, ops, start, final):
"""Every two-qubit operation is on an edge, every gate runs once on the
physical qubits of its logical qubits at that time, the order respects
the dependences, and the final layout is the one the SWAPs make."""
edge_set = {frozenset(e) for e in edges}
layout = list(start)
owner = {p: a for a, p in enumerate(layout)}
succ, npred = dependence_dag(gates)
npred = list(npred)
ran = []
for op in ops:
if op[0] == "swap":
p, q = op[1]
assert frozenset((p, q)) in edge_set
a, b = owner.get(p), owner.get(q)
owner.pop(p, None)
owner.pop(q, None)
if a is not None:
layout[a] = q
owner[q] = a
if b is not None:
layout[b] = p
owner[p] = b
else:
_, i, phys = op
assert npred[i] == 0 # all its predecessors have run
assert phys == tuple(layout[a] for a in gates[i][1])
if len(phys) == 2:
assert frozenset(phys) in edge_set
for j in succ[i]:
npred[j] -= 1
npred[i] = -1
ran.append(i)
assert sorted(ran) == list(range(len(gates)))
assert layout == list(final)
def exact_swaps(n_log, gates, n_phys, edges):
"""Fewest SWAPs over every initial layout, by breadth-first search over
(layout, set of gates run), running every ready gate for free."""
_, dist = distances(n_phys, edges)
succ, _ = dependence_dag(gates)
preds = [[j for j in range(len(gates)) if i in succ[j]] for i in range(len(gates))]
full = (1 << len(gates)) - 1
def run_ready(lay, done):
changed = True
while changed:
changed = False
for i, (_, qs) in enumerate(gates):
if done >> i & 1 or any(not done >> j & 1 for j in preds[i]):
continue
if len(qs) == 1 or dist[lay[qs[0]]][lay[qs[1]]] == 1:
done |= 1 << i
changed = True
return done
seen = {}
queue = deque()
for lay in itertools.permutations(range(n_phys), n_log):
s = (lay, run_ready(lay, 0))
if s not in seen:
seen[s] = 0
queue.append(s)
while queue:
lay, done = queue.popleft()
if done == full:
return seen[(lay, done)]
owner = {p: a for a, p in enumerate(lay)}
for p, q in edges:
if p not in owner and q not in owner:
continue
nl = list(lay)
if p in owner:
nl[owner[p]] = q
if q in owner:
nl[owner[q]] = p
nl = tuple(nl)
s = (nl, run_ready(nl, done))
if s not in seen:
seen[s] = seen[(lay, done)] + 1
queue.append(s)
raise AssertionError("no solution")
# ---------- simulation ----------
H = [[1 / math.sqrt(2), 1 / math.sqrt(2)], [1 / math.sqrt(2), -1 / math.sqrt(2)]]
T = [[1, 0], [0, cmath.exp(1j * math.pi / 4)]]
X = [[0, 1], [1, 0]]
ONE = {"h": H, "t": T, "x": X}
def apply(state, name, qs, n):
out = list(state)
if len(qs) == 1:
m, (q,) = ONE[name], qs
for s in range(1 << n):
if not s >> q & 1:
a0, a1 = state[s], state[s | 1 << q]
out[s] = m[0][0] * a0 + m[0][1] * a1
out[s | 1 << q] = m[1][0] * a0 + m[1][1] * a1
elif name == "cx":
c, t = qs
for s in range(1 << n):
if s >> c & 1:
out[s] = state[s ^ 1 << t]
else: # swap
p, q = qs
for s in range(1 << n):
if (s >> p & 1) != (s >> q & 1):
out[s] = state[s ^ (1 << p) ^ (1 << q)]
return out
def run_logical(gates, n, x):
state = [0j] * (1 << n)
state[x] = 1
for name, qs in gates:
state = apply(state, name, qs, n)
return state
def run_physical(gates, ops, n_phys, start, x):
"""Load logical basis state x through the initial layout, other qubits 0."""
s0 = sum(1 << start[a] for a in range(len(start)) if x >> a & 1)
state = [0j] * (1 << n_phys)
state[s0] = 1
for op in ops:
if op[0] == "gate":
state = apply(state, gates[op[1]][0], op[2], n_phys)
elif op[0] == "swap":
state = apply(state, "swap", op[1], n_phys)
else:
state = apply(state, op[0], op[1], n_phys)
return state
def relabel(state, n_log, n_phys, final):
"""The logical state placed on the physical qubits of the final layout."""
out = [0j] * (1 << n_phys)
for y, amp in enumerate(state):
out[sum(1 << final[a] for a in range(n_log) if y >> a & 1)] = amp
return out
# ---------- tests ----------
def test_page_example():
gates = [("cx", (0, 1)), ("cx", (1, 2)), ("cx", (0, 2))] # a, b, c = 0, 1, 2
ops, start, final = sabre(3, gates, 3, line(3), seed=0)
check_routing(gates, line(3), ops, start, final)
assert swap_count(ops) == 1 == exact_swaps(3, gates, 3, line(3))
# the layout of the page, a, b, c on q0, q1, q2: the two SWAPs (q0, q1)
# and (q1, q2) tie with score 1, and the tie is broken at random
adj, dist = distances(3, line(3))
seen = set()
for seed in range(10):
ops, final = swap_search(gates, [0, 1, 2], 3, adj, dist, random.Random(seed))
assert ops[:2] == [("gate", 0, (0, 1)), ("gate", 1, (1, 2))]
assert ops[2][0] == "swap" and ops[3][0] == "gate" and len(ops) == 4
seen.add((ops[2][1], tuple(final)))
assert seen == {((0, 1), (1, 0, 2)), ((1, 2), (0, 2, 1))}
def test_lookahead_example():
# a, b, c, d = 0, 1, 2, 3 on the line q0 - q1 - q2 - q3; CNOT(a, c), then CNOT(a, d)
gates = [("cx", (0, 2)), ("cx", (0, 3))]
adj, dist = distances(4, line(4))
for weight, counts in ((0.5, {2}), (0.0, {2, 3})):
seen = set()
for seed in range(20):
ops, _ = swap_search(gates, [0, 1, 2, 3], 4, adj, dist, random.Random(seed), weight=weight)
if weight == 0.5:
assert ops[0] == ("swap", (0, 1)) # score 1 + 0.5 * 2 = 2, against 2.5 and 4
seen.add(swap_count(ops))
assert seen == counts
# the forward pass ends in the layout a, b, c, d -> q1, q0, q3, q2 or
# q2, q0, q1, q3; started from it, the circuit needs no SWAP
ops, start, final = sabre(4, gates, 4, line(4), seed=0)
assert swap_count(ops) == 0 == exact_swaps(4, gates, 4, line(4))
def test_gates_on_edges_in_order():
rng = random.Random(0)
for _ in range(150):
kind = rng.randrange(4)
if kind == 0:
n_phys, edges = 6, line(6)
elif kind == 1:
n_phys, edges = 9, grid(3, 3)
elif kind == 2:
n_phys, edges = 7, star(7)
else:
n_phys = rng.randint(3, 10)
edges = tree(rng, n_phys)
n_log = rng.randint(2, n_phys)
gates = random_circuit(rng, n_log, rng.randint(1, 40))
ops, start, final = sabre(n_log, gates, n_phys, edges, seed=rng.randrange(10**6), trials=2)
check_routing(gates, edges, ops, start, final)
def test_equivalence_on_all_basis_states_with_three_cnots():
"""CNOT and X circuits map basis states to basis states, so agreement on
every basis state is equality of the unitaries. The SWAPs are expanded
into three CNOTs, which checks that identity too."""
rng = random.Random(1)
for _ in range(40):
n_phys = rng.randint(3, 6)
edges = rng.choice([line(n_phys), star(n_phys), tree(rng, n_phys)])
n_log = rng.randint(2, n_phys)
gates = random_circuit(rng, n_log, rng.randint(2, 15), one_qubit=("x",))
ops, start, final = sabre(n_log, gates, n_phys, edges, seed=2, trials=1)
expanded = to_three_cnots(ops)
for x in range(1 << n_log):
want = relabel(run_logical(gates, n_log, x), n_log, n_phys, final)
got = run_physical(gates, expanded, n_phys, start, x)
assert got == want
def test_equivalence_of_the_unitaries_with_h_and_t():
rng = random.Random(2)
for _ in range(25):
n_phys = rng.randint(3, 5)
edges = rng.choice([line(n_phys), star(n_phys)])
n_log = rng.randint(2, n_phys)
gates = random_circuit(rng, n_log, rng.randint(2, 12), one_qubit=("h", "t"))
ops, start, final = sabre(n_log, gates, n_phys, edges, seed=3, trials=1)
for x in range(1 << n_log): # column x of the unitary
want = relabel(run_logical(gates, n_log, x), n_log, n_phys, final)
got = run_physical(gates, ops, n_phys, start, x)
assert all(abs(u - v) < 1e-9 for u, v in zip(got, want))
def test_swap_count_against_exact_optimum():
rng = random.Random(0)
hits, total, worst = 0, 0, 0
for _ in range(150):
n_phys = rng.choice([4, 5])
edges = rng.choice([line(n_phys), star(n_phys),
grid(2, 2) if n_phys == 4 else [(0, 1), (1, 2), (2, 3), (3, 4), (1, 3)]])
n_log = rng.randint(3, n_phys)
gates = random_circuit(rng, n_log, rng.randint(5, 8))
opt = exact_swaps(n_log, gates, n_phys, edges)
ops, start, final = sabre(n_log, gates, n_phys, edges, seed=1)
check_routing(gates, edges, ops, start, final)
c = swap_count(ops)
assert c >= opt
hits += c == opt
worst = max(worst, c - opt)
total += 1
assert (hits, total, worst) == (147, 150, 1)
def test_release_valve_bounds_the_swaps():
rng = random.Random(4)
for _ in range(60):
n_phys = rng.randint(3, 9)
edges = tree(rng, n_phys)
n_log = rng.randint(2, n_phys)
gates = random_circuit(rng, n_log, rng.randint(1, 30))
g2 = sum(1 for _, qs in gates if len(qs) == 2)
adj, dist = distances(n_phys, edges)
start = rng.sample(range(n_phys), n_log)
for limit in (0, 1, 3, None):
ops, final = swap_search(gates, start, n_phys, adj, dist, random.Random(5), limit=limit)
check_routing(gates, edges, ops, start, final)
lim = 10 * n_phys if limit is None else limit
assert swap_count(ops) <= g2 * (lim + n_phys - 2)
# limit 0 is the plain walk along shortest paths
ops, _ = swap_search(gates, start, n_phys, adj, dist, random.Random(5), limit=0)
assert swap_count(ops) <= g2 * (n_phys - 2)
def test_reverse_traversal_lowers_the_swap_count():
rng = random.Random(7)
one = three = 0
for k in range(30):
gates = random_circuit(rng, 9, 40)
one += swap_count(sabre(9, gates, 9, grid(3, 3), seed=k, trials=1, traversals=1)[0])
three += swap_count(sabre(9, gates, 9, grid(3, 3), seed=k, trials=1, traversals=3)[0])
assert three < one
History
Before 2018, qubit mapping was studied for 1D and 2D grids, often with a nearest-neighbor cost. When IBM opened its devices with irregular coupling graphs, Siraichi et al. (CGO 2018) and Zulehner, Paler and Wille (DATE 2018, then TCAD 2019) gave exact and A*-based methods. Those searched over whole mappings, which grows exponentially with the number of qubits. In 2019, Li, Ding and Xie published SABRE, which searched over single SWAPs near the waiting gates and found the initial mapping by reverse traversal. Its speed made it the base of many later routers, including those in Qiskit.
References
- Gushu Li, Yufei Ding and Yuan Xie, Tackling the qubit mapping problem for NISQ-era quantum devices, Proceedings of the 24th International Conference on Architectural Support for Programming Languages and Operating Systems (ASPLOS 2019), pages 1001 to 1014 (arXiv:1809.02573), Section IV.A (distance matrix, DAG, front layer), Section IV.B and Algorithm 1 (the SWAP-based search), Section IV.C (search over SWAPs, Figure 5 reverse traversal, the decay effect), Section IV.D and Equation 2 (the heuristic), Section V (IBM Q20 Tokyo, |E| = 20, W = 0.5, δ = 0.001, Table II)
- Alwin Zulehner, Alexandru Paler and Robert Wille, An efficient methodology for mapping quantum circuits to the IBM QX architectures, IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems 38(7), 2019, pages 1226 to 1236, the layered A* search that SABRE compares with, BKA in its tables (general locator)
- Marcos Yukio Siraichi, Vinícius Fernandes dos Santos, Sylvain Collange and Fernando Magno Quintão Pereira, Qubit allocation, Proceedings of CGO 2018, pages 113 to 125, Theorem 3.1 (Qubit Assignment is NP-complete), the hardness that SABRE cites as its reason for a heuristic
- Henry Zou, Matthew Treinish, Kevin Hartman, Alexander Ivrii and Jake Lishman, LightSABRE, a lightweight and enhanced SABRE algorithm, arXiv:2409.08368, 2024, Section II.7 (the release valve), and the 18.9% fewer SWAPs than SABRE in the abstract
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 2MX74V Edit this page History Report an error Markdown