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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
from torch.nn import functional as F
|
| 5 |
+
import math
|
| 6 |
+
|
| 7 |
+
def precompute(head_dim : int, seq_len : int, device : str, base : float = 10000.0):
|
| 8 |
+
assert head_dim % 2 == 0
|
| 9 |
+
|
| 10 |
+
theta_pair = torch.arange(0,head_dim,2).float()
|
| 11 |
+
theta = 1.0 / (base ** (theta_pair / head_dim)).to(device)
|
| 12 |
+
|
| 13 |
+
m = torch.arange(seq_len,device=device)
|
| 14 |
+
freqs = torch.outer(m,theta).float()
|
| 15 |
+
|
| 16 |
+
freqs_complex = torch.polar(torch.ones_like(freqs),freqs)
|
| 17 |
+
|
| 18 |
+
return freqs_complex
|
| 19 |
+
|
| 20 |
+
def apply_rope(x : torch.tensor, freqs_complex : torch.tensor, device:str):
|
| 21 |
+
x_complex = torch.view_as_complex(x.float().reshape(*x.shape[:-1],-1,2))
|
| 22 |
+
freqs_complex = freqs_complex.unsqueeze(0).unsqueeze(0)
|
| 23 |
+
|
| 24 |
+
x_rotated = x_complex * freqs_complex
|
| 25 |
+
x_out = torch.view_as_real(x_rotated)
|
| 26 |
+
x_out = x_out.reshape(*x.shape)
|
| 27 |
+
|
| 28 |
+
return x_out.type_as(x)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class CasualSelfAttention(nn.Module):
|
| 32 |
+
def __init__(self,config):
|
| 33 |
+
super().__init__()
|
| 34 |
+
|
| 35 |
+
self.c_attn = nn.Linear(config.n_embd, config.n_embd * 3,bias=False)
|
| 36 |
+
self.c_proj = nn.Linear(config.n_embd,config.n_embd,bias=False)
|
| 37 |
+
|
| 38 |
+
self.n_head = config.n_head
|
| 39 |
+
self.n_embd = config.n_embd
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def forward(self,x,freqs):
|
| 43 |
+
B,T,C = x.size()
|
| 44 |
+
qkv = self.c_attn(x)
|
| 45 |
+
q,k,v = qkv.split(self.n_embd,dim=2)
|
| 46 |
+
|
| 47 |
+
q = q.view(B,T, self.n_head, C // self.n_head).transpose(1,2)
|
| 48 |
+
k = k.view(B,T, self.n_head, C // self.n_head).transpose(1,2)
|
| 49 |
+
v = v.view(B,T , self.n_head, C // self.n_head).transpose(1,2)
|
| 50 |
+
|
| 51 |
+
q = apply_rope(q, freqs, x.device)
|
| 52 |
+
k = apply_rope(k, freqs, x.device)
|
| 53 |
+
|
| 54 |
+
y = F.scaled_dot_product_attention(q,k,v,is_causal=True)
|
| 55 |
+
y = y.transpose(1,2).contiguous().view(B,T,C)
|
| 56 |
+
|
| 57 |
+
y = self.c_proj(y)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
return y
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class FeedForward(nn.Module):
|
| 65 |
+
def __init__(self,config):
|
| 66 |
+
super().__init__()
|
| 67 |
+
hidden_dim = int(2 * config.n_embd / 3)
|
| 68 |
+
hidden_dim = config.multiple_of * ((hidden_dim + config.multiple_of - 1) // config.multiple_of)
|
| 69 |
+
|
| 70 |
+
self.w1 = nn.Linear(config.n_embd,hidden_dim, bias=False)
|
| 71 |
+
self.w2 = nn.Linear(hidden_dim,config.n_embd, bias = False)
|
| 72 |
+
self.w3 = nn.Linear(config.n_embd, hidden_dim, bias= False)
|
| 73 |
+
|
| 74 |
+
def forward(self,x : torch.tensor):
|
| 75 |
+
return self.w2(F.silu(self.w1(x)) * self.w3(x))
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class Block(nn.Module):
|
| 79 |
+
def __init__(self,config):
|
| 80 |
+
super().__init__()
|
| 81 |
+
|
| 82 |
+
self.sa = CasualSelfAttention(config)
|
| 83 |
+
self.mlp = FeedForward(config)
|
| 84 |
+
self.ln1 = nn.RMSNorm(config.n_embd,eps=1e-05)
|
| 85 |
+
self.ln2 = nn.RMSNorm(config.n_embd,eps =1e-05)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def forward(self,x,freqs):
|
| 89 |
+
x = x + self.sa(self.ln1(x),freqs)
|
| 90 |
+
x = x + self.mlp(self.ln2(x))
|
| 91 |
+
|
| 92 |
+
return x
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class Model(nn.Module):
|
| 96 |
+
def __init__(self,config):
|
| 97 |
+
super().__init__()
|
| 98 |
+
|
| 99 |
+
self.register_buffer(
|
| 100 |
+
'freqs_complex',precompute(
|
| 101 |
+
config.n_embd // config.n_head,
|
| 102 |
+
config.block_size,
|
| 103 |
+
device=config.device
|
| 104 |
+
)
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
self.config = config
|
| 108 |
+
self.transformer = nn.ModuleDict(dict(
|
| 109 |
+
wte = nn.Embedding(config.vocab_size,config.n_embd),
|
| 110 |
+
h = nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
|
| 111 |
+
ln_f = nn.RMSNorm(config.n_embd,eps = 1e-05)
|
| 112 |
+
))
|
| 113 |
+
self.lm_head = nn.Linear(config.n_embd, config.vocab_size,bias=False)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
self.transformer.wte.weight = self.lm_head.weight
|
| 117 |
+
|
| 118 |
+
def forward(self,idx,targets=None):
|
| 119 |
+
B,T = idx.size()
|
| 120 |
+
|
| 121 |
+
x = self.transformer.wte(idx)
|
| 122 |
+
|
| 123 |
+
for block in self.transformer.h:
|
| 124 |
+
x = block(x,self.freqs_complex[:T])
|
| 125 |
+
|
| 126 |
+
x = self.transformer.ln_f(x)
|
| 127 |
+
logits = self.lm_head(x)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
loss = None
|
| 131 |
+
if targets is not None:
|
| 132 |
+
loss = F.cross_entropy(logits.view(-1,logits.size(-1)),targets.view(-1))
|
| 133 |
+
|
| 134 |
+
return logits,loss
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def sample_top_p(self,probs,p):
|
| 138 |
+
probs_sort, probs_idx = torch.sort(probs,dim=-1,descending=True)
|
| 139 |
+
probs_sum = torch.cumsum(probs_sort,dim=-1)
|
| 140 |
+
mask = probs_sum - probs_sort > p
|
| 141 |
+
probs_sort[mask] = 0.0
|
| 142 |
+
probs_sort.div_(probs_sort.sum(dim=-1,keepdim=True))
|
| 143 |
+
|
| 144 |
+
next_token = torch.multinomial(probs_sort,num_samples=1)
|
| 145 |
+
next_token = torch.gather(probs_idx,-1,next_token)
|
| 146 |
+
|
| 147 |
+
return next_token
|
| 148 |
+
|
| 149 |
+
@torch.no_grad()
|
| 150 |
+
def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None,top_p = None):
|
| 151 |
+
|
| 152 |
+
for _ in range(max_new_tokens):
|
| 153 |
+
|
| 154 |
+
idx_cond = idx if idx.size(1) <= self.config.block_size else idx[:, -self.config.block_size:]
|
| 155 |
+
|
| 156 |
+
logits, _ = self(idx_cond)
|
| 157 |
+
|
| 158 |
+
logits = logits[:, -1, :] / temperature
|
| 159 |
+
|
| 160 |
+
if top_k is not None:
|
| 161 |
+
v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
|
| 162 |
+
logits[logits < v[:, [-1]]] = -float('Inf')
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
probs = F.softmax(logits, dim=-1)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
if top_p is not None:
|
| 169 |
+
idx_next = self.sample_top_p(probs,top_p)
|
| 170 |
+
else:
|
| 171 |
+
idx_next = torch.multinomial(probs, num_samples=1)
|
| 172 |
+
|
| 173 |
+
idx = torch.cat((idx, idx_next), dim=1)
|
| 174 |
+
|
| 175 |
+
return idx
|