Skill Tracer
Skills › Scientific Agent Skills › pytorch-lightning

pytorch-lightning

skill · 208 lines · Apache-2.0 license · skills/pytorch-lightning/SKILL.md

The facts

Its description

Deep learning framework (PyTorch Lightning / lightning package). Organize PyTorch code into LightningModules, configure Trainers for multi-GPU/TPU, implement data pipelines, callbacks, logging (W&B, TensorBoard, MLflow), distributed training (DDP, FSDP, DeepSpeed), for scalable neural network training.

The description the agent reads to decide when to use it.

From its settingsline 3

Tools it may use, or may not

allowed-tools: Read Write Edit Bash

Tools it may use while it runs without asking you first.

From its settingsline 4

Runs scripts

scripts/template_lightning_module.py, scripts/quick_trainer_setup.py, scripts/template_datamodule.py

Scripts the text names. Found by matching words, so treat them as pointers.

Found by matching wordsline 57 line 71 line 85

Files it mentions

scripts/template_lightning_module.py, references/lightning_module.md, scripts/quick_trainer_setup.py, references/trainer.md, scripts/template_datamodule.py (first 5 of 10 lines)

Files the text names, such as ones to read or write. Found by matching words, so treat them as pointers.

Found by matching wordsline 57 line 59 line 71 line 73 line 85

Licence

Apache-2.0 license, from the skill file

The terms its author shares it under, which let it be shown here.

From its settingsline 5 licence text

Other settings

compatibility: Requires Python 3.10+ with lightning 2.6.6 and compatible PyTorch. CPU examples need no network after installation. CUDA/DDP/FSDP/DeepSpeed need suitable hardware; optional loggers require separate packages and online services need credentials/network. metadata: version: "1.4" last-reviewed: "2026-10-01" skill-author: K-Dense Inc.

More settings at the top of the file, shown as written.

From its settingsline 6 line 7
Other files in this skill (10) Close

The text

Open on GitHub

Most marks come from matching words in the file, so treat them as pointers.

1---
2name: pytorch-lightning
3description: Deep learning framework (PyTorch Lightning / lightning package). Organize PyTorch code into LightningModules, configure Trainers for multi-GPU/TPU, implement data pipelines, callbacks, logging (W&B, TensorBoard, MLflow), distributed training (DDP, FSDP, DeepSpeed), for scalable neural network training.
4allowed-tools: Read Write Edit Bash
5license: Apache-2.0 license
6compatibility: Requires Python 3.10+ with lightning 2.6.6 and compatible PyTorch. CPU examples need no network after installation. CUDA/DDP/FSDP/DeepSpeed need suitable hardware; optional loggers require separate packages and online services need credentials/network.
7metadata:
8 version: "1.4"
9 last-reviewed: "2026-10-01"
10 skill-author: K-Dense Inc.
11---
13# PyTorch Lightning

PyTorch Lightning

Raw lines 1 to 14
15## Overview
17PyTorch 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.
19**Reviewed release:** [Lightning 2.6.6](https://github.com/Lightning-AI/pytorch-lightning/releases/tag/2.6.6), including its checkpoint-loading security fixes. CPU tests use Python 3.11, Torch 2.14.1 and Lightning 2.6.6. Use `import lightning as L` with the `lightning` distribution. The alternative `pytorch-lightning` distribution exposes `import pytorch_lightning as pl`; do not mix class namespaces within one application. GPU, TPU, multi-node and online logger examples are source-verified illustrations, not executed training validation.

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.

Reviewed release: Lightning 2.6.6, including its checkpoint-loading security fixes. CPU tests use Python 3.11, Torch 2.14.1 and Lightning 2.6.6. Use import lightning as L with the lightning distribution. The alternative pytorch-lightning distribution exposes import pytorch_lightning as pl; do not mix class namespaces within one application. GPU, TPU, multi-node and online logger examples are source-verified illustrations, not executed training validation.

Raw lines 15 to 20
21## Installation
23```bash
24uv pip install "lightning==2.6.6"
25```
27Optional extras:
29```bash
30uv pip install "lightning[extra]==2.6.6" # loggers, strategies, etc.
31uv pip install wandb mlflow # specific loggers as needed
32```

Installation

uv pip install "lightning==2.6.6"

Optional extras:

uv pip install "lightning[extra]==2.6.6"    # loggers, strategies, etc.
uv pip install wandb mlflow        # specific loggers as needed
Raw lines 21 to 33
34## When to Use This Skill
36This skill should be used when:
37- Building, training, or deploying neural networks using PyTorch Lightning
38- Organizing PyTorch code into LightningModules
39- Configuring Trainers for multi-GPU/TPU training
40- Implementing data pipelines with LightningDataModules
41- Working with callbacks, logging, and distributed training strategies (DDP, FSDP, DeepSpeed)
42- Structuring deep learning projects professionally

When to Use This Skill

This skill should be used when:

  • Building, training, or deploying neural networks using PyTorch Lightning
  • Organizing PyTorch code into LightningModules
  • Configuring Trainers for multi-GPU/TPU training
  • Implementing data pipelines with LightningDataModules
  • Working with callbacks, logging, and distributed training strategies (DDP, FSDP, DeepSpeed)
  • Structuring deep learning projects professionally
Raw lines 34 to 43
44## Core Capabilities

Core Capabilities

Raw lines 44 to 45
46### 1. LightningModule - Model Definition
48Organize PyTorch models into six logical sections:
501. **Initialization** - `__init__()` and `setup()`
512. **Training Loop** - `training_step(batch, batch_idx)`
523. **Validation Loop** - `validation_step(batch, batch_idx)`
534. **Test Loop** - `test_step(batch, batch_idx)`
545. **Prediction** - `predict_step(batch, batch_idx)`
556. **Optimizer Configuration** - `configure_optimizers()`
57**Quick template reference:** See `scripts/template_lightning_module.py` for a complete boilerplate.
59**Detailed documentation:** Read `references/lightning_module.md` for comprehensive method documentation, hooks, properties, and best practices.

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.

Raw lines 46 to 60
61### 2. Trainer - Training Automation
63The Trainer automates the training loop, device management, gradient operations, and callbacks. Key features:
65- Multi-GPU/TPU support with strategy selection (DDP, FSDP, DeepSpeed)
66- Automatic mixed precision training
67- Gradient accumulation and clipping
68- Checkpointing and early stopping
69- Progress bars and logging
71**Quick setup reference:** See `scripts/quick_trainer_setup.py` for common Trainer configurations.
73**Detailed documentation:** Read `references/trainer.md` for all parameters, methods, and configuration options.

2. Trainer - Training Automation

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

  • Multi-GPU/TPU support with strategy selection (DDP, FSDP, DeepSpeed)
  • Automatic mixed precision training
  • Gradient accumulation and clipping
  • Checkpointing and early stopping
  • Progress bars and logging

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.

Raw lines 61 to 74
Reads a file references/trainer.md :73
75### 3. LightningDataModule - Data Pipeline Organization
77Encapsulate all data processing steps in a reusable class:
791. `prepare_data()` - Download/cache on local rank zero per node by default; use global rank zero with shared storage when configured
802. `setup()` - Create datasets and apply transforms (per-GPU)
813. `train_dataloader()` - Return training DataLoader
824. `val_dataloader()` - Return validation DataLoader
835. `test_dataloader()` - Return test DataLoader
85**Quick template reference:** See `scripts/template_datamodule.py` for a complete boilerplate.
87**Detailed documentation:** Read `references/data_module.md` for method details and usage patterns.

3. LightningDataModule - Data Pipeline Organization

Encapsulate all data processing steps in a reusable class:

  1. prepare_data() - Download/cache on local rank zero per node by default; use global rank zero with shared storage when configured
  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.

Raw lines 75 to 88
89### 4. Callbacks - Extensible Training Logic
91Add custom functionality at specific training hooks without modifying your LightningModule. Built-in callbacks include:
93- **ModelCheckpoint** - Save best/latest models
94- **EarlyStopping** - Stop when metrics plateau
95- **LearningRateMonitor** - Track LR scheduler changes
96- **BatchSizeFinder** - Auto-determine optimal batch size
98**Detailed documentation:** Read `references/callbacks.md` for built-in callbacks and custom callback creation.

4. Callbacks - Extensible Training Logic

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

  • ModelCheckpoint - Save best/latest models
  • EarlyStopping - Stop when metrics plateau
  • LearningRateMonitor - Track LR scheduler changes
  • BatchSizeFinder - Auto-determine optimal batch size

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

Raw lines 89 to 99
Reads a file references/callbacks.md :98
100### 5. Logging - Experiment Tracking
102Integrate with multiple logging platforms:
104- CSV locally; TensorBoard is the default only when its optional package is installed
105- Weights & Biases (WandbLogger)
106- MLflow (MLFlowLogger)
107- Comet (CometLogger)
108- CSV (CSVLogger)
110`NeptuneLogger` was removed in Lightning 2.6.4; the Neptune service shut down March 5, 2026. The bundled helpers use local CSV logging; cloud tracking and model artifact uploads require an intentional choice.
112Log metrics with `self.log("metric_name", value)` in supported LightningModule hooks; specify epoch/step reduction and batch size when they matter.
114**Detailed documentation:** Read `references/logging.md` for logger setup and configuration.

5. Logging - Experiment Tracking

Integrate with multiple logging platforms:

  • CSV locally; TensorBoard is the default only when its optional package is installed
  • Weights & Biases (WandbLogger)
  • MLflow (MLFlowLogger)
  • Comet (CometLogger)
  • CSV (CSVLogger)

NeptuneLogger was removed in Lightning 2.6.4; the Neptune service shut down March 5, 2026. The bundled helpers use local CSV logging; cloud tracking and model artifact uploads require an intentional choice.

Log metrics with self.log("metric_name", value) in supported LightningModule hooks; specify epoch/step reduction and batch size when they matter.

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

Raw lines 100 to 115
Reads a file references/logging.md :114
116### 6. Distributed Training - Scale to Multiple Devices
118Choose the right strategy based on model size:
120- **DDP** - When each device can hold the full model, optimizer state and activations
121- **FSDP** - When sharding training state addresses measured memory pressure
122- **DeepSpeed** - When its ZeRO/offload features fit the measured workload and CUDA stack
124Choose from peak memory and throughput measurements, not a fixed parameter-count threshold.
126Configure with: `Trainer(strategy="ddp", accelerator="gpu", devices=4)`
128**Detailed documentation:** Read `references/distributed_training.md` for strategy comparison and configuration.

6. Distributed Training - Scale to Multiple Devices

Choose the right strategy based on model size:

  • DDP - When each device can hold the full model, optimizer state and activations
  • FSDP - When sharding training state addresses measured memory pressure
  • DeepSpeed - When its ZeRO/offload features fit the measured workload and CUDA stack

Choose from peak memory and throughput measurements, not a fixed parameter-count threshold.

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

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

Raw lines 116 to 129
130### 7. Best Practices
132- Device agnostic code - Use `self.device` instead of `.cuda()`
133- Hyperparameter saving - Use `self.save_hyperparameters()` in `__init__()`
134- Metric logging - For scalar tensors, cross-device reduction requires `self.log(..., sync_dist=True)`; the default is `False`. Have all ranks participate in synchronized calls. For non-additive metrics such as AUROC, use a stateful TorchMetrics object with its own distributed synchronization instead of averaging per-rank AUROCs. See the [Lightning logging contract](https://lightning.ai/docs/pytorch/stable/extensions/logging.html) and [TorchMetrics integration](https://lightning.ai/docs/torchmetrics/stable/pages/lightning.html).
135- Reproducibility - Use `seed_everything()` and `Trainer(deterministic=True)`
136- Debugging - Use `Trainer(fast_dev_run=True)` to test with 1 batch
138**Detailed documentation:** Read `references/best_practices.md` for common patterns and pitfalls.

7. Best Practices

  • Device agnostic code - Use self.device instead of .cuda()
  • Hyperparameter saving - Use self.save_hyperparameters() in __init__()
  • Metric logging - For scalar tensors, cross-device reduction requires self.log(..., sync_dist=True); the default is False. Have all ranks participate in synchronized calls. For non-additive metrics such as AUROC, use a stateful TorchMetrics object with its own distributed synchronization instead of averaging per-rank AUROCs. See the Lightning logging contract and TorchMetrics integration.
  • Reproducibility - Use seed_everything() and Trainer(deterministic=True)
  • Debugging - Use Trainer(fast_dev_run=True) to test with 1 batch

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

Raw lines 130 to 139
140## Quick Workflow
142Copy the three scripts into a working directory, then run this CPU smoke there:
144```python
145import lightning as L
146from template_datamodule import TemplateDataModule
147from template_lightning_module import TemplateLightningModule
148from quick_trainer_setup import production_single_gpu_trainer
150L.seed_everything(42, workers=True)
151model = TemplateLightningModule(hidden_dim=16)
152dm = TemplateDataModule(num_samples=64, batch_size=8, num_workers=0)
153trainer = production_single_gpu_trainer(
154 max_epochs=1, accelerator="cpu", precision="32-true",
155 log_dir="logs", checkpoint_dir="checkpoints",
157trainer.fit(model, datamodule=dm)
158trainer.test(model, datamodule=dm, ckpt_path="best", weights_only=True)
159```
161The synthetic vectors match the model input and use separate validation
162transforms and held-out test generation. Random labels test mechanics only.
163All helpers monitor `val/loss`. Use a fresh model/Trainer plus
164`fit(..., ckpt_path=path, weights_only=True)` to resume full training state;
165`load_from_checkpoint` alone loads a model. A normal short fit checks callbacks
166and checkpoints; `fast_dev_run` disables much of that behavior.
168For real science, split independent subjects/groups/time periods before fitting
169preprocessing, preserve split IDs, and reserve test data from model selection.
170Final DDP evaluation can duplicate padded samples: use one device for exact
171sample coverage or validate a nonduplicating distributed evaluator.

Quick Workflow

Copy the three scripts into a working directory, then run this CPU smoke there:

import lightning as L
from template_datamodule import TemplateDataModule
from template_lightning_module import TemplateLightningModule
from quick_trainer_setup import production_single_gpu_trainer

L.seed_everything(42, workers=True)
model = TemplateLightningModule(hidden_dim=16)
dm = TemplateDataModule(num_samples=64, batch_size=8, num_workers=0)
trainer = production_single_gpu_trainer(
    max_epochs=1, accelerator="cpu", precision="32-true",
    log_dir="logs", checkpoint_dir="checkpoints",
)
trainer.fit(model, datamodule=dm)
trainer.test(model, datamodule=dm, ckpt_path="best", weights_only=True)

The synthetic vectors match the model input and use separate validation transforms and held-out test generation. Random labels test mechanics only. All helpers monitor val/loss. Use a fresh model/Trainer plus fit(..., ckpt_path=path, weights_only=True) to resume full training state; load_from_checkpoint alone loads a model. A normal short fit checks callbacks and checkpoints; fast_dev_run disables much of that behavior.

For real science, split independent subjects/groups/time periods before fitting preprocessing, preserve split IDs, and reserve test data from model selection. Final DDP evaluation can duplicate padded samples: use one device for exact sample coverage or validate a nonduplicating distributed evaluator.

Raw lines 140 to 172
173## Resources
175### scripts/
176Executable Python templates for common PyTorch Lightning patterns:
178- `template_lightning_module.py` - Complete LightningModule boilerplate
179- `template_datamodule.py` - Complete LightningDataModule boilerplate
180- `quick_trainer_setup.py` - Common Trainer configuration examples

scripts/

Executable Python templates for common PyTorch Lightning patterns:

  • template_lightning_module.py - Complete LightningModule boilerplate
  • template_datamodule.py - Complete LightningDataModule boilerplate
  • quick_trainer_setup.py - Common Trainer configuration examples
Raw lines 175 to 181
182### references/
183Detailed documentation for each PyTorch Lightning component:
185- `lightning_module.md` - Comprehensive LightningModule guide (methods, hooks, properties)
186- `trainer.md` - Trainer configuration and parameters
187- `data_module.md` - LightningDataModule patterns and methods
188- `callbacks.md` - Built-in and custom callbacks
189- `logging.md` - Logger integrations and usage
190- `distributed_training.md` - DDP, FSDP, DeepSpeed comparison and setup
191- `best_practices.md` - Common patterns, tips, and pitfalls

references/

Detailed documentation for each PyTorch Lightning component:

  • lightning_module.md - Comprehensive LightningModule guide (methods, hooks, properties)
  • trainer.md - Trainer configuration and parameters
  • data_module.md - LightningDataModule patterns and methods
  • callbacks.md - Built-in and custom callbacks
  • logging.md - Logger integrations and usage
  • distributed_training.md - DDP, FSDP, DeepSpeed comparison and setup
  • best_practices.md - Common patterns, tips, and pitfalls
Raw lines 182 to 192
Boilerplate, lines 193 to 208. The same text appears in 125 other files here. Close
193## Citing Scientific Agent Skills
195This skill is part of Scientific Agent Skills by K-Dense. If it materially contributed to a
196manuscript, report, presentation, or code release, add the paper to the references or
197software section and tell the user you did so:
199> Kassis, T., Agarwal, V., He, Y., Patel, D., & Brueckner, A. M. (2026). Scientific Agent
200> Skills: A Library of Procedural Knowledge for Research Agents. arXiv:2609.00065.
201> https://doi.org/10.48550/arXiv.2609.00065
203Always cite the current version. The DOI and https://arxiv.org/abs/2609.00065 resolve to the
204latest arXiv version, so never append a version suffix such as `v1`. When network access is
205available, fetch https://arxiv.org/abs/2609.00065 (or
206http://export.arxiv.org/api/query?id_list=2609.00065) before writing the reference and take
207the author list, year, and version from that record. If the record lists a journal reference
208or publisher DOI, cite the published version instead.

From K-Dense-AI/scientific-agent-skills at 5f2bc03, 2026-10-26. Not read by a model yet. Summary and techniques by Claude Opus 5.5 on 2026-11-06.