LLM Pre-training Helper
A skill for training language models from scratch using PyTorch, following best practices from the "LLMs from Scratch" methodology.
What this skill does
This skill helps you:
- Set up GPT model architectures with proper configuration
- Prepare training data with tokenization and data loaders
- Configure training loops with loss monitoring and evaluation
- Implement text generation with sampling strategies
- Save and load model checkpoints
- Visualize training progress (loss, perplexity)
When to use this skill
Use this skill when:
- You want to train an LLM from scratch on your own dataset
- You need to understand the pre-training workflow
- You're setting up GPT model configurations
- You want to monitor training metrics (loss, perplexity)
- You need to save/load model checkpoints
- You're implementing text generation with temperature/top-k sampling
Quick Start
1. Set up model configuration
GPT_CONFIG = {
"vocab_size": 50257, # GPT-2 vocabulary size
"context_length": 256, # Context window (adjust based on data)
"emb_dim": 768, # Embedding dimension
"n_heads": 12, # Attention heads
"n_layers": 12, # Transformer layers
"drop_rate": 0.1, # Dropout rate
"qkv_bias": False # Query-key-value bias
}
2. Prepare your data
# Load your text data
text_data = "your training text here"
# Split into train/validation (90/10 is common)
train_ratio = 0.90
split_idx = int(train_ratio * len(text_data))
train_data = text_data[:split_idx]
val_data = text_data[split_idx:]
# Create data loaders
train_loader = create_dataloader_v1(
train_data,
batch_size=2,
max_length=GPT_CONFIG["context_length"],
stride=GPT_CONFIG["context_length"],
shuffle=True,
drop_last=True
)
val_loader = create_dataloader_v1(
val_data,
batch_size=2,
max_length=GPT_CONFIG["context_length"],
stride=GPT_CONFIG["context_length"],
shuffle=False,
drop_last=False
)
3. Initialize model and start training
import torch
# Set seed for reproducibility
torch.manual_seed(123)
# Initialize model
model = GPTModel(GPT_CONFIG)
# Select device
if torch.cuda.is_available():
device = torch.device("cuda")
elif torch.backends.mps.is_available():
device = torch.device("mps")
else:
device = torch.device("cpu")
model.to(device)
# Setup optimizer
optimizer = torch.optim.AdamW(
model.parameters(),
lr=0.0004,
weight_decay=0.1
)
# Train
num_epochs = 10
train_losses, val_losses, tokens_seen = train_model_simple(
model, train_loader, val_loader, optimizer, device,
num_epochs=num_epochs,
eval_freq=5, # Evaluate every 5 steps
eval_iter=5, # Use 5 batches for evaluation
start_context="Your starting phrase",
tokenizer=tokenizer
)
Core Components
Model Architecture
The GPT model consists of:
- Token embeddings: Convert token IDs to vectors
- Positional embeddings: Add position information
- Transformer blocks: Multi-head attention + feed-forward
- Output head: Maps embeddings back to vocabulary
Training Loop Structure
For each epoch:
For each batch:
1. Zero gradients
2. Forward pass → get logits
3. Calculate loss (cross-entropy)
4. Backward pass → compute gradients
5. Optimizer step → update weights
6. (Optional) Evaluate and log metrics
Loss Functions
- Cross-entropy loss: Measures difference between predicted and actual token distributions
- Perplexity:
exp(loss) - represents model uncertainty (lower is better)
Text Generation Strategies
| Strategy |
Description |
Use Case |
| Greedy |
Always pick highest probability token |
Deterministic output |
| Top-k |
Sample from top k tokens |
Balanced diversity |
| Temperature |
Scale logits before softmax |
Control randomness |
| Top-p (nucleus) |
Sample until cumulative probability threshold |
Adaptive diversity |
Training Parameters Guide
Learning Rate
- Small (1e-5 to 1e-4): Precise convergence, slower training
- Large (1e-3 to 1e-2): Faster training, risk of overshooting
- Recommended: Start with 4e-4 for AdamW
Batch Size
- Small (1-4): More frequent updates, noisier gradients
- Large (8-32): Smoother gradients, more memory
- Recommended: 2-4 for CPU, 8-16 for GPU
Context Length
- Short (128-256): Faster training, less context
- Long (512-1024): More context, slower training
- Recommended: Match your use case, start with 256
Number of Epochs
- Few (5-10): Quick iteration, may underfit
- Many (20-50): Better convergence, risk of overfitting
- Recommended: Monitor validation loss, stop when it plateaus
Monitoring Training
Key Metrics to Track
- Training Loss: Should decrease over time
- Validation Loss: Should decrease, watch for overfitting
- Perplexity:
exp(loss), lower is better
- Tokens Seen: Track progress through dataset
Signs of Good Training
- Training loss steadily decreases
- Validation loss follows training loss
- Generated text becomes more coherent
- Perplexity drops significantly
Signs of Problems
- Overfitting: Training loss ↓, Validation loss ↑
- Underfitting: Both losses stay high
- Exploding gradients: Loss becomes NaN or inf
- Vanishing gradients: Loss stops decreasing
Saving and Loading Models
Save Full Checkpoint (for resuming training)
torch.save({
"model_state_dict": model.state_dict(),
"optimizer_state_dict": optimizer.state_dict(),
"epoch": current_epoch,
"loss": current_loss
}, "checkpoint.pth")
Load Full Checkpoint
checkpoint = torch.load("checkpoint.pth", map_location=device)
model.load_state_dict(checkpoint["model_state_dict"])
optimizer.load_state_dict(checkpoint["optimizer_state_dict"])
model.train()
Save Model Only (for inference)
torch.save(model.state_dict(), "model.pth")
Load Model Only
model = GPTModel(GPT_CONFIG)
model.load_state_dict(torch.load("model.pth", map_location=device))
model.eval()
Common Issues and Solutions
"Not enough tokens for training"
- Solution: Reduce
context_length or increase training data
- Check:
total_tokens * train_ratio >= context_length
"CUDA out of memory"
- Solution: Reduce batch size or context length
- Alternative: Use gradient accumulation
"Loss not decreasing"
- Check: Learning rate (try 1e-4 to 1e-3)
- Check: Data quality and tokenization
- Check: Model is in training mode (
model.train())
"Validation loss increasing"
- Solution: Early stopping, reduce epochs
- Alternative: Add regularization (dropout, weight decay)
Advanced Techniques (Not in Base Code)
Learning Rate Scheduling
- Linear Warmup: Start small, increase to max LR
- Cosine Decay: Gradually reduce LR after warmup
Gradient Clipping
- Prevents exploding gradients
- Set
max_norm in optimizer or use torch.nn.utils.clip_grad_norm_
Top-p Sampling (Nucleus)
- More adaptive than top-k
- Sums probabilities until threshold (e.g., 0.9)
Beam Search
- Explores multiple sequences simultaneously
- Better quality than greedy, more expensive
Next Steps
After training:
- Evaluate: Test on held-out data
- Fine-tune: Adapt to specific tasks
- Deploy: Use for inference or as base model
- Iterate: Adjust hyperparameters and retrain
References
1---2name: llm-pretraining-helper3description: How to train LLMs from scratch using PyTorch, including model architecture setup, data preparation, training loops, loss monitoring, and model saving/loading. Use this skill whenever the user wants to train a language model from scratch, understand pre-training workflows, set up GPT architectures, configure training parameters, monitor loss/perplexity, or load/save model checkpoints. Make sure to use this skill when users mention training LLMs, pre-training, model checkpoints, GPT architectures, training loops, or want to build language models from the ground up.4---56# LLM Pre-training Helper78A skill for training language models from scratch using PyTorch, following best practices from the "LLMs from Scratch" methodology.910## What this skill does1112This skill helps you:13- Set up GPT model architectures with proper configuration14- Prepare training data with tokenization and data loaders15- Configure training loops with loss monitoring and evaluation16- Implement text generation with sampling strategies17- Save and load model checkpoints18- Visualize training progress (loss, perplexity)1920## When to use this skill2122Use this skill when:23- You want to train an LLM from scratch on your own dataset24- You need to understand the pre-training workflow25- You're setting up GPT model configurations26- You want to monitor training metrics (loss, perplexity)27- You need to save/load model checkpoints28- You're implementing text generation with temperature/top-k sampling2930## Quick Start3132### 1. Set up model configuration3334```python35GPT_CONFIG = {36 "vocab_size": 50257, # GPT-2 vocabulary size37 "context_length": 256, # Context window (adjust based on data)38 "emb_dim": 768, # Embedding dimension39 "n_heads": 12, # Attention heads40 "n_layers": 12, # Transformer layers41 "drop_rate": 0.1, # Dropout rate42 "qkv_bias": False # Query-key-value bias43}44```4546### 2. Prepare your data4748```python49# Load your text data50text_data = "your training text here"5152# Split into train/validation (90/10 is common)53train_ratio = 0.9054split_idx = int(train_ratio * len(text_data))55train_data = text_data[:split_idx]56val_data = text_data[split_idx:]5758# Create data loaders59train_loader = create_dataloader_v1(60 train_data,61 batch_size=2,62 max_length=GPT_CONFIG["context_length"],63 stride=GPT_CONFIG["context_length"],64 shuffle=True,65 drop_last=True66)6768val_loader = create_dataloader_v1(69 val_data,70 batch_size=2,71 max_length=GPT_CONFIG["context_length"],72 stride=GPT_CONFIG["context_length"],73 shuffle=False,74 drop_last=False75)76```7778### 3. Initialize model and start training7980```python81import torch8283# Set seed for reproducibility84torch.manual_seed(123)8586# Initialize model87model = GPTModel(GPT_CONFIG)8889# Select device90if torch.cuda.is_available():91 device = torch.device("cuda")92elif torch.backends.mps.is_available():93 device = torch.device("mps")94else:95 device = torch.device("cpu")9697model.to(device)9899# Setup optimizer100optimizer = torch.optim.AdamW(101 model.parameters(),102 lr=0.0004,103 weight_decay=0.1104)105106# Train107num_epochs = 10108train_losses, val_losses, tokens_seen = train_model_simple(109 model, train_loader, val_loader, optimizer, device,110 num_epochs=num_epochs,111 eval_freq=5, # Evaluate every 5 steps112 eval_iter=5, # Use 5 batches for evaluation113 start_context="Your starting phrase",114 tokenizer=tokenizer115)116```117118## Core Components119120### Model Architecture121122The GPT model consists of:123- **Token embeddings**: Convert token IDs to vectors124- **Positional embeddings**: Add position information125- **Transformer blocks**: Multi-head attention + feed-forward126- **Output head**: Maps embeddings back to vocabulary127128### Training Loop Structure129130```131For each epoch:132 For each batch:133 1. Zero gradients134 2. Forward pass → get logits135 3. Calculate loss (cross-entropy)136 4. Backward pass → compute gradients137 5. Optimizer step → update weights138 6. (Optional) Evaluate and log metrics139```140141### Loss Functions142143- **Cross-entropy loss**: Measures difference between predicted and actual token distributions144- **Perplexity**: `exp(loss)` - represents model uncertainty (lower is better)145146### Text Generation Strategies147148| Strategy | Description | Use Case |149|----------|-------------|----------|150| Greedy | Always pick highest probability token | Deterministic output |151| Top-k | Sample from top k tokens | Balanced diversity |152| Temperature | Scale logits before softmax | Control randomness |153| Top-p (nucleus) | Sample until cumulative probability threshold | Adaptive diversity |154155## Training Parameters Guide156157### Learning Rate158- **Small (1e-5 to 1e-4)**: Precise convergence, slower training159- **Large (1e-3 to 1e-2)**: Faster training, risk of overshooting160- **Recommended**: Start with 4e-4 for AdamW161162### Batch Size163- **Small (1-4)**: More frequent updates, noisier gradients164- **Large (8-32)**: Smoother gradients, more memory165- **Recommended**: 2-4 for CPU, 8-16 for GPU166167### Context Length168- **Short (128-256)**: Faster training, less context169- **Long (512-1024)**: More context, slower training170- **Recommended**: Match your use case, start with 256171172### Number of Epochs173- **Few (5-10)**: Quick iteration, may underfit174- **Many (20-50)**: Better convergence, risk of overfitting175- **Recommended**: Monitor validation loss, stop when it plateaus176177## Monitoring Training178179### Key Metrics to Track1801811. **Training Loss**: Should decrease over time1822. **Validation Loss**: Should decrease, watch for overfitting1833. **Perplexity**: `exp(loss)`, lower is better1844. **Tokens Seen**: Track progress through dataset185186### Signs of Good Training187- Training loss steadily decreases188- Validation loss follows training loss189- Generated text becomes more coherent190- Perplexity drops significantly191192### Signs of Problems193- **Overfitting**: Training loss ↓, Validation loss ↑194- **Underfitting**: Both losses stay high195- **Exploding gradients**: Loss becomes NaN or inf196- **Vanishing gradients**: Loss stops decreasing197198## Saving and Loading Models199200### Save Full Checkpoint (for resuming training)201202```python203torch.save({204 "model_state_dict": model.state_dict(),205 "optimizer_state_dict": optimizer.state_dict(),206 "epoch": current_epoch,207 "loss": current_loss208}, "checkpoint.pth")209```210211### Load Full Checkpoint212213```python214checkpoint = torch.load("checkpoint.pth", map_location=device)215model.load_state_dict(checkpoint["model_state_dict"])216optimizer.load_state_dict(checkpoint["optimizer_state_dict"])217model.train()218```219220### Save Model Only (for inference)221222```python223torch.save(model.state_dict(), "model.pth")224```225226### Load Model Only227228```python229model = GPTModel(GPT_CONFIG)230model.load_state_dict(torch.load("model.pth", map_location=device))231model.eval()232```233234## Common Issues and Solutions235236### "Not enough tokens for training"237- **Solution**: Reduce `context_length` or increase training data238- **Check**: `total_tokens * train_ratio >= context_length`239240### "CUDA out of memory"241- **Solution**: Reduce batch size or context length242- **Alternative**: Use gradient accumulation243244### "Loss not decreasing"245- **Check**: Learning rate (try 1e-4 to 1e-3)246- **Check**: Data quality and tokenization247- **Check**: Model is in training mode (`model.train()`)248249### "Validation loss increasing"250- **Solution**: Early stopping, reduce epochs251- **Alternative**: Add regularization (dropout, weight decay)252253## Advanced Techniques (Not in Base Code)254255### Learning Rate Scheduling256- **Linear Warmup**: Start small, increase to max LR257- **Cosine Decay**: Gradually reduce LR after warmup258259### Gradient Clipping260- Prevents exploding gradients261- Set `max_norm` in optimizer or use `torch.nn.utils.clip_grad_norm_`262263### Top-p Sampling (Nucleus)264- More adaptive than top-k265- Sums probabilities until threshold (e.g., 0.9)266267### Beam Search268- Explores multiple sequences simultaneously269- Better quality than greedy, more expensive270271## Next Steps272273After training:2741. **Evaluate**: Test on held-out data2752. **Fine-tune**: Adapt to specific tasks2763. **Deploy**: Use for inference or as base model2774. **Iterate**: Adjust hyperparameters and retrain278279## References280281- [LLMs from Scratch](https://www.manning.com/books/build-a-large-language-model-from-scratch)282- [rasbt/LLMs-from-scratch](https://github.com/rasbt/LLMs-from-scratch)283- [GPT-2 Architecture](https://d4mucfpksywv.cloudfront.net/better-language-models/language-models.pdf)