shng2025 commited on
Commit
a6fd12b
1 Parent(s): 0cb341a

Finished training.

Browse files
Files changed (3) hide show
  1. full_model.pth +3 -0
  2. gpt.py +229 -0
  3. input.txt +0 -0
full_model.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c429553ba8b8f30081834ba4a779341f979c3f0139b03d53fef5b4fcd620ee03
3
+ size 52717584
gpt.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from torch.nn import functional as F
4
+
5
+ # hyperparameters
6
+ batch_size = 64 # how many independent sequences will we process in parallel?
7
+ block_size = 256 # what is the maximum context length for predictions?
8
+ max_iters = 5000
9
+ eval_interval = 500
10
+ learning_rate = 3e-4
11
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
12
+ eval_iters = 200
13
+ n_embd = 384
14
+ n_head = 6
15
+ n_layer = 6
16
+ dropout = 0.2
17
+ # ------------
18
+
19
+ torch.manual_seed(1337)
20
+
21
+ # wget https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt
22
+ with open('input.txt', 'r', encoding='utf-8') as f:
23
+ text = f.read()
24
+
25
+ # here are all the unique characters that occur in this text
26
+ chars = sorted(list(set(text)))
27
+ vocab_size = len(chars)
28
+ # create a mapping from characters to integers
29
+ stoi = { ch:i for i,ch in enumerate(chars) }
30
+ itos = { i:ch for i,ch in enumerate(chars) }
31
+ encode = lambda s: [stoi[c] for c in s] # encoder: take a string, output a list of integers
32
+ decode = lambda l: ''.join([itos[i] for i in l]) # decoder: take a list of integers, output a string
33
+
34
+ # Train and test splits
35
+ data = torch.tensor(encode(text), dtype=torch.long)
36
+ n = int(0.9*len(data)) # first 90% will be train, rest val
37
+ train_data = data[:n]
38
+ val_data = data[n:]
39
+
40
+ # data loading
41
+ def get_batch(split):
42
+ # generate a small batch of data of inputs x and targets y
43
+ data = train_data if split == 'train' else val_data
44
+ ix = torch.randint(len(data) - block_size, (batch_size,))
45
+ x = torch.stack([data[i:i+block_size] for i in ix])
46
+ y = torch.stack([data[i+1:i+block_size+1] for i in ix])
47
+ x, y = x.to(device), y.to(device)
48
+ return x, y
49
+
50
+ @torch.no_grad()
51
+ def estimate_loss():
52
+ out = {}
53
+ model.eval()
54
+ for split in ['train', 'val']:
55
+ losses = torch.zeros(eval_iters)
56
+ for k in range(eval_iters):
57
+ X, Y = get_batch(split)
58
+ logits, loss = model(X, Y)
59
+ losses[k] = loss.item()
60
+ out[split] = losses.mean()
61
+ model.train()
62
+ return out
63
+
64
+ class Head(nn.Module):
65
+ """ one head of self-attention """
66
+
67
+ def __init__(self, head_size):
68
+ super().__init__()
69
+ self.key = nn.Linear(n_embd, head_size, bias=False)
70
+ self.query = nn.Linear(n_embd, head_size, bias=False)
71
+ self.value = nn.Linear(n_embd, head_size, bias=False)
72
+ self.register_buffer('tril', torch.tril(torch.ones(block_size, block_size)))
73
+
74
+ self.dropout = nn.Dropout(dropout)
75
+
76
+ def forward(self, x):
77
+ # input of size (batch, time-step, channels)
78
+ # output of size (batch, time-step, head size)
79
+ B,T,C = x.shape
80
+ k = self.key(x) # (B,T,hs)
81
+ q = self.query(x) # (B,T,hs)
82
+ # compute attention scores ("affinities")
83
+ wei = q @ k.transpose(-2,-1) * k.shape[-1]**-0.5 # (B, T, hs) @ (B, hs, T) -> (B, T, T)
84
+ # this is the attention(Q, K, V) equation. division by sqrt(d_k) can be seen.
85
+ wei = wei.masked_fill(self.tril[:T, :T] == 0, float('-inf')) # (B, T, T)
86
+ wei = F.softmax(wei, dim=-1) # (B, T, T)
87
+ wei = self.dropout(wei)
88
+ # perform the weighted aggregation of the values
89
+ v = self.value(x) # (B,T,hs)
90
+ out = wei @ v # (B, T, T) @ (B, T, hs) -> (B, T, hs)
91
+ return out
92
+
93
+ class MultiHeadAttention(nn.Module):
94
+ """ multiple heads of self-attention in parallel """
95
+
96
+ def __init__(self, num_heads, head_size):
97
+ super().__init__()
98
+ self.heads = nn.ModuleList([Head(head_size) for _ in range(num_heads)]) # creates x number of parallel self attention heads
99
+ self.proj = nn.Linear(head_size * num_heads, n_embd)
100
+ self.dropout = nn.Dropout(dropout)
101
+
102
+ def forward(self, x):
103
+ out = torch.cat([h(x) for h in self.heads], dim=-1)
104
+ out = self.dropout(self.proj(out)) # projection back into the residual pathway
105
+ return out
106
+
107
+ class FeedFoward(nn.Module):
108
+ """ a simple linear layer followed by a non-linearity """
109
+
110
+ def __init__(self, n_embd):
111
+ super().__init__()
112
+ self.net = nn.Sequential(
113
+ nn.Linear(n_embd, 4 * n_embd), # both this and 2 lines below had been multipied by 4 based on FFN implementation in the
114
+ # paper "Attention is All you need"
115
+ nn.ReLU(),
116
+ nn.Linear(4 * n_embd, n_embd), # this is the projection layer going back into the residual pathway
117
+ nn.Dropout(dropout),
118
+ )
119
+
120
+ def forward(self, x):
121
+ return self.net(x)
122
+
123
+ class Block(nn.Module):
124
+ """ Transformer block: communication followed by computation """
125
+
126
+ def __init__(self, n_embd, n_head):
127
+ # n_embd: embedding dimension, n_head: the number of heads we'd like
128
+ super().__init__()
129
+ head_size = n_embd // n_head
130
+ self.sa = MultiHeadAttention(n_head, head_size) # multi-head attention class initialisation
131
+ self.ffwd = FeedFoward(n_embd) # notice how this occurs after attention
132
+ self.ln1 = nn.LayerNorm(n_embd)
133
+ self.ln2 = nn.LayerNorm(n_embd)
134
+
135
+ def forward(self, x):
136
+ x = x + self.sa(self.ln1(x)) # residual
137
+ x = x + self.ffwd(self.ln2(x)) # from feedforward
138
+ return x
139
+
140
+ class GPTLanguageModel(nn.Module):
141
+
142
+ def __init__(self):
143
+ super().__init__()
144
+ # each token directly reads off the logits for the next token from a lookup table
145
+ # not just encoding identity of token here. but also its position!
146
+ self.token_embedding_table = nn.Embedding(vocab_size, n_embd)
147
+ self.position_embedding_table = nn.Embedding(block_size, n_embd)
148
+ self.blocks = nn.Sequential(*[Block(n_embd, n_head=n_head) for _ in range(n_layer)]) # multiple blocks can be seen here
149
+ self.ln_f = nn.LayerNorm(n_embd) # final layer norm
150
+ self.lm_head = nn.Linear(n_embd, vocab_size) # short for language model head
151
+
152
+ # better init, not covered in the original GPT video, but important, will cover in followup video
153
+ self.apply(self._init_weights)
154
+
155
+ def _init_weights(self, module):
156
+ if isinstance(module, nn.Linear):
157
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
158
+ if module.bias is not None:
159
+ torch.nn.init.zeros_(module.bias)
160
+ elif isinstance(module, nn.Embedding):
161
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
162
+
163
+ def forward(self, idx, targets=None):
164
+ B, T = idx.shape
165
+
166
+ # idx and targets are both (B,T) tensor of integers
167
+ tok_emb = self.token_embedding_table(idx) # (B,T,C)
168
+ pos_emb = self.position_embedding_table(torch.arange(T, device=device)) # (T,C)
169
+ x = tok_emb + pos_emb # (B,T,C) // at this point x not only contains token identity. but also
170
+ # positional identity from position embedding
171
+ x = self.blocks(x) # (B,T,C)
172
+ x = self.ln_f(x) # (B,T,C)
173
+ logits = self.lm_head(x) # (B,T,vocab_size)
174
+
175
+ if targets is None:
176
+ loss = None
177
+ else:
178
+ B, T, C = logits.shape
179
+ logits = logits.view(B*T, C)
180
+ targets = targets.view(B*T)
181
+ loss = F.cross_entropy(logits, targets)
182
+
183
+ return logits, loss
184
+
185
+ def generate(self, idx, max_new_tokens):
186
+ # idx is (B, T) array of indices in the current context
187
+ for _ in range(max_new_tokens):
188
+ # crop idx to the last block_size tokens
189
+ idx_cond = idx[:, -block_size:]
190
+ # get the predictions
191
+ logits, loss = self(idx_cond)
192
+ # focus only on the last time step
193
+ logits = logits[:, -1, :] # becomes (B, C)
194
+ # apply softmax to get probabilities
195
+ probs = F.softmax(logits, dim=-1) # (B, C)
196
+ # sample from the distribution
197
+ idx_next = torch.multinomial(probs, num_samples=1) # (B, 1)
198
+ # append sampled index to the running sequence
199
+ idx = torch.cat((idx, idx_next), dim=1) # (B, T+1)
200
+ return idx
201
+
202
+ model = GPTLanguageModel()
203
+ m = model.to(device)
204
+ # print the number of parameters in the model
205
+ print(sum(p.numel() for p in m.parameters())/1e6, 'M parameters')
206
+
207
+ # create a PyTorch optimizer
208
+ optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate)
209
+
210
+ for iter in range(max_iters):
211
+
212
+ # every once in a while evaluate the loss on train and val sets
213
+ if iter % eval_interval == 0 or iter == max_iters - 1:
214
+ losses = estimate_loss()
215
+ print(f"step {iter}: train loss {losses['train']:.4f}, val loss {losses['val']:.4f}")
216
+
217
+ # sample a batch of data
218
+ xb, yb = get_batch('train')
219
+
220
+ # evaluate the loss
221
+ logits, loss = model(xb, yb)
222
+ optimizer.zero_grad(set_to_none=True)
223
+ loss.backward()
224
+ optimizer.step()
225
+
226
+ # generate from the model
227
+ context = torch.zeros((1, 1), dtype=torch.long, device=device)
228
+ print(decode(m.generate(context, max_new_tokens=500)[0].tolist()))
229
+ #open('more.txt', 'w').write(decode(m.generate(context, max_new_tokens=10000)[0].tolist()))
input.txt ADDED
The diff for this file is too large to render. See raw diff