VirtualInsight commited on
Commit
c43aac0
·
verified ·
1 Parent(s): f47d9b2

Upload ModelArchitecture.py

Browse files
Files changed (1) hide show
  1. ModelArchitecture.py +346 -0
ModelArchitecture.py ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ import math
5
+ from dataclasses import dataclass
6
+ from typing import Optional
7
+
8
+
9
+ @dataclass
10
+ class ModelConfig:
11
+ vocab_size: int
12
+ hidden_size: int
13
+ n_heads: int
14
+ n_kv_heads: int
15
+ n_kv_groups: int
16
+ head_dim: int
17
+ n_layers: int
18
+ attention_bias: bool
19
+ intermediate_size: int
20
+ mlp_bias: bool
21
+ eps: float
22
+ dropout: float
23
+ max_position_embeddings: int
24
+ pre_norm: bool
25
+ tie_weights: bool
26
+ max_seq_len: int
27
+
28
+
29
+ class RMSNorm(nn.Module):
30
+ def __init__(self, config: ModelConfig):
31
+ super().__init__()
32
+ self.eps = config.eps
33
+ self.weight = nn.Parameter(torch.ones(config.hidden_size))
34
+
35
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
36
+ rms = torch.sqrt(torch.mean(x * x, dim=-1, keepdim=True) + self.eps)
37
+ return (x / rms) * self.weight
38
+
39
+
40
+ class RotaryEmbedding(nn.Module):
41
+ def __init__(self, head_dim, max_position_embeddings=2048):
42
+ super().__init__()
43
+ inv_freq = 1.0 / (10000 ** (torch.arange(0, head_dim, 2).float() / head_dim))
44
+ t = torch.arange(max_position_embeddings, dtype=torch.float32)
45
+ freqs = torch.einsum("i,j->ij", t, inv_freq)
46
+ emb = torch.cat((freqs, freqs), dim=-1)
47
+ self.register_buffer("cos", emb.cos()[None, None, :, :], persistent=False)
48
+ self.register_buffer("sin", emb.sin()[None, None, :, :], persistent=False)
49
+
50
+ def forward(self, seq_len: int, device: torch.device, dtype: torch.dtype):
51
+ cos = self.cos[:, :, :seq_len, :].to(device=device, dtype=dtype)
52
+ sin = self.sin[:, :, :seq_len, :].to(device=device, dtype=dtype)
53
+ return cos, sin
54
+
55
+
56
+ def apply_rotary(x, cos, sin):
57
+ x1, x2 = x[..., ::2], x[..., 1::2]
58
+ x_rot = torch.stack([-x2, x1], dim=-1).reshape_as(x)
59
+ return (x * cos) + (x_rot * sin)
60
+
61
+
62
+ class GroupedMultiQueryAttention(nn.Module):
63
+ def __init__(self, config: ModelConfig):
64
+ super().__init__()
65
+ self.hidden_size = config.hidden_size
66
+ self.n_heads = config.n_heads
67
+ self.n_kv_heads = config.n_kv_heads
68
+ self.head_dim = config.head_dim
69
+ self.attention_bias = config.attention_bias
70
+ self.dropout = nn.Dropout(config.dropout)
71
+
72
+ if self.n_heads * self.head_dim != self.hidden_size:
73
+ raise ValueError("hidden_size must equal n_heads * head_dim")
74
+
75
+ # derive n_kv_groups if None
76
+ if config.n_kv_groups is None:
77
+ if self.n_kv_heads == 0:
78
+ raise ValueError("n_kv_heads must be > 0")
79
+ self.n_kv_groups = self.n_heads // self.n_kv_heads
80
+ if self.n_heads % self.n_kv_heads != 0:
81
+ raise ValueError("n_heads must be divisible by n_kv_heads to derive groups")
82
+ else:
83
+ self.n_kv_groups = config.n_kv_groups
84
+ if self.n_kv_heads * self.n_kv_groups != self.n_heads:
85
+ raise ValueError("n_heads must equal n_kv_heads * n_kv_groups")
86
+
87
+ self.q_proj = nn.Linear(self.hidden_size, self.n_heads * self.head_dim, bias=self.attention_bias)
88
+ self.k_proj = nn.Linear(self.hidden_size, self.n_kv_heads * self.head_dim, bias=self.attention_bias)
89
+ self.v_proj = nn.Linear(self.hidden_size, self.n_kv_heads * self.head_dim, bias=self.attention_bias)
90
+ self.w_o = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
91
+ self.rope = RotaryEmbedding(self.head_dim, config.max_position_embeddings)
92
+
93
+ def forward(self, x):
94
+ B, T, _ = x.shape
95
+ device = x.device
96
+ dtype = x.dtype
97
+
98
+ q = self.q_proj(x).view(B, T, self.n_heads, self.head_dim).transpose(1, 2)
99
+ k = self.k_proj(x).view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2)
100
+ v = self.v_proj(x).view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2)
101
+
102
+ cos, sin = self.rope(T, device=device, dtype=dtype)
103
+ q = apply_rotary(q, cos, sin)
104
+ k = apply_rotary(k, cos, sin)
105
+
106
+ if self.n_kv_groups != 1:
107
+ k = k.repeat_interleave(self.n_kv_groups, dim=1)
108
+ v = v.repeat_interleave(self.n_kv_groups, dim=1)
109
+
110
+ scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
111
+
112
+ # causal mask
113
+ mask = torch.triu(torch.full((T, T), float("-inf"), device=device, dtype=dtype), diagonal=1)
114
+ scores = scores + mask.unsqueeze(0).unsqueeze(0)
115
+ attn = torch.softmax(scores, dim=-1)
116
+ attn = self.dropout(attn)
117
+
118
+ out = torch.matmul(attn, v)
119
+ out = out.transpose(1, 2).contiguous().view(B, T, self.hidden_size)
120
+ return self.w_o(out)
121
+
122
+
123
+ class SwiGLUFeedForward(nn.Module):
124
+ def __init__(self, config: ModelConfig):
125
+ super().__init__()
126
+ self.hidden_size = config.hidden_size
127
+ self.intermediate_size = config.intermediate_size
128
+ self.dropout = nn.Dropout(config.dropout)
129
+
130
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size)
131
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size)
132
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size)
133
+ self.act = nn.SiLU()
134
+
135
+ def forward(self, x):
136
+ x = self.act(self.gate_proj(x)) * self.up_proj(x)
137
+ x = self.down_proj(self.dropout(x))
138
+ return x
139
+
140
+
141
+ class TransformerBlock(nn.Module):
142
+ def __init__(self, config: ModelConfig):
143
+ super().__init__()
144
+ self.attention = GroupedMultiQueryAttention(config)
145
+ self.feed_forward = SwiGLUFeedForward(config)
146
+ self.attn_norm = RMSNorm(config)
147
+ self.ffn_norm = RMSNorm(config)
148
+ self.dropout = nn.Dropout(config.dropout)
149
+ self.pre_norm = config.pre_norm
150
+
151
+ def forward(self, x):
152
+ if self.pre_norm:
153
+ x = x + self.dropout(self.attention(self.attn_norm(x)))
154
+ x = x + self.dropout(self.feed_forward(self.ffn_norm(x)))
155
+ else:
156
+ x = self.attn_norm(x + self.dropout(self.attention(x)))
157
+ x = self.ffn_norm(x + self.dropout(self.feed_forward(x)))
158
+ return x
159
+
160
+
161
+ class Transformer(nn.Module):
162
+ def __init__(self, config: ModelConfig):
163
+ super().__init__()
164
+ self.config = config
165
+ self.token_embedding = nn.Embedding(config.vocab_size, config.hidden_size)
166
+ self.blocks = nn.ModuleList([TransformerBlock(config) for _ in range(config.n_layers)])
167
+ self.embedding_dropout = nn.Dropout(config.dropout)
168
+ self.final_norm = RMSNorm(config)
169
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
170
+ if config.tie_weights:
171
+ self.lm_head.weight = self.token_embedding.weight
172
+
173
+ self.apply(self._init_weights)
174
+
175
+ def _init_weights(self, module):
176
+ if isinstance(module, nn.Linear):
177
+ nn.init.normal_(module.weight, mean=0.0, std=0.02 / math.sqrt(max(1, self.config.n_layers)))
178
+ if module.bias is not None:
179
+ nn.init.zeros_(module.bias)
180
+ elif isinstance(module, nn.Embedding):
181
+ nn.init.normal_(module.weight, mean=0.0, std=0.02)
182
+
183
+ def forward(self, input_ids: torch.Tensor, targets: Optional[torch.Tensor] = None):
184
+ x = self.token_embedding(input_ids) * math.sqrt(self.config.hidden_size)
185
+ x = self.embedding_dropout(x)
186
+ for block in self.blocks:
187
+ x = block(x)
188
+ x = self.final_norm(x)
189
+ logits = self.lm_head(x)
190
+ return logits
191
+
192
+ def top_k_top_p_filtering(logits: torch.Tensor, top_k: int = 0, top_p: float = 0.0, filter_value: float = -float('Inf')) -> torch.Tensor:
193
+ """
194
+ Filter a distribution of logits using top-k and/or nucleus (top-p) filtering.
195
+ This is taken from common implementations (Hugging Face transformers style).
196
+ Args:
197
+ logits: logits distribution shape (batch, vocab)
198
+ top_k: keep only top k tokens with highest probability (0 = no top-k)
199
+ top_p: keep the top tokens with cumulative probability >= top_p (0.0 = no nucleus)
200
+ filter_value: value to set for filtered logits
201
+ Returns:
202
+ filtered logits with the same shape
203
+ """
204
+ top_k = max(top_k, 0)
205
+ batch_size, vocab_size = logits.size()
206
+
207
+ if top_k > 0:
208
+ # Remove all tokens with a probability less than the top-k tokens
209
+ top_k = min(max(top_k, 1), vocab_size)
210
+ values_to_keep, _ = torch.topk(logits, top_k)
211
+ min_values = values_to_keep[:, -1].unsqueeze(1).expand_as(logits)
212
+ logits = torch.where(logits < min_values, torch.full_like(logits, filter_value), logits)
213
+
214
+ if top_p > 0.0:
215
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True, dim=-1)
216
+ sorted_probs = F.softmax(sorted_logits, dim=-1)
217
+ cumulative_probs = torch.cumsum(sorted_probs, dim=-1)
218
+
219
+ # Remove tokens with cumulative probability above the threshold
220
+ sorted_mask = cumulative_probs > top_p
221
+
222
+ # Shift the mask right to keep at least one token
223
+ sorted_mask[..., 1:] = sorted_mask[..., :-1].clone()
224
+ sorted_mask[..., 0] = False
225
+
226
+ indices_to_remove = sorted_mask.scatter(1, sorted_indices, sorted_mask)
227
+ logits = logits.masked_fill(indices_to_remove, filter_value)
228
+
229
+ return logits
230
+
231
+
232
+ @torch.no_grad()
233
+ def generate(
234
+ model: Transformer,
235
+ input_ids: torch.LongTensor,
236
+ max_new_tokens: int = 50,
237
+ temperature: float = 1.0,
238
+ top_k: int = 0,
239
+ top_p: float = 0.0,
240
+ do_sample: bool = True,
241
+ eos_token_id: Optional[int] = None,
242
+ pad_token_id: Optional[int] = None,
243
+ device: Optional[torch.device] = None,
244
+ ):
245
+ """
246
+ Autoregressive generation helper for the model. This implementation does NOT use KV cache
247
+ (the model defined in this file does not implement a cache), so generation is performed
248
+ by repeatedly calling the model on the growing sequence. It supports temperature,
249
+ top-k and nucleus (top-p) sampling, greedy decoding, and optional early stopping
250
+ on an `eos_token_id`.
251
+
252
+ Args:
253
+ model: the Transformer instance
254
+ input_ids: (batch, seq_len) input token ids
255
+ max_new_tokens: number of tokens to generate
256
+ temperature: sampling temperature (<=0 or do_sample=False => greedy)
257
+ top_k: top-k filtering (0 disables)
258
+ top_p: nucleus/top-p filtering (0.0 disables)
259
+ do_sample: whether to sample (True) or do greedy decoding (False)
260
+ eos_token_id: optional EOS id to stop generation for individual sequences
261
+ pad_token_id: optional pad id to use for finished sequences
262
+ device: optional torch.device to run on; if None uses model's device
263
+
264
+ Returns:
265
+ tensor of shape (batch, seq_len + generated) with generated tokens appended
266
+ """
267
+ model.eval()
268
+ if device is None:
269
+ # try to infer device
270
+ try:
271
+ device = next(model.parameters()).device
272
+ except StopIteration:
273
+ device = torch.device('cpu')
274
+
275
+ input_ids = input_ids.to(device)
276
+
277
+ batch_size, seq_len = input_ids.shape
278
+ generated = 0
279
+ unfinished = torch.ones(batch_size, dtype=torch.bool, device=device)
280
+
281
+ for _ in range(max_new_tokens):
282
+ logits = model(input_ids)
283
+ # logits shape: (batch, seq_len_total, vocab)
284
+ next_token_logits = logits[:, -1, :]
285
+
286
+ if temperature <= 0 or not do_sample:
287
+ # Greedy
288
+ next_tokens = torch.argmax(next_token_logits, dim=-1)
289
+ else:
290
+ logits_proc = next_token_logits / max(temperature, 1e-8)
291
+ logits_proc = top_k_top_p_filtering(logits_proc, top_k=top_k, top_p=top_p)
292
+ probs = F.softmax(logits_proc, dim=-1)
293
+ next_tokens = torch.multinomial(probs, num_samples=1).squeeze(-1)
294
+
295
+ # If EOS is provided, update finished sequences and pad further tokens
296
+ if eos_token_id is not None:
297
+ is_eos = next_tokens.eq(eos_token_id)
298
+ # sequences that have just finished
299
+ just_finished = unfinished & is_eos
300
+ unfinished = unfinished & (~is_eos)
301
+
302
+ # For sequences already finished, append pad_token_id (if provided), otherwise keep EOS or sampled token
303
+ if pad_token_id is not None and not unfinished.all():
304
+ finished_mask = ~unfinished
305
+ if finished_mask.any():
306
+ next_tokens = next_tokens.masked_fill(finished_mask, pad_token_id)
307
+
308
+ # append
309
+ input_ids = torch.cat([input_ids, next_tokens.unsqueeze(-1)], dim=1)
310
+ generated += 1
311
+
312
+ if eos_token_id is not None and not unfinished.any():
313
+ break
314
+
315
+ return input_ids
316
+
317
+
318
+ def _smoke_test():
319
+ config = ModelConfig(
320
+ vocab_size=128,
321
+ hidden_size=64,
322
+ n_heads=4,
323
+ n_kv_heads=4,
324
+ n_kv_groups=None,
325
+ head_dim=16,
326
+ n_layers=2,
327
+ attention_bias=False,
328
+ intermediate_size=256,
329
+ mlp_bias=False,
330
+ eps=1e-5,
331
+ )
332
+ model = Transformer(config)
333
+ model.eval()
334
+
335
+ batch, seq_len = 2, 8
336
+ input_ids = torch.randint(0, config.vocab_size, (batch, seq_len))
337
+ logits, loss = model(input_ids, targets=input_ids)
338
+
339
+ assert logits.shape == (batch, seq_len, config.vocab_size)
340
+ assert loss.dim() == 0
341
+ print("Smoke test passed: logits shape", logits.shape, "loss", loss.detach().item())
342
+
343
+
344
+ if __name__ == "__main__":
345
+ _smoke_test()
346
+