microgpt.py226 lines · Karpathy
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
11device = 'cuda' if torch.cuda.is_available() else 'cpu'
12eval_iters = 200
13n_embd = 384
14n_head = 6
15n_layer = 6
16dropout = 0.2
17# ------------
18
19torch.manual_seed(1337)
20
21# wget https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt
22with 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
26chars = sorted(list(set(text)))
27vocab_size = len(chars)
28# create a mapping from characters to integers
29stoi = { ch:i for i,ch in enumerate(chars) }
30itos = { i:ch for i,ch in enumerate(chars) }
31encode = lambda s: [stoi[c] for c in s] # encoder: take a string, output a list of integers
32decode = lambda l: ''.join([itos[i] for i in l]) # decoder: take a list of integers, output a string
33
34# Train and test splits
35data = torch.tensor(encode(text), dtype=torch.long)
36n = int(0.9*len(data)) # first 90% will be train, rest val
37train_data = data[:n]
38val_data = data[n:]
39
40# data loading
41def 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()
51def 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
64class 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 wei = wei.masked_fill(self.tril[:T, :T] == 0, float('-inf')) # (B, T, T)
85 wei = F.softmax(wei, dim=-1) # (B, T, T)
86 wei = self.dropout(wei)
87 # perform the weighted aggregation of the values
88 v = self.value(x) # (B,T,hs)
89 out = wei @ v # (B, T, T) @ (B, T, hs) -> (B, T, hs)
90 return out
91
92class MultiHeadAttention(nn.Module):
93 """ multiple heads of self-attention in parallel """
94
95 def __init__(self, num_heads, head_size):
96 super().__init__()
97 self.heads = nn.ModuleList([Head(head_size) for _ in range(num_heads)])
98 self.proj = nn.Linear(head_size * num_heads, n_embd)
99 self.dropout = nn.Dropout(dropout)
100
101 def forward(self, x):
102 out = torch.cat([h(x) for h in self.heads], dim=-1)
103 out = self.dropout(self.proj(out))
104 return out
105
106class FeedFoward(nn.Module):
107 """ a simple linear layer followed by a non-linearity """
108
109 def __init__(self, n_embd):
110 super().__init__()
111 self.net = nn.Sequential(
112 nn.Linear(n_embd, 4 * n_embd),
113 nn.ReLU(),
114 nn.Linear(4 * n_embd, n_embd),
115 nn.Dropout(dropout),
116 )
117
118 def forward(self, x):
119 return self.net(x)
120
121class Block(nn.Module):
122 """ Transformer block: communication followed by computation """
123
124 def __init__(self, n_embd, n_head):
125 # n_embd: embedding dimension, n_head: the number of heads we'd like
126 super().__init__()
127 head_size = n_embd // n_head
128 self.sa = MultiHeadAttention(n_head, head_size)
129 self.ffwd = FeedFoward(n_embd)
130 self.ln1 = nn.LayerNorm(n_embd)
131 self.ln2 = nn.LayerNorm(n_embd)
132
133 def forward(self, x):
134 x = x + self.sa(self.ln1(x))
135 x = x + self.ffwd(self.ln2(x))
136 return x
137
138class GPTLanguageModel(nn.Module):
139
140 def __init__(self):
141 super().__init__()
142 # each token directly reads off the logits for the next token from a lookup table
143 self.token_embedding_table = nn.Embedding(vocab_size, n_embd)
144 self.position_embedding_table = nn.Embedding(block_size, n_embd)
145 self.blocks = nn.Sequential(*[Block(n_embd, n_head=n_head) for _ in range(n_layer)])
146 self.ln_f = nn.LayerNorm(n_embd) # final layer norm
147 self.lm_head = nn.Linear(n_embd, vocab_size)
148
149 # better init, not covered in the original GPT video, but important, will cover in followup video
150 self.apply(self._init_weights)
151
152 def _init_weights(self, module):
153 if isinstance(module, nn.Linear):
154 torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
155 if module.bias is not None:
156 torch.nn.init.zeros_(module.bias)
157 elif isinstance(module, nn.Embedding):
158 torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
159
160 def forward(self, idx, targets=None):
161 B, T = idx.shape
162
163 # idx and targets are both (B,T) tensor of integers
164 tok_emb = self.token_embedding_table(idx) # (B,T,C)
165 pos_emb = self.position_embedding_table(torch.arange(T, device=device)) # (T,C)
166 x = tok_emb + pos_emb # (B,T,C)
167 x = self.blocks(x) # (B,T,C)
168 x = self.ln_f(x) # (B,T,C)
169 logits = self.lm_head(x) # (B,T,vocab_size)
170
171 if targets is None:
172 loss = None
173 else:
174 B, T, C = logits.shape
175 logits = logits.view(B*T, C)
176 targets = targets.view(B*T)
177 loss = F.cross_entropy(logits, targets)
178
179 return logits, loss
180
181 def generate(self, idx, max_new_tokens):
182 # idx is (B, T) array of indices in the current context
183 for _ in range(max_new_tokens):
184 # crop idx to the last block_size tokens
185 idx_cond = idx[:, -block_size:]
186 # get the predictions
187 logits, loss = self(idx_cond)
188 # focus only on the last time step
189 logits = logits[:, -1, :] # becomes (B, C)
190 # apply softmax to get probabilities
191 probs = F.softmax(logits, dim=-1) # (B, C)
192 # sample from the distribution
193 idx_next = torch.multinomial(probs, num_samples=1) # (B, 1)
194 # append sampled index to the running sequence
195 idx = torch.cat((idx, idx_next), dim=1) # (B, T+1)
196 return idx
197
198model = GPTLanguageModel()
199m = model.to(device)
200# print the number of parameters in the model
201print(sum(p.numel() for p in m.parameters())/1e6, 'M parameters')
202
203# create a PyTorch optimizer
204optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate)
205
206for iter in range(max_iters):
207
208 # every once in a while evaluate the loss on train and val sets
209 if iter % eval_interval == 0 or iter == max_iters - 1:
210 losses = estimate_loss()
211 print(f"step {iter}: train loss {losses['train']:.4f}, val loss {losses['val']:.4f}")
212
213 # sample a batch of data
214 xb, yb = get_batch('train')
215
216 # evaluate the loss
217 logits, loss = model(xb, yb)
218 optimizer.zero_grad(set_to_none=True)
219 loss.backward()
220 optimizer.step()
221
222# generate from the model
223context = torch.zeros((1, 1), dtype=torch.long, device=device)
224print(decode(m.generate(context, max_new_tokens=500)[0].tolist()))
225#open('more.txt', 'w').write(decode(m.generate(context, max_new_tokens=10000)[0].tolist()))
226