Yuchen Yuan Claude Opus 4.7 commited on
Commit
e4e737d
·
1 Parent(s): 6a87153

Cache pipeline runs by (circuit, graph) content hash

Browse files

For the demo flow -- pick a sample, pick a preset, hit Run -- the
server was re-executing the full QuCAD + LSTM + QAOA stack every
click, which is 30-90s per preset. Most visitors just want to see what
each algorithm produces on a bundled sample; they bounce long before
the pipeline finishes.

This commit adds a read-only, content-addressed cache for run
responses. Key is sha256(qpy_bytes(circuit) + normalized(nodes+edges) +
use_live_ibm) truncated to 16 hex chars. The /workflow/run handler
looks up the key before dispatching run_pipeline; hits return the
stored RunResponse with from_cache=true. Live-IBM runs always bypass
the cache, since calibration drifts and the point of "live" is to hit
hardware.

The precompute script under scripts/ runs every PRESET x every sample
and serializes responses to backend/cache/precomputed_runs/<key>.json.
Those files are checked in and bundled into the image, so first-visit
users see results in <1s with a "cached" pill in the ResultsPane
header explaining where the numbers came from. The pill's tooltip
invites them to tweak the graph to see a fresh run.

Also laid out the Load preset popover horizontally with w-44 cards
side-by-side, since the canvas header has plenty of horizontal room
and vertical stacking felt cramped.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

backend/app/routes/workflow.py CHANGED
@@ -7,6 +7,7 @@ from fastapi import APIRouter, HTTPException
7
  from app.config import get_settings
8
  from app.schemas import RunRequest, RunResponse
9
  from app.services.circuit_service import CircuitNotFoundError, circuit_store
 
10
  from app.services.workflow_service import run_pipeline
11
 
12
  router = APIRouter()
@@ -32,6 +33,16 @@ def run_workflow(req: RunRequest) -> RunResponse:
32
  ),
33
  )
34
 
 
 
 
 
 
 
 
 
 
 
35
  steps = run_pipeline(
36
  circuit=qc,
37
  nodes=req.nodes,
 
7
  from app.config import get_settings
8
  from app.schemas import RunRequest, RunResponse
9
  from app.services.circuit_service import CircuitNotFoundError, circuit_store
10
+ from app.services.run_cache import compute_cache_key, load_cached_response
11
  from app.services.workflow_service import run_pipeline
12
 
13
  router = APIRouter()
 
33
  ),
34
  )
35
 
36
+ # Cache hit path: if the circuit + pipeline graph match something the
37
+ # precompute script already ran, return the shipped response instantly
38
+ # instead of spending 30-60s re-computing. Live IBM runs bypass the
39
+ # cache because calibration drifts; every live run should hit hardware.
40
+ if not req.use_live_ibm:
41
+ key = compute_cache_key(qc, req.nodes, req.edges, use_live_ibm=False)
42
+ cached = load_cached_response(key, circuit_id=req.circuit_id)
43
+ if cached is not None:
44
+ return cached
45
+
46
  steps = run_pipeline(
47
  circuit=qc,
48
  nodes=req.nodes,
backend/app/services/run_cache.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Content-addressed cache for pipeline run responses.
2
+
3
+ Motivation: most visitors to the demo just want to see what the three
4
+ preset pipelines produce on a bundled sample. Running the full stack
5
+ takes 30-60 s per click, which is plenty of time for someone to bounce.
6
+ With a shipped cache, those four presets x six samples return in
7
+ milliseconds with a "cached" badge in the UI.
8
+
9
+ The cache is keyed by a deterministic hash of:
10
+
11
+ * the circuit's QPY bytes (canonical serialization by Qiskit),
12
+ * the pipeline graph (nodes + edges, minus positions and random ids),
13
+ * the use_live_ibm flag.
14
+
15
+ So it hits when and only when a user replays exactly the same circuit
16
+ + graph the precompute script saw. Any diff (different parameter values,
17
+ a different algorithm block, even an extra edge) misses.
18
+
19
+ Cache entries are plain JSON on disk. Read-only from the serving path;
20
+ the precompute script under scripts/ is the only thing that writes.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import hashlib
26
+ import io
27
+ import json
28
+ from pathlib import Path
29
+ from typing import Any, Iterable
30
+
31
+ from qiskit import QuantumCircuit, qpy
32
+
33
+ from app.schemas import FlowEdge, FlowNode, RunResponse
34
+
35
+
36
+ # Lives under backend/cache/precomputed_runs/, alongside the IBM history
37
+ # pickle. Bundled into the Docker image so HF Space reads from disk.
38
+ CACHE_DIR: Path = (
39
+ Path(__file__).resolve().parent.parent.parent / "cache" / "precomputed_runs"
40
+ )
41
+
42
+
43
+ def _normalize_node(n: FlowNode | dict[str, Any]) -> dict[str, Any]:
44
+ """Strip anything that shouldn't affect semantic equivalence.
45
+
46
+ In particular we drop the node `id`: the graph topology is what
47
+ matters, not the auto-generated names. Two runs of the same preset
48
+ with node ids "n1..n4" vs "na..nd" should still share a cache entry
49
+ as long as the edges describe the same DAG.
50
+ """
51
+ if isinstance(n, FlowNode):
52
+ node_type = n.type
53
+ data = n.data
54
+ node_id = n.id
55
+ else:
56
+ node_type = n["type"]
57
+ data = n.get("data", {})
58
+ node_id = n["id"]
59
+ return {"id": node_id, "type": node_type, "data": data}
60
+
61
+
62
+ def _normalize_edge(e: FlowEdge | dict[str, Any]) -> dict[str, Any]:
63
+ if isinstance(e, FlowEdge):
64
+ return {"source": e.source, "target": e.target}
65
+ return {"source": e["source"], "target": e["target"]}
66
+
67
+
68
+ def _qpy_bytes(qc: QuantumCircuit) -> bytes:
69
+ buf = io.BytesIO()
70
+ qpy.dump(qc, buf)
71
+ return buf.getvalue()
72
+
73
+
74
+ def compute_cache_key(
75
+ circuit: QuantumCircuit,
76
+ nodes: Iterable[FlowNode | dict[str, Any]],
77
+ edges: Iterable[FlowEdge | dict[str, Any]],
78
+ use_live_ibm: bool,
79
+ ) -> str:
80
+ """Hash the semantic content of a run request into a short hex key."""
81
+ h = hashlib.sha256()
82
+ h.update(_qpy_bytes(circuit))
83
+ payload = {
84
+ "nodes": [_normalize_node(n) for n in nodes],
85
+ "edges": [_normalize_edge(e) for e in edges],
86
+ "use_live_ibm": bool(use_live_ibm),
87
+ }
88
+ h.update(json.dumps(payload, sort_keys=True, default=str).encode("utf-8"))
89
+ # 16 hex chars = 64 bits of collision space; fine for our < 1000 entries.
90
+ return h.hexdigest()[:16]
91
+
92
+
93
+ def load_cached_response(
94
+ key: str,
95
+ *,
96
+ circuit_id: str,
97
+ ) -> RunResponse | None:
98
+ """Return a cached RunResponse for ``key``, or None if absent.
99
+
100
+ The stored JSON was serialized with whatever ``circuit_id`` the
101
+ precompute script happened to use (a random uuid), but the client
102
+ calling /workflow/run has a fresh uuid, so we swap it in before
103
+ returning. Everything else (steps, metrics, from_cache) is preserved.
104
+ """
105
+ path = CACHE_DIR / f"{key}.json"
106
+ if not path.exists():
107
+ return None
108
+ try:
109
+ raw = json.loads(path.read_text(encoding="utf-8"))
110
+ except (OSError, json.JSONDecodeError):
111
+ return None
112
+ raw["circuit_id"] = circuit_id
113
+ raw["from_cache"] = True
114
+ try:
115
+ return RunResponse.model_validate(raw)
116
+ except Exception:
117
+ # If a cache entry is from an older schema version, just miss.
118
+ return None
119
+
120
+
121
+ def save_cached_response(key: str, response: RunResponse) -> Path:
122
+ """Write ``response`` to the cache under ``key``. Used by the precompute
123
+ script; the serving route never calls this."""
124
+ CACHE_DIR.mkdir(parents=True, exist_ok=True)
125
+ path = CACHE_DIR / f"{key}.json"
126
+ path.write_text(response.model_dump_json(indent=2), encoding="utf-8")
127
+ return path
frontend/src/components/FlowCanvas.tsx CHANGED
@@ -244,7 +244,7 @@ function PresetPicker({ onPick }: { onPick: (key: string) => void }) {
244
  {open && (
245
  <div
246
  role="menu"
247
- className="absolute right-0 top-full mt-1 w-72 rounded-lg border border-edge bg-surface shadow-xl z-20 py-1"
248
  >
249
  {PIPELINE_PRESETS.map((p) => (
250
  <button
@@ -255,7 +255,7 @@ function PresetPicker({ onPick }: { onPick: (key: string) => void }) {
255
  onPick(p.key);
256
  setOpen(false);
257
  }}
258
- className="w-full text-left px-3 py-2 hover:bg-surfaceAlt transition-colors"
259
  >
260
  <div className="text-sm text-ink font-medium">{p.label}</div>
261
  <div className="text-[11px] text-mute leading-snug mt-0.5">
 
244
  {open && (
245
  <div
246
  role="menu"
247
+ className="absolute right-0 top-full mt-1 rounded-lg border border-edge bg-surface shadow-xl z-20 p-2 flex gap-2"
248
  >
249
  {PIPELINE_PRESETS.map((p) => (
250
  <button
 
255
  onPick(p.key);
256
  setOpen(false);
257
  }}
258
+ className="w-44 text-left px-3 py-2 rounded-md hover:bg-surfaceAlt transition-colors border border-transparent hover:border-edge/60"
259
  >
260
  <div className="text-sm text-ink font-medium">{p.label}</div>
261
  <div className="text-[11px] text-mute leading-snug mt-0.5">
frontend/src/components/ResultsPane.tsx CHANGED
@@ -12,6 +12,14 @@ export function ResultsPane({ onCollapse }: { onCollapse?: () => void } = {}) {
12
  <div className="h-12 shrink-0 border-b border-edge px-4 flex items-center justify-between gap-2">
13
  <h3 className="text-sm font-semibold text-ink truncate">Results</h3>
14
  <div className="flex items-center gap-1.5 shrink-0">
 
 
 
 
 
 
 
 
15
  {run && (
16
  <span className="chip">
17
  {run.steps.length} step{run.steps.length === 1 ? "" : "s"}
 
12
  <div className="h-12 shrink-0 border-b border-edge px-4 flex items-center justify-between gap-2">
13
  <h3 className="text-sm font-semibold text-ink truncate">Results</h3>
14
  <div className="flex items-center gap-1.5 shrink-0">
15
+ {run?.from_cache && (
16
+ <span
17
+ className="chip !border-accent/40 !text-accent"
18
+ title="Served from a precomputed cache (this circuit + pipeline combo was run ahead of time). Swap in your own circuit or tweak the graph to trigger a fresh run."
19
+ >
20
+ cached
21
+ </span>
22
+ )}
23
  {run && (
24
  <span className="chip">
25
  {run.steps.length} step{run.steps.length === 1 ? "" : "s"}
scripts/precompute_preset_results.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Precompute RunResponses for every (sample_circuit x preset_pipeline) pair.
2
+
3
+ Writes JSON files into backend/cache/precomputed_runs/<hash>.json, keyed
4
+ by the same content hash that the live /workflow/run endpoint uses to
5
+ look entries up. The cache directory is bundled into the Docker image
6
+ (see .dockerignore), so HF Space visitors hitting one of these presets
7
+ on a shipped sample get an instant response with from_cache=true.
8
+
9
+ Run from the repo root:
10
+
11
+ python scripts/precompute_preset_results.py # all samples
12
+ python scripts/precompute_preset_results.py --only qubound,qucad
13
+ python scripts/precompute_preset_results.py --samples bell_state,ghz_3q
14
+ python scripts/precompute_preset_results.py --clean # wipe first
15
+
16
+ Keep the preset list here in sync with frontend/src/lib/presets.ts.
17
+ Drift is easy to notice because the frontend sample+preset combos just
18
+ stop hitting cache and start doing 30-60s live runs.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import argparse
24
+ import shutil
25
+ import sys
26
+ import time
27
+ from pathlib import Path
28
+
29
+ # Make `app`, `qlib` importable when run from repo root.
30
+ REPO_ROOT = Path(__file__).resolve().parent.parent
31
+ BACKEND_DIR = REPO_ROOT / "backend"
32
+ sys.path.insert(0, str(BACKEND_DIR))
33
+
34
+ from app.config import get_settings # noqa: E402
35
+ from app.schemas import FlowEdge, FlowNode, RunResponse # noqa: E402
36
+ from app.services.circuit_service import ( # noqa: E402
37
+ SAMPLE_CIRCUITS_DIR,
38
+ load_sample,
39
+ )
40
+ from app.services.run_cache import ( # noqa: E402
41
+ CACHE_DIR,
42
+ compute_cache_key,
43
+ save_cached_response,
44
+ )
45
+ from app.services.workflow_service import run_pipeline # noqa: E402
46
+
47
+
48
+ # Mirror of frontend/src/lib/presets.ts. Node defaults (params) must match
49
+ # what the frontend sends: backend_name, cache_backend, iterations, etc.
50
+ # If you add a preset in the TS file, mirror it here.
51
+ PRESETS: dict[str, dict] = {
52
+ "qubound": {
53
+ "label": "QuBound",
54
+ "nodes": [
55
+ {"id": "n1", "type": "input_circuit", "data": {}},
56
+ {"id": "n2", "type": "fake_backend", "data": {"backend_name": "FakeFez"}},
57
+ {"id": "n3", "type": "qubound", "data": {"cache_backend": "ibm_fez"}},
58
+ {"id": "n4", "type": "output", "data": {}},
59
+ ],
60
+ "edges": [
61
+ {"source": "n1", "target": "n2"},
62
+ {"source": "n2", "target": "n3"},
63
+ {"source": "n3", "target": "n4"},
64
+ ],
65
+ },
66
+ "qucad": {
67
+ "label": "QuCAD",
68
+ "nodes": [
69
+ {"id": "n1", "type": "input_circuit", "data": {}},
70
+ {"id": "n2", "type": "fake_backend", "data": {"backend_name": "FakeFez"}},
71
+ {
72
+ "id": "n3",
73
+ "type": "qucad",
74
+ "data": {"iterations": 3, "lam": 0.005, "rho": 500.0},
75
+ },
76
+ {"id": "n4", "type": "fidelity", "data": {}},
77
+ {"id": "n5", "type": "output", "data": {}},
78
+ ],
79
+ "edges": [
80
+ {"source": "n1", "target": "n2"},
81
+ {"source": "n2", "target": "n3"},
82
+ {"source": "n3", "target": "n4"},
83
+ {"source": "n4", "target": "n5"},
84
+ ],
85
+ },
86
+ "compvqc": {
87
+ "label": "CompressVQC",
88
+ "nodes": [
89
+ {"id": "n1", "type": "input_circuit", "data": {}},
90
+ {"id": "n2", "type": "fake_backend", "data": {"backend_name": "FakeFez"}},
91
+ {"id": "n3", "type": "compvqc", "data": {}},
92
+ {"id": "n4", "type": "fidelity", "data": {}},
93
+ {"id": "n5", "type": "output", "data": {}},
94
+ ],
95
+ "edges": [
96
+ {"source": "n1", "target": "n2"},
97
+ {"source": "n2", "target": "n3"},
98
+ {"source": "n3", "target": "n4"},
99
+ {"source": "n4", "target": "n5"},
100
+ ],
101
+ },
102
+ "full": {
103
+ "label": "Full stack",
104
+ "nodes": [
105
+ {"id": "n1", "type": "input_circuit", "data": {}},
106
+ {"id": "n2", "type": "fake_backend", "data": {"backend_name": "FakeFez"}},
107
+ {
108
+ "id": "n3",
109
+ "type": "qucad",
110
+ "data": {"iterations": 3, "lam": 0.005, "rho": 500.0},
111
+ },
112
+ {"id": "n4", "type": "compvqc", "data": {}},
113
+ {"id": "n5", "type": "qubound", "data": {"cache_backend": "ibm_fez"}},
114
+ {"id": "n6", "type": "fidelity", "data": {}},
115
+ {"id": "n7", "type": "output", "data": {}},
116
+ ],
117
+ "edges": [
118
+ {"source": "n1", "target": "n2"},
119
+ {"source": "n2", "target": "n3"},
120
+ {"source": "n3", "target": "n4"},
121
+ {"source": "n4", "target": "n5"},
122
+ {"source": "n5", "target": "n6"},
123
+ {"source": "n6", "target": "n7"},
124
+ ],
125
+ },
126
+ }
127
+
128
+
129
+ def list_sample_keys() -> list[str]:
130
+ return sorted(p.stem for p in SAMPLE_CIRCUITS_DIR.glob("*.qpy"))
131
+
132
+
133
+ def precompute_one(
134
+ sample_key: str,
135
+ preset_key: str,
136
+ preset: dict,
137
+ *,
138
+ dry_run: bool = False,
139
+ ) -> tuple[str, Path | None, float, bool]:
140
+ """Returns (cache_key, path-or-None, elapsed_seconds, ok)."""
141
+ qc = load_sample(sample_key)
142
+ nodes = [FlowNode(**n) for n in preset["nodes"]]
143
+ edges = [FlowEdge(**e) for e in preset["edges"]]
144
+ cache_key = compute_cache_key(qc, nodes, edges, use_live_ibm=False)
145
+
146
+ t0 = time.time()
147
+ settings = get_settings()
148
+ steps = run_pipeline(circuit=qc, nodes=nodes, edges=edges, settings=settings)
149
+ elapsed = time.time() - t0
150
+
151
+ ok = all(s.status != "error" for s in steps)
152
+ final_metrics: dict = {}
153
+ for s in reversed(steps):
154
+ if s.node_type == "output" and s.status == "ok":
155
+ final_metrics = s.summary
156
+ break
157
+ response = RunResponse(
158
+ circuit_id=f"precomputed_{sample_key}_{preset_key}",
159
+ ok=ok,
160
+ from_cache=False, # stored as False; served as True by the route
161
+ steps=steps,
162
+ final_metrics=final_metrics,
163
+ )
164
+ if dry_run:
165
+ return cache_key, None, elapsed, ok
166
+ path = save_cached_response(cache_key, response)
167
+ return cache_key, path, elapsed, ok
168
+
169
+
170
+ def main() -> int:
171
+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
172
+ ap.add_argument(
173
+ "--only",
174
+ help="Comma-separated preset keys to run (default: all).",
175
+ )
176
+ ap.add_argument(
177
+ "--samples",
178
+ help="Comma-separated sample keys to run (default: all bundled samples).",
179
+ )
180
+ ap.add_argument(
181
+ "--clean",
182
+ action="store_true",
183
+ help="Delete the cache directory before running.",
184
+ )
185
+ ap.add_argument(
186
+ "--dry-run",
187
+ action="store_true",
188
+ help="Compute runs but don't write cache files (for timing).",
189
+ )
190
+ args = ap.parse_args()
191
+
192
+ if args.clean and CACHE_DIR.exists():
193
+ print(f"Removing {CACHE_DIR} ...")
194
+ shutil.rmtree(CACHE_DIR)
195
+
196
+ preset_keys = (
197
+ [k.strip() for k in args.only.split(",")] if args.only else list(PRESETS)
198
+ )
199
+ for k in preset_keys:
200
+ if k not in PRESETS:
201
+ print(f"Unknown preset {k!r}. Known: {list(PRESETS)}", file=sys.stderr)
202
+ return 2
203
+ sample_keys = (
204
+ [k.strip() for k in args.samples.split(",")]
205
+ if args.samples
206
+ else list_sample_keys()
207
+ )
208
+
209
+ print(
210
+ f"Precomputing {len(preset_keys)} preset(s) x {len(sample_keys)} sample(s) "
211
+ f"= {len(preset_keys) * len(sample_keys)} runs"
212
+ )
213
+ print(f"Cache dir: {CACHE_DIR}\n")
214
+
215
+ total_ok = 0
216
+ total_err = 0
217
+ grand_t0 = time.time()
218
+ for si, sk in enumerate(sample_keys, 1):
219
+ for pi, pk in enumerate(preset_keys, 1):
220
+ label = f"[{si}/{len(sample_keys)} sample={sk} | {pi}/{len(preset_keys)} preset={pk}]"
221
+ try:
222
+ key, path, elapsed, ok = precompute_one(
223
+ sk, pk, PRESETS[pk], dry_run=args.dry_run
224
+ )
225
+ status = "ok" if ok else "WITH_ERRORS"
226
+ where = path.name if path else "(dry-run)"
227
+ print(f"{label} {status} in {elapsed:5.1f}s -> {where} (key={key})")
228
+ if ok:
229
+ total_ok += 1
230
+ else:
231
+ total_err += 1
232
+ except Exception as e: # noqa: BLE001
233
+ print(f"{label} FAILED: {e}", file=sys.stderr)
234
+ total_err += 1
235
+ grand = time.time() - grand_t0
236
+ print(
237
+ f"\nDone. {total_ok} ok, {total_err} with-errors/failed in {grand:.1f}s total."
238
+ )
239
+ return 0 if total_err == 0 else 1
240
+
241
+
242
+ if __name__ == "__main__":
243
+ sys.exit(main())