|
| 1 | +# Copyright 2023 Google LLC |
| 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 | +import abc |
| 16 | +import logging |
| 17 | +from typing import Callable, Dict, Generic, Sequence, Set, Tuple, TYPE_CHECKING, Union |
| 18 | + |
| 19 | +import networkx as nx |
| 20 | +import sympy |
| 21 | +from attrs import frozen |
| 22 | + |
| 23 | +from qualtran import Bloq, Connection, DanglingT, DecomposeNotImplementedError, DecomposeTypeError |
| 24 | +from qualtran._infra.composite_bloq import _binst_to_cxns |
| 25 | + |
| 26 | +from ._call_graph import get_bloq_callee_counts |
| 27 | +from ._costing import CostKey |
| 28 | +from .symbolic_counting_utils import smax |
| 29 | + |
| 30 | +logger = logging.getLogger(__name__) |
| 31 | + |
| 32 | + |
| 33 | +def _cbloq_max_width( |
| 34 | + binst_graph: nx.DiGraph, _bloq_max_width: Callable[[Bloq], int] = lambda b: 0 |
| 35 | +) -> Union[int, sympy.Expr]: |
| 36 | + """Get the maximum width of a composite bloq. |
| 37 | +
|
| 38 | + Specifically, we treat each binst in series. The width at each inter-bloq time point |
| 39 | + is the sum of the bitsizes of all the connections that are "in play". The width at each |
| 40 | + during-a-binst time point is the sum of the binst width (which is provided by the |
| 41 | + `_bloq_max_width` callable) and the bystander connections that are "in play". The max |
| 42 | + width is the maximum over all the time points. |
| 43 | +
|
| 44 | + If the dataflow graph has more than one connected component, we treat each component |
| 45 | + independently. |
| 46 | + """ |
| 47 | + max_width: Union[int, sympy.Expr] = 0 |
| 48 | + in_play: Set[Connection] = set() |
| 49 | + |
| 50 | + for cc in nx.weakly_connected_components(binst_graph): |
| 51 | + for binst in nx.topological_sort(binst_graph.subgraph(cc)): |
| 52 | + pred_cxns, succ_cxns = _binst_to_cxns(binst, binst_graph=binst_graph) |
| 53 | + |
| 54 | + # Remove inbound connections from those that are 'in play'. |
| 55 | + for cxn in pred_cxns: |
| 56 | + in_play.remove(cxn) |
| 57 | + |
| 58 | + if not isinstance(binst, DanglingT): |
| 59 | + # During the application of the binst, we have "observer" connections that have |
| 60 | + # width as well as the width from the binst itself. We consider the case where |
| 61 | + # the bloq may have a max_width greater than the max of its left/right registers. |
| 62 | + during_size = _bloq_max_width(binst.bloq) + sum(s.shape for s in in_play) |
| 63 | + max_width = smax(max_width, during_size) |
| 64 | + |
| 65 | + # After the binst, its successor connections are 'in play'. |
| 66 | + in_play.update(succ_cxns) |
| 67 | + after_size = sum(s.shape for s in in_play) |
| 68 | + max_width = smax(max_width, after_size) |
| 69 | + |
| 70 | + return max_width |
| 71 | + |
| 72 | + |
| 73 | +@frozen |
| 74 | +class QubitCount(CostKey[int]): |
| 75 | + """A cost estimating the number of qubits required to implement a bloq. |
| 76 | +
|
| 77 | + The number of qubits is bounded from below by the number of qubits implied by the signature. |
| 78 | + If a bloq has no callees, the size implied by the signature will be returned. Otherwise, |
| 79 | + this CostKey will try to compute the number of qubits by inspecting the decomposition. |
| 80 | +
|
| 81 | + In the decomposition, each (sub)bloq is considered to be executed sequentially. The "width" |
| 82 | + of the circuit (i.e. the number of qubits) at each sequence point is the number of qubits |
| 83 | + required by the subbloq (computed recursively) plus any "bystander" idling wires. |
| 84 | +
|
| 85 | + This is an estimate for the number of qubits required by an algorithm. Specifically: |
| 86 | + - Bloqs are assumed to be executed sequentially, minimizing the number of qubits potentially |
| 87 | + at the expense of greater circuit depth or execution time. |
| 88 | + - We do not consider "tetris-ing" subbloqs. In a decomposition, each subbloq is assumed |
| 89 | + to be using all of its qubits for the duration of its execution. This could potentially |
| 90 | + overestimate the total number of qubits. |
| 91 | +
|
| 92 | + This Min-Max style estimate can provide a good balance between accuracy and scalability |
| 93 | + of the accounting. To fully account for each qubit and manage space-vs-time trade-offs, |
| 94 | + you must comprehensively decompose your algorithm to a `cirq.Circuit` of basic gates and |
| 95 | + use a `cirq.QubitManager` to manage trade-offs. This may be computationally expensive for |
| 96 | + large algorithms. |
| 97 | + """ |
| 98 | + |
| 99 | + def compute(self, bloq: 'Bloq', get_callee_cost: Callable[['Bloq'], int]) -> int: |
| 100 | + """Compute an estimate of the number of qubits used by `bloq`. |
| 101 | +
|
| 102 | + See the class docstring for more information. |
| 103 | + """ |
| 104 | + # Base case: No callees; use the signature |
| 105 | + min_bloq_size = bloq.signature.n_qubits() |
| 106 | + callees = get_bloq_callee_counts(bloq) |
| 107 | + if len(callees) == 0: |
| 108 | + logger.info("Computing %s for %s from signature", self, bloq) |
| 109 | + return min_bloq_size |
| 110 | + |
| 111 | + # Compute the number of qubits ("width") from the bloq's decomposition. We forward |
| 112 | + # the `get_callee_cost` function so this can recurse into subbloqs. |
| 113 | + try: |
| 114 | + cbloq = bloq.decompose_bloq() |
| 115 | + logger.info("Computing %s for %s from its decomposition", self, bloq) |
| 116 | + return _cbloq_max_width(cbloq._binst_graph, get_callee_cost) |
| 117 | + except (DecomposeNotImplementedError, DecomposeTypeError): |
| 118 | + pass |
| 119 | + |
| 120 | + # No decomposition specified, but callees present. Take the simple maximum of |
| 121 | + # all the callees' sizes. This is likely an under-estimate. |
| 122 | + tot: int = min_bloq_size |
| 123 | + logger.info("Computing %s for %s from %d callee(s)", self, bloq, len(callees)) |
| 124 | + for callee, n in callees: |
| 125 | + tot = smax(tot, get_callee_cost(callee)) |
| 126 | + return tot |
| 127 | + |
| 128 | + def zero(self) -> int: |
| 129 | + """Zero cost is zero qubits.""" |
| 130 | + return 0 |
| 131 | + |
| 132 | + def __str__(self): |
| 133 | + return 'qubit count' |
0 commit comments