previous_chapters.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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. # This file collects all the relevant code that we covered thus far
  7. # throughout Chapters 2-5.
  8. # This file can be run as a standalone script.
  9. import numpy as np
  10. import tiktoken
  11. import torch
  12. import torch.nn as nn
  13. from torch.utils.data import Dataset, DataLoader
  14. #####################################
  15. # Chapter 2
  16. #####################################
  17. class GPTDatasetV1(Dataset):
  18. def __init__(self, txt, tokenizer, max_length, stride):
  19. self.input_ids = []
  20. self.target_ids = []
  21. # Tokenize the entire text
  22. token_ids = tokenizer.encode(txt, allowed_special={"<|endoftext|>"})
  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, num_workers=0):
  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, num_workers=num_workers)
  42. return dataloader
  43. #####################################
  44. # Chapter 3
  45. #####################################
  46. class MultiHeadAttention(nn.Module):
  47. def __init__(self, d_in, d_out, context_length, 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(context_length, context_length), 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. )
  117. def forward(self, x):
  118. return self.layers(x)
  119. class TransformerBlock(nn.Module):
  120. def __init__(self, cfg):
  121. super().__init__()
  122. self.att = MultiHeadAttention(
  123. d_in=cfg["emb_dim"],
  124. d_out=cfg["emb_dim"],
  125. context_length=cfg["context_length"],
  126. num_heads=cfg["n_heads"],
  127. dropout=cfg["drop_rate"],
  128. qkv_bias=cfg["qkv_bias"])
  129. self.ff = FeedForward(cfg)
  130. self.norm1 = LayerNorm(cfg["emb_dim"])
  131. self.norm2 = LayerNorm(cfg["emb_dim"])
  132. self.drop_resid = nn.Dropout(cfg["drop_rate"])
  133. def forward(self, x):
  134. # Shortcut connection for attention block
  135. shortcut = x
  136. x = self.norm1(x)
  137. x = self.att(x) # Shape [batch_size, num_tokens, emb_size]
  138. x = self.drop_resid(x)
  139. x = x + shortcut # Add the original input back
  140. # Shortcut connection for feed-forward block
  141. shortcut = x
  142. x = self.norm2(x)
  143. x = self.ff(x)
  144. x = self.drop_resid(x)
  145. x = x + shortcut # Add the original input back
  146. return x
  147. class GPTModel(nn.Module):
  148. def __init__(self, cfg):
  149. super().__init__()
  150. self.tok_emb = nn.Embedding(cfg["vocab_size"], cfg["emb_dim"])
  151. self.pos_emb = nn.Embedding(cfg["context_length"], cfg["emb_dim"])
  152. self.drop_emb = nn.Dropout(cfg["drop_rate"])
  153. self.trf_blocks = nn.Sequential(
  154. *[TransformerBlock(cfg) for _ in range(cfg["n_layers"])])
  155. self.final_norm = LayerNorm(cfg["emb_dim"])
  156. self.out_head = nn.Linear(cfg["emb_dim"], cfg["vocab_size"], bias=False)
  157. def forward(self, in_idx):
  158. batch_size, seq_len = in_idx.shape
  159. tok_embeds = self.tok_emb(in_idx)
  160. pos_embeds = self.pos_emb(torch.arange(seq_len, device=in_idx.device))
  161. x = tok_embeds + pos_embeds # Shape [batch_size, num_tokens, emb_size]
  162. x = self.drop_emb(x)
  163. x = self.trf_blocks(x)
  164. x = self.final_norm(x)
  165. logits = self.out_head(x)
  166. return logits
  167. def generate_text_simple(model, idx, max_new_tokens, context_size):
  168. # idx is (B, T) array of indices in the current context
  169. for _ in range(max_new_tokens):
  170. # Crop current context if it exceeds the supported context size
  171. # E.g., if LLM supports only 5 tokens, and the context size is 10
  172. # then only the last 5 tokens are used as context
  173. idx_cond = idx[:, -context_size:]
  174. # Get the predictions
  175. with torch.no_grad():
  176. logits = model(idx_cond)
  177. # Focus only on the last time step
  178. # (batch, n_token, vocab_size) becomes (batch, vocab_size)
  179. logits = logits[:, -1, :]
  180. # Get the idx of the vocab entry with the highest logits value
  181. idx_next = torch.argmax(logits, dim=-1, keepdim=True) # (batch, 1)
  182. # Append sampled index to the running sequence
  183. idx = torch.cat((idx, idx_next), dim=1) # (batch, n_tokens+1)
  184. return idx
  185. #####################################
  186. # Chapter 5
  187. #####################################
  188. def assign(left, right):
  189. if left.shape != right.shape:
  190. raise ValueError(f"Shape mismatch. Left: {left.shape}, Right: {right.shape}")
  191. return torch.nn.Parameter(torch.tensor(right))
  192. def load_weights_into_gpt(gpt, params):
  193. gpt.pos_emb.weight = assign(gpt.pos_emb.weight, params['wpe'])
  194. gpt.tok_emb.weight = assign(gpt.tok_emb.weight, params['wte'])
  195. for b in range(len(params["blocks"])):
  196. q_w, k_w, v_w = np.split(
  197. (params["blocks"][b]["attn"]["c_attn"])["w"], 3, axis=-1)
  198. gpt.trf_blocks[b].att.W_query.weight = assign(
  199. gpt.trf_blocks[b].att.W_query.weight, q_w.T)
  200. gpt.trf_blocks[b].att.W_key.weight = assign(
  201. gpt.trf_blocks[b].att.W_key.weight, k_w.T)
  202. gpt.trf_blocks[b].att.W_value.weight = assign(
  203. gpt.trf_blocks[b].att.W_value.weight, v_w.T)
  204. q_b, k_b, v_b = np.split(
  205. (params["blocks"][b]["attn"]["c_attn"])["b"], 3, axis=-1)
  206. gpt.trf_blocks[b].att.W_query.bias = assign(
  207. gpt.trf_blocks[b].att.W_query.bias, q_b)
  208. gpt.trf_blocks[b].att.W_key.bias = assign(
  209. gpt.trf_blocks[b].att.W_key.bias, k_b)
  210. gpt.trf_blocks[b].att.W_value.bias = assign(
  211. gpt.trf_blocks[b].att.W_value.bias, v_b)
  212. gpt.trf_blocks[b].att.out_proj.weight = assign(
  213. gpt.trf_blocks[b].att.out_proj.weight,
  214. params["blocks"][b]["attn"]["c_proj"]["w"].T)
  215. gpt.trf_blocks[b].att.out_proj.bias = assign(
  216. gpt.trf_blocks[b].att.out_proj.bias,
  217. params["blocks"][b]["attn"]["c_proj"]["b"])
  218. gpt.trf_blocks[b].ff.layers[0].weight = assign(
  219. gpt.trf_blocks[b].ff.layers[0].weight,
  220. params["blocks"][b]["mlp"]["c_fc"]["w"].T)
  221. gpt.trf_blocks[b].ff.layers[0].bias = assign(
  222. gpt.trf_blocks[b].ff.layers[0].bias,
  223. params["blocks"][b]["mlp"]["c_fc"]["b"])
  224. gpt.trf_blocks[b].ff.layers[2].weight = assign(
  225. gpt.trf_blocks[b].ff.layers[2].weight,
  226. params["blocks"][b]["mlp"]["c_proj"]["w"].T)
  227. gpt.trf_blocks[b].ff.layers[2].bias = assign(
  228. gpt.trf_blocks[b].ff.layers[2].bias,
  229. params["blocks"][b]["mlp"]["c_proj"]["b"])
  230. gpt.trf_blocks[b].norm1.scale = assign(
  231. gpt.trf_blocks[b].norm1.scale,
  232. params["blocks"][b]["ln_1"]["g"])
  233. gpt.trf_blocks[b].norm1.shift = assign(
  234. gpt.trf_blocks[b].norm1.shift,
  235. params["blocks"][b]["ln_1"]["b"])
  236. gpt.trf_blocks[b].norm2.scale = assign(
  237. gpt.trf_blocks[b].norm2.scale,
  238. params["blocks"][b]["ln_2"]["g"])
  239. gpt.trf_blocks[b].norm2.shift = assign(
  240. gpt.trf_blocks[b].norm2.shift,
  241. params["blocks"][b]["ln_2"]["b"])
  242. gpt.final_norm.scale = assign(gpt.final_norm.scale, params["g"])
  243. gpt.final_norm.shift = assign(gpt.final_norm.shift, params["b"])
  244. gpt.out_head.weight = assign(gpt.out_head.weight, params["wte"])
  245. def text_to_token_ids(text, tokenizer):
  246. encoded = tokenizer.encode(text, allowed_special={'<|endoftext|>'})
  247. encoded_tensor = torch.tensor(encoded).unsqueeze(0) # add batch dimension
  248. return encoded_tensor
  249. def token_ids_to_text(token_ids, tokenizer):
  250. flat = token_ids.squeeze(0) # remove batch dimension
  251. return tokenizer.decode(flat.tolist())