pyqrack-complex128 2.30.0__tar.gz → 2.30.2__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_complex128-2.30.0/pyqrack_complex128.egg-info → pyqrack_complex128-2.30.2}/PKG-INFO +1 -1
  2. pyqrack_complex128-2.30.2/pyqrack/qrack_bridge.py +522 -0
  3. {pyqrack_complex128-2.30.0 → pyqrack_complex128-2.30.2/pyqrack_complex128.egg-info}/PKG-INFO +1 -1
  4. {pyqrack_complex128-2.30.0 → pyqrack_complex128-2.30.2}/setup.py +1 -1
  5. pyqrack_complex128-2.30.0/pyqrack/qrack_bridge.py +0 -266
  6. {pyqrack_complex128-2.30.0 → pyqrack_complex128-2.30.2}/LICENSE +0 -0
  7. {pyqrack_complex128-2.30.0 → pyqrack_complex128-2.30.2}/MANIFEST.in +0 -0
  8. {pyqrack_complex128-2.30.0 → pyqrack_complex128-2.30.2}/Makefile +0 -0
  9. {pyqrack_complex128-2.30.0 → pyqrack_complex128-2.30.2}/README.md +0 -0
  10. {pyqrack_complex128-2.30.0 → pyqrack_complex128-2.30.2}/pyproject.toml +0 -0
  11. {pyqrack_complex128-2.30.0 → pyqrack_complex128-2.30.2}/pyqrack/__init__.py +0 -0
  12. {pyqrack_complex128-2.30.0 → pyqrack_complex128-2.30.2}/pyqrack/neuron_activation_fn.py +0 -0
  13. {pyqrack_complex128-2.30.0 → pyqrack_complex128-2.30.2}/pyqrack/pauli.py +0 -0
  14. {pyqrack_complex128-2.30.0 → pyqrack_complex128-2.30.2}/pyqrack/qrack_ace_backend.py +0 -0
  15. {pyqrack_complex128-2.30.0 → pyqrack_complex128-2.30.2}/pyqrack/qrack_ace_mps_backend.py +0 -0
  16. {pyqrack_complex128-2.30.0 → pyqrack_complex128-2.30.2}/pyqrack/qrack_circuit.py +0 -0
  17. {pyqrack_complex128-2.30.0 → pyqrack_complex128-2.30.2}/pyqrack/qrack_near_clifford_qec_backend.py +0 -0
  18. {pyqrack_complex128-2.30.0 → pyqrack_complex128-2.30.2}/pyqrack/qrack_neuron.py +0 -0
  19. {pyqrack_complex128-2.30.0 → pyqrack_complex128-2.30.2}/pyqrack/qrack_neuron_torch_layer.py +0 -0
  20. {pyqrack_complex128-2.30.0 → pyqrack_complex128-2.30.2}/pyqrack/qrack_simulator.py +0 -0
  21. {pyqrack_complex128-2.30.0 → pyqrack_complex128-2.30.2}/pyqrack/qrack_stabilizer.py +0 -0
  22. {pyqrack_complex128-2.30.0 → pyqrack_complex128-2.30.2}/pyqrack/qrack_system/__init__.py +0 -0
  23. {pyqrack_complex128-2.30.0 → pyqrack_complex128-2.30.2}/pyqrack/qrack_system/qrack_system.py +0 -0
  24. {pyqrack_complex128-2.30.0 → pyqrack_complex128-2.30.2}/pyqrack/quimb_circuit_type.py +0 -0
  25. {pyqrack_complex128-2.30.0 → pyqrack_complex128-2.30.2}/pyqrack/stats/__init__.py +0 -0
  26. {pyqrack_complex128-2.30.0 → pyqrack_complex128-2.30.2}/pyqrack/stats/load_quantized_data.py +0 -0
  27. {pyqrack_complex128-2.30.0 → pyqrack_complex128-2.30.2}/pyqrack/stats/quantize_by_range.py +0 -0
  28. {pyqrack_complex128-2.30.0 → pyqrack_complex128-2.30.2}/pyqrack_complex128.egg-info/SOURCES.txt +0 -0
  29. {pyqrack_complex128-2.30.0 → pyqrack_complex128-2.30.2}/pyqrack_complex128.egg-info/dependency_links.txt +0 -0
  30. {pyqrack_complex128-2.30.0 → pyqrack_complex128-2.30.2}/pyqrack_complex128.egg-info/not-zip-safe +0 -0
  31. {pyqrack_complex128-2.30.0 → pyqrack_complex128-2.30.2}/pyqrack_complex128.egg-info/requires.txt +0 -0
  32. {pyqrack_complex128-2.30.0 → pyqrack_complex128-2.30.2}/pyqrack_complex128.egg-info/top_level.txt +0 -0
  33. {pyqrack_complex128-2.30.0 → pyqrack_complex128-2.30.2}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyqrack-complex128
3
- Version: 2.30.0
3
+ Version: 2.30.2
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,522 @@
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)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyqrack-complex128
3
- Version: 2.30.0
3
+ Version: 2.30.2
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.2"
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)