zkaedi commited on
Commit
a16d4c6
·
verified ·
1 Parent(s): 5a55450

enhance: PRIME live evolution, Lyapunov, bifurcation diagram, phase classifier, 4-tab legendary UI

Browse files
Files changed (1) hide show
  1. app.py +518 -228
app.py CHANGED
@@ -1,15 +1,17 @@
1
  import os
2
- import torch # type: ignore
3
- import gradio as gr # type: ignore
4
- import torch.nn as nn # type: ignore
5
- import torch.nn.functional as F # type: ignore
6
- import matplotlib.pyplot as plt # type: ignore
7
- import numpy as np # type: ignore
8
  import hashlib
9
- from transformers import AutoTokenizer # type: ignore
10
  import spaces
11
 
12
- # ── Architecture ──────────────────────────────────────────────────────────────
 
 
13
 
14
  class ZkaediTransformerBlock(nn.Module):
15
  def __init__(self, d_model: int, n_heads: int, dropout: float, ffn_mult: int = 4):
@@ -37,8 +39,7 @@ class ZkaediTransformerBlock(nn.Module):
37
  q, k, v = [t.view(B, T, self.n_heads, self.d_head).transpose(1, 2) for t in (q, k, v)]
38
  attn_logits = (q @ k.transpose(-2, -1)) * self.scale
39
  attn_logits = attn_logits.masked_fill(causal_mask[:T, :T], float('-inf'))
40
- # FIX #3 h_bias shape: (B, n_heads, 1, 1) for per-head modulation
41
- attn_logits = attn_logits + h_bias
42
  attn_weights = self.attn_dropout(F.softmax(attn_logits, dim=-1))
43
  attn_out = (attn_weights @ v).transpose(1, 2).contiguous().view(B, T, C)
44
  x = residual + self.proj(attn_out)
@@ -51,6 +52,7 @@ class ZkaediAttentionCore(nn.Module):
51
  n_layers: int = 2, dropout: float = 0.1, max_seq_len: int = 128):
52
  super().__init__()
53
  self.n_heads = n_heads
 
54
  self.embedding = nn.Embedding(vocab_size, d_model)
55
  self.pos_embedding = nn.Embedding(max_seq_len, d_model)
56
  self.drop = nn.Dropout(dropout)
@@ -60,7 +62,6 @@ class ZkaediAttentionCore(nn.Module):
60
  self.norm_final = nn.LayerNorm(d_model)
61
  self.lm_head = nn.Linear(d_model, vocab_size, bias=False)
62
  self.lm_head.weight = self.embedding.weight
63
- # FIX #3 — binary chaos classification head on [CLS] (pos 0)
64
  self.chaos_head = nn.Linear(d_model, 1)
65
  causal = torch.triu(torch.ones(max_seq_len, max_seq_len, dtype=torch.bool), diagonal=1)
66
  self.register_buffer('causal_mask', causal, persistent=False)
@@ -73,12 +74,54 @@ class ZkaediAttentionCore(nn.Module):
73
  x = block(x, h_bias, self.causal_mask)
74
  x_final = self.norm_final(x)
75
  logits = self.lm_head(x_final)
76
- # Chaos score from first token (proxy for [CLS])
77
- chaos_score = torch.sigmoid(self.chaos_head(x_final[:, 0, :])).squeeze(-1) # (B,)
78
  return logits, chaos_score
79
 
80
 
81
- # ── Inference Globals ──────────────────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
83
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
84
  tokenizer = AutoTokenizer.from_pretrained("microsoft/codebert-base")
@@ -86,287 +129,534 @@ if tokenizer.pad_token is None:
86
  tokenizer.add_special_tokens({'pad_token': '[PAD]'})
87
 
88
  model = None
89
- H_0_bias = None # will be set after checkpoint load
90
 
91
  ckpt_path = "prime_epoch_010.pt"
92
  if os.path.exists(ckpt_path):
93
  ckpt = torch.load(ckpt_path, map_location=device, weights_only=True)
94
-
95
- # FIX #1 — vocab_size: prefer checkpoint-saved value, fall back to current tokenizer
96
  vocab_size = ckpt.get('vocab_size', len(tokenizer))
97
-
98
  model = ZkaediAttentionCore(vocab_size=vocab_size).to(device)
99
-
100
- # Load with strict=False so new chaos_head initialises fresh rather than crashing
101
- missing, unexpected = model.load_state_dict(ckpt['model_state_dict'], strict=False)
102
  if missing:
103
- print(f"ℹ️ New keys initialised fresh: {missing}")
104
- if unexpected:
105
- print(f"⚠️ Unexpected keys ignored: {unexpected}")
106
-
107
  model.eval()
108
-
109
  hs = ckpt['hamiltonian_state']
110
  H_0_raw = hs['H_0'].to(device)
111
-
112
- # FIX #2 H_0 shape safety: reduce to scalar regardless of original shape
113
- if H_0_raw.numel() > 1:
114
- H_0_scalar = H_0_raw.mean()
115
- print(f"ℹ️ H_0 was shape {tuple(H_0_raw.shape)}, reduced to scalar mean")
116
- else:
117
- H_0_scalar = H_0_raw.squeeze()
118
-
119
- # FIX #3 — shape (1, n_heads, 1, 1) so each head gets its own bias dimension
120
- # We broadcast the single scalar across all heads (preserves original behaviour
121
- # while being correctly shaped for the attention kernel)
122
- H_0_bias = torch.sigmoid(H_0_scalar).detach().view(1, 1, 1, 1).expand(
123
- 1, model.n_heads, 1, 1
124
- ).contiguous()
125
-
126
- print(f"✅ Loaded prime_epoch_010.pt | vocab={vocab_size} | H_0_bias={H_0_bias[0,0,0,0].item():.4f}")
127
  else:
128
- print("❌ prime_epoch_010.pt not found — running in fallback mode")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
 
130
 
131
- # ── Inference ─────────────────────────────────────────────────────────────────
 
 
132
 
133
  @spaces.GPU
134
- def predict_anomaly(time_step, dh_variance, mse_error):
135
- if model is None or H_0_bias is None:
136
- return (
137
- "❌ Missing checkpoint `prime_epoch_010.pt`. Drop it into the Space directory!",
138
- 0.0, "UNKNOWN", None, None, "N/A", []
139
- )
140
-
141
- instruction = "Analyze the quantum telemetry inputs and predict the Hamiltonian chaos bounds."
142
- input_str = f"t: {time_step:.2f}, dH: {dh_variance:.4f}, mse: {mse_error:.4f}"
143
- text = f"Instruction: {instruction} | Context: {input_str} | Target: "
144
-
145
- encoded = tokenizer(text, return_tensors='pt', max_length=128, truncation=True).to(device)
146
- input_ids = encoded['input_ids']
147
- B = input_ids.shape[0]
148
-
 
 
 
 
 
 
 
 
 
 
 
149
  with torch.no_grad():
150
- # FIX #4 expand bias to actual batch size at inference time
151
- val_attn_bias = H_0_bias.expand(B, -1, -1, -1)
152
- logits, chaos_score = model(input_ids, val_attn_bias)
153
- prediction_ids = torch.argmax(logits, dim=-1)
154
-
155
- output_text = tokenizer.decode(prediction_ids[0], skip_special_tokens=True)
156
-
157
- # FIX #3 — use learned chaos_score from classification head as primary signal
158
- # heuristic fallback: mse > 2.0 still acts as hard override
159
- model_predicts_chaos = chaos_score.item() > 0.5
160
- physics_override = mse_error > 2.0
161
- is_chaos = model_predicts_chaos or physics_override
162
 
 
 
163
  if is_chaos:
164
  warning = "🚨 CRITICAL CHAOS ANOMALY DETECTED"
165
- h_peak = 428.99 + (mse_error * 10)
166
  else:
167
  warning = "✅ SYSTEM STABLE"
168
- h_peak = 1.0 + dh_variance
169
 
170
- # ── 3D Phase Portrait ──────────────────────────────────────────────────────
171
- fig = plt.figure(figsize=(7, 5), facecolor='#0b0514')
172
- ax = fig.add_subplot(111, projection='3d')
173
- ax.set_facecolor('#0b0514')
174
- ax.xaxis.set_pane_color((0.0, 0.0, 0.0, 0.0))
175
- ax.yaxis.set_pane_color((0.0, 0.0, 0.0, 0.0))
176
- ax.zaxis.set_pane_color((0.0, 0.0, 0.0, 0.0))
177
- ax.grid(color='#ffffff', alpha=0.08)
178
-
179
- t_vals = np.linspace(0, time_step + 10, 500)
180
- H_vals = (h_peak * 0.5) * np.sin(t_vals * 0.8 + dh_variance) + (mse_error * 5.0 * np.cos(t_vals * 2.1))
181
- dH_vals = np.gradient(H_vals, t_vals)
182
-
183
- for glow_level in range(1, 14):
184
- ax.plot3D(H_vals, dH_vals, t_vals, color='#ff00ff', alpha=0.04, linewidth=glow_level * 1.5)
185
-
186
- ax.plot3D(H_vals, dH_vals, t_vals, color='#ffffff', alpha=0.9, linewidth=1.0)
187
- ax.scatter3D(H_vals, dH_vals, t_vals, c=t_vals, cmap='plasma', s=10, alpha=0.8, zorder=3)
188
-
189
- noise_H = H_vals + np.random.normal(0, max(mse_error * 0.4, 1e-6), H_vals.shape[0])
190
- noise_dH = dH_vals + np.random.normal(0, max(mse_error * 0.4, 1e-6), dH_vals.shape[0])
191
- noise_T = t_vals + np.random.normal(0, max(mse_error * 0.4, 1e-6), t_vals.shape[0])
192
- ax.scatter3D(noise_H, noise_dH, noise_T, color='#00ffff', s=2, alpha=0.4, zorder=2)
193
 
 
 
 
 
194
  if is_chaos:
195
- ax.scatter3D(H_vals[-1], dH_vals[-1], t_vals[-1],
196
- color='#ff0000', s=150, marker='X', edgecolors='#ffffff', zorder=5)
197
- ax.set_title(f"CHAOTIC BOUNDARY REACHED: H={h_peak:.2f}", color='#ff0000', fontsize=14, fontweight='bold')
198
  else:
199
- ax.scatter3D(H_vals[-1], dH_vals[-1], t_vals[-1],
200
- color='#00ffff', s=100, marker='o', edgecolors='#ffffff', zorder=5)
201
- ax.set_title("3D TOPOLOGY: H vs dH/dt vs t", color='#00ffff', fontsize=12)
202
-
203
- ax.set_xlabel("Hamiltonian (H)", color='#ff00ff')
204
- ax.set_ylabel("Variance (dH)", color='#00ffff')
205
- ax.set_zlabel("Time (t)", color='#e0e0e0')
206
- ax.tick_params(colors='#e0e0e0')
207
-
208
- # ── Audio Sonification ─────────────────────────────────────────────────────
209
- sample_rate = 44100
210
- t_audio = np.linspace(0, 1.0, sample_rate)
211
- base_freq = 110.0 + (h_peak * 1.5)
212
 
213
- if is_chaos:
214
- audio_data = np.sign(np.sin(2 * np.pi * base_freq * t_audio))
215
- audio_data += np.random.uniform(-0.8, 0.8, sample_rate)
216
- else:
217
- audio_data = np.sin(2 * np.pi * base_freq * t_audio) * 0.5
218
- audio_data += np.sin(2 * np.pi * (base_freq * 1.5) * t_audio) * 0.2
219
-
220
- audio_data = np.int16(np.clip(audio_data, -1.0, 1.0) * 32767)
221
-
222
- # ── Cryptographic Seed ─────────────────────────────────────────────────────
223
- raw_seed_string = f"T:{time_step}|dH:{dh_variance}|MSE:{mse_error}|PEAK:{h_peak:.4f}|ZKAEDI"
224
- chaos_hash = hashlib.sha256(raw_seed_string.encode('utf-8')).hexdigest()
225
-
226
- # ── Telemetry Ledger ───────────────────────────────────────────────────────
227
- new_entry = [
228
- time_step, dh_variance, mse_error,
229
- float(f"{h_peak:.2f}"),
230
- "CHAOS" if is_chaos else "STABLE",
231
- f"0x{chaos_hash[:12]}..."
232
- ]
233
 
 
 
234
  try:
235
  import csv
236
- log_file = "zkaedi_telemetry_ledger.csv"
237
- file_exists = os.path.exists(log_file)
238
- with open(log_file, 'a', newline='') as f:
239
- writer = csv.writer(f)
240
- if not file_exists:
241
- writer.writerow(["Time (t)", "Shift (dH)", "Error (mse)",
242
- "Peak (H)", "Classification", "On-Chain Seed"])
243
- writer.writerow(new_entry)
244
  except Exception as e:
245
- print(f"CSV Save Fault: {e}")
246
-
247
- return output_text, h_peak, warning, fig, (sample_rate, audio_data), f"0x{chaos_hash}", new_entry
248
-
249
-
250
- # ── UI ─────────────────────────────────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
251
 
252
- custom_css = """
253
  .gradio-container {
254
- background: radial-gradient(circle at center, #1a0b2e 0%, #000000 100%) !important;
255
- font-family: 'Orbitron', 'Courier New', monospace !important;
256
- color: #e0e0e0 !important;
 
 
 
 
 
 
 
 
 
 
 
257
  }
258
  h1 {
259
- color: #00ffff !important;
260
- text-shadow: 0 0 15px #00ffff, 0 0 30px #00ffff;
261
- text-align: center;
262
- text-transform: uppercase;
263
- letter-spacing: 4px;
264
- font-size: 3rem !important;
 
 
 
 
265
  }
266
  .subtitle {
267
- color: #ff00ff !important;
268
- text-shadow: 0 0 10px #ff00ff;
269
- text-align: center;
270
- font-size: 1.2rem;
271
- margin-bottom: 30px;
 
 
 
 
 
 
 
 
 
 
 
 
 
272
  }
273
- .form { box-shadow: 0 0 15px rgba(255, 0, 255, 0.2) !important; border: 1px solid #ff00ff !important; background: #0b0514 !important; }
274
- button.primary {
275
- background: linear-gradient(90deg, #ff00ff 0%, #00ffff 100%) !important;
276
- border: none !important;
277
- color: black !important;
278
- font-weight: 900 !important;
279
- text-transform: uppercase;
280
- box-shadow: 0 0 15px #ff00ff !important;
281
- transition: all 0.2s ease-in-out;
 
 
 
 
 
 
 
 
 
 
282
  }
283
- button.primary:hover {
284
- transform: scale(1.02);
285
- box-shadow: 0 0 30px #00ffff !important;
 
 
 
 
 
 
286
  }
287
- .stat-box {
288
- border-left: 4px solid #00ffff;
289
- padding: 10px;
290
- background: rgba(0, 255, 255, 0.05);
291
- margin: 10px 0;
292
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
293
  """
294
 
295
- with gr.Blocks(css=custom_css, title="ZKAEDI TENSOR: Prime") as iface:
 
 
296
  gr.Markdown("# 🌌 ZKAEDI TENSOR 🌌")
297
- gr.Markdown("<div class='subtitle'>L E G E N D A R Y &nbsp; P R I M E &nbsp; T H R E A T &nbsp; I S O L A T I O N</div>")
298
 
299
  with gr.Tabs():
300
- with gr.TabItem("⚙️ PRIMARY TENSOR INFERENCE"):
 
 
301
  with gr.Row():
302
  with gr.Column(scale=1):
303
  gr.Markdown("### 📡 QUANTUM INPUT MATRIX")
304
- gr.Markdown("Manipulate the bare-metal evolutionary vectors below to stimulate the Hamiltonian prediction array.")
305
-
306
- t_input = gr.Slider(0.0, 100.0, value=12.5, step=0.1, label="Chronological T-Vector (t)")
307
- dh_input = gr.Slider(-10.0, 10.0, value=0.1, step=0.01, label="Hamiltonian Shift (dH)")
308
- mse_input = gr.Slider(0.0, 10.0, value=0.5, step=0.01, label="Mean Squared Error Variance (mse)")
309
-
310
- gr.Markdown("#### PRE-COMPUTED VECTORS:")
 
 
 
 
 
 
311
  gr.Examples(
312
  examples=[
313
- [12.5, 0.1, 0.5],
314
- [45.0, 5.0, 1.2],
315
- [89.0, -8.2, 4.2],
316
- [90.0, 10.0, 9.9],
317
  ],
318
- inputs=[t_input, dh_input, mse_input],
319
  label="Inject Saved Telemetry"
320
  )
321
-
322
- btn = gr.Button("⚡ INITIATE TRANSCENDENCE ⚡", variant="primary")
323
 
324
  with gr.Column(scale=1):
325
  gr.Markdown("### 🧠 SENSORY DECODER OUTPUT")
326
- warning_out = gr.Textbox(label="Threat Status", lines=2)
327
-
328
  with gr.Row():
329
- with gr.Column(scale=1):
330
- h_out = gr.Number(label="Predicted Chaos Boundary (Peak H)")
331
- hash_out = gr.Textbox(label="🔏 Web3 Seed Hash (Quantum Bonus)", lines=1)
332
- raw_out = gr.Textbox(label="CodeBERT Tensor Tokens", lines=2)
333
- audio_out = gr.Audio(label="Mathematical Resonance (Sonified)", type="numpy")
334
- with gr.Column(scale=2):
335
- plot_out = gr.Plot(label="Live Attractor Topology")
336
-
337
- with gr.TabItem("📜 OPERATION LOGS"):
338
- gr.Markdown("### 🗃️ TENSOR STATE HISTORY")
339
- gr.Markdown("Log of all multi-dimensional queries and their resulting Hamiltonian classifications.")
340
- history_data = gr.Dataframe(
341
- headers=["Time (t)", "Shift (dH)", "Error (mse)", "Peak (H)", "Classification", "On-Chain Seed"],
342
- datatype=["number", "number", "number", "number", "str", "str"],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
343
  column_count=(6, "fixed"),
344
- interactive=False
345
  )
346
 
347
- def update_history(existing, new_row):
348
- import pandas as pd # type: ignore
349
- cols = ["Time (t)", "Shift (dH)", "Error (mse)", "Peak (H)", "Classification", "On-Chain Seed"]
350
- if existing is None or len(existing) == 0:
351
- return pd.DataFrame([new_row], columns=cols)
352
- df = pd.DataFrame(existing, columns=cols)
353
- df.loc[len(df)] = new_row
354
- return df
355
-
356
  gr.Markdown("---")
357
- gr.Markdown("<div style='text-align: center; color: #555;'>Matrix Weights: <code>prime_epoch_010.pt</code> | VRAM Bound: 32GB</div>")
 
 
 
 
 
 
 
 
358
 
359
- hidden_entry = gr.State([])
 
360
 
361
- btn.click(
362
  fn=predict_anomaly,
363
- inputs=[t_input, dh_input, mse_input],
364
- outputs=[raw_out, h_out, warning_out, plot_out, audio_out, hash_out, hidden_entry]
365
  ).then(
366
  fn=update_history,
367
- inputs=[history_data, hidden_entry],
368
- outputs=[history_data]
369
  )
370
 
 
 
 
 
 
 
 
 
 
 
 
 
 
371
  if __name__ == "__main__":
372
  iface.launch(server_name="0.0.0.0", server_port=7860, share=False)
 
1
  import os
2
+ import torch
3
+ import gradio as gr
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+ import matplotlib.pyplot as plt
7
+ import numpy as np
8
  import hashlib
9
+ from transformers import AutoTokenizer
10
  import spaces
11
 
12
+ # ══════════════════════════════════════════════════════════════════════════════
13
+ # ARCHITECTURE
14
+ # ══════════════════════════════════════════════════════════════════════════════
15
 
16
  class ZkaediTransformerBlock(nn.Module):
17
  def __init__(self, d_model: int, n_heads: int, dropout: float, ffn_mult: int = 4):
 
39
  q, k, v = [t.view(B, T, self.n_heads, self.d_head).transpose(1, 2) for t in (q, k, v)]
40
  attn_logits = (q @ k.transpose(-2, -1)) * self.scale
41
  attn_logits = attn_logits.masked_fill(causal_mask[:T, :T], float('-inf'))
42
+ attn_logits = attn_logits + h_bias # (B, n_heads, 1, 1)
 
43
  attn_weights = self.attn_dropout(F.softmax(attn_logits, dim=-1))
44
  attn_out = (attn_weights @ v).transpose(1, 2).contiguous().view(B, T, C)
45
  x = residual + self.proj(attn_out)
 
52
  n_layers: int = 2, dropout: float = 0.1, max_seq_len: int = 128):
53
  super().__init__()
54
  self.n_heads = n_heads
55
+ self.d_model = d_model
56
  self.embedding = nn.Embedding(vocab_size, d_model)
57
  self.pos_embedding = nn.Embedding(max_seq_len, d_model)
58
  self.drop = nn.Dropout(dropout)
 
62
  self.norm_final = nn.LayerNorm(d_model)
63
  self.lm_head = nn.Linear(d_model, vocab_size, bias=False)
64
  self.lm_head.weight = self.embedding.weight
 
65
  self.chaos_head = nn.Linear(d_model, 1)
66
  causal = torch.triu(torch.ones(max_seq_len, max_seq_len, dtype=torch.bool), diagonal=1)
67
  self.register_buffer('causal_mask', causal, persistent=False)
 
74
  x = block(x, h_bias, self.causal_mask)
75
  x_final = self.norm_final(x)
76
  logits = self.lm_head(x_final)
77
+ chaos_score = torch.sigmoid(self.chaos_head(x_final[:, 0, :])).squeeze(-1)
 
78
  return logits, chaos_score
79
 
80
 
81
+ # ══════════════════════════════════════════════════════════════════════════════
82
+ # ZKAEDI PRIME MATHEMATICS
83
+ # ══════════════════════════════════════════════════════════════════════════════
84
+
85
+ def run_prime_evolution(H_0_val: float, eta: float, gamma: float,
86
+ beta: float, sigma: float, steps: int = 100) -> np.ndarray:
87
+ """H_t = H_0 + η·H_{t-1}·σ(γ·H_{t-1}) + σ·N(0, 1+β|H_{t-1}|)"""
88
+ H = H_0_val
89
+ traj = [H]
90
+ for _ in range(steps):
91
+ sig = 1.0 / (1.0 + np.exp(-gamma * float(np.clip(H, -50, 50))))
92
+ noise = np.random.normal(0.0, 1.0 + beta * abs(H))
93
+ H = H_0_val + eta * H * sig + sigma * noise
94
+ H = float(np.tanh(H / 12.0) * 12.0)
95
+ traj.append(H)
96
+ return np.array(traj)
97
+
98
+
99
+ def compute_lyapunov(traj: np.ndarray, H_0_val: float,
100
+ eta: float, gamma: float) -> float:
101
+ """λ = (1/N) Σ log|dF/dH| where dF/dH = η·σ·(1 + γ·H·(1−σ))"""
102
+ lyap, count = 0.0, 0
103
+ for H in traj[:-1]:
104
+ sig = 1.0 / (1.0 + np.exp(-gamma * float(np.clip(H, -50, 50))))
105
+ deriv = abs(eta * sig * (1.0 + gamma * H * (1.0 - sig)))
106
+ if deriv > 1e-14:
107
+ lyap += np.log(deriv)
108
+ count += 1
109
+ return lyap / count if count > 0 else -999.0
110
+
111
+
112
+ def classify_phase(lyapunov: float, traj: np.ndarray) -> tuple:
113
+ tail_var = float(np.var(traj[-50:] if len(traj) >= 50 else traj))
114
+ if lyapunov > 0.50: return "⚡ LEGEND", "#ff00ff"
115
+ elif lyapunov > 0.05: return "🔥 CHAOTIC", "#ff3333"
116
+ elif lyapunov > -0.05:return "🌀 BIFURCATING", "#ff8800"
117
+ elif lyapunov > -0.25:return "〰️ WANDERING", "#ffff00"
118
+ elif tail_var < 0.02: return "🎯 CONVERGING", "#00ff88"
119
+ else: return "🔷 INITIALIZING", "#00ccff"
120
+
121
+
122
+ # ══════════════════════════════════════════════════════════════════════════════
123
+ # CHECKPOINT LOADING
124
+ # ══════════════════════════════════════════════════════════════════════════════
125
 
126
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
127
  tokenizer = AutoTokenizer.from_pretrained("microsoft/codebert-base")
 
129
  tokenizer.add_special_tokens({'pad_token': '[PAD]'})
130
 
131
  model = None
132
+ H_0_raw_val = 0.7311
133
 
134
  ckpt_path = "prime_epoch_010.pt"
135
  if os.path.exists(ckpt_path):
136
  ckpt = torch.load(ckpt_path, map_location=device, weights_only=True)
 
 
137
  vocab_size = ckpt.get('vocab_size', len(tokenizer))
 
138
  model = ZkaediAttentionCore(vocab_size=vocab_size).to(device)
139
+ missing, _ = model.load_state_dict(ckpt['model_state_dict'], strict=False)
 
 
140
  if missing:
141
+ print(f"ℹ️ Fresh init: {missing}")
 
 
 
142
  model.eval()
 
143
  hs = ckpt['hamiltonian_state']
144
  H_0_raw = hs['H_0'].to(device)
145
+ H_0_raw_val = float(H_0_raw.mean().item() if H_0_raw.numel() > 1 else H_0_raw.item())
146
+ print(f"✅ prime_epoch_010.pt | vocab={vocab_size} | H_0={H_0_raw_val:.4f}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
  else:
148
+ print("❌ prime_epoch_010.pt not found — PRIME-only mode active")
149
+
150
+
151
+ # ══════════════════════════════════════════════════════════════════════════════
152
+ # PLOT HELPERS
153
+ # ══════════════════════════════════════════════════════════════════════════════
154
+
155
+ _BG, _CYAN, _MAG, _WHT, _GRID = '#050010', '#00ffff', '#ff00ff', '#e8e8ff', '#111133'
156
+
157
+
158
+ def _neon(ax, x, y, color, lw=1.0, layers=8):
159
+ for i in range(layers, 0, -1):
160
+ ax.plot(x, y, color=color, alpha=0.016 * i, linewidth=lw * i * 1.5)
161
+ ax.plot(x, y, color=color, linewidth=lw, alpha=0.95)
162
+
163
+
164
+ def _style(ax, title='', tc=_CYAN, xl='', yl='', ylc=_CYAN):
165
+ ax.set_facecolor(_BG)
166
+ ax.set_title(title, color=tc, fontsize=10, fontweight='bold', pad=7)
167
+ ax.set_xlabel(xl, color='#556677', fontsize=8)
168
+ ax.set_ylabel(yl, color=ylc, fontsize=8)
169
+ ax.tick_params(colors='#445566', labelsize=7)
170
+ for sp in ax.spines.values(): sp.set_color('#222244')
171
+ ax.grid(color=_GRID, alpha=0.55, linewidth=0.5)
172
+
173
+
174
+ def plot_energy_evolution(traj, lam, phase, pc):
175
+ fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 6), facecolor=_BG)
176
+ fig.subplots_adjust(hspace=0.5, top=0.93, bottom=0.09)
177
+ steps = np.arange(len(traj))
178
+ _neon(ax1, steps, traj, _CYAN, lw=1.2, layers=10)
179
+ ax1.fill_between(steps, traj, alpha=0.06, color=_CYAN)
180
+ ax1.axhline(0, color=_WHT, alpha=0.12, lw=0.6, ls='--')
181
+ _style(ax1, title=f"PRIME H_t λ={lam:.5f} {phase}", tc=pc, xl="t", yl="H_t")
182
+ dH = np.diff(traj)
183
+ _neon(ax2, steps[1:], dH, _MAG, lw=1.0, layers=8)
184
+ ax2.fill_between(steps[1:], dH, alpha=0.05, color=_MAG)
185
+ ax2.axhline(0, color=_WHT, alpha=0.12, lw=0.6, ls='--')
186
+ _style(ax2, title="Velocity dH/dt", tc=_MAG, xl="t", yl="dH/dt", ylc=_MAG)
187
+ fig.patch.set_facecolor(_BG)
188
+ return fig
189
+
190
+
191
+ def plot_bifurcation(H_0_val, gamma, beta, sigma_noise):
192
+ fig, ax = plt.subplots(figsize=(9, 5), facecolor=_BG)
193
+ ax.set_facecolor(_BG)
194
+ eta_vals = np.linspace(0.01, 0.97, 350)
195
+ all_eta, all_h = [], []
196
+ for eta in eta_vals:
197
+ H = H_0_val
198
+ for _ in range(180):
199
+ sig = 1.0 / (1.0 + np.exp(-gamma * float(np.clip(H, -50, 50))))
200
+ H = H_0_val + eta * H * sig
201
+ H = float(np.tanh(H / 12.0) * 12.0)
202
+ for _ in range(80):
203
+ sig = 1.0 / (1.0 + np.exp(-gamma * float(np.clip(H, -50, 50))))
204
+ H = H_0_val + eta * H * sig + sigma_noise * np.random.normal(0, 1 + beta * abs(H))
205
+ H = float(np.tanh(H / 12.0) * 12.0)
206
+ all_eta.append(eta); all_h.append(H)
207
+ ax.scatter(all_eta, all_h, c=_CYAN, s=0.25, alpha=0.4, linewidths=0)
208
+ y_range = (max(all_h) - min(all_h)) if all_h else 2.0
209
+ ax.axvline(x=0.70, color=_MAG, alpha=0.35, lw=0.9, ls='--')
210
+ ax.text(0.715, min(all_h) + y_range * 0.88 if all_h else 1,
211
+ 'chaos\nonset', color=_MAG, fontsize=7, alpha=0.75)
212
+ _style(ax, title="PRIME Bifurcation H*(η) — Period-Doubling & Chaos Onset",
213
+ xl="η (feedback coupling)", yl="H* (attractor)")
214
+ fig.patch.set_facecolor(_BG)
215
+ fig.tight_layout()
216
+ return fig
217
+
218
+
219
+ def plot_phase_portrait_3d(h_peak, time_step, mse_error, dh_variance, is_chaos):
220
+ fig = plt.figure(figsize=(7, 5), facecolor=_BG)
221
+ ax = fig.add_subplot(111, projection='3d')
222
+ ax.set_facecolor(_BG)
223
+ for p in [ax.xaxis, ax.yaxis, ax.zaxis]:
224
+ p.set_pane_color((0, 0, 0, 0))
225
+ ax.grid(color=_GRID, alpha=0.22)
226
+ t_vals = np.linspace(0, time_step + 10, 600)
227
+ H_vals = (h_peak * 0.5) * np.sin(t_vals * 0.8 + dh_variance) + mse_error * 5.0 * np.cos(t_vals * 2.1)
228
+ dH_vals = np.gradient(H_vals, t_vals)
229
+ gc = '#ff0044' if is_chaos else _MAG
230
+ for g in range(1, 10):
231
+ ax.plot3D(H_vals, dH_vals, t_vals, color=gc, alpha=0.02, linewidth=g * 2.0)
232
+ ax.plot3D(H_vals, dH_vals, t_vals, color=_WHT, alpha=0.8, linewidth=0.7)
233
+ ax.scatter3D(H_vals, dH_vals, t_vals, c=t_vals, cmap='cool', s=6, alpha=0.6, zorder=3)
234
+ n, sc = len(H_vals), max(mse_error * 0.25, 0.04)
235
+ ax.scatter3D(H_vals + np.random.normal(0, sc, n),
236
+ dH_vals + np.random.normal(0, sc, n),
237
+ t_vals + np.random.normal(0, sc, n),
238
+ color=_CYAN, s=1.2, alpha=0.25, zorder=2)
239
+ if is_chaos:
240
+ ax.scatter3D(H_vals[-1], dH_vals[-1], t_vals[-1],
241
+ color='#ff0000', s=200, marker='X', edgecolors=_WHT, zorder=5)
242
+ ax.set_title(f"CHAOS H={h_peak:.2f}", color='#ff2244', fontsize=11, fontweight='bold')
243
+ else:
244
+ ax.scatter3D(H_vals[-1], dH_vals[-1], t_vals[-1],
245
+ color=_CYAN, s=140, marker='o', edgecolors=_WHT, zorder=5)
246
+ ax.set_title("H ↔ dH/dt ↔ t", color=_CYAN, fontsize=10)
247
+ ax.set_xlabel("H", color=_MAG, fontsize=8)
248
+ ax.set_ylabel("dH/dt", color=_CYAN, fontsize=8)
249
+ ax.set_zlabel("t", color='#aaaacc', fontsize=8)
250
+ ax.tick_params(colors='#444466', labelsize=7)
251
+ fig.patch.set_facecolor(_BG)
252
+ return fig
253
 
254
 
255
+ # ══════════════════════════════════════════════════════════════════════════════
256
+ # GRADIO FUNCTIONS
257
+ # ══════════════════════════════════════════════════════════════════════════════
258
 
259
  @spaces.GPU
260
+ def predict_anomaly(time_step, dh_variance, mse_error,
261
+ eta, gamma, beta, sigma, prime_steps):
262
+ if model is None:
263
+ ef = plt.figure(facecolor=_BG)
264
+ plt.text(0.5, 0.5, '❌ No checkpoint', ha='center', va='center',
265
+ color=_CYAN, fontsize=14, transform=plt.gca().transAxes)
266
+ plt.close()
267
+ return ("❌ Missing prime_epoch_010.pt", 0.0, "UNKNOWN",
268
+ ef, ef, -999.0, "UNKNOWN", None, "N/A", [])
269
+
270
+ # 1. Run PRIME evolution
271
+ traj = run_prime_evolution(H_0_raw_val, float(eta), float(gamma),
272
+ float(beta), float(sigma), int(prime_steps))
273
+ lam = compute_lyapunov(traj, H_0_raw_val, float(eta), float(gamma))
274
+ phase, pc = classify_phase(lam, traj)
275
+ H_evolved = float(traj[-1])
276
+
277
+ # 2. Evolved attention bias → (B, n_heads, 1, 1)
278
+ hv = torch.tensor(float(np.tanh(H_evolved / 5.0)), dtype=torch.float32, device=device)
279
+ h_bias = torch.sigmoid(hv).view(1,1,1,1).expand(1, model.n_heads, 1,1).contiguous()
280
+
281
+ # 3. Inference
282
+ text = (f"Instruction: Analyze quantum telemetry and predict Hamiltonian chaos bounds. "
283
+ f"| Context: t:{time_step:.2f} dH:{dh_variance:.4f} mse:{mse_error:.4f} "
284
+ f"Ht:{H_evolved:.4f} lambda:{lam:.4f} | Target: ")
285
+ enc = tokenizer(text, return_tensors='pt', max_length=128, truncation=True).to(device)
286
  with torch.no_grad():
287
+ logits, chaos_score = model(enc['input_ids'], h_bias)
288
+ pred_ids = torch.argmax(logits, dim=-1)
289
+ output_text = tokenizer.decode(pred_ids[0], skip_special_tokens=True)
 
 
 
 
 
 
 
 
 
290
 
291
+ # 4. Threat classification
292
+ is_chaos = (chaos_score.item() > 0.5) or (mse_error > 2.0) or (lam > 0.05)
293
  if is_chaos:
294
  warning = "🚨 CRITICAL CHAOS ANOMALY DETECTED"
295
+ h_peak = 428.99 + mse_error * 10.0 + abs(H_evolved * 2.0)
296
  else:
297
  warning = "✅ SYSTEM STABLE"
298
+ h_peak = 1.0 + abs(dh_variance) + abs(H_evolved * 0.5)
299
 
300
+ # 5. Plots
301
+ fig_3d = plot_phase_portrait_3d(h_peak, time_step, mse_error, dh_variance, is_chaos)
302
+ fig_en = plot_energy_evolution(traj, lam, phase, pc)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
303
 
304
+ # 6. Audio
305
+ sr = 44100
306
+ ta = np.linspace(0, 1.0, sr)
307
+ bf = 110.0 + h_peak * 1.5
308
  if is_chaos:
309
+ aud = np.sign(np.sin(2 * np.pi * bf * ta)) + np.random.uniform(-0.8, 0.8, sr)
 
 
310
  else:
311
+ aud = np.sin(2*np.pi*bf*ta)*0.5 + np.sin(2*np.pi*(bf*1.5)*ta)*0.2
312
+ aud = np.int16(np.clip(aud, -1.0, 1.0) * 32767)
 
 
 
 
 
 
 
 
 
 
 
313
 
314
+ # 7. Hash
315
+ seed = f"T:{time_step}|dH:{dh_variance}|MSE:{mse_error}|Ht:{H_evolved:.4f}|λ:{lam:.6f}|ZKAEDI"
316
+ chash = hashlib.sha256(seed.encode()).hexdigest()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
317
 
318
+ entry = [time_step, dh_variance, mse_error, round(h_peak, 2),
319
+ "CHAOS" if is_chaos else "STABLE", f"0x{chash[:12]}..."]
320
  try:
321
  import csv
322
+ lf, new = "zkaedi_telemetry_ledger.csv", not os.path.exists("zkaedi_telemetry_ledger.csv")
323
+ with open(lf, 'a', newline='') as f:
324
+ w = csv.writer(f)
325
+ if new: w.writerow(["t","dH","mse","H_peak","class","hash"])
326
+ w.writerow(entry)
 
 
 
327
  except Exception as e:
328
+ print(f"CSV: {e}")
329
+
330
+ return (output_text, h_peak, warning, fig_3d, fig_en,
331
+ round(lam, 6), phase, (sr, aud), f"0x{chash}", entry)
332
+
333
+
334
+ def analyze_prime_field(H_0_init, eta, gamma, beta, sigma, steps):
335
+ traj = run_prime_evolution(float(H_0_init), float(eta), float(gamma),
336
+ float(beta), float(sigma), int(steps))
337
+ lam = compute_lyapunov(traj, float(H_0_init), float(eta), float(gamma))
338
+ phase, pc = classify_phase(lam, traj)
339
+ fig = plot_energy_evolution(traj, lam, phase, pc)
340
+ tv = float(np.var(traj[-50:]))
341
+ if lam > 0.3: att = "Strange Attractor / Chaos"
342
+ elif lam > -0.05:att = "Limit Cycle / Period-Doubling"
343
+ elif tv < 0.01: att = "Fixed-Point Attractor"
344
+ else: att = "Quasi-Periodic / Transient"
345
+ stats = (
346
+ f"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
347
+ f" ZKAEDI PRIME — Field Statistics\n"
348
+ f"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
349
+ f" H_0 : {H_0_init:.4f}\n"
350
+ f" η (eta) : {eta:.3f}\n"
351
+ f" γ (gamma) : {gamma:.3f}\n"
352
+ f" β (beta) : {beta:.3f}\n"
353
+ f" σ (sigma) : {sigma:.4f}\n"
354
+ f" Steps : {int(steps)}\n"
355
+ f"───────────────────────────────────────────\n"
356
+ f" H_final : {traj[-1]:.5f}\n"
357
+ f" H_mean : {np.mean(traj):.5f}\n"
358
+ f" H_variance : {np.var(traj):.6f}\n"
359
+ f" H_max : {np.max(traj):.5f}\n"
360
+ f" H_min : {np.min(traj):.5f}\n"
361
+ f"───────────────────────────────────────────\n"
362
+ f" Lyapunov λ : {lam:.6f}\n"
363
+ f" Phase : {phase}\n"
364
+ f" Attractor : {att}\n"
365
+ f"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
366
+ )
367
+ return fig, stats
368
+
369
+
370
+ def run_bifurcation_tab(H_0_init, gamma, beta, sigma_noise):
371
+ return plot_bifurcation(float(H_0_init), float(gamma), float(beta), float(sigma_noise))
372
+
373
+
374
+ def update_history(existing, new_row):
375
+ import pandas as pd
376
+ cols = ["t", "dH", "mse", "H_peak", "Classification", "Hash"]
377
+ if not new_row or len(new_row) == 0:
378
+ return existing
379
+ if existing is None or len(existing) == 0:
380
+ return pd.DataFrame([new_row], columns=cols)
381
+ df = pd.DataFrame(existing, columns=cols)
382
+ df.loc[len(df)] = new_row
383
+ return df
384
+
385
+
386
+ # ══════════════════════════════════════════════════════════════════════════════
387
+ # UI
388
+ # ══════════════════════════════════════════════════════════════════════════════
389
+
390
+ FONT_INJECT = """
391
+ <style>
392
+ @import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700;900&family=Space+Mono:wght@400;700&display=swap');
393
+
394
+ /* Scanline overlay */
395
+ .gradio-container::after {
396
+ content: '';
397
+ position: fixed;
398
+ inset: 0;
399
+ background: repeating-linear-gradient(
400
+ 0deg, transparent, transparent 2px,
401
+ rgba(0,255,255,0.010) 2px, rgba(0,255,255,0.010) 4px
402
+ );
403
+ pointer-events: none;
404
+ z-index: 9999;
405
+ }
406
 
407
+ /* Circuit grid background */
408
  .gradio-container {
409
+ background:
410
+ linear-gradient(rgba(0,255,255,0.022) 1px, transparent 1px),
411
+ linear-gradient(90deg, rgba(0,255,255,0.022) 1px, transparent 1px),
412
+ radial-gradient(ellipse at 25% 15%, #0e003a 0%, transparent 50%),
413
+ radial-gradient(ellipse at 80% 85%, #000a2a 0%, transparent 50%),
414
+ #050010 !important;
415
+ background-size: 64px 64px, 64px 64px, auto, auto, auto !important;
416
+ font-family: 'Space Mono', 'Courier New', monospace !important;
417
+ color: #c8c8ff !important;
418
+ }
419
+
420
+ @keyframes prime-pulse {
421
+ 0%,100% { text-shadow: 0 0 8px #00ffff, 0 0 20px #00ffff, 0 0 40px #00aaff; }
422
+ 50% { text-shadow: 0 0 20px #00ffff, 0 0 55px #00ffff, 0 0 90px #0066ff; }
423
  }
424
  h1 {
425
+ font-family: 'Orbitron', monospace !important;
426
+ color: #00ffff !important;
427
+ animation: prime-pulse 3.5s ease-in-out infinite;
428
+ text-align: center; text-transform: uppercase;
429
+ letter-spacing: 6px; font-size: 2.6rem !important;
430
+ }
431
+
432
+ @keyframes mag-pulse {
433
+ 0%,100% { text-shadow: 0 0 8px #ff00ff, 0 0 18px #ff00ff; opacity:.9; }
434
+ 50% { text-shadow: 0 0 22px #ff00ff, 0 0 44px #cc00cc; opacity:1; }
435
  }
436
  .subtitle {
437
+ font-family: 'Orbitron', monospace !important;
438
+ color: #ff00ff !important;
439
+ animation: mag-pulse 4s ease-in-out infinite;
440
+ text-align: center; font-size: .8rem;
441
+ letter-spacing: 5px; margin-bottom: 22px;
442
+ }
443
+
444
+ .form, .panel, .block {
445
+ background: rgba(5,0,20,.88) !important;
446
+ border: 1px solid rgba(0,255,255,.17) !important;
447
+ box-shadow: 0 0 20px rgba(0,255,255,.06), inset 0 0 35px rgba(0,0,0,.5) !important;
448
+ border-radius: 8px !important;
449
+ }
450
+
451
+ label, .label-wrap span {
452
+ font-family: 'Orbitron', monospace !important;
453
+ color: #6688bb !important; font-size: .70rem !important;
454
+ letter-spacing: 1.5px !important; text-transform: uppercase !important;
455
  }
456
+
457
+ .prose h3 {
458
+ font-family: 'Orbitron', monospace !important;
459
+ color: #00ffff !important; letter-spacing: 2px;
460
+ }
461
+ .prose p, .prose li {
462
+ font-family: 'Space Mono', monospace !important;
463
+ color: #7788aa !important; font-size: .78rem !important;
464
+ line-height: 1.75 !important;
465
+ }
466
+ code {
467
+ color: #ff00ff !important;
468
+ background: rgba(255,0,255,.09) !important;
469
+ border-radius: 3px !important; padding: 1px 4px !important;
470
+ }
471
+
472
+ @keyframes btn-glow {
473
+ 0%,100% { box-shadow: 0 0 14px #ff00ff, 0 0 28px rgba(255,0,255,.3); }
474
+ 50% { box-shadow: 0 0 28px #00ffff, 0 0 56px rgba(0,255,255,.3); }
475
  }
476
+ button.primary, button[variant="primary"] {
477
+ background: linear-gradient(135deg, #ff00ff 0%, #4400ff 50%, #00ffff 100%) !important;
478
+ border: none !important; color: #000 !important;
479
+ font-family: 'Orbitron', monospace !important; font-weight: 900 !important;
480
+ font-size: .82rem !important; letter-spacing: 3px !important;
481
+ text-transform: uppercase !important;
482
+ animation: btn-glow 2.5s ease-in-out infinite !important;
483
+ transition: transform .2s cubic-bezier(.34,1.56,.64,1) !important;
484
+ border-radius: 6px !important;
485
  }
486
+ button.primary:hover, button[variant="primary"]:hover {
487
+ transform: scale(1.04) translateY(-2px) !important;
 
 
 
488
  }
489
+
490
+ textarea, input[type="text"], input[type="number"] {
491
+ background: rgba(0,4,22,.92) !important;
492
+ border: 1px solid rgba(0,255,255,.22) !important;
493
+ color: #00ffff !important;
494
+ font-family: 'Space Mono', monospace !important;
495
+ border-radius: 4px !important;
496
+ }
497
+
498
+ .tab-nav button {
499
+ font-family: 'Orbitron', monospace !important;
500
+ color: #445566 !important; font-size: .68rem !important;
501
+ letter-spacing: 1.5px !important; text-transform: uppercase !important;
502
+ border-bottom: 2px solid transparent !important;
503
+ transition: all .2s ease !important;
504
+ }
505
+ .tab-nav button.selected {
506
+ color: #00ffff !important;
507
+ border-bottom: 2px solid #00ffff !important;
508
+ text-shadow: 0 0 8px #00ffff !important;
509
+ }
510
+
511
+ input[type="range"]::-webkit-slider-thumb {
512
+ background: #00ffff !important; box-shadow: 0 0 8px #00ffff !important;
513
+ }
514
+ input[type="range"]::-webkit-slider-runnable-track {
515
+ background: linear-gradient(90deg,#00ffff,#ff00ff) !important; height:3px !important;
516
+ }
517
+
518
+ .number input { color: #ff00ff !important; font-size: 1.25rem !important; font-weight: 700 !important; }
519
+ </style>
520
  """
521
 
522
+ with gr.Blocks(title="ZKAEDI TENSOR: Prime") as iface:
523
+
524
+ gr.HTML(FONT_INJECT)
525
  gr.Markdown("# 🌌 ZKAEDI TENSOR 🌌")
526
+ gr.HTML("<div class='subtitle'>L E G E N D A R Y &nbsp;·&nbsp; P R I M E &nbsp;·&nbsp; H A M I L T O N I A N &nbsp;·&nbsp; T H R E A T &nbsp;·&nbsp; I S O L A T I O N</div>")
527
 
528
  with gr.Tabs():
529
+
530
+ # ── TAB 1 — INFERENCE ────────────────────────────────────────────────
531
+ with gr.TabItem("⚙️ INFERENCE"):
532
  with gr.Row():
533
  with gr.Column(scale=1):
534
  gr.Markdown("### 📡 QUANTUM INPUT MATRIX")
535
+ gr.Markdown("Raw telemetry vectors feed the Hamiltonian tensor array.")
536
+ t_in = gr.Slider(0.0, 100.0, value=12.5, step=0.1, label="T-Vector (t)")
537
+ dh_in = gr.Slider(-10.0, 10.0, value=0.1, step=0.01, label="Hamiltonian Shift (dH)")
538
+ ms_in = gr.Slider(0.0, 10.0, value=0.5, step=0.01, label="MSE Variance (mse)")
539
+
540
+ gr.Markdown("### 🔱 PRIME EVOLUTION PARAMETERS")
541
+ eta_s = gr.Slider(0.01, 0.99, value=0.40, step=0.01, label="η — Feedback Coupling")
542
+ gam_s = gr.Slider(0.01, 2.0, value=0.30, step=0.01, label="γ — Sigmoid Sharpness")
543
+ bet_s = gr.Slider(0.0, 1.0, value=0.10, step=0.01, label="β — Noise Amplitude Scale")
544
+ sig_s = gr.Slider(0.0, 0.5, value=0.05, step=0.005, label="σ — Base Noise")
545
+ stp_s = gr.Slider(10, 500, value=100, step=10, label="PRIME Steps (pre-inference)")
546
+
547
+ gr.Markdown("#### ⚡ PRE-COMPUTED VECTORS")
548
  gr.Examples(
549
  examples=[
550
+ [12.5, 0.10, 0.5, 0.40, 0.30, 0.10, 0.05, 100],
551
+ [45.0, 5.00, 1.2, 0.65, 0.50, 0.20, 0.10, 150],
552
+ [89.0, -8.20, 4.2, 0.85, 0.80, 0.40, 0.20, 200],
553
+ [90.0, 10.00, 9.9, 0.95, 1.20, 0.60, 0.30, 300],
554
  ],
555
+ inputs=[t_in, dh_in, ms_in, eta_s, gam_s, bet_s, sig_s, stp_s],
556
  label="Inject Saved Telemetry"
557
  )
558
+ btn_inf = gr.Button("⚡ INITIATE TRANSCENDENCE ⚡", variant="primary")
 
559
 
560
  with gr.Column(scale=1):
561
  gr.Markdown("### 🧠 SENSORY DECODER OUTPUT")
562
+ warn_o = gr.Textbox(label="Threat Status", lines=2)
563
+ phase_o = gr.Textbox(label="PRIME Phase State", lines=1)
564
  with gr.Row():
565
+ h_o = gr.Number(label="Peak H")
566
+ lyap_o = gr.Number(label="Lyapunov λ")
567
+ hash_o = gr.Textbox(label="🔏 Quantum Seed Hash", lines=1)
568
+ raw_o = gr.Textbox(label="Tensor Token Decode", lines=2)
569
+ aud_o = gr.Audio(label="Hamiltonian Resonance", type="numpy")
570
+
571
+ with gr.Row():
572
+ p3d_o = gr.Plot(label="3D Phase Portrait — H × dH/dt × t")
573
+ pen_o = gr.Plot(label="PRIME Field Evolution — H_t & Velocity")
574
+
575
+ # ── TAB 2 — PRIME FIELD ──────────────────────────────────────────────
576
+ with gr.TabItem("🔱 PRIME FIELD"):
577
+ gr.Markdown("### 🔱 PURE PRIME FIELD DYNAMICS")
578
+ gr.Markdown(
579
+ "Run the recursive Hamiltonian in isolation — no model, no GPU. "
580
+ "Explore attractors, Lyapunov exponents, and phase transitions."
581
+ )
582
+ with gr.Row():
583
+ with gr.Column(scale=1):
584
+ H0_f = gr.Slider(-5.0, 5.0, value=round(H_0_raw_val, 3), step=0.01, label="H_0 (initial energy)")
585
+ eta_f = gr.Slider(0.01, 0.99, value=0.40, step=0.01, label="η — Feedback")
586
+ gam_f = gr.Slider(0.01, 3.0, value=0.30, step=0.01, label="γ — Sigmoid")
587
+ bet_f = gr.Slider(0.0, 1.0, value=0.10, step=0.01, label="β — Noise Scale")
588
+ sig_f = gr.Slider(0.0, 0.5, value=0.05, step=0.005, label="σ — Base Noise")
589
+ stp_f = gr.Slider(50, 1000, value=200, step=50, label="Steps")
590
+ btn_fld = gr.Button("🔱 EVOLVE FIELD", variant="primary")
591
+ with gr.Column(scale=1):
592
+ stats_o = gr.Textbox(label="PRIME Field Statistics", lines=20, max_lines=22)
593
+ pfld_o = gr.Plot(label="H_t Trajectory + Velocity Field")
594
+
595
+ # ── TAB 3 — BIFURCATION ─────────────────────────────────────────────
596
+ with gr.TabItem("🌀 BIFURCATION"):
597
+ gr.Markdown("### 🌀 BIFURCATION DIAGRAM")
598
+ gr.Markdown(
599
+ "Sweep **η** from 0 → 1 and reveal the period-doubling cascade "
600
+ "leading to chaos. Set `σ > 0` to smear bifurcation boundaries with noise."
601
+ )
602
+ with gr.Row():
603
+ with gr.Column(scale=1):
604
+ H0_b = gr.Slider(-5.0, 5.0, value=round(H_0_raw_val, 3), step=0.01, label="H_0")
605
+ gam_b = gr.Slider(0.01, 3.0, value=0.30, step=0.01, label="γ — Sigmoid")
606
+ bet_b = gr.Slider(0.0, 1.0, value=0.10, step=0.01, label="β — Noise Scale")
607
+ sig_b = gr.Slider(0.0, 0.3, value=0.00, step=0.005, label="σ — Noise Injection")
608
+ btn_bif = gr.Button("🌀 COMPUTE BIFURCATION", variant="primary")
609
+ gr.Markdown("_Sweeps 350 η values × 260 iters each — runs on CPU, ~5–10s._")
610
+ with gr.Column(scale=2):
611
+ bif_o = gr.Plot(label="Bifurcation Diagram — H*(η)")
612
+
613
+ # ── TAB 4 — LOGS ────────────────────────────────────────────────────
614
+ with gr.TabItem("📜 LOGS"):
615
+ gr.Markdown("### 🗃️ TENSOR STATE LEDGER")
616
+ gr.Markdown("Full history of all inference queries and their Hamiltonian classifications.")
617
+ hist_df = gr.Dataframe(
618
+ headers=["t", "dH", "mse", "H_peak", "Classification", "Hash"],
619
+ datatype=["number","number","number","number","str","str"],
620
  column_count=(6, "fixed"),
621
+ interactive=False,
622
  )
623
 
 
 
 
 
 
 
 
 
 
624
  gr.Markdown("---")
625
+ gr.HTML(
626
+ "<div style='text-align:center;color:#2a2a4a;font-family:Space Mono,monospace;"
627
+ "font-size:.68rem;letter-spacing:1.5px;padding-bottom:12px;'>"
628
+ "WEIGHTS: <code>prime_epoch_010.pt</code> &nbsp;·&nbsp; "
629
+ "TOKENIZER: <code>microsoft/codebert-base</code> &nbsp;·&nbsp; "
630
+ "RUNTIME: <code>ZeroGPU H100</code> &nbsp;·&nbsp; "
631
+ "PRIME: <code>H_t = H_0 + η·H_{t-1}·σ(γ·H_{t-1}) + σ·N(0, 1+β|H_{t-1}|)</code>"
632
+ "</div>"
633
+ )
634
 
635
+ # ── Wire-up ────────────────────────────────────────────────────────────────
636
+ hidden = gr.State([])
637
 
638
+ btn_inf.click(
639
  fn=predict_anomaly,
640
+ inputs=[t_in, dh_in, ms_in, eta_s, gam_s, bet_s, sig_s, stp_s],
641
+ outputs=[raw_o, h_o, warn_o, p3d_o, pen_o, lyap_o, phase_o, aud_o, hash_o, hidden]
642
  ).then(
643
  fn=update_history,
644
+ inputs=[hist_df, hidden],
645
+ outputs=[hist_df]
646
  )
647
 
648
+ btn_fld.click(
649
+ fn=analyze_prime_field,
650
+ inputs=[H0_f, eta_f, gam_f, bet_f, sig_f, stp_f],
651
+ outputs=[pfld_o, stats_o]
652
+ )
653
+
654
+ btn_bif.click(
655
+ fn=run_bifurcation_tab,
656
+ inputs=[H0_b, gam_b, bet_b, sig_b],
657
+ outputs=[bif_o]
658
+ )
659
+
660
+
661
  if __name__ == "__main__":
662
  iface.launch(server_name="0.0.0.0", server_port=7860, share=False)