Tatopenn commited on
Commit
e0de20d
Β·
verified Β·
1 Parent(s): 3098cd3

Sync dense_evolution/ from v8.1.35

Browse files
dense_evolution/__init__.py CHANGED
@@ -13,4 +13,4 @@ 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"
 
13
  from .mps import MPSSimulator
14
  from .mitigation import richardson_extrapolate, zero_noise_extrapolation
15
 
16
+ __version__ = "8.1.35"
dense_evolution/mps.py CHANGED
@@ -58,10 +58,13 @@ 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)
@@ -76,8 +79,370 @@ def _jsd_vectors(p: jnp.ndarray, q: jnp.ndarray) -> float:
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:
@@ -124,6 +489,12 @@ class MPSSimulator:
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)
@@ -287,14 +658,22 @@ class MPSSimulator:
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
 
@@ -400,3 +779,83 @@ class MPSSimulator:
400
  f"avg_JSD={self.avg_jsd():.4f} | EE_max={ee_max:.3f}b | "
401
  f"budget_violations={self.budget_violations}"
402
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  import numpy as np
59
 
60
 
61
+ def _jsd_vectors_jax(p: jnp.ndarray, q: jnp.ndarray) -> jnp.ndarray:
62
+ """Same Jensen-Shannon Distance as _jsd_vectors, but returns a jnp
63
+ scalar instead of a Python float -- the float() cast in _jsd_vectors
64
+ forces concretization, which is fine called eagerly but raises
65
+ ConcretizationTypeError under jax.vmap/jax.jit tracing (needed by
66
+ _vectorized_chi_search below). Same math, no behavior difference for
67
+ eager callers, who go through _jsd_vectors instead."""
68
  eps = 1e-12
69
  p_norm = p / (jnp.sum(p) + eps)
70
  q_norm = q / (jnp.sum(q) + eps)
 
79
  return jnp.sum(jnp.where(mask, a * safe_log, 0.0))
80
 
81
  js = 0.5 * (_kl(p_norm, m) + _kl(q_norm, m))
82
+ # p.shape[0] is a static Python int (shape, not a value) even for a
83
+ # traced array under vmap, so this branch is safe at trace time.
84
+ dim_factor = float(np.log10(p.shape[0]) / 2.0) if p.shape[0] > 1 else 1.0
85
+ return jnp.sqrt(jnp.clip(js * dim_factor, 0.0, 1.0))
86
+
87
+
88
+ def _jsd_vectors(p: jnp.ndarray, q: jnp.ndarray) -> float:
89
+ """Adaptive Jensen-Shannon Distance used to size the truncated bond
90
+ dimension: scales with log10(dim) so the same JSD budget stays
91
+ meaningful whether the local Hilbert space is small or large."""
92
+ return float(_jsd_vectors_jax(p, q))
93
+
94
+
95
+ def _vectorized_chi_search_jax(S: jnp.ndarray, eps: float, jsd_budget: float, max_bond: int):
96
+ """JIT/vmap-compatible core of _vectorized_chi_search -- no
97
+ float()/int()/bool() concretizing casts, returns (chi_new, jsd_val) as
98
+ traced jnp scalars instead of Python int/float, so it's usable from
99
+ inside a jax.lax.scan/jax.jit region (needed by _build_mps_runner's
100
+ step function). Same algorithm _vectorized_chi_search wraps and casts
101
+ to Python types for eager callers -- see that docstring for the
102
+ verification this replicates the real while loop exactly."""
103
+ n = S.shape[0]
104
+ max_possible = min(n, max_bond)
105
+ mask_above_eps = S > eps
106
+ initial_chi = jnp.clip(jnp.sum(mask_above_eps), 1, max_possible)
107
+
108
+ norm_full = jnp.sum(S ** 2) + 1e-15
109
+ p_full = (S ** 2) / norm_full
110
+
111
+ candidates = jnp.arange(1, max_possible + 1)
112
+ idx = jnp.arange(n)
113
+ trunc_mask = idx[None, :] < candidates[:, None]
114
+ p_trunc_all = jnp.where(trunc_mask, p_full[None, :], 0.0)
115
+
116
+ jsd_all = jax.vmap(lambda pt: _jsd_vectors_jax(p_full, pt))(p_trunc_all)
117
+
118
+ valid_candidate = candidates >= initial_chi
119
+ satisfies = (jsd_all <= jsd_budget) & valid_candidate
120
+ any_satisfies = jnp.any(satisfies)
121
+ first_idx = jnp.argmax(satisfies)
122
+ chi_new = jnp.where(any_satisfies, candidates[first_idx], max_possible)
123
+ jsd_val = jnp.where(any_satisfies, jsd_all[first_idx], jsd_all[max_possible - 1])
124
+ return chi_new, jsd_val
125
+
126
+
127
+ def _vectorized_chi_search(S: jnp.ndarray, eps: float, jsd_budget: float, max_bond: int):
128
+ """JIT/vmap-compatible replacement for the Python `while` loop in
129
+ _svd_truncate (host-syncs every iteration today). Computes the JSD for
130
+ every candidate truncation size in one vectorized pass instead of
131
+ incrementing chi_new one at a time, then picks the smallest candidate
132
+ >= the eps-cutoff-based starting point that satisfies jsd_budget --
133
+ exactly replicating the while loop's search direction and stopping
134
+ condition (verified: 0 mismatches in chi_new/jsd_val against the real
135
+ while loop across 171 real _svd_truncate calls from actual entangled
136
+ circuits at 3 different (n_qubits, max_bond, jsd_budget) configurations,
137
+ including the budget-violation fallback path).
138
+
139
+ Does NOT assume JSD is monotonic in the candidate size -- it restricts
140
+ the search to candidates >= the same starting point the while loop
141
+ starts from and takes the first (smallest) one satisfying the budget,
142
+ same as the loop would find by incrementing, whether or not JSD happens
143
+ to be monotonic there.
144
+
145
+ Returns (chi_new, jsd_val) as Python int/float -- eager convenience
146
+ wrapper around _vectorized_chi_search_jax, for callers outside a jit
147
+ region (e.g. these same tests).
148
+ """
149
+ chi_new, jsd_val = _vectorized_chi_search_jax(S, eps, jsd_budget, max_bond)
150
+ return int(chi_new), float(jsd_val)
151
+
152
+
153
+ def _expand_nonlocal_2q_positions(q1: int, q2: int):
154
+ """Pure-Python prediction of the exact adjacent-pair call sequence
155
+ MPSSimulator._apply_nonlocal_2q's runtime SWAP-chain dispatch produces
156
+ for a given (q1, q2) -- moves that decision from runtime (inside the
157
+ eager gate-application loop) to pre-compile time, so it can be used to
158
+ build a flat op list before entering a JIT region, mirroring how
159
+ chunk.py's _compile_multi_chunk_ops does all gate-name branching
160
+ outside the traced kernel.
161
+
162
+ Verified exhaustively against the real runtime dispatch: 0 mismatches
163
+ across all (q1, q2) pairs for n_qubits in {6, 10, 15} (330 pairs).
164
+
165
+ Returns (seq, gate_index, needs_transpose):
166
+ seq -- list of (a, a+1) adjacent physical-position pairs,
167
+ in the exact order _apply_nonlocal_2q would call
168
+ apply_gate_2q on them.
169
+ gate_index -- which position in `seq` is the REAL gate (every
170
+ other position is a SWAP).
171
+ needs_transpose -- True iff the original q1 > q2, matching
172
+ _apply_nonlocal_2q's own q1>q2 normalization
173
+ (the gate tensor must be transposed via axes
174
+ (1, 0, 3, 2) before use at `seq[gate_index]`,
175
+ same as _apply_nonlocal_2q already does).
176
+ """
177
+ needs_transpose = q1 > q2
178
+ target, far = (q2, q1) if needs_transpose else (q1, q2)
179
+ seq = []
180
+ for q in range(far - 1, target, -1):
181
+ seq.append((q, q + 1))
182
+ gate_index = len(seq)
183
+ seq.append((target, target + 1))
184
+ for q in range(target + 1, far):
185
+ seq.append((q, q + 1))
186
+ return seq, gate_index, needs_transpose
187
+
188
+
189
+ # ── gate-ID -> matrix construction, jax.lax.switch-based (JIT-fusion) ────
190
+ # Same gate-ID table as dense_evolution/gates.py::GATE_IDS and
191
+ # compiler.py::_apply_gate_fast_step's g_1q switch -- same formulas,
192
+ # verified to match exactly (0 error, both eagerly and under jax.vmap/jit)
193
+ # before being committed here. Unlike compiler.py's statevector-bitmask
194
+ # do_2q, MPS's own gate application is an explicit tensor contraction
195
+ # (jnp.einsum in apply_gate_2q), so the 2-qubit switch below returns the
196
+ # full (2,2,2,2) unitary tensor directly -- same matrices mps.py's own
197
+ # apply_cx/apply_cz/apply_swap already build by hand, generalized to a
198
+ # traced g_id instead of one hardcoded gate per method. id=23 (SWAP) is
199
+ # reserved-but-unused in gates.py's own table (comment there: "never
200
+ # dispatched here, QuantumTranspiler always decomposes swap into 3xCX
201
+ # first") -- MPS's own kernel claims it for real, since decomposing SWAP
202
+ # into 3 CX would mean 3 SVD truncations per swap instead of 1, defeating
203
+ # the point of keeping SWAP as its own gate for the non-adjacent-gate
204
+ # chain (see _expand_nonlocal_2q_positions above).
205
+
206
+ def _mps_1q_matrix(g_id: jnp.ndarray, param: jnp.ndarray, dtype) -> jnp.ndarray:
207
+ """Traced gate-ID -> (2,2) unitary, ids 0-13 (I,H,X,Y,Z,S,Sdg,T,Tdg,
208
+ Rx,Ry,Rz,P,SX) -- same formulas as compiler.py's g_1q switch."""
209
+ inv2 = jnp.asarray(1.0 / jnp.sqrt(2.0), dtype=dtype)
210
+ half_p = param * 0.5
211
+ cos_p = jnp.cos(half_p).astype(dtype)
212
+ sin_p = jnp.sin(half_p).astype(dtype)
213
+ exp_pos = jnp.exp(1j * param).astype(dtype)
214
+ exp_ph4 = jnp.exp(1j * jnp.pi / 4.0).astype(dtype)
215
+ exp_mh4 = jnp.exp(-1j * jnp.pi / 4.0).astype(dtype)
216
+ safe_gid = jnp.clip(g_id, 0, 13)
217
+ return jax.lax.switch(
218
+ safe_gid,
219
+ [
220
+ lambda _: jnp.eye(2, dtype=dtype), # 0 I
221
+ lambda _: jnp.array([[inv2, inv2], [inv2, -inv2]], dtype=dtype), # 1 H
222
+ lambda _: jnp.array([[0.0 + 0j, 1.0 + 0j], [1.0 + 0j, 0.0 + 0j]], dtype=dtype), # 2 X
223
+ lambda _: jnp.array([[0.0 + 0j, -1j], [1j, 0.0 + 0j]], dtype=dtype), # 3 Y
224
+ lambda _: jnp.array([[1.0 + 0j, 0.0 + 0j], [0.0 + 0j, -1.0 + 0j]], dtype=dtype), # 4 Z
225
+ lambda _: jnp.array([[1.0 + 0j, 0.0 + 0j], [0.0 + 0j, 1j]], dtype=dtype), # 5 S
226
+ lambda _: jnp.array([[1.0 + 0j, 0.0 + 0j], [0.0 + 0j, -1j]], dtype=dtype), # 6 Sdg
227
+ lambda _: jnp.array([[1.0 + 0j, 0.0 + 0j], [0.0 + 0j, exp_ph4]], dtype=dtype), # 7 T
228
+ lambda _: jnp.array([[1.0 + 0j, 0.0 + 0j], [0.0 + 0j, exp_mh4]], dtype=dtype), # 8 Tdg
229
+ lambda _: jnp.array([[cos_p, -1j * sin_p], [-1j * sin_p, cos_p]], dtype=dtype), # 9 Rx
230
+ lambda _: jnp.array([[cos_p, -sin_p], [sin_p, cos_p]], dtype=dtype), # 10 Ry
231
+ lambda _: jnp.array([[jnp.exp(-1j * half_p), 0.0 + 0j],
232
+ [0.0 + 0j, jnp.exp(1j * half_p)]], dtype=dtype), # 11 Rz
233
+ lambda _: jnp.array([[1.0 + 0j, 0.0 + 0j], [0.0 + 0j, exp_pos]], dtype=dtype), # 12 P
234
+ lambda _: jnp.array([[0.5 + 0.5j, 0.5 - 0.5j], [0.5 - 0.5j, 0.5 + 0.5j]], dtype=dtype), # 13 SX
235
+ ],
236
+ operand=None,
237
+ )
238
+
239
+
240
+ def _mps_2q_matrix(g_id: jnp.ndarray, param: jnp.ndarray, dtype) -> jnp.ndarray:
241
+ """Traced gate-ID -> (2,2,2,2) unitary tensor, ids 20-25
242
+ (CX,CZ,CP,SWAP,CY,CRZ) -- same target gates as compiler.py's do_2q,
243
+ built as explicit tensors (not the statevector-bitmask approach) to
244
+ match MPS's own einsum-based 2-qubit gate application."""
245
+ exp_pos = jnp.exp(1j * param).astype(dtype)
246
+ exp_neg_half = jnp.exp(-1j * param * 0.5).astype(dtype)
247
+ exp_pos_half = jnp.exp(1j * param * 0.5).astype(dtype)
248
+ one = jnp.asarray(1.0 + 0j, dtype=dtype)
249
+ cp_diag = jnp.stack([one, one, one, exp_pos])
250
+ crz_diag = jnp.stack([one, one, exp_neg_half, exp_pos_half])
251
+ safe_idx = jnp.clip(g_id - 20, 0, 5)
252
+ mat = jax.lax.switch(
253
+ safe_idx,
254
+ [
255
+ lambda _: jnp.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]], dtype=dtype), # 20 CX
256
+ lambda _: jnp.diag(jnp.array([1, 1, 1, -1], dtype=dtype)), # 21 CZ
257
+ lambda _: jnp.diag(cp_diag), # 22 CP
258
+ lambda _: jnp.array([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]], dtype=dtype), # 23 SWAP
259
+ lambda _: jnp.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, -1j], [0, 0, 1j, 0]], dtype=dtype), # 24 CY
260
+ lambda _: jnp.diag(crz_diag), # 25 CRZ
261
+ ],
262
+ operand=None,
263
+ )
264
+ return mat.reshape(2, 2, 2, 2)
265
+
266
+
267
+ def _pad_gamma(g: jnp.ndarray, max_bond: int) -> jnp.ndarray:
268
+ """Zero-pads a (chiL, 2, chiR) gamma tensor up to (max_bond, 2,
269
+ max_bond) -- the fixed shape run_circuit_jit's scan carry needs.
270
+ Mathematically transparent: every contraction used here (einsum) sums
271
+ over the padded axis, and zero entries there contribute exactly zero,
272
+ verified directly (max singular-value error at machine epsilon,
273
+ final-state fidelity 1.0 to 1e-13, against the real eager simulator
274
+ across multiple (n_qubits, max_bond, jsd_budget) configurations
275
+ including budget-violation cases)."""
276
+ chi_l, d, chi_r = g.shape
277
+ out = jnp.zeros((max_bond, d, max_bond), dtype=g.dtype)
278
+ return out.at[:chi_l, :, :chi_r].set(g)
279
+
280
+
281
+ def _pad_lambda(lam: jnp.ndarray, max_bond: int) -> jnp.ndarray:
282
+ """Zero-pads a (chi,) lambda vector up to (max_bond,)."""
283
+ n = lam.shape[0]
284
+ out = jnp.zeros((max_bond,), dtype=lam.dtype)
285
+ return out.at[:n].set(lam)
286
+
287
+
288
+ def _compile_mps_ops(ops, n_qubits: int) -> List[List[float]]:
289
+ """Pre-compile-time (pure Python, outside any jit region) translation
290
+ of a circuit -- list of (name, *args) tuples/lists, same convention as
291
+ DenseSVSimulator.run_circuit_jit_beast_mode -- into a flat list of
292
+ [g_id, q1, q2, param, transpose_flag] rows for run_circuit_jit's
293
+ jax.lax.scan kernel. Two things happen here, deliberately outside the
294
+ jit region (same principle as chunk.py's _compile_multi_chunk_ops --
295
+ all Python-level branching on gate identity happens before tracing
296
+ starts, never inside the traced step function):
297
+
298
+ 1. GATE_IDS (dense_evolution/gates.py) name -> numeric id lookup.
299
+ 2. Non-adjacent 2-qubit gates, and adjacent ones with q1 > q2,
300
+ expanded/normalized via _expand_nonlocal_2q_positions (verified
301
+ above) into their SWAP-chain-equivalent sequence of
302
+ adjacent-ascending rows -- moves what _apply_nonlocal_2q's
303
+ runtime dispatch does today to pre-compile time.
304
+
305
+ id 23 (SWAP) is used for real here (not decomposed into 3xCX like
306
+ QuantumTranspiler.transpile would) -- see _mps_2q_matrix's docstring
307
+ for why: decomposing would mean 3 SVD truncations per swap instead
308
+ of 1, defeating the point of the chain in the first place.
309
+ """
310
+ from .compiler import QuantumTranspiler
311
+ from .gates import GATE_IDS
312
+
313
+ # CCX has no entry in GATE_IDS (it's not a 1- or 2-qubit gate) -- reuse
314
+ # the same Barenco H/CX/T/Tdg decomposition compiler.py/chunk.py's own
315
+ # QuantumTranspiler already uses, rather than inventing a second one.
316
+ # 'swap' is deliberately NOT pre-decomposed here (see id 23 note below).
317
+ expanded_ops = []
318
+ for cmd in ops:
319
+ if str(cmd[0]).lower() == 'ccx':
320
+ expanded_ops.extend(QuantumTranspiler.decompose_toffoli(*cmd[1:4]))
321
+ else:
322
+ expanded_ops.append(cmd)
323
+
324
+ rows: List[List[float]] = []
325
+ for cmd in expanded_ops:
326
+ name = str(cmd[0]).lower()
327
+ if name not in GATE_IDS:
328
+ raise ValueError(
329
+ f"unknown gate '{cmd[0]}' -- not in GATE_IDS. run_circuit_jit "
330
+ f"does not silently drop unrecognized gates (same policy as "
331
+ f"run_circuit_jit_beast_mode, issue #4)."
332
+ )
333
+ g_id = float(GATE_IDS[name])
334
+
335
+ if g_id < 20:
336
+ q1 = int(cmd[1])
337
+ param = float(cmd[2]) if len(cmd) > 2 else 0.0
338
+ rows.append([g_id, float(q1), float(q1), param, 0.0])
339
+ continue
340
+
341
+ q1 = int(cmd[1])
342
+ q2 = int(cmd[2])
343
+ param = float(cmd[3]) if len(cmd) > 3 else 0.0
344
+
345
+ if abs(q1 - q2) == 1:
346
+ lo, hi = (q1, q2) if q1 < q2 else (q2, q1)
347
+ needs_transpose = q1 > q2
348
+ rows.append([g_id, float(lo), float(hi), param, 1.0 if needs_transpose else 0.0])
349
+ else:
350
+ seq, gate_index, needs_transpose = _expand_nonlocal_2q_positions(q1, q2)
351
+ for i, (a, b) in enumerate(seq):
352
+ if i == gate_index:
353
+ rows.append([g_id, float(a), float(b), param, 1.0 if needs_transpose else 0.0])
354
+ else:
355
+ rows.append([23.0, float(a), float(b), 0.0, 0.0]) # SWAP
356
+
357
+ return rows
358
+
359
+
360
+ def _build_mps_runner(n_qubits: int, max_bond: int, eps: float, jsd_budget: float):
361
+ """Factory: builds and returns a single @jax.jit-compiled closure that
362
+ runs an entire pre-compiled MPS circuit via jax.lax.scan -- same
363
+ factory pattern as chunk.py's _build_multi_chunk_runner, closing over
364
+ the static n_qubits/max_bond/eps/jsd_budget (fixed for one
365
+ MPSSimulator instance's whole lifetime, so the returned closure is
366
+ built once and cached on the instance, never rebuilt per call)."""
367
+
368
+ def step(carry, row):
369
+ gammas, lambdas = carry
370
+ dtype = gammas.dtype
371
+
372
+ g_id = row[0].astype(jnp.int32)
373
+ q1 = row[1].astype(jnp.int32)
374
+ q2 = row[2].astype(jnp.int32)
375
+ param = row[3]
376
+ transpose_flag = row[4] > 0.5
377
+
378
+ def branch_1q(c):
379
+ gammas_, lambdas_ = c
380
+ gate_1q = _mps_1q_matrix(g_id, param, dtype)
381
+ new_g = jnp.einsum('ij,ljr->lir', gate_1q, gammas_[q1])
382
+ new_carry = (gammas_.at[q1].set(new_g), lambdas_)
383
+ # Placeholder diagnostics for a 1-qubit step -- run_circuit_jit
384
+ # filters these out by g_id (>=20) before using the per-step
385
+ # history, same as _bond_history/jsd_per_bond only ever
386
+ # growing on 2-qubit gates in the eager path today.
387
+ diag = (jnp.asarray(0, dtype=jnp.int32), jnp.asarray(0.0, dtype=jnp.float64),
388
+ jnp.asarray(0.0, dtype=jnp.float64), jnp.asarray(0.0, dtype=jnp.float64))
389
+ return new_carry, diag
390
+
391
+ def branch_2q(c):
392
+ # Traced unconditionally only when this branch is taken --
393
+ # jax.lax.cond (not jnp.where) skips the untaken branch's
394
+ # compute entirely, same choice compiler.py's do_2q makes for
395
+ # its own outer 1q/2q split: the SVD here is real work, worth
396
+ # skipping for the common case of a 1-qubit gate.
397
+ gammas_, lambdas_ = c
398
+ gate_2q = _mps_2q_matrix(g_id, param, dtype)
399
+ gate_2q = jnp.where(transpose_flag, jnp.transpose(gate_2q, (1, 0, 3, 2)), gate_2q)
400
+
401
+ g1 = gammas_[q1]
402
+ g2 = gammas_[q2]
403
+ lam = lambdas_[q2]
404
+ theta = jnp.einsum('lik,k,kjr->lijr', g1, lam, g2)
405
+ theta_new = jnp.einsum('abcd,ecdf->eabf', gate_2q, theta)
406
+ theta_mat = theta_new.reshape(max_bond * 2, 2 * max_bond)
407
+
408
+ U, S, Vh = jnp.linalg.svd(theta_mat, full_matrices=False)
409
+ chi_new, jsd_val = _vectorized_chi_search_jax(S, eps, jsd_budget, max_bond)
410
+
411
+ col_mask = jnp.arange(max_bond) < chi_new
412
+ U_masked = jnp.where(col_mask[None, :], U[:, :max_bond], 0.0)
413
+ S_fixed = jnp.where(col_mask, S[:max_bond], 0.0)
414
+ Vh_masked = jnp.where(col_mask[:, None], Vh[:max_bond, :], 0.0)
415
+
416
+ new_g1 = U_masked.reshape(max_bond, 2, max_bond)
417
+ new_g2 = Vh_masked.reshape(max_bond, 2, max_bond)
418
+
419
+ new_gammas = gammas_.at[q1].set(new_g1).at[q2].set(new_g2)
420
+ new_lambdas = lambdas_.at[q2].set(S_fixed)
421
+
422
+ # Same formulas as the eager _apply_nonlocal_2q/apply_gate_2q
423
+ # path (trunc_err = sqrt(sum(S[chi_new:]**2)), entropy from
424
+ # the truncated distribution), rewritten vectorized/static-
425
+ # shape (jnp.where masking instead of Python len()/list
426
+ # filtering) -- same idiom _jsd_vectors_jax already uses.
427
+ trunc_err = jnp.sqrt(jnp.sum(jnp.where(jnp.arange(2 * max_bond) >= chi_new, S ** 2, 0.0)))
428
+ p_dist = S_fixed ** 2 / (jnp.sum(S_fixed ** 2) + 1e-20)
429
+ ee = -jnp.sum(jnp.where(p_dist > 1e-20, p_dist * jnp.log2(jnp.where(p_dist > 1e-20, p_dist, 1.0)), 0.0))
430
+
431
+ new_carry = (new_gammas, new_lambdas)
432
+ diag = (chi_new.astype(jnp.int32), jsd_val.astype(jnp.float64),
433
+ trunc_err.astype(jnp.float64), ee.astype(jnp.float64))
434
+ return new_carry, diag
435
+
436
+ is_2q = g_id >= 20
437
+ new_carry, diag = jax.lax.cond(is_2q, branch_2q, branch_1q, carry)
438
+ return new_carry, diag
439
+
440
+ @jax.jit
441
+ def run(gammas, lambdas, compiled_ops):
442
+ (final_gammas, final_lambdas), diag = jax.lax.scan(step, (gammas, lambdas), compiled_ops)
443
+ return final_gammas, final_lambdas, diag
444
+
445
+ return run
446
 
447
 
448
  class MPSSimulator:
 
489
  # circuit with max_bond=2, while avg_JSD read 0.0534).
490
  self.budget_violations: int = 0
491
 
492
+ # Cached compiled closure for run_circuit_jit -- built lazily on
493
+ # first use (self.n/self.chi/self.eps/self.jsd_budget are fixed
494
+ # for this instance's lifetime), never rebuilt per call. Same
495
+ # caching pattern as Chunk.__init__'s self._multi_chunk_runner.
496
+ self._mps_runner = None
497
+
498
  for _ in range(n_qubits):
499
  g = jnp.zeros((1, 2, 1), dtype=jnp.complex64 if not jax.config.jax_enable_x64 else jnp.complex128)
500
  g = g.at[0, 0, 0].set(1.0)
 
658
  f"get_probabilities_sampled or get_top_k_probable_states "
659
  f"instead for n > 24."
660
  )
661
+ # Index [0] rather than .squeeze(axis=0)/.squeeze(axis=-1): the
662
+ # boundary axis has size 1 in the eager (unpadded) representation
663
+ # (squeeze and [0]-indexing are identical there), but size
664
+ # max_bond after run_circuit_jit's fixed-shape padding -- the real
665
+ # boundary content is always at index 0 by construction either
666
+ # way (see _pad_gamma), so [0]-indexing is the strict
667
+ # generalization that works for both, not a behavior change for
668
+ # the pre-existing eager path.
669
+ result = self.gammas[0][0, :, :]
670
  for i in range(1, self.n):
671
  lam = self.lambdas[i]
672
  g = self.gammas[i]
673
  lg = jnp.einsum("k,kir->kir", lam, g)
674
  result = jnp.tensordot(result, lg, axes=([-1], [0]))
675
  result = result.reshape(-1, result.shape[-1])
676
+ sv = result[..., 0]
677
  norm = jnp.linalg.norm(sv)
678
  return sv / (norm + 1e-15)
679
 
 
779
  f"avg_JSD={self.avg_jsd():.4f} | EE_max={ee_max:.3f}b | "
780
  f"budget_violations={self.budget_violations}"
781
  )
782
+
783
+ # ── JIT-fused whole-circuit execution ─────────────────────────────
784
+ def run_circuit_jit(self, ops: List) -> None:
785
+ """Runs an entire circuit through a single jax.lax.scan-fused,
786
+ @jax.jit-compiled kernel instead of one eager Python call per gate
787
+ -- the eager path (apply_gate_1q/apply_gate_2q/_apply_nonlocal_2q,
788
+ all still available and unchanged) has zero @jax.jit anywhere and
789
+ pays a host-device sync on every 2-qubit gate's bond-dimension
790
+ search; measured 88.9s vs Qiskit Aer's 0.64s on a 60-qubit stress
791
+ circuit -- see README changelog for the real before/after number
792
+ this method produces on that same circuit.
793
+
794
+ Trade-off, explicit and intentional (not hidden): every gamma/
795
+ lambda is kept at a fixed max_bond-padded size for the rest of
796
+ this instance's lifetime after this call. Structurally correct
797
+ either way (zero-padding is mathematically transparent to every
798
+ other method here -- contract_to_statevector, get_top_k_probable_
799
+ states, etc. all still work correctly on the padded arrays,
800
+ verified), just not memory-minimal for genuinely low-entanglement
801
+ circuits, which is this module's whole point for very large qubit
802
+ counts. Use the eager methods directly instead when memory, not
803
+ speed, is the priority -- this is an addition, not a replacement.
804
+
805
+ ops: same convention as DenseSVSimulator.run_circuit_jit_beast_mode
806
+ -- list of (name, *args) tuples/lists. Unlike that method, SWAP is
807
+ never decomposed into 3xCX (kept as one real gate, see
808
+ _compile_mps_ops's docstring for why that matters here).
809
+ """
810
+ compiled_rows = _compile_mps_ops(ops, self.n)
811
+ dtype = self.gammas[0].dtype
812
+ lambda_dtype = self.lambdas[0].dtype
813
+
814
+ if compiled_rows:
815
+ ops_array = jnp.array(compiled_rows, dtype=jnp.float64)
816
+ else:
817
+ ops_array = jnp.zeros((0, 5), dtype=jnp.float64)
818
+
819
+ if self._mps_runner is None:
820
+ self._mps_runner = _build_mps_runner(self.n, self.chi, self.eps, self.jsd_budget)
821
+
822
+ gammas_padded = jnp.stack([_pad_gamma(g, self.chi).astype(dtype) for g in self.gammas])
823
+ lambdas_padded = jnp.stack([_pad_lambda(l, self.chi).astype(lambda_dtype) for l in self.lambdas])
824
+
825
+ final_gammas, final_lambdas, diag = self._mps_runner(gammas_padded, lambdas_padded, ops_array)
826
+
827
+ self.gammas = [final_gammas[i] for i in range(self.n)]
828
+ self.lambdas = [final_lambdas[i] for i in range(self.n + 1)]
829
+
830
+ # Bookkeeping parity: jax.lax.scan's stacked per-step diagnostics
831
+ # (diag) replace the eager path's Python list.append()s inside the
832
+ # loop -- same final content, populated differently. Only 2-qubit
833
+ # steps (g_id >= 20, includes SWAP -- the eager _apply_nonlocal_2q
834
+ # path routes its SWAPs through apply_gate_2q too, so its history
835
+ # lists grow on those as well, not just the "real" gate) count.
836
+ if compiled_rows:
837
+ chi_history, jsd_history, trunc_err_history, entropy_history = (
838
+ np.asarray(diag[0]), np.asarray(diag[1]), np.asarray(diag[2]), np.asarray(diag[3]))
839
+ g_ids = np.asarray([row[0] for row in compiled_rows])
840
+ q1_ids = np.asarray([int(row[1]) for row in compiled_rows])
841
+ is_2q_mask = g_ids >= 20
842
+ for i in np.nonzero(is_2q_mask)[0]:
843
+ chi_new = int(chi_history[i])
844
+ jsd_val = float(jsd_history[i])
845
+ self._bond_history.append(chi_new)
846
+ self.jsd_per_bond.append(jsd_val)
847
+ self.truncation_errors.append(float(trunc_err_history[i]))
848
+ q1 = q1_ids[i]
849
+ if q1 < len(self.entanglement_entropy):
850
+ self.entanglement_entropy[q1] = float(entropy_history[i])
851
+ if jsd_val > self.jsd_budget:
852
+ if self.budget_violations == 0:
853
+ warnings.warn(
854
+ f"MPSSimulator: bond dimension capped at max_bond={self.chi}, "
855
+ f"jsd_budget={self.jsd_budget:.1e} not honored "
856
+ f"(jsd={jsd_val:.2e}) -- results may be unreliable, "
857
+ f"consider raising max_bond.",
858
+ UserWarning,
859
+ stacklevel=2,
860
+ )
861
+ self.budget_violations += 1
dense_evolution/parser.py CHANGED
@@ -526,14 +526,19 @@ class QASMParser:
526
  `{'__builtins__': {}}` entirely), fixed in this version.
527
 
528
  Handles: numeric literals, pi, pi/2, sqrt(2), cos(0.3), etc.
529
- Returns 0.0 on any evaluation error (silent fallback) β€” same
530
- contract as before, unrelated inputs behave identically.
 
 
 
 
 
531
  """
532
  try:
533
  tree = ast.parse(tok, mode='eval')
534
  return float(self._eval_ast_node(tree, self._MATH_ENV))
535
- except Exception:
536
- return 0.0
537
 
538
  @staticmethod
539
  def _split_params(s: str) -> List[str]:
 
526
  `{'__builtins__': {}}` entirely), fixed in this version.
527
 
528
  Handles: numeric literals, pi, pi/2, sqrt(2), cos(0.3), etc.
529
+ Raises ValueError on anything else β€” malformed expressions (e.g.
530
+ 'pi * / 2') and disallowed/malicious expressions alike. Used to
531
+ silently return 0.0 on any evaluation error instead; that hid a
532
+ typo as a *different, valid* circuit (rx(0) instead of an error)
533
+ with no signal anything was wrong β€” the same class of
534
+ silent-wrong-behavior issue already fixed for unknown gate names
535
+ and mismatched parameter batches (issues #4/#6).
536
  """
537
  try:
538
  tree = ast.parse(tok, mode='eval')
539
  return float(self._eval_ast_node(tree, self._MATH_ENV))
540
+ except Exception as e:
541
+ raise ValueError(f"Invalid gate parameter expression '{tok}': {e}") from e
542
 
543
  @staticmethod
544
  def _split_params(s: str) -> List[str]: