File size: 5,435 Bytes
40cdc61 | 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 | """Independently initialized decoder with RoPE, RMSNorm, SwiGLU and KV cache."""
from dataclasses import dataclass, asdict
import time
import torch
from torch import nn
from torch.nn import functional as F
@dataclass
class Config:
vocab_size: int = 8192
dim: int = 384
layers: int = 12
heads: int = 6
ff: int = 1408
context: int = 2048
class RMSNorm(nn.Module):
def __init__(self, dim):
super().__init__()
self.weight = nn.Parameter(torch.ones(dim))
def forward(self, x):
return (x.float() * torch.rsqrt(x.float().pow(2).mean(-1, keepdim=True) + 1e-6)).to(x.dtype) * self.weight
class Block(nn.Module):
def __init__(self, c):
super().__init__()
self.c = c
self.n1, self.n2 = RMSNorm(c.dim), RMSNorm(c.dim)
self.qkv = nn.Linear(c.dim, c.dim * 3, bias=False)
self.out = nn.Linear(c.dim, c.dim, bias=False)
self.gate = nn.Linear(c.dim, c.ff, bias=False)
self.up = nn.Linear(c.dim, c.ff, bias=False)
self.down = nn.Linear(c.ff, c.dim, bias=False)
self.register_buffer('freq', 1 / (10000 ** (torch.arange(0, c.dim // c.heads, 2).float() / (c.dim // c.heads))), persistent=False)
def forward(self, x, past=None):
b, t, d = x.shape
q, k, v = [z.view(b, t, self.c.heads, d // self.c.heads).transpose(1, 2) for z in self.qkv(self.n1(x)).chunk(3, -1)]
offset = 0 if past is None else past[0].shape[-2]
angles = torch.outer(torch.arange(offset, offset+t, device=x.device), self.freq)
cos, sin = angles.cos().to(q.dtype), angles.sin().to(q.dtype)
def rotate(z):
a, b = z[..., 0::2], z[..., 1::2]
return torch.stack((a*cos-b*sin, a*sin+b*cos), -1).flatten(-2)
q, k = rotate(q), rotate(k)
if past is not None:
k, v = torch.cat((past[0], k), -2), torch.cat((past[1], v), -2)
if past is None:
a = F.scaled_dot_product_attention(q, k, v, is_causal=True)
elif t==1:
a = F.scaled_dot_product_attention(q, k, v)
else:
mask = torch.arange(k.shape[-2], device=x.device)[None, :] <= torch.arange(offset, offset+t, device=x.device)[:, None]
a = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
x = x + self.out(a.transpose(1, 2).reshape(b, t, d))
z = self.n2(x)
return x + self.down(F.silu(self.gate(z))*self.up(z)), (k, v)
class Model(nn.Module):
def __init__(self, c=Config()):
super().__init__()
if c.dim % c.heads or (c.dim//c.heads) % 2 or min(asdict(c).values()) <= 0:
raise ValueError('Invalid model dimensions')
self.config = c
self.embedding = nn.Embedding(c.vocab_size, c.dim)
self.blocks = nn.ModuleList(Block(c) for _ in range(c.layers))
self.norm = RMSNorm(c.dim)
self.head = nn.Linear(c.dim, c.vocab_size, bias=False)
self.head.weight = self.embedding.weight
self.apply(self._init)
@staticmethod
def _init(m):
if isinstance(m, (nn.Linear, nn.Embedding)):
nn.init.normal_(m.weight, std=0.02)
def forward(self, ids, past=None):
offset = 0 if past is None else past[0][0].shape[-2]
if ids.shape[1]+offset > self.config.context:
raise ValueError('Context window exceeded')
x, cache = self.embedding(ids), []
for i, block in enumerate(self.blocks):
x, kv = block(x, None if past is None else past[i])
cache.append(kv)
return self.head(self.norm(x)), cache
@torch.inference_mode()
def generate(model, ids, max_tokens=128, temperature=.8, top_k=40, top_p=.95, repetition_penalty=1.1, eos=None, stop_ids=(), timeout=60, valid_vocab_size=None):
if temperature < 0 or top_k < 0 or not 0 < top_p <= 1 or repetition_penalty < 1:
raise ValueError('Invalid sampling controls')
model.eval()
past, current, result = None, ids, ids[0].tolist()
deadline = time.monotonic()+timeout
for _ in range(min(max_tokens, model.config.context-ids.shape[1])):
if time.monotonic()>deadline: raise TimeoutError('Generation timed out')
logits, past = model(current, past)
scores = logits[:, -1].float()
if valid_vocab_size is not None:
if not 1 <= valid_vocab_size <= scores.shape[-1]: raise ValueError('Invalid tokenizer vocabulary size')
scores[:, valid_vocab_size:] = -float('inf')
seen = list(set(result))
scores[:, seen] = torch.where(scores[:, seen] < 0, scores[:, seen]*repetition_penalty, scores[:, seen]/repetition_penalty)
if temperature == 0:
token = scores.argmax(-1, keepdim=True)
else:
scores /= temperature
if top_k:
scores[scores < scores.topk(min(top_k, scores.shape[-1])).values[:, -1:]] = -float('inf')
ordered, indices = scores.sort(descending=True)
remove = ordered.softmax(-1).cumsum(-1) > top_p
remove[:, 1:] = remove[:, :-1].clone()
remove[:, 0] = False
ordered[remove] = -float('inf')
token = indices.gather(-1, torch.multinomial(ordered.softmax(-1), 1))
value = token.item()
result.append(value)
if value == eos or any(result[-len(s):] == list(s) for s in stop_ids if s):
break
current = token
return result[ids.shape[1]:]
|