shadow-50m-vision / scripts /train_proof.py
QLNI's picture
Add files using upload-large-folder tool
7039798 verified
Raw History Blame Contribute Delete
31.7 kB
"""The proof run's body: 50M-class ternary core over the frozen table, everything in the loop
that the shipped kernel does. From pilot/04_train.py, with the proof-run changes:
loop prelude 2 blocks -> tied core of 6 blocks run K times -> coda 2 blocks
(plan/LOOP.md). K = 2, then 4 from --grow-at of the tokens (tied growth,
arXiv 2609.19107). Boundary operator BO(h, e) = RMS(h) + a_k * e after every
pass: e is the prelude's output, one learned scalar a boundary. --flat N trains
the flat control of N untied blocks instead (same BO after block 2 skipped).
int8 every ternary GEMM reads int8 activations (per-token absmax, STE): the kernel's
arithmetic in the forward pass, so trained model = shipped model.
int4 KV as the pilot (keys and values quantised per head-vector, STE).
index MSA index branch per block (plan/RETRIEVAL.md): one 32-dim index query and key,
ternary, reading the DETACHED residual; a 128-token block's score is the max over
its tokens. Trained with KL from the main heads' attention (stop-gradient) to the
index's block distribution, on 64 sampled queries a window. From --sparse-ctx on,
attention runs only over each query's top-16 blocks + its own block.
readout split by position (plan/TRAINER.md): at a text position the logits run over
language + marker + control rows; inside a picture / sound / clip span (after
[image], [gen_image]... until its end row) over that band + marker + control
rows. Exact: nothing else can follow there. Loss logged per kind.
Engram the pilot's trainable ternary tables, outside the loop: after the prelude and
after the coda, canonical ids from the final table's language rows.
Data: ids_final/ shards from build_table.py remap, packed once into train.bin / val.bin.
python3 train_proof.py pack --lanes knowledge,understanding
python3 train_proof.py train --tokens 2.3e9 --engram-entries 8000000 --hf-repo QLNI/shadow-50m-vision-proof
python3 train_proof.py train --flat 10 --tokens 4.6e8 --tag flat10 # the control
python3 train_proof.py smoke # tiny, synthetic, laptop
"""
import argparse, json, math, os, pathlib, sys, time, glob, zlib
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
HERE = pathlib.Path(__file__).resolve().parent
def say(*a): print(time.strftime("%H:%M:%S"), *a, flush=True)
# ------------------------------------------------------------------ quantisers (STE)
def ste(x, q): return x + (q - x).detach()
def q_tern(w):
s = w.abs().mean().clamp_min(1e-8)
return torch.round(w / s).clamp_(-1, 1) * s
def q_int8(x):
s = x.detach().abs().amax(-1, keepdim=True).clamp_min(1e-6) / 127
return ste(x, torch.round(x / s).clamp_(-127, 127) * s)
def q_kv(t, bits=4):
n = 2 ** (bits - 1) - 1
s = t.abs().amax(-1, keepdim=True).clamp_min(1e-8)
return ste(t, torch.round(t / s * n).clamp(-n, n) * s / n)
STEP = [0] # ternary weights cached once a step
class TLinear(nn.Linear):
"""Ternary weights (absmean, STE) x int8 activations (per-token absmax, STE)."""
def __init__(self, *a, act8=True, **k):
super().__init__(*a, bias=False, **k); self.act8 = act8; self._c = (-1, None)
cache = True # off under torch.compile (a Python-side cache would recompile every step)
def forward(self, x):
if not TLinear.cache or self._c[0] != STEP[0] or not torch.is_grad_enabled():
w = ste(self.weight, q_tern(self.weight))
if TLinear.cache and torch.is_grad_enabled(): self._c = (STEP[0], w)
else:
w = self._c[1]
return F.linear(q_int8(x) if self.act8 else x, w)
def rms(x): return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + 1e-6)
ROPE_BASE = 100000.0
_ROPE = {}
def rope(x):
B, H, T, D = x.shape; half = D // 2; k = (T, D, x.device)
if k not in _ROPE:
inv = ROPE_BASE ** (-torch.arange(0, half, device=x.device, dtype=torch.float32) / half)
f = torch.outer(torch.arange(T, device=x.device, dtype=torch.float32), inv)
_ROPE[k] = (f.cos()[None, None], f.sin()[None, None])
cos, sin = _ROPE[k]; a, b = x[..., :half], x[..., half:]
return torch.cat([a * cos - b * sin, a * sin + b * cos], -1).to(x.dtype)
# ------------------------------------------------------------------ block with index branch
IBLK, ITOP, IDIM, INQ = 128, 16, 32, 64
class Block(nn.Module):
"""Post-norm, weightless RMS (the pilot's block), plus the MSA index branch."""
def __init__(self, d, heads, kv_heads, kbits=4):
super().__init__()
self.h, self.kv, self.dh, self.kbits = heads, kv_heads, d // heads, kbits
self.q = TLinear(d, d); self.k = TLinear(d, kv_heads * self.dh); self.v = TLinear(d, kv_heads * self.dh)
self.o = TLinear(d, d)
self.f1 = TLinear(d, 8 * d // 3); self.f3 = TLinear(d, 8 * d // 3); self.f2 = TLinear(8 * d // 3, d)
self.iq = TLinear(d, IDIM); self.ik = TLinear(d, IDIM)
def index_scores(self, h, rows=None):
"""(B,T,d) detached residual -> (B,n,T) index dot products for query rows (all if None)."""
hq = h if rows is None else h[:, rows]
return (self.iq(hq) @ self.ik(h).transpose(1, 2)) / IDIM ** 0.5
@staticmethod
def block_max(s, qpos):
"""(B,n,T) token scores -> (B,n,nb) block scores, causal (a block counts once it starts
at or before the query)."""
B, n, T = s.shape; nb = (T + IBLK - 1) // IBLK
causal = torch.arange(T, device=s.device)[None, :] <= qpos[:, None] # (n,T)
s = s.masked_fill(~causal[None], float("-inf"))
s = F.pad(s, (0, nb * IBLK - T), value=float("-inf"))
return s.view(B, n, nb, IBLK).amax(-1)
def forward(self, x, sparse=False, aux=None):
B, T, D = x.shape
h = rms(x)
q = rope(self.q(h).view(B, T, self.h, self.dh).transpose(1, 2))
k = rope(self.k(h).view(B, T, self.kv, self.dh).transpose(1, 2))
v = self.v(h).view(B, T, self.kv, self.dh).transpose(1, 2)
if self.kbits: k, v = q_kv(k, self.kbits), q_kv(v, self.kbits)
hd = h.detach()
mask = None
if sparse:
with torch.no_grad():
pos = torch.arange(T, device=x.device)
bs = self.block_max(self.index_scores(hd).float(), pos) # (B,T,nb)
nb = bs.shape[-1]
own = pos // IBLK
bs.scatter_(2, own[None, :, None].expand(B, T, 1), float("inf")) # own block always in
top = bs.topk(min(ITOP + 1, nb), -1).indices
sel = torch.zeros(B, T, nb, dtype=torch.bool, device=x.device).scatter_(2, top, True)
sel &= bs > float("-inf") # never a future block
tok = sel.repeat_interleave(IBLK, -1)[..., :T] & (pos[None, :] <= pos[:, None])[None]
mask = tok[:, None] # (B,1,T,T)
if self.training and aux is not None and T >= 2 * IBLK:
# index KL on sampled queries: target = main heads' attention mass per block
qpos = torch.randint(IBLK, T, (INQ,), device=x.device).sort().values
with torch.no_grad():
kk = k.repeat_interleave(self.h // self.kv, 1) if self.kv != self.h else k
att = (q[:, :, qpos].float() @ kk.float().transpose(-1, -2)) / self.dh ** 0.5 # (B,H,n,T)
att = att.masked_fill(torch.arange(T, device=x.device)[None, None, None] > qpos[None, None, :, None], float("-inf"))
p = att.softmax(-1).mean(1) # (B,n,T)
nb = (T + IBLK - 1) // IBLK
p = F.pad(p, (0, nb * IBLK - T)).view(B, INQ, nb, IBLK).sum(-1)
bsc = self.block_max(self.index_scores(hd, qpos).float(), qpos)
logq = bsc.log_softmax(-1).masked_fill(~torch.isfinite(bsc), 0.0)
aux.append((p * ((p + 1e-9).log() - logq)).sum(-1).mean())
if self.kv != self.h:
k = k.repeat_interleave(self.h // self.kv, 1); v = v.repeat_interleave(self.h // self.kv, 1)
a = F.scaled_dot_product_attention(q, k, v, attn_mask=mask, is_causal=mask is None)
x = rms(x + self.o(a.transpose(1, 2).reshape(B, T, D)))
h = rms(x)
return rms(x + self.f2(F.silu(self.f1(h)) * self.f3(h)))
# ------------------------------------------------------------------ the model
class Shadow(nn.Module):
def __init__(self, T, d=512, heads=8, kv_heads=1, prelude=2, core=6, coda=2, flat=0, engram=None, canonical=None):
super().__init__()
self.tab = T
self.register_buffer("table", torch.tensor(T["bits"], dtype=torch.float32) * 2 - 1)
self.register_buffer("ubias", torch.tensor(T["bias"], dtype=torch.float32))
self.inp = TLinear(512, d)
self.flat = flat
if flat:
self.blocks = nn.ModuleList([Block(d, heads, kv_heads) for _ in range(flat)])
else:
self.pre = nn.ModuleList([Block(d, heads, kv_heads) for _ in range(prelude)])
self.core = nn.ModuleList([Block(d, heads, kv_heads) for _ in range(core)])
self.coda = nn.ModuleList([Block(d, heads, kv_heads) for _ in range(coda)])
self.alpha = nn.Parameter(torch.full((8,), 0.1)) # one a boundary, up to K = 8
self.K = 2
self.out_proj = TLinear(d, 512)
self.scale = 512 ** -0.5
self.engrams = nn.ModuleDict()
if engram:
import importlib.util
spec = importlib.util.spec_from_file_location("eg", str(engram.pop("_path")))
eg = importlib.util.module_from_spec(spec); spec.loader.exec_module(eg)
self.engrams["pre"] = eg.EngramTable(d=d, **engram); self.engrams["post"] = eg.EngramTable(d=d, **engram)
self.register_buffer("canonical", torch.as_tensor(canonical, dtype=torch.int64))
def executed(self):
return self.flat or (len(self.pre) + self.K * len(self.core) + len(self.coda))
def features(self, ids, sparse=False, aux=None):
x = self.inp(self.table[ids])
slots = None
if self.engrams:
canon = self.canonical[ids]; slots = {k: m.slots(canon) for k, m in self.engrams.items()}
if self.flat:
for i, b in enumerate(self.blocks):
x = b(x, sparse, aux)
if i == 1 and "pre" in self.engrams: x = x + self.engrams["pre"](x, slots["pre"])
else:
for b in self.pre: x = b(x, sparse, aux)
if "pre" in self.engrams: x = x + self.engrams["pre"](x, slots["pre"])
e = x
for k in range(self.K):
for b in self.core: x = b(x, sparse, aux)
x = rms(x) + self.alpha[k] * e # boundary operator
for b in self.coda: x = b(x, sparse, aux)
if "post" in self.engrams: x = x + self.engrams["post"](x, slots["post"])
return self.out_proj(rms(x))
def body_params(self):
ep = {id(m.store.weight) for m in self.engrams.values()}
return [p for p in self.parameters() if id(p) not in ep]
def table_params(self): return [m.store.weight for m in self.engrams.values()]
def n_body(self): return sum(p.numel() for p in self.body_params())
def compile_blocks(m):
"""torch.compile each block: fuses the int8 / int4 / RMS / STE elementwise work."""
TLinear.cache = False
for mod in m.modules():
if isinstance(mod, Block): mod.forward = torch.compile(mod.forward, dynamic=False)
say("blocks compiled")
# ------------------------------------------------------------------ split readout
class Readout:
"""Row sets and position kinds. kind 0 text, 1 picture, 2 sound, 3 clip."""
def __init__(self, T, dev):
nL = int(T["n_lang"]); off = json.loads(str(T["off"])); marks = json.loads(str(T["marks"]))
cn = json.loads(str(T["ctrl_names"])); c0 = int(T["ctrl_off"]); R = len(T["bits"])
self.R = R
ctrl = np.arange(c0, c0 + len(cn)); mk = np.array(sorted(marks.values()))
sizes = {"image": 16384, "audio": 8192, "video": 4096}
sets = [np.r_[np.arange(nL), mk, ctrl]] + [np.r_[np.arange(off[m], off[m] + sizes[m]), mk, ctrl] for m in ("image", "audio", "video")]
self.sets = [torch.tensor(s, device=dev) for s in sets]
self.inv = []
for s in sets:
iv = torch.full((R,), -1, dtype=torch.long, device=dev); iv[torch.tensor(s, device=dev)] = torch.arange(len(s), device=dev)
self.inv.append(iv)
cid = {n: c0 + i for i, n in enumerate(cn)}
self.start = {1: [marks["image"], cid["[gen_image]"]], 2: [marks["audio"], cid["[gen_audio]"]], 3: [marks["video"], cid["[gen_video]"]]}
self.ends = [cid["[/image]"], cid["[/audio]"], cid["[/video]"], cid["[end_gen]"]]
self.band = {1: (off["image"], 16384), 2: (off["audio"], 8192), 3: (off["video"], 4096)}
def kinds(self, x):
"""(B,T) input ids -> (B,T) kind of the NEXT token's set."""
B, T = x.shape; pos = torch.arange(T, device=x.device).expand(B, T)
neg = torch.full_like(x, -1)
is_end = torch.zeros_like(x, dtype=torch.bool)
for e in self.ends: is_end |= x == e
last_end = torch.where(is_end, pos, neg).cummax(1).values
kind = torch.zeros_like(x)
best = neg.clone()
for k, st in self.start.items():
s = torch.zeros_like(x, dtype=torch.bool)
for t in st: s |= x == t
ls = torch.where(s, pos, neg).cummax(1).values
a, n = self.band[k]
inband = (x >= a) & (x < a + n)
hit = ((ls > last_end) & (ls > best)) | inband
kind = torch.where(hit, torch.full_like(x, k), kind)
best = torch.where(ls > best, ls, best)
return kind
def loss(self, m, z, x, y, chunk=8192):
"""z (B,T,512) features, x inputs, y targets -> (mean loss, per-kind (sum, count))."""
from torch.utils.checkpoint import checkpoint
kd = self.kinds(x).reshape(-1); z = z.reshape(-1, z.shape[-1]); y = y.reshape(-1)
total, stats = z.new_zeros((), dtype=torch.float32), []
for k in range(4):
idx = (kd == k).nonzero().squeeze(1)
if not len(idx): stats.append((0.0, 0)); continue
tgt = self.inv[k][y[idx]]
ok = tgt >= 0 # a target outside its set: never expected
idx, tgt = idx[ok], tgt[ok]
W = m.table[self.sets[k]]; bias = m.ubias[self.sets[k]]
if FLCE[0] is not None: # fused linear + cross-entropy: no logits in memory
s = FLCE[0](z[idx] * m.scale, W.to(z.dtype), tgt, bias.to(z.dtype), reduction="sum").float()
total = total + s; stats.append((s.item(), len(idx))); continue
s = z.new_zeros((), dtype=torch.float32)
for i in range(0, len(idx), chunk):
s = s + checkpoint(lambda zz, tt, W=W, bias=bias: F.cross_entropy(((zz @ W.T) * m.scale + bias).float(), tt, reduction="sum"),
z[idx[i:i + chunk]], tgt[i:i + chunk], use_reentrant=False)
total = total + s; stats.append((s.item(), len(idx)))
return total / max(1, len(y)), stats
FLCE = [None]
def use_fused_ce():
try:
from liger_kernel.transformers.functional import liger_fused_linear_cross_entropy as f
FLCE[0] = lambda x, w, t, b, reduction: f(x, w, t, b, reduction=reduction)
return True
except Exception as e:
say(f"fused CE unavailable ({type(e).__name__}); chunked readout"); return False
# ------------------------------------------------------------------ data
def pack(root, lanes, val_every=100):
root = pathlib.Path(root); out = root / "packed"; out.mkdir(exist_ok=True)
fs = sorted(f for l in lanes for f in glob.glob(str(root / "ids_final" / l / "*/part_*.npz")))
ftr, fva = open(out / "train.bin", "wb"), open(out / "val.bin", "wb"); n = [0, 0]
rng = np.random.default_rng(0); rng.shuffle(fs)
for f in fs:
v = zlib.crc32(f.encode()) % val_every == 0
ids = np.load(f)["ids"].astype(np.uint32); (fva if v else ftr).write(ids.tobytes()); n[v] += len(ids)
say(f"packed {len(fs)} shards: train {n[0]:,} tokens, val {n[1]:,}")
json.dump({"lanes": lanes, "train": n[0], "val": n[1]}, open(out / "packed.json", "w"))
class Pile:
def __init__(self, path, seed=0):
self.x = np.memmap(path, dtype=np.uint32, mode="r"); self.rng = np.random.default_rng(seed)
def batch(self, bs, ctx):
i = self.rng.integers(0, len(self.x) - ctx - 1, bs)
w = np.stack([self.x[j:j + ctx + 1] for j in i]).astype(np.int64)
return w[:, :-1], w[:, 1:]
# ------------------------------------------------------------------ train
def schedule(frac, stages):
ctx = stages[0][1]
for f, c in stages:
if frac >= f: ctx = c
return ctx
def train(a):
dev = "cuda" if torch.cuda.is_available() else "cpu"
out = pathlib.Path(a.out); out.mkdir(parents=True, exist_ok=True)
T = dict(np.load(a.table, allow_pickle=True)); R = len(T["bits"])
eng, canon = None, None
if a.engram_entries:
sys.path.insert(0, str(HERE))
eg_path = pathlib.Path(a.engram_py)
import importlib.util
spec = importlib.util.spec_from_file_location("eg", str(eg_path)); eg = importlib.util.module_from_spec(spec); spec.loader.exec_module(eg)
slots, n_tables, dh, cells = eg.size_for(a.engram_entries, 512)
old = eg.canonical_map(a.spm, a.new2old, 131072)
nL = int(T["n_lang"]); canon = np.arange(R) + old.max() + 1
canon[:nL] = old[T["lang_old_ids"]]
eng = {"n_slots": slots, "d_mem": 512, "_path": eg_path}
say(f"engram: 2 modules x {n_tables} tables x {slots:,} slots x {dh} = {2*cells/1e6:.0f}M cells")
m = Shadow(T, d=a.d, prelude=a.prelude, core=a.core, coda=a.coda, flat=a.flat, engram=eng, canonical=canon).to(dev)
ro = Readout(T, dev)
if a.fused_ce: use_fused_ce()
if a.compile: compile_blocks(m)
train_p, val_p = Pile(pathlib.Path(a.data) / "train.bin", a.seed), Pile(pathlib.Path(a.data) / "val.bin", 1)
stages = [(0.0, 2048)] + [(float(f), int(c)) for f, c in (s.split(":") for s in a.len_stages.split(",") if s)]
tok_step = a.bs * 2048
steps = int(a.tokens // tok_step)
say(f"table {R:,} rows; body {m.n_body()/1e6:.2f}M params; executed {m.executed()} blocks now"
+ ("" if a.flat else f", {len(m.pre) + 4 * len(m.core) + len(m.coda)} after growth at {a.grow_at:.0%}")
+ f"; {steps:,} steps x {tok_step:,} tokens; length stages {stages}; train {len(train_p.x):,} tokens")
opt = torch.optim.AdamW(m.body_params(), lr=a.lr, weight_decay=0.01, betas=(0.9, 0.95))
opts = [opt] + ([torch.optim.SparseAdam(m.table_params(), lr=5 * a.lr, betas=(0.9, 0.95))] if eng else [])
warm = max(1, int(0.02 * steps))
lr_at = lambda s: a.lr * (s / warm if s < warm else 0.1 + 0.9 * 0.5 * (1 + math.cos(math.pi * (s - warm) / max(1, steps - warm))))
start, tok_seen, t0, hist = 0, 0, time.time(), []
if a.resume:
ck = torch.load(a.resume, map_location="cpu", weights_only=False)
m.load_state_dict(ck["state"], strict=False)
for o, sd in zip(opts, ck["opt"]): o.load_state_dict(sd)
start, tok_seen = ck["step"] + 1, ck["tok_seen"]; train_p.rng.bit_generator.state = ck["rng"]
t0 = time.time() - ck["elapsed"]; say(f"resumed at step {start}")
log = open(out / f"{a.tag}.log", "a")
kinds = ["text", "picture", "sound", "clip"]
def save(step, final=False):
st = {k: v for k, v in m.state_dict().items() if k not in ("table", "ubias")}
ck = {"state": st, "opt": [o.state_dict() for o in opts], "step": step, "tok_seen": tok_seen,
"rng": train_p.rng.bit_generator.state, "elapsed": time.time() - t0, "cfg": vars(a), "K": m.K, "hist": hist[-2000:]}
tmp = out / f"{a.tag}_latest.pt.tmp"; torch.save(ck, tmp); tmp.replace(out / f"{a.tag}_latest.pt")
if final: torch.save({"state": st, "cfg": vars(a), "K": m.K, "step": step}, out / f"{a.tag}_final.pt")
if a.hf_repo:
try:
from huggingface_hub import HfApi
HfApi().upload_file(path_or_fileobj=str(out / f"{a.tag}_latest.pt"), path_in_repo=f"proof/ckpt/{a.tag}_latest.pt",
repo_id=a.hf_repo, repo_type="dataset")
HfApi().upload_file(path_or_fileobj=str(out / f"{a.tag}.log"), path_in_repo=f"proof/ckpt/{a.tag}.log", repo_id=a.hf_repo, repo_type="dataset")
except Exception as e: say(f" hub push failed: {str(e)[:120]}")
@torch.no_grad()
def held_out(ctx, n=32, sparse=False):
m.eval(); acc = np.zeros((4, 2))
rng = np.random.default_rng(123)
for _ in range(n // 4):
i = rng.integers(0, len(val_p.x) - ctx - 1, 4)
w = torch.tensor(np.stack([val_p.x[j:j + ctx + 1] for j in i]).astype(np.int64), device=dev)
with torch.autocast("cuda", dtype=torch.bfloat16, enabled=dev == "cuda"):
z = m.features(w[:, :-1], sparse=sparse); _, st = ro.loss(m, z, w[:, :-1], w[:, 1:])
for k, (s, c) in enumerate(st): acc[k] += (s, c)
m.train()
return {kinds[k]: acc[k, 0] / acc[k, 1] for k in range(4) if acc[k, 1]}, acc[:, 0].sum() / acc[:, 1].sum()
for step in range(start, steps):
STEP[0] = step; frac = step / steps
ctx = schedule(frac, stages); bs = max(1, tok_step // ctx)
if not a.flat: m.K = 4 if frac >= a.grow_at else 2
sparse = ctx >= a.sparse_ctx
for g in opt.param_groups: g["lr"] = lr_at(step)
if eng:
for g in opts[1].param_groups: g["lr"] = 5 * lr_at(step)
x, y = train_p.batch(bs, ctx)
micro = a.micro_k4 if m.K == 4 or ctx > 2048 else 1 # the 26-block pass in halves
for o in opts: o.zero_grad(set_to_none=True)
lm_t, ix_t, st = 0.0, 0.0, [[0.0, 0] for _ in range(4)]
for xs, ys in zip(np.array_split(x, micro), np.array_split(y, micro)):
xt, yt = torch.tensor(xs, device=dev), torch.tensor(ys, device=dev)
aux = []
with torch.autocast("cuda", dtype=torch.bfloat16, enabled=dev == "cuda"):
z = m.features(xt, sparse=sparse, aux=aux)
lm, st_ = ro.loss(m, z, xt, yt)
ix = torch.stack(aux).mean() if aux else lm.new_zeros(())
loss = (lm + a.index_w * ix) / micro
loss.backward()
lm_t += lm.item() / micro; ix_t += ix.item() / micro
for k in range(4): st[k][0] += st_[k][0]; st[k][1] += st_[k][1]
lm, ix = torch.tensor(lm_t), torch.tensor(ix_t)
torch.nn.utils.clip_grad_norm_(m.body_params(), 1.0)
for o in opts: o.step()
tok_seen += bs * ctx
hist.append((step, lm.item(), ix.item(), [(s, c) for s, c in st]))
if step % a.log_every == 0:
el = time.time() - t0; H = hist[-a.log_every:]
per = {kinds[k]: sum(h[3][k][0] for h in H) / max(1, sum(h[3][k][1] for h in H)) for k in range(4)}
line = (f"step {step:6d} ctx {ctx} K {m.K} loss {np.mean([h[1] for h in H]):.4f} index-KL {np.mean([h[2] for h in H]):.3f} "
+ " ".join(f"{k} {v:.3f}" for k, v in per.items() if v) + f" {tok_seen/max(el,1):,.0f} tok/s {el/3600:.2f} h")
say(line); log.write(line + "\n"); log.flush()
if step and step % a.eval_every == 0 or step == steps - 1:
per, tot = held_out(ctx, sparse=sparse)
line = f"HELD-OUT step {step} ctx {ctx} loss {tot:.4f} " + " ".join(f"{k} {v:.3f}" for k, v in per.items())
say(line); log.write(line + "\n"); log.flush()
if a.ckpt_every and step and step % a.ckpt_every == 0: save(step)
if a.hours and time.time() - t0 > a.hours * 3600: say("time budget reached"); break
save(step, final=True)
if eng:
for k, mod_ in m.engrams.items(): mod_.export(out / f"{a.tag}_engram_{k}")
say(f"done: {tok_seen/1e6:.0f}M tokens, {tok_seen/(time.time()-t0):,.0f} tok/s")
# ------------------------------------------------------------------ smoke test (laptop, synthetic)
def smoke(a):
"""A fake table in the proof layout and random ids with real span structure: checks the
loop, growth, BO, int8, index KL, sparse attention, split readout and a backward pass."""
rng = np.random.default_rng(0); nL = 1000
sizes = {"image": 16384, "audio": 8192, "video": 4096}
off = {"image": nL, "audio": nL + 16384, "video": nL + 16384 + 8192}; m0 = nL + 28672
marks = {"image": m0, "audio": m0 + 1, "video": m0 + 2, "sep": m0 + 3}
import importlib.util
spec = importlib.util.spec_from_file_location("bi", str(HERE / "build_ids.py")); src = open(HERE / "build_ids.py").read()
cn = eval(src[src.index("CTRL_NAMES = (") + len("CTRL_NAMES = "):src.index("assert len(CTRL_NAMES)")])
R = m0 + 4 + len(cn)
T = {"bits": (rng.random((R, 512)) < 0.5).astype(np.uint8), "bias": np.zeros(R, np.float32), "n_lang": nL,
"off": json.dumps(off), "marks": json.dumps(marks), "ctrl_off": m0 + 4, "ctrl_names": json.dumps(cn)}
dev = "cuda" if torch.cuda.is_available() else "cpu"
m = Shadow(T, d=128, heads=4, prelude=1, core=2, coda=1).to(dev); ro = Readout(T, dev)
cid = {n: m0 + 4 + i for i, n in enumerate(cn)}
seq = []
while len(seq) < 4 * 1100:
seq += list(rng.integers(0, nL, 50))
mod = ["image", "audio", "video"][rng.integers(3)]
seq += [marks[mod]] + list(off[mod] + rng.integers(0, sizes[mod], 16)) + [cid["[/" + mod + "]"]]
x = torch.tensor(np.array(seq[:4 * 1025]).reshape(4, 1025), device=dev)
kd = ro.kinds(x[:, :-1])
y = x[:, 1:]
bad = sum(int((ro.inv[k][y[kd == k]] < 0).sum()) for k in range(4))
say(f"kinds: text {(kd==0).sum().item()}, picture {(kd==1).sum().item()}, sound {(kd==2).sum().item()}, clip {(kd==3).sum().item()}; targets outside their set: {bad}")
opt = torch.optim.AdamW(m.parameters(), lr=1e-3)
for step in range(30):
STEP[0] = step; m.K = 2 if step < 15 else 4
aux = []
z = m.features(x[:, :-1], sparse=step % 2 == 1, aux=aux)
lm, st = ro.loss(m, z, x[:, :-1], y)
loss = lm + 0.1 * torch.stack(aux).mean()
opt.zero_grad(); loss.backward(); opt.step()
if step % 5 == 0 or step == 29:
say(f"step {step} K {m.K} sparse {step % 2 == 1} loss {lm.item():.3f} index-KL {torch.stack(aux).mean().item():.3f} alpha {m.alpha[:4].detach().cpu().numpy().round(3)}")
def speed(a):
"""Real shapes on random ids: tok/s of a full train step (fwd + bwd + AdamW)."""
rng = np.random.default_rng(0); nL = 65536
off = {"image": nL, "audio": nL + 16384, "video": nL + 16384 + 8192}; m0 = nL + 28672
marks = {"image": m0, "audio": m0 + 1, "video": m0 + 2, "sep": m0 + 3}
src = open(HERE / "build_ids.py").read()
cn = eval(src[src.index("CTRL_NAMES = (") + len("CTRL_NAMES = "):src.index("assert len(CTRL_NAMES)")])
R = m0 + 4 + len(cn)
T = {"bits": (rng.random((R, 512)) < 0.5).astype(np.uint8), "bias": np.zeros(R, np.float32), "n_lang": nL,
"off": json.dumps(off), "marks": json.dumps(marks), "ctrl_off": m0 + 4, "ctrl_names": json.dumps(cn)}
dev = "cuda"
m = Shadow(T, d=a.d, prelude=a.prelude, core=a.core, coda=a.coda, flat=a.flat).to(dev); ro = Readout(T, dev)
m.K = a.speed_k
if a.fused_ce: use_fused_ce()
if a.compile: compile_blocks(m)
opt = torch.optim.AdamW(m.parameters(), lr=1e-4)
say(f"body {m.n_body()/1e6:.2f}M, executed {m.executed()} blocks, bs {a.bs} x {a.speed_ctx}")
x = torch.tensor(rng.integers(0, nL, (a.bs, a.speed_ctx + 1)), device=dev)
for step in range(12):
if step == 4: torch.cuda.synchronize(); t0 = time.time()
STEP[0] = step; aux = []
with torch.autocast("cuda", dtype=torch.bfloat16):
z = m.features(x[:, :-1], sparse=a.speed_ctx >= a.sparse_ctx, aux=aux)
lm, _ = ro.loss(m, z, x[:, :-1], x[:, 1:]); loss = lm + 0.1 * torch.stack(aux).mean()
opt.zero_grad(); loss.backward(); opt.step()
torch.cuda.synchronize(); el = time.time() - t0
say(f"{8 * a.bs * a.speed_ctx / el:,.0f} tok/s ({el/8*1000:.0f} ms a step), peak {torch.cuda.max_memory_allocated()/1e9:.1f} GB")
if __name__ == "__main__":
ap = argparse.ArgumentParser(); ap.add_argument("cmd")
ap.add_argument("--root", default="/workspace/shadow"); ap.add_argument("--lanes", default="knowledge,understanding")
ap.add_argument("--table", default="/workspace/shadow/tables/proof/table.npz"); ap.add_argument("--data", default="/workspace/shadow/packed")
ap.add_argument("--d", type=int, default=512); ap.add_argument("--prelude", type=int, default=2)
ap.add_argument("--core", type=int, default=6); ap.add_argument("--coda", type=int, default=2); ap.add_argument("--flat", type=int, default=0)
ap.add_argument("--grow-at", type=float, default=0.6); ap.add_argument("--len-stages", default="0.92:4096,0.97:8192")
ap.add_argument("--sparse-ctx", type=int, default=4096); ap.add_argument("--index-w", type=float, default=0.1)
ap.add_argument("--tokens", type=float, default=2.3e9); ap.add_argument("--bs", type=int, default=16)
ap.add_argument("--micro-k4", type=int, default=2)
ap.add_argument("--compile", type=int, default=1); ap.add_argument("--fused-ce", type=int, default=1)
ap.add_argument("--speed-k", type=int, default=2); ap.add_argument("--speed-ctx", type=int, default=2048)
ap.add_argument("--lr", type=float, default=3e-4); ap.add_argument("--seed", type=int, default=0)
ap.add_argument("--engram-entries", type=int, default=0); ap.add_argument("--engram-py", default="/workspace/shadow/scripts/eng03.py")
ap.add_argument("--spm", default="/workspace/shadow/tables/tokenizer.model"); ap.add_argument("--new2old", default="/workspace/shadow/tables/new2old.u32")
ap.add_argument("--log-every", type=int, default=50); ap.add_argument("--eval-every", type=int, default=1000)
ap.add_argument("--ckpt-every", type=int, default=2000); ap.add_argument("--hours", type=float, default=0)
ap.add_argument("--out", default="/workspace/shadow/ckpt"); ap.add_argument("--tag", default="proof")
ap.add_argument("--hf-repo", default=None); ap.add_argument("--resume", default=None)
a = ap.parse_args()
if a.cmd == "pack": pack(a.root, a.lanes.split(","))
elif a.cmd == "train": train(a)
elif a.cmd == "smoke": smoke(a)
elif a.cmd == "speed": speed(a)