TheYuchen commited on
Commit
91b2cd9
·
1 Parent(s): 941d830

Seed coverage for QuBound/Qshot + cost estimates from run history

Browse files

Closes the two remaining claim-integrity gaps for "every run is
exactly replayable" over "stochastic, costly experiments":

Seeds. QuBound trains its LSTM on BOTH ok paths (live IBM history and
the cached 14-day pickle) — there is no precomputed-only branch in the
handler — so both now seed the global RNGs (_seed_stochastic_libs:
random + numpy + lazily-imported, try/except-guarded torch) and thread
node_seed into qlib (Aer seed_simulator + Sabre seed_transpiler in
get_labels_fromNoise); results carry nondeterministic=True +
seed_used. Qshot's pilot seed was 99991 + hash(str(base)) — str hashes
are PYTHONHASHSEED-salted, i.e. "fixed" only until the next server
restart. pilot_seed is now threaded predict → recommend_shots →
compute_pilot_pf, making the recommendation reproducible across
processes given the seed. Executor cache logic untouched: fresh runs
draw fresh node seeds (honest new draw, cache-bypassed), pinned runs
re-derive the same seeds (cacheable in the seed-salted namespace).

Cost. frontend/src/lib/costModel.ts learns median per-kind durations
from the browser's own archived runs (ok steps, cache hits excluded;
median so one-off warmups don't skew) and the toolbar shows a mute
"est ~Ns" chip (+ "M unknown" without history) next to Run; ×N
replicates add (N-1) x sum(stochastic blocks), approximating the
cached-prefix effect. Marker: cost-estimate.

Tests: +8 torch-free (tests/test_seed_coverage.py) — RNG helper
reproducibility/divergence, torch-less no-crash, 31-bit seed range,
source-level handler wiring. Lane: 57 green.

backend/app/services/workflow_service.py CHANGED
@@ -20,6 +20,7 @@ import hashlib
20
  import io
21
  import json
22
  import logging
 
23
  import re
24
  import time
25
  from collections import OrderedDict
@@ -496,6 +497,45 @@ def _handle_qucad(node: FlowNode, ctx: dict, settings: Settings) -> StepResult:
496
  )
497
 
498
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
499
  def _handle_qubound(node: FlowNode, ctx: dict, settings: Settings) -> StepResult:
500
  """QuBound — LSTM-based hardware-aware error bound predictor.
501
 
@@ -532,6 +572,23 @@ def _handle_qubound(node: FlowNode, ctx: dict, settings: Settings) -> StepResult
532
  threshold_raw = node.data.get("threshold")
533
  threshold = float(threshold_raw) if isinstance(threshold_raw, (int, float)) and threshold_raw > 0 else None
534
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
535
  def _build_summary(bound_value: float, source: str, extra: dict | None = None) -> dict:
536
  out: dict = {
537
  "predicted_error_bound": float(bound_value),
@@ -549,14 +606,19 @@ def _handle_qubound(node: FlowNode, ctx: dict, settings: Settings) -> StepResult
549
  # Prefer live IBM history when we have a token and it's enabled.
550
  if settings.has_ibm_token and settings.allow_live_ibm:
551
  reference = backend or _load_fake_backend("FakeFez")
552
- bound, _model = call_QuBound(qc, reference, token=settings.ibm_token)
 
 
553
  ctx["qubound_value"] = float(bound)
554
- return _make_step(
555
  node,
556
  "ok",
557
  started_at=t0,
558
  summary=_build_summary(bound, "live_ibm"),
 
559
  )
 
 
560
 
561
  # Offline path — use cached 14-day pickle shipped with the repo.
562
  cache_backend_name = node.data.get("cache_backend", "ibm_fez")
@@ -574,9 +636,11 @@ def _handle_qubound(node: FlowNode, ctx: dict, settings: Settings) -> StepResult
574
  )
575
 
576
  reference = backend # may be None — call_QuBound_from_cache will default to FakeFez
577
- bound, _model, meta = call_QuBound_from_cache(qc, cache_path, reference_backend=reference)
 
 
578
  ctx["qubound_value"] = float(bound)
579
- return _make_step(
580
  node,
581
  "ok",
582
  started_at=t0,
@@ -588,7 +652,12 @@ def _handle_qubound(node: FlowNode, ctx: dict, settings: Settings) -> StepResult
588
  "num_days": meta["num_days"],
589
  },
590
  ),
 
591
  )
 
 
 
 
592
 
593
 
594
  def _handle_compvqc(node: FlowNode, ctx: dict, _settings: Settings) -> StepResult:
@@ -707,9 +776,27 @@ def _handle_qshot(node: FlowNode, ctx: dict, _settings: Settings) -> StepResult:
707
  if qc.num_parameters > 0:
708
  qc = qc.assign_parameters([0.0] * qc.num_parameters)
709
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
710
  noise_path = resolve_noise_snapshot(snapshot_key)
711
  recommender = get_recommender()
712
- result = recommender.predict(qc, noise_path, alpha=alpha)
 
 
713
 
714
  if result is None:
715
  return _make_step(
@@ -751,7 +838,22 @@ def _handle_qshot(node: FlowNode, ctx: dict, _settings: Settings) -> StepResult:
751
  str(k): float(v) for k, v in (result.get("pilot_pf") or {}).items()
752
  },
753
  }
754
- return _make_step(node, "ok", started_at=t0, summary=summary)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
755
 
756
 
757
  def _handle_fidelity(node: FlowNode, ctx: dict, _settings: Settings) -> StepResult:
 
20
  import io
21
  import json
22
  import logging
23
+ import random
24
  import re
25
  import time
26
  from collections import OrderedDict
 
497
  )
498
 
499
 
500
+ def _seed_stochastic_libs(seed: int | None) -> list[str]:
501
+ """Seed every global RNG a stochastic handler may draw from.
502
+
503
+ QuBound's LSTM training consumes torch's global RNG (weight init,
504
+ Adam step order) and numpy/random for library-internal shuffling;
505
+ Qshot's GNN fallback touches torch as well. Handlers call this with
506
+ the executor-injected per-node seed so a pinned replay re-trains /
507
+ re-samples from the same starting point.
508
+
509
+ torch is imported lazily and guarded with try/except: the unit-test
510
+ lane runs torch-free, and /api/health must stay answerable even if
511
+ torch failed to install. numpy is guarded for symmetry (it is a
512
+ hard dependency in the real backend env). Returns the list of
513
+ libraries actually seeded so torch-less tests can still assert
514
+ behaviour.
515
+ """
516
+ if seed is None:
517
+ return []
518
+ random.seed(seed)
519
+ seeded = ["random"]
520
+ try:
521
+ import numpy as _np
522
+
523
+ _np.random.seed(seed % (2**32)) # numpy requires seed < 2**32
524
+ seeded.append("numpy")
525
+ except Exception: # pragma: no cover — numpy is a hard dep in prod
526
+ logger.exception("numpy seeding failed; continuing unseeded")
527
+ try:
528
+ import torch as _torch
529
+
530
+ _torch.manual_seed(seed)
531
+ seeded.append("torch")
532
+ except Exception:
533
+ # torch genuinely absent (unit lane) or broken — QuBound will
534
+ # fail loudly later if it actually needs it; seeding must not.
535
+ pass
536
+ return seeded
537
+
538
+
539
  def _handle_qubound(node: FlowNode, ctx: dict, settings: Settings) -> StepResult:
540
  """QuBound — LSTM-based hardware-aware error bound predictor.
541
 
 
572
  threshold_raw = node.data.get("threshold")
573
  threshold = float(threshold_raw) if isinstance(threshold_raw, (int, float)) and threshold_raw > 0 else None
574
 
575
+ # Seeding determination (claim audit: "every run is exactly
576
+ # replayable"): BOTH ok paths below — live IBM history and the
577
+ # cached-pickle path — end in qbound._train_and_predict, which
578
+ # trains a fresh LSTM every call. There is NO purely-precomputed
579
+ # branch inside this handler (the executor-level prefix cache and
580
+ # the disk prewarm cache sit ABOVE the handler), so every ok result
581
+ # here comes from actual training and is marked nondeterministic.
582
+ # The only path that skips training is the missing-cache-file error
583
+ # below, which stays deterministic. Training draws from torch's
584
+ # global RNG and the label builder samples Aer + runs Sabre
585
+ # transpilation, so we (a) seed the global RNGs here and (b) thread
586
+ # node_seed into qlib (seed_simulator / seed_transpiler). Given the
587
+ # same node_seed the predicted bound is reproducible; in fresh mode
588
+ # each run derives a new node_seed → honestly a new draw.
589
+ node_seed = ctx.get("node_seed")
590
+ _seed_stochastic_libs(node_seed)
591
+
592
  def _build_summary(bound_value: float, source: str, extra: dict | None = None) -> dict:
593
  out: dict = {
594
  "predicted_error_bound": float(bound_value),
 
606
  # Prefer live IBM history when we have a token and it's enabled.
607
  if settings.has_ibm_token and settings.allow_live_ibm:
608
  reference = backend or _load_fake_backend("FakeFez")
609
+ bound, _model = call_QuBound(
610
+ qc, reference, token=settings.ibm_token, seed=node_seed,
611
+ )
612
  ctx["qubound_value"] = float(bound)
613
+ step = _make_step(
614
  node,
615
  "ok",
616
  started_at=t0,
617
  summary=_build_summary(bound, "live_ibm"),
618
+ seed_used=node_seed,
619
  )
620
+ # LSTM training ran → fresh draw on every unpinned run.
621
+ return step.model_copy(update={"nondeterministic": True})
622
 
623
  # Offline path — use cached 14-day pickle shipped with the repo.
624
  cache_backend_name = node.data.get("cache_backend", "ibm_fez")
 
636
  )
637
 
638
  reference = backend # may be None — call_QuBound_from_cache will default to FakeFez
639
+ bound, _model, meta = call_QuBound_from_cache(
640
+ qc, cache_path, reference_backend=reference, seed=node_seed,
641
+ )
642
  ctx["qubound_value"] = float(bound)
643
+ step = _make_step(
644
  node,
645
  "ok",
646
  started_at=t0,
 
652
  "num_days": meta["num_days"],
653
  },
654
  ),
655
+ seed_used=node_seed,
656
  )
657
+ # The 'cached' here is cached CALIBRATION HISTORY, not a cached
658
+ # result — the LSTM still trains on it every call, so this path is
659
+ # just as stochastic as the live one.
660
+ return step.model_copy(update={"nondeterministic": True})
661
 
662
 
663
  def _handle_compvqc(node: FlowNode, ctx: dict, _settings: Settings) -> StepResult:
 
776
  if qc.num_parameters > 0:
777
  qc = qc.assign_parameters([0.0] * qc.num_parameters)
778
 
779
+ # Seeding determination: Qshot's pilot measurements draw their
780
+ # seed_simulator values from a PRIVATE np.random.default_rng — they
781
+ # never touch the global RNGs — and the internal transpile is
782
+ # already pinned (seed_transpiler=1234). But the historical default
783
+ # pilot seed mixed in hash(str(base)), and Python salts str hashes
784
+ # per process (PYTHONHASHSEED), so it was only "fixed" until the
785
+ # next server restart: same inputs could yield a different
786
+ # recommendation after a redeploy. We therefore thread the
787
+ # executor's per-node seed through predict() → recommend_shots() →
788
+ # compute_pilot_pf(), which makes the result reproducible ACROSS
789
+ # processes given the seed. The global seeding below is
790
+ # belt-and-suspenders for residual library entropy (the GNN
791
+ # fallback is eval-mode torch inference, deterministic).
792
+ node_seed = ctx.get("node_seed")
793
+ _seed_stochastic_libs(node_seed)
794
+
795
  noise_path = resolve_noise_snapshot(snapshot_key)
796
  recommender = get_recommender()
797
+ result = recommender.predict(
798
+ qc, noise_path, alpha=alpha, pilot_seed=node_seed,
799
+ )
800
 
801
  if result is None:
802
  return _make_step(
 
838
  str(k): float(v) for k, v in (result.get("pilot_pf") or {}).items()
839
  },
840
  }
841
+ step = _make_step(
842
+ node, "ok", started_at=t0, summary=summary, seed_used=node_seed,
843
+ )
844
+ if node_seed is not None:
845
+ # With node_seed threaded into the pilot, the recommendation
846
+ # depends on the per-run seed draw: fresh mode derives a new
847
+ # node_seed each run → a genuinely new pilot → the result must
848
+ # not be served from the fresh-namespace cache. (Pinned runs
849
+ # re-derive the same node_seed, so the seed-salted namespace
850
+ # may still cache it — executor logic, unchanged.)
851
+ step = step.model_copy(update={"nondeterministic": True})
852
+ # node_seed is None only if a caller bypasses the executor (which
853
+ # always injects one). Then the legacy in-process fixed seed
854
+ # applies: same inputs → same output within a process → honestly
855
+ # deterministic, and we leave the flag off.
856
+ return step
857
 
858
 
859
  def _handle_fidelity(node: FlowNode, ctx: dict, _settings: Settings) -> StepResult:
backend/qlib/qbound.py CHANGED
@@ -113,7 +113,10 @@ def look_back_window_ForError(
113
 
114
 
115
  def get_labels_fromNoise(
116
- qc: QuantumCircuit, historic_data: list[dict[str, Any]], backend: Any
 
 
 
117
  ) -> torch.Tensor:
118
  """For each historical day, compute the Hellinger distance between
119
  the noiseless counts and the noisy counts (noise model built from
@@ -129,17 +132,27 @@ def get_labels_fromNoise(
129
  # a counts-string delimiter and crash.
130
  qc = qc.copy()
131
  qc.measure_all()
132
- qc = transpile(qc, backend, optimization_level=3)
 
 
 
 
133
 
134
  simulator = AerSimulator()
135
- nonoise_value = simulator.run(qc, shots=SHOTS).result().get_counts()
 
 
136
 
137
  labels: list[float] = []
138
  for history in historic_data:
139
  properties = history["properties"]
140
  noise_model = NoiseModel.from_backend(backend, properties)
141
  noisy_simulator = AerSimulator(noise_model=noise_model)
142
- noise_value = noisy_simulator.run(qc, shots=SHOTS).result().get_counts()
 
 
 
 
143
 
144
  # Hellinger is a proper metric on probability distributions,
145
  # bounded in [0, 1] — convenient for training.
@@ -269,7 +282,10 @@ def predict_vqc_bound(model: QuPred, x_train: torch.Tensor) -> float:
269
 
270
 
271
  def _train_and_predict(
272
- qc: QuantumCircuit, historic_data: list[dict[str, Any]], provider: Any
 
 
 
273
  ) -> tuple[float, QuPred]:
274
  """Shared QuBound pipeline once ``historic_data`` is available.
275
 
@@ -284,7 +300,7 @@ def _train_and_predict(
284
  normalized_df = (combined_df - combined_df.mean()) / combined_df.std()
285
 
286
  x_train = create_sequences(normalized_df, window_size=SEQUENCE_WINDOW_SIZE)
287
- y_train = get_labels_fromNoise(qc, historic_data, provider)
288
  y_train = y_train[SEQUENCE_WINDOW_SIZE:].unsqueeze(1)
289
 
290
  model = train_loop(x_train, y_train)
@@ -297,6 +313,7 @@ def call_QuBound(
297
  provider: Any,
298
  token: str,
299
  date: datetime | None = None,
 
300
  ) -> tuple[float, QuPred]:
301
  """Run QuBound against the **live** IBM Quantum Platform API.
302
 
@@ -321,13 +338,14 @@ def call_QuBound(
321
  )
322
  backend = service.backend("ibm_fez")
323
  historic_data = look_back_window_ForError(backend, date)
324
- return _train_and_predict(qc, historic_data, provider)
325
 
326
 
327
  def call_QuBound_from_cache(
328
  qc: QuantumCircuit,
329
  cached_history_path: str | Path,
330
  reference_backend: Any = None,
 
331
  ) -> tuple[float, QuPred, dict[str, Any]]:
332
  """Run QuBound against a pickle of pre-fetched 14-day backend
333
  properties.
@@ -357,7 +375,7 @@ def call_QuBound_from_cache(
357
  if reference_backend is None:
358
  reference_backend = FakeFez()
359
 
360
- bound, model = _train_and_predict(qc, historic_data, reference_backend)
361
  metadata = {
362
  "backend_name": payload.get("backend_name"),
363
  "fetched_at": payload.get("fetched_at"),
 
113
 
114
 
115
  def get_labels_fromNoise(
116
+ qc: QuantumCircuit,
117
+ historic_data: list[dict[str, Any]],
118
+ backend: Any,
119
+ seed: int | None = None,
120
  ) -> torch.Tensor:
121
  """For each historical day, compute the Hellinger distance between
122
  the noiseless counts and the noisy counts (noise model built from
 
132
  # a counts-string delimiter and crash.
133
  qc = qc.copy()
134
  qc.measure_all()
135
+ # seed_transpiler / seed_simulator: None keeps the historical
136
+ # (unseeded) behaviour; an int pins Sabre layout AND every Aer
137
+ # sampling draw below, so training labels are reproducible given
138
+ # the workflow executor's per-node seed.
139
+ qc = transpile(qc, backend, optimization_level=3, seed_transpiler=seed)
140
 
141
  simulator = AerSimulator()
142
+ nonoise_value = (
143
+ simulator.run(qc, shots=SHOTS, seed_simulator=seed).result().get_counts()
144
+ )
145
 
146
  labels: list[float] = []
147
  for history in historic_data:
148
  properties = history["properties"]
149
  noise_model = NoiseModel.from_backend(backend, properties)
150
  noisy_simulator = AerSimulator(noise_model=noise_model)
151
+ noise_value = (
152
+ noisy_simulator.run(qc, shots=SHOTS, seed_simulator=seed)
153
+ .result()
154
+ .get_counts()
155
+ )
156
 
157
  # Hellinger is a proper metric on probability distributions,
158
  # bounded in [0, 1] — convenient for training.
 
282
 
283
 
284
  def _train_and_predict(
285
+ qc: QuantumCircuit,
286
+ historic_data: list[dict[str, Any]],
287
+ provider: Any,
288
+ seed: int | None = None,
289
  ) -> tuple[float, QuPred]:
290
  """Shared QuBound pipeline once ``historic_data`` is available.
291
 
 
300
  normalized_df = (combined_df - combined_df.mean()) / combined_df.std()
301
 
302
  x_train = create_sequences(normalized_df, window_size=SEQUENCE_WINDOW_SIZE)
303
+ y_train = get_labels_fromNoise(qc, historic_data, provider, seed=seed)
304
  y_train = y_train[SEQUENCE_WINDOW_SIZE:].unsqueeze(1)
305
 
306
  model = train_loop(x_train, y_train)
 
313
  provider: Any,
314
  token: str,
315
  date: datetime | None = None,
316
+ seed: int | None = None,
317
  ) -> tuple[float, QuPred]:
318
  """Run QuBound against the **live** IBM Quantum Platform API.
319
 
 
338
  )
339
  backend = service.backend("ibm_fez")
340
  historic_data = look_back_window_ForError(backend, date)
341
+ return _train_and_predict(qc, historic_data, provider, seed=seed)
342
 
343
 
344
  def call_QuBound_from_cache(
345
  qc: QuantumCircuit,
346
  cached_history_path: str | Path,
347
  reference_backend: Any = None,
348
+ seed: int | None = None,
349
  ) -> tuple[float, QuPred, dict[str, Any]]:
350
  """Run QuBound against a pickle of pre-fetched 14-day backend
351
  properties.
 
375
  if reference_backend is None:
376
  reference_backend = FakeFez()
377
 
378
+ bound, model = _train_and_predict(qc, historic_data, reference_backend, seed=seed)
379
  metadata = {
380
  "backend_name": payload.get("backend_name"),
381
  "fetched_at": payload.get("fetched_at"),
backend/qlib/qshot/recommend_shots_v4.py CHANGED
@@ -1515,6 +1515,7 @@ def recommend_shots(
1515
  actual_real_curve=None, actual_converged=None,
1516
  gnn_fallback=None,
1517
  noise_json=None,
 
1518
  ):
1519
  # --- Transpile + extract features ---
1520
  qc_meas = base.copy()
@@ -1592,9 +1593,14 @@ def recommend_shots(
1592
 
1593
  # --- Run pilot PF ---
1594
  print(f" Running pilot ({pilot_reps} reps per level)...")
 
 
 
 
1595
  pilot_pf, pilot_pf_stds = compute_pilot_pf(
1596
  tqc, nq, pilot_shots, sim, reps=pilot_reps,
1597
- seed=99991 + hash(str(base)) % (2**20))
 
1598
 
1599
  print(f" Pilot PF: { {s: f'{v:.4f}' for s, v in pilot_pf.items()} }")
1600
 
@@ -1978,6 +1984,7 @@ class QshotRecommender:
1978
  pilot_points=PILOT_POINTS,
1979
  pilot_reps=PILOT_REPS,
1980
  plot_prefix=None,
 
1981
  ):
1982
  """Recommend shots for one circuit under one noise condition.
1983
 
@@ -2035,6 +2042,7 @@ class QshotRecommender:
2035
  plot_prefix=plot_prefix,
2036
  gnn_fallback=self.gnn_fallback,
2037
  noise_json=nj,
 
2038
  )
2039
 
2040
 
 
1515
  actual_real_curve=None, actual_converged=None,
1516
  gnn_fallback=None,
1517
  noise_json=None,
1518
+ pilot_seed=None,
1519
  ):
1520
  # --- Transpile + extract features ---
1521
  qc_meas = base.copy()
 
1593
 
1594
  # --- Run pilot PF ---
1595
  print(f" Running pilot ({pilot_reps} reps per level)...")
1596
+ # pilot_seed (when given) makes the pilot reproducible ACROSS
1597
+ # processes. The historical fallback mixes hash(str(base)) into the
1598
+ # seed, and Python salts str hashes per process (PYTHONHASHSEED), so
1599
+ # it is only stable until the next server restart.
1600
  pilot_pf, pilot_pf_stds = compute_pilot_pf(
1601
  tqc, nq, pilot_shots, sim, reps=pilot_reps,
1602
+ seed=(pilot_seed if pilot_seed is not None
1603
+ else 99991 + hash(str(base)) % (2**20)))
1604
 
1605
  print(f" Pilot PF: { {s: f'{v:.4f}' for s, v in pilot_pf.items()} }")
1606
 
 
1984
  pilot_points=PILOT_POINTS,
1985
  pilot_reps=PILOT_REPS,
1986
  plot_prefix=None,
1987
+ pilot_seed=None,
1988
  ):
1989
  """Recommend shots for one circuit under one noise condition.
1990
 
 
2042
  plot_prefix=plot_prefix,
2043
  gnn_fallback=self.gnn_fallback,
2044
  noise_json=nj,
2045
+ pilot_seed=pilot_seed,
2046
  )
2047
 
2048
 
backend/tests/test_seed_coverage.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the stochastic-handler seeding added in the
2
+ seed-coverage wave (QuBound LSTM training, Qshot pilot measurements).
3
+
4
+ Deliberately torch-free: the unit lane runs on machines without torch,
5
+ so instead of executing the heavy handlers we test the seam they share
6
+ — ``_seed_stochastic_libs`` — plus a source-level wiring check that
7
+ both handlers actually consume it (cheap insurance against a refactor
8
+ silently dropping the call; the end-to-end behaviour is exercised by
9
+ the live-Space regression scripts).
10
+
11
+ Covered:
12
+
13
+ * ``_seed_stochastic_libs(None)`` is a no-op (returns []).
14
+ * random + numpy are seeded reproducibly; different seeds diverge.
15
+ * torch absence does not crash (guarded lazy import).
16
+ * 31-bit max seed is accepted (numpy's 2**32 ceiling respected).
17
+ * wiring: _handle_qubound threads seed= into qlib and marks the
18
+ result nondeterministic; _handle_qshot threads pilot_seed=.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import inspect
24
+ import random
25
+ import sys
26
+ import unittest
27
+ from pathlib import Path
28
+
29
+ ROOT = Path(__file__).resolve().parent.parent
30
+ if str(ROOT) not in sys.path:
31
+ sys.path.insert(0, str(ROOT))
32
+
33
+ from app.services import workflow_service as ws # noqa: E402
34
+
35
+ try:
36
+ import numpy as np
37
+ except Exception: # pragma: no cover
38
+ np = None
39
+
40
+ try:
41
+ import torch # noqa: F401
42
+ HAVE_TORCH = True
43
+ except Exception:
44
+ HAVE_TORCH = False
45
+
46
+
47
+ class SeedStochasticLibsTests(unittest.TestCase):
48
+ def test_none_seed_is_noop(self) -> None:
49
+ self.assertEqual(ws._seed_stochastic_libs(None), [])
50
+
51
+ def test_random_is_seeded_reproducibly(self) -> None:
52
+ libs = ws._seed_stochastic_libs(12345)
53
+ self.assertIn("random", libs)
54
+ seq1 = [random.random() for _ in range(5)]
55
+ ws._seed_stochastic_libs(12345)
56
+ seq2 = [random.random() for _ in range(5)]
57
+ self.assertEqual(seq1, seq2)
58
+
59
+ def test_different_seeds_diverge(self) -> None:
60
+ ws._seed_stochastic_libs(1)
61
+ seq1 = [random.random() for _ in range(5)]
62
+ ws._seed_stochastic_libs(2)
63
+ seq2 = [random.random() for _ in range(5)]
64
+ self.assertNotEqual(seq1, seq2)
65
+
66
+ @unittest.skipIf(np is None, "numpy not installed")
67
+ def test_numpy_is_seeded_reproducibly(self) -> None:
68
+ libs = ws._seed_stochastic_libs(424242)
69
+ self.assertIn("numpy", libs)
70
+ a = np.random.rand(4).tolist()
71
+ ws._seed_stochastic_libs(424242)
72
+ b = np.random.rand(4).tolist()
73
+ self.assertEqual(a, b)
74
+
75
+ def test_torch_absence_does_not_crash(self) -> None:
76
+ # On the torch-free unit lane this exercises the except branch;
77
+ # with torch installed it asserts the seeding still reports it.
78
+ libs = ws._seed_stochastic_libs(7)
79
+ if HAVE_TORCH:
80
+ self.assertIn("torch", libs)
81
+ else:
82
+ self.assertNotIn("torch", libs)
83
+ self.assertIn("random", libs)
84
+
85
+ def test_31bit_max_seed_accepted(self) -> None:
86
+ # Executor-derived node seeds are 31-bit; numpy caps at 2**32.
87
+ libs = ws._seed_stochastic_libs(2**31 - 1)
88
+ self.assertIn("random", libs)
89
+ if np is not None:
90
+ self.assertIn("numpy", libs)
91
+
92
+
93
+ class HandlerWiringTests(unittest.TestCase):
94
+ """Source-level wiring assertions. The handlers themselves need
95
+ torch / hdbscan to execute, which the unit lane doesn't have, so we
96
+ pin the contract textually: the seeding helper is called and the
97
+ node seed is threaded into qlib. Brittle by design — if a refactor
98
+ renames these seams, this test SHOULD fail and force a re-audit."""
99
+
100
+ def test_qubound_seeds_and_threads(self) -> None:
101
+ src = inspect.getsource(ws._handle_qubound)
102
+ self.assertIn("_seed_stochastic_libs(node_seed)", src)
103
+ self.assertIn("seed=node_seed", src) # into qlib.qbound
104
+ self.assertIn('"nondeterministic": True', src)
105
+ self.assertIn("seed_used=node_seed", src)
106
+
107
+ def test_qshot_seeds_and_threads(self) -> None:
108
+ src = inspect.getsource(ws._handle_qshot)
109
+ self.assertIn("_seed_stochastic_libs(node_seed)", src)
110
+ self.assertIn("pilot_seed=node_seed", src) # into qshot.predict
111
+ self.assertIn("seed_used=node_seed", src)
112
+
113
+
114
+ if __name__ == "__main__":
115
+ unittest.main(verbosity=2)
docs/EVIDENCE_WORKBENCH.md CHANGED
@@ -89,8 +89,8 @@ vqc_2q_small showed P-2; interval-overlap callout fires).
89
  derivation, threaded into sampled fidelity as seed_simulator; the
90
  exported script reproduces the archived run's exact draw.
91
 
92
- Backend test lane: 49 green (test_provenance_phase0 24,
93
- test_gate_diff 14, test_workflow_helpers 11).
94
 
95
  ## Shipped, third push (waves E-F, commits 324791f → 4bf1a9d)
96
 
@@ -111,19 +111,40 @@ test_gate_diff 14, test_workflow_helpers 11).
111
  decision surface and the paper's second hero figure (multiverse
112
  analysis narrative anchor).
113
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
  ## Not done yet (ordered backlog)
115
 
116
  * **Phase 3.5 leftovers** — pick-which-fidelity-node in comparison,
117
  dual-canvas visual diff, >2-way comparison.
118
- * **Phase 4 leftovers** — cost preview (per-node runtime estimates,
119
- replicate budget); opt-in interaction logging (schema first —
120
- needed for the user study). Reproducible export is DONE.
121
  * **Gate-diff niceties** — pair remove+add of the same op with only a
122
  param change into a "modified" state; column-align lanes across
123
  qubits by circuit moment.
124
- * **Seeding audit** — QuBound LSTM training and Qshot pilot runs are
125
- stochastic but not yet seed-plumbed; only sampled fidelity is.
126
- Their distribution payloads are also missing.
127
  * **Prewarm decision** — precomputed disk cache untouched and still
128
  served (fresh-mode namespace unchanged), but responses in it lack
129
  provenance/transformation fields. Either re-run
 
89
  derivation, threaded into sampled fidelity as seed_simulator; the
90
  exported script reproduces the archived run's exact draw.
91
 
92
+ Backend test lane: 57 green (test_provenance_phase0 24,
93
+ test_gate_diff 14, test_workflow_helpers 11, test_seed_coverage 8).
94
 
95
  ## Shipped, third push (waves E-F, commits 324791f → 4bf1a9d)
96
 
 
111
  decision surface and the paper's second hero figure (multiverse
112
  analysis narrative anchor).
113
 
114
+ ## Shipped, fourth push (claim-integrity wave)
115
+
116
+ 15. **Seed coverage: QuBound + Qshot** — the last two stochastic
117
+ handlers now honour the executor's per-node seed. QuBound: both ok
118
+ paths (live IBM / cached-history pickle) always train the LSTM, so
119
+ both seed the global RNGs via `_seed_stochastic_libs` (random +
120
+ numpy + lazily-imported torch) AND thread `seed=` into qlib
121
+ (Aer `seed_simulator`, Sabre `seed_transpiler`); results are
122
+ `nondeterministic=True` + `seed_used`. Qshot: the pilot's
123
+ "fixed" internal seed mixed in `hash(str(base))`, which Python
124
+ salts per process — reproducible only until a restart. `pilot_seed`
125
+ is now threaded `predict → recommend_shots → compute_pilot_pf`, so
126
+ the recommendation is reproducible across processes given the
127
+ seed; marked nondeterministic since fresh runs draw fresh seeds.
128
+ 16. **Cost estimate chip** (`cost-estimate`) — `lib/costModel.ts`
129
+ learns median per-kind step durations from the browser's own run
130
+ archive (ok steps only, cache hits excluded) and the canvas
131
+ toolbar shows "est ~Ns" (+ "M unknown" when a kind has no
132
+ history) next to Run; ×N replicates add (N−1)×Σ(stochastic
133
+ blocks), approximating the cached-prefix effect.
134
+
135
  ## Not done yet (ordered backlog)
136
 
137
  * **Phase 3.5 leftovers** — pick-which-fidelity-node in comparison,
138
  dual-canvas visual diff, >2-way comparison.
139
+ * **Phase 4 leftovers** — opt-in interaction logging (schema first —
140
+ needed for the user study). Reproducible export and the cost
141
+ preview are DONE.
142
  * **Gate-diff niceties** — pair remove+add of the same op with only a
143
  param change into a "modified" state; column-align lanes across
144
  qubits by circuit moment.
145
+ * **Distribution payloads for QuBound/Qshot** — seed-plumbed now
146
+ (see 15), but they still emit scalar summaries only; no
147
+ across-replicate distribution payload like sampled fidelity's.
148
  * **Prewarm decision** — precomputed disk cache untouched and still
149
  served (fresh-mode namespace unchanged), but responses in it lack
150
  provenance/transformation fields. Either re-run
frontend/src/components/FlowCanvas.tsx CHANGED
@@ -54,7 +54,13 @@ import {
54
  readHashPayload,
55
  type SharePayload,
56
  } from "../lib/share";
57
- import { buildRunRecord, saveRun } from "../lib/runStore";
 
 
 
 
 
 
58
  import { QNode, type QNodeData } from "./QNode";
59
  import { RibbonEdge } from "./RibbonEdge";
60
  import { PresetPicker } from "./PresetPicker";
@@ -165,6 +171,74 @@ export function FlowCanvas() {
165
  const setReplicateCount = useApp((s) => s.setReplicateCount);
166
  const pendingRestore = useApp((s) => s.pendingRestore);
167
  const [notice, setNotice] = useState<Notice>(null);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
  // Non-danger toasts auto-fade; success is quick, warnings linger a bit
169
  // longer so the user has time to read every bullet. Runner errors stay
170
  // put until the next action (Run, Clear, preset change) clears them —
@@ -1068,6 +1142,20 @@ export function FlowCanvas() {
1068
  <option value={20}>×20</option>
1069
  </select>
1070
  )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1071
  <button
1072
  onClick={runPipeline}
1073
  disabled={running || !circuit}
 
54
  readHashPayload,
55
  type SharePayload,
56
  } from "../lib/share";
57
+ import { buildRunRecord, listRuns, saveRun } from "../lib/runStore";
58
+ import {
59
+ estimatePipeline,
60
+ formatSeconds,
61
+ replicateExtraS,
62
+ type PipelineEstimate,
63
+ } from "../lib/costModel";
64
  import { QNode, type QNodeData } from "./QNode";
65
  import { RibbonEdge } from "./RibbonEdge";
66
  import { PresetPicker } from "./PresetPicker";
 
171
  const setReplicateCount = useApp((s) => s.setReplicateCount);
172
  const pendingRestore = useApp((s) => s.pendingRestore);
173
  const [notice, setNotice] = useState<Notice>(null);
174
+ // cost-estimate: per-kind medians from this browser's run archive,
175
+ // recomputed when the canvas kind-set changes or a run is archived
176
+ // (historyVersion bump). Purely client-side — see lib/costModel.ts.
177
+ const historyVersion = useApp((s) => s.historyVersion);
178
+ const [costEst, setCostEst] = useState<PipelineEstimate | null>(null);
179
+ // Kind multiset key: dragging nodes around must not refetch, but
180
+ // adding/removing/retyping a block must.
181
+ const kindsKey = useMemo(
182
+ () =>
183
+ nodes
184
+ .map((n) => (n.data as QNodeData).kind)
185
+ .sort()
186
+ .join("|"),
187
+ [nodes],
188
+ );
189
+ useEffect(() => {
190
+ let alive = true;
191
+ if (nodes.length === 0) {
192
+ setCostEst(null);
193
+ return;
194
+ }
195
+ listRuns(100)
196
+ .then((records) => {
197
+ if (!alive) return;
198
+ setCostEst(
199
+ estimatePipeline(
200
+ nodes.map((n) => ({ id: n.id, kind: (n.data as QNodeData).kind })),
201
+ records,
202
+ ),
203
+ );
204
+ })
205
+ .catch(() => {
206
+ if (alive) setCostEst(null); // archive unreadable → just no chip
207
+ });
208
+ return () => {
209
+ alive = false;
210
+ };
211
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- kindsKey stands in for nodes
212
+ }, [kindsKey, historyVersion]);
213
+ const costChip = useMemo(() => {
214
+ if (!costEst || nodes.length === 0) return null;
215
+ const unknownN = costEst.unknownKinds.length;
216
+ // Nothing observed for ANY canvas kind → an "estimate" would be
217
+ // pure fiction; show nothing until at least one run is archived.
218
+ if (costEst.knownS <= 0 && unknownN > 0) return null;
219
+ let text = `est ~${formatSeconds(costEst.knownS)}`;
220
+ if (unknownN > 0) text += ` + ${unknownN} unknown`;
221
+ let title =
222
+ `Estimated from ${costEst.sampleRuns} archived run(s) in this ` +
223
+ `browser's own run history — median duration per block kind, ` +
224
+ `cache hits excluded.`;
225
+ if (unknownN > 0) {
226
+ title += ` No history yet for: ${costEst.unknownKinds.join(", ")}.`;
227
+ }
228
+ if (replicateCount > 1 && pinnedSeed == null) {
229
+ const extra = replicateExtraS(
230
+ costEst,
231
+ nodes.map((n) => ({ id: n.id, kind: (n.data as QNodeData).kind })),
232
+ replicateCount,
233
+ );
234
+ text += ` · ×${replicateCount} ≈ ${formatSeconds(costEst.knownS + extra)}`;
235
+ title +=
236
+ ` Replicate approximation: the deterministic prefix is served ` +
237
+ `from cache after run 1; only stochastic blocks (sampled ` +
238
+ `fidelity / QuBound / Qshot) re-run each time.`;
239
+ }
240
+ return { text, title };
241
+ }, [costEst, nodes, replicateCount, pinnedSeed]);
242
  // Non-danger toasts auto-fade; success is quick, warnings linger a bit
243
  // longer so the user has time to read every bullet. Runner errors stay
244
  // put until the next action (Run, Clear, preset change) clears them —
 
1142
  <option value={20}>×20</option>
1143
  </select>
1144
  )}
1145
+ {/* cost-estimate chip: what will pressing Run cost, judged
1146
+ from this browser's own archived step timings. Sits next
1147
+ to Run so the price tag is read together with the
1148
+ trigger. Mute styling on purpose — it's advisory, not a
1149
+ gate. */}
1150
+ {costChip && (
1151
+ <span
1152
+ data-marker="cost-estimate"
1153
+ className="chip hidden md:inline-flex whitespace-nowrap"
1154
+ title={costChip.title}
1155
+ >
1156
+ {costChip.text}
1157
+ </span>
1158
+ )}
1159
  <button
1160
  onClick={runPipeline}
1161
  disabled={running || !circuit}
frontend/src/lib/costModel.ts ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /** cost-estimate — a tiny cost model derived from the browser's OWN
2
+ * run archive (IndexedDB), no server involvement.
3
+ *
4
+ * The paper frames pipelines as *stochastic, costly experiments*;
5
+ * this module makes the "costly" half visible before the user clicks
6
+ * Run. Every archived RunRecord's `response.steps` carries
7
+ * `started_at` / `finished_at` (server-side epoch seconds), so we can
8
+ * learn a per-block-kind duration profile from history:
9
+ *
10
+ * estimate(kind) = median over all archived OK steps of that kind
11
+ *
12
+ * Median, not mean: first-hit steps pay one-off warmups (Qshot's
13
+ * ~30-40s HDBSCAN singleton build, lazy torch import) that would
14
+ * wreck a mean; the median tracks the steady-state cost.
15
+ *
16
+ * Steps served from the step cache (`from_step_cache`) are EXCLUDED
17
+ * from the samples — they measure a dictionary lookup, not the
18
+ * computation, and would drag the median toward zero. The estimate
19
+ * answers "what does this block cost when it actually runs?".
20
+ */
21
+
22
+ import type { RunRecord } from "./runStore";
23
+
24
+ export interface PipelineEstimate {
25
+ /** Whole-pipeline estimate in seconds. null when at least one canvas
26
+ * kind has no observed history — `knownS` + `unknownKinds` then
27
+ * carry the honest partial answer. */
28
+ totalS: number | null;
29
+ /** Sum of estimates over the kinds we DO have data for (seconds). */
30
+ knownS: number;
31
+ /** Median observed duration (seconds) per node kind. */
32
+ perKind: Record<string, number>;
33
+ /** Distinct canvas kinds with zero archived observations. */
34
+ unknownKinds: string[];
35
+ /** How many archived runs contributed samples (tooltip honesty). */
36
+ sampleRuns: number;
37
+ }
38
+
39
+ /** Kinds whose handlers are seed-dependent (nondeterministic in fresh
40
+ * mode). Mirrors the backend audit: sampled fidelity, QuBound's LSTM
41
+ * training, Qshot's pilot measurements. Used by the replicate
42
+ * approximation below. */
43
+ export const STOCHASTIC_KINDS: ReadonlySet<string> = new Set([
44
+ "fidelity",
45
+ "qubound",
46
+ "qshot",
47
+ ]);
48
+
49
+ function median(xs: number[]): number {
50
+ const s = [...xs].sort((a, b) => a - b);
51
+ const mid = Math.floor(s.length / 2);
52
+ return s.length % 2 ? s[mid] : (s[mid - 1] + s[mid]) / 2;
53
+ }
54
+
55
+ /** Estimate the wall-clock cost of running `nodes` once, from the
56
+ * durations observed in `records` (this browser's archive). */
57
+ export function estimatePipeline(
58
+ nodes: { id: string; kind: string }[],
59
+ records: RunRecord[],
60
+ ): PipelineEstimate {
61
+ const samples = new Map<string, number[]>();
62
+ const runsWithSamples = new Set<string>();
63
+
64
+ for (const rec of records) {
65
+ const steps = rec.response?.steps;
66
+ if (!Array.isArray(steps)) continue;
67
+ for (const step of steps) {
68
+ if (step.status !== "ok" || step.from_step_cache) continue;
69
+ const dur = step.finished_at - step.started_at;
70
+ if (!Number.isFinite(dur) || dur < 0) continue;
71
+ const kind = step.node_type;
72
+ if (!samples.has(kind)) samples.set(kind, []);
73
+ samples.get(kind)!.push(dur);
74
+ runsWithSamples.add(rec.run_id);
75
+ }
76
+ }
77
+
78
+ const perKind: Record<string, number> = {};
79
+ for (const [kind, xs] of samples) perKind[kind] = median(xs);
80
+
81
+ let knownS = 0;
82
+ const unknown = new Set<string>();
83
+ for (const n of nodes) {
84
+ const est = perKind[n.kind];
85
+ if (est === undefined) unknown.add(n.kind);
86
+ else knownS += est; // per NODE: two fidelity blocks cost twice
87
+ }
88
+
89
+ return {
90
+ totalS: unknown.size === 0 ? knownS : null,
91
+ knownS,
92
+ perKind,
93
+ unknownKinds: [...unknown],
94
+ sampleRuns: runsWithSamples.size,
95
+ };
96
+ }
97
+
98
+ /** Extra seconds that replicates 2..n add on top of one full run.
99
+ *
100
+ * Approximation (deliberately simple): after replicate 1 the
101
+ * deterministic prefix sits in the server's step cache, so replicates
102
+ * 2..n only pay for the seed-dependent blocks — we charge
103
+ * (n-1) x Σ estimate(stochastic nodes on canvas). This UNDERSTATES
104
+ * when a deterministic block sits downstream of a stochastic one
105
+ * (cache is disabled for the whole suffix, so e.g. `output` re-runs
106
+ * too — cheap in practice), and it charges nothing for stochastic
107
+ * kinds with no history (they are already surfaced as unknown). */
108
+ export function replicateExtraS(
109
+ est: PipelineEstimate,
110
+ nodes: { id: string; kind: string }[],
111
+ n: number,
112
+ ): number {
113
+ if (n <= 1) return 0;
114
+ let stochasticS = 0;
115
+ for (const node of nodes) {
116
+ if (!STOCHASTIC_KINDS.has(node.kind)) continue;
117
+ stochasticS += est.perKind[node.kind] ?? 0;
118
+ }
119
+ return (n - 1) * stochasticS;
120
+ }
121
+
122
+ /** "12s" / "3.4s" / "2m 05s" — compact duration for the toolbar chip. */
123
+ export function formatSeconds(s: number): string {
124
+ if (s >= 90) {
125
+ const m = Math.floor(s / 60);
126
+ const rem = Math.round(s % 60);
127
+ return `${m}m ${String(rem).padStart(2, "0")}s`;
128
+ }
129
+ return s >= 10 ? `${Math.round(s)}s` : `${s.toFixed(1)}s`;
130
+ }