RFTSystems commited on
Commit
d01a4f3
·
verified ·
1 Parent(s): d089458

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -52
app.py CHANGED
@@ -1,6 +1,6 @@
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
@@ -34,7 +34,6 @@ RESULTS_DIR = "receipts"
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
@@ -46,7 +45,6 @@ def np_step(Psi, E, L, scale=1.0):
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
@@ -56,25 +54,20 @@ def pyloop_step(Psi, E, L, scale=1.0):
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
@@ -91,7 +84,6 @@ 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
@@ -100,8 +92,6 @@ if NUMBA_OK:
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
@@ -109,17 +99,9 @@ def compute_coherence(Psi_before, Psi_after):
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:
@@ -134,19 +116,19 @@ def make_receipt(payload: dict):
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
 
@@ -155,18 +137,14 @@ def run_engine(n_oscillators: int, steps: int, include_baselines: bool):
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()
@@ -183,7 +161,6 @@ def run_engine(n_oscillators: int, steps: int, include_baselines: bool):
183
 
184
  elapsed = max(1e-9, time.time() - t0)
185
 
186
- # Metrics
187
  items = n * steps
188
  thr_Bps = (items / elapsed) / 1e9
189
 
@@ -191,14 +168,13 @@ def run_engine(n_oscillators: int, steps: int, include_baselines: bool):
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)
@@ -208,16 +184,14 @@ def run_engine(n_oscillators: int, steps: int, include_baselines: bool):
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(),
@@ -246,7 +220,6 @@ def run_engine(n_oscillators: int, steps: int, include_baselines: bool):
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}",
@@ -259,23 +232,19 @@ def run_engine(n_oscillators: int, steps: int, include_baselines: bool):
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**
@@ -292,10 +261,11 @@ 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
 
@@ -317,14 +287,13 @@ with gr.Blocks(theme=gr.themes.Soft(), title=APP_TITLE) as demo:
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)
@@ -336,4 +305,5 @@ with gr.Blocks(theme=gr.themes.Soft(), title=APP_TITLE) as demo:
336
  )
337
 
338
  if __name__ == "__main__":
339
- demo.queue(concurrency_count=1).launch()
 
 
1
+ # app.py — Coherent_Compute_Engine (RFTSystems) — Gradio 6.x compatible
2
+ # Live measured throughput + stability + energy proxy, with verification baselines + receipt download.
3
+ # No estimates. No precomputed data.
4
 
5
  import os
6
  import time
 
34
  # Core update: vectorised (NumPy)
35
  # -----------------------------
36
  def np_step(Psi, E, L, scale=1.0):
 
37
  phase = 0.997 * Psi + 0.003 * E
38
  drive = np.tanh(phase * scale)
39
  Psi_n = 0.999 * Psi + 0.001 * drive
 
45
  # Baseline: tiny Python loop (safety-capped)
46
  # -----------------------------
47
  def pyloop_step(Psi, E, L, scale=1.0):
 
48
  phase = 0.997 * Psi + 0.003 * E
49
  drive = math.tanh(phase * scale)
50
  Psi_n = 0.999 * Psi + 0.001 * drive
 
54
 
55
  def run_python_loop_baseline(n, steps, seed=7, cap_seconds=1.2):
56
  """
57
+ Scalar baseline on a small subset for a short capped duration.
58
+ Reports throughput in items/sec for that subset.
 
59
  """
60
  rng = np.random.default_rng(seed)
61
+ n0 = min(int(n), 150_000) # safety subset
 
62
  Psi = rng.random(n0, dtype=np.float32)
63
  E = rng.random(n0, dtype=np.float32)
64
  L = rng.random(n0, dtype=np.float32)
65
 
 
66
  t0 = time.time()
67
  done = 0
68
  for _ in range(int(steps)):
 
69
  if (time.time() - t0) > cap_seconds:
70
  break
 
71
  for i in range(n0):
72
  Psi[i], E[i], L[i] = pyloop_step(float(Psi[i]), float(E[i]), float(L[i]))
73
  done += 1
 
84
  @nb.njit(fastmath=True, parallel=True)
85
  def nb_run(Psi, E, L, steps):
86
  for _ in range(steps):
 
87
  phase = 0.997 * Psi + 0.003 * E
88
  drive = np.tanh(phase)
89
  Psi = 0.999 * Psi + 0.001 * drive
 
92
  return Psi, E, L
93
 
94
  def compute_coherence(Psi_before, Psi_after):
 
 
95
  v1 = Psi_before.astype(np.float64, copy=False)
96
  v2 = Psi_after.astype(np.float64, copy=False)
97
  num = float(np.dot(v1, v2)) + 1e-12
 
99
  return num / den
100
 
101
  def compute_energy(E):
 
102
  return float(np.mean(np.clip(E, 0.0, 1.5)))
103
 
 
 
 
 
 
 
104
  def get_cpu_string():
 
105
  try:
106
  return platform.processor() or platform.uname().processor or ""
107
  except Exception:
 
116
  fname = f"receipt_{ts}.json"
117
  path = os.path.join(RESULTS_DIR, fname)
118
 
 
119
  canon = json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
120
  h = sha256_bytes(canon)
121
 
122
  payload_out = dict(payload)
123
  payload_out["receipt_sha256"] = h
124
+
125
  with open(path, "w", encoding="utf-8") as f:
126
  json.dump(payload_out, f, indent=2)
127
 
128
  return path, h, payload_out
129
 
130
  def run_engine(n_oscillators: int, steps: int, include_baselines: bool):
131
+ # Safety rails for HF Spaces stability
132
  n = int(max(50_000, min(int(n_oscillators), 25_000_000)))
133
  steps = int(max(10, min(int(steps), 2_000)))
134
 
 
137
  E = rng.random(n, dtype=np.float32)
138
  L = rng.random(n, dtype=np.float32)
139
 
 
140
  sample = min(n, 250_000)
141
  Psi0 = Psi[:sample].copy()
142
 
 
143
  engine = "numpy"
144
  t0 = time.time()
145
 
146
  if NUMBA_OK:
147
  engine = "numba"
 
 
148
  try:
149
  _Psi_w = Psi[:50_000].copy()
150
  _E_w = E[:50_000].copy()
 
161
 
162
  elapsed = max(1e-9, time.time() - t0)
163
 
 
164
  items = n * steps
165
  thr_Bps = (items / elapsed) / 1e9
166
 
 
168
  coh_abs = abs(coh)
169
  meanE = compute_energy(E[:sample])
170
 
 
171
  base_numpy = None
172
  base_py = None
173
  speedup_vs_py = None
174
  speedup_vs_numpy = None
175
 
176
  if include_baselines:
177
+ # Baseline A: forced NumPy
178
  t1 = time.time()
179
  PsiA = rng.random(n, dtype=np.float32)
180
  EA = rng.random(n, dtype=np.float32)
 
184
  elA = max(1e-9, time.time() - t1)
185
  base_numpy = (n * steps / elA) / 1e9
186
 
187
+ # Baseline B: Python loop (subset + cap)
188
  base_py, py_elapsed, py_n, py_steps_done = run_python_loop_baseline(n=n, steps=steps, seed=7)
189
 
 
190
  if base_py and base_py > 0:
191
  speedup_vs_py = thr_Bps / base_py
192
  if base_numpy and base_numpy > 0:
193
  speedup_vs_numpy = thr_Bps / base_numpy
194
 
 
195
  payload = {
196
  "app": APP_TITLE,
197
  "timestamp_utc": datetime.now(timezone.utc).isoformat(),
 
220
 
221
  receipt_path, receipt_sha, payload_out = make_receipt(payload)
222
 
 
223
  result = {
224
  "Throughput (B/s)": f"{thr_Bps:.3f}",
225
  "Coherence (|C|)": f"{coh_abs:.5f}",
 
232
  }
233
 
234
  if include_baselines:
235
+ result["Baseline: numpy (B/s)"] = f"{base_numpy:.3f}" if base_numpy is not None else "n/a"
236
+ result["Baseline: python_loop (B/s)"] = f"{base_py:.3f}" if base_py is not None else "n/a"
237
  if speedup_vs_py is not None:
238
+ result["Speedup vs python_loop (x)"] = f"{speedup_vs_py:.1f}"
239
  if speedup_vs_numpy is not None:
240
+ result["Speedup vs numpy (x)"] = f"{speedup_vs_numpy:.2f}"
241
+ result["Note"] = "Speedups can be <1.0 depending on runtime/Numba warmup/CPU features. Reported as-is."
 
242
 
243
  result["Receipt SHA-256 (in file)"] = "written in receipt"
244
 
245
  return json.dumps(result, indent=2), receipt_path
246
 
247
 
 
 
 
248
  INTRO_MD = """
249
  ### What this is
250
  - **No precomputed results**
 
261
  **Notes**
262
  - This runs on the Hugging Face Space runtime machine. Your browser just displays the UI.
263
  - If the Space is under load, throughput will vary — that variance is real and is part of the measurement.
264
+ - Baselines are verification anchors measured live on the same machine.
265
  """
266
 
267
+ # Gradio 6.x: do NOT pass theme into Blocks(); pass theme into launch()
268
+ with gr.Blocks(title=APP_TITLE) as demo:
269
  gr.Markdown(f"# {APP_TITLE}")
270
  gr.Markdown(INTRO_MD)
271
 
 
287
 
288
  include_baselines = gr.Checkbox(
289
  value=True,
290
+ label="Include baselines (NumPy + tiny Python loop)",
291
  info="Baselines are measured live too. Python loop is safety-capped."
292
  )
293
 
294
  run_btn = gr.Button("Run Engine", variant="primary")
295
 
296
+ out_json = gr.Code(label="Results", language="json")
 
297
  receipt_file = gr.File(label="Receipt (download)", file_count="single")
298
 
299
  gr.Markdown(NOTES_MD)
 
305
  )
306
 
307
  if __name__ == "__main__":
308
+ # Gradio 6.x: queue() signature changed; keep it simple and stable.
309
+ demo.queue().launch(theme=gr.themes.Soft())