Positronic-144M / visualize.py
Quazim0t0's picture
Package full source (code, tokenizer, viz, training); add Dean Byrne citation; add chkpt/quazimoto_sft.pt
276dfb7 verified
Raw History Blame Contribute Delete
17.1 kB
"""
visualize.py -- generate while capturing internal state, then emit a self-contained
HTML dashboard showing what the model is doing token-by-token.
Pipeline:
1. auto-find the checkpoint (newest *.pt in ./chkpt, or --ckpt)
2. activate the instrument.Recorder and generate --tokens tokens (one full forward
per token so every position is live), capturing per token:
* ring synchronization -- order parameter R + phase psi per ring per layer,
and individual oscillator phases for one layer (the dot-circle view)
* trait activity -- HRM/MoE contribution norms, per-layer quaz norm
* attention -- last-query attention over the context (one layer)
* specialist routing -- per-ring MoE routing over the 7 memory specialists
3. run a short speculative-decode pass and capture draft/accept per cycle
4. write a single HTML file (data embedded -> opens via file:// with no server)
and open it in the browser.
Usage:
python visualize.py --prompt "the quazimoto oscillator" --tokens 60
"""
import argparse
import json
import os
import sys
import webbrowser
import torch
from model import QuazimotoLM, QuazimotoConfig
import instrument
from generate import generate_speculative
PKG_DIR = os.path.dirname(os.path.abspath(__file__))
def find_ckpt(path):
if path and os.path.isfile(path):
return path
folder = (os.path.dirname(path) if path else os.path.join(PKG_DIR, "chkpt")) or "."
if not os.path.isdir(folder):
return None
pts = [os.path.join(folder, f) for f in os.listdir(folder) if f.endswith(".pt")]
return max(pts, key=os.path.getmtime) if pts else None
def load_tokenizer(tok_dir):
sys.path.insert(0, tok_dir)
from spike_tokenizer import SpikeTokenizer
return SpikeTokenizer(vocab_file=os.path.join(tok_dir, "tokenizer.json"))
@torch.no_grad()
def run_capture(model, cfg, tok, ids, n_tokens, temperature, top_k, device):
"""Greedy/sampled generation with full per-token capture (no KV cache so the
last position always reflects the freshly predicted token)."""
rec = instrument.Recorder(phase_layer=cfg.n_layer // 2, attn_layer=cfg.n_layer // 2)
instrument.set_rec(rec)
idx = torch.tensor([ids], device=device)
try:
for _ in range(n_tokens):
cond = idx[:, -cfg.block_size:]
rec.begin()
logits, _, _ = model(cond)
lg = torch.nan_to_num(logits[:, -1, :].float(), nan=0.0,
posinf=1e4, neginf=-1e4) / max(temperature, 1e-6)
if top_k:
v = torch.topk(lg, min(top_k, lg.size(-1))).values
lg = lg.masked_fill(lg < v[:, [-1]], float("-inf"))
probs = torch.softmax(lg, dim=-1)
nxt = (torch.argmax(lg, dim=-1, keepdim=True) if temperature <= 1e-3
else torch.multinomial(probs, 1))
top = torch.topk(torch.softmax(logits[:, -1].float(), -1), 5)
rec.end(token=int(nxt),
char=tok.decode([int(nxt)], skip_special_tokens=False),
top=[[int(t), round(float(p), 3)] for t, p in zip(top.indices[0], top.values[0])])
idx = torch.cat([idx, nxt], dim=1)
finally:
instrument.set_rec(None)
return rec.frames, idx[0].tolist()
def main():
p = argparse.ArgumentParser(description="Quazimoto-LM live visualizer")
p.add_argument("--ckpt", default="", help="checkpoint (default: newest in ./chkpt)")
p.add_argument("--tok_dir", default=PKG_DIR)
p.add_argument("--prompt", default="the quazimoto oscillator")
p.add_argument("--tokens", type=int, default=60)
p.add_argument("--temperature", type=float, default=0.0, help="0 = greedy")
p.add_argument("--top_k", type=int, default=40)
p.add_argument("--device", default="cpu")
p.add_argument("--out", default=os.path.join(PKG_DIR, "viz.html"))
p.add_argument("--no_open", action="store_true", help="write the HTML but don't open a browser")
args = p.parse_args()
path = find_ckpt(args.ckpt)
if path is None:
print("No checkpoint found; pass --ckpt or train one."); return
ckpt = torch.load(path, map_location=args.device, weights_only=False)
cfg = QuazimotoConfig(**ckpt["family_config"])
model = QuazimotoLM(cfg)
model.load_state_dict(ckpt["model"], strict=False)
model.to(args.device).eval()
tok = load_tokenizer(args.tok_dir)
print(f"loaded {path} (step {ckpt.get('step')}) | capturing {args.tokens} tokens ...")
ids = tok.encode(args.prompt, add_special_tokens=False)
frames, full = run_capture(model, cfg, tok, ids, args.tokens,
args.temperature, args.top_k or None, args.device)
# speculative-decode trace (only if MTP heads exist)
spec = None
if model.mtp_heads is not None:
tr = []
generate_speculative(model, cfg, torch.tensor([ids], device=args.device),
min(args.tokens, 40), trace=tr)
spec = {"cycles": [{"drafts": [tok.decode([t], skip_special_tokens=False) for t in c["drafts"]],
"accepted": c["accepted"],
"correction": tok.decode([c["correction"]], skip_special_tokens=False)}
for c in tr]}
ring_sizes = list(cfg.ring_sizes)
data = {
"meta": {"ckpt": os.path.basename(path), "step": ckpt.get("step"),
"n_layer": cfg.n_layer, "ring_sizes": ring_sizes, "n_osc": cfg.n_osc,
"phase_layer": cfg.n_layer // 2, "attn_layer": cfg.n_layer // 2,
"prompt": args.prompt, "prompt_len": len(ids),
"use_specialists": cfg.use_ring_specialists,
"n_specialists": cfg.ring_n_specialists if cfg.use_ring_specialists else 0},
"prompt_chars": [tok.decode([t], skip_special_tokens=False) for t in ids],
"frames": frames, "spec": spec,
}
html = HTML_TEMPLATE.replace("/*__DATA__*/", json.dumps(data))
with open(args.out, "w", encoding="utf-8") as f:
f.write(html)
print(f"wrote {args.out} ({os.path.getsize(args.out)//1024} KB)")
if not args.no_open:
webbrowser.open("file://" + os.path.abspath(args.out))
# --------------------------------------------------------------------------- #
# self-contained dashboard (data injected at /*__DATA__*/)
# --------------------------------------------------------------------------- #
HTML_TEMPLATE = r"""<!doctype html>
<html><head><meta charset="utf-8"><title>Quazimoto-LM live</title>
<style>
:root{--bg:#0d1117;--panel:#161b22;--ink:#e6edf3;--mut:#8b949e;--ac:#58a6ff;--hot:#f78166;}
*{box-sizing:border-box} body{margin:0;background:var(--bg);color:var(--ink);
font:13px/1.4 ui-monospace,Menlo,Consolas,monospace}
header{padding:10px 16px;background:var(--panel);border-bottom:1px solid #30363d;
display:flex;gap:16px;align-items:center;flex-wrap:wrap}
h1{font-size:15px;margin:0;color:var(--ac)} .mut{color:var(--mut)}
#wrap{display:grid;grid-template-columns:340px 1fr 320px;gap:12px;padding:12px}
.panel{background:var(--panel);border:1px solid #30363d;border-radius:8px;padding:10px}
.panel h2{font-size:12px;margin:0 0 8px;color:var(--mut);text-transform:uppercase;letter-spacing:.5px}
#stream{line-height:1.9;max-height:120px;overflow:auto}
.tk{padding:1px 2px;border-radius:3px;cursor:pointer;white-space:pre}
.tk.prompt{color:var(--mut)} .tk.cur{background:var(--ac);color:#000}
.tk:hover{background:#30363d}
.ctrl{display:flex;gap:10px;align-items:center}
input[type=range]{width:260px} button{background:#21262d;color:var(--ink);
border:1px solid #30363d;border-radius:6px;padding:4px 10px;cursor:pointer}
button:hover{border-color:var(--ac)}
.bar{height:10px;background:#21262d;border-radius:5px;overflow:hidden;margin:2px 0}
.bar>div{height:100%;background:var(--ac)}
table{border-collapse:collapse;width:100%} td{padding:1px 4px}
.lbl{color:var(--mut);width:46px} svg{display:block;width:100%;height:auto}
.grid{display:grid;gap:3px} .cell{height:16px;border-radius:2px}
.small{font-size:11px;color:var(--mut)}
</style></head><body>
<header>
<h1>Quazimoto-LM &middot; live</h1>
<span class="mut" id="meta"></span>
<span style="flex:1"></span>
<div class="ctrl">
<button id="play">▶ play</button>
<input type="range" id="seek" min="0" value="0">
<span id="pos" class="mut"></span>
</div>
</header>
<div id="wrap">
<div style="display:flex;flex-direction:column;gap:12px">
<div class="panel"><h2>Token stream</h2><div id="stream"></div></div>
<div class="panel"><h2>Trait activity (this token)</h2><div id="traits"></div></div>
<div class="panel"><h2>Top predictions</h2><div id="top"></div></div>
</div>
<div style="display:flex;flex-direction:column;gap:12px">
<div class="panel"><h2>Ring synchronization &mdash; layer <span id="pl"></span> (dot = oscillator phase)</h2>
<svg id="rings" viewBox="0 0 460 460"></svg></div>
<div class="panel"><h2>Order parameter R per ring &times; layer (bright = synchronized)</h2>
<div id="heat"></div></div>
<div class="panel"><h2>Fractal phase seed &mdash; Mandelbrot orbit (layer <span id="fl"></span>)</h2>
<svg id="fract" viewBox="0 0 460 460"></svg>
<div class="small">token's orbit-angle seed: the phases the oscillator bank starts from, before Kuramoto settles them</div>
<h2 style="margin-top:8px">Fractal injection gate tanh(gate) per layer</h2><div id="fgate"></div></div>
</div>
<div style="display:flex;flex-direction:column;gap:12px">
<div class="panel"><h2>Attention &mdash; layer <span id="al"></span> (last token &rarr; context)</h2>
<div id="attn"></div></div>
<div class="panel"><h2>Specialist routing (per ring &times; 7)</h2><div id="route"></div></div>
<div class="panel"><h2>Speculative decode (MTP draft &rarr; verify)</h2><div id="spec"></div></div>
</div>
</div>
<script>
const D = /*__DATA__*/;
const M = D.meta, F = D.frames, RS = M.ring_sizes, NL = M.n_layer;
let i = 0, playing = false, timer = null;
const $ = id => document.getElementById(id);
$("meta").textContent = `${M.ckpt} · step ${M.step} · ${NL} layers · rings [${RS}] · ${M.n_osc} osc/token · "${M.prompt}"`;
$("pl").textContent = M.phase_layer; $("al").textContent = M.attn_layer;
const seek = $("seek"); seek.max = F.length - 1;
// hue for a value in [0,1]: blue(cold)->orange(hot)
const hue = v => `hsl(${(1-Math.max(0,Math.min(1,v)))*210},80%,${30+40*Math.max(0,Math.min(1,v))}%)`;
// token stream
const stream = $("stream");
D.prompt_chars.forEach(c => { const s=document.createElement("span"); s.className="tk prompt"; s.textContent=esc(c); stream.appendChild(s); });
F.forEach((f,k)=>{ const s=document.createElement("span"); s.className="tk gen"; s.textContent=esc(f.char);
s.onclick=()=>{i=k;render()}; s.dataset.k=k; stream.appendChild(s); });
function esc(c){return c.replace(/\n/g,"⏎").replace(/ /g,"·");}
function ringsSVG(f){
const cx=230,cy=230,maxR=205,svg=$("rings"); let h="";
// concentric guide circles + dots
RS.forEach((n,r)=>{
const rad = maxR*(r+1)/RS.length;
h+=`<circle cx=${cx} cy=${cy} r=${rad} fill="none" stroke="#30363d" stroke-width="1"/>`;
});
if(f.phases){
let off=0;
RS.forEach((n,r)=>{
const rad = maxR*(r+1)/RS.length;
const Rval = f.rings[f.phases.layer] ? f.rings[f.phases.layer].R[r] : 0;
for(let j=0;j<n;j++){
const th=f.phases.theta[off+j];
const x=cx+rad*Math.cos(th), y=cy+rad*Math.sin(th);
h+=`<circle cx=${x.toFixed(1)} cy=${y.toFixed(1)} r="2.4" fill="${hue(Rval)}"/>`;
}
// mean-field vector (resultant) per ring
const psi=f.rings[f.phases.layer].psi[r];
h+=`<line x1=${cx} y1=${cy} x2=${(cx+rad*Rval*Math.cos(psi)).toFixed(1)} y2=${(cy+rad*Rval*Math.sin(psi)).toFixed(1)} stroke="#fff" stroke-width="1" opacity=".5"/>`;
off+=n;
});
}
svg.innerHTML=h;
}
function heat(f){
// rows = rings, cols = layers, color = R
let h=`<div class="grid" style="grid-template-columns:auto repeat(${NL},1fr)">`;
h+=`<div class="small"></div>`; for(let l=0;l<NL;l++) h+=`<div class="small" style="text-align:center">L${l}</div>`;
RS.forEach((n,r)=>{
h+=`<div class="small">r${r}(${n})</div>`;
for(let l=0;l<NL;l++){ const R=f.rings[l]?f.rings[l].R[r]:0;
h+=`<div class="cell" title="L${l} ring${r} R=${R.toFixed(2)}" style="background:${hue(R)}"></div>`; }
});
h+="</div>"; $("heat").innerHTML=h;
}
function fractalV(f){
const fr=f.fractal;
if(!fr||!fr.seed){ $("fract").innerHTML=""; $("fgate").innerHTML="<span class='small'>fractal seeding off</span>"; return; }
$("fl").textContent=fr.seed.layer;
const cx=230,cy=230,maxR=205; let h="";
RS.forEach((n,r)=>{ const rad=maxR*(r+1)/RS.length;
h+=`<circle cx=${cx} cy=${cy} r=${rad} fill="none" stroke="#30363d" stroke-width="1"/>`; });
let off=0;
RS.forEach((n,r)=>{ const rad=maxR*(r+1)/RS.length, col=`hsl(${290-32*r},85%,62%)`;
for(let j=0;j<n;j++){ const th=fr.seed.theta[off+j];
const x=cx+rad*Math.cos(th), y=cy+rad*Math.sin(th);
h+=`<circle cx=${x.toFixed(1)} cy=${y.toFixed(1)} r="2.2" fill="${col}"/>`; }
off+=n; });
$("fract").innerHTML=h;
const gs=fr.gate, mx=Math.max(1e-6,...gs.map(Math.abs)); let hb="<table>";
gs.forEach((v,l)=>{ const w=Math.abs(v)/mx, col=v>=0?"#58a6ff":"#f78166";
hb+=`<tr><td class="lbl">L${l}</td><td style="width:100%"><div class="bar"><div style="width:${(w*100).toFixed(0)}%;background:${col}"></div></div></td><td class="small">${v.toFixed(3)}</td></tr>`; });
hb+="</table>"; $("fgate").innerHTML=hb;
}
function bars(el,arr,labels,fmt){
let h="<table>";
arr.forEach((v,k)=>{ const w=Math.max(0,Math.min(1,v));
h+=`<tr><td class="lbl">${labels[k]}</td><td style="width:100%"><div class="bar"><div style="width:${(w*100).toFixed(0)}%;background:${hue(w)}"></div></div></td><td class="small">${fmt(v)}</td></tr>`;});
h+="</table>"; el.innerHTML=h;
}
function render(){
const f=F[i];
$("pos").textContent=`${i+1}/${F.length}`; seek.value=i;
document.querySelectorAll(".tk.gen").forEach(s=>s.classList.toggle("cur",+s.dataset.k===i));
ringsSVG(f); heat(f); fractalV(f);
// traits: per-layer quaz norm (normalized) + hrm/moe
const qn=f.quaz_norm, mx=Math.max(...qn,1e-6);
let tlabels=qn.map((_,l)=>"quaz L"+l), tvals=qn.map(v=>v/mx);
if(f.traits.hrm!=null){tlabels.push("HRM");tvals.push(Math.min(1,f.traits.hrm/mx));}
if(f.traits.moe!=null){tlabels.push("MoE");tvals.push(Math.min(1,f.traits.moe/mx));}
bars($("traits"),tvals,tlabels,v=>(v).toFixed(2));
// top predictions
let th="<table>"; f.top.forEach(([t,p])=>{th+=`<tr><td class="lbl">${p.toFixed(2)}</td><td><div class="bar"><div style="width:${(p*100).toFixed(0)}%"></div></div></td><td class="small">id ${t}</td></tr>`;});
th+="</table>"; $("top").innerHTML=th;
// attention over context
if(f.attn){ const w=f.attn.w, m=Math.max(...w,1e-6);
let h="<div style='display:flex;flex-wrap:wrap;gap:1px'>";
w.forEach((a,p)=>{h+=`<div title="pos ${p}: ${a.toFixed(3)}" style="width:8px;height:14px;background:${hue(a/m)}"></div>`;});
h+="</div><div class='small'>"+w.length+" context positions</div>"; $("attn").innerHTML=h;
} else $("attn").innerHTML="<span class='small'>n/a</span>";
// specialist routing: rows=rings, cols=specialists
if(f.spec && f.spec.length){ const layer=Math.min(M.phase_layer,f.spec.length-1); const sp=f.spec[layer];
let h=`<div class='small'>layer ${layer}</div><div class="grid" style="grid-template-columns:auto repeat(${M.n_specialists},1fr)">`;
h+="<div class='small'></div>"; for(let s=0;s<M.n_specialists;s++) h+=`<div class='small' style='text-align:center'>${s}</div>`;
sp.forEach((row,r)=>{ h+=`<div class='small'>r${r}</div>`;
row.forEach(v=>{h+=`<div class="cell" title="${v.toFixed(2)}" style="background:${hue(v)}"></div>`;});});
h+="</div>"; $("route").innerHTML=h;
} else $("route").innerHTML="<span class='small'>specialists off</span>";
// spec decode
if(D.spec){ let h="";
D.spec.cycles.slice(0,12).forEach((c,k)=>{ h+=`<div style="margin:3px 0">`;
c.drafts.forEach((d,j)=>{ const ok=j<c.accepted;
h+=`<span class="tk" style="background:${ok?'#1f6f3f':'#5a1d1d'};color:#fff">${esc(d)}</span>`;});
h+=` <span class="small">→ ${esc(c.correction)} (${c.accepted}/${c.drafts.length} ok)</span></div>`;});
$("spec").innerHTML=h;
} else $("spec").innerHTML="<span class='small'>no MTP heads</span>";
}
seek.oninput=()=>{i=+seek.value;render()};
$("play").onclick=()=>{ playing=!playing; $("play").textContent=playing?"⏸ pause":"▶ play";
if(playing) timer=setInterval(()=>{i=(i+1)%F.length;render();},400); else clearInterval(timer); };
document.onkeydown=e=>{ if(e.key==="ArrowRight"){i=Math.min(F.length-1,i+1);render();}
if(e.key==="ArrowLeft"){i=Math.max(0,i-1);render();} };
render();
</script></body></html>"""
if __name__ == "__main__":
main()