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