Creating a complete implementation of GPT-1 (Generative Pre-trained Transformer 1) from scratch is a complex task that involves building various components of the transformer architecture, including the multi-head self-attention, position-wise feed-forward networks, layer normalization, and positional encodings. Below, I'll provide a simplified version of the main components and how to assemble them together using PyTorch. This will not be a full-scale model but should give you a good understanding of how GPT-1 works at a high level.
Step 1: Import Necessary Libraries
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
Step 2: Define the Multi-Head Self-Attention Mechanism
class MultiHeadSelfAttention(nn.Module):
def __init__(self, embed_size, heads):
super(MultiHeadSelfAttention, self).__init__()
self.embed_size = embed_size
self.heads = heads
self.head_dim = embed_size // heads
assert (
self.head_dim * heads == embed_size
), "Embedding size must be divisible by heads"
self.values = nn.Linear(embed_size, embed_size, bias=False)
self.keys = nn.Linear(embed_size, embed_size, bias=False)
self.queries = nn.Linear(embed_size, embed_size, bias=False)
self.fc_out = nn.Linear(embed_size, embed_size)
def forward(self, x):
N, seq_length, _ = x.shape
values = self.values(x)
keys = self.keys(x)
queries = self.queries(x)
# Split into multiple heads
values = values.view(N, seq_length, self.heads, self.head_dim)
keys = keys.view(N, seq_length, self.heads, self.head_dim)
queries = queries.view(N, seq_length, self.heads, self.head_dim)
values = values.permute(0, 2, 1, 3) # (N, heads, seq_length, head_dim)
keys = keys.permute(0, 2, 1, 3)
queries = queries.permute(0, 2, 1, 3)
energy = queries @ keys.permute(0, 1, 3, 2) # (N, heads, seq_length, seq_length)
attention = F.softmax(energy / (self.embed_size ** (1 / 2)), dim=3)
out = attention @ values # (N, heads, seq_length, head_dim)
out = out.permute(0, 2, 1, 3).contiguous() # (N, seq_length, heads, head_dim)
out = out.view(N, seq_length, self.embed_size) # (N, seq_length, embed_size)
return self.fc_out(out)
Step 3: Define the Feed-Forward Neural Network
class FeedForward(nn.Module):
def __init__(self, embed_size, ff_hidden_dim):
super(FeedForward, self).__init__()
self.fc1 = nn.Linear(embed_size, ff_hidden_dim)
self.fc2 = nn.Linear(ff_hidden_dim, embed_size)
def forward(self, x):
return self.fc2(F.relu(self.fc1(x)))
Step 4: Define the Transformer Block
class TransformerBlock(nn.Module):
def __init__(self, embed_size, heads, ff_hidden_dim, dropout):
super(TransformerBlock, self).__init__()
self.attention = MultiHeadSelfAttention(embed_size, heads)
self.norm1 = nn.LayerNorm(embed_size)
self.norm2 = nn.LayerNorm(embed_size)
self.feed_forward = FeedForward(embed_size, ff_hidden_dim)
self.dropout = nn.Dropout(dropout)
def forward(self, x):
attention = self.attention(x)
x = self.norm1(attention + x) # Add & Norm
forward = self.feed_forward(x)
x = self.norm2(forward + x) # Add & Norm
return x
Step 5: Define the GPT Model
class GPT(nn.Module):
def __init__(self, embed_size, num_heads, num_layers, ff_hidden_dim, vocab_size, max_length, dropout):
super(GPT, self).__init__()
self.embed_size = embed_size
self.word_embeds = nn.Embedding(vocab_size, embed_size)
self.position_embeds = nn.Embedding(max_length, embed_size)
self.transformer_blocks = nn.ModuleList(
[TransformerBlock(embed_size, num_heads, ff_hidden_dim, dropout) for _ in range(num_layers)]
)
self.fc_out = nn.Linear(embed_size, vocab_size)
def forward(self, x):
N, seq_length = x.shape
positions = torch.arange(0, seq_length).expand(N, seq_length).to(x.device)
x = self.word_embeds(x) + self.position_embeds(positions)
for block in self.transformer_blocks:
x = block(x)
return self.fc_out(x)
Step 6: Example Usage
You can now create an instance of the GPT model. Here's an example:
# Hyperparameters
embed_size = 256 # Embedding size
num_heads = 8 # Number of attention heads
num_layers = 6 # Number of Transformer blocks
ff_hidden_dim = 512 # Feed forward hidden size
vocab_size = 10000 # Size of the vocabulary
max_length = 100 # Maximum sequence length
dropout = 0.1 # Dropout rate
# Initialize model
model = GPT(embed_size, num_heads, num_layers, ff_hidden_dim, vocab_size, max_length, dropout)
# Example input (batch size of 2, sequence length of 10)
input_tensor = torch.randint(0, vocab_size, (2, 10))
output = model(input_tensor)
print(output.shape) # Should output: (2, 10, vocab_size)
Notes:
- This is a very basic implementation designed to give you a foundational understanding of the architecture. In practice, you would need to add features like masking for the attention scores, gradient clipping, better initialization, etc.
- Training this model would require a lot of data and computational resources, as it involves significant optimization of both architecture and hyperparameters. Use frameworks like Hugging Face's Transformers for production-ready models.
Feel free to expand, improve, or modify this code to better suit your needs!