Alterlab pytorch lightning

From AlterLab-IEU/AlterLab-Academic-Skills · View interactive version

Alterlab pytorch lightning is an AI agent skill from the GitHub repository AlterLab-IEU/AlterLab-Academic-Skills. Scalable deep-learning training with PyTorch Lightning — organize PyTorch code into LightningModules, configure Trainers for multi-GPU/TPU, build data pipelines and callbacks, log to W&B or TensorBoard, and run distributed training (DDP, FSDP, DeepSpeed). Use when structuring PyTorch training loops,

How to use this skill

Skill file

PyTorch Lightning

Overview

PyTorch Lightning is a deep learning framework that organizes PyTorch code to eliminate boilerplate while maintaining full flexibility. Automate training workflows, multi-device orchestration, and implement best practices for neural network training and scaling across multiple GPUs/TPUs.

uv run --python ">=3.12" --with "lightning>=2.5" python train.py   # no install step; `import lightning as L` and `lightning.pytorch.*`
# torch already importable (`python -c "import torch, lightning"`)? run with plain `python`. CPU-only machine: add --index https://download.pytorch.org/whl/cpu (no CUDA wheels)

All code in this skill uses the unified lightning package. The separately published pytorch-lightning package installs the older pytorch_lightning namespace instead; do not mix the two namespaces in one project, because their classes are distinct (e.g. lightning.Trainer.fit rejects a pytorch_lightning.LightningModule with a TypeError).

When to Use This Skill

This skill should be used when:

Does NOT Trigger

| Scenario | Use Instead |

|----------|-------------|

| Fine-tuning a pretrained Hugging Face model with the transformers Trainer / pipelines | alterlab-transformers |

| Designing graph neural network layers or loading graph datasets (GCN, GAT, message passing) | alterlab-torch-geometric |

| Reinforcement-learning agents trained on environments (PPO, SAC, DQN) | alterlab-stable-baselines3 |

| Classical ML on tabular data (random forests, gradient boosting, linear models) | alterlab-scikit-learn |

Hand-off rule. When the request matches a row above, open your answer by naming that skill by its exact id (for example alterlab-transformers) and saying in one line why it fits better, then stop applying this skill's procedure. Name it even when you also need to ask for missing input. If only part of the request is out of scope, name the skill for that part and do only the in-scope part. A brief general pointer is fine; the named skill does the work.

Core Capabilities

1. LightningModule - Model Definition

Organize PyTorch models into six logical sections:

  1. Initialization - __init__() and setup()
  2. Training Loop - training_step(batch, batch_idx)
  3. Validation Loop - validation_step(batch, batch_idx)
  4. Test Loop - test_step(batch, batch_idx)
  5. Prediction - predict_step(batch, batch_idx)
  6. Optimizer Configuration - configure_optimizers()

Quick template reference: See scripts/template_lightning_module.py for a complete boilerplate.

Detailed documentation: Read references/lightning_module.md for comprehensive method documentation, hooks, properties, and best practices.

2. Trainer - Training Automation

The Trainer automates the training loop, device management, gradient operations, and callbacks. Key features:

Quick setup reference: See scripts/quick_trainer_setup.py for common Trainer configurations.

Detailed documentation: Read references/trainer.md for all parameters, methods, and configuration options.

3. LightningDataModule - Data Pipeline Organization

Encapsulate all data processing steps in a reusable class:

  1. prepare_data() - Download and process data (single-process)
  2. setup() - Create datasets and apply transforms (per-GPU)
  3. train_dataloader() - Return training DataLoader
  4. val_dataloader() - Return validation DataLoader
  5. test_dataloader() - Return test DataLoader

Quick template reference: See scripts/template_datamodule.py for a complete boilerplate.

Detailed documentation: Read references/data_module.md for method details and usage patterns.

4. Callbacks - Extensible Training Logic

Add custom functionality at specific training hooks without modifying your LightningModule. Built-in callbacks include:

Detailed documentation: Read references/callbacks.md for built-in callbacks and custom callback creation.

5. Logging - Experiment Tracking

Integrate with multiple logging platforms:

NeptuneLogger was removed in Lightning 2.6.4 after Neptune's hosted service shut down (March 2026).

Log metrics using self.log("metric_name", value) in any LightningModule method.

Detailed documentation: Read references/logging.md for logger setup and configuration.

6. Distributed Training - Scale to Multiple Devices

Choose the right strategy based on model size:

Configure with: Trainer(strategy="ddp", accelerator="gpu", devices=4)

Detailed documentation: Read references/distributed_training.md for strategy comparison and configuration.

7. Best Practices

Detailed documentation: Read references/best_practices.md for common patterns and pitfalls.

Quick Workflow

  1. Define model:

```python

class MyModel(L.LightningModule):

def init(self):

super().init()

self.save_hyperparameters()

self.model = YourNetwork()

def training_step(self, batch, batch_idx):

x, y = batch

loss = F.cross_entropy(self.model(x), y)

self.log("train_loss", loss)

return loss

def configure_optimizers(self):

return torch.optim.Adam(self.parameters())

```

  1. Prepare data:

```python

# Option 1: Direct DataLoaders

train_loader = DataLoader(train_dataset, batch_size=32)

# Option 2: LightningDataModule (recommended for reusability)

dm = MyDataModule(batch_size=32)

```

  1. Train:

```python

trainer = L.Trainer(max_epochs=10, accelerator="gpu", devices=2)

trainer.fit(model, train_loader) # or trainer.fit(model, datamodule=dm)

```

Resources

scripts/

Executable Python templates for common PyTorch Lightning patterns:

references/

Detailed documentation for each PyTorch Lightning component:

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.