Redhanuman's picture
Pocket Storyteller: 4.6 MB story model, browser demo, weights and training code
ebf8f81 verified
Raw History Blame Contribute Delete
3.6 kB
"""A tiny Llama-style transformer: RMSNorm, rotary positions, SwiGLU, tied embeddings."""
import math, torch, torch.nn as nn, torch.nn.functional as F
from dataclasses import dataclass
@dataclass
class Config:
vocab: int = 4096
dim: int = 256
layers: int = 6
heads: int = 8
hidden: int = 688
ctx: int = 256
class RMSNorm(nn.Module):
def __init__(self, d):
super().__init__()
self.w = nn.Parameter(torch.ones(d))
def forward(self, x):
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + 1e-5) * self.w
def rope(x, rot):
# rotary positions: turn each pair of numbers by an angle that depends on the position.
# One complex multiply does it: (x1 + i*x2) * (cos + i*sin).
xc = torch.view_as_complex(x.float().reshape(*x.shape[:-1], -1, 2))
return torch.view_as_real(xc * rot).flatten(-2)
class Block(nn.Module):
def __init__(self, c):
super().__init__()
self.h = c.heads
self.n1, self.n2 = RMSNorm(c.dim), RMSNorm(c.dim)
self.wq = nn.Linear(c.dim, c.dim, bias=False)
self.wk = nn.Linear(c.dim, c.dim, bias=False)
self.wv = nn.Linear(c.dim, c.dim, bias=False)
self.wo = nn.Linear(c.dim, c.dim, bias=False)
self.w1 = nn.Linear(c.dim, c.hidden, bias=False)
self.w3 = nn.Linear(c.dim, c.hidden, bias=False)
self.w2 = nn.Linear(c.hidden, c.dim, bias=False)
def forward(self, x, rot):
B, T, D = x.shape
h = self.n1(x)
q = self.wq(h).view(B, T, self.h, -1).transpose(1, 2)
k = self.wk(h).view(B, T, self.h, -1).transpose(1, 2)
v = self.wv(h).view(B, T, self.h, -1).transpose(1, 2)
q, k = rope(q, rot), rope(k, rot)
a = F.scaled_dot_product_attention(q, k, v, is_causal=True)
x = x + self.wo(a.transpose(1, 2).reshape(B, T, D))
h = self.n2(x)
return x + self.w2(F.silu(self.w1(h)) * self.w3(h))
class Storyteller(nn.Module):
def __init__(self, c: Config):
super().__init__()
self.c = c
self.emb = nn.Embedding(c.vocab, c.dim)
self.blocks = nn.ModuleList(Block(c) for _ in range(c.layers))
self.norm = RMSNorm(c.dim)
hd = c.dim // c.heads
inv = 1.0 / (10000 ** (torch.arange(0, hd, 2).float() / hd))
f = torch.outer(torch.arange(c.ctx).float(), inv)
self.register_buffer("rot", torch.polar(torch.ones_like(f), f), persistent=False) # cos + i*sin
self.apply(self._init)
for n, p in self.named_parameters():
if n.endswith("wo.weight") or n.endswith("w2.weight"):
nn.init.normal_(p, std=0.02 / math.sqrt(2 * c.layers))
def _init(self, m):
if isinstance(m, (nn.Linear, nn.Embedding)):
nn.init.normal_(m.weight, std=0.02)
def forward(self, idx, targets=None):
T = idx.shape[1]
x = self.emb(idx)
for b in self.blocks:
x = b(x, self.rot[:T])
logits = self.norm(x) @ self.emb.weight.T # tied weights
if targets is None:
return logits
return F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))
@torch.no_grad()
def generate(self, idx, n, temp=0.8, top_k=40):
for _ in range(n):
logits = self(idx[:, -self.c.ctx:])[:, -1] / temp
v, _ = torch.topk(logits, top_k)
logits[logits < v[:, -1:]] = -1e9
nxt = torch.multinomial(F.softmax(logits, -1), 1)
idx = torch.cat([idx, nxt], 1)
if nxt.item() == 0:
break
return idx