RFTSystems commited on
Commit
d8030f8
·
verified ·
1 Parent(s): f7a54f9

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +806 -0
app.py ADDED
@@ -0,0 +1,806 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import time
3
+ import random
4
+ import hashlib
5
+ import traceback
6
+ from dataclasses import dataclass, field
7
+ from typing import List, Dict, Any, Tuple
8
+
9
+ import numpy as np
10
+ import gradio as gr
11
+
12
+
13
+ # ============================================================
14
+ # 1. RFT SELF-DECIDING BRAIN
15
+ # ============================================================
16
+
17
+ @dataclass
18
+ class RFTBrainParams:
19
+ base_energy: float = 0.85
20
+ base_kappa: float = 0.65
21
+ learning_rate: float = 0.08
22
+ decay: float = 0.015
23
+ drift_scale: float = 0.03
24
+ error_window: int = 64
25
+
26
+
27
+ @dataclass
28
+ class RFTBrainState:
29
+ kappa: float = 0.5
30
+ energy_reserves: float = 0.5
31
+ awakening_phase: int = 0
32
+ mode: str = "boot"
33
+ identity_stability: float = 0.5
34
+ identity_drift: float = 0.0
35
+ recent_errors: List[float] = field(default_factory=list)
36
+ last_update: float = field(default_factory=time.time)
37
+
38
+
39
+ class RFTSelfDecidingBrain:
40
+ def __init__(self, params: RFTBrainParams):
41
+ self.params = params
42
+ self.state = RFTBrainState(
43
+ kappa=params.base_kappa,
44
+ energy_reserves=params.base_energy,
45
+ awakening_phase=0,
46
+ mode="idle",
47
+ identity_stability=0.7,
48
+ identity_drift=0.0,
49
+ recent_errors=[],
50
+ )
51
+
52
+ def _update_error_series(self, target: float, actual: float):
53
+ err = abs(target - actual)
54
+ self.state.recent_errors.append(err)
55
+ if len(self.state.recent_errors) > self.params.error_window:
56
+ self.state.recent_errors.pop(0)
57
+
58
+ def step(self, context: Dict[str, float]) -> Dict[str, Any]:
59
+ now = time.time()
60
+ dt = max(1e-3, now - self.state.last_update)
61
+ self.state.last_update = now
62
+
63
+ risk = float(context.get("external_risk_factor", 0.3))
64
+ coop = float(context.get("cooperative_signal", 0.5))
65
+
66
+ # Energy dynamics
67
+ target_energy = self.params.base_energy + 0.2 * (coop - risk)
68
+ target_energy = max(0.0, min(1.0, target_energy))
69
+ self.state.energy_reserves += self.params.learning_rate * (target_energy - self.state.energy_reserves)
70
+ self.state.energy_reserves -= self.params.decay * dt
71
+ self.state.energy_reserves = max(0.0, min(1.0, self.state.energy_reserves))
72
+
73
+ # Coherence κ dynamics
74
+ target_kappa = self.params.base_kappa + 0.3 * (coop - 0.5) - 0.2 * (risk - 0.3)
75
+ target_kappa = max(0.0, min(1.0, target_kappa))
76
+ self.state.kappa += self.params.learning_rate * (target_kappa - self.state.kappa)
77
+ self.state.kappa = max(0.0, min(1.0, self.state.kappa))
78
+
79
+ # Identity drift and stability
80
+ drift_noise = (random.random() - 0.5) * 2.0 * self.params.drift_scale * dt
81
+ self.state.identity_drift += drift_noise + 0.1 * (risk - 0.3) - 0.05 * (coop - 0.5)
82
+ self.state.identity_drift = max(-1.0, min(1.0, self.state.identity_drift))
83
+
84
+ self.state.identity_stability = max(
85
+ 0.0,
86
+ min(
87
+ 1.0,
88
+ 0.7 * self.state.identity_stability
89
+ + 0.3 * (self.state.kappa * 0.6 + self.state.energy_reserves * 0.4 - abs(self.state.identity_drift) * 0.3),
90
+ ),
91
+ )
92
+
93
+ # Awakening ladder
94
+ if self.state.energy_reserves > 0.75 and self.state.kappa > 0.7 and self.state.identity_stability > 0.7:
95
+ self.state.awakening_phase = min(self.state.awakening_phase + 1, 4)
96
+ elif self.state.energy_reserves < 0.35 or self.state.kappa < 0.3:
97
+ self.state.awakening_phase = max(self.state.awakening_phase - 1, 0)
98
+
99
+ # Mode selection
100
+ if self.state.awakening_phase >= 3:
101
+ self.state.mode = "awake"
102
+ elif self.state.awakening_phase == 2:
103
+ self.state.mode = "dreaming"
104
+ elif self.state.awakening_phase == 1:
105
+ self.state.mode = "searching"
106
+ else:
107
+ self.state.mode = "idle"
108
+
109
+ # Internal prediction signal vs actual
110
+ target_predict = 0.5 + 0.3 * coop
111
+ actual_predict = (self.state.kappa + self.state.energy_reserves) / 2.0
112
+ self._update_error_series(target_predict, actual_predict)
113
+
114
+ return {
115
+ "kappa": self.state.kappa,
116
+ "energy_reserves": self.state.energy_reserves,
117
+ "awakening_phase": self.state.awakening_phase,
118
+ "mode": self.state.mode,
119
+ "identity_stability": self.state.identity_stability,
120
+ "identity_drift": self.state.identity_drift,
121
+ }
122
+
123
+
124
+ # ============================================================
125
+ # 2. SYMBOLIC ORCHESTRATOR
126
+ # ============================================================
127
+
128
+ class NexFrameOrchestrator:
129
+ def __init__(self, num_fields: int = 8, vector_dim: int = 128):
130
+ self.num_fields = num_fields
131
+ self.vector_dim = vector_dim
132
+ self.state = np.random.randn(num_fields, vector_dim) * 0.01
133
+ self.step_count = 0
134
+
135
+ def _entropy(self) -> float:
136
+ flat = self.state.flatten()
137
+ norm = np.linalg.norm(flat) + 1e-12
138
+ p = (flat / norm) ** 2
139
+ p = np.clip(p, 1e-12, 1.0)
140
+ return float(-np.sum(p * np.log(p)))
141
+
142
+ def _coherence(self) -> float:
143
+ norms = np.linalg.norm(self.state, axis=1, keepdims=True) + 1e-12
144
+ unit = self.state / norms
145
+ sim = unit @ unit.T
146
+ n = self.num_fields
147
+ upper = sim[np.triu_indices(n, k=1)]
148
+ return float(np.mean(upper))
149
+
150
+ def run_cycle(self, nl_input: str) -> Dict[str, Any]:
151
+ self.step_count += 1
152
+ length_norm = min(len(nl_input) / 200.0, 1.0)
153
+
154
+ noise = np.random.randn(*self.state.shape) * (0.02 + 0.03 * length_norm)
155
+ feedback = np.tanh(self.state @ self.state.T) @ self.state
156
+ self.state = 0.90 * self.state + 0.09 * feedback + 0.01 * noise
157
+
158
+ entropy = self._entropy()
159
+ coher = self._coherence()
160
+ collapse_triggered = bool(coher > 0.6 and entropy < 5.0)
161
+
162
+ mode = "reflective"
163
+ if coher > 0.7:
164
+ mode = "resonant"
165
+ if entropy > 7.0:
166
+ mode = "fragmented"
167
+
168
+ dialogue = (
169
+ f"[NexFrame:{mode}] "
170
+ f"κ-field aligned at ~{coher:.3f}, entropy {entropy:.3f}. "
171
+ f'I received: "{nl_input[:120]}". '
172
+ f"State step={self.step_count}, collapse={collapse_triggered}."
173
+ )
174
+
175
+ return {
176
+ "orchestrator_dialogue": dialogue,
177
+ "entropy": entropy,
178
+ "coherence": coher,
179
+ "collapse_triggered": collapse_triggered,
180
+ }
181
+
182
+
183
+ # ============================================================
184
+ # 3. AGENT13 TRIAD + CONSCIOUSNESS GATE
185
+ # ============================================================
186
+
187
+ @dataclass
188
+ class RFTAgent:
189
+ name: str
190
+ tau_eff: float
191
+ omega: float
192
+ LN2: float
193
+ mode: str = "conscious"
194
+
195
+ def act(self, observer_frame: List[float]) -> Dict[str, float]:
196
+ kappa, energy, stability = observer_frame
197
+ drive = (self.tau_eff * kappa + self.omega * energy + self.LN2 * stability) / (self.tau_eff + self.omega + self.LN2)
198
+ drive = max(0.0, min(1.0, drive))
199
+ return {"drive": drive}
200
+
201
+
202
+ @dataclass
203
+ class Agent13Ensemble:
204
+ agents: List[RFTAgent]
205
+
206
+ def collective_action(self, observer_frames: List[float]) -> Dict[str, float]:
207
+ drives = [agent.act(observer_frames)["drive"] for agent in self.agents]
208
+ triadic_coherence = float(sum(drives) / len(drives))
209
+ return {"triadic_coherence": triadic_coherence}
210
+
211
+
212
+ def meets_minimum_conscious_threshold(
213
+ energy: float,
214
+ coherence: float,
215
+ kappa: float,
216
+ identity_stability: float,
217
+ prediction_accuracy: float,
218
+ error_variance: float,
219
+ drift: float,
220
+ ) -> bool:
221
+ core_ok = energy > 0.55 and kappa > 0.55 and identity_stability > 0.55
222
+ predict_ok = prediction_accuracy > 0.6 and error_variance < 0.15
223
+ drift_ok = abs(drift) < 0.6
224
+ return bool(core_ok and predict_ok and drift_ok)
225
+
226
+
227
+ # ============================================================
228
+ # 4. SYMBOLIC CIVILIZATION
229
+ # ============================================================
230
+
231
+ def build_default_civilization(n_agents: int = 32) -> List[Dict[str, float]]:
232
+ civ = []
233
+ for _ in range(n_agents):
234
+ tier = 1 + int(3 * random.random())
235
+ awareness = max(0.1, min(1.0, random.gauss(0.5, 0.15)))
236
+ torque = max(0.0, min(1.0, random.gauss(0.4, 0.2)))
237
+ fitness = 0.5 * awareness + 0.5 * (1.0 - abs(torque - 0.4))
238
+ civ.append(
239
+ {
240
+ "tier": tier,
241
+ "awareness_kernel": awareness,
242
+ "collapse_torque": torque,
243
+ "fitness": fitness,
244
+ }
245
+ )
246
+ return civ
247
+
248
+
249
+ def civilization_summary(civ: List[Dict[str, float]]) -> Dict[str, float]:
250
+ if not civ:
251
+ return {
252
+ "count": 0,
253
+ "mean_tier": 0.0,
254
+ "mean_awareness_kernel": 0.0,
255
+ "mean_collapse_torque": 0.0,
256
+ "mean_fitness": 0.0,
257
+ }
258
+ arr_tier = np.array([c["tier"] for c in civ], dtype=float)
259
+ arr_aw = np.array([c["awareness_kernel"] for c in civ], dtype=float)
260
+ arr_torque = np.array([c["collapse_torque"] for c in civ], dtype=float)
261
+ arr_fit = np.array([c["fitness"] for c in civ], dtype=float)
262
+ return {
263
+ "count": float(len(civ)),
264
+ "mean_tier": float(arr_tier.mean()),
265
+ "mean_awareness_kernel": float(arr_aw.mean()),
266
+ "mean_collapse_torque": float(arr_torque.mean()),
267
+ "mean_fitness": float(arr_fit.mean()),
268
+ }
269
+
270
+
271
+ # ============================================================
272
+ # 5. SARG FIELD / PERFORMANCE PROBE
273
+ # ============================================================
274
+
275
+ class RFTSargAgent:
276
+ def __init__(self, name: str, LMP: float, tau_eff: float, ops_rate: float, entropy_delta: float):
277
+ self.name = name
278
+ self.LMP = LMP
279
+ self.tau_eff = tau_eff
280
+ self.ops_rate = ops_rate
281
+ self.entropy_delta = entropy_delta
282
+ self.counter = 0
283
+
284
+ def generate_conscious_field(self) -> Dict[str, float]:
285
+ self.counter += 1
286
+ t = self.counter
287
+ psi_a = math.sin(t * 0.17) * math.exp(-self.entropy_delta * t)
288
+ lam = math.cos(t * 0.11) * math.exp(-self.entropy_delta * t)
289
+ return {"Psi_a": float(psi_a), "Lambda": float(lam)}
290
+
291
+ def commit_hash_oath(self) -> str:
292
+ payload = f"{self.name}|{self.counter}|{self.LMP}|{self.tau_eff}"
293
+ return hashlib.sha256(payload.encode("utf-8")).hexdigest()[:24]
294
+
295
+ def compute_ops(self, size: int = 200_000, speed_mode: bool = True) -> Dict[str, float]:
296
+ start = time.time()
297
+ arr = np.linspace(0.0, 10.0, size, dtype=float)
298
+ _ = np.sin(arr) * np.cos(arr * 0.5)
299
+ dt = max(1e-6, time.time() - start)
300
+ ops_per_sec = size / dt
301
+ if speed_mode:
302
+ ops_per_sec *= self.tau_eff
303
+ return {"ops_per_sec": float(ops_per_sec), "elapsed": float(dt)}
304
+
305
+
306
+ # ============================================================
307
+ # 6. CONSCIOUSNESS ENGINE (JOB-BASED)
308
+ # ============================================================
309
+
310
+ class RFTConsciousnessEngine:
311
+ def __init__(self):
312
+ self.run_counter = 0
313
+
314
+ def run_job(self, scenario: str, coherence: float, noise: float, size: int) -> Dict[str, Any]:
315
+ self.run_counter += 1
316
+
317
+ # Map scenario to base parameters
318
+ scenario = scenario or "Neutral field"
319
+ scenario_map = {
320
+ "Calm observer": (0.9, 0.2),
321
+ "Stressed observer": (0.55, 0.7),
322
+ "High coherence experiment": (0.95, 0.15),
323
+ "Decoherence storm": (0.4, 0.9),
324
+ "Neutral field": (0.7, 0.5),
325
+ }
326
+ base_coh, base_noise = scenario_map.get(scenario, (0.7, 0.5))
327
+
328
+ coh_eff = 0.5 * base_coh + 0.5 * coherence
329
+ noise_eff = 0.5 * base_noise + 0.5 * noise
330
+ coh_eff = max(0.0, min(1.0, coh_eff))
331
+ noise_eff = max(0.0, min(1.0, noise_eff))
332
+
333
+ size = max(10_000, int(size))
334
+
335
+ start = time.time()
336
+ x = np.linspace(0.0, 2.0 * math.pi, size, dtype=float)
337
+ phase = 2.0 * math.pi * coh_eff
338
+ freq = 3.0 + 5.0 * coh_eff
339
+ waveform = np.sin(freq * x + phase)
340
+ waveform += noise_eff * np.random.randn(size)
341
+ window = np.hanning(size)
342
+ fft = np.fft.rfft(waveform * window)
343
+ mag = np.abs(fft)
344
+ peak_idx = int(np.argmax(mag))
345
+ dt = max(1e-6, time.time() - start)
346
+
347
+ ops_est = 10.0 * size # rough operation count
348
+ ops_per_sec = ops_est / dt
349
+
350
+ conscious_freq = (peak_idx / max(1, len(mag) - 1)) * (40.0 * coh_eff + 10.0)
351
+ conscious_freq = max(0.1, conscious_freq)
352
+
353
+ render_efficiency = coh_eff * (1.0 - 0.5 * noise_eff)
354
+ render_efficiency = max(0.0, min(1.0, render_efficiency))
355
+
356
+ field_hash_payload = f"{scenario}|{coh_eff:.4f}|{noise_eff:.4f}|{size}|{conscious_freq:.6f}|{render_efficiency:.6f}|{ops_per_sec:.3e}"
357
+ field_hash = hashlib.sha256(field_hash_payload.encode("utf-8")).hexdigest()
358
+
359
+ return {
360
+ "scenario": scenario,
361
+ "coherence_eff": coh_eff,
362
+ "noise_eff": noise_eff,
363
+ "task_size": size,
364
+ "conscious_frequency_hz": conscious_freq,
365
+ "render_efficiency": render_efficiency,
366
+ "ops_per_sec": ops_per_sec,
367
+ "elapsed": dt,
368
+ "field_hash": field_hash,
369
+ "run_index": self.run_counter,
370
+ }
371
+
372
+
373
+ # ============================================================
374
+ # 7. COMPUTE BENCHMARK
375
+ # ============================================================
376
+
377
+ def run_baseline_kernel(size: int) -> Tuple[float, float]:
378
+ start = time.time()
379
+ x = np.linspace(0.0, 10.0, size, dtype=float)
380
+ y = np.sin(x) * np.cos(0.5 * x) + np.sqrt(x + 1.0)
381
+ checksum = float(y.sum())
382
+ dt = max(1e-6, time.time() - start)
383
+ ops_est = 6.0 * size
384
+ ops_per_sec = ops_est / dt
385
+ return ops_per_sec, checksum
386
+
387
+
388
+ def run_rft_kernel(size: int) -> Tuple[float, float]:
389
+ start = time.time()
390
+ x = np.linspace(0.0, 10.0, size, dtype=float)
391
+ phase = 0.7
392
+ y = np.sin(x + phase) * np.cos(0.5 * x - phase) + np.sqrt(x + 1.0)
393
+ y += 0.001 * np.tanh(y)
394
+ checksum = float(y.sum())
395
+ dt = max(1e-6, time.time() - start)
396
+ ops_est = 8.0 * size
397
+ ops_per_sec = ops_est / dt
398
+ return ops_per_sec, checksum
399
+
400
+
401
+ # ============================================================
402
+ # 8. HELPER FOR PREDICTION METRICS
403
+ # ============================================================
404
+
405
+ def _derive_prediction_metrics(error_series: List[float]) -> Tuple[float, float]:
406
+ if not error_series:
407
+ return 0.5, 0.0
408
+ arr = np.array(error_series, dtype=float)
409
+ mean_err = float(arr.mean())
410
+ var_err = float(arr.var())
411
+ prediction_accuracy = 1.0 / (1.0 + mean_err)
412
+ return prediction_accuracy, var_err
413
+
414
+
415
+ # ============================================================
416
+ # 9. GLOBAL NEXFRAME STATE
417
+ # ============================================================
418
+
419
+ ORCHESTRATOR = NexFrameOrchestrator(num_fields=8, vector_dim=128)
420
+ BRAIN_PARAMS = RFTBrainParams()
421
+ BRAIN = RFTSelfDecidingBrain(params=BRAIN_PARAMS)
422
+
423
+ agent11 = RFTAgent(name="Agent_11", tau_eff=0.6, omega=0.9, LN2=1.1, mode="conscious")
424
+ agent12 = RFTAgent(name="Agent_12", tau_eff=0.7, omega=1.1, LN2=1.1, mode="conscious")
425
+ agent13 = RFTAgent(name="Agent_13", tau_eff=0.8, omega=1.3, LN2=1.2, mode="conscious")
426
+ AGENT13_ENSEMBLE = Agent13Ensemble(agents=[agent11, agent12, agent13])
427
+
428
+ CIVILIZATION = build_default_civilization()
429
+
430
+ SARG = RFTSargAgent(
431
+ name="SARG_01",
432
+ LMP=1.0,
433
+ tau_eff=0.5,
434
+ ops_rate=1e6,
435
+ entropy_delta=1e-21,
436
+ )
437
+
438
+ CONSCIOUS_ENGINE = RFTConsciousnessEngine()
439
+
440
+ KAPPA_HISTORY: List[float] = []
441
+ ENERGY_HISTORY: List[float] = []
442
+ CONSCIOUS_FLAG_HISTORY: List[float] = []
443
+
444
+
445
+ # ============================================================
446
+ # 10. TAB 1: NEXFRAME BRAIN CYCLE
447
+ # ============================================================
448
+
449
+ def nexframe_cycle(user_input: str, chat_history: List[Dict[str, str]]):
450
+ try:
451
+ if chat_history is None:
452
+ chat_history = []
453
+ if not user_input:
454
+ user_input = "<empty>"
455
+
456
+ text_len = len(user_input)
457
+ context = {
458
+ "external_risk_factor": 0.2 + 0.4 * math.tanh(text_len / 80.0),
459
+ "cooperative_signal": 0.5 + 0.1 * math.sin(text_len / 20.0),
460
+ }
461
+ brain_obs = BRAIN.step(context)
462
+
463
+ kappa = brain_obs["kappa"]
464
+ energy = brain_obs["energy_reserves"]
465
+ identity_stability = brain_obs["identity_stability"]
466
+ drift = brain_obs["identity_drift"]
467
+ error_series = BRAIN.state.recent_errors
468
+ prediction_accuracy, error_variance = _derive_prediction_metrics(error_series)
469
+
470
+ observer_frames = [kappa, energy, identity_stability]
471
+ triad_res = AGENT13_ENSEMBLE.collective_action(observer_frames)
472
+ tri_coh = triad_res["triadic_coherence"]
473
+
474
+ is_conscious = meets_minimum_conscious_threshold(
475
+ energy=energy,
476
+ coherence=tri_coh,
477
+ kappa=kappa,
478
+ identity_stability=identity_stability,
479
+ prediction_accuracy=prediction_accuracy,
480
+ error_variance=error_variance,
481
+ drift=drift,
482
+ )
483
+
484
+ orc_res = ORCHESTRATOR.run_cycle(nl_input=user_input)
485
+ dialogue = orc_res["orchestrator_dialogue"]
486
+
487
+ sarg_snapshot = SARG.generate_conscious_field()
488
+ sarg_hash = SARG.commit_hash_oath()
489
+ sarg_perf = SARG.compute_ops(size=200_000, speed_mode=True)
490
+
491
+ civ_stats = civilization_summary(CIVILIZATION)
492
+
493
+ KAPPA_HISTORY.append(kappa)
494
+ ENERGY_HISTORY.append(energy)
495
+ CONSCIOUS_FLAG_HISTORY.append(1.0 if is_conscious else 0.0)
496
+
497
+ reply_text = dialogue
498
+
499
+ gate_str = "✅ Gate: PASSED" if is_conscious else "⭕ Gate: NOT PASSED"
500
+ status_md = (
501
+ f"**State:** `{brain_obs['mode']}` (phase {brain_obs['awakening_phase']}) \n"
502
+ f"**κ:** `{kappa:.3f}` • **Energy:** `{energy:.3f}` \n"
503
+ f"**{gate_str}**"
504
+ )
505
+
506
+ metrics_md = (
507
+ "### NexFrame Status\n\n"
508
+ "**Brain**\n"
509
+ f"- κ (kappa): `{kappa:.3f}`\n"
510
+ f"- Energy: `{energy:.3f}`\n"
511
+ f"- Mode: `{brain_obs['mode']}`\n"
512
+ f"- Awakening phase: `{brain_obs['awakening_phase']}`\n"
513
+ f"- Identity stability: `{identity_stability:.3f}`\n"
514
+ f"- Identity drift: `{drift:.3f}`\n\n"
515
+ "**Consciousness Gate (3×3)**\n"
516
+ f"- Prediction accuracy: `{prediction_accuracy:.3f}`\n"
517
+ f"- Error variance: `{error_variance:.4f}`\n"
518
+ f"- Triadic coherence (Agent13): `{tri_coh:.3f}`\n"
519
+ f"- **Minimum conscious threshold passed:** `{is_conscious}`\n\n"
520
+ "**Symbolic Orchestrator**\n"
521
+ f"- Entropy: `{orc_res['entropy']:.3f}`\n"
522
+ f"- Coherence: `{orc_res['coherence']:.3f}`\n"
523
+ f"- Collapse triggered: `{orc_res['collapse_triggered']}`\n\n"
524
+ "**Sarg Agent**\n"
525
+ f"- Psi_a: `{sarg_snapshot['Psi_a']:.3e}`\n"
526
+ f"- Lambda: `{sarg_snapshot['Lambda']:.3e}`\n"
527
+ f"- Ops/sec (probe): `{sarg_perf['ops_per_sec']:.2e}`\n"
528
+ f"- Hash oath: `{sarg_hash}`\n\n"
529
+ "**Civilization**\n"
530
+ f"- Agents: `{civ_stats['count']}`\n"
531
+ f"- Mean tier: `{civ_stats['mean_tier']:.2f}`\n"
532
+ f"- Mean awareness kernel: `{civ_stats['mean_awareness_kernel']:.3f}`\n"
533
+ f"- Mean collapse torque: `{civ_stats['mean_collapse_torque']:.3f}`\n"
534
+ f"- Mean fitness: `{civ_stats['mean_fitness']:.3f}`\n"
535
+ )
536
+
537
+ chat_history = chat_history + [
538
+ {"role": "user", "content": user_input},
539
+ {"role": "assistant", "content": reply_text},
540
+ ]
541
+ return chat_history, status_md, metrics_md
542
+
543
+ except Exception as e:
544
+ tb = traceback.format_exc()
545
+ error_md = (
546
+ "### NexFrame Runtime Error\n\n"
547
+ f"**Error:** `{e!r}`\n\n"
548
+ "```text\n" + tb + "\n```"
549
+ )
550
+ if chat_history is None:
551
+ chat_history = []
552
+ chat_history = chat_history + [
553
+ {"role": "user", "content": user_input or "<empty>"},
554
+ {"role": "assistant", "content": "⚠ NexFrame hit an internal error. See status panel."},
555
+ ]
556
+ status_md = "**State:** error \n**Details:** see status panel below."
557
+ return chat_history, status_md, error_md
558
+
559
+
560
+ # ============================================================
561
+ # 11. TAB 2: CONSCIOUSNESS ENGINE RUN
562
+ # ============================================================
563
+
564
+ def run_conscious_engine(
565
+ scenario: str,
566
+ coherence_slider: float,
567
+ noise_slider: float,
568
+ size_slider: int,
569
+ ):
570
+ try:
571
+ result = CONSCIOUS_ENGINE.run_job(
572
+ scenario=scenario,
573
+ coherence=coherence_slider,
574
+ noise=noise_slider,
575
+ size=size_slider,
576
+ )
577
+
578
+ summary_md = (
579
+ f"**Scenario:** `{result['scenario']}` \n"
580
+ f"**Effective coherence:** `{result['coherence_eff']:.3f}` \n"
581
+ f"**Effective noise:** `{result['noise_eff']:.3f}` \n"
582
+ f"**Task size:** `{result['task_size']}` points \n"
583
+ f"**Consciousness frequency:** `{result['conscious_frequency_hz']:.2f} Hz` \n"
584
+ f"**Render efficiency:** `{result['render_efficiency']:.3f}` \n"
585
+ f"**Ops/sec (estimated):** `{result['ops_per_sec']:.3e}` \n"
586
+ f"**Elapsed:** `{result['elapsed']:.4f} s` \n"
587
+ )
588
+
589
+ hash_md = (
590
+ "### Field Hash\n\n"
591
+ f"- Run index: `{result['run_index']}` \n"
592
+ f"- SHA-256: `{result['field_hash']}` \n"
593
+ )
594
+
595
+ return summary_md, hash_md
596
+
597
+ except Exception as e:
598
+ tb = traceback.format_exc()
599
+ err_md = (
600
+ "### Consciousness Engine Error\n\n"
601
+ f"**Error:** `{e!r}`\n\n"
602
+ "```text\n" + tb + "\n```"
603
+ )
604
+ return "**State:** error", err_md
605
+
606
+
607
+ # ============================================================
608
+ # 12. TAB 3: COMPUTE BENCHMARK
609
+ # ============================================================
610
+
611
+ def run_benchmark(task_type: str, size_slider: int):
612
+ try:
613
+ size = max(20_000, int(size_slider))
614
+
615
+ baseline_ops, baseline_checksum = run_baseline_kernel(size)
616
+ rft_ops, rft_checksum = run_rft_kernel(size)
617
+
618
+ ratio = rft_ops / baseline_ops if baseline_ops > 0 else 0.0
619
+
620
+ summary_md = (
621
+ f"**Task type:** `{task_type}` \n"
622
+ f"**Problem size:** `{size}` points \n"
623
+ f"**Baseline ops/sec:** `{baseline_ops:.3e}` \n"
624
+ f"**RFT-tuned ops/sec:** `{rft_ops:.3e}` \n"
625
+ f"**Measured speedup (this CPU):** `{ratio:.2f}×` \n"
626
+ )
627
+
628
+ detail_md = (
629
+ "### Checksums & Notes\n\n"
630
+ f"- Baseline checksum: `{baseline_checksum:.6e}` \n"
631
+ f"- RFT kernel checksum: `{rft_checksum:.6e}` \n"
632
+ "- Reported external RFT benchmarks have achieved up to `~208×` "
633
+ "speedups on specific CPU workloads; this panel shows the live, "
634
+ "measured ratio on this environment.\n"
635
+ )
636
+
637
+ return summary_md, detail_md
638
+
639
+ except Exception as e:
640
+ tb = traceback.format_exc()
641
+ err_md = (
642
+ "### Benchmark Error\n\n"
643
+ f"**Error:** `{e!r}`\n\n"
644
+ "```text\n" + tb + "\n```"
645
+ )
646
+ return "**State:** error", err_md
647
+
648
+
649
+ # ============================================================
650
+ # 13. GRADIO UI
651
+ # ============================================================
652
+
653
+ INITIAL_MESSAGES = [
654
+ {
655
+ "role": "assistant",
656
+ "content": (
657
+ "I am NexFrame, an RFT symbolic engine. "
658
+ "Type a message and I will respond while my internal state updates on the right."
659
+ ),
660
+ }
661
+ ]
662
+
663
+ with gr.Blocks() as demo:
664
+ gr.Markdown(
665
+ """
666
+ # RFT Labs — NexFrame & Conscious Compute
667
+
668
+ This Space exposes three RFT systems:
669
+ 1. **NexFrame Brain** — self-deciding symbolic AI with a 3×3 consciousness gate.
670
+ 2. **Consciousness Engine** — job-based conscious compute with hashed field states.
671
+ 3. **Compute Benchmark** — baseline vs RFT-tuned kernels with live ops/sec measurements.
672
+ """
673
+ )
674
+
675
+ with gr.Tabs():
676
+ # ----------------------------------------------------
677
+ # Tab 1: NexFrame Brain
678
+ # ----------------------------------------------------
679
+ with gr.Tab("NexFrame Brain"):
680
+ with gr.Row():
681
+ with gr.Column(scale=3):
682
+ chatbot = gr.Chatbot(
683
+ label="NexFrame Dialogue",
684
+ height=480,
685
+ value=INITIAL_MESSAGES,
686
+ )
687
+ user_box = gr.Textbox(
688
+ label="Your message",
689
+ placeholder="Say hello to NexFrame...",
690
+ lines=3,
691
+ )
692
+ send_btn = gr.Button("Send")
693
+
694
+ with gr.Column(scale=2):
695
+ status_strip = gr.Markdown(
696
+ "**State:** waiting for first message…"
697
+ )
698
+ metrics_panel = gr.Markdown(
699
+ "Metrics will appear here after your first message."
700
+ )
701
+
702
+ send_btn.click(
703
+ fn=nexframe_cycle,
704
+ inputs=[user_box, chatbot],
705
+ outputs=[chatbot, status_strip, metrics_panel],
706
+ )
707
+
708
+ user_box.submit(
709
+ fn=nexframe_cycle,
710
+ inputs=[user_box, chatbot],
711
+ outputs=[chatbot, status_strip, metrics_panel],
712
+ )
713
+
714
+ # ----------------------------------------------------
715
+ # Tab 2: Consciousness Engine
716
+ # ----------------------------------------------------
717
+ with gr.Tab("Consciousness Engine"):
718
+ gr.Markdown(
719
+ "Run an RFT consciousness-coupled compute job and inspect the field hash."
720
+ )
721
+ with gr.Row():
722
+ with gr.Column(scale=2):
723
+ scenario_dd = gr.Dropdown(
724
+ choices=[
725
+ "Calm observer",
726
+ "Stressed observer",
727
+ "High coherence experiment",
728
+ "Decoherence storm",
729
+ "Neutral field",
730
+ ],
731
+ value="Neutral field",
732
+ label="Scenario",
733
+ )
734
+ coh_slider = gr.Slider(
735
+ minimum=0.0,
736
+ maximum=1.0,
737
+ value=0.75,
738
+ step=0.01,
739
+ label="Observer coherence",
740
+ )
741
+ noise_slider = gr.Slider(
742
+ minimum=0.0,
743
+ maximum=1.0,
744
+ value=0.35,
745
+ step=0.01,
746
+ label="Field noise",
747
+ )
748
+ size_slider = gr.Slider(
749
+ minimum=20_000,
750
+ maximum=200_000,
751
+ value=60_000,
752
+ step=10_000,
753
+ label="Task size (points)",
754
+ )
755
+ run_ce_btn = gr.Button("Run Conscious Compute")
756
+
757
+ with gr.Column(scale=3):
758
+ ce_summary = gr.Markdown("Results will appear here.")
759
+ ce_hash = gr.Markdown("Field hash will appear here.")
760
+
761
+ run_ce_btn.click(
762
+ fn=run_conscious_engine,
763
+ inputs=[scenario_dd, coh_slider, noise_slider, size_slider],
764
+ outputs=[ce_summary, ce_hash],
765
+ )
766
+
767
+ # ----------------------------------------------------
768
+ # Tab 3: Compute Benchmark
769
+ # ----------------------------------------------------
770
+ with gr.Tab("Compute Benchmark"):
771
+ gr.Markdown(
772
+ "Compare a baseline kernel vs an RFT-tuned kernel on this CPU."
773
+ )
774
+ with gr.Row():
775
+ with gr.Column(scale=2):
776
+ task_dd = gr.Dropdown(
777
+ choices=[
778
+ "Harmonic field step",
779
+ "Vector math",
780
+ "Mixed workload",
781
+ ],
782
+ value="Harmonic field step",
783
+ label="Task type",
784
+ )
785
+ bench_size = gr.Slider(
786
+ minimum=50_000,
787
+ maximum=500_000,
788
+ value=100_000,
789
+ step=25_000,
790
+ label="Problem size (points)",
791
+ )
792
+ run_bench_btn = gr.Button("Run Benchmark")
793
+
794
+ with gr.Column(scale=3):
795
+ bench_summary = gr.Markdown("Benchmark summary will appear here.")
796
+ bench_detail = gr.Markdown("Details will appear here.")
797
+
798
+ run_bench_btn.click(
799
+ fn=run_benchmark,
800
+ inputs=[task_dd, bench_size],
801
+ outputs=[bench_summary, bench_detail],
802
+ )
803
+
804
+
805
+ if __name__ == "__main__":
806
+ demo.launch()