File size: 30,066 Bytes
4acaaff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
"""Nessim-48M-Base for Transformers, in plain PyTorch: it runs on CPU or any GPU with only torch and transformers.

Derived from modeling_klm.py of KLM 1.6 (Apache-2.0, https://huggingface.co/MinimaLabs/KLM-1.6): the Gated DeltaNet-2
and attention layers, Block Attention Residuals, the exact n-gram memory, the document handling and the plain
PyTorch recurrence are that file's. Changes: a looped core (`n_core` layers applied `loops` times, every application
its own Block Attention Residuals consumer, `loop_signal[l]` added to the newest source at the start of loop l > 0),
and four programs computed from `input_ids` inside forward: previous-token and induction inputs read through one
low-rank map (an extra Block Attention Residuals source), a learned distance bias per attention head, and a copy
pointer that boosts the logits of tokens already in the document. The files of the KLM 1.6 directory that are
not needed here (fast_decode.py, the Triton decoder) are not shipped, and generation keeps no cache: every step
runs the whole sequence again.

A sequence may hold several documents separated by <eos>: after each <eos> the attention mask, the Gated DeltaNet-2
state and its short convolutions, the n-gram history and all four programs restart, as they did in training. A
sequence without <eos> is one document, which is what lm-eval and the ArithMark-3 script feed. Right padding is
invisible to earlier positions; left padding (an attention_mask that is 0 then 1) starts a document at each row's
first real token.

The model computes every function below in the dtype of its weights, except the Gated DeltaNet-2 recurrence, the
Block Attention Residuals softmax, the decay and the pointer, which run in float32.
"""
from __future__ import annotations

import math
from dataclasses import dataclass

import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import PreTrainedModel
from transformers.generation import GenerationMixin
from transformers.modeling_outputs import CausalLMOutputWithPast

from .configuration_nessim import NessimConfig

CONV = 4  # short-convolution width
POINTER_FEATURES = 5
OFFSET_BUCKETS = 24


@dataclass(frozen=True)
class Application:
    """One use of an unshared layer; `index` counts applications in order and gives its Block Attention Residuals
    consumers 2 * index (mixer input) and 2 * index + 1 (feed-forward input)."""

    slot: int
    loop: int
    loop_start: bool


@dataclass(frozen=True)
class Segments:
    starts: torch.Tensor  # (B, T) bool, first token of a document
    docs: torch.Tensor  # (B, T) document id, equal inside a document
    pos: torch.Tensor  # (B, T) position inside the document


@dataclass(frozen=True)
class Sources:
    """Block Attention Residuals sources in preallocated buffers; each is RMS-normalized once, when it is added."""

    values: torch.Tensor  # (B, T, capacity, D) in the model dtype
    normed: torch.Tensor  # (B, T, capacity, D) float32


def is_attention(cfg: NessimConfig, slot: int) -> bool:
    return slot % cfg.attention_every == cfg.attention_every - 1


def applications(cfg: NessimConfig) -> list[Application]:
    order = [Application(slot, 0, False) for slot in range(cfg.n_prelude)]
    for loop in range(cfg.loops):
        order += [Application(cfg.n_prelude + j, loop, j == 0 and loop > 0) for j in range(cfg.n_core)]
    order += [Application(cfg.n_prelude + cfg.n_core + j, 0, False) for j in range(cfg.n_coda)]
    return order


def has_front(cfg: NessimConfig) -> bool:
    return cfg.previous_tokens > 0 or cfg.induction_inputs


def attention_slots(cfg: NessimConfig) -> list[int]:
    return [slot for slot in range(cfg.num_hidden_layers) if is_attention(cfg, slot)]


def holder(**members: nn.Module | nn.Parameter) -> nn.Module:
    """A bare container: parameters and submodules under the given names, so state-dict names are the dotted paths."""
    module = nn.Module()
    for name, member in members.items():
        setattr(module, name, member)
    return module


def norm_weight(dim: int) -> nn.Module:
    return holder(weight=nn.Parameter(torch.ones(dim)))


def build_mixer(cfg: NessimConfig, slot: int) -> nn.Module:
    dim = cfg.hidden_size
    if is_attention(cfg, slot):
        head_dim = dim // cfg.num_attention_heads
        return holder(
            q_proj=nn.Linear(dim, cfg.num_attention_heads * head_dim, bias=False),
            k_proj=nn.Linear(dim, cfg.num_key_value_heads * head_dim, bias=False),
            v_proj=nn.Linear(dim, cfg.num_key_value_heads * head_dim, bias=False),
            gate_proj=nn.Linear(dim, dim, bias=False),
            o_proj=nn.Linear(dim, dim, bias=False),
            q_norm=norm_weight(head_dim),
            k_norm=norm_weight(head_dim),
            value_mix=nn.Parameter(torch.tensor([0.5, 0.5])),
        )
    inner = cfg.gdn_heads * cfg.gdn_head_dim

    def conv() -> nn.Conv1d:
        return nn.Conv1d(inner, inner, CONV, groups=inner, bias=False)

    return holder(
        q_proj=nn.Linear(dim, inner, bias=False),
        k_proj=nn.Linear(dim, inner, bias=False),
        v_proj=nn.Linear(dim, inner, bias=False),
        q_conv1d=conv(),
        k_conv1d=conv(),
        v_conv1d=conv(),
        f_proj=nn.Sequential(nn.Linear(dim, cfg.gdn_head_dim, bias=False), nn.Linear(cfg.gdn_head_dim, inner, bias=False)),
        b_proj=nn.Linear(dim, inner, bias=False),
        w_proj=nn.Linear(dim, inner, bias=False),
        A_log=nn.Parameter(torch.zeros(cfg.gdn_heads)),
        dt_bias=nn.Parameter(torch.zeros(inner)),
        g_proj=nn.Sequential(nn.Linear(dim, cfg.gdn_head_dim, bias=False), nn.Linear(cfg.gdn_head_dim, inner, bias=True)),
        o_norm=norm_weight(cfg.gdn_head_dim),
        o_proj=nn.Linear(inner, dim, bias=False),
    )


def build_block(cfg: NessimConfig, slot: int) -> nn.Module:
    dim = cfg.hidden_size
    return holder(
        mixer_norm=norm_weight(dim),
        mixer=build_mixer(cfg, slot),
        ffn_norm=norm_weight(dim),
        ffn=holder(
            gate=nn.Linear(dim, cfg.intermediate_size, bias=False),
            up=nn.Linear(dim, cfg.intermediate_size, bias=False),
            down=nn.Linear(cfg.intermediate_size, dim, bias=False),
        ),
    )


def build_network(cfg: NessimConfig) -> nn.Module:
    """Parameters and buffers under the training code's names; every value comes from the checkpoint."""
    dim, rank = cfg.hidden_size, cfg.front_rank
    consumers = 2 * len(applications(cfg)) + 1
    members: dict[str, nn.Module | nn.Parameter] = {
        "embed": nn.Embedding(cfg.vocab_size, dim),
        "memory": holder(
            bigram=nn.Embedding(cfg.n_bigrams + 1, cfg.ngram_dim),
            trigram=nn.Embedding(cfg.n_trigrams + 1, cfg.ngram_dim),
            bigram_proj=nn.Linear(cfg.ngram_dim, dim, bias=False),
            trigram_proj=nn.Linear(cfg.ngram_dim, dim, bias=False),
        ),
        "blocks": nn.ModuleList([build_block(cfg, slot) for slot in range(cfg.num_hidden_layers)]),
        "attn_res_query": nn.Parameter(torch.zeros(consumers, dim)),
        "attn_res_norm": nn.Parameter(torch.ones(consumers, dim)),
        "norm": norm_weight(dim),
    }
    if cfg.loops > 1:
        members["loop_signal"] = nn.Parameter(torch.zeros(cfg.loops, dim))
    if has_front(cfg):
        columns = cfg.previous_tokens + (2 if cfg.induction_inputs else 0)
        members["front_proj"] = nn.Parameter(torch.zeros(dim, rank))
        members["front_mix"] = nn.Parameter(torch.zeros(columns * rank, dim))
    if cfg.copy_pointer:
        members["pointer_gate"] = nn.Parameter(torch.zeros(dim + 1, POINTER_FEATURES))
        members["pointer_decay"] = nn.Parameter(torch.zeros(POINTER_FEATURES))
    if cfg.distance_bias:
        members["distance_bias"] = nn.ParameterDict(
            {str(slot): nn.Parameter(torch.zeros(cfg.num_attention_heads, OFFSET_BUCKETS)) for slot in attention_slots(cfg)}
        )
    network = holder(**members)
    network.memory.register_buffer("bigram_keys", torch.zeros(cfg.n_bigrams, dtype=torch.int32))
    network.memory.register_buffer("trigram_keys", torch.zeros(cfg.n_trigrams, dtype=torch.int64))
    return network


def rms(x: torch.Tensor, weight: torch.Tensor, eps: float) -> torch.Tensor:
    return F.rms_norm(x, (x.shape[-1],), weight.to(x.dtype), eps)


def segments(tokens: torch.Tensor, eos_id: int, real: torch.Tensor | None) -> Segments:
    """Document starts, ids and in-document positions of tokens (B, T): the first token and every token after <eos>;
    with `real` (B, T), the first real token after left padding as well."""
    batch, seq_len = tokens.shape
    starts = torch.zeros_like(tokens, dtype=torch.bool)
    starts[:, 1:] = tokens[:, :-1] == eos_id
    if real is not None:
        starts[:, 1:] |= real[:, 1:] & ~real[:, :-1]
    starts[:, 0] = True
    idx = torch.arange(seq_len, device=tokens.device).expand(batch, seq_len)
    return Segments(starts=starts, docs=starts.cumsum(1), pos=idx - torch.where(starts, idx, 0).cummax(1).values)


def lookup(keys: torch.Tensor, queries: torch.Tensor) -> torch.Tensor:
    """Row of each query in a sorted key bank: p + 1 where keys[p] == query, else 0 (unknown)."""
    queries = queries.to(keys.dtype)
    p = torch.searchsorted(keys, queries).clamp_(max=keys.numel() - 1)
    return torch.where(keys[p] == queries, p + 1, 0)


def ngram_vectors(w: dict[str, torch.Tensor], cfg: NessimConfig, tokens: torch.Tensor) -> torch.Tensor:
    """Learned rows for the most frequent bigrams and trigrams, found by exact key lookup. Missing history (row
    start, or right after <eos>) is token 0."""
    t = tokens.long()
    n, v = t.shape[1], cfg.vocab_size
    prev1 = F.pad(t, (1, 0))[:, :n]
    prev2 = F.pad(t, (2, 0))[:, :n]
    reset = prev1 == cfg.eos_token_id
    prev1 = prev1.masked_fill(reset, 0)
    prev2 = prev2.masked_fill(reset | (prev2 == cfg.eos_token_id), 0)
    bigram = prev1 * v + t
    trigram = (prev2 * v + prev1) * v + t
    bi = F.embedding(lookup(w["memory.bigram_keys"], bigram), w["memory.bigram.weight"])
    tri = F.embedding(lookup(w["memory.trigram_keys"], trigram), w["memory.trigram.weight"])
    return F.linear(bi, w["memory.bigram_proj.weight"]) + F.linear(tri, w["memory.trigram_proj.weight"])


def in_document(docs: torch.Tensor, back: int) -> torch.Tensor:
    """Whether position t - back exists and belongs to the document of position t."""
    size = docs.shape[1]
    return F.pad(docs[:, : size - back] == docs[:, back:], (back, 0), value=False)


def induction_slots(tokens: torch.Tensor, docs: torch.Tensor, chunk: int) -> torch.Tensor:
    """(B, T, 2) int64: for column 0 (1) the position after the most recent s < t, in the document of t, whose last 1
    (2) tokens, all in that document, equal those ending at t; -1 if there is none. Query rows go in blocks of
    `chunk` against the sources before their last row."""
    tokens = tokens.long()
    size = tokens.shape[1]
    previous = F.pad(tokens[:, : size - 1], (1, 0))
    inside = in_document(docs, 1)
    blocks = []
    for start in range(0, size, chunk):
        stop = min(start + chunk, size)
        t = torch.arange(start, stop, device=tokens.device).view(1, -1, 1)
        s = torch.arange(stop, device=tokens.device).view(1, 1, -1)
        one = (docs[:, start:stop, None] == docs[:, None, :stop]) & (s < t) & (tokens[:, start:stop, None] == tokens[:, None, :stop])
        two = one & (previous[:, start:stop, None] == previous[:, None, :stop]) & inside[:, start:stop, None] & inside[:, None, :stop]
        found = torch.stack([torch.where(m, s, -1).amax(-1) for m in (one, two)], dim=-1)
        blocks.append(torch.where(found >= 0, found + 1, -1))
    return torch.cat(blocks, dim=1)


def front_inputs(w: dict[str, torch.Tensor], cfg: NessimConfig, tokens: torch.Tensor, docs: torch.Tensor) -> torch.Tensor:
    """Inputs added to the first hidden state: the token embeddings read through one low-rank map `front_proj`, at
    the `previous_tokens` positions before t in the same document and at the positions after the last earlier match
    of the current token and of the current token pair, concatenated and mixed by `front_mix` (zero for a missing
    position)."""
    size = tokens.shape[1]
    low = F.embedding(tokens.long(), w["embed.weight"]) @ w["front_proj"].to(w["embed.weight"].dtype)
    columns = []
    for back in range(1, cfg.previous_tokens + 1):
        columns.append(F.pad(low[:, : size - back], (0, 0, back, 0)) * in_document(docs, back).unsqueeze(-1))
    if cfg.induction_inputs:
        slots = induction_slots(tokens, docs, cfg.pointer_chunk)
        for column in range(2):
            position = slots[..., column]
            picked = low.gather(1, position.clamp(min=0).unsqueeze(-1).expand(-1, -1, low.shape[-1]))
            columns.append(picked * (position >= 0).unsqueeze(-1))
    return torch.cat(columns, dim=-1) @ w["front_mix"].to(low.dtype)


def offset_bucket_table(size: int, device: torch.device) -> torch.Tensor:
    """Bucket of each offset t - s in [0, size): exact below 8, then two buckets per octave, 24 in total; they start at
    the offsets 0 1 2 3 4 5 6 7 8 12 16 23 32 46 64 91 128 182 256 363 512 725 1024 1449."""
    delta = torch.arange(size, device=device)
    coarse = 8 + torch.floor(2.0 * torch.log2(delta.clamp(min=8).to(torch.float32) / 8.0)).to(torch.int64)
    return torch.where(delta < 8, delta, coarse.clamp(max=OFFSET_BUCKETS - 1))


def attention_mask(seg: Segments, bias: torch.Tensor | None, dtype: torch.dtype) -> torch.Tensor:
    """(B, 1 or H, T, T): True where the query may read the key (same document, not later), or, with a distance bias
    table (H, 24), 0 there plus bias[h, bucket(t - s)] and -inf elsewhere."""
    size = seg.docs.shape[1]
    index = torch.arange(size, device=seg.docs.device)
    allowed = ((seg.docs[:, :, None] == seg.docs[:, None, :]) & (index[None, :] <= index[:, None])).unsqueeze(1)
    if bias is None:
        return allowed
    delta = (index[:, None] - index[None, :]).clamp(min=0)
    dense = bias.float()[:, offset_bucket_table(size, seg.docs.device)[delta]].unsqueeze(0)
    return torch.where(allowed, dense, float("-inf")).to(dtype)


def rope(x: torch.Tensor, theta: float) -> torch.Tensor:
    """Half-rotation RoPE on (B, H, T, D) at the row positions."""
    dim = x.shape[-1]
    freqs = 1.0 / (theta ** (torch.arange(0, dim, 2, device=x.device).float() / dim))
    angles = torch.arange(x.shape[2], device=x.device).float()[:, None] * freqs
    cos, sin = angles.cos().to(x.dtype), angles.sin().to(x.dtype)
    x1, x2 = x.chunk(2, dim=-1)
    return torch.cat([x1 * cos - x2 * sin, x2 * cos + x1 * sin], dim=-1)


def attention_mixer(
    w: dict[str, torch.Tensor], cfg: NessimConfig, slot: int, x: torch.Tensor, v_first: torch.Tensor | None, mask: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
    """GQA with per-head QK-RMSNorm, RoPE, a sigmoid output gate and a value residual mixing each application's values
    with the first attention application's. Returns the output and the first application's raw values."""
    m = f"blocks.{slot}.mixer."
    batch, seq_len, dim = x.shape
    heads, kv_heads = cfg.num_attention_heads, cfg.num_key_value_heads
    head_dim = dim // heads
    q = F.linear(x, w[m + "q_proj.weight"]).view(batch, seq_len, heads, head_dim)
    k = F.linear(x, w[m + "k_proj.weight"]).view(batch, seq_len, kv_heads, head_dim)
    v = F.linear(x, w[m + "v_proj.weight"]).view(batch, seq_len, kv_heads, head_dim)
    if v_first is None:
        v_first = v
    mix = w[m + "value_mix"].float()
    values = (mix[0] * v.float() + mix[1] * v_first.float()).to(x.dtype).transpose(1, 2)
    q = rope(F.rms_norm(q.float(), (head_dim,), w[m + "q_norm.weight"].float(), cfg.rms_norm_eps).transpose(1, 2), cfg.rope_theta).to(x.dtype)
    keys = rope(F.rms_norm(k.float(), (head_dim,), w[m + "k_norm.weight"].float(), cfg.rms_norm_eps).transpose(1, 2), cfg.rope_theta).to(x.dtype)
    out = F.scaled_dot_product_attention(q, keys, values, attn_mask=mask, enable_gqa=True)
    out = out.transpose(1, 2).reshape(batch, seq_len, dim)
    return F.linear(out * torch.sigmoid(F.linear(x, w[m + "gate_proj.weight"])), w[m + "o_proj.weight"]), v_first


def short_conv(weight: torch.Tensor, x: torch.Tensor, taps_valid: torch.Tensor) -> torch.Tensor:
    """Causal depthwise convolution plus SiLU that never reaches back past a document start.
    x (B, T, C); taps_valid (B, T, CONV) zeroes the taps before the document start."""
    batch, seq_len, channels = x.shape
    ext = torch.cat([x.new_zeros(batch, CONV - 1, channels), x], 1)
    windows = ext.unfold(1, CONV, 1)  # (B, T, C, CONV), oldest input first
    return F.silu((windows * weight.view(channels, CONV).to(x.dtype) * taps_valid.unsqueeze(2)).sum(-1))


def l2norm(x: torch.Tensor) -> torch.Tensor:
    return x * torch.rsqrt((x * x).sum(-1, keepdim=True) + 1e-6)


def recurrence(
    q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, g: torch.Tensor, b: torch.Tensor, w: torch.Tensor, starts: torch.Tensor,
) -> torch.Tensor:
    """Gated DeltaNet-2 step by step in float32: S <- (I - k (b*k)^T) diag(exp g) S + k (w*v)^T and o = q^T S / sqrt(K),
    with S cleared at every document start. Inputs are (B, T, H, K)."""
    batch, seq_len, heads, key_dim = k.shape
    q = q * key_dim**-0.5
    state = q.new_zeros(batch, heads, key_dim, v.shape[-1])
    decay = (~starts).float()[:, :, None, None] * g.exp()
    erase_key, write_value = b * k, w * v
    out = []
    with torch.autocast(q.device.type, enabled=False):
        for t in range(seq_len):
            state = state * decay[:, t].unsqueeze(-1)
            erase = torch.einsum("bhk,bhkv->bhv", erase_key[:, t], state)
            state = state + k[:, t].unsqueeze(-1) * (write_value[:, t] - erase).unsqueeze(-2)
            out.append(torch.einsum("bhk,bhkv->bhv", q[:, t], state))
    return torch.stack(out, 1)


def log_decay(w: dict[str, torch.Tensor], cfg: NessimConfig, slot: int, x: torch.Tensor) -> torch.Tensor:
    """-exp(A_log) * softplus(f(x) + dt_bias), combined in log space in float32 and floored."""
    m = f"blocks.{slot}.mixer."
    f = F.linear(F.linear(x, w[m + "f_proj.0.weight"]), w[m + "f_proj.1.weight"])
    s = f.float().unflatten(-1, (cfg.gdn_heads, cfg.gdn_head_dim)) + w[m + "dt_bias"].float().view(cfg.gdn_heads, cfg.gdn_head_dim)
    log_act = torch.where(s < -20, s, F.softplus(s.clamp_min(-20)).log())
    log_mag = w[m + "A_log"].float().unsqueeze(-1) + log_act
    ceiling = math.log(-cfg.decay_floor)
    return torch.where(log_mag >= ceiling, cfg.decay_floor, -log_mag.clamp(max=ceiling).exp())


def gdn_mixer(
    w: dict[str, torch.Tensor], cfg: NessimConfig, slot: int, x: torch.Tensor, seg: Segments, taps_valid: torch.Tensor,
) -> torch.Tensor:
    """Gated DeltaNet-2 in flash-linear-attention's parameter layout: q/k/v short convolutions, channel-wise erase (b)
    and write (w) gates, a low-rank channel-wise decay, and a sigmoid-gated RMSNorm on the output."""
    m = f"blocks.{slot}.mixer."
    batch, seq_len, _ = x.shape
    heads, head_dim = cfg.gdn_heads, cfg.gdn_head_dim
    q = short_conv(w[m + "q_conv1d.weight"], F.linear(x, w[m + "q_proj.weight"]), taps_valid)
    k = short_conv(w[m + "k_conv1d.weight"], F.linear(x, w[m + "k_proj.weight"]), taps_valid)
    v = short_conv(w[m + "v_conv1d.weight"], F.linear(x, w[m + "v_proj.weight"]), taps_valid)

    def split(t: torch.Tensor) -> torch.Tensor:
        return t.float().view(batch, seq_len, heads, head_dim)

    o = recurrence(
        l2norm(split(q)), l2norm(split(k)), split(v), log_decay(w, cfg, slot, x),
        torch.sigmoid(split(F.linear(x, w[m + "b_proj.weight"]))), torch.sigmoid(split(F.linear(x, w[m + "w_proj.weight"]))),
        seg.starts,
    )
    gate = F.linear(F.linear(x, w[m + "g_proj.0.weight"]), w[m + "g_proj.1.weight"], w[m + "g_proj.1.bias"])
    o = rms(o.to(x.dtype), w[m + "o_norm.weight"], cfg.gdn_norm_eps) * torch.sigmoid(gate.view(batch, seq_len, heads, head_dim))
    return F.linear(o.reshape(batch, seq_len, -1), w[m + "o_proj.weight"])


def add_source(sources: Sources, n: int, v: torch.Tensor, eps: float) -> int:
    sources.values[:, :, n] = v
    sources.normed[:, :, n] = F.rms_norm(v.float(), (v.shape[-1],), eps=eps)
    return n + 1


def mix_sources(sources: Sources, n: int, query: torch.Tensor, partial: torch.Tensor | None, eps: float) -> torch.Tensor:
    """Softmax mix of the first n sources weighted by query . RMSNorm(source); `partial` (the current layer's mixer
    output, seen only by its feed-forward) joins as one more source."""
    with torch.autocast(query.device.type, enabled=False):
        logits = sources.normed[:, :, :n] @ query
        if partial is not None:
            normed = F.rms_norm(partial.float(), (partial.shape[-1],), eps=eps)
            logits = torch.cat([logits, (normed @ query).unsqueeze(-1)], -1)
        weights = logits.softmax(-1)
    out = (weights[..., :n, None].to(sources.values.dtype) * sources.values[:, :, :n]).sum(-2)
    if partial is not None:
        out = out + weights[..., n:].to(partial.dtype) * partial
    return out


def local_vocabulary(tokens: torch.Tensor, vocab: int) -> tuple[torch.Tensor, torch.Tensor]:
    """Number the distinct tokens of each window 0, 1, ... in sorted order: (number of each position, token of each
    number, `vocab` for numbers beyond the distinct count)."""
    sorted_tokens, order = tokens.sort(dim=1, stable=True)
    first = F.pad(sorted_tokens[:, 1:] != sorted_tokens[:, :-1], (1, 0), value=True)
    rank = first.to(torch.int64).cumsum(dim=1) - 1
    return (
        torch.zeros_like(tokens).scatter_(1, order, rank),
        torch.full_like(tokens, vocab).scatter_(1, rank, sorted_tokens),
    )


def previous_tokens(tokens: torch.Tensor, docs: torch.Tensor, back: int, missing: int) -> torch.Tensor:
    """tokens[t - back] where it lies in the document of t, else `missing`."""
    shifted = F.pad(tokens[:, : tokens.shape[1] - back], (back, 0), value=missing)
    return torch.where(in_document(docs, back), shifted, torch.full_like(shifted, missing))


def pointer_boost(
    w: dict[str, torch.Tensor], cfg: NessimConfig, tokens: torch.Tensor, docs: torch.Tensor, hidden: torch.Tensor,
) -> torch.Tensor:
    """Logit boost (B, T, V) for the tokens already in the document, added to the logits of position t.

    With the evidence of source c for query t in feature f, e_f(t, c) = [c in the document of t] x exp(-a_f (t - c)) x match_f:
      f = 0, 1: every c <= t (copy; a_0 fast, a_1 slow);
      f = 2, 3, 4: c = s + 1 where s < t is a source whose last 1, 2, 3-or-more tokens equal those ending at t, longest match only.
    S_f(t, v) = sum over the sources c holding token v of e_f(t, c), and boost(t, v) = sum_f gate_f(t) log1p(S_f(t, v)),
    with gate(t) = layer_norm(hidden_t) @ pointer_gate[:-1] + pointer_gate[-1] and a_f = softplus(pointer_decay_f).
    The sources are scattered into planes over the window's own distinct tokens, query rows in blocks of `pointer_chunk`
    against the sources up to their last row."""
    tokens = tokens.to(torch.int64)
    docs = docs.to(torch.int64)
    batch, size = tokens.shape
    width, vocab = hidden.shape[-1], cfg.vocab_size
    slots = min(size, vocab)
    gate_weight = w["pointer_gate"].float()
    gate = F.layer_norm(hidden.float(), (width,)) @ gate_weight[:-1] + gate_weight[-1]
    decay = F.softplus(w["pointer_decay"].float()).view(1, 1, POINTER_FEATURES, 1)
    lag = torch.tensor([0.0, 0.0, 1.0, 1.0, 1.0], device=tokens.device).view(1, 1, POINTER_FEATURES, 1)
    query_one = previous_tokens(tokens, docs, 1, -1)
    source_one = previous_tokens(tokens, docs, 1, -2)
    query_two = previous_tokens(tokens, docs, 2, -1)
    source_two = previous_tokens(tokens, docs, 2, -2)
    local, token_of = local_vocabulary(tokens, vocab)
    successor = F.pad(local[:, 1:], (0, 1))
    voted = torch.stack((local, local, successor, successor, successor), dim=1)
    boosts = []
    for start in range(0, size, cfg.pointer_chunk):
        stop = min(start + cfg.pointer_chunk, size)
        t = torch.arange(start, stop, device=tokens.device).view(1, -1, 1)
        s = torch.arange(stop, device=tokens.device).view(1, 1, -1)
        same_doc = docs[:, start:stop, None] == docs[:, None, :stop]
        match_one = (tokens[:, start:stop, None] == tokens[:, None, :stop]) & same_doc & (s < t)
        match_two = match_one & (query_one[:, start:stop, None] == source_one[:, None, :stop])
        match_three = match_two & (query_two[:, start:stop, None] == source_two[:, None, :stop])
        level = match_one.to(torch.int8) + match_two + match_three
        copy = same_doc & (s <= t)
        selected = torch.stack((copy, copy, level == 1, level == 2, level == 3), dim=2)
        distance = (t - s).clamp(min=0).to(torch.float32).unsqueeze(2)
        weight = selected.to(torch.float32) * torch.exp(-decay * (distance - lag).clamp(min=0))
        plane = torch.zeros(batch, stop - start, POINTER_FEATURES, slots, device=tokens.device)
        plane.scatter_add_(-1, voted[:, None, :, :stop].expand(-1, stop - start, -1, -1), weight)
        per_token = (gate[:, start:stop].unsqueeze(-1) * torch.log1p(plane)).sum(dim=2)
        columns = torch.zeros(batch, stop - start, vocab + 1, device=tokens.device)
        columns.scatter_(-1, token_of[:, None, :slots].expand(-1, stop - start, -1), per_token)
        boosts.append(columns[..., :vocab])
    return torch.cat(boosts, dim=1)


def forward_logits(w: dict[str, torch.Tensor], cfg: NessimConfig, tokens: torch.Tensor, real: torch.Tensor | None) -> torch.Tensor:
    """Logits (B, T, V) of tokens (B, T), every program computed from the tokens."""
    eps = cfg.rms_norm_eps
    dtype = w["embed.weight"].dtype
    apps = applications(cfg)
    seg = segments(tokens, cfg.eos_token_id, real)
    lags = torch.arange(CONV - 1, -1, -1, device=tokens.device)
    taps_valid = (seg.pos[..., None] >= lags).to(dtype)
    biases = {slot: w[f"distance_bias.{slot}"] for slot in attention_slots(cfg)} if cfg.distance_bias else {}
    masks = {slot: attention_mask(seg, bias, dtype) for slot, bias in biases.items()}
    shared_mask = None if cfg.distance_bias else attention_mask(seg, None, dtype)

    queries = (w["attn_res_query"] * w["attn_res_norm"]).float()
    base = [F.embedding(tokens.long(), w["embed.weight"]), ngram_vectors(w, cfg, tokens)]
    if has_front(cfg):
        base.append(front_inputs(w, cfg, tokens, seg.docs).to(dtype))
    batch, seq_len = tokens.shape
    capacity = len(base) + len(apps)
    sources = Sources(
        values=base[0].new_empty(batch, seq_len, capacity, cfg.hidden_size),
        normed=torch.empty(batch, seq_len, capacity, cfg.hidden_size, dtype=torch.float32, device=tokens.device),
    )
    n = 0
    for source in base:
        n = add_source(sources, n, source, eps)
    v_first = None
    newest = None
    for index, app in enumerate(apps):
        block = f"blocks.{app.slot}."
        if newest is not None:
            n = add_source(sources, n, newest + w["loop_signal"][app.loop].to(dtype) if app.loop_start else newest, eps)
        h = rms(mix_sources(sources, n, queries[2 * index], None, eps), w[block + "mixer_norm.weight"], eps)
        if is_attention(cfg, app.slot):
            mask = masks[app.slot] if cfg.distance_bias else shared_mask
            out, v_first = attention_mixer(w, cfg, app.slot, h, v_first, mask)
        else:
            out = gdn_mixer(w, cfg, app.slot, h, seg, taps_valid)
        g = rms(mix_sources(sources, n, queries[2 * index + 1], out, eps), w[block + "ffn_norm.weight"], eps)
        newest = out + F.linear(F.silu(F.linear(g, w[block + "ffn.gate.weight"])) * F.linear(g, w[block + "ffn.up.weight"]), w[block + "ffn.down.weight"])
    n = add_source(sources, n, newest, eps)
    x = rms(mix_sources(sources, n, queries[-1], None, eps), w["norm.weight"], eps)
    logits = F.linear(x, w["embed.weight"].to(x.dtype))
    if cfg.copy_pointer:
        logits = logits.float() + pointer_boost(w, cfg, tokens, seg.docs, x)
    return logits


class NessimForCausalLM(PreTrainedModel, GenerationMixin):
    config_class = NessimConfig
    base_model_prefix = "model"
    main_input_name = "input_ids"
    _no_split_modules: list[str] = []

    def __init__(self, config: NessimConfig):
        super().__init__(config)
        self.model = build_network(config)
        self.post_init()

    def _init_weights(self, module):
        pass  # every weight comes from the checkpoint

    def get_input_embeddings(self) -> nn.Embedding:
        return self.model.embed

    def set_input_embeddings(self, value: nn.Embedding) -> None:
        self.model.embed = value

    def get_output_embeddings(self) -> nn.Embedding:
        return self.model.embed  # tied: the output layer reads embed.weight

    def forward(self, input_ids, attention_mask=None, past_key_values=None, use_cache=None, labels=None,
                return_dict=True, **kwargs) -> CausalLMOutputWithPast:
        real = None
        if attention_mask is not None:
            mask = attention_mask.bool()
            left = bool((mask[:, 1:] >= mask[:, :-1]).all())
            if not left and not bool((mask[:, 1:] <= mask[:, :-1]).all()):
                raise ValueError("only left or right padding is supported")
            if left:
                real = mask[:, -input_ids.shape[1]:]
        weights = {**dict(self.model.named_parameters()), **dict(self.model.named_buffers())}
        logits = forward_logits(weights, self.config, input_ids, real)
        loss = None
        if labels is not None:
            loss = F.cross_entropy(logits[:, :-1].flatten(0, 1).float(), labels[:, 1:].flatten(), ignore_index=-100)
        return CausalLMOutputWithPast(loss=loss, logits=logits)

    def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, use_cache=None, **kwargs):
        return {"input_ids": input_ids, "attention_mask": attention_mask}