-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Move
GreedyQubitManager
from Cirq-FT to Cirq-Core (#6309)
* Move GreedyQubitManager from Cirq-FT to Cirq-Core * Mark Cirq-FT qubit manager as deprecated * Fix tests * Fix coverage test
- Loading branch information
1 parent
87f77be
commit fee056e
Showing
22 changed files
with
241 additions
and
183 deletions.
There are no files selected for viewing
This file contains 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 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 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 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,98 @@ | ||
# 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 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 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 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 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 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 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 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 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 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 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 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 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.