import os import torch import gradio as gr import torch.nn as nn import torch.nn.functional as F import matplotlib.pyplot as plt import numpy as np import hashlib from transformers import AutoTokenizer import spaces # ══════════════════════════════════════════════════════════════════════════════ # ARCHITECTURE # ══════════════════════════════════════════════════════════════════════════════ class ZkaediTransformerBlock(nn.Module): def __init__(self, d_model: int, n_heads: int, dropout: float, ffn_mult: int = 4): super().__init__() self.norm1 = nn.LayerNorm(d_model) self.n_heads = n_heads self.d_head = d_model // n_heads self.scale = self.d_head ** -0.5 self.qkv = nn.Linear(d_model, d_model * 3, bias=False) self.proj = nn.Linear(d_model, d_model) self.attn_dropout = nn.Dropout(dropout) self.norm2 = nn.LayerNorm(d_model) self.ffn = nn.Sequential( nn.Linear(d_model, d_model * ffn_mult, bias=False), nn.GELU(), nn.Dropout(dropout), nn.Linear(d_model * ffn_mult, d_model, bias=False), ) def forward(self, x, h_bias, causal_mask): B, T, C = x.shape residual = x x_norm = self.norm1(x) q, k, v = self.qkv(x_norm).chunk(3, dim=-1) q, k, v = [t.view(B, T, self.n_heads, self.d_head).transpose(1, 2) for t in (q, k, v)] attn_logits = (q @ k.transpose(-2, -1)) * self.scale attn_logits = attn_logits.masked_fill(causal_mask[:T, :T], float('-inf')) attn_logits = attn_logits + h_bias # (B, n_heads, 1, 1) attn_weights = self.attn_dropout(F.softmax(attn_logits, dim=-1)) attn_out = (attn_weights @ v).transpose(1, 2).contiguous().view(B, T, C) x = residual + self.proj(attn_out) x = x + self.ffn(self.norm2(x)) return x class ZkaediAttentionCore(nn.Module): def __init__(self, vocab_size: int, d_model: int = 256, n_heads: int = 8, n_layers: int = 2, dropout: float = 0.1, max_seq_len: int = 128): super().__init__() self.n_heads = n_heads self.d_model = d_model self.embedding = nn.Embedding(vocab_size, d_model) self.pos_embedding = nn.Embedding(max_seq_len, d_model) self.drop = nn.Dropout(dropout) self.blocks = nn.ModuleList([ ZkaediTransformerBlock(d_model, n_heads, dropout) for _ in range(n_layers) ]) self.norm_final = nn.LayerNorm(d_model) self.lm_head = nn.Linear(d_model, vocab_size, bias=False) self.lm_head.weight = self.embedding.weight self.chaos_head = nn.Linear(d_model, 1) causal = torch.triu(torch.ones(max_seq_len, max_seq_len, dtype=torch.bool), diagonal=1) self.register_buffer('causal_mask', causal, persistent=False) def forward(self, input_ids, h_bias): B, T = input_ids.shape positions = torch.arange(T, device=input_ids.device).unsqueeze(0) x = self.drop(self.embedding(input_ids) + self.pos_embedding(positions)) for block in self.blocks: x = block(x, h_bias, self.causal_mask) x_final = self.norm_final(x) logits = self.lm_head(x_final) chaos_score = torch.sigmoid(self.chaos_head(x_final[:, 0, :])).squeeze(-1) return logits, chaos_score # ══════════════════════════════════════════════════════════════════════════════ # ZKAEDI PRIME MATHEMATICS # ══════════════════════════════════════════════════════════════════════════════ def run_prime_evolution(H_0_val: float, eta: float, gamma: float, beta: float, sigma: float, steps: int = 100) -> np.ndarray: """H_t = H_0 + η·H_{t-1}·σ(γ·H_{t-1}) + σ·N(0, 1+β|H_{t-1}|)""" H = H_0_val traj = [H] for _ in range(steps): sig = 1.0 / (1.0 + np.exp(-gamma * float(np.clip(H, -50, 50)))) noise = np.random.normal(0.0, 1.0 + beta * abs(H)) H = H_0_val + eta * H * sig + sigma * noise H = float(np.tanh(H / 12.0) * 12.0) traj.append(H) return np.array(traj) def compute_lyapunov(traj: np.ndarray, H_0_val: float, eta: float, gamma: float) -> float: """λ = (1/N) Σ log|dF/dH| where dF/dH = η·σ·(1 + γ·H·(1−σ))""" lyap, count = 0.0, 0 for H in traj[:-1]: sig = 1.0 / (1.0 + np.exp(-gamma * float(np.clip(H, -50, 50)))) deriv = abs(eta * sig * (1.0 + gamma * H * (1.0 - sig))) if deriv > 1e-14: lyap += np.log(deriv) count += 1 return lyap / count if count > 0 else -999.0 def classify_phase(lyapunov: float, traj: np.ndarray) -> tuple: tail_var = float(np.var(traj[-50:] if len(traj) >= 50 else traj)) if lyapunov > 0.50: return "⚡ LEGEND", "#ff00ff" elif lyapunov > 0.05: return "🔥 CHAOTIC", "#ff3333" elif lyapunov > -0.05:return "🌀 BIFURCATING", "#ff8800" elif lyapunov > -0.25:return "〰️ WANDERING", "#ffff00" elif tail_var < 0.02: return "🎯 CONVERGING", "#00ff88" else: return "🔷 INITIALIZING", "#00ccff" # ══════════════════════════════════════════════════════════════════════════════ # CHECKPOINT LOADING # ══════════════════════════════════════════════════════════════════════════════ device = torch.device("cuda" if torch.cuda.is_available() else "cpu") tokenizer = AutoTokenizer.from_pretrained("microsoft/codebert-base") if tokenizer.pad_token is None: tokenizer.add_special_tokens({'pad_token': '[PAD]'}) model = None H_0_raw_val = 0.7311 ckpt_path = "prime_epoch_010.pt" if os.path.exists(ckpt_path): ckpt = torch.load(ckpt_path, map_location=device, weights_only=True) vocab_size = ckpt.get('vocab_size', len(tokenizer)) model = ZkaediAttentionCore(vocab_size=vocab_size).to(device) missing, _ = model.load_state_dict(ckpt['model_state_dict'], strict=False) if missing: print(f"ℹ️ Fresh init: {missing}") model.eval() hs = ckpt['hamiltonian_state'] H_0_raw = hs['H_0'].to(device) H_0_raw_val = float(H_0_raw.mean().item() if H_0_raw.numel() > 1 else H_0_raw.item()) print(f"✅ prime_epoch_010.pt | vocab={vocab_size} | H_0={H_0_raw_val:.4f}") else: print("❌ prime_epoch_010.pt not found — PRIME-only mode active") # ══════════════════════════════════════════════════════════════════════════════ # PLOT HELPERS # ══════════════════════════════════════════════════════════════════════════════ _BG, _CYAN, _MAG, _WHT, _GRID = '#050010', '#00ffff', '#ff00ff', '#e8e8ff', '#111133' def _neon(ax, x, y, color, lw=1.0, layers=8): for i in range(layers, 0, -1): ax.plot(x, y, color=color, alpha=0.016 * i, linewidth=lw * i * 1.5) ax.plot(x, y, color=color, linewidth=lw, alpha=0.95) def _style(ax, title='', tc=_CYAN, xl='', yl='', ylc=_CYAN): ax.set_facecolor(_BG) ax.set_title(title, color=tc, fontsize=10, fontweight='bold', pad=7) ax.set_xlabel(xl, color='#556677', fontsize=8) ax.set_ylabel(yl, color=ylc, fontsize=8) ax.tick_params(colors='#445566', labelsize=7) for sp in ax.spines.values(): sp.set_color('#222244') ax.grid(color=_GRID, alpha=0.55, linewidth=0.5) def plot_energy_evolution(traj, lam, phase, pc): fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 6), facecolor=_BG) fig.subplots_adjust(hspace=0.5, top=0.93, bottom=0.09) steps = np.arange(len(traj)) _neon(ax1, steps, traj, _CYAN, lw=1.2, layers=10) ax1.fill_between(steps, traj, alpha=0.06, color=_CYAN) ax1.axhline(0, color=_WHT, alpha=0.12, lw=0.6, ls='--') _style(ax1, title=f"PRIME H_t λ={lam:.5f} {phase}", tc=pc, xl="t", yl="H_t") dH = np.diff(traj) _neon(ax2, steps[1:], dH, _MAG, lw=1.0, layers=8) ax2.fill_between(steps[1:], dH, alpha=0.05, color=_MAG) ax2.axhline(0, color=_WHT, alpha=0.12, lw=0.6, ls='--') _style(ax2, title="Velocity dH/dt", tc=_MAG, xl="t", yl="dH/dt", ylc=_MAG) fig.patch.set_facecolor(_BG) return fig def plot_bifurcation(H_0_val, gamma, beta, sigma_noise): fig, ax = plt.subplots(figsize=(9, 5), facecolor=_BG) ax.set_facecolor(_BG) eta_vals = np.linspace(0.01, 0.97, 350) all_eta, all_h = [], [] for eta in eta_vals: H = H_0_val for _ in range(180): sig = 1.0 / (1.0 + np.exp(-gamma * float(np.clip(H, -50, 50)))) H = H_0_val + eta * H * sig H = float(np.tanh(H / 12.0) * 12.0) for _ in range(80): sig = 1.0 / (1.0 + np.exp(-gamma * float(np.clip(H, -50, 50)))) H = H_0_val + eta * H * sig + sigma_noise * np.random.normal(0, 1 + beta * abs(H)) H = float(np.tanh(H / 12.0) * 12.0) all_eta.append(eta); all_h.append(H) ax.scatter(all_eta, all_h, c=_CYAN, s=0.25, alpha=0.4, linewidths=0) y_range = (max(all_h) - min(all_h)) if all_h else 2.0 ax.axvline(x=0.70, color=_MAG, alpha=0.35, lw=0.9, ls='--') ax.text(0.715, min(all_h) + y_range * 0.88 if all_h else 1, 'chaos\nonset', color=_MAG, fontsize=7, alpha=0.75) _style(ax, title="PRIME Bifurcation H*(η) — Period-Doubling & Chaos Onset", xl="η (feedback coupling)", yl="H* (attractor)") fig.patch.set_facecolor(_BG) fig.tight_layout() return fig def plot_phase_portrait_3d(h_peak, time_step, mse_error, dh_variance, is_chaos): fig = plt.figure(figsize=(7, 5), facecolor=_BG) ax = fig.add_subplot(111, projection='3d') ax.set_facecolor(_BG) for p in [ax.xaxis, ax.yaxis, ax.zaxis]: p.set_pane_color((0, 0, 0, 0)) ax.grid(color=_GRID, alpha=0.22) t_vals = np.linspace(0, time_step + 10, 600) H_vals = (h_peak * 0.5) * np.sin(t_vals * 0.8 + dh_variance) + mse_error * 5.0 * np.cos(t_vals * 2.1) dH_vals = np.gradient(H_vals, t_vals) gc = '#ff0044' if is_chaos else _MAG for g in range(1, 10): ax.plot3D(H_vals, dH_vals, t_vals, color=gc, alpha=0.02, linewidth=g * 2.0) ax.plot3D(H_vals, dH_vals, t_vals, color=_WHT, alpha=0.8, linewidth=0.7) ax.scatter3D(H_vals, dH_vals, t_vals, c=t_vals, cmap='cool', s=6, alpha=0.6, zorder=3) n, sc = len(H_vals), max(mse_error * 0.25, 0.04) ax.scatter3D(H_vals + np.random.normal(0, sc, n), dH_vals + np.random.normal(0, sc, n), t_vals + np.random.normal(0, sc, n), color=_CYAN, s=1.2, alpha=0.25, zorder=2) if is_chaos: ax.scatter3D(H_vals[-1], dH_vals[-1], t_vals[-1], color='#ff0000', s=200, marker='X', edgecolors=_WHT, zorder=5) ax.set_title(f"CHAOS H={h_peak:.2f}", color='#ff2244', fontsize=11, fontweight='bold') else: ax.scatter3D(H_vals[-1], dH_vals[-1], t_vals[-1], color=_CYAN, s=140, marker='o', edgecolors=_WHT, zorder=5) ax.set_title("H ↔ dH/dt ↔ t", color=_CYAN, fontsize=10) ax.set_xlabel("H", color=_MAG, fontsize=8) ax.set_ylabel("dH/dt", color=_CYAN, fontsize=8) ax.set_zlabel("t", color='#aaaacc', fontsize=8) ax.tick_params(colors='#444466', labelsize=7) fig.patch.set_facecolor(_BG) return fig # ══════════════════════════════════════════════════════════════════════════════ # GRADIO FUNCTIONS # ══════════════════════════════════════════════════════════════════════════════ @spaces.GPU def predict_anomaly(time_step, dh_variance, mse_error, eta, gamma, beta, sigma, prime_steps): if model is None: ef = plt.figure(facecolor=_BG) plt.text(0.5, 0.5, '❌ No checkpoint', ha='center', va='center', color=_CYAN, fontsize=14, transform=plt.gca().transAxes) plt.close() return ("❌ Missing prime_epoch_010.pt", 0.0, "UNKNOWN", ef, ef, -999.0, "UNKNOWN", None, "N/A", []) # 1. Run PRIME evolution traj = run_prime_evolution(H_0_raw_val, float(eta), float(gamma), float(beta), float(sigma), int(prime_steps)) lam = compute_lyapunov(traj, H_0_raw_val, float(eta), float(gamma)) phase, pc = classify_phase(lam, traj) H_evolved = float(traj[-1]) # 2. Evolved attention bias → (B, n_heads, 1, 1) hv = torch.tensor(float(np.tanh(H_evolved / 5.0)), dtype=torch.float32, device=device) h_bias = torch.sigmoid(hv).view(1,1,1,1).expand(1, model.n_heads, 1,1).contiguous() # 3. Inference text = (f"Instruction: Analyze quantum telemetry and predict Hamiltonian chaos bounds. " f"| Context: t:{time_step:.2f} dH:{dh_variance:.4f} mse:{mse_error:.4f} " f"Ht:{H_evolved:.4f} lambda:{lam:.4f} | Target: ") enc = tokenizer(text, return_tensors='pt', max_length=128, truncation=True).to(device) with torch.no_grad(): logits, chaos_score = model(enc['input_ids'], h_bias) pred_ids = torch.argmax(logits, dim=-1) output_text = tokenizer.decode(pred_ids[0], skip_special_tokens=True) # 4. Threat classification is_chaos = (chaos_score.item() > 0.5) or (mse_error > 2.0) or (lam > 0.05) if is_chaos: warning = "🚨 CRITICAL CHAOS ANOMALY DETECTED" h_peak = 428.99 + mse_error * 10.0 + abs(H_evolved * 2.0) else: warning = "✅ SYSTEM STABLE" h_peak = 1.0 + abs(dh_variance) + abs(H_evolved * 0.5) # 5. Plots fig_3d = plot_phase_portrait_3d(h_peak, time_step, mse_error, dh_variance, is_chaos) fig_en = plot_energy_evolution(traj, lam, phase, pc) # 6. Audio sr = 44100 ta = np.linspace(0, 1.0, sr) bf = 110.0 + h_peak * 1.5 if is_chaos: aud = np.sign(np.sin(2 * np.pi * bf * ta)) + np.random.uniform(-0.8, 0.8, sr) else: aud = np.sin(2*np.pi*bf*ta)*0.5 + np.sin(2*np.pi*(bf*1.5)*ta)*0.2 aud = np.int16(np.clip(aud, -1.0, 1.0) * 32767) # 7. Hash seed = f"T:{time_step}|dH:{dh_variance}|MSE:{mse_error}|Ht:{H_evolved:.4f}|λ:{lam:.6f}|ZKAEDI" chash = hashlib.sha256(seed.encode()).hexdigest() entry = [time_step, dh_variance, mse_error, round(h_peak, 2), "CHAOS" if is_chaos else "STABLE", f"0x{chash[:12]}..."] try: import csv lf, new = "zkaedi_telemetry_ledger.csv", not os.path.exists("zkaedi_telemetry_ledger.csv") with open(lf, 'a', newline='') as f: w = csv.writer(f) if new: w.writerow(["t","dH","mse","H_peak","class","hash"]) w.writerow(entry) except Exception as e: print(f"CSV: {e}") return (output_text, h_peak, warning, fig_3d, fig_en, round(lam, 6), phase, (sr, aud), f"0x{chash}", entry) def analyze_prime_field(H_0_init, eta, gamma, beta, sigma, steps): traj = run_prime_evolution(float(H_0_init), float(eta), float(gamma), float(beta), float(sigma), int(steps)) lam = compute_lyapunov(traj, float(H_0_init), float(eta), float(gamma)) phase, pc = classify_phase(lam, traj) fig = plot_energy_evolution(traj, lam, phase, pc) tv = float(np.var(traj[-50:])) if lam > 0.3: att = "Strange Attractor / Chaos" elif lam > -0.05:att = "Limit Cycle / Period-Doubling" elif tv < 0.01: att = "Fixed-Point Attractor" else: att = "Quasi-Periodic / Transient" stats = ( f"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n" f" ZKAEDI PRIME — Field Statistics\n" f"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n" f" H_0 : {H_0_init:.4f}\n" f" η (eta) : {eta:.3f}\n" f" γ (gamma) : {gamma:.3f}\n" f" β (beta) : {beta:.3f}\n" f" σ (sigma) : {sigma:.4f}\n" f" Steps : {int(steps)}\n" f"───────────────────────────────────────────\n" f" H_final : {traj[-1]:.5f}\n" f" H_mean : {np.mean(traj):.5f}\n" f" H_variance : {np.var(traj):.6f}\n" f" H_max : {np.max(traj):.5f}\n" f" H_min : {np.min(traj):.5f}\n" f"───────────────────────────────────────────\n" f" Lyapunov λ : {lam:.6f}\n" f" Phase : {phase}\n" f" Attractor : {att}\n" f"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" ) return fig, stats def run_bifurcation_tab(H_0_init, gamma, beta, sigma_noise): return plot_bifurcation(float(H_0_init), float(gamma), float(beta), float(sigma_noise)) def update_history(existing, new_row): import pandas as pd cols = ["t", "dH", "mse", "H_peak", "Classification", "Hash"] if not new_row or len(new_row) == 0: return existing if existing is None or len(existing) == 0: return pd.DataFrame([new_row], columns=cols) df = pd.DataFrame(existing, columns=cols) df.loc[len(df)] = new_row return df # ══════════════════════════════════════════════════════════════════════════════ # UI # ══════════════════════════════════════════════════════════════════════════════ FONT_INJECT = """ """ with gr.Blocks(title="ZKAEDI TENSOR: Prime") as iface: gr.HTML(FONT_INJECT) gr.Markdown("# 🌌 ZKAEDI TENSOR 🌌") gr.HTML("
L E G E N D A R Y  ·  P R I M E  ·  H A M I L T O N I A N  ·  T H R E A T  ·  I S O L A T I O N
") with gr.Tabs(): # ── TAB 1 — INFERENCE ──────────────────────────────────────────────── with gr.TabItem("⚙️ INFERENCE"): with gr.Row(): with gr.Column(scale=1): gr.Markdown("### 📡 QUANTUM INPUT MATRIX") gr.Markdown("Raw telemetry vectors feed the Hamiltonian tensor array.") t_in = gr.Slider(0.0, 100.0, value=12.5, step=0.1, label="T-Vector (t)") dh_in = gr.Slider(-10.0, 10.0, value=0.1, step=0.01, label="Hamiltonian Shift (dH)") ms_in = gr.Slider(0.0, 10.0, value=0.5, step=0.01, label="MSE Variance (mse)") gr.Markdown("### 🔱 PRIME EVOLUTION PARAMETERS") eta_s = gr.Slider(0.01, 0.99, value=0.40, step=0.01, label="η — Feedback Coupling") gam_s = gr.Slider(0.01, 2.0, value=0.30, step=0.01, label="γ — Sigmoid Sharpness") bet_s = gr.Slider(0.0, 1.0, value=0.10, step=0.01, label="β — Noise Amplitude Scale") sig_s = gr.Slider(0.0, 0.5, value=0.05, step=0.005, label="σ — Base Noise") stp_s = gr.Slider(10, 500, value=100, step=10, label="PRIME Steps (pre-inference)") gr.Markdown("#### ⚡ PRE-COMPUTED VECTORS") gr.Examples( examples=[ [12.5, 0.10, 0.5, 0.40, 0.30, 0.10, 0.05, 100], [45.0, 5.00, 1.2, 0.65, 0.50, 0.20, 0.10, 150], [89.0, -8.20, 4.2, 0.85, 0.80, 0.40, 0.20, 200], [90.0, 10.00, 9.9, 0.95, 1.20, 0.60, 0.30, 300], ], inputs=[t_in, dh_in, ms_in, eta_s, gam_s, bet_s, sig_s, stp_s], label="Inject Saved Telemetry" ) btn_inf = gr.Button("⚡ INITIATE TRANSCENDENCE ⚡", variant="primary") with gr.Column(scale=1): gr.Markdown("### 🧠 SENSORY DECODER OUTPUT") warn_o = gr.Textbox(label="Threat Status", lines=2) phase_o = gr.Textbox(label="PRIME Phase State", lines=1) with gr.Row(): h_o = gr.Number(label="Peak H") lyap_o = gr.Number(label="Lyapunov λ") hash_o = gr.Textbox(label="🔏 Quantum Seed Hash", lines=1) raw_o = gr.Textbox(label="Tensor Token Decode", lines=2) aud_o = gr.Audio(label="Hamiltonian Resonance", type="numpy") with gr.Row(): p3d_o = gr.Plot(label="3D Phase Portrait — H × dH/dt × t") pen_o = gr.Plot(label="PRIME Field Evolution — H_t & Velocity") # ── TAB 2 — PRIME FIELD ────────────────────────────────────────────── with gr.TabItem("🔱 PRIME FIELD"): gr.Markdown("### 🔱 PURE PRIME FIELD DYNAMICS") gr.Markdown( "Run the recursive Hamiltonian in isolation — no model, no GPU. " "Explore attractors, Lyapunov exponents, and phase transitions." ) with gr.Row(): with gr.Column(scale=1): H0_f = gr.Slider(-5.0, 5.0, value=round(H_0_raw_val, 3), step=0.01, label="H_0 (initial energy)") eta_f = gr.Slider(0.01, 0.99, value=0.40, step=0.01, label="η — Feedback") gam_f = gr.Slider(0.01, 3.0, value=0.30, step=0.01, label="γ — Sigmoid") bet_f = gr.Slider(0.0, 1.0, value=0.10, step=0.01, label="β — Noise Scale") sig_f = gr.Slider(0.0, 0.5, value=0.05, step=0.005, label="σ — Base Noise") stp_f = gr.Slider(50, 1000, value=200, step=50, label="Steps") btn_fld = gr.Button("🔱 EVOLVE FIELD", variant="primary") with gr.Column(scale=1): stats_o = gr.Textbox(label="PRIME Field Statistics", lines=20, max_lines=22) pfld_o = gr.Plot(label="H_t Trajectory + Velocity Field") # ── TAB 3 — BIFURCATION ───────────────────────────────────────────── with gr.TabItem("🌀 BIFURCATION"): gr.Markdown("### 🌀 BIFURCATION DIAGRAM") gr.Markdown( "Sweep **η** from 0 → 1 and reveal the period-doubling cascade " "leading to chaos. Set `σ > 0` to smear bifurcation boundaries with noise." ) with gr.Row(): with gr.Column(scale=1): H0_b = gr.Slider(-5.0, 5.0, value=round(H_0_raw_val, 3), step=0.01, label="H_0") gam_b = gr.Slider(0.01, 3.0, value=0.30, step=0.01, label="γ — Sigmoid") bet_b = gr.Slider(0.0, 1.0, value=0.10, step=0.01, label="β — Noise Scale") sig_b = gr.Slider(0.0, 0.3, value=0.00, step=0.005, label="σ — Noise Injection") btn_bif = gr.Button("🌀 COMPUTE BIFURCATION", variant="primary") gr.Markdown("_Sweeps 350 η values × 260 iters each — runs on CPU, ~5–10s._") with gr.Column(scale=2): bif_o = gr.Plot(label="Bifurcation Diagram — H*(η)") # ── TAB 4 — LOGS ──────────────────────────────────────────────────── with gr.TabItem("📜 LOGS"): gr.Markdown("### 🗃️ TENSOR STATE LEDGER") gr.Markdown("Full history of all inference queries and their Hamiltonian classifications.") hist_df = gr.Dataframe( headers=["t", "dH", "mse", "H_peak", "Classification", "Hash"], datatype=["number","number","number","number","str","str"], column_count=(6, "fixed"), interactive=False, ) gr.Markdown("---") gr.HTML( "
" "WEIGHTS: prime_epoch_010.pt  ·  " "TOKENIZER: microsoft/codebert-base  ·  " "RUNTIME: ZeroGPU H100  ·  " "PRIME: H_t = H_0 + η·H_{t-1}·σ(γ·H_{t-1}) + σ·N(0, 1+β|H_{t-1}|)" "
" ) # ── Wire-up ──────────────────────────────────────────────────────────────── hidden = gr.State([]) btn_inf.click( fn=predict_anomaly, inputs=[t_in, dh_in, ms_in, eta_s, gam_s, bet_s, sig_s, stp_s], outputs=[raw_o, h_o, warn_o, p3d_o, pen_o, lyap_o, phase_o, aud_o, hash_o, hidden] ).then( fn=update_history, inputs=[hist_df, hidden], outputs=[hist_df] ) btn_fld.click( fn=analyze_prime_field, inputs=[H0_f, eta_f, gam_f, bet_f, sig_f, stp_f], outputs=[pfld_o, stats_o] ) btn_bif.click( fn=run_bifurcation_tab, inputs=[H0_b, gam_b, bet_b, sig_b], outputs=[bif_o] ) if __name__ == "__main__": iface.launch(server_name="0.0.0.0", server_port=7860, share=False)