File size: 18,979 Bytes
7dd3211
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""MaxGPT-Ultra - a modern decoder-only transformer.

Design (Llama / Qwen / SmolLM2 lineage), every choice documented in TECHNIQUES.md:
  - RoPE rotary positions (no learned position embeddings)
  - RMSNorm, pre-norm, no biases anywhere
  - SwiGLU feed-forward
  - Grouped-query attention (GQA)
  - QK-norm (RMSNorm on per-head Q/K) for high-LR stability
  - Tied input/output embeddings
  - z-loss available in the loss for logit-scale control

Attention uses torch's scaled_dot_product_attention, which dispatches to
FlashAttention on supported GPUs (and a math fallback on CPU).
"""
from __future__ import annotations

import math

import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.checkpoint import checkpoint as grad_checkpoint

from .config import ModelConfig


# --------------------------------------------------------------------------- #
# Normalization
# --------------------------------------------------------------------------- #
class RMSNorm(nn.Module):
    """Root-mean-square norm: rescale by RMS over the feature dim, then a learned
    per-feature gain. No mean-centering and no bias, so it's cheaper than LayerNorm
    and empirically just as stable. Computed in fp32 for numerical safety."""

    def __init__(self, dim: int, eps: float = 1e-5):
        super().__init__()
        self.eps = eps
        self.weight = nn.Parameter(torch.ones(dim))

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        dtype = x.dtype
        x = x.float()
        x = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
        return x.to(dtype) * self.weight


# --------------------------------------------------------------------------- #
# Rotary position embeddings (RoPE)
# --------------------------------------------------------------------------- #
def precompute_rope(head_dim: int, seq_len: int, theta: float,
                    dtype: torch.dtype = torch.float32):
    """Build the (seq_len, head_dim) cos/sin tables once. Rotating Q/K by these
    angles injects *relative* position into the dot product, which generalizes
    better than absolute learned positions."""
    inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2).float() / head_dim))  # (hd/2,)
    pos = torch.arange(seq_len).float()                                            # (T,)
    freqs = torch.outer(pos, inv_freq)                                             # (T, hd/2)
    emb = torch.cat((freqs, freqs), dim=-1)                                        # (T, hd)
    return emb.cos().to(dtype), emb.sin().to(dtype)


def rotate_half(x: torch.Tensor) -> torch.Tensor:
    x1, x2 = x.chunk(2, dim=-1)
    return torch.cat((-x2, x1), dim=-1)


def apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
    # x: (B, n_heads, T, head_dim); cos/sin: (T, head_dim)
    cos = cos[None, None, :, :]
    sin = sin[None, None, :, :]
    return (x * cos) + (rotate_half(x) * sin)


def repeat_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor:
    """Expand (B, n_kv, T, hd) -> (B, n_kv*n_rep, T, hd) so each KV head is shared
    by n_rep query heads (the GQA trick: fewer KV heads = smaller KV cache + less
    memory bandwidth, at almost no quality cost)."""
    if n_rep == 1:
        return x
    B, n_kv, T, hd = x.shape
    return (x[:, :, None, :, :]
            .expand(B, n_kv, n_rep, T, hd)
            .reshape(B, n_kv * n_rep, T, hd))


# --------------------------------------------------------------------------- #
# Attention (GQA + QK-norm + RoPE)
# --------------------------------------------------------------------------- #
class Attention(nn.Module):
    def __init__(self, cfg: ModelConfig, layer_idx: int = 0):
        super().__init__()
        self.n_heads = cfg.n_heads
        self.n_kv_heads = cfg.n_kv_heads
        self.n_rep = cfg.n_heads // cfg.n_kv_heads
        self.head_dim = cfg.head_dim

        self.q_proj = nn.Linear(cfg.d_model, cfg.n_heads * self.head_dim, bias=False)
        self.k_proj = nn.Linear(cfg.d_model, cfg.n_kv_heads * self.head_dim, bias=False)
        self.v_proj = nn.Linear(cfg.d_model, cfg.n_kv_heads * self.head_dim, bias=False)
        self.o_proj = nn.Linear(cfg.n_heads * self.head_dim, cfg.d_model, bias=False)

        self.qk_norm = cfg.qk_norm
        if cfg.qk_norm:
            self.q_norm = RMSNorm(self.head_dim, cfg.rms_eps)
            self.k_norm = RMSNorm(self.head_dim, cfg.rms_eps)

        # Gated attention: one sigmoid gate per head, computed from the block input, multiplies the
        # attention output. 2*sigmoid(0) = 1, and the projection is zero-initialized, so the model
        # starts exactly as an ungated one. Adds sparsity, removes attention sinks, stabilizes
        # training (Qwen, NeurIPS 2025). Cost: one d_model x n_heads matmul per layer.
        self.attn_gate = cfg.attn_gate
        if cfg.attn_gate:
            self.attn_gate_proj = nn.Linear(cfg.d_model, cfg.n_heads, bias=False)
        # Value residual: layers after the first mix the FIRST layer's values into their own,
        # V = s * (a1*V_local + a2*V_1) / sqrt(a1^2 + a2^2), learned (s, a1, a2) starting at (1, 1, 0)
        # so it is an identity at init. Counters the value-stream degradation of deep stacks.
        self.value_residual = cfg.value_residual and layer_idx > 0
        if self.value_residual:
            self.vr_scale = nn.Parameter(torch.ones(()))
            self.vr_alpha = nn.Parameter(torch.tensor([1.0, 0.0]))

    def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor,
                past=None, use_cache: bool = False, v1: torch.Tensor | None = None,
                mask: torch.Tensor | None = None):
        """Returns (out, new_kv or None, v_local). v_local is this layer's own values (pre-mix),
        which the model hands to later layers as v1 when value_residual is on. `mask` (B, 1, T, T)
        bool, True = may attend, replaces plain causal attention: the document mask for packed
        SFT batches (see MaxGPTUltra.doc_mask)."""
        B, T, _ = x.shape
        q = self.q_proj(x).view(B, T, self.n_heads, self.head_dim)
        k = self.k_proj(x).view(B, T, self.n_kv_heads, self.head_dim)
        v = self.v_proj(x).view(B, T, self.n_kv_heads, self.head_dim)

        # QK-norm: normalize each head's Q and K (over head_dim) before RoPE. Keeps
        # the attention logits well-scaled so we can train at a higher learning rate.
        if self.qk_norm:
            q = self.q_norm(q)
            k = self.k_norm(k)

        q = q.transpose(1, 2)  # (B, n_heads,    T, hd)
        k = k.transpose(1, 2)  # (B, n_kv_heads, T, hd)
        v = v.transpose(1, 2)
        v_local = v
        if self.value_residual and v1 is not None:
            a1, a2 = self.vr_alpha[0], self.vr_alpha[1]
            v = self.vr_scale * (a1 * v + a2 * v1) * torch.rsqrt(a1 * a1 + a2 * a2)

        # RoPE uses absolute positions; cos/sin are pre-sliced to this chunk's positions (offset
        # past the cache during incremental decode), so new tokens rotate at the right angle.
        q = apply_rope(q, cos, sin)
        k = apply_rope(k, cos, sin)

        if past is not None:                       # prepend cached keys/values (post-RoPE, pre-GQA-repeat)
            pk, pv = past
            k = torch.cat([pk, k], dim=2)
            v = torch.cat([pv, v], dim=2)
        new_kv = (k, v) if use_cache else None

        kr = repeat_kv(k, self.n_rep)
        vr = repeat_kv(v, self.n_rep)
        if past is None and mask is not None:
            out = F.scaled_dot_product_attention(q, kr, vr, attn_mask=mask)   # causal AND same document
        elif past is None:
            out = F.scaled_dot_product_attention(q, kr, vr, is_causal=True)   # prefill / training
        elif q.size(2) == 1:
            out = F.scaled_dot_product_attention(q, kr, vr)                   # 1 new token attends to all cached
        else:
            Tq, Tk = q.size(2), kr.size(2)                                    # several new tokens: causal among them
            mask = torch.ones(Tq, Tk, dtype=torch.bool, device=q.device).tril(diagonal=Tk - Tq)
            out = F.scaled_dot_product_attention(q, kr, vr, attn_mask=mask)
        if self.attn_gate:
            gate = 2.0 * torch.sigmoid(self.attn_gate_proj(x))            # (B, T, n_heads)
            out = out * gate.transpose(1, 2).unsqueeze(-1).to(out.dtype)
        out = out.transpose(1, 2).contiguous().view(B, T, self.n_heads * self.head_dim)
        out = self.o_proj(out)
        return out, new_kv, v_local


# --------------------------------------------------------------------------- #
# SwiGLU feed-forward
# --------------------------------------------------------------------------- #
class SwiGLU(nn.Module):
    """FFN(x) = down( silu(gate(x)) * up(x) ). The gated activation outperforms a
    plain GELU MLP at the same parameter budget; hidden width is ~8/3 * d_model so
    the three projections roughly match a 4x GELU MLP's parameter count."""

    def __init__(self, cfg: ModelConfig):
        super().__init__()
        self.gate_proj = nn.Linear(cfg.d_model, cfg.mlp_hidden, bias=False)
        self.up_proj = nn.Linear(cfg.d_model, cfg.mlp_hidden, bias=False)
        self.down_proj = nn.Linear(cfg.mlp_hidden, cfg.d_model, bias=False)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))


# --------------------------------------------------------------------------- #
# Transformer block (pre-norm)
# --------------------------------------------------------------------------- #
class Block(nn.Module):
    def __init__(self, cfg: ModelConfig, layer_idx: int = 0):
        super().__init__()
        self.attn_norm = RMSNorm(cfg.d_model, cfg.rms_eps)
        self.attn = Attention(cfg, layer_idx)
        self.mlp_norm = RMSNorm(cfg.d_model, cfg.rms_eps)
        self.mlp = SwiGLU(cfg)
        # "LayerNorm scaling": deeper blocks see a 1/sqrt(depth)-scaled normalized input, which
        # keeps late layers from being drowned by the growing residual stream (IMU-1, 2026).
        self.norm_scale = (1.0 / math.sqrt(layer_idx + 1)) if cfg.norm_scaling else 1.0

    def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor,
                past=None, use_cache: bool = False, v1: torch.Tensor | None = None,
                mask: torch.Tensor | None = None):
        """Pre-norm residuals: normalize the input to each sublayer, add the result back.
        Returns (x, kv or None, v_local)."""
        h = self.attn_norm(x)
        if self.norm_scale != 1.0:
            h = h * self.norm_scale
        a, kv, v_local = self.attn(h, cos, sin, past, use_cache, v1, mask)
        x = x + a
        h = self.mlp_norm(x)
        if self.norm_scale != 1.0:
            h = h * self.norm_scale
        x = x + self.mlp(h)
        return x, kv, v_local


# --------------------------------------------------------------------------- #
# Full model
# --------------------------------------------------------------------------- #
class MaxGPTUltra(nn.Module):
    def __init__(self, cfg: ModelConfig):
        super().__init__()
        self.cfg = cfg
        self.grad_checkpointing = False   # trainer sets True to trade compute for memory (fits the 1B on 12GB)
        # Document (block-diagonal) attention for packed batches: with doc_mask on, a token may only
        # attend to earlier tokens of ITS OWN document, documents being the spans separated by
        # doc_sep_id (<|endoftext|>, which stays with the document it ends). Without it, packed SFT
        # conversations attend into each other (measured up to +7% GSM8K / +4% HumanEval for the
        # fix, docs/research_2026-09-22.md 3.1). RoPE is relative, so no position reset is needed:
        # a packed conversation gets exactly the logits it would get alone (scripts/test_sft.py [5]).
        self.doc_mask = False
        self.doc_sep_id: int | None = None
        self.tok_emb = nn.Embedding(cfg.vocab_size, cfg.d_model)
        self.blocks = nn.ModuleList([Block(cfg, i) for i in range(cfg.n_layers)])
        self.norm = RMSNorm(cfg.d_model, cfg.rms_eps)
        self.lm_head = nn.Linear(cfg.d_model, cfg.vocab_size, bias=False)
        if cfg.tie_embeddings:
            self.lm_head.weight = self.tok_emb.weight  # weight tying

        cos, sin = precompute_rope(cfg.head_dim, cfg.seq_len, cfg.rope_theta)
        self.register_buffer("rope_cos", cos, persistent=False)
        self.register_buffer("rope_sin", sin, persistent=False)

        self.apply(self._init_weights)
        # Deep-net residual init: scale the *output* projection of each sublayer by
        # 1/sqrt(2 * n_layers) so the residual stream doesn't blow up with depth.
        for name, p in self.named_parameters():
            if name.endswith("o_proj.weight") or name.endswith("down_proj.weight"):
                nn.init.normal_(p, mean=0.0, std=cfg.init_std / math.sqrt(2 * cfg.n_layers))
            elif name.endswith("attn_gate_proj.weight"):
                nn.init.zeros_(p)            # gate = 2*sigmoid(0) = 1: identical to no gate at init

    def _init_weights(self, module: nn.Module) -> None:
        if isinstance(module, nn.Linear):
            nn.init.normal_(module.weight, mean=0.0, std=self.cfg.init_std)
            if module.bias is not None:
                nn.init.zeros_(module.bias)
        elif isinstance(module, nn.Embedding):
            nn.init.normal_(module.weight, mean=0.0, std=self.cfg.init_std)

    def document_mask(self, idx: torch.Tensor) -> torch.Tensor:
        """(B, 1, T, T) bool: causal AND same document, documents split at doc_sep_id (the separator
        belongs to the document it ends, so the token after it starts a new one)."""
        assert self.doc_sep_id is not None, "doc_mask needs doc_sep_id (the tokenizer's eos_id)"
        sep = (idx == self.doc_sep_id).long()
        seg = torch.cumsum(sep, dim=1) - sep                        # (B, T) document index per token
        same = seg[:, :, None] == seg[:, None, :]                   # (B, T, T)
        causal = torch.ones(idx.size(1), idx.size(1), dtype=torch.bool, device=idx.device).tril()
        return (same & causal)[:, None, :, :]

    def forward(self, idx: torch.Tensor, targets: torch.Tensor | None = None,
                z_loss_weight: float = 0.0, past=None, use_cache: bool = False):
        B, T = idx.shape
        past_len = past[0][0].size(2) if past is not None else 0   # cached key length (incremental decode)
        assert past_len + T <= self.cfg.seq_len, \
            f"sequence length {past_len + T} exceeds seq_len {self.cfg.seq_len}"

        x = self.tok_emb(idx)
        cos = self.rope_cos[past_len:past_len + T].to(x.dtype)     # positions offset past the cache
        sin = self.rope_sin[past_len:past_len + T].to(x.dtype)
        mask = self.document_mask(idx) if (self.doc_mask and past is None and not use_cache) else None
        new_caches = [] if use_cache else None
        v1 = None                                                   # layer 1's values (value_residual)
        for i, block in enumerate(self.blocks):
            if self.grad_checkpointing and self.training:
                x, _, v_loc = grad_checkpoint(block, x, cos, sin, None, False, v1, mask, use_reentrant=False)
            else:
                x, kv, v_loc = block(x, cos, sin, (past[i] if past is not None else None), use_cache, v1, mask)
                if use_cache:
                    new_caches.append(kv)
            if i == 0 and self.cfg.value_residual:
                v1 = v_loc
        x = self.norm(x)

        # incremental-decode path: just logits + the updated KV cache (generation needs no loss)
        if use_cache:
            return self.lm_head(x), new_caches

        # --- chunked loss (training, opt-in via self.loss_chunk) ---------------------------
        # Compute CE (+ z-loss) over slices of positions, each slice checkpointed so its
        # [chunk, vocab] logits are recomputed in backward instead of retained. The full
        # [B*T, vocab] logits tensor (the single biggest VRAM block, ~GBs at 49k vocab) never
        # materializes, which frees room for a larger micro_batch. Numerically identical to the
        # full path below (sum the per-token loss, divide by the token count). Returns no logits
        # (every targets-given caller discards them); targets=None still returns full logits.
        chunk = getattr(self, "loss_chunk", 0)
        if targets is not None and chunk:
            xf = x.reshape(-1, x.size(-1))
            tf = targets.reshape(-1)
            zw = z_loss_weight

            def _chunk_loss(xc, tc):
                lc = self.lm_head(xc).float()
                ce = F.cross_entropy(lc, tc, ignore_index=-100, reduction="sum")
                z = ((torch.logsumexp(lc, dim=-1).pow(2) * (tc != -100).float()).sum()
                     if zw > 0.0 else lc.new_zeros(()))
                return ce, z

            ce_sum, z_sum, n_tok = xf.new_zeros(()), xf.new_zeros(()), xf.new_zeros(())
            for i in range(0, xf.size(0), chunk):
                xc, tc = xf[i:i + chunk], tf[i:i + chunk]
                ce, z = (grad_checkpoint(_chunk_loss, xc, tc, use_reentrant=False)
                         if self.training else _chunk_loss(xc, tc))
                ce_sum = ce_sum + ce
                z_sum = z_sum + z
                n_tok = n_tok + (tc != -100).sum()
            denom = n_tok.clamp(min=1)
            loss = ce_sum / denom
            if zw > 0.0:
                loss = loss + zw * (z_sum / denom)
            return None, loss
        # ------------------------------------------------------------------------------------

        logits = self.lm_head(x)

        loss = None
        if targets is not None:
            logits_flat = logits.view(-1, logits.size(-1)).float()  # fp32 for the softmax
            targets_flat = targets.view(-1)
            if (targets_flat != -100).any():
                loss = F.cross_entropy(logits_flat, targets_flat, ignore_index=-100)
            else:
                loss = logits_flat.sum() * 0.0   # batch had no supervised tokens (SFT masking edge case)
            if z_loss_weight > 0.0:
                # z-loss penalizes large logsumexp, keeping logits from drifting huge
                lse = torch.logsumexp(logits_flat, dim=-1)
                keep = targets_flat != -100
                z = (lse[keep].pow(2).mean() if keep.any() else lse.pow(2).mean())
                loss = loss + z_loss_weight * z
        return logits, loss

    @torch.no_grad()
    def num_params(self, non_embedding: bool = False) -> int:
        n = sum(p.numel() for p in self.parameters())  # tied weights counted once
        if non_embedding:
            n -= self.tok_emb.weight.numel()
            if self.lm_head.weight is not self.tok_emb.weight:
                n -= self.lm_head.weight.numel()
        return n