GPT Models
The Generative Pre-trained Transformer (GPT) family demonstrates the power of scaling autoregressive language models. GPT models use only the decoder portion of the transformer with causal masking.
Autoregressive Language Modeling
GPT models predict the next token given all previous tokens.
The model maximizes the log-likelihood of the training data:
Causal Masking
Causal masking ensures each position can only attend to previous positions (and itself), preventing information leakage from future tokens.
import torch
import torch.nn as nn
import math
def create_causal_attention_mask(seq_len, device='cpu'):
mask = torch.triu(torch.ones(seq_len, seq_len, device=device), diagonal=1)
mask = mask.masked_fill(mask == 1, float('-inf'))
return mask.unsqueeze(0).unsqueeze(0)
# Example for sequence length 5
mask = create_causal_attention_mask(5)
print(mask)
# tensor([[[[ 0., -inf, -inf, -inf, -inf],
# [ 0., 0., -inf, -inf, -inf],
# [ 0., 0., 0., -inf, -inf],
# [ 0., 0., 0., 0., -inf],
# [ 0., 0., 0., 0., 0.]]]])
GPT-2 Architecture
| Parameter | Value |
|---|---|
| Vocabulary size | 50,257 (BPE) |
| Context window | 1024 tokens |
| Model dimension | 1600 |
| Attention heads | 25 |
| Transformer layers | 48 |
| Total parameters | 1.5 billion |
from transformers import GPT2LMHeadModel, GPT2Tokenizer
tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
model = GPT2LMHeadModel.from_pretrained('gpt2')
def generate_text(prompt, max_length=50, temperature=1.0, top_k=50):
input_ids = tokenizer.encode(prompt, return_tensors='pt')
output = model.generate(
input_ids,
max_length=max_length,
temperature=temperature,
top_k=top_k,
do_sample=True,
no_repeat_ngram_size=2
)
return tokenizer.decode(output[0], skip_special_tokens=True)
print(generate_text("The future of AI is"))
GPT-3 Scaling
GPT-3 demonstrated that scaling up language models dramatically improves few-shot and zero-shot performance.
| Model | Parameters | Layers | d_model | Heads | Training Tokens |
|---|---|---|---|---|---|
| GPT-3 Small | 125M | 12 | 768 | 12 | 300B |
| GPT-3 Medium | 350M | 24 | 1024 | 16 | 300B |
| GPT-3 Large | 760M | 24 | 1536 | 16 | 300B |
| GPT-3 XL | 1.3B | 24 | 2048 | 24 | 300B |
| GPT-3 2.7B | 2.7B | 32 | 2564 | 32 | 300B |
| GPT-3 6.7B | 6.7B | 32 | 4096 | 32 | 300B |
| GPT-3 13B | 13B | 40 | 5140 | 40 | 300B |
| GPT-3 175B | 175B | 96 | 12288 | 96 | 300B |
Where N is the number of parameters, and L is the expected loss.
Complete GPT Implementation
import torch
import torch.nn as nn
class CausalSelfAttention(nn.Module):
def __init__(self, d_model, num_heads, max_len, dropout=0.1):
super().__init__()
self.num_heads = num_heads
self.head_dim = d_model // num_heads
self.qkv = nn.Linear(d_model, 3 * d_model)
self.proj = nn.Linear(d_model, d_model)
self.attn_dropout = nn.Dropout(dropout)
self.resid_dropout = nn.Dropout(dropout)
# Causal mask
self.register_buffer("mask", torch.tril(
torch.ones(max_len, max_len)
).view(1, 1, max_len, max_len))
def forward(self, x):
B, T, C = x.size()
qkv = self.qkv(x).reshape(B, T, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4)
q, k, v = qkv[0], qkv[1], qkv[2]
att = (q @ k.transpose(-2, -1)) * (1.0 / (k.size(-1) ** 0.5))
att = att.masked_fill(self.mask[:, :, :T, :T] == 0, float('-inf'))
att = torch.softmax(att, dim=-1)
att = self.attn_dropout(att)
y = (att @ v).transpose(1, 2).reshape(B, T, C)
y = self.resid_dropout(self.proj(y))
return y
class GPTBlock(nn.Module):
def __init__(self, d_model, num_heads, max_len, dropout=0.1):
super().__init__()
self.ln1 = nn.LayerNorm(d_model)
self.attn = CausalSelfAttention(d_model, num_heads, max_len, dropout)
self.ln2 = nn.LayerNorm(d_model)
self.ffn = nn.Sequential(
nn.Linear(d_model, 4 * d_model),
nn.GELU(),
nn.Linear(4 * d_model, d_model),
nn.Dropout(dropout)
)
def forward(self, x):
x = x + self.attn(self.ln1(x))
x = x + self.ffn(self.ln2(x))
return x
class GPT(nn.Module):
def __init__(self, vocab_size, d_model, num_heads, num_layers, max_len, dropout=0.1):
super().__init__()
self.token_emb = nn.Embedding(vocab_size, d_model)
self.pos_emb = nn.Embedding(max_len, d_model)
self.dropout = nn.Dropout(dropout)
self.blocks = nn.Sequential(*[
GPTBlock(d_model, num_heads, max_len, dropout)
for _ in range(num_layers)
])
self.ln_f = nn.LayerNorm(d_model)
self.head = nn.Linear(d_model, vocab_size, bias=False)
def forward(self, idx, targets=None):
B, T = idx.size()
pos = torch.arange(0, T, device=idx.device).unsqueeze(0)
x = self.dropout(self.token_emb(idx) + self.pos_emb(pos))
x = self.blocks(x)
x = self.ln_f(x)
logits = self.head(x)
if targets is None:
return logits
loss = nn.functional.cross_entropy(
logits.view(-1, logits.size(-1)),
targets.view(-1)
)
return logits, loss
Zero-Shot vs Few-Shot vs Fine-Tuning
| Approach | Examples | Performance | Cost |
|---|---|---|---|
| Zero-shot | 0 | Moderate | Low |
| One-shot | 1 | Good | Low |
| Few-shot | 5-100 | Very Good | Low |
| Fine-tuning | 1000+ | Best | High |
Text Generation Strategies
| Strategy | Description | Control |
|---|---|---|
| Greedy | Always pick highest probability | None |
| Beam search | Keep top-k sequences | num_beams |
| Top-k | Sample from top-k tokens | top_k |
| Top-p (nucleus) | Sample from smallest set with cumulative prob âĨ p | top_p |
| Temperature | Scale logits before softmax | temperature |
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type â Always start by categorizing the problem
- Incorrect formula application â Verify the formula applies to your specific case
- Unit errors â Always check units are consistent throughout
- Sign errors â Pay careful attention to positive and negative values
- Rounding too early â Keep full precision until the final answer
- Forgetting constraints â Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic â Build on the foundation laid here
- Next Topic â See how this concept extends to more advanced material
- Practice Problems â Additional exercises with solutions
- Video Explanation â Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions