Skip to content

A straightforward method for training your LLM, from downloading data to generating text.

feat: re-implement network architecture

Tianyi (Alex) Qiu2d0c8b18644e
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..ba0430d
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+__pycache__/
\ No newline at end of file
diff --git a/PITFALLS.md b/PITFALLS.md
new file mode 100644
index 0000000..64c2507
--- /dev/null
+++ b/PITFALLS.md
@@ -0,0 +1,5 @@
+- No bias in Q/K/V
+- `attn = torch.tril(attn, diagonal=0) + torch.triu(torch.ones_like(attn) * (-torch.inf), diagonal=1)`
+- `k = torch.transpose(k, -1, -2)`
+- `x += self.attn(self.ln_attn(x)); x += self.mlp(self.ln_mlp(x))`
+- `x = self.lm_head(self.ln_lmhead(x))`
\ No newline at end of file
diff --git a/src/models/__init__.py b/src/models/__init__.py
index dab85fd..db69368 100644
--- a/src/models/__init__.py
+++ b/src/models/__init__.py
@@ -1,5 +1,5 @@
# This file makes the 'src.models' directory a Python package.
from .mlp import MLP
-from .attention import Head, MultiHeadAttention
-from .transformer_block import Block
+from .attention import MultiHeadAttn
+from .transformer_block import TransformerBlock
from .transformer import Transformer
\ No newline at end of file
diff --git a/src/models/attention.py b/src/models/attention.py
index c57ccd7..c92ce75 100644
--- a/src/models/attention.py
+++ b/src/models/attention.py
@@ -1,111 +1,62 @@
import torch
-import torch.nn as nn
-import torch.nn.functional as F
-import math
-
-class Head(nn.Module):
- """
- A single attention head.
-
- This module calculates attention scores and applies them to the values.
- It includes key, query, and value projections, and uses causal masking
- to prevent attending to future tokens.
-
- Args:
- head_size (int): The dimensionality of the key, query, and value projections.
- n_embed (int): The dimensionality of the input embedding.
- context_length (int): The maximum length of the input sequence, used for causal masking.
- """
- def __init__(self, head_size: int, n_embed: int, context_length: int) -> None:
- """
- Initializes the attention head.
-
- Args:
- head_size (int): The dimensionality of the key, query, and value projections.
- n_embed (int): The dimensionality of the input embedding.
- context_length (int): The maximum length of the input sequence.
- """
+from torch import nn
+
+class Attention(nn.Module):
+ emb_dim: int
+ attn_dim: int
+ q_head: nn.Linear
+ k_head: nn.Linear
+ v_head: nn.Linear
+
+ def __init__(self, emb_dim: int, attn_dim: int):
super().__init__()
- self.key = nn.Linear(n_embed, head_size, bias=False) # Key projection
- self.query = nn.Linear(n_embed, head_size, bias=False) # Query projection
- self.value = nn.Linear(n_embed, head_size, bias=False) # Value projection
- # Lower triangular matrix for causal masking
- self.register_buffer('tril', torch.tril(torch.ones(context_length, context_length)))
-
+ self.emb_dim = emb_dim
+ self.attn_dim = attn_dim
+ self.q_head = nn.Linear(emb_dim, attn_dim, bias=False)
+ self.k_head = nn.Linear(emb_dim, attn_dim, bias=False)
+ self.v_head = nn.Linear(emb_dim, attn_dim, bias=False)
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
- """
- Forward pass through the attention head.
-
- Args:
- x (torch.Tensor): Input tensor of shape (B, T, C).
-
- Returns:
- torch.Tensor: Output tensor after applying attention.
- """
- B, T, C = x.shape
- head_size = self.key.out_features
- k = self.key(x) # (B, T, head_size)
- q = self.query(x) # (B, T, head_size)
- scale_factor = 1 / math.sqrt(head_size)
- # Calculate attention weights: (B, T, head_size) @ (B, head_size, T) -> (B, T, T)
- attn_weights = q @ k.transpose(-2, -1) * scale_factor
- # Apply causal masking
- attn_weights = attn_weights.masked_fill(self.tril[:T, :T] == 0, float('-inf'))
- attn_weights = F.softmax(attn_weights, dim=-1)
- v = self.value(x) # (B, T, head_size)
- # Apply attention weights to values
- out = attn_weights @ v # (B, T, T) @ (B, T, head_size) -> (B, T, head_size)
- return out
-
-class MultiHeadAttention(nn.Module):
- """
- Multi-Head Attention module.
-
- This module combines multiple attention heads in parallel. The outputs of each head
- are concatenated to form the final output.
-
- Args:
- n_head (int): The number of parallel attention heads.
- n_embed (int): The dimensionality of the input embedding.
- context_length (int): The maximum length of the input sequence.
- """
- def __init__(self, n_head: int, n_embed: int, context_length: int) -> None:
- """
- Initializes the multi-head attention module.
-
- Args:
- n_head (int): The number of parallel attention heads.
- n_embed (int): The dimensionality of the input embedding.
- context_length (int): The maximum length of the input sequence.
- """
+ # x: (B, ctx_len, emb_dim)
+ assert len(x.shape) == 3 and x.shape[-1] == self.emb_dim
+
+ q: torch.Tensor = self.q_head(x) # (B, ctx_len, attn_dim)
+ k: torch.Tensor = self.k_head(x)
+ k = torch.transpose(k, -1, -2) # (B, attn_dim, ctx_len)
+ attn = q @ k * (self.attn_dim ** -0.5)
+ attn = torch.tril(attn, diagonal=0) + torch.triu(torch.ones_like(attn) * (-torch.inf), diagonal=1)
+ attn = nn.functional.softmax(attn, dim=-1) # (B, ctx_len, ctx_len)
+
+ v: torch.Tensor = self.v_head(x) # (B, ctx_len, attn_dim)
+ return attn @ v
+
+
+class MultiHeadAttn(nn.Module):
+ emb_dim: int
+ num_heads: int
+ heads: nn.ModuleList
+
+ def __init__(self, emb_dim: int, num_heads: int):
super().__init__()
- self.heads = nn.ModuleList([Head(n_embed // n_head, n_embed, context_length) for _ in range(n_head)])
-
- def forward(self, x: torch.Tensor) -> torch.Tensor:
- """
- Forward pass through the multi-head attention.
-
- Args:
- x (torch.Tensor): Input tensor of shape (B, T, C).
-
- Returns:
- torch.Tensor: Output tensor after concatenating the outputs of all heads.
- """
- # Concatenate the output of each head along the last dimension (C)
- x = torch.cat([h(x) for h in self.heads], dim=-1)
- return x
-
-if __name__ == '__main__':
- # Example Usage (optional, for testing the module independently)
- batch_size = 2
- sequence_length = 5
- embedding_dim = 32
- num_heads = 4
- context_len = 5
- input_tensor = torch.randn(batch_size, sequence_length, embedding_dim)
-
- multihead_attn = MultiHeadAttention(n_head=num_heads, n_embed=embedding_dim, context_length=context_len)
- output_tensor = multihead_attn(input_tensor)
-
- print("MultiHeadAttention Input Shape:", input_tensor.shape)
- print("MultiHeadAttention Output Shape:", output_tensor.shape)
+ self.emb_dim = emb_dim
+ self.num_heads = num_heads
+
+ assert emb_dim % num_heads == 0
+
+ self.heads = nn.ModuleList([
+ Attention(emb_dim, emb_dim // num_heads)
+ for _ in range(num_heads)
+ ])
+
+ def forward(self, x: torch.Tensor):
+ return torch.cat(
+ [attn(x) for attn in self.heads],
+ dim = -1
+ )
+
+if __name__ == "__main__":
+ mha = MultiHeadAttn(16, 4)
+ x = torch.randn((5, 64, 16))
+ y = mha(x)
+ print(x.shape)
+ print(y.shape)
\ No newline at end of file
diff --git a/src/models/mlp.py b/src/models/mlp.py
index c7baa79..7f1b7bf 100644
--- a/src/models/mlp.py
+++ b/src/models/mlp.py
@@ -1,80 +1,29 @@
import torch
-import torch.nn as nn
-from torch import Tensor
+from torch import nn
class MLP(nn.Module):
- """
- A simple Multi-Layer Perceptron with one hidden layer.
-
- This module is used within the Transformer block for feed-forward processing.
- It expands the input embedding size, applies a ReLU activation, and then projects it back
- to the original embedding size.
-
- Args:
- n_embed (int): The dimensionality of the input embedding.
- """
- def __init__(self, n_embed: int) -> None:
- """
- Initializes the MLP module.
-
- Args:
- n_embed (int): The dimensionality of the input embedding.
- """
+ emb_dim: int
+ relu: nn.Module
+ in_linear: nn.Linear
+ out_linear: nn.Linear
+
+ def __init__(self, emb_dim: int):
super().__init__()
- self.hidden = nn.Linear(n_embed, 4 * n_embed) # Linear layer to expand embedding size
- self.relu = nn.ReLU() # ReLU activation function
- self.proj = nn.Linear(4 * n_embed, n_embed) # Linear layer to project back to original size
-
- def forward(self, x: Tensor) -> Tensor:
- """
- Forward pass through the MLP.
-
- Args:
- x (torch.Tensor): Input tensor of shape (B, T, C), where B is batch size,
- T is sequence length, and C is embedding size.
-
- Returns:
- torch.Tensor: Output tensor of the same shape as the input.
- """
- x = self.forward_embedding(x)
- x = self.project_embedding(x)
+ self.emb_dim = emb_dim
+ self.in_linear = nn.Linear(emb_dim, emb_dim * 4)
+ self.relu = nn.ReLU()
+ self.out_linear = nn.Linear(emb_dim * 4, emb_dim)
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ x = self.in_linear(x)
+ x = self.relu(x)
+ x = self.out_linear(x)
return x
- def forward_embedding(self, x: Tensor) -> Tensor:
- """
- Applies the hidden linear layer followed by ReLU activation.
-
- Args:
- x (torch.Tensor): Input tensor.
-
- Returns:
- torch.Tensor: Output after the hidden layer and ReLU.
- """
- x = self.relu(self.hidden(x))
- return x
-
- def project_embedding(self, x: Tensor) -> Tensor:
- """
- Applies the projection linear layer.
-
- Args:
- x (torch.Tensor): Input tensor.
-
- Returns:
- torch.Tensor: Output after the projection layer.
- """
- x = self.proj(x)
- return x
-
-if __name__ == '__main__':
- # Example Usage (optional, for testing the module independently)
- batch_size = 2
- sequence_length = 3
- embedding_dim = 16
- input_tensor = torch.randn(batch_size, sequence_length, embedding_dim)
-
- mlp_module = MLP(n_embed=embedding_dim)
- output_tensor = mlp_module(input_tensor)
- print("MLP Input Shape:", input_tensor.shape)
- print("MLP Output Shape:", output_tensor.shape)
\ No newline at end of file
+if __name__ == "__main__":
+ mlp = MLP(10)
+ x = torch.randn((5, 64, 10))
+ y = mlp(x)
+ print(x.shape)
+ print(y.shape)
\ No newline at end of file
diff --git a/src/models/transformer.py b/src/models/transformer.py
index 4650753..1250faf 100644
--- a/src/models/transformer.py
+++ b/src/models/transformer.py
@@ -1,136 +1,63 @@
import torch
-import torch.nn as nn
-import torch.nn.functional as F
-from src.models.transformer_block import Block
+from torch import nn
+from src.models.transformer_block import TransformerBlock
class Transformer(nn.Module):
- """
- The main Transformer model.
-
- This class combines token and position embeddings with a sequence of Transformer blocks
- and a final linear layer for language modeling.
-
- Args:
- n_head (int): The number of attention heads in each transformer block.
- n_embed (int): The dimensionality of the embedding space.
- context_length (int): The maximum length of the input sequence.
- vocab_size (int): The size of the vocabulary.
- N_BLOCKS (int): The number of transformer blocks in the model.
- """
- def __init__(self, n_head: int, n_embed: int, context_length: int, vocab_size: int, N_BLOCKS: int) -> None:
- """
- Initializes the Transformer model.
-
- Args:
- n_head (int): Number of attention heads.
- n_embed (int): Embedding dimension.
- context_length (int): Maximum sequence length.
- vocab_size (int): Size of the vocabulary.
- N_BLOCKS (int): Number of transformer blocks.
- """
+ text_dim: int
+ ctx_len: int
+ emb_dim: int
+ num_heads: int
+ num_blocks: int
+
+ text_emb: nn.Embedding
+ pos_emb: nn.Embedding
+ blocks: nn.ModuleList
+ lm_head: nn.Linear
+
+ def __init__(self, text_dim: int, ctx_len: int, emb_dim: int, num_heads: int, num_blocks: int):
super().__init__()
- self.context_length = context_length
- self.N_BLOCKS = N_BLOCKS
- self.token_embed = nn.Embedding(vocab_size, n_embed)
- self.position_embed = nn.Embedding(context_length, n_embed)
- self.attn_blocks = nn.ModuleList([Block(n_head, n_embed, context_length) for _ in range(N_BLOCKS)])
- self.layer_norm = nn.LayerNorm(n_embed)
- self.lm_head = nn.Linear(n_embed, vocab_size)
- self.register_buffer('pos_idxs', torch.arange(context_length))
-
- def _pre_attn_pass(self, idx: torch.Tensor) -> torch.Tensor:
- """
- Combines token and position embeddings.
-
- Args:
- idx (torch.Tensor): Input token indices.
-
- Returns:
- torch.Tensor: Sum of token and position embeddings.
- """
- B, T = idx.shape
- tok_embedding = self.token_embed(idx)
- pos_embedding = self.position_embed(self.pos_idxs[:T])
- return tok_embedding + pos_embedding
-
- def forward(self, idx: torch.Tensor, targets: torch.Tensor = None) -> tuple[torch.Tensor, torch.Tensor | None]:
- """
- Forward pass through the Transformer.
-
- Args:
- idx (torch.Tensor): Input token indices.
- targets (torch.Tensor, optional): Target token indices for loss calculation. Defaults to None.
-
- Returns:
- tuple: Logits and loss (if targets are provided).
- """
- x = self._pre_attn_pass(idx)
- for block in self.attn_blocks:
+ self.text_dim = text_dim
+ self.ctx_len = ctx_len
+ self.emb_dim = emb_dim
+ self.num_heads = num_heads
+ self.num_blocks = num_blocks
+
+ self.text_emb = nn.Embedding(text_dim, emb_dim)
+ self.pos_emb = nn.Embedding(ctx_len, emb_dim)
+ self.blocks = nn.ModuleList([
+ TransformerBlock(emb_dim, num_heads)
+ for _ in range(num_blocks)
+ ])
+ self.ln_lmhead = nn.LayerNorm(emb_dim)
+ self.lm_head = nn.Linear(emb_dim, text_dim)
+
+ def forward(self, x: torch.Tensor, get_probs: bool = False, keep_prompt_seg: bool = False):
+ """Transformer forward pass. Input 2-D tensor contains raw tokens, NOT one-hot encoded."""
+ assert len(x.shape) == 2 and x.shape[-1] <= self.ctx_len
+
+ x = self.text_emb(x) + self.pos_emb(torch.arange(x.shape[-1]))
+ assert len(x.shape) == 3 and x.shape[2] == self.emb_dim
+
+ for block in self.blocks:
x = block(x)
- x = self.layer_norm(x)
- logits = self.lm_head(x)
- loss = None
- if targets is not None:
- B, T, C = logits.shape
- flat_logits = logits.view(B * T, C)
- targets = targets.view(B * T).long()
- loss = F.cross_entropy(flat_logits, targets)
- return logits, loss
-
- def forward_embedding(self, idx: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
- """
- Forward pass focusing on the embedding and attention blocks.
-
- Args:
- idx (torch.Tensor): Input token indices.
-
- Returns:
- tuple: Output after attention blocks and the residual.
- """
- x = self._pre_attn_pass(idx)
- residual = x
- for block in self.attn_blocks:
- x, residual = block.forward_embedding(x)
- return x, residual
-
- def generate(self, idx: torch.Tensor, max_new_tokens: int) -> torch.Tensor:
- """
- Generates new tokens given a starting sequence.
-
- Args:
- idx (torch.Tensor): Initial sequence of token indices.
- max_new_tokens (int): Number of tokens to generate.
-
- Returns:
- torch.Tensor: The extended sequence of tokens.
- """
- for _ in range(max_new_tokens):
- idx_cond = idx[:, -self.context_length:]
- logits, _ = self(idx_cond)
- logits = logits[:, -1, :]
- probs = F.softmax(logits, dim=-1)
- idx_next = torch.multinomial(probs, num_samples=1)
- idx = torch.cat((idx, idx_next), dim=1)
- return idx
-
-if __name__ == '__main__':
- # Example Usage (optional, for testing the module independently)
- batch_size = 2
- sequence_length = 5
- vocab_size = 100
- embedding_dim = 32
- num_heads = 4
- num_blocks = 2
- context_len = 5
- input_indices = torch.randint(0, vocab_size, (batch_size, sequence_length))
-
- transformer_model = Transformer(n_head=num_heads, n_embed=embedding_dim, context_length=context_len, vocab_size=vocab_size, N_BLOCKS=num_blocks)
- logits, loss = transformer_model(input_indices, targets=input_indices) # Using input as target for simplicity
-
- print("Transformer Logits Shape:", logits.shape)
- print("Transformer Loss:", loss)
-
- # Example of generating tokens
- start_indices = input_indices[:, :1] # Take the first token of each sequence as start
- generated_tokens = transformer_model.generate(start_indices, max_new_tokens=5)
- print("Generated Tokens Shape:", generated_tokens.shape)
\ No newline at end of file
+
+ x = self.lm_head(self.ln_lmhead(x))
+ assert len(x.shape) == 3 and x.shape[2] == self.text_dim
+
+ if get_probs:
+ # Compute probs instead of logits
+ x = nn.functional.softmax(x, dim=-1)
+
+ if not keep_prompt_seg:
+ # Only return the next-token results
+ x = x[:, -1, :]
+
+ return x
+
+if __name__ == "__main__":
+ transformer = Transformer(8, 8, 32, 4, 5)
+ x = torch.randint(8, (3, 7))
+ y = transformer(x, get_probs = True, keep_prompt_seg = True)
+ print(x.shape)
+ print(y.shape)
+ print(y)
\ No newline at end of file
diff --git a/src/models/transformer_block.py b/src/models/transformer_block.py
index b6cfd29..dfc345f 100644
--- a/src/models/transformer_block.py
+++ b/src/models/transformer_block.py
@@ -1,76 +1,23 @@
import torch
-import torch.nn as nn
-from src.models.attention import MultiHeadAttention
+from torch import nn
from src.models.mlp import MLP
-
-class Block(nn.Module):
- """
- A single Transformer block.
-
- This block consists of a multi-head attention layer followed by an MLP,
- with layer normalization and residual connections.
-
- Args:
- n_head (int): The number of attention heads in the multi-head attention layer.
- n_embed (int): The dimensionality of the input embedding.
- context_length (int): The maximum length of the input sequence.
- """
- def __init__(self, n_head: int, n_embed: int, context_length: int) -> None:
- """
- Initializes the Transformer block.
-
- Args:
- n_head (int): The number of attention heads.
- n_embed (int): The dimensionality of the embedding space.
- context_length (int): The maximum sequence length.
- """
+from src.models.attention import MultiHeadAttn
+
+class TransformerBlock(nn.Module):
+ emb_dim: int
+ attn: MultiHeadAttn
+ ln_attn: nn.LayerNorm
+ mlp: MLP
+ ln_mlp: nn.LayerNorm
+
+ def __init__(self, emb_dim: int, num_heads: int):
super().__init__()
- self.ln1 = nn.LayerNorm(n_embed)
- self.attn = MultiHeadAttention(n_head, n_embed, context_length)
- self.ln2 = nn.LayerNorm(n_embed)
- self.mlp = MLP(n_embed)
-
- def forward(self, x: torch.Tensor) -> torch.Tensor:
- """
- Forward pass through the Transformer block.
-
- Args:
- x (torch.Tensor): Input tensor.
-
- Returns:
- torch.Tensor: Output tensor after the block.
- """
- # Apply multi-head attention with residual connection
- x = x + self.attn(self.ln1(x))
- # Apply MLP with residual connection
- x = x + self.mlp(self.ln2(x))
- return x
-
- def forward_embedding(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
- """
- Forward pass focusing on the embedding and attention parts.
-
- Args:
- x (torch.Tensor): Input tensor.
-
- Returns:
- tuple: A tuple containing the output after MLP embedding and the residual.
- """
- res = x + self.attn(self.ln1(x))
- x = self.mlp.forward_embedding(self.ln2(res))
- return x, res
-
-if __name__ == '__main__':
- # Example Usage (optional, for testing the module independently)
- batch_size = 2
- sequence_length = 5
- embedding_dim = 32
- num_heads = 4
- context_len = 5
- input_tensor = torch.randn(batch_size, sequence_length, embedding_dim)
-
- transformer_block = Block(n_head=num_heads, n_embed=embedding_dim, context_length=context_len)
- output_tensor = transformer_block(input_tensor)
-
- print("Transformer Block Input Shape:", input_tensor.shape)
- print("Transformer Block Output Shape:", output_tensor.shape)
\ No newline at end of file
+ self.attn = MultiHeadAttn(emb_dim, num_heads)
+ self.ln_attn = nn.LayerNorm(emb_dim)
+ self.mlp = MLP(emb_dim)
+ self.ln_mlp = nn.LayerNorm(emb_dim)
+
+ def forward(self, x: torch.Tensor):
+ x += self.attn(self.ln_attn(x))
+ x += self.mlp(self.ln_mlp(x))
+ return x
\ No newline at end of file