previous_chapters.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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, disable_causal_mask=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. if not disable_causal_mask:
  59. self.register_buffer('mask', torch.triu(torch.ones(context_length, context_length), diagonal=1))
  60. self.disable_causal_mask = disable_causal_mask
  61. def forward(self, x):
  62. b, num_tokens, d_in = x.shape
  63. keys = self.W_key(x) # Shape: (b, num_tokens, d_out)
  64. queries = self.W_query(x)
  65. values = self.W_value(x)
  66. # We implicitly split the matrix by adding a `num_heads` dimension
  67. # Unroll last dim: (b, num_tokens, d_out) -> (b, num_tokens, num_heads, head_dim)
  68. keys = keys.view(b, num_tokens, self.num_heads, self.head_dim)
  69. values = values.view(b, num_tokens, self.num_heads, self.head_dim)
  70. queries = queries.view(b, num_tokens, self.num_heads, self.head_dim)
  71. # Transpose: (b, num_tokens, num_heads, head_dim) -> (b, num_heads, num_tokens, head_dim)
  72. keys = keys.transpose(1, 2)
  73. queries = queries.transpose(1, 2)
  74. values = values.transpose(1, 2)
  75. # Compute scaled dot-product attention (aka self-attention) with a causal mask
  76. attn_scores = queries @ keys.transpose(2, 3) # Dot product for each head
  77. if not self.disable_causal_mask:
  78. # Original mask truncated to the number of tokens and converted to boolean
  79. mask_bool = self.mask.bool()[:num_tokens, :num_tokens]
  80. # Use the mask to fill attention scores
  81. attn_scores.masked_fill_(mask_bool, -torch.inf)
  82. attn_weights = torch.softmax(attn_scores / keys.shape[-1]**0.5, dim=-1)
  83. attn_weights = self.dropout(attn_weights)
  84. # Shape: (b, num_tokens, num_heads, head_dim)
  85. context_vec = (attn_weights @ values).transpose(1, 2)
  86. # Combine heads, where self.d_out = self.num_heads * self.head_dim
  87. context_vec = context_vec.reshape(b, num_tokens, self.d_out)
  88. context_vec = self.out_proj(context_vec) # optional projection
  89. return context_vec
  90. #####################################
  91. # Chapter 4
  92. #####################################
  93. class LayerNorm(nn.Module):
  94. def __init__(self, emb_dim):
  95. super().__init__()
  96. self.eps = 1e-5
  97. self.scale = nn.Parameter(torch.ones(emb_dim))
  98. self.shift = nn.Parameter(torch.zeros(emb_dim))
  99. def forward(self, x):
  100. mean = x.mean(dim=-1, keepdim=True)
  101. var = x.var(dim=-1, keepdim=True, unbiased=False)
  102. norm_x = (x - mean) / torch.sqrt(var + self.eps)
  103. return self.scale * norm_x + self.shift
  104. class GELU(nn.Module):
  105. def __init__(self):
  106. super().__init__()
  107. def forward(self, x):
  108. return 0.5 * x * (1 + torch.tanh(
  109. torch.sqrt(torch.tensor(2.0 / torch.pi)) *
  110. (x + 0.044715 * torch.pow(x, 3))
  111. ))
  112. class FeedForward(nn.Module):
  113. def __init__(self, cfg):
  114. super().__init__()
  115. self.layers = nn.Sequential(
  116. nn.Linear(cfg["emb_dim"], 4 * cfg["emb_dim"]),
  117. GELU(),
  118. nn.Linear(4 * cfg["emb_dim"], cfg["emb_dim"]),
  119. )
  120. def forward(self, x):
  121. return self.layers(x)
  122. class TransformerBlock(nn.Module):
  123. def __init__(self, cfg, disable_causal_mask=False):
  124. super().__init__()
  125. self.att = MultiHeadAttention(
  126. d_in=cfg["emb_dim"],
  127. d_out=cfg["emb_dim"],
  128. context_length=cfg["context_length"],
  129. num_heads=cfg["n_heads"],
  130. dropout=cfg["drop_rate"],
  131. qkv_bias=cfg["qkv_bias"],
  132. disable_causal_mask=disable_causal_mask
  133. )
  134. self.ff = FeedForward(cfg)
  135. self.norm1 = LayerNorm(cfg["emb_dim"])
  136. self.norm2 = LayerNorm(cfg["emb_dim"])
  137. self.drop_shortcut = nn.Dropout(cfg["drop_rate"])
  138. def forward(self, x):
  139. # Shortcut connection for attention block
  140. shortcut = x
  141. x = self.norm1(x)
  142. x = self.att(x) # Shape [batch_size, num_tokens, emb_size]
  143. x = self.drop_shortcut(x)
  144. x = x + shortcut # Add the original input back
  145. # Shortcut connection for feed-forward block
  146. shortcut = x
  147. x = self.norm2(x)
  148. x = self.ff(x)
  149. x = self.drop_shortcut(x)
  150. x = x + shortcut # Add the original input back
  151. return x
  152. class GPTModel(nn.Module):
  153. def __init__(self, cfg, disable_causal_mask=False):
  154. super().__init__()
  155. self.tok_emb = nn.Embedding(cfg["vocab_size"], cfg["emb_dim"])
  156. self.pos_emb = nn.Embedding(cfg["context_length"], cfg["emb_dim"])
  157. self.drop_emb = nn.Dropout(cfg["drop_rate"])
  158. self.trf_blocks = nn.Sequential(
  159. *[TransformerBlock(cfg, disable_causal_mask) for _ in range(cfg["n_layers"])])
  160. self.final_norm = LayerNorm(cfg["emb_dim"])
  161. self.out_head = nn.Linear(cfg["emb_dim"], cfg["vocab_size"], bias=False)
  162. def forward(self, in_idx):
  163. batch_size, seq_len = in_idx.shape
  164. tok_embeds = self.tok_emb(in_idx)
  165. pos_embeds = self.pos_emb(torch.arange(seq_len, device=in_idx.device))
  166. x = tok_embeds + pos_embeds # Shape [batch_size, num_tokens, emb_size]
  167. x = self.drop_emb(x)
  168. x = self.trf_blocks(x)
  169. x = self.final_norm(x)
  170. logits = self.out_head(x)
  171. return logits
  172. def generate_text_simple(model, idx, max_new_tokens, context_size):
  173. # idx is (B, T) array of indices in the current context
  174. for _ in range(max_new_tokens):
  175. # Crop current context if it exceeds the supported context size
  176. # E.g., if LLM supports only 5 tokens, and the context size is 10
  177. # then only the last 5 tokens are used as context
  178. idx_cond = idx[:, -context_size:]
  179. # Get the predictions
  180. with torch.no_grad():
  181. logits = model(idx_cond)
  182. # Focus only on the last time step
  183. # (batch, n_token, vocab_size) becomes (batch, vocab_size)
  184. logits = logits[:, -1, :]
  185. # Get the idx of the vocab entry with the highest logits value
  186. idx_next = torch.argmax(logits, dim=-1, keepdim=True) # (batch, 1)
  187. # Append sampled index to the running sequence
  188. idx = torch.cat((idx, idx_next), dim=1) # (batch, n_tokens+1)
  189. return idx
  190. #####################################
  191. # Chapter 5
  192. #####################################
  193. def assign(left, right):
  194. if left.shape != right.shape:
  195. raise ValueError(f"Shape mismatch. Left: {left.shape}, Right: {right.shape}")
  196. return torch.nn.Parameter(torch.tensor(right))
  197. def load_weights_into_gpt(gpt, params):
  198. gpt.pos_emb.weight = assign(gpt.pos_emb.weight, params['wpe'])
  199. gpt.tok_emb.weight = assign(gpt.tok_emb.weight, params['wte'])
  200. for b in range(len(params["blocks"])):
  201. q_w, k_w, v_w = np.split(
  202. (params["blocks"][b]["attn"]["c_attn"])["w"], 3, axis=-1)
  203. gpt.trf_blocks[b].att.W_query.weight = assign(
  204. gpt.trf_blocks[b].att.W_query.weight, q_w.T)
  205. gpt.trf_blocks[b].att.W_key.weight = assign(
  206. gpt.trf_blocks[b].att.W_key.weight, k_w.T)
  207. gpt.trf_blocks[b].att.W_value.weight = assign(
  208. gpt.trf_blocks[b].att.W_value.weight, v_w.T)
  209. q_b, k_b, v_b = np.split(
  210. (params["blocks"][b]["attn"]["c_attn"])["b"], 3, axis=-1)
  211. gpt.trf_blocks[b].att.W_query.bias = assign(
  212. gpt.trf_blocks[b].att.W_query.bias, q_b)
  213. gpt.trf_blocks[b].att.W_key.bias = assign(
  214. gpt.trf_blocks[b].att.W_key.bias, k_b)
  215. gpt.trf_blocks[b].att.W_value.bias = assign(
  216. gpt.trf_blocks[b].att.W_value.bias, v_b)
  217. gpt.trf_blocks[b].att.out_proj.weight = assign(
  218. gpt.trf_blocks[b].att.out_proj.weight,
  219. params["blocks"][b]["attn"]["c_proj"]["w"].T)
  220. gpt.trf_blocks[b].att.out_proj.bias = assign(
  221. gpt.trf_blocks[b].att.out_proj.bias,
  222. params["blocks"][b]["attn"]["c_proj"]["b"])
  223. gpt.trf_blocks[b].ff.layers[0].weight = assign(
  224. gpt.trf_blocks[b].ff.layers[0].weight,
  225. params["blocks"][b]["mlp"]["c_fc"]["w"].T)
  226. gpt.trf_blocks[b].ff.layers[0].bias = assign(
  227. gpt.trf_blocks[b].ff.layers[0].bias,
  228. params["blocks"][b]["mlp"]["c_fc"]["b"])
  229. gpt.trf_blocks[b].ff.layers[2].weight = assign(
  230. gpt.trf_blocks[b].ff.layers[2].weight,
  231. params["blocks"][b]["mlp"]["c_proj"]["w"].T)
  232. gpt.trf_blocks[b].ff.layers[2].bias = assign(
  233. gpt.trf_blocks[b].ff.layers[2].bias,
  234. params["blocks"][b]["mlp"]["c_proj"]["b"])
  235. gpt.trf_blocks[b].norm1.scale = assign(
  236. gpt.trf_blocks[b].norm1.scale,
  237. params["blocks"][b]["ln_1"]["g"])
  238. gpt.trf_blocks[b].norm1.shift = assign(
  239. gpt.trf_blocks[b].norm1.shift,
  240. params["blocks"][b]["ln_1"]["b"])
  241. gpt.trf_blocks[b].norm2.scale = assign(
  242. gpt.trf_blocks[b].norm2.scale,
  243. params["blocks"][b]["ln_2"]["g"])
  244. gpt.trf_blocks[b].norm2.shift = assign(
  245. gpt.trf_blocks[b].norm2.shift,
  246. params["blocks"][b]["ln_2"]["b"])
  247. gpt.final_norm.scale = assign(gpt.final_norm.scale, params["g"])
  248. gpt.final_norm.shift = assign(gpt.final_norm.shift, params["b"])
  249. gpt.out_head.weight = assign(gpt.out_head.weight, params["wte"])
  250. def generate(model, idx, max_new_tokens, context_size, temperature=0.0, top_k=None, eos_id=None):
  251. # For-loop is the same as before: Get logits, and only focus on last time step
  252. for _ in range(max_new_tokens):
  253. idx_cond = idx[:, -context_size:]
  254. with torch.no_grad():
  255. logits = model(idx_cond)
  256. logits = logits[:, -1, :]
  257. # New: Filter logits with top_k sampling
  258. if top_k is not None:
  259. # Keep only top_k values
  260. top_logits, _ = torch.topk(logits, top_k)
  261. min_val = top_logits[:, -1]
  262. logits = torch.where(logits < min_val, torch.tensor(float('-inf')).to(logits.device), logits)
  263. # New: Apply temperature scaling
  264. if temperature > 0.0:
  265. logits = logits / temperature
  266. # Apply softmax to get probabilities
  267. probs = torch.softmax(logits, dim=-1) # (batch_size, context_len)
  268. # Sample from the distribution
  269. idx_next = torch.multinomial(probs, num_samples=1) # (batch_size, 1)
  270. # Otherwise same as before: get idx of the vocab entry with the highest logits value
  271. else:
  272. idx_next = torch.argmax(logits, dim=-1, keepdim=True) # (batch_size, 1)
  273. if idx_next == eos_id: # Stop generating early if end-of-sequence token is encountered and eos_id is specified
  274. break
  275. # Same as before: append sampled index to the running sequence
  276. idx = torch.cat((idx, idx_next), dim=1) # (batch_size, num_tokens+1)
  277. return idx