tinystories-50m / load_model.py
Compactbot's picture
Add self-contained loader + TinyStoriesGPT class
8cacb5e verified
Raw
History Blame Contribute Delete
3.29 kB
"""Load Compactbot/tinystories-50m.
Custom small GPT (not a transformers model). Weights are plain state-dict
tensors in model.safetensors. Tokenizer is a HuggingFace `tokenizers` BPE
file (tokenizer.json).
from load_model import TinyStoriesGPT, load
model, tok = load()
ids = tok.encode("Once upon a time,")
...
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from tokenizers import Tokenizer
D, L, H, FFN, VOCAB, SEQ = 512, 16, 8, 2048, 8192, 512
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):
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, Dd = x.shape
h = self.ln1(x)
qkv = self.qkv(h).view(B, T, 3, self.h, Dd // 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, Dd)
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):
super().__init__()
self.tok = nn.Embedding(VOCAB, D)
self.pos = nn.Embedding(SEQ, D)
self.blocks = nn.ModuleList([Block(D, H) for _ in range(L)])
self.ln_f = RMSNorm(D)
self.lm_head = self.tok # weight-tied
def forward(self, idx, targets=None):
B, T = idx.shape
x = self.tok(idx) + self.pos(torch.arange(T, device=idx.device))
for b in self.blocks:
x = b(x)
x = self.ln_f(x)
logits = self.lm_head(x)
loss = None
if targets is not None:
loss = F.cross_entropy(logits.view(-1, VOCAB), targets.view(-1))
return logits, loss
def generate(self, idx, max_new, temp=0.8, top_k=40):
for _ in range(max_new):
logits, _ = self(idx)
logits = logits[:, -1] / temp
if top_k:
v, _ = torch.topk(logits, top_k)
logits[logits < v[:, [-1]]] = float("-inf")
nxt = torch.multinomial(F.softmax(logits, -1), 1)
idx = torch.cat([idx, nxt], 1)
return idx
def load(weights="model.safetensors", tokenizer="tokenizer.json", device="cuda"):
from safetensors.torch import load_file
m = TinyStoriesGPT().to(device)
sd = load_file(weights)
m.load_state_dict(sd)
m.eval()
tok = Tokenizer.from_file(tokenizer)
return m, tok
if __name__ == "__main__":
m, tok = load()
ids = tok.encode("Once upon a time,")
ids = torch.tensor([ids], device="cuda")
out = m.generate(ids, 100, temp=0.8, top_k=40)
print(tok.decode(out[0].tolist(), skip_special_tokens=True))