Creating a GPT-1 model from scratch using PyTorch involves implementing the Transformer decoder architecture as described in the original GPT-1 paper. Below is a comprehensive implementation that includes the necessary components such as token embeddings, positional embeddings, multi-head self-attention, and feed-forward networks.
Overview of the Implementation
- Token and Position Embeddings: Converts input tokens into dense vectors and adds positional information to capture the order of tokens.
- Multi-Head Self-Attention: Allows the model to focus on different positions within the input sequence simultaneously.
- Feed-Forward Network (FFN): Applies a two-layer fully connected neural network to each position separately and identically.
- Transformer Blocks: Stacks multiple layers of self-attention and FFN with residual connections and layer normalization.
- GPT Model: Combines embeddings and transformer blocks, culminating in a linear layer to generate logits for each token in the vocabulary.
Complete PyTorch Implementation
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
class GPT1Config:
"""
Configuration parameters for the GPT-1 model.
Adjust these parameters to change the model size.
"""
def __init__(self,
vocab_size=30522,
n_positions=512,
n_ctx=512,
n_embd=768,
n_layer=12,
n_head=12,
dropout=0.1):
self.vocab_size = vocab_size
self.n_positions = n_positions # Maximum sequence length
self.n_ctx = n_ctx # Context size
self.n_embd = n_embd # Embedding size
self.n_layer = n_layer # Number of transformer blocks
self.n_head = n_head # Number of attention heads
self.dropout = dropout
class MultiHeadSelfAttention(nn.Module):
def __init__(self, config: GPT1Config):
super(MultiHeadSelfAttention, self).__init__()
assert config.n_embd % config.n_head == 0, "Embedding size must be divisible by number of heads"
self.num_heads = config.n_head
self.head_dim = config.n_embd // config.n_head
# Define linear projections for queries, keys, and values
self.q_proj = nn.Linear(config.n_embd, config.n_embd)
self.k_proj = nn.Linear(config.n_embd, config.n_embd)
self.v_proj = nn.Linear(config.n_embd, config.n_embd)
self.out_proj = nn.Linear(config.n_embd, config.n_embd)
self.dropout = nn.Dropout(config.dropout)
self.scale = math.sqrt(self.head_dim)
def forward(self, x, mask=None):
batch_size, seq_length, embed_dim = x.size()
# Project inputs to queries, keys, and values
Q = self.q_proj(x) # (batch_size, seq_length, embed_dim)
K = self.k_proj(x)
V = self.v_proj(x)
# Split into multiple heads
Q = Q.view(batch_size, seq_length, self.num_heads, self.head_dim).transpose(1, 2) # (batch_size, num_heads, seq_length, head_dim)
K = K.view(batch_size, seq_length, self.num_heads, self.head_dim).transpose(1, 2)
V = V.view(batch_size, seq_length, self.num_heads, self.head_dim).transpose(1, 2)
# Compute scaled dot-product attention
scores = torch.matmul(Q, K.transpose(-2, -1)) / self.scale # (batch_size, num_heads, seq_length, seq_length)
if mask is not None:
scores = scores.masked_fill(mask == 0, float('-inf'))
attn_weights = F.softmax(scores, dim=-1) # (batch_size, num_heads, seq_length, seq_length)
attn_weights = self.dropout(attn_weights)
attn_output = torch.matmul(attn_weights, V) # (batch_size, num_heads, seq_length, head_dim)
# Concatenate heads
attn_output = attn_output.transpose(1, 2).contiguous().view(batch_size, seq_length, embed_dim) # (batch_size, seq_length, embed_dim)
output = self.out_proj(attn_output) # (batch_size, seq_length, embed_dim)
return output
class FeedForwardNetwork(nn.Module):
def __init__(self, config: GPT1Config):
super(FeedForwardNetwork, self).__init__()
self.linear1 = nn.Linear(config.n_embd, 4 * config.n_embd)
self.linear2 = nn.Linear(4 * config.n_embd, config.n_embd)
self.dropout = nn.Dropout(config.dropout)
def forward(self, x):
x = self.linear1(x)
x = F.gelu(x) # GPT-1 uses Gaussian Error Linear Units (GELU)
x = self.dropout(x)
x = self.linear2(x)
x = self.dropout(x)
return x
class TransformerBlock(nn.Module):
def __init__(self, config: GPT1Config):
super(TransformerBlock, self).__init__()
self.ln1 = nn.LayerNorm(config.n_embd, eps=1e-5)
self.attn = MultiHeadSelfAttention(config)
self.ln2 = nn.LayerNorm(config.n_embd, eps=1e-5)
self.ffn = FeedForwardNetwork(config)
def forward(self, x, mask=None):
# Self-Attention Block
attn_output = self.attn(self.ln1(x), mask=mask)
x = x + attn_output # Residual connection
# Feed-Forward Block
ffn_output = self.ffn(self.ln2(x))
x = x + ffn_output # Residual connection
return x
class GPT1Model(nn.Module):
def __init__(self, config: GPT1Config):
super(GPT1Model, self).__init__()
self.config = config
# Token and Position Embeddings
self.token_emb = nn.Embedding(config.vocab_size, config.n_embd)
self.position_emb = nn.Embedding(config.n_positions, config.n_embd)
self.dropout = nn.Dropout(config.dropout)
# Transformer Blocks
self.blocks = nn.ModuleList([TransformerBlock(config) for _ in range(config.n_layer)])
# Layer Normalization
self.ln_f = nn.LayerNorm(config.n_embd, eps=1e-5)
# Output layer for language modeling
self.head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
self._init_weights()
def _init_weights(self):
# Initialize weights following GPT-1 initialization
for name, param in self.named_parameters():
if param.dim() > 1:
nn.init.xavier_uniform_(param)
else:
nn.init.normal_(param, mean=0.0, std=0.02)
def forward(self, input_ids, attention_mask=None):
"""
Args:
input_ids: (batch_size, seq_length)
attention_mask: (batch_size, seq_length) where 1 indicates tokens to attend to and 0 otherwise
Returns:
logits: (batch_size, seq_length, vocab_size)
"""
batch_size, seq_length = input_ids.size()
# Create position ids
position_ids = torch.arange(0, seq_length, dtype=torch.long, device=input_ids.device)
position_ids = position_ids.unsqueeze(0).expand(batch_size, seq_length) # (batch_size, seq_length)
# Embed tokens and positions
token_embeddings = self.token_emb(input_ids) # (batch_size, seq_length, embed_dim)
position_embeddings = self.position_emb(position_ids) # (batch_size, seq_length, embed_dim)
# Sum token and position embeddings
x = token_embeddings + position_embeddings
x = self.dropout(x)
# Generate causal mask if attention_mask is not provided
if attention_mask is None:
# Causal mask to prevent attention to future tokens
mask = torch.tril(torch.ones((seq_length, seq_length), device=input_ids.device)).unsqueeze(0).unsqueeze(0) # (1,1,seq_length,seq_length)
else:
# Combine attention mask with causal mask
mask = attention_mask.unsqueeze(1).unsqueeze(2) * torch.tril(torch.ones((seq_length, seq_length), device=input_ids.device)).unsqueeze(0).unsqueeze(0)
# Pass through transformer blocks
for block in self.blocks:
x = block(x, mask=mask)
x = self.ln_f(x)
logits = self.head(x) # (batch_size, seq_length, vocab_size)
return logits
# Example usage
if __name__ == "__main__":
# Define model configuration
config = GPT1Config(
vocab_size=30522, # Typically the size of BERT's vocabulary or similar
n_positions=512,
n_ctx=512,
n_embd=768,
n_layer=12,
n_head=12,
dropout=0.1
)
# Initialize model
model = GPT1Model(config)
# Sample input (batch_size=2, seq_length=10)
input_ids = torch.randint(0, config.vocab_size, (2, 10)) # Random token IDs
# Forward pass
logits = model(input_ids) # (2, 10, 30522)
print("Logits shape:", logits.shape)
Explanation of Components
-
Configuration (GPT1Config): Defines the hyperparameters of the model such as vocabulary size, embedding dimensions, number of layers, etc. Adjust these to scale the model up or down.
-
Multi-Head Self-Attention (MultiHeadSelfAttention):
- Splits the input embeddings into multiple heads.
- Computes scaled dot-product attention for each head.
- Concatenates the outputs of all heads and projects them back to the embedding dimension.
-
Feed-Forward Network (FeedForwardNetwork):
- Consists of two linear layers with a GELU activation in between.
- Applies dropout for regularization.
-
Transformer Block (TransformerBlock):
- Applies layer normalization before each sub-layer (Pre-LN Transformer).
- Contains a self-attention layer followed by a feed-forward network.
- Utilizes residual connections to facilitate gradient flow.
-
GPT Model (GPT1Model):
- Combines token embeddings and positional embeddings.
- Passes the embeddings through a stack of transformer blocks.
- Applies a final layer normalization.
- Projects the output to vocabulary size to generate logits for each token position.
-
Causal Masking:
- Ensures that each position can only attend to previous positions in the sequence, maintaining the autoregressive property required for language generation.
-
Initialization (_init_weights):
- Initializes weights using Xavier uniform initialization for linear layers and normal distribution for bias terms, following the GPT-1 initialization strategy.
-
Example Usage:
- Demonstrates how to instantiate the model and perform a forward pass with sample input.
Training Considerations
- Loss Function: Typically, Cross-Entropy Loss is used for language modeling tasks.
- Optimizer: Adam or AdamW optimizers with suitable learning rate schedules.
- Data Processing: Proper tokenization and batching are crucial for effective training.
- GPU Acceleration: Training large models like GPT-1 requires GPUs for efficient computation.
Final Notes
This implementation provides a foundation for the GPT-1 architecture. For a full training pipeline, you'll need to integrate data loading, training loops, and optimization strategies. Additionally, for practical use, consider leveraging existing libraries and frameworks that offer optimized implementations and utilities for training large-scale language models.