Changelog¶
Included directly from the repository README.md
so it never goes stale relative to the single source of truth.
v8.1.43¶
- Added: seven standard-convenience functions Qiskit/PennyLane ship as everyday API that this package didn't:
entangling_layer(n, pattern='linear'|'circular'|'full'|'star'|'brick'),pauli_expectation/pauli_sum_expectation(Pauli-string expectation values via O(dim) bit manipulation, never building the 2^n_qubits Hamiltonian matrix),ghz_state(n),sample_counts(sv, n_shots)(Qiskit-styleget_counts()),statevector_fidelity(a, b)(the pure-state counterpart touhlmann_fidelity, which only handles density matrices),qft(n, inverse=False, do_swaps=True),random_circuit(n_qubits, n_gates, ...), anddraw_circuit(circuit, n_qubits)(plain-text diagrams). The first five were confirmed as real gaps, not speculative additions: the same patterns were found hand-duplicated with no shared, tested implementation across 20+ VQE/observable scripts and every test/experiment that preps a GHZ or Bell state, in this repo and the siblingDense-Evolution-Ising-Tests.qft/random_circuit/draw_circuitround out the pass for completeness (no internal duplication motivated them the same way). - Real bug found and fixed while verifying
pauli_expectation: the first implementation assumed qubitqis bitqof the basis-state index.DenseSVSimulatoractually stores qubit 0 as the most significant bit (confirmed empirically and matchesconftest.py's own patchedmeasure():phys_q = self.n - 1 - qubit_idx). Fixed and re-verified — 500 random 4-qubit states cross-checked against brute-force dense Pauli matrices (numpy.kron), exact match (max error 0.00e+00).qftwas verified the same way: max error 1.4e-15 against the analytic DFT matrix across 1-4 qubits, plus an exact QFT-then-inverse-QFT round trip. - Real bug caught before commit:
draw_circuit's first version used Unicode box-drawing characters (─│●), which crashedprint()on a default Windows console (cp1252 can't encode them). Switched to plain ASCII (-|*) — a diagram meant for a terminal or log file has to survive whatever console encoding the caller has. - 72 new tests across
test_topology.py/test_observables.py/test_states.py/test_measurement.py/test_qft.py/test_random_circuit.py/test_drawing.py. - Added:
macos-latestto the CI test matrix (previouslyubuntu-latestonly), prompted by a direct question about macOS support that had never actually been verified. This surfaced two real, unrelated macOS-only process crashes, both fixed: - Qiskit itself segfaults on macOS CI runners.
qiskit.circuit.QuantumCircuit.__init__— the simplest possible call,QuantumCircuit(3)— reproducibly crashed the whole process (SIGSEGV) on Python 3.10/3.11/3.12, macos-latest (arm64), deterministically at the same line every time. Not a Dense-Evolution bug: every Dense-Evolution-only test passed cleanly on macOS before hitting this file. First fix attempt (skipifon the test class) didn't actually solve it —qiskit = pytest.importorskip('qiskit')is a class-body statement, and pytest runs class bodies at collection time regardless of a skip marker on the class, so qiskit was still being imported into the process either way, and the crash just moved to a non-deterministic segfault during interpreter shutdown instead. Real fix: guard the class definition itself behindif sys.platform == 'darwin', so the class body never executes there at all; apytest.mark.skip-decorated empty stub stands in for visibility.TestPennyLaneInterop, same file, unaffected either way. - A second, unrelated shutdown-time segfault, independent of Qiskit. Confirmed by the above fix: with Qiskit fully removed from the macOS process, the exact same class of crash (SIGSEGV, exit 139) still happened on Python 3.10/macos-latest — every one of 523 tests passing,
coverage.xmlalready written, pytest's own summary already printed, then a crash a few seconds later during Python interpreter finalization. Points to native-extension teardown (most likely JAX/XLA's runtime shutdown on macOS ARM, a known category of issue unrelated to this package's own code). Fixed with atrylastpytest_sessionfinishhook inconftest.pythat callsos._exit(exitstatus)on macOS right after pytest's own work — and pytest-cov's coverage.xml write — are done, bypassing the interpreter-finalization phase that was crashing. No-op on Windows/Linux. - CI now runs 6 jobs (2 OSes x 3 Python versions) instead of 3; all green.
v8.1.42¶
- Added: a full documentation site, tatopenn-cell.github.io/Dense-Evolution — MkDocs + Material, auto-deployed to GitHub Pages on every push to
docs/**/mkdocs.yml/dense_evolution/**via.github/workflows/docs.yml. The full API reference (api/*.md, 11 module pages) is generated directly from this codebase's own docstrings viamkdocstrings(docstring_style: google), not hand-duplicated; the Changelog and License pages are single-sourced from this README andlicense.mdviamkdocs-include-markdown-pluginso they can't drift out of sync. Two real bugs surfaced only by the strict-mode CI build, both fixed before the first deploy: a docstring bracket sequence inQASMCircuit.to_tuplesmisparsed as a broken markdown link bymkdocs-autorefs, and a Linux/Windows filesystem case-sensitivity mismatch (docs/LICENSE.mdincluding../LICENSE.md, but the tracked file is lowercaselicense.md) that only failed on the Linux CI runner, not locally. - First honest self-review pass (rereading the live site page by page rather than assuming it was finished) found and fixed 6 real gaps: the Getting Started Zero-Noise-Extrapolation example referenced undefined variables and couldn't actually be run as published; the dashboard command didn't mention
app_dashboard.pyonly exists in a cloned checkout, not the pip package; there was no examples/tutorial page beyond the short Quick Start (addeddocs/examples.md— density-matrix ZNE healing, MPS for low-entanglement circuits, differentiable VQE, each adapted from already-tested code —experiments/matrix_healing_zne.py,test_mps.py,test_autodiff.py— not written fresh); related API pages had no cross-links (mitigation.md↔healing.md/registry.md,mps.md↔chunk.md/simulator.md); there was no favicon/logo (hand-authoreddocs/assets/favicon.svg, a qubit-orbit glyph in the site's own cyan accent); and there was no architecture diagram (added a Mermaid module-dependency graph todocs/index.md, traced from the realimportstatements in everydense_evolution/*.pyfile, not an idealized layering). - Second review pass found 3 more: API reference function signatures rendered as cramped single-line text because
mkdocstringsneeds Black or Ruff installed to format them (addedruffto thedocsextras — confirmed via a before/after strict rebuild that signatures now render properly indented); this README's own## ▍ Benchmarkssection (real throughput/PennyLane-comparison numbers) had no path onto the site at all (addeddocs/benchmarks.md, single-sourced from this file); andCONTRIBUTING.mdexisted in the repo but wasn't linked from the site nav (addeddocs/contributing.md— also fixed two of its relative links, tolicense.md/SECURITY.md, to absolute GitHub URLs so they resolve correctly both on GitHub and once included into the docs site, the same class of case-sensitivity fragility as the earlier LICENSE.md bug). - Added:
test_docs_examples.py, run in CI (ci.yml) on every push — locates each Python code block actually published ingetting-started.md/examples.mdby its section heading and executes it directly (not a hand-maintained copy), asserting on real output (ZNE fidelity improves, GHZ probabilities are exactly 0.5/0.5, VQE converges well below the Hamiltonian's mid-spectrum). A future signature change anywhere these examples touch now fails CI immediately instead of silently going stale until someone rereads the site by hand. Also broughtCONTRIBUTING.md's own "Running tests" command back in sync with what CI actually runs — it had already drifted, missing four test files, before this release. - This README now links the docs site prominently (a
docsbadge alongside the existing CI/PyPI badges, plus a callout line right under "What It Is").
v8.1.41¶
- Added: test coverage tracking via
pytest-cov([tool.coverage.run]/[tool.coverage.report]inpyproject.toml, adevextras group, a coverage step in CI uploadingcoverage.xmlas an artifact -- codecov badge/upload would need aCODECOV_TOKENthe user sets up themselves, not done here). Real measured project-wide coverage, honestly characterized before writing anything: an initial pass found 84.1%, driven up to 94.4% (449/450 tests passing, one isolated failure confirmed to be the same RAM-pressure artifact already documented forTestChunkMultiPiece, not a regression) by closing genuinely untested code paths acrossdashboard_core/md_telemetry.py(39.8%→100%),dashboard_core/qasm_library.py(61.1%→100%),dashboard_core/simulation_runner.py(64.4%→87.6%),dense_evolution/chunk.py(63.6%→95.9%),dense_evolution/registry.py(84.9%→99.5%), anddense_evolution/parser.py(87.6%→97.4%).dense_evolution/simulator.py(72.5%→78.6%) is limited by a confirmed coverage-tooling artifact, not a real gap:DenseSVSimulator.measure()is already thoroughly tested (TestMeasurement, 5 pre-existing tests) butcoverage/pytest-covfails to trace it correctly inside this specific large test suite -- confirmed directly with an isolatedcoverage.Coverage()script (bypassing pytest entirely) that the method traces correctly on its own, so no duplicate tests were added for it.dashboard_core/interactive_panel.py(82.0%) was deliberately left as-is, out of scope -- it overlaps with the separate, larger, not-yet-started "rebuildlaunch_interactive_panelwith full Streamlit parity" task. - Real bug found and fixed along the way:
dashboard_core.simulation_runner.estrai_valore_purosilently returned0for any numeric string input (e.g.estrai_valore_puro("3.5")returned0, not3.5) -- every Pythonstrhas a.index()method, sohasattr(elemento, 'index')was true for any string, routing it into the "object with an.indexattribute" branch before ever reaching theisinstance(str)numeric-parsing block below it; calling.index()with no arguments always raisedTypeError, silently caught and falling through to0. If the QASM parser ever handed this function a string-typed qubit index or parameter, it was silently read as0instead of the real value. Fixed by moving theisinstance(str)check to run first. chunk.py's biggest apparent gap (~200 lines, the distributed multi-device kernel) turned out to be a measurement gap, not a test gap: it's already covered byTestChunkDistributed, which only runs underXLA_FLAGS=--xla_force_host_platform_device_count=8in a separate pytest invocation (same as CI already does) -- combining both invocations' coverage data gave the real 95.9% number.- 61 new tests total across
test_dense_evolution.pyandtest_dashboard_core.py.
v8.1.40¶
- Added: full
jax.jit-compatible coverage for every function indense_evolution.mitigation--richardson_extrapolate_jit,zero_noise_extrapolation_jit(the predictive-healing branch),polynomial_extrapolate_jit,uhlmann_fidelity_jit,zne_density_matrix_jit. Each is a jit-safe_core(nonp.iscomplexobj/np.asarray/float()calls on possibly-traced values -- those breakjax.jittracing) plus an unchanged eager wrapper, the same split already used bydense_evolution.mps's_jsd_vectors_jax/_jsd_vectors. Verified: each_jitvariant matches its eager counterpart exactly; all compose correctly together inside a single outerjax.jit(the realistic use case -- several of these called in sequence inside a step function passed tojax.lax.scan, not each jitted in isolation). Real measured speedup on the fullzne_density_matrixpipeline (not a single function): 4.5x-150x across 2x2-32x32 matrices, positive in every case tested. - Checked and rejected a suggestion (from the same external-AI source as v8.1.39's rewrite) to mark
target_sigma_idealstatic viafunctools.partial(static_argnames=...):calculate_delta_preempalready usesjnp.whereinternally, not a Pythonif, so it's trace-safe as a dynamic value -- marking it static would force a fresh XLA recompilation every time a caller varies it, with no benefit. Confirmed directly by testing both ways before deciding, not by assumption. - This closes out the density-matrix ZNE healing work for now. A further step -- wiring these functions into
MPSSimulatorso error mitigation can run on tensor-network-simulated circuits -- was scoped and intentionally deferred: it requires noise-channel support for MPS (doesn't exist yet, a large feature on its own -- MPO-based or trajectory-based), reduced (not global) density-matrix extraction via partial trace (also doesn't exist yet), and handling the multiple-noise-scale requirement ZNE needs, none of which reduce to "just call the existing functions." A global density matrix is the wrong target for large-qubit MPS use in the first place -- materializing a full 2^n x 2^n matrix defeats MPS's own reason for existing. Tracked separately, not started here.
v8.1.39¶
- Changed:
project_to_physical/uhlmann_fidelityrewritten as fully vectorized,jax.jit-compatible JAX (no Pythonwhile/forloop over eigenvalues) -- the previous versions had a dynamic Python loop that isn't traceable, forcing a host round-trip on every call.project_to_physicalnow uses Euclidean projection onto the probability simplex (Held, Wolfe & Crowder 1974; also Duchi et al. 2008) applied to the eigenvalues -- a different, fully array-vectorized algorithm for the exact same convex projection problem Smolin-Gambetta-Smith's paper solves (unique global minimum, so any correct algorithm must agree).uhlmann_fidelitynow computesTr(sqrt(inner))as the sum ofinner's eigenvalues' square roots instead of reconstructing the full matrix square root. Both verified numerically identical to the previous versions (~1e-15 max difference on the SGS paper's own worked example and 30 random test matrices) and confirmed to actually compile and run underjax.jit. No behavior change for any existing caller -- same inputs, same outputs, just usable inside a jitted pipeline (e.g.jax.lax.scan) going forward. - Originated as a suggestion from an external AI (Gemini), independently verified numerically before adopting -- same source also proposed reintroducing the predictive-healing coefficient perturbation (
calculate_delta_preemp) for the density-matrix case as "the real improvement." That specific claim was rejected: it directly contradicts the already-measured result that the perturbation's effect is negligible (~0.14% coefficient shift even at a large observed coherence deviation, confirmed with a live numeric trace, not assumed) -- an external source getting a plausible-sounding architecture story right doesn't make an unverified empirical claim inside it right; each part was checked on its own.
v8.1.38¶
- Documented:
zne_density_matrix's docstring extended with a broader honest finding beyond v8.1.37's original single-configuration result.experiments/matrix_healing_zne_sweep.py(new) sweeps GHZ states from 2 to 5 qubits across all 5NoiseModelchannels (depolarizing, bitflip, phaseflip, amplitude_damping, combined). First pass (3 seeds, K=150 trajectories, 60 runs) looked mixed -- 54/60 positive, mean delta +0.09, but apparently unreliable for phaseflip/amplitude_damping (small or net-negative deltas at some qubit counts). Investigated further before trusting it:richardson_extrapolate's 3-point Lagrange coefficients (3, -3, 1) amplify statistical noise in their inputs (sum of squares 19x a single raw measurement's variance), so an undersampled density-matrix estimate makes the corrected result noisy even when the correction itself is sound -- confirmed directly by re-running the same "failing" configurations at higher K (300-1200 trajectories, more seeds), which turned them consistently and strongly positive. Re-ran the full sweep properly (K=400, 5 seeds, 100 runs total): 96/100 positive, mean delta +0.12, every single (qubit count, noise channel) combination net positive on average, growing to +0.20-0.25 at 5 qubits for depolarizing/bitflip. The 4 remaining negative runs are small (worst -0.02), consistent with residual Monte Carlo noise, not a systematic failure. No code behavior changed -- this is a documentation update, but the earlier "unreliable for phaseflip/amplitude_damping" wording in an intermediate draft of this entry was itself wrong and has been corrected here before ever reaching PyPI. zne_density_matrix's docstring carries the corrected numbers plus a practical caveat for callers: correction quality depends onrho_at_scalesbeing a low-noise (large-enough-K) estimate to begin with -- an inherent property of Richardson-style extrapolation's noise amplification, not a bug in this function.- Also tested: whether more noise-scale points (4, 5, or denser spacing) improve exact interpolation further. They don't -- more points make Lagrange coefficients larger (worse with denser spacing, a Runge's-phenomenon-like effect), amplifying noise further: mean delta drops from +0.148 (3 points, the original choice) to +0.081 (5 points, same spacing) to -0.220 (5 points, denser spacing -- actively worse than not correcting at all on some channels).
- Added:
dense_evolution.mitigation.polynomial_extrapolate-- least-squares polynomial extrapolation to zero noise, generalizingrichardson_extrapolate. At exactlydegree + 1points it's mathematically identical to exact interpolation (verified to 1e-12); with MORE points it becomes an overdetermined fit that trades a little bias for real variance reduction instead of the exact interpolation instability above.zne_density_matrixnow uses this (degree=2 default) instead ofrichardson_extrapolate-- at the standard 3-point setup this changes nothing (mathematically identical, all prior tests pass unchanged), but makes "pass more noise-scale points" safe instead of a trap. - Real, measured gain, fixed total measurement budget (
experiments/matrix_healing_fixed_budget.py, the fair comparison -- splitting the same total number of Monte Carlo trajectories differently, not spending more): 3 points x K=400 (1200 total, classic 3-point ZNE) vs. 5 points x K=240 (1200 total, degree=2 fit) vs. 7 points x K=171 (~1200 total). 5 points matches or slightly beats the 3-point mean improvement (+0.150 vs +0.148) with 19% lower variance (std 0.050 vs 0.062) -- a free reliability gain at equal experimental cost. 7 points trades a little mean (+0.132) for 30% lower variance (std 0.043), a genuine tradeoff point. - Tested and rejected, for honesty: (1) applying
zero_noise_extrapolation's existing predictive-healing coefficient perturbation (calculate_delta_preemp, originally designed for scalar coherence signals around target_sigma_ideal=10) to density matrices, using either matrix purity or Jensen-Shannon divergence (dense_evolution.mps._jsd_vectors) as the coherence signal -- no measurable effect even amplified 100x over its default strength. (2) Selecting the polynomial degree per-run via leave-one-out cross-validation on the noisy points themselves -- worse than a fixed degree (mean +0.113 vs +0.150, higher variance), because LOOCV on few noisy points is biased toward under-fitting. (3) Selecting degree via the same JSD coherence signal -- no exploitable correlation found between JSD and which degree actually performs best (degree 2 and 3 win about equally often across the whole measured JSD range). None of these are shipped;degree=2fixed remains the best-tested default.
v8.1.37¶
- Added:
dense_evolution.mitigation.zne_density_matrix/project_to_physical/uhlmann_fidelity-- Zero-Noise Extrapolation extended from scalars/vectors to full density matrices, for noisy simulations tracked as ρ rather than a single statevector.project_to_physicalimplements Smolin, Gambetta & Smith's "Maximum Likelihood, Minimum Effort" (2012, arXiv:1106.5458) eigenvalue-projection algorithm (transcribed and checked against the paper's own worked numeric example before use) to correct the rawrichardson_extrapolateoutput on a matrix stack -- polynomial extrapolation across noise-scaled density matrices is not itself guaranteed to be a valid (positive-semidefinite) density matrix, even when every input was.uhlmann_fidelityis a validation-only utility (F(ρ_A,ρ_B) = (Tr√(√ρ_A ρ_B √ρ_A))², reduces to|⟨ψ_A|ψ_B⟩|²for pure states, verified directly) -- deliberately not accepted as an input anywhere in the correction path, keeping "the ideal state is a grading criterion, not something the algorithm gets to see" structural rather than a convention callers have to remember on their own (the general principle: an error-mitigation technique that needs to know the answer already isn't one). - Honest, measured result (
experiments/matrix_healing_zne.py, reproducible): 2-qubit Bell state,NoiseModeldepolarizing noise at base_p=0.05, scales 1x/2x/3x, a 200-trajectory Monte Carlo density-matrix estimate per scale, averaged over 4 independent random seeds -- raw noisy fidelity ~0.865, corrected (extrapolated + projected) fidelity ~0.947, a real improvement of ~+0.08, positive individually on every seed tested (range +0.060 to +0.106). This is one measured data point in one noise regime, not a general guarantee -- other noise models, circuits, or noise strengths are untested and may behave differently; the docstrings say exactly this, not more. - This formalizes an experiment built directly on top of v8.1.36's
richardson_extrapolatecomplex-dtype fix -- the same experiment run before that fix gave an invalid, misleadingly negative result (corrected fidelity worse than raw) purely because the bug was silently discarding the density matrices' imaginary parts, not because the technique doesn't work.
v8.1.36¶
- Fixed:
dense_evolution.mitigation.richardson_extrapolate(andzero_noise_extrapolation's healing-adapted branch) hardcodeddtype=jnp.float64forexpectation_values, silently discarding the imaginary part of complex input with only a low-signalComplexWarning, no explicit error. Real inputs (the only case exercised by any existing caller) were unaffected, but any complex-valued caller -- e.g. extrapolating density-matrix entries, which are complex off-diagonal in general -- got a silently wrong, purely-real result. Found while building a density-matrix-healing experiment on top of this function; verified directly pre-fix (richardson_extrapolate([1+2j, 3+4j], ...)returned a purely real value, dropping real information). Fixed by pickingvalues's dtype from the input itself (jnp.complex128ifnp.iscomplexobj(expectation_values), elsejnp.float64-- identical behavior to before for every existing real-valued call site, verified: all prior tests pass unchanged).
v8.1.35¶
- Added:
MPSSimulator.run_circuit_jit(ops)-- ajax.lax.scan-fused,@jax.jit-compiled whole-circuit execution path forMPSSimulator, which previously had zero@jax.jitanywhere in the file: every gate ran as an eager JAX call, and the adaptive bond-dimension search inside_svd_truncatewas a Pythonwhileloop forcing a host-device sync on every 2-qubit gate. Measured directly on a 60-qubit/428-gate stress circuit (the same one used to originally diagnose this): 88.9s (eager) -> 0.74s (fused, steady-state post-compile), ~120x faster, now within range of Qiskit Aer's MPS backend (0.64s) on the same circuit -- same physics exactly (chi_used=16,budget_violations=0,avg_JSD=0.0000, matching the eager run's own summary). - The two root causes, quantified before fixing: (1) zero JIT fusion -- confirmed via direct grep, not assumed; (2) non-adjacent 2-qubit gates expand into a SWAP chain at runtime, multiplying the real SVD-bearing gate count 2.4x on the stress circuit (187 logical 2-qubit gates -> 451 real
apply_gate_2qcalls, counted directly). - New technique (no precedent for this specific problem in
chunk.py's own earlier JIT fusion, issue #5, whose geometry never changes gate-to-gate): the bond-dimension search is now a single vectorized pass (JSD computed for every candidate truncation size at once viajax.vmap, replacing the incrementingwhileloop) over gamma/lambda tensors padded to a fixedmax_bondsize always, with the real bond dimension tracked as a traced scalar and everything beyond it zero-masked rather than dynamically sliced (jax.lax.scan's carry requires constant shape/dtype every step). Non-adjacent gates are expanded into their SWAP-chain-equivalent adjacent-only op sequence at Python pre-compile time instead of via runtime dispatch, mirroringchunk.py::_compile_multi_chunk_ops's "all gate-identity branching happens before tracing starts" principle. apply_gate_1q/apply_gate_2q/_apply_nonlocal_2q(the eager path) are unchanged and still available --run_circuit_jitis a new, additional entry point, not a replacement. Explicit, intentional trade-off: the fused path pads every gamma/lambda tomax_bondfor the rest of the instance's lifetime after the call, trading this module's adaptive-memory benefit (its whole point for very large, low-entanglement circuits) for speed -- use the eager methods directly when memory, not speed, matters more.- Verified in 5 separately-checked stages, each against real data before moving to the next: (1) the vectorized bond-dimension search matches the eager
whileloop's(chi_new, jsd_val)exactly across 171 real cases from real circuits, including the budget-violation fallback; (2) the SWAP-chain pre-expansion matches the real runtime dispatch's exact call sequence across all 330(q1, q2)pairs for 3 qubit counts, plus an end-to-end final-state replay check; (3) the fused kernel matchesDenseSVSimulatoron real entangling circuits (TVD < 1e-6) and matches the eager path bit-for-bit (fidelity 1.0 to machine precision) even under a genuinebudget_violationstruncation scenario, both dtypes; (4)entanglement_entropy/_bond_history/jsd_per_bond/truncation_errors/budget_violationsend up populated identically to the eager path (machine-precision match), sourced fromjax.lax.scan's stacked per-step diagnostics instead of Python list appends; (5) the real speed number above. contract_to_statevectorgeneralized (.squeeze(axis=0)/.squeeze(axis=-1)->[0]-indexing) to work correctly on both the original unpadded boundary tensors (identical behavior, verified against the full existing test suite) and the new padded ones.
v8.1.34¶
- Fixed:
QASMParser._eval_paramsilently returned0.0for any gate-parameter expression it couldn't evaluate -- a malformed expression likerx(pi * / 2) q[0];parsed successfully and silently producedrx(0.0), a different, valid circuit, with no signal a typo had happened. Found via an independent code-review report, reproduced directly (ast.parse('pi * / 2', mode='eval')itself correctly raisesSyntaxError-- the bug was a blanketexcept Exception: return 0.0around it, added when the previous raw-eval()code-execution vulnerability was fixed, that swallowed genuine syntax errors along with rejected/malicious expressions). Now raisesValueErrorinstead, for both cases -- malformed expressions and disallowed/malicious ones alike (still structurally blocked by the same AST node-type whitelist either way, just explicit about it instead of silent). Same class of silent-wrong-behavior issue already fixed for unknown gate names and mismatched parameter batches (v8.1.27, issues #4/#6). 2 existing security tests (test_eval_param_blocks_sandbox_escapes, the full-parse exploit test) updated to expect the raised exception instead of a silent0.0; 2 new regression tests added for the originally-reported malformed-expression case.
v8.1.33¶
- Fixed:
MPSSimulator._apply_nonlocal_2qsilently swapped which qubit acted as gate-argument-1 vs gate-argument-2 whenever a non-adjacent 2-qubit gate (abs(q1-q2) != 1) was called withq1 > q2-- e.g.apply_cx(ctrl=3, tgt=1)-- because the SWAP chain always ends up applying the gate at(min(q1,q2), min(q1,q2)+1)regardless of the caller's original argument order. For an asymmetric gate like CNOT this silently applied the wrong gate (control/target inverted) with no error or warning. Found via an independent code-review report, reproduced directly before trusting it: building a 4-qubit GHZ state viaH(0), CX(0,3), CX(3,1), CX(1,2)gave fidelity 0.25 against the exact GHZ state ((|0000⟩+|1001⟩)/√2instead of(|0000⟩+|1111⟩)/√2). Fixed with the same q1>q2 normalizationapply_gate_2q's adjacent-qubit branch already used (transpose the gate's tensor axes, swap q1/q2) applied before the SWAP chain runs -- same fidelity check now reads 0.9999999657714559. Affectsapply_cx/apply_cz/apply_swap/apply_ccxfor any non-adjacent qubit pair called in decreasing order, reachable fromdashboard_core'sengine='mps'option on any QASM circuit with such a gate. 6 new regression tests intest_mps.py(direct repro, cross-check againstDenseSVSimulator, non-adjacent unordered-control Toffoli, both float32/float64). - Checked, not changed: the same external report also flagged
MPSSimulator.get_top_k_probable_states's amplitude summation as a potential bug -- independently re-verified against the exact contraction (matches to machine precision) and against the module's own documented history of already fixing exactly this class of bug. No live issue found. Its performance observation (thewhileloop in_svd_truncateisn'tjax.jit-compiled) is real but is a speed question, not correctness, and is deliberately out of scope here. - Added:
dashboard_core.run_md_telemetrynow computes real molecular-dynamics-style telemetry (exact phase evolution under the selected diagonal Hamiltonian, plusdense_evolution's ownNoiseModeldriving a physically-grounded thermal-noise channel) whenever a compatible Hamiltonian and the circuit's current statevector are supplied, instead of always returning the synthetic placeholder data (run_md_simulation_dummy, documented as a placeholder since it was first written) that shipped every prior version. Falls back to the same labeled mock when no compatible Hamiltonian is active -- the result now carriesdf.attrs['is_real']/df.attrs['note']so callers (and the UI) can show honestly whether a given MD panel is real or a demonstration, rather than presenting synthetic numbers as if they were physics. Energy/entropy/purity are all genuinely computed (purity via an ensemble-averaged density matrix, exact given the ensemble -- everyLIBRERIA_HAMILTONIANEentry is ≤6 qubits, so this stays cheap). Wired into bothui_pages/quantum_simulator.py(Streamlit) and the new interactive panel below with a visible "DATI REALI" / "MOCK" badge on the MD tab. - Added:
dashboard_core.launch_interactive_panel-- a full ipywidgets-based interactive dashboard for Colab/Jupyter, built directly ondashboard_core's existing functions (not a port of the oldlegacy/dash.pynotebook export). Same panels as the Streamlit page (Overview, Fisica Stato, Mosaico, VQE Results, MD Results, Performance, 3D Helix, Hamiltonian, Mitigation (ZNE)) and the same sidebar controls (circuit source, engine, noise, ZNE/predictive healing, VQE, custom Hamiltonian, MD), driven by ipywidgets instead of Streamlit's rerun model -- stays inside a single notebook cell's output, no external tunnel/link. Requires thedashboardextra'sipywidgets>=8.0.0(now included in that extra).
v8.1.32¶
- Added:
dashboard_core.mitigation_runner.run_mitigation_sweep/dashboard_core.mitigation_panel.build_panel_mitigation-- Zero-Noise Extrapolation and predictive healing, wired into the Streamlit dashboard as a real feature for the first time (dense_evolution.mitigation/dense_evolution.healingexisted in the core package but had zero references anywhere in the dashboard before this). Runs the active circuit at 3 noise scales (1x/2x/3xthe sidebar's noise probability) and extrapolates to zero noise viazero_noise_extrapolation, reused exactly as-is -- no reimplementation of the Richardson/healing math in the dashboard layer. New sidebar section ("🩹 Error Mitigation (ZNE)") and a new "Mitigation (ZNE)" tab showing fidelity-vs-noise-scale and ideal/raw/ZNE-corrected probability overlays; the healing-adapted path's coherence signal (sigma_at_base_noise) reuses the shot-noise binomial sigma already computed and shown elsewhere in the dashboard (build_panel_overview's NISQ Shot Histogram) as a pragmatic proxy, documented as such rather than presented as a first-principles derivation. - Fixed:
dense_evolution.mitigation.richardson_extrapolateraisedValueError: Incompatible shapes for broadcastingwheneverexpectation_values[i]was itself array-valued (e.g. a full probability distribution per noise scale, not a bare scalar) -- found building the panel above, where each noise scale's "expectation value" is naturally a whole probability vector. Root cause: stackingexpectation_valuesviajnp.asarrayand multiplying by the(n,)-shaped Lagrange coefficients relied on JAX's default trailing-axis broadcast alignment, which pairs the coefficients against the last axis of the stacked array instead of the leading "one row per noise scale" axis. Fixed by reshaping the coefficients to broadcast against the leading axis explicitly and summing overaxis=0-- a no-op reshape for the pre-existing scalar case (verified: all prior scalar-input tests pass unchanged), now also correct for vector/array-valued inputs. - Fixed:
dashboard_core.run_simulation'sseedparameter only ever reachednp.random.seed()(shot sampling) -- for a JAX statevector (the normal case), the actual noise channel applied viaNoiseModel.apply_to_svwas never givenrng=/jax_key=, so it silently fell back to OS-entropy randomness regardless ofseed. Two calls with the identical seed produced different noisy results. Found as a flaky test (run_mitigation_sweep's 3-noise-scale sweep, same seed passed to each scale, expected -- and needed, for a meaningful extrapolation -- the same underlying noise realization scaled byp, got a fresh random one each time). Fixed by passingrng=np.random.default_rng(seed)explicitly toapply_to_sv. - Refactor:
dashboard_core.py(1900-line single file) split into a package (dashboard_core/:qasm_library,hamiltonians,simulation_runner,vqe_engine,md_telemetry,plot_theme,metrics,panels,helix_3d,mitigation_runner,mitigation_panel,provenance) behind a backward-compatible__init__.pyfaçade re-exporting the same public surface --import dashboard_core as dcand everydc.xxxcall site unchanged, verified via the existing test suite passing identically with zero test-file edits._series_plot/_series_enhanced/_energy_enhanced(three near-duplicate time-series plotting functions,_energy_enhancedduplicating_series_enhanced's logic inline instead of calling it) unified into one parameterized_series_plot. Hardcoded color literals inbuild_panel_fisica/vqe_results/md_results/performancethat exactly matched an existingplot_theme.Cvalue now reference it instead of repeating the literal -- zero visual change, by construction; near-miss shades (close but not identical to aC[...]value) deliberately left alone rather than forced onto the "closest" key, which would have been a small but real, unauthorized color drift. - Also fixed:
.github/workflows/ci.ymlnever rantest_mitigation.pyortest_mps.py. - Refactor (
ui_pages/, repo-only, not part of the pip package): the gradient header banner, the "run → session_state → guard → render" early-return pattern, and the neutral AI-shield metadata dict were each copy-pasted across 2-3 ofquantum_simulator.py/vector_healing.py/quantum_scars.py/ai_middleware.pyinstead of shared. Newui_pages/components.pyhelpers (render_page_banner,render_run_guard,render_matplotlib_figure) andAI_SHIELD_NEUTRAL_METAreplace them -- same visuals, one place to change instead of three. Fixes, as a side effect, three independently-drifted hardcoded version numbers in the page banners (v8.1.9/v8.1.7/v8.1.22) plus a fourth inapp_dashboard.py's ownst.set_page_config/docstring -- all four now readdense_evolution.__version__instead of a stale literal. Verified: existingtest_ai_middleware.py/test_quantum_scars.pypass unchanged (22/22); allui_pagesmodules import cleanly; the actual Streamlit server started and served all 3 page routes with no server-side exceptions in the log (no automated UI test exists for this layer, per the pre-existing documented gap -- this is the closest verification available without a browser screenshot tool in this environment).
v8.1.31¶
- Changed:
dashboard_core(the compute/panel layer behind the Streamlit dashboard) is now part of the installable package (pyproject.toml'spackages), not repo-only --pip install dense-evolution[dashboard,jax]alone now givesimport dashboard_core as dcwith the full 53-circuit QASM library and every panel builder, nogit clonerequired. Superseded within the same release by v8.1.32's package split (dashboard_core.py→dashboard_core/) -- the packaging mechanism changed from a singlepy-modulesentry to a real package directory, but the end result (pip installalone is sufficient) is unchanged.
v8.1.30¶
- Added:
Chunk.run_chunk_distributed-- dispatches the multi-chunk kernel across a real JAX device mesh (jax.shard_map+jax.lax.ppermute) instead of one process's RAM, one physical chunk per device (issue #1, v1 scope:jax.device_count() >= num_chunks). Cross-chunk gate mixing becomes point-to-point communication viappermute, keyed on the fixed XOR-stride pairing between chunk indices -- the same pairwise-exchange pattern real distributed statevector simulators use; gates entirely local to a chunk, or with a chunk-select control and a local target (decidable from a device's own chunk index alone), need no communication at all. Verified for correctness againstDenseSVSimulatoron simulated multi-device CPU (XLA_FLAGS=--xla_force_host_platform_device_count=N) across all 6 gate/qubit-location cases individually, randomized mixed circuits atnum_chunksin {4, 8}, and both dtypes -- CI now runs these in a dedicated step with 8 simulated devices (they skip cleanly on a single-device run). Real GPU-cluster network performance is not and cannot be measured in a single-device CI environment -- honest scope: this validates the sharding/communication logic is correct, not real multi-GPU throughput. - Fixed while building it: the
ppermutepermutation for each chunk-select qubit was built inside a Python list comprehension with the loop variable referenced directly in the lambda body -- classic late-binding closure bug, every branch silently used the last qubit's stride regardless of which was actually selected at runtime (only the branch for the last-iterated qubit happened to come out correct, which is exactly the failure pattern that surfaced it:q0/q1wrong,q2right, on a 3-chunk-select-qubit circuit). Fixed by binding the fully-precomputed staticpermlist as a default argument, evaluated eagerly at lambda-creation time instead of looked up by reference at call time. - Also fixed:
.github/workflows/ci.ymlnever rantest_mitigation.pyortest_mps.py-- both existed and passed locally but had never actually executed in CI. Added to the main test run.
v8.1.29¶
- Added:
dense_evolution.NoiseSpec-- a JAX PyTree (model/qubitsstatic,p/jax_keyas leaves, registered viajax.tree_util.register_pytree_node) thatcircuit_to_energy_fn'senergy_fnnow accepts as a fourthnoise=argument, applyingNoiseModel.apply_to_svnatively inside the same traced computation astheta(issue #8, scoped up from #7's narrower fix). Removes the need for an external, Python-side noise-application step and manual PRNG key bookkeeping around a training loop --jax_keyis a pytree leaf, so it flows throughjax.jit/jax.grad/jax.vmap/jax.lax.scanthe same way any other JAX array does, with no OS-entropy fallback (reproducibility is structural, not opt-in). Verified: reproducible from the same key, energy differs from the ideal circuit under nonzerop, gradient w.r.t.thetaflows correctly through the noisy pipeline,jax.vmapover a batch of independent keys works with no external Python loop,jax.jit-wrapped result matches eager evaluation exactly. - Fixed: found while wiring the above --
NoiseModel.apply_to_sv'sif model == 'ideal' or p <= 0.0: return svearly-exit raisedTracerBoolConversionErroras soon aspbecame a traced value (e.g. aNoiseSpecleaf underjax.jit) -- exactly the case #8 asked to enable. Fixed with a targetedtry/exceptaround only thep <= 0.0optimization: every channel's math already reduces to a no-op atp=0(fire = r < pis alwaysFalse), so skipping the shortcut and falling through is still correct, it just loses the eager-mode fast path whenpcan't be checked concretely. - Note:
noise.pis technically a differentiable pytree leaf, but the gradient through it is ~0 almost everywhere in practice -- the existing channels sample via a hard threshold (fire = r < p), not usefully differentiable without a smooth relaxation (e.g. Gumbel-softmax). Not addressed here, out of scope for what #8 asked (removing the state/key workaround, not making noise strength itself gradient-optimizable).
v8.1.28¶
- Note: v8.1.27 was published to PyPI from a stale local checkout that predated the
mitigation.pymodule and the #4/#6/#7 fixes below -- the installable v8.1.27 package on PyPI does not contain them, despite this changelog. PyPI doesn't allow re-uploading files under an already-published version, so this release exists specifically to ship the real content. If you're on 8.1.27, upgrade to 8.1.28 -- don't rely on 8.1.27's changelog matching what you actually have installed (same situation as v8.1.15, see that entry below).
v8.1.27¶
- Added:
dense_evolution.mitigation-- a Zero-Noise Extrapolation orchestrator (richardson_extrapolate,zero_noise_extrapolation, both exported from package root) using the field's standard ZNE vocabulary, composed on top ofhealing.py's existing primitives rather than duplicating or renaming them. Motivated by the ZNE+predictive-healing combination previously existing only as hand-written logic (_static_richardson/_adaptive_healing_richardson) inside a downstream repo's test file, callingcalculate_delta_preempas one ingredient with no reusable, standard-named entry point in the package itself -- undiscoverable by name for anyone (human or AI) readingdense_evolutionlooking for "ZNE".richardson_extrapolategeneralizes to N arbitrary noise factors (verified: reduces exactly to the textbook(3, -3, 1)3-point coefficients atnoise_factors=(1,2,3), and is exact on synthetic linear data); the healing-adapted path is scoped to exactly 3 noise factors -- the only case it has been derived and verified against (cross-checked numerically against the original 3-point formula) -- and raisesNotImplementedErrorrather than silently generalizing an unverified formula for other point counts. - Breaking:
run_circuit/run_circuit_jit_beast_mode/run_parametric_batch_jitnow raiseValueErroron an unrecognized gate name instead of silently dropping the gate (issue #4). Verified pre-fix:run_circuit_jit_beast_mode([('h', 0), ('ch', 0, 1), ('x', 2)])executed onlyh/x,chvanished with no error or warning -- a typo in a gate name ('crx'instead of'crz') used to silently run a different circuit than the one written. Anyone relying on the old silent-skip behavior will now get an explicit error instead -- there is no legitimate use case for a gate name silently doing nothing. - Breaking:
run_parametric_batch_jitnow validatesparameter_batch.shape[1]against the actual number of parametric gates (rx/ry/rz/p/u1/phase/cp/crz/cphase) inbase_circuit, raisingValueErroron a mismatch instead of letting JAX's default out-of-bounds indexing clip silently (issue #6). This is the same positional-slot contract responsible for two independently-discovered corrupted-results bugs in a downstream repo (Dense-Evolution-Ising-Testsv2.1.0): a literal-float rotation gate still consumes a column, it is never exempt, and a grid built assuming otherwise used to produce a plausible-looking but wrong statevector with no signal that anything was off. - Fixed:
NoiseModel.apply_to_svused to silently ignorerngwheneversvwas a JAX array, drawing from OS entropy instead -- a caller seedingrng = np.random.default_rng(42)for reproducibility got a different, non-reproducible result on every call, silently (issue #7). Verified pre-fix directly: two consecutive calls with the identical seededrngand identical input diverged. Found while reviewing an end-to-end QML+noise+ZNE test script combiningcircuit_to_energy_fn,NoiseModel, and the newzero_noise_extrapolationunder onejax.value_and_grad-- gradients did flow correctly through the whole pipeline (that part worked as intended), but the epoch-to-epoch loss instability in that script traced back to this, not to the optimizer or tomitigation.py. Fixed: whensvis a JAX array andjax_keyisn't given explicitly,rng(if given) now derives the JAX key (rng.integers(...)seedsjax.random.PRNGKey) instead of being ignored -- a fresh, identically-seededrngnow reproduces the exact same sequence of keys across separate runs, matching the guarantee the NumPy path already gave.jax_key, when given explicitly, still takes precedence over a derived one. Makingapply_to_svitself composable inside a singlejax.jitblock (no internal Python-level branching or OS-entropy side effects) is a larger, separate redesign -- not done here, see issue #7 for the remaining scope.
v8.1.26¶
- Verified, no bug found: two areas flagged as untested in a prior RAM-constrained environment --
Chunk's genuine multi-chunk dispatch (num_chunks > 1) on a 2-qubit gate spanning the very first (chunk-select) and very last (local) qubit of the register, andQASMParser's handling offor-loops with an unresolvable bound (an undeclared bound variable, so_resolve_int_exprreturnsNone) -- both confirmed correct. Closed the real test-coverage gap: 4 new tests inTestChunkMultiPiece(the long-range 2-qubit gate case, plusMemoryPressureErroractually firing on simulated low RAM for both thenum_chunks==1andnum_chunks>1code paths -- previously only ever exercised indirectly, never asserted on directly) and 6 new tests inTestQASMForLoop(unresolvableforbound stripped cleanly with following code preserved -- verified via probability comparison, not just the op list --whileblocks, multiple unresolvable constructs in sequence, and a resolvablefor-unroll immediately followed by an unresolvableif-strip).
v8.1.25¶
- Fixed:
MPSSimulator._svd_truncateused to silently violatejsd_budgetwhenevermax_bondwas too small for the circuit's real entanglement -- thewhile jsd_val > self.jsd_budget and chi_new < max_possibleloop exits with no signal oncechi_newhitsmax_bond, even ifjsd_valis still far above budget.summary()'savg_JSDonly reports the mean of the per-step local errors, not the accumulated global error, so it can read deceptively low while the final contracted state is badly wrong -- verified directly on an 8-qubit/15-layer entangling circuit withmax_bond=2: TVD ~0.97 againstDenseSVSimulator(a near-total mismatch) whileavg_JSDread a reassuring-looking 0.0534. Added abudget_violationscounter (incremented every time this happens, exposed insummary()) and aUserWarningon the first violation ("bond dimension capped at max_bond=..., jsd_budget=... not honored ... results may be unreliable") -- not an exception, so existing code that tolerates the tradeoff keeps working, but now with an explicit, checkable signal instead of a silently-optimistic average.
v8.1.24¶
- Fixed:
dense_evolution.healing.calculate_phi_abraisedValueError: Clip received a complex valuewhen called with complex statevectors (e.g.sim.get_statevector()) --jnp.dot(semantic_change, ipg_vector)is the bilinear (non-conjugated) product on complex arrays and stays complex, which then hitjnp.clipat the end of the function. Fixed by usingjnp.real(jnp.vdot(...))-- the correct Hermitian-inner-product real part, identical tojnp.dotfor the real-valued inputs every existing caller already uses (ia_utils.vector_healing.enhanced_dense_healing_hybrid), and now also correct for genuinely complex input. Verified against a manual NumPyRe(vdot(...))calculation on a case with nonzero imaginary amplitudes (H+S gates), not just the crash repro (H+CX alone never produces a nonzero imaginary part, so it only proved "doesn't crash," not "computes the right number"). - Fixed:
ia_utils.vector_healing.median_healing/enhanced_dense_healing_hybridemittedRuntimeWarning: Mean of empty slicewhenever an input column was entirelyNaN--np.nanmeanon an all-NaN slice returnsNaNwith a warning (silently caught and zeroed by the very next line, so the output was already correct, only the warning was noise). Fixed by pre-replacing whole all-NaN columns with0.0before callingnanmean, so it never sees an empty slice -- verified byte-identical output, zero warnings, in both functions (the preprocessing block was duplicated verbatim in each). - Fixed:
enhanced_dense_healing_hybrid'sfallback_triggeredmetadata flag used to reflect only the internal Phi-Trigger heuristic classifying a step as "static", regardless of whether the input actually contained anyNaN/Inf-- verified directly that a clean, uncorrupted random Gaussian array (no corruption at all) still came backfallback_triggered=True. Root cause: the heuristic is tuned for trajectories with real underlying dynamics (verified separately against a real noisy VQE run, where it correctly stayed quiet at low noise and fired at high noise) and mistakes pure structureless IID noise -- which has no coherent trend to recognize as "genuine change" -- for anomalous static behavior on nearly every step.fallback_triggeredis now gated on the original input actually containingNaN/Inf(checked before sanitization) in addition to the fallback having fired -- the dashboard's "Fallback scattato" indicator will now only light up for genuine NaN/Inf corruption, not general noise-driven Phi-Trigger corrections (those corrections still happen internally, they're just no longer mislabeled as a NaN/Inf fallback). - Docs: removed two README rows (
kappa_stabilization,richardson_integration) describing functions that never existed indense_evolution/healing.py(confirmed against the full 140-line file -- 7 functions plusMemoryReflectionEngine, neither name present anywhere), and corrected two code examples that still showed amedian_fallback_thresholdparameter onenhanced_dense_healing_hybridthat was removed from the actual function signature back when its corresponding UI slider was dropped (commit69fc8a4) without updating the docs to match.
v8.1.23¶
- Added:
MPSSimulator(dense_evolution/mps.py, re-exported from the package root) -- a JAX-backed Matrix Product State simulator with adaptive SVD-truncated bond dimension. Verified exact againstDenseSVSimulatoron entangling circuits (TVD=0). Selectable as a dashboard engine (Quantum Simulator page) for circuits up to 24 qubits; for larger low-entanglement circuits,get_probabilities_sampled/get_top_k_probable_statesscale to hundreds of qubits without ever materializing a(2**n,)statevector. - Fixed: large-qubit circuits submitted through the dashboard used to crash the whole Streamlit process (uncatchable OS-level OOM) instead of failing cleanly. They now route automatically through the existing
Chunkanti-OOM wrapper, which raises a catchable, informativeMemoryPressureErrorinstead. - Changed (breaking): JAX is now a required core dependency (
dependencies, notoptional-dependencies) --pip install dense-evolutioninstalls it by default, no[jax]extra needed anymore. Every simulator backend in this package already required JAX in practice; the previoustry/except ImportErrornumpy-fallback path was never a real, maintained alternative and is no longer reachable (the numpy code itself is left in place for reference, just dead). If you were pinning an environment without JAX and relying on degraded-numpy behavior, this release will break that -- installdense-evolution<8.1.23to keep the old behavior.
v8.1.22¶
- Added:
ui_pages/quantum_scars.py— a new "Quantum Scars" dashboard page (app_dashboard.py'sst.navigation), an interactive live demo of the PXP quantum many-body scar model (Rydberg blockade): buildsH_PXPvia sparse Pauli operators, exact-diagonalizes it (scipy.linalg.eigh, cached viast.cache_resourcekeyed on qubit count — the first use of that decorator in this codebase, since diagonalizing a dense2**n_qubitsmatrix is genuinely expensive and depends only on that one slider), propagates a Néel initial state under real-time Hamiltonian evolution, injects real noise viaNoiseModel.apply_to_sv, and lets you compare fidelity revival with no protection, a cheap constraint-subspace projection (no extra diagonalization needed — a combinatorial mask of which computational-basis bitstrings have no two adjacent 1-bits), or an idealized exact-eigenstate "tower" projection. Distills the investigation already published atquantum_scar_investigation— which found no genuine scar in Dense Evolution's own frustrated Ising grids (wrong observable + gauge equivalence), then validated the same verification pipeline against PXP, where scars are real and well documented — into something runnable instead of only readable. Verified viastreamlit.testing.v1.AppTest(real button-click simulation, zero exceptions) and a newtest_quantum_scars.py(17 tests, all passing) unit-testing the numerical core directly: validity-mask combinatorics,H_PXPHermiticity and Hilbert dimension, fidelity=1/norm-preservation under propagation, and both projections staying normalized with zero weight outside their target subspace.
v8.1.21¶
- Added:
QASMCircuit.__iter__— duck-types a parsed circuit as an iterable of the same tuples.to_tuples()returns, so it works anywhere a plain circuit list is expected (Chunk.run_chunk,QuantumTranspiler.transpile, ...) without remembering to call.to_tuples()first. Found via a user's own Colab testing:Chunk.run_chunk(QASMParser().parse(qasm))— a very natural thing to try — raisedTypeError: 'QASMCircuit' object is not iterable. - Fixed / Performance:
Chunk's multi-chunk dispatch (num_chunks > 1) used to apply every gate through a Python loop calling non-JITapply_gate_1q/apply_gate_2q— measured 6x slower thanrun_circuit_jit_beast_modeon an identical workload. Replaced with a singlejax.lax.scanover the whole circuit operating directly on the stacked(num_chunks, chunk_dim)representation — never materializing a(2**n_qubits,)array, preserving the anti-OOM propertyChunkexists for. The 6 gate/qubit-location cases were ported formula-for-formula from the old Python-loop implementation and verified case-by-case against it (all 18 pre-existingTestChunkMultiPiecetests, which cross-check againstDenseSVSimulator, pass unchanged against the new kernel) before the old code was removed. Gate coverage is now built viaGATE_IDSinstead of the oldGATES/PARAMETRIC_GATESlookup, aligning it with beast-mode's own coverage. Measured speedup on the exact benchmark that surfaced the problem (10 qubits/200 gates/4 forced chunks): 2.2s → 0.42s, now close to beast-mode's 0.37s on the same non-chunked workload. - Note: a Colab report of "17s vs milliseconds" that prompted this investigation turned out, on reproduction, to be
num_chunks==1(not the multi-chunk path at all) — 0.49s locally on the identical circuit, most likely first-time JIT compilation overhead on Colab's specific hardware rather than a code defect. The 6x slowdown that was real and is fixed here was found and confirmed with a separate synthetic benchmark (num_chunksforced via monkeypatch), not the original report.
v8.1.20¶
- Fixed:
from_pennylane/run_pennylane_circuitsilently renumbered qubits whenever wires weren't touched in ascending order — both PennyLane'sqml.to_openqasmand the oldertape.to_openqasm()number exported QASM qubits by first-touch order, not by actual wire index (e.g.PauliX(wires=2)thenCNOT(wires=[2,1])exported asx q[0]; cx q[0],q[1];, silently mapping wire 2→q[0] and wire 1→q[1]). Found via independent fuzz testing (20 random circuits touching 4 wires in random order: 9/20 matched PennyLane's own results before the fix, 20/20 after). Fixed by passing an explicitwires=argument — the device's declared wire order for a QNode, the tape's own wires sorted ascending for a bare tape — forcing the true wire order into the export instead of relying on touch order. - Fixed:
NoiseModel.apply_to_sv'sdepolarizingchannel (and thecombinedchannel's depolarizing sub-channel) picked which Pauli error (X/Y/Z) to apply using thresholdsp/3and2p/3compared against a draw uniform on the full[0,1)range — but that draw should only ever decide which Pauli fires, independent of the overall fire-ratep, so the thresholds needed to be the fixed values1/3and2/3instead. The bug skewed every depolarizing/combined-noise circuit heavily toward Z regardless ofp(verified: atp=0.3,P(X|fire)=P(Y|fire)=10%,P(Z|fire)=80%instead of the documented 33.3% each — confirmed both via an isolated 100k-sample trace of the raw branch logic and via full statevector simulation, both matching the bug's predicted skew to within statistical noise). Found via independent statistical fuzz testing comparing measured frequencies against the analytic prediction — a test that only checks "the channel runs without crashing" would never have caught this.bitflip,phaseflip, andamplitude_dampingwere verified unaffected (correct by construction, don't use this three-way branch). - Docs: opened a tracking issue for a related robustness gap found during the same fuzzing pass — unrecognized gate names (a typo like
'crx'instead of'crz', or any gate not inGATE_IDS) are silently dropped everywhere in the simulator instead of raising, same pattern already documented for the Qiskit interop bridge's unsupported custom gates. Not fixed here — would be a breaking-change decision forrun_circuit/run_circuit_jit_beast_mode/run_parametric_batch_jit's public behavior, tracked separately.
v8.1.19 — Security fix¶
- Fixed (security):
QASMParser's gate-parameter evaluator (_eval_param, used for expressions likerx(...),p(...)) calledeval()with{'__builtins__': {}}as its only protection. That blocks direct builtin names (open,len,__import__, ...) but does not block attribute/dunder traversal of the live Python object graph (().__class__.__bases__[0].__subclasses__()...), which needs no builtin name at all — from there, any class loaded in the process is reachable, including ones whose__globals__referenceos/subprocess. Verified directly: a crafted gate-parameter expression, passed through the publicQASMParser.parse()entry point (the primary entry point of the whole library — used by the dashboard, the Qiskit/PennyLane interop bridge, and any direct usage), executed successfully. Anyone parsing untrusted QASM text was affected, in every previously published version. Fixed by replacingeval()with an AST node-type whitelist evaluator (_eval_ast_node) — only literals,+-*/%**arithmetic, and calls/lookups restricted to the documented math environment (pi,sin,sqrt, ...) are ever evaluated; anast.Attributenode (produced by any.in the expression) is never one of the handled cases, so attribute-based escapes are structurally impossible rather than blocklisted._resolve_int_expr(QASM3for-loop bounds) used the sameeval()pattern but was already protected by a pre-filter regex rejecting any non-arithmetic character — verified safe before this fix — now shares the same AST evaluator for consistency, so no raweval()/exec()remains anywhere in the codebase (confirmed via full-repo search). No public API or behavior change for legitimate expressions — every previously-supported parameter syntax (pi,pi/2,sqrt(2),cos(0.3), etc.) evaluates identically.
If you parse QASM text from any source you don't fully trust, upgrade immediately.
v8.1.18¶
- Fixed: removed a global
warnings.filterwarnings('ignore')fromregistry.py, run unconditionally onimport dense_evolution. It silenced every Python warning process-wide for the importing user's whole session — not just this package's, but their own code's and every other library's too. Inherited unchanged from the original Colab notebook (added in v8.0.6, never reconsidered once this became a real pip package). Concretely masked real signal: the JAX float64→float32 truncationUserWarnings visible throughout this project's own test output (precision silently lost underuse_float32=True) would have been invisible to anyone using the package normally.
v8.1.17¶
- Added:
donate_argnums=(0,)onrun_circuit_jit_beast_mode's statevector buffer — the only one of_compile_and_run_circuit_jit's four call sites where it's safe (self.svis always rebound immediately after, verified across chunked/repeated calls and separate simulator instances).run_parametric_batch_jit(itsinit_svis avmap-broadcast closure shared across the whole batch) andcircuit_to_energy_fn's VQE loop (samestato_zeroreused every epoch) are deliberately left un-donated — donating there would make JAX raise on the second use instead of helping. Verified with a real measurement, not just a claim: RSS growth on a 22-qubit/300-gate circuit drops from +89.4MB to +4.5MB.
v8.1.16¶
- Note: v8.1.15's published PyPI package does not contain the
from_pennylanePython 3.10 fix described below, despite the changelog entry — the fix landed in the repo before the PyPI upload, but the actualpip install-able wheel/sdist for 8.1.15 was built and uploaded from an earlier commit. PyPI doesn't allow re-uploading files under an already-published version, so this release exists specifically to ship that fix as an installable package. If you're on 8.1.15, upgrade to 8.1.16 — don't rely on 8.1.15's changelog matching what you actually have installed.
v8.1.15¶
- Added:
dense_evolution.autodiff.circuit_to_energy_fn(circuit, n_qubits)— the real VQE gradient engine (jax.value_and_gradthrough ajax.lax.scancircuit template, verified against finite differences to ~1e-11) is now public API, independent ofdashboard_core.py/Streamlit. Takes aQASMCircuit— the same typefrom_qiskit/from_pennylanereturn — so it closes the non-differentiability gap documented in v8.1.14:circuit_to_energy_fn(from_pennylane(qnode, ...), n_qubits)now gives a real, non-zerojax.grad, verified directly, whererun_pennylane_circuitalone silently returned0.0. - Changed:
dashboard_core.py's_build_vqe_template/_vqe_energy_fnremoved —_run_vqe_telemetry_bodynow calls the same publiccircuit_to_energy_fn, one engine instead of two copies of the same math that could silently drift apart. Verified behaviorally identical: all existing dashboard VQE tests pass unchanged, same tolerances. - Fixed: found while testing the newly-public API — calling the engine on a circuit with zero parametric gates crashed on empty-array indexing during JAX tracing. Previously unreachable because
dashboard_core.pyalways special-casedn_params == 0before calling in; a real gap once this became public API someone could call directly. Fixed with a static (non-traced) branch. - Docs: the README's VQE Engine section had drifted stale, still describing the deleted
risolvi_qasm()mechanism from before the real-gradient rewrite — corrected, and a new "Differentiable Circuits" section documentscircuit_to_energy_fnwith a verified end-to-end example. - Fixed:
from_pennylanebroke on Python 3.10 — CI caught it (3.10 job red, 3.11/3.12 green). Newer PennyLane releases dropped Python 3.10 support, so pip resolves an older PennyLane (0.42.3) there instead of the version this bridge was built against (0.45.1);qml.to_openqasm(tape)behaves incompatibly between the two for a bare tape/QuantumScript input (crashes withAttributeError: 'QuantumTape' object has no attribute 'func'on the older one). Verified against both versions directly (installed 0.42.3 in an isolated venv to reproduce).from_pennylanenow picks whichever serialization path the installed PennyLane version actually supports instead of assuming the newer one unconditionally.
v8.1.14¶
- Added: interop bridge for Qiskit and PennyLane —
from_qiskit/from_pennylaneconvert an existing circuit to aQASMCircuitby reusing the existingQASMParser(viaqiskit.qasm2.dumps/qml.to_openqasm) instead of a bespoke gate-by-gate translator;run_qiskit_circuit/run_pennylane_circuitexecute it directly onDenseSVSimulator. Handles the bit-order mismatch explicitly instead of leaving it as a silent trap: Qiskit indexes arrays little-endian (qubit 0 = LSB), Dense-Evolution is MSB-first everywhere else in the codebase, sorun_qiskit_circuitreorders its output to match Qiskit's own convention (verified againstStatevector(...).probabilities()on an asymmetric circuit); PennyLane's own wire order already matches Dense-Evolution's natively (verified the same way), sorun_pennylane_circuitdoes not reorder — kept as two separate code paths on purpose. New optional extrasdense-evolution[qiskit]/dense-evolution[pennylane]. - Fixed: found while building the Qiskit bridge —
qiskit.qasm2.dumpsexports composite gates (e.g.mcx) as agate NAME params { ... }definition on a single line, the same brace-delimited block corruption already fixed for QASM3for/if/while/defin v8.1.13, just not covered becausegatewasn't in that fix's keyword set (verified: before the fix, a 4-qubit circuit usingmcxsilently inflated ton_qubits=5with a ghost op). Extended the same brace-matching preprocessor to also stripgatedefinitions cleanly.
v8.1.13¶
- Fixed:
QASMParserdeclared OpenQASM 3.0 support butfor/if/while/defblocks — brace-delimited, not;-terminated — were mishandled by the naivesplit(';')statement splitter: afor-loop's body was never extracted, and its closing}merged into whatever real statement followed on the same line, corrupting it too (verified:for int i in [0:2] { h q[i]; } cx q[0],q[1];produced a single ghost op named'}', with the loop body lost and the realcxsilently dropped — executed circuit stayed|000⟩at 100% probability, no error). Needed for writing VQE ansätze with a loop over qubits instead of one line per qubit. Added_process_block_constructs, run before the;-split:for-loops with resolvable integer bounds (literals, orint/const intvariables declared earlier in the source — QASM3's inclusive-end range semantics) are now genuinely unrolled by substituting the loop variable into the body per iteration;if/while/defblocks andfor-loops with unresolvable bounds are cleanly stripped instead of corrupting the source that follows them.
v8.1.12¶
- Fixed:
run_circuit_jit_beast_mode/run_parametric_batch_jitsilently droppedcy,cp,crz,u1,p,sx— they weren't inGATE_IDS, soif name not in GATE_IDS: continueskipped them with no error (verified:h(0);h(1);crz(0,1,1.2)produced the exact same output ash(0);h(1)alone).dashboard_core.pyalready treats these as first-class gates, so any circuit using them — dashboard-built or hand-written QASM — silently ran the wrong physics through the fast path nearly everything uses. Added the missingGATE_IDSentries and the missing kernel implementations forcy/crz/sxin_apply_gate_fast_step—crzspecifically needed its own kernel, not reuse ofcp's (CP phases|11⟩only; CRZ phases the target conditioned on its own bit, a different gate). - Fixed:
run_circuit_jit_beast_modeused the raw qubit index as bit position (LSB-first) instead of the documented MSB-first convention (phys = n_qubits - 1 - qubit) used byrun_circuit()/apply_gate_1q()/apply_gate_2q()/measure()elsewhere in the simulator. Pre-existing, not introduced by the fix above — found while verifying it, masked until now because every beast-mode circuit tested to date happened to be symmetric under qubit reversal (Bell states, GHZ states, uniform superpositions), so the wrong labeling never showed up in the probabilities. Verified withXon qubit 0 in a 3-qubit register: gave index 1 (LSB) instead of index 4 (MSB, correct).do_1q/do_2qnow compute physical bit positions consistently with the rest of the simulator;Chunk'snum_chunks==1(via beast mode) andnum_chunks>1(viaapply_gate_1q/apply_gate_2q) paths are now finally consistent with each other too. - Fixed: the VQE gradient (
run_vqe_telemetry) was never a real derivative —grad_vqe_params[i] = 0.5*(energy-target)*sin(theta[i]) + gaussian_noise, nojax.grad, no parameter-shift rule, no backprop on θ anywhere in the codebase (the only realjax.value_and_gradusage, inQMMMForceEngine, differentiates classical QM/MM forces w.r.t. atomic positions, not circuit parameters).risolvi_qasm(the old circuit-building path) converted θ to a Pythonfloatbefore use, severing the JAX trace, so backprop couldn't pass through it. Replaced with a realjax.gradpipeline reusingrun_parametric_batch_jit's own sentinel-injection pattern (θ substituted viajnp.whereinside ajax.lax.scan, never afloat()call) — verified against a finite-difference gradient (~1.5e-10 agreement) on a real circuit fromQASM_LIBRARY, and confirmed genuine Adam-optimizer convergence (monotonic energy descent to a minimum) over 40 epochs, unlike the old noisy formula. Public signature and DataFrame columns ofrun_vqe_telemetryunchanged.
v8.1.11¶
- Fixed:
dash.py(the original Colab notebook) was declared as an installable module (py-modules = ["dash"]) with the same name as the real Plotlydashpackage, itself listed as an optional dependency in the very samepyproject.toml— a genuine packaging collision, not just a local dev annoyance. It also had unconditional module-levelfrom google.colab import files/import ipywidgets, soimport dashcrashed immediately outside Colab. Nothing in the maintained codebase (dashboard_core.py/app_dashboard.py, the real Streamlit port) imports it anymore. Moved tolegacy/dash.py(reference only, not packaged), removed frompy-modules. Thedashboardextra now installs what the real dashboard actually needs (streamlit,pandas,seaborn,plotly) instead of the unuseddashpackage. - Docs: README's Quick Start (the very first example in the file) passed
circuit.ops— raw dicts — torun_circuit_jit_beast_mode, which expects the tuple format fromcircuit.to_tuples(); crashed withKeyError: 0. Fixed, and the "Dashboard" quick-start snippet now points atstreamlit run app_dashboard.pyinstead of the retired Colab-onlyimport dashpattern.
v8.1.10¶
- Fixed:
run_circuit_jit_beast_mode/run_parametric_batch_jit— a gate referencing a qubit index out of range silently corrupted the entire statevector to zero instead of raising (verified:get_probabilities().sum()went from 1.0 to 0.0, no exception).apply_gate_1q/apply_gate_2qalready validated qubit indices, but these two JIT fast paths build their own compiled ops and never called them. Both now validate before dispatch, matching the existing behavior of the non-JIT path. - Fixed:
Chunk— forn_qubitsbeyond the RAM-safe budget (chunk_size_bits), it silently ran the circuit on a smaller inner simulator (min(n_qubits, chunk_size_bits)) instead of genuinely chunking:num_chunks/chunk_dimwere computed but never used to combine multiple pieces. Found testingChunk(n_qubits=28):get_probabilities()returned2**27elements, not2**28. Now implements real multi-chunk simulation (RAM-only, no disk paging — covers moderate overflow beyond the safe budget, not arbitrarily large qubit counts):num_chunksindependent chunk-sized simulators held in memory, with gate dispatch across chunk boundaries for all six local/chunk-select combinations. Verified against a plainDenseSVSimulatorrunning the identical circuit (exact match, not just "looks right"). A sized RAM check now raisesMemoryPressureErrorup front if the chunks wouldn't fit, instead of attempting and OOMing.
v8.1.9¶
- Fixed:
ia_utils/vector_healing.py—enhanced_dense_healing_hybridhad an unreachable third branch (a dense/blend fallback): the underlyingtriggersignal fromevaluate_phi_triggeris strictly binary (0.0/1.0), so the branch could never execute. Collapsed to the genuine 2-state logic (pass-through vs. median fallback); runtime output is unchanged since the branch never ran. - Fixed:
dashboard_core.py—run_simulation/run_vqe_telemetrymutated the process-wide JAXjax_enable_x64flag without ever restoring it, so running one float32 simulation silently downgraded numerical precision for unrelated code later in the same process (e.g. the Vector Healing page, which sets no precision of its own). Both now save/restore the flag around their own execution. - Docs: README's
NoiseModelexample called a nonexistent.apply()method with a wrong parameter name (n_qubitsinstead ofn) — corrected toapply_to_sv(sv, n=..., ...). DocumentedQASMCircuit.to_tuples()andDenseSVSimulator.run_circuit, which already existed and work correctly but were never mentioned in the README.
v8.1.8¶
- Fixed:
parser.py— controlled two-qubit gates (cx/cy/cz/cp/crz) parsed from QASM in the dashboard layer had control and target swapped relative tocompiler.py's documented(gate, control, target)contract, breaking entanglement for circuits run through the dashboard. The coreQASMCircuit.to_tuples()path was already correct. - Fixed:
parser.py— range syntax (q[0:3]) on single-qubit gates only applied to the first qubit in the range, silently dropping the rest. Now expands into one gate application per qubit, matching the parser's own documented contract. - Fixed:
from dense_evolution import ChunkraisedImportError—Chunkis now re-exported from the package root. Addedget_probabilities()/get_statevector()toChunkfor parity withDenseSVSimulator. - Removed:
dense_evolution/test2.pyandstress_test.py— byte-identical, assertion-free debug scripts that shipped inside every install with 0% test coverage. Their one real check (Kraus noise is genuinely stochastic across independent runs) is now a real regression test.
v8.1.7¶
ia_utils/— new package:median_healing,enhanced_dense_healing_hybridfor vector sequence healing (NaN/Inf-safe)jaximport inia_utils.vector_healingmade lazy — importable without the[jax]extra- Fixed
reconstruction_errortelemetry returningNaNwhen input containedNaN/Inf - Added
scipyto core dependencies (was used but undeclared)
v8.1.6¶
- Modular package structure (
dense_evolution/directory) - Split
registry.py,gates.py,healing.py,chunk.pyinto dedicated modules
v8.1.5¶
chunk.py—SafeMemoryGuard: hard block at configurable free-RAM threshold (default 15%), soft warning at 2× threshold,gc.collect()before every checkchunk.py—Chunkno longer subclassesDenseSVSimulator; inner simulator allocated atsafe_qubitsonly — eliminatesRESOURCE_EXHAUSTEDon 28q–34q circuitschunk.py—CircuitChunker.split_circuitRAM-checks every gate-slice before dispatchchunk.py—MemoryChunkerattributes (num_chunks,chunk_size_bits,dtype) forwarded as@propertyonChunkfor benchmark compatibility
v8.1.0¶
healing.py— Predictive State Engine:calculate_phi_ab,calculate_vettore_dinamico,calculate_delta_preemp,evaluate_phi_trigger,calculate_jax_reflection— all@jax.jitMemoryReflectionEngine— event logging + JAX Zero-Drift spectral aggregation
v8.0.x¶
run_parametric_batch_jit()—jax.vmapover full parameter grids in single XLA callrun_circuit_jit_beast_mode()— static JIT compilation with QuantumTranspiler- OpenQASM 2.0/3.0 dual-mode parser with paren-depth-aware expression splitting
NoiseModelKraus channels inregistry.py