AYYasaswini commited on
Commit
4a5a9f1
·
verified ·
1 Parent(s): 22a02b7

Upload gpt_dev.py

Browse files
Files changed (1) hide show
  1. gpt_dev.py +525 -0
gpt_dev.py ADDED
@@ -0,0 +1,525 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """gpt_dev.ipynb
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1zxxLfIi8_EDLqYODY8TyNLpr8RTxV-Ct
8
+
9
+ ## Building a GPT
10
+
11
+ Companion notebook to the [Zero To Hero](https://karpathy.ai/zero-to-hero.html) video on GPT.
12
+ """
13
+
14
+ # We always start with a dataset to train on. Let's download the tiny shakespeare dataset
15
+ !wget https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt
16
+
17
+ # read it in to inspect it
18
+ with open('input.txt', 'r', encoding='utf-8') as f:
19
+ text = f.read()
20
+
21
+ print("length of dataset in characters: ", len(text))
22
+
23
+ # let's look at the first 1000 characters
24
+ print(text[:1000])
25
+
26
+ # here are all the unique characters that occur in this text
27
+ chars = sorted(list(set(text)))
28
+ vocab_size = len(chars)
29
+ print(''.join(chars))
30
+ print(vocab_size)
31
+
32
+ # create a mapping from characters to integers
33
+ stoi = { ch:i for i,ch in enumerate(chars) }
34
+ itos = { i:ch for i,ch in enumerate(chars) }
35
+ encode = lambda s: [stoi[c] for c in s] # encoder: take a string, output a list of integers
36
+ decode = lambda l: ''.join([itos[i] for i in l]) # decoder: take a list of integers, output a string
37
+
38
+ print(encode("hii there"))
39
+ print(decode(encode("hii there")))
40
+
41
+ # let's now encode the entire text dataset and store it into a torch.Tensor
42
+ import torch # we use PyTorch: https://pytorch.org
43
+ data = torch.tensor(encode(text), dtype=torch.long)
44
+ print(data.shape, data.dtype)
45
+ print(data[:1000]) # the 1000 characters we looked at earier will to the GPT look like this
46
+
47
+ # Let's now split up the data into train and validation sets
48
+ n = int(0.9*len(data)) # first 90% will be train, rest val
49
+ train_data = data[:n]
50
+ val_data = data[n:]
51
+
52
+ block_size = 8
53
+ train_data[:block_size+1]
54
+
55
+ x = train_data[:block_size]
56
+ y = train_data[1:block_size+1]
57
+ for t in range(block_size):
58
+ context = x[:t+1]
59
+ target = y[t]
60
+ print(f"when input is {context} the target: {target}")
61
+
62
+ torch.manual_seed(1337)
63
+ batch_size = 4 # how many independent sequences will we process in parallel?
64
+ block_size = 8 # what is the maximum context length for predictions?
65
+
66
+ def get_batch(split):
67
+ # generate a small batch of data of inputs x and targets y
68
+ data = train_data if split == 'train' else val_data
69
+ ix = torch.randint(len(data) - block_size, (batch_size,))
70
+ x = torch.stack([data[i:i+block_size] for i in ix])
71
+ y = torch.stack([data[i+1:i+block_size+1] for i in ix])
72
+ return x, y
73
+
74
+ xb, yb = get_batch('train')
75
+ print('inputs:')
76
+ print(xb.shape)
77
+ print(xb)
78
+ print('targets:')
79
+ print(yb.shape)
80
+ print(yb)
81
+
82
+ print('----')
83
+
84
+ for b in range(batch_size): # batch dimension
85
+ for t in range(block_size): # time dimension
86
+ context = xb[b, :t+1]
87
+ target = yb[b,t]
88
+ print(f"when input is {context.tolist()} the target: {target}")
89
+
90
+ print(xb) # our input to the transformer
91
+
92
+ import torch
93
+ import torch.nn as nn
94
+ from torch.nn import functional as F
95
+ torch.manual_seed(1337)
96
+
97
+ class BigramLanguageModel(nn.Module):
98
+
99
+ def __init__(self, vocab_size):
100
+ super().__init__()
101
+ # each token directly reads off the logits for the next token from a lookup table
102
+ self.token_embedding_table = nn.Embedding(vocab_size, vocab_size)
103
+
104
+ def forward(self, idx, targets=None):
105
+
106
+ # idx and targets are both (B,T) tensor of integers
107
+ logits = self.token_embedding_table(idx) # (B,T,C)
108
+
109
+ if targets is None:
110
+ loss = None
111
+ else:
112
+ B, T, C = logits.shape
113
+ logits = logits.view(B*T, C)
114
+ targets = targets.view(B*T)
115
+ loss = F.cross_entropy(logits, targets)
116
+
117
+ return logits, loss
118
+
119
+ def generate(self, idx, max_new_tokens):
120
+ # idx is (B, T) array of indices in the current context
121
+ for _ in range(max_new_tokens):
122
+ # get the predictions
123
+ logits, loss = self(idx)
124
+ # focus only on the last time step
125
+ logits = logits[:, -1, :] # becomes (B, C)
126
+ # apply softmax to get probabilities
127
+ probs = F.softmax(logits, dim=-1) # (B, C)
128
+ # sample from the distribution
129
+ idx_next = torch.multinomial(probs, num_samples=1) # (B, 1)
130
+ # append sampled index to the running sequence
131
+ idx = torch.cat((idx, idx_next), dim=1) # (B, T+1)
132
+ return idx
133
+
134
+ m = BigramLanguageModel(vocab_size)
135
+
136
+
137
+ logits, loss = m(xb, yb)
138
+ print(logits.shape)
139
+ print(loss)
140
+
141
+ print(decode(m.generate(idx = torch.zeros((1, 1), dtype=torch.long), max_new_tokens=100)[0].tolist()))
142
+
143
+
144
+
145
+ # create a PyTorch optimizer
146
+ optimizer = torch.optim.AdamW(m.parameters(), lr=1e-3)
147
+
148
+ batch_size = 32
149
+ for steps in range(100): # increase number of steps for good results...
150
+
151
+ # sample a batch of data
152
+ xb, yb = get_batch('train')
153
+
154
+ # evaluate the loss
155
+ logits, loss = m(xb, yb)
156
+ optimizer.zero_grad(set_to_none=True)
157
+ loss.backward()
158
+ optimizer.step()
159
+
160
+ print(loss.item())
161
+
162
+ print(decode(m.generate(idx = torch.zeros((1, 1), dtype=torch.long), max_new_tokens=500)[0].tolist()))
163
+
164
+ """## The mathematical trick in self-attention"""
165
+
166
+ # toy example illustrating how matrix multiplication can be used for a "weighted aggregation"
167
+ torch.manual_seed(42)
168
+ a = torch.tril(torch.ones(3, 3))
169
+ a = a / torch.sum(a, 1, keepdim=True)
170
+ b = torch.randint(0,10,(3,2)).float()
171
+ c = a @ b
172
+ print('a=')
173
+ print(a)
174
+ print('--')
175
+ print('b=')
176
+ print(b)
177
+ print('--')
178
+ print('c=')
179
+ print(c)
180
+
181
+ # consider the following toy example:
182
+
183
+ torch.manual_seed(1337)
184
+ B,T,C = 4,8,2 # batch, time, channels
185
+ x = torch.randn(B,T,C)
186
+ x.shape
187
+
188
+ # We want x[b,t] = mean_{i<=t} x[b,i]
189
+ xbow = torch.zeros((B,T,C))
190
+ for b in range(B):
191
+ for t in range(T):
192
+ xprev = x[b,:t+1] # (t,C)
193
+ xbow[b,t] = torch.mean(xprev, 0)
194
+
195
+ # version 2: using matrix multiply for a weighted aggregation
196
+ wei = torch.tril(torch.ones(T, T))
197
+ wei = wei / wei.sum(1, keepdim=True)
198
+ xbow2 = wei @ x # (B, T, T) @ (B, T, C) ----> (B, T, C)
199
+ torch.allclose(xbow, xbow2)
200
+
201
+ # version 3: use Softmax
202
+ tril = torch.tril(torch.ones(T, T))
203
+ wei = torch.zeros((T,T))
204
+ wei = wei.masked_fill(tril == 0, float('-inf'))
205
+ wei = F.softmax(wei, dim=-1)
206
+ xbow3 = wei @ x
207
+ torch.allclose(xbow, xbow3)
208
+
209
+ # version 4: self-attention!
210
+ torch.manual_seed(1337)
211
+ B,T,C = 4,8,32 # batch, time, channels
212
+ x = torch.randn(B,T,C)
213
+
214
+ # let's see a single Head perform self-attention
215
+ head_size = 16
216
+ key = nn.Linear(C, head_size, bias=False)
217
+ query = nn.Linear(C, head_size, bias=False)
218
+ value = nn.Linear(C, head_size, bias=False)
219
+ k = key(x) # (B, T, 16)
220
+ q = query(x) # (B, T, 16)
221
+ wei = q @ k.transpose(-2, -1) # (B, T, 16) @ (B, 16, T) ---> (B, T, T)
222
+
223
+ tril = torch.tril(torch.ones(T, T))
224
+ #wei = torch.zeros((T,T))
225
+ wei = wei.masked_fill(tril == 0, float('-inf'))
226
+ wei = F.softmax(wei, dim=-1)
227
+
228
+ v = value(x)
229
+ out = wei @ v
230
+ #out = wei @ x
231
+
232
+ out.shape
233
+
234
+ wei[0]
235
+
236
+ """Notes:
237
+ - Attention is a **communication mechanism**. Can be seen as nodes in a directed graph looking at each other and aggregating information with a weighted sum from all nodes that point to them, with data-dependent weights.
238
+ - There is no notion of space. Attention simply acts over a set of vectors. This is why we need to positionally encode tokens.
239
+ - Each example across batch dimension is of course processed completely independently and never "talk" to each other
240
+ - In an "encoder" attention block just delete the single line that does masking with `tril`, allowing all tokens to communicate. This block here is called a "decoder" attention block because it has triangular masking, and is usually used in autoregressive settings, like language modeling.
241
+ - "self-attention" just means that the keys and values are produced from the same source as queries. In "cross-attention", the queries still get produced from x, but the keys and values come from some other, external source (e.g. an encoder module)
242
+ - "Scaled" attention additional divides `wei` by 1/sqrt(head_size). This makes it so when input Q,K are unit variance, wei will be unit variance too and Softmax will stay diffuse and not saturate too much. Illustration below
243
+ """
244
+
245
+ k = torch.randn(B,T,head_size)
246
+ q = torch.randn(B,T,head_size)
247
+ wei = q @ k.transpose(-2, -1) * head_size**-0.5
248
+
249
+ k.var()
250
+
251
+ q.var()
252
+
253
+ wei.var()
254
+
255
+ torch.softmax(torch.tensor([0.1, -0.2, 0.3, -0.2, 0.5]), dim=-1)
256
+
257
+ torch.softmax(torch.tensor([0.1, -0.2, 0.3, -0.2, 0.5])*8, dim=-1) # gets too peaky, converges to one-hot
258
+
259
+ class LayerNorm1d: # (used to be BatchNorm1d)
260
+
261
+ def __init__(self, dim, eps=1e-5, momentum=0.1):
262
+ self.eps = eps
263
+ self.gamma = torch.ones(dim)
264
+ self.beta = torch.zeros(dim)
265
+
266
+ def __call__(self, x):
267
+ # calculate the forward pass
268
+ xmean = x.mean(1, keepdim=True) # batch mean
269
+ xvar = x.var(1, keepdim=True) # batch variance
270
+ xhat = (x - xmean) / torch.sqrt(xvar + self.eps) # normalize to unit variance
271
+ self.out = self.gamma * xhat + self.beta
272
+ return self.out
273
+
274
+ def parameters(self):
275
+ return [self.gamma, self.beta]
276
+
277
+ torch.manual_seed(1337)
278
+ module = LayerNorm1d(100)
279
+ x = torch.randn(32, 100) # batch size 32 of 100-dimensional vectors
280
+ x = module(x)
281
+ x.shape
282
+
283
+ x[:,0].mean(), x[:,0].std() # mean,std of one feature across all batch inputs
284
+
285
+ x[0,:].mean(), x[0,:].std() # mean,std of a single input from the batch, of its features
286
+
287
+ # French to English translation example:
288
+
289
+ # <--------- ENCODE ------------------><--------------- DECODE ----------------->
290
+ # les réseaux de neurones sont géniaux! <START> neural networks are awesome!<END>
291
+
292
+ """### Full finished code, for reference
293
+
294
+ You may want to refer directly to the git repo instead though.
295
+ """
296
+
297
+ import torch
298
+ import torch.nn as nn
299
+ from torch.nn import functional as F
300
+
301
+ # hyperparameters
302
+ batch_size = 16 # how many independent sequences will we process in parallel?
303
+ block_size = 32 # what is the maximum context length for predictions?
304
+ max_iters = 5000
305
+ #00
306
+ eval_interval = 100
307
+ learning_rate = 1e-3
308
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
309
+ eval_iters = 200
310
+ n_embd = 64
311
+ n_head = 4
312
+ n_layer = 4
313
+ dropout = 0.0
314
+ # ------------
315
+
316
+ torch.manual_seed(1337)
317
+
318
+ # wget https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt
319
+ with open('input.txt', 'r', encoding='utf-8') as f:
320
+ text = f.read()
321
+
322
+ # here are all the unique characters that occur in this text
323
+ chars = sorted(list(set(text)))
324
+ vocab_size = len(chars)
325
+ # create a mapping from characters to integers
326
+ stoi = { ch:i for i,ch in enumerate(chars) }
327
+ itos = { i:ch for i,ch in enumerate(chars) }
328
+ encode = lambda s: [stoi[c] for c in s] # encoder: take a string, output a list of integers
329
+ decode = lambda l: ''.join([itos[i] for i in l]) # decoder: take a list of integers, output a string
330
+
331
+ # Train and test splits
332
+ data = torch.tensor(encode(text), dtype=torch.long)
333
+ n = int(0.9*len(data)) # first 90% will be train, rest val
334
+ train_data = data[:n]
335
+ val_data = data[n:]
336
+
337
+ # data loading
338
+ def get_batch(split):
339
+ # generate a small batch of data of inputs x and targets y
340
+ data = train_data if split == 'train' else val_data
341
+ ix = torch.randint(len(data) - block_size, (batch_size,))
342
+ x = torch.stack([data[i:i+block_size] for i in ix])
343
+ y = torch.stack([data[i+1:i+block_size+1] for i in ix])
344
+ x, y = x.to(device), y.to(device)
345
+ return x, y
346
+
347
+ @torch.no_grad()
348
+ def estimate_loss():
349
+ out = {}
350
+ model.eval()
351
+ for split in ['train', 'val']:
352
+ losses = torch.zeros(eval_iters)
353
+ for k in range(eval_iters):
354
+ X, Y = get_batch(split)
355
+ logits, loss = model(X, Y)
356
+ losses[k] = loss.item()
357
+ out[split] = losses.mean()
358
+ model.train()
359
+ return out
360
+
361
+ class Head(nn.Module):
362
+ """ one head of self-attention """
363
+
364
+ def __init__(self, head_size):
365
+ super().__init__()
366
+ self.key = nn.Linear(n_embd, head_size, bias=False)
367
+ self.query = nn.Linear(n_embd, head_size, bias=False)
368
+ self.value = nn.Linear(n_embd, head_size, bias=False)
369
+ self.register_buffer('tril', torch.tril(torch.ones(block_size, block_size)))
370
+
371
+ self.dropout = nn.Dropout(dropout)
372
+
373
+ def forward(self, x):
374
+ B,T,C = x.shape
375
+ k = self.key(x) # (B,T,C)
376
+ q = self.query(x) # (B,T,C)
377
+ # compute attention scores ("affinities")
378
+ wei = q @ k.transpose(-2,-1) * C**-0.5 # (B, T, C) @ (B, C, T) -> (B, T, T)
379
+ wei = wei.masked_fill(self.tril[:T, :T] == 0, float('-inf')) # (B, T, T)
380
+ wei = F.softmax(wei, dim=-1) # (B, T, T)
381
+ wei = self.dropout(wei)
382
+ # perform the weighted aggregation of the values
383
+ v = self.value(x) # (B,T,C)
384
+ out = wei @ v # (B, T, T) @ (B, T, C) -> (B, T, C)
385
+ return out
386
+
387
+ class MultiHeadAttention(nn.Module):
388
+ """ multiple heads of self-attention in parallel """
389
+
390
+ def __init__(self, num_heads, head_size):
391
+ super().__init__()
392
+ self.heads = nn.ModuleList([Head(head_size) for _ in range(num_heads)])
393
+ self.proj = nn.Linear(n_embd, n_embd)
394
+ self.dropout = nn.Dropout(dropout)
395
+
396
+ def forward(self, x):
397
+ out = torch.cat([h(x) for h in self.heads], dim=-1)
398
+ out = self.dropout(self.proj(out))
399
+ return out
400
+
401
+ class FeedFoward(nn.Module):
402
+ """ a simple linear layer followed by a non-linearity """
403
+
404
+ def __init__(self, n_embd):
405
+ super().__init__()
406
+ self.net = nn.Sequential(
407
+ nn.Linear(n_embd, 4 * n_embd),
408
+ nn.ReLU(),
409
+ nn.Linear(4 * n_embd, n_embd),
410
+ nn.Dropout(dropout),
411
+ )
412
+
413
+ def forward(self, x):
414
+ return self.net(x)
415
+
416
+ class Block(nn.Module):
417
+ """ Transformer block: communication followed by computation """
418
+
419
+ def __init__(self, n_embd, n_head):
420
+ # n_embd: embedding dimension, n_head: the number of heads we'd like
421
+ super().__init__()
422
+ head_size = n_embd // n_head
423
+ self.sa = MultiHeadAttention(n_head, head_size)
424
+ self.ffwd = FeedFoward(n_embd)
425
+ self.ln1 = nn.LayerNorm(n_embd)
426
+ self.ln2 = nn.LayerNorm(n_embd)
427
+
428
+ def forward(self, x):
429
+ x = x + self.sa(self.ln1(x))
430
+ x = x + self.ffwd(self.ln2(x))
431
+ return x
432
+
433
+ # super simple bigram model
434
+ class BigramLanguageModel(nn.Module):
435
+
436
+ def __init__(self):
437
+ #super().__init__()
438
+ super(BigramLanguageModel, self).__init__()
439
+ # each token directly reads off the logits for the next token from a lookup table
440
+ self.token_embedding_table = nn.Embedding(vocab_size, n_embd)
441
+ self.position_embedding_table = nn.Embedding(block_size, n_embd)
442
+ self.blocks = nn.Sequential(*[Block(n_embd, n_head=n_head) for _ in range(n_layer)])
443
+ self.ln_f = nn.LayerNorm(n_embd) # final layer norm
444
+ self.lm_head = nn.Linear(n_embd, vocab_size)
445
+
446
+ def forward(self, idx, targets=None):
447
+ B, T = idx.shape
448
+
449
+ # idx and targets are both (B,T) tensor of integers
450
+ tok_emb = self.token_embedding_table(idx) # (B,T,C)
451
+ pos_emb = self.position_embedding_table(torch.arange(T, device=device)) # (T,C)
452
+ x = tok_emb + pos_emb # (B,T,C)
453
+ x = self.blocks(x) # (B,T,C)
454
+ x = self.ln_f(x) # (B,T,C)
455
+ logits = self.lm_head(x) # (B,T,vocab_size)
456
+
457
+ if targets is None:
458
+ loss = None
459
+ else:
460
+ B, T, C = logits.shape
461
+ logits = logits.view(B*T, C)
462
+ targets = targets.view(B*T)
463
+ loss = F.cross_entropy(logits, targets)
464
+
465
+ return logits, loss
466
+
467
+ def generate(self, idx, max_new_tokens):
468
+ # idx is (B, T) array of indices in the current context
469
+ for _ in range(max_new_tokens):
470
+ # crop idx to the last block_size tokens
471
+ idx_cond = idx[:, -block_size:]
472
+ # get the predictions
473
+ logits, loss = self(idx_cond)
474
+ # focus only on the last time step
475
+ logits = logits[:, -1, :] # becomes (B, C)
476
+ # apply softmax to get probabilities
477
+ probs = F.softmax(logits, dim=-1) # (B, C)
478
+ # sample from the distribution
479
+ idx_next = torch.multinomial(probs, num_samples=1) # (B, 1)
480
+ # append sampled index to the running sequence
481
+ idx = torch.cat((idx, idx_next), dim=1) # (B, T+1)
482
+ return idx
483
+
484
+ model = BigramLanguageModel()
485
+ torch.save(model.state_dict(), 'transformer_weights.pth')
486
+ m = model.to(device)
487
+ # print the number of parameters in the model
488
+ print(sum(p.numel() for p in m.parameters())/1e6, 'M parameters')
489
+ torch.save(model, 'transformer_model.pth')
490
+
491
+ # create a PyTorch optimizer
492
+ optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate)
493
+
494
+ for iter in range(max_iters):
495
+
496
+ # every once in a while evaluate the loss on train and val sets
497
+ if iter % eval_interval == 0 or iter == max_iters - 1:
498
+ losses = estimate_loss()
499
+ print(f"step {iter}: train loss {losses['train']:.4f}, val loss {losses['val']:.4f}")
500
+
501
+ # sample a batch of data
502
+ xb, yb = get_batch('train')
503
+
504
+ # evaluate the loss
505
+ logits, loss = model(xb, yb)
506
+ optimizer.zero_grad(set_to_none=True)
507
+ loss.backward()
508
+ optimizer.step()
509
+
510
+ # generate from the model
511
+ context = torch.zeros((1, 1), dtype=torch.long, device=device)
512
+ print(decode(m.generate(context, max_new_tokens=2000)[0].tolist()))
513
+
514
+ # Load the saved weights into the model
515
+ model.load_state_dict(torch.load('transformer_weights.pth'))
516
+
517
+ print("Model weights loaded successfully.")
518
+
519
+ import torch
520
+
521
+ # Load the entire model
522
+ model = torch.load('transformer_model.pth')
523
+ model.eval() # Set the model to evaluation mode
524
+
525
+ print("Entire model loaded successfully.")