previous_chapters.py 11 KB

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