Spaces:
Running
Running
| """ | |
| METACOG -- Metacognitive Inference Monitoring | |
| Act 3: C2/C3 cognitive layers on top of Glossolalia. | |
| Glossolalia (fork/race/fold) vs Metacog (fork/race/fold + C2/C3). | |
| C2 detects entropy regime collapse. C3 breaks absorbing states | |
| via diversity perturbation. THM-META-CONVERGE (Lean 4 + TLA+). | |
| All inference via Aether WASM-SIMD engine. | |
| """ | |
| import gradio as gr | |
| import json | |
| import time | |
| import subprocess | |
| import urllib.request | |
| import urllib.error | |
| import select | |
| from concurrent.futures import ThreadPoolExecutor, as_completed | |
| print("[Metacog] Starting Aether...", flush=True) | |
| aether_proc = subprocess.Popen( | |
| ["node", "aether-server.mjs"], | |
| env={**__import__('os').environ, "AETHER_PORT": "7861"}, | |
| stdout=subprocess.PIPE, stderr=subprocess.STDOUT, | |
| ) | |
| print("[Metacog] Waiting for Aether...", flush=True) | |
| for attempt in range(180): | |
| try: | |
| req = urllib.request.Request("http://127.0.0.1:7861/health") | |
| resp = urllib.request.urlopen(req, timeout=2) | |
| health = json.loads(resp.read()) | |
| if health.get("status") == "ok" and health.get("models"): | |
| print(f"[Metacog] Aether ready (models: {health.get('models')}, SIMD: {health.get('simd')})", flush=True) | |
| break | |
| except Exception: | |
| pass | |
| if aether_proc.stdout and select.select([aether_proc.stdout], [], [], 0)[0]: | |
| line = aether_proc.stdout.readline() | |
| if line: | |
| print(f" {line.decode().strip()}", flush=True) | |
| time.sleep(1) | |
| else: | |
| print("[Metacog] WARNING: Aether not ready after 180s", flush=True) | |
| def call_aether(endpoint, prompt, max_tokens=128, model_name="buleyean"): | |
| try: | |
| data = json.dumps({"prompt": prompt, "max_tokens": max_tokens, "model": model_name}).encode() | |
| req = urllib.request.Request( | |
| f"http://127.0.0.1:7861/{endpoint}", data=data, | |
| headers={"Content-Type": "application/json"}, | |
| ) | |
| resp = urllib.request.urlopen(req, timeout=600) | |
| return json.loads(resp.read()) | |
| except urllib.error.HTTPError as e: | |
| body = e.read().decode() if e.fp else str(e) | |
| try: detail = json.loads(body).get("error", body[:300]) | |
| except Exception: detail = body[:300] | |
| return {"error": detail, "text": f"[Error: {detail}]", "tokens": 0, "totalTimeMs": 0, "avgTokenMs": 0} | |
| except Exception as e: | |
| return {"error": str(e), "text": f"[Error: {e}]", "tokens": 0, "totalTimeMs": 0, "avgTokenMs": 0} | |
| def format_metacog_diag(diag_list, metacog_summary): | |
| if not diag_list: | |
| return "No diagnostics." | |
| lines = ["METACOGNITIVE MONITORING (C0-C3)", "=" * 60, "", | |
| "C0: Compute | C1: NaN filter | C2: Entropy regime detection", | |
| "C3: Absorbing state perturbation (eta scales with repeat depth)", ""] | |
| if metacog_summary: | |
| lines.append(f"SUMMARY: {metacog_summary.get('totalPerturbations', 0)} C3 interventions applied") | |
| lines.append("") | |
| for step, d in enumerate(diag_list): | |
| if not isinstance(d, dict): continue | |
| ppl = d.get("perplexity", "?") | |
| me = d.get("mergedEntropy", "?") | |
| c3 = d.get("c3", {}) | |
| c3_str = "" | |
| if c3 and c3.get("perturbed"): | |
| c3_str = f" ** C3: {c3.get('reason')} eta={c3.get('eta',0):.2f} perturbation #{c3.get('perturbationCount',0)} **" | |
| lines.append(f"Token {step+1} | ppl={ppl} | H_merged={me}{c3_str}") | |
| for a in d.get("agents", []): | |
| if not isinstance(a, dict): continue | |
| top_str = ", ".join(f"'{t['token']}' ({t['prob']:.3f})" for t in a.get("top3", [])) | |
| lines.append(f" tau={a.get('tau','?'):.1f} | H={a.get('entropy',0):.3f} | w={a.get('weight',0):.3f} | {top_str}") | |
| lines.append("") | |
| return "\n".join(lines) | |
| def format_glossolalia_diag(diag_list): | |
| if not diag_list: | |
| return "No diagnostics." | |
| lines = ["GLOSSOLALIA (no metacog)", "=" * 60, ""] | |
| for step, d in enumerate(diag_list): | |
| if not isinstance(d, dict): continue | |
| ppl = d.get("perplexity", "?") | |
| vc = d.get("vocabCoverage", "?") | |
| lines.append(f"Token {step+1} | ppl={ppl} | vc={vc}") | |
| for a in d.get("agents", []): | |
| if not isinstance(a, dict): continue | |
| top_str = ", ".join(f"'{t['token']}' ({t['prob']:.3f})" for t in a.get("top3", [])) | |
| lines.append(f" tau={a.get('tau','?'):.1f} | H={a.get('entropy',0):.3f} | w={a.get('weight',0):.3f} | {top_str}") | |
| lines.append("") | |
| return "\n".join(lines) | |
| def format_layer_health(diag_list): | |
| if not diag_list: return "No layer data." | |
| last = diag_list[-1] if diag_list else {} | |
| if not isinstance(last, dict): return "No layer data." | |
| norms = last.get("layerNorms", []) | |
| if not norms: return "No layer norms." | |
| lines = ["LAYER HEALTH (last token)", "=" * 60, "Layer | Norm | Residual", "-" * 45] | |
| for i, n in enumerate(norms): | |
| if not isinstance(n, dict): continue | |
| bar = "#" * min(int(n.get("residual", 0) * 40), 40) | |
| lines.append(f" {i:2d} | {n.get('norm',0):9.2f} | {n.get('residual',0):.4f} {bar}") | |
| return "\n".join(lines) | |
| def compare(prompt, max_tokens, model_name): | |
| empty = ("", "", "", "", "", "", "") | |
| if not prompt or not prompt.strip(): | |
| yield empty | |
| return | |
| max_tokens = int(max_tokens) | |
| glo_result = [None] | |
| meta_result = [None] | |
| def run_glo(): | |
| glo_result[0] = call_aether("generate-glossolalia", prompt, max_tokens, model_name) | |
| def run_meta(): | |
| meta_result[0] = call_aether("generate-metacog", prompt, max_tokens, model_name) | |
| def fmt(r): | |
| if not r: return "running..." | |
| return f"{r['tokens']} tokens in {r['totalTimeMs']/1000:.1f}s ({r['avgTokenMs']}ms/tok)" | |
| def build(): | |
| gr_, mr = glo_result[0], meta_result[0] | |
| return ( | |
| gr_["text"] if gr_ else "generating...", | |
| mr["text"] if mr else "generating...", | |
| fmt(gr_), fmt(mr), | |
| format_glossolalia_diag(gr_.get("diagnostics", [])) if gr_ else "", | |
| format_metacog_diag(mr.get("diagnostics", []), mr.get("metacogSummary")) if mr else "", | |
| format_layer_health(mr.get("diagnostics", [])) if mr else "", | |
| ) | |
| with ThreadPoolExecutor(max_workers=2) as pool: | |
| futures = {pool.submit(run_glo): "glo", pool.submit(run_meta): "meta"} | |
| for future in as_completed(futures): | |
| future.result() | |
| yield build() | |
| yield build() | |
| CSS = """ | |
| .gradio-container { max-width: 1060px !important; margin: 0 auto !important; } | |
| .gradio-container, .dark { background: #09090b !important; } | |
| #hero { text-align: center; padding: 2rem 0 1rem; } | |
| #hero h1 { font-size: 2.5rem; font-weight: 300; letter-spacing: -0.02em; color: #fafafa; margin: 0; } | |
| #hero .accent { color: #22c55e; } | |
| #hero .subtitle { color: #71717a; font-size: 0.95rem; margin-top: 0.5rem; } | |
| .response-card { background: #0c0c0f !important; border: 1px solid #1f1f23 !important; border-radius: 8px !important; } | |
| .response-card textarea { background: #0c0c0f !important; border: none !important; color: #e4e4e7 !important; font-size: 0.95rem !important; line-height: 1.6 !important; } | |
| .glo-label { color: #a855f7 !important; font-size: 0.8rem !important; text-transform: uppercase !important; letter-spacing: 0.05em !important; font-weight: 500 !important; } | |
| .meta-label { color: #22c55e !important; font-size: 0.8rem !important; text-transform: uppercase !important; letter-spacing: 0.05em !important; font-weight: 500 !important; } | |
| .stats-text { font-family: 'SF Mono', 'Fira Code', monospace !important; font-size: 0.8rem !important; color: #52525b !important; } | |
| #prompt-input > label > span { display: none !important; } | |
| #prompt-input textarea { background: #111114 !important; border: 1px solid #1f1f23 !important; border-radius: 8px !important; color: #fafafa !important; font-size: 1rem !important; padding: 1rem !important; } | |
| #prompt-input textarea:focus { border-color: #22c55e !important; box-shadow: 0 0 0 2px rgba(34,197,94,0.1) !important; } | |
| #gen-btn { background: #22c55e !important; border: none !important; border-radius: 8px !important; font-weight: 500 !important; font-size: 0.9rem !important; padding: 0.75rem 2rem !important; color: #09090b !important; } | |
| #gen-btn:hover { background: #16a34a !important; } | |
| .prompt-chip { background: #111114 !important; border: 1px solid #1f1f23 !important; border-radius: 6px !important; color: #a1a1aa !important; font-size: 0.85rem !important; } | |
| .prompt-chip:hover { border-color: #22c55e !important; color: #fafafa !important; } | |
| #footer { text-align: center; padding: 2rem 0; border-top: 1px solid #1f1f23; margin-top: 2rem; } | |
| #footer p { color: #52525b; font-size: 0.8rem; } | |
| #footer a { color: #22c55e; text-decoration: none; } | |
| footer.svelte-1ax1toq { display: none !important; } | |
| .built-with { display: none !important; } | |
| """ | |
| with gr.Blocks(css=CSS, theme=gr.themes.Base(primary_hue="green", neutral_hue="zinc"), title="METACOG") as demo: | |
| gr.HTML(""" | |
| <div id="hero"> | |
| <h1><span class="accent">METACOG</span></h1> | |
| <p class="subtitle">Metacognitive inference monitoring. Same model, same Glossolalia decoder.<br/> | |
| Left: Glossolalia alone. Right: Glossolalia + C2/C3 cognitive monitoring.<br/> | |
| C2 detects entropy collapse. C3 breaks absorbing states via diversity perturbation.<br/> | |
| THM-META-CONVERGE -- proved in Lean 4, model-checked in TLA+.</p> | |
| </div> | |
| """) | |
| with gr.Row(): | |
| prompt = gr.Textbox(elem_id="prompt-input", placeholder="The difference between knowing and understanding is", lines=2, label="Prompt", show_label=False, interactive=True, scale=4) | |
| with gr.Column(scale=1): | |
| model_choice = gr.Radio(choices=["buleyean", "base"], value="buleyean", label="Model", info="Buleyean = void-trained") | |
| max_tok = gr.Slider(minimum=8, maximum=8192, value=128, step=1, label="Max tokens") | |
| btn = gr.Button("Generate", elem_id="gen-btn", variant="primary") | |
| with gr.Row(equal_height=True): | |
| with gr.Column(): | |
| gr.HTML('<p class="glo-label">Glossolalia (no metacog)</p>') | |
| glo_out = gr.Textbox(lines=10, show_label=False, interactive=False, elem_classes=["response-card"]) | |
| glo_stats = gr.HTML('<p class="stats-text">--</p>') | |
| with gr.Column(min_width=30): | |
| gr.HTML('<p style="color:#27272a; text-align:center; padding-top:4rem; font-size:0.75rem; letter-spacing:0.1em;">VS</p>') | |
| with gr.Column(): | |
| gr.HTML('<p class="meta-label">Metacog (C2/C3)</p>') | |
| meta_out = gr.Textbox(lines=10, show_label=False, interactive=False, elem_classes=["response-card"]) | |
| meta_stats = gr.HTML('<p class="stats-text">--</p>') | |
| with gr.Accordion("Metacog C2/C3 Diagnostics", open=False): | |
| meta_diag = gr.Textbox(lines=18, show_label=False, interactive=False) | |
| with gr.Accordion("Glossolalia Diagnostics (baseline)", open=False): | |
| glo_diag = gr.Textbox(lines=12, show_label=False, interactive=False) | |
| with gr.Accordion("Layer Health (32 layers)", open=False): | |
| layer_health = gr.Textbox(lines=18, show_label=False, interactive=False) | |
| outputs = [glo_out, meta_out, glo_stats, meta_stats, glo_diag, meta_diag, layer_health] | |
| inputs = [prompt, max_tok, model_choice] | |
| def run(prompt_text, max_tokens, model_name): | |
| for vals in compare(prompt_text, max_tokens, model_name): | |
| gt, mt, gs, ms, gd, md, lh = vals | |
| yield gt, mt, f'<p class="stats-text">{gs}</p>', f'<p class="stats-text">{ms}</p>', gd, md, lh | |
| btn.click(run, inputs, outputs) | |
| prompt.submit(run, inputs, outputs) | |
| gr.HTML('<p style="color:#52525b; font-size:0.8rem; margin-top:1.5rem; margin-bottom:0.5rem;">Try these:</p>') | |
| with gr.Row(): | |
| for p in ["The difference between knowing and understanding is", "Repeat after me: hello hello hello hello", "What happens when a model gets stuck?", "Explain consciousness to a machine"]: | |
| gr.Button(p, size="sm", elem_classes=["prompt-chip"]).click( | |
| fn=lambda x=p: x, outputs=[prompt] | |
| ).then(fn=run, inputs=inputs, outputs=outputs) | |
| gr.HTML(""" | |
| <div id="footer"> | |
| <p style="color:#a1a1aa; font-size:0.85rem; margin-bottom:0.5rem;"> | |
| SmolLM2-360M · Aether WASM-SIMD · THM-META-CONVERGE (Lean 4 + TLA+) | |
| </p> | |
| <p> | |
| <a href="https://forkracefold.com/">Whitepaper</a> · | |
| <a href="https://huggingface.co/spaces/forkjoin-ai/aether">Aether</a> · | |
| <a href="https://huggingface.co/spaces/forkjoin-ai/aether-browser">Edge Mesh</a> · | |
| <a href="https://huggingface.co/spaces/forkjoin-ai/the-void">The Void</a> · | |
| <a href="https://huggingface.co/spaces/forkjoin-ai/buleyean-rl">Buleyean RL</a> · | |
| <a href="https://huggingface.co/spaces/forkjoin-ai/glossolalia">Glossolalia</a> · | |
| <a href="https://huggingface.co/spaces/forkjoin-ai/metacog">Metacog</a> · | |
| <a href="https://huggingface.co/spaces/forkjoin-ai/five-bules">Five Bules</a> · | |
| <a href="https://huggingface.co/spaces/forkjoin-ai/void-attention">Void Attention</a> · | |
| <a href="https://huggingface.co/spaces/forkjoin-ai/quark-personality">Quark Personality</a> | |
| </p> | |
| <p style="margin-top:1rem;">C3 prevents absorbing states · proved by contradiction · | |
| <a href="https://forkracefold.com/">φ² = φ + 1</a></p> | |
| <p style="margin-top:1rem;">Copyright 2026 forkjoin.ai</p> | |
| </div> | |
| """) | |
| if __name__ == "__main__": | |
| demo.launch(server_name="0.0.0.0", server_port=7860) | |