pyqrack-cpu-complex128 2.30.0__tar.gz → 2.30.1__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.
Files changed (33) hide show
  1. {pyqrack_cpu_complex128-2.30.0/pyqrack_cpu_complex128.egg-info → pyqrack_cpu_complex128-2.30.1}/PKG-INFO +1 -1
  2. pyqrack_cpu_complex128-2.30.1/pyqrack/qrack_bridge.py +419 -0
  3. {pyqrack_cpu_complex128-2.30.0 → pyqrack_cpu_complex128-2.30.1/pyqrack_cpu_complex128.egg-info}/PKG-INFO +1 -1
  4. {pyqrack_cpu_complex128-2.30.0 → pyqrack_cpu_complex128-2.30.1}/setup.py +1 -1
  5. pyqrack_cpu_complex128-2.30.0/pyqrack/qrack_bridge.py +0 -266
  6. {pyqrack_cpu_complex128-2.30.0 → pyqrack_cpu_complex128-2.30.1}/LICENSE +0 -0
  7. {pyqrack_cpu_complex128-2.30.0 → pyqrack_cpu_complex128-2.30.1}/MANIFEST.in +0 -0
  8. {pyqrack_cpu_complex128-2.30.0 → pyqrack_cpu_complex128-2.30.1}/Makefile +0 -0
  9. {pyqrack_cpu_complex128-2.30.0 → pyqrack_cpu_complex128-2.30.1}/README.md +0 -0
  10. {pyqrack_cpu_complex128-2.30.0 → pyqrack_cpu_complex128-2.30.1}/pyproject.toml +0 -0
  11. {pyqrack_cpu_complex128-2.30.0 → pyqrack_cpu_complex128-2.30.1}/pyqrack/__init__.py +0 -0
  12. {pyqrack_cpu_complex128-2.30.0 → pyqrack_cpu_complex128-2.30.1}/pyqrack/neuron_activation_fn.py +0 -0
  13. {pyqrack_cpu_complex128-2.30.0 → pyqrack_cpu_complex128-2.30.1}/pyqrack/pauli.py +0 -0
  14. {pyqrack_cpu_complex128-2.30.0 → pyqrack_cpu_complex128-2.30.1}/pyqrack/qrack_ace_backend.py +0 -0
  15. {pyqrack_cpu_complex128-2.30.0 → pyqrack_cpu_complex128-2.30.1}/pyqrack/qrack_ace_mps_backend.py +0 -0
  16. {pyqrack_cpu_complex128-2.30.0 → pyqrack_cpu_complex128-2.30.1}/pyqrack/qrack_circuit.py +0 -0
  17. {pyqrack_cpu_complex128-2.30.0 → pyqrack_cpu_complex128-2.30.1}/pyqrack/qrack_near_clifford_qec_backend.py +0 -0
  18. {pyqrack_cpu_complex128-2.30.0 → pyqrack_cpu_complex128-2.30.1}/pyqrack/qrack_neuron.py +0 -0
  19. {pyqrack_cpu_complex128-2.30.0 → pyqrack_cpu_complex128-2.30.1}/pyqrack/qrack_neuron_torch_layer.py +0 -0
  20. {pyqrack_cpu_complex128-2.30.0 → pyqrack_cpu_complex128-2.30.1}/pyqrack/qrack_simulator.py +0 -0
  21. {pyqrack_cpu_complex128-2.30.0 → pyqrack_cpu_complex128-2.30.1}/pyqrack/qrack_stabilizer.py +0 -0
  22. {pyqrack_cpu_complex128-2.30.0 → pyqrack_cpu_complex128-2.30.1}/pyqrack/qrack_system/__init__.py +0 -0
  23. {pyqrack_cpu_complex128-2.30.0 → pyqrack_cpu_complex128-2.30.1}/pyqrack/qrack_system/qrack_system.py +0 -0
  24. {pyqrack_cpu_complex128-2.30.0 → pyqrack_cpu_complex128-2.30.1}/pyqrack/quimb_circuit_type.py +0 -0
  25. {pyqrack_cpu_complex128-2.30.0 → pyqrack_cpu_complex128-2.30.1}/pyqrack/stats/__init__.py +0 -0
  26. {pyqrack_cpu_complex128-2.30.0 → pyqrack_cpu_complex128-2.30.1}/pyqrack/stats/load_quantized_data.py +0 -0
  27. {pyqrack_cpu_complex128-2.30.0 → pyqrack_cpu_complex128-2.30.1}/pyqrack/stats/quantize_by_range.py +0 -0
  28. {pyqrack_cpu_complex128-2.30.0 → pyqrack_cpu_complex128-2.30.1}/pyqrack_cpu_complex128.egg-info/SOURCES.txt +0 -0
  29. {pyqrack_cpu_complex128-2.30.0 → pyqrack_cpu_complex128-2.30.1}/pyqrack_cpu_complex128.egg-info/dependency_links.txt +0 -0
  30. {pyqrack_cpu_complex128-2.30.0 → pyqrack_cpu_complex128-2.30.1}/pyqrack_cpu_complex128.egg-info/not-zip-safe +0 -0
  31. {pyqrack_cpu_complex128-2.30.0 → pyqrack_cpu_complex128-2.30.1}/pyqrack_cpu_complex128.egg-info/requires.txt +0 -0
  32. {pyqrack_cpu_complex128-2.30.0 → pyqrack_cpu_complex128-2.30.1}/pyqrack_cpu_complex128.egg-info/top_level.txt +0 -0
  33. {pyqrack_cpu_complex128-2.30.0 → pyqrack_cpu_complex128-2.30.1}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyqrack-cpu-complex128
3
- Version: 2.30.0
3
+ Version: 2.30.1
4
4
  Summary: pyqrack - Pure Python vm6502q/qrack Wrapper
5
5
  Home-page: https://github.com/vm6502q/pyqrack
6
6
  Author: Daniel Strano
@@ -0,0 +1,419 @@
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 is 3 CNOTs; iSWAP is (S x S), CZ, SWAP; iSWAP^dagger is SWAP, CZ, (S^dag x S^dag).
28
+ #
29
+ # Recompression after each bridged two-qubit gate (one MPS-style sweep over the touched segment):
30
+ # - Gates on data qubits are unitary on each patch's (left, data) and (data, right) row spaces, so
31
+ # they preserve left/right isometry. Only patches on a gate's path lose it.
32
+ # - An orthogonality centre is tracked. QR-sweep left-to-right over the touched segment (and up to
33
+ # the centre), then SVD-sweep right-to-left, keeping the largest singular values per cut (exact
34
+ # when only zeros are dropped; above max_bonds, greedy or Born-rule group selection).
35
+ # - On an open chain the environment is isometric at every SVD, so these are the true Schmidt values
36
+ # of the state and each truncation is the optimal one for that cut, as with 2 patches.
37
+ # - On a ring, the wrap cut is first recompressed between patches P-1 and 0 locally (QR of both
38
+ # sides, SVD of the core), then the open sweep runs with the wrap bond treated as a physical leg.
39
+ # Dropping only zeros is still exact. Truncating the wrap cut, and truncating inner cuts while wrap
40
+ # bonds are live, is locally optimal but not globally optimal (a periodic MPS has no canonical
41
+ # form), so fidelity_estimate is an estimate there and not the kept Schmidt weight.
42
+ # Nothing larger than the patch kets and per-cut cores is ever formed: no density matrix.
43
+ #
44
+ # Readout. Exact for the stored state: sequential conditional sampling, patch by patch, from the
45
+ # exported kets, with shots grouped by prefix. On an open chain the canonical form (centre at patch 0)
46
+ # makes each step a local marginal. On a ring, right environments carry the open wrap index, at a cost
47
+ # of (chi * chi_wrap)^2 per environment.
48
+ #
49
+ # fidelity_estimate multiplies the kept Schmidt weight (greedy) or sum_g p_g^2 (born) per truncation.
50
+
51
+ import ctypes
52
+ import math
53
+
54
+ import numpy as np
55
+ from .qrack_simulator import QrackSimulator
56
+ from .qrack_system import Qrack
57
+
58
+ # Ket I/O straight into/out of numpy buffers (PyQrack's out_ket()/in_ket() round-trip through Python
59
+ # lists of complex, which dominated runtime). Same library calls, OutKet/InKet, without the copies.
60
+ _REAL = np.float32 if Qrack.fppow < 6 else np.float64
61
+ _CREAL = ctypes.c_float if Qrack.fppow < 6 else ctypes.c_double
62
+
63
+
64
+ def _out_ket(sim):
65
+ buf = np.empty(2 << sim.num_qubits(), dtype=_REAL)
66
+ Qrack.qrack_lib.OutKet(sim.sid, buf.ctypes.data_as(ctypes.POINTER(_CREAL)))
67
+ sim._throw_if_error()
68
+ return buf.view(np.complex64 if _REAL is np.float32 else np.complex128).astype(complex)
69
+
70
+
71
+ def _in_ket(sim, v):
72
+ buf = np.ascontiguousarray(np.asarray(v, dtype=complex).view(np.float64).astype(_REAL))
73
+ Qrack.qrack_lib.InKet(sim.sid, buf.ctypes.data_as(ctypes.POINTER(_CREAL)))
74
+ sim._throw_if_error()
75
+
76
+
77
+ def _bits(dim):
78
+ """Bond qubits needed for bond dimension dim."""
79
+ return (max(int(dim), 1) - 1).bit_length()
80
+
81
+
82
+ _X = [0, 1, 1, 0]
83
+ _Y = [0, -1j, 1j, 0]
84
+ _Z = [1, 0, 0, -1]
85
+ _TOL = 1e-6 # relative singular-value floor treated as exactly zero (Qrack is single precision)
86
+
87
+
88
+ class QrackBridge:
89
+ def __init__(self, qubit_count, max_bonds=6, seed=None, truncation="greedy", patches=2, wrap=False,
90
+ _clone=None):
91
+ if _clone is not None:
92
+ src = _clone
93
+ for k in ("n", "P", "ring", "max_bonds", "truncation", "fidelity_estimate", "truncations",
94
+ "peak_bonds", "center", "_wrap_touched"):
95
+ setattr(self, k, getattr(src, k))
96
+ self.part = [list(x) for x in src.part]
97
+ self.start = list(src.start)
98
+ self.side = dict(src.side)
99
+ self.layout = [list(x) for x in src.layout]
100
+ self.bond = list(src.bond)
101
+ self.sim = [s.clone() for s in src.sim]
102
+ self._touched = set(src._touched)
103
+ self._defer = False
104
+ self.rng = np.random.default_rng(int(src.rng.integers(1 << 62)))
105
+ return
106
+ if truncation not in ("greedy", "born"):
107
+ raise ValueError("truncation must be 'greedy' or 'born'")
108
+ if not 1 <= patches <= qubit_count:
109
+ raise ValueError("need 1 <= patches <= qubit_count")
110
+ self.n = qubit_count
111
+ self.P = patches
112
+ self.ring = bool(wrap) and patches >= 3
113
+ base, rem = divmod(qubit_count, patches)
114
+ sizes = [base + (1 if p >= patches - rem else 0) for p in range(patches)]
115
+ self.start = [sum(sizes[:p]) for p in range(patches)]
116
+ self.part = [list(range(self.start[p], self.start[p] + sizes[p])) for p in range(patches)]
117
+ self.side = {q: (p, i) for p, qs in enumerate(self.part) for i, q in enumerate(qs)}
118
+ # internal qubit order of each patch sim: ("d", i) data, ("L", j) / ("R", j) bond slots
119
+ self.layout = [[("d", i) for i in range(len(qs))] for qs in self.part]
120
+ self.sim = [QrackSimulator(len(qs)) for qs in self.part]
121
+ self.bond = [0] * (patches if self.ring else patches - 1) # cut c joins patch c (R) to c+1 (L)
122
+ self.max_bonds = max_bonds
123
+ self.truncation = truncation
124
+ self.fidelity_estimate = 1.0
125
+ self.truncations = 0
126
+ self.peak_bonds = 0
127
+ self.center = 0
128
+ self._touched = set()
129
+ self._wrap_touched = False
130
+ self._defer = False
131
+ self.rng = np.random.default_rng(seed)
132
+
133
+ def clone(self):
134
+ return QrackBridge(None, _clone=self)
135
+
136
+ # --- chain geometry --------------------------------------------------------
137
+
138
+ def _nd(self, p):
139
+ return len(self.part[p])
140
+
141
+ def _lcut(self, p):
142
+ if p > 0:
143
+ return p - 1
144
+ return self.P - 1 if self.ring else None
145
+
146
+ def _rcut(self, p):
147
+ return p if (p < self.P - 1 or self.ring) else None
148
+
149
+ def _dims(self, p):
150
+ lc, rc = self._lcut(p), self._rcut(p)
151
+ bl = 0 if lc is None else self.bond[lc]
152
+ br = 0 if rc is None else self.bond[rc]
153
+ return bl, br
154
+
155
+ def _path(self, pa, pb):
156
+ """Patches visited from pa to pb along the chain (shorter way round on a ring)."""
157
+ step = 1 if pb > pa else -1
158
+ if self.ring:
159
+ right = (pb - pa) % self.P
160
+ step = 1 if right <= self.P - right else -1
161
+ path = [pa]
162
+ while path[-1] != pb:
163
+ path.append((path[-1] + step) % self.P)
164
+ return path
165
+
166
+ def _new_bond(self, here, there):
167
+ """Fresh bond pair on the cut between adjacent patches here and there; returns (id here, id there)."""
168
+ rightward = there == ((here + 1) % self.P if self.ring else here + 1)
169
+ c = here if rightward else there
170
+ j = self.bond[c]
171
+ self.bond[c] += 1
172
+ self.peak_bonds = max(self.peak_bonds, self.bond[c])
173
+ if self.ring and c == self.P - 1:
174
+ self._wrap_touched = True
175
+ ids = {}
176
+ for p, tag in ((c, ("R", j)), ((c + 1) % self.P, ("L", j))):
177
+ qid = len(self.layout[p])
178
+ self.sim[p].allocate_qubit(qid)
179
+ self.layout[p].append(tag)
180
+ ids[p] = qid
181
+ return ids[here], ids[there]
182
+
183
+ def _loc(self, q):
184
+ p, i = self.side[q]
185
+ return self.sim[p], p, i
186
+
187
+ # --- local gates ---------------------------------------------------------
188
+
189
+ def u(self, q, th, ph, lm):
190
+ s, _, i = self._loc(q)
191
+ s.u(i, th, ph, lm)
192
+
193
+ def x(self, q):
194
+ s, _, i = self._loc(q)
195
+ s.x(i)
196
+
197
+ def h(self, q):
198
+ s, _, i = self._loc(q)
199
+ s.h(i)
200
+
201
+ def s(self, q):
202
+ s, _, i = self._loc(q)
203
+ s.s(i)
204
+
205
+ def adjs(self, q):
206
+ s, _, i = self._loc(q)
207
+ s.adjs(i)
208
+
209
+ # --- controlled gates, local or bridged ----------------------------------
210
+
211
+ def _controlled(self, c, t, mtrx, anti):
212
+ sc, pc, ic = self._loc(c)
213
+ st, pt, it = self._loc(t)
214
+ if pc == pt:
215
+ (sc.macmtrx if anti else sc.mcmtrx)([ic], mtrx, it)
216
+ return
217
+ path = self._path(pc, pt)
218
+ out, inc = self._new_bond(path[0], path[1])
219
+ (sc.macx if anti else sc.mcx)([ic], out)
220
+ for k in range(1, len(path) - 1): # relay patches: pass the copy of c along
221
+ s = self.sim[path[k]]
222
+ s.h(inc)
223
+ out, nxt = self._new_bond(path[k], path[k + 1])
224
+ s.mcx([inc], out)
225
+ inc = nxt
226
+ st.h(inc)
227
+ st.mcmtrx([inc], mtrx, it)
228
+ self._touched.update(path)
229
+ # Inside a SWAP-type gate, recompress exactly between its CNOTs; truncate once at its end.
230
+ self._compress(exact_only=self._defer)
231
+
232
+ def mcx(self, c, t): self._controlled(c[0], t, _X, False)
233
+ def mcy(self, c, t): self._controlled(c[0], t, _Y, False)
234
+ def mcz(self, c, t): self._controlled(c[0], t, _Z, False)
235
+ def macx(self, c, t): self._controlled(c[0], t, _X, True)
236
+ def macy(self, c, t): self._controlled(c[0], t, _Y, True)
237
+ def macz(self, c, t): self._controlled(c[0], t, _Z, True)
238
+
239
+ def cx(self, a, b): self.mcx([a], b)
240
+ def cy(self, a, b): self.mcy([a], b)
241
+ def cz(self, a, b): self.mcz([a], b)
242
+
243
+ def _composite(self, steps):
244
+ outer = self._defer
245
+ self._defer = True
246
+ for f in steps:
247
+ f()
248
+ self._defer = outer
249
+ if not outer:
250
+ self._compress()
251
+
252
+ def swap(self, a, b):
253
+ if self.side[a][0] == self.side[b][0]:
254
+ s, _, i = self._loc(a)
255
+ s.swap(i, self.side[b][1])
256
+ return
257
+ self._composite([lambda: self.mcx([a], b), lambda: self.mcx([b], a), lambda: self.mcx([a], b)])
258
+
259
+ def iswap(self, a, b):
260
+ if self.side[a][0] == self.side[b][0]:
261
+ s, _, i = self._loc(a)
262
+ s.iswap(i, self.side[b][1])
263
+ return
264
+ self._composite([lambda: self.s(a), lambda: self.s(b), lambda: self.mcz([a], b), lambda: self.swap(a, b)])
265
+
266
+ def adjiswap(self, a, b):
267
+ if self.side[a][0] == self.side[b][0]:
268
+ s, _, i = self._loc(a)
269
+ s.adjiswap(i, self.side[b][1])
270
+ return
271
+ self._composite([lambda: self.swap(a, b), lambda: self.mcz([a], b), lambda: self.adjs(a), lambda: self.adjs(b)])
272
+
273
+ # --- patch tensors through the kets --------------------------------------
274
+
275
+ def _tensor(self, p):
276
+ """Patch p's ket as A[l, d, r] (left bonds, data, right bonds), whatever its internal order."""
277
+ lay = self.layout[p]
278
+ k = len(lay)
279
+ bl, br = self._dims(p)
280
+ nd = self._nd(p)
281
+ v = _out_ket(self.sim[p])
282
+ order = ([("L", j) for j in reversed(range(bl))] + [("d", i) for i in reversed(range(nd))]
283
+ + [("R", j) for j in reversed(range(br))])
284
+ pos = {tag: x for x, tag in enumerate(lay)}
285
+ t = v.reshape([2] * k).transpose([k - 1 - pos[tag] for tag in order])
286
+ return t.reshape(1 << bl, 1 << nd, 1 << br)
287
+
288
+ def _store(self, p, a):
289
+ """Write A[l, d, r] back as a fresh patch sim: data low, then L bonds, then R bonds."""
290
+ bl, br = self._dims(p)
291
+ nd = self._nd(p)
292
+ full = np.zeros((1 << bl, 1 << nd, 1 << br), dtype=complex)
293
+ full[: a.shape[0], :, : a.shape[2]] = a
294
+ v = full.transpose(2, 0, 1).reshape(-1)
295
+ v = v / np.linalg.norm(v)
296
+ self.layout[p] = [("d", i) for i in range(nd)] + [("L", j) for j in range(bl)] + [("R", j) for j in range(br)]
297
+ self.sim[p] = QrackSimulator(nd + bl + br)
298
+ _in_ket(self.sim[p], v)
299
+
300
+ # --- recompression -------------------------------------------------------
301
+
302
+ def _select(self, sv, exact_only):
303
+ if sv[0] <= 0:
304
+ return np.arange(1)
305
+ live = int(np.sum(sv > _TOL * sv[0]))
306
+ b_exact = _bits(live)
307
+ b_new = b_exact if exact_only else min(b_exact, self.max_bonds)
308
+ keep = min(live, 1 << b_new)
309
+ if keep >= live:
310
+ return np.arange(keep)
311
+ w = sv[:live] ** 2
312
+ self.truncations += 1
313
+ if self.truncation == "greedy":
314
+ self.fidelity_estimate *= float(np.sum(w[:keep]) / np.sum(w))
315
+ return np.arange(keep)
316
+ groups = [np.arange(i, min(i + keep, live)) for i in range(0, live, keep)]
317
+ pg = np.array([np.sum(w[g]) for g in groups]) / np.sum(w)
318
+ self.fidelity_estimate *= float(np.sum(pg ** 2))
319
+ return groups[int(self.rng.choice(len(groups), p=pg))]
320
+
321
+ def _sweep(self, lo, hi, exact_only):
322
+ """Canonicalize and truncate inner cuts over [lo, hi] (plus up to the centre); centre ends at lo."""
323
+ start, end = min(lo, self.center), max(hi, self.center)
324
+ if start == end:
325
+ self.center = lo
326
+ return
327
+ T = {k: self._tensor(k) for k in range(start, end + 1)}
328
+ for k in range(start, end): # left-isometric up to the centre at `end`
329
+ l, d, r = T[k].shape
330
+ q, rr = np.linalg.qr(T[k].reshape(l * d, r))
331
+ T[k] = q.reshape(l, d, -1)
332
+ T[k + 1] = np.einsum("ab,bdr->adr", rr, T[k + 1])
333
+ self.bond[k] = _bits(q.shape[1])
334
+ for k in range(end, lo, -1): # right-isometric back down to `lo`
335
+ l, d, r = T[k].shape
336
+ u, sv, vh = np.linalg.svd(T[k].reshape(l, d * r), full_matrices=False)
337
+ idx = self._select(sv, exact_only)
338
+ T[k] = vh[idx].reshape(len(idx), d, r)
339
+ T[k - 1] = np.einsum("ldr,rs->lds", T[k - 1], u[:, idx] * sv[idx][None, :])
340
+ self.bond[k - 1] = _bits(len(idx))
341
+ for k, a in T.items():
342
+ self._store(k, a)
343
+ self.center = lo
344
+
345
+ def _compress_wrap(self, exact_only):
346
+ """Ring only: recompress the wrap cut (P-1 | 0) locally, QR both sides and SVD of the core."""
347
+ P = self.P
348
+ a, b = self._tensor(P - 1), self._tensor(0)
349
+ l, d, w = a.shape
350
+ _, d0, r0 = b.shape
351
+ qa, ra = np.linalg.qr(a.reshape(l * d, w))
352
+ qb, rb = np.linalg.qr(b.reshape(w, d0 * r0).T)
353
+ u, sv, vh = np.linalg.svd(ra @ rb.T)
354
+ idx = self._select(sv, exact_only)
355
+ self.bond[P - 1] = _bits(len(idx))
356
+ self._store(P - 1, ((qa @ u[:, idx]) * sv[idx][None, :]).reshape(l, d, -1))
357
+ self._store(0, (qb @ vh[idx, :].T).T.reshape(-1, d0, r0))
358
+
359
+ def _compress(self, exact_only=False):
360
+ if not self._touched:
361
+ return
362
+ if self._wrap_touched:
363
+ self._compress_wrap(exact_only)
364
+ self._touched.update((0, self.P - 1))
365
+ self._sweep(min(self._touched), max(self._touched), exact_only)
366
+ if not exact_only:
367
+ self._touched.clear()
368
+ self._wrap_touched = False
369
+
370
+ # --- readout -----------------------------------------------------------------
371
+
372
+ def measure_shots(self, qubits, shots):
373
+ self._compress()
374
+ self._sweep(0, 0, exact_only=True) # centre at patch 0: patches 1.. right-isometric
375
+ T = [self._tensor(p) for p in range(self.P)]
376
+ R = None
377
+ if self.ring: # right environments with the wrap index open
378
+ cw = T[0].shape[0]
379
+ eye = np.eye(cw)
380
+ R = [None] * (self.P + 1)
381
+ R[self.P] = np.einsum("rw,sv->rwsv", eye, eye)
382
+ for k in range(self.P - 1, 0, -1):
383
+ R[k] = np.einsum("ldr,rwsv,mds->lwmv", T[k], R[k + 1], T[k].conj(), optimize=True)
384
+ groups = [(eye, shots, 0)]
385
+ else:
386
+ groups = [(np.ones((1, 1)), shots, 0)]
387
+ for k in range(self.P):
388
+ nxt = []
389
+ for X, cnt, bits in groups:
390
+ M = np.einsum("wl,ldr->wdr", X, T[k])
391
+ if R is None:
392
+ p = np.sum(np.abs(M) ** 2, axis=(0, 2))
393
+ else:
394
+ p = np.einsum("wdr,rwsv,vds->d", M, R[k + 1], M.conj(), optimize=True).real
395
+ p = np.clip(p, 0, None)
396
+ p /= p.sum()
397
+ for d, c in enumerate(self.rng.multinomial(cnt, p)):
398
+ if c:
399
+ Y = M[:, d, :]
400
+ nxt.append((Y / np.linalg.norm(Y), int(c), bits | (d << self.start[k])))
401
+ groups = nxt
402
+ out = []
403
+ for _, c, full in groups:
404
+ out += [sum(((full >> q) & 1) << j for j, q in enumerate(qubits))] * c
405
+ self.rng.shuffle(out)
406
+ return out
407
+
408
+ def out_ket(self):
409
+ """Dense contracted state (2^n), little-endian over logical qubits; for testing."""
410
+ C = None
411
+ for p in range(self.P):
412
+ A = self._tensor(p)
413
+ if C is None:
414
+ C = np.einsum("wl,ldr->wdr", np.eye(A.shape[0]), A)
415
+ else:
416
+ w, D, _ = C.shape
417
+ C = np.einsum("wDr,rdq->wdDq", C, A).reshape(w, -1, A.shape[2])
418
+ v = np.einsum("wDw->D", C)
419
+ return v / np.linalg.norm(v)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyqrack-cpu-complex128
3
- Version: 2.30.0
3
+ Version: 2.30.1
4
4
  Summary: pyqrack - Pure Python vm6502q/qrack Wrapper
5
5
  Home-page: https://github.com/vm6502q/pyqrack
6
6
  Author: Daniel Strano
@@ -7,7 +7,7 @@ from setuptools import setup
7
7
  from setuptools.command.build_py import build_py
8
8
 
9
9
 
10
- VERSION = "2.30.0"
10
+ VERSION = "2.30.1"
11
11
 
12
12
  # Read long description from README.
13
13
  README_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'README.md')
@@ -1,266 +0,0 @@
1
- # Bridged patching on QrackSimulator patches, recompressed through out_ket()/in_ket().
2
- #
3
- # By (Anthropic) Claude and Dan Strano
4
- #
5
- # Two-patch split: patch A = qubits [0, n // 2), patch B = the rest (first patch rounded down).
6
- #
7
- # Representation. Each patch is ONE QrackSimulator holding its data qubits (low indices) plus exactly
8
- # b bond qubits (high indices), allocated and released as the bridge grows and shrinks. Bond j of
9
- # patch A is paired with bond j of patch B. The represented state is both patch states contracted on
10
- # the live bond pairs with the unnormalized virtual Bell projection sum_k <k|<k|:
11
- #
12
- # |Psi> ~ sum_k <k|psi_A> (x) <k|psi_B> (k over the 2^b bond basis states)
13
- #
14
- # i.e. with each patch's ket read as a (2^n_patch x 2^b) matrix M_A, M_B: Psi = M_A M_B^T.
15
- # Rank chi = 2^b. Every in-patch gate is applied natively, once, to all chi branches at once.
16
- #
17
- # Cross-cut gates by gate teleportation through a fresh bond pair (exact, gates only):
18
- # controlled-U from c (one patch) to t (the other):
19
- # control patch: CNOT c -> bond_b (copy the control into the bond)
20
- # target patch: H bond_b ; controlled-U bond_b -> t
21
- # Contracting on (bond_b, bond_b) enforces equality, which is exactly controlled-U(c -> t).
22
- # SWAP is 3 CNOTs; iSWAP is (S x S), CZ, SWAP; iSWAP^dagger is SWAP, CZ, (S^dag x S^dag).
23
- #
24
- # Recompression after each bridged two-qubit gate: out_ket() both patches, thin QR of each
25
- # (2^n_patch x chi) matrix, SVD of the chi x chi core, keep the largest singular values (exact when
26
- # only zeros are dropped; above max_bonds, greedy or Born-rule group selection), and in_ket() back.
27
- # The singular values are absorbed into patch A, so patch B's bond columns stay orthonormal (B is
28
- # isometric), which makes patch A's own marginal over its data qubits the exact marginal.
29
- # Nothing larger than the kets themselves and a chi x chi core is ever formed: no density matrix,
30
- # no (2^n x 2^n) object of any kind.
31
- #
32
- # Readout (exact for the stored state): sample patch A's data natively with its own measure_shots
33
- # (exact because B is isometric); for each distinct outcome a, patch B's conditional state is
34
- # M_B @ M_A[a, :], sampled in numpy from the exported B ket.
35
- #
36
- # fidelity_estimate multiplies the kept Schmidt weight (greedy) or sum_g p_g^2 (born) per cut.
37
-
38
- import ctypes
39
- import math
40
-
41
- import numpy as np
42
- from .qrack_simulator import QrackSimulator
43
- from .qrack_system import Qrack
44
-
45
- # Ket I/O straight into/out of numpy buffers (PyQrack's out_ket()/in_ket() round-trip through Python
46
- # lists of complex, which dominated runtime). Same library calls, OutKet/InKet, without the copies.
47
- _REAL = np.float32 if Qrack.fppow < 6 else np.float64
48
- _CREAL = ctypes.c_float if Qrack.fppow < 6 else ctypes.c_double
49
-
50
-
51
- def _out_ket(sim):
52
- buf = np.empty(2 << sim.num_qubits(), dtype=_REAL)
53
- Qrack.qrack_lib.OutKet(sim.sid, buf.ctypes.data_as(ctypes.POINTER(_CREAL)))
54
- sim._throw_if_error()
55
- return buf.view(np.complex64 if _REAL is np.float32 else np.complex128).astype(complex)
56
-
57
-
58
- def _in_ket(sim, v):
59
- buf = np.ascontiguousarray(np.asarray(v, dtype=complex).view(np.float64).astype(_REAL))
60
- Qrack.qrack_lib.InKet(sim.sid, buf.ctypes.data_as(ctypes.POINTER(_CREAL)))
61
- sim._throw_if_error()
62
-
63
- _X = [0, 1, 1, 0]
64
- _Y = [0, -1j, 1j, 0]
65
- _Z = [1, 0, 0, -1]
66
- _TOL = 1e-6 # relative singular-value floor treated as exactly zero (Qrack is single precision)
67
-
68
-
69
- class QrackBridge:
70
- def __init__(self, qubit_count, max_bonds=6, seed=None, truncation="greedy", _clone=None):
71
- if _clone is not None:
72
- src = _clone
73
- self.n, self.qa, self.qb, self.side = src.n, src.qa, src.qb, src.side
74
- self.max_bonds, self.truncation = src.max_bonds, src.truncation
75
- self.sim = [s.clone() for s in src.sim]
76
- self.b = src.b
77
- self.fidelity_estimate, self.truncations, self.peak_bonds = src.fidelity_estimate, src.truncations, src.peak_bonds
78
- self._defer = False
79
- self.rng = np.random.default_rng(int(src.rng.integers(1 << 62)))
80
- return
81
- if truncation not in ("greedy", "born"):
82
- raise ValueError("truncation must be 'greedy' or 'born'")
83
- self.n = qubit_count
84
- self.qa = list(range(qubit_count // 2))
85
- self.qb = list(range(qubit_count // 2, qubit_count))
86
- self.side = {q: (0, i) for i, q in enumerate(self.qa)}
87
- self.side.update({q: (1, i) for i, q in enumerate(self.qb)})
88
- self.max_bonds = max_bonds
89
- self.truncation = truncation
90
- self.sim = [QrackSimulator(len(self.qa)), QrackSimulator(len(self.qb))]
91
- self.b = 0
92
- self.fidelity_estimate = 1.0
93
- self.truncations = 0
94
- self.peak_bonds = 0
95
- self._defer = False
96
- self.rng = np.random.default_rng(seed)
97
-
98
- def clone(self):
99
- return QrackBridge(None, _clone=self)
100
-
101
- def _nd(self, p):
102
- return len(self.qa) if p == 0 else len(self.qb)
103
-
104
- def _loc(self, q):
105
- p, i = self.side[q]
106
- return self.sim[p], p, i
107
-
108
- # --- local gates ---------------------------------------------------------
109
-
110
- def u(self, q, th, ph, lm):
111
- s, _, i = self._loc(q)
112
- s.u(i, th, ph, lm)
113
-
114
- def x(self, q):
115
- s, _, i = self._loc(q)
116
- s.x(i)
117
-
118
- def h(self, q):
119
- s, _, i = self._loc(q)
120
- s.h(i)
121
-
122
- def s(self, q):
123
- s, _, i = self._loc(q)
124
- s.s(i)
125
-
126
- def adjs(self, q):
127
- s, _, i = self._loc(q)
128
- s.adjs(i)
129
-
130
- # --- controlled gates, local or bridged ----------------------------------
131
-
132
- def _controlled(self, c, t, mtrx, anti):
133
- sc, pc, ic = self._loc(c)
134
- st, pt, it = self._loc(t)
135
- if pc == pt:
136
- (sc.macmtrx if anti else sc.mcmtrx)([ic], mtrx, it)
137
- return
138
- kc = self._nd(pc) + self.b
139
- kt = self._nd(pt) + self.b
140
- sc.allocate_qubit(kc)
141
- st.allocate_qubit(kt)
142
- (sc.macx if anti else sc.mcx)([ic], kc)
143
- st.h(kt)
144
- st.mcmtrx([kt], mtrx, it)
145
- self.b += 1
146
- self.peak_bonds = max(self.peak_bonds, self.b)
147
- # Inside a SWAP-type gate, recompress exactly between its CNOTs; truncate once at its end.
148
- self._compress(exact_only=self._defer)
149
-
150
- def mcx(self, c, t): self._controlled(c[0], t, _X, False)
151
- def mcy(self, c, t): self._controlled(c[0], t, _Y, False)
152
- def mcz(self, c, t): self._controlled(c[0], t, _Z, False)
153
- def macx(self, c, t): self._controlled(c[0], t, _X, True)
154
- def macy(self, c, t): self._controlled(c[0], t, _Y, True)
155
- def macz(self, c, t): self._controlled(c[0], t, _Z, True)
156
-
157
- def cx(self, a, b): self.mcx([a], b)
158
- def cy(self, a, b): self.mcy([a], b)
159
- def cz(self, a, b): self.mcz([a], b)
160
-
161
- def _composite(self, steps):
162
- outer = self._defer
163
- self._defer = True
164
- for f in steps:
165
- f()
166
- self._defer = outer
167
- if not outer:
168
- self._compress()
169
-
170
- def swap(self, a, b):
171
- if self.side[a][0] == self.side[b][0]:
172
- s, _, i = self._loc(a)
173
- s.swap(i, self.side[b][1])
174
- return
175
- self._composite([lambda: self.mcx([a], b), lambda: self.mcx([b], a), lambda: self.mcx([a], b)])
176
-
177
- def iswap(self, a, b):
178
- if self.side[a][0] == self.side[b][0]:
179
- s, _, i = self._loc(a)
180
- s.iswap(i, self.side[b][1])
181
- return
182
- self._composite([lambda: self.s(a), lambda: self.s(b), lambda: self.mcz([a], b), lambda: self.swap(a, b)])
183
-
184
- def adjiswap(self, a, b):
185
- if self.side[a][0] == self.side[b][0]:
186
- s, _, i = self._loc(a)
187
- s.adjiswap(i, self.side[b][1])
188
- return
189
- self._composite([lambda: self.swap(a, b), lambda: self.mcz([a], b), lambda: self.adjs(a), lambda: self.adjs(b)])
190
-
191
- # --- recompression through the kets --------------------------------------
192
-
193
- def _matrices(self):
194
- """Each patch ket as a (2^n_patch x 2^b) matrix over the live bonds (dead slots are |0>)."""
195
- out = []
196
- for p in (0, 1):
197
- nd = self._nd(p)
198
- v = _out_ket(self.sim[p])
199
- out.append(v.reshape(1 << self.b, 1 << nd).T) # (data, bond): bond = high qubits
200
- return out
201
-
202
- def _store(self, p, mat, b_new):
203
- nd = self._nd(p)
204
- full = np.zeros((1 << b_new, 1 << nd), dtype=complex)
205
- full[: mat.shape[1], :] = mat.T
206
- v = full.reshape(-1)
207
- v = v / np.linalg.norm(v)
208
- self.sim[p] = QrackSimulator(nd + b_new)
209
- _in_ket(self.sim[p], v)
210
-
211
- def _compress(self, exact_only=False):
212
- if self.b == 0:
213
- return
214
- ma, mb = self._matrices()
215
- qa_, ra = np.linalg.qr(ma)
216
- qb_, rb = np.linalg.qr(mb)
217
- u, sv, vh = np.linalg.svd(ra @ rb.T)
218
- if sv[0] <= 0:
219
- return
220
- live = int(np.sum(sv > _TOL * sv[0]))
221
- b_exact = int(math.ceil(math.log2(max(live, 1))))
222
- b_new = b_exact if exact_only else min(b_exact, self.max_bonds)
223
- keep = min(live, 1 << b_new)
224
- w = sv ** 2
225
- if keep < live:
226
- self.truncations += 1
227
- if self.truncation == "greedy":
228
- idx = np.arange(keep)
229
- self.fidelity_estimate *= float(np.sum(w[:keep]) / np.sum(w[:live]))
230
- else:
231
- groups = [np.arange(i, min(i + keep, live)) for i in range(0, live, keep)]
232
- pg = np.array([np.sum(w[g]) for g in groups]) / np.sum(w[:live])
233
- idx = groups[int(self.rng.choice(len(groups), p=pg))]
234
- self.fidelity_estimate *= float(np.sum(pg ** 2))
235
- else:
236
- idx = np.arange(keep)
237
- new_a = (qa_ @ u[:, idx]) * sv[idx][None, :] # singular values absorbed into patch A
238
- new_b = qb_ @ vh[idx, :].T # orthonormal columns: patch B isometric
239
- self._store(0, new_a, b_new)
240
- self._store(1, new_b, b_new)
241
- self.b = b_new
242
-
243
- # --- readout -----------------------------------------------------------------
244
-
245
- def measure_shots(self, qubits, shots):
246
- self._compress(exact_only=True) # canonical: patch B isometric
247
- na, nb = len(self.qa), len(self.qb)
248
- a_draws = self.sim[0].measure_shots(list(range(na)), shots) # exact marginal of patch A
249
- ma, mb = self._matrices()
250
- out = []
251
- for a, cnt in zip(*np.unique(np.asarray(a_draws, dtype=np.int64), return_counts=True)):
252
- amp = mb @ ma[a, :]
253
- pb = np.abs(amp) ** 2
254
- pb /= pb.sum()
255
- for bidx in self.rng.choice(len(pb), size=int(cnt), p=pb):
256
- full = int(a) | (int(bidx) << na)
257
- out.append(sum(((full >> q) & 1) << j for j, q in enumerate(qubits)))
258
- self.rng.shuffle(out)
259
- return out
260
-
261
- def out_ket(self):
262
- """Dense contracted state (2^n), little-endian over logical qubits; for testing."""
263
- ma, mb = self._matrices()
264
- psi = (ma @ mb.T) # [a, b]
265
- v = psi.T.reshape(-1) # index = a + 2^na * b
266
- return v / np.linalg.norm(v)