Ecosystem: Lightning, Hugging Face, Captum, skorch, Ray & TorchRL

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

PyTorch itself deliberately stays small: tensors, autograd, torch.nn, optimizers and data loading. Much of what practitioners use daily lives in libraries around it. This page surveys six of them, says what problem each solves, and shows the smallest useful example. They are independent projects with their own release cycles, so always check that a given version supports your PyTorch version. The libraries maintained under the PyTorch organization itself (torchvision, torchaudio, torchao, ExecuTorch, torchtune, TorchRec) are covered on their own pages or in the PyTorch overview, and several older ones are archived (see Legacy APIs & Migration).

Targeted versions: Python 3.13 and PyTorch 2.15. The Lightning, Accelerate, Captum and skorch examples were run on Python 3.13 with PyTorch 2.15 (CPU) on 2026-10-31, with lightning 2.6.6, accelerate 1.15.0, captum 0.9.0 and skorch 1.4.0; the Ray Train example was not executed (Ray was not installed).

Choosing a library

Library What it adds to PyTorch Reach for it when

PyTorch Lightning

A structured training loop (LightningModule and Trainer), device and strategy selection, logging, checkpointing

You want the loop, multi-GPU and logging boilerplate handled for you

Hugging Face Transformers and Accelerate

Pretrained models and tokenizers; a thin wrapper that runs the same loop on any device or distributed setup

You use pretrained language, vision or speech models, or want multi-device training with minimal edits to a loop

Captum

Attribution methods such as Integrated Gradients

You need to explain individual predictions of a PyTorch model

skorch

A scikit-learn compatible estimator around a PyTorch module

You want to use a neural network inside Pipeline and GridSearchCV

Ray Train

Distributed training orchestration on a cluster

You scale beyond one machine and want scheduling, fault tolerance and checkpoint reporting

TorchRL

Reinforcement-learning building blocks: environments, collectors, replay buffers, losses

You do RL research or applications on PyTorch

The generic training loop these libraries wrap is in The Training Loop.

PyTorch Lightning

PyTorch Lightning organizes code into a LightningModule (the model plus training_step, validation_step and configure_optimizers) and a Trainer that runs the loop, moves data and models to devices, applies mixed precision, handles distributed strategies, checkpoints and logs. Install it with pip install lightning (the install page also lists a conda command from conda-forge). The "Lightning in 15 minutes", LightningModule and Trainer pages of the documentation describe the conventions the snippet follows.

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


class LitRegressor(L.LightningModule):
    def __init__(self, lr: float = 1e-2):
        super().__init__()
        self.save_hyperparameters()
        self.net = nn.Linear(10, 1)

    def training_step(self, batch, batch_idx):
        x, y = batch
        loss = nn.functional.mse_loss(self.net(x), y)
        self.log("train_loss", loss)
        return loss

    def configure_optimizers(self):
        return torch.optim.SGD(self.parameters(), lr=self.hparams.lr)


x = torch.randn(256, 10)
y = x.sum(dim=1, keepdim=True)
loader = DataLoader(TensorDataset(x, y), batch_size=32)

trainer = L.Trainer(max_epochs=3, accelerator="auto", devices="auto")
trainer.fit(LitRegressor(), loader)

Lightning writes TensorBoard logs by default when TensorBoard is installed (see TensorBoard Integration). Its main trade-off is indirection: you give up direct control of the loop in exchange for less code, so use a plain loop when you need an unusual step structure.

Hugging Face Transformers and Accelerate

The Hugging Face transformers library provides thousands of pretrained models behind a uniform API with PyTorch as a backend, plus tokenizers and a Trainer class. It is the usual route for fine-tuning language models; the workflow, adapters and licensing are covered in Hugging Face, Hugging Face Hub Essentials and Fine-tuning with PEFT and TRL, and the model side in Transfer Learning & Foundation Models, so this page does not repeat them.

accelerate is a separate, smaller library for people who want to keep their own loop. Its documentation describes it as letting the same PyTorch code run on any distributed configuration with four added lines: create an Accelerator, pass the model, optimizer, dataloader and scheduler through accelerator.prepare, replace loss.backward() with accelerator.backward(loss), and launch with accelerate launch my_script.py. It sits on torch.distributed and torch_xla and can also enable DeepSpeed and fully sharded data parallelism.

import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
from accelerate import Accelerator

accelerator = Accelerator()

model = nn.Linear(10, 1)
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
x = torch.randn(256, 10)
y = x.sum(dim=1, keepdim=True)
loader = DataLoader(TensorDataset(x, y), batch_size=32)

model, optimizer, loader = accelerator.prepare(model, optimizer, loader)

for xb, yb in loader:               # batches are already on the right device
    optimizer.zero_grad()
    loss = nn.functional.mse_loss(model(xb), yb)
    accelerator.backward(loss)
    optimizer.step()

Core PyTorch offers the same capabilities directly with DDP and FSDP2; see DistributedDataParallel and FSDP2. Accelerate trades explicit control for portability across hardware setups.

Captum

Captum is a model interpretability library for PyTorch that supports multiple modalities. Install it with pip install captum (the site also shows a conda command). Its overview example uses Integrated Gradients: construct IntegratedGradients(model) from captum.attr and call attribute with the input, a baseline and a target class, optionally asking for the convergence delta. The meaning of such attributions, their limits and alternatives such as SHAP are explained in Interpretability & Explainability.

import torch
from torch import nn
from captum.attr import IntegratedGradients

model = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 3)).eval()
inputs = torch.randn(2, 4, requires_grad=True)
baseline = torch.zeros(2, 4)

ig = IntegratedGradients(model)
attributions, delta = ig.attribute(
    inputs, baseline, target=0, return_convergence_delta=True
)
print(attributions.shape)    # torch.Size([2, 4]): one score per input feature

Attributions depend on the chosen baseline, so a method is only as meaningful as that choice; check that the convergence delta is small before trusting the numbers. The overview page lists only Integrated Gradients, so consult the API reference for the other algorithms.

skorch

skorch wraps a PyTorch module in a scikit-learn compatible estimator, so net.fit(X, y) runs the training loop and the result can be placed in a scikit-learn Pipeline or searched with GridSearchCV. Install it with pip install skorch; the documentation’s quickstart sections "Training a model", "In an sklearn Pipeline" and "Grid search" show the patterns. The snippet below puts a network in a Pipeline; on the run for this page it printed a training accuracy of about 0.8 after five epochs. For the scikit-learn side see Using scikit-learn with PyTorch & Keras.

import numpy as np
import torch
from torch import nn
from skorch import NeuralNetClassifier
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler


class Net(nn.Module):
    def __init__(self, hidden=16):
        super().__init__()
        self.body = nn.Sequential(nn.Linear(4, hidden), nn.ReLU(), nn.Linear(hidden, 2))

    def forward(self, X):
        return self.body(X)


X = np.random.randn(200, 4).astype(np.float32)      # skorch expects float32
y = (X.sum(axis=1) > 0).astype(np.int64)

pipe = Pipeline([
    ("scale", StandardScaler()),
    ("net", NeuralNetClassifier(Net, max_epochs=5, lr=0.1, criterion=nn.CrossEntropyLoss)),
])
pipe.fit(X, y)
print(pipe.score(X, y))

StandardScaler keeps float32 input as float32, so the pipeline above needs no cast; a float64 array reaching the network fails with a dtype mismatch, so cast with astype(np.float32) before fitting.

Ray Train

Ray Train turns a single-process PyTorch script into a distributed job. The documented changes are: wrap the model with ray.train.torch.prepare_model, wrap the data loader with ray.train.torch.prepare_data_loader (and call set_epoch on its sampler each epoch when there are several workers), report metrics and checkpoints with ray.train.report, describe the cluster with ScalingConfig, and launch with TorchTrainer(...).fit(). Multi-node runs need a shared storage_path in RunConfig.

import ray.train
import ray.train.torch
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
from ray.train import RunConfig, ScalingConfig
from ray.train.torch import TorchTrainer


def train_func(config):
    model = ray.train.torch.prepare_model(nn.Linear(10, 1))
    x = torch.randn(256, 10)
    y = x.sum(dim=1, keepdim=True)
    loader = ray.train.torch.prepare_data_loader(
        DataLoader(TensorDataset(x, y), batch_size=32, shuffle=True)
    )
    opt = torch.optim.SGD(model.parameters(), lr=0.01)
    for epoch in range(config["epochs"]):
        if ray.train.get_context().get_world_size() > 1:
            loader.sampler.set_epoch(epoch)
        for xb, yb in loader:
            opt.zero_grad()
            loss = nn.functional.mse_loss(model(xb), yb)
            loss.backward()
            opt.step()
        ray.train.report({"epoch": epoch, "loss": loss.item()})


trainer = TorchTrainer(
    train_func,
    train_loop_config={"epochs": 3},
    scaling_config=ScalingConfig(num_workers=2, use_gpu=False),
    run_config=RunConfig(storage_path="/tmp/ray_results", name="demo"),
)
result = trainer.fit()
print(result.metrics)

The documented example attaches a checkpoint built from a temporary directory to each report; the snippet omits it for brevity. Ray Train sits above DDP and FSDP rather than replacing them; the concepts are in Distributed Training and Distributed Training in PyTorch.

TorchRL

TorchRL is the PyTorch organization’s reinforcement-learning library, installed with pip install torchrl. It depends only on the standard library, NumPy and PyTorch, and treats simulators such as Gym environments as optional. Its API reference is organized by component: environments and transforms (torchrl.envs), data collectors (torchrl.collectors), replay buffers (torchrl.data) and loss modules (torchrl.objectives). Releases track PyTorch releases, and the documentation I read showed version 0.14. Several sections of that page are labelled legacy or removed, so check names against the current reference rather than older tutorials. For the underlying theory (policies, value functions, policy gradients) see Reinforcement Learning.

pip install torchrl

A full example requires an environment package and a specific algorithm recipe, so follow the official tutorials rather than copying fragments.

Other projects worth knowing

The official ecosystem page lists many more projects (for example vision, graph, tabular and tooling libraries) grouped by category, and is the right place to browse; it is a curated directory rather than a statement of compatibility with PyTorch 2.15. Source: https://pytorch.org/ecosystem/