RFTSystems commited on
Commit
d0b9a0c
·
verified ·
1 Parent(s): c09c071

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +279 -347
app.py CHANGED
@@ -1,103 +1,40 @@
1
- # app.py
2
- # Coherent_Compute_Engine RFTSystems
3
- # Real, on-machine coherent throughput benchmark + tamper-evident receipt download (SHA-256).
4
- #
5
- # What an “item” is:
6
- # 1 item = one per-oscillator coherent state update of [Psi, E, L] per step.
7
- #
8
- # Notes:
9
- # - Measurements reflect the Hugging Face Space runtime hardware (not the visitor’s local machine).
10
- # - Includes optional baselines (NumPy vectorised + tiny Python loop) computed live.
11
- # - Produces a downloadable receipt JSON with canonical hashing for verification.
12
 
13
  import os
14
- import json
15
  import time
 
16
  import math
17
- import csv
18
  import hashlib
19
  import platform
20
- import datetime as dt
21
- from pathlib import Path
22
 
23
  import numpy as np
24
  import gradio as gr
25
 
26
- # Optional: Numba acceleration (used if available)
27
  try:
28
  import numba as nb
29
  NUMBA_OK = True
30
  except Exception:
31
- nb = None
32
  NUMBA_OK = False
 
33
 
34
- APP_NAME = "Coherent_Compute_Engine"
35
- APP_VERSION = "v1.0.0"
36
- RESULTS_DIR = Path("results")
37
- RESULTS_DIR.mkdir(exist_ok=True)
38
-
39
- # ----------------------------
40
- # Canonical JSON + integrity
41
- # ----------------------------
42
- def canon_json_bytes(obj) -> bytes:
43
- return json.dumps(
44
- obj,
45
- ensure_ascii=False,
46
- sort_keys=True,
47
- separators=(",", ":"),
48
- ).encode("utf-8")
49
-
50
- def sha256_hex(b: bytes) -> str:
51
- return hashlib.sha256(b).hexdigest()
52
-
53
- def utc_now_iso() -> str:
54
- # Avoid deprecated utcnow warning in newer Python versions
55
- return dt.datetime.now(dt.timezone.utc).isoformat().replace("+00:00", "Z")
56
-
57
- def write_receipt(payload: dict) -> str:
58
- """
59
- Writes a JSON receipt to disk and returns the filepath for Gradio download.
60
- Receipt includes its own SHA-256 of the canonical JSON (tamper-evident).
61
- """
62
- # hash without integrity field
63
- payload = dict(payload) # copy
64
- payload.pop("integrity", None)
65
-
66
- b0 = canon_json_bytes(payload)
67
- h = sha256_hex(b0)
68
 
69
- payload["integrity"] = {
70
- "sha256": h,
71
- "receipt_id": h[:12],
72
- "canonical_json": "sorted_keys + compact_separators",
73
- }
74
 
75
- b1 = canon_json_bytes(payload)
76
-
77
- ts = payload.get("timestamp_utc", utc_now_iso())
78
- safe_ts = ts.replace(":", "").replace(".", "").replace("Z", "")
79
- fname = f"receipt_{safe_ts}_{h[:12]}.json"
80
- path = RESULTS_DIR / fname
81
- path.write_bytes(b1)
82
- return str(path)
83
-
84
- def append_csv_row(row: dict, csv_path: Path):
85
- headers = [
86
- "timestamp_utc","engine","device_note","oscillators","steps",
87
- "elapsed_s","throughput_Bps","coherence_abs","mean_energy",
88
- "python","platform","cpu_count_logical","numba_available","seed","scale"
89
- ]
90
- need_header = not csv_path.exists()
91
- with csv_path.open("a", newline="") as f:
92
- w = csv.DictWriter(f, fieldnames=headers)
93
- if need_header:
94
- w.writeheader()
95
- w.writerow({k: row.get(k, "") for k in headers})
96
-
97
- # ----------------------------
98
- # RFT-lite coherent kernel
99
- # ----------------------------
100
- def _np_step(Psi, E, L, scale=1.0):
101
  phase = 0.997 * Psi + 0.003 * E
102
  drive = np.tanh(phase * scale)
103
  Psi_n = 0.999 * Psi + 0.001 * drive
@@ -105,303 +42,298 @@ def _np_step(Psi, E, L, scale=1.0):
105
  L_n = 0.998 * L + 0.001 * (Psi_n * E_n)
106
  return Psi_n, E_n, L_n
107
 
108
- def coherence_abs(Psi0: np.ndarray, Psi1: np.ndarray) -> float:
109
- v0 = Psi0.astype(np.float64, copy=False)
110
- v1 = Psi1.astype(np.float64, copy=False)
111
- num = float(np.dot(v0, v1))
112
- den = float(np.linalg.norm(v0) * np.linalg.norm(v1)) + 1e-12
113
- return abs(num / den)
 
 
 
 
 
114
 
115
- def mean_energy(E: np.ndarray) -> float:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  return float(np.mean(np.clip(E, 0.0, 1.5)))
117
 
118
- def run_engine_numpy(n: int, steps: int, seed: int, scale: float):
119
- rng = np.random.default_rng(seed)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  Psi = rng.random(n, dtype=np.float32)
121
  E = rng.random(n, dtype=np.float32)
122
  L = rng.random(n, dtype=np.float32)
123
 
124
- sample = min(n, 200_000)
 
125
  Psi0 = Psi[:sample].copy()
126
 
127
- t0 = time.perf_counter()
128
- for _ in range(steps):
129
- Psi, E, L = _np_step(Psi, E, L, scale=scale)
130
- t1 = time.perf_counter()
131
-
132
- elapsed = t1 - t0
133
- Psi1 = Psi[:sample].copy()
134
-
135
- items = int(n) * int(steps)
136
- throughput_Bps = (items / elapsed) / 1e9
137
-
138
- return {
139
- "engine": "numpy",
140
- "oscillators": int(n),
141
- "steps": int(steps),
142
- "elapsed_s": float(elapsed),
143
- "throughput_Bps": float(throughput_Bps),
144
- "coherence_abs": float(coherence_abs(Psi0, Psi1)),
145
- "mean_energy": float(mean_energy(E[:sample])),
146
- }
147
-
148
- # ----------------------------
149
- # Baselines (optional, live)
150
- # ----------------------------
151
- def run_baseline_python(n: int, steps: int, seed: int):
152
- # Safety caps for hosted runtimes
153
- n = min(n, 200_000)
154
- steps = min(steps, 10)
155
-
156
- rng = np.random.default_rng(seed)
157
- Psi = rng.random(n).tolist()
158
- E = rng.random(n).tolist()
159
- L = rng.random(n).tolist()
160
-
161
- def step(Psi, E, L):
162
- outPsi = [0.0]*n
163
- outE = [0.0]*n
164
- outL = [0.0]*n
165
- for i in range(n):
166
- phase = 0.997*Psi[i] + 0.003*E[i]
167
- drive = math.tanh(phase)
168
- p = 0.999*Psi[i] + 0.001*drive
169
- e = 0.995*E[i] + 0.004*p
170
- l = 0.998*L[i] + 0.001*(p*e)
171
- outPsi[i], outE[i], outL[i] = p, e, l
172
- return outPsi, outE, outL
173
-
174
- t0 = time.perf_counter()
175
- for _ in range(steps):
176
- Psi, E, L = step(Psi, E, L)
177
- t1 = time.perf_counter()
178
-
179
- elapsed = t1 - t0
180
- items = int(n) * int(steps)
181
- throughput_Bps = (items / elapsed) / 1e9
182
-
183
- return {
184
- "engine": "python_loop",
185
- "oscillators": int(n),
186
- "steps": int(steps),
187
- "elapsed_s": float(elapsed),
188
- "throughput_Bps": float(throughput_Bps),
189
- "coherence_abs": 1.0,
190
- "mean_energy": float(np.mean(np.clip(np.array(E[:min(n, 50_000)], dtype=np.float32), 0.0, 1.5))),
191
- "note": "Python baseline is safety-capped (n<=200k, steps<=10).",
192
- }
193
 
194
- # ----------------------------
195
- # Numba engine (if available)
196
- # ----------------------------
197
- if NUMBA_OK:
198
- @nb.njit(fastmath=True)
199
- def _numba_kernel(Psi, E, L, scale):
200
- n = Psi.shape[0]
201
- for i in range(n):
202
- phase = 0.997 * Psi[i] + 0.003 * E[i]
203
- drive = math.tanh(phase * scale)
204
- p = 0.999 * Psi[i] + 0.001 * drive
205
- e = 0.995 * E[i] + 0.004 * p
206
- l = 0.998 * L[i] + 0.001 * (p * e)
207
- Psi[i] = p
208
- E[i] = e
209
- L[i] = l
210
-
211
- def run_engine_numba(n: int, steps: int, seed: int, scale: float):
212
- rng = np.random.default_rng(seed)
213
- Psi = rng.random(n, dtype=np.float32)
214
- E = rng.random(n, dtype=np.float32)
215
- L = rng.random(n, dtype=np.float32)
216
-
217
- sample = min(n, 200_000)
218
- Psi0 = Psi[:sample].copy()
219
-
220
- # compile warmup on tiny arrays
221
- tiny = min(n, 1024)
222
- _numba_kernel(Psi[:tiny], E[:tiny], L[:tiny], scale)
223
-
224
- t0 = time.perf_counter()
225
- for _ in range(steps):
226
- _numba_kernel(Psi, E, L, scale)
227
- t1 = time.perf_counter()
228
-
229
- elapsed = t1 - t0
230
- Psi1 = Psi[:sample].copy()
231
-
232
- items = int(n) * int(steps)
233
- throughput_Bps = (items / elapsed) / 1e9
234
-
235
- return {
236
- "engine": "numba",
237
- "oscillators": int(n),
238
- "steps": int(steps),
239
- "elapsed_s": float(elapsed),
240
- "throughput_Bps": float(throughput_Bps),
241
- "coherence_abs": float(coherence_abs(Psi0, Psi1)),
242
- "mean_energy": float(mean_energy(E[:sample])),
243
- }
244
-
245
- # ----------------------------
246
- # Runner + UI helpers
247
- # ----------------------------
248
- def format_ui(primary: dict, baselines: dict | None):
249
- ui = {
250
- "Throughput (B/s)": f'{primary["throughput_Bps"]:.3f} B/s',
251
- "Coherence (|C|)": f'{primary["coherence_abs"]:.5f}',
252
- "Mean Energy": f'{primary["mean_energy"]:.5f}',
253
- "Elapsed Time (s)": f'{primary["elapsed_s"]:.2f}',
254
- "Oscillators": f'{primary["oscillators"]:,}',
255
- "Steps": f'{primary["steps"]:,}',
256
- "Engine": primary["engine"],
257
- "CPU Cores Available": os.cpu_count(),
258
- }
259
- if baselines:
260
- for name, b in baselines.items():
261
- ui[f"Baseline: {name} (B/s)"] = f'{b["throughput_Bps"]:.3f}'
262
- ui[f"Baseline: {name} Engine"] = b["engine"]
263
- return ui
264
-
265
- def run_and_receipt(n_oscillators, steps, seed, scale, include_baselines):
266
- n = int(n_oscillators)
267
- s = int(steps)
268
- seed = int(seed)
269
- scale = float(scale)
270
-
271
- # Safety rails (prevents accidental crash / OOM on Space)
272
- n = max(100_000, min(n, 40_000_000))
273
- s = max(10, min(s, 5000))
274
-
275
- # primary engine
276
  if NUMBA_OK:
277
- primary = run_engine_numba(n, s, seed, scale)
 
 
 
 
 
 
 
 
 
 
 
 
278
  else:
279
- primary = run_engine_numpy(n, s, seed, scale)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
280
 
281
- # optional baselines
282
- baselines = {}
283
  if include_baselines:
284
- baselines["numpy"] = run_engine_numpy(min(n, 8_000_000), min(s, 2000), seed, scale)
285
- baselines["python_loop"] = run_baseline_python(min(n, 500_000), min(s, 200), seed)
 
 
 
 
 
 
 
 
 
 
286
 
287
- # build receipt payload
 
 
 
 
 
 
288
  payload = {
289
- "timestamp_utc": utc_now_iso(),
290
- "app": {"name": APP_NAME, "version": APP_VERSION},
291
- "definition": {
292
- "item": "1 item = one per-oscillator coherent state update of [Psi, E, L] per step (as implemented here)."
293
- },
294
- "runtime": {
295
- "device_note": "Hugging Face Space runtime machine (results are not from the visitor's local CPU).",
296
- "platform": platform.platform(),
297
- "python": platform.python_version(),
298
- "cpu_count_logical": os.cpu_count(),
299
- "numba_available": bool(NUMBA_OK),
300
- },
301
- "inputs": {
302
- "oscillators": int(n),
303
- "steps": int(s),
304
- "seed": int(seed),
305
- "scale": float(scale),
306
- "include_baselines": bool(include_baselines),
307
- },
308
- "results": {
309
- "primary": primary,
310
- "baselines": baselines,
311
- },
312
  }
313
 
314
- receipt_path = write_receipt(payload)
315
-
316
- # append csv row (primary only)
317
- csv_row = {
318
- "timestamp_utc": payload["timestamp_utc"],
319
- "engine": primary["engine"],
320
- "device_note": payload["runtime"]["device_note"],
321
- "oscillators": primary["oscillators"],
322
- "steps": primary["steps"],
323
- "elapsed_s": primary["elapsed_s"],
324
- "throughput_Bps": primary["throughput_Bps"],
325
- "coherence_abs": primary["coherence_abs"],
326
- "mean_energy": primary["mean_energy"],
327
- "python": payload["runtime"]["python"],
328
- "platform": payload["runtime"]["platform"],
329
- "cpu_count_logical": payload["runtime"]["cpu_count_logical"],
330
- "numba_available": payload["runtime"]["numba_available"],
331
- "seed": seed,
332
- "scale": scale,
333
  }
334
- append_csv_row(csv_row, RESULTS_DIR / "runs.csv")
335
 
336
- # UI output
337
- ui = format_ui(primary, baselines if include_baselines else None)
338
- ui["Receipt SHA-256 (in file)"] = payload["integrity"]["sha256"] if "integrity" in payload else "written in receipt"
 
 
 
 
 
 
 
 
 
 
339
 
340
- return ui, receipt_path
341
 
342
- # ----------------------------
343
  # UI
344
- # ----------------------------
345
- CSS = """
346
- :root { --rft-accent: #ff7a18; }
347
- .gradio-container { max-width: 980px !important; }
348
- #titlebar h1 { font-size: 2.05rem; letter-spacing: -0.02em; }
349
- .rft-card { border-radius: 16px !important; border: 1px solid rgba(255,255,255,0.08) !important; }
350
- """
351
 
352
- with gr.Blocks(css=CSS, theme=gr.themes.Soft()) as demo:
353
- gr.Markdown(
354
- """
355
- <div id="titlebar"><h1>Coherent Compute Engine</h1></div>
356
 
357
- **What this Space does**
358
- Runs a real coherent state-update benchmark and reports measured throughput, stability proxy, and energy behavior. No precomputed results.
359
 
360
- **What an “item” is**
361
- One coherent update of **[Ψ, E, L]** per oscillator per step.
 
 
 
 
362
 
363
- **Verification**
364
- Every run generates a tamper-evident receipt (JSON) with a SHA-256 hash you can download.
365
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
366
  )
367
 
 
 
368
  with gr.Row():
369
- with gr.Column(scale=1):
370
- with gr.Group(elem_classes=["rft-card"]):
371
- n_slider = gr.Slider(
372
- minimum=100_000, maximum=40_000_000, step=100_000,
373
- value=6_400_000, label="Number of Oscillators"
374
- )
375
- steps_slider = gr.Slider(
376
- minimum=10, maximum=5000, step=10,
377
- value=650, label="Simulation Steps"
378
- )
379
- seed_box = gr.Number(value=7, precision=0, label="Seed")
380
- scale_box = gr.Number(value=1.0, precision=3, label="Scale (stability knob)")
381
- include_baselines = gr.Checkbox(
382
- value=False,
383
- label="Include baselines (NumPy + tiny Python loop)",
384
- info="Baselines are measured live too. Python loop is safety-capped."
385
- )
386
- run_btn = gr.Button("Run Engine", variant="primary")
387
-
388
- with gr.Column(scale=1):
389
- results_json = gr.JSON(label="Results")
390
- receipt_file = gr.File(label="Receipt (download)")
391
 
392
- run_btn.click(
393
- fn=run_and_receipt,
394
- inputs=[n_slider, steps_slider, seed_box, scale_box, include_baselines],
395
- outputs=[results_json, receipt_file],
396
- )
397
 
398
- gr.Markdown(
399
- """
400
- **Notes**
401
- - This runs on the Hugging Face Space runtime machine. Your browser is just the UI.
402
- - If the Space is under load, throughput will vary; the receipt captures the environment at run time.
403
- """
404
  )
405
 
406
  if __name__ == "__main__":
407
- demo.launch()
 
1
+ # app.py — Coherent_Compute_Engine (RFTSystems)
2
+ # Live, measurable throughput + stability + energy proxy, with verification baselines + receipt download.
3
+ # No estimates. No precomputed data. Same workload, same machine, same rules.
 
 
 
 
 
 
 
 
4
 
5
  import os
 
6
  import time
7
+ import json
8
  import math
 
9
  import hashlib
10
  import platform
11
+ from datetime import datetime, timezone
 
12
 
13
  import numpy as np
14
  import gradio as gr
15
 
16
+ # Optional: numba acceleration
17
  try:
18
  import numba as nb
19
  NUMBA_OK = True
20
  except Exception:
 
21
  NUMBA_OK = False
22
+ nb = None
23
 
24
+ APP_TITLE = "Coherent Compute Engine"
25
+ RESULTS_DIR = "receipts"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
+ # -----------------------------
28
+ # Definition: what an "item" is
29
+ # -----------------------------
30
+ # One coherent state update of [Psi, E, L] per oscillator per step.
31
+ # Items/sec = (N oscillators * steps) / elapsed_seconds
32
 
33
+ # -----------------------------
34
+ # Core update: vectorised (NumPy)
35
+ # -----------------------------
36
+ def np_step(Psi, E, L, scale=1.0):
37
+ # Numerically tame, branchless-ish ops; stable for large N.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  phase = 0.997 * Psi + 0.003 * E
39
  drive = np.tanh(phase * scale)
40
  Psi_n = 0.999 * Psi + 0.001 * drive
 
42
  L_n = 0.998 * L + 0.001 * (Psi_n * E_n)
43
  return Psi_n, E_n, L_n
44
 
45
+ # -----------------------------
46
+ # Baseline: tiny Python loop (safety-capped)
47
+ # -----------------------------
48
+ def pyloop_step(Psi, E, L, scale=1.0):
49
+ # Scalar operations; intentionally slow baseline.
50
+ phase = 0.997 * Psi + 0.003 * E
51
+ drive = math.tanh(phase * scale)
52
+ Psi_n = 0.999 * Psi + 0.001 * drive
53
+ E_n = 0.995 * E + 0.004 * Psi_n
54
+ L_n = 0.998 * L + 0.001 * (Psi_n * E_n)
55
+ return Psi_n, E_n, L_n
56
 
57
+ def run_python_loop_baseline(n, steps, seed=7, cap_seconds=1.2):
58
+ """
59
+ Runs a scalar baseline on a small subset for a short capped duration.
60
+ Reports throughput in *equivalent* items/sec for that baseline subset only.
61
+ This is a "floor" baseline, not a competitor.
62
+ """
63
+ rng = np.random.default_rng(seed)
64
+ # Keep tiny so we don't lock the Space.
65
+ n0 = min(n, 150_000) # safety subset
66
+ Psi = rng.random(n0, dtype=np.float32)
67
+ E = rng.random(n0, dtype=np.float32)
68
+ L = rng.random(n0, dtype=np.float32)
69
+
70
+ # Run until either steps done or time cap hit
71
+ t0 = time.time()
72
+ done = 0
73
+ for _ in range(int(steps)):
74
+ # time cap guard
75
+ if (time.time() - t0) > cap_seconds:
76
+ break
77
+ # scalar loop over subset
78
+ for i in range(n0):
79
+ Psi[i], E[i], L[i] = pyloop_step(float(Psi[i]), float(E[i]), float(L[i]))
80
+ done += 1
81
+
82
+ elapsed = max(1e-9, time.time() - t0)
83
+ items = done * n0
84
+ thr_Bps = (items / elapsed) / 1e9
85
+ return thr_Bps, elapsed, n0, done
86
+
87
+ # -----------------------------
88
+ # Optional: Numba kernel
89
+ # -----------------------------
90
+ if NUMBA_OK:
91
+ @nb.njit(fastmath=True, parallel=True)
92
+ def nb_run(Psi, E, L, steps):
93
+ for _ in range(steps):
94
+ # same math as numpy step, inside jit loop
95
+ phase = 0.997 * Psi + 0.003 * E
96
+ drive = np.tanh(phase)
97
+ Psi = 0.999 * Psi + 0.001 * drive
98
+ E = 0.995 * E + 0.004 * Psi
99
+ L = 0.998 * L + 0.001 * (Psi * E)
100
+ return Psi, E, L
101
+
102
+ def compute_coherence(Psi_before, Psi_after):
103
+ # Normalised dot product: magnitude is the point; can be signed.
104
+ # We report |C| for "stability" to avoid phase sign confusion.
105
+ v1 = Psi_before.astype(np.float64, copy=False)
106
+ v2 = Psi_after.astype(np.float64, copy=False)
107
+ num = float(np.dot(v1, v2)) + 1e-12
108
+ den = float(np.linalg.norm(v1) * np.linalg.norm(v2)) + 1e-12
109
+ return num / den
110
+
111
+ def compute_energy(E):
112
+ # Energy proxy: bounded mean in [0,1.5]
113
  return float(np.mean(np.clip(E, 0.0, 1.5)))
114
 
115
+ def human_bps(x_bps):
116
+ # x_bps is in billions/sec (B/s)
117
+ if x_bps >= 1.0:
118
+ return f"{x_bps:.3f} B/s"
119
+ return f"{x_bps:.3f} B/s"
120
+
121
+ def get_cpu_string():
122
+ # best-effort
123
+ try:
124
+ return platform.processor() or platform.uname().processor or ""
125
+ except Exception:
126
+ return ""
127
+
128
+ def sha256_bytes(b: bytes) -> str:
129
+ return hashlib.sha256(b).hexdigest()
130
+
131
+ def make_receipt(payload: dict):
132
+ os.makedirs(RESULTS_DIR, exist_ok=True)
133
+ ts = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H-%M-%SZ")
134
+ fname = f"receipt_{ts}.json"
135
+ path = os.path.join(RESULTS_DIR, fname)
136
+
137
+ # Canonical JSON for stable hashing
138
+ canon = json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
139
+ h = sha256_bytes(canon)
140
+
141
+ payload_out = dict(payload)
142
+ payload_out["receipt_sha256"] = h
143
+ with open(path, "w", encoding="utf-8") as f:
144
+ json.dump(payload_out, f, indent=2)
145
+
146
+ return path, h, payload_out
147
+
148
+ def run_engine(n_oscillators: int, steps: int, include_baselines: bool):
149
+ # Hard safety rails for HF Spaces stability (still "full throttle" within reason)
150
+ n = int(max(50_000, min(int(n_oscillators), 25_000_000)))
151
+ steps = int(max(10, min(int(steps), 2_000)))
152
+
153
+ rng = np.random.default_rng(7)
154
  Psi = rng.random(n, dtype=np.float32)
155
  E = rng.random(n, dtype=np.float32)
156
  L = rng.random(n, dtype=np.float32)
157
 
158
+ # Snapshot for coherence metric (small sample)
159
+ sample = min(n, 250_000)
160
  Psi0 = Psi[:sample].copy()
161
 
162
+ # Choose engine: prefer numba if available, else numpy
163
+ engine = "numpy"
164
+ t0 = time.time()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
  if NUMBA_OK:
167
+ engine = "numba"
168
+ # warm-up compile on a tiny slice if first run
169
+ # (keeps first-run penalty from ruining the metric)
170
+ try:
171
+ _Psi_w = Psi[:50_000].copy()
172
+ _E_w = E[:50_000].copy()
173
+ _L_w = L[:50_000].copy()
174
+ nb_run(_Psi_w, _E_w, _L_w, 2)
175
+ except Exception:
176
+ engine = "numpy"
177
+
178
+ if engine == "numba":
179
+ Psi, E, L = nb_run(Psi, E, L, steps)
180
  else:
181
+ for _ in range(steps):
182
+ Psi, E, L = np_step(Psi, E, L)
183
+
184
+ elapsed = max(1e-9, time.time() - t0)
185
+
186
+ # Metrics
187
+ items = n * steps
188
+ thr_Bps = (items / elapsed) / 1e9
189
+
190
+ coh = compute_coherence(Psi0, Psi[:sample])
191
+ coh_abs = abs(coh)
192
+ meanE = compute_energy(E[:sample])
193
+
194
+ # Optional baselines (measured live)
195
+ base_numpy = None
196
+ base_py = None
197
+ speedup_vs_py = None
198
+ speedup_vs_numpy = None
199
 
 
 
200
  if include_baselines:
201
+ # Baseline A: NumPy (forced) on same n/steps
202
+ t1 = time.time()
203
+ PsiA = rng.random(n, dtype=np.float32)
204
+ EA = rng.random(n, dtype=np.float32)
205
+ LA = rng.random(n, dtype=np.float32)
206
+ for _ in range(steps):
207
+ PsiA, EA, LA = np_step(PsiA, EA, LA)
208
+ elA = max(1e-9, time.time() - t1)
209
+ base_numpy = (n * steps / elA) / 1e9
210
+
211
+ # Baseline B: Python loop (subset, capped)
212
+ base_py, py_elapsed, py_n, py_steps_done = run_python_loop_baseline(n=n, steps=steps, seed=7)
213
 
214
+ # Speedups (honest: can be < 1.0)
215
+ if base_py and base_py > 0:
216
+ speedup_vs_py = thr_Bps / base_py
217
+ if base_numpy and base_numpy > 0:
218
+ speedup_vs_numpy = thr_Bps / base_numpy
219
+
220
+ # Receipt payload
221
  payload = {
222
+ "app": APP_TITLE,
223
+ "timestamp_utc": datetime.now(timezone.utc).isoformat(),
224
+ "definition_of_item": "One coherent update of [Psi,E,L] per oscillator per step",
225
+ "n_oscillators": n,
226
+ "steps": steps,
227
+ "engine": engine,
228
+ "elapsed_seconds": elapsed,
229
+ "throughput_Bps": thr_Bps,
230
+ "coherence_C": coh,
231
+ "coherence_abs": coh_abs,
232
+ "mean_energy_proxy": meanE,
233
+ "cpu": get_cpu_string(),
234
+ "cores_available": os.cpu_count() or 1,
235
+ "baselines_enabled": bool(include_baselines),
236
+ "baseline_numpy_Bps": base_numpy,
237
+ "baseline_python_loop_Bps": base_py,
238
+ "speedup_vs_python_loop_x": speedup_vs_py,
239
+ "speedup_vs_numpy_x": speedup_vs_numpy,
240
+ "notes": [
241
+ "All values measured live on the Space runtime machine.",
242
+ "Baselines are measured on the same machine with the same workload settings.",
243
+ "Python loop baseline is safety-capped and uses a subset to keep the Space responsive.",
244
+ ],
245
  }
246
 
247
+ receipt_path, receipt_sha, payload_out = make_receipt(payload)
248
+
249
+ # UI-friendly output (minimal, factual)
250
+ result = {
251
+ "Throughput (B/s)": f"{thr_Bps:.3f}",
252
+ "Coherence (|C|)": f"{coh_abs:.5f}",
253
+ "Mean Energy": f"{meanE:.5f}",
254
+ "Elapsed Time (s)": f"{elapsed:.2f}",
255
+ "Oscillators": f"{n:,}",
256
+ "Steps": f"{steps}",
257
+ "Engine": engine,
258
+ "CPU Cores Available": int(os.cpu_count() or 1),
 
 
 
 
 
 
 
259
  }
 
260
 
261
+ if include_baselines:
262
+ result["Baseline (Vectorised NumPy) (B/s)"] = f"{base_numpy:.3f}" if base_numpy is not None else "n/a"
263
+ result["Baseline (Python loop, capped) (B/s)"] = f"{base_py:.3f}" if base_py is not None else "n/a"
264
+ if speedup_vs_py is not None:
265
+ result["Speedup vs Python loop (x)"] = f"{speedup_vs_py:.1f}"
266
+ if speedup_vs_numpy is not None:
267
+ result["Speedup vs NumPy (x)"] = f"{speedup_vs_numpy:.2f}"
268
+ # add one explicit honesty line
269
+ result["Note"] = "Speedups can be <1.0 depending on runtime/Numba warmup/CPU features. That is expected and is reported as-is."
270
+
271
+ result["Receipt SHA-256 (in file)"] = "written in receipt"
272
+
273
+ return json.dumps(result, indent=2), receipt_path
274
 
 
275
 
276
+ # -----------------------------
277
  # UI
278
+ # -----------------------------
279
+ INTRO_MD = """
280
+ ### What this is
281
+ - **No precomputed results**
282
+ - **No GPUs required**
283
+ - Measures **real throughput**, **stability**, and **energy behaviour** on the machine running this Space.
 
284
 
285
+ ### What an “item” is
286
+ - One coherent state update of **[Ψ, E, L]** per oscillator per step.
 
 
287
 
288
+ Everything you see below is computed **right now**, on this machine.
289
+ """
290
 
291
+ NOTES_MD = """
292
+ **Notes**
293
+ - This runs on the Hugging Face Space runtime machine. Your browser just displays the UI.
294
+ - If the Space is under load, throughput will vary — that variance is real and is part of the measurement.
295
+ - Baselines are not “competitions”. They are **verification anchors** measured live on the same machine.
296
+ """
297
 
298
+ with gr.Blocks(theme=gr.themes.Soft(), title=APP_TITLE) as demo:
299
+ gr.Markdown(f"# {APP_TITLE}")
300
+ gr.Markdown(INTRO_MD)
301
+
302
+ with gr.Row():
303
+ n_slider = gr.Slider(
304
+ minimum=250_000,
305
+ maximum=25_000_000,
306
+ value=6_400_000,
307
+ step=50_000,
308
+ label="Number of Oscillators",
309
+ )
310
+ steps_slider = gr.Slider(
311
+ minimum=50,
312
+ maximum=2000,
313
+ value=650,
314
+ step=10,
315
+ label="Simulation Steps",
316
+ )
317
+
318
+ include_baselines = gr.Checkbox(
319
+ value=True,
320
+ label="Show verification baselines (same machine)",
321
+ info="Baselines are measured live too. Python loop is safety-capped."
322
  )
323
 
324
+ run_btn = gr.Button("Run Engine", variant="primary")
325
+
326
  with gr.Row():
327
+ out_json = gr.Code(label="Results", language="json")
328
+ receipt_file = gr.File(label="Receipt (download)", file_count="single")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
329
 
330
+ gr.Markdown(NOTES_MD)
 
 
 
 
331
 
332
+ run_btn.click(
333
+ fn=run_engine,
334
+ inputs=[n_slider, steps_slider, include_baselines],
335
+ outputs=[out_json, receipt_file],
 
 
336
  )
337
 
338
  if __name__ == "__main__":
339
+ demo.queue(concurrency_count=1).launch()