Download model.py from aldigobbler/constoloop: direct link, hf CLI and curl.
- Browser
- Download file 9.29 kB
-
https://huggingface.co/aldigobbler/constoloop/resolve/main/model.py
- Command line
-
hf download hf://aldigobbler/constoloop/model.py
-
curl -L -o model.py https://huggingface.co/aldigobbler/constoloop/resolve/main/model.py
9.29 kB
| """Looped hybrid transformer. | |
| embed -> prelude (2 blocks) -> core (10 blocks, run R times, shared weights) | |
| -> coda (2 blocks) -> tied output | |
| Blocks alternate a gated short convolution (cheap, 2-token state) with grouped-query | |
| attention, so only half of them need a KV cache. Looping adds depth without adding | |
| parameters, and R can be chosen at inference to trade speed for quality. | |
| """ | |
| from dataclasses import asdict, dataclass | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| import torch.utils.checkpoint | |
| class Config: | |
| vocab: int = 64512 # 64,402 LFM2.5 tokens padded to a multiple of 128 | |
| dim: int = 1024 | |
| ff: int = 2432 | |
| heads: int = 16 | |
| kv_heads: int = 8 | |
| prelude: int = 2 | |
| core: int = 10 | |
| coda: int = 2 | |
| max_loops: int = 3 | |
| rope_theta: float = 50_000.0 | |
| class TiedCE(torch.autograd.Function): | |
| """Mean cross-entropy over a large tied vocabulary. Gradients are formed slice by slice | |
| during the forward pass, so logits are computed once and never stored.""" | |
| def forward(ctx, h, weight, y, chunk): | |
| n = max(1, len(y)) | |
| need = ctx.needs_input_grad[0] or ctx.needs_input_grad[1] | |
| dtype = h.dtype | |
| E = weight.to(dtype) | |
| total = h.new_zeros((), dtype=torch.float32) | |
| gh = torch.empty_like(h) if need else None | |
| gE = torch.zeros_like(weight) if need else None | |
| with torch.autocast(h.device.type, enabled=False): | |
| for lo in range(0, len(y), chunk): | |
| a, t = h[lo:lo + chunk], y[lo:lo + chunk] | |
| p = torch.softmax(a @ E.T, -1, dtype=torch.float32) | |
| t = t[:, None] | |
| gold = p.gather(1, t) | |
| total -= gold.clamp(min=1e-30).log().sum() | |
| if need: | |
| p.scatter_(1, t, gold - 1) | |
| p = p.to(dtype) | |
| gh[lo:lo + chunk] = p @ E | |
| gE += p.T @ a | |
| if need: | |
| ctx.save_for_backward(gh, gE) | |
| ctx.n = n | |
| return total / n | |
| def backward(ctx, g): | |
| gh, gE = ctx.saved_tensors | |
| return gh * (g / ctx.n).to(gh.dtype), gE * (g / ctx.n), None, None | |
| class RMSNorm(nn.Module): | |
| def __init__(self, dim): | |
| super().__init__() | |
| self.weight = nn.Parameter(torch.ones(dim)) | |
| def forward(self, x): | |
| return F.rms_norm(x, (x.shape[-1],), self.weight.to(x.dtype), 1e-5) | |
| def sample(l, seen, temperature=0.7, top_p=0.9, rep=1.1, *, top_k=0, generator=None): | |
| """Pick a token id from logits, penalizing those in the last 128 seen.""" | |
| l = l.float().cpu() | |
| if rep != 1: | |
| u = torch.tensor(sorted(set(seen[-128:]))) | |
| l[u] = torch.where(l[u] > 0, l[u] / rep, l[u] * rep) | |
| if temperature == 0: | |
| return int(l.argmax()) | |
| if 0 < top_k < l.numel(): | |
| l, idx = l.topk(top_k) | |
| p = (l / temperature).softmax(-1) | |
| else: | |
| p, idx = (l / temperature).softmax(-1).sort(descending=True) | |
| if top_p < 1: | |
| p[p.cumsum(-1) - p > top_p] = 0 | |
| return int(idx[torch.multinomial(p, 1, generator=generator)]) | |
| def rope(q, pos, theta): | |
| """Rotary embedding; q is [B, H, T, D], pos is [T].""" | |
| d = q.shape[-1] | |
| freq = theta ** (-torch.arange(0, d, 2, device=q.device, dtype=torch.float32) / d) | |
| ang = pos.float()[:, None] * freq | |
| cos, sin = ang.cos().to(q.dtype), ang.sin().to(q.dtype) | |
| a, b = q[..., : d // 2], q[..., d // 2:] | |
| return torch.cat((a * cos - b * sin, a * sin + b * cos), -1) | |
| class Attention(nn.Module): | |
| def __init__(self, c): | |
| super().__init__() | |
| self.c, self.hd = c, c.dim // c.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.out = nn.Linear(c.dim, c.dim, bias=False) | |
| self.qn, self.kn = RMSNorm(self.hd), RMSNorm(self.hd) | |
| def forward(self, x, pos, cache=None): | |
| B, T, D = x.shape | |
| c = self.c | |
| q = self.qn(self.q(x).view(B, T, c.heads, self.hd)).transpose(1, 2) | |
| k, v = self.kv(x).view(B, T, c.kv_heads, 2 * self.hd).chunk(2, -1) | |
| k, v = self.kn(k).transpose(1, 2), v.transpose(1, 2) | |
| q, k = rope(q, pos, c.rope_theta), rope(k, pos, c.rope_theta) | |
| new = None | |
| if cache is not None: | |
| if cache: | |
| k, v = torch.cat((cache[0], k), 2), torch.cat((cache[1], v), 2) | |
| new = (k, v) | |
| rep = c.heads // c.kv_heads | |
| k = k[:, :, None].expand(-1, -1, rep, -1, -1).flatten(1, 2) | |
| v = v[:, :, None].expand(-1, -1, rep, -1, -1).flatten(1, 2) | |
| if cache and T > 1: | |
| raise ValueError("feed the prompt at once, then one token at a time") | |
| y = F.scaled_dot_product_attention(q, k, v, is_causal=T > 1) | |
| return self.out(y.transpose(1, 2).reshape(B, T, D)), new | |
| class ShortConv(nn.Module): | |
| """Gated causal depthwise convolution of width 3.""" | |
| def __init__(self, c): | |
| super().__init__() | |
| self.inp = nn.Linear(c.dim, 2 * c.dim, bias=False) | |
| self.out = nn.Linear(c.dim, c.dim, bias=False) | |
| self.w = nn.Parameter(torch.tensor([1.0, 0.0, 0.0])[:, None].repeat(1, c.dim)) | |
| def forward(self, x, pos, cache=None): | |
| gate, v = self.inp(x).chunk(2, -1) | |
| past = cache[0] if cache else v.new_zeros(v.shape[0], 2, v.shape[2]) | |
| h = torch.cat((past, v), 1) | |
| w = self.w.to(v.dtype) | |
| y = w[0] * v + w[1] * h[:, 1:-1] + w[2] * h[:, :-2] | |
| return self.out(gate * y), None if cache is None else (h[:, -2:],) | |
| class Block(nn.Module): | |
| def __init__(self, c, kind): | |
| super().__init__() | |
| self.n1, self.n2 = RMSNorm(c.dim), RMSNorm(c.dim) | |
| self.mix = Attention(c) if kind == "attn" else ShortConv(c) | |
| self.up = nn.Linear(c.dim, 2 * c.ff, bias=False) | |
| self.down = nn.Linear(c.ff, c.dim, bias=False) | |
| def forward(self, x, pos, cache=None): | |
| y, new = self.mix(self.n1(x), pos, cache) | |
| x = x + y | |
| a, b = self.up(self.n2(x)).chunk(2, -1) | |
| return x + self.down(F.silu(a) * b), new | |
| class LoopLM(nn.Module): | |
| def __init__(self, c: Config): | |
| super().__init__() | |
| self.c = c | |
| stack = lambda n: nn.ModuleList(Block(c, "attn" if i % 2 else "conv") for i in range(n)) | |
| self.embed = nn.Embedding(c.vocab, c.dim) | |
| self.prelude, self.core, self.coda = stack(c.prelude), stack(c.core), stack(c.coda) | |
| self.loop_norm, self.inject_norm, self.norm = RMSNorm(c.dim), RMSNorm(c.dim), RMSNorm(c.dim) | |
| self.inject = nn.Parameter(torch.full((c.dim,), 0.5)) | |
| depth = c.prelude + 2 * c.core + c.coda | |
| for n, p in self.named_parameters(): | |
| if p.ndim == 2 and not n.endswith(".w"): | |
| last = n.endswith(("out.weight", "down.weight")) | |
| nn.init.normal_(p, std=0.02 / (2 * depth) ** 0.5 if last else 0.02) | |
| def count(self): | |
| total = sum(p.numel() for p in self.parameters()) | |
| return total, total - self.embed.weight.numel() | |
| def forward(self, ids, loops=2, pos=0, caches=None): | |
| """Hidden states; caches is a list to fill/reuse when generating.""" | |
| positions = torch.arange(pos, pos + ids.shape[1], device=ids.device) | |
| fresh = caches is not None and not caches | |
| i = 0 | |
| def run(block, x): | |
| nonlocal i | |
| if caches is None: | |
| return block(x, positions)[0] | |
| x, new = block(x, positions, () if fresh else caches[i]) | |
| if fresh: | |
| caches.append(new) | |
| else: | |
| caches[i] = new | |
| i += 1 | |
| return x | |
| x = self.embed(ids) | |
| for b in self.prelude: | |
| x = run(b, x) | |
| first = x | |
| for r in range(loops): | |
| if r: # re-read the input so repeated passes stay anchored to it | |
| x = self.loop_norm(x) + self.inject.to(x.dtype) * self.inject_norm(first) | |
| for b in self.core: | |
| x = run(b, x) | |
| for b in self.coda: | |
| x = run(b, x) | |
| return self.norm(x) | |
| 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(): # fine-tuning: skip masked positions before the softmax | |
| keep = y >= 0 | |
| h, y = h[keep], y[keep] | |
| if torch.is_autocast_enabled(h.device.type): | |
| h = h.to(torch.get_autocast_dtype(h.device.type)) | |
| return TiedCE.apply(h, self.embed.weight, y, chunk) | |
| def generate(self, ids, max_new, stop, loops=2, temperature=0.7, top_p=0.9, rep=1.1, *, top_k=0, generator=None): | |
| """Yield token ids.""" | |
| caches, pos, feed, seen = [], 0, ids, list(ids) | |
| dev = self.embed.weight.device | |
| for _ in range(max_new): | |
| h = self(torch.tensor([feed], device=dev), loops, pos, caches) | |
| 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] | |
| def save_config(c): | |
| return asdict(c) | |