previous_chapters.py 9.7 KB

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