pyqrack-cpu 2.30.1__tar.gz → 2.30.3__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 (32) hide show
  1. {pyqrack_cpu-2.30.1/pyqrack_cpu.egg-info → pyqrack_cpu-2.30.3}/PKG-INFO +1 -1
  2. {pyqrack_cpu-2.30.1 → pyqrack_cpu-2.30.3}/pyqrack/qrack_bridge.py +172 -40
  3. {pyqrack_cpu-2.30.1 → pyqrack_cpu-2.30.3/pyqrack_cpu.egg-info}/PKG-INFO +1 -1
  4. {pyqrack_cpu-2.30.1 → pyqrack_cpu-2.30.3}/setup.py +1 -1
  5. {pyqrack_cpu-2.30.1 → pyqrack_cpu-2.30.3}/LICENSE +0 -0
  6. {pyqrack_cpu-2.30.1 → pyqrack_cpu-2.30.3}/MANIFEST.in +0 -0
  7. {pyqrack_cpu-2.30.1 → pyqrack_cpu-2.30.3}/Makefile +0 -0
  8. {pyqrack_cpu-2.30.1 → pyqrack_cpu-2.30.3}/README.md +0 -0
  9. {pyqrack_cpu-2.30.1 → pyqrack_cpu-2.30.3}/pyproject.toml +0 -0
  10. {pyqrack_cpu-2.30.1 → pyqrack_cpu-2.30.3}/pyqrack/__init__.py +0 -0
  11. {pyqrack_cpu-2.30.1 → pyqrack_cpu-2.30.3}/pyqrack/neuron_activation_fn.py +0 -0
  12. {pyqrack_cpu-2.30.1 → pyqrack_cpu-2.30.3}/pyqrack/pauli.py +0 -0
  13. {pyqrack_cpu-2.30.1 → pyqrack_cpu-2.30.3}/pyqrack/qrack_ace_backend.py +0 -0
  14. {pyqrack_cpu-2.30.1 → pyqrack_cpu-2.30.3}/pyqrack/qrack_ace_mps_backend.py +0 -0
  15. {pyqrack_cpu-2.30.1 → pyqrack_cpu-2.30.3}/pyqrack/qrack_circuit.py +0 -0
  16. {pyqrack_cpu-2.30.1 → pyqrack_cpu-2.30.3}/pyqrack/qrack_near_clifford_qec_backend.py +0 -0
  17. {pyqrack_cpu-2.30.1 → pyqrack_cpu-2.30.3}/pyqrack/qrack_neuron.py +0 -0
  18. {pyqrack_cpu-2.30.1 → pyqrack_cpu-2.30.3}/pyqrack/qrack_neuron_torch_layer.py +0 -0
  19. {pyqrack_cpu-2.30.1 → pyqrack_cpu-2.30.3}/pyqrack/qrack_simulator.py +0 -0
  20. {pyqrack_cpu-2.30.1 → pyqrack_cpu-2.30.3}/pyqrack/qrack_stabilizer.py +0 -0
  21. {pyqrack_cpu-2.30.1 → pyqrack_cpu-2.30.3}/pyqrack/qrack_system/__init__.py +0 -0
  22. {pyqrack_cpu-2.30.1 → pyqrack_cpu-2.30.3}/pyqrack/qrack_system/qrack_system.py +0 -0
  23. {pyqrack_cpu-2.30.1 → pyqrack_cpu-2.30.3}/pyqrack/quimb_circuit_type.py +0 -0
  24. {pyqrack_cpu-2.30.1 → pyqrack_cpu-2.30.3}/pyqrack/stats/__init__.py +0 -0
  25. {pyqrack_cpu-2.30.1 → pyqrack_cpu-2.30.3}/pyqrack/stats/load_quantized_data.py +0 -0
  26. {pyqrack_cpu-2.30.1 → pyqrack_cpu-2.30.3}/pyqrack/stats/quantize_by_range.py +0 -0
  27. {pyqrack_cpu-2.30.1 → pyqrack_cpu-2.30.3}/pyqrack_cpu.egg-info/SOURCES.txt +0 -0
  28. {pyqrack_cpu-2.30.1 → pyqrack_cpu-2.30.3}/pyqrack_cpu.egg-info/dependency_links.txt +0 -0
  29. {pyqrack_cpu-2.30.1 → pyqrack_cpu-2.30.3}/pyqrack_cpu.egg-info/not-zip-safe +0 -0
  30. {pyqrack_cpu-2.30.1 → pyqrack_cpu-2.30.3}/pyqrack_cpu.egg-info/requires.txt +0 -0
  31. {pyqrack_cpu-2.30.1 → pyqrack_cpu-2.30.3}/pyqrack_cpu.egg-info/top_level.txt +0 -0
  32. {pyqrack_cpu-2.30.1 → pyqrack_cpu-2.30.3}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyqrack-cpu
3
- Version: 2.30.1
3
+ Version: 2.30.3
4
4
  Summary: pyqrack - Pure Python vm6502q/qrack Wrapper
5
5
  Home-page: https://github.com/vm6502q/pyqrack
6
6
  Author: Daniel Strano
@@ -24,7 +24,10 @@
24
24
  # Contracting on each bond pair enforces equality, so every relay bond carries a copy of c and the
25
25
  # result is exactly controlled-U(c -> t). A gate between patches k apart costs one bond on each of
26
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).
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.
28
31
  #
29
32
  # Recompression after each bridged two-qubit gate (one MPS-style sweep over the touched segment):
30
33
  # - Gates on data qubits are unitary on each patch's (left, data) and (data, right) row spaces, so
@@ -41,6 +44,21 @@
41
44
  # form), so fidelity_estimate is an estimate there and not the kept Schmidt weight.
42
45
  # Nothing larger than the patch kets and per-cut cores is ever formed: no density matrix.
43
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
+ #
44
62
  # Readout. Exact for the stored state: sequential conditional sampling, patch by patch, from the
45
63
  # exported kets, with shots grouped by prefix. On an open chain the canonical form (centre at patch 0)
46
64
  # makes each step a local marginal. On a ring, right environments carry the open wrap index, at a cost
@@ -48,6 +66,7 @@
48
66
  #
49
67
  # fidelity_estimate multiplies the kept Schmidt weight (greedy) or sum_g p_g^2 (born) per truncation.
50
68
 
69
+ import contextlib
51
70
  import ctypes
52
71
  import math
53
72
 
@@ -79,6 +98,26 @@ def _bits(dim):
79
98
  return (max(int(dim), 1) - 1).bit_length()
80
99
 
81
100
 
101
+ def _gram_svd(m):
102
+ """Left singular vectors and values of a short-wide m (rows <= 2^bonds) via its rows x rows Gram
103
+ matrix: one BLAS product plus a tiny Hermitian eigensolve, instead of a LAPACK SVD of the whole
104
+ patch. Double precision Gram keeps singular values to ~1e-8 relative, well under _TOL."""
105
+ lam, u = np.linalg.eigh(m @ m.conj().T)
106
+ order = np.argsort(lam)[::-1]
107
+ return u[:, order], np.sqrt(np.clip(lam[order], 0, None))
108
+
109
+
110
+ def _left_factor(a):
111
+ """a = q @ r with q's columns orthonormal, through a's columns x columns Gram matrix; modes with
112
+ zero weight are dropped (exactly), so the bond only ever shrinks here."""
113
+ lam, v = np.linalg.eigh(a.conj().T @ a)
114
+ keep = lam > (_TOL * _TOL) * lam[-1]
115
+ keep[-1] = True # never an empty bond (lam[-1] > 0 for a live state)
116
+ s = np.sqrt(lam[keep])
117
+ v = v[:, keep]
118
+ return (a @ v) / s[None, :], s[:, None] * v.conj().T
119
+
120
+
82
121
  _X = [0, 1, 1, 0]
83
122
  _Y = [0, -1j, 1j, 0]
84
123
  _Z = [1, 0, 0, -1]
@@ -87,10 +126,11 @@ _TOL = 1e-6 # relative singular-value floor treated as exactly zero (Qr
87
126
 
88
127
  class QrackBridge:
89
128
  def __init__(self, qubit_count, max_bonds=6, seed=None, truncation="greedy", patches=2, wrap=False,
90
- _clone=None):
129
+ lazy_bonds=0, max_patch_qubits=None, _clone=None):
91
130
  if _clone is not None:
92
131
  src = _clone
93
- for k in ("n", "P", "ring", "max_bonds", "truncation", "fidelity_estimate", "truncations",
132
+ for k in ("n", "P", "ring", "max_bonds", "lazy_bonds", "max_patch_qubits", "truncation",
133
+ "fidelity_estimate", "truncations", "flushes",
94
134
  "peak_bonds", "center", "_wrap_touched"):
95
135
  setattr(self, k, getattr(src, k))
96
136
  self.part = [list(x) for x in src.part]
@@ -100,7 +140,7 @@ class QrackBridge:
100
140
  self.bond = list(src.bond)
101
141
  self.sim = [s.clone() for s in src.sim]
102
142
  self._touched = set(src._touched)
103
- self._defer = False
143
+ self._deferring = 0
104
144
  self.rng = np.random.default_rng(int(src.rng.integers(1 << 62)))
105
145
  return
106
146
  if truncation not in ("greedy", "born"):
@@ -120,6 +160,12 @@ class QrackBridge:
120
160
  self.sim = [QrackSimulator(len(qs)) for qs in self.part]
121
161
  self.bond = [0] * (patches if self.ring else patches - 1) # cut c joins patch c (R) to c+1 (L)
122
162
  self.max_bonds = max_bonds
163
+ if lazy_bonds < 0:
164
+ raise ValueError("lazy_bonds must be >= 0")
165
+ self.lazy_bonds = lazy_bonds
166
+ self.max_patch_qubits = max_patch_qubits
167
+ self.flushes = 0
168
+ self._deferring = 0
123
169
  self.truncation = truncation
124
170
  self.fidelity_estimate = 1.0
125
171
  self.truncations = 0
@@ -127,7 +173,6 @@ class QrackBridge:
127
173
  self.center = 0
128
174
  self._touched = set()
129
175
  self._wrap_touched = False
130
- self._defer = False
131
176
  self.rng = np.random.default_rng(seed)
132
177
 
133
178
  def clone(self):
@@ -180,6 +225,46 @@ class QrackBridge:
180
225
  ids[p] = qid
181
226
  return ids[here], ids[there]
182
227
 
228
+ def _new_scratch(self, p):
229
+ """Fresh |0> working qubit in patch p; it is returned to |0> before any recompression."""
230
+ qid = len(self.layout[p])
231
+ self.sim[p].allocate_qubit(qid)
232
+ self.layout[p].append(("0", qid))
233
+ return qid
234
+
235
+ def _ship(self, path, src):
236
+ """Teleport the state of qubit src (in patch path[0]) onto a fresh scratch qubit in patch
237
+ path[-1], through one new bond per cut: src is SWAPped onto the outgoing bond (src left |0>),
238
+ relays are identity wires (H in; CNOT in -> out), and the destination Bell-pairs its incoming
239
+ bond with the scratch qubit (H in; CNOT in -> scratch). Returns the scratch qubit's id."""
240
+ out, inc = self._new_bond(path[0], path[1])
241
+ self.sim[path[0]].swap(src, out)
242
+ for k in range(1, len(path) - 1):
243
+ s = self.sim[path[k]]
244
+ s.h(inc)
245
+ out, nxt = self._new_bond(path[k], path[k + 1])
246
+ s.mcx([inc], out)
247
+ inc = nxt
248
+ s = self.sim[path[-1]]
249
+ z = self._new_scratch(path[-1])
250
+ s.h(inc)
251
+ s.mcx([inc], z)
252
+ return z
253
+
254
+ def _unship(self, path, z, dst):
255
+ """Teleport scratch qubit z (in patch path[0]) back onto qubit dst (|0>, in patch path[-1])."""
256
+ out, inc = self._new_bond(path[0], path[1])
257
+ self.sim[path[0]].swap(z, out) # z back to |0>
258
+ for k in range(1, len(path) - 1):
259
+ s = self.sim[path[k]]
260
+ s.h(inc)
261
+ out, nxt = self._new_bond(path[k], path[k + 1])
262
+ s.mcx([inc], out)
263
+ inc = nxt
264
+ s = self.sim[path[-1]]
265
+ s.h(inc)
266
+ s.mcx([inc], dst)
267
+
183
268
  def _loc(self, q):
184
269
  p, i = self.side[q]
185
270
  return self.sim[p], p, i
@@ -226,8 +311,7 @@ class QrackBridge:
226
311
  st.h(inc)
227
312
  st.mcmtrx([inc], mtrx, it)
228
313
  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)
314
+ self._maybe_compress()
231
315
 
232
316
  def mcx(self, c, t): self._controlled(c[0], t, _X, False)
233
317
  def mcy(self, c, t): self._controlled(c[0], t, _Y, False)
@@ -240,35 +324,25 @@ class QrackBridge:
240
324
  def cy(self, a, b): self.mcy([a], b)
241
325
  def cz(self, a, b): self.mcz([a], b)
242
326
 
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])
327
+ def _pair_gate(self, a, b, op):
328
+ """Any two-qubit gate across patches: ship a's state into b's patch, apply the gate natively
329
+ there, ship it back. Exactly two bonds per cut crossed (operator-Schmidt rank <= 4), and one
330
+ recompression for the whole gate."""
331
+ sa, pa, ia = self._loc(a)
332
+ sb, pb, ib = self._loc(b)
333
+ if pa == pb:
334
+ getattr(sa, op)(ia, ib)
256
335
  return
257
- self._composite([lambda: self.mcx([a], b), lambda: self.mcx([b], a), lambda: self.mcx([a], b)])
336
+ path = self._path(pa, pb)
337
+ z = self._ship(path, ia)
338
+ getattr(sb, op)(z, ib)
339
+ self._unship(path[::-1], z, ia)
340
+ self._touched.update(path)
341
+ self._maybe_compress()
258
342
 
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)])
343
+ def swap(self, a, b): self._pair_gate(a, b, "swap")
344
+ def iswap(self, a, b): self._pair_gate(a, b, "iswap")
345
+ def adjiswap(self, a, b): self._pair_gate(a, b, "adjiswap")
272
346
 
273
347
  # --- patch tensors through the kets --------------------------------------
274
348
 
@@ -281,8 +355,13 @@ class QrackBridge:
281
355
  v = _out_ket(self.sim[p])
282
356
  order = ([("L", j) for j in reversed(range(bl))] + [("d", i) for i in reversed(range(nd))]
283
357
  + [("R", j) for j in reversed(range(br))])
358
+ t = v.reshape([2] * k)
359
+ if any(tag[0] == "0" for tag in lay): # scratch qubits are back in |0>: project them out
360
+ t = t[tuple(0 if lay[k - 1 - x][0] == "0" else slice(None) for x in range(k))]
361
+ lay = [tag for tag in lay if tag[0] != "0"]
362
+ k = len(lay)
284
363
  pos = {tag: x for x, tag in enumerate(lay)}
285
- t = v.reshape([2] * k).transpose([k - 1 - pos[tag] for tag in order])
364
+ t = t.transpose([k - 1 - pos[tag] for tag in order])
286
365
  return t.reshape(1 << bl, 1 << nd, 1 << br)
287
366
 
288
367
  def _store(self, p, a):
@@ -327,16 +406,20 @@ class QrackBridge:
327
406
  T = {k: self._tensor(k) for k in range(start, end + 1)}
328
407
  for k in range(start, end): # left-isometric up to the centre at `end`
329
408
  l, d, r = T[k].shape
330
- q, rr = np.linalg.qr(T[k].reshape(l * d, r))
409
+ q, rr = _left_factor(T[k].reshape(l * d, r)) # exact; also drops zero modes
331
410
  T[k] = q.reshape(l, d, -1)
332
- T[k + 1] = np.einsum("ab,bdr->adr", rr, T[k + 1])
411
+ nl, nd_, nr = T[k + 1].shape
412
+ T[k + 1] = (rr @ T[k + 1].reshape(nl, nd_ * nr)).reshape(-1, nd_, nr)
333
413
  self.bond[k] = _bits(q.shape[1])
334
414
  for k in range(end, lo, -1): # right-isometric back down to `lo`
335
415
  l, d, r = T[k].shape
336
- u, sv, vh = np.linalg.svd(T[k].reshape(l, d * r), full_matrices=False)
416
+ m = T[k].reshape(l, d * r)
417
+ u, sv = _gram_svd(m)
337
418
  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, :])
419
+ us = u[:, idx]
420
+ T[k] = ((us.conj().T @ m) / sv[idx][:, None]).reshape(len(idx), d, r)
421
+ pl, pd, pr = T[k - 1].shape
422
+ T[k - 1] = (T[k - 1].reshape(pl * pd, pr) @ (us * sv[idx][None, :])).reshape(pl, pd, -1)
340
423
  self.bond[k - 1] = _bits(len(idx))
341
424
  for k, a in T.items():
342
425
  self._store(k, a)
@@ -356,6 +439,53 @@ class QrackBridge:
356
439
  self._store(P - 1, ((qa @ u[:, idx]) * sv[idx][None, :]).reshape(l, d, -1))
357
440
  self._store(0, (qb @ vh[idx, :].T).T.reshape(-1, d0, r0))
358
441
 
442
+ def _over_budget(self):
443
+ """Lazy mode: has any cut, or any patch's total width, outgrown its buffer?"""
444
+ if any(b > self.max_bonds + self.lazy_bonds for b in self.bond):
445
+ return True
446
+ if self.max_patch_qubits is not None:
447
+ return any(len(lay) > self.max_patch_qubits for lay in self.layout)
448
+ return False
449
+
450
+ def _maybe_compress(self):
451
+ if self._deferring:
452
+ # Inside deferred(): keep only the exact rank (drop zero singular values); never truncate.
453
+ if not self.lazy_bonds or self._over_budget():
454
+ self._compress(exact_only=True)
455
+ return
456
+ if not self.lazy_bonds:
457
+ self._compress() # eager: one sweep per bridged gate
458
+ return
459
+ # Lazy: let bridged gates pile up as raw bond qubits and truncate the whole batch in one sweep,
460
+ # only when a cut exceeds max_bonds + lazy_bonds (or a patch exceeds max_patch_qubits).
461
+ if self._over_budget():
462
+ self._compress()
463
+
464
+ @contextlib.contextmanager
465
+ def deferred(self):
466
+ """Truncate once, after the whole block, never inside it:
467
+
468
+ with sim.deferred():
469
+ for i in range(9):
470
+ sim.mcx([b[i]], a[i]) # e.g. a transversal logical CNOT
471
+
472
+ Inside, bridged gates are recompressed only exactly, so bonds carry the full transient
473
+ entanglement of the block; on exit one sweep truncates to max_bonds. Use it around any
474
+ multi-gate operation whose intermediate states are more entangled than its result
475
+ (transversal logical gates, decode/encode, gate decompositions). Heap grows with the
476
+ transient rank inside the block. Nests; only the outermost exit truncates."""
477
+ self._deferring += 1
478
+ try:
479
+ yield self
480
+ finally:
481
+ self._deferring -= 1
482
+ if not self._deferring:
483
+ self._maybe_compress()
484
+
485
+ def flush(self):
486
+ """Truncate any buffered bonds back to max_bonds now (readout does this automatically)."""
487
+ self._compress()
488
+
359
489
  def _compress(self, exact_only=False):
360
490
  if not self._touched:
361
491
  return
@@ -364,6 +494,7 @@ class QrackBridge:
364
494
  self._touched.update((0, self.P - 1))
365
495
  self._sweep(min(self._touched), max(self._touched), exact_only)
366
496
  if not exact_only:
497
+ self.flushes += 1
367
498
  self._touched.clear()
368
499
  self._wrap_touched = False
369
500
 
@@ -407,6 +538,7 @@ class QrackBridge:
407
538
 
408
539
  def out_ket(self):
409
540
  """Dense contracted state (2^n), little-endian over logical qubits; for testing."""
541
+ self._compress() # same (flushed) state that measure_shots samples
410
542
  C = None
411
543
  for p in range(self.P):
412
544
  A = self._tensor(p)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyqrack-cpu
3
- Version: 2.30.1
3
+ Version: 2.30.3
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.1"
10
+ VERSION = "2.30.3"
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')
File without changes
File without changes
File without changes
File without changes
File without changes