File size: 3,601 Bytes
ebf8f81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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