|
| 1 | +from typing import Any, TypeVar, ParamSpec |
| 2 | +from dataclasses import field, dataclass |
| 3 | + |
| 4 | +import numpy as np |
| 5 | +from kirin import ir |
| 6 | + |
| 7 | +from pyqrack.pauli import Pauli |
| 8 | +from bloqade.device import AbstractSimulatorDevice |
| 9 | +from bloqade.pyqrack.reg import Measurement, PyQrackQubit |
| 10 | +from bloqade.pyqrack.base import ( |
| 11 | + MemoryABC, |
| 12 | + StackMemory, |
| 13 | + DynamicMemory, |
| 14 | + PyQrackOptions, |
| 15 | + PyQrackInterpreter, |
| 16 | + _default_pyqrack_args, |
| 17 | +) |
| 18 | +from bloqade.pyqrack.task import PyQrackSimulatorTask |
| 19 | +from bloqade.analysis.address.lattice import AnyAddress |
| 20 | +from bloqade.analysis.address.analysis import AddressAnalysis |
| 21 | + |
| 22 | +RetType = TypeVar("RetType") |
| 23 | +Params = ParamSpec("Params") |
| 24 | + |
| 25 | + |
| 26 | +@dataclass |
| 27 | +class PyQrackSimulatorBase(AbstractSimulatorDevice[PyQrackSimulatorTask]): |
| 28 | + options: PyQrackOptions = field(default_factory=_default_pyqrack_args) |
| 29 | + loss_m_result: Measurement = field(default=Measurement.One, kw_only=True) |
| 30 | + rng_state: np.random.Generator = field( |
| 31 | + default_factory=np.random.default_rng, kw_only=True |
| 32 | + ) |
| 33 | + |
| 34 | + MemoryType = TypeVar("MemoryType", bound=MemoryABC) |
| 35 | + |
| 36 | + def __post_init__(self): |
| 37 | + self.options = PyQrackOptions({**_default_pyqrack_args(), **self.options}) |
| 38 | + |
| 39 | + def new_task( |
| 40 | + self, |
| 41 | + mt: ir.Method[Params, RetType], |
| 42 | + args: tuple[Any, ...], |
| 43 | + kwargs: dict[str, Any], |
| 44 | + memory: MemoryType, |
| 45 | + ) -> PyQrackSimulatorTask[Params, RetType, MemoryType]: |
| 46 | + interp = PyQrackInterpreter( |
| 47 | + mt.dialects, |
| 48 | + memory=memory, |
| 49 | + rng_state=self.rng_state, |
| 50 | + loss_m_result=self.loss_m_result, |
| 51 | + ) |
| 52 | + return PyQrackSimulatorTask( |
| 53 | + kernel=mt, args=args, kwargs=kwargs, pyqrack_interp=interp |
| 54 | + ) |
| 55 | + |
| 56 | + def state_vector( |
| 57 | + self, |
| 58 | + kernel: ir.Method[Params, RetType], |
| 59 | + args: tuple[Any, ...] = (), |
| 60 | + kwargs: dict[str, Any] | None = None, |
| 61 | + ) -> list[complex]: |
| 62 | + """Runs task and returns the state vector.""" |
| 63 | + task = self.task(kernel, args, kwargs) |
| 64 | + task.run() |
| 65 | + return task.state.sim_reg.out_ket() |
| 66 | + |
| 67 | + @staticmethod |
| 68 | + def pauli_expectation(pauli: list[Pauli], qubits: list[PyQrackQubit]) -> float: |
| 69 | + """Returns the expectation value of the given Pauli operator given a list of Pauli operators and qubits. |
| 70 | +
|
| 71 | + Args: |
| 72 | + pauli (list[Pauli]): |
| 73 | + List of Pauli operators to compute the expectation value for. |
| 74 | + qubits (list[PyQrackQubit]): |
| 75 | + List of qubits corresponding to the Pauli operators. |
| 76 | +
|
| 77 | + returns: |
| 78 | + float: |
| 79 | + The expectation value of the Pauli operator. |
| 80 | +
|
| 81 | + """ |
| 82 | + |
| 83 | + if len(pauli) == 0: |
| 84 | + return 0.0 |
| 85 | + |
| 86 | + if len(pauli) != len(qubits): |
| 87 | + raise ValueError("Length of Pauli and qubits must match.") |
| 88 | + |
| 89 | + sim_reg = qubits[0].sim_reg |
| 90 | + |
| 91 | + if any(qubit.sim_reg is not sim_reg for qubit in qubits): |
| 92 | + raise ValueError("All qubits must belong to the same simulator register.") |
| 93 | + |
| 94 | + qubit_ids = [qubit.addr for qubit in qubits] |
| 95 | + |
| 96 | + if len(qubit_ids) != len(set(qubit_ids)): |
| 97 | + raise ValueError("Qubits must be unique.") |
| 98 | + |
| 99 | + return sim_reg.pauli_expectation(pauli, qubit_ids) |
| 100 | + |
| 101 | + |
| 102 | +@dataclass |
| 103 | +class StackMemorySimulator(PyQrackSimulatorBase): |
| 104 | + """PyQrack simulator device with precalculated stack of qubits.""" |
| 105 | + |
| 106 | + min_qubits: int = field(default=0, kw_only=True) |
| 107 | + |
| 108 | + def task( |
| 109 | + self, |
| 110 | + kernel: ir.Method[Params, RetType], |
| 111 | + args: tuple[Any, ...] = (), |
| 112 | + kwargs: dict[str, Any] | None = None, |
| 113 | + ): |
| 114 | + if kwargs is None: |
| 115 | + kwargs = {} |
| 116 | + |
| 117 | + address_analysis = AddressAnalysis(dialects=kernel.dialects) |
| 118 | + frame, _ = address_analysis.run_analysis(kernel) |
| 119 | + if self.min_qubits == 0 and any( |
| 120 | + isinstance(a, AnyAddress) for a in frame.entries.values() |
| 121 | + ): |
| 122 | + raise ValueError( |
| 123 | + "All addresses must be resolved. Or set min_qubits to a positive integer." |
| 124 | + ) |
| 125 | + |
| 126 | + num_qubits = max(address_analysis.qubit_count, self.min_qubits) |
| 127 | + options = self.options.copy() |
| 128 | + options["qubitCount"] = num_qubits |
| 129 | + memory = StackMemory( |
| 130 | + options, |
| 131 | + total=num_qubits, |
| 132 | + ) |
| 133 | + |
| 134 | + return self.new_task(kernel, args, kwargs, memory) |
| 135 | + |
| 136 | + |
| 137 | +@dataclass |
| 138 | +class DynamicMemorySimulator(PyQrackSimulatorBase): |
| 139 | + """PyQrack simulator device with dynamic qubit allocation.""" |
| 140 | + |
| 141 | + def task( |
| 142 | + self, |
| 143 | + kernel: ir.Method[Params, RetType], |
| 144 | + args: tuple[Any, ...] = (), |
| 145 | + kwargs: dict[str, Any] | None = None, |
| 146 | + ): |
| 147 | + if kwargs is None: |
| 148 | + kwargs = {} |
| 149 | + |
| 150 | + memory = DynamicMemory(self.options.copy()) |
| 151 | + return self.new_task(kernel, args, kwargs, memory) |
| 152 | + |
| 153 | + |
| 154 | +def test(): |
| 155 | + from bloqade.qasm2 import extended |
| 156 | + |
| 157 | + @extended |
| 158 | + def main(): |
| 159 | + return 1 |
| 160 | + |
| 161 | + @extended |
| 162 | + def obs(result: int) -> int: |
| 163 | + return result |
| 164 | + |
| 165 | + res = DynamicMemorySimulator().task(main) |
| 166 | + return res.run() |
0 commit comments