File size: 9,285 Bytes
3110cd8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 | """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
@dataclass
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."""
@staticmethod
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
@staticmethod
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)
@torch.no_grad()
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)
|