sohv commited on
Commit
8ad8b73
·
verified ·
1 Parent(s): 7ec2f3b

Upload src/model.py

Browse files
Files changed (1) hide show
  1. src/model.py +341 -0
src/model.py ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Kimi-K2 Model Implementation for nanoKimi
3
+
4
+ This is the main model implementation that combines all the Kimi-K2 innovations:
5
+ - Latent Attention for memory efficiency
6
+ - Mixture of Experts for sparse scaling
7
+ - Compatible with Muon optimizer
8
+ """
9
+
10
+ import torch
11
+ import torch.nn as nn
12
+ import torch.nn.functional as F
13
+ import math
14
+ import inspect
15
+
16
+ from attention import LatentAttention, MultiHeadAttention
17
+ from moe import MoELayer, StandardFFN
18
+
19
+
20
+ class LayerNorm(nn.Module):
21
+ """LayerNorm but with an optional bias. PyTorch doesn't support simply bias=False"""
22
+
23
+ def __init__(self, ndim, bias):
24
+ super().__init__()
25
+ self.weight = nn.Parameter(torch.ones(ndim))
26
+ self.bias = nn.Parameter(torch.zeros(ndim)) if bias else None
27
+
28
+ def forward(self, input):
29
+ return F.layer_norm(input, self.weight.shape, self.weight, self.bias, 1e-5)
30
+
31
+
32
+ class KimiBlock(nn.Module):
33
+ """
34
+ Kimi-K2 Transformer Block
35
+
36
+ Combines the innovations of Kimi-K2:
37
+ - Latent Attention (optional)
38
+ - Mixture of Experts (optional)
39
+ - Standard layer normalization and residual connections
40
+ """
41
+
42
+ def __init__(self, config):
43
+ super().__init__()
44
+
45
+ # Layer normalization
46
+ self.ln_1 = LayerNorm(config['n_embd'], bias=config['bias'])
47
+ self.ln_2 = LayerNorm(config['n_embd'], bias=config['bias'])
48
+
49
+ # Attention layer
50
+ if config.get('use_latent_attention', False):
51
+ self.attn = LatentAttention(
52
+ n_embd=config['n_embd'],
53
+ n_head=config['n_head'],
54
+ latent_dim=config.get('latent_dim', 64),
55
+ dropout=config['dropout'],
56
+ bias=config['bias']
57
+ )
58
+ else:
59
+ self.attn = MultiHeadAttention(
60
+ n_embd=config['n_embd'],
61
+ n_head=config['n_head'],
62
+ dropout=config['dropout'],
63
+ bias=config['bias']
64
+ )
65
+
66
+ # Feed-forward layer
67
+ if config.get('use_moe', False):
68
+ self.mlp = MoELayer(
69
+ n_embd=config['n_embd'],
70
+ num_experts=config.get('num_experts', 8),
71
+ expert_capacity=config.get('expert_capacity', 32),
72
+ top_k=config.get('top_k_experts', 2),
73
+ dropout=config['dropout'],
74
+ bias=config['bias']
75
+ )
76
+ else:
77
+ self.mlp = StandardFFN(
78
+ n_embd=config['n_embd'],
79
+ dropout=config['dropout'],
80
+ bias=config['bias']
81
+ )
82
+
83
+ def forward(self, x):
84
+ # Attention with residual connection
85
+ x = x + self.attn(self.ln_1(x))
86
+
87
+ # MLP with residual connection
88
+ mlp_out, load_balance_loss = self.mlp(self.ln_2(x))
89
+ x = x + mlp_out
90
+
91
+ return x, load_balance_loss
92
+
93
+
94
+ class KimiK2(nn.Module):
95
+ """
96
+ Kimi-K2 Model
97
+
98
+ A transformer model incorporating the key innovations from Kimi-K2:
99
+ - Latent Attention for memory efficiency
100
+ - Mixture of Experts for sparse scaling
101
+ - Optimized for use with Muon optimizer
102
+ """
103
+
104
+ def __init__(self, config):
105
+ super().__init__()
106
+ assert config['vocab_size'] is not None
107
+ assert config['block_size'] is not None
108
+ self.config = config
109
+
110
+ # Embedding layers
111
+ self.transformer = nn.ModuleDict(dict(
112
+ wte = nn.Embedding(config['vocab_size'], config['n_embd']), # token embeddings
113
+ wpe = nn.Embedding(config['block_size'], config['n_embd']), # position embeddings
114
+ drop = nn.Dropout(config['dropout']),
115
+ h = nn.ModuleList([KimiBlock(config) for _ in range(config['n_layer'])]),
116
+ ln_f = LayerNorm(config['n_embd'], bias=config['bias']),
117
+ ))
118
+ self.lm_head = nn.Linear(config['n_embd'], config['vocab_size'], bias=False)
119
+
120
+ # Weight tying
121
+ self.transformer.wte.weight = self.lm_head.weight
122
+
123
+ # Initialize weights
124
+ self.apply(self._init_weights)
125
+
126
+ # Apply special scaled init to the residual projections, per GPT-2 paper
127
+ for pn, p in self.named_parameters():
128
+ if pn.endswith('o_proj.weight'):
129
+ torch.nn.init.normal_(p, mean=0.0, std=0.02/math.sqrt(2 * config['n_layer']))
130
+
131
+ # Report number of parameters
132
+ print("Number of parameters: %.2fM" % (self.get_num_params()/1e6,))
133
+
134
+ def get_num_params(self, non_embedding=True):
135
+ """
136
+ Return the number of parameters in the model.
137
+ For non-embedding count (default), the position embeddings get subtracted.
138
+ The token embeddings would too, except due to the parameter sharing these
139
+ params are actually used as weights in the final layer, so we include them.
140
+ """
141
+ n_params = sum(p.numel() for p in self.parameters())
142
+ if non_embedding:
143
+ n_params -= self.transformer.wpe.weight.numel()
144
+ return n_params
145
+
146
+ def _init_weights(self, module):
147
+ if isinstance(module, nn.Linear):
148
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
149
+ if module.bias is not None:
150
+ torch.nn.init.zeros_(module.bias)
151
+ elif isinstance(module, nn.Embedding):
152
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
153
+
154
+ def forward(self, idx, targets=None):
155
+ device = idx.device
156
+ b, t = idx.size()
157
+ assert t <= self.config['block_size'], f"Cannot forward sequence of length {t}, block size is only {self.config['block_size']}"
158
+ pos = torch.arange(0, t, dtype=torch.long, device=device) # shape (t)
159
+
160
+ # Forward the model
161
+ tok_emb = self.transformer.wte(idx) # token embeddings of shape (b, t, n_embd)
162
+ pos_emb = self.transformer.wpe(pos) # position embeddings of shape (t, n_embd)
163
+ x = self.transformer.drop(tok_emb + pos_emb)
164
+
165
+ # Accumulate load balance losses from MoE layers
166
+ total_load_balance_loss = 0.0
167
+
168
+ for block in self.transformer.h:
169
+ x, load_balance_loss = block(x)
170
+ total_load_balance_loss += load_balance_loss
171
+
172
+ x = self.transformer.ln_f(x)
173
+
174
+ if targets is not None:
175
+ # If we are given some desired targets also calculate the loss
176
+ logits = self.lm_head(x)
177
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1)
178
+
179
+ # Add load balance loss
180
+ loss = loss + total_load_balance_loss
181
+ else:
182
+ # Inference-time mini-optimization: only forward the lm_head on the very last position
183
+ logits = self.lm_head(x[:, [-1], :]) # note: using list [-1] to preserve the time dim
184
+ loss = None
185
+
186
+ return logits, loss
187
+
188
+ def crop_block_size(self, block_size):
189
+ # model surgery to decrease the block size if necessary
190
+ # e.g. we may load the GPT2 pretrained model checkpoint (block size 1024)
191
+ # but want to use a smaller block size for some smaller, simpler model
192
+ assert block_size <= self.config['block_size']
193
+ self.config['block_size'] = block_size
194
+ self.transformer.wpe.weight = nn.Parameter(self.transformer.wpe.weight[:block_size])
195
+ for block in self.transformer.h:
196
+ if hasattr(block.attn, 'bias'):
197
+ block.attn.bias = block.attn.bias[:,:,:block_size,:block_size]
198
+
199
+ @classmethod
200
+ def from_pretrained(cls, model_type, override_args=None):
201
+ """
202
+ Initialize a pretrained GPT model by copying over the weights
203
+ from a huggingface/transformers checkpoint.
204
+ """
205
+ assert model_type in {'gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'}
206
+ override_args = override_args or {} # default to empty dict
207
+ # only dropout can be overridden see more notes below
208
+ assert all(k == 'dropout' for k in override_args)
209
+ from transformers import GPT2LMHeadModel
210
+ print("loading weights from pretrained gpt: %s" % model_type)
211
+
212
+ # n_layer, n_head and n_embd are determined from model_type
213
+ config_args = {
214
+ 'gpt2': dict(n_layer=12, n_head=12, n_embd=768), # 124M params
215
+ 'gpt2-medium': dict(n_layer=24, n_head=16, n_embd=1024), # 350M params
216
+ 'gpt2-large': dict(n_layer=36, n_head=20, n_embd=1280), # 774M params
217
+ 'gpt2-xl': dict(n_layer=48, n_head=25, n_embd=1600), # 1558M params
218
+ }[model_type]
219
+ print("forcing vocab_size=50257, block_size=1024, bias=True")
220
+ config_args['vocab_size'] = 50257 # always 50257 for GPT model checkpoints
221
+ config_args['block_size'] = 1024 # always 1024 for GPT model checkpoints
222
+ config_args['bias'] = True # always True for GPT model checkpoints
223
+ # we can override the dropout rate, if desired
224
+ if 'dropout' in override_args:
225
+ print(f"overriding dropout rate to {override_args['dropout']}")
226
+ config_args['dropout'] = override_args['dropout']
227
+
228
+ # create a from-scratch initialized KimiK2 model
229
+ model = cls(config_args)
230
+ sd = model.state_dict()
231
+ sd_keys = sd.keys()
232
+ sd_keys = [k for k in sd_keys if not k.endswith('.attn.bias')] # discard this mask / buffer, not a param
233
+
234
+ # init a huggingface/transformers model
235
+ model_hf = GPT2LMHeadModel.from_pretrained(model_type)
236
+ sd_hf = model_hf.state_dict()
237
+
238
+ # copy while ensuring all of the parameters are aligned and match in names and shapes
239
+ sd_keys_hf = sd_hf.keys()
240
+ sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.masked_bias')] # ignore these, just a buffer
241
+ sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.bias')] # same, just the mask (buffer)
242
+ transposed = ['attn.c_attn.weight', 'attn.c_proj.weight', 'mlp.c_fc.weight', 'mlp.c_proj.weight']
243
+ # basically the openai checkpoints use a "Conv1D" module, but we only want to use a vanilla Linear
244
+ # this means that we have to transpose these weights when we import them
245
+ assert len(sd_keys_hf) == len(sd_keys), f"mismatched keys: {len(sd_keys_hf)} != {len(sd_keys)}"
246
+ for k in sd_keys_hf:
247
+ if any(k.endswith(w) for w in transposed):
248
+ # special treatment for the Conv1D weights we need to transpose
249
+ assert sd_hf[k].shape[::-1] == sd[k].shape
250
+ with torch.no_grad():
251
+ sd[k].copy_(sd_hf[k].t())
252
+ else:
253
+ # vanilla copy over the other parameters
254
+ assert sd_hf[k].shape == sd[k].shape
255
+ with torch.no_grad():
256
+ sd[k].copy_(sd_hf[k])
257
+
258
+ return model
259
+
260
+ def configure_optimizers(self, weight_decay, learning_rate, betas, device_type):
261
+ """
262
+ This long function is unfortunately doing something very simple and is being very defensive:
263
+ We are separating out all parameters of the model into two buckets: those that will experience
264
+ weight decay for regularization and those that won't (biases, and layernorm/embedding weights).
265
+ We are then returning the PyTorch optimizer object.
266
+ """
267
+
268
+ # separate out all parameters to those that will and won't experience regularizing weight decay
269
+ decay = set()
270
+ no_decay = set()
271
+ whitelist_weight_modules = (torch.nn.Linear, )
272
+ blacklist_weight_modules = (torch.nn.LayerNorm, LayerNorm, torch.nn.Embedding)
273
+ for mn, m in self.named_modules():
274
+ for pn, p in m.named_parameters():
275
+ fpn = '%s.%s' % (mn, pn) if mn else pn # full param name
276
+ # random note: because named_modules and named_parameters are recursive
277
+ # we will see the same tensors p many times. but doing it this way
278
+ # allows us to know which parent module any tensor p belongs to...
279
+ if pn.endswith('bias'):
280
+ # all biases will not be decayed
281
+ no_decay.add(fpn)
282
+ elif pn.endswith('weight') and isinstance(m, whitelist_weight_modules):
283
+ # weights of whitelist modules will be weight decayed
284
+ decay.add(fpn)
285
+ elif pn.endswith('weight') and isinstance(m, blacklist_weight_modules):
286
+ # weights of blacklist modules will NOT be weight decayed
287
+ no_decay.add(fpn)
288
+
289
+ # subtle: 'transformer.wte.weight' and 'lm_head.weight' are tied, so they
290
+ # will appear in the no_decay and decay sets respectively after the above.
291
+ # In addition, because named_parameters() doesn't return duplicates, it
292
+ # will only return the first occurence, key'd by 'transformer.wte.weight', below.
293
+ # so let's manually remove 'lm_head.weight' from decay set. This will leave us with
294
+ # transformer.wte.weight decaying via no_decay set.
295
+ decay.discard('lm_head.weight')
296
+
297
+ # validate that we considered every parameter
298
+ param_dict = {pn: p for pn, p in self.named_parameters()}
299
+ inter_params = decay & no_decay
300
+ union_params = decay | no_decay
301
+ assert len(inter_params) == 0, "parameters %s made it into both decay/no_decay sets!" % (str(inter_params), )
302
+ assert len(param_dict.keys() - union_params) == 0, "parameters %s were not separated into either decay/no_decay set!" \
303
+ % (str(param_dict.keys() - union_params), )
304
+
305
+ # create the pytorch optimizer object
306
+ optim_groups = [
307
+ {"params": [param_dict[pn] for pn in sorted(list(decay))], "weight_decay": weight_decay},
308
+ {"params": [param_dict[pn] for pn in sorted(list(no_decay))], "weight_decay": 0.0},
309
+ ]
310
+ # new PyTorch nightly has a new 'fused' option for AdamW that is much faster
311
+ use_fused = (device_type == 'cuda') and ('fused' in inspect.signature(torch.optim.AdamW).parameters)
312
+ print(f"using fused AdamW: {use_fused}")
313
+ optimizer = torch.optim.AdamW(optim_groups, lr=learning_rate, betas=betas, fused=use_fused)
314
+ return optimizer
315
+
316
+ @torch.no_grad()
317
+ def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None):
318
+ """
319
+ Take a conditioning sequence of indices idx (LongTensor of shape (b,t)) and complete
320
+ the sequence max_new_tokens times, feeding the predictions back into the model each time.
321
+ Most likely you'll want to make sure to be in model.eval() mode of operation for this.
322
+ """
323
+ for _ in range(max_new_tokens):
324
+ # if the sequence context is growing too long we must crop it at block_size
325
+ idx_cond = idx if idx.size(1) <= self.config['block_size'] else idx[:, -self.config['block_size']:]
326
+ # forward the model to get the logits for the index in the sequence
327
+ logits, _ = self(idx_cond)
328
+ # pluck the logits at the final step and scale by desired temperature
329
+ logits = logits[:, -1, :] / temperature
330
+ # optionally crop the logits to only the top k options
331
+ if top_k is not None:
332
+ v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
333
+ logits[logits < v[:, [-1]]] = -float('Inf')
334
+ # apply softmax to convert logits to (normalized) probabilities
335
+ probs = F.softmax(logits, dim=-1)
336
+ # sample from the distribution
337
+ idx_next = torch.multinomial(probs, num_samples=1)
338
+ # append sampled index to the running sequence and continue
339
+ idx = torch.cat((idx, idx_next), dim=1)
340
+
341
+ return idx