Skip to content

Commit e96e3e8

Browse files
cduckrht
authored andcommitted
Add Circuit Optimizer for sqrt-iSWAP (quantumlib#4224)
Follow up to quantumlib#4213. Fixes quantumlib#4083. (Also contains a one-line change to fix quantumlib#4225.) I'm open to name suggestions for `MergeInteractionsToSqrtIswap`.
1 parent 4ee0114 commit e96e3e8

File tree

7 files changed

+516
-15
lines changed

7 files changed

+516
-15
lines changed

cirq-core/cirq/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -318,6 +318,7 @@
318318
merge_single_qubit_gates_into_phased_x_z,
319319
merge_single_qubit_gates_into_phxz,
320320
MergeInteractions,
321+
MergeInteractionsToSqrtIswap,
321322
MergeSingleQubitGates,
322323
single_qubit_matrix_to_gates,
323324
single_qubit_matrix_to_pauli_rotations,

cirq-core/cirq/circuits/circuit.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -2312,7 +2312,7 @@ def _pick_inserted_ops_moment_indices(
23122312
frontier = defaultdict(lambda: 0)
23132313
moment_indices = []
23142314
for op in operations:
2315-
op_start = max(start, max(frontier[q] for q in op.qubits))
2315+
op_start = max(start, max((frontier[q] for q in op.qubits), default=0))
23162316
moment_indices.append(op_start)
23172317
for q in op.qubits:
23182318
frontier[q] = max(frontier[q], op_start + 1)

cirq-core/cirq/optimizers/__init__.py

+4
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,10 @@
6060
MergeInteractions,
6161
)
6262

63+
from cirq.optimizers.merge_interactions_to_sqrt_iswap import (
64+
MergeInteractionsToSqrtIswap,
65+
)
66+
6367
from cirq.optimizers.merge_single_qubit_gates import (
6468
merge_single_qubit_gates_into_phased_x_z,
6569
merge_single_qubit_gates_into_phxz,

cirq-core/cirq/optimizers/merge_interactions.py

+88-14
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,11 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
"""An optimization pass that combines adjacent single-qubit rotations."""
15+
"""An optimization pass that combines adjacent series of gates on two qubits."""
1616

1717
from typing import Callable, List, Optional, Sequence, Tuple, cast, TYPE_CHECKING
1818

19+
import abc
1920
import numpy as np
2021

2122
from cirq import circuits, ops, protocols
@@ -25,19 +26,25 @@
2526
import cirq
2627

2728

28-
class MergeInteractions(circuits.PointOptimizer):
29-
"""Combines series of adjacent one and two-qubit gates operating on a pair
30-
of qubits."""
29+
class MergeInteractionsAbc(circuits.PointOptimizer, metaclass=abc.ABCMeta):
30+
"""Combines series of adjacent one- and two-qubit, non-parametrized gates
31+
operating on a pair of qubits."""
3132

3233
def __init__(
3334
self,
3435
tolerance: float = 1e-8,
35-
allow_partial_czs: bool = True,
3636
post_clean_up: Callable[[Sequence[ops.Operation]], ops.OP_TREE] = lambda op_list: op_list,
3737
) -> None:
38+
"""
39+
Args:
40+
tolerance: A limit on the amount of absolute error introduced by the
41+
construction.
42+
post_clean_up: This function is called on each set of optimized
43+
operations before they are put into the circuit to replace the
44+
old operations.
45+
"""
3846
super().__init__(post_clean_up=post_clean_up)
3947
self.tolerance = tolerance
40-
self.allow_partial_czs = allow_partial_czs
4148

4249
def optimization_at(
4350
self, circuit: circuits.Circuit, index: int, op: ops.Operation
@@ -63,10 +70,8 @@ def optimization_at(
6370
if not switch_to_new and old_interaction_count <= 1:
6471
return None
6572

66-
# Find a max-3-cz construction.
67-
new_operations = two_qubit_decompositions.two_qubit_matrix_to_operations(
68-
op.qubits[0], op.qubits[1], matrix, self.allow_partial_czs, self.tolerance, False
69-
)
73+
# Find a (possibly ideal) decomposition of the merged operations.
74+
new_operations = self._two_qubit_matrix_to_operations(op.qubits[0], op.qubits[1], matrix)
7075
new_interaction_count = len(
7176
[new_op for new_op in new_operations if len(new_op.qubits) == 2]
7277
)
@@ -82,12 +87,29 @@ def optimization_at(
8287
new_operations=new_operations,
8388
)
8489

90+
@abc.abstractmethod
8591
def _may_keep_old_op(self, old_op: 'cirq.Operation') -> bool:
8692
"""Returns True if the old two-qubit operation may be left unchanged
8793
without decomposition."""
88-
if self.allow_partial_czs:
89-
return isinstance(old_op.gate, ops.CZPowGate)
90-
return isinstance(old_op.gate, ops.CZPowGate) and old_op.gate.exponent == 1
94+
95+
@abc.abstractmethod
96+
def _two_qubit_matrix_to_operations(
97+
self,
98+
q0: 'cirq.Qid',
99+
q1: 'cirq.Qid',
100+
mat: np.ndarray,
101+
) -> Sequence['cirq.Operation']:
102+
"""Decomposes the merged two-qubit gate unitary into the minimum number
103+
of two-qubit gates.
104+
105+
Args:
106+
q0: The first qubit being operated on.
107+
q1: The other qubit being operated on.
108+
mat: Defines the operation to apply to the pair of qubits.
109+
110+
Returns:
111+
A list of operations implementing the matrix.
112+
"""
91113

92114
def _op_to_matrix(
93115
self, op: ops.Operation, qubits: Tuple['cirq.Qid', ...]
@@ -130,7 +152,7 @@ def _op_to_matrix(
130152

131153
def _scan_two_qubit_ops_into_matrix(
132154
self, circuit: circuits.Circuit, index: Optional[int], qubits: Tuple['cirq.Qid', ...]
133-
) -> Tuple[List[ops.Operation], List[int], np.ndarray]:
155+
) -> Tuple[Sequence[ops.Operation], List[int], np.ndarray]:
134156
"""Accumulates operations affecting the given pair of qubits.
135157
136158
The scan terminates when it hits the end of the circuit, finds an
@@ -181,3 +203,55 @@ def _flip_kron_order(mat4x4: np.ndarray) -> np.ndarray:
181203
for j in range(4):
182204
result[order[i], order[j]] = mat4x4[i, j]
183205
return result
206+
207+
208+
class MergeInteractions(MergeInteractionsAbc):
209+
"""Combines series of adjacent one- and two-qubit, non-parametrized gates
210+
operating on a pair of qubits and replaces each series with the minimum
211+
number of CZ gates."""
212+
213+
def __init__(
214+
self,
215+
tolerance: float = 1e-8,
216+
allow_partial_czs: bool = True,
217+
post_clean_up: Callable[[Sequence[ops.Operation]], ops.OP_TREE] = lambda op_list: op_list,
218+
) -> None:
219+
"""
220+
Args:
221+
tolerance: A limit on the amount of absolute error introduced by the
222+
construction.
223+
allow_partial_czs: Enables the use of Partial-CZ gates.
224+
post_clean_up: This function is called on each set of optimized
225+
operations before they are put into the circuit to replace the
226+
old operations.
227+
"""
228+
super().__init__(tolerance=tolerance, post_clean_up=post_clean_up)
229+
self.allow_partial_czs = allow_partial_czs
230+
231+
def _may_keep_old_op(self, old_op: 'cirq.Operation') -> bool:
232+
"""Returns True if the old two-qubit operation may be left unchanged
233+
without decomposition."""
234+
if self.allow_partial_czs:
235+
return isinstance(old_op.gate, ops.CZPowGate)
236+
return isinstance(old_op.gate, ops.CZPowGate) and old_op.gate.exponent == 1
237+
238+
def _two_qubit_matrix_to_operations(
239+
self,
240+
q0: 'cirq.Qid',
241+
q1: 'cirq.Qid',
242+
mat: np.ndarray,
243+
) -> Sequence['cirq.Operation']:
244+
"""Decomposes the merged two-qubit gate unitary into the minimum number
245+
of CZ gates.
246+
247+
Args:
248+
q0: The first qubit being operated on.
249+
q1: The other qubit being operated on.
250+
mat: Defines the operation to apply to the pair of qubits.
251+
252+
Returns:
253+
A list of operations implementing the matrix.
254+
"""
255+
return two_qubit_decompositions.two_qubit_matrix_to_operations(
256+
q0, q1, mat, self.allow_partial_czs, self.tolerance, False
257+
)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
# Copyright 2021 The Cirq Developers
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# https://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
"""An optimization pass that combines adjacent series of gates on two qubits and
16+
outputs a circuit with SQRT_ISWAP or SQRT_ISWAP_INV gates."""
17+
18+
from typing import Callable, Optional, Sequence, TYPE_CHECKING
19+
20+
import numpy as np
21+
22+
from cirq import ops
23+
from cirq.optimizers import two_qubit_to_sqrt_iswap, merge_interactions
24+
25+
if TYPE_CHECKING:
26+
import cirq
27+
28+
29+
class MergeInteractionsToSqrtIswap(merge_interactions.MergeInteractionsAbc):
30+
"""Combines series of adjacent one- and two-qubit, non-parametrized gates
31+
operating on a pair of qubits and replaces each series with the minimum
32+
number of SQRT_ISWAP gates.
33+
34+
See also: ``two_qubit_matrix_to_sqrt_iswap_operations``
35+
"""
36+
37+
def __init__(
38+
self,
39+
tolerance: float = 1e-8,
40+
*,
41+
required_sqrt_iswap_count: Optional[int] = None,
42+
use_sqrt_iswap_inv: bool = False,
43+
post_clean_up: Callable[[Sequence[ops.Operation]], ops.OP_TREE] = lambda op_list: op_list,
44+
) -> None:
45+
"""
46+
Args:
47+
tolerance: A limit on the amount of absolute error introduced by the
48+
construction.
49+
required_sqrt_iswap_count: When specified, each merged group of
50+
two-qubit gates will be decomposed into exactly this many
51+
sqrt-iSWAP gates even if fewer is possible (maximum 3). Circuit
52+
optimization will raise a ``ValueError`` if this number is 2 or
53+
lower and synthesis of any set of merged interactions requires
54+
more.
55+
use_sqrt_iswap_inv: If True, optimizes circuits using
56+
``SQRT_ISWAP_INV`` gates instead of ``SQRT_ISWAP``.
57+
post_clean_up: This function is called on each set of optimized
58+
operations before they are put into the circuit to replace the
59+
old operations.
60+
61+
Raises:
62+
ValueError:
63+
If ``required_sqrt_iswap_count`` is not one of the supported
64+
values 0, 1, 2, or 3.
65+
"""
66+
if required_sqrt_iswap_count is not None and not 0 <= required_sqrt_iswap_count <= 3:
67+
raise ValueError('the argument `required_sqrt_iswap_count` must be 0, 1, 2, or 3.')
68+
super().__init__(tolerance=tolerance, post_clean_up=post_clean_up)
69+
self.required_sqrt_iswap_count = required_sqrt_iswap_count
70+
self.use_sqrt_iswap_inv = use_sqrt_iswap_inv
71+
72+
def _may_keep_old_op(self, old_op: 'cirq.Operation') -> bool:
73+
"""Returns True if the old two-qubit operation may be left unchanged
74+
without decomposition."""
75+
if self.use_sqrt_iswap_inv:
76+
return isinstance(old_op.gate, ops.ISwapPowGate) and old_op.gate.exponent == -0.5
77+
return isinstance(old_op.gate, ops.ISwapPowGate) and old_op.gate.exponent == 0.5
78+
79+
def _two_qubit_matrix_to_operations(
80+
self,
81+
q0: 'cirq.Qid',
82+
q1: 'cirq.Qid',
83+
mat: np.ndarray,
84+
) -> Sequence['cirq.Operation']:
85+
"""Decomposes the merged two-qubit gate unitary into the minimum number
86+
of SQRT_ISWAP gates.
87+
88+
Args:
89+
q0: The first qubit being operated on.
90+
q1: The other qubit being operated on.
91+
mat: Defines the operation to apply to the pair of qubits.
92+
93+
Returns:
94+
A list of operations implementing the matrix.
95+
"""
96+
return two_qubit_to_sqrt_iswap.two_qubit_matrix_to_sqrt_iswap_operations(
97+
q0,
98+
q1,
99+
mat,
100+
required_sqrt_iswap_count=self.required_sqrt_iswap_count,
101+
use_sqrt_iswap_inv=self.use_sqrt_iswap_inv,
102+
atol=self.tolerance,
103+
check_preconditions=False,
104+
)

0 commit comments

Comments
 (0)