SKILL.md
SKILL.mdBrowse 4 files
2,227 tokens
8,971 bytes
Token encoding: o200k_base
Snapshot 24fd22b
1---2name: pytorch-lightning3description: Clean training loops with built-in distributed support.4version: 1.0.05author: Orchestra Research6license: MIT7dependencies: [lightning, torch, transformers]8platforms: [linux, macos, windows]9metadata:10 hermes:11 tags: [PyTorch Lightning, Training Framework, Distributed Training, DDP, FSDP, DeepSpeed, High-Level API, Callbacks, Best Practices, Scalable]12 13---14 15# PyTorch Lightning - High-Level Training Framework16 17## Quick start18 19PyTorch Lightning organizes PyTorch code to eliminate boilerplate while maintaining flexibility.20 21**Installation**:22```bash23pip install lightning24```25 26**Convert PyTorch to Lightning** (3 steps):27 28```python29import lightning as L30import torch31from torch import nn32from torch.utils.data import DataLoader, Dataset33 34# Step 1: Define LightningModule (organize your PyTorch code)35class LitModel(L.LightningModule):36 def __init__(self, hidden_size=128):37 super().__init__()38 self.model = nn.Sequential(39 nn.Linear(28 * 28, hidden_size),40 nn.ReLU(),41 nn.Linear(hidden_size, 10)42 )43 44 def training_step(self, batch, batch_idx):45 x, y = batch46 y_hat = self.model(x)47 loss = nn.functional.cross_entropy(y_hat, y)48 self.log('train_loss', loss) # Auto-logged to TensorBoard49 return loss50 51 def configure_optimizers(self):52 return torch.optim.Adam(self.parameters(), lr=1e-3)53 54# Step 2: Create data55train_loader = DataLoader(train_dataset, batch_size=32)56 57# Step 3: Train with Trainer (handles everything else!)58trainer = L.Trainer(max_epochs=10, accelerator='gpu', devices=2)59model = LitModel()60trainer.fit(model, train_loader)61```62 63**That's it!** Trainer handles:64- GPU/TPU/CPU switching65- Distributed training (DDP, FSDP, DeepSpeed)66- Mixed precision (FP16, BF16)67- Gradient accumulation68- Checkpointing69- Logging70- Progress bars71 72## Common workflows73 74### Workflow 1: From PyTorch to Lightning75 76**Original PyTorch code**:77```python78model = MyModel()79optimizer = torch.optim.Adam(model.parameters())80model.to('cuda')81 82for epoch in range(max_epochs):83 for batch in train_loader:84 batch = batch.to('cuda')85 optimizer.zero_grad()86 loss = model(batch)87 loss.backward()88 optimizer.step()89```90 91**Lightning version**:92```python93class LitModel(L.LightningModule):94 def __init__(self):95 super().__init__()96 self.model = MyModel()97 98 def training_step(self, batch, batch_idx):99 loss = self.model(batch) # No .to('cuda') needed!100 return loss101 102 def configure_optimizers(self):103 return torch.optim.Adam(self.parameters())104 105# Train106trainer = L.Trainer(max_epochs=10, accelerator='gpu')107trainer.fit(LitModel(), train_loader)108```109 110**Benefits**: 40+ lines → 15 lines, no device management, automatic distributed111 112### Workflow 2: Validation and testing113 114```python115class LitModel(L.LightningModule):116 def __init__(self):117 super().__init__()118 self.model = MyModel()119 120 def training_step(self, batch, batch_idx):121 x, y = batch122 y_hat = self.model(x)123 loss = nn.functional.cross_entropy(y_hat, y)124 self.log('train_loss', loss)125 return loss126 127 def validation_step(self, batch, batch_idx):128 x, y = batch129 y_hat = self.model(x)130 val_loss = nn.functional.cross_entropy(y_hat, y)131 acc = (y_hat.argmax(dim=1) == y).float().mean()132 self.log('val_loss', val_loss)133 self.log('val_acc', acc)134 135 def test_step(self, batch, batch_idx):136 x, y = batch137 y_hat = self.model(x)138 test_loss = nn.functional.cross_entropy(y_hat, y)139 self.log('test_loss', test_loss)140 141 def configure_optimizers(self):142 return torch.optim.Adam(self.parameters(), lr=1e-3)143 144# Train with validation145trainer = L.Trainer(max_epochs=10)146trainer.fit(model, train_loader, val_loader)147 148# Test149trainer.test(model, test_loader)150```151 152**Automatic features**:153- Validation runs every epoch by default154- Metrics logged to TensorBoard155- Best model checkpointing based on val_loss156 157### Workflow 3: Distributed training (DDP)158 159```python160# Same code as single GPU!161model = LitModel()162 163# 8 GPUs with DDP (automatic!)164trainer = L.Trainer(165 accelerator='gpu',166 devices=8,167 strategy='ddp' # Or 'fsdp', 'deepspeed'168)169 170trainer.fit(model, train_loader)171```172 173**Launch**:174```bash175# Single command, Lightning handles the rest176python train.py177```178 179**No changes needed**:180- Automatic data distribution181- Gradient synchronization182- Multi-node support (just set `num_nodes=2`)183 184### Workflow 4: Callbacks for monitoring185 186```python187from lightning.pytorch.callbacks import ModelCheckpoint, EarlyStopping, LearningRateMonitor188 189# Create callbacks190checkpoint = ModelCheckpoint(191 monitor='val_loss',192 mode='min',193 save_top_k=3,194 filename='model-{epoch:02d}-{val_loss:.2f}'195)196 197early_stop = EarlyStopping(198 monitor='val_loss',199 patience=5,200 mode='min'201)202 203lr_monitor = LearningRateMonitor(logging_interval='epoch')204 205# Add to Trainer206trainer = L.Trainer(207 max_epochs=100,208 callbacks=[checkpoint, early_stop, lr_monitor]209)210 211trainer.fit(model, train_loader, val_loader)212```213 214**Result**:215- Auto-saves best 3 models216- Stops early if no improvement for 5 epochs217- Logs learning rate to TensorBoard218 219### Workflow 5: Learning rate scheduling220 221```python222class LitModel(L.LightningModule):223 # ... (training_step, etc.)224 225 def configure_optimizers(self):226 optimizer = torch.optim.Adam(self.parameters(), lr=1e-3)227 228 # Cosine annealing229 scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(230 optimizer,231 T_max=100,232 eta_min=1e-5233 )234 235 return {236 'optimizer': optimizer,237 'lr_scheduler': {238 'scheduler': scheduler,239 'interval': 'epoch', # Update per epoch240 'frequency': 1241 }242 }243 244# Learning rate auto-logged!245trainer = L.Trainer(max_epochs=100)246trainer.fit(model, train_loader)247```248 249## When to use vs alternatives250 251**Use PyTorch Lightning when**:252- Want clean, organized code253- Need production-ready training loops254- Switching between single GPU, multi-GPU, TPU255- Want built-in callbacks and logging256- Team collaboration (standardized structure)257 258**Key advantages**:259- **Organized**: Separates research code from engineering260- **Automatic**: DDP, FSDP, DeepSpeed with 1 line261- **Callbacks**: Modular training extensions262- **Reproducible**: Less boilerplate = fewer bugs263- **Tested**: 1M+ downloads/month, battle-tested264 265**Use alternatives instead**:266- **Accelerate**: Minimal changes to existing code, more flexibility267- **Ray Train**: Multi-node orchestration, hyperparameter tuning268- **Raw PyTorch**: Maximum control, learning purposes269- **Keras**: TensorFlow ecosystem270 271## Common issues272 273**Issue: Loss not decreasing**274 275Check data and model setup:276```python277# Add to training_step278def training_step(self, batch, batch_idx):279 if batch_idx == 0:280 print(f"Batch shape: {batch[0].shape}")281 print(f"Labels: {batch[1]}")282 loss = ...283 return loss284```285 286**Issue: Out of memory**287 288Reduce batch size or use gradient accumulation:289```python290trainer = L.Trainer(291 accumulate_grad_batches=4, # Effective batch = batch_size × 4292 precision='bf16' # Or 'fp16', reduces memory 50%293)294```295 296**Issue: Validation not running**297 298Ensure you pass val_loader:299```python300# WRONG301trainer.fit(model, train_loader)302 303# CORRECT304trainer.fit(model, train_loader, val_loader)305```306 307**Issue: DDP spawns multiple processes unexpectedly**308 309Lightning auto-detects GPUs. Explicitly set devices:310```python311# Test on CPU first312trainer = L.Trainer(accelerator='cpu', devices=1)313 314# Then GPU315trainer = L.Trainer(accelerator='gpu', devices=1)316```317 318## Advanced topics319 320**Callbacks**: See [references/callbacks.md](references/callbacks.md) for EarlyStopping, ModelCheckpoint, custom callbacks, and callback hooks.321 322**Distributed strategies**: See [references/distributed.md](references/distributed.md) for DDP, FSDP, DeepSpeed ZeRO integration, multi-node setup.323 324**Hyperparameter tuning**: See [references/hyperparameter-tuning.md](references/hyperparameter-tuning.md) for integration with Optuna, Ray Tune, and WandB sweeps.325 326## Hardware requirements327 328- **CPU**: Works (good for debugging)329- **Single GPU**: Works330- **Multi-GPU**: DDP (default), FSDP, or DeepSpeed331- **Multi-node**: DDP, FSDP, DeepSpeed332- **TPU**: Supported (8 cores)333- **Apple MPS**: Supported334 335**Precision options**:336- FP32 (default)337- FP16 (V100, older GPUs)338- BF16 (A100/H100, recommended)339- FP8 (H100)340 341## Resources342 343- Docs: https://lightning.ai/docs/pytorch/stable/344- GitHub: https://github.com/Lightning-AI/pytorch-lightning ⭐ 29,000+345- Version: 2.5.5+346- Examples: https://github.com/Lightning-AI/pytorch-lightning/tree/master/examples347- Discord: https://discord.gg/lightning-ai348- Used by: Kaggle winners, research labs, production teams349 350 351 Discovery context
Discovered by repository scan. No exact path reference found in the snapshot’s root AGENTS.md.