117 coding exercises (1184 tests) for learning RL-based LLM training concepts, inspired by the slime codebase and general LLM training patterns.
Each exercise has 3 files:
problem.py- Function signatures with docstrings and TODO placeholders (what you implement)solution.py- Reference solutiontest_solution.py- Pytest test cases (import from solution.py; copy and change import to test your own)
| # | Category | Exercises | Framework | Difficulty |
|---|---|---|---|---|
| 01 | RL Fundamentals - GAE, PPO clipping, KL divergence, GRPO, REINFORCE | 5 | numpy | Easy-Medium |
| 02 | Reward Functions - Math normalization, F1 score, reward shaping, outcome RM | 4 | numpy/stdlib | Easy-Medium |
| 03 | Data Processing - Chat templates, sequence packing, seq-len balancing, loss masks | 4 | numpy | Easy-Hard |
| 04 | Distributed Training - GPU placement, weight sharding, async scheduling | 3 | numpy | Medium-Hard |
| 05 | Rollout Pipeline - Data sources, replay buffers, filters, best-of-N sampling | 4 | numpy | Easy-Medium |
| 06 | Metrics & Logging - Pass@k, training tracker, compression/repetition detection | 3 | numpy/stdlib | Easy-Medium |
| 07 | Loss & Masking - Cross-entropy, log probs, OPSM, dual-clip PPO | 4 | numpy | Easy-Hard |
| 08 | Attention Mechanisms - Flash attention, RoPE, GQA, KV cache, sliding window | 8 | PyTorch | Easy-Hard |
| 09 | Torch RL Training - PPO/GRPO/KL loss in PyTorch, GAE, entropy, importance sampling | 8 | PyTorch | Easy-Hard |
| 10 | Model Architecture - RMSNorm, SwiGLU, LoRA, transformer block, LM head | 8 | PyTorch | Easy-Hard |
| 11 | Sampling & Decoding - Top-k/p, beam search, speculative decoding, repetition penalty | 8 | PyTorch/numpy | Easy-Hard |
| 12 | Distributed Primitives - All-reduce, tensor parallel, pipeline schedule, gradient accumulation | 7 | PyTorch/numpy | Easy-Hard |
| 13 | Weight Conversion - QKV split, gate-up split, LoRA merge, dtype conversion, name mapping | 7 | PyTorch/numpy | Easy-Medium |
| 14 | Memory & Efficiency - Gradient checkpointing, mixed precision, FLOPs, CPU offloading | 7 | PyTorch/numpy | Easy-Hard |
| 15 | Evaluation & Benchmarks - Perplexity, ECE, majority voting, exact match, MCQA | 7 | PyTorch/numpy | Easy-Medium |
| 16 | MoE & Routing - Top-k routing, load balancing, expert dispatch, routing replay | 7 | PyTorch/numpy | Easy-Hard |
| 17 | Training Loop Patterns - LR scheduler, DPO loss, EMA, SFT step, curriculum learning | 8 | PyTorch/numpy | Easy-Hard |
| 18 | RLHF & Alignment - Bradley-Terry RM, RLOO, IPO, KTO, win-rate/ELO | 5 | PyTorch/numpy | Medium-Hard |
| 19 | Optimizers & Tokenization - AdamW internals, BPE, ZeRO sharding, special tokens, constrained decoding | 5 | PyTorch/numpy | Easy-Hard |
| 20 | Inference & Serving - PagedAttention, INT8 quantization, ALiBi, cross-attention, multi-token prediction | 5 | PyTorch | Medium-Hard |
The categories are numbered by topic, not by recommended order. Follow this path for the best learning progression — each phase builds on the previous one.
Core RL algorithms and loss functions that underpin LLM training.
- Cat 01 — RL Fundamentals (GAE, PPO, KL, GRPO, REINFORCE)
- Cat 07 — Loss & Masking (cross-entropy, log probs, OPSM, dual-clip PPO)
- Cat 02 — Reward Functions (math normalization, F1, reward shaping)
- Cat 03 — Data Processing (chat templates, packing, loss masks)
Understand the transformer architecture from the ground up.
- Cat 08 — Attention Mechanisms (start with ex01→ex04→ex02→ex05→ex06→ex07→ex03→ex08)
- Cat 10 — Model Architecture (RMSNorm → SwiGLU → transformer block → LM head)
- Cat 11 — Sampling & Decoding (temperature → top-k/p → beam search → speculative decoding)
Combine RL + model knowledge into actual training code.
- Cat 09 — Torch RL Training (PPO/GAE/KL/GRPO re-implemented with autograd)
- Cat 17 — Training Loop Patterns (LR scheduler, gradient clipping, SFT, DPO)
- Cat 19 — Optimizers & Tokenization (AdamW, BPE, ZeRO, constrained decoding)
Make training work on large models across multiple GPUs.
- Cat 14 — Memory & Efficiency (gradient checkpointing, mixed precision, FLOPs)
- Cat 12 — Distributed Primitives (all-reduce, tensor parallel, pipeline schedule)
- Cat 04 — Distributed Training (GPU placement, weight sharding, async scheduling)
- Cat 05 — Rollout Pipeline (data sources, replay buffers, filters, best-of-N)
- Cat 06 — Metrics & Logging (pass@k, training tracker, repetition detection)
Specialized knowledge for production LLM systems.
- Cat 13 — Weight Conversion (QKV split, LoRA merge, name mapping)
- Cat 15 — Evaluation & Benchmarks (perplexity, calibration, exact match)
- Cat 16 — MoE & Routing (top-k routing, load balancing, expert dispatch)
- Cat 18 — RLHF & Alignment (Bradley-Terry, RLOO, IPO, KTO, ELO)
- Cat 20 — Inference & Serving (paged attention, INT8 quantization, ALiBi, MTP)
# Run all solution tests (1184 tests)
python -m pytest exercises/ -v
# Work on an exercise
cp exercises/01_rl_fundamentals/ex01_gae/problem.py exercises/01_rl_fundamentals/ex01_gae/my_solution.py
# Edit my_solution.py to implement the functions
# Then test against the test cases (modify import in test file)- Python 3.10+
- numpy
- pytest
- PyTorch (for categories 08-17)
Categories 01-07 use numpy only. Categories 08-17 require PyTorch (CPU is sufficient, no GPU needed).
- GAE (Medium) - Generalized Advantage Estimation with gamma/lambda discounting
- PPO Clipping (Medium) - Clipped surrogate objective for policy optimization
- KL Divergence (Easy) - k1/k2/k3 approximation methods
- GRPO Advantages (Easy) - Group Relative Policy Optimization normalization
- REINFORCE Baseline (Medium) - Discounted returns with baseline subtraction
- Math Answer Normalization (Medium) - Strip LaTeX formatting for answer comparison
- F1 Score (Easy) - Token-level precision/recall/F1
- Reward Shaping (Easy) - Length penalties and format bonuses
- Outcome Reward Model (Medium) - Multi-strategy answer extraction and comparison
- Chat Template (Easy) - ChatML message formatting
- Sequence Packing (Medium) - Bin-packing variable-length sequences
- Sequence Length Balancing (Hard) - Karmarkar-Karp partitioning algorithm
- Loss Mask Generation (Medium) - Multi-turn SFT loss masks
- GPU Placement (Medium) - Actor/critic/rollout GPU allocation
- Weight Sharding (Medium) - Tensor splitting and gathering across workers
- Async Training Scheduler (Hard) - Overlapping generation and training
- Data Source (Medium) - Epoch-tracking prompt dataset
- Replay Buffer (Medium) - FIFO + priority experience buffer
- Dynamic Sampling Filter (Easy) - Chainable sample group filters
- Best-of-N Sampling (Medium) - Greedy, weighted, and rejection sampling
- Pass@k (Medium) - Unbiased pass rate estimation
- Training Metrics Tracker (Medium) - Moving averages and anomaly detection
- Compression Repetition Detection (Easy) - zlib ratio and n-gram methods
- Cross-Entropy Loss (Medium) - Numerically stable masked LM loss
- Log Probs from Logits (Easy) - Per-token log probability extraction
- Off-Policy Masking (Easy) - OPSM: KL + advantage-based sequence masking
- Dual-Clip PPO (Hard) - Extended PPO with lower bound clipping
- Scaled Dot-Product Attention (Medium) - Q@K^T/sqrt(d_k) with causal mask
- Multi-Head Attention (Medium) - Head splitting, parallel attention, concatenation
- Flash Attention Tiling (Hard) - Block-wise attention with online softmax trick
- Causal Mask (Easy) - Lower-triangular autoregressive mask generation
- Rotary Positional Embedding (Hard) - RoPE rotation matrices for Q, K
- Grouped Query Attention (Medium) - GQA with KV head expansion
- KV Cache (Medium) - Incremental cache for autoregressive decoding
- Sliding Window Attention (Medium) - Local attention with window size limit
- Policy Gradient Loss (Medium) - PPO clipped loss with autograd
- GAE in PyTorch (Medium) - Vectorized GAE with batch support
- Value Function Loss (Easy) - Clipped value loss for critic training
- Entropy Bonus (Easy) - Entropy computation from logits
- Importance Sampling Ratio (Medium) - Per-token ratios with TIS clipping
- Reward Normalization (Easy) - Running EMA normalization
- KL Penalty Loss (Medium) - Per-token KL with loss mask
- GRPO Loss (Hard) - Full GRPO: group advantages + PPO clip + KL penalty
- RMSNorm (Easy) - Root Mean Square Layer Normalization
- SwiGLU (Easy) - Gated activation for FFN
- Transformer Block (Hard) - Full decoder block with pre-norm residuals
- Positional Encoding (Easy) - Sinusoidal position embeddings
- LoRA Linear (Medium) - Low-rank adaptation with merge/unmerge
- Embedding with Tying (Medium) - Shared input/output embeddings
- Residual Stream (Easy) - Pre-norm residual connections with scaling
- Simple LM Head (Medium) - Minimal GPT-style language model
- Temperature Scaling (Easy) - Logit temperature adjustment
- Top-K Sampling (Easy) - Keep only top-k logits
- Top-P Sampling (Medium) - Nucleus sampling with cumulative probability
- Repetition Penalty (Easy) - Penalize repeated tokens
- Beam Search (Hard) - Multi-beam decoding with length normalization
- Speculative Decoding (Hard) - Draft-verify acceleration
- Logit Processor Chain (Medium) - Composable logit transformations
- Stop Criteria (Easy) - Token/length/string stopping conditions
- All-Reduce Simulation (Medium) - Sum/mean/max across virtual workers
- Gradient Accumulation (Medium) - Micro-batch gradient accumulation
- Distributed Whitening (Medium) - Global advantage normalization
- Tensor Parallel Linear (Hard) - Column and row parallel linear layers
- Pipeline Schedule (Medium) - GPipe scheduling with bubble ratio
- Data Parallel Partitioning (Easy) - Contiguous/interleaved/balanced splits
- Checkpoint Sharding (Medium) - Shard state dict across files
- QKV Split (Medium) - Split fused QKV weight for GQA
- Gate-Up Split (Easy) - Split fused MoE gate/up projections
- Weight Name Mapping (Medium) - Megatron to HuggingFace name conversion
- Dtype Conversion (Easy) - fp32/bf16/fp16/fp8 conversion with error tracking
- Tensor Hash Verification (Easy) - Checkpoint integrity via uint32 hashing
- LoRA Merge (Medium) - Merge/unmerge LoRA adapters into base model
- Expert Weight Reorder (Medium) - Reorder MoE experts by routing frequency
- Gradient Checkpointing (Hard) - Recompute activations during backward
- Mixed Precision Training (Medium) - fp16/bf16 forward with loss scaling
- Activation Memory Estimation (Medium) - Predict memory usage from config
- CPU Offloading (Medium) - Parameter offload/onload for memory saving
- FLOPs Counter (Medium) - Count FLOPs for transformer operations
- Memory Budget Planner (Medium) - GPU memory allocation planning
- Throughput Calculator (Easy) - tokens/sec, TFLOPs, MFU metrics
- Perplexity (Medium) - Compute PPL from masked log probabilities
- Calibration Metrics (Medium) - Expected Calibration Error (ECE)
- Majority Voting (Medium) - Self-consistency with weighted voting
- Exact Match (Easy) - Normalized text comparison
- MCQA Evaluation (Medium) - Multiple-choice answer extraction
- Eval Config Builder (Medium) - Hierarchical config resolution
- Benchmark Aggregation (Easy) - Macro/weighted averages with bootstrap CI
- Top-K Routing (Medium) - Expert selection with router logits
- Load Balancing Loss (Medium) - Auxiliary loss for uniform utilization
- Expert Parallel Dispatch (Hard) - Token scatter/gather through experts
- Routing Replay (Medium) - Cache and replay routing decisions
- Shared Expert (Medium) - Shared + routed expert architecture
- Expert Frequency Analysis (Easy) - Utilization and dead expert detection
- Capacity Factor (Medium) - Expert token capacity limiting
- Learning Rate Scheduler (Medium) - Warmup-cosine and warmup-linear decay
- Gradient Clipping (Easy) - Global norm clipping
- EMA Model (Medium) - Exponential moving average of weights
- SFT Training Step (Medium) - Masked cross-entropy for supervised fine-tuning
- DPO Loss (Hard) - Direct Preference Optimization
- Curriculum Scheduler (Medium) - Difficulty-based data ordering
- Training State Manager (Medium) - Checkpointing with early stopping
- Online vs Offline RL (Medium) - Data flow simulation and staleness
- Bradley-Terry Reward Model (Hard) - Pairwise ranking loss for reward model training
- RLOO Advantages (Medium) - REINFORCE Leave-One-Out variance reduction
- IPO Loss (Medium) - Identity Preference Optimization squared-loss variant
- KTO Loss (Medium) - Kahneman-Tversky Optimization with unpaired feedback
- Win-Rate & ELO (Medium) - Pairwise comparison metrics and rating systems
- AdamW Optimizer (Medium) - First/second moment, bias correction, decoupled weight decay
- BPE Tokenizer (Medium) - Byte-Pair Encoding training, encoding, and decoding
- ZeRO Optimizer Sharding (Hard) - Stage 1/2/3 optimizer state partitioning
- Special Token Handler (Easy) - BOS/EOS/PAD management and batch padding
- Constrained Decoding (Medium) - FSM-based structured output generation
- Paged Attention (Hard) - Block-based KV cache with allocation/free
- INT8 Quantization (Medium) - Symmetric/asymmetric per-channel quantization
- ALiBi Attention (Medium) - Attention with Linear Biases for position encoding
- Cross-Attention (Medium) - Encoder-decoder cross-attention mechanism
- Multi-Token Prediction (Medium) - N-ahead prediction heads from single hidden state