Text Generation
PyTorch
English
recurrent-depth
fineweb-edu
File size: 14,573 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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
"""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


@dataclass
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])

    @torch.no_grad()
    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)

    @torch.inference_mode()
    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]