Creating a full implementation of GPT-1 from scratch is quite complex due to the intricacies involved in developing such a model. However, I can provide you with a simplified version of the core components. GPT-1, like any GPT model, mainly consists of the Transformer architecture proposed by Vaswani et al. in "Attention is All You Need". Below is a simplified implementation focusing on the core parts using PyTorch. However, note that this is a basic version and doesn't cover aspects like training loops, data preprocessing, or optimizations that would be necessary for a practical implementation.
import torch
import torch.nn as nn
import torch.nn.functional as F
class GPT(nn.Module):
def __init__(self, vocab_size, n_embd, n_layer, n_head, block_size):
super(GPT, self).__init__()
self.vocab_size = vocab_size
self.block_size = block_size
self.token_embedding = nn.Embedding(vocab_size, n_embd)
self.position_embedding = nn.Embedding(block_size, n_embd)
self.transformer_blocks = nn.ModuleList([
TransformerBlock(n_embd, n_head) for _ in range(n_layer)
])
self.ln_f = nn.LayerNorm(n_embd)
self.head = nn.Linear(n_embd, vocab_size, bias=False)
def forward(self, idx):
b, t = idx.size()
assert t <= self.block_size, "Cannot forward, model block size is exhausted."
position = torch.arange(t, dtype=torch.long, device=idx.device)
token_emb = self.token_embedding(idx)
position_emb = self.position_embedding(position)
x = token_emb + position_emb
for block in self.transformer_blocks:
x = block(x)
x = self.ln_f(x)
logits = self.head(x)
return logits
class TransformerBlock(nn.Module):
def __init__(self, n_embd, n_head):
super(TransformerBlock, self).__init__()
self.ln1 = nn.LayerNorm(n_embd)
self.ln2 = nn.LayerNorm(n_embd)
self.attn = MultiHeadAttention(n_embd, n_head)
self.mlp = nn.Sequential(
nn.Linear(n_embd, 4 * n_embd),
nn.GELU(),
nn.Linear(4 * n_embd, n_embd),
)
def forward(self, x):
x = x + self.attn(self.ln1(x))
x = x + self.mlp(self.ln2(x))
return x
class MultiHeadAttention(nn.Module):
def __init__(self, n_embd, n_head):
super(MultiHeadAttention, self).__init__()
assert n_embd % n_head == 0
self.key = nn.Linear(n_embd, n_embd)
self.query = nn.Linear(n_embd, n_embd)
self.value = nn.Linear(n_embd, n_embd)
self.n_head = n_head
self.head_dim = n_embd // n_head
self.proj = nn.Linear(n_embd, n_embd)
self.register_buffer("mask", torch.tril(torch.ones(512, 512)).unsqueeze(0))
def forward(self, x):
B, T, C = x.size()
k = self.key(x).view(B, T, self.n_head, self.head_dim).transpose(1, 2)
q = self.query(x).view(B, T, self.n_head, self.head_dim).transpose(1, 2)
v = self.value(x).view(B, T, self.n_head, self.head_dim).transpose(1, 2)
attn = (q @ k.transpose(-2, -1)) * (1.0 / float(k.size(-1)) ** 0.5)
attn = attn.masked_fill(self.mask[:, :, :T, :T] == 0, float('-inf'))
attn = F.softmax(attn, dim=-1)
y = attn @ v
y = y.transpose(1, 2).contiguous().view(B, T, C)
y = self.proj(y)
return y
# Hyperparameters
vocab_size = 50000 # Size of vocabulary
n_embd = 768 # Embedding dimension
n_layer = 12 # Number of layers (blocks)
n_head = 12 # Number of attention heads
block_size = 512 # Maximum context size
# Instantiate and test the GPT model
model = GPT(vocab_size=vocab_size, n_embd=n_embd, n_layer=n_layer, n_head=n_head, block_size=block_size)
dummy_input = torch.randint(0, vocab_size, (1, block_size)) # Random input sequence
logits = model(dummy_input)
print(logits.shape) # Output logits shape
Important Points:
- Positional Encoding: The model uses positional embeddings to retain the order of tokens since self-attention does not inherently contain positional information.
- Attention Mechanism: The core of the Transformer block is self-attention followed by a feedforward layer.
- Pre-layer Normalization: Layer normalization prior to the sublayers for stabilizing training.
- Autoregressive Masking: Ensures that the model does not attend to subsequent words when predicting the next word in a sequence.
This implementation is a simplified educational example. For real-world use, you'd want to incorporate data handling, tokenizer preprocessing, model training loops, parameter tuning, optimizers, learning rate schedules, etc.