pyqrack-cpu-complex128 2.30.1__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 (32) hide show
  1. {pyqrack_cpu_complex128-2.30.1/pyqrack_cpu_complex128.egg-info → pyqrack_cpu_complex128-2.30.2}/PKG-INFO +1 -1
  2. {pyqrack_cpu_complex128-2.30.1 → pyqrack_cpu_complex128-2.30.2}/pyqrack/qrack_bridge.py +143 -40
  3. {pyqrack_cpu_complex128-2.30.1 → pyqrack_cpu_complex128-2.30.2/pyqrack_cpu_complex128.egg-info}/PKG-INFO +1 -1
  4. {pyqrack_cpu_complex128-2.30.1 → pyqrack_cpu_complex128-2.30.2}/setup.py +1 -1
  5. {pyqrack_cpu_complex128-2.30.1 → pyqrack_cpu_complex128-2.30.2}/LICENSE +0 -0
  6. {pyqrack_cpu_complex128-2.30.1 → pyqrack_cpu_complex128-2.30.2}/MANIFEST.in +0 -0
  7. {pyqrack_cpu_complex128-2.30.1 → pyqrack_cpu_complex128-2.30.2}/Makefile +0 -0
  8. {pyqrack_cpu_complex128-2.30.1 → pyqrack_cpu_complex128-2.30.2}/README.md +0 -0
  9. {pyqrack_cpu_complex128-2.30.1 → pyqrack_cpu_complex128-2.30.2}/pyproject.toml +0 -0
  10. {pyqrack_cpu_complex128-2.30.1 → pyqrack_cpu_complex128-2.30.2}/pyqrack/__init__.py +0 -0
  11. {pyqrack_cpu_complex128-2.30.1 → pyqrack_cpu_complex128-2.30.2}/pyqrack/neuron_activation_fn.py +0 -0
  12. {pyqrack_cpu_complex128-2.30.1 → pyqrack_cpu_complex128-2.30.2}/pyqrack/pauli.py +0 -0
  13. {pyqrack_cpu_complex128-2.30.1 → pyqrack_cpu_complex128-2.30.2}/pyqrack/qrack_ace_backend.py +0 -0
  14. {pyqrack_cpu_complex128-2.30.1 → pyqrack_cpu_complex128-2.30.2}/pyqrack/qrack_ace_mps_backend.py +0 -0
  15. {pyqrack_cpu_complex128-2.30.1 → pyqrack_cpu_complex128-2.30.2}/pyqrack/qrack_circuit.py +0 -0
  16. {pyqrack_cpu_complex128-2.30.1 → pyqrack_cpu_complex128-2.30.2}/pyqrack/qrack_near_clifford_qec_backend.py +0 -0
  17. {pyqrack_cpu_complex128-2.30.1 → pyqrack_cpu_complex128-2.30.2}/pyqrack/qrack_neuron.py +0 -0
  18. {pyqrack_cpu_complex128-2.30.1 → pyqrack_cpu_complex128-2.30.2}/pyqrack/qrack_neuron_torch_layer.py +0 -0
  19. {pyqrack_cpu_complex128-2.30.1 → pyqrack_cpu_complex128-2.30.2}/pyqrack/qrack_simulator.py +0 -0
  20. {pyqrack_cpu_complex128-2.30.1 → pyqrack_cpu_complex128-2.30.2}/pyqrack/qrack_stabilizer.py +0 -0
  21. {pyqrack_cpu_complex128-2.30.1 → pyqrack_cpu_complex128-2.30.2}/pyqrack/qrack_system/__init__.py +0 -0
  22. {pyqrack_cpu_complex128-2.30.1 → pyqrack_cpu_complex128-2.30.2}/pyqrack/qrack_system/qrack_system.py +0 -0
  23. {pyqrack_cpu_complex128-2.30.1 → pyqrack_cpu_complex128-2.30.2}/pyqrack/quimb_circuit_type.py +0 -0
  24. {pyqrack_cpu_complex128-2.30.1 → pyqrack_cpu_complex128-2.30.2}/pyqrack/stats/__init__.py +0 -0
  25. {pyqrack_cpu_complex128-2.30.1 → pyqrack_cpu_complex128-2.30.2}/pyqrack/stats/load_quantized_data.py +0 -0
  26. {pyqrack_cpu_complex128-2.30.1 → pyqrack_cpu_complex128-2.30.2}/pyqrack/stats/quantize_by_range.py +0 -0
  27. {pyqrack_cpu_complex128-2.30.1 → pyqrack_cpu_complex128-2.30.2}/pyqrack_cpu_complex128.egg-info/SOURCES.txt +0 -0
  28. {pyqrack_cpu_complex128-2.30.1 → pyqrack_cpu_complex128-2.30.2}/pyqrack_cpu_complex128.egg-info/dependency_links.txt +0 -0
  29. {pyqrack_cpu_complex128-2.30.1 → pyqrack_cpu_complex128-2.30.2}/pyqrack_cpu_complex128.egg-info/not-zip-safe +0 -0
  30. {pyqrack_cpu_complex128-2.30.1 → pyqrack_cpu_complex128-2.30.2}/pyqrack_cpu_complex128.egg-info/requires.txt +0 -0
  31. {pyqrack_cpu_complex128-2.30.1 → pyqrack_cpu_complex128-2.30.2}/pyqrack_cpu_complex128.egg-info/top_level.txt +0 -0
  32. {pyqrack_cpu_complex128-2.30.1 → pyqrack_cpu_complex128-2.30.2}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyqrack-cpu-complex128
3
- Version: 2.30.1
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
@@ -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
@@ -79,6 +97,26 @@ def _bits(dim):
79
97
  return (max(int(dim), 1) - 1).bit_length()
80
98
 
81
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
+
82
120
  _X = [0, 1, 1, 0]
83
121
  _Y = [0, -1j, 1j, 0]
84
122
  _Z = [1, 0, 0, -1]
@@ -87,10 +125,11 @@ _TOL = 1e-6 # relative singular-value floor treated as exactly zero (Qr
87
125
 
88
126
  class QrackBridge:
89
127
  def __init__(self, qubit_count, max_bonds=6, seed=None, truncation="greedy", patches=2, wrap=False,
90
- _clone=None):
128
+ lazy_bonds=0, max_patch_qubits=None, _clone=None):
91
129
  if _clone is not None:
92
130
  src = _clone
93
- for k in ("n", "P", "ring", "max_bonds", "truncation", "fidelity_estimate", "truncations",
131
+ for k in ("n", "P", "ring", "max_bonds", "lazy_bonds", "max_patch_qubits", "truncation",
132
+ "fidelity_estimate", "truncations", "flushes",
94
133
  "peak_bonds", "center", "_wrap_touched"):
95
134
  setattr(self, k, getattr(src, k))
96
135
  self.part = [list(x) for x in src.part]
@@ -100,7 +139,6 @@ class QrackBridge:
100
139
  self.bond = list(src.bond)
101
140
  self.sim = [s.clone() for s in src.sim]
102
141
  self._touched = set(src._touched)
103
- self._defer = False
104
142
  self.rng = np.random.default_rng(int(src.rng.integers(1 << 62)))
105
143
  return
106
144
  if truncation not in ("greedy", "born"):
@@ -120,6 +158,11 @@ class QrackBridge:
120
158
  self.sim = [QrackSimulator(len(qs)) for qs in self.part]
121
159
  self.bond = [0] * (patches if self.ring else patches - 1) # cut c joins patch c (R) to c+1 (L)
122
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
123
166
  self.truncation = truncation
124
167
  self.fidelity_estimate = 1.0
125
168
  self.truncations = 0
@@ -127,7 +170,6 @@ class QrackBridge:
127
170
  self.center = 0
128
171
  self._touched = set()
129
172
  self._wrap_touched = False
130
- self._defer = False
131
173
  self.rng = np.random.default_rng(seed)
132
174
 
133
175
  def clone(self):
@@ -180,6 +222,46 @@ class QrackBridge:
180
222
  ids[p] = qid
181
223
  return ids[here], ids[there]
182
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
+
183
265
  def _loc(self, q):
184
266
  p, i = self.side[q]
185
267
  return self.sim[p], p, i
@@ -226,8 +308,7 @@ class QrackBridge:
226
308
  st.h(inc)
227
309
  st.mcmtrx([inc], mtrx, it)
228
310
  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)
311
+ self._maybe_compress()
231
312
 
232
313
  def mcx(self, c, t): self._controlled(c[0], t, _X, False)
233
314
  def mcy(self, c, t): self._controlled(c[0], t, _Y, False)
@@ -240,35 +321,25 @@ class QrackBridge:
240
321
  def cy(self, a, b): self.mcy([a], b)
241
322
  def cz(self, a, b): self.mcz([a], b)
242
323
 
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])
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)
263
332
  return
264
- self._composite([lambda: self.s(a), lambda: self.s(b), lambda: self.mcz([a], b), lambda: self.swap(a, b)])
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()
265
339
 
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)])
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")
272
343
 
273
344
  # --- patch tensors through the kets --------------------------------------
274
345
 
@@ -281,8 +352,13 @@ class QrackBridge:
281
352
  v = _out_ket(self.sim[p])
282
353
  order = ([("L", j) for j in reversed(range(bl))] + [("d", i) for i in reversed(range(nd))]
283
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)
284
360
  pos = {tag: x for x, tag in enumerate(lay)}
285
- t = v.reshape([2] * k).transpose([k - 1 - pos[tag] for tag in order])
361
+ t = t.transpose([k - 1 - pos[tag] for tag in order])
286
362
  return t.reshape(1 << bl, 1 << nd, 1 << br)
287
363
 
288
364
  def _store(self, p, a):
@@ -327,16 +403,20 @@ class QrackBridge:
327
403
  T = {k: self._tensor(k) for k in range(start, end + 1)}
328
404
  for k in range(start, end): # left-isometric up to the centre at `end`
329
405
  l, d, r = T[k].shape
330
- q, rr = np.linalg.qr(T[k].reshape(l * d, r))
406
+ q, rr = _left_factor(T[k].reshape(l * d, r)) # exact; also drops zero modes
331
407
  T[k] = q.reshape(l, d, -1)
332
- T[k + 1] = np.einsum("ab,bdr->adr", rr, T[k + 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)
333
410
  self.bond[k] = _bits(q.shape[1])
334
411
  for k in range(end, lo, -1): # right-isometric back down to `lo`
335
412
  l, d, r = T[k].shape
336
- u, sv, vh = np.linalg.svd(T[k].reshape(l, d * r), full_matrices=False)
413
+ m = T[k].reshape(l, d * r)
414
+ u, sv = _gram_svd(m)
337
415
  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, :])
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)
340
420
  self.bond[k - 1] = _bits(len(idx))
341
421
  for k, a in T.items():
342
422
  self._store(k, a)
@@ -356,6 +436,27 @@ class QrackBridge:
356
436
  self._store(P - 1, ((qa @ u[:, idx]) * sv[idx][None, :]).reshape(l, d, -1))
357
437
  self._store(0, (qb @ vh[idx, :].T).T.reshape(-1, d0, r0))
358
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
+
359
460
  def _compress(self, exact_only=False):
360
461
  if not self._touched:
361
462
  return
@@ -364,6 +465,7 @@ class QrackBridge:
364
465
  self._touched.update((0, self.P - 1))
365
466
  self._sweep(min(self._touched), max(self._touched), exact_only)
366
467
  if not exact_only:
468
+ self.flushes += 1
367
469
  self._touched.clear()
368
470
  self._wrap_touched = False
369
471
 
@@ -407,6 +509,7 @@ class QrackBridge:
407
509
 
408
510
  def out_ket(self):
409
511
  """Dense contracted state (2^n), little-endian over logical qubits; for testing."""
512
+ self._compress() # same (flushed) state that measure_shots samples
410
513
  C = None
411
514
  for p in range(self.P):
412
515
  A = self._tensor(p)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyqrack-cpu-complex128
3
- Version: 2.30.1
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.1"
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')