ch03.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  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. import torch
  6. import torch.nn as nn
  7. class SelfAttention_v1(nn.Module):
  8. def __init__(self, d_in, d_out):
  9. super().__init__()
  10. self.W_query = nn.Parameter(torch.rand(d_in, d_out))
  11. self.W_key = nn.Parameter(torch.rand(d_in, d_out))
  12. self.W_value = nn.Parameter(torch.rand(d_in, d_out))
  13. def forward(self, x):
  14. keys = x @ self.W_key
  15. queries = x @ self.W_query
  16. values = x @ self.W_value
  17. attn_scores = queries @ keys.T # omega
  18. attn_weights = torch.softmax(
  19. attn_scores / keys.shape[-1]**0.5, dim=-1
  20. )
  21. context_vec = attn_weights @ values
  22. return context_vec
  23. class SelfAttention_v2(nn.Module):
  24. def __init__(self, d_in, d_out, qkv_bias=False):
  25. super().__init__()
  26. self.W_query = nn.Linear(d_in, d_out, bias=qkv_bias)
  27. self.W_key = nn.Linear(d_in, d_out, bias=qkv_bias)
  28. self.W_value = nn.Linear(d_in, d_out, bias=qkv_bias)
  29. def forward(self, x):
  30. keys = self.W_key(x)
  31. queries = self.W_query(x)
  32. values = self.W_value(x)
  33. attn_scores = queries @ keys.T
  34. attn_weights = torch.softmax(attn_scores / keys.shape[-1]**0.5, dim=-1)
  35. context_vec = attn_weights @ values
  36. return context_vec
  37. class CausalAttention(nn.Module):
  38. def __init__(self, d_in, d_out, context_length,
  39. dropout, qkv_bias=False):
  40. super().__init__()
  41. self.d_out = d_out
  42. self.W_query = nn.Linear(d_in, d_out, bias=qkv_bias)
  43. self.W_key = nn.Linear(d_in, d_out, bias=qkv_bias)
  44. self.W_value = nn.Linear(d_in, d_out, bias=qkv_bias)
  45. self.dropout = nn.Dropout(dropout) # New
  46. self.register_buffer('mask', torch.triu(torch.ones(context_length, context_length), diagonal=1)) # New
  47. def forward(self, x):
  48. b, num_tokens, d_in = x.shape # New batch dimension b
  49. # For inputs where `num_tokens` exceeds `context_length`, this will result in errors
  50. # in the mask creation further below.
  51. # In practice, this is not a problem since the LLM (chapters 4-7) ensures that inputs
  52. # do not exceed `context_length` before reaching this forward method.
  53. keys = self.W_key(x)
  54. queries = self.W_query(x)
  55. values = self.W_value(x)
  56. attn_scores = queries @ keys.transpose(1, 2) # Changed transpose
  57. attn_scores.masked_fill_( # New, _ ops are in-place
  58. self.mask.bool()[:num_tokens, :num_tokens], -torch.inf) # `:num_tokens` to account for cases where the number of tokens in the batch is smaller than the supported context_size
  59. attn_weights = torch.softmax(
  60. attn_scores / keys.shape[-1]**0.5, dim=-1
  61. )
  62. attn_weights = self.dropout(attn_weights) # New
  63. context_vec = attn_weights @ values
  64. return context_vec
  65. class MultiHeadAttentionWrapper(nn.Module):
  66. def __init__(self, d_in, d_out, context_length, dropout, num_heads, qkv_bias=False):
  67. super().__init__()
  68. self.heads = nn.ModuleList(
  69. [CausalAttention(d_in, d_out, context_length, dropout, qkv_bias)
  70. for _ in range(num_heads)]
  71. )
  72. def forward(self, x):
  73. return torch.cat([head(x) for head in self.heads], dim=-1)
  74. class MultiHeadAttention(nn.Module):
  75. def __init__(self, d_in, d_out, context_length, dropout, num_heads, qkv_bias=False):
  76. super().__init__()
  77. assert d_out % num_heads == 0, "d_out must be divisible by n_heads"
  78. self.d_out = d_out
  79. self.num_heads = num_heads
  80. self.head_dim = d_out // num_heads # Reduce the projection dim to match desired output dim
  81. self.W_query = nn.Linear(d_in, d_out, bias=qkv_bias)
  82. self.W_key = nn.Linear(d_in, d_out, bias=qkv_bias)
  83. self.W_value = nn.Linear(d_in, d_out, bias=qkv_bias)
  84. self.out_proj = nn.Linear(d_out, d_out) # Linear layer to combine head outputs
  85. self.dropout = nn.Dropout(dropout)
  86. self.register_buffer('mask', torch.triu(torch.ones(context_length, context_length), diagonal=1))
  87. def forward(self, x):
  88. b, num_tokens, d_in = x.shape
  89. keys = self.W_key(x) # Shape: (b, num_tokens, d_out)
  90. queries = self.W_query(x)
  91. values = self.W_value(x)
  92. # We implicitly split the matrix by adding a `num_heads` dimension
  93. # Unroll last dim: (b, num_tokens, d_out) -> (b, num_tokens, num_heads, head_dim)
  94. keys = keys.view(b, num_tokens, self.num_heads, self.head_dim)
  95. values = values.view(b, num_tokens, self.num_heads, self.head_dim)
  96. queries = queries.view(b, num_tokens, self.num_heads, self.head_dim)
  97. # Transpose: (b, num_tokens, num_heads, head_dim) -> (b, num_heads, num_tokens, head_dim)
  98. keys = keys.transpose(1, 2)
  99. queries = queries.transpose(1, 2)
  100. values = values.transpose(1, 2)
  101. # Compute scaled dot-product attention (aka self-attention) with a causal mask
  102. attn_scores = queries @ keys.transpose(2, 3) # Dot product for each head
  103. # Original mask truncated to the number of tokens and converted to boolean
  104. mask_bool = self.mask.bool()[:num_tokens, :num_tokens]
  105. # Use the mask to fill attention scores
  106. attn_scores.masked_fill_(mask_bool, -torch.inf)
  107. attn_weights = torch.softmax(attn_scores / keys.shape[-1]**0.5, dim=-1)
  108. attn_weights = self.dropout(attn_weights)
  109. # Shape: (b, num_tokens, num_heads, head_dim)
  110. context_vec = (attn_weights @ values).transpose(1, 2)
  111. # Combine heads, where self.d_out = self.num_heads * self.head_dim
  112. context_vec = context_vec.reshape(b, num_tokens, self.d_out)
  113. context_vec = self.out_proj(context_vec) # optional projection
  114. return context_vec