""" 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"""