Download model2.py from aldigobbler/constoloop: direct link, hf CLI and curl.
- Browser
- Download file 14.6 kB
-
https://huggingface.co/aldigobbler/constoloop/resolve/main/model2.py
- Command line
-
hf download hf://aldigobbler/constoloop/model2.py
-
curl -L -o model2.py https://huggingface.co/aldigobbler/constoloop/resolve/main/model2.py
14.6 kB
| """O(n) sparse transformer built to read few bytes per generated token. | |
| Mixer: text is cut into chunks of 128 tokens. A token attends exactly (softmax, RoPE) to its | |
| own chunk so far and the previous chunk. Older chunks are evicted into a fixed-size linear | |
| memory per head that fades at a learned rate; the memory is constant within a chunk. State | |
| size never grows, so training is O(n) and generation O(1) per token. | |
| Feed-forward: 8 experts, 2 used per token, so most parameters are not read for any one token. | |
| Looping: the middle 8 blocks run `loops` times with shared weights. Each pass after the first | |
| re-reads the prelude output and adds a learned pass embedding, which also steers the expert | |
| router, so passes can specialize. | |
| Embedding and output share a rank-256 table, which shrinks the softmax 3x. | |
| """ | |
| from dataclasses import dataclass | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| from model import RMSNorm, TiedCE, rope, sample | |
| class Config2: | |
| vocab: int = 64512 | |
| rank: int = 256 | |
| dim: int = 768 | |
| layers: int = 12 | |
| prelude: int = 2 | |
| coda: int = 2 | |
| max_loops: int = 3 | |
| heads: int = 12 | |
| kv_heads: int = 4 | |
| chunk: int = 128 | |
| experts: int = 8 | |
| active: int = 2 | |
| ff: int = 592 | |
| capacity: float = 1.25 | |
| rope_theta: float = 10_000.0 | |
| phi = lambda x: F.elu(x) + 1 | |
| class Mixer(nn.Module): | |
| def __init__(self, c): | |
| super().__init__() | |
| self.c, self.hd, self.rep = c, c.dim // c.heads, c.heads // c.kv_heads | |
| self.q = nn.Linear(c.dim, c.dim, bias=False) | |
| self.kv = nn.Linear(c.dim, 2 * c.kv_heads * self.hd, bias=False) | |
| self.gate = nn.Linear(c.dim, c.heads) | |
| self.out = nn.Linear(c.dim, c.dim, bias=False) | |
| self.qn, self.kn = RMSNorm(self.hd), RMSNorm(self.hd) | |
| self.decay = nn.Parameter(torch.linspace(0.0, 4.0, c.kv_heads)) # sigmoid, per chunk | |
| nn.init.zeros_(self.gate.weight) | |
| nn.init.constant_(self.gate.bias, -2.0) | |
| def qkv(self, x): | |
| B, T, _ = x.shape | |
| q = self.qn(self.q(x).view(B, T, self.c.heads, self.hd)).transpose(1, 2) | |
| k, v = self.kv(x).view(B, T, self.c.kv_heads, 2 * self.hd).chunk(2, -1) | |
| return q, self.kn(k).transpose(1, 2), v.transpose(1, 2) | |
| def expand(self, t): # [B, K, ...] -> [B, H, ...] | |
| return t.repeat_interleave(self.rep, 1) | |
| def forward(self, x, pos): | |
| B, T, D = x.shape | |
| c, w, K, rep = self.c, self.c.chunk, self.c.kv_heads, self.rep | |
| C = T // w | |
| q, k, v = self.qkv(x) | |
| # Exact attention over [previous chunk, own chunk]: causal windows of two chunks, half | |
| # overlapping, so the fast is_causal kernel applies. The first window also yields chunk 0. | |
| qr, kr = rope(q, pos, c.rope_theta), rope(k, pos, c.rope_theta) | |
| if C > 1: | |
| def win(t): # [B,heads,T,D] -> [B,C-1,heads,2w,D] | |
| t = t.unflatten(2, (C, w)).transpose(1, 2) | |
| return torch.cat((t[:, :-1], t[:, 1:]), 3) | |
| grow = lambda t: t[:, :, :, None].expand(-1, -1, -1, rep, -1, -1).flatten(2, 3) | |
| y = F.scaled_dot_product_attention(win(qr).flatten(0, 1), grow(win(kr)).flatten(0, 1), | |
| grow(win(v)).flatten(0, 1), is_causal=True).unflatten(0, (B, C - 1)) | |
| y = torch.cat((y[:, 0, :, :w], y[:, :, :, w:].transpose(1, 2).flatten(2, 3)), 2) # [B,H,T,D] | |
| else: | |
| y = F.scaled_dot_product_attention(qr, self.expand(kr), self.expand(v), is_causal=True) | |
| # Fading memory of everything older. | |
| if C > 2: | |
| with torch.autocast(x.device.type, enabled=False): # accumulate in fp32 | |
| fk, vb = phi(k.float()).unflatten(2, (C, w)), v.float().unflatten(2, (C, w)) | |
| U, S = fk[:, :, :-2].transpose(-1, -2) @ vb[:, :, :-2], fk[:, :, :-2].sum(3) | |
| lag = (torch.arange(C - 2, device=x.device)[:, None] - torch.arange(C - 2, device=x.device)[None]).float() | |
| W = torch.where(lag >= 0, torch.sigmoid(self.decay)[:, None, None] ** lag.clamp(min=0), 0.0) | |
| M = torch.einsum("kcj,bkjde->bkcde", W, U) | |
| Z = torch.einsum("kcj,bkjd->bkcd", W, S) | |
| scale = Z.mean(-1, keepdim=True) + 1e-3 # same ratio, but safe to read in bf16 | |
| M, Z, eps = M / scale.unsqueeze(-1), Z / scale, 1e-3 / scale | |
| # queries of one key/value head are read together, so nothing is copied | |
| f = phi(q[:, :, 2 * w:]).unflatten(1, (K, rep)).unflatten(3, (C - 2, w)) # [B,K,rep,C-2,w,D] | |
| f = f.transpose(2, 3).flatten(3, 4) # [B,K,C-2,rep*w,D] | |
| num = f @ M.to(f.dtype) | |
| den = f.float() @ Z.unsqueeze(-1) + eps.unsqueeze(-1) | |
| r = num / den.to(num.dtype) | |
| r = r.unflatten(3, (rep, w)).transpose(2, 3).flatten(3, 4).flatten(1, 2) # [B,H,T-2w,D] | |
| g = torch.sigmoid(self.gate(x[:, 2 * w:])).transpose(1, 2).unsqueeze(-1) | |
| y = torch.cat((y[:, :, :2 * w], y[:, :, 2 * w:] + (g.to(r.dtype) * r).to(y.dtype)), 2) | |
| return self.out(y.transpose(1, 2).reshape(B, T, D)) | |
| def step(self, x, pos, st): | |
| """A segment inside one chunk. st: dict with M, Z, prev (k,v), cur (k,v).""" | |
| B, T, D = x.shape | |
| c = self.c | |
| q, k, v = self.qkv(x) | |
| kr = rope(k, pos, c.rope_theta) | |
| if not st: | |
| z = k.new_zeros(B, c.kv_heads, self.hd, self.hd, dtype=torch.float32) | |
| st.update(M=z, Z=z[..., 0], prev=None, cur=None) | |
| if st["cur"] is not None and st["cur"][0].shape[2] == c.chunk: # chunk finished: evict the older one | |
| if st["prev"] is not None: | |
| g = torch.sigmoid(self.decay).view(1, -1, 1, 1) | |
| f = phi(st["prev"][2].float()) | |
| st["M"] = g * st["M"] + f.transpose(-1, -2) @ st["prev"][1].float() | |
| st["Z"] = g[..., 0] * st["Z"] + f.sum(2) | |
| st["prev"], st["cur"] = st["cur"], None | |
| new = (kr, v, k) # rotated keys for attention, plain keys for the memory | |
| st["cur"] = new if st["cur"] is None else tuple(torch.cat(p, 2) for p in zip(st["cur"], new)) | |
| K, V = st["cur"][0], st["cur"][1] | |
| if st["prev"] is not None: | |
| K, V = torch.cat((st["prev"][0], K), 2), torch.cat((st["prev"][1], V), 2) | |
| n = K.shape[2] | |
| mask = torch.ones(T, n, dtype=torch.bool, device=x.device).tril(n - T) | |
| y = F.scaled_dot_product_attention(rope(q, pos, c.rope_theta), self.expand(K), self.expand(V), attn_mask=mask) | |
| f = phi(q.float()) | |
| r = (f @ self.expand(st["M"])) / ((f * self.expand(st["Z"]).unsqueeze(2)).sum(-1, keepdim=True) + 1e-3) | |
| y = y + torch.sigmoid(self.gate(x)).transpose(1, 2).unsqueeze(-1) * r.to(y.dtype) | |
| return self.out(y.transpose(1, 2).reshape(B, T, D)) | |
| class Experts(nn.Module): | |
| def __init__(self, c): | |
| super().__init__() | |
| self.c = c | |
| self.route = nn.Linear(c.dim, c.experts, bias=False) | |
| self.up = nn.Parameter(torch.empty(c.experts, c.dim, 2 * c.ff)) | |
| self.down = nn.Parameter(torch.empty(c.experts, c.ff, c.dim)) | |
| self.register_buffer("bias", torch.zeros(c.experts)) # keeps expert load even | |
| def forward(self, x): | |
| """-> (output, pairs per expert, dropped pairs)""" | |
| c = self.c | |
| B, T, D = x.shape | |
| flat = x.reshape(-1, D) | |
| N = len(flat) | |
| logit = self.route(flat).float() | |
| pick = (logit + self.bias).topk(c.active, -1).indices # balancing affects choice only | |
| weight = logit.gather(1, pick).softmax(-1).flatten() | |
| expert = pick.flatten() # N * active pairs | |
| token = torch.arange(N, device=x.device).repeat_interleave(c.active) | |
| cap = int(N * c.active / c.experts * c.capacity) if self.training else N | |
| empty = c.experts * cap | |
| with torch.no_grad(): # integer bookkeeping only; features move in two gathers | |
| order = torch.argsort(expert, stable=True) | |
| e = expert[order] | |
| load = torch.zeros(c.experts, dtype=torch.long, device=x.device).scatter_add_(0, expert, torch.ones_like(expert)) | |
| rank = torch.arange(len(e), device=x.device) - (load.cumsum(0) - load)[e] | |
| ok = rank < cap | |
| slot = torch.where(ok, e * cap + rank, empty) # overflow -> the zero row | |
| source = torch.full((empty + 1,), N, device=x.device).scatter_(0, slot, torch.where(ok, token[order], N)) | |
| where = torch.empty_like(slot).scatter_(0, order, slot) # slot of each (token, pick) pair | |
| pad = lambda t: torch.cat((t, t.new_zeros(1, D))) | |
| h = pad(flat).index_select(0, source[:-1]).view(c.experts, cap, D) | |
| a, b = torch.bmm(h, self.up.to(h.dtype)).chunk(2, -1) | |
| o = torch.bmm(F.silu(a) * b, self.down.to(h.dtype)).reshape(-1, D) | |
| o = pad(o).index_select(0, where).view(N, c.active, D) | |
| y = (o * weight.view(N, c.active, 1).to(o.dtype)).sum(1) | |
| return y.view(B, T, D), load, (~ok).sum() | |
| def infer(self, x): | |
| """Small batches: run only the experts that were chosen.""" | |
| flat = x.reshape(-1, x.shape[-1]) | |
| logit = self.route(flat).float() | |
| pick = (logit + self.bias).topk(self.c.active, -1).indices | |
| weight = logit.gather(1, pick).softmax(-1).to(x.dtype) | |
| y = torch.zeros_like(flat) | |
| for e in pick.unique().tolist(): | |
| i, j = (pick == e).nonzero(as_tuple=True) | |
| a, b = (flat[i] @ self.up[e]).chunk(2, -1) | |
| y[i] += (F.silu(a) * b) @ self.down[e] * weight[i, j][:, None] | |
| return y.view_as(x) | |
| class Block2(nn.Module): | |
| def __init__(self, c): | |
| super().__init__() | |
| self.n1, self.n2, self.mix, self.ff = RMSNorm(c.dim), RMSNorm(c.dim), Mixer(c), Experts(c) | |
| def forward(self, x, pos): | |
| x = x + self.mix(self.n1(x), pos) | |
| y, load, dropped = self.ff(self.n2(x)) | |
| return x + y, load, dropped | |
| class ChunkLM(nn.Module): | |
| def __init__(self, c: Config2): | |
| super().__init__() | |
| self.c = c | |
| self.embed = nn.Embedding(c.vocab, c.rank) | |
| self.inp, self.outp = nn.Linear(c.rank, c.dim, bias=False), nn.Linear(c.dim, c.rank, bias=False) | |
| self.blocks = nn.ModuleList(Block2(c) for _ in range(c.layers)) | |
| self.norm, self.loop_norm, self.inject_norm = RMSNorm(c.dim), RMSNorm(c.dim), RMSNorm(c.dim) | |
| self.inject = nn.Parameter(torch.full((c.dim,), 0.5)) | |
| self.pass_emb = nn.Parameter(torch.zeros(c.max_loops, c.dim)) | |
| for n, p in self.named_parameters(): | |
| if p.ndim >= 2 and "gate" not in n and n != "pass_emb": | |
| last = n.endswith(("out.weight", "down")) | |
| nn.init.normal_(p, std=0.02 / (2 * c.layers) ** 0.5 if last else 0.02) | |
| nn.init.normal_(self.inp.weight, std=c.rank ** -0.5) | |
| nn.init.normal_(self.outp.weight, std=c.dim ** -0.5) | |
| def count(self): | |
| total = sum(p.numel() for p in self.parameters()) | |
| experts = sum(b.ff.up.numel() + b.ff.down.numel() for b in self.blocks) | |
| emb = self.embed.weight.numel() | |
| fixed, per = total - experts, experts * self.c.active // self.c.experts | |
| core = (self.c.layers - self.c.prelude - self.c.coda) / self.c.layers | |
| mixers = fixed - emb | |
| read = lambda r: emb + (mixers + per) * (1 + core * (r - 1)) | |
| return {"total": total, "excl_embed": total - emb, **{f"read_R{r}": read(r) for r in (1, 2, 3)}} | |
| def run(self, x, loops, call): | |
| """Apply prelude, looped core and coda; call(i, pass_no, x) runs block i.""" | |
| c = self.c | |
| end = c.layers - c.coda | |
| for i in range(c.prelude): | |
| x = call(i, 0, x) | |
| first = x | |
| for r in range(loops): | |
| if r: | |
| x = self.loop_norm(x) + self.inject.to(x.dtype) * self.inject_norm(first) + self.pass_emb[r].to(x.dtype) | |
| for i in range(c.prelude, end): | |
| x = call(i, r, x) | |
| for i in range(end, c.layers): | |
| x = call(i, 0, x) | |
| return self.norm(x) | |
| def forward(self, ids, loops=2): | |
| T = ids.shape[1] | |
| pad = -T % self.c.chunk | |
| pos = torch.arange(T + pad, device=ids.device) | |
| self.loads, self.dropped = [0] * self.c.layers, 0 | |
| def call(i, r, x): | |
| x, load, d = self.blocks[i](x, pos) | |
| self.loads[i] = self.loads[i] + load | |
| self.dropped = self.dropped + d | |
| return x | |
| return self.outp(self.run(self.inp(self.embed(F.pad(ids, (0, pad)))), loops, call)[:, :T]) | |
| def balance(self, rate=0.01): | |
| """Nudge routing toward equal expert load (call once per step).""" | |
| for b, load in zip(self.blocks, self.loads): | |
| b.ff.bias += rate * (load.float().mean() - load).sign() | |
| def logits(self, h): | |
| return F.linear(h, self.embed.weight) | |
| def loss(self, h, y, chunk=8192): | |
| h, y = h.flatten(0, 1), y.flatten() | |
| if (y < 0).any(): | |
| keep = y >= 0 | |
| h, y = h[keep], y[keep] | |
| return TiedCE.apply(h, self.embed.weight, y, chunk) | |
| def step(self, ids, pos, state, loops=2): | |
| """Feed ids (any length) after `pos` tokens; state maps (block, pass) to its memory.""" | |
| outs, w = [], self.c.chunk | |
| while ids.shape[1]: | |
| n = min(ids.shape[1], w - pos % w) # stay inside one chunk | |
| p = torch.arange(pos, pos + n, device=ids.device) | |
| def call(i, r, x): | |
| b = self.blocks[i] | |
| x = x + b.mix.step(b.n1(x), p, state.setdefault((i, r), {})) | |
| return x + b.ff.infer(b.n2(x)) | |
| outs.append(self.outp(self.run(self.inp(self.embed(ids[:, :n])), loops, call))) | |
| ids, pos = ids[:, n:], pos + n | |
| return torch.cat(outs, 1) | |
| def generate(self, ids, max_new, stop, loops=1, temperature=0.7, top_p=0.9, rep=1.1, *, top_k=0, generator=None): | |
| """Yield token ids.""" | |
| state, pos, feed, seen = {}, 0, ids, list(ids) | |
| dev = self.embed.weight.device | |
| for _ in range(max_new): | |
| h = self.step(torch.tensor([feed], device=dev), pos, state, loops) | |
| pos += len(feed) | |
| w = sample(self.logits(h[0, -1]), seen, temperature, top_p, rep, top_k=top_k, generator=generator) | |
| if w in stop: | |
| return | |
| yield w | |
| seen.append(w) | |
| feed = [w] | |