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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
import torch.nn.functional as F
|
4 |
+
from torch.nn import SiLU
|
5 |
+
import yaml
|
6 |
+
|
7 |
+
|
8 |
+
def _init_weights(module, std=0.041666666666666664):
|
9 |
+
if isinstance(module, nn.Linear):
|
10 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
11 |
+
elif isinstance(module, nn.Embedding):
|
12 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
13 |
+
|
14 |
+
class RotaryPositionalEmbedding(nn.Module):
|
15 |
+
"""
|
16 |
+
# https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py#L240
|
17 |
+
Rotary Positional Embedding (RoPE) for transformers Implemntation derived from https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py
|
18 |
+
"""
|
19 |
+
def __init__(self, dim: int, theta: float = 10000.0):
|
20 |
+
super().__init__()
|
21 |
+
self.dim = dim
|
22 |
+
self.theta = theta
|
23 |
+
|
24 |
+
def forward(self, x: torch.Tensor, seq_len: int) -> torch.Tensor:
|
25 |
+
"""
|
26 |
+
Apply rotary positional embedding to the input tensor.
|
27 |
+
|
28 |
+
Args:
|
29 |
+
x (torch.Tensor): Input tensor of shape # B, T, H, D
|
30 |
+
seq_len (int): Sequence length. #T
|
31 |
+
|
32 |
+
Returns:
|
33 |
+
torch.Tensor: Output tensor with rotary positional embeddings applied.
|
34 |
+
"""
|
35 |
+
B, T, H, H_D = x.shape
|
36 |
+
|
37 |
+
# Generate position indices
|
38 |
+
position = torch.arange(T, dtype=torch.float32, device=x.device).unsqueeze(-1)
|
39 |
+
|
40 |
+
# Generate frequencies
|
41 |
+
freqs = torch.exp(
|
42 |
+
torch.arange(0, H_D, 2, dtype=torch.float32, device=x.device) *
|
43 |
+
-(torch.log(torch.tensor(self.theta)) / H_D)
|
44 |
+
|
45 |
+
)
|
46 |
+
|
47 |
+
# Compute sinusoids
|
48 |
+
sinusoid = position * freqs
|
49 |
+
sin = torch.sin(sinusoid)
|
50 |
+
cos = torch.cos(sinusoid)
|
51 |
+
|
52 |
+
# Reshape sin and cos to match the input tensor's shape
|
53 |
+
sin = sin.unsqueeze(0).unsqueeze(2) # Shape: (1, T, 1, D // 2)
|
54 |
+
cos = cos.unsqueeze(0).unsqueeze(2) # Shape: (1, T, 1, D // 2)
|
55 |
+
|
56 |
+
# Apply rotary embeddings
|
57 |
+
x_rotated = x.clone()
|
58 |
+
x_rotated[..., 0::2] = x[..., 0::2] * cos - x[..., 1::2] * sin
|
59 |
+
x_rotated[..., 1::2] = x[..., 1::2] * cos + x[..., 0::2] * sin
|
60 |
+
|
61 |
+
return x_rotated
|
62 |
+
|
63 |
+
class LlamaAttention(nn.Module):
|
64 |
+
"""
|
65 |
+
(self_attn): LlamaAttention(
|
66 |
+
(q_proj): Linear(in_features=576, out_features=576, bias=False)
|
67 |
+
(k_proj): Linear(in_features=576, out_features=192, bias=False)
|
68 |
+
(v_proj): Linear(in_features=576, out_features=192, bias=False)
|
69 |
+
(o_proj): Linear(in_features=576, out_features=576, bias=False)
|
70 |
+
)
|
71 |
+
"""
|
72 |
+
def __init__(self, config, rotary_emb):
|
73 |
+
super().__init__()
|
74 |
+
self.config = config
|
75 |
+
self.num_attention_heads = self.config['num_attention_heads']
|
76 |
+
self.hidden_size = self.config['hidden_size']
|
77 |
+
# Ensure the hidden size is divisible by the number of attention heads
|
78 |
+
if self.hidden_size % self.num_attention_heads != 0:
|
79 |
+
raise ValueError(
|
80 |
+
f"hidden_size ({self.hidden_size}) must be divisible by num_attention_heads ({self.num_attention_heads})"
|
81 |
+
)
|
82 |
+
self.num_key_value_heads = self.config['num_key_value_heads']
|
83 |
+
self.head_dim = self.hidden_size // self.num_attention_heads
|
84 |
+
self.q_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False) # D,D
|
85 |
+
self.k_proj = nn.Linear(self.hidden_size, self.head_dim*self.num_key_value_heads, bias=False) # D,D/H
|
86 |
+
self.v_proj = nn.Linear(self.hidden_size, self.head_dim*self.num_key_value_heads, bias=False) # D,D/H
|
87 |
+
self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False) # D,D
|
88 |
+
|
89 |
+
# Convert the mask to boolean type when creating it
|
90 |
+
# self.register_buffer("mask",
|
91 |
+
# torch.triu(torch.ones(self.config['max_position_embeddings'],
|
92 |
+
# self.config['max_position_embeddings']),
|
93 |
+
# diagonal=1)) # Convert to boolean
|
94 |
+
|
95 |
+
self.rotary_pos_emb = rotary_emb
|
96 |
+
|
97 |
+
def forward(self, x):
|
98 |
+
B, T, C = x.size()
|
99 |
+
|
100 |
+
q = self.q_proj(x) # B,T,D
|
101 |
+
k = self.k_proj(x) # B,T,D/H
|
102 |
+
v = self.v_proj(x) # B,T,D/H
|
103 |
+
|
104 |
+
q = q.view(B, T, self.num_attention_heads, self.head_dim) # B,T,H,D
|
105 |
+
k = k.view(B, T, self.num_key_value_heads, self.head_dim) # B,T,H,D
|
106 |
+
v = v.view(B, T, self.num_key_value_heads, self.head_dim) # B,T,H,D
|
107 |
+
|
108 |
+
q = q.transpose(1,2) # B,H,T,D
|
109 |
+
k = k.transpose(1,2) # B,num_key_value_heads,T,D
|
110 |
+
v = v.transpose(1,2) # B,num_key_value_heads,T,D
|
111 |
+
|
112 |
+
# apply rotary positional embedding
|
113 |
+
q = self.rotary_pos_emb(q, T)
|
114 |
+
k = self.rotary_pos_emb(k, T)
|
115 |
+
|
116 |
+
# Repeat k/v heads if num_key_value_heads < num_attention_heads
|
117 |
+
if self.num_key_value_heads != self.num_attention_heads:
|
118 |
+
k = k.repeat_interleave(self.num_attention_heads // self.num_key_value_heads, dim=1) # B,kv_head,T,D -> B,H,T,D
|
119 |
+
v = v.repeat_interleave(self.num_attention_heads // self.num_key_value_heads, dim=1) # B,kv_head,T,D -> B,H,T,D
|
120 |
+
|
121 |
+
# Manual attention Stats
|
122 |
+
# Q(B,H,T,D) @K.T(B,H,D,T) = Q.K_T (B,H,T,T)
|
123 |
+
# attn_scores = q @ k.transpose(-2,-1) # B,H,T,T
|
124 |
+
# mask_bool = self.mask[:T,:T].bool() # T,T
|
125 |
+
# attn_scores.masked_fill_(mask_bool, -torch.inf) # B,H,T,T
|
126 |
+
# attn_weights = F.softmax(attn_scores/k.size(-1)**0.5, dim=-1) # B,H,T,T
|
127 |
+
# context_vector = attn_weights @ v # B,H,T,T * B,H,T,D = B,H,T,D
|
128 |
+
# context_vector = context_vector.transpose(1,2) # B,T,H,D
|
129 |
+
# context_vector = context_vector.contiguous().view(B,T,C) # B,T,H,D -> B,T,D
|
130 |
+
# Manual attention Stats ENDS
|
131 |
+
|
132 |
+
# Scaled dot-product attention STARTS
|
133 |
+
attn_out = F.scaled_dot_product_attention(q, k, v, is_causal=True)
|
134 |
+
context_vector = attn_out.transpose(1,2).reshape(B,T,C)
|
135 |
+
# Scaled dot-product attention ENDS
|
136 |
+
|
137 |
+
context_vector = self.o_proj(context_vector)
|
138 |
+
|
139 |
+
return context_vector
|
140 |
+
|
141 |
+
|
142 |
+
class LlamaMLP(nn.Module):
|
143 |
+
"""
|
144 |
+
(mlp): LlamaMLP(
|
145 |
+
(gate_proj): Linear(in_features=576, out_features=1536, bias=False)
|
146 |
+
(up_proj): Linear(in_features=576, out_features=1536, bias=False)
|
147 |
+
(down_proj): Linear(in_features=1536, out_features=576, bias=False)
|
148 |
+
(act_fn): SiLU()
|
149 |
+
)
|
150 |
+
"""
|
151 |
+
def __init__(self, config):
|
152 |
+
super().__init__()
|
153 |
+
self.config = config
|
154 |
+
self.gate_proj = nn.Linear(self.config['hidden_size'], self.config['intermediate_size'], bias=False)
|
155 |
+
self.up_proj = nn.Linear(self.config['hidden_size'], self.config['intermediate_size'], bias=False)
|
156 |
+
self.down_proj = nn.Linear(self.config['intermediate_size'], self.config['hidden_size'], bias=False)
|
157 |
+
self.act_fn = SiLU()
|
158 |
+
def forward(self, x):
|
159 |
+
gate = self.gate_proj(x)
|
160 |
+
up = self.up_proj(x)
|
161 |
+
down = self.down_proj(self.act_fn(gate)*up)
|
162 |
+
return down
|
163 |
+
|
164 |
+
class LlamaRMSNorm(nn.Module):
|
165 |
+
"""
|
166 |
+
(norm): LlamaRMSNorm((576,), eps=1e-05)
|
167 |
+
# RMSNorm Formula:
|
168 |
+
# RMS(x) = sqrt((1 / d) * sum(x_i^2 for i in range(d)))
|
169 |
+
# x_normalized = x / RMS(x)
|
170 |
+
# output = gamma * x_normalized
|
171 |
+
|
172 |
+
"""
|
173 |
+
def __init__(self, config):
|
174 |
+
super().__init__()
|
175 |
+
self.config = config
|
176 |
+
self.eps = self.config['rms_norm_eps']
|
177 |
+
self.weight = nn.Parameter(torch.ones(self.config['hidden_size']))
|
178 |
+
def forward(self, x):
|
179 |
+
rms = torch.rsqrt(torch.mean(x ** 2, dim=-1, keepdim=True) + self.eps)
|
180 |
+
return self.weight *rms * x
|
181 |
+
|
182 |
+
class LlamaDecoderLayer(nn.Module):
|
183 |
+
def __init__(self, config, rotary_emb):
|
184 |
+
super().__init__()
|
185 |
+
self.config = config
|
186 |
+
self.self_attn = LlamaAttention(self.config, rotary_emb)
|
187 |
+
self.mlp = LlamaMLP(self.config)
|
188 |
+
self.input_layernorm = LlamaRMSNorm(self.config)
|
189 |
+
self.post_attention_layernorm = LlamaRMSNorm(self.config)
|
190 |
+
|
191 |
+
def forward(self, x):
|
192 |
+
residual = x
|
193 |
+
x = self.input_layernorm(x)
|
194 |
+
x = self.self_attn(x)
|
195 |
+
x = x + residual
|
196 |
+
|
197 |
+
residual = x
|
198 |
+
x = self.post_attention_layernorm(x)
|
199 |
+
x = self.mlp(x)
|
200 |
+
x = x + residual
|
201 |
+
return x
|
202 |
+
|
203 |
+
class LlamaModel(nn.Module):
|
204 |
+
def __init__(self, config):
|
205 |
+
super().__init__()
|
206 |
+
self.init_method = config['init_method']
|
207 |
+
self.config = config['model_config']
|
208 |
+
self.embed_tokens = nn.Embedding(self.config['vocab_size'], self.config['hidden_size'])
|
209 |
+
self.rotary_emb = RotaryPositionalEmbedding(self.config['hidden_size'], self.config['rope_theta'])
|
210 |
+
self.layers = nn.ModuleList([LlamaDecoderLayer(self.config, self.rotary_emb) for _ in range(self.config['num_hidden_layers'])])
|
211 |
+
self.norm = LlamaRMSNorm(self.config)
|
212 |
+
self.lm_head = nn.Linear(self.config['hidden_size'], self.config['vocab_size'], bias=False)
|
213 |
+
|
214 |
+
if self.config['tie_word_embeddings']:
|
215 |
+
self.lm_head.weight = self.embed_tokens.weight
|
216 |
+
|
217 |
+
self.apply(lambda m: _init_weights(m, self.init_method['std']))
|
218 |
+
|
219 |
+
def forward(self, x, y=None):
|
220 |
+
x = self.embed_tokens(x)
|
221 |
+
for layer in self.layers:
|
222 |
+
x = layer(x)
|
223 |
+
x = self.norm(x)
|
224 |
+
logits = self.lm_head(x) # B,T,V
|
225 |
+
logits = logits.view(-1, logits.size(-1)) # Shape: [B*T, V]
|
226 |
+
if y is not None:
|
227 |
+
y = y.view(-1) # Shape: [B*T]
|
228 |
+
loss = torch.nn.functional.cross_entropy(logits, y)
|
229 |
+
return logits, loss
|
230 |
+
else:
|
231 |
+
return logits, None
|
232 |
+
|
233 |
+
|
234 |
+
def generate(self, idx, max_new_tokens, context_length, temperature=1.0, top_k=None, eos_token=None, device=None):
|
235 |
+
model = self.to(device)
|
236 |
+
idx = idx.to(device)
|
237 |
+
model.eval()
|
238 |
+
for _ in range(max_new_tokens):
|
239 |
+
idx_cond = idx[:, -context_length:]
|
240 |
+
with torch.no_grad():
|
241 |
+
logits, _ = model(idx_cond) # Unpack both logits and loss (ignore loss)
|
242 |
+
logits = logits.view(idx_cond.shape[0], -1, model.config['vocab_size']) # Reshape to [batch, seq, vocab]
|
243 |
+
|
244 |
+
# Get the logits for the last token only
|
245 |
+
logits = logits[:, -1, :] # Shape: [batch_size, vocab_size]
|
246 |
+
|
247 |
+
if top_k is not None:
|
248 |
+
# top k sampling
|
249 |
+
top_logits, top_pos = torch.topk(logits, top_k)
|
250 |
+
min_logit = top_logits[:, -1].unsqueeze(-1)
|
251 |
+
logits = torch.where(logits < min_logit,
|
252 |
+
torch.tensor(float('-inf')).to(logits.device),
|
253 |
+
logits)
|
254 |
+
|
255 |
+
# temperature scaling
|
256 |
+
if temperature > 0.0:
|
257 |
+
logits /= temperature
|
258 |
+
probs = torch.softmax(logits, dim=-1)
|
259 |
+
idx_next = torch.multinomial(probs, num_samples=1)
|
260 |
+
else:
|
261 |
+
idx_next = torch.argmax(logits, dim=-1, keepdim=True)
|
262 |
+
|
263 |
+
if idx_next.item() == eos_token:
|
264 |
+
break
|
265 |
+
|
266 |
+
idx = torch.cat((idx, idx_next), dim=1)
|
267 |
+
model.train()
|
268 |
+
return idx
|
269 |
+
|
270 |
+
# if __name__ == "__main__":
|
271 |
+
# torch.manual_seed(0)
|
272 |
+
# config = yaml.load(open("config_smollm2_135M.yaml", "r"), Loader=yaml.FullLoader)
|
273 |
+
# print(config.keys())
|
274 |
+
# model_config = config['model']['model_config']
|
275 |
+
# print(model_config)
|
276 |
+
# model = LlamaModel(config['model'])
|
277 |
+
# x_tokens = torch.randint(0, model_config['vocab_size'], (1, 10)) # Generate random token indices
|
278 |
+
# print(model(x_tokens).shape)
|
279 |
+
# total_params = sum(p.numel() for p in model.parameters())
|
280 |
+
# print(f"Total parameters: {total_params}") #134515008
|
281 |
+
# print(model)
|