Text Generation
Safetensors
PyTorch
English
tiny
from-scratch
chat
Sugarcane-10M / model.py
Jainam59's picture
Upload 8 files
aaeed9c verified
Raw History Blame Contribute Delete
5.45 kB
"""Sugarcane: a small decoder-only transformer written from scratch.
Architecture: token embedding -> N x [RMSNorm -> causal self-attention (RoPE)
-> residual, RMSNorm -> SwiGLU MLP -> residual] -> RMSNorm -> tied output head.
"""
import math
from dataclasses import dataclass, asdict
import torch
import torch.nn as nn
import torch.nn.functional as F
@dataclass
class Config:
vocab_size: int = 4096
dim: int = 320
n_layers: int = 7
n_heads: int = 5
hidden_dim: int = 864
max_seq_len: int = 256
rope_theta: float = 10000.0
norm_eps: float = 1e-5
def to_dict(self):
return asdict(self)
class RMSNorm(nn.Module):
def __init__(self, dim, eps):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim))
def forward(self, x):
xf = x.float()
xf = xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + self.eps)
return xf.type_as(x) * self.weight
def rope_tables(head_dim, seq_len, theta):
inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2).float() / head_dim))
t = torch.arange(seq_len).float()
freqs = torch.outer(t, inv_freq) # (T, hd/2)
return freqs.cos(), freqs.sin()
def apply_rope(x, cos, sin):
# x: (B, H, T, hd); rotate pairs (x1, x2) = halves of the head dim
x1, x2 = x.chunk(2, dim=-1)
cos, sin = cos[None, None], sin[None, None]
return torch.cat([x1 * cos - x2 * sin, x1 * sin + x2 * cos], dim=-1)
class Attention(nn.Module):
def __init__(self, c: Config):
super().__init__()
self.n_heads, self.head_dim = c.n_heads, c.dim // c.n_heads
self.wqkv = nn.Linear(c.dim, 3 * c.dim, bias=False)
self.wo = nn.Linear(c.dim, c.dim, bias=False)
def forward(self, x, cos, sin):
B, T, C = x.shape
q, k, v = self.wqkv(x).split(C, dim=-1)
q, k, v = (t.view(B, T, self.n_heads, self.head_dim).transpose(1, 2) for t in (q, k, v))
q, k = apply_rope(q, cos, sin), apply_rope(k, cos, sin)
# causal attention: softmax(q k^T / sqrt(d) + mask) v
y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
return self.wo(y.transpose(1, 2).reshape(B, T, C))
class SwiGLU(nn.Module):
def __init__(self, c: Config):
super().__init__()
self.w1 = nn.Linear(c.dim, c.hidden_dim, bias=False)
self.w3 = nn.Linear(c.dim, c.hidden_dim, bias=False)
self.w2 = nn.Linear(c.hidden_dim, c.dim, bias=False)
def forward(self, x):
return self.w2(F.silu(self.w1(x)) * self.w3(x))
class Block(nn.Module):
def __init__(self, c: Config):
super().__init__()
self.attn_norm = RMSNorm(c.dim, c.norm_eps)
self.attn = Attention(c)
self.mlp_norm = RMSNorm(c.dim, c.norm_eps)
self.mlp = SwiGLU(c)
def forward(self, x, cos, sin):
x = x + self.attn(self.attn_norm(x), cos, sin)
return x + self.mlp(self.mlp_norm(x))
class Sugarcane(nn.Module):
def __init__(self, c: Config):
super().__init__()
self.config = c
self.tok_emb = nn.Embedding(c.vocab_size, c.dim)
self.blocks = nn.ModuleList(Block(c) for _ in range(c.n_layers))
self.norm = RMSNorm(c.dim, c.norm_eps)
self.head = nn.Linear(c.dim, c.vocab_size, bias=False)
self.head.weight = self.tok_emb.weight # weight tying
cos, sin = rope_tables(c.dim // c.n_heads, c.max_seq_len, c.rope_theta)
self.register_buffer("rope_cos", cos, persistent=False)
self.register_buffer("rope_sin", sin, persistent=False)
self.apply(self._init)
for name, p in self.named_parameters(): # scale residual projections
if name.endswith("wo.weight") or name.endswith("w2.weight"):
nn.init.normal_(p, 0.0, 0.02 / math.sqrt(2 * c.n_layers))
@staticmethod
def _init(m):
if isinstance(m, (nn.Linear, nn.Embedding)):
nn.init.normal_(m.weight, 0.0, 0.02)
def num_params(self):
return sum(p.numel() for p in self.parameters())
def forward(self, idx, targets=None, loss_mask=None):
T = idx.shape[1]
x = self.tok_emb(idx)
cos, sin = self.rope_cos[:T], self.rope_sin[:T]
for b in self.blocks:
x = b(x, cos, sin)
logits = self.head(self.norm(x)).float()
if targets is None:
return logits, None
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), reduction="none")
if loss_mask is None:
return logits, loss.mean()
m = loss_mask.view(-1).float()
return logits, (loss * m).sum() / m.sum().clamp(min=1)
@torch.no_grad()
def generate(self, idx, max_new_tokens, temperature=0.7, top_k=40, stop_ids=()):
for _ in range(max_new_tokens):
ctx = idx[:, -self.config.max_seq_len:]
logits, _ = self(ctx)
logits = logits[:, -1, :]
if temperature <= 0:
nxt = logits.argmax(-1, keepdim=True)
else:
logits = logits / temperature
if top_k:
v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
logits[logits < v[:, [-1]]] = -float("inf")
nxt = torch.multinomial(F.softmax(logits, -1), 1)
idx = torch.cat([idx, nxt], dim=1)
if nxt.item() in stop_ids:
break
return idx