-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Move GreedyQubitManager
from Cirq-FT to Cirq-Core
#6309
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
Merged
tanujkhattar
merged 5 commits into
quantumlib:master
from
tanujkhattar:greedy_qm_to_cirq_core
Oct 6, 2023
Merged
Changes from 2 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
6318d05
Move GreedyQubitManager from Cirq-FT to Cirq-Core
tanujkhattar 21339a2
Mark Cirq-FT qubit manager as deprecated
tanujkhattar d9ba32a
Merge branch 'master' of https://github.com/quantumlib/cirq into gree…
tanujkhattar 2490382
Fix tests
tanujkhattar d81fb26
Fix coverage test
tanujkhattar 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
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
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,86 @@ | ||
# Copyright 2023 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. | ||
|
||
from typing import Iterable, List, Set, TYPE_CHECKING | ||
|
||
from cirq.ops import named_qubit, qid_util, qubit_manager | ||
|
||
if TYPE_CHECKING: | ||
import cirq | ||
|
||
|
||
class GreedyQubitManager(qubit_manager.QubitManager): | ||
"""Greedy allocator that maximizes/minimizes qubit reuse based on a configurable parameter. | ||
|
||
GreedyQubitManager can be configured, using `maximize_reuse` flag, to work in one of two modes: | ||
- Minimize qubit reuse (maximize_reuse=False): For a fixed width, this mode uses a FIFO (First | ||
in First out) strategy s.t. next allocated qubit is one which was freed the earliest. | ||
- Maximize qubit reuse (maximize_reuse=True): For a fixed width, this mode uses a LIFO (Last in | ||
First out) strategy s.t. the next allocated qubit is one which was freed the latest. | ||
|
||
If the requested qubits are more than the set of free qubits, the qubit manager automatically | ||
resizes the size of the managed qubit pool and adds new free qubits, that have their last | ||
freed time to be -infinity. | ||
|
||
For borrowing qubits, the qubit manager simply delegates borrow requests to `self.qalloc`, thus | ||
always allocating new clean qubits. | ||
""" | ||
|
||
def __init__(self, prefix: str, *, size: int = 0, maximize_reuse: bool = False): | ||
"""Initializes `GreedyQubitManager` | ||
|
||
Args: | ||
prefix: The prefix to use for naming new clean ancillas allocated by the qubit manager. | ||
The i'th allocated qubit is of the type `cirq.NamedQubit(f'{prefix}_{i}')`. | ||
size: The initial size of the pool of ancilla qubits managed by the qubit manager. The | ||
qubit manager can automatically resize itself when the allocation request | ||
exceeds the number of available qubits. | ||
maximize_reuse: Flag to control a FIFO vs LIFO strategy, defaults to False (FIFO). | ||
""" | ||
self._prefix = prefix | ||
self._used_qubits: Set['cirq.Qid'] = set() | ||
self._free_qubits: List['cirq.Qid'] = [] | ||
self._size = 0 | ||
self.maximize_reuse = maximize_reuse | ||
self.resize(size) | ||
|
||
def _allocate_qid(self, name: str, dim: int) -> 'cirq.Qid': | ||
return qid_util.q(name) if dim == 2 else named_qubit.NamedQid(name, dimension=dim) | ||
|
||
def resize(self, new_size: int, dim: int = 2) -> None: | ||
if new_size <= self._size: | ||
return | ||
new_qubits: List['cirq.Qid'] = [ | ||
self._allocate_qid(f'{self._prefix}_{s}', dim) for s in range(self._size, new_size) | ||
] | ||
self._free_qubits = new_qubits + self._free_qubits | ||
self._size = new_size | ||
|
||
def qalloc(self, n: int, dim: int = 2) -> List['cirq.Qid']: | ||
if not n: | ||
return [] | ||
self.resize(self._size + n - len(self._free_qubits), dim=dim) | ||
ret_qubits = self._free_qubits[-n:] if self.maximize_reuse else self._free_qubits[:n] | ||
self._free_qubits = self._free_qubits[:-n] if self.maximize_reuse else self._free_qubits[n:] | ||
self._used_qubits.update(ret_qubits) | ||
return ret_qubits | ||
|
||
def qfree(self, qubits: Iterable['cirq.Qid']) -> None: | ||
qs = list(dict(zip(qubits, qubits)).keys()) | ||
assert self._used_qubits.issuperset(qs), "Only managed qubits currently in-use can be freed" | ||
self._used_qubits = self._used_qubits.difference(qs) | ||
self._free_qubits.extend(qs) | ||
|
||
def qborrow(self, n: int, dim: int = 2) -> List['cirq.Qid']: | ||
return self.qalloc(n, dim) |
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,101 @@ | ||
# Copyright 2023 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. | ||
|
||
import cirq | ||
|
||
|
||
class GateAllocInDecompose(cirq.Gate): | ||
def __init__(self, num_alloc: int = 1): | ||
self.num_alloc = num_alloc | ||
|
||
def _num_qubits_(self) -> int: | ||
return 1 | ||
|
||
def _decompose_with_context_(self, qubits, context): | ||
assert context is not None | ||
qm = context.qubit_manager | ||
for q in qm.qalloc(self.num_alloc): | ||
yield cirq.CNOT(qubits[0], q) | ||
qm.qfree([q]) | ||
|
||
def __str__(self): | ||
return 'TestGateAlloc' | ||
|
||
|
||
def test_greedy_qubit_manager(): | ||
def make_circuit(qm: cirq.QubitManager): | ||
q = cirq.LineQubit.range(2) | ||
g = GateAllocInDecompose(1) | ||
context = cirq.DecompositionContext(qubit_manager=qm) | ||
circuit = cirq.Circuit( | ||
cirq.decompose_once(g.on(q[0]), context=context), | ||
cirq.decompose_once(g.on(q[1]), context=context), | ||
) | ||
return circuit | ||
|
||
qm = cirq.GreedyQubitManager(prefix="ancilla", size=1) | ||
# Qubit manager with only 1 managed qubit. Will always repeat the same qubit. | ||
circuit = make_circuit(qm) | ||
cirq.testing.assert_has_diagram( | ||
circuit, | ||
""" | ||
0: ───────────@─────── | ||
│ | ||
1: ───────────┼───@─── | ||
│ │ | ||
ancilla_0: ───X───X─── | ||
""", | ||
) | ||
|
||
qm = cirq.GreedyQubitManager(prefix="ancilla", size=2) | ||
# Qubit manager with 2 managed qubits and maximize_reuse=False, tries to minimize adding | ||
# additional data dependencies by minimizing qubit reuse. | ||
circuit = make_circuit(qm) | ||
cirq.testing.assert_has_diagram( | ||
circuit, | ||
""" | ||
┌──┐ | ||
0: ────────────@───── | ||
│ | ||
1: ────────────┼@──── | ||
││ | ||
ancilla_0: ────X┼──── | ||
│ | ||
ancilla_1: ─────X──── | ||
└──┘ | ||
""", | ||
) | ||
|
||
qm = cirq.GreedyQubitManager(prefix="ancilla", size=2, maximize_reuse=True) | ||
# Qubit manager with 2 managed qubits and maximize_reuse=True, tries to maximize reuse by | ||
# potentially adding new data dependencies. | ||
circuit = make_circuit(qm) | ||
cirq.testing.assert_has_diagram( | ||
circuit, | ||
""" | ||
0: ───────────@─────── | ||
│ | ||
1: ───────────┼───@─── | ||
│ │ | ||
ancilla_1: ───X───X─── | ||
""", | ||
) | ||
|
||
|
||
def test_greedy_qubit_manager_preserves_order(): | ||
qm = cirq.GreedyQubitManager(prefix="anc") | ||
ancillae = [cirq.q(f"anc_{i}") for i in range(100)] | ||
assert qm.qalloc(100) == ancillae | ||
qm.qfree(ancillae) | ||
assert qm.qalloc(100) == ancillae |
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
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
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
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
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
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
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
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
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
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
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.
let the record reflect that I tried to actually verify that this is just a move but you've changed a few things :p including quoting the types now
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.
Quoting the types was necessary because earlier, in Cirq-FT, we could just do
import cirq
but now we either need to import the submodules or putimport cirq
underif TYPE_CHECKING
and quote the types.This should be the only change, I haven't made any logic changes as part of the move.