Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Token swapper permutation synthesis plugin #10657

Merged
merged 29 commits into from
Jan 30, 2024
Merged
Show file tree
Hide file tree
Changes from 23 commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
4181428
trying to implement permutation synthesis plugin based on token swapper
alexanderivrii Aug 14, 2023
ace8693
improving plugin and tests
alexanderivrii Aug 17, 2023
3f948d2
pylint fixes
alexanderivrii Aug 18, 2023
1d6ee58
Merge branch 'main' into token-swapper-permutation-plugin
alexanderivrii Aug 18, 2023
5858b3d
Merge branch 'token-swapper-permutation-plugin' of github.com:alexand…
alexanderivrii Aug 18, 2023
74ccc4b
exposing seed and parallel_threshold
alexanderivrii Aug 18, 2023
a689b02
release notes
alexanderivrii Aug 18, 2023
e725b37
clarification comment
alexanderivrii Aug 18, 2023
e3e2c3f
Merge branch 'main' into token-swapper-permutation-plugin
alexanderivrii Sep 15, 2023
816ac1e
Merge branch 'main' into token-swapper-permutation-plugin
alexanderivrii Sep 20, 2023
a4b97c7
improved support for disconnected coupling maps
alexanderivrii Sep 20, 2023
2eb7075
unused import
alexanderivrii Sep 20, 2023
8677dcb
fix arxiv reference
alexanderivrii Oct 5, 2023
e15d739
Merge branch 'main' into token-swapper-permutation-plugin
alexanderivrii Oct 18, 2023
ecd793e
Merge branch 'token-swapper-permutation-plugin' of github.com:alexand…
alexanderivrii Oct 18, 2023
9dd1f85
minor fix
alexanderivrii Oct 18, 2023
73e80a7
fix merge
alexanderivrii Oct 18, 2023
3389c31
more merge fixes
alexanderivrii Oct 18, 2023
fb8956d
Merge branch 'main' into token-swapper-permutation-plugin
alexanderivrii Oct 23, 2023
e111e63
fixing imports
alexanderivrii Oct 23, 2023
ef4e877
Merge branch 'main' into token-swapper-permutation-plugin
alexanderivrii Jan 25, 2024
e9b4766
updating toml file
alexanderivrii Jan 25, 2024
24ae130
additional fixes
alexanderivrii Jan 25, 2024
8e65d74
better way to find the position in the circuit
alexanderivrii Jan 25, 2024
f06dc65
Merge branch 'main' into token-swapper-permutation-plugin
alexanderivrii Jan 30, 2024
5e9ff47
bump rustworkx version to 0.14.0
alexanderivrii Jan 30, 2024
7886221
doc and autosummary improvements
alexanderivrii Jan 30, 2024
c3bd53b
Update plugin docs configuration
mtreinish Jan 30, 2024
b617f6f
Remove autosummary for available plugins list
mtreinish Jan 30, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ sk = "qiskit.transpiler.passes.synthesis.solovay_kitaev_synthesis:SolovayKitaevS
"permutation.kms" = "qiskit.transpiler.passes.synthesis.high_level_synthesis:KMSSynthesisPermutation"
"permutation.basic" = "qiskit.transpiler.passes.synthesis.high_level_synthesis:BasicSynthesisPermutation"
"permutation.acg" = "qiskit.transpiler.passes.synthesis.high_level_synthesis:ACGSynthesisPermutation"
"permutation.token_swapper" = "qiskit.transpiler.passes.synthesis.high_level_synthesis:TokenSwapperSynthesisPermutation"

[project.entry-points."qiskit.transpiler.init"]
default = "qiskit.transpiler.preset_passmanagers.builtin_plugins:DefaultInitPassManager"
Expand Down
82 changes: 81 additions & 1 deletion qiskit/transpiler/passes/synthesis/high_level_synthesis.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@

from typing import Optional, Union, List, Tuple

import rustworkx as rx

from qiskit.circuit.operation import Operation
from qiskit.converters import circuit_to_dag, dag_to_circuit
from qiskit.transpiler.basepasses import TransformationPass
Expand All @@ -25,6 +27,7 @@
from qiskit.transpiler.coupling import CouplingMap
from qiskit.dagcircuit.dagcircuit import DAGCircuit
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.transpiler.passes.routing.algorithms import ApproximateTokenSwapper

from qiskit.circuit.annotated_operation import (
AnnotatedOperation,
Expand Down Expand Up @@ -297,7 +300,7 @@ def _recursively_handle_op(

# Try to apply plugin mechanism
decomposition = self._synthesize_op_using_plugins(op, qubits)
if decomposition:
if decomposition is not None:
return decomposition, True
Comment on lines +303 to 304
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This probably fixes a minor bug in the existing code, though previously after defining an empty circuit qc = Quantum(3), the check if qc: would return True, but now it returns False.


# Handle annotated operations
Expand Down Expand Up @@ -644,3 +647,80 @@ def run(self, high_level_object, coupling_map=None, target=None, qubits=None, **
"""Run synthesis for the given Permutation."""
decomposition = synth_permutation_acg(high_level_object.pattern)
return decomposition


class TokenSwapperSynthesisPermutation(HighLevelSynthesisPlugin):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need to add this class somewhere in the toctree to render the docstring here. Right now this class (nor any of the HLS plugins) is not being included in the documentation builds. I was talking to @Cryoris offline about this a bit the other day as there isn't a unified place to document this right now things are spread out a bit too much in the organizational structure. I think for right now if you added a HLS Plugins section to the module docstring in qiskit/transpiler/passes/synthesis/plugin.py and added an autosummary for this class that'd be enough. We can refactor the organizational structure in a follow up easily enough.

"""The permutation synthesis plugin based on the token swapper algorithm.

This plugin name is :``permutation.token_swapper`` which can be used as the key on
an :class:`~.HLSConfig` object to use this method with :class:`~.HighLevelSynthesis`.

In more detail, this plugin is used to synthesize objects of type `PermutationGate`.
When synthesis succeeds, the plugin outputs a quantum circuit consisting only of swap
gates. When synthesis does not succeed, the plugin outputs `None`.

If either `coupling_map` or `qubits` is None, then the synthesized circuit
is not required to adhere to connectivity constraints, as is the case
when the synthesis is done before layout/routing.

On the other hand, if both `coupling_map` and `qubits` are specified, the synthesized
circuit is supposed to adhere to connectivity constraints. At the moment, the
plugin only creates swap gates between qubits in `qubits`, i.e. it does not use
any other qubits in the coupling map (if such synthesis is not possible, the
plugin outputs `None`).

The plugin supports the following plugin-specific options:

* trials: The number of trials for the token swapper to perform the mapping. The
circuit with the smallest number of SWAPs is returned.
* seed: The argument to the token swapper specifying the seed for random trials.
* parallel_threshold: The argument to the token swapper specifying the number of nodes
in the graph beyond which the algorithm will use parallel processing.

For more details on the token swapper algorithm, see to the paper:
`arXiv:1902.09102 <https://arxiv.org/abs/1902.09102>`__.

"""

def run(self, high_level_object, coupling_map=None, target=None, qubits=None, **options):
"""Run synthesis for the given Permutation."""

trials = options.get("trials", 5)
seed = options.get("seed", 0)
parallel_threshold = options.get("parallel_threshold", 50)

pattern = high_level_object.pattern
pattern_as_dict = {j: i for i, j in enumerate(pattern)}

# When the plugin is called from the HighLevelSynthesis transpiler pass,
# the coupling map already takes target into account.
if coupling_map is None or qubits is None:
# The abstract synthesis uses a fully connected coupling map, allowing
# arbitrary connections between qubits.
used_coupling_map = CouplingMap.from_full(len(pattern))
else:
# The concrete synthesis uses the coupling map restricted to the set of
# qubits over which the permutation gate is defined. If we allow using other
# qubits in the coupling map, replacing the node in the DAGCircuit that
# defines this PermutationGate by the DAG corresponding to the constructed
# decomposition becomes problematic. Note that we allow the reduced
# coupling map to be disconnected.
used_coupling_map = coupling_map.reduce(qubits, check_if_connected=False)

graph = used_coupling_map.graph.to_undirected()
swapper = ApproximateTokenSwapper(graph, seed=seed)

try:
swapper_result = swapper.map(
pattern_as_dict, trials, parallel_threshold=parallel_threshold
)
except rx.InvalidMapping:
swapper_result = None

if swapper_result is not None:
decomposition = QuantumCircuit(len(graph.node_indices()))
for swap in swapper_result:
decomposition.swap(*swap)
return decomposition

return None
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
---
features:
- |
Added a new :class:`.HighLevelSynthesisPlugin` for :class:`.PermutationGate`
objects based on Qiskit's token swapper algorithm. To use this plugin,
specify ``token_swapper`` when defining high-level-synthesis config.

This synthesis plugin is able to run before or after the layout is set.
When synthesis succeeds, the plugin outputs a quantum circuit consisting only of
swap gates. When synthesis does not succeed, the plugin outputs `None`.

The following code illustrates how the new plugin can be run::

from qiskit.circuit import QuantumCircuit
from qiskit.circuit.library import PermutationGate
from qiskit.transpiler import PassManager, CouplingMap
from qiskit.transpiler.passes.synthesis.high_level_synthesis import HighLevelSynthesis, HLSConfig

# This creates a circuit with a permutation gate.
qc = QuantumCircuit(8)
perm_gate = PermutationGate([0, 1, 4, 3, 2])
qc.append(perm_gate, [3, 4, 5, 6, 7])

# This defines the coupling map.
coupling_map = CouplingMap.from_ring(8)

# This high-level-synthesis config specifies that we want to use
# the "token_swapper" plugin for synthesizing permutation gates,
# with the option to use 10 trials.
synthesis_config = HLSConfig(permutation=[("token_swapper", {"trials": 10})])

# This creates the pass manager that runs high-level-synthesis on our circuit.
# The option use_qubit_indices=True indicates that synthesis run after the layout is set,
# and hence should preserve the specified coupling map.
pm = PassManager(
HighLevelSynthesis(
synthesis_config, coupling_map=coupling_map, target=None, use_qubit_indices=True
)
)

qc_transpiled = pm.run(qc)
190 changes: 187 additions & 3 deletions test/python/transpiler/test_high_level_synthesis.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,7 @@
"""
Tests the interface for HighLevelSynthesis transpiler pass.
"""


import itertools
import unittest.mock
import numpy as np
from qiskit.circuit import (
Expand Down Expand Up @@ -42,12 +41,15 @@
from qiskit.circuit.library.generalized_gates import LinearFunction
from qiskit.quantum_info import Clifford
from qiskit.test import QiskitTestCase
from qiskit.transpiler.passes.synthesis.plugin import (
HighLevelSynthesisPlugin,
HighLevelSynthesisPluginManager,
)
from qiskit.compiler import transpile
from qiskit.exceptions import QiskitError
from qiskit.converters import dag_to_circuit, circuit_to_dag, circuit_to_instruction
from qiskit.transpiler import PassManager, TranspilerError, CouplingMap, Target
from qiskit.transpiler.passes.basis import BasisTranslator
from qiskit.transpiler.passes.synthesis.plugin import HighLevelSynthesisPlugin
from qiskit.transpiler.passes.synthesis.high_level_synthesis import HighLevelSynthesis, HLSConfig
from qiskit.circuit.annotated_operation import (
AnnotatedOperation,
Expand Down Expand Up @@ -501,6 +503,188 @@ def test_qubits_get_passed_to_plugins(self):
pm_use_qubits_true.run(qc)


class TestTokenSwapperPermutationPlugin(QiskitTestCase):
"""Tests for the token swapper plugin for synthesizing permutation gates."""

def test_token_swapper_in_known_plugin_names(self):
"""Test that "token_swapper" is an available synthesis plugin for permutation gates."""
self.assertIn(
"token_swapper", HighLevelSynthesisPluginManager().method_names("permutation")
)

def test_abstract_synthesis(self):
"""Test abstract synthesis of a permutation gate (either the coupling map or the set
of qubits over which the permutation is defined is not specified).
"""

# Permutation gate
# 4->0, 6->1, 3->2, 7->3, 1->4, 2->5, 0->6, 5->7
perm = PermutationGate([4, 6, 3, 7, 1, 2, 0, 5])

# Circuit with permutation gate
qc = QuantumCircuit(8)
qc.append(perm, range(8))

# Synthesize circuit using the token swapper plugin
synthesis_config = HLSConfig(permutation=[("token_swapper", {"trials": 10, "seed": 1})])
qc_transpiled = PassManager(HighLevelSynthesis(synthesis_config)).run(qc)

# Construct the expected quantum circuit
# From the description below we can see that
# 0->6, 1->4, 2->5, 3->2, 4->0, 5->2->3->7, 6->0->4->1, 7->3
qc_expected = QuantumCircuit(8)
qc_expected.swap(2, 5)
qc_expected.swap(0, 6)
qc_expected.swap(2, 3)
qc_expected.swap(0, 4)
qc_expected.swap(1, 4)
qc_expected.swap(3, 7)

self.assertEqual(qc_transpiled, qc_expected)

def test_concrete_synthesis(self):
"""Test concrete synthesis of a permutation gate (we have both the coupling map and the
set of qubits over which the permutation gate is defined; moreover, the coupling map may
have more qubits than the permutation gate).
"""

# Permutation gate
perm = PermutationGate([0, 1, 4, 3, 2])

# Circuit with permutation gate
qc = QuantumCircuit(8)
qc.append(perm, [3, 4, 5, 6, 7])

coupling_map = CouplingMap.from_ring(8)

synthesis_config = HLSConfig(permutation=[("token_swapper", {"trials": 10})])
qc_transpiled = PassManager(
HighLevelSynthesis(
synthesis_config, coupling_map=coupling_map, target=None, use_qubit_indices=True
)
).run(qc)

qc_expected = QuantumCircuit(8)
qc_expected.swap(6, 7)
qc_expected.swap(5, 6)
qc_expected.swap(6, 7)
self.assertEqual(qc_transpiled, qc_expected)

def test_concrete_synthesis_over_disconnected_qubits(self):
"""Test concrete synthesis of a permutation gate over a disconnected set of qubits,
when synthesis is possible.
"""

# Permutation gate
perm = PermutationGate([1, 0, 3, 2])

# Circuit with permutation gate
qc = QuantumCircuit(10)
qc.append(perm, [3, 2, 7, 8])

coupling_map = CouplingMap.from_ring(10)

synthesis_config = HLSConfig(permutation=[("token_swapper", {"trials": 10})])
qc_transpiled = PassManager(
HighLevelSynthesis(
synthesis_config, coupling_map=coupling_map, target=None, use_qubit_indices=True
)
).run(qc)

qc_expected = QuantumCircuit(10)
qc_expected.swap(2, 3)
qc_expected.swap(7, 8)

# Even though the permutation is over a disconnected set of qubits, the synthesis
# is possible.
self.assertEqual(qc_transpiled, qc_expected)

def test_concrete_synthesis_is_not_possible(self):
"""Test concrete synthesis of a permutation gate over a disconnected set of qubits,
when synthesis is not possible.
"""

# Permutation gate
perm = PermutationGate([0, 2, 1, 3])

# Circuit with permutation gate
qc = QuantumCircuit(10)
qc.append(perm, [3, 2, 7, 8])

coupling_map = CouplingMap.from_ring(10)

synthesis_config = HLSConfig(permutation=[("token_swapper", {"trials": 10})])
qc_transpiled = PassManager(
HighLevelSynthesis(
synthesis_config, coupling_map=coupling_map, target=None, use_qubit_indices=True
)
).run(qc)

# The synthesis is not possible. In this case the plugin should return `None`
# and `HighLevelSynthesis` should not change the original circuit.
self.assertEqual(qc_transpiled, qc)

def test_abstract_synthesis_all_permutations(self):
"""Test abstract synthesis of permutation gates, varying permutation gate patterns."""

edges = [(0, 1), (1, 0), (1, 2), (2, 1), (1, 3), (3, 1), (3, 4), (4, 3)]

coupling_map = CouplingMap()
for i in range(5):
coupling_map.add_physical_qubit(i)
for edge in edges:
coupling_map.add_edge(*edge)

synthesis_config = HLSConfig(permutation=[("token_swapper", {"trials": 10})])
pm = PassManager(
HighLevelSynthesis(
synthesis_config, coupling_map=coupling_map, target=None, use_qubit_indices=False
)
)

for pattern in itertools.permutations(range(4)):
qc = QuantumCircuit(5)
qc.append(PermutationGate(pattern), [2, 0, 3, 1])
self.assertIn("permutation", qc.count_ops())

qc_transpiled = pm.run(qc)
self.assertNotIn("permutation", qc_transpiled.count_ops())

self.assertEqual(Operator(qc), Operator(qc_transpiled))

def test_concrete_synthesis_all_permutations(self):
"""Test concrete synthesis of permutation gates, varying permutation gate patterns."""

edges = [(0, 1), (1, 0), (1, 2), (2, 1), (1, 3), (3, 1), (3, 4), (4, 3)]

coupling_map = CouplingMap()
for i in range(5):
coupling_map.add_physical_qubit(i)
for edge in edges:
coupling_map.add_edge(*edge)

synthesis_config = HLSConfig(permutation=[("token_swapper", {"trials": 10})])
pm = PassManager(
HighLevelSynthesis(
synthesis_config, coupling_map=coupling_map, target=None, use_qubit_indices=True
)
)

for pattern in itertools.permutations(range(4)):

qc = QuantumCircuit(5)
qc.append(PermutationGate(pattern), [2, 0, 3, 1])
self.assertIn("permutation", qc.count_ops())

qc_transpiled = pm.run(qc)
self.assertNotIn("permutation", qc_transpiled.count_ops())
self.assertEqual(Operator(qc), Operator(qc_transpiled))

for inst in qc_transpiled:
qubits = tuple(q._index for q in inst.qubits)
self.assertIn(qubits, edges)


class TestHighLevelSynthesisModifiers(QiskitTestCase):
"""Tests for high-level-synthesis pass."""

Expand Down
Loading