Agent skill

PyTorch Lightning Training

by Orchestra-Research in Orchestra-Research/AI-Research-SKILLs

Shows how to organize PyTorch training with Lightning's LightningModule and Trainer, covering validation, DDP, callbacks and learning-rate scheduling.

MITAuto-check passedAI & LLM Engineering

Install PyTorch Lightning Training

skills CLI
$ npx skills add Orchestra-Research/AI-Research-SKILLs --skill pytorch-lightning -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install Orchestra-Research/AI-Research-SKILLs pytorch-lightning --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/Orchestra-Research/AI-Research-SKILLs.git skills-src && mkdir -p .claude/skills && cp -r skills-src/08-distributed-training/pytorch-lightning .claude/skills/pytorch-lightning && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
pytorch-lightning
GitHub stars
13k
Used in
6 other repos
Token cost
~2.3k tokens
SKILL.md length
365 words
Files
4 (incl. references)
Skills in repo
96
Repo updated
First seen
Licence
MIT

At a glance

Shows how to organize PyTorch training with Lightning's LightningModule and Trainer, covering validation, DDP, callbacks and learning-rate scheduling.

  • Refactoring a plain PyTorch training loop into a LightningModule and Trainer
  • SKILL.md covers Quick start, Common workflows, When to use vs alternatives and Common issues, plus 3 more sections
  • Calls pip and python
  • Scaling the same training code from one GPU to several GPUs or nodes

What it does

The skill introduces PyTorch Lightning, installed with pip install lightning, as a way to cut boilerplate from PyTorch training. It shows how to convert plain PyTorch into a LightningModule that a Trainer runs, with the Trainer taking over GPU, TPU or CPU switching, distributed training with DDP, FSDP or DeepSpeed, mixed precision, gradient accumulation, checkpointing, logging and progress bars.

Worked examples cover moving from PyTorch to Lightning, validation and testing with TensorBoard logging and best-checkpoint saving, distributed training that uses the same code as a single GPU (multi-node by setting the node count), monitoring callbacks such as ModelCheckpoint, EarlyStopping and LearningRateMonitor, and learning rate scheduling. A comparison section says when Lightning fits, for example when moving between single GPU, multi-GPU and TPU or when a team wants standard structure. Reference files cover callbacks, distributed training and hyperparameter tuning.

When your agent uses it

  • Refactoring a plain PyTorch training loop into a LightningModule and Trainer
  • Scaling the same training code from one GPU to several GPUs or nodes
  • Adding checkpointing, early stopping or learning-rate monitoring with callbacks
  • Setting up validation, testing and TensorBoard logging
  • Tuning hyperparameters for a Lightning model

Example prompts

  • “Convert this PyTorch training script into a LightningModule with a Trainer.”
  • “Run my Lightning model on four GPUs with DDP and no code changes.”
  • “Add early stopping and best-model checkpointing to my Lightning trainer.”
  • “Set up a cosine learning rate schedule in the LightningModule.”

Requirements

  • Python with the lightning package, installed with pip install lightning
  • GPUs, TPUs or a cluster for distributed runs

What it can do on your machine

Read from SKILL.md and the folder at commit 773a529. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Shell commands in SKILL.md call:

    • pip
    • python

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    Links to these hosts (documentation or services it may open):

    • github.com
    • lightning.ai
    • discord.gg

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

PyTorch Lightning Training loads about 2.3k tokens when it runs, and up to ~11k if it reads all its reference files. Until then it costs about 71 tokens; SKILL.md has 365 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~71
When it runs · the whole SKILL.md, loaded when a task matches
~2.3k
With references · SKILL.md plus every file in references/, read only if the agent opens them
~11k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from Orchestra-Research/AI-Research-SKILLs at commit 773a529, republished under its MIT licence (© Orchestra-Research). 365 words, ~2,279 tokens.

Download SKILL.mdSave it as .claude/skills/pytorch-lightning/SKILL.md (or your agent's skills folder). This skill also uses 3 other files; get the full folder from GitHub.
name
pytorch-lightning
description
High-level PyTorch framework with Trainer class, automatic distributed training (DDP/FSDP/DeepSpeed), callbacks system, and minimal boilerplate. Scales from laptop to supercomputer with same code. Use when you want clean training loops with built-in best practices.
version
1.0.0
author
Orchestra Research
license
MIT
tags
PyTorch Lightning, Training Framework, Distributed Training, DDP, FSDP, DeepSpeed, High-Level API, Callbacks, Best Practices, Scalable
dependencies
lightning, torch, transformers

PyTorch Lightning - High-Level Training Framework

Quick start

PyTorch Lightning organizes PyTorch code to eliminate boilerplate while maintaining flexibility.

Installation:

bash
pip install lightning

Convert PyTorch to Lightning (3 steps):

python
import lightning as L
import torch
from torch import nn
from torch.utils.data import DataLoader, Dataset

# Step 1: Define LightningModule (organize your PyTorch code)
class LitModel(L.LightningModule):
    def __init__(self, hidden_size=128):
        super().__init__()
        self.model = nn.Sequential(
            nn.Linear(28 * 28, hidden_size),
            nn.ReLU(),
            nn.Linear(hidden_size, 10)
        )

    def training_step(self, batch, batch_idx):
        x, y = batch
        y_hat = self.model(x)
        loss = nn.functional.cross_entropy(y_hat, y)
        self.log('train_loss', loss)  # Auto-logged to TensorBoard
        return loss

    def configure_optimizers(self):
        return torch.optim.Adam(self.parameters(), lr=1e-3)

# Step 2: Create data
train_loader = DataLoader(train_dataset, batch_size=32)

# Step 3: Train with Trainer (handles everything else!)
trainer = L.Trainer(max_epochs=10, accelerator='gpu', devices=2)
model = LitModel()
trainer.fit(model, train_loader)

That's it! Trainer handles:

  • GPU/TPU/CPU switching
  • Distributed training (DDP, FSDP, DeepSpeed)
  • Mixed precision (FP16, BF16)
  • Gradient accumulation
  • Checkpointing
  • Logging
  • Progress bars

Common workflows

Workflow 1: From PyTorch to Lightning

Original PyTorch code:

python
model = MyModel()
optimizer = torch.optim.Adam(model.parameters())
model.to('cuda')

for epoch in range(max_epochs):
    for batch in train_loader:
        batch = batch.to('cuda')
        optimizer.zero_grad()
        loss = model(batch)
        loss.backward()
        optimizer.step()

Lightning version:

python
class LitModel(L.LightningModule):
    def __init__(self):
        super().__init__()
        self.model = MyModel()

    def training_step(self, batch, batch_idx):
        loss = self.model(batch)  # No .to('cuda') needed!
        return loss

    def configure_optimizers(self):
        return torch.optim.Adam(self.parameters())

# Train
trainer = L.Trainer(max_epochs=10, accelerator='gpu')
trainer.fit(LitModel(), train_loader)

Benefits: 40+ lines → 15 lines, no device management, automatic distributed

Workflow 2: Validation and testing
python
class LitModel(L.LightningModule):
    def __init__(self):
        super().__init__()
        self.model = MyModel()

    def training_step(self, batch, batch_idx):
        x, y = batch
        y_hat = self.model(x)
        loss = nn.functional.cross_entropy(y_hat, y)
        self.log('train_loss', loss)
        return loss

    def validation_step(self, batch, batch_idx):
        x, y = batch
        y_hat = self.model(x)
        val_loss = nn.functional.cross_entropy(y_hat, y)
        acc = (y_hat.argmax(dim=1) == y).float().mean()
        self.log('val_loss', val_loss)
        self.log('val_acc', acc)

    def test_step(self, batch, batch_idx):
        x, y = batch
        y_hat = self.model(x)
        test_loss = nn.functional.cross_entropy(y_hat, y)
        self.log('test_loss', test_loss)

    def configure_optimizers(self):
        return torch.optim.Adam(self.parameters(), lr=1e-3)

# Train with validation
trainer = L.Trainer(max_epochs=10)
trainer.fit(model, train_loader, val_loader)

# Test
trainer.test(model, test_loader)

Automatic features:

  • Validation runs every epoch by default
  • Metrics logged to TensorBoard
  • Best model checkpointing based on val_loss
Workflow 3: Distributed training (DDP)
python
# Same code as single GPU!
model = LitModel()

# 8 GPUs with DDP (automatic!)
trainer = L.Trainer(
    accelerator='gpu',
    devices=8,
    strategy='ddp'  # Or 'fsdp', 'deepspeed'
)

trainer.fit(model, train_loader)

Launch:

bash
# Single command, Lightning handles the rest
python train.py

No changes needed:

  • Automatic data distribution
  • Gradient synchronization
  • Multi-node support (just set num_nodes=2)
Workflow 4: Callbacks for monitoring
python
from lightning.pytorch.callbacks import ModelCheckpoint, EarlyStopping, LearningRateMonitor

# Create callbacks
checkpoint = ModelCheckpoint(
    monitor='val_loss',
    mode='min',
    save_top_k=3,
    filename='model-{epoch:02d}-{val_loss:.2f}'
)

early_stop = EarlyStopping(
    monitor='val_loss',
    patience=5,
    mode='min'
)

lr_monitor = LearningRateMonitor(logging_interval='epoch')

# Add to Trainer
trainer = L.Trainer(
    max_epochs=100,
    callbacks=[checkpoint, early_stop, lr_monitor]
)

trainer.fit(model, train_loader, val_loader)

Result:

  • Auto-saves best 3 models
  • Stops early if no improvement for 5 epochs
  • Logs learning rate to TensorBoard
Workflow 5: Learning rate scheduling
python
class LitModel(L.LightningModule):
    # ... (training_step, etc.)

    def configure_optimizers(self):
        optimizer = torch.optim.Adam(self.parameters(), lr=1e-3)

        # Cosine annealing
        scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
            optimizer,
            T_max=100,
            eta_min=1e-5
        )

        return {
            'optimizer': optimizer,
            'lr_scheduler': {
                'scheduler': scheduler,
                'interval': 'epoch',  # Update per epoch
                'frequency': 1
            }
        }

# Learning rate auto-logged!
trainer = L.Trainer(max_epochs=100)
trainer.fit(model, train_loader)

When to use vs alternatives

Use PyTorch Lightning when:

  • Want clean, organized code
  • Need production-ready training loops
  • Switching between single GPU, multi-GPU, TPU
  • Want built-in callbacks and logging
  • Team collaboration (standardized structure)

Key advantages:

  • Organized: Separates research code from engineering
  • Automatic: DDP, FSDP, DeepSpeed with 1 line
  • Callbacks: Modular training extensions
  • Reproducible: Less boilerplate = fewer bugs
  • Tested: 1M+ downloads/month, battle-tested

Use alternatives instead:

  • Accelerate: Minimal changes to existing code, more flexibility
  • Ray Train: Multi-node orchestration, hyperparameter tuning
  • Raw PyTorch: Maximum control, learning purposes
  • Keras: TensorFlow ecosystem
Show full SKILL.md (140 more words)Show less

Common issues

Issue: Loss not decreasing

Check data and model setup:

python
# Add to training_step
def training_step(self, batch, batch_idx):
    if batch_idx == 0:
        print(f"Batch shape: {batch[0].shape}")
        print(f"Labels: {batch[1]}")
    loss = ...
    return loss

Issue: Out of memory

Reduce batch size or use gradient accumulation:

python
trainer = L.Trainer(
    accumulate_grad_batches=4,  # Effective batch = batch_size × 4
    precision='bf16'  # Or 'fp16', reduces memory 50%
)

Issue: Validation not running

Ensure you pass val_loader:

python
# WRONG
trainer.fit(model, train_loader)

# CORRECT
trainer.fit(model, train_loader, val_loader)

Issue: DDP spawns multiple processes unexpectedly

Lightning auto-detects GPUs. Explicitly set devices:

python
# Test on CPU first
trainer = L.Trainer(accelerator='cpu', devices=1)

# Then GPU
trainer = L.Trainer(accelerator='gpu', devices=1)

Advanced topics

Callbacks: See references/callbacks.md for EarlyStopping, ModelCheckpoint, custom callbacks, and callback hooks.

Distributed strategies: See references/distributed.md for DDP, FSDP, DeepSpeed ZeRO integration, multi-node setup.

Hyperparameter tuning: See references/hyperparameter-tuning.md for integration with Optuna, Ray Tune, and WandB sweeps.

Hardware requirements

  • CPU: Works (good for debugging)
  • Single GPU: Works
  • Multi-GPU: DDP (default), FSDP, or DeepSpeed
  • Multi-node: DDP, FSDP, DeepSpeed
  • TPU: Supported (8 cores)
  • Apple MPS: Supported

Precision options:

  • FP32 (default)
  • FP16 (V100, older GPUs)
  • BF16 (A100/H100, recommended)
  • FP8 (H100)

Resources

© Orchestra-Research, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 3 other files (references) in 08-distributed-training/pytorch-lightning of Orchestra-Research/AI-Research-SKILLs.

  • SKILL.md
  • references/callbacks.md
  • references/distributed.md
  • references/hyperparameter-tuning.md

Open the folder on GitHubat commit 773a529

Used in 6 other repositories

We found 6 copies of this SKILL.md (exact, near-identical or edited) in other folders, from 6 other GitHub owners. This page covers the copy in Orchestra-Research/AI-Research-SKILLs, which our catalogue first saw on October 7, 2026.

Compare with similar skills

PyTorch Lightning Training next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

PyTorch Lightning Training compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
PyTorch Lightning Training this skillOrchestra-Research/AI-Research-SKILLs13k6 repos~2.3kAutomated safety check: PassMIT
PyTorch Lightning Training Setupdavila7/claude-code-templates32k11 repos~1.7kAutomated safety check: PassMIT
GPU OptimizerMathews-Tom/armory328—~3.5kAutomated safety check: NotesMIT
Magpie Kernel Evaluatoramd/skills406—~2.3kAutomated safety check: PassMIT
Hyperpod Version Checkerawslabs/agent-plugins915—~910Automated safety check: PassApache-2.0
Deep Learningericrisco/rsc-harness174—~3.4kAutomated safety check: PassMIT

Similar skills

  • PyTorch Lightning Training Setup

    davila7/claude-code-templates

    Organizes PyTorch training code into LightningModules, DataModules and Trainers, with multi-GPU strategies, callbacks and logging configured.

    32k GitHub starsUsed in 11 repos~1.7k tokens
    AI & LLM EngineeringAuto-check passed
  • GPU Optimizer

    Mathews-Tom/armory

    GPU optimization for consumer NVIDIA GPUs (8-24GB VRAM) covering mixed precision, gradient checkpointing, XGBoost GPU, CuPy/cuDF migration, and torch.compile.

    328 GitHub stars~3.5k tokensUpdated 3 days ago
    AI & LLM EngineeringAuto-check: notes
  • Benchmarks LLM inference and drives GPU kernel optimization with Magpie.

    406 GitHub stars~2.3k tokensUpdated today
    AI & LLM EngineeringAuto-check passed
  • Hyperpod Version Checker

    awslabs/agent-plugins

    Official

    Check and compare software component versions on SageMaker HyperPod cluster nodes - NVIDIA drivers, CUDA toolkit, cuDNN, NCCL, EFA, AWS OFI NCCL, GDRCopy, MPI, Neuron SDK (Trainium/Inferentia)…

    915 GitHub stars~910 tokensUpdated today
    AI & LLM EngineeringAuto-check passed
  • Deep Learning

    ericrisco/rsc-harness

    A skill your agent uses when training or debugging a neural net in PyTorch — the forward/loss/backward/step loop and its silent bugs, mixed precision (AMP), AdamW/LR schedules, DDP/FSDP/ZeRO…

    174 GitHub stars~3.4k tokensUpdated yesterday
    AI & LLM EngineeringAuto-check passed
  • Triton Lang

    mohitmishra786/low-level-dev-skills

    Triton language skill for Python GPU kernel authoring. An agent skill from mohitmishra786/low-level-dev-skills.

    253 GitHub stars~1.8k tokensUpdated 3 mo ago
    AI & LLM EngineeringAuto-check passed

More from Orchestra-Research/AI-Research-SKILLs

All 96 skills in this repo
  • AudioCraft Audio Generation

    Orchestra-Research/AI-Research-SKILLs

    Generates music from text descriptions with MusicGen and sound effects with AudioGen, using Meta's AudioCraft PyTorch library with melody and style conditioning.

    13k GitHub starsUsed in 8 repos~3.9k tokens
    Auto-check passed
  • LLM Benchmarking with lm-evaluation-harness

    Orchestra-Research/AI-Research-SKILLs

    Runs lm-evaluation-harness to benchmark language models on academic suites such as MMLU, GSM8K and HumanEval, compare models and track training checkpoints.

    13k GitHub starsUsed in 8 repos~3k tokens
    Auto-check passed
  • Segment Anything Model Guide

    Orchestra-Research/AI-Research-SKILLs

    Guide to using Meta's Segment Anything Model for zero-shot image segmentation with point, box or mask prompts, or automatic mask generation.

    13k GitHub starsUsed in 8 repos~3.3k tokens
    Auto-check passed
  • Chroma Vector Database

    Orchestra-Research/AI-Research-SKILLs

    Shows how to store documents and embeddings in Chroma, query them by similarity with metadata filters, and persist them to disk for RAG and semantic search projects.

    13k GitHub starsUsed in 7 repos~2.3k tokens
    Auto-check passed
  • CLIP Image-Text Matching

    Orchestra-Research/AI-Research-SKILLs

    Explains OpenAI's CLIP model for zero-shot image classification, image-text similarity, semantic image search and content moderation, with install steps and code patterns.

    13k GitHub starsUsed in 7 repos~1.7k tokens
    Auto-check passed
  • Whisper Speech Recognition

    Orchestra-Research/AI-Research-SKILLs

    Transcribes audio with OpenAI's Whisper: 99 languages, translation to English, language detection, six model sizes and word-level timestamps, from Python or the CLI.

    13k GitHub starsUsed in 7 repos~1.9k tokens
    Auto-check: notes

Questions about PyTorch Lightning Training

What does PyTorch Lightning Training do?

Shows how to organize PyTorch training with Lightning's LightningModule and Trainer, covering validation, DDP, callbacks and learning-rate scheduling. The skill introduces PyTorch Lightning, installed with pip install lightning, as a way to cut boilerplate from PyTorch training. It shows how to convert plain PyTorch into a LightningModule that a Trainer runs, with the Trainer taking over GPU, TPU or CPU switching, distributed training with DDP, FSDP or DeepSpeed, mixed precision, gradient accumulation, checkpointing, logging and progress bars.

When should I use PyTorch Lightning Training?

PyTorch Lightning Training fits situations like: refactoring a plain PyTorch training loop into a LightningModule and Trainer; scaling the same training code from one GPU to several GPUs or nodes; adding checkpointing, early stopping or learning-rate monitoring with callbacks; setting up validation, testing and TensorBoard logging.

How do I install PyTorch Lightning Training in Claude Code?

Run `npx skills add Orchestra-Research/AI-Research-SKILLs --skill pytorch-lightning -a claude-code`. Or copy the skill folder (08-distributed-training/pytorch-lightning in Orchestra-Research/AI-Research-SKILLs) into .claude/skills/pytorch-lightning in your project. Claude Code loads it when a task matches its description.

How do I install PyTorch Lightning Training in Codex?

Run `npx skills add Orchestra-Research/AI-Research-SKILLs --skill pytorch-lightning -a codex`. Or copy the skill folder (08-distributed-training/pytorch-lightning in Orchestra-Research/AI-Research-SKILLs) into .agents/skills/pytorch-lightning in your project. Codex loads it when a task matches its description.

Can I use PyTorch Lightning Training in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add Orchestra-Research/AI-Research-SKILLs --skill pytorch-lightning -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/pytorch-lightning, .gemini/skills/pytorch-lightning, .github/skills/pytorch-lightning and .opencode/skills/pytorch-lightning in your project.

What does PyTorch Lightning Training need to run?

Going by SKILL.md and its folder, PyTorch Lightning Training needs the command-line tools its instructions call (pip and python). Our summary lists: Python with the lightning package, installed with pip install lightning; GPUs, TPUs or a cluster for distributed runs.

Does PyTorch Lightning Training access the network?

SKILL.md names 3 domains. As links in the text: github.com, lightning.ai and discord.gg. This is read from the text; nothing was executed.

Is PyTorch Lightning Training safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does PyTorch Lightning Training use?

PyTorch Lightning Training is published under the MIT licence (declared in SKILL.md). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does PyTorch Lightning Training use?

About 2.3k tokens (SKILL.md is roughly 9.1k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 8.8k tokens, read only when the agent opens those files.

What are the alternatives to PyTorch Lightning Training?

Skills that share tags, products or a category with PyTorch Lightning Training: PyTorch Lightning Training Setup (davila7/claude-code-templates, 32k stars), GPU Optimizer (Mathews-Tom/armory, 328 stars), Magpie Kernel Evaluator (amd/skills, 406 stars) and Hyperpod Version Checker (awslabs/agent-plugins, 915 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains PyTorch Lightning Training?

Orchestra-Research (a GitHub organization) maintains it in Orchestra-Research/AI-Research-SKILLs, which has 13,374 GitHub stars. The repository holds 96 skills in this directory. The repository was last updated on June 16, 2026.

Source: Orchestra-Research/AI-Research-SKILLs on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.