previous_chapters.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. # This file collects all the relevant code that we covered thus far
  2. # throughout Chapters 2-4.
  3. # This file can be run as a standalone script.
  4. import tiktoken
  5. import torch
  6. import torch.nn as nn
  7. from torch.utils.data import Dataset, DataLoader
  8. #####################################
  9. # Chapter 2
  10. #####################################
  11. class GPTDatasetV1(Dataset):
  12. def __init__(self, txt, tokenizer, max_length, stride):
  13. self.tokenizer = tokenizer
  14. self.input_ids = []
  15. self.target_ids = []
  16. # Tokenize the entire text
  17. token_ids = tokenizer.encode(txt)
  18. # Use a sliding window to chunk the book into overlapping sequences of max_length
  19. for i in range(0, len(token_ids) - max_length, stride):
  20. input_chunk = token_ids[i:i + max_length]
  21. target_chunk = token_ids[i + 1: i + max_length + 1]
  22. self.input_ids.append(torch.tensor(input_chunk))
  23. self.target_ids.append(torch.tensor(target_chunk))
  24. def __len__(self):
  25. return len(self.input_ids)
  26. def __getitem__(self, idx):
  27. return self.input_ids[idx], self.target_ids[idx]
  28. def create_dataloader_v1(txt, batch_size=4, max_length=256,
  29. stride=128, shuffle=True, drop_last=True):
  30. # Initialize the tokenizer
  31. tokenizer = tiktoken.get_encoding("gpt2")
  32. # Create dataset
  33. dataset = GPTDatasetV1(txt, tokenizer, max_length, stride)
  34. # Create dataloader
  35. dataloader = DataLoader(
  36. dataset, batch_size=batch_size, shuffle=shuffle, drop_last=drop_last)
  37. return dataloader
  38. #####################################
  39. # Chapter 3
  40. #####################################
  41. class MultiHeadAttention(nn.Module):
  42. def __init__(self, d_in, d_out, context_length, dropout, num_heads, qkv_bias=False):
  43. super().__init__()
  44. assert d_out % num_heads == 0, "d_out must be divisible by n_heads"
  45. self.d_out = d_out
  46. self.num_heads = num_heads
  47. self.head_dim = d_out // num_heads # Reduce the projection dim to match desired output dim
  48. self.W_query = nn.Linear(d_in, d_out, bias=qkv_bias)
  49. self.W_key = nn.Linear(d_in, d_out, bias=qkv_bias)
  50. self.W_value = nn.Linear(d_in, d_out, bias=qkv_bias)
  51. self.out_proj = nn.Linear(d_out, d_out) # Linear layer to combine head outputs
  52. self.dropout = nn.Dropout(dropout)
  53. self.register_buffer('mask', torch.triu(torch.ones(context_length, context_length), diagonal=1))
  54. def forward(self, x):
  55. b, num_tokens, d_in = x.shape
  56. keys = self.W_key(x) # Shape: (b, num_tokens, d_out)
  57. queries = self.W_query(x)
  58. values = self.W_value(x)
  59. # We implicitly split the matrix by adding a `num_heads` dimension
  60. # Unroll last dim: (b, num_tokens, d_out) -> (b, num_tokens, num_heads, head_dim)
  61. keys = keys.view(b, num_tokens, self.num_heads, self.head_dim)
  62. values = values.view(b, num_tokens, self.num_heads, self.head_dim)
  63. queries = queries.view(b, num_tokens, self.num_heads, self.head_dim)
  64. # Transpose: (b, num_tokens, num_heads, head_dim) -> (b, num_heads, num_tokens, head_dim)
  65. keys = keys.transpose(1, 2)
  66. queries = queries.transpose(1, 2)
  67. values = values.transpose(1, 2)
  68. # Compute scaled dot-product attention (aka self-attention) with a causal mask
  69. attn_scores = queries @ keys.transpose(2, 3) # Dot product for each head
  70. # Original mask truncated to the number of tokens and converted to boolean
  71. mask_bool = self.mask.bool()[:num_tokens, :num_tokens]
  72. # Use the mask to fill attention scores
  73. attn_scores.masked_fill_(mask_bool, -torch.inf)
  74. attn_weights = torch.softmax(attn_scores / keys.shape[-1]**0.5, dim=-1)
  75. attn_weights = self.dropout(attn_weights)
  76. # Shape: (b, num_tokens, num_heads, head_dim)
  77. context_vec = (attn_weights @ values).transpose(1, 2)
  78. # Combine heads, where self.d_out = self.num_heads * self.head_dim
  79. context_vec = context_vec.reshape(b, num_tokens, self.d_out)
  80. context_vec = self.out_proj(context_vec) # optional projection
  81. return context_vec
  82. #####################################
  83. # Chapter 4
  84. #####################################
  85. class LayerNorm(nn.Module):
  86. def __init__(self, emb_dim):
  87. super().__init__()
  88. self.eps = 1e-5
  89. self.scale = nn.Parameter(torch.ones(emb_dim))
  90. self.shift = nn.Parameter(torch.zeros(emb_dim))
  91. def forward(self, x):
  92. mean = x.mean(dim=-1, keepdim=True)
  93. var = x.var(dim=-1, keepdim=True, unbiased=False)
  94. norm_x = (x - mean) / torch.sqrt(var + self.eps)
  95. return self.scale * norm_x + self.shift
  96. class GELU(nn.Module):
  97. def __init__(self):
  98. super().__init__()
  99. def forward(self, x):
  100. return 0.5 * x * (1 + torch.tanh(
  101. torch.sqrt(torch.tensor(2.0 / torch.pi)) *
  102. (x + 0.044715 * torch.pow(x, 3))
  103. ))
  104. class FeedForward(nn.Module):
  105. def __init__(self, cfg):
  106. super().__init__()
  107. self.layers = nn.Sequential(
  108. nn.Linear(cfg["emb_dim"], 4 * cfg["emb_dim"]),
  109. GELU(),
  110. nn.Linear(4 * cfg["emb_dim"], cfg["emb_dim"]),
  111. )
  112. def forward(self, x):
  113. return self.layers(x)
  114. class TransformerBlock(nn.Module):
  115. def __init__(self, cfg):
  116. super().__init__()
  117. self.att = MultiHeadAttention(
  118. d_in=cfg["emb_dim"],
  119. d_out=cfg["emb_dim"],
  120. context_length=cfg["context_length"],
  121. num_heads=cfg["n_heads"],
  122. dropout=cfg["drop_rate"],
  123. qkv_bias=cfg["qkv_bias"])
  124. self.ff = FeedForward(cfg)
  125. self.norm1 = LayerNorm(cfg["emb_dim"])
  126. self.norm2 = LayerNorm(cfg["emb_dim"])
  127. self.drop_resid = nn.Dropout(cfg["drop_rate"])
  128. def forward(self, x):
  129. # Shortcut connection for attention block
  130. shortcut = x
  131. x = self.norm1(x)
  132. x = self.att(x) # Shape [batch_size, num_tokens, emb_size]
  133. x = self.drop_resid(x)
  134. x = x + shortcut # Add the original input back
  135. # Shortcut connection for feed-forward block
  136. shortcut = x
  137. x = self.norm2(x)
  138. x = self.ff(x)
  139. x = self.drop_resid(x)
  140. x = x + shortcut # Add the original input back
  141. return x
  142. class GPTModel(nn.Module):
  143. def __init__(self, cfg):
  144. super().__init__()
  145. self.tok_emb = nn.Embedding(cfg["vocab_size"], cfg["emb_dim"])
  146. self.pos_emb = nn.Embedding(cfg["context_length"], cfg["emb_dim"])
  147. self.drop_emb = nn.Dropout(cfg["drop_rate"])
  148. self.trf_blocks = nn.Sequential(
  149. *[TransformerBlock(cfg) for _ in range(cfg["n_layers"])])
  150. self.final_norm = LayerNorm(cfg["emb_dim"])
  151. self.out_head = nn.Linear(cfg["emb_dim"], cfg["vocab_size"], bias=False)
  152. def forward(self, in_idx):
  153. batch_size, seq_len = in_idx.shape
  154. tok_embeds = self.tok_emb(in_idx)
  155. pos_embeds = self.pos_emb(torch.arange(seq_len, device=in_idx.device))
  156. x = tok_embeds + pos_embeds # Shape [batch_size, num_tokens, emb_size]
  157. x = self.drop_emb(x)
  158. x = self.trf_blocks(x)
  159. x = self.final_norm(x)
  160. logits = self.out_head(x)
  161. return logits
  162. def generate_text_simple(model, idx, max_new_tokens, context_size):
  163. # idx is (B, T) array of indices in the current context
  164. for _ in range(max_new_tokens):
  165. # Crop current context if it exceeds the supported context size
  166. # E.g., if LLM supports only 5 tokens, and the context size is 10
  167. # then only the last 5 tokens are used as context
  168. idx_cond = idx[:, -context_size:]
  169. # Get the predictions
  170. with torch.no_grad():
  171. logits = model(idx_cond)
  172. # Focus only on the last time step
  173. # (batch, n_token, vocab_size) becomes (batch, vocab_size)
  174. logits = logits[:, -1, :]
  175. # Get the idx of the vocab entry with the highest logits value
  176. idx_next = torch.argmax(logits, dim=-1, keepdim=True) # (batch, 1)
  177. # Append sampled index to the running sequence
  178. idx = torch.cat((idx, idx_next), dim=1) # (batch, n_tokens+1)
  179. return idx
  180. #####################################
  181. # Chapter 5
  182. #####################################
  183. def text_to_token_ids(text, tokenizer):
  184. encoded = tokenizer.encode(text)
  185. encoded_tensor = torch.tensor(encoded).unsqueeze(0) # add batch dimension
  186. return encoded_tensor
  187. def token_ids_to_text(token_ids, tokenizer):
  188. flat = token_ids.squeeze(0) # remove batch dimension
  189. return tokenizer.decode(flat.tolist())
  190. def generate(model, idx, max_new_tokens, context_size, temperature, top_k=None):
  191. # For-loop is the same as before: Get logits, and only focus on last time step
  192. for _ in range(max_new_tokens):
  193. idx_cond = idx[:, -context_size:]
  194. with torch.no_grad():
  195. logits = model(idx_cond)
  196. logits = logits[:, -1, :]
  197. # New: Filter logits with top_k sampling
  198. if top_k is not None:
  199. # Keep only top_k values
  200. top_logits, _ = torch.topk(logits, top_k)
  201. min_val = top_logits[:, -1]
  202. logits = torch.where(logits < min_val, torch.tensor(float('-inf')).to(logits.device), logits)
  203. # New: Apply temperature scaling
  204. if temperature > 0.0:
  205. logits = logits / temperature
  206. # Apply softmax to get probabilities
  207. probs = torch.softmax(logits, dim=-1) # (batch_size, context_len)
  208. # Sample from the distribution
  209. idx_next = torch.multinomial(probs, num_samples=1) # (batch_size, 1)
  210. # Otherwise same as before: get idx of the vocab entry with the highest logits value
  211. else:
  212. idx_next = torch.argmax(logits, dim=-1, keepdim=True) # (batch_size, 1)
  213. # Same as before: append sampled index to the running sequence
  214. idx = torch.cat((idx, idx_next), dim=1) # (batch_size, num_tokens+1)
  215. return idx