""" SnapKitty Parallel Swarm Computation — Hugging Face Space The computation is the interface. Five parallel swarms execute from a single input: Resonance Words · SUBLEQ Attention · ICP-DAG · Fibonacci Anyons · Jordan Algebra Every visual element traces back to an actual computational value. """ import math import json import hashlib import numpy as np import gradio as gr import plotly.graph_objects as go import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from matplotlib.patches import FancyArrowPatch from matplotlib.colors import Normalize from swarm_engine import ( SwarmEngine, SwarmEvent, SWARM_LAYER, SWARM_COLORS, SWARM_NAMES, PHI, PHI_INV, ) # ═══════════════════════════════════════════════════════════════════════════ # 3D PARALLEL SWARM VIEW (plotly) # ═══════════════════════════════════════════════════════════════════════════ def build_3d_swarm(engine: SwarmEngine, tick: int | None = None) -> go.Figure: events = engine.events_up_to(tick) if tick is not None else engine.events fig = go.Figure() for swarm_name in SWARM_LAYER: se = [e for e in events if e.swarm == swarm_name] if not se: continue fig.add_trace(go.Scatter3d( x=[e.x for e in se], y=[e.y for e in se], z=[e.z for e in se], mode='markers', marker=dict( size=[e.size for e in se], color=[e.color for e in se], opacity=0.85, line=dict(width=0.5, color='#333'), ), text=[e.label for e in se], customdata=[e.node_id for e in se], name=SWARM_NAMES[swarm_name], hovertemplate='%{text}
ID: %{customdata}', )) # Cross-swarm connections for e in events: for cid in e.connections: target = engine.get_node(cid) if target and (tick is None or target.tick <= tick): fig.add_trace(go.Scatter3d( x=[e.x, target.x], y=[e.y, target.y], z=[e.z, target.z], mode='lines', line=dict(color='rgba(255,255,255,0.2)', width=3), showlegend=False, hoverinfo='skip', )) y_labels = {v: k.upper() for k, v in SWARM_LAYER.items()} fig.update_layout( scene=dict( xaxis=dict(title='Time (tick)', color='#888', gridcolor='#222', backgroundcolor='#0a0a0f'), yaxis=dict(title='', tickvals=list(range(5)), ticktext=[y_labels.get(i, '') for i in range(5)], color='#888', gridcolor='#222', backgroundcolor='#0a0a0f'), zaxis=dict(title='State', color='#888', gridcolor='#222', backgroundcolor='#0a0a0f'), bgcolor='#0a0a0f', camera=dict(eye=dict(x=1.8, y=-1.5, z=0.8)), ), paper_bgcolor='#0a0a0f', plot_bgcolor='#0a0a0f', font=dict(color='#ccc'), legend=dict(bgcolor='rgba(10,10,15,0.8)', font=dict(size=10)), margin=dict(l=0, r=0, t=30, b=0), height=550, ) return fig # ═══════════════════════════════════════════════════════════════════════════ # EXECUTION TIMELINE (plotly) # ═══════════════════════════════════════════════════════════════════════════ def build_timeline(engine: SwarmEngine, tick: int | None = None) -> go.Figure: fig = go.Figure() for swarm_name in reversed(list(SWARM_LAYER.keys())): se = engine.events_for_swarm(swarm_name) if not se: continue ticks = [e.tick for e in se] y_val = SWARM_LAYER[swarm_name] colors = [e.color for e in se] sizes = [max(6, e.size) for e in se] labels = [e.label for e in se] fig.add_trace(go.Scatter( x=ticks, y=[y_val] * len(ticks), mode='markers+lines', marker=dict(size=sizes, color=colors, opacity=0.9, line=dict(width=0.5, color='#333')), line=dict(color=SWARM_COLORS[swarm_name], width=1, dash='dot'), text=labels, name=SWARM_NAMES[swarm_name], hovertemplate='%{text}
Tick %{x}', )) # Tick cursor if tick is not None: fig.add_vline(x=tick, line=dict(color='#ffffff', width=2, dash='dash')) y_labels = {v: SWARM_NAMES[k] for k, v in SWARM_LAYER.items()} fig.update_layout( xaxis=dict(title='Execution Tick', color='#888', gridcolor='#1a1a2a', zeroline=False), yaxis=dict(tickvals=list(range(5)), ticktext=[y_labels.get(i, '') for i in range(5)], color='#888', gridcolor='#1a1a2a', zeroline=False), paper_bgcolor='#0a0a0f', plot_bgcolor='#0f0f1a', font=dict(color='#ccc', size=10), legend=dict(bgcolor='rgba(10,10,15,0.8)', orientation='h', yanchor='bottom', y=1.02, font=dict(size=9)), margin=dict(l=10, r=10, t=10, b=10), height=200, ) return fig # ═══════════════════════════════════════════════════════════════════════════ # ALGORITHMIC ART — computation drives every visual property # ═══════════════════════════════════════════════════════════════════════════ def generate_art_radial(engine: SwarmEngine): """Radial mandala — each ring is a swarm, each point is an event.""" fig, ax = plt.subplots(1, 1, figsize=(10, 10), facecolor='#0a0a0f', subplot_kw=dict(projection='polar')) ax.set_facecolor('#0a0a0f') ax.grid(True, color='#1a1a2a', alpha=0.5) ax.tick_params(colors='#333') ax.set_yticklabels([]) ax.spines['polar'].set_color('#222') for swarm_name, layer in SWARM_LAYER.items(): se = engine.events_for_swarm(swarm_name) if not se: continue n = len(se) ring_r = 1.0 + layer * 0.8 base_color = SWARM_COLORS[swarm_name] thetas = [] radii = [] sizes = [] colors = [] for i, e in enumerate(se): theta = 2 * math.pi * i / max(n, 1) r = ring_r + e.z * 0.35 thetas.append(theta) radii.append(r) sizes.append(e.size * 4) colors.append(e.color) ax.scatter(thetas, radii, c=colors, s=sizes, alpha=0.85, edgecolors='#222', linewidths=0.3, zorder=3) # Connect sequential events within swarm if len(thetas) > 1: ax.plot(thetas + [thetas[0]], radii + [radii[0]], color=base_color, alpha=0.3, linewidth=0.8, zorder=2) # Cross-swarm connections for e in engine.events: for cid in e.connections: target = engine.get_node(cid) if target: se_list = engine.events_for_swarm(e.swarm) te_list = engine.events_for_swarm(target.swarm) if se_list and te_list: si = se_list.index(e) if e in se_list else 0 ti = te_list.index(target) if target in te_list else 0 sn = max(len(se_list), 1) tn = max(len(te_list), 1) t1 = 2 * math.pi * si / sn r1 = 1.0 + SWARM_LAYER[e.swarm] * 0.8 + e.z * 0.35 t2 = 2 * math.pi * ti / tn r2 = 1.0 + SWARM_LAYER[target.swarm] * 0.8 + target.z * 0.35 ax.plot([t1, t2], [r1, r2], color='#ffffff', alpha=0.12, linewidth=1.5, zorder=1) ax.set_title(f'SnapKitty Algorithmic Art — "{engine.text}"', color='#00ff88', fontsize=13, fontweight='bold', pad=20) plt.tight_layout() return fig def generate_art_bitfield(engine: SwarmEngine): """Bit constellation — resonance word bits become geometry.""" res = engine.events_for_swarm('resonance') sq = engine.events_for_swarm('subleq') fig, axes = plt.subplots(1, 2, figsize=(14, 7), facecolor='#0a0a0f') fig.suptitle(f'Bit Constellation — "{engine.text}"', color='#00ff88', fontsize=14, fontweight='bold') # Left: resonance word bit patterns as pixel grid ax = axes[0] ax.set_facecolor('#0a0a0f') if res: n = len(res) grid_w = min(n, 16) rows = [] for e in res[:64]: word = int(e.data['word_hex'], 16) bits = [(word >> (63 - b)) & 1 for b in range(64)] rows.append(bits) arr = np.array(rows) ax.imshow(arr, cmap='cividis', aspect='auto', interpolation='nearest') ax.set_title('Resonance Word Bit Patterns\n(each row = one 64-bit GF(p) element)', color='#ccc', fontsize=10) ax.set_xlabel('Bit position [63..0]', color='#888') ax.set_ylabel('Token index', color='#888') ax.tick_params(colors='#888') else: ax.text(0.5, 0.5, 'No resonance data', ha='center', va='center', color='#888', transform=ax.transAxes) # Right: SUBLEQ branch path as braid-like diagram ax2 = axes[1] ax2.set_facecolor('#0a0a0f') if sq: for i, e in enumerate(sq[:60]): x = i y = e.data['pc'] if isinstance(e.data.get('pc'), (int, float)) else 0 dx = 1 dy = e.data['next_pc'] - e.data['pc'] if isinstance(e.data.get('next_pc'), (int, float)) else 3 color = '#00ff88' if e.data.get('branch_taken') else '#ff4444' alpha = 0.7 if e.data.get('branch_taken') else 0.4 ax2.annotate('', xy=(x + dx, y + dy), xytext=(x, y), arrowprops=dict(arrowstyle='->', color=color, alpha=alpha, lw=1.2)) ax2.plot(x, y, 'o', color=color, markersize=3, alpha=alpha) ax2.set_title('SUBLEQ Branch Path\n(green=branch taken, red=fallthrough)', color='#ccc', fontsize=10) ax2.set_xlabel('Execution step', color='#888') ax2.set_ylabel('Program Counter', color='#888') ax2.tick_params(colors='#888') ax2.invert_yaxis() else: ax2.text(0.5, 0.5, 'No SUBLEQ data', ha='center', va='center', color='#888', transform=ax2.transAxes) for ax in axes: for spine in ax.spines.values(): spine.set_color('#333') plt.tight_layout() return fig def generate_art_convergence(engine: SwarmEngine): """Algebra convergence — Jordan map approaching [U,ρ*]=0.""" alg = engine.events_for_swarm('algebra') sq = engine.events_for_swarm('subleq') q = engine.events_for_swarm('quantum') fig, axes = plt.subplots(1, 3, figsize=(16, 6), facecolor='#0a0a0f') fig.suptitle(f'Convergence Analysis — "{engine.text}"', color='#00ff88', fontsize=14, fontweight='bold') for ax in axes: ax.set_facecolor('#0f0f1a') for spine in ax.spines.values(): spine.set_color('#333') ax.tick_params(colors='#888') # Left: Jordan convergence if alg: iters = [e.data['iteration'] for e in alg] norms = [e.data['commutator_norm'] for e in alg] evals0 = [e.data['eigenvalues'][0] for e in alg] evals1 = [e.data['eigenvalues'][1] for e in alg] axes[0].semilogy(iters, [max(n, 1e-12) for n in norms], color='#ff6644', linewidth=2, label='‖[U,ρ]‖') axes[0].axhline(0.001, color='#44ff66', linestyle='--', alpha=0.6, label='Convergence threshold') axes[0].fill_between(iters, [1e-12]*len(iters), [max(n,1e-12) for n in norms], alpha=0.1, color='#ff6644') axes[0].set_xlabel('Iteration', color='#888') axes[0].set_ylabel('‖[U, ρ]‖ (log scale)', color='#888') axes[0].set_title('Jordan Fixed-Point\nT(ρ) = φ⁻¹·U·ρ·U† + φ⁻²·ρ', color='#ccc', fontsize=10) axes[0].legend(facecolor='#0f0f1a', labelcolor='white', fontsize=8) # Middle: SUBLEQ M[B]-M[A] distribution if sq: results = [e.data['result'] for e in sq] branches = [e.data['branch_taken'] for e in sq] colors = ['#00ff88' if b else '#ff4444' for b in branches] axes[1].bar(range(len(results)), results, color=colors, width=0.8, alpha=0.8) axes[1].axhline(0, color='#ffaa00', linewidth=1.5, linestyle='--') axes[1].set_xlabel('SUBLEQ step', color='#888') axes[1].set_ylabel('M[B] - M[A]', color='#888') axes[1].set_title('SUBLEQ Execution Trace\n(green=branch, red=fall)', color='#ccc', fontsize=10) n_branch = sum(branches) n_fall = len(branches) - n_branch axes[1].text(0.98, 0.98, f'Branch: {n_branch}\nFall: {n_fall}', transform=axes[1].transAxes, ha='right', va='top', color='#888', fontsize=9, bbox=dict(boxstyle='round', facecolor='#0f0f1a', edgecolor='#333')) # Right: Quantum fusion tree if q: fusions = [e for e in q if e.data.get('type') == 'fusion'] if fusions: rounds = [e.data['round'] for e in fusions] charges = [1.0 if e.data['output'] == 'τ' else 0.5 for e in fusions] c_colors = ['#cc66ff' if e.data['output'] == 'τ' else '#9944aa' for e in fusions] axes[2].scatter(range(len(fusions)), rounds, c=c_colors, s=[c*80 for c in charges], edgecolors='#333', linewidths=0.5, zorder=3) for i, f in enumerate(fusions): axes[2].annotate(f.label, (i, f.data['round']), color='#ccc', fontsize=7, ha='center', va='bottom', xytext=(0, 5), textcoords='offset points') axes[2].set_xlabel('Fusion index', color='#888') axes[2].set_ylabel('Round', color='#888') axes[2].set_title('Fibonacci Anyon Fusion\nτ⊗τ = 1⊕τ (classical simulation)', color='#ccc', fontsize=10) plt.tight_layout() return fig # ═══════════════════════════════════════════════════════════════════════════ # RESEARCH VIEW — raw computation tables # ═══════════════════════════════════════════════════════════════════════════ def build_research_view(engine: SwarmEngine) -> str: s = engine.summary() lines = [ "## Computation Summary", "", f"**Input:** `{s['input']}`", f"**Total events:** {s['total_events']}", f"**Max tick:** {s['max_tick']}", "", "| Swarm | Events |", "|-------|--------|", ] for name, count in s['swarm_counts'].items(): lines.append(f"| {SWARM_NAMES[name]} | {count} |") lines += [ "", "### SUBLEQ Execution", f"- Branches taken: **{s['subleq_branches']}**", f"- Fallthroughs: **{s['subleq_fallthroughs']}**", f"- Branch ratio: **{s['subleq_branches']/(s['subleq_branches']+s['subleq_fallthroughs']):.1%}**" if (s['subleq_branches'] + s['subleq_fallthroughs']) > 0 else "", "", "### Fibonacci Anyon Fusion", f"- Total fusions: **{s['quantum_fusions']}**", f"- τ outcomes: **{s['quantum_tau_outcomes']}**", f"- Note: **Classical simulation** — not physical quantum hardware", "", "### Jordan Algebra", f"- Final ‖[U,ρ]‖: **{s['algebra_final_commutator']:.6f}**" if s['algebra_final_commutator'] is not None else "", f"- Converged: **{'Yes' if s['algebra_final_commutator'] and s['algebra_final_commutator'] < 0.001 else 'No'}**", f"- Proof: **JordanMatrixProof.lean (0 sorry)**", "", "### Benchmarks", "- SUBLEQ vs softmax attention: **Benchmark unavailable**", "- Latency comparison: **Benchmark unavailable**", "- Hallucination rate: **Benchmark unavailable**", "- FLOPs comparison: **Benchmark unavailable**", ] return '\n'.join(lines) def build_event_table(engine: SwarmEngine, swarm: str) -> str: events = engine.events_for_swarm(swarm) if not events: return "No events." lines = ["| Tick | ID | Label |", "|------|-----|-------|"] for e in events[:50]: lines.append(f"| {e.tick} | `{e.node_id}` | {e.label} |") if len(events) > 50: lines.append(f"| ... | ... | *({len(events) - 50} more events)* |") return '\n'.join(lines) # ═══════════════════════════════════════════════════════════════════════════ # VISUAL MAPPING DOCUMENTATION # ═══════════════════════════════════════════════════════════════════════════ MAPPING_DOC = """## Visual Mapping — Computation → Visualization Every visual property traces to a computational value. Nothing is decorative. | Visual Property | Source | Transformation | |-----------------|--------|----------------| | **3D X position** | Event tick | Direct: x = tick | | **3D Y position** | Swarm type | Layer: resonance=0, subleq=1, dag=2, quantum=3, algebra=4 | | **3D Z position** | State value | Normalized: lattice_idx/12288, result/max, comm_norm, round/5 | | **Node color** | Event type | Branch=#00ff88, Fall=#ff4444, Swarm base color otherwise | | **Node size** | Magnitude | 5 + scaled(payload, abs(result), comm_norm, fusion_round) | | **Connection line** | Cross-swarm link | Resonance→SUBLEQ, SUBLEQ→DAG, DAG→Algebra | | **Radial angle** | Event index | θ = 2π · index / count | | **Radial distance** | Swarm layer + z | r = 1.0 + layer·0.8 + z·0.35 | | **Bit pattern row** | 64-bit word | Binary decomposition of GF(p) element | | **Branch arrow** | SUBLEQ step | Direction: PC → next_pc, Color: branch/fall | | **Convergence curve** | ‖[U,ρ]‖ | Log scale of commutator norm per iteration | | **Fusion node** | Anyon fusion | Position: (index, round), Color: τ=#cc66ff, 1=#9944aa | ### Determinism Same input text → same seed → same RNG state → same computation → same visualization. Different input → different resonance words → different SUBLEQ memory → different art. ### What Is NOT Shown - No fake measurements (benchmarks say "unavailable" when they don't exist) - No implied quantum advantage (fusion is labeled "classical simulation") - No decorative particles or animations unrelated to computation - No performance claims without actual benchmark data """ # ═══════════════════════════════════════════════════════════════════════════ # GRADIO UI # ═══════════════════════════════════════════════════════════════════════════ CSS = """ body { background: #0a0a0f; } .gradio-container { max-width: 1400px; font-family: 'JetBrains Mono', 'Fira Code', monospace; } h1, h2, h3 { color: #00ff88; } footer { display: none !important; } .tab-nav button { background: #0f0f1a !important; color: #aaa !important; border: 1px solid #222 !important; } .tab-nav button.selected { color: #00ff88 !important; border-color: #00ff88 !important; } """ _engine: SwarmEngine | None = None def run_computation(text: str): global _engine _engine = SwarmEngine(text) e = _engine fig_3d = build_3d_swarm(e) fig_timeline = build_timeline(e) fig_art = generate_art_radial(e) research = build_research_view(e) summary_text = ( f"**{e.summary()['total_events']} events** across 5 swarms, " f"**{e.max_tick} ticks**" ) # Build node dropdown node_ids = [e_item.node_id for e_item in e.events[:200]] return (fig_3d, fig_timeline, fig_art, research, summary_text, gr.update(choices=node_ids, value=node_ids[0] if node_ids else None), e.inspect_node(node_ids[0]) if node_ids else "No events.") def update_tick(tick: int): if _engine is None: return None, None return build_3d_swarm(_engine, tick), build_timeline(_engine, tick) def inspect_selected(node_id: str): if _engine is None or not node_id: return "Run computation first." return _engine.inspect_node(node_id) def switch_art_style(style: str): if _engine is None: return None if style == "Radial Mandala": return generate_art_radial(_engine) elif style == "Bit Constellation": return generate_art_bitfield(_engine) elif style == "Convergence Analysis": return generate_art_convergence(_engine) return None def show_swarm_table(swarm: str): if _engine is None: return "Run computation first." key = {v: k for k, v in SWARM_NAMES.items()}.get(swarm, 'resonance') return build_event_table(_engine, key) with gr.Blocks(title="SnapKitty Parallel Swarm Computation") as demo: # ── Header ─────────────────────────────────────────────────────────── gr.Markdown("""# SnapKitty Parallel Swarm Computation **The computation is the interface.** Enter text. Watch 5 computational processes execute in parallel. Inspect any node. See the computation become algorithmic art. | Swarm | Algorithm | Source | |-------|-----------|--------| | Resonance Words | GF(2⁶⁴−2³²+1) field elements + lattice routing | `j-matrix-twin/resonance_word.ijs` | | SUBLEQ Attention | 256-cell integer memory, subtract-and-branch | `j-matrix-twin/subleq_attention.ijs` | | ICP-DAG | Governance: EVIDENCE→CLAIM→PROOF→DECISION→EXECUTION | `ICP-DAG.m` + `ICP-DAG.lp` | | Fibonacci Anyons | τ⊗τ=1⊕τ fusion simulation (φ-weighted) | `FibonacciAnyon.lean` | | Jordan Algebra | T(ρ)=φ⁻¹UρU†+φ⁻²ρ → [U,ρ*]=0 | `JordanMatrixProof.lean` (0 sorry) | """) # ── Controls ───────────────────────────────────────────────────────── with gr.Row(): text_input = gr.Textbox( label="Input Text", value="sovereign entropy lattice", max_lines=1, scale=3, ) run_btn = gr.Button("Compute", variant="primary", scale=1) status_md = gr.Markdown("") with gr.Tabs(): # ── TAB: Parallel Swarms ───────────────────────────────────────── with gr.Tab("Parallel Swarms"): with gr.Row(): with gr.Column(scale=3): plot_3d = gr.Plot(label="3D Swarm View") with gr.Column(scale=1): node_dropdown = gr.Dropdown( label="Select Node", choices=[], interactive=True, ) inspector_md = gr.Markdown("Run computation to inspect nodes.") gr.Markdown("### Execution Timeline") with gr.Row(): tick_slider = gr.Slider( 0, 100, value=100, step=1, label="Tick (drag to scrub timeline)", ) timeline_plot = gr.Plot(label="Timeline") # ── TAB: Algorithmic Art ───────────────────────────────────────── with gr.Tab("Algorithmic Art"): gr.Markdown("""### Computation → Visual Form Every visual property maps to a computational value. Same input = same art. Different input = different art. """) with gr.Row(): art_style = gr.Radio( ["Radial Mandala", "Bit Constellation", "Convergence Analysis"], value="Radial Mandala", label="Art Style", ) art_plot = gr.Plot(label="Algorithmic Art") # ── TAB: Research ──────────────────────────────────────────────── with gr.Tab("Research"): with gr.Row(): with gr.Column(scale=2): research_md = gr.Markdown("Run computation first.") with gr.Column(scale=1): swarm_select = gr.Dropdown( label="Swarm Event Table", choices=list(SWARM_NAMES.values()), value="SUBLEQ Attention", ) event_table_md = gr.Markdown("") # ── TAB: Visual Mapping ────────────────────────────────────────── with gr.Tab("Visual Mapping"): gr.Markdown(MAPPING_DOC) # ── Wiring ─────────────────────────────────────────────────────────── run_btn.click( run_computation, inputs=[text_input], outputs=[plot_3d, timeline_plot, art_plot, research_md, status_md, node_dropdown, inspector_md], ) tick_slider.change( update_tick, inputs=[tick_slider], outputs=[plot_3d, timeline_plot], ) node_dropdown.change( inspect_selected, inputs=[node_dropdown], outputs=[inspector_md], ) art_style.change( switch_art_style, inputs=[art_style], outputs=[art_plot], ) swarm_select.change( show_swarm_table, inputs=[swarm_select], outputs=[event_table_md], ) # ── Footer ─────────────────────────────────────────────────────────── gr.Markdown("""--- **Scientific integrity:** Algorithm, simulation, visualization, and benchmark are separated. The quantum swarm is explicitly a classical simulation — no quantum advantage is claimed. Benchmarks say "unavailable" when data does not exist. *The algorithm generates the visualization. Not decoration.* [GitHub](https://github.com/SNAPKITTYWEST) | BSL-1.1 / AGPL-3.0 / Apache-2.0 | Patent Pending — Bel Esprit D'Accord Irrevocable Trust """) if __name__ == "__main__": demo.launch(server_name="0.0.0.0", server_port=7861, share=False)