Tatopenn commited on
Commit
b0b2232
Β·
verified Β·
1 Parent(s): fcd8efb

Sync dense_evolution/ from v8.1.33

Browse files
dense_evolution/__init__.py CHANGED
@@ -5,11 +5,12 @@ High-performance quantum statevector simulator optimized for NISQ circuits.
5
  from .simulator import DenseSVSimulator
6
  from .parser import QASMParser, QASMCircuit
7
  from .compiler import QuantumTranspiler
8
- from .registry import NoiseModel, QuantumHardwareRegistry
9
  from .gates import GATES, PARAMETRIC_GATES, GATE_IDS
10
  from .chunk import Chunk
11
  from .interop import from_qiskit, from_pennylane, run_qiskit_circuit, run_pennylane_circuit
12
  from .autodiff import circuit_to_energy_fn
13
  from .mps import MPSSimulator
 
14
 
15
- __version__ = "8.1.25"
 
5
  from .simulator import DenseSVSimulator
6
  from .parser import QASMParser, QASMCircuit
7
  from .compiler import QuantumTranspiler
8
+ from .registry import NoiseModel, NoiseSpec, QuantumHardwareRegistry
9
  from .gates import GATES, PARAMETRIC_GATES, GATE_IDS
10
  from .chunk import Chunk
11
  from .interop import from_qiskit, from_pennylane, run_qiskit_circuit, run_pennylane_circuit
12
  from .autodiff import circuit_to_energy_fn
13
  from .mps import MPSSimulator
14
+ from .mitigation import richardson_extrapolate, zero_noise_extrapolation
15
 
16
+ __version__ = "8.1.33"
dense_evolution/autodiff.py CHANGED
@@ -3,7 +3,7 @@ from typing import Callable, Optional, Tuple
3
  from .parser import QASMCircuit
4
  from .gates import GATE_IDS
5
  from .compiler import QuantumTranspiler
6
- from .registry import HAS_JAX
7
 
8
  if HAS_JAX:
9
  import jax
@@ -83,14 +83,27 @@ def circuit_to_energy_fn(
83
  Qiskit/PennyLane interop bridge (from_qiskit/from_pennylane).
84
 
85
  Returns (energy_fn, n_params):
86
- energy_fn(theta, h_matrix, stato_zero=None) -> (energy, statevector)
87
- is a pure JAX function, differentiable w.r.t. theta via jax.grad /
88
- jax.value_and_grad(energy_fn, argnums=0, has_aux=True). stato_zero
89
- defaults to |0...0> if not given.
90
  n_params is the number of parametric gates in the circuit, in the
91
  same order theta is injected β€” build theta as an array of that
92
  length.
93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  This is the same engine dashboard_core.py's real VQE gradient uses
95
  internally (verified against finite differences, ~1e-11 agreement) β€”
96
  exposed here as public API so it's reachable without reading
@@ -104,7 +117,8 @@ def circuit_to_energy_fn(
104
  n_params = sum(1 for op in circuit.ops
105
  if str(op['name']).lower().strip() in _PARAMETRIC_GATES)
106
 
107
- def energy_fn(theta, h_matrix, stato_zero: Optional["jnp.ndarray"] = None):
 
108
  if stato_zero is None:
109
  stato_zero = jnp.zeros(2 ** n_qubits, dtype=jnp.complex128).at[0].set(1.0)
110
 
@@ -116,18 +130,23 @@ def circuit_to_energy_fn(
116
  # at circuit_to_energy_fn() call time, so this branch is
117
  # resolved before any tracing happens β€” not a jax.lax.cond).
118
  sv = _compile_and_run_circuit_jit(stato_zero, template)
119
- energy = jnp.real(jnp.vdot(sv, h_matrix @ sv))
120
- return energy, sv
121
-
122
- def patch_and_apply(carry, op):
123
- idx = carry
124
- is_param = op[3] == -1.0
125
- final_p = jnp.where(is_param, theta[idx], op[3])
126
- next_idx = jnp.where(is_param, idx + jnp.int32(1), idx)
127
- return next_idx, jnp.array([op[0], op[1], op[2], final_p], dtype=jnp.float64)
128
-
129
- _, patched_ops = jax.lax.scan(patch_and_apply, jnp.int32(0), template)
130
- sv = _compile_and_run_circuit_jit(stato_zero, patched_ops)
 
 
 
 
 
131
  energy = jnp.real(jnp.vdot(sv, h_matrix @ sv))
132
  return energy, sv
133
 
 
3
  from .parser import QASMCircuit
4
  from .gates import GATE_IDS
5
  from .compiler import QuantumTranspiler
6
+ from .registry import HAS_JAX, NoiseModel, NoiseSpec
7
 
8
  if HAS_JAX:
9
  import jax
 
83
  Qiskit/PennyLane interop bridge (from_qiskit/from_pennylane).
84
 
85
  Returns (energy_fn, n_params):
86
+ energy_fn(theta, h_matrix, stato_zero=None, noise=None) ->
87
+ (energy, statevector) is a pure JAX function, differentiable w.r.t.
88
+ theta via jax.grad / jax.value_and_grad(energy_fn, argnums=0,
89
+ has_aux=True). stato_zero defaults to |0...0> if not given.
90
  n_params is the number of parametric gates in the circuit, in the
91
  same order theta is injected β€” build theta as an array of that
92
  length.
93
 
94
+ noise, when given, is a registry.NoiseSpec (a JAX PyTree) applied
95
+ to the statevector right after the circuit and before the energy
96
+ expectation value is computed β€” natively inside the same traced
97
+ computation as theta, not as an external step the caller has to
98
+ splice in around energy_fn themselves. Because NoiseSpec carries
99
+ its own jax_key as a pytree leaf, the whole thing stays
100
+ jit/grad/vmap-composable with no OS-entropy fallback and no
101
+ external key-management workaround:
102
+
103
+ noise = NoiseSpec(model='depolarizing', p=0.05,
104
+ jax_key=jax.random.PRNGKey(0))
105
+ energy, sv = energy_fn(theta, h_matrix, noise=noise)
106
+
107
  This is the same engine dashboard_core.py's real VQE gradient uses
108
  internally (verified against finite differences, ~1e-11 agreement) β€”
109
  exposed here as public API so it's reachable without reading
 
117
  n_params = sum(1 for op in circuit.ops
118
  if str(op['name']).lower().strip() in _PARAMETRIC_GATES)
119
 
120
+ def energy_fn(theta, h_matrix, stato_zero: Optional["jnp.ndarray"] = None,
121
+ noise: Optional["NoiseSpec"] = None):
122
  if stato_zero is None:
123
  stato_zero = jnp.zeros(2 ** n_qubits, dtype=jnp.complex128).at[0].set(1.0)
124
 
 
130
  # at circuit_to_energy_fn() call time, so this branch is
131
  # resolved before any tracing happens β€” not a jax.lax.cond).
132
  sv = _compile_and_run_circuit_jit(stato_zero, template)
133
+ else:
134
+ def patch_and_apply(carry, op):
135
+ idx = carry
136
+ is_param = op[3] == -1.0
137
+ final_p = jnp.where(is_param, theta[idx], op[3])
138
+ next_idx = jnp.where(is_param, idx + jnp.int32(1), idx)
139
+ return next_idx, jnp.array([op[0], op[1], op[2], final_p], dtype=jnp.float64)
140
+
141
+ _, patched_ops = jax.lax.scan(patch_and_apply, jnp.int32(0), template)
142
+ sv = _compile_and_run_circuit_jit(stato_zero, patched_ops)
143
+
144
+ if noise is not None:
145
+ sv = NoiseModel.apply_to_sv(
146
+ sv, n_qubits, model=noise.model, p=noise.p,
147
+ jax_key=noise.jax_key, qubits=list(noise.qubits) if noise.qubits else None,
148
+ )
149
+
150
  energy = jnp.real(jnp.vdot(sv, h_matrix @ sv))
151
  return energy, sv
152
 
dense_evolution/chunk.py CHANGED
@@ -1,776 +1,1101 @@
1
- import gc
2
- import psutil
3
- import numpy as np
4
- from typing import List, Optional, Tuple
5
-
6
- # JAX is now a mandatory dependency (see registry.py) -- kept as an
7
- # import-time flag for the dual-path code below, which stays as-is.
8
- import jax
9
- import jax.numpy as jnp
10
- HAS_JAX = True
11
-
12
- # ── Flexible import with stub fallback ──────────────────────────────────────
13
- try:
14
- from simulator import DenseSVSimulator
15
- from compiler import QuantumTranspiler
16
- from gates import GATE_IDS
17
- except ModuleNotFoundError:
18
- try:
19
- from dense_evolution.simulator import DenseSVSimulator
20
- from dense_evolution.compiler import QuantumTranspiler
21
- from dense_evolution.gates import GATE_IDS
22
- except ModuleNotFoundError:
23
- class DenseSVSimulator: # type: ignore[no-redef]
24
- def __init__(self, n_qubits, **kwargs):
25
- self.n = n_qubits
26
- self.dim = 2 ** n_qubits
27
- self.dtype = np.complex128
28
- self.sv = np.zeros(self.dim, dtype=self.dtype)
29
- self.sv[0] = 1.0
30
- def run_circuit_jit_beast_mode(self, circuit_slice): pass
31
- def memory_mb(self) -> float:
32
- return (self.dim * np.dtype(self.dtype).itemsize) / 1_000_000
33
-
34
- class QuantumTranspiler: # type: ignore[no-redef]
35
- @staticmethod
36
- def transpile(circuit): return circuit
37
-
38
- GATE_IDS: dict = {}
39
-
40
- # ─────────────────────────────────────────────────────────────────────────────
41
- # Helpers
42
- # ─────────────────────────────────────────────────────────────────────────────
43
-
44
- def get_dynamic_chunk(dtype_target) -> int:
45
- vm = psutil.virtual_memory()
46
- safe_ram = vm.available * 0.85
47
- if HAS_JAX and dtype_target is jnp.complex128:
48
- bpe = 16
49
- elif dtype_target is np.complex128:
50
- bpe = 16
51
- else:
52
- bpe = 8
53
- max_elements = safe_ram / bpe
54
- max_bits = int(np.floor(np.log2(max(max_elements, 2.0))))
55
- return max(16, min(max_bits, 27))
56
-
57
-
58
- def _dtype_for_qubits(n_qubits: int):
59
- xp = jnp if HAS_JAX else np
60
- return xp.complex64 if n_qubits > 26 else xp.complex128
61
-
62
-
63
- # ─────────────────────────────────────────────────────────────────────────────
64
- # SafeMemoryGuard β€” Anti-OOM block
65
- # ─────────────────────────────────────────────────────────────────────────────
66
-
67
- class MemoryPressureError(RuntimeError):
68
- """
69
- Raised when available system RAM drops below the configured safety threshold.
70
- Catches the condition *before* the allocator attempts and crashes with
71
- jaxlib.xla_extension.XlaRuntimeError: RESOURCE_EXHAUSTED.
72
- """
73
- pass
74
-
75
-
76
- class SafeMemoryGuard:
77
- """
78
- Monitors system RAM before every high-memory operation and blocks execution
79
- if free RAM falls below ``threshold_pct`` of total physical memory.
80
- """
81
-
82
- _WARN_MULTIPLIER = 2.0
83
-
84
- def __init__(self, threshold_pct: float = 0.15, gc_before_check: bool = True):
85
- if not 0.0 < threshold_pct < 1.0:
86
- raise ValueError(f"threshold_pct must be in (0, 1), got {threshold_pct}")
87
- self.threshold_pct = threshold_pct
88
- self.gc_before_check = gc_before_check
89
- self._total_mb = psutil.virtual_memory().total / (1024 * 1024)
90
-
91
- def status(self) -> dict:
92
- vm = psutil.virtual_memory()
93
- available_mb = vm.available / (1024 * 1024)
94
- free_pct = vm.available / vm.total
95
- return {
96
- "total_mb" : self._total_mb,
97
- "available_mb": available_mb,
98
- "used_pct" : vm.percent,
99
- "free_pct" : free_pct * 100.0,
100
- "safe" : free_pct >= self.threshold_pct,
101
- }
102
-
103
- def check(self, context: str = "") -> None:
104
- if self.gc_before_check:
105
- gc.collect()
106
-
107
- s = self.status()
108
- tag = f"[{context}] " if context else ""
109
- free_frac = s["free_pct"] / 100.0
110
-
111
- if not s["safe"]:
112
- raise MemoryPressureError(
113
- f"\n{'─'*60}\n"
114
- f" {tag}MEMORIA CRITICA β€” simulazione bloccata\n"
115
- f" Disponibile : {s['available_mb']:.0f} MB "
116
- f"({s['free_pct']:.1f}% libera)\n"
117
- f" Soglia : {self.threshold_pct * 100:.0f}% "
118
- f"({self._total_mb * self.threshold_pct:.0f} MB)\n"
119
- f" Azione : liberare RAM o ridurre n_qubits / chunk_size.\n"
120
- f"{'─'*60}"
121
- )
122
-
123
- warn_threshold = self.threshold_pct * self._WARN_MULTIPLIER
124
- if free_frac < warn_threshold:
125
- print(
126
- f" [WARN] {tag}RAM bassa: {s['available_mb']:.0f} MB liberi "
127
- f"({s['free_pct']:.1f}%) β€” soglia critica al "
128
- f"{self.threshold_pct * 100:.0f}%."
129
- )
130
-
131
- def check_allocation(self, required_mb: float, context: str = "") -> None:
132
- """Like check(), but sized: verifies that *required_mb* can be
133
- allocated while still leaving threshold_pct free afterwards β€”
134
- check() alone only looks at RAM free *right now*, independent of
135
- what's about to be allocated (needed for Chunk's multi-chunk path,
136
- where several chunk-sized simulators are held in RAM at once)."""
137
- if self.gc_before_check:
138
- gc.collect()
139
-
140
- s = self.status()
141
- tag = f"[{context}] " if context else ""
142
- available_after_mb = s["available_mb"] - required_mb
143
- free_frac_after = available_after_mb / self._total_mb if self._total_mb > 0 else 0.0
144
-
145
- if available_after_mb < 0 or free_frac_after < self.threshold_pct:
146
- raise MemoryPressureError(
147
- f"\n{'─'*60}\n"
148
- f" {tag}MEMORIA INSUFFICIENTE per l'allocazione richiesta\n"
149
- f" Richiesti : {required_mb:.0f} MB\n"
150
- f" Disponibile : {s['available_mb']:.0f} MB ({s['free_pct']:.1f}% libera)\n"
151
- f" Dopo alloc. : {available_after_mb:.0f} MB ({free_frac_after * 100:.1f}% libera)\n"
152
- f" Soglia : {self.threshold_pct * 100:.0f}% libera dopo l'allocazione\n"
153
- f" Azione : ridurre n_qubits o liberare RAM. Il chunking su\n"
154
- f" disco per overflow oltre la RAM disponibile non\n"
155
- f" e' implementato β€” vedi CHANGELOG.\n"
156
- f"{'─'*60}"
157
- )
158
-
159
- def __repr__(self) -> str:
160
- s = self.status()
161
- return (
162
- f"SafeMemoryGuard("
163
- f"threshold={self.threshold_pct*100:.0f}%, "
164
- f"available={s['available_mb']:.0f} MB / {s['free_pct']:.1f}% free, "
165
- f"safe={s['safe']})"
166
- )
167
-
168
-
169
- # ─────────────────────────────────────────────────────────────────────────────
170
- # MemoryChunker (chunk1)
171
- # ─────────────────────────────────────────────────────────────────────────────
172
-
173
- class MemoryChunker:
174
- """
175
- Geometry calculator for chunked simulation.
176
-
177
- Attributes
178
- ----------
179
- n_qubits int β€” requested logical qubit count
180
- dtype β€” numpy/jax dtype for the statevector
181
- chunk_size_bits int β€” safe qubit-width that fits in RAM
182
- num_chunks int β€” number of statevector chunks required
183
- chunk_dim int β€” 2 ** chunk_size_bits
184
- """
185
-
186
- def __init__(self, n_qubits: int):
187
- self.n_qubits = n_qubits
188
- self.dtype = _dtype_for_qubits(n_qubits)
189
- self.chunk_size_bits = get_dynamic_chunk(self.dtype)
190
-
191
- if self.n_qubits <= self.chunk_size_bits:
192
- self.num_chunks = 1
193
- self.chunk_dim = 2 ** self.n_qubits
194
- else:
195
- self.num_chunks = 2 ** (self.n_qubits - self.chunk_size_bits)
196
- self.chunk_dim = 2 ** self.chunk_size_bits
197
-
198
- def geometry(self) -> Tuple[int, int, int]:
199
- """(num_chunks, chunk_dim, chunk_size_bits)"""
200
- return self.num_chunks, self.chunk_dim, self.chunk_size_bits
201
-
202
- def memory_mb(self) -> float:
203
- """Estimated RAM per chunk in MB."""
204
- bpe = np.dtype(self.dtype).itemsize
205
- return (self.chunk_dim * bpe) / (1024 * 1024)
206
-
207
- def __repr__(self) -> str:
208
- return (
209
- f"MemoryChunker(n_qubits={self.n_qubits}, "
210
- f"num_chunks={self.num_chunks}, "
211
- f"chunk_dim={self.chunk_dim}, "
212
- f"chunk_size_bits={self.chunk_size_bits}, "
213
- f"dtype={self.dtype}, "
214
- f"mem_per_chunk={self.memory_mb():.2f} MB)"
215
- )
216
-
217
-
218
- # ─────────────────────────────────────────────────────────────────────────────
219
- # Multi-chunk JIT kernel (num_chunks > 1)
220
- # ─────────────────────────────────────────────────────────────────────────────
221
-
222
- if HAS_JAX:
223
-
224
- def _build_multi_chunk_step(num_chunks: int, m: int, k: int):
225
- """
226
- Build a jax.lax.scan-compatible step function operating on the
227
- STACKED multi-chunk representation β€” a (num_chunks, chunk_dim)
228
- array β€” instead of a flat (2**n_qubits,) statevector.
229
-
230
- Modeled directly on compiler.py's _apply_gate_fast_step (same
231
- [g_id, q1, q2, param] encoding via GATE_IDS, same lax.switch for the
232
- 1-qubit matrix, same per-gate controlled-U dispatch for the 5
233
- two-qubit gate types) β€” but a gate touching a "chunk-select" qubit
234
- (index < m, the top m logical qubits that select WHICH chunk) mixes
235
- whole (chunk_dim,)-shaped ROWS instead of individual amplitudes,
236
- while a gate touching a "local" qubit (index >= m) mixes individual
237
- elements WITHIN each row in parallel. This never materializes a
238
- (2**n_qubits,) array β€” Chunk's whole reason to exist β€” because the
239
- stacked shape (num_chunks, chunk_dim) holds exactly the same total
240
- elements as the num_chunks separate per-chunk arrays it replaces.
241
-
242
- The 6 gate/qubit-location combinations below are a direct
243
- translation of the pre-JIT _apply_gate_multi's Python-loop formulas
244
- (removed once this replaced it) β€” verified case-by-case against
245
- DenseSVSimulator on non-chunked reference circuits before being
246
- wired in, not derived fresh. All 6 are traced unconditionally every
247
- step and selected via jnp.where on the runtime q1/q2 vs static m
248
- comparison, same "trace every branch" pattern _apply_gate_fast_step
249
- already uses for is_1q/is_2q and the 5 two-qubit sub-gates.
250
- """
251
- chunk_dim = 1 << k
252
-
253
- def step(chunks, operation):
254
- g_id = operation[0].astype(jnp.int32)
255
- q1 = operation[1].astype(jnp.int32)
256
- q2 = operation[2].astype(jnp.int32)
257
- param = operation[3]
258
- dtype = chunks.dtype # never hardcode complex128 β€” see the
259
- # use_float32 bug this exact mistake
260
- # caused once already in beast-mode.
261
-
262
- inv2 = jnp.asarray(1.0 / jnp.sqrt(2.0), dtype=dtype)
263
- half_p = param * jnp.float64(0.5)
264
- cos_p = jnp.cos(half_p).astype(dtype)
265
- sin_p = jnp.sin(half_p).astype(dtype)
266
- exp_pos = jnp.exp(1j * param).astype(dtype)
267
- exp_ph4 = jnp.exp(1j * jnp.pi / 4.0).astype(dtype)
268
- exp_mh4 = jnp.exp(-1j * jnp.pi / 4.0).astype(dtype)
269
- exp_pos_half = jnp.exp(1j * half_p).astype(dtype)
270
- exp_neg_half = jnp.exp(-1j * half_p).astype(dtype)
271
-
272
- # 1-qubit gate matrix β€” identical table to _apply_gate_fast_step
273
- safe_gid = jnp.clip(g_id, 0, 13)
274
- g_1q = jax.lax.switch(
275
- safe_gid,
276
- [
277
- lambda _: jnp.eye(2, dtype=dtype),
278
- lambda _: jnp.array([[inv2, inv2], [inv2, -inv2]], dtype=dtype),
279
- lambda _: jnp.array([[0.0 + 0j, 1.0 + 0j], [1.0 + 0j, 0.0 + 0j]], dtype=dtype),
280
- lambda _: jnp.array([[0.0 + 0j, -1j], [1j, 0.0 + 0j]], dtype=dtype),
281
- lambda _: jnp.array([[1.0 + 0j, 0.0 + 0j], [0.0 + 0j, -1.0 + 0j]], dtype=dtype),
282
- lambda _: jnp.array([[1.0 + 0j, 0.0 + 0j], [0.0 + 0j, 1j]], dtype=dtype),
283
- lambda _: jnp.array([[1.0 + 0j, 0.0 + 0j], [0.0 + 0j, -1j]], dtype=dtype),
284
- lambda _: jnp.array([[1.0 + 0j, 0.0 + 0j], [0.0 + 0j, exp_ph4]], dtype=dtype),
285
- lambda _: jnp.array([[1.0 + 0j, 0.0 + 0j], [0.0 + 0j, exp_mh4]], dtype=dtype),
286
- lambda _: jnp.array([[cos_p, -1j * sin_p], [-1j * sin_p, cos_p]], dtype=dtype),
287
- lambda _: jnp.array([[cos_p, -sin_p], [sin_p, cos_p]], dtype=dtype),
288
- lambda _: jnp.array([[jnp.exp(-1j * half_p), 0.0 + 0j], [0.0 + 0j, jnp.exp(1j * half_p)]], dtype=dtype),
289
- lambda _: jnp.array([[1.0 + 0j, 0.0 + 0j], [0.0 + 0j, exp_pos]], dtype=dtype),
290
- lambda _: jnp.array([[0.5 + 0.5j, 0.5 - 0.5j], [0.5 - 0.5j, 0.5 + 0.5j]], dtype=dtype),
291
- ],
292
- operand=None,
293
- )
294
-
295
- # Controlled-U submatrix for the 5 two-qubit gate types (mat[2:,2:]
296
- # of each gate's full 4x4 form β€” same values _apply_gate_multi's
297
- # `U = mat[2:, 2:]` extracted from GATES/PARAMETRIC_GATES).
298
- # 20=CX->X, 21=CZ->Z, 22=CP->P(theta), 24=CY->Y, 25=CRZ->RZ(theta).
299
- two_q_idx = jnp.where(g_id == 20, 0,
300
- jnp.where(g_id == 21, 1,
301
- jnp.where(g_id == 22, 2,
302
- jnp.where(g_id == 24, 3, 4))))
303
- U = jax.lax.switch(
304
- two_q_idx,
305
- [
306
- lambda _: jnp.array([[0.0 + 0j, 1.0 + 0j], [1.0 + 0j, 0.0 + 0j]], dtype=dtype),
307
- lambda _: jnp.array([[1.0 + 0j, 0.0 + 0j], [0.0 + 0j, -1.0 + 0j]], dtype=dtype),
308
- lambda _: jnp.array([[1.0 + 0j, 0.0 + 0j], [0.0 + 0j, exp_pos]], dtype=dtype),
309
- lambda _: jnp.array([[0.0 + 0j, -1j], [1j, 0.0 + 0j]], dtype=dtype),
310
- lambda _: jnp.array([[exp_neg_half, 0.0 + 0j], [0.0 + 0j, exp_pos_half]], dtype=dtype),
311
- ],
312
- operand=None,
313
- )
314
- g00, g01, g10, g11 = g_1q[0, 0], g_1q[0, 1], g_1q[1, 0], g_1q[1, 1]
315
- u00, u01, u10, u11 = U[0, 0], U[0, 1], U[1, 0], U[1, 1]
316
-
317
- # ── case 1: 1-qubit gate, LOCAL qubit (q1 >= m) ──────────────
318
- # Same do_1q amplitude-pair math as beast-mode, applied to every
319
- # chunk row in parallel (gather along axis 1, broadcasts over
320
- # axis 0 for free).
321
- def case_1q_local(_c):
322
- local_phys = (k - 1) - (q1 - m)
323
- stride = jnp.int32(1) << local_phys
324
- idx = jnp.arange(chunk_dim, dtype=jnp.int32)
325
- idx_pair = idx ^ stride
326
- mask0 = (idx & stride) == 0
327
- amp_pair = _c[:, idx_pair]
328
- new0 = g00 * _c + g01 * amp_pair
329
- new1 = g10 * amp_pair + g11 * _c
330
- return jnp.where(mask0[None, :], new0, new1)
331
-
332
- # ── case 2: 1-qubit gate, CHUNK-SELECT qubit (q1 < m) ────────
333
- # Same math, one level up: each "amplitude" is a whole
334
- # (chunk_dim,)-shaped row, mixed pairwise across axis 0.
335
- def case_1q_chunk(_c):
336
- stride = jnp.int32(1) << (m - 1 - q1)
337
- idxc = jnp.arange(num_chunks, dtype=jnp.int32)
338
- idxc_pair = idxc ^ stride
339
- mask0 = (idxc & stride) == 0
340
- amp_pair = _c[idxc_pair]
341
- new0 = g00 * _c + g01 * amp_pair
342
- new1 = g10 * amp_pair + g11 * _c
343
- return jnp.where(mask0[:, None], new0, new1)
344
-
345
- # ── case 3: 2-qubit, ctrl AND tgt both LOCAL ─────────────────
346
- def case_2q_local_local(_c):
347
- ctrl_phys = (k - 1) - (q1 - m)
348
- tgt_phys = (k - 1) - (q2 - m)
349
- idx = jnp.arange(chunk_dim, dtype=jnp.int32)
350
- ctrl_bit = (idx & (jnp.int32(1) << ctrl_phys)) != 0
351
- tgt_bit = (idx & (jnp.int32(1) << tgt_phys)) != 0
352
- partner = idx ^ (jnp.int32(1) << tgt_phys)
353
- amp_partner = _c[:, partner]
354
- new0 = u00 * _c + u01 * amp_partner
355
- new1 = u10 * amp_partner + u11 * _c
356
- after = jnp.where(tgt_bit[None, :], new1, new0)
357
- return jnp.where(ctrl_bit[None, :], after, _c)
358
-
359
- # ── case 4: ctrl CHUNK-SELECT, tgt LOCAL ─────────────────────
360
- # Whole chunks where the chunk-index's ctrl bit is set get U
361
- # applied as a local 1-qubit gate; the rest are untouched.
362
- def case_2q_ctrl_chunk_tgt_local(_c):
363
- ctrl_stride = jnp.int32(1) << (m - 1 - q1)
364
- idxc = jnp.arange(num_chunks, dtype=jnp.int32)
365
- ctrl_set = (idxc & ctrl_stride) != 0
366
- tgt_phys = (k - 1) - (q2 - m)
367
- idxl = jnp.arange(chunk_dim, dtype=jnp.int32)
368
- tgt_bit = (idxl & (jnp.int32(1) << tgt_phys)) != 0
369
- partner = idxl ^ (jnp.int32(1) << tgt_phys)
370
- amp_partner = _c[:, partner]
371
- new0 = u00 * _c + u01 * amp_partner
372
- new1 = u10 * amp_partner + u11 * _c
373
- after = jnp.where(tgt_bit[None, :], new1, new0)
374
- return jnp.where(ctrl_set[:, None], after, _c)
375
-
376
- # ── case 5: ctrl LOCAL, tgt CHUNK-SELECT ─────────────────────
377
- # Pairs of chunks get mixed, but ONLY where the local ctrl bit
378
- # (same position in every chunk) is set β€” an elementwise mask.
379
- def case_2q_ctrl_local_tgt_chunk(_c):
380
- ctrl_phys = (k - 1) - (q1 - m)
381
- idxl = jnp.arange(chunk_dim, dtype=jnp.int32)
382
- ctrl_bit = (idxl & (jnp.int32(1) << ctrl_phys)) != 0
383
- tgt_stride = jnp.int32(1) << (m - 1 - q2)
384
- idxc = jnp.arange(num_chunks, dtype=jnp.int32)
385
- idxc_pair = idxc ^ tgt_stride
386
- is_c0 = (idxc & tgt_stride) == 0
387
- amp_pair = _c[idxc_pair]
388
- new_c0 = u00 * _c + u01 * amp_pair
389
- new_c1 = u10 * amp_pair + u11 * _c
390
- after = jnp.where(is_c0[:, None], new_c0, new_c1)
391
- return jnp.where(ctrl_bit[None, :], after, _c)
392
-
393
- # ── case 6: ctrl AND tgt both CHUNK-SELECT ───────────────────
394
- def case_2q_both_chunk(_c):
395
- ctrl_stride = jnp.int32(1) << (m - 1 - q1)
396
- tgt_stride = jnp.int32(1) << (m - 1 - q2)
397
- idxc = jnp.arange(num_chunks, dtype=jnp.int32)
398
- ctrl_set = (idxc & ctrl_stride) != 0
399
- idxc_pair = idxc ^ tgt_stride
400
- is_c0 = (idxc & tgt_stride) == 0
401
- amp_pair = _c[idxc_pair]
402
- new_c0 = u00 * _c + u01 * amp_pair
403
- new_c1 = u10 * amp_pair + u11 * _c
404
- after = jnp.where(is_c0[:, None], new_c0, new_c1)
405
- return jnp.where(ctrl_set[:, None], after, _c)
406
-
407
- is_2q = g_id >= 20
408
- q1_chunk = q1 < m
409
- q2_chunk = q2 < m
410
-
411
- result_2q = jnp.where(
412
- q1_chunk & q2_chunk, case_2q_both_chunk(chunks),
413
- jnp.where(q1_chunk & (~q2_chunk), case_2q_ctrl_chunk_tgt_local(chunks),
414
- jnp.where((~q1_chunk) & q2_chunk, case_2q_ctrl_local_tgt_chunk(chunks),
415
- case_2q_local_local(chunks))))
416
- result_1q = jnp.where(q1_chunk, case_1q_chunk(chunks), case_1q_local(chunks))
417
-
418
- new_chunks = jnp.where(is_2q, result_2q, result_1q)
419
- return new_chunks.astype(dtype), None
420
-
421
- return step
422
-
423
-
424
- def _build_multi_chunk_runner(num_chunks: int, m: int, k: int):
425
- """jax.jit-compiled (chunks, compiled_ops) -> final_chunks, closed
426
- over the static per-Chunk-instance geometry (num_chunks, m, k don't
427
- change across calls on the same instance)."""
428
- step = _build_multi_chunk_step(num_chunks, m, k)
429
-
430
- @jax.jit
431
- def run(chunks, compiled_ops):
432
- final, _ = jax.lax.scan(step, chunks, compiled_ops)
433
- return final
434
-
435
- return run
436
-
437
-
438
- def _compile_multi_chunk_ops(circuit: List) -> "jnp.ndarray":
439
- """Structural + GATE_IDS compilation shared by the multi-chunk JIT
440
- path β€” same [g_id, q1, q2, param] row format as beast-mode's own
441
- compiled ops, built via GATE_IDS instead of the old _resolve_gate's
442
- GATES/PARAMETRIC_GATES lookup. This finally aligns multi-chunk's
443
- gate coverage with beast-mode's (both silently skip a gate name not
444
- in GATE_IDS β€” same known, tracked behavior, see issue #4 β€” instead
445
- of the old _resolve_gate's NotImplementedError for e.g. ecr/iswap)."""
446
- target = QuantumTranspiler.transpile(circuit)
447
- rows = []
448
- for cmd in target:
449
- name = cmd[0].lower() if isinstance(cmd[0], str) else str(cmd[0]).lower()
450
- if name not in GATE_IDS:
451
- continue
452
- g_id = float(GATE_IDS[name])
453
- args = cmd[1:]
454
- if name in ('cx', 'cz', 'cp', 'cphase', 'cy', 'crz'):
455
- q1, q2 = float(args[0]), float(args[1])
456
- param = float(args[2]) if len(args) > 2 else 0.0
457
- rows.append([g_id, q1, q2, param])
458
- elif args:
459
- q1 = float(args[0])
460
- param = float(args[1]) if len(args) > 1 else 0.0
461
- rows.append([g_id, q1, 0.0, param])
462
- if not rows:
463
- return jnp.empty((0, 4), dtype=jnp.float64)
464
- return jnp.array(rows, dtype=jnp.float64)
465
-
466
-
467
- # ─────────────────────────────────────────────────────────────────────────────
468
- # CircuitChunker
469
- # ─────────────────────────────────────────────────────────────────────────────
470
-
471
- class CircuitChunker:
472
- """
473
- Transpile a circuit once, then execute it in fixed-size gate-slices so
474
- XLA sees the same trace shape on every compilation.
475
-
476
- A SafeMemoryGuard is checked **before every slice** β€” if RAM drops below
477
- 15% the current slice is aborted with MemoryPressureError before JAX
478
- attempts the allocation.
479
-
480
- Parameters
481
- ----------
482
- simulator_instance : DenseSVSimulator
483
- Physical simulator (sized to safe_qubits, not logical n_qubits).
484
- memory_threshold : float
485
- Passed to SafeMemoryGuard. Default 0.15 (15%).
486
- """
487
-
488
- def __init__(
489
- self,
490
- simulator_instance: Optional[DenseSVSimulator] = None,
491
- memory_threshold: float = 0.15,
492
- ):
493
- self.sim = simulator_instance
494
- self._guard = SafeMemoryGuard(threshold_pct=memory_threshold)
495
-
496
- def split_circuit(self, circuit: List, chunk_size: int = 500) -> None:
497
- """
498
- Execute *circuit* in slices of *chunk_size* gates.
499
-
500
- Raises
501
- ------
502
- RuntimeError if no simulator instance is attached.
503
- MemoryPressureError if RAM drops below threshold before a slice.
504
- """
505
- if self.sim is None:
506
- raise RuntimeError(
507
- "CircuitChunker: no simulator instance attached. "
508
- "Pass simulator_instance= at construction or assign .sim."
509
- )
510
-
511
- target: List = QuantumTranspiler.transpile(circuit)
512
- n_slices = (len(target) + chunk_size - 1) // chunk_size
513
-
514
- for idx, i in enumerate(range(0, len(target), chunk_size)):
515
- # ── Anti-OOM check before every slice ───────────────────────────
516
- self._guard.check(f"slice {idx + 1}/{n_slices}")
517
- self.sim.run_circuit_jit_beast_mode(target[i : i + chunk_size])
518
-
519
-
520
- # ─────────────────────────────────────────────────────────────────────────────
521
- # Chunk (chunk2 / Chunk2Incrociato)
522
- # ─────────────────────────────────────────────────────────────────────────────
523
-
524
- class Chunk:
525
- """
526
- Anti-OOM wrapper for large-qubit simulation.
527
-
528
- Does NOT subclass DenseSVSimulator directly β€” the parent __init__ allocates
529
- 2**n_qubits elements immediately (17 GB for 30 qubits).
530
-
531
- For n_qubits <= chunk_size_bits (the RAM-safe budget): a single inner
532
- simulator is allocated and the logical qubit count is stored separately.
533
-
534
- For n_qubits > chunk_size_bits: num_chunks separate chunk_size_bits-qubit
535
- simulators are held in RAM simultaneously (see _dispatch_multi) β€” no
536
- disk/memmap paging, so this only covers a *moderate* overflow beyond the
537
- safe budget (as many chunks as actually fit in RAM at once, checked
538
- up front via SafeMemoryGuard.check_allocation before anything is
539
- allocated). Benchmark attributes (num_chunks, chunk_size_bits, dtype)
540
- are forwarded transparently from the embedded MemoryChunker.
541
-
542
- A SafeMemoryGuard fires before any simulator is instantiated
543
- (pre-allocation check) and is also embedded in CircuitChunker for
544
- per-slice protection during execution (n_qubits <= chunk_size_bits path).
545
-
546
- Parameters
547
- ----------
548
- n_qubits : logical qubit count of the target circuit
549
- chunk_size_gates : gate-slice size for JIT compilation (default 500)
550
- memory_threshold : free-RAM fraction below which execution is blocked
551
- (default 0.15 = 15%)
552
- use_gpu : forwarded to DenseSVSimulator
553
- use_float32 : forwarded to DenseSVSimulator
554
- """
555
-
556
- def __init__(
557
- self,
558
- n_qubits: int,
559
- chunk_size_gates: int = 500,
560
- memory_threshold: float = 0.15,
561
- use_gpu: bool = False,
562
- use_float32: bool = False,
563
- ):
564
- # 1. Geometry β€” purely RAM-based, no JAX allocation yet
565
- self._mem_chunker = MemoryChunker(n_qubits)
566
- self._guard = SafeMemoryGuard(threshold_pct=memory_threshold)
567
-
568
- # 2. Logical qubit count (for circuit parsing)
569
- self.n = n_qubits
570
- self.chunk_size_gates = chunk_size_gates
571
- self._m = n_qubits - self._mem_chunker.chunk_size_bits # chunk-select qubit count (0 if num_chunks==1)
572
-
573
- if self._mem_chunker.num_chunks == 1:
574
- # 3a. Pre-allocation RAM check β€” block here rather than inside JAX
575
- safe_q = min(n_qubits, self._mem_chunker.chunk_size_bits)
576
- self._guard.check(f"Chunk.__init__ β€” allocating {safe_q}-qubit simulator")
577
-
578
- # 4a. Physical simulator sized to what RAM can actually hold
579
- self._inner_sim = DenseSVSimulator(
580
- safe_q,
581
- use_gpu=use_gpu,
582
- use_float32=use_float32,
583
- )
584
- self._chunk_sims = None
585
- self._multi_chunk_runner = None
586
-
587
- # 5a. Circuit chunker wired to the physical simulator, with same threshold
588
- self._circuit_chunker = CircuitChunker(
589
- simulator_instance=self._inner_sim,
590
- memory_threshold=memory_threshold,
591
- )
592
- else:
593
- # 3b. Sized pre-allocation check: num_chunks chunk-sized simulators
594
- # held in RAM at once, plus ~2 chunks of headroom for the temporary
595
- # arrays the cross-chunk gate-mixing math allocates at its peak.
596
- num_chunks = self._mem_chunker.num_chunks
597
- per_chunk_mb = self._mem_chunker.memory_mb()
598
- required_mb = (num_chunks + 2) * per_chunk_mb
599
- self._guard.check_allocation(
600
- required_mb,
601
- f"Chunk.__init__ β€” allocating {num_chunks} chunks of "
602
- f"{self._mem_chunker.chunk_size_bits} qubits each",
603
- )
604
-
605
- # 4b. num_chunks independent chunk-sized simulators. Each one's own
606
- # __init__ resets it to |0...0>: only chunk 0 should carry the
607
- # amplitude-1 seed for the LOGICAL |0...0>, the rest must start
608
- # at all-zero (direct .sv assignment β€” set_state/set_initial_state
609
- # reject zero-norm vectors by design).
610
- self._chunk_sims = [
611
- DenseSVSimulator(self._mem_chunker.chunk_size_bits, use_gpu=use_gpu, use_float32=use_float32)
612
- for _ in range(num_chunks)
613
- ]
614
- for sim in self._chunk_sims[1:]:
615
- sim.sv = sim.xp.zeros(self._mem_chunker.chunk_dim, dtype=sim.dtype)
616
-
617
- self._inner_sim = None
618
- self._circuit_chunker = None
619
-
620
- # 6b. JIT runner for the multi-chunk dispatch β€” built once here
621
- # since num_chunks/m/chunk_size_bits are fixed for this
622
- # instance's whole lifetime, reused by every run_chunk() call.
623
- self._multi_chunk_runner = _build_multi_chunk_runner(
624
- num_chunks, self._m, self._mem_chunker.chunk_size_bits)
625
-
626
- # ── Benchmark-facing attribute forwarding ────────────────────────────────
627
-
628
- @property
629
- def num_chunks(self) -> int:
630
- return self._mem_chunker.num_chunks
631
-
632
- @property
633
- def chunk_size_bits(self) -> int:
634
- return self._mem_chunker.chunk_size_bits
635
-
636
- @property
637
- def chunk_dim(self) -> int:
638
- return self._mem_chunker.chunk_dim
639
-
640
- @property
641
- def dtype(self):
642
- return self._mem_chunker.dtype
643
-
644
- @property
645
- def memory_geometry(self) -> MemoryChunker:
646
- return self._mem_chunker
647
-
648
- # ── Simulator-facing forwarding ──────────────────────────────────────────
649
-
650
- @property
651
- def sv(self):
652
- """Current statevector. For num_chunks==1, the physical (chunk-sized)
653
- simulator's own array. For num_chunks>1, the chunks concatenated in
654
- ascending order β€” valid because of the MSB-first correspondence
655
- between chunk index and the top `_m` logical qubits (see
656
- _dispatch_multi's docstring)."""
657
- if self._chunk_sims is None:
658
- return self._inner_sim.sv
659
- xp = self._chunk_sims[0].xp
660
- return xp.concatenate([sim.sv for sim in self._chunk_sims])
661
-
662
- @sv.setter
663
- def sv(self, value):
664
- """Accepts a full-length (2**n,) statevector (e.g. the output of
665
- NoiseModel.apply_to_sv called on `.sv`) and writes it back through
666
- to the physical storage -- the inner simulator directly for
667
- num_chunks==1, or split back into per-chunk slices (same ascending
668
- concatenation order as the getter) for num_chunks>1."""
669
- if self._chunk_sims is None:
670
- self._inner_sim.sv = value
671
- return
672
- chunk_dim = self._mem_chunker.chunk_dim
673
- xp = self._chunk_sims[0].xp
674
- value = xp.asarray(value)
675
- for i, sim in enumerate(self._chunk_sims):
676
- sim.sv = value[i * chunk_dim:(i + 1) * chunk_dim]
677
-
678
- def memory_mb(self) -> float:
679
- """RAM used by the physical statevector(s) in MB."""
680
- if self._chunk_sims is None:
681
- return self._inner_sim.memory_mb()
682
- return sum(sim.memory_mb() for sim in self._chunk_sims)
683
-
684
- def get_probabilities(self):
685
- """|amplitude|^2 for every basis state.
686
-
687
- num_chunks==1: forwards to the inner DenseSVSimulator for parity
688
- with its own get_probabilities().
689
-
690
- num_chunks>1: concatenates the RAW statevectors first and normalizes
691
- ONCE over the full array β€” NOT each chunk's own get_probabilities()
692
- (that would independently renormalize each chunk's partial mass to
693
- 1, summing to num_chunks overall and destroying the relative
694
- weighting between chunks)."""
695
- if self._chunk_sims is None:
696
- return self._inner_sim.get_probabilities()
697
- full_sv = np.concatenate([np.array(sim.sv) for sim in self._chunk_sims])
698
- probs = np.abs(full_sv) ** 2
699
- probs = np.clip(probs, 0.0, 1.0)
700
- total = probs.sum()
701
- if total > 1e-12:
702
- probs /= total
703
- return probs
704
-
705
- def get_statevector(self):
706
- """Full complex statevector, num_qubits logical qubits long
707
- (2**n elements). num_chunks==1: forwards to the inner
708
- DenseSVSimulator. num_chunks>1: raw chunks concatenated in order
709
- (see `sv` property)."""
710
- if self._chunk_sims is None:
711
- return self._inner_sim.get_statevector()
712
- return np.concatenate([np.array(sim.sv, dtype=sim.dtype) for sim in self._chunk_sims])
713
-
714
- # ── Multi-chunk gate dispatch (num_chunks > 1) ───────────────────────────
715
-
716
- def _dispatch_multi(self, circuit: List) -> None:
717
- """Executes *circuit* against the num_chunks>1 chunk representation
718
- via one jax.lax.scan call over the whole (transpiled, GATE_IDS-
719
- compiled) circuit β€” see _build_multi_chunk_step/_build_multi_chunk_runner
720
- above for the kernel, and _compile_multi_chunk_ops for the encoding.
721
-
722
- Convention: chunk index `c` (m = self._m bits, MSB-first, same
723
- n-1-qubit convention as DenseSVSimulator) equals the value of the
724
- top m logical qubits (indices [0, m)); chunk_sims[c].sv holds the
725
- chunk_dim amplitudes for the remaining (local) qubits [m, n). This
726
- makes full_sv.reshape(num_chunks, chunk_dim)[c] == chunk_sims[c].sv
727
- exactly, since NumPy's row-major reshape splits a (2,)*n tensor on
728
- the leading axes first β€” i.e. the most-significant qubits, matching
729
- this simulator's MSB-first indexing throughout. Stacking
730
- chunk_sims[i].sv into one (num_chunks, chunk_dim) array before the
731
- scan, and unstacking after, holds exactly the same total element
732
- count as the num_chunks separate arrays it replaces β€” the anti-OOM
733
- property this class exists for is preserved, nothing (2**n_qubits,)
734
- shaped is ever materialized."""
735
- compiled_ops = _compile_multi_chunk_ops(circuit)
736
- xp = self._chunk_sims[0].xp
737
- stacked = xp.stack([sim.sv for sim in self._chunk_sims])
738
- final = self._multi_chunk_runner(stacked, compiled_ops)
739
- for i, sim in enumerate(self._chunk_sims):
740
- sim.sv = final[i]
741
-
742
- # ── Public API ───────────────────────────────────────────────────────────
743
-
744
- def run_chunk(
745
- self,
746
- circuit: List,
747
- chunk_size_gates: Optional[int] = None,
748
- ) -> None:
749
-
750
- if self._chunk_sims is not None:
751
- self._dispatch_multi(circuit)
752
- return
753
- size = chunk_size_gates if chunk_size_gates is not None else self.chunk_size_gates
754
- self._circuit_chunker.split_circuit(circuit, chunk_size=size)
755
-
756
- def __repr__(self) -> str:
757
- s = self._guard.status()
758
- safe_qubits = self._inner_sim.n if self._inner_sim is not None else self._mem_chunker.chunk_size_bits
759
- return (
760
- f"Chunk(n_qubits={self.n}, "
761
- f"safe_qubits={safe_qubits}, "
762
- f"num_chunks={self.num_chunks}, "
763
- f"chunk_size_bits={self.chunk_size_bits}, "
764
- f"dtype={self.dtype}, "
765
- f"mem_per_chunk={self.memory_mb():.1f} MB, "
766
- f"ram_free={s['free_pct']:.1f}%, "
767
- f"has_jax={HAS_JAX})"
768
- )
769
-
770
-
771
- # ─────────────────────────────────────────────────────────────────────────────
772
- # Backward-compatibility aliases
773
- # ─────────────────────────────────────────────────────────────────────────────
774
- chunk1 = MemoryChunker
775
- chunk2 = Chunk
776
- Chunk2Incrociato = Chunk
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gc
2
+ import psutil
3
+ import numpy as np
4
+ from typing import List, Optional, Tuple
5
+
6
+ # JAX is now a mandatory dependency (see registry.py) -- kept as an
7
+ # import-time flag for the dual-path code below, which stays as-is.
8
+ import jax
9
+ import jax.numpy as jnp
10
+ HAS_JAX = True
11
+
12
+ # ── Flexible import with stub fallback ──────────────────────────────────────
13
+ try:
14
+ from simulator import DenseSVSimulator
15
+ from compiler import QuantumTranspiler
16
+ from gates import GATE_IDS
17
+ except ModuleNotFoundError:
18
+ try:
19
+ from dense_evolution.simulator import DenseSVSimulator
20
+ from dense_evolution.compiler import QuantumTranspiler
21
+ from dense_evolution.gates import GATE_IDS
22
+ except ModuleNotFoundError:
23
+ class DenseSVSimulator: # type: ignore[no-redef]
24
+ def __init__(self, n_qubits, **kwargs):
25
+ self.n = n_qubits
26
+ self.dim = 2 ** n_qubits
27
+ self.dtype = np.complex128
28
+ self.sv = np.zeros(self.dim, dtype=self.dtype)
29
+ self.sv[0] = 1.0
30
+ def run_circuit_jit_beast_mode(self, circuit_slice): pass
31
+ def memory_mb(self) -> float:
32
+ return (self.dim * np.dtype(self.dtype).itemsize) / 1_000_000
33
+
34
+ class QuantumTranspiler: # type: ignore[no-redef]
35
+ @staticmethod
36
+ def transpile(circuit): return circuit
37
+
38
+ GATE_IDS: dict = {}
39
+
40
+ # ─────────────────────────────────────────────────────────────────────────────
41
+ # Helpers
42
+ # ─────────────────────────────────────────────────────────────────────────────
43
+
44
+ def get_dynamic_chunk(dtype_target) -> int:
45
+ vm = psutil.virtual_memory()
46
+ safe_ram = vm.available * 0.85
47
+ if HAS_JAX and dtype_target is jnp.complex128:
48
+ bpe = 16
49
+ elif dtype_target is np.complex128:
50
+ bpe = 16
51
+ else:
52
+ bpe = 8
53
+ max_elements = safe_ram / bpe
54
+ max_bits = int(np.floor(np.log2(max(max_elements, 2.0))))
55
+ return max(16, min(max_bits, 27))
56
+
57
+
58
+ def _dtype_for_qubits(n_qubits: int):
59
+ xp = jnp if HAS_JAX else np
60
+ return xp.complex64 if n_qubits > 26 else xp.complex128
61
+
62
+
63
+ # ─────────────────────────────────────────────────────────────────────────────
64
+ # SafeMemoryGuard β€” Anti-OOM block
65
+ # ─────────────────────────────────────────────────────────────────────────────
66
+
67
+ class MemoryPressureError(RuntimeError):
68
+ """
69
+ Raised when available system RAM drops below the configured safety threshold.
70
+ Catches the condition *before* the allocator attempts and crashes with
71
+ jaxlib.xla_extension.XlaRuntimeError: RESOURCE_EXHAUSTED.
72
+ """
73
+ pass
74
+
75
+
76
+ class SafeMemoryGuard:
77
+ """
78
+ Monitors system RAM before every high-memory operation and blocks execution
79
+ if free RAM falls below ``threshold_pct`` of total physical memory.
80
+ """
81
+
82
+ _WARN_MULTIPLIER = 2.0
83
+
84
+ def __init__(self, threshold_pct: float = 0.15, gc_before_check: bool = True):
85
+ if not 0.0 < threshold_pct < 1.0:
86
+ raise ValueError(f"threshold_pct must be in (0, 1), got {threshold_pct}")
87
+ self.threshold_pct = threshold_pct
88
+ self.gc_before_check = gc_before_check
89
+ self._total_mb = psutil.virtual_memory().total / (1024 * 1024)
90
+
91
+ def status(self) -> dict:
92
+ vm = psutil.virtual_memory()
93
+ available_mb = vm.available / (1024 * 1024)
94
+ free_pct = vm.available / vm.total
95
+ return {
96
+ "total_mb" : self._total_mb,
97
+ "available_mb": available_mb,
98
+ "used_pct" : vm.percent,
99
+ "free_pct" : free_pct * 100.0,
100
+ "safe" : free_pct >= self.threshold_pct,
101
+ }
102
+
103
+ def check(self, context: str = "") -> None:
104
+ if self.gc_before_check:
105
+ gc.collect()
106
+
107
+ s = self.status()
108
+ tag = f"[{context}] " if context else ""
109
+ free_frac = s["free_pct"] / 100.0
110
+
111
+ if not s["safe"]:
112
+ raise MemoryPressureError(
113
+ f"\n{'─'*60}\n"
114
+ f" {tag}MEMORIA CRITICA β€” simulazione bloccata\n"
115
+ f" Disponibile : {s['available_mb']:.0f} MB "
116
+ f"({s['free_pct']:.1f}% libera)\n"
117
+ f" Soglia : {self.threshold_pct * 100:.0f}% "
118
+ f"({self._total_mb * self.threshold_pct:.0f} MB)\n"
119
+ f" Azione : liberare RAM o ridurre n_qubits / chunk_size.\n"
120
+ f"{'─'*60}"
121
+ )
122
+
123
+ warn_threshold = self.threshold_pct * self._WARN_MULTIPLIER
124
+ if free_frac < warn_threshold:
125
+ print(
126
+ f" [WARN] {tag}RAM bassa: {s['available_mb']:.0f} MB liberi "
127
+ f"({s['free_pct']:.1f}%) β€” soglia critica al "
128
+ f"{self.threshold_pct * 100:.0f}%."
129
+ )
130
+
131
+ def check_allocation(self, required_mb: float, context: str = "") -> None:
132
+ """Like check(), but sized: verifies that *required_mb* can be
133
+ allocated while still leaving threshold_pct free afterwards β€”
134
+ check() alone only looks at RAM free *right now*, independent of
135
+ what's about to be allocated (needed for Chunk's multi-chunk path,
136
+ where several chunk-sized simulators are held in RAM at once)."""
137
+ if self.gc_before_check:
138
+ gc.collect()
139
+
140
+ s = self.status()
141
+ tag = f"[{context}] " if context else ""
142
+ available_after_mb = s["available_mb"] - required_mb
143
+ free_frac_after = available_after_mb / self._total_mb if self._total_mb > 0 else 0.0
144
+
145
+ if available_after_mb < 0 or free_frac_after < self.threshold_pct:
146
+ raise MemoryPressureError(
147
+ f"\n{'─'*60}\n"
148
+ f" {tag}MEMORIA INSUFFICIENTE per l'allocazione richiesta\n"
149
+ f" Richiesti : {required_mb:.0f} MB\n"
150
+ f" Disponibile : {s['available_mb']:.0f} MB ({s['free_pct']:.1f}% libera)\n"
151
+ f" Dopo alloc. : {available_after_mb:.0f} MB ({free_frac_after * 100:.1f}% libera)\n"
152
+ f" Soglia : {self.threshold_pct * 100:.0f}% libera dopo l'allocazione\n"
153
+ f" Azione : ridurre n_qubits o liberare RAM. Il chunking su\n"
154
+ f" disco per overflow oltre la RAM disponibile non\n"
155
+ f" e' implementato β€” vedi CHANGELOG.\n"
156
+ f"{'─'*60}"
157
+ )
158
+
159
+ def __repr__(self) -> str:
160
+ s = self.status()
161
+ return (
162
+ f"SafeMemoryGuard("
163
+ f"threshold={self.threshold_pct*100:.0f}%, "
164
+ f"available={s['available_mb']:.0f} MB / {s['free_pct']:.1f}% free, "
165
+ f"safe={s['safe']})"
166
+ )
167
+
168
+
169
+ # ─────────────────────────────────────────────────────────────────────────────
170
+ # MemoryChunker (chunk1)
171
+ # ─────────────────────────────────────────────────────────────────────────────
172
+
173
+ class MemoryChunker:
174
+ """
175
+ Geometry calculator for chunked simulation.
176
+
177
+ Attributes
178
+ ----------
179
+ n_qubits int β€” requested logical qubit count
180
+ dtype β€” numpy/jax dtype for the statevector
181
+ chunk_size_bits int β€” safe qubit-width that fits in RAM
182
+ num_chunks int β€” number of statevector chunks required
183
+ chunk_dim int β€” 2 ** chunk_size_bits
184
+ """
185
+
186
+ def __init__(self, n_qubits: int):
187
+ self.n_qubits = n_qubits
188
+ self.dtype = _dtype_for_qubits(n_qubits)
189
+ self.chunk_size_bits = get_dynamic_chunk(self.dtype)
190
+
191
+ if self.n_qubits <= self.chunk_size_bits:
192
+ self.num_chunks = 1
193
+ self.chunk_dim = 2 ** self.n_qubits
194
+ else:
195
+ self.num_chunks = 2 ** (self.n_qubits - self.chunk_size_bits)
196
+ self.chunk_dim = 2 ** self.chunk_size_bits
197
+
198
+ def geometry(self) -> Tuple[int, int, int]:
199
+ """(num_chunks, chunk_dim, chunk_size_bits)"""
200
+ return self.num_chunks, self.chunk_dim, self.chunk_size_bits
201
+
202
+ def memory_mb(self) -> float:
203
+ """Estimated RAM per chunk in MB."""
204
+ bpe = np.dtype(self.dtype).itemsize
205
+ return (self.chunk_dim * bpe) / (1024 * 1024)
206
+
207
+ def __repr__(self) -> str:
208
+ return (
209
+ f"MemoryChunker(n_qubits={self.n_qubits}, "
210
+ f"num_chunks={self.num_chunks}, "
211
+ f"chunk_dim={self.chunk_dim}, "
212
+ f"chunk_size_bits={self.chunk_size_bits}, "
213
+ f"dtype={self.dtype}, "
214
+ f"mem_per_chunk={self.memory_mb():.2f} MB)"
215
+ )
216
+
217
+
218
+ # ─────────────────────────────────────────────────────────────────────────────
219
+ # Multi-chunk JIT kernel (num_chunks > 1)
220
+ # ─────────────────────────────────────────────────────────────────────────────
221
+
222
+ if HAS_JAX:
223
+
224
+ def _build_multi_chunk_step(num_chunks: int, m: int, k: int):
225
+ """
226
+ Build a jax.lax.scan-compatible step function operating on the
227
+ STACKED multi-chunk representation β€” a (num_chunks, chunk_dim)
228
+ array β€” instead of a flat (2**n_qubits,) statevector.
229
+
230
+ Modeled directly on compiler.py's _apply_gate_fast_step (same
231
+ [g_id, q1, q2, param] encoding via GATE_IDS, same lax.switch for the
232
+ 1-qubit matrix, same per-gate controlled-U dispatch for the 5
233
+ two-qubit gate types) β€” but a gate touching a "chunk-select" qubit
234
+ (index < m, the top m logical qubits that select WHICH chunk) mixes
235
+ whole (chunk_dim,)-shaped ROWS instead of individual amplitudes,
236
+ while a gate touching a "local" qubit (index >= m) mixes individual
237
+ elements WITHIN each row in parallel. This never materializes a
238
+ (2**n_qubits,) array β€” Chunk's whole reason to exist β€” because the
239
+ stacked shape (num_chunks, chunk_dim) holds exactly the same total
240
+ elements as the num_chunks separate per-chunk arrays it replaces.
241
+
242
+ The 6 gate/qubit-location combinations below are a direct
243
+ translation of the pre-JIT _apply_gate_multi's Python-loop formulas
244
+ (removed once this replaced it) β€” verified case-by-case against
245
+ DenseSVSimulator on non-chunked reference circuits before being
246
+ wired in, not derived fresh. All 6 are traced unconditionally every
247
+ step and selected via jnp.where on the runtime q1/q2 vs static m
248
+ comparison, same "trace every branch" pattern _apply_gate_fast_step
249
+ already uses for is_1q/is_2q and the 5 two-qubit sub-gates.
250
+ """
251
+ chunk_dim = 1 << k
252
+
253
+ def step(chunks, operation):
254
+ g_id = operation[0].astype(jnp.int32)
255
+ q1 = operation[1].astype(jnp.int32)
256
+ q2 = operation[2].astype(jnp.int32)
257
+ param = operation[3]
258
+ dtype = chunks.dtype # never hardcode complex128 β€” see the
259
+ # use_float32 bug this exact mistake
260
+ # caused once already in beast-mode.
261
+
262
+ inv2 = jnp.asarray(1.0 / jnp.sqrt(2.0), dtype=dtype)
263
+ half_p = param * jnp.float64(0.5)
264
+ cos_p = jnp.cos(half_p).astype(dtype)
265
+ sin_p = jnp.sin(half_p).astype(dtype)
266
+ exp_pos = jnp.exp(1j * param).astype(dtype)
267
+ exp_ph4 = jnp.exp(1j * jnp.pi / 4.0).astype(dtype)
268
+ exp_mh4 = jnp.exp(-1j * jnp.pi / 4.0).astype(dtype)
269
+ exp_pos_half = jnp.exp(1j * half_p).astype(dtype)
270
+ exp_neg_half = jnp.exp(-1j * half_p).astype(dtype)
271
+
272
+ # 1-qubit gate matrix β€” identical table to _apply_gate_fast_step
273
+ safe_gid = jnp.clip(g_id, 0, 13)
274
+ g_1q = jax.lax.switch(
275
+ safe_gid,
276
+ [
277
+ lambda _: jnp.eye(2, dtype=dtype),
278
+ lambda _: jnp.array([[inv2, inv2], [inv2, -inv2]], dtype=dtype),
279
+ lambda _: jnp.array([[0.0 + 0j, 1.0 + 0j], [1.0 + 0j, 0.0 + 0j]], dtype=dtype),
280
+ lambda _: jnp.array([[0.0 + 0j, -1j], [1j, 0.0 + 0j]], dtype=dtype),
281
+ lambda _: jnp.array([[1.0 + 0j, 0.0 + 0j], [0.0 + 0j, -1.0 + 0j]], dtype=dtype),
282
+ lambda _: jnp.array([[1.0 + 0j, 0.0 + 0j], [0.0 + 0j, 1j]], dtype=dtype),
283
+ lambda _: jnp.array([[1.0 + 0j, 0.0 + 0j], [0.0 + 0j, -1j]], dtype=dtype),
284
+ lambda _: jnp.array([[1.0 + 0j, 0.0 + 0j], [0.0 + 0j, exp_ph4]], dtype=dtype),
285
+ lambda _: jnp.array([[1.0 + 0j, 0.0 + 0j], [0.0 + 0j, exp_mh4]], dtype=dtype),
286
+ lambda _: jnp.array([[cos_p, -1j * sin_p], [-1j * sin_p, cos_p]], dtype=dtype),
287
+ lambda _: jnp.array([[cos_p, -sin_p], [sin_p, cos_p]], dtype=dtype),
288
+ lambda _: jnp.array([[jnp.exp(-1j * half_p), 0.0 + 0j], [0.0 + 0j, jnp.exp(1j * half_p)]], dtype=dtype),
289
+ lambda _: jnp.array([[1.0 + 0j, 0.0 + 0j], [0.0 + 0j, exp_pos]], dtype=dtype),
290
+ lambda _: jnp.array([[0.5 + 0.5j, 0.5 - 0.5j], [0.5 - 0.5j, 0.5 + 0.5j]], dtype=dtype),
291
+ ],
292
+ operand=None,
293
+ )
294
+
295
+ # Controlled-U submatrix for the 5 two-qubit gate types (mat[2:,2:]
296
+ # of each gate's full 4x4 form β€” same values _apply_gate_multi's
297
+ # `U = mat[2:, 2:]` extracted from GATES/PARAMETRIC_GATES).
298
+ # 20=CX->X, 21=CZ->Z, 22=CP->P(theta), 24=CY->Y, 25=CRZ->RZ(theta).
299
+ two_q_idx = jnp.where(g_id == 20, 0,
300
+ jnp.where(g_id == 21, 1,
301
+ jnp.where(g_id == 22, 2,
302
+ jnp.where(g_id == 24, 3, 4))))
303
+ U = jax.lax.switch(
304
+ two_q_idx,
305
+ [
306
+ lambda _: jnp.array([[0.0 + 0j, 1.0 + 0j], [1.0 + 0j, 0.0 + 0j]], dtype=dtype),
307
+ lambda _: jnp.array([[1.0 + 0j, 0.0 + 0j], [0.0 + 0j, -1.0 + 0j]], dtype=dtype),
308
+ lambda _: jnp.array([[1.0 + 0j, 0.0 + 0j], [0.0 + 0j, exp_pos]], dtype=dtype),
309
+ lambda _: jnp.array([[0.0 + 0j, -1j], [1j, 0.0 + 0j]], dtype=dtype),
310
+ lambda _: jnp.array([[exp_neg_half, 0.0 + 0j], [0.0 + 0j, exp_pos_half]], dtype=dtype),
311
+ ],
312
+ operand=None,
313
+ )
314
+ g00, g01, g10, g11 = g_1q[0, 0], g_1q[0, 1], g_1q[1, 0], g_1q[1, 1]
315
+ u00, u01, u10, u11 = U[0, 0], U[0, 1], U[1, 0], U[1, 1]
316
+
317
+ # ── case 1: 1-qubit gate, LOCAL qubit (q1 >= m) ──────────────
318
+ # Same do_1q amplitude-pair math as beast-mode, applied to every
319
+ # chunk row in parallel (gather along axis 1, broadcasts over
320
+ # axis 0 for free).
321
+ def case_1q_local(_c):
322
+ local_phys = (k - 1) - (q1 - m)
323
+ stride = jnp.int32(1) << local_phys
324
+ idx = jnp.arange(chunk_dim, dtype=jnp.int32)
325
+ idx_pair = idx ^ stride
326
+ mask0 = (idx & stride) == 0
327
+ amp_pair = _c[:, idx_pair]
328
+ new0 = g00 * _c + g01 * amp_pair
329
+ new1 = g10 * amp_pair + g11 * _c
330
+ return jnp.where(mask0[None, :], new0, new1)
331
+
332
+ # ── case 2: 1-qubit gate, CHUNK-SELECT qubit (q1 < m) ────────
333
+ # Same math, one level up: each "amplitude" is a whole
334
+ # (chunk_dim,)-shaped row, mixed pairwise across axis 0.
335
+ def case_1q_chunk(_c):
336
+ stride = jnp.int32(1) << (m - 1 - q1)
337
+ idxc = jnp.arange(num_chunks, dtype=jnp.int32)
338
+ idxc_pair = idxc ^ stride
339
+ mask0 = (idxc & stride) == 0
340
+ amp_pair = _c[idxc_pair]
341
+ new0 = g00 * _c + g01 * amp_pair
342
+ new1 = g10 * amp_pair + g11 * _c
343
+ return jnp.where(mask0[:, None], new0, new1)
344
+
345
+ # ── case 3: 2-qubit, ctrl AND tgt both LOCAL ─────────────────
346
+ def case_2q_local_local(_c):
347
+ ctrl_phys = (k - 1) - (q1 - m)
348
+ tgt_phys = (k - 1) - (q2 - m)
349
+ idx = jnp.arange(chunk_dim, dtype=jnp.int32)
350
+ ctrl_bit = (idx & (jnp.int32(1) << ctrl_phys)) != 0
351
+ tgt_bit = (idx & (jnp.int32(1) << tgt_phys)) != 0
352
+ partner = idx ^ (jnp.int32(1) << tgt_phys)
353
+ amp_partner = _c[:, partner]
354
+ new0 = u00 * _c + u01 * amp_partner
355
+ new1 = u10 * amp_partner + u11 * _c
356
+ after = jnp.where(tgt_bit[None, :], new1, new0)
357
+ return jnp.where(ctrl_bit[None, :], after, _c)
358
+
359
+ # ── case 4: ctrl CHUNK-SELECT, tgt LOCAL ─────────────────────
360
+ # Whole chunks where the chunk-index's ctrl bit is set get U
361
+ # applied as a local 1-qubit gate; the rest are untouched.
362
+ def case_2q_ctrl_chunk_tgt_local(_c):
363
+ ctrl_stride = jnp.int32(1) << (m - 1 - q1)
364
+ idxc = jnp.arange(num_chunks, dtype=jnp.int32)
365
+ ctrl_set = (idxc & ctrl_stride) != 0
366
+ tgt_phys = (k - 1) - (q2 - m)
367
+ idxl = jnp.arange(chunk_dim, dtype=jnp.int32)
368
+ tgt_bit = (idxl & (jnp.int32(1) << tgt_phys)) != 0
369
+ partner = idxl ^ (jnp.int32(1) << tgt_phys)
370
+ amp_partner = _c[:, partner]
371
+ new0 = u00 * _c + u01 * amp_partner
372
+ new1 = u10 * amp_partner + u11 * _c
373
+ after = jnp.where(tgt_bit[None, :], new1, new0)
374
+ return jnp.where(ctrl_set[:, None], after, _c)
375
+
376
+ # ── case 5: ctrl LOCAL, tgt CHUNK-SELECT ─────────────────────
377
+ # Pairs of chunks get mixed, but ONLY where the local ctrl bit
378
+ # (same position in every chunk) is set β€” an elementwise mask.
379
+ def case_2q_ctrl_local_tgt_chunk(_c):
380
+ ctrl_phys = (k - 1) - (q1 - m)
381
+ idxl = jnp.arange(chunk_dim, dtype=jnp.int32)
382
+ ctrl_bit = (idxl & (jnp.int32(1) << ctrl_phys)) != 0
383
+ tgt_stride = jnp.int32(1) << (m - 1 - q2)
384
+ idxc = jnp.arange(num_chunks, dtype=jnp.int32)
385
+ idxc_pair = idxc ^ tgt_stride
386
+ is_c0 = (idxc & tgt_stride) == 0
387
+ amp_pair = _c[idxc_pair]
388
+ new_c0 = u00 * _c + u01 * amp_pair
389
+ new_c1 = u10 * amp_pair + u11 * _c
390
+ after = jnp.where(is_c0[:, None], new_c0, new_c1)
391
+ return jnp.where(ctrl_bit[None, :], after, _c)
392
+
393
+ # ── case 6: ctrl AND tgt both CHUNK-SELECT ───────────────────
394
+ def case_2q_both_chunk(_c):
395
+ ctrl_stride = jnp.int32(1) << (m - 1 - q1)
396
+ tgt_stride = jnp.int32(1) << (m - 1 - q2)
397
+ idxc = jnp.arange(num_chunks, dtype=jnp.int32)
398
+ ctrl_set = (idxc & ctrl_stride) != 0
399
+ idxc_pair = idxc ^ tgt_stride
400
+ is_c0 = (idxc & tgt_stride) == 0
401
+ amp_pair = _c[idxc_pair]
402
+ new_c0 = u00 * _c + u01 * amp_pair
403
+ new_c1 = u10 * amp_pair + u11 * _c
404
+ after = jnp.where(is_c0[:, None], new_c0, new_c1)
405
+ return jnp.where(ctrl_set[:, None], after, _c)
406
+
407
+ is_2q = g_id >= 20
408
+ q1_chunk = q1 < m
409
+ q2_chunk = q2 < m
410
+
411
+ result_2q = jnp.where(
412
+ q1_chunk & q2_chunk, case_2q_both_chunk(chunks),
413
+ jnp.where(q1_chunk & (~q2_chunk), case_2q_ctrl_chunk_tgt_local(chunks),
414
+ jnp.where((~q1_chunk) & q2_chunk, case_2q_ctrl_local_tgt_chunk(chunks),
415
+ case_2q_local_local(chunks))))
416
+ result_1q = jnp.where(q1_chunk, case_1q_chunk(chunks), case_1q_local(chunks))
417
+
418
+ new_chunks = jnp.where(is_2q, result_2q, result_1q)
419
+ return new_chunks.astype(dtype), None
420
+
421
+ return step
422
+
423
+
424
+ # ─────────────────────────────────────────────────────────────────────
425
+ # Distributed (multi-device) variant β€” one physical chunk per device
426
+ # ─────────────────────────────────────────────────────────────────────
427
+
428
+ def _build_distributed_chunk_step(num_chunks: int, m: int, k: int, axis_name: str):
429
+ """Same 6-case formula set as _build_multi_chunk_step, but each
430
+ device holds exactly ONE chunk row (chunk_dim,) instead of the
431
+ whole (num_chunks, chunk_dim) stack living on one device/process β€”
432
+ issue #1: distribute chunks across a device mesh (multi-GPU/
433
+ multi-host), not just multi-chunk within one process's RAM.
434
+
435
+ The stacked-array formulation's "mix pairs of rows across axis 0"
436
+ (cases 2/5/6, touching a chunk-select qubit) becomes real
437
+ point-to-point network communication here: jax.lax.ppermute,
438
+ keyed on the fixed XOR-stride pairing between chunk indices β€” the
439
+ textbook pairwise-exchange communication pattern used by
440
+ distributed statevector simulators (each device sends its local
441
+ row to its stride-partner device and receives the partner's row
442
+ back). Cases 1/3/4 need NO communication at all: case 1/3 are
443
+ purely local (both qubits live inside this device's own chunk_dim
444
+ index space), and case 4 (ctrl chunk-select, tgt local) is a
445
+ decision every device can make on its OWN chunk index alone
446
+ (whether ITS id has the ctrl bit set) β€” no data from any other
447
+ device is needed to decide or to apply the local tgt gate.
448
+
449
+ ppermute's `perm` argument is a communication topology and must be
450
+ STATIC (known at trace time) β€” it cannot be built from q1/q2,
451
+ which are traced values read from the scanned circuit array. Since
452
+ q1/q2 only ever range over the m possible chunk-select qubit
453
+ indices [0, m), every possible stride is enumerated as its own
454
+ statically-built ppermute call, and jax.lax.switch (traced
455
+ unconditionally, same "trace every branch" pattern used
456
+ throughout this codebase) picks the right one at runtime β€” plus
457
+ one extra identity branch for "no chunk-select qubit involved,
458
+ no communication needed" (verified below to be exactly cases
459
+ 1/3/4, never 2/5/6)."""
460
+ chunk_dim = 1 << k
461
+
462
+ def step(local_row, operation):
463
+ g_id = operation[0].astype(jnp.int32)
464
+ q1 = operation[1].astype(jnp.int32)
465
+ q2 = operation[2].astype(jnp.int32)
466
+ param = operation[3]
467
+ dtype = local_row.dtype
468
+
469
+ my_id = jax.lax.axis_index(axis_name).astype(jnp.int32)
470
+
471
+ inv2 = jnp.asarray(1.0 / jnp.sqrt(2.0), dtype=dtype)
472
+ half_p = param * jnp.float64(0.5)
473
+ cos_p = jnp.cos(half_p).astype(dtype)
474
+ sin_p = jnp.sin(half_p).astype(dtype)
475
+ exp_pos = jnp.exp(1j * param).astype(dtype)
476
+ exp_ph4 = jnp.exp(1j * jnp.pi / 4.0).astype(dtype)
477
+ exp_mh4 = jnp.exp(-1j * jnp.pi / 4.0).astype(dtype)
478
+ exp_pos_half = jnp.exp(1j * half_p).astype(dtype)
479
+ exp_neg_half = jnp.exp(-1j * half_p).astype(dtype)
480
+
481
+ safe_gid = jnp.clip(g_id, 0, 13)
482
+ g_1q = jax.lax.switch(
483
+ safe_gid,
484
+ [
485
+ lambda _: jnp.eye(2, dtype=dtype),
486
+ lambda _: jnp.array([[inv2, inv2], [inv2, -inv2]], dtype=dtype),
487
+ lambda _: jnp.array([[0.0 + 0j, 1.0 + 0j], [1.0 + 0j, 0.0 + 0j]], dtype=dtype),
488
+ lambda _: jnp.array([[0.0 + 0j, -1j], [1j, 0.0 + 0j]], dtype=dtype),
489
+ lambda _: jnp.array([[1.0 + 0j, 0.0 + 0j], [0.0 + 0j, -1.0 + 0j]], dtype=dtype),
490
+ lambda _: jnp.array([[1.0 + 0j, 0.0 + 0j], [0.0 + 0j, 1j]], dtype=dtype),
491
+ lambda _: jnp.array([[1.0 + 0j, 0.0 + 0j], [0.0 + 0j, -1j]], dtype=dtype),
492
+ lambda _: jnp.array([[1.0 + 0j, 0.0 + 0j], [0.0 + 0j, exp_ph4]], dtype=dtype),
493
+ lambda _: jnp.array([[1.0 + 0j, 0.0 + 0j], [0.0 + 0j, exp_mh4]], dtype=dtype),
494
+ lambda _: jnp.array([[cos_p, -1j * sin_p], [-1j * sin_p, cos_p]], dtype=dtype),
495
+ lambda _: jnp.array([[cos_p, -sin_p], [sin_p, cos_p]], dtype=dtype),
496
+ lambda _: jnp.array([[jnp.exp(-1j * half_p), 0.0 + 0j], [0.0 + 0j, jnp.exp(1j * half_p)]], dtype=dtype),
497
+ lambda _: jnp.array([[1.0 + 0j, 0.0 + 0j], [0.0 + 0j, exp_pos]], dtype=dtype),
498
+ lambda _: jnp.array([[0.5 + 0.5j, 0.5 - 0.5j], [0.5 - 0.5j, 0.5 + 0.5j]], dtype=dtype),
499
+ ],
500
+ operand=None,
501
+ )
502
+
503
+ two_q_idx = jnp.where(g_id == 20, 0,
504
+ jnp.where(g_id == 21, 1,
505
+ jnp.where(g_id == 22, 2,
506
+ jnp.where(g_id == 24, 3, 4))))
507
+ U = jax.lax.switch(
508
+ two_q_idx,
509
+ [
510
+ lambda _: jnp.array([[0.0 + 0j, 1.0 + 0j], [1.0 + 0j, 0.0 + 0j]], dtype=dtype),
511
+ lambda _: jnp.array([[1.0 + 0j, 0.0 + 0j], [0.0 + 0j, -1.0 + 0j]], dtype=dtype),
512
+ lambda _: jnp.array([[1.0 + 0j, 0.0 + 0j], [0.0 + 0j, exp_pos]], dtype=dtype),
513
+ lambda _: jnp.array([[0.0 + 0j, -1j], [1j, 0.0 + 0j]], dtype=dtype),
514
+ lambda _: jnp.array([[exp_neg_half, 0.0 + 0j], [0.0 + 0j, exp_pos_half]], dtype=dtype),
515
+ ],
516
+ operand=None,
517
+ )
518
+ g00, g01, g10, g11 = g_1q[0, 0], g_1q[0, 1], g_1q[1, 0], g_1q[1, 1]
519
+ u00, u01, u10, u11 = U[0, 0], U[0, 1], U[1, 0], U[1, 1]
520
+
521
+ is_2q = g_id >= 20
522
+ q1_chunk = q1 < m
523
+ q2_chunk = q2 < m
524
+
525
+ # ── single point-to-point exchange, done once per step ──────
526
+ # comm_qubit selects which stride to ppermute on: q2 (tgt) for
527
+ # any 2-qubit gate with a chunk-select target (cases 5 and 6),
528
+ # q1 for a 1-qubit gate on a chunk-select qubit (case 2),
529
+ # sentinel `m` (-> identity, no network traffic) for cases
530
+ # 1/3/4, which never need another device's data.
531
+ needs_comm_2q = is_2q & q2_chunk
532
+ needs_comm_1q = (~is_2q) & q1_chunk
533
+ comm_qubit = jnp.where(needs_comm_2q, q2, jnp.where(needs_comm_1q, q1, m))
534
+ safe_comm_idx = jnp.clip(comm_qubit, 0, m)
535
+
536
+ # NOTE: `_perm` MUST be bound as a default-argument value here
537
+ # (evaluated eagerly, once, at lambda-creation time inside this
538
+ # loop) rather than referencing `q`/`m` freely inside the
539
+ # lambda body -- a free reference would be looked up at CALL
540
+ # time via Python's normal late-binding closure semantics, by
541
+ # which point the loop variable `q` has already reached its
542
+ # final value (m-1) for every branch, silently making every
543
+ # ppermute use the LAST qubit's stride regardless of which
544
+ # branch was actually selected. Caught by exactly that
545
+ # symptom: only the branch for q == m-1 gave correct results.
546
+ ppermute_branches = [
547
+ (lambda _row, _perm=[(i, i ^ (1 << (m - 1 - q))) for i in range(num_chunks)]:
548
+ jax.lax.ppermute(_row, axis_name, perm=_perm))
549
+ for q in range(m)
550
+ ] + [lambda _row: _row] # identity: no chunk-select qubit involved
551
+ paired_row = jax.lax.switch(safe_comm_idx, ppermute_branches, local_row)
552
+
553
+ # ── case 1: 1-qubit, LOCAL qubit (q1 >= m) β€” no comm ─────────
554
+ def case_1q_local(_row):
555
+ local_phys = (k - 1) - (q1 - m)
556
+ stride = jnp.int32(1) << local_phys
557
+ idx = jnp.arange(chunk_dim, dtype=jnp.int32)
558
+ idx_pair = idx ^ stride
559
+ mask0 = (idx & stride) == 0
560
+ amp_pair = _row[idx_pair]
561
+ new0 = g00 * _row + g01 * amp_pair
562
+ new1 = g10 * amp_pair + g11 * _row
563
+ return jnp.where(mask0, new0, new1)
564
+
565
+ # ── case 2: 1-qubit, CHUNK-SELECT qubit (q1 < m) ─────────────
566
+ # paired_row already fetched via ppermute above (comm_qubit=q1).
567
+ def case_1q_chunk(_row):
568
+ stride = jnp.int32(1) << (m - 1 - q1)
569
+ mask0 = (my_id & stride) == 0
570
+ new0 = g00 * _row + g01 * paired_row
571
+ new1 = g10 * paired_row + g11 * _row
572
+ return jnp.where(mask0, new0, new1)
573
+
574
+ # ── case 3: 2-qubit, ctrl AND tgt both LOCAL β€” no comm ───────
575
+ def case_2q_local_local(_row):
576
+ ctrl_phys = (k - 1) - (q1 - m)
577
+ tgt_phys = (k - 1) - (q2 - m)
578
+ idx = jnp.arange(chunk_dim, dtype=jnp.int32)
579
+ ctrl_bit = (idx & (jnp.int32(1) << ctrl_phys)) != 0
580
+ partner = idx ^ (jnp.int32(1) << tgt_phys)
581
+ amp_partner = _row[partner]
582
+ new0 = u00 * _row + u01 * amp_partner
583
+ new1 = u10 * amp_partner + u11 * _row
584
+ tgt_bit = (idx & (jnp.int32(1) << tgt_phys)) != 0
585
+ after = jnp.where(tgt_bit, new1, new0)
586
+ return jnp.where(ctrl_bit, after, _row)
587
+
588
+ # ── case 4: ctrl CHUNK-SELECT, tgt LOCAL β€” no comm needed: ─
589
+ # every device decides purely from its OWN chunk index (my_id)
590
+ # whether the control bit is set, and if so applies U locally.
591
+ def case_2q_ctrl_chunk_tgt_local(_row):
592
+ ctrl_stride = jnp.int32(1) << (m - 1 - q1)
593
+ ctrl_set = (my_id & ctrl_stride) != 0
594
+ tgt_phys = (k - 1) - (q2 - m)
595
+ idx = jnp.arange(chunk_dim, dtype=jnp.int32)
596
+ tgt_bit = (idx & (jnp.int32(1) << tgt_phys)) != 0
597
+ partner = idx ^ (jnp.int32(1) << tgt_phys)
598
+ amp_partner = _row[partner]
599
+ new0 = u00 * _row + u01 * amp_partner
600
+ new1 = u10 * amp_partner + u11 * _row
601
+ after = jnp.where(tgt_bit, new1, new0)
602
+ return jnp.where(ctrl_set, after, _row)
603
+
604
+ # ── case 5: ctrl LOCAL, tgt CHUNK-SELECT ──────────────────────
605
+ # paired_row already fetched via ppermute above (comm_qubit=q2,
606
+ # keyed on tgt's stride). is_c0 is a per-device scalar decision
607
+ # (which side of the tgt pairing this device is on); ctrl_bit
608
+ # is a per-element mask within the row (elementwise, local).
609
+ def case_2q_ctrl_local_tgt_chunk(_row):
610
+ ctrl_phys = (k - 1) - (q1 - m)
611
+ idx = jnp.arange(chunk_dim, dtype=jnp.int32)
612
+ ctrl_bit = (idx & (jnp.int32(1) << ctrl_phys)) != 0
613
+ tgt_stride = jnp.int32(1) << (m - 1 - q2)
614
+ is_c0 = (my_id & tgt_stride) == 0
615
+ new_c0 = u00 * _row + u01 * paired_row
616
+ new_c1 = u10 * paired_row + u11 * _row
617
+ after = jnp.where(is_c0, new_c0, new_c1)
618
+ return jnp.where(ctrl_bit, after, _row)
619
+
620
+ # ── case 6: ctrl AND tgt both CHUNK-SELECT ────────────────────
621
+ # paired_row via ppermute keyed on tgt's stride (comm_qubit=q2);
622
+ # ctrl_set and is_c0 are both per-device scalars (this device's
623
+ # own chunk index bits) β€” no per-element masking needed at all.
624
+ def case_2q_both_chunk(_row):
625
+ ctrl_stride = jnp.int32(1) << (m - 1 - q1)
626
+ ctrl_set = (my_id & ctrl_stride) != 0
627
+ tgt_stride = jnp.int32(1) << (m - 1 - q2)
628
+ is_c0 = (my_id & tgt_stride) == 0
629
+ new_c0 = u00 * _row + u01 * paired_row
630
+ new_c1 = u10 * paired_row + u11 * _row
631
+ after = jnp.where(is_c0, new_c0, new_c1)
632
+ return jnp.where(ctrl_set, after, _row)
633
+
634
+ result_2q = jnp.where(
635
+ q1_chunk & q2_chunk, case_2q_both_chunk(local_row),
636
+ jnp.where(q1_chunk & (~q2_chunk), case_2q_ctrl_chunk_tgt_local(local_row),
637
+ jnp.where((~q1_chunk) & q2_chunk, case_2q_ctrl_local_tgt_chunk(local_row),
638
+ case_2q_local_local(local_row))))
639
+ result_1q = jnp.where(q1_chunk, case_1q_chunk(local_row), case_1q_local(local_row))
640
+
641
+ new_row = jnp.where(is_2q, result_2q, result_1q)
642
+ return new_row.astype(dtype), None
643
+
644
+ return step
645
+
646
+
647
+ def _build_distributed_chunk_runner(num_chunks: int, m: int, k: int):
648
+ """shard_map-wrapped runner: one chunk row per physical JAX device.
649
+ Requires jax.device_count() >= num_chunks (v1 scope: exactly one
650
+ chunk per device, the literal reading of issue #1 -- "distribuire
651
+ i chunk su piΓΉ device"; a hybrid scheme with several chunks per
652
+ device is a possible future refinement, not attempted here).
653
+
654
+ compiled_ops (the small [g_id, q1, q2, param] sequence, identical
655
+ on every device) is replicated, not sharded -- P(None, None).
656
+ local_row is sharded along axis 0 of the (num_chunks, chunk_dim)
657
+ logical array, one (chunk_dim,) row per device -- P(axis_name,
658
+ None) on input/output, so each device's shard is that one row."""
659
+ from jax.sharding import Mesh, PartitionSpec as P
660
+
661
+ axis_name = 'chunks'
662
+ step = _build_distributed_chunk_step(num_chunks, m, k, axis_name)
663
+
664
+ devices = np.array(jax.devices()[:num_chunks])
665
+ mesh = Mesh(devices, axis_names=(axis_name,))
666
+
667
+ def run_local(local_shard, compiled_ops):
668
+ # shard_map keeps the sharded axis in the local shape (size
669
+ # num_chunks/mesh_size along axis 0 -- 1 in this v1 one-
670
+ # chunk-per-device scope), it doesn't squeeze it away: a
671
+ # (num_chunks, chunk_dim) input shards to (1, chunk_dim) per
672
+ # device here, not (chunk_dim,). `step` itself works on a
673
+ # clean (chunk_dim,) row -- squeeze going in, restore going out.
674
+ local_row = local_shard[0]
675
+ final_row, _ = jax.lax.scan(step, local_row, compiled_ops)
676
+ return final_row[None, :]
677
+
678
+ sharded_run = jax.shard_map(
679
+ run_local,
680
+ mesh=mesh,
681
+ in_specs=(P(axis_name, None), P(None, None)),
682
+ out_specs=P(axis_name, None),
683
+ check_vma=False,
684
+ )
685
+ return jax.jit(sharded_run), mesh
686
+
687
+
688
+ def _build_multi_chunk_runner(num_chunks: int, m: int, k: int):
689
+ """jax.jit-compiled (chunks, compiled_ops) -> final_chunks, closed
690
+ over the static per-Chunk-instance geometry (num_chunks, m, k don't
691
+ change across calls on the same instance)."""
692
+ step = _build_multi_chunk_step(num_chunks, m, k)
693
+
694
+ @jax.jit
695
+ def run(chunks, compiled_ops):
696
+ final, _ = jax.lax.scan(step, chunks, compiled_ops)
697
+ return final
698
+
699
+ return run
700
+
701
+
702
+ def _compile_multi_chunk_ops(circuit: List) -> "jnp.ndarray":
703
+ """Structural + GATE_IDS compilation shared by the multi-chunk JIT
704
+ path β€” same [g_id, q1, q2, param] row format as beast-mode's own
705
+ compiled ops, built via GATE_IDS instead of the old _resolve_gate's
706
+ GATES/PARAMETRIC_GATES lookup. This finally aligns multi-chunk's
707
+ gate coverage with beast-mode's (both silently skip a gate name not
708
+ in GATE_IDS β€” same known, tracked behavior, see issue #4 β€” instead
709
+ of the old _resolve_gate's NotImplementedError for e.g. ecr/iswap)."""
710
+ target = QuantumTranspiler.transpile(circuit)
711
+ rows = []
712
+ for cmd in target:
713
+ name = cmd[0].lower() if isinstance(cmd[0], str) else str(cmd[0]).lower()
714
+ if name not in GATE_IDS:
715
+ continue
716
+ g_id = float(GATE_IDS[name])
717
+ args = cmd[1:]
718
+ if name in ('cx', 'cz', 'cp', 'cphase', 'cy', 'crz'):
719
+ q1, q2 = float(args[0]), float(args[1])
720
+ param = float(args[2]) if len(args) > 2 else 0.0
721
+ rows.append([g_id, q1, q2, param])
722
+ elif args:
723
+ q1 = float(args[0])
724
+ param = float(args[1]) if len(args) > 1 else 0.0
725
+ rows.append([g_id, q1, 0.0, param])
726
+ if not rows:
727
+ return jnp.empty((0, 4), dtype=jnp.float64)
728
+ return jnp.array(rows, dtype=jnp.float64)
729
+
730
+
731
+ # ─────────────────────────────────────────────────────────────────────────────
732
+ # CircuitChunker
733
+ # ─────────────────────────────────────────────────────────────────────────────
734
+
735
+ class CircuitChunker:
736
+ """
737
+ Transpile a circuit once, then execute it in fixed-size gate-slices so
738
+ XLA sees the same trace shape on every compilation.
739
+
740
+ A SafeMemoryGuard is checked **before every slice** β€” if RAM drops below
741
+ 15% the current slice is aborted with MemoryPressureError before JAX
742
+ attempts the allocation.
743
+
744
+ Parameters
745
+ ----------
746
+ simulator_instance : DenseSVSimulator
747
+ Physical simulator (sized to safe_qubits, not logical n_qubits).
748
+ memory_threshold : float
749
+ Passed to SafeMemoryGuard. Default 0.15 (15%).
750
+ """
751
+
752
+ def __init__(
753
+ self,
754
+ simulator_instance: Optional[DenseSVSimulator] = None,
755
+ memory_threshold: float = 0.15,
756
+ ):
757
+ self.sim = simulator_instance
758
+ self._guard = SafeMemoryGuard(threshold_pct=memory_threshold)
759
+
760
+ def split_circuit(self, circuit: List, chunk_size: int = 500) -> None:
761
+ """
762
+ Execute *circuit* in slices of *chunk_size* gates.
763
+
764
+ Raises
765
+ ------
766
+ RuntimeError if no simulator instance is attached.
767
+ MemoryPressureError if RAM drops below threshold before a slice.
768
+ """
769
+ if self.sim is None:
770
+ raise RuntimeError(
771
+ "CircuitChunker: no simulator instance attached. "
772
+ "Pass simulator_instance= at construction or assign .sim."
773
+ )
774
+
775
+ target: List = QuantumTranspiler.transpile(circuit)
776
+ n_slices = (len(target) + chunk_size - 1) // chunk_size
777
+
778
+ for idx, i in enumerate(range(0, len(target), chunk_size)):
779
+ # ── Anti-OOM check before every slice ───────────────────────────
780
+ self._guard.check(f"slice {idx + 1}/{n_slices}")
781
+ self.sim.run_circuit_jit_beast_mode(target[i : i + chunk_size])
782
+
783
+
784
+ # ─────────────────────────────────────────────────────────────────────────────
785
+ # Chunk (chunk2 / Chunk2Incrociato)
786
+ # ─────────────────────────────────────────────────────────────────────────────
787
+
788
+ class Chunk:
789
+ """
790
+ Anti-OOM wrapper for large-qubit simulation.
791
+
792
+ Does NOT subclass DenseSVSimulator directly β€” the parent __init__ allocates
793
+ 2**n_qubits elements immediately (17 GB for 30 qubits).
794
+
795
+ For n_qubits <= chunk_size_bits (the RAM-safe budget): a single inner
796
+ simulator is allocated and the logical qubit count is stored separately.
797
+
798
+ For n_qubits > chunk_size_bits: num_chunks separate chunk_size_bits-qubit
799
+ simulators are held in RAM simultaneously (see _dispatch_multi) β€” no
800
+ disk/memmap paging, so this only covers a *moderate* overflow beyond the
801
+ safe budget (as many chunks as actually fit in RAM at once, checked
802
+ up front via SafeMemoryGuard.check_allocation before anything is
803
+ allocated). Benchmark attributes (num_chunks, chunk_size_bits, dtype)
804
+ are forwarded transparently from the embedded MemoryChunker.
805
+
806
+ A SafeMemoryGuard fires before any simulator is instantiated
807
+ (pre-allocation check) and is also embedded in CircuitChunker for
808
+ per-slice protection during execution (n_qubits <= chunk_size_bits path).
809
+
810
+ Parameters
811
+ ----------
812
+ n_qubits : logical qubit count of the target circuit
813
+ chunk_size_gates : gate-slice size for JIT compilation (default 500)
814
+ memory_threshold : free-RAM fraction below which execution is blocked
815
+ (default 0.15 = 15%)
816
+ use_gpu : forwarded to DenseSVSimulator
817
+ use_float32 : forwarded to DenseSVSimulator
818
+ """
819
+
820
+ def __init__(
821
+ self,
822
+ n_qubits: int,
823
+ chunk_size_gates: int = 500,
824
+ memory_threshold: float = 0.15,
825
+ use_gpu: bool = False,
826
+ use_float32: bool = False,
827
+ ):
828
+ # 1. Geometry β€” purely RAM-based, no JAX allocation yet
829
+ self._mem_chunker = MemoryChunker(n_qubits)
830
+ self._guard = SafeMemoryGuard(threshold_pct=memory_threshold)
831
+
832
+ # 2. Logical qubit count (for circuit parsing)
833
+ self.n = n_qubits
834
+ self.chunk_size_gates = chunk_size_gates
835
+ self._m = n_qubits - self._mem_chunker.chunk_size_bits # chunk-select qubit count (0 if num_chunks==1)
836
+
837
+ if self._mem_chunker.num_chunks == 1:
838
+ # 3a. Pre-allocation RAM check β€” block here rather than inside JAX
839
+ safe_q = min(n_qubits, self._mem_chunker.chunk_size_bits)
840
+ self._guard.check(f"Chunk.__init__ β€” allocating {safe_q}-qubit simulator")
841
+
842
+ # 4a. Physical simulator sized to what RAM can actually hold
843
+ self._inner_sim = DenseSVSimulator(
844
+ safe_q,
845
+ use_gpu=use_gpu,
846
+ use_float32=use_float32,
847
+ )
848
+ self._chunk_sims = None
849
+ self._multi_chunk_runner = None
850
+
851
+ # 5a. Circuit chunker wired to the physical simulator, with same threshold
852
+ self._circuit_chunker = CircuitChunker(
853
+ simulator_instance=self._inner_sim,
854
+ memory_threshold=memory_threshold,
855
+ )
856
+ else:
857
+ # 3b. Sized pre-allocation check: num_chunks chunk-sized simulators
858
+ # held in RAM at once, plus ~2 chunks of headroom for the temporary
859
+ # arrays the cross-chunk gate-mixing math allocates at its peak.
860
+ num_chunks = self._mem_chunker.num_chunks
861
+ per_chunk_mb = self._mem_chunker.memory_mb()
862
+ required_mb = (num_chunks + 2) * per_chunk_mb
863
+ self._guard.check_allocation(
864
+ required_mb,
865
+ f"Chunk.__init__ β€” allocating {num_chunks} chunks of "
866
+ f"{self._mem_chunker.chunk_size_bits} qubits each",
867
+ )
868
+
869
+ # 4b. num_chunks independent chunk-sized simulators. Each one's own
870
+ # __init__ resets it to |0...0>: only chunk 0 should carry the
871
+ # amplitude-1 seed for the LOGICAL |0...0>, the rest must start
872
+ # at all-zero (direct .sv assignment β€” set_state/set_initial_state
873
+ # reject zero-norm vectors by design).
874
+ self._chunk_sims = [
875
+ DenseSVSimulator(self._mem_chunker.chunk_size_bits, use_gpu=use_gpu, use_float32=use_float32)
876
+ for _ in range(num_chunks)
877
+ ]
878
+ for sim in self._chunk_sims[1:]:
879
+ sim.sv = sim.xp.zeros(self._mem_chunker.chunk_dim, dtype=sim.dtype)
880
+
881
+ self._inner_sim = None
882
+ self._circuit_chunker = None
883
+
884
+ # 6b. JIT runner for the multi-chunk dispatch β€” built once here
885
+ # since num_chunks/m/chunk_size_bits are fixed for this
886
+ # instance's whole lifetime, reused by every run_chunk() call.
887
+ self._multi_chunk_runner = _build_multi_chunk_runner(
888
+ num_chunks, self._m, self._mem_chunker.chunk_size_bits)
889
+
890
+ # 7b. Distributed (multi-device) runner β€” built lazily on first
891
+ # run_chunk_distributed() call, not here: it requires
892
+ # jax.device_count() >= num_chunks, which most single-process
893
+ # uses of Chunk will never need or satisfy.
894
+ self._distributed_runner = None
895
+ self._distributed_mesh = None
896
+
897
+ # ── Benchmark-facing attribute forwarding ────────────────────────────────
898
+
899
+ @property
900
+ def num_chunks(self) -> int:
901
+ return self._mem_chunker.num_chunks
902
+
903
+ @property
904
+ def chunk_size_bits(self) -> int:
905
+ return self._mem_chunker.chunk_size_bits
906
+
907
+ @property
908
+ def chunk_dim(self) -> int:
909
+ return self._mem_chunker.chunk_dim
910
+
911
+ @property
912
+ def dtype(self):
913
+ return self._mem_chunker.dtype
914
+
915
+ @property
916
+ def memory_geometry(self) -> MemoryChunker:
917
+ return self._mem_chunker
918
+
919
+ # ── Simulator-facing forwarding ──────────────────────────────────────────
920
+
921
+ @property
922
+ def sv(self):
923
+ """Current statevector. For num_chunks==1, the physical (chunk-sized)
924
+ simulator's own array. For num_chunks>1, the chunks concatenated in
925
+ ascending order β€” valid because of the MSB-first correspondence
926
+ between chunk index and the top `_m` logical qubits (see
927
+ _dispatch_multi's docstring)."""
928
+ if self._chunk_sims is None:
929
+ return self._inner_sim.sv
930
+ xp = self._chunk_sims[0].xp
931
+ return xp.concatenate([sim.sv for sim in self._chunk_sims])
932
+
933
+ @sv.setter
934
+ def sv(self, value):
935
+ """Accepts a full-length (2**n,) statevector (e.g. the output of
936
+ NoiseModel.apply_to_sv called on `.sv`) and writes it back through
937
+ to the physical storage -- the inner simulator directly for
938
+ num_chunks==1, or split back into per-chunk slices (same ascending
939
+ concatenation order as the getter) for num_chunks>1."""
940
+ if self._chunk_sims is None:
941
+ self._inner_sim.sv = value
942
+ return
943
+ chunk_dim = self._mem_chunker.chunk_dim
944
+ xp = self._chunk_sims[0].xp
945
+ value = xp.asarray(value)
946
+ for i, sim in enumerate(self._chunk_sims):
947
+ sim.sv = value[i * chunk_dim:(i + 1) * chunk_dim]
948
+
949
+ def memory_mb(self) -> float:
950
+ """RAM used by the physical statevector(s) in MB."""
951
+ if self._chunk_sims is None:
952
+ return self._inner_sim.memory_mb()
953
+ return sum(sim.memory_mb() for sim in self._chunk_sims)
954
+
955
+ def get_probabilities(self):
956
+ """|amplitude|^2 for every basis state.
957
+
958
+ num_chunks==1: forwards to the inner DenseSVSimulator for parity
959
+ with its own get_probabilities().
960
+
961
+ num_chunks>1: concatenates the RAW statevectors first and normalizes
962
+ ONCE over the full array β€” NOT each chunk's own get_probabilities()
963
+ (that would independently renormalize each chunk's partial mass to
964
+ 1, summing to num_chunks overall and destroying the relative
965
+ weighting between chunks)."""
966
+ if self._chunk_sims is None:
967
+ return self._inner_sim.get_probabilities()
968
+ full_sv = np.concatenate([np.array(sim.sv) for sim in self._chunk_sims])
969
+ probs = np.abs(full_sv) ** 2
970
+ probs = np.clip(probs, 0.0, 1.0)
971
+ total = probs.sum()
972
+ if total > 1e-12:
973
+ probs /= total
974
+ return probs
975
+
976
+ def get_statevector(self):
977
+ """Full complex statevector, num_qubits logical qubits long
978
+ (2**n elements). num_chunks==1: forwards to the inner
979
+ DenseSVSimulator. num_chunks>1: raw chunks concatenated in order
980
+ (see `sv` property)."""
981
+ if self._chunk_sims is None:
982
+ return self._inner_sim.get_statevector()
983
+ return np.concatenate([np.array(sim.sv, dtype=sim.dtype) for sim in self._chunk_sims])
984
+
985
+ # ── Multi-chunk gate dispatch (num_chunks > 1) ───────────────────────────
986
+
987
+ def _dispatch_multi(self, circuit: List) -> None:
988
+ """Executes *circuit* against the num_chunks>1 chunk representation
989
+ via one jax.lax.scan call over the whole (transpiled, GATE_IDS-
990
+ compiled) circuit β€” see _build_multi_chunk_step/_build_multi_chunk_runner
991
+ above for the kernel, and _compile_multi_chunk_ops for the encoding.
992
+
993
+ Convention: chunk index `c` (m = self._m bits, MSB-first, same
994
+ n-1-qubit convention as DenseSVSimulator) equals the value of the
995
+ top m logical qubits (indices [0, m)); chunk_sims[c].sv holds the
996
+ chunk_dim amplitudes for the remaining (local) qubits [m, n). This
997
+ makes full_sv.reshape(num_chunks, chunk_dim)[c] == chunk_sims[c].sv
998
+ exactly, since NumPy's row-major reshape splits a (2,)*n tensor on
999
+ the leading axes first β€” i.e. the most-significant qubits, matching
1000
+ this simulator's MSB-first indexing throughout. Stacking
1001
+ chunk_sims[i].sv into one (num_chunks, chunk_dim) array before the
1002
+ scan, and unstacking after, holds exactly the same total element
1003
+ count as the num_chunks separate arrays it replaces β€” the anti-OOM
1004
+ property this class exists for is preserved, nothing (2**n_qubits,)
1005
+ shaped is ever materialized."""
1006
+ compiled_ops = _compile_multi_chunk_ops(circuit)
1007
+ xp = self._chunk_sims[0].xp
1008
+ stacked = xp.stack([sim.sv for sim in self._chunk_sims])
1009
+ final = self._multi_chunk_runner(stacked, compiled_ops)
1010
+ for i, sim in enumerate(self._chunk_sims):
1011
+ sim.sv = final[i]
1012
+
1013
+ # ── Distributed multi-device gate dispatch (issue #1) ────────────────────
1014
+
1015
+ def dispatch_distributed(self, circuit: List) -> None:
1016
+ """Executes *circuit* the same way _dispatch_multi does, but with
1017
+ each chunk pinned to its own physical JAX device instead of all
1018
+ chunks sharing one process's RAM β€” see
1019
+ _build_distributed_chunk_step/_build_distributed_chunk_runner for
1020
+ the kernel. Requires jax.device_count() >= num_chunks (v1 scope:
1021
+ exactly one chunk per device); raises RuntimeError otherwise
1022
+ rather than silently falling back to the single-process path,
1023
+ since that would silently give up the whole point of calling this
1024
+ method instead of run_chunk().
1025
+
1026
+ The (num_chunks, chunk_dim) logical array is never materialized
1027
+ on any single device here (unlike _dispatch_multi, where it's one
1028
+ process's RAM) -- each device holds and ever sees only its own
1029
+ (chunk_dim,) row, exchanging edge data with its stride-partner
1030
+ device via jax.lax.ppermute inside the kernel, not through this
1031
+ Python method."""
1032
+ if self._chunk_sims is None:
1033
+ raise RuntimeError(
1034
+ "dispatch_distributed() requires num_chunks > 1 "
1035
+ "(this Chunk instance fits in a single chunk)."
1036
+ )
1037
+ num_chunks = self._mem_chunker.num_chunks
1038
+ available = jax.device_count()
1039
+ if available < num_chunks:
1040
+ raise RuntimeError(
1041
+ f"dispatch_distributed() needs >= {num_chunks} JAX devices "
1042
+ f"(one per chunk), only {available} available. Force extra "
1043
+ f"CPU devices for testing via the XLA_FLAGS environment "
1044
+ f"variable: --xla_force_host_platform_device_count=N "
1045
+ f"(set before the process starts, JAX's device count is "
1046
+ f"fixed at first initialization)."
1047
+ )
1048
+ if self._distributed_runner is None:
1049
+ self._distributed_runner, self._distributed_mesh = _build_distributed_chunk_runner(
1050
+ num_chunks, self._m, self._mem_chunker.chunk_size_bits)
1051
+
1052
+ compiled_ops = _compile_multi_chunk_ops(circuit)
1053
+ xp = self._chunk_sims[0].xp
1054
+ stacked = xp.stack([sim.sv for sim in self._chunk_sims])
1055
+ final = self._distributed_runner(stacked, compiled_ops)
1056
+ for i, sim in enumerate(self._chunk_sims):
1057
+ sim.sv = np.asarray(final[i])
1058
+
1059
+ # ── Public API ───────────────────────────────────────────────────────────
1060
+
1061
+ def run_chunk(
1062
+ self,
1063
+ circuit: List,
1064
+ chunk_size_gates: Optional[int] = None,
1065
+ ) -> None:
1066
+
1067
+ if self._chunk_sims is not None:
1068
+ self._dispatch_multi(circuit)
1069
+ return
1070
+ size = chunk_size_gates if chunk_size_gates is not None else self.chunk_size_gates
1071
+ self._circuit_chunker.split_circuit(circuit, chunk_size=size)
1072
+
1073
+ def run_chunk_distributed(self, circuit: List) -> None:
1074
+ """Like run_chunk(), but dispatches across a real JAX device mesh
1075
+ (dispatch_distributed) instead of one process's RAM β€” issue #1.
1076
+ Requires jax.device_count() >= num_chunks; raises RuntimeError
1077
+ otherwise (see dispatch_distributed's docstring for how to test
1078
+ this with simulated multi-device CPU)."""
1079
+ self.dispatch_distributed(circuit)
1080
+
1081
+ def __repr__(self) -> str:
1082
+ s = self._guard.status()
1083
+ safe_qubits = self._inner_sim.n if self._inner_sim is not None else self._mem_chunker.chunk_size_bits
1084
+ return (
1085
+ f"Chunk(n_qubits={self.n}, "
1086
+ f"safe_qubits={safe_qubits}, "
1087
+ f"num_chunks={self.num_chunks}, "
1088
+ f"chunk_size_bits={self.chunk_size_bits}, "
1089
+ f"dtype={self.dtype}, "
1090
+ f"mem_per_chunk={self.memory_mb():.1f} MB, "
1091
+ f"ram_free={s['free_pct']:.1f}%, "
1092
+ f"has_jax={HAS_JAX})"
1093
+ )
1094
+
1095
+
1096
+ # ───────────────────────────────────────────────────────────────────────────���─
1097
+ # Backward-compatibility aliases
1098
+ # ─────────────────────────────────────────────────────────────────────────────
1099
+ chunk1 = MemoryChunker
1100
+ chunk2 = Chunk
1101
+ Chunk2Incrociato = Chunk
dense_evolution/healing.py CHANGED
@@ -1,149 +1,149 @@
1
- import jax
2
- import jax.numpy as jnp
3
- import json
4
- from datetime import datetime, timezone
5
- from typing import Dict, Tuple, List, Any
6
-
7
-
8
- GLOBAL_CONSTANTS = {
9
- 'TARGET_SIGMA_IDEALE': 10.0,
10
- 'THRESHOLD_DELTA_PREEMP': 0.2,
11
- 'SEMANTIC_LEARNING_RATE': 0.05,
12
- 'V_DINAMIC_K_COEFF': 5.0,
13
- 'V_STATIC_K_PRIME_COEFF': 1.0,
14
- 'V_DINAMIC_MIN_EFFECTIVE_VALUE': 0.01,
15
- 'MAX_SEMANTIC_DISTANCE': jnp.sqrt(2.0),
16
- 'WEIGHT_SEMANTIC': 0.6,
17
- 'WEIGHT_COHERENCE': 0.4,
18
- 'NON_STATIC_THRESHOLD_A': 1e-2,
19
- 'DAMPING_BOOST_ON_STASIS': 0.1,
20
- 'EPSILON_DISSIPATION_BASE': 0.01
21
- }
22
-
23
- # =====================================================================
24
- # πŸ“Š STRATO CORE
25
- # =====================================================================
26
-
27
- @jax.jit
28
- def calculate_advanced_sigma(kappa: jnp.ndarray, H: jnp.ndarray, Psi: jnp.ndarray, Omega_sync: jnp.ndarray, tau_K: jnp.ndarray) -> jnp.ndarray:
29
- """Calcola la funzione di sincronizzazione avanzata Sigma."""
30
- return kappa * H * Psi * Omega_sync * tau_K
31
-
32
- @jax.jit
33
- def calculate_phi_ab(state_A: jnp.ndarray, state_B: jnp.ndarray, ipg_vector: jnp.ndarray) -> jnp.ndarray:
34
- """Calcola il fattore di allineamento e coerenza spaziale Phi_AB."""
35
- semantic_change = state_B - state_A
36
- norm_change = jnp.linalg.norm(semantic_change)
37
- norm_ipg = jnp.linalg.norm(ipg_vector)
38
-
39
- alignment = jnp.where(
40
- (norm_change > 1e-12) & (norm_ipg > 1e-12),
41
- # jnp.dot on complex arrays is the bilinear (non-conjugated) product
42
- # and stays complex, which used to blow up jnp.clip below with
43
- # "ValueError: Clip received a complex value". jnp.real(jnp.vdot(..))
44
- # is the correct Hermitian-inner-product real part -- for real
45
- # inputs it reduces exactly to jnp.dot (no behavior change for
46
- # existing real-valued callers), and for complex inputs (e.g. a
47
- # genuine statevector) it gives the real alignment value this
48
- # function needs. Re(vdot(a,b)) == Re(vdot(b,a)) always, even
49
- # though vdot(a,b) != vdot(b,a) in general (they're conjugates) --
50
- # argument order doesn't matter here only because we take the real part.
51
- jnp.real(jnp.vdot(semantic_change, ipg_vector)) / (norm_change * norm_ipg),
52
- 0.0
53
- )
54
- semantic_alignment = (alignment + 1.0) / 2.0
55
-
56
- distance_A_B = jnp.linalg.norm(state_A - state_B)
57
- coherence_component = 1.0 - (distance_A_B / GLOBAL_CONSTANTS['MAX_SEMANTIC_DISTANCE'])
58
-
59
- phi_ab = (semantic_alignment * GLOBAL_CONSTANTS['WEIGHT_SEMANTIC']) + (coherence_component * GLOBAL_CONSTANTS['WEIGHT_COHERENCE'])
60
- return jnp.clip(phi_ab, 0.0, 1.0)
61
-
62
- @jax.jit
63
- def calculate_vettore_dinamico(E_A: jnp.ndarray, E_B: jnp.ndarray, Phi_AB: jnp.ndarray) -> jnp.ndarray:
64
- """Calcola il Vettore Dinamico (V_dinamic) come variazione logaritmica differenziale energetica."""
65
- valid_inputs = (E_A > 1e-12) & (E_B > 1e-12)
66
- ratio = jnp.where(valid_inputs, E_B / E_A, 1.0)
67
- log_ratio_clamped = jnp.clip(jnp.log(ratio), -5.0, 5.0)
68
- v_vita = GLOBAL_CONSTANTS['V_DINAMIC_K_COEFF'] * log_ratio_clamped * Phi_AB
69
- return jnp.where(valid_inputs, v_vita, 0.0)
70
-
71
- @jax.jit
72
- def calculate_vettore_statico(v_dinamic_value: jnp.ndarray) -> jnp.ndarray:
73
- """Calcola l'indicatore di stasi tensoriale Vettore Statico."""
74
- is_growing = v_dinamic_value > GLOBAL_CONSTANTS['V_DINAMIC_MIN_EFFECTIVE_VALUE']
75
- return GLOBAL_CONSTANTS['V_STATIC_K_PRIME_COEFF'] * (1.0 - jnp.where(is_growing, 1.0, 0.0))
76
-
77
- @jax.jit
78
- def calculate_delta_preemp(current_sigma: jnp.ndarray, target_sigma_ideal: float = 10.0) -> jnp.ndarray:
79
- """Calcola la deviazione predittiva Delta_Pre_emp normalizzata rispetto all'autostato ideale."""
80
- safe_target = jnp.where(target_sigma_ideal <= 0.0, 1.0, target_sigma_ideal)
81
- return jnp.abs(current_sigma - target_sigma_ideal) / safe_target
82
-
83
- @jax.jit
84
- def evaluate_phi_trigger(deterministic_dq_dt_a: jnp.ndarray) -> Tuple[jnp.ndarray, jnp.ndarray, jnp.ndarray]:
85
- """Valuta lo stato del Phi-Trigger calcolando i coefficienti di damping condizionati."""
86
- magnitude_change_a = jnp.abs(deterministic_dq_dt_a)
87
- trigger_active = magnitude_change_a > GLOBAL_CONSTANTS['NON_STATIC_THRESHOLD_A']
88
-
89
- lambda_step = jnp.where(trigger_active, 0.05, 0.05 + GLOBAL_CONSTANTS['DAMPING_BOOST_ON_STASIS'])
90
- epsilon_dissip = jnp.where(trigger_active, GLOBAL_CONSTANTS['EPSILON_DISSIPATION_BASE'],
91
- GLOBAL_CONSTANTS['EPSILON_DISSIPATION_BASE'] + GLOBAL_CONSTANTS['DAMPING_BOOST_ON_STASIS'])
92
-
93
- return jnp.where(trigger_active, 1.0, 0.0), lambda_step, epsilon_dissip
94
-
95
- @jax.jit
96
- def calculate_jax_reflection(coherence_values: jnp.ndarray, noise_levels: jnp.ndarray) -> Tuple[jnp.ndarray, jnp.ndarray, jnp.ndarray]:
97
- """Esegue l'aggregazione statistica spettrale (Zero-Drift) sul runtime XLA."""
98
- n_coh = coherence_values.shape[0]
99
- avg_coherence = jnp.where(n_coh > 0, jnp.mean(coherence_values), 0.0)
100
- var_coherence = jnp.where(n_coh > 0, jnp.var(coherence_values), 0.0)
101
-
102
- n_noise = noise_levels.shape[0]
103
- avg_noise = jnp.where(n_noise > 0, jnp.mean(noise_levels), 0.0)
104
-
105
- return avg_coherence, var_coherence, avg_noise
106
-
107
- # =====================================================================
108
- # STRATO OPERATIVO: LOGGING E STORICIZZAZIONE
109
- # =====================================================================
110
-
111
- class MemoryReflectionEngine:
112
- def __init__(self):
113
- self.memory: List[Dict[str, Any]] = []
114
-
115
- def record_event(self, event_type: str, value: float, description: str = ""):
116
- event = {
117
- "timestamp": datetime.now(timezone.utc).isoformat(),
118
- "type": event_type,
119
- "value": float(value),
120
- "description": description
121
- }
122
- self.memory.append(event)
123
-
124
- def reflect(self) -> Dict[str, Any]:
125
- coherence_list = [e['value'] for e in self.memory if e['type'] == 'coherence']
126
- interventions = [e for e in self.memory if e['type'] == 'intervention']
127
- noise_list = [e['value'] for e in self.memory if e['type'] == 'noise']
128
-
129
- j_coherence = jnp.array(coherence_list, dtype=jnp.float64) if coherence_list else jnp.array([], dtype=jnp.float64)
130
- j_noise = jnp.array(noise_list, dtype=jnp.float64) if noise_list else jnp.array([], dtype=jnp.float64)
131
-
132
- avg_coh, var_coh, avg_noise = calculate_jax_reflection(j_coherence, j_noise)
133
-
134
- report = {
135
- 'average_coherence': float(avg_coh) if coherence_list else None,
136
- 'variance_coherence': float(var_coh) if coherence_list else None,
137
- 'interventions_count': len(interventions),
138
- 'average_noise': float(avg_noise) if noise_list else None,
139
- 'total_events': len(self.memory)
140
- }
141
- return report
142
-
143
- def export_memory(self, filepath: str):
144
- with open(filepath, 'w') as f:
145
- json.dump(self.memory, f, indent=2)
146
-
147
- def load_memory(self, filepath: str):
148
- with open(filepath, 'r') as f:
149
- self.memory = json.load(f)
 
1
+ import jax
2
+ import jax.numpy as jnp
3
+ import json
4
+ from datetime import datetime, timezone
5
+ from typing import Dict, Tuple, List, Any
6
+
7
+
8
+ GLOBAL_CONSTANTS = {
9
+ 'TARGET_SIGMA_IDEALE': 10.0,
10
+ 'THRESHOLD_DELTA_PREEMP': 0.2,
11
+ 'SEMANTIC_LEARNING_RATE': 0.05,
12
+ 'V_DINAMIC_K_COEFF': 5.0,
13
+ 'V_STATIC_K_PRIME_COEFF': 1.0,
14
+ 'V_DINAMIC_MIN_EFFECTIVE_VALUE': 0.01,
15
+ 'MAX_SEMANTIC_DISTANCE': jnp.sqrt(2.0),
16
+ 'WEIGHT_SEMANTIC': 0.6,
17
+ 'WEIGHT_COHERENCE': 0.4,
18
+ 'NON_STATIC_THRESHOLD_A': 1e-2,
19
+ 'DAMPING_BOOST_ON_STASIS': 0.1,
20
+ 'EPSILON_DISSIPATION_BASE': 0.01
21
+ }
22
+
23
+ # =====================================================================
24
+ # πŸ“Š STRATO CORE
25
+ # =====================================================================
26
+
27
+ @jax.jit
28
+ def calculate_advanced_sigma(kappa: jnp.ndarray, H: jnp.ndarray, Psi: jnp.ndarray, Omega_sync: jnp.ndarray, tau_K: jnp.ndarray) -> jnp.ndarray:
29
+ """Calcola la funzione di sincronizzazione avanzata Sigma."""
30
+ return kappa * H * Psi * Omega_sync * tau_K
31
+
32
+ @jax.jit
33
+ def calculate_phi_ab(state_A: jnp.ndarray, state_B: jnp.ndarray, ipg_vector: jnp.ndarray) -> jnp.ndarray:
34
+ """Calcola il fattore di allineamento e coerenza spaziale Phi_AB."""
35
+ semantic_change = state_B - state_A
36
+ norm_change = jnp.linalg.norm(semantic_change)
37
+ norm_ipg = jnp.linalg.norm(ipg_vector)
38
+
39
+ alignment = jnp.where(
40
+ (norm_change > 1e-12) & (norm_ipg > 1e-12),
41
+ # jnp.dot on complex arrays is the bilinear (non-conjugated) product
42
+ # and stays complex, which used to blow up jnp.clip below with
43
+ # "ValueError: Clip received a complex value". jnp.real(jnp.vdot(..))
44
+ # is the correct Hermitian-inner-product real part -- for real
45
+ # inputs it reduces exactly to jnp.dot (no behavior change for
46
+ # existing real-valued callers), and for complex inputs (e.g. a
47
+ # genuine statevector) it gives the real alignment value this
48
+ # function needs. Re(vdot(a,b)) == Re(vdot(b,a)) always, even
49
+ # though vdot(a,b) != vdot(b,a) in general (they're conjugates) --
50
+ # argument order doesn't matter here only because we take the real part.
51
+ jnp.real(jnp.vdot(semantic_change, ipg_vector)) / (norm_change * norm_ipg),
52
+ 0.0
53
+ )
54
+ semantic_alignment = (alignment + 1.0) / 2.0
55
+
56
+ distance_A_B = jnp.linalg.norm(state_A - state_B)
57
+ coherence_component = 1.0 - (distance_A_B / GLOBAL_CONSTANTS['MAX_SEMANTIC_DISTANCE'])
58
+
59
+ phi_ab = (semantic_alignment * GLOBAL_CONSTANTS['WEIGHT_SEMANTIC']) + (coherence_component * GLOBAL_CONSTANTS['WEIGHT_COHERENCE'])
60
+ return jnp.clip(phi_ab, 0.0, 1.0)
61
+
62
+ @jax.jit
63
+ def calculate_vettore_dinamico(E_A: jnp.ndarray, E_B: jnp.ndarray, Phi_AB: jnp.ndarray) -> jnp.ndarray:
64
+ """Calcola il Vettore Dinamico (V_dinamic) come variazione logaritmica differenziale energetica."""
65
+ valid_inputs = (E_A > 1e-12) & (E_B > 1e-12)
66
+ ratio = jnp.where(valid_inputs, E_B / E_A, 1.0)
67
+ log_ratio_clamped = jnp.clip(jnp.log(ratio), -5.0, 5.0)
68
+ v_vita = GLOBAL_CONSTANTS['V_DINAMIC_K_COEFF'] * log_ratio_clamped * Phi_AB
69
+ return jnp.where(valid_inputs, v_vita, 0.0)
70
+
71
+ @jax.jit
72
+ def calculate_vettore_statico(v_dinamic_value: jnp.ndarray) -> jnp.ndarray:
73
+ """Calcola l'indicatore di stasi tensoriale Vettore Statico."""
74
+ is_growing = v_dinamic_value > GLOBAL_CONSTANTS['V_DINAMIC_MIN_EFFECTIVE_VALUE']
75
+ return GLOBAL_CONSTANTS['V_STATIC_K_PRIME_COEFF'] * (1.0 - jnp.where(is_growing, 1.0, 0.0))
76
+
77
+ @jax.jit
78
+ def calculate_delta_preemp(current_sigma: jnp.ndarray, target_sigma_ideal: float = 10.0) -> jnp.ndarray:
79
+ """Calcola la deviazione predittiva Delta_Pre_emp normalizzata rispetto all'autostato ideale."""
80
+ safe_target = jnp.where(target_sigma_ideal <= 0.0, 1.0, target_sigma_ideal)
81
+ return jnp.abs(current_sigma - target_sigma_ideal) / safe_target
82
+
83
+ @jax.jit
84
+ def evaluate_phi_trigger(deterministic_dq_dt_a: jnp.ndarray) -> Tuple[jnp.ndarray, jnp.ndarray, jnp.ndarray]:
85
+ """Valuta lo stato del Phi-Trigger calcolando i coefficienti di damping condizionati."""
86
+ magnitude_change_a = jnp.abs(deterministic_dq_dt_a)
87
+ trigger_active = magnitude_change_a > GLOBAL_CONSTANTS['NON_STATIC_THRESHOLD_A']
88
+
89
+ lambda_step = jnp.where(trigger_active, 0.05, 0.05 + GLOBAL_CONSTANTS['DAMPING_BOOST_ON_STASIS'])
90
+ epsilon_dissip = jnp.where(trigger_active, GLOBAL_CONSTANTS['EPSILON_DISSIPATION_BASE'],
91
+ GLOBAL_CONSTANTS['EPSILON_DISSIPATION_BASE'] + GLOBAL_CONSTANTS['DAMPING_BOOST_ON_STASIS'])
92
+
93
+ return jnp.where(trigger_active, 1.0, 0.0), lambda_step, epsilon_dissip
94
+
95
+ @jax.jit
96
+ def calculate_jax_reflection(coherence_values: jnp.ndarray, noise_levels: jnp.ndarray) -> Tuple[jnp.ndarray, jnp.ndarray, jnp.ndarray]:
97
+ """Esegue l'aggregazione statistica spettrale (Zero-Drift) sul runtime XLA."""
98
+ n_coh = coherence_values.shape[0]
99
+ avg_coherence = jnp.where(n_coh > 0, jnp.mean(coherence_values), 0.0)
100
+ var_coherence = jnp.where(n_coh > 0, jnp.var(coherence_values), 0.0)
101
+
102
+ n_noise = noise_levels.shape[0]
103
+ avg_noise = jnp.where(n_noise > 0, jnp.mean(noise_levels), 0.0)
104
+
105
+ return avg_coherence, var_coherence, avg_noise
106
+
107
+ # =====================================================================
108
+ # STRATO OPERATIVO: LOGGING E STORICIZZAZIONE
109
+ # =====================================================================
110
+
111
+ class MemoryReflectionEngine:
112
+ def __init__(self):
113
+ self.memory: List[Dict[str, Any]] = []
114
+
115
+ def record_event(self, event_type: str, value: float, description: str = ""):
116
+ event = {
117
+ "timestamp": datetime.now(timezone.utc).isoformat(),
118
+ "type": event_type,
119
+ "value": float(value),
120
+ "description": description
121
+ }
122
+ self.memory.append(event)
123
+
124
+ def reflect(self) -> Dict[str, Any]:
125
+ coherence_list = [e['value'] for e in self.memory if e['type'] == 'coherence']
126
+ interventions = [e for e in self.memory if e['type'] == 'intervention']
127
+ noise_list = [e['value'] for e in self.memory if e['type'] == 'noise']
128
+
129
+ j_coherence = jnp.array(coherence_list, dtype=jnp.float64) if coherence_list else jnp.array([], dtype=jnp.float64)
130
+ j_noise = jnp.array(noise_list, dtype=jnp.float64) if noise_list else jnp.array([], dtype=jnp.float64)
131
+
132
+ avg_coh, var_coh, avg_noise = calculate_jax_reflection(j_coherence, j_noise)
133
+
134
+ report = {
135
+ 'average_coherence': float(avg_coh) if coherence_list else None,
136
+ 'variance_coherence': float(var_coh) if coherence_list else None,
137
+ 'interventions_count': len(interventions),
138
+ 'average_noise': float(avg_noise) if noise_list else None,
139
+ 'total_events': len(self.memory)
140
+ }
141
+ return report
142
+
143
+ def export_memory(self, filepath: str):
144
+ with open(filepath, 'w') as f:
145
+ json.dump(self.memory, f, indent=2)
146
+
147
+ def load_memory(self, filepath: str):
148
+ with open(filepath, 'r') as f:
149
+ self.memory = json.load(f)
dense_evolution/mitigation.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Zero-Noise Extrapolation (ZNE)
3
+ -------------------------------
4
+ Standard error-mitigation entry points, named the way the field already
5
+ names them (Richardson extrapolation, noise factors, zero-noise
6
+ extrapolation -- same vocabulary as e.g. Mitiq's `zne` API), so callers
7
+ and tooling can find "ZNE" without first learning Dense-Evolution's
8
+ internal healing vocabulary.
9
+
10
+ This module composes `dense_evolution.healing`'s existing primitives
11
+ (`calculate_delta_preemp`, ...) -- it does not rename or replace them.
12
+ """
13
+ import jax.numpy as jnp
14
+
15
+ from .healing import calculate_delta_preemp
16
+
17
+ __all__ = ["richardson_extrapolate", "zero_noise_extrapolation"]
18
+
19
+
20
+ def richardson_extrapolate(expectation_values, noise_factors) -> jnp.ndarray:
21
+ """Polynomial (Lagrange) Richardson extrapolation to zero noise.
22
+
23
+ `expectation_values[i]` is the value measured/simulated at noise scale
24
+ `noise_factors[i]` (e.g. 1x, 2x, 3x folded/scaled noise) -- a scalar,
25
+ or itself an array (e.g. a full probability distribution sampled at
26
+ that noise scale; extrapolated elementwise). Returns the extrapolated
27
+ zero-noise estimate, same shape as one `expectation_values[i]`. Works
28
+ for any number of points and any (not necessarily equally spaced)
29
+ noise factors; for the common 3-point case at noise_factors=(1,2,3)
30
+ this reduces exactly to the textbook coefficients (3, -3, 1).
31
+ """
32
+ lambdas = jnp.asarray(noise_factors, dtype=jnp.float64)
33
+ values = jnp.asarray(expectation_values, dtype=jnp.float64)
34
+ n = lambdas.shape[0]
35
+
36
+ def lagrange_coeff(i):
37
+ others = jnp.concatenate([lambdas[:i], lambdas[i + 1:]])
38
+ return jnp.prod((0.0 - others) / (lambdas[i] - others))
39
+
40
+ coeffs = jnp.stack([lagrange_coeff(i) for i in range(n)])
41
+ # Broadcast coeffs against the LEADING axis of values (the "one row per
42
+ # noise scale" axis), not jnp's default trailing-axis alignment --
43
+ # values may itself be array-valued per scale (values.shape = (n,
44
+ # *extra_dims)), e.g. a whole probability distribution rather than a
45
+ # bare scalar. A no-op reshape when values is 1-D (the scalar case),
46
+ # so existing scalar callers are unaffected.
47
+ coeffs = coeffs.reshape((n,) + (1,) * (values.ndim - 1))
48
+ return jnp.sum(coeffs * values, axis=0)
49
+
50
+
51
+ def zero_noise_extrapolation(expectation_values, noise_factors,
52
+ sigma_at_base_noise=None,
53
+ target_sigma_ideal: float = 10.0) -> jnp.ndarray:
54
+ """Zero-Noise Extrapolation -- plain, or healing-adapted when a
55
+ coherence signal is available.
56
+
57
+ Without `sigma_at_base_noise`: standard Richardson ZNE
58
+ (`richardson_extrapolate`).
59
+
60
+ With `sigma_at_base_noise` (the measured/simulated coherence sigma at
61
+ the base, unscaled noise level): the 3 Richardson coefficients are
62
+ perturbed by `dense_evolution.healing.calculate_delta_preemp` -- the
63
+ normalized deviation between the observed sigma and the ideal target
64
+ -- then renormalized to sum to 1. This is Dense-Evolution's
65
+ "predictive healing" ZNE variant: when the observed coherence is off
66
+ the ideal target, the extrapolation is nudged accordingly instead of
67
+ trusting the 3 raw noise-scaled points equally.
68
+
69
+ The healing-adapted path currently only supports exactly 3 noise
70
+ factors (the case it has been derived and tested against); passing
71
+ `sigma_at_base_noise` with any other point count raises
72
+ NotImplementedError rather than silently generalizing an unverified
73
+ formula.
74
+ """
75
+ if sigma_at_base_noise is None:
76
+ return richardson_extrapolate(expectation_values, noise_factors)
77
+
78
+ lambdas = jnp.asarray(noise_factors, dtype=jnp.float64)
79
+ if lambdas.shape[0] != 3:
80
+ raise NotImplementedError(
81
+ "Healing-adapted ZNE is only defined for exactly 3 noise factors; "
82
+ "call richardson_extrapolate(...) directly for the plain N-point case."
83
+ )
84
+ values = jnp.asarray(expectation_values, dtype=jnp.float64)
85
+ e_l1, e_l2, e_l3 = values[0], values[1], values[2]
86
+
87
+ delta_p = calculate_delta_preemp(jnp.asarray(sigma_at_base_noise, dtype=jnp.float64),
88
+ target_sigma_ideal)
89
+ c1 = 3.0 - 0.01 * delta_p
90
+ c2 = -3.0 + 0.02 * delta_p
91
+ c3 = 1.0 - 0.01 * delta_p
92
+ return (c1 * e_l1 + c2 * e_l2 + c3 * e_l3) / (c1 + c2 + c3)
dense_evolution/mps.py CHANGED
@@ -1,392 +1,402 @@
1
- """
2
- MPSSimulator - Matrix Product State statevector simulator, JAX-backed.
3
-
4
- Ported from the "TurboQuant TUREQ MPSSimulator v8.2 MatryoshkaFlash"
5
- prototype (private research notebook, never published as part of the
6
- dense-evolution package). Two real bugs were found and fixed by
7
- independent verification against DenseSVSimulator before this module
8
- existed in its current form:
9
-
10
- 1. The original applied Lloyd-Max quantization to the SVD singular
11
- values on every truncation ("PolarQuantizer"). Measured a real ~0.5%
12
- Total Variation Distance error against DenseSVSimulator on an
13
- 8-qubit entangling test circuit, with ZERO bond-dimension savings to
14
- show for it. Dropped entirely -- this module keeps only the plain
15
- adaptive SVD truncation (JSD-budget-driven bond dimension, the
16
- author's own stopping criterion -- standard SVD truncation,
17
- non-standard stopping metric).
18
-
19
- 2. get_top_k_probable_states (originally "_extract_top_k_paths") picked
20
- a single "best" bond index via argmax at each step instead of
21
- correctly summing over the bond dimension. Measured 0/8 correct
22
- states against the exact contraction on the same test circuit,
23
- values off by ~30x. Fixed by propagating the true partial-contraction
24
- vector through each bond (matches exactly, to machine precision, on
25
- every state it finds) -- but note it's a genuine greedy beam search,
26
- not an exact top-k finder: recall of the true top states grows with
27
- beam width k but isn't guaranteed complete for any fixed k.
28
-
29
- Originally ported in plain numpy (matching the prototype), then
30
- converted to jax.numpy so the core tensor contractions (einsum, SVD) run
31
- on the same backend as the rest of dense_evolution instead of a second,
32
- inconsistent numerics stack. Re-verified against DenseSVSimulator after
33
- the conversion -- see test_mps.py.
34
-
35
- Uses whatever jax_enable_x64 precision is currently active in the
36
- process (does not toggle it itself) -- same convention as
37
- DenseSVSimulator/Chunk, which rely on the caller (dashboard_core.py's
38
- run_simulation) to set precision, since jax_enable_x64 is a process-wide
39
- flag and toggling it locally would leak to unrelated code running later
40
- in the same process.
41
-
42
- For circuits with LOW entanglement (product states, GHZ/Bell-like chains,
43
- shallow local circuits), the bond dimension stays small regardless of
44
- qubit count, so this scales to hundreds of qubits where DenseSVSimulator
45
- (or Chunk) cannot -- see get_probabilities_sampled and
46
- get_top_k_probable_states, neither of which ever materializes a
47
- (2**n,)-shaped array. For HIGHLY entangled circuits the bond dimension
48
- grows and this degrades back toward the same exponential cost
49
- DenseSVSimulator has -- it is not a universal replacement, it is
50
- complementary.
51
- """
52
-
53
- import warnings
54
- from typing import List, Optional, Tuple
55
-
56
- import jax
57
- import jax.numpy as jnp
58
- import numpy as np
59
-
60
-
61
- def _jsd_vectors(p: jnp.ndarray, q: jnp.ndarray) -> float:
62
- """Adaptive Jensen-Shannon Distance used to size the truncated bond
63
- dimension: scales with log10(dim) so the same JSD budget stays
64
- meaningful whether the local Hilbert space is small or large."""
65
- eps = 1e-12
66
- p_norm = p / (jnp.sum(p) + eps)
67
- q_norm = q / (jnp.sum(q) + eps)
68
- m = 0.5 * (p_norm + q_norm)
69
-
70
- def _kl(a, b):
71
- mask = a > eps
72
- # jnp.where still traces both branches, but log(0) only ever
73
- # feeds into a term multiplied by 0 through the mask -- safe,
74
- # and avoids a Python-side branch on a traced value.
75
- safe_log = jnp.where(mask, jnp.log2(jnp.where(mask, a, 1.0) / (b + eps)), 0.0)
76
- return jnp.sum(jnp.where(mask, a * safe_log, 0.0))
77
-
78
- js = 0.5 * (_kl(p_norm, m) + _kl(q_norm, m))
79
- dim_factor = float(np.log10(len(p)) / 2.0) if len(p) > 1 else 1.0
80
- return float(jnp.sqrt(jnp.clip(js * dim_factor, 0.0, 1.0)))
81
-
82
-
83
- class MPSSimulator:
84
- """
85
- Matrix Product State simulator with adaptive SVD-truncated bond
86
- dimension (JSD-budget driven), no lossy post-truncation quantization.
87
- JAX-backed core (einsum, SVD).
88
-
89
- Parameters
90
- ----------
91
- n_qubits : int
92
- max_bond : int -- hard cap on bond dimension chi
93
- svd_cutoff : float -- singular values below this are dropped outright
94
- jsd_budget : float -- max tolerated Jensen-Shannon distance between the
95
- full and truncated singular-value distributions
96
- at each cut; chi is grown by 1 until satisfied
97
- or max_bond is hit.
98
- """
99
-
100
- def __init__(
101
- self,
102
- n_qubits: int,
103
- max_bond: int = 64,
104
- svd_cutoff: float = 1e-12,
105
- jsd_budget: float = 1e-5,
106
- ):
107
- self.n = n_qubits
108
- self.chi = max_bond
109
- self.eps = svd_cutoff
110
- self.jsd_budget = jsd_budget
111
-
112
- self.gammas: List[jnp.ndarray] = []
113
- self.lambdas: List[jnp.ndarray] = [jnp.ones(1)] * (n_qubits + 1)
114
-
115
- self.truncation_errors: List[float] = []
116
- self.jsd_per_bond: List[float] = []
117
- self.entanglement_entropy = np.zeros(max(n_qubits - 1, 0))
118
- self._bond_history: List[int] = []
119
- # Counts truncations where max_bond was hit before jsd_budget could
120
- # be satisfied -- the while loop below exits silently in that case,
121
- # and avg_JSD (a mean over all steps) can look deceptively low even
122
- # when the final contracted state is badly wrong (verified: TVD
123
- # ~0.97 against DenseSVSimulator on an 8-qubit/15-layer entangling
124
- # circuit with max_bond=2, while avg_JSD read 0.0534).
125
- self.budget_violations: int = 0
126
-
127
- for _ in range(n_qubits):
128
- g = jnp.zeros((1, 2, 1), dtype=jnp.complex64 if not jax.config.jax_enable_x64 else jnp.complex128)
129
- g = g.at[0, 0, 0].set(1.0)
130
- self.gammas.append(g)
131
-
132
- # gate 1q
133
- def apply_gate_1q(self, gate: jnp.ndarray, qubit: int) -> None:
134
- """O(chi^2) -- updates only Gamma[qubit]."""
135
- gate = jnp.asarray(gate)
136
- self.gammas[qubit] = jnp.einsum("ij,ljr->lir", gate, self.gammas[qubit])
137
-
138
- # core: plain adaptive SVD truncation (no quantization)
139
- def _svd_truncate(
140
- self, theta_mat: jnp.ndarray
141
- ) -> Tuple[jnp.ndarray, jnp.ndarray, jnp.ndarray, float, float]:
142
- U, S, Vh = jnp.linalg.svd(theta_mat, full_matrices=False)
143
-
144
- mask = S > self.eps
145
- chi_new = max(1, min(int(jnp.sum(mask)), self.chi))
146
- max_possible = min(len(S), self.chi)
147
-
148
- norm_full = float(jnp.sum(S**2)) + 1e-15
149
- p_full = (S**2) / norm_full
150
-
151
- def _trunc_jsd(chi_try):
152
- p_trunc = jnp.zeros_like(p_full)
153
- p_trunc = p_trunc.at[:chi_try].set((S[:chi_try] ** 2) / norm_full)
154
- return _jsd_vectors(p_full, p_trunc)
155
-
156
- jsd_val = _trunc_jsd(chi_new)
157
- while jsd_val > self.jsd_budget and chi_new < max_possible:
158
- chi_new += 1
159
- jsd_val = _trunc_jsd(chi_new)
160
-
161
- if jsd_val > self.jsd_budget:
162
- # Loop exited because chi_new hit max_possible (== max_bond, in
163
- # the common case where the bond isn't already capped by the
164
- # SVD's own rank), not because jsd_budget was satisfied.
165
- if self.budget_violations == 0:
166
- warnings.warn(
167
- f"MPSSimulator: bond dimension capped at max_bond={self.chi}, "
168
- f"jsd_budget={self.jsd_budget:.1e} not honored "
169
- f"(jsd={jsd_val:.2e}) -- results may be unreliable, "
170
- f"consider raising max_bond.",
171
- UserWarning,
172
- stacklevel=2,
173
- )
174
- self.budget_violations += 1
175
-
176
- trunc_err = float(jnp.sqrt(jnp.sum(S[chi_new:] ** 2))) if len(S) > chi_new else 0.0
177
- self.truncation_errors.append(trunc_err)
178
-
179
- return U[:, :chi_new], S[:chi_new], Vh[:chi_new, :], trunc_err, jsd_val
180
-
181
- # gate 2q adjacent
182
- def apply_gate_2q(self, gate_2q: jnp.ndarray, q1: int, q2: int) -> None:
183
- """2-qubit gate with adaptive SVD truncation. O(chi^3)."""
184
- gate_2q = jnp.asarray(gate_2q)
185
- if abs(q1 - q2) != 1:
186
- self._apply_nonlocal_2q(gate_2q, q1, q2)
187
- return
188
- if q1 > q2:
189
- q1, q2 = q2, q1
190
- gate_2q = jnp.transpose(gate_2q, (1, 0, 3, 2))
191
-
192
- g1 = self.gammas[q1]
193
- g2 = self.gammas[q2]
194
- lam = self.lambdas[q2]
195
-
196
- theta = jnp.einsum("lik,k,kjr->lijr", g1, lam, g2)
197
- chiL, d1, d2, chiR = theta.shape
198
-
199
- theta_new = jnp.einsum("abcd,ecdf->eabf", gate_2q, theta)
200
- theta_mat = theta_new.reshape(chiL * d1, d2 * chiR)
201
-
202
- U_t, S_t, Vh_t, trunc_err, jsd_val = self._svd_truncate(theta_mat)
203
- chi_new = len(S_t)
204
-
205
- s_sq = S_t**2
206
- p_dist = s_sq / (jnp.sum(s_sq) + 1e-20)
207
- p_v = p_dist[p_dist > 1e-20]
208
- ee = float(-jnp.sum(p_v * jnp.log2(p_v))) if len(p_v) > 1 else 0.0
209
- if q1 < len(self.entanglement_entropy):
210
- self.entanglement_entropy[q1] = ee
211
-
212
- self.lambdas[q2] = S_t
213
- self.gammas[q1] = U_t.reshape(chiL, d1, chi_new)
214
- self.gammas[q2] = Vh_t.reshape(chi_new, d2, chiR)
215
-
216
- self._bond_history.append(chi_new)
217
- self.jsd_per_bond.append(jsd_val)
218
-
219
- def _apply_nonlocal_2q(self, gate_2q: jnp.ndarray, q1: int, q2: int) -> None:
220
- """Non-adjacent 2-qubit gate via a SWAP chain down to adjacent."""
221
- swap = jnp.array(
222
- [[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]], dtype=complex
223
- ).reshape(2, 2, 2, 2)
224
- target = min(q1, q2)
225
- for q in range(max(q1, q2) - 1, target, -1):
226
- self.apply_gate_2q(swap, q, q + 1)
227
- self.apply_gate_2q(gate_2q, target, target + 1)
228
- for q in range(target + 1, max(q1, q2)):
229
- self.apply_gate_2q(swap, q, q + 1)
230
-
231
- # gate shortcuts
232
- def apply_cx(self, ctrl: int, tgt: int) -> None:
233
- cx = jnp.array(
234
- [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]], dtype=complex
235
- ).reshape(2, 2, 2, 2)
236
- self.apply_gate_2q(cx, ctrl, tgt)
237
-
238
- def apply_cz(self, ctrl: int, tgt: int) -> None:
239
- cz = jnp.diag(jnp.array([1, 1, 1, -1])).astype(complex).reshape(2, 2, 2, 2)
240
- self.apply_gate_2q(cz, ctrl, tgt)
241
-
242
- def apply_swap(self, q1: int, q2: int) -> None:
243
- sw = jnp.array(
244
- [[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]], dtype=complex
245
- ).reshape(2, 2, 2, 2)
246
- self.apply_gate_2q(sw, q1, q2)
247
-
248
- def apply_ccx(self, c1: int, c2: int, tgt: int) -> None:
249
- """Toffoli via standard T-gate decomposition (all 1q/2q gates)."""
250
- inv2 = 1.0 / np.sqrt(2.0)
251
- h = inv2 * jnp.array([[1, 1], [1, -1]], dtype=complex)
252
- t = jnp.array([[1, 0], [0, jnp.exp(1j * jnp.pi / 4)]], dtype=complex)
253
- tdg = jnp.array([[1, 0], [0, jnp.exp(-1j * jnp.pi / 4)]], dtype=complex)
254
-
255
- self.apply_gate_1q(h, tgt)
256
- self.apply_cx(c2, tgt)
257
- self.apply_gate_1q(tdg, tgt)
258
- self.apply_cx(c1, tgt)
259
- self.apply_gate_1q(t, tgt)
260
- self.apply_cx(c2, tgt)
261
- self.apply_gate_1q(tdg, tgt)
262
- self.apply_cx(c1, tgt)
263
- self.apply_gate_1q(t, c2)
264
- self.apply_gate_1q(t, tgt)
265
- self.apply_gate_1q(h, tgt)
266
- self.apply_cx(c1, c2)
267
- self.apply_gate_1q(t, c1)
268
- self.apply_gate_1q(tdg, c2)
269
- self.apply_cx(c1, c2)
270
-
271
- # contraction to a full statevector -- O(2**n), n <= ~24 only
272
- def contract_to_statevector(self) -> jnp.ndarray:
273
- if self.n > 24:
274
- raise MemoryError(
275
- f"contract_to_statevector at {self.n} qubits would need "
276
- f"~{2**self.n * 16 / 1e9:.1f} GB -- use "
277
- f"get_probabilities_sampled or get_top_k_probable_states "
278
- f"instead for n > 24."
279
- )
280
- result = self.gammas[0].squeeze(axis=0)
281
- for i in range(1, self.n):
282
- lam = self.lambdas[i]
283
- g = self.gammas[i]
284
- lg = jnp.einsum("k,kir->kir", lam, g)
285
- result = jnp.tensordot(result, lg, axes=([-1], [0]))
286
- result = result.reshape(-1, result.shape[-1])
287
- sv = result.squeeze(axis=-1)
288
- norm = jnp.linalg.norm(sv)
289
- return sv / (norm + 1e-15)
290
-
291
- # sequential sampling -- O(chi^2) per qubit per sample, never
292
- # materializes a (2**n,) array. The only way to get results for
293
- # n_qubits beyond ~24. Sampling decisions themselves stay on host
294
- # (np.random.Generator): each step needs a concrete probability to
295
- # branch on, not a traced value, so this loop isn't a jax.jit
296
- # candidate as a whole regardless of backend.
297
- def _sample_bitstring(self, rng: np.random.Generator) -> List[int]:
298
- bits = []
299
- state = jnp.ones(1, dtype=complex)
300
- for i in range(self.n):
301
- g = self.gammas[i]
302
- lam = self.lambdas[i + 1] if i < self.n - 1 else jnp.ones(g.shape[2])
303
- p0v = jnp.einsum("l,lr->r", state, g[:, 0, :])
304
- p1v = jnp.einsum("l,lr->r", state, g[:, 1, :])
305
- p0l = p0v * lam
306
- p1l = p1v * lam
307
- p0 = float(jnp.real(jnp.dot(p0l, jnp.conj(p0l))))
308
- p1 = float(jnp.real(jnp.dot(p1l, jnp.conj(p1l))))
309
- norm = p0 + p1 + 1e-15
310
- bit = 0 if rng.random() < p0 / norm else 1
311
- bits.append(bit)
312
- state = p0l if bit == 0 else p1l
313
- state = state / (jnp.linalg.norm(state) + 1e-15)
314
- return bits
315
-
316
- def get_probabilities_sampled(
317
- self, n_samples: int = 100_000, seed: Optional[int] = None
318
- ) -> dict:
319
- """Returns a {bitstring: empirical_probability} dict from n_samples
320
- sequential draws -- the only entry point safe for n_qubits > 24."""
321
- from collections import Counter
322
-
323
- rng = np.random.default_rng(seed)
324
- counts: Counter = Counter()
325
- for _ in range(n_samples):
326
- bits = self._sample_bitstring(rng)
327
- counts["".join(map(str, bits))] += 1
328
- return {bitstr: c / n_samples for bitstr, c in counts.items()}
329
-
330
- # ──────────────────────────────────────────────
331
- # approximate top-k extraction -- see module docstring point 2.
332
- # ──────────────────────────────────────────────
333
- def get_top_k_probable_states(self, k: int = 128) -> Tuple[np.ndarray, np.ndarray]:
334
- """Greedy beam search (beam width k) for approximately-most-probable
335
- basis states, without ever contracting to a full statevector.
336
-
337
- Returns (indices, probabilities): indices are computational-basis
338
- integers, probabilities are exact for the states found (not
339
- approximated), sorted descending. Recall of the TRUE top states
340
- improves with k but is not guaranteed for any fixed k -- see the
341
- module docstring."""
342
- paths: List[Tuple[int, jnp.ndarray]] = [(0, jnp.array([1.0 + 0.0j]))]
343
- for i in range(self.n):
344
- candidates = []
345
- gamma = self.gammas[i]
346
- lam = self.lambdas[i + 1] if (i + 1) < len(self.lambdas) else jnp.ones(gamma.shape[2])
347
- for idx_p, vec_p in paths:
348
- for bit in (0, 1):
349
- new_vec = jnp.einsum("l,lr->r", vec_p, gamma[:, bit, :]) * lam
350
- weight = float(jnp.sum(jnp.abs(new_vec) ** 2))
351
- candidates.append(((idx_p << 1) | bit, new_vec, weight))
352
- candidates.sort(key=lambda c: c[2], reverse=True)
353
- paths = [(idx, vec) for idx, vec, _ in candidates[:k]]
354
-
355
- indices = np.array([p[0] for p in paths])
356
- amplitudes = np.array([
357
- complex(vec[0]) if len(vec) == 1 else complex(jnp.sum(vec))
358
- for _, vec in paths
359
- ])
360
- probabilities = np.abs(amplitudes) ** 2
361
- order = np.argsort(-probabilities)
362
- return indices[order], probabilities[order]
363
-
364
- # metrics
365
- def max_bond_used(self) -> int:
366
- return max(self._bond_history) if self._bond_history else 1
367
-
368
- def total_truncation_error(self) -> float:
369
- if not self.truncation_errors:
370
- return 0.0
371
- return float(np.sqrt(np.sum(np.array(self.truncation_errors) ** 2)))
372
-
373
- def avg_jsd(self) -> float:
374
- return float(np.mean(self.jsd_per_bond)) if self.jsd_per_bond else 0.0
375
-
376
- def memory_bytes(self) -> int:
377
- bytes_gammas = sum(g.size * g.dtype.itemsize for g in self.gammas)
378
- bytes_lambdas = sum(l.size * l.dtype.itemsize for l in self.lambdas)
379
- return int(bytes_gammas + bytes_lambdas)
380
-
381
- def memory_mb(self) -> float:
382
- return self.memory_bytes() / (1024 * 1024)
383
-
384
- def summary(self) -> str:
385
- ee_max = self.entanglement_entropy.max() if len(self.entanglement_entropy) else 0.0
386
- return (
387
- f"MPSSimulator | n={self.n} | chi_max={self.chi} | "
388
- f"chi_used={self.max_bond_used()} | mem={self.memory_mb():.3f}MB | "
389
- f"trunc_err={self.total_truncation_error():.2e} | "
390
- f"avg_JSD={self.avg_jsd():.4f} | EE_max={ee_max:.3f}b | "
391
- f"budget_violations={self.budget_violations}"
392
- )
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ MPSSimulator - Matrix Product State statevector simulator, JAX-backed.
3
+
4
+ Ported from the "TurboQuant TUREQ MPSSimulator v8.2 MatryoshkaFlash"
5
+ prototype (private research notebook, never published as part of the
6
+ dense-evolution package). Two real bugs were found and fixed by
7
+ independent verification against DenseSVSimulator before this module
8
+ existed in its current form:
9
+
10
+ 1. The original applied Lloyd-Max quantization to the SVD singular
11
+ values on every truncation ("PolarQuantizer"). Measured a real ~0.5%
12
+ Total Variation Distance error against DenseSVSimulator on an
13
+ 8-qubit entangling test circuit, with ZERO bond-dimension savings to
14
+ show for it. Dropped entirely -- this module keeps only the plain
15
+ adaptive SVD truncation (JSD-budget-driven bond dimension, the
16
+ author's own stopping criterion -- standard SVD truncation,
17
+ non-standard stopping metric).
18
+
19
+ 2. get_top_k_probable_states (originally "_extract_top_k_paths") picked
20
+ a single "best" bond index via argmax at each step instead of
21
+ correctly summing over the bond dimension. Measured 0/8 correct
22
+ states against the exact contraction on the same test circuit,
23
+ values off by ~30x. Fixed by propagating the true partial-contraction
24
+ vector through each bond (matches exactly, to machine precision, on
25
+ every state it finds) -- but note it's a genuine greedy beam search,
26
+ not an exact top-k finder: recall of the true top states grows with
27
+ beam width k but isn't guaranteed complete for any fixed k.
28
+
29
+ Originally ported in plain numpy (matching the prototype), then
30
+ converted to jax.numpy so the core tensor contractions (einsum, SVD) run
31
+ on the same backend as the rest of dense_evolution instead of a second,
32
+ inconsistent numerics stack. Re-verified against DenseSVSimulator after
33
+ the conversion -- see test_mps.py.
34
+
35
+ Uses whatever jax_enable_x64 precision is currently active in the
36
+ process (does not toggle it itself) -- same convention as
37
+ DenseSVSimulator/Chunk, which rely on the caller (dashboard_core.py's
38
+ run_simulation) to set precision, since jax_enable_x64 is a process-wide
39
+ flag and toggling it locally would leak to unrelated code running later
40
+ in the same process.
41
+
42
+ For circuits with LOW entanglement (product states, GHZ/Bell-like chains,
43
+ shallow local circuits), the bond dimension stays small regardless of
44
+ qubit count, so this scales to hundreds of qubits where DenseSVSimulator
45
+ (or Chunk) cannot -- see get_probabilities_sampled and
46
+ get_top_k_probable_states, neither of which ever materializes a
47
+ (2**n,)-shaped array. For HIGHLY entangled circuits the bond dimension
48
+ grows and this degrades back toward the same exponential cost
49
+ DenseSVSimulator has -- it is not a universal replacement, it is
50
+ complementary.
51
+ """
52
+
53
+ import warnings
54
+ from typing import List, Optional, Tuple
55
+
56
+ import jax
57
+ import jax.numpy as jnp
58
+ import numpy as np
59
+
60
+
61
+ def _jsd_vectors(p: jnp.ndarray, q: jnp.ndarray) -> float:
62
+ """Adaptive Jensen-Shannon Distance used to size the truncated bond
63
+ dimension: scales with log10(dim) so the same JSD budget stays
64
+ meaningful whether the local Hilbert space is small or large."""
65
+ eps = 1e-12
66
+ p_norm = p / (jnp.sum(p) + eps)
67
+ q_norm = q / (jnp.sum(q) + eps)
68
+ m = 0.5 * (p_norm + q_norm)
69
+
70
+ def _kl(a, b):
71
+ mask = a > eps
72
+ # jnp.where still traces both branches, but log(0) only ever
73
+ # feeds into a term multiplied by 0 through the mask -- safe,
74
+ # and avoids a Python-side branch on a traced value.
75
+ safe_log = jnp.where(mask, jnp.log2(jnp.where(mask, a, 1.0) / (b + eps)), 0.0)
76
+ return jnp.sum(jnp.where(mask, a * safe_log, 0.0))
77
+
78
+ js = 0.5 * (_kl(p_norm, m) + _kl(q_norm, m))
79
+ dim_factor = float(np.log10(len(p)) / 2.0) if len(p) > 1 else 1.0
80
+ return float(jnp.sqrt(jnp.clip(js * dim_factor, 0.0, 1.0)))
81
+
82
+
83
+ class MPSSimulator:
84
+ """
85
+ Matrix Product State simulator with adaptive SVD-truncated bond
86
+ dimension (JSD-budget driven), no lossy post-truncation quantization.
87
+ JAX-backed core (einsum, SVD).
88
+
89
+ Parameters
90
+ ----------
91
+ n_qubits : int
92
+ max_bond : int -- hard cap on bond dimension chi
93
+ svd_cutoff : float -- singular values below this are dropped outright
94
+ jsd_budget : float -- max tolerated Jensen-Shannon distance between the
95
+ full and truncated singular-value distributions
96
+ at each cut; chi is grown by 1 until satisfied
97
+ or max_bond is hit.
98
+ """
99
+
100
+ def __init__(
101
+ self,
102
+ n_qubits: int,
103
+ max_bond: int = 64,
104
+ svd_cutoff: float = 1e-12,
105
+ jsd_budget: float = 1e-5,
106
+ ):
107
+ self.n = n_qubits
108
+ self.chi = max_bond
109
+ self.eps = svd_cutoff
110
+ self.jsd_budget = jsd_budget
111
+
112
+ self.gammas: List[jnp.ndarray] = []
113
+ self.lambdas: List[jnp.ndarray] = [jnp.ones(1)] * (n_qubits + 1)
114
+
115
+ self.truncation_errors: List[float] = []
116
+ self.jsd_per_bond: List[float] = []
117
+ self.entanglement_entropy = np.zeros(max(n_qubits - 1, 0))
118
+ self._bond_history: List[int] = []
119
+ # Counts truncations where max_bond was hit before jsd_budget could
120
+ # be satisfied -- the while loop below exits silently in that case,
121
+ # and avg_JSD (a mean over all steps) can look deceptively low even
122
+ # when the final contracted state is badly wrong (verified: TVD
123
+ # ~0.97 against DenseSVSimulator on an 8-qubit/15-layer entangling
124
+ # circuit with max_bond=2, while avg_JSD read 0.0534).
125
+ self.budget_violations: int = 0
126
+
127
+ for _ in range(n_qubits):
128
+ g = jnp.zeros((1, 2, 1), dtype=jnp.complex64 if not jax.config.jax_enable_x64 else jnp.complex128)
129
+ g = g.at[0, 0, 0].set(1.0)
130
+ self.gammas.append(g)
131
+
132
+ # gate 1q
133
+ def apply_gate_1q(self, gate: jnp.ndarray, qubit: int) -> None:
134
+ """O(chi^2) -- updates only Gamma[qubit]."""
135
+ gate = jnp.asarray(gate)
136
+ self.gammas[qubit] = jnp.einsum("ij,ljr->lir", gate, self.gammas[qubit])
137
+
138
+ # core: plain adaptive SVD truncation (no quantization)
139
+ def _svd_truncate(
140
+ self, theta_mat: jnp.ndarray
141
+ ) -> Tuple[jnp.ndarray, jnp.ndarray, jnp.ndarray, float, float]:
142
+ U, S, Vh = jnp.linalg.svd(theta_mat, full_matrices=False)
143
+
144
+ mask = S > self.eps
145
+ chi_new = max(1, min(int(jnp.sum(mask)), self.chi))
146
+ max_possible = min(len(S), self.chi)
147
+
148
+ norm_full = float(jnp.sum(S**2)) + 1e-15
149
+ p_full = (S**2) / norm_full
150
+
151
+ def _trunc_jsd(chi_try):
152
+ p_trunc = jnp.zeros_like(p_full)
153
+ p_trunc = p_trunc.at[:chi_try].set((S[:chi_try] ** 2) / norm_full)
154
+ return _jsd_vectors(p_full, p_trunc)
155
+
156
+ jsd_val = _trunc_jsd(chi_new)
157
+ while jsd_val > self.jsd_budget and chi_new < max_possible:
158
+ chi_new += 1
159
+ jsd_val = _trunc_jsd(chi_new)
160
+
161
+ if jsd_val > self.jsd_budget:
162
+ # Loop exited because chi_new hit max_possible (== max_bond, in
163
+ # the common case where the bond isn't already capped by the
164
+ # SVD's own rank), not because jsd_budget was satisfied.
165
+ if self.budget_violations == 0:
166
+ warnings.warn(
167
+ f"MPSSimulator: bond dimension capped at max_bond={self.chi}, "
168
+ f"jsd_budget={self.jsd_budget:.1e} not honored "
169
+ f"(jsd={jsd_val:.2e}) -- results may be unreliable, "
170
+ f"consider raising max_bond.",
171
+ UserWarning,
172
+ stacklevel=2,
173
+ )
174
+ self.budget_violations += 1
175
+
176
+ trunc_err = float(jnp.sqrt(jnp.sum(S[chi_new:] ** 2))) if len(S) > chi_new else 0.0
177
+ self.truncation_errors.append(trunc_err)
178
+
179
+ return U[:, :chi_new], S[:chi_new], Vh[:chi_new, :], trunc_err, jsd_val
180
+
181
+ # gate 2q adjacent
182
+ def apply_gate_2q(self, gate_2q: jnp.ndarray, q1: int, q2: int) -> None:
183
+ """2-qubit gate with adaptive SVD truncation. O(chi^3)."""
184
+ gate_2q = jnp.asarray(gate_2q)
185
+ if abs(q1 - q2) != 1:
186
+ self._apply_nonlocal_2q(gate_2q, q1, q2)
187
+ return
188
+ if q1 > q2:
189
+ q1, q2 = q2, q1
190
+ gate_2q = jnp.transpose(gate_2q, (1, 0, 3, 2))
191
+
192
+ g1 = self.gammas[q1]
193
+ g2 = self.gammas[q2]
194
+ lam = self.lambdas[q2]
195
+
196
+ theta = jnp.einsum("lik,k,kjr->lijr", g1, lam, g2)
197
+ chiL, d1, d2, chiR = theta.shape
198
+
199
+ theta_new = jnp.einsum("abcd,ecdf->eabf", gate_2q, theta)
200
+ theta_mat = theta_new.reshape(chiL * d1, d2 * chiR)
201
+
202
+ U_t, S_t, Vh_t, trunc_err, jsd_val = self._svd_truncate(theta_mat)
203
+ chi_new = len(S_t)
204
+
205
+ s_sq = S_t**2
206
+ p_dist = s_sq / (jnp.sum(s_sq) + 1e-20)
207
+ p_v = p_dist[p_dist > 1e-20]
208
+ ee = float(-jnp.sum(p_v * jnp.log2(p_v))) if len(p_v) > 1 else 0.0
209
+ if q1 < len(self.entanglement_entropy):
210
+ self.entanglement_entropy[q1] = ee
211
+
212
+ self.lambdas[q2] = S_t
213
+ self.gammas[q1] = U_t.reshape(chiL, d1, chi_new)
214
+ self.gammas[q2] = Vh_t.reshape(chi_new, d2, chiR)
215
+
216
+ self._bond_history.append(chi_new)
217
+ self.jsd_per_bond.append(jsd_val)
218
+
219
+ def _apply_nonlocal_2q(self, gate_2q: jnp.ndarray, q1: int, q2: int) -> None:
220
+ """Non-adjacent 2-qubit gate via a SWAP chain down to adjacent.
221
+
222
+ The SWAP chain always ends up applying the gate at (target, target+1)
223
+ with target = min(q1, q2) first -- so without normalizing here, a
224
+ caller passing q1 > q2 (e.g. apply_cx(ctrl=3, tgt=1)) would silently
225
+ have its control/target roles swapped for asymmetric gates like CNOT.
226
+ Same fix as apply_gate_2q's adjacent-qubit branch just above, applied
227
+ before the swap chain runs so it always sees q1 < q2."""
228
+ if q1 > q2:
229
+ q1, q2 = q2, q1
230
+ gate_2q = jnp.transpose(gate_2q, (1, 0, 3, 2))
231
+ swap = jnp.array(
232
+ [[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]], dtype=complex
233
+ ).reshape(2, 2, 2, 2)
234
+ target = min(q1, q2)
235
+ for q in range(max(q1, q2) - 1, target, -1):
236
+ self.apply_gate_2q(swap, q, q + 1)
237
+ self.apply_gate_2q(gate_2q, target, target + 1)
238
+ for q in range(target + 1, max(q1, q2)):
239
+ self.apply_gate_2q(swap, q, q + 1)
240
+
241
+ # gate shortcuts
242
+ def apply_cx(self, ctrl: int, tgt: int) -> None:
243
+ cx = jnp.array(
244
+ [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]], dtype=complex
245
+ ).reshape(2, 2, 2, 2)
246
+ self.apply_gate_2q(cx, ctrl, tgt)
247
+
248
+ def apply_cz(self, ctrl: int, tgt: int) -> None:
249
+ cz = jnp.diag(jnp.array([1, 1, 1, -1])).astype(complex).reshape(2, 2, 2, 2)
250
+ self.apply_gate_2q(cz, ctrl, tgt)
251
+
252
+ def apply_swap(self, q1: int, q2: int) -> None:
253
+ sw = jnp.array(
254
+ [[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]], dtype=complex
255
+ ).reshape(2, 2, 2, 2)
256
+ self.apply_gate_2q(sw, q1, q2)
257
+
258
+ def apply_ccx(self, c1: int, c2: int, tgt: int) -> None:
259
+ """Toffoli via standard T-gate decomposition (all 1q/2q gates)."""
260
+ inv2 = 1.0 / np.sqrt(2.0)
261
+ h = inv2 * jnp.array([[1, 1], [1, -1]], dtype=complex)
262
+ t = jnp.array([[1, 0], [0, jnp.exp(1j * jnp.pi / 4)]], dtype=complex)
263
+ tdg = jnp.array([[1, 0], [0, jnp.exp(-1j * jnp.pi / 4)]], dtype=complex)
264
+
265
+ self.apply_gate_1q(h, tgt)
266
+ self.apply_cx(c2, tgt)
267
+ self.apply_gate_1q(tdg, tgt)
268
+ self.apply_cx(c1, tgt)
269
+ self.apply_gate_1q(t, tgt)
270
+ self.apply_cx(c2, tgt)
271
+ self.apply_gate_1q(tdg, tgt)
272
+ self.apply_cx(c1, tgt)
273
+ self.apply_gate_1q(t, c2)
274
+ self.apply_gate_1q(t, tgt)
275
+ self.apply_gate_1q(h, tgt)
276
+ self.apply_cx(c1, c2)
277
+ self.apply_gate_1q(t, c1)
278
+ self.apply_gate_1q(tdg, c2)
279
+ self.apply_cx(c1, c2)
280
+
281
+ # contraction to a full statevector -- O(2**n), n <= ~24 only
282
+ def contract_to_statevector(self) -> jnp.ndarray:
283
+ if self.n > 24:
284
+ raise MemoryError(
285
+ f"contract_to_statevector at {self.n} qubits would need "
286
+ f"~{2**self.n * 16 / 1e9:.1f} GB -- use "
287
+ f"get_probabilities_sampled or get_top_k_probable_states "
288
+ f"instead for n > 24."
289
+ )
290
+ result = self.gammas[0].squeeze(axis=0)
291
+ for i in range(1, self.n):
292
+ lam = self.lambdas[i]
293
+ g = self.gammas[i]
294
+ lg = jnp.einsum("k,kir->kir", lam, g)
295
+ result = jnp.tensordot(result, lg, axes=([-1], [0]))
296
+ result = result.reshape(-1, result.shape[-1])
297
+ sv = result.squeeze(axis=-1)
298
+ norm = jnp.linalg.norm(sv)
299
+ return sv / (norm + 1e-15)
300
+
301
+ # sequential sampling -- O(chi^2) per qubit per sample, never
302
+ # materializes a (2**n,) array. The only way to get results for
303
+ # n_qubits beyond ~24. Sampling decisions themselves stay on host
304
+ # (np.random.Generator): each step needs a concrete probability to
305
+ # branch on, not a traced value, so this loop isn't a jax.jit
306
+ # candidate as a whole regardless of backend.
307
+ def _sample_bitstring(self, rng: np.random.Generator) -> List[int]:
308
+ bits = []
309
+ state = jnp.ones(1, dtype=complex)
310
+ for i in range(self.n):
311
+ g = self.gammas[i]
312
+ lam = self.lambdas[i + 1] if i < self.n - 1 else jnp.ones(g.shape[2])
313
+ p0v = jnp.einsum("l,lr->r", state, g[:, 0, :])
314
+ p1v = jnp.einsum("l,lr->r", state, g[:, 1, :])
315
+ p0l = p0v * lam
316
+ p1l = p1v * lam
317
+ p0 = float(jnp.real(jnp.dot(p0l, jnp.conj(p0l))))
318
+ p1 = float(jnp.real(jnp.dot(p1l, jnp.conj(p1l))))
319
+ norm = p0 + p1 + 1e-15
320
+ bit = 0 if rng.random() < p0 / norm else 1
321
+ bits.append(bit)
322
+ state = p0l if bit == 0 else p1l
323
+ state = state / (jnp.linalg.norm(state) + 1e-15)
324
+ return bits
325
+
326
+ def get_probabilities_sampled(
327
+ self, n_samples: int = 100_000, seed: Optional[int] = None
328
+ ) -> dict:
329
+ """Returns a {bitstring: empirical_probability} dict from n_samples
330
+ sequential draws -- the only entry point safe for n_qubits > 24."""
331
+ from collections import Counter
332
+
333
+ rng = np.random.default_rng(seed)
334
+ counts: Counter = Counter()
335
+ for _ in range(n_samples):
336
+ bits = self._sample_bitstring(rng)
337
+ counts["".join(map(str, bits))] += 1
338
+ return {bitstr: c / n_samples for bitstr, c in counts.items()}
339
+
340
+ # ──────────────────────────────────────────────
341
+ # approximate top-k extraction -- see module docstring point 2.
342
+ # ──────────────────────────────────────────────
343
+ def get_top_k_probable_states(self, k: int = 128) -> Tuple[np.ndarray, np.ndarray]:
344
+ """Greedy beam search (beam width k) for approximately-most-probable
345
+ basis states, without ever contracting to a full statevector.
346
+
347
+ Returns (indices, probabilities): indices are computational-basis
348
+ integers, probabilities are exact for the states found (not
349
+ approximated), sorted descending. Recall of the TRUE top states
350
+ improves with k but is not guaranteed for any fixed k -- see the
351
+ module docstring."""
352
+ paths: List[Tuple[int, jnp.ndarray]] = [(0, jnp.array([1.0 + 0.0j]))]
353
+ for i in range(self.n):
354
+ candidates = []
355
+ gamma = self.gammas[i]
356
+ lam = self.lambdas[i + 1] if (i + 1) < len(self.lambdas) else jnp.ones(gamma.shape[2])
357
+ for idx_p, vec_p in paths:
358
+ for bit in (0, 1):
359
+ new_vec = jnp.einsum("l,lr->r", vec_p, gamma[:, bit, :]) * lam
360
+ weight = float(jnp.sum(jnp.abs(new_vec) ** 2))
361
+ candidates.append(((idx_p << 1) | bit, new_vec, weight))
362
+ candidates.sort(key=lambda c: c[2], reverse=True)
363
+ paths = [(idx, vec) for idx, vec, _ in candidates[:k]]
364
+
365
+ indices = np.array([p[0] for p in paths])
366
+ amplitudes = np.array([
367
+ complex(vec[0]) if len(vec) == 1 else complex(jnp.sum(vec))
368
+ for _, vec in paths
369
+ ])
370
+ probabilities = np.abs(amplitudes) ** 2
371
+ order = np.argsort(-probabilities)
372
+ return indices[order], probabilities[order]
373
+
374
+ # metrics
375
+ def max_bond_used(self) -> int:
376
+ return max(self._bond_history) if self._bond_history else 1
377
+
378
+ def total_truncation_error(self) -> float:
379
+ if not self.truncation_errors:
380
+ return 0.0
381
+ return float(np.sqrt(np.sum(np.array(self.truncation_errors) ** 2)))
382
+
383
+ def avg_jsd(self) -> float:
384
+ return float(np.mean(self.jsd_per_bond)) if self.jsd_per_bond else 0.0
385
+
386
+ def memory_bytes(self) -> int:
387
+ bytes_gammas = sum(g.size * g.dtype.itemsize for g in self.gammas)
388
+ bytes_lambdas = sum(l.size * l.dtype.itemsize for l in self.lambdas)
389
+ return int(bytes_gammas + bytes_lambdas)
390
+
391
+ def memory_mb(self) -> float:
392
+ return self.memory_bytes() / (1024 * 1024)
393
+
394
+ def summary(self) -> str:
395
+ ee_max = self.entanglement_entropy.max() if len(self.entanglement_entropy) else 0.0
396
+ return (
397
+ f"MPSSimulator | n={self.n} | chi_max={self.chi} | "
398
+ f"chi_used={self.max_bond_used()} | mem={self.memory_mb():.3f}MB | "
399
+ f"trunc_err={self.total_truncation_error():.2e} | "
400
+ f"avg_JSD={self.avg_jsd():.4f} | EE_max={ee_max:.3f}b | "
401
+ f"budget_violations={self.budget_violations}"
402
+ )
dense_evolution/registry.py CHANGED
@@ -96,6 +96,62 @@ def _qubit_index_pairs(dim: int, q: int):
96
  return idx_0, idx_1
97
 
98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  # ─────────────────────────────────────────────────────────────────────────────
100
  # NoiseModel
101
  # ─────────────────────────────────────────────────────────────────────────────
@@ -144,29 +200,59 @@ class NoiseModel:
144
  n : number of qubits
145
  model : one of NoiseModel.MODELS
146
  p : error probability (or damping rate Ξ³ for amplitude_damping)
147
- rng : optional pre-seeded numpy Generator; created fresh if None
 
 
 
 
 
 
 
 
148
  qubits : subset of qubits to apply the channel to; defaults to all
149
- jax_key : optional JAX PRNGKey; created fresh if None and sv is a JAX array
 
 
 
150
 
151
  Returns
152
  -------
153
  Normalised statevector (same array type as input).
154
  """
155
- if model == 'ideal' or p <= 0.0:
156
  return sv
 
 
 
 
 
 
 
 
 
 
 
157
 
158
  is_jax = HAS_JAX and isinstance(sv, jnp.ndarray)
159
  dim = len(sv)
160
 
161
  # ── RNG initialisation ────────────────────────────────────────
162
  if is_jax:
163
- if jax_key is None:
 
 
 
 
 
 
 
 
 
 
164
  seed_bytes = os.urandom(4)
165
  jax_seed = int.from_bytes(seed_bytes, byteorder='big')
166
  jax_seed ^= time.perf_counter_ns() & 0xFFFF_FFFF
167
  key = jax.random.PRNGKey(jax_seed)
168
- else:
169
- key = jax_key
170
  else:
171
  if rng is None:
172
  rng = _fresh_rng()
 
96
  return idx_0, idx_1
97
 
98
 
99
+ # ─────────────────────────────────────────────────────────────────────────────
100
+ # NoiseSpec β€” JAX PyTree wrapper for NoiseModel.apply_to_sv's parameters
101
+ # ─────────────────────────────────────────────────────────────────────────────
102
+
103
+ class NoiseSpec:
104
+ """JAX PyTree wrapper around a NoiseModel configuration, so noise
105
+ parameters can be threaded through jax.jit/jax.grad/jax.vmap natively
106
+ -- e.g. as the `noise=` argument to circuit_to_energy_fn's energy_fn
107
+ -- instead of being applied as an external, Python-side step around
108
+ the already-traced circuit (the old way: build sv, exit the trace,
109
+ call apply_to_sv separately).
110
+
111
+ `model`/`qubits` are static (aux_data): they select which code path
112
+ runs, not values to differentiate or batch over -- the same role
113
+ `static_argnames` plays for a plain jax.jit function, but automatic
114
+ here because it's part of the pytree structure. `p`/`jax_key` are
115
+ pytree leaves (children): `p` can be a traced/differentiable value
116
+ (e.g. optimizing noise strength itself), and `jax_key` flows through
117
+ jit/vmap/scan the way any other JAX array does -- no external
118
+ Python-level key management, no OS-entropy fallback (unlike
119
+ apply_to_sv called standalone with jax_key=None), so a NoiseSpec's
120
+ result is always reproducible from the key it was built with.
121
+
122
+ `jax_key` is required (not Optional) -- the whole point of wiring
123
+ noise into the traced computation this way is to remove the need for
124
+ an external, ad-hoc key-management workaround; a caller who wants a
125
+ fresh key per call should split one themselves (`jax.random.split`)
126
+ and build a fresh NoiseSpec, the same as any other JAX-idiomatic
127
+ stateless-key pattern.
128
+ """
129
+ def __init__(self, model: str, p, jax_key, qubits: Optional[List[int]] = None):
130
+ self.model = model
131
+ self.p = p
132
+ self.jax_key = jax_key
133
+ self.qubits = tuple(qubits) if qubits is not None else None
134
+
135
+ def __repr__(self):
136
+ return f"NoiseSpec(model={self.model!r}, p={self.p!r}, qubits={self.qubits!r})"
137
+
138
+ def tree_flatten(self):
139
+ children = (self.p, self.jax_key)
140
+ aux_data = (self.model, self.qubits)
141
+ return children, aux_data
142
+
143
+ @classmethod
144
+ def tree_unflatten(cls, aux_data, children):
145
+ model, qubits = aux_data
146
+ p, jax_key = children
147
+ return cls(model, p, jax_key, qubits)
148
+
149
+
150
+ jax.tree_util.register_pytree_node(
151
+ NoiseSpec, NoiseSpec.tree_flatten, NoiseSpec.tree_unflatten
152
+ )
153
+
154
+
155
  # ─────────────────────────────────────────────────────────────────────────────
156
  # NoiseModel
157
  # ─────────────────────────────────────────────────────────────────────────────
 
200
  n : number of qubits
201
  model : one of NoiseModel.MODELS
202
  p : error probability (or damping rate Ξ³ for amplitude_damping)
203
+ rng : optional pre-seeded numpy Generator. Used directly when
204
+ *sv* is a NumPy array. When *sv* is a JAX array, `rng`
205
+ used to be silently ignored in favor of `jax_key` (or a
206
+ non-reproducible OS-entropy key if that was also None
207
+ -- issue #7); it is now used to *derive* a reproducible
208
+ jax_key (`rng.integers(...)` seeds `jax.random.PRNGKey`)
209
+ whenever `jax_key` isn't given explicitly, so seeding
210
+ `rng` has the effect a caller expects on both array
211
+ types instead of only on one of them.
212
  qubits : subset of qubits to apply the channel to; defaults to all
213
+ jax_key : optional JAX PRNGKey, only meaningful when *sv* is a JAX
214
+ array. Takes precedence over `rng` when both are given
215
+ (explicit key beats a derived one). Created from OS
216
+ entropy if neither `jax_key` nor `rng` is given.
217
 
218
  Returns
219
  -------
220
  Normalised statevector (same array type as input).
221
  """
222
+ if model == 'ideal':
223
  return sv
224
+ try:
225
+ if p <= 0.0:
226
+ return sv
227
+ except jax.errors.TracerBoolConversionError:
228
+ # p is a traced value (e.g. flowing through jax.jit/vmap/grad
229
+ # as a NoiseSpec pytree leaf) -- can't early-exit on a Python
230
+ # bool of it. Falling through is still correct: every channel
231
+ # below already reduces to a no-op at p=0 (`fire = r < p` is
232
+ # always False), this skips only the eager-mode optimization,
233
+ # not correctness.
234
+ pass
235
 
236
  is_jax = HAS_JAX and isinstance(sv, jnp.ndarray)
237
  dim = len(sv)
238
 
239
  # ── RNG initialisation ────────────────────────────────────────
240
  if is_jax:
241
+ if jax_key is not None:
242
+ key = jax_key
243
+ elif rng is not None:
244
+ # Derive a reproducible JAX key from the caller's seeded
245
+ # NumPy generator instead of silently ignoring it -- each
246
+ # call advances `rng`'s state, so a fresh, identically-
247
+ # seeded `rng` reproduces the exact same sequence of keys
248
+ # across separate runs (same guarantee the NumPy path
249
+ # already gives).
250
+ key = jax.random.PRNGKey(int(rng.integers(0, 2**32 - 1)))
251
+ else:
252
  seed_bytes = os.urandom(4)
253
  jax_seed = int.from_bytes(seed_bytes, byteorder='big')
254
  jax_seed ^= time.perf_counter_ns() & 0xFFFF_FFFF
255
  key = jax.random.PRNGKey(jax_seed)
 
 
256
  else:
257
  if rng is None:
258
  rng = _fresh_rng()
dense_evolution/simulator.py CHANGED
@@ -1,505 +1,532 @@
1
- import numpy as np
2
- from typing import List, Tuple, Optional
3
- from .registry import HAS_JAX
4
- from .gates import GATES, PARAMETRIC_GATES, GATE_IDS
5
- from .compiler import QuantumTranspiler
6
-
7
- if HAS_JAX:
8
- import jax
9
- import jax.numpy as jnp
10
- jax.config.update("jax_enable_x64", True)
11
- from .compiler import _compile_and_run_circuit_jit, _compile_and_run_circuit_jit_donated
12
-
13
-
14
- # ─────────────────────────────────────────────────────────────────────────────
15
- # Internal helpers
16
- # ─────────────────────────────────────────────────────────────────────────────
17
-
18
- def _qubit_stride_pairs(n: int, qubit: int):
19
- """
20
- Return (stride, outer_step, inner_step) for the MSB-first statevector
21
- convention used throughout this simulator.
22
-
23
- In MSB-first ordering qubit 0 is the *most* significant bit, so:
24
- physical_bit_position = n - 1 - qubit
25
- stride = 1 << physical_bit_position
26
- """
27
- phys = n - 1 - qubit
28
- stride = 1 << phys
29
- return stride
30
-
31
-
32
- def _cx_numpy(sv: np.ndarray, n: int, ctrl: int, tgt: int) -> np.ndarray:
33
- """
34
- Vectorised CX on a NumPy statevector.
35
- No Python loops β€” uses strided index arithmetic.
36
- """
37
- dim = len(sv)
38
- c_stride = 1 << (n - 1 - ctrl)
39
- t_stride = 1 << (n - 1 - tgt)
40
- all_i = np.arange(dim, dtype=np.intp)
41
- # Select indices where ctrl bit == 1 and tgt bit == 0
42
- mask = ((all_i & c_stride) != 0) & ((all_i & t_stride) == 0)
43
- idx_0 = all_i[mask]
44
- idx_1 = idx_0 | t_stride
45
- sv = sv.copy()
46
- sv[idx_0], sv[idx_1] = sv[idx_1].copy(), sv[idx_0].copy()
47
- return sv
48
-
49
-
50
- def _cz_numpy(sv: np.ndarray, n: int, ctrl: int, tgt: int) -> np.ndarray:
51
- """Vectorised CZ on a NumPy statevector."""
52
- dim = len(sv)
53
- c_stride = 1 << (n - 1 - ctrl)
54
- t_stride = 1 << (n - 1 - tgt)
55
- all_i = np.arange(dim, dtype=np.intp)
56
- mask = ((all_i & c_stride) != 0) & ((all_i & t_stride) != 0)
57
- sv = sv.copy()
58
- sv[mask] *= -1
59
- return sv
60
-
61
-
62
- # ─────────────────────────────────────────────────────────────────────────────
63
- # DenseSVSimulator
64
- # ─────────────────────────────────────────────────────────────────────────────
65
-
66
- class DenseSVSimulator:
67
- """
68
- Dense statevector quantum circuit simulator.
69
-
70
- Qubit ordering: MSB-first (qubit 0 is the most significant bit).
71
- Backends: NumPy (CPU), JAX XLA JIT (CPU/GPU/TPU).
72
-
73
- Parameters
74
- ----------
75
- n_qubits : number of qubits
76
- use_gpu : reserved for future CuPy/JAX GPU dispatch
77
- use_float32: use complex64 instead of complex128
78
- """
79
-
80
- def __init__(self, n_qubits: int,
81
- use_gpu: bool = False,
82
- use_float32: bool = False):
83
- if n_qubits < 1 or n_qubits > 34:
84
- raise ValueError(f"n_qubits must be in [1, 34], got {n_qubits}")
85
- self.n = n_qubits
86
- self.dim = 1 << n_qubits # 2 ** n_qubits
87
- self.use_float32 = use_float32
88
- self.dtype = np.complex64 if use_float32 else np.complex128
89
- self.xp = jnp if HAS_JAX else np
90
- self._reset_sv()
91
-
92
- # ── state initialisation ─────────────────────────────────────────
93
-
94
- def _reset_sv(self):
95
- """Allocate |0...0⟩ on the active backend."""
96
- if HAS_JAX:
97
- self.sv = jnp.zeros(self.dim, dtype=self.dtype).at[0].set(1.0)
98
- else:
99
- self.sv = np.zeros(self.dim, dtype=self.dtype)
100
- self.sv[0] = 1.0
101
-
102
- def set_initial_state(self, state: Optional[np.ndarray] = None):
103
- """
104
- Reset the simulator.
105
-
106
- Parameters
107
- ----------
108
- state : optional complex array of length 2**n.
109
- If None, resets to |0...0⟩.
110
- The array is normalised automatically.
111
- """
112
- if state is None:
113
- self._reset_sv()
114
- return
115
- state = np.asarray(state, dtype=self.dtype)
116
- if state.shape != (self.dim,):
117
- raise ValueError(
118
- f"State vector length {len(state)} != 2**{self.n} = {self.dim}")
119
- norm = np.linalg.norm(state)
120
- if norm < 1e-12:
121
- raise ValueError("Cannot set a zero-norm state vector")
122
- state = state / norm
123
- if HAS_JAX:
124
- self.sv = jnp.array(state)
125
- else:
126
- self.sv = state.copy()
127
-
128
- # Alias used by the VQE engine
129
- def set_state(self, state: np.ndarray):
130
- self.set_initial_state(state)
131
-
132
- # ── normalisation ─────────────────────────────────────────────────
133
-
134
- def normalize(self):
135
- norm = float(self.xp.linalg.norm(self.sv))
136
- if norm > 1e-12:
137
- if HAS_JAX:
138
- self.sv = self.sv / norm
139
- else:
140
- self.sv /= norm
141
-
142
- def _check_qubit_range(self, qubit: float, context: str) -> None:
143
- """Validate a qubit index before it reaches the JIT-compiled fast
144
- paths (run_circuit_jit_beast_mode / run_parametric_batch_jit).
145
-
146
- Those paths encode qubit indices as bit-shift amounts inside
147
- jax.lax.scan/switch and never call apply_gate_1q/apply_gate_2q
148
- (which already validate) β€” an out-of-range index there doesn't
149
- raise, it silently corrupts the entire statevector to zero
150
- (verified: a single gate on an out-of-range qubit on an otherwise
151
- normalized state left get_probabilities().sum() == 0.0, no error).
152
- """
153
- qi = int(qubit)
154
- if not 0 <= qi < self.n:
155
- raise ValueError(
156
- f"Qubit index {qi} out of range [0, {self.n}) in {context}")
157
-
158
- # ── 1-qubit gate ──────────────────────────────────────────────────
159
-
160
- def apply_gate_1q(self, gate: np.ndarray, qubit: int):
161
- """
162
- Apply a 2Γ—2 unitary to *qubit* via tensor contraction.
163
-
164
- Uses reshape + moveaxis + matmul β€” fully vectorised,
165
- no Python loops, compatible with both NumPy and JAX.
166
- """
167
- if not 0 <= qubit < self.n:
168
- raise ValueError(f"Qubit index {qubit} out of range [0, {self.n})")
169
- gate = self.xp.array(gate, dtype=self.dtype)
170
- sv_nd = self.sv.reshape([2] * self.n)
171
- sv_moved = self.xp.moveaxis(sv_nd, qubit, -1) # qubit axis β†’ last
172
- flat_shape = (self.dim >> 1, 2)
173
- # matmul: (dim/2, 2) @ (2, 2).T β†’ (dim/2, 2)
174
- result = self.xp.dot(sv_moved.reshape(flat_shape),
175
- gate.T)
176
- self.sv = self.xp.moveaxis(
177
- result.reshape([2] * self.n), -1, qubit).ravel()
178
-
179
- # ── 2-qubit gate ──────────────────────────────────────────────────
180
-
181
- def apply_gate_2q(self, gate: np.ndarray, q1: int, q2: int):
182
- """
183
- Apply a 4Γ—4 unitary to qubits (q1, q2) via tensor contraction.
184
- """
185
- if q1 == q2:
186
- raise ValueError("Control and target qubits must differ")
187
- if not (0 <= q1 < self.n and 0 <= q2 < self.n):
188
- raise ValueError(f"Qubit indices ({q1},{q2}) out of range [0, {self.n})")
189
- gate = self.xp.array(gate, dtype=self.dtype)
190
- sv_nd = self.sv.reshape([2] * self.n)
191
- sv_moved = self.xp.moveaxis(sv_nd, (q1, q2), (-2, -1))
192
- flat_shape = (self.dim >> 2, 4)
193
- result = self.xp.dot(sv_moved.reshape(flat_shape),
194
- gate.reshape(4, 4).T)
195
- self.sv = self.xp.moveaxis(
196
- result.reshape([2] * self.n), (-2, -1), (q1, q2)).ravel()
197
-
198
- # ── specialised 2-qubit gates ─────────────────────────────────────
199
-
200
- def apply_cx(self, ctrl: int, tgt: int):
201
- """
202
- CX (CNOT) gate.
203
-
204
- JAX path: matrix contraction via apply_gate_2q.
205
- NumPy path: fully vectorised index swap β€” no Python loops.
206
- """
207
- if ctrl == tgt:
208
- raise ValueError("Control and target qubits must differ")
209
- if not (0 <= ctrl < self.n and 0 <= tgt < self.n):
210
- raise ValueError(f"Qubit indices ({ctrl},{tgt}) out of range [0, {self.n})")
211
- if HAS_JAX:
212
- cx_mat = jnp.array([
213
- [1, 0, 0, 0],
214
- [0, 1, 0, 0],
215
- [0, 0, 0, 1],
216
- [0, 0, 1, 0],
217
- ], dtype=self.dtype)
218
- self.apply_gate_2q(cx_mat, ctrl, tgt)
219
- else:
220
- self.sv = _cx_numpy(np.array(self.sv), self.n, ctrl, tgt)
221
-
222
- def apply_cz(self, ctrl: int, tgt: int):
223
- """
224
- CZ gate.
225
-
226
- JAX path: matrix contraction via apply_gate_2q.
227
- NumPy path: fully vectorised sign flip β€” no Python loops.
228
- """
229
- if ctrl == tgt:
230
- raise ValueError("Control and target qubits must differ")
231
- if not (0 <= ctrl < self.n and 0 <= tgt < self.n):
232
- raise ValueError(f"Qubit indices ({ctrl},{tgt}) out of range [0, {self.n})")
233
- if HAS_JAX:
234
- cz_mat = jnp.array([
235
- [1, 0, 0, 0],
236
- [0, 1, 0, 0],
237
- [0, 0, 1, 0],
238
- [0, 0, 0, -1],
239
- ], dtype=self.dtype)
240
- self.apply_gate_2q(cz_mat, ctrl, tgt)
241
- else:
242
- self.sv = _cz_numpy(np.array(self.sv), self.n, ctrl, tgt)
243
-
244
- def apply_rx(self, qubit: int, theta: float):
245
- """Apply a parameterized RX gate using the active backend (NumPy/JAX)."""
246
- cos, sin = self.xp.cos(theta / 2), self.xp.sin(theta / 2)
247
- mat = self.xp.array([[cos, -1j * sin], [-1j * sin, cos]], dtype=self.dtype)
248
- self.apply_gate_1q(mat, qubit)
249
-
250
- def apply_ry(self, qubit: int, theta: float):
251
- """Apply a parameterized RY gate using the active backend (NumPy/JAX)."""
252
- cos, sin = self.xp.cos(theta / 2), self.xp.sin(theta / 2)
253
- mat = self.xp.array([[cos, -sin], [sin, cos]], dtype=self.dtype)
254
- self.apply_gate_1q(mat, qubit)
255
-
256
- def apply_rz(self, qubit: int, theta: float):
257
- """Apply a parameterized RZ gate using the active backend (NumPy/JAX)."""
258
- exp_neg = self.xp.exp(-1j * theta / 2)
259
- exp_pos = self.xp.exp(1j * theta / 2)
260
- mat = self.xp.array([[exp_neg, 0.0], [0.0, exp_pos]], dtype=self.dtype)
261
- self.apply_gate_1q(mat, qubit)
262
-
263
- # ── measurement ───────────────────────────────────────────────────
264
-
265
- def measure(self, qubit_idx: int) -> int:
266
- """
267
- Projective measurement on *qubit_idx*.
268
-
269
- Returns 0 or 1 and collapses the statevector.
270
- Uses MSB-first physical bit index: phys = n - 1 - qubit_idx.
271
-
272
- BUG FIX (original): the original NumPy collapse wrote
273
- sv_reshaped[:, 1 if result == 0 else 0, :] = 0.0
274
- which zeroed the *wrong* basis state (0 when result=1, 1 when result=0)
275
- and never normalised the JAX path.
276
- """
277
- if not 0 <= qubit_idx < self.n:
278
- raise ValueError(
279
- f"Qubit {qubit_idx} out of range [0, {self.n})")
280
-
281
- phys = self.n - 1 - qubit_idx
282
- stride = 1 << phys
283
-
284
- # ── compute marginal probabilities ──────────────────────────
285
- if HAS_JAX:
286
- probs = jnp.abs(self.sv) ** 2
287
- sv_nd = probs.reshape([2] * self.n)
288
- mv = jnp.moveaxis(sv_nd, phys, 0)
289
- prob_0 = float(jnp.sum(mv[0]))
290
- prob_1 = float(jnp.sum(mv[1]))
291
- else:
292
- sv_res = self.sv.reshape(-1, 2, stride)
293
- prob_0 = float(np.sum(np.abs(sv_res[:, 0, :]) ** 2))
294
- prob_1 = float(np.sum(np.abs(sv_res[:, 1, :]) ** 2))
295
-
296
- total = prob_0 + prob_1
297
- if total < 1e-12:
298
- raise RuntimeError("Statevector norm is zero β€” cannot measure")
299
- prob_0 /= total
300
- prob_1 /= total
301
-
302
- result = int(np.random.choice([0, 1], p=[prob_0, prob_1]))
303
-
304
- # ── collapse ────────────────────────────────────────────────
305
- # Zero out the amplitudes corresponding to the *opposite* outcome.
306
- zero_slot = 1 - result # if result=0, zero slot 1; if result=1, zero slot 0
307
-
308
- if HAS_JAX:
309
- sv_nd = self.sv.reshape([2] * self.n)
310
- mv = jnp.moveaxis(sv_nd, phys, 0)
311
- mv = mv.at[zero_slot].set(0.0 + 0j)
312
- self.sv = jnp.moveaxis(mv, 0, phys).ravel()
313
- else:
314
- sv_res = self.sv.reshape(-1, 2, stride)
315
- sv_res[:, zero_slot, :] = 0.0
316
- self.sv = sv_res.ravel()
317
-
318
- self.normalize()
319
- return result
320
-
321
- # ── circuit execution ─────────────────────────────────────────────
322
-
323
- def run_circuit(self, circuit: List[Tuple], transpile: bool = True):
324
- target = QuantumTranspiler.transpile(circuit) if transpile else circuit
325
- for cmd in target:
326
- name = cmd[0].lower()
327
- args = cmd[1:]
328
-
329
- if name in GATES:
330
- mat = self.xp.array(GATES[name], dtype=self.dtype)
331
- if mat.shape == (2, 2):
332
- self.apply_gate_1q(mat, int(args[0]))
333
- else:
334
- self.apply_gate_2q(mat, int(args[0]), int(args[1]))
335
-
336
- elif name in PARAMETRIC_GATES:
337
- if len(args) == 2:
338
- mat = self.xp.array(PARAMETRIC_GATES[name](args[1]), dtype=self.dtype)
339
- self.apply_gate_1q(mat, int(args[0]))
340
- elif len(args) == 3:
341
- mat = self.xp.array(PARAMETRIC_GATES[name](args[2]), dtype=self.dtype)
342
- self.apply_gate_2q(mat, int(args[0]), int(args[1]))
343
- elif len(args) == 4:
344
- mat = self.xp.array(
345
- PARAMETRIC_GATES[name](args[1], args[2], args[3]),
346
- dtype=self.dtype)
347
- self.apply_gate_1q(mat, int(args[0]))
348
-
349
-
350
-
351
- def run_circuit_jit_beast_mode(self, circuit: List):
352
-
353
- if not HAS_JAX:
354
- return self.run_circuit(circuit)
355
-
356
- target = QuantumTranspiler.transpile(circuit)
357
- compiled_ops = []
358
-
359
- for cmd in target:
360
- name = cmd[0].lower() if isinstance(cmd[0], str) else str(cmd[0]).lower()
361
- if name not in GATE_IDS:
362
- continue
363
-
364
- g_id = float(GATE_IDS[name])
365
- args = cmd[1:]
366
-
367
- # ── gate argument parsing ──────────────────────────────
368
- # 1-qubit parametric: (name, qubit, param)
369
- if name in ('rx', 'ry', 'rz', 'p', 'u1', 'phase'):
370
- q1 = float(args[0])
371
- self._check_qubit_range(q1, f"gate '{name}'")
372
- p = float(args[1]) if len(args) > 1 else 0.0
373
- compiled_ops.append([g_id, q1, 0.0, p])
374
-
375
- # 2-qubit parametric: (name, ctrl, tgt, param)
376
- elif name in ('cp', 'crz', 'cphase'):
377
- ctrl = float(args[0])
378
- tgt = float(args[1]) if len(args) > 1 else 0.0
379
- self._check_qubit_range(ctrl, f"gate '{name}' (control)")
380
- self._check_qubit_range(tgt, f"gate '{name}' (target)")
381
- p = float(args[2]) if len(args) > 2 else 0.0
382
- compiled_ops.append([g_id, ctrl, tgt, p])
383
-
384
- # 2-qubit non-parametric: (name, ctrl, tgt)
385
- elif name in ('cx', 'cz', 'swap', 'cy'):
386
- ctrl = float(args[0])
387
- tgt = float(args[1]) if len(args) > 1 else 0.0
388
- self._check_qubit_range(ctrl, f"gate '{name}' (control)")
389
- self._check_qubit_range(tgt, f"gate '{name}' (target)")
390
- compiled_ops.append([g_id, ctrl, tgt, 0.0])
391
-
392
- # 1-qubit non-parametric: (name, qubit)
393
- else:
394
- q1 = float(args[0]) if args else 0.0
395
- self._check_qubit_range(q1, f"gate '{name}'")
396
- compiled_ops.append([g_id, q1, 0.0, 0.0])
397
-
398
- if compiled_ops:
399
- ops_jnp = jnp.array(compiled_ops, dtype=jnp.float64)
400
- # Safe to donate self.sv here: it's rebound immediately below and
401
- # no code path anywhere keeps a stale reference to the old buffer
402
- # across this call (verified across chunked/repeated calls too,
403
- # see _compile_and_run_circuit_jit_donated's docstring).
404
- self.sv = _compile_and_run_circuit_jit_donated(self.sv, ops_jnp)
405
-
406
- def run_circuit_with_chunking(self, circuit: List, chunk_size: int = 500):
407
- """
408
- Execute a circuit in chunks to avoid JIT recompilation on
409
- large variable-length circuits.
410
-
411
- Each chunk is a separate _compile_and_run_circuit_jit call
412
- with a fixed-size ops array, allowing XLA to cache each size.
413
- """
414
- target = QuantumTranspiler.transpile(circuit)
415
- for i in range(0, len(target), chunk_size):
416
- self.run_circuit_jit_beast_mode(target[i: i + chunk_size])
417
-
418
- def run_parametric_batch_jit(self,
419
- base_circuit: List,
420
- parameter_batch: np.ndarray) -> "jnp.ndarray":
421
-
422
- if not HAS_JAX:
423
- raise RuntimeError("run_parametric_batch_jit requires JAX")
424
-
425
- target = QuantumTranspiler.transpile(base_circuit)
426
- compiled_ops = []
427
-
428
- for cmd in target:
429
- name = cmd[0].lower() if isinstance(cmd[0], str) else str(cmd[0]).lower()
430
- if name not in GATE_IDS:
431
- continue
432
- g_id = float(GATE_IDS[name])
433
- args = cmd[1:]
434
- if name in ('rx', 'ry', 'rz', 'p', 'u1', 'phase'):
435
- q1 = float(args[0])
436
- self._check_qubit_range(q1, f"gate '{name}'")
437
- compiled_ops.append([g_id, q1, 0.0, -1.0]) # -1.0 = param slot
438
- elif name in ('cp', 'crz', 'cphase'):
439
- ctrl = float(args[0])
440
- tgt = float(args[1]) if len(args) > 1 else 0.0
441
- self._check_qubit_range(ctrl, f"gate '{name}' (control)")
442
- self._check_qubit_range(tgt, f"gate '{name}' (target)")
443
- compiled_ops.append([g_id, ctrl, tgt, -1.0])
444
- elif name in ('cx', 'cz', 'swap', 'cy'):
445
- ctrl = float(args[0])
446
- tgt = float(args[1]) if len(args) > 1 else 0.0
447
- self._check_qubit_range(ctrl, f"gate '{name}' (control)")
448
- self._check_qubit_range(tgt, f"gate '{name}' (target)")
449
- compiled_ops.append([g_id, ctrl, tgt, 0.0])
450
- else:
451
- q1 = float(args[0]) if args else 0.0
452
- self._check_qubit_range(q1, f"gate '{name}'")
453
- compiled_ops.append([g_id, q1, 0.0, 0.0])
454
-
455
- template = jnp.array(compiled_ops, dtype=jnp.float64)
456
- init_sv = jnp.zeros(self.dim, dtype=jnp.complex128).at[0].set(1.0)
457
-
458
- def simulate_single_instance(single_params: "jnp.ndarray") -> "jnp.ndarray":
459
- """Run one parameter vector through the circuit."""
460
-
461
- def patch_and_apply(carry: "jnp.ndarray",
462
- op: "jnp.ndarray"):
463
- """
464
- carry: jnp.int32 scalar β€” current parametric gate index.
465
- op: [g_id, q1, q2, p_sentinel]
466
- """
467
- idx = carry
468
- is_param = op[3] == -1.0
469
- final_p = jnp.where(is_param, single_params[idx], op[3])
470
- next_idx = jnp.where(is_param, idx + jnp.int32(1), idx)
471
- patched = jnp.array([op[0], op[1], op[2], final_p],
472
- dtype=jnp.float64)
473
- return next_idx, patched
474
-
475
- _, patched_ops = jax.lax.scan(
476
- patch_and_apply,
477
- jnp.int32(0), # BUG FIX: was (0,) tuple β€” must be a scalar
478
- template,
479
- )
480
- return _compile_and_run_circuit_jit(init_sv, patched_ops)
481
-
482
- return jax.jit(jax.vmap(simulate_single_instance, in_axes=(0,)))(
483
- jnp.asarray(parameter_batch, dtype=jnp.float64)
484
- )
485
-
486
- # ── observables ───────────────────────────────────────────────────
487
-
488
- def get_probabilities(self) -> np.ndarray:
489
- """Return measurement probability distribution as a NumPy float64 array."""
490
- probs = np.array(self.xp.abs(self.sv) ** 2, dtype=np.float64)
491
- # guard against floating-point leakage outside [0, 1]
492
- probs = np.clip(probs, 0.0, 1.0)
493
- total = probs.sum()
494
- if total > 1e-12:
495
- probs /= total
496
- return probs
497
-
498
- def get_statevector(self) -> np.ndarray:
499
- """Return the current statevector as a NumPy complex array."""
500
- return np.array(self.sv, dtype=self.dtype)
501
-
502
- def memory_mb(self) -> float:
503
- """Statevector memory footprint in megabytes."""
504
- bytes_per_element = 8 if self.use_float32 else 16 # complex64=8, complex128=16
505
- return self.dim * bytes_per_element / 1_000_000
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from typing import List, Tuple, Optional
3
+ from .registry import HAS_JAX
4
+ from .gates import GATES, PARAMETRIC_GATES, GATE_IDS
5
+ from .compiler import QuantumTranspiler
6
+
7
+ if HAS_JAX:
8
+ import jax
9
+ import jax.numpy as jnp
10
+ jax.config.update("jax_enable_x64", True)
11
+ from .compiler import _compile_and_run_circuit_jit, _compile_and_run_circuit_jit_donated
12
+
13
+
14
+ # ─────────────────────────────────────────────────────────────────────────────
15
+ # Internal helpers
16
+ # ─────────────────────────────────────────────────────────────────────────────
17
+
18
+ def _qubit_stride_pairs(n: int, qubit: int):
19
+ """
20
+ Return (stride, outer_step, inner_step) for the MSB-first statevector
21
+ convention used throughout this simulator.
22
+
23
+ In MSB-first ordering qubit 0 is the *most* significant bit, so:
24
+ physical_bit_position = n - 1 - qubit
25
+ stride = 1 << physical_bit_position
26
+ """
27
+ phys = n - 1 - qubit
28
+ stride = 1 << phys
29
+ return stride
30
+
31
+
32
+ def _cx_numpy(sv: np.ndarray, n: int, ctrl: int, tgt: int) -> np.ndarray:
33
+ """
34
+ Vectorised CX on a NumPy statevector.
35
+ No Python loops β€” uses strided index arithmetic.
36
+ """
37
+ dim = len(sv)
38
+ c_stride = 1 << (n - 1 - ctrl)
39
+ t_stride = 1 << (n - 1 - tgt)
40
+ all_i = np.arange(dim, dtype=np.intp)
41
+ # Select indices where ctrl bit == 1 and tgt bit == 0
42
+ mask = ((all_i & c_stride) != 0) & ((all_i & t_stride) == 0)
43
+ idx_0 = all_i[mask]
44
+ idx_1 = idx_0 | t_stride
45
+ sv = sv.copy()
46
+ sv[idx_0], sv[idx_1] = sv[idx_1].copy(), sv[idx_0].copy()
47
+ return sv
48
+
49
+
50
+ def _cz_numpy(sv: np.ndarray, n: int, ctrl: int, tgt: int) -> np.ndarray:
51
+ """Vectorised CZ on a NumPy statevector."""
52
+ dim = len(sv)
53
+ c_stride = 1 << (n - 1 - ctrl)
54
+ t_stride = 1 << (n - 1 - tgt)
55
+ all_i = np.arange(dim, dtype=np.intp)
56
+ mask = ((all_i & c_stride) != 0) & ((all_i & t_stride) != 0)
57
+ sv = sv.copy()
58
+ sv[mask] *= -1
59
+ return sv
60
+
61
+
62
+ # ─────────────────────────────────────────────────────────────────────────────
63
+ # DenseSVSimulator
64
+ # ────────────────────────────────────────────────────────────────────────────���
65
+
66
+ class DenseSVSimulator:
67
+ """
68
+ Dense statevector quantum circuit simulator.
69
+
70
+ Qubit ordering: MSB-first (qubit 0 is the most significant bit).
71
+ Backends: NumPy (CPU), JAX XLA JIT (CPU/GPU/TPU).
72
+
73
+ Parameters
74
+ ----------
75
+ n_qubits : number of qubits
76
+ use_gpu : reserved for future CuPy/JAX GPU dispatch
77
+ use_float32: use complex64 instead of complex128
78
+ """
79
+
80
+ def __init__(self, n_qubits: int,
81
+ use_gpu: bool = False,
82
+ use_float32: bool = False):
83
+ if n_qubits < 1 or n_qubits > 34:
84
+ raise ValueError(f"n_qubits must be in [1, 34], got {n_qubits}")
85
+ self.n = n_qubits
86
+ self.dim = 1 << n_qubits # 2 ** n_qubits
87
+ self.use_float32 = use_float32
88
+ self.dtype = np.complex64 if use_float32 else np.complex128
89
+ self.xp = jnp if HAS_JAX else np
90
+ self._reset_sv()
91
+
92
+ # ── state initialisation ─────────────────────────────────────────
93
+
94
+ def _reset_sv(self):
95
+ """Allocate |0...0⟩ on the active backend."""
96
+ if HAS_JAX:
97
+ self.sv = jnp.zeros(self.dim, dtype=self.dtype).at[0].set(1.0)
98
+ else:
99
+ self.sv = np.zeros(self.dim, dtype=self.dtype)
100
+ self.sv[0] = 1.0
101
+
102
+ def set_initial_state(self, state: Optional[np.ndarray] = None):
103
+ """
104
+ Reset the simulator.
105
+
106
+ Parameters
107
+ ----------
108
+ state : optional complex array of length 2**n.
109
+ If None, resets to |0...0⟩.
110
+ The array is normalised automatically.
111
+ """
112
+ if state is None:
113
+ self._reset_sv()
114
+ return
115
+ state = np.asarray(state, dtype=self.dtype)
116
+ if state.shape != (self.dim,):
117
+ raise ValueError(
118
+ f"State vector length {len(state)} != 2**{self.n} = {self.dim}")
119
+ norm = np.linalg.norm(state)
120
+ if norm < 1e-12:
121
+ raise ValueError("Cannot set a zero-norm state vector")
122
+ state = state / norm
123
+ if HAS_JAX:
124
+ self.sv = jnp.array(state)
125
+ else:
126
+ self.sv = state.copy()
127
+
128
+ # Alias used by the VQE engine
129
+ def set_state(self, state: np.ndarray):
130
+ self.set_initial_state(state)
131
+
132
+ # ── normalisation ─────────────────────────────────────────────────
133
+
134
+ def normalize(self):
135
+ norm = float(self.xp.linalg.norm(self.sv))
136
+ if norm > 1e-12:
137
+ if HAS_JAX:
138
+ self.sv = self.sv / norm
139
+ else:
140
+ self.sv /= norm
141
+
142
+ def _check_qubit_range(self, qubit: float, context: str) -> None:
143
+ """Validate a qubit index before it reaches the JIT-compiled fast
144
+ paths (run_circuit_jit_beast_mode / run_parametric_batch_jit).
145
+
146
+ Those paths encode qubit indices as bit-shift amounts inside
147
+ jax.lax.scan/switch and never call apply_gate_1q/apply_gate_2q
148
+ (which already validate) β€” an out-of-range index there doesn't
149
+ raise, it silently corrupts the entire statevector to zero
150
+ (verified: a single gate on an out-of-range qubit on an otherwise
151
+ normalized state left get_probabilities().sum() == 0.0, no error).
152
+ """
153
+ qi = int(qubit)
154
+ if not 0 <= qi < self.n:
155
+ raise ValueError(
156
+ f"Qubit index {qi} out of range [0, {self.n}) in {context}")
157
+
158
+ # ── 1-qubit gate ──────────────────────────────────────────────────
159
+
160
+ def apply_gate_1q(self, gate: np.ndarray, qubit: int):
161
+ """
162
+ Apply a 2Γ—2 unitary to *qubit* via tensor contraction.
163
+
164
+ Uses reshape + moveaxis + matmul β€” fully vectorised,
165
+ no Python loops, compatible with both NumPy and JAX.
166
+ """
167
+ if not 0 <= qubit < self.n:
168
+ raise ValueError(f"Qubit index {qubit} out of range [0, {self.n})")
169
+ gate = self.xp.array(gate, dtype=self.dtype)
170
+ sv_nd = self.sv.reshape([2] * self.n)
171
+ sv_moved = self.xp.moveaxis(sv_nd, qubit, -1) # qubit axis β†’ last
172
+ flat_shape = (self.dim >> 1, 2)
173
+ # matmul: (dim/2, 2) @ (2, 2).T β†’ (dim/2, 2)
174
+ result = self.xp.dot(sv_moved.reshape(flat_shape),
175
+ gate.T)
176
+ self.sv = self.xp.moveaxis(
177
+ result.reshape([2] * self.n), -1, qubit).ravel()
178
+
179
+ # ── 2-qubit gate ──────────────────────────────────────────────────
180
+
181
+ def apply_gate_2q(self, gate: np.ndarray, q1: int, q2: int):
182
+ """
183
+ Apply a 4Γ—4 unitary to qubits (q1, q2) via tensor contraction.
184
+ """
185
+ if q1 == q2:
186
+ raise ValueError("Control and target qubits must differ")
187
+ if not (0 <= q1 < self.n and 0 <= q2 < self.n):
188
+ raise ValueError(f"Qubit indices ({q1},{q2}) out of range [0, {self.n})")
189
+ gate = self.xp.array(gate, dtype=self.dtype)
190
+ sv_nd = self.sv.reshape([2] * self.n)
191
+ sv_moved = self.xp.moveaxis(sv_nd, (q1, q2), (-2, -1))
192
+ flat_shape = (self.dim >> 2, 4)
193
+ result = self.xp.dot(sv_moved.reshape(flat_shape),
194
+ gate.reshape(4, 4).T)
195
+ self.sv = self.xp.moveaxis(
196
+ result.reshape([2] * self.n), (-2, -1), (q1, q2)).ravel()
197
+
198
+ # ── specialised 2-qubit gates ─────────────────────────────────────
199
+
200
+ def apply_cx(self, ctrl: int, tgt: int):
201
+ """
202
+ CX (CNOT) gate.
203
+
204
+ JAX path: matrix contraction via apply_gate_2q.
205
+ NumPy path: fully vectorised index swap β€” no Python loops.
206
+ """
207
+ if ctrl == tgt:
208
+ raise ValueError("Control and target qubits must differ")
209
+ if not (0 <= ctrl < self.n and 0 <= tgt < self.n):
210
+ raise ValueError(f"Qubit indices ({ctrl},{tgt}) out of range [0, {self.n})")
211
+ if HAS_JAX:
212
+ cx_mat = jnp.array([
213
+ [1, 0, 0, 0],
214
+ [0, 1, 0, 0],
215
+ [0, 0, 0, 1],
216
+ [0, 0, 1, 0],
217
+ ], dtype=self.dtype)
218
+ self.apply_gate_2q(cx_mat, ctrl, tgt)
219
+ else:
220
+ self.sv = _cx_numpy(np.array(self.sv), self.n, ctrl, tgt)
221
+
222
+ def apply_cz(self, ctrl: int, tgt: int):
223
+ """
224
+ CZ gate.
225
+
226
+ JAX path: matrix contraction via apply_gate_2q.
227
+ NumPy path: fully vectorised sign flip β€” no Python loops.
228
+ """
229
+ if ctrl == tgt:
230
+ raise ValueError("Control and target qubits must differ")
231
+ if not (0 <= ctrl < self.n and 0 <= tgt < self.n):
232
+ raise ValueError(f"Qubit indices ({ctrl},{tgt}) out of range [0, {self.n})")
233
+ if HAS_JAX:
234
+ cz_mat = jnp.array([
235
+ [1, 0, 0, 0],
236
+ [0, 1, 0, 0],
237
+ [0, 0, 1, 0],
238
+ [0, 0, 0, -1],
239
+ ], dtype=self.dtype)
240
+ self.apply_gate_2q(cz_mat, ctrl, tgt)
241
+ else:
242
+ self.sv = _cz_numpy(np.array(self.sv), self.n, ctrl, tgt)
243
+
244
+ def apply_rx(self, qubit: int, theta: float):
245
+ """Apply a parameterized RX gate using the active backend (NumPy/JAX)."""
246
+ cos, sin = self.xp.cos(theta / 2), self.xp.sin(theta / 2)
247
+ mat = self.xp.array([[cos, -1j * sin], [-1j * sin, cos]], dtype=self.dtype)
248
+ self.apply_gate_1q(mat, qubit)
249
+
250
+ def apply_ry(self, qubit: int, theta: float):
251
+ """Apply a parameterized RY gate using the active backend (NumPy/JAX)."""
252
+ cos, sin = self.xp.cos(theta / 2), self.xp.sin(theta / 2)
253
+ mat = self.xp.array([[cos, -sin], [sin, cos]], dtype=self.dtype)
254
+ self.apply_gate_1q(mat, qubit)
255
+
256
+ def apply_rz(self, qubit: int, theta: float):
257
+ """Apply a parameterized RZ gate using the active backend (NumPy/JAX)."""
258
+ exp_neg = self.xp.exp(-1j * theta / 2)
259
+ exp_pos = self.xp.exp(1j * theta / 2)
260
+ mat = self.xp.array([[exp_neg, 0.0], [0.0, exp_pos]], dtype=self.dtype)
261
+ self.apply_gate_1q(mat, qubit)
262
+
263
+ # ── measurement ───────────────────────────────────────────────────
264
+
265
+ def measure(self, qubit_idx: int) -> int:
266
+ """
267
+ Projective measurement on *qubit_idx*.
268
+
269
+ Returns 0 or 1 and collapses the statevector.
270
+ Uses MSB-first physical bit index: phys = n - 1 - qubit_idx.
271
+
272
+ BUG FIX (original): the original NumPy collapse wrote
273
+ sv_reshaped[:, 1 if result == 0 else 0, :] = 0.0
274
+ which zeroed the *wrong* basis state (0 when result=1, 1 when result=0)
275
+ and never normalised the JAX path.
276
+ """
277
+ if not 0 <= qubit_idx < self.n:
278
+ raise ValueError(
279
+ f"Qubit {qubit_idx} out of range [0, {self.n})")
280
+
281
+ phys = self.n - 1 - qubit_idx
282
+ stride = 1 << phys
283
+
284
+ # ── compute marginal probabilities ──────────────────────────
285
+ if HAS_JAX:
286
+ probs = jnp.abs(self.sv) ** 2
287
+ sv_nd = probs.reshape([2] * self.n)
288
+ mv = jnp.moveaxis(sv_nd, phys, 0)
289
+ prob_0 = float(jnp.sum(mv[0]))
290
+ prob_1 = float(jnp.sum(mv[1]))
291
+ else:
292
+ sv_res = self.sv.reshape(-1, 2, stride)
293
+ prob_0 = float(np.sum(np.abs(sv_res[:, 0, :]) ** 2))
294
+ prob_1 = float(np.sum(np.abs(sv_res[:, 1, :]) ** 2))
295
+
296
+ total = prob_0 + prob_1
297
+ if total < 1e-12:
298
+ raise RuntimeError("Statevector norm is zero β€” cannot measure")
299
+ prob_0 /= total
300
+ prob_1 /= total
301
+
302
+ result = int(np.random.choice([0, 1], p=[prob_0, prob_1]))
303
+
304
+ # ── collapse ────────────────────────────────────────────────
305
+ # Zero out the amplitudes corresponding to the *opposite* outcome.
306
+ zero_slot = 1 - result # if result=0, zero slot 1; if result=1, zero slot 0
307
+
308
+ if HAS_JAX:
309
+ sv_nd = self.sv.reshape([2] * self.n)
310
+ mv = jnp.moveaxis(sv_nd, phys, 0)
311
+ mv = mv.at[zero_slot].set(0.0 + 0j)
312
+ self.sv = jnp.moveaxis(mv, 0, phys).ravel()
313
+ else:
314
+ sv_res = self.sv.reshape(-1, 2, stride)
315
+ sv_res[:, zero_slot, :] = 0.0
316
+ self.sv = sv_res.ravel()
317
+
318
+ self.normalize()
319
+ return result
320
+
321
+ # ── circuit execution ─────────────────────────────────────────────
322
+
323
+ def run_circuit(self, circuit: List[Tuple], transpile: bool = True):
324
+ target = QuantumTranspiler.transpile(circuit) if transpile else circuit
325
+ for cmd in target:
326
+ name = cmd[0].lower()
327
+ args = cmd[1:]
328
+
329
+ if name in GATES:
330
+ mat = self.xp.array(GATES[name], dtype=self.dtype)
331
+ if mat.shape == (2, 2):
332
+ self.apply_gate_1q(mat, int(args[0]))
333
+ else:
334
+ self.apply_gate_2q(mat, int(args[0]), int(args[1]))
335
+
336
+ elif name in PARAMETRIC_GATES:
337
+ if len(args) == 2:
338
+ mat = self.xp.array(PARAMETRIC_GATES[name](args[1]), dtype=self.dtype)
339
+ self.apply_gate_1q(mat, int(args[0]))
340
+ elif len(args) == 3:
341
+ mat = self.xp.array(PARAMETRIC_GATES[name](args[2]), dtype=self.dtype)
342
+ self.apply_gate_2q(mat, int(args[0]), int(args[1]))
343
+ elif len(args) == 4:
344
+ mat = self.xp.array(
345
+ PARAMETRIC_GATES[name](args[1], args[2], args[3]),
346
+ dtype=self.dtype)
347
+ self.apply_gate_1q(mat, int(args[0]))
348
+
349
+ else:
350
+ raise ValueError(
351
+ f"unknown gate '{cmd[0]}' -- not in GATES or PARAMETRIC_GATES. "
352
+ f"A typo in a gate name used to be silently dropped from the "
353
+ f"circuit instead of raising (issue #4)."
354
+ )
355
+
356
+
357
+
358
+ def run_circuit_jit_beast_mode(self, circuit: List):
359
+
360
+ if not HAS_JAX:
361
+ return self.run_circuit(circuit)
362
+
363
+ target = QuantumTranspiler.transpile(circuit)
364
+ compiled_ops = []
365
+
366
+ for cmd in target:
367
+ name = cmd[0].lower() if isinstance(cmd[0], str) else str(cmd[0]).lower()
368
+ if name not in GATE_IDS:
369
+ raise ValueError(
370
+ f"unknown gate '{cmd[0]}' -- not in GATE_IDS. A typo in a gate "
371
+ f"name used to be silently dropped from the circuit instead of "
372
+ f"raising (issue #4)."
373
+ )
374
+
375
+ g_id = float(GATE_IDS[name])
376
+ args = cmd[1:]
377
+
378
+ # ── gate argument parsing ──────────────────────────────
379
+ # 1-qubit parametric: (name, qubit, param)
380
+ if name in ('rx', 'ry', 'rz', 'p', 'u1', 'phase'):
381
+ q1 = float(args[0])
382
+ self._check_qubit_range(q1, f"gate '{name}'")
383
+ p = float(args[1]) if len(args) > 1 else 0.0
384
+ compiled_ops.append([g_id, q1, 0.0, p])
385
+
386
+ # 2-qubit parametric: (name, ctrl, tgt, param)
387
+ elif name in ('cp', 'crz', 'cphase'):
388
+ ctrl = float(args[0])
389
+ tgt = float(args[1]) if len(args) > 1 else 0.0
390
+ self._check_qubit_range(ctrl, f"gate '{name}' (control)")
391
+ self._check_qubit_range(tgt, f"gate '{name}' (target)")
392
+ p = float(args[2]) if len(args) > 2 else 0.0
393
+ compiled_ops.append([g_id, ctrl, tgt, p])
394
+
395
+ # 2-qubit non-parametric: (name, ctrl, tgt)
396
+ elif name in ('cx', 'cz', 'swap', 'cy'):
397
+ ctrl = float(args[0])
398
+ tgt = float(args[1]) if len(args) > 1 else 0.0
399
+ self._check_qubit_range(ctrl, f"gate '{name}' (control)")
400
+ self._check_qubit_range(tgt, f"gate '{name}' (target)")
401
+ compiled_ops.append([g_id, ctrl, tgt, 0.0])
402
+
403
+ # 1-qubit non-parametric: (name, qubit)
404
+ else:
405
+ q1 = float(args[0]) if args else 0.0
406
+ self._check_qubit_range(q1, f"gate '{name}'")
407
+ compiled_ops.append([g_id, q1, 0.0, 0.0])
408
+
409
+ if compiled_ops:
410
+ ops_jnp = jnp.array(compiled_ops, dtype=jnp.float64)
411
+ # Safe to donate self.sv here: it's rebound immediately below and
412
+ # no code path anywhere keeps a stale reference to the old buffer
413
+ # across this call (verified across chunked/repeated calls too,
414
+ # see _compile_and_run_circuit_jit_donated's docstring).
415
+ self.sv = _compile_and_run_circuit_jit_donated(self.sv, ops_jnp)
416
+
417
+ def run_circuit_with_chunking(self, circuit: List, chunk_size: int = 500):
418
+ """
419
+ Execute a circuit in chunks to avoid JIT recompilation on
420
+ large variable-length circuits.
421
+
422
+ Each chunk is a separate _compile_and_run_circuit_jit call
423
+ with a fixed-size ops array, allowing XLA to cache each size.
424
+ """
425
+ target = QuantumTranspiler.transpile(circuit)
426
+ for i in range(0, len(target), chunk_size):
427
+ self.run_circuit_jit_beast_mode(target[i: i + chunk_size])
428
+
429
+ def run_parametric_batch_jit(self,
430
+ base_circuit: List,
431
+ parameter_batch: np.ndarray) -> "jnp.ndarray":
432
+
433
+ if not HAS_JAX:
434
+ raise RuntimeError("run_parametric_batch_jit requires JAX")
435
+
436
+ target = QuantumTranspiler.transpile(base_circuit)
437
+ compiled_ops = []
438
+
439
+ for cmd in target:
440
+ name = cmd[0].lower() if isinstance(cmd[0], str) else str(cmd[0]).lower()
441
+ if name not in GATE_IDS:
442
+ raise ValueError(
443
+ f"unknown gate '{cmd[0]}' -- not in GATE_IDS. A typo in a gate "
444
+ f"name used to be silently dropped from the circuit instead of "
445
+ f"raising (issue #4)."
446
+ )
447
+ g_id = float(GATE_IDS[name])
448
+ args = cmd[1:]
449
+ if name in ('rx', 'ry', 'rz', 'p', 'u1', 'phase'):
450
+ q1 = float(args[0])
451
+ self._check_qubit_range(q1, f"gate '{name}'")
452
+ compiled_ops.append([g_id, q1, 0.0, -1.0]) # -1.0 = param slot
453
+ elif name in ('cp', 'crz', 'cphase'):
454
+ ctrl = float(args[0])
455
+ tgt = float(args[1]) if len(args) > 1 else 0.0
456
+ self._check_qubit_range(ctrl, f"gate '{name}' (control)")
457
+ self._check_qubit_range(tgt, f"gate '{name}' (target)")
458
+ compiled_ops.append([g_id, ctrl, tgt, -1.0])
459
+ elif name in ('cx', 'cz', 'swap', 'cy'):
460
+ ctrl = float(args[0])
461
+ tgt = float(args[1]) if len(args) > 1 else 0.0
462
+ self._check_qubit_range(ctrl, f"gate '{name}' (control)")
463
+ self._check_qubit_range(tgt, f"gate '{name}' (target)")
464
+ compiled_ops.append([g_id, ctrl, tgt, 0.0])
465
+ else:
466
+ q1 = float(args[0]) if args else 0.0
467
+ self._check_qubit_range(q1, f"gate '{name}'")
468
+ compiled_ops.append([g_id, q1, 0.0, 0.0])
469
+
470
+ n_param_slots = sum(1 for op in compiled_ops if op[3] == -1.0)
471
+ parameter_batch = np.asarray(parameter_batch)
472
+ if parameter_batch.ndim != 2 or parameter_batch.shape[1] != n_param_slots:
473
+ raise ValueError(
474
+ f"parameter_batch has {parameter_batch.shape[-1] if parameter_batch.ndim else 0} "
475
+ f"column(s) but base_circuit has {n_param_slots} parametric gate(s) (rx/ry/rz/p/u1/"
476
+ f"phase/cp/crz/cphase) -- one column per parametric gate, in gate-appearance order. "
477
+ f"A literal float passed for one of these gates is NOT exempt: it still consumes a "
478
+ f"positional column. A mismatch here used to be clipped silently by JAX's default "
479
+ f"out-of-bounds indexing instead of raising (issue #6)."
480
+ )
481
+
482
+ template = jnp.array(compiled_ops, dtype=jnp.float64)
483
+ init_sv = jnp.zeros(self.dim, dtype=jnp.complex128).at[0].set(1.0)
484
+
485
+ def simulate_single_instance(single_params: "jnp.ndarray") -> "jnp.ndarray":
486
+ """Run one parameter vector through the circuit."""
487
+
488
+ def patch_and_apply(carry: "jnp.ndarray",
489
+ op: "jnp.ndarray"):
490
+ """
491
+ carry: jnp.int32 scalar β€” current parametric gate index.
492
+ op: [g_id, q1, q2, p_sentinel]
493
+ """
494
+ idx = carry
495
+ is_param = op[3] == -1.0
496
+ final_p = jnp.where(is_param, single_params[idx], op[3])
497
+ next_idx = jnp.where(is_param, idx + jnp.int32(1), idx)
498
+ patched = jnp.array([op[0], op[1], op[2], final_p],
499
+ dtype=jnp.float64)
500
+ return next_idx, patched
501
+
502
+ _, patched_ops = jax.lax.scan(
503
+ patch_and_apply,
504
+ jnp.int32(0), # BUG FIX: was (0,) tuple β€” must be a scalar
505
+ template,
506
+ )
507
+ return _compile_and_run_circuit_jit(init_sv, patched_ops)
508
+
509
+ return jax.jit(jax.vmap(simulate_single_instance, in_axes=(0,)))(
510
+ jnp.asarray(parameter_batch, dtype=jnp.float64)
511
+ )
512
+
513
+ # ── observables ───────────────────────────────────────────────────
514
+
515
+ def get_probabilities(self) -> np.ndarray:
516
+ """Return measurement probability distribution as a NumPy float64 array."""
517
+ probs = np.array(self.xp.abs(self.sv) ** 2, dtype=np.float64)
518
+ # guard against floating-point leakage outside [0, 1]
519
+ probs = np.clip(probs, 0.0, 1.0)
520
+ total = probs.sum()
521
+ if total > 1e-12:
522
+ probs /= total
523
+ return probs
524
+
525
+ def get_statevector(self) -> np.ndarray:
526
+ """Return the current statevector as a NumPy complex array."""
527
+ return np.array(self.sv, dtype=self.dtype)
528
+
529
+ def memory_mb(self) -> float:
530
+ """Statevector memory footprint in megabytes."""
531
+ bytes_per_element = 8 if self.use_float32 else 16 # complex64=8, complex128=16
532
+ return self.dim * bytes_per_element / 1_000_000