-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Use an efficient representation for merged components of operations #7484
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
Open
codrut3
wants to merge
8
commits into
quantumlib:main
Choose a base branch
from
codrut3:issue-6777-d
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
6a51439
Use an efficient representation for connected components of operation…
codrut3 3828322
Fix lint, format and coverage issues.
codrut3 0aeafa8
Address review comments.
codrut3 3d1de8d
Address review comments.
codrut3 58a84b8
Merge remote-tracking branch 'upstream/main' into issue-6777-d
codrut3 c240b3a
Use scipy.DisjointSet to do union-find.
codrut3 3b783c6
Update attribute comment.
codrut3 867f2c0
Fix lint issue.
codrut3 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,240 @@ | ||
# Copyright 2025 The Cirq Developers | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# https://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
"""Defines a connected component of operations, to be used in merge transformers.""" | ||
|
||
from __future__ import annotations | ||
|
||
from typing import Callable, cast, Sequence, TYPE_CHECKING | ||
|
||
from scipy.cluster.hierarchy import DisjointSet | ||
from typing_extensions import override | ||
|
||
from cirq import ops, protocols | ||
|
||
if TYPE_CHECKING: | ||
import cirq | ||
|
||
|
||
class Component: | ||
"""Internal representation for a connected component of operations.""" | ||
|
||
# Circuit moment containing the component | ||
moment_id: int | ||
# Union of all op qubits in the component | ||
qubits: frozenset[cirq.Qid] | ||
# Union of all measurement keys in the component | ||
mkeys: frozenset[cirq.MeasurementKey] | ||
# Union of all control keys in the component | ||
ckeys: frozenset[cirq.MeasurementKey] | ||
# Initial operation in the component | ||
op: cirq.Operation | ||
|
||
# True if the component can be merged with other components | ||
is_mergeable: bool | ||
|
||
def __init__(self, op: cirq.Operation, moment_id: int, is_mergeable=True): | ||
"""Initializes a singleton component.""" | ||
self.op = op | ||
self.is_mergeable = is_mergeable | ||
self.moment_id = moment_id | ||
self.qubits = frozenset(op.qubits) | ||
self.mkeys = protocols.measurement_key_objs(op) | ||
self.ckeys = protocols.control_keys(op) | ||
|
||
|
||
class ComponentWithOps(Component): | ||
"""Component that keeps track of operations.""" | ||
|
||
# List of all operations in the component | ||
ops: list[cirq.Operation] | ||
|
||
def __init__(self, op: cirq.Operation, moment_id: int, is_mergeable=True): | ||
super().__init__(op, moment_id, is_mergeable) | ||
self.ops = [op] | ||
|
||
|
||
class ComponentWithCircuitOp(Component): | ||
"""Component that keeps track of operations as a CircuitOperation.""" | ||
|
||
# CircuitOperation containing all the operations in the component, | ||
# or a single Operation if the component is a singleton | ||
circuit_op: cirq.Operation | ||
|
||
def __init__(self, op: cirq.Operation, moment_id: int, is_mergeable=True): | ||
super().__init__(op, moment_id, is_mergeable) | ||
self.circuit_op = op | ||
|
||
|
||
class ComponentSet: | ||
"""Represents a set of mergeable components of operations.""" | ||
|
||
_comp_type: type[Component] | ||
|
||
_disjoint_set: DisjointSet | ||
|
||
# Callable to decide if a component is mergeable | ||
_is_mergeable: Callable[[cirq.Operation], bool] | ||
|
||
# List of components in creation order | ||
_components: list[Component] | ||
|
||
def __init__(self, is_mergeable: Callable[[cirq.Operation], bool]): | ||
self._is_mergeable = is_mergeable | ||
self._disjoint_set = DisjointSet() | ||
self._components = [] | ||
self._comp_type = Component | ||
|
||
def new_component(self, op: cirq.Operation, moment_id: int, is_mergeable=True) -> Component: | ||
"""Creates a new component and adds it to the set.""" | ||
c = self._comp_type(op, moment_id, self._is_mergeable(op) and is_mergeable) | ||
self._disjoint_set.add(c) | ||
self._components.append(c) | ||
return c | ||
|
||
def components(self) -> list[Component]: | ||
"""Returns the initial components in creation order.""" | ||
return self._components | ||
|
||
def find(self, x: Component) -> Component: | ||
"""Finds the representative for a merged component.""" | ||
return self._disjoint_set[x] | ||
|
||
def merge(self, x: Component, y: Component, merge_left=True) -> Component | None: | ||
"""Attempts to merge two components. | ||
|
||
If merge_left is True, y is merged into x, and the representative will keep | ||
y's moment. If merge_left is False, x is merged into y, and the representative | ||
will keep y's moment. | ||
|
||
Args: | ||
x: First component to merge. | ||
y: Second component to merge. | ||
merge_left: True to keep x's moment for the merged component, False to | ||
keep y's moment for the merged component. | ||
|
||
Returns: | ||
None, if the components can't be merged. | ||
Otherwise the new component representative. | ||
""" | ||
x = self._disjoint_set[x] | ||
y = self._disjoint_set[y] | ||
|
||
if not x.is_mergeable or not y.is_mergeable: | ||
return None | ||
|
||
if not self._disjoint_set.merge(x, y): | ||
return x | ||
|
||
root = self._disjoint_set[x] | ||
root.moment_id = x.moment_id if merge_left else y.moment_id | ||
root.qubits = x.qubits.union(y.qubits) | ||
root.mkeys = x.mkeys.union(y.mkeys) | ||
root.ckeys = x.ckeys.union(y.ckeys) | ||
|
||
return root | ||
|
||
|
||
class ComponentWithOpsSet(ComponentSet): | ||
"""Represents a set of mergeable components, where each component tracks operations.""" | ||
|
||
# Callable that returns if two components can be merged based on their operations | ||
_can_merge: Callable[[Sequence[cirq.Operation], Sequence[cirq.Operation]], bool] | ||
|
||
def __init__( | ||
self, | ||
is_mergeable: Callable[[cirq.Operation], bool], | ||
can_merge: Callable[[Sequence[cirq.Operation], Sequence[cirq.Operation]], bool], | ||
): | ||
super().__init__(is_mergeable) | ||
self._can_merge = can_merge | ||
self._comp_type = ComponentWithOps | ||
|
||
@override | ||
def merge(self, x: Component, y: Component, merge_left=True) -> Component | None: | ||
"""Attempts to merge two components. | ||
|
||
Returns: | ||
None if can_merge is False or the merge doesn't succeed, otherwise the | ||
new representative. The representative will have ops = x.ops + y.ops. | ||
""" | ||
x = cast(ComponentWithOps, self._disjoint_set[x]) | ||
y = cast(ComponentWithOps, self._disjoint_set[y]) | ||
|
||
if x == y: | ||
return x | ||
|
||
if not x.is_mergeable or not y.is_mergeable or not self._can_merge(x.ops, y.ops): | ||
return None | ||
|
||
root = cast(ComponentWithOps, super().merge(x, y, merge_left)) | ||
root.ops = x.ops + y.ops | ||
# Clear the ops list in the non-representative component to avoid memory consumption | ||
if x != root: | ||
x.ops = [] | ||
else: | ||
y.ops = [] | ||
return root | ||
|
||
|
||
class ComponentWithCircuitOpSet(ComponentSet): | ||
"""Represents a set of mergeable components, with operations as a CircuitOperation.""" | ||
|
||
# Callable that merges CircuitOperations from two components | ||
_merge_func: Callable[[ops.Operation, ops.Operation], ops.Operation | None] | ||
|
||
def __init__( | ||
self, | ||
is_mergeable: Callable[[cirq.Operation], bool], | ||
merge_func: Callable[[ops.Operation, ops.Operation], ops.Operation | None], | ||
): | ||
super().__init__(is_mergeable) | ||
self._merge_func = merge_func | ||
self._comp_type = ComponentWithCircuitOp | ||
|
||
@override | ||
def merge(self, x: Component, y: Component, merge_left=True) -> Component | None: | ||
"""Attempts to merge two components. | ||
|
||
Returns: | ||
None if merge_func returns None or the merge doesn't succeed, | ||
otherwise the new representative. | ||
""" | ||
x = cast(ComponentWithCircuitOp, self._disjoint_set[x]) | ||
y = cast(ComponentWithCircuitOp, self._disjoint_set[y]) | ||
|
||
if x == y: | ||
return x | ||
|
||
if not x.is_mergeable or not y.is_mergeable: | ||
return None | ||
|
||
new_op = self._merge_func(x.circuit_op, y.circuit_op) | ||
if not new_op: | ||
return None | ||
|
||
root = cast(ComponentWithCircuitOp, super().merge(x, y, merge_left)) | ||
|
||
root.circuit_op = new_op | ||
# The merge_func can be arbitrary, so we need to recompute the component properties | ||
root.qubits = frozenset(new_op.qubits) | ||
root.mkeys = protocols.measurement_key_objs(new_op) | ||
root.ckeys = protocols.control_keys(new_op) | ||
|
||
# Clear the circuit op in the non-representative component to avoid memory consumption | ||
if x != root: | ||
del x.circuit_op | ||
else: | ||
del y.circuit_op | ||
return root |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
As it is Component objects cannot be reliably used in sets or as dictionary keys, because they do not have
__eq__
and__hash__
methods (the default forobject
type relies on instance identity rather than equality of the data).For example, the following fails:
Please rewrite using the attrs.frozen decorator which should cut down on boilerplate
__init__
code and provide sensible hash and equality support. This will also require that any fields in the Component class are immutable and only set at object creation, ie, ComponentWithOps will need to use tuple for.ops
instead oflist
.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thank you for your review Pavol!
Component properties can be changed by a merge. Merging components
x
andy
means that:x
andy
are merged usingscipy.DisjointSet
, and one of them becomes the representative of the set{x, y}
. Call this representativeroot
: as an object, it is either thex
or they
Component.to account for the fact that the merged component now spans all the qubits spanned by
x
andy
. This mutates the original properties of eitherx
ory
, depending which was chosen as the representative byscipy.DisjointSet
. I'm always retrieving the representative of a component before doing anything, to ensure I have the up-to-date properties.Because of this I can't define a
__hash__
method or use theattrs.frozen
decorator. Still I used Components as keys in_MergedCircuit.components_by_index
with the understanding that the instance identity is used for indexing: this works because the same object instance is used for insert and pop. The current implementation usescirq.Operation
as keys in the same manner, even thoughcirq.Operation
doesn't have a hash method.Right now it is possible to define two distinct operations
cirq.X(cirq.q(0))
andcirq.X(cirq.q(0))
, wrap them in aCircuitOperation
, and then place thisCircuitOperation
in another Circuit at moment0
. So I would go out on a limb and say thatc0 != c1
is maybe not so bad. Let me know what you think!