|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | + |
| 3 | +# This code is part of Qiskit. |
| 4 | +# |
| 5 | +# (C) Copyright IBM 2017, 2020. |
| 6 | +# |
| 7 | +# This code is licensed under the Apache License, Version 2.0. You may |
| 8 | +# obtain a copy of this license in the LICENSE.txt file in the root directory |
| 9 | +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. |
| 10 | +# |
| 11 | +# Any modifications or derivative works of this code must retain this |
| 12 | +# copyright notice, and modified files need to carry a notice indicating |
| 13 | +# that they have been altered from the originals. |
| 14 | + |
| 15 | +"""Layout selection using the SABRE bidirectional search approach from Li et al. |
| 16 | +""" |
| 17 | + |
| 18 | +import logging |
| 19 | +import numpy as np |
| 20 | + |
| 21 | +from qiskit.converters import dag_to_circuit |
| 22 | +from qiskit.transpiler.passes.layout.set_layout import SetLayout |
| 23 | +from qiskit.transpiler.passes.layout.full_ancilla_allocation import FullAncillaAllocation |
| 24 | +from qiskit.transpiler.passes.layout.enlarge_with_ancilla import EnlargeWithAncilla |
| 25 | +from qiskit.transpiler.passes.layout.apply_layout import ApplyLayout |
| 26 | +from qiskit.transpiler.passes.routing import SabreSwap |
| 27 | +from qiskit.transpiler.passmanager import PassManager |
| 28 | +from qiskit.transpiler.layout import Layout |
| 29 | +from qiskit.transpiler.basepasses import AnalysisPass |
| 30 | +from qiskit.transpiler.exceptions import TranspilerError |
| 31 | + |
| 32 | +logger = logging.getLogger(__name__) |
| 33 | + |
| 34 | + |
| 35 | +class SabreLayout(AnalysisPass): |
| 36 | + """Choose a Layout via iterative bidirectional routing of the input circuit. |
| 37 | +
|
| 38 | + Starting with a random initial `Layout`, the algorithm does a full routing |
| 39 | + of the circuit (via the `routing_pass` method) to end up with a |
| 40 | + `final_layout`. This final_layout is then used as the initial_layout for |
| 41 | + routing the reverse circuit. The algorithm iterates a number of times until |
| 42 | + it finds an initial_layout that reduces full routing cost. |
| 43 | +
|
| 44 | + This method exploits the reversibility of quantum circuits, and tries to |
| 45 | + include global circuit information in the choice of initial_layout. |
| 46 | +
|
| 47 | + **References:** |
| 48 | +
|
| 49 | + [1] Li, Gushu, Yufei Ding, and Yuan Xie. "Tackling the qubit mapping problem |
| 50 | + for NISQ-era quantum devices." ASPLOS 2019. |
| 51 | + `arXiv:1809.02573 <https://arxiv.org/pdf/1809.02573.pdf>`_ |
| 52 | + """ |
| 53 | + |
| 54 | + def __init__(self, coupling_map, routing_pass=None, seed=None, |
| 55 | + max_iterations=3): |
| 56 | + """SabreLayout initializer. |
| 57 | +
|
| 58 | + Args: |
| 59 | + coupling_map (Coupling): directed graph representing a coupling map. |
| 60 | + routing_pass (BasePass): the routing pass to use while iterating. |
| 61 | + seed (int): seed for setting a random first trial layout. |
| 62 | + max_iterations (int): number of forward-backward iterations. |
| 63 | + """ |
| 64 | + super().__init__() |
| 65 | + self.coupling_map = coupling_map |
| 66 | + self.routing_pass = routing_pass |
| 67 | + self.seed = seed |
| 68 | + self.max_iterations = max_iterations |
| 69 | + |
| 70 | + def run(self, dag): |
| 71 | + """Run the SabreLayout pass on `dag`. |
| 72 | +
|
| 73 | + Args: |
| 74 | + dag (DAGCircuit): DAG to find layout for. |
| 75 | +
|
| 76 | + Raises: |
| 77 | + TranspilerError: if dag wider than self.coupling_map |
| 78 | + """ |
| 79 | + if len(dag.qubits) > self.coupling_map.size(): |
| 80 | + raise TranspilerError('More virtual qubits exist than physical.') |
| 81 | + |
| 82 | + # Choose a random initial_layout. |
| 83 | + if self.seed is None: |
| 84 | + self.seed = np.random.randint(0, np.iinfo(np.int32).max) |
| 85 | + rng = np.random.default_rng(self.seed) |
| 86 | + |
| 87 | + physical_qubits = rng.choice(self.coupling_map.size(), |
| 88 | + len(dag.qubits), replace=False) |
| 89 | + physical_qubits = rng.permutation(physical_qubits) |
| 90 | + initial_layout = Layout({q: dag.qubits[i] |
| 91 | + for i, q in enumerate(physical_qubits)}) |
| 92 | + |
| 93 | + if self.routing_pass is None: |
| 94 | + self.routing_pass = SabreSwap(self.coupling_map, 'decay') |
| 95 | + |
| 96 | + # Do forward-backward iterations. |
| 97 | + circ = dag_to_circuit(dag) |
| 98 | + for i in range(self.max_iterations): |
| 99 | + for _ in ('forward', 'backward'): |
| 100 | + pm = self._layout_and_route_passmanager(initial_layout) |
| 101 | + new_circ = pm.run(circ) |
| 102 | + |
| 103 | + # Update initial layout and reverse the unmapped circuit. |
| 104 | + pass_final_layout = pm.property_set['final_layout'] |
| 105 | + final_layout = self._compose_layouts(initial_layout, |
| 106 | + pass_final_layout, |
| 107 | + circ.qregs) |
| 108 | + initial_layout = final_layout |
| 109 | + circ = circ.reverse_ops() |
| 110 | + |
| 111 | + # Diagnostics |
| 112 | + logger.info('After round %d, num_swaps: %d', |
| 113 | + i+1, new_circ.count_ops().get('swap', 0)) |
| 114 | + logger.info('new initial layout') |
| 115 | + logger.info(initial_layout) |
| 116 | + |
| 117 | + self.property_set['layout'] = initial_layout |
| 118 | + |
| 119 | + def _layout_and_route_passmanager(self, initial_layout): |
| 120 | + """Return a passmanager for a full layout and routing. |
| 121 | +
|
| 122 | + We use a factory to remove potential statefulness of passes. |
| 123 | + """ |
| 124 | + layout_and_route = [SetLayout(initial_layout), |
| 125 | + FullAncillaAllocation(self.coupling_map), |
| 126 | + EnlargeWithAncilla(), |
| 127 | + ApplyLayout(), |
| 128 | + self.routing_pass] |
| 129 | + pm = PassManager(layout_and_route) |
| 130 | + return pm |
| 131 | + |
| 132 | + def _compose_layouts(self, initial_layout, pass_final_layout, qregs): |
| 133 | + """Return the real final_layout resulting from the composition |
| 134 | + of an initial_layout with the final_layout reported by a pass. |
| 135 | +
|
| 136 | + The routing passes internally start with a trivial layout, as the |
| 137 | + layout gets applied to the circuit prior to running them. So the |
| 138 | + "final_layout" they report must be amended to account for the actual |
| 139 | + initial_layout that was selected. |
| 140 | + """ |
| 141 | + trivial_layout = Layout.generate_trivial_layout(*qregs) |
| 142 | + pass_final_layout = Layout({trivial_layout[v.index]: p |
| 143 | + for v, p in pass_final_layout.get_virtual_bits().items()}) |
| 144 | + qubit_map = Layout.combine_into_edge_map(initial_layout, trivial_layout) |
| 145 | + final_layout = {v: pass_final_layout[qubit_map[v]] |
| 146 | + for v, _ in initial_layout.get_virtual_bits().items()} |
| 147 | + return Layout(final_layout) |
0 commit comments