TinyStories-24m: 24.59M BPE GPT trained from scratch on TinyStories (val ppl 8.76, coherent)
c6c9cdf verified | """TinyStoriesGPT — 24.59M-param BPE GPT trained on roneneldan/TinyStories. | |
| Architecture: weight-tied decoder-only GPT, RMSNorm, fused qkv, GELU FFN. | |
| Not a transformers model — load with this class + safetensors. | |
| """ | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| class RMSNorm(nn.Module): | |
| def __init__(self, d): | |
| super().__init__() | |
| self.w = nn.Parameter(torch.ones(d)) | |
| def forward(self, x): | |
| return self.w * x * torch.rsqrt(x.float().pow(2).mean(-1, keepdim=True) + 1e-6) | |
| class Block(nn.Module): | |
| def __init__(self, d, h, ffn): | |
| super().__init__() | |
| self.ln1 = RMSNorm(d) | |
| self.ln2 = RMSNorm(d) | |
| self.qkv = nn.Linear(d, 3*d, bias=False) | |
| self.proj = nn.Linear(d, d, bias=False) | |
| self.fc1 = nn.Linear(d, ffn, bias=False) | |
| self.fc2 = nn.Linear(ffn, d, bias=False) | |
| self.h, self.d = h, d | |
| def forward(self, x): | |
| B, T, D = x.shape | |
| h = self.ln1(x) | |
| qkv = self.qkv(h).view(B, T, 3, self.h, D//self.h).transpose(2,1) | |
| q, k, v = qkv[:,0], qkv[:,1], qkv[:,2] | |
| q, k, v = q.transpose(1,2), k.transpose(1,2), v.transpose(1,2) | |
| att = F.scaled_dot_product_attention(q, k, v, is_causal=True) | |
| att = att.transpose(1,2).reshape(B, T, D) | |
| x = x + self.proj(att) | |
| x = x + self.fc2(F.gelu(self.fc1(self.ln2(x)))) | |
| return x | |
| class TinyStoriesGPT(nn.Module): | |
| def __init__(self, vocab_size=8192, d=384, n_layers=12, n_heads=8, ffn=1536, seq=512): | |
| super().__init__() | |
| self.tok = nn.Embedding(vocab_size, d) | |
| self.pos = nn.Embedding(seq, d) | |
| self.blocks = nn.ModuleList([Block(d, n_heads, ffn) for _ in range(n_layers)]) | |
| self.ln_f = RMSNorm(d) | |
| self.vocab_size = vocab_size | |
| def forward(self, x, targets=None): | |
| b, t = x.shape | |
| h = self.tok(x) + self.pos(torch.arange(t, device=x.device)) | |
| for blk in self.blocks: | |
| h = blk(h) | |
| h = self.ln_f(h) | |
| logits = h @ self.tok.weight.t() | |
| if targets is not None: | |
| return F.cross_entropy(logits.float().view(-1, self.vocab_size), targets.view(-1)) | |
| return logits | |
| def from_pretrained(cls, path, device="cpu"): | |
| import json | |
| from safetensors.torch import load_file | |
| cfg = json.load(open(f"{path}/config.json")) | |
| model = cls(vocab_size=cfg["vocab_size"], d=cfg["D"], n_layers=cfg["L"], | |
| n_heads=cfg["H"], ffn=cfg["FFN"], seq=cfg["max_position_embeddings"]) | |
| sd = load_file(f"{path}/model.safetensors") | |
| model.load_state_dict(sd) | |
| model = model.to(device).eval() | |
| return model | |