Best Practices Intermediate

Training ML models is as much art as science. These best practices distill years of collective experience from the ML community into actionable guidelines. Following these recipes will save you countless hours of debugging and help you achieve better results faster.

Training Recipe

  1. Start simple, then scale

    Begin with a small model on a small dataset. Verify it can overfit a single batch (loss goes to near zero). This confirms your pipeline is correct.

  2. Use standard defaults first

    AdamW with lr=3e-4, batch size 32-64, no fancy scheduling. Get a baseline before experimenting.

  3. Monitor everything

    Track training loss, validation loss, gradient norms, learning rate, and parameter norms. Use W&B or TensorBoard.

  4. Add complexity gradually

    Learning rate schedules, data augmentation, regularization - add one at a time and measure the impact.

Debugging Optimization

When Training Goes Wrong:
  • Loss not decreasing: Learning rate too low, bug in loss computation, or data preprocessing error. Try 10x larger learning rate.
  • Loss NaN/Inf: Learning rate too high, missing gradient clipping, log(0), or division by zero. Add epsilon values and clip gradients.
  • Loss oscillating wildly: Learning rate too high or batch size too small. Reduce learning rate by 3-10x.
  • Training loss low, validation loss high: Overfitting. Add dropout, weight decay, data augmentation, or use a smaller model.
  • Both losses plateau early: Model too small, learning rate too low, or data issue. Try a larger model or higher learning rate.

Essential Techniques

Technique When to Use Typical Values
Learning rate warmup Transformers, large batch training 1000-4000 steps linear warmup
Gradient clipping RNNs, transformers, any exploding gradient risk Max norm of 1.0 or 5.0
Weight decay Almost always 0.01 for AdamW, 1e-4 for SGD
Early stopping When validation loss stops improving Patience of 5-10 epochs
Mixed precision GPU training for speed/memory savings fp16 or bf16 with loss scaling

Quick Reference

Python
import torch
import torch.nn as nn

# Standard training loop with best practices
model = MyModel()
optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4, weight_decay=0.01)
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=num_epochs)

best_val_loss = float('inf')
patience_counter = 0

for epoch in range(num_epochs):
    model.train()
    for batch in train_loader:
        optimizer.zero_grad()
        loss = criterion(model(batch.x), batch.y)
        loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
        optimizer.step()

    scheduler.step()

    # Validation + early stopping
    val_loss = evaluate(model, val_loader)
    if val_loss < best_val_loss:
        best_val_loss = val_loss
        torch.save(model.state_dict(), 'best_model.pt')
        patience_counter = 0
    else:
        patience_counter += 1
        if patience_counter >= 10:
            break  # Early stopping

Course Complete!

Congratulations! You have completed the Optimization for ML course and the entire Math for AI series. You now have a solid mathematical foundation for understanding and building machine learning systems.

Review: Linear Algebra →

Ready to Go Deeper?

Live instructor-led courses from our partners. Affiliate disclosure.