File size: 2,921 Bytes
76389c9 | 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 | from dataclasses import dataclass
import math
import torch
from torch import nn
from torch.nn import functional as F
@dataclass
class Config:
vocab_size:int=4096
dim:int=256
layers:int=12
heads:int=4
ff:int=608
context:int=512
class RMSNorm(nn.Module):
def __init__(self,d):
super().__init__();self.weight=nn.Parameter(torch.ones(d))
def forward(self,x):
f=x.float();return (f*torch.rsqrt(f.square().mean(-1,keepdim=True)+1e-5)*self.weight.float()).to(x.dtype)
def rope(x):
b,h,t,d=x.shape
inv=1.0/(10000**(torch.arange(0,d,2,device=x.device,dtype=torch.float32)/d))
angles=torch.outer(torch.arange(t,device=x.device,dtype=torch.float32),inv)
cos=angles.cos().to(x.dtype)[None,None,:,:];sin=angles.sin().to(x.dtype)[None,None,:,:]
even=x[...,::2];odd=x[...,1::2]
return torch.stack((even*cos-odd*sin,even*sin+odd*cos),dim=-1).flatten(-2)
class Attention(nn.Module):
def __init__(self,c):
super().__init__();self.h=c.heads;self.d=c.dim//c.heads
self.qkv=nn.Linear(c.dim,c.dim*3,bias=False)
self.proj=nn.Linear(c.dim,c.dim,bias=False)
def forward(self,x):
b,t,d=x.shape
q,k,v=self.qkv(x).chunk(3,dim=-1)
q=rope(q.view(b,t,self.h,self.d).transpose(1,2))
k=rope(k.view(b,t,self.h,self.d).transpose(1,2))
v=v.view(b,t,self.h,self.d).transpose(1,2)
y=F.scaled_dot_product_attention(q,k,v,is_causal=True)
return self.proj(y.transpose(1,2).contiguous().view(b,t,d))
class FFN(nn.Module):
def __init__(self,c):
super().__init__();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)
def forward(self,x):return self.down(F.silu(self.gate(x))*self.up(x))
class Block(nn.Module):
def __init__(self,c):
super().__init__();self.n1=RMSNorm(c.dim);self.a=Attention(c)
self.n2=RMSNorm(c.dim);self.f=FFN(c)
def forward(self,x):
x=x+self.a(self.n1(x))
return x+self.f(self.n2(x))
class DiChat10M(nn.Module):
def __init__(self,c=None):
super().__init__();c=c or Config();self.config=c
if c.dim%c.heads or (c.dim//c.heads)%2:raise ValueError('invalid head dimensions')
self.emb=nn.Embedding(c.vocab_size,c.dim)
self.blocks=nn.ModuleList([Block(c) for _ in range(c.layers)])
self.norm=RMSNorm(c.dim)
self.lm=nn.Linear(c.dim,c.vocab_size,bias=False)
self.lm.weight=self.emb.weight
self.apply(self.init)
scale=1/math.sqrt(2*c.layers)
for block in self.blocks:
nn.init.normal_(block.a.proj.weight,std=.02*scale)
nn.init.normal_(block.f.down.weight,std=.02*scale)
def init(self,m):
if isinstance(m,(nn.Linear,nn.Embedding)):nn.init.normal_(m.weight,mean=0,std=.02)
def forward(self,idx,targets=None):
if idx.shape[1]>self.config.context:raise ValueError('context length exceeded')
x=self.emb(idx)
for block in self.blocks:x=block(x)
logits=self.lm(self.norm(x))
if targets is None:return logits
return F.cross_entropy(logits.float().flatten(0,1),targets.flatten())
|