previous_chapters.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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. import torch
  9. import torch.nn as nn
  10. #####################################
  11. # Chapter 3
  12. #####################################
  13. class MultiHeadAttention(nn.Module):
  14. def __init__(self, d_in, d_out, context_length, dropout, num_heads, qkv_bias=False):
  15. super().__init__()
  16. assert d_out % num_heads == 0, "d_out must be divisible by n_heads"
  17. self.d_out = d_out
  18. self.num_heads = num_heads
  19. self.head_dim = d_out // num_heads # Reduce the projection dim to match desired output dim
  20. self.W_query = nn.Linear(d_in, d_out, bias=qkv_bias)
  21. self.W_key = nn.Linear(d_in, d_out, bias=qkv_bias)
  22. self.W_value = nn.Linear(d_in, d_out, bias=qkv_bias)
  23. self.out_proj = nn.Linear(d_out, d_out) # Linear layer to combine head outputs
  24. self.dropout = nn.Dropout(dropout)
  25. self.register_buffer('mask', torch.triu(torch.ones(context_length, context_length), diagonal=1))
  26. def forward(self, x):
  27. b, num_tokens, d_in = x.shape
  28. keys = self.W_key(x) # Shape: (b, num_tokens, d_out)
  29. queries = self.W_query(x)
  30. values = self.W_value(x)
  31. # We implicitly split the matrix by adding a `num_heads` dimension
  32. # Unroll last dim: (b, num_tokens, d_out) -> (b, num_tokens, num_heads, head_dim)
  33. keys = keys.view(b, num_tokens, self.num_heads, self.head_dim)
  34. values = values.view(b, num_tokens, self.num_heads, self.head_dim)
  35. queries = queries.view(b, num_tokens, self.num_heads, self.head_dim)
  36. # Transpose: (b, num_tokens, num_heads, head_dim) -> (b, num_heads, num_tokens, head_dim)
  37. keys = keys.transpose(1, 2)
  38. queries = queries.transpose(1, 2)
  39. values = values.transpose(1, 2)
  40. # Compute scaled dot-product attention (aka self-attention) with a causal mask
  41. attn_scores = queries @ keys.transpose(2, 3) # Dot product for each head
  42. # Original mask truncated to the number of tokens and converted to boolean
  43. mask_bool = self.mask.bool()[:num_tokens, :num_tokens]
  44. # Use the mask to fill attention scores
  45. attn_scores.masked_fill_(mask_bool, -torch.inf)
  46. attn_weights = torch.softmax(attn_scores / keys.shape[-1]**0.5, dim=-1)
  47. attn_weights = self.dropout(attn_weights)
  48. # Shape: (b, num_tokens, num_heads, head_dim)
  49. context_vec = (attn_weights @ values).transpose(1, 2)
  50. # Combine heads, where self.d_out = self.num_heads * self.head_dim
  51. context_vec = context_vec.reshape(b, num_tokens, self.d_out)
  52. context_vec = self.out_proj(context_vec) # optional projection
  53. return context_vec
  54. #####################################
  55. # Chapter 4
  56. #####################################
  57. class LayerNorm(nn.Module):
  58. def __init__(self, emb_dim):
  59. super().__init__()
  60. self.eps = 1e-5
  61. self.scale = nn.Parameter(torch.ones(emb_dim))
  62. self.shift = nn.Parameter(torch.zeros(emb_dim))
  63. def forward(self, x):
  64. mean = x.mean(dim=-1, keepdim=True)
  65. var = x.var(dim=-1, keepdim=True, unbiased=False)
  66. norm_x = (x - mean) / torch.sqrt(var + self.eps)
  67. return self.scale * norm_x + self.shift
  68. class GELU(nn.Module):
  69. def __init__(self):
  70. super().__init__()
  71. def forward(self, x):
  72. return 0.5 * x * (1 + torch.tanh(
  73. torch.sqrt(torch.tensor(2.0 / torch.pi)) *
  74. (x + 0.044715 * torch.pow(x, 3))
  75. ))
  76. class FeedForward(nn.Module):
  77. def __init__(self, cfg):
  78. super().__init__()
  79. self.layers = nn.Sequential(
  80. nn.Linear(cfg["emb_dim"], 4 * cfg["emb_dim"]),
  81. GELU(),
  82. nn.Linear(4 * cfg["emb_dim"], cfg["emb_dim"]),
  83. )
  84. def forward(self, x):
  85. return self.layers(x)
  86. class TransformerBlock(nn.Module):
  87. def __init__(self, cfg):
  88. super().__init__()
  89. self.att = MultiHeadAttention(
  90. d_in=cfg["emb_dim"],
  91. d_out=cfg["emb_dim"],
  92. context_length=cfg["context_length"],
  93. num_heads=cfg["n_heads"],
  94. dropout=cfg["drop_rate"],
  95. qkv_bias=cfg["qkv_bias"])
  96. self.ff = FeedForward(cfg)
  97. self.norm1 = LayerNorm(cfg["emb_dim"])
  98. self.norm2 = LayerNorm(cfg["emb_dim"])
  99. self.drop_shortcut = nn.Dropout(cfg["drop_rate"])
  100. def forward(self, x):
  101. # Shortcut connection for attention block
  102. shortcut = x
  103. x = self.norm1(x)
  104. x = self.att(x) # Shape [batch_size, num_tokens, emb_size]
  105. x = self.drop_shortcut(x)
  106. x = x + shortcut # Add the original input back
  107. # Shortcut connection for feed-forward block
  108. shortcut = x
  109. x = self.norm2(x)
  110. x = self.ff(x)
  111. x = self.drop_shortcut(x)
  112. x = x + shortcut # Add the original input back
  113. return x
  114. class GPTModel(nn.Module):
  115. def __init__(self, cfg):
  116. super().__init__()
  117. self.tok_emb = nn.Embedding(cfg["vocab_size"], cfg["emb_dim"])
  118. self.pos_emb = nn.Embedding(cfg["context_length"], cfg["emb_dim"])
  119. self.drop_emb = nn.Dropout(cfg["drop_rate"])
  120. self.trf_blocks = nn.Sequential(
  121. *[TransformerBlock(cfg) for _ in range(cfg["n_layers"])])
  122. self.final_norm = LayerNorm(cfg["emb_dim"])
  123. self.out_head = nn.Linear(cfg["emb_dim"], cfg["vocab_size"], bias=False)
  124. def forward(self, in_idx):
  125. batch_size, seq_len = in_idx.shape
  126. tok_embeds = self.tok_emb(in_idx)
  127. pos_embeds = self.pos_emb(torch.arange(seq_len, device=in_idx.device))
  128. x = tok_embeds + pos_embeds # Shape [batch_size, num_tokens, emb_size]
  129. x = self.drop_emb(x)
  130. x = self.trf_blocks(x)
  131. x = self.final_norm(x)
  132. logits = self.out_head(x)
  133. return logits