previous_chapters.py 9.9 KB

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