| name | nanogpt |
| description | Educational GPT implementation in ~300 lines. Reproduces GPT-2 (124M) on OpenWebText. Clean, hackable code for learning transformers. By Andrej Karpathy. Perfect for understanding GPT architecture from scratch. Train on Shakespeare (CPU) or OpenWebText (multi-GPU). |
| version | 1.0.0 |
| author | Orchestra Research |
| license | MIT |
| tags | ["Model Architecture","NanoGPT","GPT-2","Educational","Andrej Karpathy","Transformer","Minimalist","From Scratch","Training"] |
| dependencies | ["torch","transformers","datasets","tiktoken","wandb"] |
nanoGPT - Minimalist GPT Training
Quick start
nanoGPT is a simplified GPT implementation designed for learning and experimentation.
Installation:
pip install torch numpy transformers datasets tiktoken wandb tqdm
Train on Shakespeare (CPU-friendly):
python data/shakespeare_char/prepare.py
python train.py config/train_shakespeare_char.py
python sample.py --out_dir=out-shakespeare-char
Output:
ROMEO:
What say'st thou? Shall I speak, and be a man?
JULIET:
I am afeard, and yet I'll speak; for thou art
One that hath been a man, and yet I know not
What thou art.
Common workflows
Workflow 1: Character-level Shakespeare
Complete training pipeline:
python data/shakespeare_char/prepare.py
python train.py config/train_shakespeare_char.py
python sample.py --out_dir=out-shakespeare-char
Config (config/train_shakespeare_char.py):
n_layer = 6
n_head = 6
n_embd = 384
block_size = 256
batch_size = 64
learning_rate = 1e-3
max_iters = 5000
eval_interval = 500
device = 'cpu'
compile = False
Training time: ~5 minutes (CPU), ~1 minute (GPU)
Workflow 2: Reproduce GPT-2 (124M)
Multi-GPU training on OpenWebText:
python data/openwebtext/prepare.py
torchrun --standalone --nproc_per_node=8 \
train.py config/train_gpt2.py
python sample.py --out_dir=out
Config (config/train_gpt2.py):
n_layer = 12
n_head = 12
n_embd = 768
block_size = 1024
dropout = 0.0
batch_size = 12
gradient_accumulation_steps = 5 * 8
learning_rate = 6e-4
max_iters = 600000
lr_decay_iters = 600000
compile = True
Training time: ~4 days (8× A100)
Workflow 3: Fine-tune pretrained GPT-2
Start from OpenAI checkpoint:
init_from = 'gpt2'
python train.py config/finetune_shakespeare.py
Example config (config/finetune_shakespeare.py):
init_from = 'gpt2'
dataset = 'shakespeare_char'
batch_size = 1
block_size = 1024
learning_rate = 3e-5
max_iters = 2000
warmup_iters = 100
weight_decay = 1e-1
Workflow 4: Custom dataset
Train on your own text:
import numpy as np
with open('my_data.txt', 'r') as f:
text = f.read()
chars = sorted(list(set(text)))
stoi = {ch: i for i, ch in enumerate(chars)}
itos = {i: ch for i, ch in enumerate(chars)}
data = np.array([stoi[ch] for ch in text], dtype=np.uint16)
n = len(data)
train_data = data[:int(n*0.9)]
val_data = data[int(n*0.9):]
train_data.tofile('data/custom/train.bin')
val_data.tofile('data/custom/val.bin')
Train:
python data/custom/prepare.py
python train.py --dataset=custom
When to use vs alternatives
Use nanoGPT when:
- Learning how GPT works
- Experimenting with transformer variants
- Teaching/education purposes
- Quick prototyping
- Limited compute (can run on CPU)
Simplicity advantages:
- ~300 lines: Entire model in
model.py
- ~300 lines: Training loop in
train.py
- Hackable: Easy to modify
- No abstractions: Pure PyTorch
Use alternatives instead:
- HuggingFace Transformers: Production use, many models
- Megatron-LM: Large-scale distributed training
- LitGPT: More architectures, production-ready
- PyTorch Lightning: Need high-level framework
Common issues
Issue: CUDA out of memory
Reduce batch size or context length:
batch_size = 1
block_size = 512
gradient_accumulation_steps = 40
Issue: Training too slow
Enable compilation (PyTorch 2.0+):
compile = True
Use mixed precision:
dtype = 'bfloat16'
Issue: Poor generation quality
Train longer:
max_iters = 10000
Lower temperature:
temperature = 0.7
top_k = 200
Issue: Can't load GPT-2 weights
Install transformers:
pip install transformers
Check model name:
init_from = 'gpt2'
Advanced topics
Model architecture: See references/architecture.md for GPT block structure, multi-head attention, and MLP layers explained simply.
Training loop: See references/training.md for learning rate schedule, gradient accumulation, and distributed data parallel setup.
Data preparation: See references/data.md for tokenization strategies (character-level vs BPE) and binary format details.
Hardware requirements
Performance:
- With
compile=True: 2× speedup
- With
dtype=bfloat16: 50% memory reduction
Resources