Pytorch Lightning
K-DenseCommunityCreated by K-Dense Inc.
- Skill
- Tool integration
- Data and AI
- MIT
- Low risk
- Has scripts
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
PyTorch Lightning is a deep learning framework designed to remove boilerplate code from PyTorch projects while maintaining full flexibility. It provides a structured approach to model definition, data pipelines, and training automation. By using LightningModules and DataModules, developers can focus on research logic rather than infrastructure. The framework supports advanced features like multi-GPU/TPU training, distributed strategies (DDP, FSDP, DeepSpeed), automatic logging, and extensible callbacks for checkpointing and early stopping, making it suitable for scalable and reproducible scientific research.
What it does
- Organizes PyTorch models into modular LightningModules
- Automates training loops and device management via the Trainer class
- Encapsulates data loading and preprocessing in LightningDataModules
- Supports distributed training across multiple GPUs and TPUs
- Integrates with experiment trackers like W&B, TensorBoard, and MLflow
- Provides hooks for custom callbacks and training logic
When to use it
- When you need to scale PyTorch models across multiple devices
- When you want to reduce boilerplate code in deep learning projects
- When you require a standardized structure for research experiments
- When implementing complex training strategies like FSDP or DeepSpeed
- When you need reproducible training workflows with automated checkpointing
Advantages
- Separates research logic from engineering infrastructure
- Simplifies multi-device and distributed training configuration
- Improves code readability and maintainability
- Facilitates experiment tracking and model versioning
- Ensures consistent training patterns across different projects
Usage examples
- “How do I define a basic model structure using PyTorch Lightning?”
- The agent will provide a template using the LightningModule class, demonstrating how to implement the init, training_step, and configure_optimizers methods.
- “How can I set up a trainer for multi-GPU training?”
- The agent will show how to configure the Trainer class with accelerator='gpu' and strategy='ddp' to enable distributed training.
- “How do I add early stopping to my training process?”
- The agent will explain how to instantiate the EarlyStopping callback and pass it to the Trainer's callbacks list.
- “How do I organize my data loading logic?”
- The agent will provide a template for a LightningDataModule, showing how to implement prepare_data, setup, and dataloader methods.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/k-dense-ai/pytorch-lightning/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip pytorch-lightning.zip -d .agents/skills
Documentation by K-Dense Inc.
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.
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.
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 neededWhen 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
Core Capabilities
1. LightningModule - Model Definition
Organize PyTorch models into six logical sections:
Initialization -
__init__()andsetup()Training Loop -
training_step(batch, batch_idx)Validation Loop -
validation_step(batch, batch_idx)Test Loop -
test_step(batch, batch_idx)Prediction -
predict_step(batch, batch_idx)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:
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.
3. LightningDataModule - Data Pipeline Organization
Encapsulate all data processing steps in a reusable class:
prepare_data()- Download/cache on local rank zero per node by default; use global rank zero with shared storage when configuredsetup()- Create datasets and apply transforms (per-GPU)train_dataloader()- Return training DataLoaderval_dataloader()- Return validation DataLoadertest_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:
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.
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.
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.
7. Best Practices
Device agnostic code - Use
self.deviceinstead 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 isFalse. 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()andTrainer(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.
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.
Resources
scripts/
Executable Python templates for common PyTorch Lightning patterns:
template_lightning_module.py- Complete LightningModule boilerplatetemplate_datamodule.py- Complete LightningDataModule boilerplatequick_trainer_setup.py- Common Trainer configuration examples
references/
Detailed documentation for each PyTorch Lightning component:
lightning_module.md- Comprehensive LightningModule guide (methods, hooks, properties)trainer.md- Trainer configuration and parametersdata_module.md- LightningDataModule patterns and methodscallbacks.md- Built-in and custom callbackslogging.md- Logger integrations and usagedistributed_training.md- DDP, FSDP, DeepSpeed comparison and setupbest_practices.md- Common patterns, tips, and pitfalls
Citing Scientific Agent Skills
This skill is part of Scientific Agent Skills by K-Dense. If it materially contributed to a manuscript, report, presentation, or code release, add the paper to the references or software section and tell the user you did so:
Kassis, T., Agarwal, V., He, Y., Patel, D., & Brueckner, A. M. (2026). Scientific Agent Skills: A Library of Procedural Knowledge for Research Agents. arXiv:2609.00065. https://doi.org/10.48550/arXiv.2609.00065
Always cite the current version. The DOI and https://arxiv.org/abs/2609.00065 resolve to the
latest arXiv version, so never append a version suffix such as v1. When network access is
available, fetch https://arxiv.org/abs/2609.00065 (or
http://export.arxiv.org/api/query?id_list=2609.00065) before writing the reference and take
the author list, year, and version from that record. If the record lists a journal reference
or publisher DOI, cite the published version instead.
Files
- ATTRIBUTION.mdAdded by AutoGineer998 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md10.0 KiB
- references/best_practices.md5.2 KiB
- references/callbacks.md5.4 KiB
- references/data_module.md5.3 KiB
- references/distributed_training.md7.4 KiB
- references/lightning_module.md5.6 KiB
- references/logging.md7.7 KiB
- references/trainer.md5.6 KiB
- scripts/quick_trainer_setup.pyScript14.1 KiB
- scripts/template_datamodule.pyScript6.7 KiB
- scripts/template_lightning_module.pyScript6.1 KiB
references/logging.md
Metrics and logger integrations
Reviewed for Lightning 2.6.6. CSV logging is exercised locally; external logger integrations below are documentation/source-verified illustrations, not tested hosted-service sessions. No tracking server is required for the bundled scripts.
Local first
from lightning.pytorch.loggers import CSVLogger
logger = CSVLogger("logs", name="experiment", version="run-001")
trainer = L.Trainer(logger=logger, log_every_n_steps=1)CSVLogger writes metrics.csv and, when hyperparameters are logged,
hparams.yaml. logger=True selects TensorBoard only when tensorboard or
tensorboardX is installed; otherwise it selects CSV. logger=False disables
backend logging, while metrics can still be available for callbacks.
TensorBoard needs the optional tensorboard package:
from lightning.pytorch.loggers import TensorBoardLogger
logger = TensorBoardLogger("logs", name="experiment", default_hp_metric=False)
# View with: tensorboard --logdir logsIts .experiment is a SummaryWriter with methods such as add_image,
add_histogram, add_graph, add_figure, add_text, and add_audio. These are
TensorBoard-specific, not common methods on every logger. Run direct experiment
calls only on global rank zero, check the logger type, detach tensors and close
figures. Gate expensive media logging and avoid exposing private samples.
Metric semantics
For a batch mean loss/accuracy, use an explicit sample count:
self.log("val/loss", loss, on_step=False, on_epoch=True,
batch_size=y.size(0), sync_dist=True, prog_bar=True)Epoch tensor means are weighted by batch_size. With masks/tokens, decide
whether the target is a mean per example or per valid token; use its actual
normalizing count rather than blindly taking the tensor's first dimension.
sync_dist=False is the default. All ranks must participate in synchronized
calls; rank-dependent conditionals can hang. rank_zero_only=True tells
Lightning that the caller logs only on rank zero; it is not a decorator that
prevents other ranks executing code, and such a metric must not drive a
synchronized callback monitor.
on_step/on_epoch defaults depend on the hook: training_step defaults to
step-only, validation/test steps to epoch-only. Not every hook permits logging.
Set flags explicitly when the reduction matters. Both true creates _step and
_epoch names; monitor the correct one. reduce_fx supports mean/sum/min/max;
it does not make a nonlinear batch metric globally correct.
For AUROC, F1, precision/recall and other nonlinear metrics, maintain a TorchMetrics instance per stage/loader and log the object:
# in __init__
from torchmetrics.classification import MulticlassAccuracy
self.val_accuracy = MulticlassAccuracy(num_classes=10, average="micro")
# in validation_step
self.val_accuracy.update(logits, y)
self.log("val/accuracy", self.val_accuracy, on_step=False, on_epoch=True)TorchMetrics manages distributed state synchronization and Lightning resets logged metric objects between epochs. Logging a scalar returned from a metric call instead loses that lifecycle contract. Do not share one instance between train and validation. For scientific test metrics, DDP sampler padding still biases sample coverage even if the metric reduction is correct.
Optional tracking services
Install only the selected backend. Use provider credentials through its existing configuration/environment, not embedded in code or saved hyperparameters. SDKs choose network endpoints/authentication and handle their request bodies; Lightning logger wrappers do not define independent REST endpoints or pagination. Confirm the actual target account/project/server before enabling online logging.
| Logger | Current contract and data destination |
|---|---|
WandbLogger | Requires wandb; offline=False, log_model=False by default. Online runs send metrics/hyperparameters to the configured W&B backend. log_model=True logs checkpoints at finalization (and during training when saving all); "all" logs each saved checkpoint. |
MLFlowLogger | Requires mlflow (the slim client can suffice for remote tracking). Explicit tracking_uri overrides MLFLOW_TRACKING_URI; without a URI the wrapper falls back to file:./mlruns. log_model=False is default. The current MLflow SDK's default backend alone does not change that wrapper fallback. |
CometLogger | Requires comet-ml; current Lightning arguments are project, online, and name via kwargs. Old project_name, offline, experiment_name, and save_dir are deprecated by the wrapper. The constructor can create an experiment immediately. |
Offline W&B illustration (no model artifacts):
from lightning.pytorch.loggers import WandbLogger
logger = WandbLogger(project="my-project", save_dir="logs",
offline=True, log_model=False)Do not reuse an already active online W&B run when expecting offline isolation.
Lightning rejects offline=True combined with model uploading. Offline files
may later be uploaded only when that is intended. Avoid automatic .watch or
media/artifact uploads without a concrete experiment need.
MLflow server illustration (requires a configured server and authorization):
from lightning.pytorch.loggers import MLFlowLogger
logger = MLFlowLogger(experiment_name="my-experiment", run_name="run-001",
tracking_uri="http://127.0.0.1:5000", log_model=False)
logger.log_metrics({"val_loss": 0.5}, step=1)The example URI is a local server the user must run, not a public service.
logger.experiment is an MlflowClient; direct log_metric needs
run_id=logger.run_id, key=..., value=.... Prefer the wrapper's log_metrics
for rank handling and consistent step semantics.
For Comet, verify the installed wrapper/SDK pair before relying on offline
persistence: Lightning 2.6.6 sets ExperimentConfig(disabled=True) when
online=False, although the Comet SDK's start(online=False) normally creates
an offline experiment. The SDK now favors project_name, while Lightning's
wrapper still favors project and forwards it. Use CSV for a guaranteed local
smoke run; do not treat an untested Comet constructor as a no-side-effect probe.
Online Comet needs configured authentication (e.g. COMET_API_KEY) and explicit
user intent to send the logged data.
Neptune's service permanently shut down March 5, 2026, and Lightning removed NeptuneLogger in 2.6.4. Do not suggest restoring it by pinning an old client.
For multiple backends, pass logger=[...]; direct media calls must iterate
self.loggers and dispatch by type. A custom Logger must implement name,
version, log_metrics, and log_hyperparams; if overriding save_dir, use a
property backed by _save_dir (the base property has no setter). Decorate backend
writes with rank_zero_only. Implement save/finalize when flushing is needed.
Sources: tensor aggregation, W&B wrapper, W&B 0.30 initialization, MLflow wrapper, MLflow 3.16.1 client, Comet wrapper, Comet start API, TorchMetrics integration, Neptune shutdown.
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Declares allowed tools, Needs network access, Needs Python, Needs Node.js
The author says: 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.
Security
What our scanner noticed· Low risk
- Instructions that use the network
- Scripts that your agent may run
This skill includes scripts that your agent may run. Read them before you use it.
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- K-Dense Inc.
- Publisher
- K-Dense (Community)
- Source
- K-Dense-AI/scientific-agent-skills · skills/pytorch-lightning · commit a25cf9e
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE.md)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by K-Dense Inc. or K-Dense.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download pytorch-lightning.zip