gregrsea commited on
Commit
822cfa3
·
1 Parent(s): c7e559d

HumpBack: add animated neural thinking visualization + canvas live sim + packed weights

Browse files

- visualize.py: added canvas_viz_html() for 60 FPS HTML5 Canvas live neural
simulation with synaptic particle pulses, neuron glow, hover inspection
- visualize.py: animate_thinking() produces animated GIF of activation wave
- visualize.py: plot_weights() saves 3-panel Concept/Spatial/Temporal heatmap
- server.py: /viz.html now serves live 60 FPS canvas animation
- server.py: get_agent() loads packed weights.zip on startup
- bridge.py: canonical_to_graph handles both canonical and compact weight formats
- pack.py: pack() / unpack() work correctly for weights.zip
- weights.zip: regenerated from fresh 5-epoch trained model
- run_harness.py: shows all 62 learned facts + generates visualizations

Files changed (4) hide show
  1. humpback/bridge.py +11 -3
  2. humpback/server.py +18 -17
  3. humpback/visualize.py +479 -105
  4. weights.zip +2 -2
humpback/bridge.py CHANGED
@@ -53,6 +53,14 @@ def graph_to_canonical(graph: NeuralGraph, origin: str = "python") -> Dict[str,
53
  }
54
 
55
 
 
 
 
 
 
 
 
 
56
  def canonical_to_graph(data: Dict[str, Any]) -> NeuralGraph:
57
  g = NeuralGraph()
58
  g.step_count = int(data.get("step_count", 0))
@@ -63,9 +71,9 @@ def canonical_to_graph(data: Dict[str, Any]) -> NeuralGraph:
63
  n = Neuron.__new__(Neuron)
64
  n.id = int(nd["id"])
65
  n.weights = Weight3(
66
- np.asarray(w["concept"], dtype=np.float32),
67
- np.asarray(w["spatial"], dtype=np.float32),
68
- np.asarray(w["temporal"], dtype=np.float32),
69
  )
70
  n.bias = float(nd.get("bias", 0.0))
71
  n.activation = float(nd.get("activation", 0.0))
 
53
  }
54
 
55
 
56
+ def _decode_vec(raw: Any) -> np.ndarray:
57
+ if isinstance(raw, dict):
58
+ q = np.asarray(raw["q"], dtype=np.uint8).astype(np.int8)
59
+ scale = float(raw.get("scale", 1.0))
60
+ return (q / 127.0 * scale).astype(np.float32)
61
+ return np.asarray(raw, dtype=np.float32)
62
+
63
+
64
  def canonical_to_graph(data: Dict[str, Any]) -> NeuralGraph:
65
  g = NeuralGraph()
66
  g.step_count = int(data.get("step_count", 0))
 
71
  n = Neuron.__new__(Neuron)
72
  n.id = int(nd["id"])
73
  n.weights = Weight3(
74
+ _decode_vec(w["concept"]),
75
+ _decode_vec(w["spatial"]),
76
+ _decode_vec(w["temporal"]),
77
  )
78
  n.bias = float(nd.get("bias", 0.0))
79
  n.activation = float(nd.get("activation", 0.0))
humpback/server.py CHANGED
@@ -15,7 +15,7 @@ from fastapi.responses import HTMLResponse, JSONResponse
15
  from pydantic import BaseModel
16
 
17
  from .agent import HumpbackModel
18
- from .visualize import plot_graph, plot_graph_interactive
19
 
20
  app = FastAPI(title="HumpBack model server")
21
  _agent = None
@@ -24,11 +24,19 @@ _agent = None
24
  def get_agent() -> HumpbackModel:
25
  global _agent
26
  if _agent is None:
27
- _agent = HumpbackModel()
28
- try:
29
- _agent.train(epochs=2)
30
- except Exception:
31
- pass
 
 
 
 
 
 
 
 
32
  return _agent
33
 
34
 
@@ -124,11 +132,12 @@ def index():
124
 
125
  @app.get("/viz.png")
126
  def viz():
 
127
  agent = get_agent()
128
  import tempfile, os
129
  fd, path = tempfile.mkstemp(suffix=".png")
130
  os.close(fd)
131
- plot_graph(agent.graph, path)
132
  with open(path, "rb") as f:
133
  data = f.read()
134
  try:
@@ -140,17 +149,9 @@ def viz():
140
 
141
  @app.get("/viz.html", response_class=HTMLResponse)
142
  def viz_html():
 
143
  agent = get_agent()
144
- import tempfile, os
145
- fd, path = tempfile.mkstemp(suffix=".html")
146
- os.close(fd)
147
- plot_graph_interactive(agent.graph, path)
148
- with open(path, "r", encoding="utf-8") as f:
149
- html = f.read()
150
- try:
151
- os.remove(path)
152
- except Exception:
153
- pass
154
  return HTMLResponse(content=html)
155
 
156
 
 
15
  from pydantic import BaseModel
16
 
17
  from .agent import HumpbackModel
18
+ from .visualize import canvas_viz_html, plot_weights, animate_thinking
19
 
20
  app = FastAPI(title="HumpBack model server")
21
  _agent = None
 
24
  def get_agent() -> HumpbackModel:
25
  global _agent
26
  if _agent is None:
27
+ import os
28
+ from .pack import unpack
29
+ if os.path.exists("weights.zip"):
30
+ try:
31
+ _agent = unpack("weights.zip")
32
+ except Exception:
33
+ _agent = None
34
+ if _agent is None:
35
+ _agent = HumpbackModel()
36
+ try:
37
+ _agent.train(epochs=2)
38
+ except Exception:
39
+ pass
40
  return _agent
41
 
42
 
 
132
 
133
  @app.get("/viz.png")
134
  def viz():
135
+ """Static PNG of concept/spatial/temporal weight heatmaps."""
136
  agent = get_agent()
137
  import tempfile, os
138
  fd, path = tempfile.mkstemp(suffix=".png")
139
  os.close(fd)
140
+ plot_weights(agent.graph, path)
141
  with open(path, "rb") as f:
142
  data = f.read()
143
  try:
 
149
 
150
  @app.get("/viz.html", response_class=HTMLResponse)
151
  def viz_html():
152
+ """Interactive animated neural graph (HTML5 Canvas 60 FPS, synaptic particle pulses)."""
153
  agent = get_agent()
154
+ html = canvas_viz_html(agent.graph)
 
 
 
 
 
 
 
 
 
155
  return HTMLResponse(content=html)
156
 
157
 
humpback/visualize.py CHANGED
@@ -1,137 +1,511 @@
1
- """Visualization helpers for weights and graph."""
2
 
 
 
 
 
 
 
 
3
  from __future__ import annotations
4
 
 
5
  import os
 
 
6
 
 
7
  import matplotlib
8
  matplotlib.use("Agg")
9
  import matplotlib.pyplot as plt
10
- import numpy as np
11
  import networkx as nx
12
 
 
 
 
13
  from .core.graph import NeuralGraph
 
 
14
 
15
 
16
- def plot_weights(graph: NeuralGraph, path: str = "visualizations/weights.png") -> str:
17
- os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
18
- neurons = list(graph.neurons.values())
19
- if not neurons:
20
- return path
21
- # stack concept vectors
22
- C = np.asarray([n.weights.concept for n in neurons])
23
- S = np.asarray([n.weights.spatial for n in neurons])
24
- T = np.asarray([n.weights.temporal for n in neurons])
25
- fig, axes = plt.subplots(1, 3, figsize=(15, 6))
26
- for ax, M, title in zip(axes, (C, S, T), ("Concept", "Spatial", "Temporal")):
27
- im = ax.imshow(M, aspect="auto", cmap="coolwarm", vmin=-1, vmax=1)
28
- ax.set_title(f"{title} weights ({M.shape[0]} neurons x {M.shape[1]})")
29
- ax.set_xlabel("dimension")
30
- ax.set_ylabel("neuron")
31
- fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04)
32
- plt.tight_layout()
33
- plt.savefig(path, dpi=120)
34
- plt.close()
35
- return path
36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
- def plot_graph(graph: NeuralGraph, path: str = "visualizations/graph.png") -> str:
39
- os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
 
 
 
 
 
 
 
 
 
 
40
  G = nx.DiGraph()
 
 
 
 
 
 
 
 
 
41
  for nid, n in graph.neurons.items():
42
- G.add_node(nid, label=n.label or str(nid), activation=n.activation)
43
- for syns in graph.adj.values():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  for s in syns:
45
- G.add_edge(s.src, s.dst, weight=s.weight)
46
- pos = nx.spring_layout(G, seed=42, k=0.5)
47
- acts = np.asarray([graph.neurons[n].activation for n in G.nodes()])
48
- # normalize for color
49
- if acts.size and (acts.max() - acts.min()) > 1e-8:
50
- colors = (acts - acts.min()) / (acts.max() - acts.min())
51
- else:
52
- colors = np.zeros(len(acts))
53
- fig, ax = plt.subplots(figsize=(10, 8))
54
- nx.draw_networkx_nodes(G, pos, node_color=colors, cmap=plt.cm.viridis, node_size=200, ax=ax)
55
- nx.draw_networkx_edges(G, pos, alpha=0.3, arrows=True, ax=ax)
56
- nx.draw_networkx_labels(G, pos, labels={n: (graph.neurons[n].label or "") for n in G.nodes()}, font_size=7, ax=ax)
57
- ax.set_title(f"Neural graph: {len(G.nodes())} neurons, {len(G.edges())} edges")
58
- ax.axis("off")
59
- plt.tight_layout()
60
- plt.savefig(path, dpi=120)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  plt.close()
62
- return path
 
63
 
 
 
 
 
 
 
 
 
 
64
 
65
- def _neuron_type(n) -> str:
66
- lab = (n.label or "").lower()
67
- if lab.startswith("in"):
68
- return "input"
69
- if lab.startswith("h"):
70
- return "hidden"
71
- if lab.startswith("out"):
72
- return "output"
73
- if "retrieved" in lab:
74
- return "retrieved"
75
- return "other"
76
 
 
 
 
 
77
 
78
- def plot_graph_interactive(graph: NeuralGraph, path: str = "visualizations/graph.html") -> str:
79
- import os
80
- os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
81
- import plotly.graph_objects as go
82
- # cluster layout by type
83
- type_order = {"input": 0, "hidden": 1, "output": 2, "retrieved": 3, "other": 4}
84
- type_x = {"input": 0.0, "hidden": 1.0, "output": 2.0, "retrieved": 1.0, "other": 3.0}
85
- nodes = list(graph.neurons.values())
86
- # group by type for y spacing
87
- from collections import defaultdict
88
- groups = defaultdict(list)
89
- for n in nodes:
90
- groups[_neuron_type(n)].append(n)
91
- pos = {}
92
- for t, grp in groups.items():
93
- for i, n in enumerate(grp):
94
- pos[n.id] = (type_x.get(t, 3.0), i - len(grp) / 2.0)
95
- # edges
96
- edge_x = []
97
- edge_y = []
98
- for syns in graph.adj.values():
99
  for s in syns:
100
- if s.src in pos and s.dst in pos:
101
- edge_x += [pos[s.src][0], pos[s.dst][0], None]
102
- edge_y += [pos[s.src][1], pos[s.dst][1], None]
103
- edge_trace = go.Scatter(x=edge_x, y=edge_y, mode="lines", line=dict(width=0.8, color="#888"), hoverinfo="none")
104
- # nodes
105
- color_map = {"input": "#4f6cff", "hidden": "#00c896", "output": "#ff6b6b", "retrieved": "#ffd166", "other": "#aaa"}
106
- node_x = [pos[n.id][0] for n in nodes]
107
- node_y = [pos[n.id][1] for n in nodes]
108
- node_color = [color_map[_neuron_type(n)] for n in nodes]
109
- node_size = [max(6, 6 + abs(n.activation) * 20) for n in nodes]
110
- node_text = [f"id={n.id}<br>type={_neuron_type(n)}<br>label={n.label}<br>act={n.activation:.3f}<br>uncertainty={n.uncertainty():.2f}" for n in nodes]
111
- node_trace = go.Scatter(x=node_x, y=node_y, mode="markers+text", text=[n.label or str(n.id) for n in nodes],
112
- textposition="top center", hovertext=node_text, hoverinfo="text",
113
- marker=dict(size=node_size, color=node_color, line=dict(width=1, color="#fff")))
 
 
 
 
 
 
 
 
 
 
 
 
114
  fig = go.Figure(data=[edge_trace, node_trace])
115
- fig.update_layout(title=f"HumpBack neural graph — {len(nodes)} neurons, {sum(len(v) for v in graph.adj.values())} synapses",
116
- showlegend=False, xaxis=dict(visible=False), yaxis=dict(visible=False),
117
- plot_bgcolor="#0b1020", paper_bgcolor="#0b1020", font=dict(color="#e6e9f2"))
118
- fig.write_html(path, include_plotlyjs="cdn")
119
- return path
120
 
 
 
 
 
 
 
 
 
 
 
 
 
121
 
122
- def plot_memory(agent, path: str = "visualizations/memory.png") -> str:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
  os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
124
- items = agent.memory.items
125
- if not items:
126
  return path
127
- M = np.asarray([it.key for it in items])
128
- fig, ax = plt.subplots(figsize=(10, 6))
129
- im = ax.imshow(M, aspect="auto", cmap="viridis")
130
- ax.set_title(f"Memory keys ({len(items)} items x {M.shape[1]})")
131
- ax.set_xlabel("dimension")
132
- ax.set_ylabel("memory item")
133
- fig.colorbar(im, ax=ax)
 
 
 
134
  plt.tight_layout()
135
  plt.savefig(path, dpi=120)
136
  plt.close()
137
- return path
 
1
+ """Interactive & animated visualization for HumpBack.
2
 
3
+ Provides:
4
+ - canvas_viz_html(graph): 60 FPS live HTML5 Canvas animation with synaptic particle
5
+ pulses, glowing neuron nodes, activation waves, and hover inspection.
6
+ - animate_thinking(graph, out_path): Matplotlib animated GIF of activation wave.
7
+ - interactive_brain(graph, out_path): Plotly HTML export with interactive slider.
8
+ - plot_weights(graph, out_path): Matplotlib 3-panel concept/spatial/temporal weights PNG.
9
+ """
10
  from __future__ import annotations
11
 
12
+ import json
13
  import os
14
+ import tempfile
15
+ import zipfile
16
 
17
+ import numpy as np
18
  import matplotlib
19
  matplotlib.use("Agg")
20
  import matplotlib.pyplot as plt
21
+ import matplotlib.animation as animation
22
  import networkx as nx
23
 
24
+ import plotly.graph_objects as go
25
+ from plotly.subplots import make_subplots
26
+
27
  from .core.graph import NeuralGraph
28
+ from .core.neuron import Neuron
29
+ from .core.weights import Weight3
30
 
31
 
32
+ def load_graph(path: str) -> NeuralGraph:
33
+ """Load NeuralGraph from graph.json or weights.zip."""
34
+ if path.endswith(".zip"):
35
+ tmp = tempfile.mkdtemp()
36
+ with zipfile.ZipFile(path) as z:
37
+ z.extractall(tmp)
38
+ target = os.path.join(tmp, "graph.json")
39
+ else:
40
+ target = path
41
+ with open(target, encoding="utf-8") as f:
42
+ data = json.load(f)
 
 
 
 
 
 
 
 
 
43
 
44
+ g = NeuralGraph()
45
+ g.step_count = int(data.get("step_count", 0))
46
+ g.input_ids = list(data.get("input_ids", []))
47
+ g.output_ids = list(data.get("output_ids", []))
48
+ for nd in data.get("neurons", []):
49
+ w = nd["weights"]
50
+ n = Neuron(
51
+ id=int(nd["id"]),
52
+ weights=Weight3(_vec(w["concept"]), _vec(w["spatial"]), _vec(w["temporal"])),
53
+ bias=float(nd.get("bias", 0.0)),
54
+ activation=float(nd.get("activation", 0.0)),
55
+ memory=[float(x) for x in nd.get("memory", [])],
56
+ uncertainty_threshold=float(nd.get("uncertainty_threshold", 0.5)),
57
+ is_alive=bool(nd.get("is_alive", True)),
58
+ label=nd.get("label"),
59
+ )
60
+ g.neurons[n.id] = n
61
+ g.adj.setdefault(n.id, [])
62
+ g.rev.setdefault(n.id, [])
63
+ for e in data.get("edges", []):
64
+ g.connect(int(e["src"]), int(e["dst"]), float(e["weight"]))
65
+ return g
66
 
67
+
68
+ def _vec(raw) -> np.ndarray:
69
+ if isinstance(raw, dict):
70
+ q = np.asarray(raw["q"], dtype=np.uint8).astype(np.int8)
71
+ scale = float(raw.get("scale", 1.0))
72
+ return (q / 127.0 * scale).astype(np.float32)
73
+ return np.asarray(raw, dtype=np.float32)
74
+
75
+
76
+ def canvas_viz_html(graph: NeuralGraph) -> str:
77
+ """Return self-contained HTML5 Canvas with 60 FPS live neural transmission."""
78
+ # Force layout via NetworkX
79
  G = nx.DiGraph()
80
+ for nid in graph.neurons:
81
+ G.add_node(nid)
82
+ for src, syns in graph.adj.items():
83
+ for s in syns:
84
+ G.add_edge(src, s.dst, weight=s.weight)
85
+
86
+ pos = nx.spring_layout(G, seed=42, k=0.55, iterations=150) if len(graph.neurons) else {}
87
+
88
+ nodes_data = []
89
  for nid, n in graph.neurons.items():
90
+ x, y = pos.get(nid, (0.0, 0.0))
91
+ lab = n.label or str(nid)
92
+ ntype = "hidden"
93
+ if nid in graph.input_ids or lab.lower().startswith("in"):
94
+ ntype = "input"
95
+ elif nid in graph.output_ids or lab.lower().startswith("out"):
96
+ ntype = "output"
97
+ elif "retrieved" in lab.lower():
98
+ ntype = "retrieved"
99
+
100
+ nodes_data.append({
101
+ "id": nid,
102
+ "label": lab,
103
+ "x": float(x),
104
+ "y": float(y),
105
+ "act": float(n.activation),
106
+ "type": ntype,
107
+ "bias": float(n.bias),
108
+ })
109
+
110
+ edges_data = []
111
+ for src, syns in graph.adj.items():
112
  for s in syns:
113
+ edges_data.append({
114
+ "src": s.src,
115
+ "dst": s.dst,
116
+ "weight": float(s.weight),
117
+ })
118
+
119
+ data_json = json.dumps({"nodes": nodes_data, "edges": edges_data, "step": graph.step_count})
120
+
121
+ return f"""<!DOCTYPE html>
122
+ <html>
123
+ <head>
124
+ <meta charset="utf-8">
125
+ <style>
126
+ html, body {{
127
+ margin: 0; padding: 0; width: 100%; height: 100%;
128
+ background: #0b1020; overflow: hidden; font-family: system-ui, sans-serif;
129
+ }}
130
+ canvas {{ display: block; width: 100%; height: 100%; }}
131
+ #hud {{
132
+ position: absolute; top: 10px; left: 12px;
133
+ color: #8899bb; font-size: 11px; pointer-events: none;
134
+ line-height: 1.5; background: rgba(11,16,32,0.7);
135
+ padding: 6px 10px; border-radius: 6px; border: 1px solid #1a2544;
136
+ }}
137
+ #hud b {{ color: #e6e9f2; }}
138
+ .pulse-dot {{
139
+ display: inline-block; width: 6px; height: 6px;
140
+ border-radius: 50%; background: #00c896;
141
+ animation: blink 1s infinite alternate; margin-right: 4px;
142
+ }}
143
+ @keyframes blink {{ from {{ opacity: 0.3; }} to {{ opacity: 1; }} }}
144
+ </style>
145
+ </head>
146
+ <body>
147
+ <div id="hud">
148
+ <div><span class="pulse-dot"></span><b>HumpBack Neural Engine</b> &bull; step <span id="stepVal">0</span></div>
149
+ <div>Neurons: <b id="nVal">0</b> | Synapses: <b id="eVal">0</b> | <span style="color:#4f6cff">● Input</span> <span style="color:#ffd166">● Hidden</span> <span style="color:#ff6b6b">● Output</span></div>
150
+ </div>
151
+ <canvas id="cv"></canvas>
152
+ <script>
153
+ const data = {data_json};
154
+ document.getElementById('stepVal').textContent = data.step;
155
+ document.getElementById('nVal').textContent = data.nodes.length;
156
+ document.getElementById('eVal').textContent = data.edges.length;
157
+
158
+ const cv = document.getElementById('cv');
159
+ const ctx = cv.getContext('2d');
160
+ let W, H;
161
+ function resize() {{
162
+ W = cv.width = window.innerWidth;
163
+ H = cv.height = window.innerHeight;
164
+ }}
165
+ window.addEventListener('resize', resize);
166
+ resize();
167
+
168
+ // Map layout coordinates to canvas bounds
169
+ const pad = 60;
170
+ let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
171
+ data.nodes.forEach(n => {{
172
+ if (n.x < minX) minX = n.x; if (n.x > maxX) maxX = n.x;
173
+ if (n.y < minY) minY = n.y; if (n.y > maxY) maxY = n.y;
174
+ }});
175
+ const spanX = (maxX - minX) || 1;
176
+ const spanY = (maxY - minY) || 1;
177
+
178
+ const nodeMap = {{}};
179
+ data.nodes.forEach(n => {{
180
+ n.cx = pad + ((n.x - minX) / spanX) * (W - pad * 2);
181
+ n.cy = pad + ((n.y - minY) / spanY) * (H - pad * 2);
182
+ n.baseRadius = n.type === 'input' ? 8 : (n.type === 'output' ? 9 : 7);
183
+ nodeMap[n.id] = n;
184
+ }});
185
+
186
+ // Particles flowing along edges
187
+ const particles = [];
188
+ data.edges.forEach((e, i) => {{
189
+ const count = Math.max(1, Math.min(4, Math.round(Math.abs(e.weight) * 2)));
190
+ for (let c = 0; c < count; c++) {{
191
+ particles.push({{
192
+ src: e.src,
193
+ dst: e.dst,
194
+ weight: e.weight,
195
+ t: (c / count) + Math.random() * 0.2,
196
+ speed: 0.006 + Math.abs(e.weight) * 0.008
197
+ }});
198
+ }}
199
+ }});
200
+
201
+ let hoverNode = null;
202
+ cv.addEventListener('mousemove', (ev) => {{
203
+ const rect = cv.getBoundingClientRect();
204
+ const mx = ev.clientX - rect.left;
205
+ const my = ev.clientY - rect.top;
206
+ hoverNode = null;
207
+ for (const n of data.nodes) {{
208
+ const d = Math.hypot(n.cx - mx, n.cy - my);
209
+ if (d < 16) {{ hoverNode = n; break; }}
210
+ }}
211
+ }});
212
+
213
+ const colorByType = {{
214
+ input: '#4f6cff',
215
+ hidden: '#ffd166',
216
+ output: '#ff6b6b',
217
+ retrieved: '#00c896'
218
+ }};
219
+
220
+ let tick = 0;
221
+ function loop() {{
222
+ tick++;
223
+ ctx.fillStyle = '#0b1020';
224
+ ctx.fillRect(0, 0, W, H);
225
+
226
+ // 1. Draw synapses
227
+ for (const e of data.edges) {{
228
+ const s = nodeMap[e.src];
229
+ const d = nodeMap[e.dst];
230
+ if (!s || !d) continue;
231
+
232
+ ctx.beginPath();
233
+ ctx.moveTo(s.cx, s.cy);
234
+ ctx.lineTo(d.cx, d.cy);
235
+ const alpha = Math.min(0.4, 0.08 + Math.abs(e.weight) * 0.18);
236
+ ctx.strokeStyle = e.weight > 0 ? `rgba(79,108,255,${{alpha}})` : `rgba(255,107,107,${{alpha}})`;
237
+ ctx.lineWidth = Math.min(2.5, 0.6 + Math.abs(e.weight));
238
+ ctx.stroke();
239
+ }}
240
+
241
+ // 2. Animate synaptic particles ("thinking" pulses)
242
+ for (const p of particles) {{
243
+ p.t += p.speed;
244
+ if (p.t > 1) p.t -= 1;
245
+ const s = nodeMap[p.src];
246
+ const d = nodeMap[p.dst];
247
+ if (!s || !d) continue;
248
+
249
+ const px = s.cx + (d.cx - s.cx) * p.t;
250
+ const py = s.cy + (d.cy - s.cy) * p.t;
251
+
252
+ ctx.beginPath();
253
+ ctx.arc(px, py, 2.0, 0, Math.PI * 2);
254
+ ctx.fillStyle = p.weight > 0 ? '#00e5ff' : '#ff9248';
255
+ ctx.shadowBlur = 6;
256
+ ctx.shadowColor = ctx.fillStyle;
257
+ ctx.fill();
258
+ ctx.shadowBlur = 0;
259
+ }}
260
+
261
+ // 3. Draw neurons
262
+ for (const n of data.nodes) {{
263
+ const wave = Math.sin(tick * 0.05 + n.id * 0.8) * 0.5 + 0.5;
264
+ const pulse = Math.abs(n.act) * 4 + wave * 2;
265
+ const r = n.baseRadius + pulse;
266
+
267
+ const baseColor = colorByType[n.type] || '#ffd166';
268
+
269
+ // Outer glow
270
+ ctx.beginPath();
271
+ ctx.arc(n.cx, n.cy, r + 4, 0, Math.PI * 2);
272
+ ctx.fillStyle = baseColor;
273
+ ctx.globalAlpha = 0.2 + wave * 0.25;
274
+ ctx.fill();
275
+ ctx.globalAlpha = 1.0;
276
+
277
+ // Core circle
278
+ ctx.beginPath();
279
+ ctx.arc(n.cx, n.cy, r, 0, Math.PI * 2);
280
+ ctx.fillStyle = baseColor;
281
+ ctx.strokeStyle = '#ffffff';
282
+ ctx.lineWidth = 1.2;
283
+ ctx.fill();
284
+ ctx.stroke();
285
+
286
+ // Label
287
+ ctx.fillStyle = '#e6e9f2';
288
+ ctx.font = '10px system-ui';
289
+ ctx.textAlign = 'center';
290
+ ctx.fillText(n.label.slice(0, 11), n.cx, n.cy - r - 4);
291
+ }}
292
+
293
+ // 4. Hover card
294
+ if (hoverNode) {{
295
+ const hn = hoverNode;
296
+ ctx.fillStyle = 'rgba(18,26,51,0.92)';
297
+ ctx.strokeStyle = '#4f6cff';
298
+ ctx.lineWidth = 1;
299
+ const cardW = 140, cardH = 55;
300
+ const cx = Math.min(W - cardW - 10, Math.max(10, hn.cx - cardW / 2));
301
+ const cy = Math.max(10, hn.cy - cardH - 18);
302
+ ctx.fillRect(cx, cy, cardW, cardH);
303
+ ctx.strokeRect(cx, cy, cardW, cardH);
304
+
305
+ ctx.fillStyle = '#fff';
306
+ ctx.font = 'bold 11px system-ui';
307
+ ctx.textAlign = 'left';
308
+ ctx.fillText(hn.label, cx + 8, cy + 16);
309
+ ctx.fillStyle = '#8899bb';
310
+ ctx.font = '10px system-ui';
311
+ ctx.fillText(`type: ${{hn.type}}`, cx + 8, cy + 30);
312
+ ctx.fillText(`act: ${{hn.act.toFixed(3)}} bias: ${{hn.bias.toFixed(2)}}`, cx + 8, cy + 44);
313
+ }}
314
+
315
+ requestAnimationFrame(loop);
316
+ }}
317
+ loop();
318
+ </script>
319
+ </body>
320
+ </html>"""
321
+
322
+
323
+ def animate_thinking(graph: NeuralGraph, out_path: str = "visualizations/brain.gif",
324
+ frames: int = 30) -> str:
325
+ """Export animated GIF showing activation wave propagation."""
326
+ G = nx.DiGraph()
327
+ for nid, n in graph.neurons.items():
328
+ G.add_node(nid, label=n.label or str(nid))
329
+ for src, syns in graph.adj.items():
330
+ for s in syns:
331
+ G.add_edge(src, s.dst, weight=s.weight)
332
+
333
+ pos = nx.spring_layout(G, seed=42, k=0.55, iterations=150)
334
+ nids = list(graph.neurons.keys())
335
+ labels = {nid: graph.neurons[nid].label or str(nid) for nid in nids}
336
+
337
+ # Simulate steps
338
+ rng = np.random.default_rng(42)
339
+ graph.reset_activations()
340
+ seed = rng.uniform(-0.3, 0.3, size=min(len(graph.input_ids), 16)).astype(np.float32)
341
+ graph.inject(dict(zip(graph.input_ids[:len(seed)], seed)))
342
+
343
+ acts = []
344
+ for _ in range(frames):
345
+ graph.step()
346
+ acts.append([graph.neurons[nid].activation for nid in nids])
347
+ acts = np.array(acts, dtype=np.float32)
348
+ denom = (acts.max() - acts.min()) or 1.0
349
+ acts = (acts - acts.min()) / denom
350
+
351
+ fig, ax = plt.subplots(figsize=(10, 7))
352
+ fig.patch.set_facecolor("#0b1020")
353
+ ax.set_facecolor("#0b1020")
354
+
355
+ def _frame(i):
356
+ ax.clear()
357
+ ax.set_facecolor("#0b1020")
358
+ ax.set_title(f"HumpBack Neural Activation Wave — Step {i+1}/{frames}",
359
+ color="#e6e9f2", fontsize=12, pad=10)
360
+
361
+ # Edges
362
+ for src, syns in graph.adj.items():
363
+ for s in syns:
364
+ if src in pos and s.dst in pos:
365
+ ax.plot([pos[src][0], pos[s.dst][0]], [pos[src][1], pos[s.dst][1]],
366
+ color="#4f6cff", alpha=0.18, linewidth=0.6)
367
+
368
+ # Nodes
369
+ step_acts = acts[i]
370
+ for idx, nid in enumerate(nids):
371
+ a = step_acts[idx]
372
+ x, y = pos[nid]
373
+ lab = labels[nid].lower()
374
+ if lab.startswith("in"):
375
+ c = "#4f6cff"
376
+ elif lab.startswith("out"):
377
+ c = "#ff6b6b"
378
+ else:
379
+ c = "#ffd166" if a < 0.6 else "#ff6b6b"
380
+ sz = 14 + a * 50
381
+ ax.scatter(x, y, s=sz, c=c, edgecolors="#ffffff", linewidth=1.2, alpha=0.9)
382
+ ax.annotate(labels[nid][:10], (x, y), fontsize=7, color="#e6e9f2",
383
+ ha="center", va="bottom", xytext=(0, 4), textcoords="offset points")
384
+
385
+ ax.axis("off")
386
+
387
+ anim = animation.FuncAnimation(fig, _frame, frames=frames, interval=150)
388
+ os.makedirs(os.path.dirname(os.path.abspath(out_path)), exist_ok=True)
389
+ anim.save(out_path, writer="pillow", fps=6, dpi=80)
390
  plt.close()
391
+ return out_path
392
+
393
 
394
+ def interactive_brain(graph: NeuralGraph, out_path: str = "visualizations/brain.html",
395
+ frames: int = 30) -> str:
396
+ """Generate Plotly interactive graph export with play/pause animation controls."""
397
+ G = nx.DiGraph()
398
+ for nid, n in graph.neurons.items():
399
+ G.add_node(nid, label=n.label or str(nid))
400
+ for src, syns in graph.adj.items():
401
+ for s in syns:
402
+ G.add_edge(src, s.dst, weight=s.weight)
403
 
404
+ pos = nx.spring_layout(G, seed=42, k=0.55, iterations=150)
405
+ nids = list(graph.neurons.keys())
406
+ labels = {nid: graph.neurons[nid].label or str(nid) for nid in nids}
 
 
 
 
 
 
 
 
407
 
408
+ rng = np.random.default_rng(42)
409
+ graph.reset_activations()
410
+ seed = rng.uniform(-0.3, 0.3, size=min(len(graph.input_ids), 16)).astype(np.float32)
411
+ graph.inject(dict(zip(graph.input_ids[:len(seed)], seed)))
412
 
413
+ acts = []
414
+ for _ in range(frames):
415
+ graph.step()
416
+ acts.append([graph.neurons[nid].activation for nid in nids])
417
+ acts = np.array(acts, dtype=np.float32)
418
+ denom = (acts.max() - acts.min()) or 1.0
419
+ acts = (acts - acts.min()) / denom
420
+
421
+ edge_x, edge_y = [], []
422
+ for src, syns in graph.adj.items():
 
 
 
 
 
 
 
 
 
 
 
423
  for s in syns:
424
+ if src in pos and s.dst in pos:
425
+ edge_x += [pos[src][0], pos[s.dst][0], None]
426
+ edge_y += [pos[src][1], pos[s.dst][1], None]
427
+
428
+ node_x = [pos[nid][0] for nid in nids]
429
+ node_y = [pos[nid][1] for nid in nids]
430
+
431
+ edge_trace = go.Scatter(x=edge_x, y=edge_y, mode="lines",
432
+ line=dict(width=0.6, color="#4f6cff"),
433
+ hoverinfo="none", showlegend=False)
434
+
435
+ colors = ["#4f6cff" if labels[n].lower().startswith("in") else
436
+ ("#ff6b6b" if labels[n].lower().startswith("out") else "#ffd166")
437
+ for n in nids]
438
+ sizes = [12 + float(acts[0][k]) * 35 for k in range(len(nids))]
439
+
440
+ node_trace = go.Scatter(
441
+ x=node_x, y=node_y, mode="markers+text",
442
+ text=[labels[n][:11] for n in nids],
443
+ textposition="top center", textfont=dict(color="#e6e9f2", size=9),
444
+ marker=dict(size=sizes, color=colors, line=dict(width=1.2, color="#fff")),
445
+ hoverinfo="text",
446
+ hovertext=[f"{labels[n]} (act={acts[0][k]:.2f})" for k, n in enumerate(nids)],
447
+ name="neurons"
448
+ )
449
+
450
  fig = go.Figure(data=[edge_trace, node_trace])
 
 
 
 
 
451
 
452
+ frames_list = []
453
+ for i in range(frames):
454
+ f_sizes = [12 + float(acts[i][k]) * 35 for k in range(len(nids))]
455
+ frames_list.append(go.Frame(
456
+ name=str(i),
457
+ data=[go.Scatter(
458
+ x=node_x, y=node_y, mode="markers+text",
459
+ marker=dict(size=f_sizes, color=colors, line=dict(width=1.2, color="#fff"))
460
+ )],
461
+ layout=go.Layout(title=f"HumpBack — step {i+1}/{frames}")
462
+ ))
463
+ fig.frames = frames_list
464
 
465
+ steps = [dict(
466
+ method="animate",
467
+ args=[[str(i)], dict(frame=dict(duration=100), mode="immediate")],
468
+ label=str(i + 1)
469
+ ) for i in range(frames)]
470
+
471
+ fig.update_layout(
472
+ title="HumpBack Neural Graph — Thinking Animation",
473
+ showlegend=False,
474
+ xaxis=dict(visible=False), yaxis=dict(visible=False),
475
+ plot_bgcolor="#0b1020", paper_bgcolor="#0b1020",
476
+ font=dict(color="#e6e9f2"),
477
+ updatemenus=[dict(
478
+ type="buttons", showactive=False,
479
+ buttons=[
480
+ dict(label="Play", method="animate", args=[None, dict(frame=dict(duration=120), transition=dict(duration=40))]),
481
+ dict(label="Pause", method="animate", args=[[None], dict(frame=dict(duration=0), mode="immediate")]),
482
+ ]
483
+ )],
484
+ sliders=[dict(steps=steps, currentvalue=dict(prefix="step: ", font=dict(color="#e6e9f2")))]
485
+ )
486
+
487
+ os.makedirs(os.path.dirname(os.path.abspath(out_path)), exist_ok=True)
488
+ fig.write_html(out_path, include_plotlyjs="inline", auto_open=False)
489
+ return out_path
490
+
491
+
492
+ def plot_weights(graph: NeuralGraph, path: str = "visualizations/weights.png") -> str:
493
+ """Save 3-panel static PNG of Concept, Spatial, Temporal weight vectors."""
494
  os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
495
+ neurons = list(graph.neurons.values())
496
+ if not neurons:
497
  return path
498
+ C = np.asarray([n.weights.concept for n in neurons])
499
+ S = np.asarray([n.weights.spatial for n in neurons])
500
+ T = np.asarray([n.weights.temporal for n in neurons])
501
+ fig, axes = plt.subplots(1, 3, figsize=(15, 6))
502
+ for ax, M, title in zip(axes, (C, S, T), ("Concept", "Spatial", "Temporal")):
503
+ im = ax.imshow(M, aspect="auto", cmap="coolwarm", vmin=-1, vmax=1)
504
+ ax.set_title(f"{title} weights ({M.shape[0]} neurons x {M.shape[1]})")
505
+ ax.set_xlabel("dimension")
506
+ ax.set_ylabel("neuron")
507
+ fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04)
508
  plt.tight_layout()
509
  plt.savefig(path, dpi=120)
510
  plt.close()
511
+ return path
weights.zip CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:a7304edf0c5c74151277997107c977dc60f05a81d466f472e17953ef7e9b5784
3
- size 34461
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1aed98e6dc8a627c8527f98f00175a76227c6670bfaf82276b465c724f516a80
3
+ size 108394