Skip to content

Commit

Permalink
Add ElidePermutations pass to optimization level 3 (Qiskit#12111)
Browse files Browse the repository at this point in the history
* Add ElideSwaps transpiler pass

This commit adds a new transpiler pass ElideSwaps which is a logical
optimization pass designed to run prior to layout or any other physical
embedding steps in the transpiler pipeline. It traverses the DAG in
topological order and when a swap gate is encountered it removes that
gate and instead permutes the logical qubits for any subsequent gates
in the DAG. This will eliminate any swaps in a circuit not caused by
routing. Additionally, this pass is added to the preset pass manager for
optimization level 3, we can consider adding it to other levels too if
we think it makes sense (there is little overhead, and almost 0 if there
are no swaps).

One thing to note is that this pass does not recurse into control flow
blocks at all, it treats them as black box operations. So if any control
flow blocks contain swap gates those will not be optimized away. This
change was made because mapping the permutation outside and inside any
control flow block was larger in scope than what the intent for this
pass was. That type of work is better suited for the routing passes
which already have to reason about this.

* Update tests with optimization level 3

* Pass final layout from ElideSwap to output

The new ElideSwap pass is causing an output permutation just as a
routing pass would. This information needs to be passed through to the
output in case there is no layout or routing run. In those cases the
information about the output permutation caused by the swap elision will
be lost and doing layout aware operations like Operator.from_circuit()
will not be able to reason about the permutation. This commit fixes this
by inserting the original layout and qubit mapping into the property set
along with the final layout. Then the base pass class and pass manager
class are updated to use the original layout as the initial layout if
one isn't set. In cases where we run layout and routing the output
metadata from those passes will superscede these new metadata fields.

* Move pass in opt level 3 earlier in stage and skip with explicit layout

This commit fixes 2 issues in the execution of the new ElideSwaps pass
as part of optimization level 3. First we were running it too late in
the process both after high level synthesis (which isn't relavant yet,
but will be soon when this is expanded to elide all permutations not
just swaps) and also after reset diagonal before measurement. The second
issue is that if the user is specifying to run with a manual layout set
we should not run this pass, as it will interfere with the user intent.

* Doc and copy paste fixes

* Expand test coverage

* Update permutation tracking

There were 2 issues with the permutation tracking done in an earlier
commit. First, it conflicted with the final_layout property set via
routing (or internally by the routing done in the combined sabre
layout). This was breaking conditional checks in the preset pass manager
around embedding. To fix this a different property is used and set as
the output final layout if no final layout is set. The second issue was
the output layout object was not taking into account a set initial
layout which will permute the qubits and cause the output to not be up
to date. This is fixed by updating apply layout to apply the initial
layout to the elision_final_layout in the property set.

* Generalize pass to support PermutationGate too

This commit generalizes the pass from just considering swap gates to all
permutations (via the PermutationGate class). This enables the pass to
elide additional circuit permutations, not just the special case of a
swap gate. The pass and module are renamed accordingly to
ElidePermutations and elide_permutations respectively.

* Fix permutation handling

This commit fixes the recently added handling of the PermutationGate so
that it correctly is mapping the qubits. The previous iteration of this
messed up the mapping logic so it wasn't valid.

* Fix formatting

* Fix final layout handling for no initial layout

* Improve documentation and log a warning if run post layout

* Fix final layout handling with no ElideSwaps being run

* Fix docs build

* Fix release note

* Fix typo

* Add test for routing and elide permutations

* Apply suggestions from code review

Co-authored-by: Jim Garrison <[email protected]>

* Rename test file to test_elide_permutations.py

* Apply suggestions from code review

Co-authored-by: Kevin Hartman <[email protected]>

* Fix test import after rebase

* fixing failing test cases

this should pass CI after merging Qiskit#12057

* addresses kehas comments - thx

* Adding FinalyzeLayouts pass to pull the virtual circuit permutation from ElidePermutations to the final layout

* formatting

* partial rebase on top of 12057 + tests

* also need test_operator for partial rebase

* removing from transpiler flow for now; reworking elide tests

* also adding permutation gate to the example

* also temporarily reverting test_transpiler.py

* update to release notes

* minor fixes

* adding ElidePermutations and FinalizeLayouts to level 3

* fixing tests

* release notes

* properly merging with main (now that ElidePermutations is merged)

* and also deleting finalize_layouts

* Update releasenotes/notes/add-elide-permutations-to-pipeline-077dad03bd55ab9c.yaml

* updating code comment

* Fixing failing test: now that ElidePermutations pass runs with optimization level 3, it does remove the SWAP gate. So we need to consider optimization_level=1 to assert that the extra pass does not remove SWAP gates

---------

Co-authored-by: Matthew Treinish <[email protected]>
Co-authored-by: Jim Garrison <[email protected]>
Co-authored-by: Kevin Hartman <[email protected]>
Co-authored-by: Sebastian Brandhofer <[email protected]>
  • Loading branch information
5 people authored and ElePT committed May 31, 2024
1 parent d9e2403 commit 6a12fd9
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 7 deletions.
4 changes: 2 additions & 2 deletions qiskit/transpiler/preset_passmanagers/builtin_plugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
from qiskit.transpiler.passes import TrivialLayout
from qiskit.transpiler.passes import CheckMap
from qiskit.transpiler.passes import BarrierBeforeFinalMeasurements
from qiskit.transpiler.passes import OptimizeSwapBeforeMeasure
from qiskit.transpiler.passes import ElidePermutations
from qiskit.transpiler.passes import RemoveDiagonalGatesBeforeMeasure
from qiskit.transpiler.preset_passmanagers import common
from qiskit.transpiler.preset_passmanagers.plugin import (
Expand Down Expand Up @@ -133,7 +133,7 @@ def pass_manager(self, pass_manager_config, optimization_level=None) -> PassMana
pass_manager_config.unitary_synthesis_plugin_config,
pass_manager_config.hls_config,
)
init.append(OptimizeSwapBeforeMeasure())
init.append(ElidePermutations())
init.append(RemoveDiagonalGatesBeforeMeasure())
init.append(
InverseCancellation(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
features:
- |
The transpiler pass :class:`~.ElidePermutations`
runs by default with optimization level 2 and 3. Intuitively, removing
:class:`~.SwapGate`\s and :class:`~qiskit.circuit.library.PermutationGate`\s
in a virtual circuit is almost always beneficial, as it makes the circuit shorter
and easier to route. As :class:`~.OptimizeSwapBeforeMeasure` is a special case
of :class:`~.ElidePermutations`, it has been removed from optimization level 3.
16 changes: 12 additions & 4 deletions test/python/compiler/test_transpiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -1750,8 +1750,11 @@ def test_translate_ecr_basis(self, optimization_level):
optimization_level=optimization_level,
seed_transpiler=42,
)
self.assertEqual(res.count_ops()["ecr"], 9)
self.assertTrue(Operator(res).equiv(circuit))

# Swap gates get optimized away in opt. level 2, 3
expected_num_ecr_gates = 6 if optimization_level in (2, 3) else 9
self.assertEqual(res.count_ops()["ecr"], expected_num_ecr_gates)
self.assertEqual(Operator(circuit), Operator.from_circuit(res))

def test_optimize_ecr_basis(self):
"""Test highest optimization level can optimize over ECR."""
Expand All @@ -1760,8 +1763,13 @@ def test_optimize_ecr_basis(self):
circuit.iswap(0, 1)

res = transpile(circuit, basis_gates=["u", "ecr"], optimization_level=3, seed_transpiler=42)
self.assertEqual(res.count_ops()["ecr"], 1)
self.assertTrue(Operator(res).equiv(circuit))

# an iswap gate is equivalent to (swap, CZ) up to single-qubit rotations. Normally, the swap gate
# in the circuit would cancel with the swap gate of the (swap, CZ), leaving a single CZ gate that
# can be realized via one ECR gate. However, with the introduction of ElideSwap, the swap gate
# cancellation can not occur anymore, thus requiring two ECR gates for the iswap gate.
self.assertEqual(res.count_ops()["ecr"], 2)
self.assertEqual(Operator(circuit), Operator.from_circuit(res))

def test_approximation_degree_invalid(self):
"""Test invalid approximation degree raises."""
Expand Down
3 changes: 2 additions & 1 deletion test/python/transpiler/test_elide_permutations.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,7 @@ class TestElidePermutationsInTranspileFlow(QiskitTestCase):

def test_not_run_after_layout(self):
"""Test ElidePermutations doesn't do anything after layout."""

qc = QuantumCircuit(3)
qc.h(0)
qc.swap(0, 2)
Expand All @@ -312,7 +313,7 @@ def test_not_run_after_layout(self):
qc.h(1)

spm = generate_preset_pass_manager(
optimization_level=3, initial_layout=list(range(2, -1, -1)), seed_transpiler=42
optimization_level=1, initial_layout=list(range(2, -1, -1)), seed_transpiler=42
)
spm.layout += ElidePermutations()
res = spm.run(qc)
Expand Down

0 comments on commit 6a12fd9

Please sign in to comment.