#!/usr/bin/env python3 """Landing page of `recur`: the computed header picture and the data-driven page sections. python3 -m venv .venv && .venv/bin/pip install -r book/requirements.txt # once (brings numpy, pillow) .venv/bin/python -I scripts/generate_hero.py # pictures + page python3 -I scripts/generate_hero.py --page-only # page only (stdlib) 1. THE PICTURE (assets/hero.webp, hero.jpg, og.png, favicon.png, logo.png; facts in assets/hero-facts.json) is the sliding-window source pattern of the released ARLoop-0.6B model, obtained by simulating the bookkeeping of its forward pass: for each of the 108 effective sublayers (18 physical layers x 3 loops x {attention, FFN}) and for the final readout, which residual sources the depth attention can read. Rows are sources: the embedding b0 (bottom) and the residual blocks b1..b6; columns are routing calls in order. A block appears as an aqua wedge while it is the partial block (its height grows with the number of sublayer updates it holds), becomes a blue tile once committed, and disappears when it leaves the window; the embedding is orange, and so is the core of b1, which starts from the embedding (finding F6). If the coordinator's routing probe `runs/e1/routing/ar06-R3/routing.json` exists, every tile is blended over the background with opacity 0.15 + 0.85 * w**0.6, where w is the measured mean routing weight; otherwise all visible tiles are drawn at full opacity. The left part of the picture fades into the page background (#0b1020) so that the title stays readable; the other edges fade too, so the picture can be letterboxed by the page without a visible border. The simulation is a transcription of `ARLoopForCausalLM.forward` / `_route` of `osunlp/ARLoop-0.6B` @ 5cd28f3dbf0d46a7f82f9d34b62aca42ac0ab039 (modeling_arloop.py lines 131-134 and 189-206; digest section 2), with the configuration values of its config.json: blocks, partial = [embedding], embedding for every effective layer e: route(attention) ; if e > 0 and e % 9 == 0: commit partial ; partial += attention ; route(FFN) ; partial += FFN route(readout) route(...) sees blocks + [partial], cut to [embedding] + the 3 most recent if longer. CHECKS that stop the script if the picture would show something false: at most 4 sources per routing call, and exactly min(4, available); the embedding visible at every call; blocks committed at effective layers 9, 18, 27, 36, 45; every block = 9 consecutive layers, two per loop, none straddling a loop boundary; the digest's worked example at effective layer 36; F6 (only b1 contains the embedding); the routing parameter count (one query and one RMSNorm weight per routing call) equals the parameter gap between ARLoop-0.6B and PreNormLoop-0.6B recorded in source/SOURCE.md; when routing.json exists, its source lists equal the simulated windows call by call and its weights are distributions; and in the rendered picture, every visible tile lies outside the faded zones and the tile count equals the number of visible (call, source) pairs. 2. THE PAGE: regions of index.html between `` and `` are rewritten from files, never typed: the cards' availability, the talk in three lines, the claims and the findings (artifacts/mathematical/digest.md), the plan of the minutes (slides/OUTLINE.md), the test cells and their status (labyrinth/cells.json, runs/*/summary.json, runs/e1/figures/*.svg), "About the image" (the facts computed here), and a build stamp. Everything outside the markers is left as it is. """ from __future__ import annotations import argparse import datetime as dt import html import json import re import sys from collections import Counter from dataclasses import dataclass, field from pathlib import Path ROOT = Path(__file__).resolve().parents[1] ASSETS = ROOT / "assets" INDEX = ROOT / "index.html" DIGEST = ROOT / "artifacts" / "mathematical" / "digest.md" OUTLINE = ROOT / "slides" / "OUTLINE.md" SOURCE_MD = ROOT / "source" / "SOURCE.md" CELLS = ROOT / "labyrinth" / "cells.json" RUNS = ROOT / "runs" ROUTING = RUNS / "e1" / "routing" / "ar06-R3" / "routing.json" FACTS = ASSETS / "hero-facts.json" # --------------------------------------------------------------------------------------------- # The model: config.json of osunlp/ARLoop-0.6B @ 5cd28f3dbf0d46a7f82f9d34b62aca42ac0ab039 # (SHA-256 d4de7ddcfc27fc1a4d672339ebea7726d3b2085758ea1a1e5c59db4db3fbf365), as in digest section 2. # --------------------------------------------------------------------------------------------- REPO, REVISION = "osunlp/ARLoop-0.6B", "5cd28f3dbf0d46a7f82f9d34b62aca42ac0ab039" CONFIG = {"physical_layers": 18, "loop_count": 3, "num_hidden_layers": 54, "attnres_block_size": 18, "sw_blocks": 3, "hidden_size": 1536} DIGEST_COMMITS = [9, 18, 27, 36, 45] # digest section 2: "committed at effective layers ..." BG = (11, 16, 32) # page background behind the hero (#0b1020) EMBED = (217, 89, 38) # embedding b0 and the embedding inside b1: orange BLOCK = (57, 135, 229) # completed residual block: blue PARTIAL = (25, 158, 112) # partial block (under construction): aqua FOG = (30, 40, 66) # grid positions not visible to the routing call INK = (120, 134, 166) # labels inside the picture TITLE = "ARLoop: attention over depth for looped transformers" SUBTITLE = "review and tests in the recurrent-proof regime" # ============================================================================================= # 1. Simulation of the block bookkeeping # ============================================================================================= @dataclass class Block: id: int # 0 = embedding, i = residual block b_i embedding: bool # holds the embedding (b0 itself, and b1: F6) updates: list = field(default_factory=list) # (effective layer, "attn" | "ffn") @dataclass class Call: k: int # routing call 0..108, the key in routing.json sublayer: int | None # 0..107; None for the readout layer: int | None # effective layer 0..53 kind: str # "attn" | "ffn" | "readout" window: tuple # visible sources (the partial has the id it will get) available: int # completed blocks (b0 included) + the partial partial: int # id of the partial block partial_updates: int # sublayer updates inside the partial partial_layers: tuple # effective layers whose updates it holds def simulate(cfg: dict): sw, period = cfg["sw_blocks"], cfg["attnres_block_size"] // 2 blocks = [Block(0, True)] partial = Block(1, True) # `blocks, partial = [embedded], embedded` (F6) calls, commits = [], [] def route(sublayer, layer, kind): ids = [b.id for b in blocks] + [partial.id] window = ids if len(ids) <= sw + 1 else [ids[0], *ids[-sw:]] calls.append(Call(len(calls), sublayer, layer, kind, tuple(window), len(ids), partial.id, len(partial.updates), tuple(sorted({e for e, _ in partial.updates})))) for loop in range(cfg["loop_count"]): for i in range(cfg["physical_layers"]): e = loop * cfg["physical_layers"] + i route(2 * e, e, "attn") if e > 0 and e % period == 0: blocks.append(partial) commits.append(e) partial = Block(partial.id + 1, False) partial.updates.append((e, "attn")) route(2 * e + 1, e, "ffn") partial.updates.append((e, "ffn")) route(None, None, "readout") return calls, blocks, partial, commits def parameter_counts() -> dict: """Parameter counts of the released checkpoints, as recorded in source/SOURCE.md.""" text = SOURCE_MD.read_text(encoding="utf-8") out = {} for repo in ("osunlp/ARLoop-0.6B", "osunlp/PreNormLoop-0.6B"): m = re.search(re.escape(repo) + r"`\s*@\s*`[0-9a-f]+`\s*—\s*([\d,]+) parameters", text) if not m: raise SystemExit(f"CHECK FAILED: no parameter count for {repo} in {SOURCE_MD}") out[repo] = int(m.group(1).replace(",", "")) return out def check_structure(cfg, calls, blocks, final, commits) -> dict: """Assertions on the simulated structure; returns the facts the page states.""" def need(cond, msg): if not cond: raise SystemExit("CHECK FAILED: " + msg) n_layers, phys, sw = cfg["num_hidden_layers"], cfg["physical_layers"], cfg["sw_blocks"] period = cfg["attnres_block_size"] // 2 need(n_layers == phys * cfg["loop_count"], "effective layers != physical layers x loops") subs = [c for c in calls if c.kind != "readout"] need(len(subs) == 2 * n_layers == 108, "not 108 effective sublayers") need([c.sublayer for c in subs] == list(range(2 * n_layers)), "sublayers out of order") need(len(calls) == 2 * n_layers + 1 and calls[-1].kind == "readout", "readout call missing") for c in calls: need(len(c.window) <= sw + 1, f"call {c.k}: more than {sw + 1} sources") need(len(c.window) == min(sw + 1, c.available), f"call {c.k}: window smaller than allowed") need(c.window[0] == 0, f"call {c.k}: embedding not visible") need(list(c.window) == sorted(set(c.window)), f"call {c.k}: sources repeated or unordered") need(c.window[-1] == c.partial, f"call {c.k}: partial block not visible") need(commits == DIGEST_COMMITS, f"commits at {commits}, digest says {DIGEST_COMMITS}") residual = blocks[1:] + [final] need([b.id for b in residual] == list(range(1, len(residual) + 1)), "block ids not consecutive") starts = [] for b in residual: layers = sorted({e for e, _ in b.updates}) need(len(b.updates) == 2 * period, f"b{b.id}: {len(b.updates)} sublayer updates, not {2 * period}") need(layers == list(range(layers[0], layers[0] + period)), f"b{b.id}: layers not consecutive") need(layers[0] // phys == layers[-1] // phys, f"b{b.id} straddles a loop boundary") starts.append(layers[0]) per_loop = Counter(s // phys for s in starts) need(sorted(per_loop) == list(range(cfg["loop_count"])) and set(per_loop.values()) == {2}, f"blocks per loop {dict(per_loop)}, expected two in each loop") need(residual[0].embedding and not any(b.embedding for b in residual[1:]), "F6: only b1 should start from the embedding") # worked example of the digest (section 2): first sublayer of loop 3 = effective layer 36 a36 = next(c for c in calls if c.layer == 36 and c.kind == "attn") f36 = next(c for c in calls if c.layer == 36 and c.kind == "ffn") need(a36.window == (0, 2, 3, 4) and a36.partial_layers == tuple(range(27, 36)), f"layer 36 attention reads {a36.window} with partial layers {a36.partial_layers}") need(f36.window == (0, 3, 4, 5) and f36.partial_layers == (36,) and f36.partial_updates == 1, f"layer 36 FFN reads {f36.window}") # routing parameters: one query and one RMSNorm weight vector per routing call (finding F1) vectors = 2 * len(calls) counts = parameter_counts() gap = counts["osunlp/ARLoop-0.6B"] - counts["osunlp/PreNormLoop-0.6B"] need(vectors * cfg["hidden_size"] == gap, f"{vectors} x {cfg['hidden_size']} routing parameters != recorded gap {gap}") life = {} for c in calls: for s in c.window: role = "embedding" if s == 0 else ("partial" if s == c.partial else "block") life.setdefault(s, {}).setdefault(role, []).append(c.k) lifetimes = {} for s, roles in sorted(life.items()): ks = sorted(k for v in roles.values() for k in v) need(ks == list(range(ks[0], ks[-1] + 1)), f"b{s} visible with gaps") lifetimes[f"b{s}"] = {r: [min(v), max(v)] for r, v in roles.items()} sizes = Counter(len(c.window) for c in calls) b1_last = lifetimes["b1"]["block"][1] return { "model": f"{REPO} @ {REVISION}", "config": cfg, "sublayers": len(subs), "routing_calls": len(calls), "commit_layers": commits, "window_size_counts": {str(k): sizes[k] for k in sorted(sizes)}, "visible_pairs": sum(len(c.window) for c in calls), "first_full_window_sublayer": next(c.sublayer for c in calls if len(c.window) == sw + 1), "lifetimes": lifetimes, "b1_last_sublayer": b1_last, "b1_last_layer": calls[b1_last].layer, "b1_last_kind": calls[b1_last].kind, "routing_vectors": vectors, "routing_parameters": vectors * cfg["hidden_size"], "parameter_counts": counts, } def _rel(path: Path) -> str: try: return str(path.relative_to(ROOT)) except ValueError: return str(path) def load_routing(calls) -> dict | None: """The coordinator's routing probe, checked call by call against the simulation.""" if not ROUTING.exists(): return None data = json.loads(ROUTING.read_text(encoding="utf-8")) rows = data.get("routing") def need(cond, msg): if not cond: raise SystemExit(f"CHECK FAILED ({_rel(ROUTING)}): {msg}") meta = data.get("model") or {} need(meta.get("repo", REPO) == REPO and meta.get("revision", REVISION) == REVISION, f"model {meta}") need(meta.get("loops", 3) == CONFIG["loop_count"] and meta.get("rule") in (None, ""), f"loops/rule {meta}") need(isinstance(rows, list) and len(rows) == len(calls), f"{len(rows or [])} routing entries, expected {len(calls)}") weights = [] for row, c in zip(sorted(rows, key=lambda r: r["sublayer"]), calls): need(row["sublayer"] == c.k, f"entry {row['sublayer']} where call {c.k} was expected") need(tuple(row["sources"]) == c.window, f"call {c.k}: sources {row['sources']} != simulated {list(c.window)}") w = [float(x) for x in row["weights"]] need(len(w) == len(c.window), f"call {c.k}: {len(w)} weights for {len(c.window)} sources") need(all(-1e-6 <= x <= 1 + 1e-6 for x in w) and abs(sum(w) - 1) < 1e-3, f"call {c.k}: weights {w}") weights.append(dict(zip(c.window, w))) return {"weights": weights, "n_prompts": data.get("n_prompts"), "job_id": data.get("job_id"), "path": _rel(ROUTING)} # ============================================================================================= # 2. Rendering (numpy + pillow, imported only here) # ============================================================================================= def _font(size: int, bold: bool = False): from PIL import ImageFont names = (["DejaVuSans-Bold.ttf", "Arial Bold.ttf", "/System/Library/Fonts/Supplemental/Arial Bold.ttf"] if bold else ["DejaVuSans.ttf", "Arial.ttf", "/System/Library/Fonts/Supplemental/Arial.ttf"]) for name in names: try: return ImageFont.truetype(name, size) except OSError: continue try: return ImageFont.load_default(size=size) except TypeError: # Pillow < 10.1 return ImageFont.load_default() def _smooth(t): import numpy as np t = np.clip(t, 0.0, 1.0) return t * t * (3 - 2 * t) def render(calls, routing, W, H, box, *, labels=True, row_labels=True, fade_left=True, title=False, ss=2): """Draw the source pattern into box = (x0, y0, x1, y1) as fractions of the canvas. Returns (PIL image, list of drawn tiles). A tile is (call k, source id, role, rectangle). """ import numpy as np from PIL import Image, ImageDraw, ImageFilter S = ss # supersampling factor w, h = W * S, H * S gx0, gy0, gx1, gy1 = box[0] * w, box[1] * h, box[2] * w, box[3] * h n_sub = sum(1 for c in calls if c.kind != "readout") n_src = max(max(c.window) for c in calls) + 1 gap_cols = 1.6 # empty columns between the last sublayer and the readout pitch = (gx1 - gx0) / (n_sub + gap_cols + 1) rpitch = (gy1 - gy0) / n_src tile_w = max(1.0, pitch * 0.70) full_h = rpitch * 0.62 radius = max(1, int(min(tile_w, full_h) * 0.35)) def col_x(c): return gx0 + pitch * (c.k + (gap_cols if c.kind == "readout" else 0)) + (pitch - tile_w) / 2 def row_y(s): # centre line of source row s (b0 at the bottom) return gy1 - rpitch * (s + 0.5) emit = Image.new("RGB", (w, h), (0, 0, 0)) # tiles in their exact colours alpha = Image.new("L", (w, h), 0) # where the tiles are fog = Image.new("RGB", (w, h), (0, 0, 0)) # background marks: fog dots, loop separators de, da, df = ImageDraw.Draw(emit), ImageDraw.Draw(alpha), ImageDraw.Draw(fog) loop_cols = 2 * CONFIG["physical_layers"] if labels: for L in range(1, CONFIG["loop_count"]): xa = gx0 + pitch * L * loop_cols df.line([(xa, gy0 - rpitch * 0.12), (xa, gy1 + rpitch * 0.05)], fill=(40, 52, 84), width=max(1, S)) tiles = [] for c in calls: x = col_x(c) for s in range(n_src): yc = row_y(s) if s not in c.window: # position not visible: faint fog dot fh = full_h * 0.16 df.rounded_rectangle([x, yc - fh / 2, x + tile_w, yc + fh / 2], radius=max(1, radius // 2), fill=FOG) continue if routing is not None: wgt = routing["weights"][c.k][s] bright = 0.15 + 0.85 * max(wgt, 0.0) ** 0.6 else: bright = 1.0 if s == 0: role, colour, th = "embedding", EMBED, full_h elif s == c.partial: role, colour = "partial", PARTIAL # height: share of the block's 18 updates held so far th = max(full_h * c.partial_updates / CONFIG["attnres_block_size"], 1.5 * S) else: role, colour, th = "block", BLOCK, full_h opacity = int(round(255 * bright)) # a tile is blended over the background with this opacity rect = [x, yc - th / 2, x + tile_w, yc + th / 2] rad = radius if th > 2 * radius else max(0, int(th / 2) - 1) de.rounded_rectangle(rect, radius=rad, fill=colour) da.rounded_rectangle(rect, radius=rad, fill=opacity) if s == 1: # b1 started from the embedding (F6): orange core ch = full_h * 0.24 crect = [x, yc - ch / 2, x + tile_w, yc + ch / 2] de.rounded_rectangle(crect, radius=max(0, int(ch / 2) - 1), fill=EMBED) da.rounded_rectangle(crect, radius=max(0, int(ch / 2) - 1), fill=opacity) tiles.append((c.k, s, role, [v / S for v in rect])) E = np.asarray(emit, dtype=np.float32) A = np.asarray(alpha, dtype=np.float32)[..., None] / 255.0 F = np.asarray(fog, dtype=np.float32) lit = Image.fromarray(np.clip(E * A, 0, 255).astype(np.uint8), "RGB") # dim tiles glow less glow = (np.asarray(lit.filter(ImageFilter.GaussianBlur(5 * S)), dtype=np.float32) * 0.42 + np.asarray(lit.filter(ImageFilter.GaussianBlur(24 * S)), dtype=np.float32) * 0.30) bg = np.empty((h, w, 3), dtype=np.float32) bg[:] = BG yy, xx = np.mgrid[0:h, 0:w].astype(np.float32) cx, cy = (gx0 + gx1) / 2, (gy0 + gy1) / 2 halo = np.exp(-(((xx - cx) / (0.42 * w)) ** 2 + ((yy - cy) / (0.42 * h)) ** 2)) bg += halo[..., None] * np.array([7, 10, 20], dtype=np.float32) # the glow lives around the tiles; a tile is its exact colour blended over the background with its opacity img = (np.maximum(bg, F) + glow) * (1.0 - A) + E * A # fades: the left part into the background (title), the other edges softly (letterboxing) lab = 0.085 * w if labels and row_labels else 0.0 mask = np.ones((h, w), dtype=np.float32) if fade_left: a, b = 0.10 * w, gx0 - lab - 0.02 * w mask *= _smooth((xx - a) / max(b - a, 1.0)) ** 1.3 edge = 0.035 * min(w, h) mask *= _smooth(xx / edge) * _smooth((w - 1 - xx) / edge) * _smooth(yy / edge) * _smooth((h - 1 - yy) / edge) for k, s, role, (x0r, y0r, x1r, y1r) in tiles: sub = mask[int(y0r * S):int(y1r * S) + 1, int(x0r * S):int(x1r * S) + 1] if sub.size and float(sub.min()) < 0.999: raise SystemExit(f"CHECK FAILED: tile (call {k}, b{s}) lies in a faded zone") img = np.array(BG, dtype=np.float32) + (img - np.array(BG, dtype=np.float32)) * mask[..., None] out = Image.fromarray(np.clip(img, 0, 255).astype(np.uint8), "RGB") if labels: d = ImageDraw.Draw(out) f = _font(int(rpitch * 0.24)) for s in (range(n_src) if row_labels else ()): text = "b0 embedding" if s == 0 else f"b{s}" colour = tuple(int(v * 0.55 + c2 * 0.45) for v, c2 in zip(INK, EMBED)) if s == 0 else INK d.text((gx0 - 0.012 * w, row_y(s)), text, fill=colour, font=f, anchor="rm") f2 = _font(int(rpitch * 0.22)) top = gy0 - rpitch * 0.30 for L in range(CONFIG["loop_count"]): xa = gx0 + pitch * L * loop_cols xb = gx0 + pitch * (L + 1) * loop_cols d.text(((xa + xb) / 2, top), f"loop {L + 1}", fill=INK, font=f2, anchor="mm") xr = col_x(calls[-1]) + tile_w / 2 d.text((xr, top), "readout", fill=INK, font=f2, anchor="mm") if title: d = ImageDraw.Draw(out) x = int(0.047 * w) y = int(0.30 * h) ft = _font(int(0.074 * h), bold=True) for line in _wrap(d, TITLE, ft, gx0 - x - 0.05 * w): d.text((x, y), line, fill=(248, 250, 252), font=ft) y += int(0.088 * h) fs = _font(int(0.043 * h)) y += int(0.018 * h) for line in _wrap(d, SUBTITLE, fs, gx0 - x - 0.05 * w): d.text((x, y), line, fill=(163, 177, 198), font=fs) y += int(0.056 * h) y += int(0.04 * h) d.text((x, y), "Bartosz Naskręcki · 2026-11-17", fill=(203, 213, 225), font=_font(int(0.036 * h))) if S > 1: from PIL import Image as _I out = out.resize((W, H), _I.LANCZOS) return out, tiles def _wrap(draw, text, font, width): words, lines, cur = text.split(), [], "" for wd in words: trial = (cur + " " + wd).strip() if draw.textlength(trial, font=font) <= width or not cur: cur = trial else: lines.append(cur) cur = wd return lines + ([cur] if cur else []) def make_pictures(calls, facts, routing): import numpy as np from PIL import Image ASSETS.mkdir(exist_ok=True) hero, tiles = render(calls, routing, 1600, 900, (0.40, 0.17, 0.965, 0.79)) if len(tiles) != facts["visible_pairs"]: raise SystemExit(f"CHECK FAILED: drawn {len(tiles)} tiles, simulated {facts['visible_pairs']} pairs") per_row = Counter(s for _, s, _, _ in tiles) for name, roles in facts["lifetimes"].items(): n = sum(b - a + 1 for a, b in roles.values()) if per_row[int(name[1:])] != n: raise SystemExit(f"CHECK FAILED: row {name} drawn {per_row[int(name[1:])]} times, visible {n}") arr = np.asarray(hero, dtype=np.float32) edge = np.concatenate([arr[:, :8].reshape(-1, 3), arr[:4].reshape(-1, 3), arr[-4:].reshape(-1, 3), arr[:, -4:].reshape(-1, 3)]) if np.abs(edge - np.array(BG)).max() > 3.0: raise SystemExit("CHECK FAILED: the picture's border does not blend into the page background") noise = np.random.default_rng(0).uniform(-1.2, 1.2, arr.shape) dithered = Image.fromarray(np.clip(arr + noise, 0, 255).astype(np.uint8), "RGB") dithered.save(ASSETS / "hero.webp", quality=90, method=6) dithered.save(ASSETS / "hero.jpg", quality=90, optimize=True, progressive=True) og, _ = render(calls, routing, 1200, 630, (0.55, 0.20, 0.965, 0.80), row_labels=False, title=True) og.save(ASSETS / "og.png", optimize=True) fav, _ = render(calls, routing, 256, 256, (0.06, 0.08, 0.94, 0.92), labels=False, fade_left=False) fav.resize((64, 64), Image.LANCZOS).save(ASSETS / "favicon.png", optimize=True) fav.resize((128, 128), Image.LANCZOS).save(ASSETS / "logo.png", optimize=True) # the book's sidebar logo return {"hero": [1600, 900], "og": [1200, 630], "favicon": [64, 64], "logo": [128, 128], "tiles": len(tiles)} # ============================================================================================= # 3. Page sections (standard library only) # ============================================================================================= def esc(s: str) -> str: return html.escape(s, quote=True) TEX = {r"\sum": "Σ", r"\alpha": "α", r"\le": "≤", r"\ge": "≥", r"\odot": "⊙", r"\times": "×", r"\top": "⊤", r"\dots": "…", r"\ldots": "…", r"\circ": "∘", r"\cdot": "·", r"\max": "max", r"\in": "∈", r"\infty": "∞", r"\sqrt": "√", r"\,": " ", r"\{": "{", r"\}": "}", r"\big": "", r"\mathcal": "", r"\operatorname": "", r"\mathrm": "", r"\text": ""} def tex(s: str) -> str: """A small TeX-to-HTML conversion for the inline formulas of the digest (sub/superscripts).""" out, i = [], 0 def group(j): if j < len(s) and s[j] == "{": depth, k = 1, j + 1 while k < len(s) and depth: depth += {"{": 1, "}": -1}.get(s[k], 0) k += 1 return s[j + 1:k - 1], k if j < len(s) and s[j] == "\\": m = re.match(r"\\[A-Za-z]+", s[j:]) if m: return s[j:j + m.end()], j + m.end() return s[j:j + 1], j + 1 while i < len(s): ch = s[i] if ch in "_^": body, i = group(i + 1) tag = "sub" if ch == "_" else "sup" out.append(f"<{tag}>{tex(body)}") elif ch == "\\": m = re.match(r"\\([A-Za-z]+|.)", s[i:]) name = m.group(0) i += m.end() out.append(esc(TEX.get(name, name.lstrip("\\")))) elif ch in "{}": i += 1 else: out.append(esc(ch)) i += 1 return "".join(out) def md_inline(s: str) -> str: """Inline markdown of the digest/outline: `code`, $math$, **bold**, *italic*, [tag], .""" parts = re.split(r"(`[^`]+`|\$[^$]+\$)", s) out = [] for p in parts: if p.startswith("`") and p.endswith("`") and len(p) > 1: out.append(f"{esc(p[1:-1])}") elif p.startswith("$") and p.endswith("$") and len(p) > 1: out.append(f'{tex(p[1:-1])}') else: t = esc(p) t = re.sub(r"\*\*(.+?)\*\*", r"\1", t) t = re.sub(r"(?\1", t) t = re.sub(r"\[(paper|code|exp|num)\]", r'\1', t) t = re.sub(r"<(https?://[^&\s]+)>", r'\1', t) out.append(t) return "".join(out) def digest_sections() -> dict: text = DIGEST.read_text(encoding="utf-8") secs, cur = {}, None for line in text.splitlines(): m = re.match(r"^## (\d+)\. (.*)$", line) if m: cur = int(m.group(1)) secs[cur] = {"title": m.group(2), "lines": []} elif cur is not None: secs[cur]["lines"].append(line) return secs def bullets(lines) -> list: items, cur = [], None for line in lines: if line.startswith("* "): cur = [line[2:].strip()] items.append(cur) elif cur is not None and line.startswith(" ") and line.strip(): cur.append(line.strip()) elif not line.strip() and cur is not None: cur = None return [" ".join(x) for x in items] def md_table(lines) -> list: rows = [] for line in lines: if line.startswith("|") and not re.match(r"^\|[\s\-:|]+\|$", line): cells = [c.strip() for c in line.strip().strip("|").split(" | ")] rows.append(cells) return rows def sec_talk(secs) -> str: items = bullets(secs[0]["lines"]) if len(items) != 3: raise SystemExit(f"digest §0 has {len(items)} bullets, expected 3") lis = "\n".join(f"
  • {md_inline(x)}
  • " for x in items) return f' ' def sec_claims(secs) -> str: rows = [] for n, sec in sorted(secs.items()): m = re.match(r"Claim (C\d+) — (.+?) \((§[^)]*)\) \[(\w+)\]\s*$", sec["title"]) if not m: continue cid, title, where, tag = m.groups() body = " ".join(sec["lines"]) tests = [] for m2 in re.finditer(r"E\d\.\d", body): t = m2.group(0) + (" (optional)" if "optional" in body[max(0, m2.start() - 40):m2.start()].lower() else "") if t not in tests: tests.append(t) test = ", ".join(tests) if tests else "not re-run (paper only)" title = title[:1].upper() + title[1:] rows.append(f" {cid}{md_inline(title)}{esc(where)}" f'{esc(tag)}{esc(test)}') if len(rows) != 7: raise SystemExit(f"digest has {len(rows)} claim sections, expected C1–C7") head = " claimstatementpapertagour test" return '
    \n' + head + "\n" + "\n".join(rows) + "\n
    " def sec_findings(secs) -> str: sec = next(s for s in secs.values() if s["title"].lower().startswith("findings register")) rows = md_table(sec["lines"]) head, body = rows[0], rows[1:] if [h.lower() for h in head[:4]] != ["#", "place", "finding", "severity"]: raise SystemExit(f"unexpected findings header {head}") body.sort(key=lambda r: int(re.sub(r"\D", "", r[0]) or 0)) out = [" " + "".join(f"{esc(h)}" for h in head) + ""] for r in body: out.append(" " + "".join(f"{md_inline(c)}" for c in r) + "") note = " ".join(l.strip() for l in sec["lines"] if l.strip().startswith("*") and not l.startswith("|")) return ('
    \n' + "\n".join(out) + "\n
    \n" + (f'

    {md_inline(note)}

    ' if note else "")) def sec_plan() -> str: text = OUTLINE.read_text(encoding="utf-8") rows = md_table(text.splitlines()) head, body = rows[0], rows[1:] if [h.lower() for h in head[:3]] != ["min", "block", "content"]: raise SystemExit(f"unexpected outline header {head}") draft = re.search(r"\((draft [^)]*)\)", text.splitlines()[0]) out = [" minblockcontent"] for r in body: out.append(f' {esc(r[0])}{md_inline(r[1])}' f"{md_inline(r[2])}") built = " · ".join(f"{name}: " + _link(rel) + ("" if (ROOT / rel).exists() else " (not built yet)") for name, rel in (("the deck", "slides/seminar.html"), ("board plan", "slides/board-plan.html"))) cap = f"Read from slides/OUTLINE.md{' (' + esc(draft.group(1)) + ')' if draft else ''} · {built}." return (f'

    {cap}

    \n
    \n' + "\n".join(out) + "\n
    ") def _pct(x): return f"{100 * x:.1f}%" def _signed(x, digits=1): return f"{x:+.{digits}f}".replace("-", "\u2212") def _pts(x): return _signed(100 * x, 1) E1_CELLS = { # cell id -> key of summary["paired"] written by experiments/e1_release/analyze.py "e1.pair-gsm8k": "ARLoop-0.6B vs PreNormLoop-0.6B at R=3", "e1.ar-r4-repeat": "ar06-R4-repeat vs ar06-R3", "e1.ar-r4-cycle": "ar06-R4-cycle vs ar06-R3", "e1.pn-r4": "pn06-R4 vs pn06-R3", "e1.pn-r5": "pn06-R5 vs pn06-R3", "e1.pn-r6": "pn06-R6 vs pn06-R3", "e1.ar-r2": "ar06-R2 vs ar06-R3", "e1.pn-r2": "pn06-R2 vs pn06-R3", "e1.ar-r5-repeat": "ar06-R5-repeat vs ar06-R3", "e1.ar-r6-repeat": "ar06-R6-repeat vs ar06-R3", "e1.ar12-r4-repeat": "ar12-R4-repeat vs ar12-R3", "e1.pair-nobos": "no BOS: ARLoop-0.6B vs PreNormLoop-0.6B at R=3", } E2_CELLS = { # cell id -> (x, y, split) of analysis.json["comparisons"] (experiments/e2_small/scripts/analyze.py) "e2.prenorm-iid": [("prenorm-loop@r4", "latent-recurrent@r4", "iid"), ("prenorm-loop@r16", "latent-recurrent@r16", "iid")], "e2.arloop-untied-iid": [("arloop-untied@r4", "latent-recurrent@r4", "iid"), ("arloop-untied@r16", "latent-recurrent@r16", "iid")], "e2.arloop-tied-iid": [("arloop-tied@r4", "latent-recurrent@r4", "iid"), ("arloop-tied@r16", "latent-recurrent@r16", "iid")], "e2.arloop-untied-ood": [("arloop-untied@r4", "latent-recurrent@r4", "ood_operand"), ("arloop-untied@r16", "latent-recurrent@r16", "ood_operand")], "e2.arloop-tied-ood": [("arloop-tied@r4", "latent-recurrent@r4", "ood_operand"), ("arloop-tied@r16", "latent-recurrent@r16", "ood_operand")], "e2.tied-depth": [("arloop-tied@r16", "arloop-tied@r4", "iid"), ("arloop-tied@r16", "arloop-tied@r4", "ood_operand")], } STATUS = {"unknown": ("pending", "s-pending"), "supports": ("supports", "s-supports"), "contradicts": ("contradicts", "s-contradicts"), "inconclusive": ("inconclusive", "s-inconclusive")} PROTOCOLS = {"E1": "experiments/e1_release/PROTOCOL.md", "E2": "experiments/e2_small/PROTOCOL.md", "E3": "experiments/e3_pair/PROTOCOL.md"} EXP_DIRS = {"E1": "experiments/e1_release", "E2": "experiments/e2_small", "E3": "experiments/e3_pair"} def _link(rel: str, label: str | None = None) -> str: text = f"{esc(label or rel)}" return f'{text}' if (ROOT / rel).exists() else text def _evidence(e: str) -> str: """An evidence entry is a path, or a path followed by a sentence: link the path, keep the sentence.""" if (ROOT / e).exists(): return _link(e, Path(e).name) head, sep, rest = e.partition(" ") path = head.rstrip(":") if sep and path and (ROOT / path).exists(): return _link(path, Path(path).name) + " " + esc(rest) return esc(e) def _measured_e1(cid, summary): if not summary: return None paired = summary.get("paired") or {} if cid in E1_CELLS and E1_CELLS[cid] in paired: p = paired[E1_CELLS[cid]] lo, hi = p["ci95"] return (f"{esc(p['a'])} {_pct(p['acc_a'])} vs {esc(p['b'])} {_pct(p['acc_b'])}; " f"difference {_pts(p['diff'])} pts, 95% CI [{_pts(lo)}, {_pts(hi)}], " f"McNemar p = {p['mcnemar_p']:.2g}, n = {p['n']}") if cid == "e1.1p2b-gsm8k": acc = (summary.get("gsm8k_acc") or {}).get("ar12-R3") if acc is not None: return f"ar12-R3 {_pct(acc)} (all items of the run)" return None def _analysis_from_evidence(cells): """An analysis.json with paired comparisons, named in the evidence of the family's cells.""" for c in cells: for e in c.get("evidence") or []: p = ROOT / e if p.name == "analysis.json" and p.exists(): data = json.loads(p.read_text(encoding="utf-8")) if isinstance(data, dict) and isinstance(data.get("comparisons"), list): return e, data return None, None def _measured_e2(cid, analysis): if not analysis or cid not in E2_CELLS: return None idx = {(c["x"], c["y"], c["split"]): c for c in analysis["comparisons"]} parts = [] for key in E2_CELLS[cid]: c = idx.get(key) if c is None: continue n = c["n"] lo, hi = c["ci95"] (ax, rx), (ay, ry) = (c["x"].split("@r"), c["y"].split("@r")) where = f"r = {rx} vs {ry}" if ax == ay else (f"r = {rx}" if rx == ry else f"{c['x']} vs {c['y']}") parts.append(f"{esc(where)}, {esc(c['split'])}: {round(c['acc_x'] * n)}/{n} vs " f"{round(c['acc_y'] * n)}/{n} · difference {_signed(c['diff'], 3)}, 95% CI " f"[{_signed(lo, 3)}, {_signed(hi, 3)}] · McNemar p = {c['mcnemar_p']:.2g}") return "
    ".join(parts) or None def sec_tests() -> str: cells = json.loads(CELLS.read_text(encoding="utf-8")) out = [] for fam in cells["families"]: label = fam["label"] exp = label.split()[0] rdir = RUNS / exp.lower() summary_p = rdir / "summary.json" summary = json.loads(summary_p.read_text(encoding="utf-8")) if summary_p.exists() else None an_path, analysis = _analysis_from_evidence(fam["cells"]) counts = Counter(c["status"] for c in fam["cells"]) tally = ", ".join(f"{n} {STATUS.get(s, (s, ''))[0]}" for s, n in sorted(counts.items())) docs = [] for name, rel in (("protocol", PROTOCOLS.get(exp)), ("results", f"{EXP_DIRS.get(exp, '')}/RESULTS.md"), ("referee note", f"runs/{exp.lower()}/referee.md"), ("builder log", f"{EXP_DIRS.get(exp, '')}/STATUS.md"), ("summary", f"runs/{exp.lower()}/summary.json")): if rel and (ROOT / rel).exists(): docs.append(f'{name}') lines = [f'{len(fam["cells"])} test cells: {esc(tally)}' + (" · " + " · ".join(docs) if docs else "")] if summary is not None: when = dt.datetime.fromtimestamp(summary_p.stat().st_mtime).strftime("%Y-%m-%d %H:%M") lines.append(f"results file {_link(str(summary_p.relative_to(ROOT)))} written {when}") elif analysis is not None: rep = analysis.get("reproduction_verdict") or {} job = f" (job {esc(str(analysis.get('job_id')))})" if analysis.get("job_id") else "" txt = f"analysis {_link(an_path)}{job}" if rep.get("records_compared") and rep.get("records_identical") is True: txt += (f"; latent's job 284986 reproduced item by item: {rep['records_compared']} of " f"{rep['records_compared']} item records identical") lines.append(txt) else: recount = rdir / "referee" / f"{exp.lower()}_referee.json" if recount.exists(): lines.append(f"results: the referee's recount {_link(str(recount.relative_to(ROOT)))} " f"(this experiment writes no summary.json)") else: lines.append(f"results file runs/{esc(exp.lower())}/summary.json: not yet present") if rdir.is_dir(): subs = sorted(d.name + "/" for d in rdir.iterdir() if d.is_dir()) if subs: lines.append("run directories in runs/" + esc(exp.lower()) + "/: " + ", ".join(f"{esc(d)}" for d in subs)) out.append(f'
    \n

    {esc(label)}

    \n' + "".join(f'

    {ln}

    \n' for ln in lines)) rows = [' test cellverdictquestionmeasured'] for c in fam["cells"]: name, cls = STATUS.get(c["status"], (c["status"], "s-pending")) meas = (_measured_e1(c["id"], summary) if exp == "E1" else _measured_e2(c["id"], analysis) if exp == "E2" else None) if meas and c["status"] == "unknown": meas += ' not yet refereed' ev = ", ".join(_evidence(e) for e in c.get("evidence") or []) cell = meas or ("—" if not ev else "") if ev: cell += ("
    " if meas else "") + "evidence: " + ev rows.append(f' {esc(c["id"])}' f'{esc(name)}{esc(c["title"])}' f'{cell}') out.append('
    \n' + "\n".join(rows) + "\n
    ") if exp == "E1" and summary: out.append(_e1_tables(summary)) figs = sorted((rdir / "figures").glob("*.svg")) if (rdir / "figures").is_dir() else [] if figs: fig_html = "\n".join(f'
    figure {esc(p.stem)} from {esc(str(p.parent.relative_to(ROOT)))}' f'
    {esc(str(p.relative_to(ROOT)))}
    ' for p in figs) out.append(f'
    \n{fig_html}\n
    ') out.append("
    ") return "\n".join(out) def _e1_tables(summary) -> str: acc = summary.get("gsm8k_acc") or {} bpb = summary.get("wikitext_bpb") or {} runs = sorted(set(acc) | set(bpb)) if not runs: return "" rows = [" runGSM8K 5-shot CoT (flexible-extract)WikiText-2 bits per byte"] for r in runs: a = _pct(acc[r]) if r in acc and acc[r] is not None else "—" b = f"{bpb[r]:.4f}" if r in bpb and bpb[r] is not None else "—" rows.append(f" {esc(r)}{a}{b}") return ('
    All E1 runs in runs/e1/summary.json\n' '
    \n' + "\n".join(rows) + "\n
    \n
    ") def sec_cards() -> str: cards = [ ("b-embed", "Digest", "The paper rewritten for the seminar: claims C1–C7 with tags, the released models " "as configured, the findings register. The single source of truth.", "artifacts/mathematical/digest.md", "Read the digest"), ("b-block", "Notes", "The seminar notes (Jupyter Book): background, the method, every number computed in a cell.", "book/_build/html/index.html", "Open the notes"), ("b-block", "Slides", "The 45-minute deck with the board plan and the live-demo moments (reveal.js, offline).", "slides/seminar.html", "Open the slides"), ("b-partial", "Research map", "The labyrinth: claims, open doors, conjectures, hunches and the test-cell " "frontier of E1–E3.", "labyrinth/dashboard/index.html", "Open the map"), ("b-partial", "Experiments", None, None, None), ("b-muted", "Source record", "Citation, checksums of the PDF and the LaTeX e-print, the pinned code commit " "and checkpoint revisions.", "source/SOURCE.md", "Open the record"), ] out = [] for bar, title, text, href, cta in cards: if href is None: # the experiments card: three links, so no stretched link links = [] for exp, name in (("E1", "released checkpoints"), ("E2", "small canary, latent regime"), ("E3", "the 0.6B pair on checked proofs")): p = PROTOCOLS[exp] missing = "" if (ROOT / p).exists() else ' missing' links.append(f'
  • {exp} — {name}{missing}
  • ') out.append(f'

    {title}

    \n' f"

    Protocols written before any run: questions, decision rules, compute.

    \n" f'
    ') continue ok = (ROOT / href).exists() state = "" if ok else ' being written' out.append(f'

    {title}{state}

    \n' f"

    {text}

    \n" f' {cta} →
    ') return "\n".join(out) KIND = {"attn": "attention", "ffn": "FFN", "readout": "readout"} def sec_about(facts) -> str: lt = facts["lifetimes"] cfg = facts["config"] ws = facts["window_size_counts"] commits = ", ".join(str(x) for x in facts["commit_layers"]) b1 = lt["b1"] meas = facts.get("measured") if meas: bright = (f"The opacity of every tile follows the mean routing weight w measured by the routing probe " f"({esc(meas['path'])}" + (f", {meas['n_prompts']} prompts" if meas.get("n_prompts") else "") + (f", job {esc(str(meas['job_id']))}" if meas.get("job_id") else "") + "): a tile is drawn with opacity 0.15 + 0.85·w0.6 over the dark background, so faint " "tiles are sources the model barely reads. Before drawing, the script checks that the probe's source lists equal the simulated " "windows call by call.") else: bright = ("All visible tiles are drawn at full opacity: the measured routing weights of the coordinator's probe " "(runs/e1/routing/ar06-R3/routing.json) were not available when the picture was computed; " "once they are, re-running the script sets every tile's opacity from its measured mean routing weight.") p1 = (f"The picture in the header is computed, not drawn. It shows which residual sources the depth attention of the released " f"ARLoop-0.6B can read at each of its {facts['routing_calls']} routing calls: the " f"{facts['sublayers']} effective sublayers ({cfg['physical_layers']} physical layers × {cfg['loop_count']} loops × " f"attention and FFN, from left to right, " f"loops separated by thin lines) and the final readout (the separated column on the right). Rows are the sources: the " f"embedding b0 at the bottom and the residual blocks b1–b6 above it. A block is " f"drawn as an aqua wedge while it is the partial block, its height growing with " f"the number of sublayer updates it holds, then as a blue tile once it is " f"committed, and it disappears when it leaves the window. Faint dots mark positions that are not visible.") p2 = (f"The pattern is obtained by replaying the bookkeeping of the model's forward pass (modeling_arloop.py of " f"{esc(facts['model'])}; digest §2): a block is committed at effective layers {commits}; each routing " f"call sees the embedding and the {facts['config']['sw_blocks']} most recent sources (the partial block included). " f"Hence {ws.get('2', 0)} calls read 2 sources, {ws.get('3', 0)} read 3 and {ws.get('4', 0)} read 4 (every call from " f"sublayer {facts['first_full_window_sublayer']} on), {facts['visible_pairs']} visible pairs in all. Block b1 starts " f"from the embedding (finding F6), so its tiles carry an orange core: the embedding is visible twice from sublayer " f"{b1['partial'][0]} to sublayer {facts['b1_last_sublayer']} (the {KIND[facts['b1_last_kind']]} sublayer of effective " f"layer {facts['b1_last_layer']}), after which b1 leaves the window.") p3 = (f"The script stops instead of drawing if any check fails: at most {cfg['sw_blocks'] + 1} sources per call (and exactly " f"as many as the window allows), the embedding visible everywhere, two blocks of {cfg['attnres_block_size'] // 2} " "consecutive layers in each loop, the digest's " f"worked example at effective layer 36, only b1 holding the embedding, and {facts['routing_vectors']} routing vectors × " f"{facts['config']['hidden_size']} = {facts['routing_parameters']:,} parameters equal to the parameter gap between " "ARLoop-0.6B and PreNormLoop-0.6B recorded in source/SOURCE.md (finding F1). The left part fades into " "the page colour so that the title stays readable.") return "\n".join(f"

    {p}

    " for p in (p1, p2, bright, p3)) + \ '\n

    Source: scripts/generate_hero.py; ' \ 'computed facts: assets/hero-facts.json.

    ' def sec_stamp(facts) -> str: now = dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%d %H:%M UTC") inputs = ["artifacts/mathematical/digest.md", "slides/OUTLINE.md", "labyrinth/cells.json"] inputs += [str(p.relative_to(ROOT)) for p in sorted(RUNS.glob("*/summary.json"))] pic = facts.get("pictures_generated") return (f'

    Sections marked by the script were generated on {now} by scripts/generate_hero.py from ' + ", ".join(f"{esc(i)}" for i in inputs) + (f"; header picture computed on {esc(pic)}." if pic else ".") + "

    ") def replace_region(page: str, name: str, content: str) -> str: pat = re.compile(rf"()(.*?)()", re.S) if len(pat.findall(page)) != 1: raise SystemExit(f"index.html: marker pair generated:{name} missing or repeated") return pat.sub(lambda m: m.group(1) + "\n" + content.rstrip("\n") + "\n" + m.group(3), page) def build_page(facts): secs = digest_sections() page = INDEX.read_text(encoding="utf-8") for name, content in (("cards", sec_cards()), ("talk", sec_talk(secs)), ("plan", sec_plan()), ("claims", sec_claims(secs)), ("tests", sec_tests()), ("findings", sec_findings(secs)), ("image", sec_about(facts)), ("stamp", sec_stamp(facts))): page = replace_region(page, name, content) leftover = re.findall(r"\{\{[A-Z_]+\}\}", page) if leftover: raise SystemExit(f"index.html: placeholders left {sorted(set(leftover))}") INDEX.write_text(page, encoding="utf-8") # ============================================================================================= def main(argv=None) -> int: ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) ap.add_argument("--page-only", action="store_true", help="refresh the page sections only (no numpy/pillow)") a = ap.parse_args(argv) calls, blocks, final, commits = simulate(CONFIG) facts = check_structure(CONFIG, calls, blocks, final, commits) routing = load_routing(calls) if a.page_only: old = json.loads(FACTS.read_text(encoding="utf-8")) if FACTS.exists() else {} facts["measured"] = old.get("measured") facts["pictures_generated"] = old.get("pictures_generated") if routing and not facts["measured"]: print("note: routing.json is present but the pictures were computed without it; run without --page-only") else: facts["pictures"] = make_pictures(calls, facts, routing) facts["measured"] = ({k: routing[k] for k in ("path", "n_prompts", "job_id")} if routing else None) facts["pictures_generated"] = dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%d %H:%M UTC") FACTS.write_text(json.dumps(facts, indent=1, ensure_ascii=False) + "\n", encoding="utf-8") build_page(facts) print("checks passed;", "pictures and page" if not a.page_only else "page", "written", "(measured routing weights)" if facts.get("measured") else "(structure only: no routing.json)") return 0 if __name__ == "__main__": sys.exit(main())