namanbnsl commited on
Commit
479d404
1 Parent(s): 649b521

Upload model.py

Browse files
Files changed (1) hide show
  1. model.py +406 -0
model.py ADDED
@@ -0,0 +1,406 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ import math
5
+
6
+ from dataclasses import dataclass
7
+ from typing import Optional, Tuple
8
+
9
+ import tiktoken
10
+ import os
11
+ import numpy as np
12
+
13
+ torch.set_float32_matmul_precision('high')
14
+
15
+ def load_tokens(filename):
16
+ npt = np.load(filename)
17
+ npt = npt.astype(np.int32) # added after video
18
+ ptt = torch.tensor(npt, dtype=torch.long)
19
+ return ptt
20
+
21
+ class DataLoaderLite:
22
+ def __init__(self, B, T, split):
23
+ self.B = B
24
+ self.T = T
25
+ assert split in {'train', 'val'}
26
+
27
+ # get the shard filenames
28
+ data_root = "tinystories"
29
+ shards = os.listdir(data_root)
30
+ shards = [s for s in shards if split in s]
31
+ shards = sorted(shards)
32
+ shards = [os.path.join(data_root, s) for s in shards]
33
+ self.shards = shards
34
+ assert len(shards) > 0, f"no shards found for split {split}"
35
+ print(f"found {len(shards)} shards for split {split}")
36
+ self.reset()
37
+
38
+ def reset(self):
39
+ # state, init at shard zero
40
+ self.current_shard = 0
41
+ self.tokens = load_tokens(self.shards[self.current_shard])
42
+ self.current_position = self.B * self.T
43
+
44
+ def next_batch(self):
45
+ B, T = self.B, self.T
46
+ buf = self.tokens[self.current_position : self.current_position+B*T+1]
47
+ x = (buf[:-1]).view(B, T) # inputs
48
+ y = (buf[1:]).view(B, T) # targets
49
+ # advance the position in the tensor
50
+ self.current_position += B * T
51
+ # if loading the next batch would be out of bounds, advance to next shard
52
+ if self.current_position + (B * T ) > len(self.tokens):
53
+ self.current_shard = (self.current_shard + 1) % len(self.shards)
54
+ self.tokens = load_tokens(self.shards[self.current_shard])
55
+ self.current_position = B * T
56
+ return x, y
57
+
58
+ @dataclass # the hyperparameters
59
+ class ModelArgs:
60
+ dim: int = 768
61
+ n_layers: int = 16
62
+ n_heads: int = 16
63
+ n_kv_heads: Optional[int] = 4
64
+ vocab_size: int = 50304
65
+ multiple_of: int = 256
66
+ ffn_dim_multiplier: Optional[float] = None
67
+ norm_eps: float = 1e-5
68
+ rope_theta: float = 50000
69
+ max_batch_size: int = 4
70
+ max_seq_len: int = 1024
71
+ device: str = 'cuda' if torch.cuda.is_available() else 'cpu'
72
+ dropout_rate: float = 0.1
73
+
74
+ params = ModelArgs()
75
+
76
+ class RMSNorm(torch.nn.Module):
77
+ def __init__(self, dim: int, eps: float = 1e-6):
78
+ super().__init__()
79
+ self.eps = eps
80
+ self.weight = nn.Parameter(torch.ones(dim))
81
+
82
+ def _norm(self, x):
83
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
84
+
85
+ def forward(self, x):
86
+ output = self._norm(x.float()).type_as(x)
87
+ return output * self.weight
88
+
89
+
90
+ def precompute_freqs_cis(dim: int, end: int, theta: float = 10000.0):
91
+ freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
92
+ t = torch.arange(end, device=freqs.device, dtype=torch.float32)
93
+ freqs = torch.outer(t, freqs)
94
+ freqs_cis = torch.polar(torch.ones_like(freqs), freqs) # complex64
95
+ return freqs_cis.to(params.device)
96
+
97
+ def reshape_for_broadcast(freqs_cis: torch.Tensor, x: torch.Tensor):
98
+ ndim = x.ndim
99
+ assert 0 <= 1 < ndim
100
+ assert freqs_cis.shape == (x.shape[1], x.shape[-1]), f'freqs_cis.shape {freqs_cis.shape} != (x.shape[1], x.shape[-1]) {(x.shape[1], x.shape[-1])}'
101
+ shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)]
102
+ return freqs_cis.view(*shape)
103
+
104
+ def apply_rotary_emb(
105
+ xq: torch.Tensor,
106
+ xk: torch.Tensor,
107
+ freqs_cis: torch.Tensor,
108
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
109
+ xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
110
+ xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
111
+ freqs_cis = reshape_for_broadcast(freqs_cis, xq_)
112
+ xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3)
113
+ xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3)
114
+ return xq_out.type_as(xq), xk_out.type_as(xk)
115
+
116
+ def repeat_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor:
117
+ """torch.repeat_interleave(x, dim=2, repeats=n_rep)"""
118
+ bs, seqlen, n_kv_heads, head_dim = x.shape
119
+ if n_rep == 1:
120
+ return x
121
+ return (
122
+ x[:, :, :, None, :]
123
+ .expand(bs, seqlen, n_kv_heads, n_rep, head_dim)
124
+ .reshape(bs, seqlen, n_kv_heads * n_rep, head_dim)
125
+ )
126
+
127
+ class Attention(nn.Module):
128
+ def __init__(self, args: ModelArgs):
129
+ super().__init__()
130
+ self.n_heads = args.n_heads
131
+ self.n_kv_heads = args.n_heads if args.n_kv_heads is None else args.n_kv_heads
132
+ self.n_rep = args.n_heads // self.n_kv_heads
133
+ self.head_dim = args.dim // args.n_heads
134
+
135
+ self.wq = nn.Linear(args.dim, args.n_heads * self.head_dim, bias=False)
136
+ self.wk = nn.Linear(args.dim, self.n_kv_heads * self.head_dim, bias=False)
137
+ self.wv = nn.Linear(args.dim, self.n_kv_heads * self.head_dim, bias=False)
138
+ self.wo = nn.Linear(args.n_heads * self.head_dim, args.dim, bias=False)
139
+
140
+ self.cache_k = torch.zeros(
141
+ (args.max_batch_size, args.max_seq_len, self.n_kv_heads, self.head_dim),
142
+ requires_grad = False
143
+ ).to(args.device)
144
+ self.cache_v = torch.zeros(
145
+ (args.max_batch_size, args.max_seq_len, self.n_kv_heads, self.head_dim),
146
+ requires_grad = False
147
+ ).to(args.device)
148
+
149
+ def forward(
150
+ self,
151
+ x: torch.Tensor,
152
+ freqs_cis: torch.Tensor,
153
+ mask: Optional[torch.Tensor],
154
+ start_pos: int = None,
155
+ ):
156
+ bsz, seqlen, _ = x.shape
157
+ xq, xk, xv = self.wq(x), self.wk(x), self.wv(x)
158
+
159
+ xq = xq.view(bsz, seqlen, self.n_heads, self.head_dim)
160
+ xk = xk.view(bsz, seqlen, self.n_kv_heads, self.head_dim)
161
+ xv = xv.view(bsz, seqlen, self.n_kv_heads, self.head_dim)
162
+
163
+ xq, xk = apply_rotary_emb(xq, xk, freqs_cis=freqs_cis)
164
+
165
+ if start_pos is not None: # if we're performing inference, use kv caching
166
+ self.cache_k = self.cache_k.to(xq)
167
+ self.cache_v = self.cache_v.to(xq)
168
+
169
+ # set the values in our cache according to the current input
170
+ self.cache_k[:bsz, start_pos : start_pos + seqlen] = xk
171
+ self.cache_v[:bsz, start_pos : start_pos + seqlen] = xv
172
+
173
+ # grab our key and value matrixes which have a longer sequence length than our queries
174
+ keys = self.cache_k[:bsz, : start_pos + seqlen]
175
+ values = self.cache_v[:bsz, : start_pos + seqlen]
176
+ else:
177
+ # if we're training, do full sequence length
178
+ keys, values = xk, xv
179
+
180
+ keys = repeat_kv(keys, self.n_rep)
181
+ values = repeat_kv(values, self.n_rep)
182
+
183
+ xq = xq.transpose(1, 2)
184
+ keys = keys.transpose(1, 2)
185
+ values = values.transpose(1, 2)
186
+
187
+ scores = torch.matmul(xq, keys.transpose(2, 3)) / math.sqrt(self.head_dim)
188
+ if mask is not None:
189
+ scores = scores + mask
190
+ scores = F.softmax(scores.float(), dim=-1).type_as(xq)
191
+
192
+ output = torch.matmul(scores, values)
193
+ output = output.transpose(1, 2).contiguous().view(bsz, seqlen, -1)
194
+ return self.wo(output)
195
+
196
+ class FeedForward(nn.Module):
197
+ def __init__(
198
+ self,
199
+ dim: int,
200
+ hidden_dim: int,
201
+ multiple_of: int,
202
+ ffn_dim_multiplier: Optional[float],
203
+ ):
204
+ super().__init__()
205
+ # custom dim factor multiplier that ensures we're using a multiple of "multiple_of" for hardware efficiency reasons
206
+ hidden_dim = int(2 * hidden_dim / 3)
207
+ if ffn_dim_multiplier is not None:
208
+ hidden_dim = int(ffn_dim_multiplier * hidden_dim)
209
+ hidden_dim = multiple_of * ((hidden_dim + multiple_of - 1) // multiple_of)
210
+
211
+ self.w1 = nn.Linear(dim, hidden_dim, bias=False)
212
+ self.w2 = nn.Linear(hidden_dim, dim, bias=False)
213
+ self.w3 = nn.Linear(dim, hidden_dim, bias=False)
214
+
215
+ def forward(self, x):
216
+ return self.w2(F.silu(self.w1(x)) * self.w3(x))
217
+
218
+ class TransformerBlock(nn.Module):
219
+ def __init__(self, args: ModelArgs):
220
+ super().__init__()
221
+ self.n_heads = args.n_heads
222
+ self.dim = args.dim
223
+ self.head_dim = args.dim // args.n_heads
224
+ self.attention = Attention(args)
225
+ self.feed_forward = FeedForward(
226
+ dim=args.dim,
227
+ hidden_dim=4 * args.dim,
228
+ multiple_of=args.multiple_of,
229
+ ffn_dim_multiplier=args.ffn_dim_multiplier,
230
+ )
231
+ self.attention_norm = RMSNorm(args.dim, eps=args.norm_eps)
232
+ self.ffn_norm = RMSNorm(args.dim, eps=args.norm_eps)
233
+ self.dropout_rate = args.dropout_rate
234
+
235
+ def forward(
236
+ self,
237
+ x: torch.Tensor,
238
+ freqs_cis: torch.Tensor,
239
+ mask: Optional[torch.Tensor],
240
+ start_pos: int = None,
241
+ training = False,
242
+ ):
243
+ h = x + F.dropout(self.attention(self.attention_norm(x), freqs_cis, mask, start_pos), p=self.dropout_rate, training=training)
244
+ out = h + F.dropout(self.feed_forward(self.ffn_norm(h)), p=self.dropout_rate, training=training)
245
+ return out
246
+
247
+ class Moose(nn.Module):
248
+ def __init__(self, params: ModelArgs):
249
+ super().__init__()
250
+ self.params = params
251
+ self.vocab_size = params.vocab_size
252
+ self.n_layers = params.n_layers
253
+ self.max_seq_len = params.max_seq_len
254
+
255
+ self.tok_embeddings = nn.Embedding(params.vocab_size, params.dim)
256
+
257
+ self.layers = torch.nn.ModuleList()
258
+ for _ in range(params.n_layers):
259
+ self.layers.append(TransformerBlock(params))
260
+
261
+ self.norm = RMSNorm(params.dim, eps=params.norm_eps)
262
+ self.output = nn.Linear(
263
+ params.dim,
264
+ params.vocab_size,
265
+ bias=False)
266
+
267
+ self.freqs_cis = precompute_freqs_cis(
268
+ params.dim // params.n_heads,
269
+ params.max_seq_len * 2,
270
+ params.rope_theta,)
271
+
272
+ # precompute the causal attention mask
273
+ mask = torch.full((params.max_seq_len, params.max_seq_len),
274
+ float("-inf"),
275
+ device=params.device)
276
+ mask = torch.triu(mask, diagonal=1)
277
+ self.register_buffer('mask', mask)
278
+
279
+ self.criterion = nn.CrossEntropyLoss()
280
+
281
+ def forward(self,
282
+ tokens: torch.Tensor,
283
+ targets: torch.Tensor):
284
+ bsz, seqlen = tokens.shape
285
+ assert tokens.shape == targets.shape
286
+ assert seqlen == self.max_seq_len
287
+
288
+ h = self.tok_embeddings(tokens)
289
+
290
+ freqs_cis = self.freqs_cis.to(h.device)
291
+ freqs_cis = self.freqs_cis[:seqlen]
292
+
293
+ for layer in self.layers:
294
+ h = layer(
295
+ h,
296
+ freqs_cis,
297
+ self.mask,
298
+ start_pos = None,
299
+ training = True
300
+ )
301
+
302
+ h = self.norm(h)
303
+ logits = self.output(h).float()
304
+
305
+ loss = self.criterion(
306
+ logits.view(bsz * seqlen, self.vocab_size),
307
+ targets.reshape(bsz * seqlen))
308
+
309
+ return logits, loss
310
+
311
+ @torch.inference_mode()
312
+ def forward_inference(self,
313
+ tokens: torch.Tensor,
314
+ start_pos: int,
315
+ max_context_window: int,
316
+ ):
317
+ _bsz, seqlen = tokens.shape
318
+ h = self.tok_embeddings(tokens)
319
+ self.freqs_cis = self.freqs_cis.to(h.device)
320
+ freqs_cis = self.freqs_cis[start_pos : start_pos + seqlen]
321
+
322
+ mask = self.mask[:seqlen, :seqlen]
323
+ mask = torch.hstack(
324
+ [torch.zeros((seqlen, start_pos), device=tokens.device), mask]
325
+ ).type_as(h)
326
+
327
+ for layer in self.layers:
328
+ h = layer(
329
+ h,
330
+ freqs_cis,
331
+ mask,
332
+ start_pos = start_pos
333
+ )
334
+ h = self.norm(h)
335
+ logits = self.output(h).float()
336
+ return logits
337
+
338
+ @torch.inference_mode()
339
+ def Sampler(
340
+ self,
341
+ logits: torch.Tensor,
342
+ temperature: float,
343
+ top_p: float
344
+ ) -> torch.Tensor:
345
+ logits = logits[:,-1,:]
346
+
347
+ logits.div_(temperature)
348
+
349
+ probs = torch.softmax(logits, dim=-1, dtype=torch.float)
350
+
351
+ probs_sort, probs_idx = torch.sort(probs, dim=-1, descending=True)
352
+
353
+ probs_sum = torch.cumsum(probs_sort, dim=-1)
354
+ top_ps_mask = (probs_sum - probs_sort) > top_p
355
+ probs_sort = torch.where(top_ps_mask, 0, probs_sort)
356
+ probs_sort.div_(probs_sort.sum(dim=-1, keepdim=True))
357
+ probs = torch.gather(probs_sort, dim=-1, index=torch.argsort(probs_idx, dim=-1))
358
+ next_token_id = torch.multinomial(probs, num_samples=1)
359
+
360
+ return next_token_id
361
+
362
+ @torch.inference_mode()
363
+ def generate(
364
+ self,
365
+ prompt: str,
366
+ max_gen_len: int = 100,
367
+ memory_saver_div: int = 1,
368
+ temperature: float = 0.6,
369
+ top_p: float = 0.9,
370
+ ) -> str:
371
+ assert ((memory_saver_div & (memory_saver_div-1)) == 0) & (memory_saver_div > 0), f'memory_saver_div {memory_saver_div} must be power of 2'
372
+ max_context_window = self.max_seq_len // memory_saver_div
373
+
374
+ enc = tiktoken.get_encoding('gpt2')
375
+ tokens = enc.encode(prompt)
376
+
377
+ tokens = torch.tensor(tokens, device=self.params.device)
378
+ tokens = tokens.unsqueeze(0) if len(tokens.shape)==1 else tokens
379
+
380
+ start_pos = max(tokens.shape[1] - max_context_window, 0)
381
+ eot = enc._special_tokens['<|endoftext|>'] # end of text token
382
+
383
+ while True:
384
+ logits = self.forward_inference(
385
+ tokens[:,-max_context_window:],
386
+ start_pos = start_pos,
387
+ max_context_window = max_context_window
388
+ )
389
+
390
+ next_token = self.Sampler(
391
+ logits = logits,
392
+ temperature = temperature,
393
+ top_p = top_p,
394
+ )
395
+
396
+ tokens = torch.cat((tokens, next_token), dim=1)
397
+
398
+ if next_token.item() == eot:
399
+ break
400
+
401
+ if tokens.shape[1] >= max_context_window:
402
+ start_pos += 1
403
+
404
+ output = enc.decode(tokens.squeeze(0).tolist())
405
+
406
+ return output