Spaces:
Sleeping
Sleeping
| # app.py | |
| # Coherent_Compute_Engine — RFTSystems | |
| # Real, on-machine benchmark + tamper-evident receipt download (SHA-256). | |
| # Notes: | |
| # - Runs on the Space runtime hardware (not the visitor's local machine). | |
| # - “Item” = one per-oscillator state update of [Psi, E, L] per step. | |
| import os | |
| import json | |
| import time | |
| import math | |
| import hashlib | |
| import platform | |
| import datetime as dt | |
| from pathlib import Path | |
| import numpy as np | |
| import gradio as gr | |
| # Optional: Numba baseline (will be used if available) | |
| try: | |
| import numba as nb | |
| NUMBA_OK = True | |
| except Exception: | |
| nb = None | |
| NUMBA_OK = False | |
| APP_VERSION = "Coherent_Compute_Engine_v1.0.0" | |
| RESULTS_DIR = Path("results") | |
| RESULTS_DIR.mkdir(exist_ok=True) | |
| # ---------------------------- | |
| # Canonical JSON + integrity | |
| # ---------------------------- | |
| def canon_json_bytes(obj) -> bytes: | |
| return json.dumps( | |
| obj, | |
| ensure_ascii=False, | |
| sort_keys=True, | |
| separators=(",", ":"), | |
| ).encode("utf-8") | |
| def sha256_hex(b: bytes) -> str: | |
| return hashlib.sha256(b).hexdigest() | |
| def write_receipt(payload: dict) -> str: | |
| """ | |
| Writes a JSON receipt to disk and returns the filepath for Gradio download. | |
| Receipt contains its own SHA-256 hash (tamper-evident). | |
| """ | |
| # hash without integrity first | |
| b0 = canon_json_bytes(payload) | |
| h = sha256_hex(b0) | |
| payload["integrity"] = { | |
| "sha256": h, | |
| "receipt_id": h[:12], | |
| "canonical_json": "sorted_keys + compact_separators", | |
| } | |
| b1 = canon_json_bytes(payload) | |
| ts = payload.get("timestamp_utc", dt.datetime.utcnow().isoformat() + "Z") | |
| safe_ts = ts.replace(":", "").replace(".", "").replace("Z", "") | |
| fname = f"receipt_{safe_ts}_{h[:12]}.json" | |
| path = RESULTS_DIR / fname | |
| path.write_bytes(b1) | |
| return str(path) | |
| # ---------------------------- | |
| # Core RFT-lite engine | |
| # ---------------------------- | |
| def _np_step(Psi, E, L, scale=1.0): | |
| # numerically tame, branchless-ish | |
| phase = 0.997 * Psi + 0.003 * E | |
| drive = np.tanh(phase * scale) | |
| Psi_n = 0.999 * Psi + 0.001 * drive | |
| E_n = 0.995 * E + 0.004 * Psi_n | |
| L_n = 0.998 * L + 0.001 * (Psi_n * E_n) | |
| return Psi_n, E_n, L_n | |
| def coherence_abs(Psi0: np.ndarray, Psi1: np.ndarray) -> float: | |
| # Normalized dot product (magnitude used) | |
| # (If values are constant, den can go tiny — guard it.) | |
| v0 = Psi0.astype(np.float64, copy=False) | |
| v1 = Psi1.astype(np.float64, copy=False) | |
| num = float(np.dot(v0, v1)) | |
| den = float(np.linalg.norm(v0) * np.linalg.norm(v1)) + 1e-12 | |
| return abs(num / den) | |
| def mean_energy(E: np.ndarray) -> float: | |
| # bounded to keep metric stable across runs | |
| return float(np.mean(np.clip(E, 0.0, 1.5))) | |
| def run_engine_numpy(n: int, steps: int, seed: int, scale: float): | |
| rng = np.random.default_rng(seed) | |
| Psi = rng.random(n, dtype=np.float32) | |
| E = rng.random(n, dtype=np.float32) | |
| L = rng.random(n, dtype=np.float32) | |
| # capture Psi for coherence (small sample for speed) | |
| sample = min(n, 200_000) | |
| Psi0 = Psi[:sample].copy() | |
| t0 = time.perf_counter() | |
| for _ in range(steps): | |
| Psi, E, L = _np_step(Psi, E, L, scale=scale) | |
| t1 = time.perf_counter() | |
| Psi1 = Psi[:sample].copy() | |
| elapsed = t1 - t0 | |
| # “items” = per-oscillator update of [Psi,E,L] per step | |
| items = int(n) * int(steps) | |
| throughput_Bps = (items / elapsed) / 1e9 | |
| coh = coherence_abs(Psi0, Psi1) | |
| eng = mean_energy(E[:sample]) | |
| return { | |
| "engine": "numpy", | |
| "oscillators": int(n), | |
| "steps": int(steps), | |
| "elapsed_s": float(elapsed), | |
| "throughput_Bps": float(throughput_Bps), | |
| "coherence_abs": float(coh), | |
| "mean_energy": float(eng), | |
| } | |
| # ---------------------------- | |
| # Baselines (optional) | |
| # ---------------------------- | |
| def run_baseline_python(n: int, steps: int, seed: int): | |
| # Deliberately small n to avoid melting the Space. | |
| n = min(n, 200_000) | |
| rng = np.random.default_rng(seed) | |
| Psi = rng.random(n).tolist() | |
| E = rng.random(n).tolist() | |
| L = rng.random(n).tolist() | |
| def step(Psi, E, L): | |
| outPsi = [0.0]*n | |
| outE = [0.0]*n | |
| outL = [0.0]*n | |
| for i in range(n): | |
| phase = 0.997*Psi[i] + 0.003*E[i] | |
| drive = math.tanh(phase) | |
| p = 0.999*Psi[i] + 0.001*drive | |
| e = 0.995*E[i] + 0.004*p | |
| l = 0.998*L[i] + 0.001*(p*e) | |
| outPsi[i], outE[i], outL[i] = p, e, l | |
| return outPsi, outE, outL | |
| t0 = time.perf_counter() | |
| for _ in range(min(steps, 10)): # hard cap for safety | |
| Psi, E, L = step(Psi, E, L) | |
| t1 = time.perf_counter() | |
| elapsed = t1 - t0 | |
| items = int(n) * int(min(steps, 10)) | |
| throughput_Bps = (items / elapsed) / 1e9 | |
| # Coherence proxy (cheap) | |
| Psi0 = np.array(Psi[:min(n, 50_000)], dtype=np.float32) | |
| Psi1 = Psi0 # can't compare pre/post cheaply here without extra memory | |
| coh = 1.0 | |
| eng = float(np.mean(np.clip(np.array(E[:min(n, 50_000)], dtype=np.float32), 0.0, 1.5))) | |
| return { | |
| "engine": "python_loop", | |
| "oscillators": int(n), | |
| "steps": int(min(steps, 10)), | |
| "elapsed_s": float(elapsed), | |
| "throughput_Bps": float(throughput_Bps), | |
| "coherence_abs": float(coh), | |
| "mean_energy": float(eng), | |
| "note": "Python loop is capped (n<=200k, steps<=10) to keep the Space stable.", | |
| } | |
| if NUMBA_OK: | |
| def _numba_kernel(Psi, E, L, scale): | |
| n = Psi.shape[0] | |
| for i in range(n): | |
| phase = 0.997 * Psi[i] + 0.003 * E[i] | |
| drive = math.tanh(phase * scale) | |
| p = 0.999 * Psi[i] + 0.001 * drive | |
| e = 0.995 * E[i] + 0.004 * p | |
| l = 0.998 * L[i] + 0.001 * (p * e) | |
| Psi[i] = p | |
| E[i] = e | |
| L[i] = l | |
| def run_engine_numba(n: int, steps: int, seed: int, scale: float): | |
| rng = np.random.default_rng(seed) | |
| Psi = rng.random(n, dtype=np.float32) | |
| E = rng.random(n, dtype=np.float32) | |
| L = rng.random(n, dtype=np.float32) | |
| sample = min(n, 200_000) | |
| Psi0 = Psi[:sample].copy() | |
| # warmup compile | |
| _numba_kernel(Psi[:min(n, 1024)], E[:min(n, 1024)], L[:min(n, 1024)], scale) | |
| t0 = time.perf_counter() | |
| for _ in range(steps): | |
| _numba_kernel(Psi, E, L, scale) | |
| t1 = time.perf_counter() | |
| Psi1 = Psi[:sample].copy() | |
| elapsed = t1 - t0 | |
| items = int(n) * int(steps) | |
| throughput_Bps = (items / elapsed) / 1e9 | |
| coh = coherence_abs(Psi0, Psi1) | |
| eng = mean_energy(E[:sample]) | |
| return { | |
| "engine": "numba", | |
| "oscillators": int(n), | |
| "steps": int(steps), | |
| "elapsed_s": float(elapsed), | |
| "throughput_Bps": float(throughput_Bps), | |
| "coherence_abs": float(coh), | |
| "mean_energy": float(eng), | |
| } | |
| # ---------------------------- | |
| # Run + Receipt wrapper | |
| # ---------------------------- | |
| def run_and_receipt(n_oscillators, steps, seed, scale, include_baseline): | |
| n = int(n_oscillators) | |
| s = int(steps) | |
| seed = int(seed) | |
| scale = float(scale) | |
| # Safety rails for a public Space | |
| # (Users can still push, but this avoids accidental hard-crashes.) | |
| n = max(100_000, min(n, 40_000_000)) | |
| s = max(10, min(s, 5000)) | |
| # Decide engine: if numba is available, prefer it; else numpy | |
| if NUMBA_OK: | |
| primary = run_engine_numba(n, s, seed, scale) | |
| else: | |
| primary = run_engine_numpy(n, s, seed, scale) | |
| baselines = {} | |
| if include_baseline: | |
| baselines["numpy"] = run_engine_numpy(min(n, 8_000_000), min(s, 2000), seed, scale) | |
| baselines["python_loop"] = run_baseline_python(min(n, 500_000), min(s, 200), seed) | |
| # System metadata (honest) | |
| meta = { | |
| "timestamp_utc": dt.datetime.utcnow().isoformat() + "Z", | |
| "app_version": APP_VERSION, | |
| "space_runtime_note": "All measurements are performed on the Hugging Face Space runtime machine.", | |
| "platform": platform.platform(), | |
| "python": platform.python_version(), | |
| "cpu_count_logical": os.cpu_count(), | |
| "numba_available": bool(NUMBA_OK), | |
| "inputs": { | |
| "oscillators": int(n), | |
| "steps": int(s), | |
| "seed": seed, | |
| "scale": scale, | |
| "include_baselines": bool(include_baseline), | |
| }, | |
| "definition": { | |
| "item": "1 item = one per-oscillator coherent state update of [Psi, E, L] per step (as implemented in this Space)." | |
| }, | |
| "results": { | |
| "primary": primary, | |
| "baselines": baselines, | |
| }, | |
| } | |
| receipt_path = write_receipt(meta) | |
| # UI results (clean, human readable) | |
| ui = { | |
| "Throughput (B/s)": f'{primary["throughput_Bps"]:.3f} B/s', | |
| "Coherence (|C|)": f'{primary["coherence_abs"]:.5f}', | |
| "Mean Energy": f'{primary["mean_energy"]:.5f}', | |
| "Elapsed Time (s)": f'{primary["elapsed_s"]:.2f}', | |
| "Oscillators": f'{primary["oscillators"]:,}', | |
| "Steps": f'{primary["steps"]:,}', | |
| "Engine": primary["engine"], | |
| "CPU Cores Available": os.cpu_count(), | |
| "Baselines Included": bool(include_baseline), | |
| } | |
| if include_baseline: | |
| # add short baseline summary (no hype; facts only) | |
| for k, v in baselines.items(): | |
| ui[f"Baseline: {k} (B/s)"] = f'{v["throughput_Bps"]:.3f}' | |
| ui[f"Baseline: {k} Engine"] = v["engine"] | |
| return ui, receipt_path | |
| # ---------------------------- | |
| # UI (clean, simple, visual) | |
| # ---------------------------- | |
| CSS = """ | |
| :root { | |
| --rft-accent: #ff7a18; | |
| } | |
| .gradio-container { | |
| max-width: 980px !important; | |
| } | |
| #titlebar h1 { | |
| font-size: 2.05rem; | |
| letter-spacing: -0.02em; | |
| } | |
| .rft-card { | |
| border-radius: 16px !important; | |
| border: 1px solid rgba(255,255,255,0.08) !important; | |
| } | |
| """ | |
| with gr.Blocks(css=CSS, theme=gr.themes.Soft()) as demo: | |
| gr.Markdown( | |
| """ | |
| <div id="titlebar"> | |
| <h1>Coherent Compute Engine</h1> | |
| </div> | |
| **What this Space does** | |
| It runs a real, on-machine benchmark of a coherent state-update engine and reports **measured throughput**, **stability**, and **energy behavior**. No precomputed results. | |
| **What an “item” is** | |
| One coherent update of **[Ψ, E, L]** per oscillator per step. | |
| **Verification** | |
| Every run generates a tamper-evident **receipt (JSON)** with a SHA-256 hash you can download. | |
| """ | |
| ) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| with gr.Group(elem_classes=["rft-card"]): | |
| n_slider = gr.Slider( | |
| minimum=100_000, maximum=40_000_000, step=100_000, | |
| value=6_400_000, label="Number of Oscillators" | |
| ) | |
| steps_slider = gr.Slider( | |
| minimum=10, maximum=5000, step=10, | |
| value=650, label="Simulation Steps" | |
| ) | |
| seed_box = gr.Number(value=7, precision=0, label="Seed") | |
| scale_box = gr.Number(value=1.0, precision=3, label="Scale (stability knob)") | |
| include_baseline = gr.Checkbox( | |
| value=False, | |
| label="Include baselines (numpy + tiny python loop)", | |
| info="Baselines are measured live too. Python loop is safety-capped." | |
| ) | |
| run_btn = gr.Button("Run Engine", variant="primary") | |
| with gr.Column(scale=1): | |
| results_json = gr.JSON(label="Results") | |
| receipt_file = gr.File(label="Receipt (JSON download)") | |
| run_btn.click( | |
| fn=run_and_receipt, | |
| inputs=[n_slider, steps_slider, seed_box, scale_box, include_baseline], | |
| outputs=[results_json, receipt_file], | |
| ) | |
| gr.Markdown( | |
| """ | |
| **Notes** | |
| - This runs on the Hugging Face Space runtime machine. If you want numbers from your own hardware, run the same code locally. | |
| - If the Space is under load, throughput will vary. That’s normal; the receipt captures the environment at run time. | |
| """ | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() |