pyqrack-cuda-complex128 2.30.2__tar.gz → 2.30.4__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4}/Makefile +1 -1
- {pyqrack_cuda_complex128-2.30.2/pyqrack_cuda_complex128.egg-info → pyqrack_cuda_complex128-2.30.4}/PKG-INFO +1 -1
- pyqrack_cuda_complex128-2.30.4/pyqrack/qrack_bridge.py +297 -0
- {pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4}/pyqrack/qrack_system/qrack_system.py +84 -0
- {pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4/pyqrack_cuda_complex128.egg-info}/PKG-INFO +1 -1
- {pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4}/setup.py +1 -1
- pyqrack_cuda_complex128-2.30.2/pyqrack/qrack_bridge.py +0 -522
- {pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4}/LICENSE +0 -0
- {pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4}/MANIFEST.in +0 -0
- {pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4}/README.md +0 -0
- {pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4}/pyproject.toml +0 -0
- {pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4}/pyqrack/__init__.py +0 -0
- {pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4}/pyqrack/neuron_activation_fn.py +0 -0
- {pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4}/pyqrack/pauli.py +0 -0
- {pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4}/pyqrack/qrack_ace_backend.py +0 -0
- {pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4}/pyqrack/qrack_ace_mps_backend.py +0 -0
- {pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4}/pyqrack/qrack_circuit.py +0 -0
- {pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4}/pyqrack/qrack_near_clifford_qec_backend.py +0 -0
- {pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4}/pyqrack/qrack_neuron.py +0 -0
- {pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4}/pyqrack/qrack_neuron_torch_layer.py +0 -0
- {pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4}/pyqrack/qrack_simulator.py +0 -0
- {pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4}/pyqrack/qrack_stabilizer.py +0 -0
- {pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4}/pyqrack/qrack_system/__init__.py +0 -0
- {pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4}/pyqrack/quimb_circuit_type.py +0 -0
- {pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4}/pyqrack/stats/__init__.py +0 -0
- {pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4}/pyqrack/stats/load_quantized_data.py +0 -0
- {pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4}/pyqrack/stats/quantize_by_range.py +0 -0
- {pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4}/pyqrack_cuda_complex128.egg-info/SOURCES.txt +0 -0
- {pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4}/pyqrack_cuda_complex128.egg-info/dependency_links.txt +0 -0
- {pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4}/pyqrack_cuda_complex128.egg-info/not-zip-safe +0 -0
- {pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4}/pyqrack_cuda_complex128.egg-info/requires.txt +0 -0
- {pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4}/pyqrack_cuda_complex128.egg-info/top_level.txt +0 -0
- {pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4}/setup.cfg +0 -0
|
@@ -30,7 +30,7 @@ build-deps:
|
|
|
30
30
|
rm -rf pyqrack/qrack_system/qrack_cl_precompile
|
|
31
31
|
ifneq ($(OS),Windows_NT)
|
|
32
32
|
ifeq ($(QRACK_PRESENT),)
|
|
33
|
-
git clone https://github.com/unitaryfund/qrack.git; cd qrack; git checkout
|
|
33
|
+
git clone https://github.com/unitaryfund/qrack.git; cd qrack; git checkout 2fda2a7cebcff4c6e0a2c500380a30cf0e11c6ae; cd ..
|
|
34
34
|
endif
|
|
35
35
|
mkdir -p qrack/build
|
|
36
36
|
ifeq ($(UNAME_S),Linux)
|
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
# (C) Daniel Strano and the Qrack contributors 2017-2026. All rights reserved.
|
|
2
|
+
#
|
|
3
|
+
# QrackBridge: bridged patching, backed by Qrack's native QBridge.
|
|
4
|
+
#
|
|
5
|
+
# By (Anthropic) Claude and Dan Strano
|
|
6
|
+
#
|
|
7
|
+
# The qubits are split into `patches` contiguous blocks (equal up to the remainder; the last
|
|
8
|
+
# qubit_count % patches blocks get one more), each simulated exactly by its own Qrack engine. Patches
|
|
9
|
+
# sit on a 1D chain (a ring with wrap=True and 3+ patches) and share "bond" qubits only with their
|
|
10
|
+
# nearest neighbours: the state is a matrix-product state whose sites are whole state-vector simulators.
|
|
11
|
+
# Gates within a patch run natively; gates between patches are teleported through fresh bond pairs and
|
|
12
|
+
# each cut is recompressed to at most 2^max_bonds Schmidt components (greedy, or Born-rule groups).
|
|
13
|
+
#
|
|
14
|
+
# Same API as the pure-Python reference implementation (pyqrack.QrackPyBridge), plus pauli_expectation().
|
|
15
|
+
# If the loaded Qrack library predates QBridge, pyqrack.QrackBridge is QrackPyBridge instead.
|
|
16
|
+
#
|
|
17
|
+
# Use of this source code is governed by an MIT-style license that can be
|
|
18
|
+
# found in the LICENSE file or at https://opensource.org/licenses/MIT.
|
|
19
|
+
|
|
20
|
+
import contextlib
|
|
21
|
+
import ctypes
|
|
22
|
+
import math
|
|
23
|
+
import os
|
|
24
|
+
|
|
25
|
+
import numpy as np
|
|
26
|
+
|
|
27
|
+
from .qrack_system import Qrack
|
|
28
|
+
|
|
29
|
+
_SQ = 1 / math.sqrt(2)
|
|
30
|
+
_X = [0, 1, 1, 0]
|
|
31
|
+
_Y = [0, -1j, 1j, 0]
|
|
32
|
+
_Z = [1, 0, 0, -1]
|
|
33
|
+
_H = [_SQ, _SQ, _SQ, -_SQ]
|
|
34
|
+
_S = [1, 0, 0, 1j]
|
|
35
|
+
_ADJS = [1, 0, 0, -1j]
|
|
36
|
+
_T = [1, 0, 0, complex(_SQ, _SQ)]
|
|
37
|
+
_ADJT = [1, 0, 0, complex(_SQ, -_SQ)]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _mtrx_byref(m):
|
|
41
|
+
flat = []
|
|
42
|
+
for c in m:
|
|
43
|
+
c = complex(c)
|
|
44
|
+
flat += [c.real, c.imag]
|
|
45
|
+
return (ctypes.c_double * 8)(*flat)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _ulonglong_byref(a):
|
|
49
|
+
return (ctypes.c_ulonglong * len(a))(*a)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class QrackBridge:
|
|
53
|
+
"""Bridged patching on native Qrack patches (see module docstring).
|
|
54
|
+
|
|
55
|
+
Args:
|
|
56
|
+
qubit_count: number of logical qubits
|
|
57
|
+
max_bonds: bond qubits per cut (bond dimension 2^max_bonds)
|
|
58
|
+
seed: sampler seed (None: random)
|
|
59
|
+
truncation: "greedy" (keep the largest Schmidt values) or "born" (Born-rule group selection)
|
|
60
|
+
patches: number of patches (default 2: one cut, all-to-all coupling)
|
|
61
|
+
wrap: close the patch chain into a ring (3+ patches)
|
|
62
|
+
lazy_bonds: extra bond qubits a cut may buffer before a truncating sweep (0 = eager)
|
|
63
|
+
max_patch_qubits: optional cap on any patch's total width that also forces a sweep
|
|
64
|
+
is_*: engine layers for every patch, as for QrackSimulator
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
def __init__(
|
|
68
|
+
self,
|
|
69
|
+
qubit_count,
|
|
70
|
+
max_bonds=6,
|
|
71
|
+
seed=None,
|
|
72
|
+
truncation="greedy",
|
|
73
|
+
patches=2,
|
|
74
|
+
wrap=False,
|
|
75
|
+
lazy_bonds=0,
|
|
76
|
+
max_patch_qubits=None,
|
|
77
|
+
_clone=None,
|
|
78
|
+
is_tensor_network=True,
|
|
79
|
+
is_schmidt_decompose=True,
|
|
80
|
+
is_schmidt_decompose_multi=False,
|
|
81
|
+
is_stabilizer_hybrid=False,
|
|
82
|
+
is_binary_decision_tree=False,
|
|
83
|
+
is_paged=True,
|
|
84
|
+
is_cpu_gpu_hybrid=True,
|
|
85
|
+
is_gpu=True,
|
|
86
|
+
):
|
|
87
|
+
self.bid = None
|
|
88
|
+
if _clone is not None:
|
|
89
|
+
self.bid = Qrack.qrack_lib.init_qbridge_clone(_clone.bid)
|
|
90
|
+
for k in ("n", "P", "ring", "max_bonds", "lazy_bonds", "max_patch_qubits", "truncation"):
|
|
91
|
+
setattr(self, k, getattr(_clone, k))
|
|
92
|
+
self._throw_if_error()
|
|
93
|
+
self._partition()
|
|
94
|
+
return
|
|
95
|
+
if truncation not in ("greedy", "born"):
|
|
96
|
+
raise ValueError("truncation must be 'greedy' or 'born'")
|
|
97
|
+
if not 1 <= patches <= qubit_count:
|
|
98
|
+
raise ValueError("need 1 <= patches <= qubit_count")
|
|
99
|
+
if lazy_bonds < 0:
|
|
100
|
+
raise ValueError("lazy_bonds must be >= 0")
|
|
101
|
+
self.n = qubit_count
|
|
102
|
+
self.P = patches
|
|
103
|
+
self.ring = bool(wrap) and patches >= 3
|
|
104
|
+
self.max_bonds = max_bonds
|
|
105
|
+
self.lazy_bonds = lazy_bonds
|
|
106
|
+
self.max_patch_qubits = max_patch_qubits
|
|
107
|
+
self.truncation = truncation
|
|
108
|
+
if seed is None:
|
|
109
|
+
seed = int.from_bytes(os.urandom(8), "little")
|
|
110
|
+
self.bid = Qrack.qrack_lib.init_qbridge(
|
|
111
|
+
qubit_count,
|
|
112
|
+
max_bonds,
|
|
113
|
+
patches,
|
|
114
|
+
bool(wrap),
|
|
115
|
+
truncation == "born",
|
|
116
|
+
lazy_bonds,
|
|
117
|
+
max_patch_qubits or 0,
|
|
118
|
+
seed & ((1 << 64) - 1),
|
|
119
|
+
is_tensor_network,
|
|
120
|
+
is_schmidt_decompose_multi,
|
|
121
|
+
is_schmidt_decompose,
|
|
122
|
+
is_stabilizer_hybrid,
|
|
123
|
+
is_binary_decision_tree,
|
|
124
|
+
is_paged,
|
|
125
|
+
is_cpu_gpu_hybrid,
|
|
126
|
+
is_gpu,
|
|
127
|
+
)
|
|
128
|
+
self._throw_if_error()
|
|
129
|
+
self._partition()
|
|
130
|
+
|
|
131
|
+
def _partition(self):
|
|
132
|
+
base, rem = divmod(self.n, self.P)
|
|
133
|
+
sizes = [base + (1 if p >= self.P - rem else 0) for p in range(self.P)]
|
|
134
|
+
self.start = [sum(sizes[:p]) for p in range(self.P)]
|
|
135
|
+
self.part = [list(range(self.start[p], self.start[p] + sizes[p])) for p in range(self.P)]
|
|
136
|
+
self.side = {q: (p, i) for p, qs in enumerate(self.part) for i, q in enumerate(qs)}
|
|
137
|
+
|
|
138
|
+
def __del__(self):
|
|
139
|
+
if getattr(self, "bid", None) is not None:
|
|
140
|
+
Qrack.qrack_lib.destroy_qbridge(self.bid)
|
|
141
|
+
self.bid = None
|
|
142
|
+
|
|
143
|
+
def _throw_if_error(self):
|
|
144
|
+
if Qrack.qrack_lib.get_qbridge_error(self.bid) != 0:
|
|
145
|
+
raise RuntimeError("QrackBridge C++ library raised exception.")
|
|
146
|
+
|
|
147
|
+
def clone(self):
|
|
148
|
+
return QrackBridge(None, _clone=self)
|
|
149
|
+
|
|
150
|
+
def num_qubits(self):
|
|
151
|
+
return self.n
|
|
152
|
+
|
|
153
|
+
# --- statistics ----------------------------------------------------------
|
|
154
|
+
|
|
155
|
+
@property
|
|
156
|
+
def fidelity_estimate(self):
|
|
157
|
+
return Qrack.qrack_lib.qbridge_get_fidelity_estimate(self.bid)
|
|
158
|
+
|
|
159
|
+
@property
|
|
160
|
+
def truncations(self):
|
|
161
|
+
return Qrack.qrack_lib.qbridge_get_truncations(self.bid)
|
|
162
|
+
|
|
163
|
+
@property
|
|
164
|
+
def flushes(self):
|
|
165
|
+
return Qrack.qrack_lib.qbridge_get_flushes(self.bid)
|
|
166
|
+
|
|
167
|
+
@property
|
|
168
|
+
def peak_bonds(self):
|
|
169
|
+
return Qrack.qrack_lib.qbridge_get_peak_bonds(self.bid)
|
|
170
|
+
|
|
171
|
+
@property
|
|
172
|
+
def bond(self):
|
|
173
|
+
"""Live bond qubits per cut (cut c joins patch c to patch c + 1, mod P on a ring)."""
|
|
174
|
+
c = Qrack.qrack_lib.qbridge_get_cut_count(self.bid)
|
|
175
|
+
out = (ctypes.c_ulonglong * max(c, 1))()
|
|
176
|
+
Qrack.qrack_lib.qbridge_get_bonds(self.bid, out)
|
|
177
|
+
return [int(out[i]) for i in range(c)]
|
|
178
|
+
|
|
179
|
+
# --- single-qubit gates --------------------------------------------------
|
|
180
|
+
|
|
181
|
+
def mtrx(self, m, q):
|
|
182
|
+
Qrack.qrack_lib.qbridge_mtrx(self.bid, _mtrx_byref(m), q)
|
|
183
|
+
self._throw_if_error()
|
|
184
|
+
|
|
185
|
+
def u(self, q, th, ph, lm):
|
|
186
|
+
Qrack.qrack_lib.qbridge_u(self.bid, q, th, ph, lm)
|
|
187
|
+
self._throw_if_error()
|
|
188
|
+
|
|
189
|
+
def x(self, q):
|
|
190
|
+
self.mtrx(_X, q)
|
|
191
|
+
|
|
192
|
+
def y(self, q):
|
|
193
|
+
self.mtrx(_Y, q)
|
|
194
|
+
|
|
195
|
+
def z(self, q):
|
|
196
|
+
self.mtrx(_Z, q)
|
|
197
|
+
|
|
198
|
+
def h(self, q):
|
|
199
|
+
self.mtrx(_H, q)
|
|
200
|
+
|
|
201
|
+
def s(self, q):
|
|
202
|
+
self.mtrx(_S, q)
|
|
203
|
+
|
|
204
|
+
def adjs(self, q):
|
|
205
|
+
self.mtrx(_ADJS, q)
|
|
206
|
+
|
|
207
|
+
def t(self, q):
|
|
208
|
+
self.mtrx(_T, q)
|
|
209
|
+
|
|
210
|
+
def adjt(self, q):
|
|
211
|
+
self.mtrx(_ADJT, q)
|
|
212
|
+
|
|
213
|
+
# --- controlled gates, local or bridged ----------------------------------
|
|
214
|
+
# One control across patches; several controls only when all qubits share a patch.
|
|
215
|
+
|
|
216
|
+
def mcmtrx(self, c, m, t):
|
|
217
|
+
Qrack.qrack_lib.qbridge_mcmtrx(self.bid, len(c), _ulonglong_byref(c), _mtrx_byref(m), t)
|
|
218
|
+
self._throw_if_error()
|
|
219
|
+
|
|
220
|
+
def macmtrx(self, c, m, t):
|
|
221
|
+
Qrack.qrack_lib.qbridge_macmtrx(self.bid, len(c), _ulonglong_byref(c), _mtrx_byref(m), t)
|
|
222
|
+
self._throw_if_error()
|
|
223
|
+
|
|
224
|
+
def mcx(self, c, t): self.mcmtrx(c, _X, t)
|
|
225
|
+
def mcy(self, c, t): self.mcmtrx(c, _Y, t)
|
|
226
|
+
def mcz(self, c, t): self.mcmtrx(c, _Z, t)
|
|
227
|
+
def macx(self, c, t): self.macmtrx(c, _X, t)
|
|
228
|
+
def macy(self, c, t): self.macmtrx(c, _Y, t)
|
|
229
|
+
def macz(self, c, t): self.macmtrx(c, _Z, t)
|
|
230
|
+
|
|
231
|
+
def cx(self, a, b): self.mcx([a], b)
|
|
232
|
+
def cy(self, a, b): self.mcy([a], b)
|
|
233
|
+
def cz(self, a, b): self.mcz([a], b)
|
|
234
|
+
|
|
235
|
+
# --- two-qubit gates (ship-and-return across patches: 2 bonds per cut, one sweep) ----------
|
|
236
|
+
|
|
237
|
+
def swap(self, a, b):
|
|
238
|
+
Qrack.qrack_lib.qbridge_swap(self.bid, a, b)
|
|
239
|
+
self._throw_if_error()
|
|
240
|
+
|
|
241
|
+
def iswap(self, a, b):
|
|
242
|
+
Qrack.qrack_lib.qbridge_iswap(self.bid, a, b)
|
|
243
|
+
self._throw_if_error()
|
|
244
|
+
|
|
245
|
+
def adjiswap(self, a, b):
|
|
246
|
+
Qrack.qrack_lib.qbridge_adjiswap(self.bid, a, b)
|
|
247
|
+
self._throw_if_error()
|
|
248
|
+
|
|
249
|
+
def fsim(self, th, ph, a, b):
|
|
250
|
+
Qrack.qrack_lib.qbridge_fsim(self.bid, th, ph, a, b)
|
|
251
|
+
self._throw_if_error()
|
|
252
|
+
|
|
253
|
+
# --- truncation control --------------------------------------------------
|
|
254
|
+
|
|
255
|
+
@contextlib.contextmanager
|
|
256
|
+
def deferred(self):
|
|
257
|
+
"""Truncate once, after the whole block, never inside it (e.g. around a transversal logical
|
|
258
|
+
gate); inside, bridged gates are recompressed only exactly. Nests."""
|
|
259
|
+
Qrack.qrack_lib.qbridge_begin_deferred(self.bid)
|
|
260
|
+
try:
|
|
261
|
+
yield self
|
|
262
|
+
finally:
|
|
263
|
+
Qrack.qrack_lib.qbridge_end_deferred(self.bid)
|
|
264
|
+
self._throw_if_error()
|
|
265
|
+
|
|
266
|
+
def flush(self):
|
|
267
|
+
"""Truncate any buffered bonds back to max_bonds now (readout does this automatically)."""
|
|
268
|
+
Qrack.qrack_lib.qbridge_flush(self.bid)
|
|
269
|
+
self._throw_if_error()
|
|
270
|
+
|
|
271
|
+
# --- readout -----------------------------------------------------------------
|
|
272
|
+
|
|
273
|
+
def measure_shots(self, qubits, shots):
|
|
274
|
+
"""Exact samples of the stored state; bit j of each result is qubits[j]."""
|
|
275
|
+
out = (ctypes.c_ulonglong * shots)()
|
|
276
|
+
Qrack.qrack_lib.qbridge_measure_shots(self.bid, len(qubits), _ulonglong_byref(qubits), shots, out)
|
|
277
|
+
self._throw_if_error()
|
|
278
|
+
return list(out)
|
|
279
|
+
|
|
280
|
+
def pauli_expectation(self, q, b):
|
|
281
|
+
"""Exact <P> for the Pauli product with basis b[i] (pyqrack.Pauli) on qubit q[i]."""
|
|
282
|
+
if len(q) != len(b):
|
|
283
|
+
raise RuntimeError("pauli_expectation argument lengths do not match.")
|
|
284
|
+
result = Qrack.qrack_lib.qbridge_pauli_expectation(
|
|
285
|
+
self.bid, len(q), _ulonglong_byref(q), _ulonglong_byref([int(x) for x in b])
|
|
286
|
+
)
|
|
287
|
+
self._throw_if_error()
|
|
288
|
+
return result
|
|
289
|
+
|
|
290
|
+
def out_ket(self):
|
|
291
|
+
"""Dense contracted state (2^n), little-endian over logical qubits; for testing."""
|
|
292
|
+
real = ctypes.c_float if Qrack.fppow < 6 else ctypes.c_double
|
|
293
|
+
buf = (real * (2 << self.n))()
|
|
294
|
+
Qrack.qrack_lib.qbridge_out_ket(self.bid, buf)
|
|
295
|
+
self._throw_if_error()
|
|
296
|
+
a = np.frombuffer(buf, dtype=np.float32 if Qrack.fppow < 6 else np.float64)
|
|
297
|
+
return a[0::2].astype(float) + 1j * a[1::2].astype(float)
|
|
@@ -1400,3 +1400,87 @@ class QrackSystem:
|
|
|
1400
1400
|
|
|
1401
1401
|
self.qrack_lib.qcircuit_out_to_string.restype = None
|
|
1402
1402
|
self.qrack_lib.qcircuit_out_to_string.argtypes = [c_ulonglong, c_char_p]
|
|
1403
|
+
|
|
1404
|
+
# QBridge (bridged patching); absent from Qrack libraries that predate it.
|
|
1405
|
+
self.has_qbridge = hasattr(self.qrack_lib, "init_qbridge")
|
|
1406
|
+
if self.has_qbridge:
|
|
1407
|
+
self.qrack_lib.init_qbridge.restype = c_ulonglong
|
|
1408
|
+
self.qrack_lib.init_qbridge.argtypes = [
|
|
1409
|
+
c_ulonglong, # qubits
|
|
1410
|
+
c_ulonglong, # max bonds
|
|
1411
|
+
c_ulonglong, # patches
|
|
1412
|
+
c_bool, # wrap
|
|
1413
|
+
c_bool, # Born-rule truncation
|
|
1414
|
+
c_ulonglong, # lazy bonds
|
|
1415
|
+
c_ulonglong, # max patch qubits (0 = none)
|
|
1416
|
+
c_ulonglong, # sampler seed
|
|
1417
|
+
c_bool, # tn
|
|
1418
|
+
c_bool, # md
|
|
1419
|
+
c_bool, # sd
|
|
1420
|
+
c_bool, # sh
|
|
1421
|
+
c_bool, # bdt
|
|
1422
|
+
c_bool, # pg
|
|
1423
|
+
c_bool, # hy
|
|
1424
|
+
c_bool, # oc
|
|
1425
|
+
]
|
|
1426
|
+
self.qrack_lib.init_qbridge_clone.restype = c_ulonglong
|
|
1427
|
+
self.qrack_lib.init_qbridge_clone.argtypes = [c_ulonglong]
|
|
1428
|
+
self.qrack_lib.destroy_qbridge.restype = None
|
|
1429
|
+
self.qrack_lib.destroy_qbridge.argtypes = [c_ulonglong]
|
|
1430
|
+
self.qrack_lib.get_qbridge_error.restype = c_int
|
|
1431
|
+
self.qrack_lib.get_qbridge_error.argtypes = [c_ulonglong]
|
|
1432
|
+
self.qrack_lib.get_qbridge_qubit_count.restype = c_ulonglong
|
|
1433
|
+
self.qrack_lib.get_qbridge_qubit_count.argtypes = [c_ulonglong]
|
|
1434
|
+
self.qrack_lib.qbridge_mtrx.restype = None
|
|
1435
|
+
self.qrack_lib.qbridge_mtrx.argtypes = [c_ulonglong, POINTER(c_double), c_ulonglong]
|
|
1436
|
+
self.qrack_lib.qbridge_u.restype = None
|
|
1437
|
+
self.qrack_lib.qbridge_u.argtypes = [c_ulonglong, c_ulonglong, c_double, c_double, c_double]
|
|
1438
|
+
for fn in ("qbridge_mcmtrx", "qbridge_macmtrx"):
|
|
1439
|
+
getattr(self.qrack_lib, fn).restype = None
|
|
1440
|
+
getattr(self.qrack_lib, fn).argtypes = [
|
|
1441
|
+
c_ulonglong,
|
|
1442
|
+
c_ulonglong,
|
|
1443
|
+
POINTER(c_ulonglong),
|
|
1444
|
+
POINTER(c_double),
|
|
1445
|
+
c_ulonglong,
|
|
1446
|
+
]
|
|
1447
|
+
for fn in ("qbridge_swap", "qbridge_iswap", "qbridge_adjiswap"):
|
|
1448
|
+
getattr(self.qrack_lib, fn).restype = None
|
|
1449
|
+
getattr(self.qrack_lib, fn).argtypes = [c_ulonglong, c_ulonglong, c_ulonglong]
|
|
1450
|
+
self.qrack_lib.qbridge_fsim.restype = None
|
|
1451
|
+
self.qrack_lib.qbridge_fsim.argtypes = [c_ulonglong, c_double, c_double, c_ulonglong, c_ulonglong]
|
|
1452
|
+
for fn in ("qbridge_begin_deferred", "qbridge_end_deferred", "qbridge_flush"):
|
|
1453
|
+
getattr(self.qrack_lib, fn).restype = None
|
|
1454
|
+
getattr(self.qrack_lib, fn).argtypes = [c_ulonglong]
|
|
1455
|
+
self.qrack_lib.qbridge_measure_shots.restype = None
|
|
1456
|
+
self.qrack_lib.qbridge_measure_shots.argtypes = [
|
|
1457
|
+
c_ulonglong,
|
|
1458
|
+
c_ulonglong,
|
|
1459
|
+
POINTER(c_ulonglong),
|
|
1460
|
+
c_ulonglong,
|
|
1461
|
+
POINTER(c_ulonglong),
|
|
1462
|
+
]
|
|
1463
|
+
self.qrack_lib.qbridge_pauli_expectation.restype = c_double
|
|
1464
|
+
self.qrack_lib.qbridge_pauli_expectation.argtypes = [
|
|
1465
|
+
c_ulonglong,
|
|
1466
|
+
c_ulonglong,
|
|
1467
|
+
POINTER(c_ulonglong),
|
|
1468
|
+
POINTER(c_ulonglong),
|
|
1469
|
+
]
|
|
1470
|
+
self.qrack_lib.qbridge_out_ket.restype = None
|
|
1471
|
+
self.qrack_lib.qbridge_out_ket.argtypes = [
|
|
1472
|
+
c_ulonglong,
|
|
1473
|
+
POINTER(c_float) if self.fppow < 6 else POINTER(c_double),
|
|
1474
|
+
]
|
|
1475
|
+
self.qrack_lib.qbridge_get_fidelity_estimate.restype = c_double
|
|
1476
|
+
self.qrack_lib.qbridge_get_fidelity_estimate.argtypes = [c_ulonglong]
|
|
1477
|
+
for fn in (
|
|
1478
|
+
"qbridge_get_truncations",
|
|
1479
|
+
"qbridge_get_flushes",
|
|
1480
|
+
"qbridge_get_peak_bonds",
|
|
1481
|
+
"qbridge_get_cut_count",
|
|
1482
|
+
):
|
|
1483
|
+
getattr(self.qrack_lib, fn).restype = c_ulonglong
|
|
1484
|
+
getattr(self.qrack_lib, fn).argtypes = [c_ulonglong]
|
|
1485
|
+
self.qrack_lib.qbridge_get_bonds.restype = None
|
|
1486
|
+
self.qrack_lib.qbridge_get_bonds.argtypes = [c_ulonglong, POINTER(c_ulonglong)]
|
|
@@ -1,522 +0,0 @@
|
|
|
1
|
-
# Bridged patching on QrackSimulator patches, recompressed through out_ket()/in_ket().
|
|
2
|
-
#
|
|
3
|
-
# By (Anthropic) Claude and Dan Strano
|
|
4
|
-
#
|
|
5
|
-
# Patches. `patches` (default 2) contiguous blocks of logical qubits, equal up to the rounding
|
|
6
|
-
# remainder: every patch gets n // patches qubits and the LAST n % patches patches get one more (so
|
|
7
|
-
# for 2 patches the first is rounded down, as before). Patches sit on a 1D chain; only direct
|
|
8
|
-
# nearest-neighbour patches share bonds. With wrap=True and 3+ patches, the chain closes into a ring
|
|
9
|
-
# (patch P-1 shares bonds with patch 0). With 2 patches there is one cut and all-to-all coupling.
|
|
10
|
-
#
|
|
11
|
-
# Representation. Each patch is ONE QrackSimulator holding its data qubits plus its live bond qubits:
|
|
12
|
-
# "L" bonds on the cut to its left neighbour and "R" bonds on the cut to its right neighbour. Bond j
|
|
13
|
-
# on the right of patch p is paired with bond j on the left of patch p+1. The represented state is
|
|
14
|
-
# all patch kets contracted on every live bond pair with the unnormalized virtual Bell projection
|
|
15
|
-
# sum_k <k|<k|. Reading patch p's ket as a tensor A_p[l, d, r] (left bonds, data, right bonds), the
|
|
16
|
-
# state is the matrix-product contraction A_0 A_1 ... A_{P-1} (traced through the wrap cut on a ring).
|
|
17
|
-
# Every in-patch gate is applied natively, once, to all bond branches at once.
|
|
18
|
-
#
|
|
19
|
-
# Cross-patch gates by gate teleportation along the chain (exact, gates only). Controlled-U from c
|
|
20
|
-
# (patch pc) to t (patch pt), along the shorter way round on a ring:
|
|
21
|
-
# control patch: CNOT c -> fresh bond on the first cut (copy the control)
|
|
22
|
-
# each relay patch: H incoming bond ; CNOT incoming -> fresh bond on the next cut
|
|
23
|
-
# target patch: H incoming bond ; controlled-U incoming -> t
|
|
24
|
-
# Contracting on each bond pair enforces equality, so every relay bond carries a copy of c and the
|
|
25
|
-
# result is exactly controlled-U(c -> t). A gate between patches k apart costs one bond on each of
|
|
26
|
-
# the k cuts in between; nothing ever couples non-adjacent patches directly.
|
|
27
|
-
# SWAP, iSWAP and iSWAP^dagger (any two-qubit gate) cross by "ship and return": a's state is
|
|
28
|
-
# teleported along the chain onto a scratch qubit in b's patch (a SWAPped onto the outgoing bond,
|
|
29
|
-
# identity-wire relays, Bell pairing at the destination), the gate is applied there natively, and the
|
|
30
|
-
# scratch qubit is teleported back onto a. Exactly 2 bonds per cut crossed, one recompression per gate.
|
|
31
|
-
#
|
|
32
|
-
# Recompression after each bridged two-qubit gate (one MPS-style sweep over the touched segment):
|
|
33
|
-
# - Gates on data qubits are unitary on each patch's (left, data) and (data, right) row spaces, so
|
|
34
|
-
# they preserve left/right isometry. Only patches on a gate's path lose it.
|
|
35
|
-
# - An orthogonality centre is tracked. QR-sweep left-to-right over the touched segment (and up to
|
|
36
|
-
# the centre), then SVD-sweep right-to-left, keeping the largest singular values per cut (exact
|
|
37
|
-
# when only zeros are dropped; above max_bonds, greedy or Born-rule group selection).
|
|
38
|
-
# - On an open chain the environment is isometric at every SVD, so these are the true Schmidt values
|
|
39
|
-
# of the state and each truncation is the optimal one for that cut, as with 2 patches.
|
|
40
|
-
# - On a ring, the wrap cut is first recompressed between patches P-1 and 0 locally (QR of both
|
|
41
|
-
# sides, SVD of the core), then the open sweep runs with the wrap bond treated as a physical leg.
|
|
42
|
-
# Dropping only zeros is still exact. Truncating the wrap cut, and truncating inner cuts while wrap
|
|
43
|
-
# bonds are live, is locally optimal but not globally optimal (a periodic MPS has no canonical
|
|
44
|
-
# form), so fidelity_estimate is an estimate there and not the kept Schmidt weight.
|
|
45
|
-
# Nothing larger than the patch kets and per-cut cores is ever formed: no density matrix.
|
|
46
|
-
#
|
|
47
|
-
# Lazy bond buffering (lazy_bonds > 0). Each ket round-trip costs O(patch ket), so instead of
|
|
48
|
-
# recompressing after every bridged gate, bridged gates pile up as raw bond qubits until some cut
|
|
49
|
-
# exceeds max_bonds + lazy_bonds (or some patch exceeds max_patch_qubits, if set); then ONE sweep
|
|
50
|
-
# truncates the whole batch back to max_bonds. Truncating the accumulated state once is the optimal
|
|
51
|
-
# truncation of that state, rather than a sequence of per-gate truncations. Heap cost: each buffered
|
|
52
|
-
# bond qubit doubles the patches on that cut, so a patch can reach
|
|
53
|
-
# n_patch + 2 * (max_bonds + lazy_bonds) + 3 qubits (one gate's 2 bonds and 1 scratch qubit in
|
|
54
|
-
# flight). lazy_bonds=0 is the eager behaviour. Readout (measure_shots, out_ket) flushes first;
|
|
55
|
-
# flush() does it on demand. On random circuits, lazy buffering mostly pays when consecutive gates
|
|
56
|
-
# cross the same cut on the same pair (e.g. CZ then SWAP); otherwise a larger max_bonds at the same
|
|
57
|
-
# heap is the better use of memory.
|
|
58
|
-
#
|
|
59
|
-
# Linear algebra: the sweeps use Gram matrices (one BLAS product and a small Hermitian eigensolve per
|
|
60
|
-
# cut) instead of LAPACK QR/SVD on the whole patch tensor, and plain matmuls instead of einsum.
|
|
61
|
-
#
|
|
62
|
-
# Readout. Exact for the stored state: sequential conditional sampling, patch by patch, from the
|
|
63
|
-
# exported kets, with shots grouped by prefix. On an open chain the canonical form (centre at patch 0)
|
|
64
|
-
# makes each step a local marginal. On a ring, right environments carry the open wrap index, at a cost
|
|
65
|
-
# of (chi * chi_wrap)^2 per environment.
|
|
66
|
-
#
|
|
67
|
-
# fidelity_estimate multiplies the kept Schmidt weight (greedy) or sum_g p_g^2 (born) per truncation.
|
|
68
|
-
|
|
69
|
-
import ctypes
|
|
70
|
-
import math
|
|
71
|
-
|
|
72
|
-
import numpy as np
|
|
73
|
-
from .qrack_simulator import QrackSimulator
|
|
74
|
-
from .qrack_system import Qrack
|
|
75
|
-
|
|
76
|
-
# Ket I/O straight into/out of numpy buffers (PyQrack's out_ket()/in_ket() round-trip through Python
|
|
77
|
-
# lists of complex, which dominated runtime). Same library calls, OutKet/InKet, without the copies.
|
|
78
|
-
_REAL = np.float32 if Qrack.fppow < 6 else np.float64
|
|
79
|
-
_CREAL = ctypes.c_float if Qrack.fppow < 6 else ctypes.c_double
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
def _out_ket(sim):
|
|
83
|
-
buf = np.empty(2 << sim.num_qubits(), dtype=_REAL)
|
|
84
|
-
Qrack.qrack_lib.OutKet(sim.sid, buf.ctypes.data_as(ctypes.POINTER(_CREAL)))
|
|
85
|
-
sim._throw_if_error()
|
|
86
|
-
return buf.view(np.complex64 if _REAL is np.float32 else np.complex128).astype(complex)
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
def _in_ket(sim, v):
|
|
90
|
-
buf = np.ascontiguousarray(np.asarray(v, dtype=complex).view(np.float64).astype(_REAL))
|
|
91
|
-
Qrack.qrack_lib.InKet(sim.sid, buf.ctypes.data_as(ctypes.POINTER(_CREAL)))
|
|
92
|
-
sim._throw_if_error()
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
def _bits(dim):
|
|
96
|
-
"""Bond qubits needed for bond dimension dim."""
|
|
97
|
-
return (max(int(dim), 1) - 1).bit_length()
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
def _gram_svd(m):
|
|
101
|
-
"""Left singular vectors and values of a short-wide m (rows <= 2^bonds) via its rows x rows Gram
|
|
102
|
-
matrix: one BLAS product plus a tiny Hermitian eigensolve, instead of a LAPACK SVD of the whole
|
|
103
|
-
patch. Double precision Gram keeps singular values to ~1e-8 relative, well under _TOL."""
|
|
104
|
-
lam, u = np.linalg.eigh(m @ m.conj().T)
|
|
105
|
-
order = np.argsort(lam)[::-1]
|
|
106
|
-
return u[:, order], np.sqrt(np.clip(lam[order], 0, None))
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
def _left_factor(a):
|
|
110
|
-
"""a = q @ r with q's columns orthonormal, through a's columns x columns Gram matrix; modes with
|
|
111
|
-
zero weight are dropped (exactly), so the bond only ever shrinks here."""
|
|
112
|
-
lam, v = np.linalg.eigh(a.conj().T @ a)
|
|
113
|
-
keep = lam > (_TOL * _TOL) * lam[-1]
|
|
114
|
-
keep[-1] = True # never an empty bond (lam[-1] > 0 for a live state)
|
|
115
|
-
s = np.sqrt(lam[keep])
|
|
116
|
-
v = v[:, keep]
|
|
117
|
-
return (a @ v) / s[None, :], s[:, None] * v.conj().T
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
_X = [0, 1, 1, 0]
|
|
121
|
-
_Y = [0, -1j, 1j, 0]
|
|
122
|
-
_Z = [1, 0, 0, -1]
|
|
123
|
-
_TOL = 1e-6 # relative singular-value floor treated as exactly zero (Qrack is single precision)
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
class QrackBridge:
|
|
127
|
-
def __init__(self, qubit_count, max_bonds=6, seed=None, truncation="greedy", patches=2, wrap=False,
|
|
128
|
-
lazy_bonds=0, max_patch_qubits=None, _clone=None):
|
|
129
|
-
if _clone is not None:
|
|
130
|
-
src = _clone
|
|
131
|
-
for k in ("n", "P", "ring", "max_bonds", "lazy_bonds", "max_patch_qubits", "truncation",
|
|
132
|
-
"fidelity_estimate", "truncations", "flushes",
|
|
133
|
-
"peak_bonds", "center", "_wrap_touched"):
|
|
134
|
-
setattr(self, k, getattr(src, k))
|
|
135
|
-
self.part = [list(x) for x in src.part]
|
|
136
|
-
self.start = list(src.start)
|
|
137
|
-
self.side = dict(src.side)
|
|
138
|
-
self.layout = [list(x) for x in src.layout]
|
|
139
|
-
self.bond = list(src.bond)
|
|
140
|
-
self.sim = [s.clone() for s in src.sim]
|
|
141
|
-
self._touched = set(src._touched)
|
|
142
|
-
self.rng = np.random.default_rng(int(src.rng.integers(1 << 62)))
|
|
143
|
-
return
|
|
144
|
-
if truncation not in ("greedy", "born"):
|
|
145
|
-
raise ValueError("truncation must be 'greedy' or 'born'")
|
|
146
|
-
if not 1 <= patches <= qubit_count:
|
|
147
|
-
raise ValueError("need 1 <= patches <= qubit_count")
|
|
148
|
-
self.n = qubit_count
|
|
149
|
-
self.P = patches
|
|
150
|
-
self.ring = bool(wrap) and patches >= 3
|
|
151
|
-
base, rem = divmod(qubit_count, patches)
|
|
152
|
-
sizes = [base + (1 if p >= patches - rem else 0) for p in range(patches)]
|
|
153
|
-
self.start = [sum(sizes[:p]) for p in range(patches)]
|
|
154
|
-
self.part = [list(range(self.start[p], self.start[p] + sizes[p])) for p in range(patches)]
|
|
155
|
-
self.side = {q: (p, i) for p, qs in enumerate(self.part) for i, q in enumerate(qs)}
|
|
156
|
-
# internal qubit order of each patch sim: ("d", i) data, ("L", j) / ("R", j) bond slots
|
|
157
|
-
self.layout = [[("d", i) for i in range(len(qs))] for qs in self.part]
|
|
158
|
-
self.sim = [QrackSimulator(len(qs)) for qs in self.part]
|
|
159
|
-
self.bond = [0] * (patches if self.ring else patches - 1) # cut c joins patch c (R) to c+1 (L)
|
|
160
|
-
self.max_bonds = max_bonds
|
|
161
|
-
if lazy_bonds < 0:
|
|
162
|
-
raise ValueError("lazy_bonds must be >= 0")
|
|
163
|
-
self.lazy_bonds = lazy_bonds
|
|
164
|
-
self.max_patch_qubits = max_patch_qubits
|
|
165
|
-
self.flushes = 0
|
|
166
|
-
self.truncation = truncation
|
|
167
|
-
self.fidelity_estimate = 1.0
|
|
168
|
-
self.truncations = 0
|
|
169
|
-
self.peak_bonds = 0
|
|
170
|
-
self.center = 0
|
|
171
|
-
self._touched = set()
|
|
172
|
-
self._wrap_touched = False
|
|
173
|
-
self.rng = np.random.default_rng(seed)
|
|
174
|
-
|
|
175
|
-
def clone(self):
|
|
176
|
-
return QrackBridge(None, _clone=self)
|
|
177
|
-
|
|
178
|
-
# --- chain geometry --------------------------------------------------------
|
|
179
|
-
|
|
180
|
-
def _nd(self, p):
|
|
181
|
-
return len(self.part[p])
|
|
182
|
-
|
|
183
|
-
def _lcut(self, p):
|
|
184
|
-
if p > 0:
|
|
185
|
-
return p - 1
|
|
186
|
-
return self.P - 1 if self.ring else None
|
|
187
|
-
|
|
188
|
-
def _rcut(self, p):
|
|
189
|
-
return p if (p < self.P - 1 or self.ring) else None
|
|
190
|
-
|
|
191
|
-
def _dims(self, p):
|
|
192
|
-
lc, rc = self._lcut(p), self._rcut(p)
|
|
193
|
-
bl = 0 if lc is None else self.bond[lc]
|
|
194
|
-
br = 0 if rc is None else self.bond[rc]
|
|
195
|
-
return bl, br
|
|
196
|
-
|
|
197
|
-
def _path(self, pa, pb):
|
|
198
|
-
"""Patches visited from pa to pb along the chain (shorter way round on a ring)."""
|
|
199
|
-
step = 1 if pb > pa else -1
|
|
200
|
-
if self.ring:
|
|
201
|
-
right = (pb - pa) % self.P
|
|
202
|
-
step = 1 if right <= self.P - right else -1
|
|
203
|
-
path = [pa]
|
|
204
|
-
while path[-1] != pb:
|
|
205
|
-
path.append((path[-1] + step) % self.P)
|
|
206
|
-
return path
|
|
207
|
-
|
|
208
|
-
def _new_bond(self, here, there):
|
|
209
|
-
"""Fresh bond pair on the cut between adjacent patches here and there; returns (id here, id there)."""
|
|
210
|
-
rightward = there == ((here + 1) % self.P if self.ring else here + 1)
|
|
211
|
-
c = here if rightward else there
|
|
212
|
-
j = self.bond[c]
|
|
213
|
-
self.bond[c] += 1
|
|
214
|
-
self.peak_bonds = max(self.peak_bonds, self.bond[c])
|
|
215
|
-
if self.ring and c == self.P - 1:
|
|
216
|
-
self._wrap_touched = True
|
|
217
|
-
ids = {}
|
|
218
|
-
for p, tag in ((c, ("R", j)), ((c + 1) % self.P, ("L", j))):
|
|
219
|
-
qid = len(self.layout[p])
|
|
220
|
-
self.sim[p].allocate_qubit(qid)
|
|
221
|
-
self.layout[p].append(tag)
|
|
222
|
-
ids[p] = qid
|
|
223
|
-
return ids[here], ids[there]
|
|
224
|
-
|
|
225
|
-
def _new_scratch(self, p):
|
|
226
|
-
"""Fresh |0> working qubit in patch p; it is returned to |0> before any recompression."""
|
|
227
|
-
qid = len(self.layout[p])
|
|
228
|
-
self.sim[p].allocate_qubit(qid)
|
|
229
|
-
self.layout[p].append(("0", qid))
|
|
230
|
-
return qid
|
|
231
|
-
|
|
232
|
-
def _ship(self, path, src):
|
|
233
|
-
"""Teleport the state of qubit src (in patch path[0]) onto a fresh scratch qubit in patch
|
|
234
|
-
path[-1], through one new bond per cut: src is SWAPped onto the outgoing bond (src left |0>),
|
|
235
|
-
relays are identity wires (H in; CNOT in -> out), and the destination Bell-pairs its incoming
|
|
236
|
-
bond with the scratch qubit (H in; CNOT in -> scratch). Returns the scratch qubit's id."""
|
|
237
|
-
out, inc = self._new_bond(path[0], path[1])
|
|
238
|
-
self.sim[path[0]].swap(src, out)
|
|
239
|
-
for k in range(1, len(path) - 1):
|
|
240
|
-
s = self.sim[path[k]]
|
|
241
|
-
s.h(inc)
|
|
242
|
-
out, nxt = self._new_bond(path[k], path[k + 1])
|
|
243
|
-
s.mcx([inc], out)
|
|
244
|
-
inc = nxt
|
|
245
|
-
s = self.sim[path[-1]]
|
|
246
|
-
z = self._new_scratch(path[-1])
|
|
247
|
-
s.h(inc)
|
|
248
|
-
s.mcx([inc], z)
|
|
249
|
-
return z
|
|
250
|
-
|
|
251
|
-
def _unship(self, path, z, dst):
|
|
252
|
-
"""Teleport scratch qubit z (in patch path[0]) back onto qubit dst (|0>, in patch path[-1])."""
|
|
253
|
-
out, inc = self._new_bond(path[0], path[1])
|
|
254
|
-
self.sim[path[0]].swap(z, out) # z back to |0>
|
|
255
|
-
for k in range(1, len(path) - 1):
|
|
256
|
-
s = self.sim[path[k]]
|
|
257
|
-
s.h(inc)
|
|
258
|
-
out, nxt = self._new_bond(path[k], path[k + 1])
|
|
259
|
-
s.mcx([inc], out)
|
|
260
|
-
inc = nxt
|
|
261
|
-
s = self.sim[path[-1]]
|
|
262
|
-
s.h(inc)
|
|
263
|
-
s.mcx([inc], dst)
|
|
264
|
-
|
|
265
|
-
def _loc(self, q):
|
|
266
|
-
p, i = self.side[q]
|
|
267
|
-
return self.sim[p], p, i
|
|
268
|
-
|
|
269
|
-
# --- local gates ---------------------------------------------------------
|
|
270
|
-
|
|
271
|
-
def u(self, q, th, ph, lm):
|
|
272
|
-
s, _, i = self._loc(q)
|
|
273
|
-
s.u(i, th, ph, lm)
|
|
274
|
-
|
|
275
|
-
def x(self, q):
|
|
276
|
-
s, _, i = self._loc(q)
|
|
277
|
-
s.x(i)
|
|
278
|
-
|
|
279
|
-
def h(self, q):
|
|
280
|
-
s, _, i = self._loc(q)
|
|
281
|
-
s.h(i)
|
|
282
|
-
|
|
283
|
-
def s(self, q):
|
|
284
|
-
s, _, i = self._loc(q)
|
|
285
|
-
s.s(i)
|
|
286
|
-
|
|
287
|
-
def adjs(self, q):
|
|
288
|
-
s, _, i = self._loc(q)
|
|
289
|
-
s.adjs(i)
|
|
290
|
-
|
|
291
|
-
# --- controlled gates, local or bridged ----------------------------------
|
|
292
|
-
|
|
293
|
-
def _controlled(self, c, t, mtrx, anti):
|
|
294
|
-
sc, pc, ic = self._loc(c)
|
|
295
|
-
st, pt, it = self._loc(t)
|
|
296
|
-
if pc == pt:
|
|
297
|
-
(sc.macmtrx if anti else sc.mcmtrx)([ic], mtrx, it)
|
|
298
|
-
return
|
|
299
|
-
path = self._path(pc, pt)
|
|
300
|
-
out, inc = self._new_bond(path[0], path[1])
|
|
301
|
-
(sc.macx if anti else sc.mcx)([ic], out)
|
|
302
|
-
for k in range(1, len(path) - 1): # relay patches: pass the copy of c along
|
|
303
|
-
s = self.sim[path[k]]
|
|
304
|
-
s.h(inc)
|
|
305
|
-
out, nxt = self._new_bond(path[k], path[k + 1])
|
|
306
|
-
s.mcx([inc], out)
|
|
307
|
-
inc = nxt
|
|
308
|
-
st.h(inc)
|
|
309
|
-
st.mcmtrx([inc], mtrx, it)
|
|
310
|
-
self._touched.update(path)
|
|
311
|
-
self._maybe_compress()
|
|
312
|
-
|
|
313
|
-
def mcx(self, c, t): self._controlled(c[0], t, _X, False)
|
|
314
|
-
def mcy(self, c, t): self._controlled(c[0], t, _Y, False)
|
|
315
|
-
def mcz(self, c, t): self._controlled(c[0], t, _Z, False)
|
|
316
|
-
def macx(self, c, t): self._controlled(c[0], t, _X, True)
|
|
317
|
-
def macy(self, c, t): self._controlled(c[0], t, _Y, True)
|
|
318
|
-
def macz(self, c, t): self._controlled(c[0], t, _Z, True)
|
|
319
|
-
|
|
320
|
-
def cx(self, a, b): self.mcx([a], b)
|
|
321
|
-
def cy(self, a, b): self.mcy([a], b)
|
|
322
|
-
def cz(self, a, b): self.mcz([a], b)
|
|
323
|
-
|
|
324
|
-
def _pair_gate(self, a, b, op):
|
|
325
|
-
"""Any two-qubit gate across patches: ship a's state into b's patch, apply the gate natively
|
|
326
|
-
there, ship it back. Exactly two bonds per cut crossed (operator-Schmidt rank <= 4), and one
|
|
327
|
-
recompression for the whole gate."""
|
|
328
|
-
sa, pa, ia = self._loc(a)
|
|
329
|
-
sb, pb, ib = self._loc(b)
|
|
330
|
-
if pa == pb:
|
|
331
|
-
getattr(sa, op)(ia, ib)
|
|
332
|
-
return
|
|
333
|
-
path = self._path(pa, pb)
|
|
334
|
-
z = self._ship(path, ia)
|
|
335
|
-
getattr(sb, op)(z, ib)
|
|
336
|
-
self._unship(path[::-1], z, ia)
|
|
337
|
-
self._touched.update(path)
|
|
338
|
-
self._maybe_compress()
|
|
339
|
-
|
|
340
|
-
def swap(self, a, b): self._pair_gate(a, b, "swap")
|
|
341
|
-
def iswap(self, a, b): self._pair_gate(a, b, "iswap")
|
|
342
|
-
def adjiswap(self, a, b): self._pair_gate(a, b, "adjiswap")
|
|
343
|
-
|
|
344
|
-
# --- patch tensors through the kets --------------------------------------
|
|
345
|
-
|
|
346
|
-
def _tensor(self, p):
|
|
347
|
-
"""Patch p's ket as A[l, d, r] (left bonds, data, right bonds), whatever its internal order."""
|
|
348
|
-
lay = self.layout[p]
|
|
349
|
-
k = len(lay)
|
|
350
|
-
bl, br = self._dims(p)
|
|
351
|
-
nd = self._nd(p)
|
|
352
|
-
v = _out_ket(self.sim[p])
|
|
353
|
-
order = ([("L", j) for j in reversed(range(bl))] + [("d", i) for i in reversed(range(nd))]
|
|
354
|
-
+ [("R", j) for j in reversed(range(br))])
|
|
355
|
-
t = v.reshape([2] * k)
|
|
356
|
-
if any(tag[0] == "0" for tag in lay): # scratch qubits are back in |0>: project them out
|
|
357
|
-
t = t[tuple(0 if lay[k - 1 - x][0] == "0" else slice(None) for x in range(k))]
|
|
358
|
-
lay = [tag for tag in lay if tag[0] != "0"]
|
|
359
|
-
k = len(lay)
|
|
360
|
-
pos = {tag: x for x, tag in enumerate(lay)}
|
|
361
|
-
t = t.transpose([k - 1 - pos[tag] for tag in order])
|
|
362
|
-
return t.reshape(1 << bl, 1 << nd, 1 << br)
|
|
363
|
-
|
|
364
|
-
def _store(self, p, a):
|
|
365
|
-
"""Write A[l, d, r] back as a fresh patch sim: data low, then L bonds, then R bonds."""
|
|
366
|
-
bl, br = self._dims(p)
|
|
367
|
-
nd = self._nd(p)
|
|
368
|
-
full = np.zeros((1 << bl, 1 << nd, 1 << br), dtype=complex)
|
|
369
|
-
full[: a.shape[0], :, : a.shape[2]] = a
|
|
370
|
-
v = full.transpose(2, 0, 1).reshape(-1)
|
|
371
|
-
v = v / np.linalg.norm(v)
|
|
372
|
-
self.layout[p] = [("d", i) for i in range(nd)] + [("L", j) for j in range(bl)] + [("R", j) for j in range(br)]
|
|
373
|
-
self.sim[p] = QrackSimulator(nd + bl + br)
|
|
374
|
-
_in_ket(self.sim[p], v)
|
|
375
|
-
|
|
376
|
-
# --- recompression -------------------------------------------------------
|
|
377
|
-
|
|
378
|
-
def _select(self, sv, exact_only):
|
|
379
|
-
if sv[0] <= 0:
|
|
380
|
-
return np.arange(1)
|
|
381
|
-
live = int(np.sum(sv > _TOL * sv[0]))
|
|
382
|
-
b_exact = _bits(live)
|
|
383
|
-
b_new = b_exact if exact_only else min(b_exact, self.max_bonds)
|
|
384
|
-
keep = min(live, 1 << b_new)
|
|
385
|
-
if keep >= live:
|
|
386
|
-
return np.arange(keep)
|
|
387
|
-
w = sv[:live] ** 2
|
|
388
|
-
self.truncations += 1
|
|
389
|
-
if self.truncation == "greedy":
|
|
390
|
-
self.fidelity_estimate *= float(np.sum(w[:keep]) / np.sum(w))
|
|
391
|
-
return np.arange(keep)
|
|
392
|
-
groups = [np.arange(i, min(i + keep, live)) for i in range(0, live, keep)]
|
|
393
|
-
pg = np.array([np.sum(w[g]) for g in groups]) / np.sum(w)
|
|
394
|
-
self.fidelity_estimate *= float(np.sum(pg ** 2))
|
|
395
|
-
return groups[int(self.rng.choice(len(groups), p=pg))]
|
|
396
|
-
|
|
397
|
-
def _sweep(self, lo, hi, exact_only):
|
|
398
|
-
"""Canonicalize and truncate inner cuts over [lo, hi] (plus up to the centre); centre ends at lo."""
|
|
399
|
-
start, end = min(lo, self.center), max(hi, self.center)
|
|
400
|
-
if start == end:
|
|
401
|
-
self.center = lo
|
|
402
|
-
return
|
|
403
|
-
T = {k: self._tensor(k) for k in range(start, end + 1)}
|
|
404
|
-
for k in range(start, end): # left-isometric up to the centre at `end`
|
|
405
|
-
l, d, r = T[k].shape
|
|
406
|
-
q, rr = _left_factor(T[k].reshape(l * d, r)) # exact; also drops zero modes
|
|
407
|
-
T[k] = q.reshape(l, d, -1)
|
|
408
|
-
nl, nd_, nr = T[k + 1].shape
|
|
409
|
-
T[k + 1] = (rr @ T[k + 1].reshape(nl, nd_ * nr)).reshape(-1, nd_, nr)
|
|
410
|
-
self.bond[k] = _bits(q.shape[1])
|
|
411
|
-
for k in range(end, lo, -1): # right-isometric back down to `lo`
|
|
412
|
-
l, d, r = T[k].shape
|
|
413
|
-
m = T[k].reshape(l, d * r)
|
|
414
|
-
u, sv = _gram_svd(m)
|
|
415
|
-
idx = self._select(sv, exact_only)
|
|
416
|
-
us = u[:, idx]
|
|
417
|
-
T[k] = ((us.conj().T @ m) / sv[idx][:, None]).reshape(len(idx), d, r)
|
|
418
|
-
pl, pd, pr = T[k - 1].shape
|
|
419
|
-
T[k - 1] = (T[k - 1].reshape(pl * pd, pr) @ (us * sv[idx][None, :])).reshape(pl, pd, -1)
|
|
420
|
-
self.bond[k - 1] = _bits(len(idx))
|
|
421
|
-
for k, a in T.items():
|
|
422
|
-
self._store(k, a)
|
|
423
|
-
self.center = lo
|
|
424
|
-
|
|
425
|
-
def _compress_wrap(self, exact_only):
|
|
426
|
-
"""Ring only: recompress the wrap cut (P-1 | 0) locally, QR both sides and SVD of the core."""
|
|
427
|
-
P = self.P
|
|
428
|
-
a, b = self._tensor(P - 1), self._tensor(0)
|
|
429
|
-
l, d, w = a.shape
|
|
430
|
-
_, d0, r0 = b.shape
|
|
431
|
-
qa, ra = np.linalg.qr(a.reshape(l * d, w))
|
|
432
|
-
qb, rb = np.linalg.qr(b.reshape(w, d0 * r0).T)
|
|
433
|
-
u, sv, vh = np.linalg.svd(ra @ rb.T)
|
|
434
|
-
idx = self._select(sv, exact_only)
|
|
435
|
-
self.bond[P - 1] = _bits(len(idx))
|
|
436
|
-
self._store(P - 1, ((qa @ u[:, idx]) * sv[idx][None, :]).reshape(l, d, -1))
|
|
437
|
-
self._store(0, (qb @ vh[idx, :].T).T.reshape(-1, d0, r0))
|
|
438
|
-
|
|
439
|
-
def _over_budget(self):
|
|
440
|
-
"""Lazy mode: has any cut, or any patch's total width, outgrown its buffer?"""
|
|
441
|
-
if any(b > self.max_bonds + self.lazy_bonds for b in self.bond):
|
|
442
|
-
return True
|
|
443
|
-
if self.max_patch_qubits is not None:
|
|
444
|
-
return any(len(lay) > self.max_patch_qubits for lay in self.layout)
|
|
445
|
-
return False
|
|
446
|
-
|
|
447
|
-
def _maybe_compress(self):
|
|
448
|
-
if not self.lazy_bonds:
|
|
449
|
-
self._compress() # eager: one sweep per bridged gate
|
|
450
|
-
return
|
|
451
|
-
# Lazy: let bridged gates pile up as raw bond qubits and truncate the whole batch in one sweep,
|
|
452
|
-
# only when a cut exceeds max_bonds + lazy_bonds (or a patch exceeds max_patch_qubits).
|
|
453
|
-
if self._over_budget():
|
|
454
|
-
self._compress()
|
|
455
|
-
|
|
456
|
-
def flush(self):
|
|
457
|
-
"""Truncate any buffered bonds back to max_bonds now (readout does this automatically)."""
|
|
458
|
-
self._compress()
|
|
459
|
-
|
|
460
|
-
def _compress(self, exact_only=False):
|
|
461
|
-
if not self._touched:
|
|
462
|
-
return
|
|
463
|
-
if self._wrap_touched:
|
|
464
|
-
self._compress_wrap(exact_only)
|
|
465
|
-
self._touched.update((0, self.P - 1))
|
|
466
|
-
self._sweep(min(self._touched), max(self._touched), exact_only)
|
|
467
|
-
if not exact_only:
|
|
468
|
-
self.flushes += 1
|
|
469
|
-
self._touched.clear()
|
|
470
|
-
self._wrap_touched = False
|
|
471
|
-
|
|
472
|
-
# --- readout -----------------------------------------------------------------
|
|
473
|
-
|
|
474
|
-
def measure_shots(self, qubits, shots):
|
|
475
|
-
self._compress()
|
|
476
|
-
self._sweep(0, 0, exact_only=True) # centre at patch 0: patches 1.. right-isometric
|
|
477
|
-
T = [self._tensor(p) for p in range(self.P)]
|
|
478
|
-
R = None
|
|
479
|
-
if self.ring: # right environments with the wrap index open
|
|
480
|
-
cw = T[0].shape[0]
|
|
481
|
-
eye = np.eye(cw)
|
|
482
|
-
R = [None] * (self.P + 1)
|
|
483
|
-
R[self.P] = np.einsum("rw,sv->rwsv", eye, eye)
|
|
484
|
-
for k in range(self.P - 1, 0, -1):
|
|
485
|
-
R[k] = np.einsum("ldr,rwsv,mds->lwmv", T[k], R[k + 1], T[k].conj(), optimize=True)
|
|
486
|
-
groups = [(eye, shots, 0)]
|
|
487
|
-
else:
|
|
488
|
-
groups = [(np.ones((1, 1)), shots, 0)]
|
|
489
|
-
for k in range(self.P):
|
|
490
|
-
nxt = []
|
|
491
|
-
for X, cnt, bits in groups:
|
|
492
|
-
M = np.einsum("wl,ldr->wdr", X, T[k])
|
|
493
|
-
if R is None:
|
|
494
|
-
p = np.sum(np.abs(M) ** 2, axis=(0, 2))
|
|
495
|
-
else:
|
|
496
|
-
p = np.einsum("wdr,rwsv,vds->d", M, R[k + 1], M.conj(), optimize=True).real
|
|
497
|
-
p = np.clip(p, 0, None)
|
|
498
|
-
p /= p.sum()
|
|
499
|
-
for d, c in enumerate(self.rng.multinomial(cnt, p)):
|
|
500
|
-
if c:
|
|
501
|
-
Y = M[:, d, :]
|
|
502
|
-
nxt.append((Y / np.linalg.norm(Y), int(c), bits | (d << self.start[k])))
|
|
503
|
-
groups = nxt
|
|
504
|
-
out = []
|
|
505
|
-
for _, c, full in groups:
|
|
506
|
-
out += [sum(((full >> q) & 1) << j for j, q in enumerate(qubits))] * c
|
|
507
|
-
self.rng.shuffle(out)
|
|
508
|
-
return out
|
|
509
|
-
|
|
510
|
-
def out_ket(self):
|
|
511
|
-
"""Dense contracted state (2^n), little-endian over logical qubits; for testing."""
|
|
512
|
-
self._compress() # same (flushed) state that measure_shots samples
|
|
513
|
-
C = None
|
|
514
|
-
for p in range(self.P):
|
|
515
|
-
A = self._tensor(p)
|
|
516
|
-
if C is None:
|
|
517
|
-
C = np.einsum("wl,ldr->wdr", np.eye(A.shape[0]), A)
|
|
518
|
-
else:
|
|
519
|
-
w, D, _ = C.shape
|
|
520
|
-
C = np.einsum("wDr,rdq->wdDq", C, A).reshape(w, -1, A.shape[2])
|
|
521
|
-
v = np.einsum("wDw->D", C)
|
|
522
|
-
return v / np.linalg.norm(v)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4}/pyqrack/neuron_activation_fn.py
RENAMED
|
File without changes
|
|
File without changes
|
{pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4}/pyqrack/qrack_ace_backend.py
RENAMED
|
File without changes
|
{pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4}/pyqrack/qrack_ace_mps_backend.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4}/pyqrack/qrack_simulator.py
RENAMED
|
File without changes
|
{pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4}/pyqrack/qrack_stabilizer.py
RENAMED
|
File without changes
|
{pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4}/pyqrack/qrack_system/__init__.py
RENAMED
|
File without changes
|
{pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4}/pyqrack/quimb_circuit_type.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
{pyqrack_cuda_complex128-2.30.2 → pyqrack_cuda_complex128-2.30.4}/pyqrack/stats/quantize_by_range.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|