Algorithm Search⌘K

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.

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
Properties
randomizednot exactiterative
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 nn logical qubits and a connected coupling graph GG on N≥nN \ge n physical qubits, find an initial mapping and a sequence of gates and SWAPs on the edges of GG 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 jj depends on gate ii if ii is the last gate before jj on one of jj's qubits. The front layer FF is the set of gates whose predecessors have all run. The extended set EE is the next ee two-qubit gates after FF in the DAG. D[p][q]D[p][q] is the distance of pp and qq in GG, so D−1D - 1 SWAPs bring two qubits next to each other. With π\pi the current mapping, the score of a candidate SWAP (Equation 2 of the paper) is

H=max⁡(decay(p),decay(q))(1∣F∣∑(a,b)∈FD[π′(a)][π′(b)]+W∣E∣∑(a,b)∈ED[π′(a)][π′(b)]),H = \max(\mathrm{decay}(p), \mathrm{decay}(q)) \left( \frac{1}{|F|} \sum_{(a, b) \in F} D[\pi'(a)][\pi'(b)] + \frac{W}{|E|} \sum_{(a, b) \in E} D[\pi'(a)][\pi'(b)] \right),

where π′\pi' is the mapping after the SWAP on (p,q)(p, q), 0≤W<10 \le W < 1, and decay\mathrm{decay} is 11 for a qubit not in a recent SWAP and rises by δ\delta for each recent one, so the search favors SWAPs on other qubits, which can run at the same time.

  1. SABRE(C, G, trials, traversals)
  2. 1compute the distance matrix D of G by breadth-first search from every vertex
  3. 2for each trial: choose a random initial mapping π
  4. 3run 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
  5. 4run SWAP-SEARCH on C from π; keep the output with the fewest SWAPs and its initial mapping π
  6. 5return the best output, its initial mapping and its final mapping
  7. SWAP-SEARCH(C, π)
  8. 6F ← the gates of C with no predecessor
  9. 7while F is not empty:
  10. 8if 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
  11. 9if 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
  12. 10E ← the first e two-qubit gates after F in the DAG
  13. 11for each SWAP on an edge of G that touches a qubit of a gate in F: compute its score H
  14. 12apply 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 ll SWAPs in a row with no gate run (l=10Nl = 10N 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 e=20e = 20, W=0.5W = 0.5 and δ=0.001\delta = 0.001 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 FF. It uses breadth-first search for DD instead of Floyd-Warshall, since the graph has no weights. It builds the extended set again at each step, which costs O(g)O(g); a real tool keeps it up to date.

Example

Take the line q0−q1−q2−q3q_0 - q_1 - q_2 - q_3, logical qubits a,b,c,da, b, c, d on q0,…,q3q_0, \dots, q_3, and the circuit CNOT(a,c)\mathrm{CNOT}(a, c), then CNOT(a,d)\mathrm{CNOT}(a, d). No gate is ready: F={CNOT(a,c)}F = \{\mathrm{CNOT}(a, c)\} at distance 2, and E={CNOT(a,d)}E = \{\mathrm{CNOT}(a, d)\}. The candidate SWAPs touch q0q_0 or q2q_2:

SWAP FF term EE term with W=0.5W = 0.5 HH
(q0,q1)(q_0, q_1), aa to q1q_1 1 0.5⋅D[q1][q3]=10.5 \cdot D[q_1][q_3] = 1 2
(q1,q2)(q_1, q_2), cc to q1q_1 1 0.5⋅D[q0][q3]=1.50.5 \cdot D[q_0][q_3] = 1.5 2.5
(q2,q3)(q_2, q_3), cc to q3q_3 3 0.5⋅D[q0][q2]=10.5 \cdot D[q_0][q_2] = 1 4

SABRE picks (q0,q1)(q_0, q_1), runs CNOT(a,c)\mathrm{CNOT}(a, c) on (q1,q2)(q_1, q_2), then needs one more SWAP for CNOT(a,d)\mathrm{CNOT}(a, d): 2 SWAPs. Without lookahead (W=0W = 0) 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 c−a−dc - a - d, which fits on the line with aa in the middle, so the right initial mapping needs no SWAP. The forward pass ends with aa in the middle of cc and dd, for example c,a,dc, a, d on q1,q2,q3q_1, q_2, q_3, 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 g2(l+N−2)g_2 (l + N - 2) SWAPs for g2g_2 two-qubit gates, because of the release valve. Second, every two-qubit gate of the output, SWAPs included, acts on an edge of GG, and every gate of CC runs exactly once, after its predecessors. Third, the output is equivalent to CC up to the final permutation: with PπP_\pi the map that puts each logical qubit on its physical qubit π(a)\pi(a) and the free physical qubits in ∣0⟩|0\rangle, the output C′C' satisfies C′Pπ0=PπfCC' P_{\pi_0} = P_{\pi_f} C. The proof uses two facts: a gate on logical qubits under π\pi is the same gate on π\pi's physical qubits, and a SWAP on (p,q)(p, q) 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 C=(c1,…,cg)C = (c_1, \dots, c_g) on logical qubits {0,…,n−1}\{0, \dots, n-1\}, each gate on one or two qubits, and a connected coupling graph GG on physical qubits {0,…,N−1}\{0, \dots, N-1\} with N≥nN \ge n. A mapping is an injective π:{0,…,n−1}→{0,…,N−1}\pi : \{0, \dots, n-1\} \to \{0, \dots, N-1\}. Gate cjc_j depends on cic_i if i<ji < j and cic_i is the last gate before cjc_j on one of cjc_j's qubits; this gives the DAG. g2g_2 is the number of two-qubit gates, DD is the distance in GG, and ll is the limit of the release valve.

Termination

Lemma 1 (SWAPs touch occupied qubits). Every candidate SWAP of line L11 is an edge of GG with at least one end that holds a logical qubit.

Proof. Line L11 takes the edges {p,q}\{p, q\} of GG where p=π(a)p = \pi(a) for a qubit aa of a gate in FF. ∎

Lemma 2 (when SWAPs happen, F holds only waiting two-qubit gates). Whenever lines L9 to L12 run, every gate of FF 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 FF 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 gg gate runs and at most g2(l+N−2)g_2 (l + N - 2) SWAPs.

Proof. Each gate enters FF once, when its last predecessor runs, and leaves it once, when it runs; so there are gg 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 ll, line L9 takes the gate (a,b)(a, b) of FF of least distance d=D[π(a)][π(b)]≥2d = D[\pi(a)][\pi(b)] \ge 2 (Lemma 2), and moves aa along a shortest path: each SWAP is on an edge {p,q}\{p, q\} with D[q][π(b)]=D[p][π(b)]−1D[q][\pi(b)] = D[p][\pi(b)] - 1, and such a qq exists on every shortest path. After d−1≤diam(G)−1≤N−2d - 1 \le \mathrm{diam}(G) - 1 \le N - 2 SWAPs, aa and bb are adjacent, and since no other gate ran, the gate is still in FF, so the next L8 runs it. So every stall has at most l+N−2l + N - 2 SWAPs and ends with a gate run. By Lemma 2, FF 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 g2g_2 stalls. While FF is not empty and no stall is going on, line L8 runs a gate in each iteration. So the loop ends after at most gg iterations of L8 and g2(l+N−2)g_2 (l + N - 2) 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 CC run in an order that is a linear extension of the DAG, each exactly once.

Proof. A gate enters FF 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 F=∅F = \emptyset, every gate enters and leaves FF, so every gate runs exactly once. ∎

Lemma 5 (edges). Every SWAP of the output is on an edge of GG, and every two-qubit gate of CC 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 GG. Line L8 runs a two-qubit gate on (π(a),π(b))(\pi(a), \pi(b)) only when D[π(a)][π(b)]=1D[\pi(a)][\pi(b)] = 1, that is, when they are joined by an edge. ∎

The output is equivalent

Take the state space of the NN physical qubits. For a mapping π\pi, let PπP_\pi be the linear map from the nn logical qubits to the NN physical qubits that puts logical qubit aa on physical qubit π(a)\pi(a) and the other physical qubits in ∣0⟩|0\rangle:

Pπ ∣x0x1…xn−1⟩=∣y⟩,yπ(a)=xa,yp=0 for p∉π({0,…,n−1}).P_\pi\, |x_0 x_1 \dots x_{n-1}\rangle = |y\rangle, \quad y_{\pi(a)} = x_a, \quad y_p = 0 \text{ for } p \notin \pi(\{0, \dots, n-1\}).

For a gate UU on logical qubits AA, write UAU_A for it on the logical register and Uπ(A)U_{\pi(A)} for the same gate on the physical qubits π(A)\pi(A), in the same order.

Lemma 6 (gates move through the mapping). Uπ(A) Pπ=Pπ UAU_{\pi(A)}\, P_\pi = P_\pi\, U_A.

Proof. PπP_\pi is a relabeling of tensor factors followed by adding factors in ∣0⟩|0\rangle. Under it, the factors of AA become the factors of π(A)\pi(A), so a gate on AA before the map is the same gate on π(A)\pi(A) after it, and the added factors are not touched. ∎

Lemma 7 (a SWAP only changes the mapping). Let {p,q}\{p, q\} be an edge and τ\tau the transposition of pp and qq. Then SWAPpq Pπ=Pτ∘π\mathrm{SWAP}_{pq}\, P_\pi = P_{\tau \circ \pi}.

Proof. SWAPpq\mathrm{SWAP}_{pq} exchanges the values of qubits pp and qq in every basis state. Applied to Pπ∣x⟩P_\pi |x\rangle, the value that was on pp (logical xax_a if π(a)=p\pi(a) = p, or 0 if pp is free) moves to q=τ(p)q = \tau(p), and the other way round, so the result puts logical qubit aa on τ(π(a))\tau(\pi(a)) and keeps the free qubits in ∣0⟩|0\rangle. That is Pτ∘π∣x⟩P_{\tau \circ \pi} |x\rangle, and both sides are linear. ∎

This is the same update the code makes in apply_swap, so after each SWAP the variable layout is τ∘π\tau \circ \pi. Lemma 7 also holds for SWAP written as three CNOTs, since the CNOT page proves that CNOTpqCNOTqpCNOTpq=SWAPpq\mathrm{CNOT}_{pq}\mathrm{CNOT}_{qp}\mathrm{CNOT}_{pq} = \mathrm{SWAP}_{pq}.

Lemma 8 (reordering). Let σ\sigma be the order in which the gates of CC run. Then cσ(g)⋯cσ(1)=cg⋯c1c_{\sigma(g)} \cdots c_{\sigma(1)} = c_g \cdots c_1 as operators.

Proof. By Lemma 4, σ\sigma 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 C′C' be the output of SWAP-SEARCH from π0\pi_0, with final mapping πf\pi_f, as an operator on the physical qubits. Then

C′ Pπ0=Pπf C.C'\, P_{\pi_0} = P_{\pi_f}\, C.

Proof. Write the output as operations o1,…,oko_1, \dots, o_k, with mappings π0,π1,…,πk=πf\pi_0, \pi_1, \dots, \pi_k = \pi_f, where πt\pi_t is the mapping after oto_t. Let LtL_t be the product, in run order, of the gates of CC among o1,…,oto_1, \dots, o_t. We show ot⋯o1Pπ0=PπtLto_t \cdots o_1 P_{\pi_0} = P_{\pi_t} L_t by induction on tt. For t=0t = 0 both sides are Pπ0P_{\pi_0}. If oto_t is a SWAP on {p,q}\{p, q\}, then πt=τ∘πt−1\pi_t = \tau \circ \pi_{t-1}, Lt=Lt−1L_t = L_{t-1}, and Lemma 7 gives otPπt−1Lt−1=PπtLto_t P_{\pi_{t-1}} L_{t-1} = P_{\pi_t} L_t. If oto_t runs gate UU on AA, the code emits it on πt−1(A)\pi_{t-1}(A), the mapping does not change, and Lemma 6 gives Uπt−1(A)Pπt−1Lt−1=Pπt−1UALt−1=PπtLtU_{\pi_{t-1}(A)} P_{\pi_{t-1}} L_{t-1} = P_{\pi_{t-1}} U_A L_{t-1} = P_{\pi_t} L_t. At t=kt = k, LkL_k is the product of all gates of CC in run order, which equals CC by Lemma 8. ∎

So the output, started with logical qubit aa on π0(a)\pi_0(a) and the free qubits in ∣0⟩|0\rangle, ends with the state that CC produces, with logical qubit aa on πf(a)\pi_f(a) and the free qubits back in ∣0⟩|0\rangle. A measurement of logical qubit aa reads physical qubit πf(a)\pi_f(a). 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 CC.

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 PπfCP_{\pi_f} C 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 ll, including l=0l = 0, where the search is the plain walk along shortest paths.

Complexity

Breadth-first search from each vertex gives DD in O(N(N+m))O(N(N + m)). In a search step, FF holds at most n/2≤Nn/2 \le N two-qubit gates, so there are at most NDN D candidate SWAPs, and each costs O(∣F∣+e)=O(N+e)O(|F| + e) = O(N + e) to score: O(ND(N+e))O(N D (N + e)) per step. Each run of SWAPs between two gate runs has at most l+N−2l + N - 2 SWAPs, and there are at most gg runs, so a pass costs O(g(l+N)ND(N+e))O(g (l + N) N D (N + e)) in the worst case. The paper argues that a gate needs at most about the diameter of GG in SWAPs, O(N)O(\sqrt{N}) for a 2D grid, which gives its bound of O(N2.5g)O(N^{2.5} g); that argument assumes every SWAP makes progress, which the score does not promise without a rule like the release valve. Space is O(N2)O(N^2) for DD and O(g)O(g) for the DAG.

Properties

What is proved. Each pass ends with at most g2(l+N−2)g_2 (l + N - 2) 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 3×33 \times 3 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 WW in {0,0.5,0.9}\{0, 0.5, 0.9\}, δ\delta in {0,0.001}\{0, 0.001\} and ee in {1,5,20}\{1, 5, 20\}, no pass ever made 4N+204N + 20 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 DD 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.

sabre_qubit_mapping.pyI0RawGitHub
# 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

  1. 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)
  2. 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)
  3. 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
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.distances
  • a full proof of time.one pass
  • a full proof of time.one search step
  • a full proof of space.total
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example