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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) Sebastian Raschka under Apache License 2.0 (see LICENSE.txt).
|
2 |
+
# Source for "Build a Large Language Model From Scratch"
|
3 |
+
# - https://www.manning.com/books/build-a-large-language-model-from-scratch
|
4 |
+
# Code: https://github.com/rasbt/LLMs-from-scratch
|
5 |
+
|
6 |
+
import matplotlib.pyplot as plt
|
7 |
+
from matplotlib.ticker import MaxNLocator
|
8 |
+
import tiktoken
|
9 |
+
import torch
|
10 |
+
import torch.nn as nn
|
11 |
+
from torch.utils.data import Dataset, DataLoader
|
12 |
+
|
13 |
+
|
14 |
+
class GPTDatasetV1(Dataset):
|
15 |
+
def __init__(self, txt, tokenizer, max_length, stride):
|
16 |
+
self.input_ids = []
|
17 |
+
self.target_ids = []
|
18 |
+
|
19 |
+
# Tokenize the entire text
|
20 |
+
token_ids = tokenizer.encode(txt, allowed_special={"<|endoftext|>"})
|
21 |
+
|
22 |
+
# Use a sliding window to chunk the book into overlapping sequences of max_length
|
23 |
+
for i in range(0, len(token_ids) - max_length, stride):
|
24 |
+
input_chunk = token_ids[i:i + max_length]
|
25 |
+
target_chunk = token_ids[i + 1: i + max_length + 1]
|
26 |
+
self.input_ids.append(torch.tensor(input_chunk))
|
27 |
+
self.target_ids.append(torch.tensor(target_chunk))
|
28 |
+
|
29 |
+
def __len__(self):
|
30 |
+
return len(self.input_ids)
|
31 |
+
|
32 |
+
def __getitem__(self, idx):
|
33 |
+
return self.input_ids[idx], self.target_ids[idx]
|
34 |
+
|
35 |
+
|
36 |
+
def create_dataloader_v1(txt, batch_size=4, max_length=256,
|
37 |
+
stride=128, shuffle=True, drop_last=True, num_workers=0):
|
38 |
+
# Initialize the tokenizer
|
39 |
+
tokenizer = tiktoken.get_encoding("gpt2")
|
40 |
+
|
41 |
+
# Create dataset
|
42 |
+
dataset = GPTDatasetV1(txt, tokenizer, max_length, stride)
|
43 |
+
|
44 |
+
# Create dataloader
|
45 |
+
dataloader = DataLoader(
|
46 |
+
dataset, batch_size=batch_size, shuffle=shuffle, drop_last=drop_last, num_workers=num_workers)
|
47 |
+
|
48 |
+
return dataloader
|
49 |
+
|
50 |
+
|
51 |
+
class MultiHeadAttention(nn.Module):
|
52 |
+
def __init__(self, d_in, d_out, context_length, dropout, num_heads, qkv_bias=False):
|
53 |
+
super().__init__()
|
54 |
+
assert d_out % num_heads == 0, "d_out must be divisible by num_heads"
|
55 |
+
|
56 |
+
self.d_out = d_out
|
57 |
+
self.num_heads = num_heads
|
58 |
+
self.head_dim = d_out // num_heads # Reduce the projection dim to match desired output dim
|
59 |
+
|
60 |
+
self.W_query = nn.Linear(d_in, d_out, bias=qkv_bias)
|
61 |
+
self.W_key = nn.Linear(d_in, d_out, bias=qkv_bias)
|
62 |
+
self.W_value = nn.Linear(d_in, d_out, bias=qkv_bias)
|
63 |
+
self.out_proj = nn.Linear(d_out, d_out) # Linear layer to combine head outputs
|
64 |
+
self.dropout = nn.Dropout(dropout)
|
65 |
+
self.register_buffer('mask', torch.triu(torch.ones(context_length, context_length), diagonal=1))
|
66 |
+
|
67 |
+
def forward(self, x):
|
68 |
+
b, num_tokens, d_in = x.shape
|
69 |
+
|
70 |
+
keys = self.W_key(x) # Shape: (b, num_tokens, d_out)
|
71 |
+
queries = self.W_query(x)
|
72 |
+
values = self.W_value(x)
|
73 |
+
|
74 |
+
# We implicitly split the matrix by adding a `num_heads` dimension
|
75 |
+
# Unroll last dim: (b, num_tokens, d_out) -> (b, num_tokens, num_heads, head_dim)
|
76 |
+
keys = keys.view(b, num_tokens, self.num_heads, self.head_dim)
|
77 |
+
values = values.view(b, num_tokens, self.num_heads, self.head_dim)
|
78 |
+
queries = queries.view(b, num_tokens, self.num_heads, self.head_dim)
|
79 |
+
|
80 |
+
# Transpose: (b, num_tokens, num_heads, head_dim) -> (b, num_heads, num_tokens, head_dim)
|
81 |
+
keys = keys.transpose(1, 2)
|
82 |
+
queries = queries.transpose(1, 2)
|
83 |
+
values = values.transpose(1, 2)
|
84 |
+
|
85 |
+
# Compute scaled dot-product attention (aka self-attention) with a causal mask
|
86 |
+
attn_scores = queries @ keys.transpose(2, 3) # Dot product for each head
|
87 |
+
|
88 |
+
# Original mask truncated to the number of tokens and converted to boolean
|
89 |
+
mask_bool = self.mask.bool()[:num_tokens, :num_tokens]
|
90 |
+
|
91 |
+
# Use the mask to fill attention scores
|
92 |
+
attn_scores.masked_fill_(mask_bool, -torch.inf)
|
93 |
+
|
94 |
+
attn_weights = torch.softmax(attn_scores / keys.shape[-1]**0.5, dim=-1)
|
95 |
+
attn_weights = self.dropout(attn_weights)
|
96 |
+
|
97 |
+
# Shape: (b, num_tokens, num_heads, head_dim)
|
98 |
+
context_vec = (attn_weights @ values).transpose(1, 2)
|
99 |
+
|
100 |
+
# Combine heads, where self.d_out = self.num_heads * self.head_dim
|
101 |
+
context_vec = context_vec.contiguous().view(b, num_tokens, self.d_out)
|
102 |
+
context_vec = self.out_proj(context_vec) # optional projection
|
103 |
+
|
104 |
+
return context_vec
|
105 |
+
|
106 |
+
|
107 |
+
class LayerNorm(nn.Module):
|
108 |
+
def __init__(self, emb_dim):
|
109 |
+
super().__init__()
|
110 |
+
self.eps = 1e-5
|
111 |
+
self.scale = nn.Parameter(torch.ones(emb_dim))
|
112 |
+
self.shift = nn.Parameter(torch.zeros(emb_dim))
|
113 |
+
|
114 |
+
def forward(self, x):
|
115 |
+
mean = x.mean(dim=-1, keepdim=True)
|
116 |
+
var = x.var(dim=-1, keepdim=True, unbiased=False)
|
117 |
+
norm_x = (x - mean) / torch.sqrt(var + self.eps)
|
118 |
+
return self.scale * norm_x + self.shift
|
119 |
+
|
120 |
+
|
121 |
+
class GELU(nn.Module):
|
122 |
+
def __init__(self):
|
123 |
+
super().__init__()
|
124 |
+
|
125 |
+
def forward(self, x):
|
126 |
+
return 0.5 * x * (1 + torch.tanh(
|
127 |
+
torch.sqrt(torch.tensor(2.0 / torch.pi)) *
|
128 |
+
(x + 0.044715 * torch.pow(x, 3))
|
129 |
+
))
|
130 |
+
|
131 |
+
|
132 |
+
class FeedForward(nn.Module):
|
133 |
+
def __init__(self, cfg):
|
134 |
+
super().__init__()
|
135 |
+
self.layers = nn.Sequential(
|
136 |
+
nn.Linear(cfg["emb_dim"], 4 * cfg["emb_dim"]),
|
137 |
+
GELU(),
|
138 |
+
nn.Linear(4 * cfg["emb_dim"], cfg["emb_dim"]),
|
139 |
+
)
|
140 |
+
|
141 |
+
def forward(self, x):
|
142 |
+
return self.layers(x)
|
143 |
+
|
144 |
+
|
145 |
+
class TransformerBlock(nn.Module):
|
146 |
+
def __init__(self, cfg):
|
147 |
+
super().__init__()
|
148 |
+
self.att = MultiHeadAttention(
|
149 |
+
d_in=cfg["emb_dim"],
|
150 |
+
d_out=cfg["emb_dim"],
|
151 |
+
context_length=cfg["context_length"],
|
152 |
+
num_heads=cfg["n_heads"],
|
153 |
+
dropout=cfg["drop_rate"],
|
154 |
+
qkv_bias=cfg["qkv_bias"])
|
155 |
+
self.ff = FeedForward(cfg)
|
156 |
+
self.norm1 = LayerNorm(cfg["emb_dim"])
|
157 |
+
self.norm2 = LayerNorm(cfg["emb_dim"])
|
158 |
+
self.drop_shortcut = nn.Dropout(cfg["drop_rate"])
|
159 |
+
|
160 |
+
def forward(self, x):
|
161 |
+
# Shortcut connection for attention block
|
162 |
+
shortcut = x
|
163 |
+
x = self.norm1(x)
|
164 |
+
x = self.att(x) # Shape [batch_size, num_tokens, emb_size]
|
165 |
+
x = self.drop_shortcut(x)
|
166 |
+
x = x + shortcut # Add the original input back
|
167 |
+
|
168 |
+
# Shortcut connection for feed forward block
|
169 |
+
shortcut = x
|
170 |
+
x = self.norm2(x)
|
171 |
+
x = self.ff(x)
|
172 |
+
x = self.drop_shortcut(x)
|
173 |
+
x = x + shortcut # Add the original input back
|
174 |
+
|
175 |
+
return x
|
176 |
+
|
177 |
+
|
178 |
+
class GPTModel(nn.Module):
|
179 |
+
def __init__(self, cfg):
|
180 |
+
super().__init__()
|
181 |
+
self.tok_emb = nn.Embedding(cfg["vocab_size"], cfg["emb_dim"])
|
182 |
+
self.pos_emb = nn.Embedding(cfg["context_length"], cfg["emb_dim"])
|
183 |
+
self.drop_emb = nn.Dropout(cfg["drop_rate"])
|
184 |
+
|
185 |
+
self.trf_blocks = nn.Sequential(
|
186 |
+
*[TransformerBlock(cfg) for _ in range(cfg["n_layers"])])
|
187 |
+
|
188 |
+
self.final_norm = LayerNorm(cfg["emb_dim"])
|
189 |
+
self.out_head = nn.Linear(
|
190 |
+
cfg["emb_dim"], cfg["vocab_size"], bias=False
|
191 |
+
)
|
192 |
+
|
193 |
+
def forward(self, in_idx):
|
194 |
+
batch_size, seq_len = in_idx.shape
|
195 |
+
tok_embeds = self.tok_emb(in_idx)
|
196 |
+
pos_embeds = self.pos_emb(torch.arange(seq_len, device=in_idx.device))
|
197 |
+
x = tok_embeds + pos_embeds # Shape [batch_size, num_tokens, emb_size]
|
198 |
+
x = self.drop_emb(x)
|
199 |
+
x = self.trf_blocks(x)
|
200 |
+
x = self.final_norm(x)
|
201 |
+
logits = self.out_head(x)
|
202 |
+
return logits
|
203 |
+
|
204 |
+
|
205 |
+
def calc_loss_batch(input_batch, target_batch, model, device):
|
206 |
+
input_batch, target_batch = input_batch.to(device), target_batch.to(device)
|
207 |
+
logits = model(input_batch)
|
208 |
+
loss = torch.nn.functional.cross_entropy(logits.flatten(0, 1), target_batch.flatten())
|
209 |
+
return loss
|
210 |
+
|
211 |
+
|
212 |
+
def calc_loss_loader(data_loader, model, device, num_batches=None):
|
213 |
+
total_loss = 0.
|
214 |
+
if len(data_loader) == 0:
|
215 |
+
return float("nan")
|
216 |
+
elif num_batches is None:
|
217 |
+
num_batches = len(data_loader)
|
218 |
+
else:
|
219 |
+
# Reduce the number of batches to match the total number of batches in the data loader
|
220 |
+
# if num_batches exceeds the number of batches in the data loader
|
221 |
+
num_batches = min(num_batches, len(data_loader))
|
222 |
+
for i, (input_batch, target_batch) in enumerate(data_loader):
|
223 |
+
if i < num_batches:
|
224 |
+
loss = calc_loss_batch(input_batch, target_batch, model, device)
|
225 |
+
total_loss += loss.item()
|
226 |
+
else:
|
227 |
+
break
|
228 |
+
return total_loss / num_batches
|
229 |
+
|
230 |
+
|
231 |
+
def evaluate_model(model, train_loader, val_loader, device, eval_iter):
|
232 |
+
model.eval()
|
233 |
+
with torch.no_grad():
|
234 |
+
train_loss = calc_loss_loader(train_loader, model, device, num_batches=eval_iter)
|
235 |
+
val_loss = calc_loss_loader(val_loader, model, device, num_batches=eval_iter)
|
236 |
+
model.train()
|
237 |
+
return train_loss, val_loss
|
238 |
+
|
239 |
+
|
240 |
+
def text_to_token_ids(text, tokenizer):
|
241 |
+
encoded = tokenizer.encode(text, allowed_special={'<|endoftext|>'})
|
242 |
+
encoded_tensor = torch.tensor(encoded).unsqueeze(0) # add batch dimension
|
243 |
+
return encoded_tensor
|
244 |
+
|
245 |
+
|
246 |
+
def token_ids_to_text(token_ids, tokenizer):
|
247 |
+
flat = token_ids.squeeze(0) # remove batch dimension
|
248 |
+
return tokenizer.decode(flat.tolist())
|
249 |
+
|
250 |
+
|
251 |
+
def generate_and_print_sample(model, tokenizer, device, start_context):
|
252 |
+
model.eval()
|
253 |
+
context_size = model.pos_emb.weight.shape[0]
|
254 |
+
encoded = text_to_token_ids(start_context, tokenizer).to(device)
|
255 |
+
with torch.no_grad():
|
256 |
+
token_ids = generate_text_simple(
|
257 |
+
model=model, idx=encoded,
|
258 |
+
max_new_tokens=50, context_size=context_size
|
259 |
+
)
|
260 |
+
decoded_text = token_ids_to_text(token_ids, tokenizer)
|
261 |
+
print(decoded_text.replace("\n", " ")) # Compact print format
|
262 |
+
model.train()
|
263 |
+
|
264 |
+
|
265 |
+
def plot_losses(epochs_seen, tokens_seen, train_losses, val_losses):
|
266 |
+
fig, ax1 = plt.subplots(figsize=(5, 3))
|
267 |
+
|
268 |
+
# Plot training and validation loss against epochs
|
269 |
+
ax1.plot(epochs_seen, train_losses, label="Training loss")
|
270 |
+
ax1.plot(epochs_seen, val_losses, linestyle="-.", label="Validation loss")
|
271 |
+
ax1.set_xlabel("Epochs")
|
272 |
+
ax1.set_ylabel("Loss")
|
273 |
+
ax1.legend(loc="upper right")
|
274 |
+
ax1.xaxis.set_major_locator(MaxNLocator(integer=True)) # only show integer labels on x-axis
|
275 |
+
|
276 |
+
# Create a second x-axis for tokens seen
|
277 |
+
ax2 = ax1.twiny() # Create a second x-axis that shares the same y-axis
|
278 |
+
ax2.plot(tokens_seen, train_losses, alpha=0) # Invisible plot for aligning ticks
|
279 |
+
ax2.set_xlabel("Tokens seen")
|
280 |
+
|
281 |
+
fig.tight_layout() # Adjust layout to make room
|
282 |
+
plt.savefig("loss-plot.pdf")
|
283 |
+
plt.show()
|
284 |
+
|
285 |
+
|
286 |
+
def generate_text_simple(model, idx, max_new_tokens, context_size):
|
287 |
+
# idx is (batch, n_tokens) array of indices in the current context
|
288 |
+
for _ in range(max_new_tokens):
|
289 |
+
|
290 |
+
# Crop current context if it exceeds the supported context size
|
291 |
+
# E.g., if LLM supports only 5 tokens, and the context size is 10
|
292 |
+
# then only the last 5 tokens are used as context
|
293 |
+
idx_cond = idx[:, -context_size:]
|
294 |
+
|
295 |
+
# Get the predictions
|
296 |
+
with torch.no_grad():
|
297 |
+
logits = model(idx_cond)
|
298 |
+
|
299 |
+
# Focus only on the last time step
|
300 |
+
# (batch, n_tokens, vocab_size) becomes (batch, vocab_size)
|
301 |
+
logits = logits[:, -1, :]
|
302 |
+
|
303 |
+
# Apply softmax to get probabilities
|
304 |
+
probas = torch.softmax(logits, dim=-1) # (batch, vocab_size)
|
305 |
+
|
306 |
+
# Get the idx of the vocab entry with the highest probability value
|
307 |
+
idx_next = torch.argmax(probas, dim=-1, keepdim=True) # (batch, 1)
|
308 |
+
|
309 |
+
# Append sampled index to the running sequence
|
310 |
+
idx = torch.cat((idx, idx_next), dim=1) # (batch, n_tokens+1)
|
311 |
+
|
312 |
+
return idx
|