File size: 5,726 Bytes
5b3859c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
"""
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())