Creating a GPT-1 model from scratch involves implementing a transformer-based architecture, which includes components such as token embeddings, positional encodings, multi-head self-attention, and feedforward neural networks. Below is a simplified version of GPT-1 using PyTorch. Note that this code aims to resemble the architectural essence of GPT-1 and may omit some optimizations and configurations found in the original research.
Complete GPT-1 Model Implementation in PyTorch
import torch
import torch.nn as nn
import torch.nn.functional as F
class GPT1Config:
def __init__(self, vocab_size=50257, max_position_embeddings=512, n_embd=768, n_layer=12, n_head=12):
self.vocab_size = vocab_size
self.max_position_embeddings = max_position_embeddings
self.n_embd = n_embd
self.n_layer = n_layer
self.n_head = n_head
class MultiHeadSelfAttention(nn.Module):
def __init__(self, config: GPT1Config):
super().__init__()
assert config.n_embd % config.n_head == 0
self.n_head = config.n_head
self.head_dim = config.n_embd // config.n_head
self.qkv_proj = nn.Linear(config.n_embd, config.n_embd * 3)
self.out_proj = nn.Linear(config.n_embd, config.n_embd)
def forward(self, x):
b, t, c = x.size()
qkv = self.qkv_proj(x)
q, k, v = qkv.split(c, dim=2)
q = q.view(b, t, self.n_head, self.head_dim).transpose(1, 2)
k = k.view(b, t, self.n_head, self.head_dim).transpose(1, 2)
v = v.view(b, t, self.n_head, self.head_dim).transpose(1, 2)
attn_weights = (q @ k.transpose(-2, -1)) * (1.0 / (k.size(-1)**0.5))
attn_weights = F.softmax(attn_weights, dim=-1)
attn_output = attn_weights @ v
attn_output = attn_output.transpose(1, 2).contiguous().view(b, t, c)
return self.out_proj(attn_output)
class FeedForward(nn.Module):
def __init__(self, config):
super().__init__()
self.fc1 = nn.Linear(config.n_embd, 4 * config.n_embd)
self.fc2 = nn.Linear(4 * config.n_embd, config.n_embd)
def forward(self, x):
return self.fc2(F.gelu(self.fc1(x)))
class Block(nn.Module):
def __init__(self, config):
super().__init__()
self.ln1 = nn.LayerNorm(config.n_embd)
self.ln2 = nn.LayerNorm(config.n_embd)
self.attn = MultiHeadSelfAttention(config)
self.ff = FeedForward(config)
def forward(self, x):
x = x + self.attn(self.ln1(x))
x = x + self.ff(self.ln2(x))
return x
class GPT1(nn.Module):
def __init__(self, config: GPT1Config):
super().__init__()
self.embed = nn.Embedding(config.vocab_size, config.n_embd)
self.pos_embed = nn.Embedding(config.max_position_embeddings, config.n_embd)
self.blocks = nn.ModuleList([Block(config) for _ in range(config.n_layer)])
self.ln_f = nn.LayerNorm(config.n_embd)
self.head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
def forward(self, idx):
b, t = idx.size()
pos = torch.arange(t, dtype=torch.long, device=idx.device)
tok_emb = self.embed(idx)
pos_emb = self.pos_embed(pos)
x = tok_emb + pos_emb.unsqueeze(0)
for block in self.blocks:
x = block(x)
x = self.ln_f(x)
logits = self.head(x)
return logits
# Function to initialize weights
def initialize_weights(model):
for name, param in model.named_parameters():
if param.dim() > 1:
nn.init.xavier_uniform_(param)
# Initialize the GPT-1 model with desired configurations
config = GPT1Config()
model = GPT1(config)
initialize_weights(model)
# Example usage with random input
input_ids = torch.randint(0, config.vocab_size, (1, 256)) # Batch size of 1, sequence length of 256
outputs = model(input_ids)
print(outputs.shape) # Expected output shape: (1, 256, config.vocab_size)
Explanation:
-
Configuration: A GPT1Config class sets hyperparameters like vocabulary size, embedding dimensions, number of layers, and number of attention heads.
-
Multi-Head Self-Attention: This component performs the key, query, and value transformations, scales and applies softmax to the attention scores, computes the outputs, and projects them back to the original dimension.
-
Feed-Forward Network: This component consists of two linear layers with a GELU non-linearity in between, typical for transformer architectures.
-
Transformer Block: Combines attention and feed-forward layers with residual connections and layer normalization.
-
GPT-1 Model: Comprises token embeddings, positional encodings, and a stack of transformer blocks. Finally, it employs a linear layer to project the output to the vocabulary size for logits prediction.
-
Weight Initialization: Uses Xavier initialization for all linear layers.
Note:
This code is a basic approximation of the GPT-1 architecture. The original implementation may include additional complexities such as specific initialization schemes, dropout for regularization, and finer gradient scaling and normalization techniques. Additionally, this simplified model assumes several default training and operational considerations to focus on implementing the core structure.