""" Pronghorn: a small Llama-style language model (5,078,208 parameters). Architecture: token embedding -> 8 x [RMSNorm -> attention with RoPE -> add back, RMSNorm -> SwiGLU -> add back] -> RMSNorm -> output scores over the vocabulary. The output layer shares its weights with the embedding table (weight tying). License: MIT (see LICENSE). Usage: from tokenizers import Tokenizer from model import load_model, generate tok = Tokenizer.from_file("tokenizer.json") model = load_model("final_model.pt") print(generate(model, tok, "Welcome back to the channel. Today we are going to")) """ import math from dataclasses import dataclass import torch import torch.nn as nn import torch.nn.functional as F @dataclass class Config: vocab_size: int = 8000 dim: int = 192 n_layers: int = 8 n_heads: int = 6 hidden: int = 512 # width of the SwiGLU feed-forward layer ctx: int = 256 # context length the model was trained with class RMSNorm(nn.Module): def __init__(self, dim, eps=1e-6): super().__init__() self.eps = eps self.scale = nn.Parameter(torch.ones(dim)) def forward(self, x): rms = torch.sqrt(x.pow(2).mean(dim=-1, keepdim=True) + self.eps) return (x / rms) * self.scale def precompute_rope(head_dim, max_len, base=10000.0): speeds = 1.0 / (base ** (torch.arange(0, head_dim, 2).float() / head_dim)) angles = torch.outer(torch.arange(max_len).float(), speeds) return torch.cos(angles), torch.sin(angles) def apply_rope(x, cos, sin): # x: (batch, heads, seq_len, head_dim) seq_len, half = x.shape[2], x.shape[-1] // 2 cos = cos[:seq_len][None, None, :, :] sin = sin[:seq_len][None, None, :, :] x1, x2 = x[..., :half], x[..., half:] out = torch.cat([x1 * cos - x2 * sin, x1 * sin + x2 * cos], dim=-1) return out.type_as(x) class Attention(nn.Module): def __init__(self, cfg): super().__init__() self.n_heads = cfg.n_heads self.head_dim = cfg.dim // cfg.n_heads self.wq = nn.Linear(cfg.dim, cfg.dim, bias=False) self.wk = nn.Linear(cfg.dim, cfg.dim, bias=False) self.wv = nn.Linear(cfg.dim, cfg.dim, bias=False) self.wo = nn.Linear(cfg.dim, cfg.dim, bias=False) def forward(self, x, cos, sin): B, T, C = x.shape q = self.wq(x).view(B, T, self.n_heads, self.head_dim).transpose(1, 2) k = self.wk(x).view(B, T, self.n_heads, self.head_dim).transpose(1, 2) v = self.wv(x).view(B, T, self.n_heads, self.head_dim).transpose(1, 2) q, k = apply_rope(q, cos, sin), apply_rope(k, cos, sin) scores = (q @ k.transpose(-2, -1)) / math.sqrt(self.head_dim) mask = torch.triu(torch.ones(T, T, dtype=torch.bool, device=x.device), diagonal=1) scores = scores.masked_fill(mask, float("-inf")) out = F.softmax(scores, dim=-1) @ v return self.wo(out.transpose(1, 2).contiguous().view(B, T, C)) class SwiGLU(nn.Module): def __init__(self, cfg): super().__init__() self.w_gate = nn.Linear(cfg.dim, cfg.hidden, bias=False) self.w_up = nn.Linear(cfg.dim, cfg.hidden, bias=False) self.w_down = nn.Linear(cfg.hidden, cfg.dim, bias=False) def forward(self, x): return self.w_down(F.silu(self.w_gate(x)) * self.w_up(x)) class Block(nn.Module): def __init__(self, cfg): super().__init__() self.norm1, self.attn = RMSNorm(cfg.dim), Attention(cfg) self.norm2, self.ffn = RMSNorm(cfg.dim), SwiGLU(cfg) def forward(self, x, cos, sin): x = x + self.attn(self.norm1(x), cos, sin) x = x + self.ffn(self.norm2(x)) return x class Pronghorn(nn.Module): def __init__(self, cfg=None): super().__init__() cfg = cfg or Config() self.cfg = cfg self.tok_emb = nn.Embedding(cfg.vocab_size, cfg.dim) self.blocks = nn.ModuleList([Block(cfg) for _ in range(cfg.n_layers)]) self.norm_f = RMSNorm(cfg.dim) self.lm_head = nn.Linear(cfg.dim, cfg.vocab_size, bias=False) self.lm_head.weight = self.tok_emb.weight # weight tying cos, sin = precompute_rope(cfg.dim // cfg.n_heads, cfg.ctx) self.register_buffer("cos", cos, persistent=False) self.register_buffer("sin", sin, persistent=False) def forward(self, idx): x = self.tok_emb(idx) for blk in self.blocks: x = blk(x, self.cos, self.sin) return self.lm_head(self.norm_f(x)) def load_model(weights_path, device="cpu"): """Build the model and load the trained weights.""" model = Pronghorn(Config()) state = torch.load(weights_path, map_location="cpu") model.load_state_dict(state) return model.to(device).eval() @torch.no_grad() def generate(model, tokenizer, prompt, max_new_tokens=80, temperature=0.8, top_k=40, rep_penalty=1.2, window=64): """Continue a prompt. rep_penalty > 1 discourages repeating recent tokens.""" device = next(model.parameters()).device ctx = model.cfg.ctx x = torch.tensor([tokenizer.encode(prompt).ids], device=device) for _ in range(max_new_tokens): logits = model(x[:, -ctx:])[:, -1, :].float() if rep_penalty != 1.0: recent = x[0, -window:].unique() vals = logits[0, recent] logits[0, recent] = torch.where(vals > 0, vals / rep_penalty, vals * rep_penalty) logits = logits / temperature v, _ = torch.topk(logits, top_k) logits[logits < v[:, [-1]]] = -float("inf") next_id = torch.multinomial(F.softmax(logits, dim=-1), 1) x = torch.cat([x, next_id], dim=1) return tokenizer.decode(x[0].tolist())