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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Llama-style decoder-only transformer.
|
| 2 |
+
|
| 3 |
+
RMSNorm, rotary position embeddings, SwiGLU MLP, untied input/output
|
| 4 |
+
embeddings. Deliberately small and dependency-light (just torch) so it runs
|
| 5 |
+
unchanged on the GH200 nodes and on a login-node CPU smoke test.
|
| 6 |
+
|
| 7 |
+
Configs live in configs/*.yaml; ModelConfig mirrors the yaml `model:` block.
|
| 8 |
+
"""
|
| 9 |
+
from dataclasses import dataclass
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
import torch.nn as nn
|
| 13 |
+
import torch.nn.functional as F
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@dataclass
|
| 17 |
+
class ModelConfig:
|
| 18 |
+
vocab_size: int = 65536
|
| 19 |
+
dim: int = 2048
|
| 20 |
+
n_layers: int = 16
|
| 21 |
+
n_heads: int = 16
|
| 22 |
+
n_kv_heads: int | None = None # None -> = n_heads (no GQA)
|
| 23 |
+
ffn_dim: int = 5632
|
| 24 |
+
max_seq_len: int = 2048
|
| 25 |
+
rope_theta: float = 10000.0
|
| 26 |
+
norm_eps: float = 1e-5
|
| 27 |
+
|
| 28 |
+
@property
|
| 29 |
+
def kv_heads(self) -> int:
|
| 30 |
+
return self.n_kv_heads or self.n_heads
|
| 31 |
+
|
| 32 |
+
@property
|
| 33 |
+
def head_dim(self) -> int:
|
| 34 |
+
return self.dim // self.n_heads
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class RMSNorm(nn.Module):
|
| 38 |
+
def __init__(self, dim: int, eps: float):
|
| 39 |
+
super().__init__()
|
| 40 |
+
self.eps = eps
|
| 41 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 42 |
+
|
| 43 |
+
def forward(self, x):
|
| 44 |
+
dt = x.dtype
|
| 45 |
+
x = x.float()
|
| 46 |
+
x = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
|
| 47 |
+
return (x * self.weight.float()).to(dt)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _rope_cache(seq_len: int, head_dim: int, theta: float, device, dtype):
|
| 51 |
+
inv = 1.0 / (theta ** (torch.arange(0, head_dim, 2, device=device).float() / head_dim))
|
| 52 |
+
t = torch.arange(seq_len, device=device).float()
|
| 53 |
+
freqs = torch.outer(t, inv) # (T, head_dim/2)
|
| 54 |
+
return torch.cos(freqs).to(dtype), torch.sin(freqs).to(dtype)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _apply_rope(x, cos, sin):
|
| 58 |
+
# x: (B, H, T, D). split even/odd halves (rotate-half convention)
|
| 59 |
+
x1, x2 = x[..., ::2], x[..., 1::2]
|
| 60 |
+
cos = cos[None, None, :, :]
|
| 61 |
+
sin = sin[None, None, :, :]
|
| 62 |
+
o1 = x1 * cos - x2 * sin
|
| 63 |
+
o2 = x1 * sin + x2 * cos
|
| 64 |
+
out = torch.empty_like(x)
|
| 65 |
+
out[..., ::2] = o1
|
| 66 |
+
out[..., 1::2] = o2
|
| 67 |
+
return out
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class Attention(nn.Module):
|
| 71 |
+
def __init__(self, cfg: ModelConfig):
|
| 72 |
+
super().__init__()
|
| 73 |
+
self.n_heads = cfg.n_heads
|
| 74 |
+
self.kv_heads = cfg.kv_heads
|
| 75 |
+
self.head_dim = cfg.head_dim
|
| 76 |
+
self.wq = nn.Linear(cfg.dim, cfg.n_heads * cfg.head_dim, bias=False)
|
| 77 |
+
self.wk = nn.Linear(cfg.dim, cfg.kv_heads * cfg.head_dim, bias=False)
|
| 78 |
+
self.wv = nn.Linear(cfg.dim, cfg.kv_heads * cfg.head_dim, bias=False)
|
| 79 |
+
self.wo = nn.Linear(cfg.n_heads * cfg.head_dim, cfg.dim, bias=False)
|
| 80 |
+
|
| 81 |
+
def forward(self, x, cos, sin):
|
| 82 |
+
B, T, _ = x.shape
|
| 83 |
+
q = self.wq(x).view(B, T, self.n_heads, self.head_dim).transpose(1, 2)
|
| 84 |
+
k = self.wk(x).view(B, T, self.kv_heads, self.head_dim).transpose(1, 2)
|
| 85 |
+
v = self.wv(x).view(B, T, self.kv_heads, self.head_dim).transpose(1, 2)
|
| 86 |
+
q = _apply_rope(q, cos, sin)
|
| 87 |
+
k = _apply_rope(k, cos, sin)
|
| 88 |
+
if self.kv_heads != self.n_heads:
|
| 89 |
+
rep = self.n_heads // self.kv_heads
|
| 90 |
+
k = k.repeat_interleave(rep, dim=1)
|
| 91 |
+
v = v.repeat_interleave(rep, dim=1)
|
| 92 |
+
out = F.scaled_dot_product_attention(q, k, v, is_causal=True)
|
| 93 |
+
out = out.transpose(1, 2).contiguous().view(B, T, -1)
|
| 94 |
+
return self.wo(out)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class SwiGLU(nn.Module):
|
| 98 |
+
def __init__(self, cfg: ModelConfig):
|
| 99 |
+
super().__init__()
|
| 100 |
+
self.w1 = nn.Linear(cfg.dim, cfg.ffn_dim, bias=False) # gate
|
| 101 |
+
self.w3 = nn.Linear(cfg.dim, cfg.ffn_dim, bias=False) # up
|
| 102 |
+
self.w2 = nn.Linear(cfg.ffn_dim, cfg.dim, bias=False) # down
|
| 103 |
+
|
| 104 |
+
def forward(self, x):
|
| 105 |
+
return self.w2(F.silu(self.w1(x)) * self.w3(x))
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
class Block(nn.Module):
|
| 109 |
+
def __init__(self, cfg: ModelConfig):
|
| 110 |
+
super().__init__()
|
| 111 |
+
self.attn_norm = RMSNorm(cfg.dim, cfg.norm_eps)
|
| 112 |
+
self.attn = Attention(cfg)
|
| 113 |
+
self.ffn_norm = RMSNorm(cfg.dim, cfg.norm_eps)
|
| 114 |
+
self.ffn = SwiGLU(cfg)
|
| 115 |
+
|
| 116 |
+
def forward(self, x, cos, sin):
|
| 117 |
+
x = x + self.attn(self.attn_norm(x), cos, sin)
|
| 118 |
+
x = x + self.ffn(self.ffn_norm(x))
|
| 119 |
+
return x
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class Transformer(nn.Module):
|
| 123 |
+
def __init__(self, cfg: ModelConfig):
|
| 124 |
+
super().__init__()
|
| 125 |
+
self.cfg = cfg
|
| 126 |
+
self.tok_emb = nn.Embedding(cfg.vocab_size, cfg.dim)
|
| 127 |
+
self.layers = nn.ModuleList(Block(cfg) for _ in range(cfg.n_layers))
|
| 128 |
+
self.norm = RMSNorm(cfg.dim, cfg.norm_eps)
|
| 129 |
+
self.lm_head = nn.Linear(cfg.dim, cfg.vocab_size, bias=False) # untied
|
| 130 |
+
self._rope = None
|
| 131 |
+
self.apply(self._init)
|
| 132 |
+
# scale residual-projection inits by depth (GPT-2/Llama convention)
|
| 133 |
+
for name, p in self.named_parameters():
|
| 134 |
+
if name.endswith("wo.weight") or name.endswith("w2.weight"):
|
| 135 |
+
nn.init.normal_(p, mean=0.0, std=0.02 / (2 * cfg.n_layers) ** 0.5)
|
| 136 |
+
|
| 137 |
+
def _init(self, m):
|
| 138 |
+
if isinstance(m, nn.Linear):
|
| 139 |
+
nn.init.normal_(m.weight, mean=0.0, std=0.02)
|
| 140 |
+
elif isinstance(m, nn.Embedding):
|
| 141 |
+
nn.init.normal_(m.weight, mean=0.0, std=0.02)
|
| 142 |
+
|
| 143 |
+
def _rope_for(self, T, device, dtype):
|
| 144 |
+
if self._rope is None or self._rope[0].shape[0] < T or self._rope[0].device != device:
|
| 145 |
+
self._rope = _rope_cache(self.cfg.max_seq_len, self.cfg.head_dim,
|
| 146 |
+
self.cfg.rope_theta, device, dtype)
|
| 147 |
+
cos, sin = self._rope
|
| 148 |
+
return cos[:T], sin[:T]
|
| 149 |
+
|
| 150 |
+
def forward(self, idx, targets=None):
|
| 151 |
+
B, T = idx.shape
|
| 152 |
+
x = self.tok_emb(idx)
|
| 153 |
+
cos, sin = self._rope_for(T, idx.device, x.dtype)
|
| 154 |
+
for layer in self.layers:
|
| 155 |
+
x = layer(x, cos, sin)
|
| 156 |
+
x = self.norm(x)
|
| 157 |
+
if targets is None:
|
| 158 |
+
return self.lm_head(x[:, -1:, :])
|
| 159 |
+
logits = self.lm_head(x)
|
| 160 |
+
loss = F.cross_entropy(logits.view(-1, logits.size(-1)),
|
| 161 |
+
targets.reshape(-1), ignore_index=-100)
|
| 162 |
+
return logits, loss
|
| 163 |
+
|
| 164 |
+
@torch.no_grad()
|
| 165 |
+
def layer_reps(self, idx):
|
| 166 |
+
"""Per-layer hidden states for representation analysis (MEXA).
|
| 167 |
+
|
| 168 |
+
Returns a tensor (n_layers+1, B, T, dim): index 0 is the embedding
|
| 169 |
+
output, index i>=1 is the output of block i. Causal attention means
|
| 170 |
+
right-padding never contaminates real positions, so callers can pool
|
| 171 |
+
over a length mask safely.
|
| 172 |
+
"""
|
| 173 |
+
B, T = idx.shape
|
| 174 |
+
x = self.tok_emb(idx)
|
| 175 |
+
cos, sin = self._rope_for(T, idx.device, x.dtype)
|
| 176 |
+
reps = [x]
|
| 177 |
+
for layer in self.layers:
|
| 178 |
+
x = layer(x, cos, sin)
|
| 179 |
+
reps.append(x)
|
| 180 |
+
return torch.stack(reps, dim=0)
|
| 181 |
+
|
| 182 |
+
def num_params(self, embedding: bool = True) -> int:
|
| 183 |
+
n = sum(p.numel() for p in self.parameters())
|
| 184 |
+
if not embedding:
|
| 185 |
+
n -= self.tok_emb.weight.numel() + self.lm_head.weight.numel()
|
| 186 |
+
return n
|