示例代码依赖 torchvision,需单独 pip 安装;README 未给出默认端口等运行参数;README 未说明是否需要额外下载预训练权重。
pytorch-lightning
Lightning-AIApache-2.0活跃维护统一的 PyTorch 训练框架,让同一份代码在单卡到上万张 GPU 上都能跑,免去改代码就能做预训练和微调。
Pretrain, finetune ANY AI model of ANY size on 1 or 10,000+ GPUs with zero code changes.
pip install lightning
pip install torchvision
python main.pyREADME 未说明具体显存或 GPU 型号要求,仅说明可从 CPU 扩展到多节点 GPU,也可在自有硬件或云端运行。
把 PyTorch 训练工程代码组织起来的框架,让你专注模型逻辑,从 CPU 平滑扩到多机多卡
统一的 PyTorch 训练框架,让同一份代码在单卡到上万张 GPU 上都能跑,免去改代码就能做预训练和微调。
核心能力
- 用 LightningModule 封装训练、验证与优化器配置
- Trainer 自动处理反向传播、混合精度与分布式训练
- 同一份核心代码从 CPU 扩到多节点 GPU 无需改动
- 提供 Fabric 包供专家级细粒度控制抽象层级
- 覆盖分类、分割、检测、LLM 微调等示例
容易踩的坑
- 2.6.6Lightning 2.6.6最新正式版2026-09-10 · 2026-09-10 09:39 UTC
Changes in
2.6.6PyTorch Lightning
-
Fixed arbitrary code execution in
load_from_checkpointby restricting the_instantiatorhyperparameter to an allowlist of trusted instantiators (#21832) -
Fixed arbitrary code execution in
load_from_checkpointby rejecting a checkpoint_class_paththat does not resolve to an already imported subclass of the loaded class (#21914)Full commit list: 2.6.5 -> 2.6.6
Contributors
We thank all folks who submitted issues, features, fixes and doc changes. It's the only way we can collectively make Lightning :zap: better for everyone, nice job!
In particular, we would like to thank the authors and co-authors of the pull-requests above:
@addyCooks @bhimrazy
-
- 2.6.5Lightning 2.6.52026-05-27 · 2026-05-27 14:32 UTC
查看更新说明
Changes in
2.6.5Lightning Fabric
- Use fs.pipe() for S3/GCS checkpoint uploads in _atomic_save (#21595
Full commit list: 2.6.4 -> 2.6.5
Contributors
New Contributors
- @c-pozzi made their first contribution in https://github.com/Lightning-AI/pytorch-lightning/pull/21595
We thank all folks who submitted issues, features, fixes and doc changes. It's the only way we can collectively make Lightning :zap: better for everyone, nice job!
In particular, we would like to thank the authors and co-authors of the pull-requests above:
@c-pozzi @justusschock
- 2.6.4Lightning 2.6.42026-05-20 · 2026-05-20 22:08 UTC
查看更新说明
Changes in
2.6.4PyTorch Lightning
- Removed support for Neptune logger (#21572).
Note: We usually don't remove features in a patch release, however in this case it's an exception since even without removing it the integration would be broken due to Neptune being acquired and sunsetting public service
- Raised minimum
LitLoggerversion to2026-03-17(#21591)
- Fixed
val_check_intervalraisingValueErrorwhenlimit_val_batches=0and interval exceeds training batches (#21560) - Fixed FSDP mixed precision (
bf16-mixed,16-mixed) initializing model parameters in half precision instead of fp32 (#21586) - Fixed
device_meshtype hint inFSDPStrategyto accept a 2-element tuple via the CLI (#21581) - Fixed
RichModelSummarymodel size display formatting (#21467) - Fixed floating-point precision in
SimpleProfilerduration aggregation by usingmath.fsum(#21525)
Lightning Fabric
- Fixed FSDP mixed precision (
bf16-mixed,16-mixed) initializing model parameters in half precision instead of fp32 (#21586) - Fixed
device_meshtype hint inFSDPStrategyto accept a 2-element tuple via the CLI (#21581)
Full commit list: 2.6.1 -> 2.6.4
Contributors
New Contributors
- @AsherJingkongChen made their first contribution in https://github.com/Lightning-AI/pytorch-lightning/pull/21467
- @ManasVardhan made their first contribution in https://github.com/Lightning-AI/pytorch-lightning/pull/21560
We thank all folks who submitted issues, features, fixes and doc changes. It's the only way we can collectively make Lightning :zap: better for everyone, nice job!
In particular, we would like to thank the authors and co-authors of the pull-requests above:
@AsherJingkongChen, @Borda, @bhimrazy, @deependujha, @justusschock, @littlebullGit, @ManasVardhan, @taha-yassine
- 2.6.1Lightning v2.6.12026-01-30 · 2026-01-30 14:57 UTC
查看更新说明
Changes in
2.6.1PyTorch Lightning
- Added method chaining support to
LightningModule.freeze()andLightningModule.unfreeze()by returningself(#21469) - Added litlogger integration(#21430)
- Deprecated
to_torchscriptmethod due to deprecation of TorchScript in PyTorch (#21397)
- Removed support for Python 3.9 due to end-of-life status (#21398)
- Fixed
save_hyperparameters(ignore=...)behavior so subclass ignore rules override base class rules (#21490) - Fixed
LightningDataModule.load_from_checkpointto restore the datamodule subclass and hyperparameters (#21478) - Fixed
ModelParallelStrategysingle-file checkpointing whentorch.compilewraps the model so optimizer states no longer raiseKeyErrorduring save (#21357) - Sanitize profiler filenames when saving to avoid crashes due to invalid characters (#21395)
- Fixed
StochasticWeightAveragingwith infinite epochs (#21396) - Fixed
_generate_seed_sequence_samplingfunction not producing unique seeds (#21399) - Fixed
ThroughputMonitorcallback emitting warnings too frequently (#21453)
Lightning Fabric
- Exposed
weights_onlyargument for loading checkpoints inFabric.load()andFabric.load_raw()(#21470)
- Fixed
DistributedSamplerWrappernot forwardingset_epochto the underlying sampler (#21454) - Fixed DDP notebook CUDA fork check to allow passive initialization when CUDA is not actively used (#21402)
Full commit list: 2.6.0 -> 2.6.1
Contributors
New Contributors
- @arrdel made their first contribution in https://github.com/Lightning-AI/pytorch-lightning/pull/21402
- @CodeVishal-17 made their first contribution in https://github.com/Lightning-AI/pytorch-lightning/pull/21470
- @aditya0by0 made their first contribution in https://github.com/Lightning-AI/pytorch-lightning/pull/21478
We thank all folks who submitted issues, features, fixes and doc changes. It's the only way we can collectively make Lightning :zap: better for everyone, nice job!
In particular, we would like to thank the authors of the pull-requests above
- Added method chaining support to
- 2.6.0Lightning v2.6.02025-11-28 · 2025-11-28 09:33 UTC
查看更新说明
Changes in
2.6.0PyTorch Lightning
- Added
WeightAveragingcallback that wraps the PyTorchAveragedModelclass (#20545) - Added Torch-Tensorrt integration with
LightningModule(#20808) - Added time-based validation support though
val_check_interval(#21071) - Added attributes to access stopping reason in
EarlyStoppingcallback (#21188) - Added support for variable batch size in
ThroughputMonitor(#20236) - Added
EMAWeightAveragingcallback that wraps Lightning'sWeightAveragingclass (#21260)
- Expose
weights_onlyargument forTrainer.{fit,validate,test,predict}and lettorchhandle default value (#21072) - Default to
RichProgressBarandRichModelSummaryif the rich package is available. Fallback to TQDMProgressBar and ModelSummary otherwise (#20896) - Add MPS accelerator support for mixed precision (#21209)
- Fixed edgecase when
max_trialsis reached inTuner.scale_batch_size(#21187) - Fixed case where
LightningCLIcould not be initialized withtrainer_defaultcontaining callbacks (#21192) - Fixed missing reset when
ModelPruningis applied with lottery ticket hypothesis (#21191) - Fixed preventing recursive symlink creation iwhen
save_last='link'andsave_top_k=-1(#21186) - Fixed
last.ckptbeing created and not linked to another checkpoint (#21244) - Fixed bug that prevented
BackboneFinetuningfrom being used together withLearningRateFinder(#21224) - Fixed
ModelPruningsparsity logging bug that caused incorrect sparsity percentages (#21223) - Fixed
LightningCLIloading of hyperparameters fromckpt_pathfailing for subclass model mode (#21246) - Fixed check the init args only when the given frames are in
__init__method (#21227) - Fixed how
ThroughputMonitorcalculated training time (#21291) - Fixed synchronization of gradients in manual optimization with
DDPStrategy(static_graph=True)(#21251) - Fixed FSDP mixed precision semantics and added user warning (#21361)
Lightning Fabric
- Added
用户点评
登录用户的真实使用记录,可按版本和硬件筛选还没有人点评。第一个说出真实体验的人最有价值。
The deep learning framework to pretrain and finetune AI models.
Serving models? Use LitServe to build custom inference servers in pure Python.
Why PyTorch Lightning?
Training models in plain PyTorch requires writing and maintaining a lot of repetitive engineering code. Handling backpropagation, mixed precision, multi-GPU, and distributed training is error-prone and often reimplemented for every project. PyTorch Lightning organizes PyTorch code to automate this infrastructure while keeping full control over your model logic. You write the science. Lightning handles the engineering, and scales from CPU to multi-node GPUs without changing your core code. PyTorch experts can still opt into expert-level control.
Fun analogy: If PyTorch is Javascript, PyTorch Lightning is ReactJS or NextJS.
Looking for GPUs?
Lightning Cloud is the easiest way to run PyTorch Lightning without managing infrastructure. Start training with one command and get GPUs, autoscaling, monitoring, and a free tier. No cloud setup required.
You can also run PyTorch Lightning on your own hardware or cloud.
Lightning has 2 core packages
PyTorch Lightning: Train and deploy PyTorch at scale. Lightning Fabric: Expert control.
Lightning gives you granular control over how much abstraction you want to add over PyTorch.
Quick start
Install Lightning:
pip install lightning
Install with optional dependencies
pip install lightning['extra']
Conda
conda install lightning -c conda-forge
Install stable version
Install future release from the source
pip install https://github.com/Lightning-AI/lightning/archive/refs/heads/release/stable.zip -U
Install bleeding-edge
Install nightly from the source (no guarantees)
pip install https://github.com/Lightning-AI/lightning/archive/refs/heads/master.zip -U
or from testing PyPI
pip install -iU https://test.pypi.org/simple/ pytorch-lightning
PyTorch Lightning example
Define the training workflow. Here's a toy example (explore real examples):
# main.py
# ! pip install torchvision
import torch, torch.nn as nn, torch.utils.data as data, torchvision as tv, torch.nn.functional as F
import lightning as L
# --------------------------------
# Step 1: Define a LightningModule
# --------------------------------
# A LightningModule (nn.Module subclass) defines a full *system*
# (ie: an LLM, diffusion model, autoencoder, or simple image classifier).
class LitAutoEncoder(L.LightningModule):
def __init__(self):
super().__init__()
self.encoder = nn.Sequential(nn.Linear(28 * 28, 128), nn.ReLU(), nn.Linear(128, 3))
self.decoder = nn.Sequential(nn.Linear(3, 128), nn.ReLU(), nn.Linear(128, 28 * 28))
def forward(self, x):
# in lightning, forward defines the prediction/inference actions
embedding = self.encoder(x)
return embedding
def training_step(self, batch, batch_idx):
# training_step defines the train loop. It is independent of forward
x, _ = batch
x = x.view(x.size(0), -1)
z = self.encoder(x)
x_hat = self.decoder(z)
loss = F.mse_loss(x_hat, x)
self.log("train_loss", loss)
return loss
def configure_optimizers(self):
optimizer = torch.optim.Adam(self.parameters(), lr=1e-3)
return optimizer
# -------------------
# Step 2: Define data
# -------------------
dataset = tv.datasets.MNIST(".", download=True, transform=tv.transforms.ToTensor())
train, val = data.random_split(dataset, [55000, 5000])
# -------------------
# Step 3: Train
# -------------------
autoencoder = LitAutoEncoder()
trainer = L.Trainer()
trainer.fit(autoencoder, data.DataLoader(train), data.DataLoader(val))
Run the model on your terminal
pip install torchvision
python main.py
Convert from PyTorch to PyTorch Lightning
PyTorch Lightning is just organized PyTorch - Lightning disentangles PyTorch code to decouple the science from the engineering.

Examples
Explore various types of training possible with PyTorch Lightning. Pretrain and finetune ANY kind of model to perform ANY task like classification, segmentation, summarization and more:
| Task | Description | Run |
|---|---|---|
| Hello world | Pretrain - Hello world example | |
| Image classification | Finetune - ResNet-34 model to classify images of cars | |
| Image segmentation | Finetune - ResNet-50 model to segment images | |
| Object detection | Finetune - Faster R-CNN model to detect objects | |
| Text classification | Finetune - text classifier (BERT model) | |
| Text summarization | Finetune - text summarization (Hugging Face transformer model) | |
| Audio generation | Finetune - audio generator (transformer model) | |
| LLM finetuning | Finetune - LLM (Meta Llama 3.1 8B) | |
| Image generation | Pretrain - Image generator (diffusion model) | |
| Recommendation system | Train - recommendation system (factorization and embedding) | |
| Time-series forecasting | Train - Time-series forecasting with LSTM |
Advanced features
Lightning has over 40+ advanced features designed for professional AI research at scale.
Here are some examples:
# 8 GPUs
# no code changes needed
trainer = Trainer(accelerator="gpu", devices=8)
# 256 GPUs
trainer = Trainer(accelerator="gpu", devices=8, num_nodes=32)
# no code changes needed
trainer = Trainer(accelerator="tpu", devices=8)
# no code changes needed
trainer = Trainer(precision=16)
from lightning import loggers
# litlogger
trainer = Trainer(logger=LitLogger())
# tensorboard
trainer = Trainer(logger=TensorBoardLogger("logs/"))
# weights and biases
trainer = Trainer(logger=loggers.WandbLogger())
# comet
trainer = Trainer(logger=loggers.CometLogger())
# mlflow
trainer = Trainer(logger=loggers.MLFlowLogger())
# ... and dozens more
es = EarlyStopping(monitor="val_loss")
trainer = Trainer(callbacks=[es])
checkpointing = ModelCheckpoint(monitor="val_loss")
trainer = Trainer(callbacks=[checkpointing])
# torchscript
autoencoder = LitAutoEncoder()
torch.jit.save(autoencoder.to_torchscript(), "model.pt")
# onnx
with tempfile.NamedTemporaryFile(suffix=".onnx", delete=False) as tmpfile:
autoencoder = LitAutoEncoder()
input_sample = torch.randn((1, 64))
autoencoder.to_onnx(tmpfile.name, input_sample, export_params=True)
os.path.isfile(tmpfile.name)
Advantages over unstructured PyTorch
- Models become hardware agnostic
- Code is clear to read because engineering code is abstracted away
- Easier to reproduce
- Make fewer mistakes because lightning handles the tricky engineering
- Keeps all the flexibility (LightningModules are still PyTorch modules), but removes a ton of boilerplate
- Lightning has dozens of integrations with popular machine learning tools.
- Tested rigorously with every new PR. We test every combination of PyTorch and Python supported versions, every OS, multi GPUs and even TPUs.
- Minimal running speed overhead (about 300 ms per epoch compared with pure PyTorch).
Lightning Fabric: Expert control
Run on any device at any scale with expert-level control over PyTorch training loop and scaling strategy. You can even write your own Trainer.
Fabric is designed for the most complex models like foundation model scaling, LLMs, diffusion, transformers, reinforcement learning, active learning. Of any size.
+ import lightning as L
import torch; import torchvision as tv
dataset = tv.datasets.CIFAR10("data", download=True,
train=True,
transform=tv.transforms.ToTensor())
+ fabric = L.Fabric()
+ fabric.launch()
model = tv.models.resnet18()
optimizer = torch.optim.SGD(model.parameters(), lr=0.001)
- device = "cuda" if torch.cuda.is_available() else "cpu"
- model.to(device)
+ model, optimizer = fabric.setup(model, optimizer)
dataloader = torch.utils.data.DataLoader(dataset, batch_size=8)
+ dataloader = fabric.setup_dataloaders(dataloader)
model.train()
num_epochs = 10
for epoch in range(num_epochs):
for batch in dataloader:
inputs, labels = batch
- inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = torch.nn.functional.cross_entropy(outputs, labels)
- loss.backward()
+ fabric.backward(loss)
optimizer.step()
print(loss.data)
import lightning as L
import torch; import torchvision as tv
dataset = tv.datasets.CIFAR10("data", download=True,
train=True,
transform=tv.transforms.ToTensor())
fabric = L.Fabric()
fabric.launch()
model = tv.models.resnet18()
optimizer = torch.optim.SGD(model.parameters(), lr=0.001)
model, optimizer = fabric.setup(model, optimizer)
dataloader = torch.utils.data.DataLoader(dataset, batch_size=8)
dataloader = fabric.setup_dataloaders(dataloader)
model.train()
num_epochs = 10
for epoch in range(num_epochs):
for batch in dataloader:
inputs, labels = batch
optimizer.zero_grad()
outputs = model(inputs)
loss = torch.nn.functional.cross_entropy(outputs, labels)
fabric.backward(loss)
optimizer.step()
print(loss.data)
Key features
# Use your available hardware
# no code changes needed
fabric = Fabric()
# Run on GPUs (CUDA or MPS)
fabric = Fabric(accelerator="gpu")
# 8 GPUs
fabric = Fabric(accelerator="gpu", devices=8)
# 256 GPUs, multi-node
fabric = Fabric(accelerator="gpu", devices=8, num_nodes=32)
# Run on TPUs
fabric = Fabric(accelerator="tpu")
# Use state-of-the-art distributed training techniques
fabric = Fabric(strategy="ddp")
fabric = Fabric(strategy="deepspeed")
fabric = Fabric(strategy="fsdp")
# Switch the precision
fabric = Fabric(precision="16-mixed")
fabric = Fabric(precision="64")
# no more of this!
- model.to(device)
- batch.to(device)
import lightning as L
class MyCustomTrainer:
def __init__(self, accelerator="auto", strategy="auto", devices="auto", precision="32-true"):
self.fabric = L.Fabric(accelerator=accelerator, strategy=strategy, devices=devices, precision=precision)
def fit(self, model, optimizer, dataloader, max_epochs):
self.fabric.launch()
model, optimizer = self.fabric.setup(model, optimizer)
dataloader = self.fabric.setup_dataloaders(dataloader)
model.train()
for epoch in range(max_epochs):
for batch in dataloader:
input, target = batch
optimizer.zero_grad()
output = model(input)
loss = loss_fn(output, target)
self.fabric.backward(loss)
optimizer.step()
You can find a more extensive example in our examples
Examples
Self-supervised Learning
Convolutional Architectures
Reinforcement Learning
GANs
Classic ML
Continuous Integration
Lightning is rigorously tested across multiple CPUs, GPUs and TPUs and against major Python and PyTorch versions.
*Codecov is > 90%+ but build delays may show less
| System / PyTorch ver. | 1.13 | 2.0 | 2.1 |
|---|---|---|---|
| Linux py3.9 [GPUs] | |||
| Linux (multiple Python versions) | |||
| OSX (multiple Python versions) | |||
| Windows (multiple Python versions) |
Community
The lightning community is maintained by
- 10+ core contributors who are all a mix of professional engineers, Research Scientists, and Ph.D. students from top AI labs.
- 800+ community contributors.
Want to help us build Lightning and reduce boilerplate for thousands of researchers? Learn how to make your first contribution here
Lightning is also part of the PyTorch ecosystem which requires projects to have solid testing, documentation and support.
Asking for help
If you have any questions please: