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.

2.6.6发布于 2026-09-10 09:39 UTC31,447star +1 / 7 天3,853fork同步于 2026-11-10 11:21 UTC

怎么上手

由 README 提炼,执行前请确认
pip install lightning
pip install torchvision
python main.py
硬件要求按 README 说明

README 未说明具体显存或 GPU 型号要求,仅说明可从 CPU 扩展到多节点 GPU,也可在自有硬件或云端运行。

支持 Apple Silicon需要 CUDA多卡 / 张量并行
下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

把 PyTorch 训练工程代码组织起来的框架,让你专注模型逻辑,从 CPU 平滑扩到多机多卡

统一的 PyTorch 训练框架,让同一份代码在单卡到上万张 GPU 上都能跑,免去改代码就能做预训练和微调。

核心能力

  • 用 LightningModule 封装训练、验证与优化器配置
  • Trainer 自动处理反向传播、混合精度与分布式训练
  • 同一份核心代码从 CPU 扩到多节点 GPU 无需改动
  • 提供 Fabric 包供专家级细粒度控制抽象层级
  • 覆盖分类、分割、检测、LLM 微调等示例

容易踩的坑

示例代码依赖 torchvision,需单独 pip 安装;README 未给出默认端口等运行参数;README 未说明是否需要额外下载预训练权重。

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

5 个版本2.6.6
  1. 2.6.6Lightning 2.6.6最新正式版2026-09-10 · 2026-09-10 09:39 UTC

    Changes in 2.6.6

    PyTorch Lightning

    • Fixed arbitrary code execution in load_from_checkpoint by restricting the _instantiator hyperparameter to an allowlist of trusted instantiators (#21832)

    • Fixed arbitrary code execution in load_from_checkpoint by rejecting a checkpoint _class_path that 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. 2.6.5Lightning 2.6.52026-05-27 · 2026-05-27 14:32 UTC
    查看更新说明

    Changes in 2.6.5

    Lightning 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

    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

  3. 2.6.4Lightning 2.6.42026-05-20 · 2026-05-20 22:08 UTC
    查看更新说明

    Changes in 2.6.4

    PyTorch 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 LitLogger version to 2026-03-17 (#21591)
    • Fixed val_check_interval raising ValueError when limit_val_batches=0 and 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_mesh type hint in FSDPStrategy to accept a 2-element tuple via the CLI (#21581)
    • Fixed RichModelSummary model size display formatting (#21467)
    • Fixed floating-point precision in SimpleProfiler duration aggregation by using math.fsum (#21525)

    Lightning Fabric

    • Fixed FSDP mixed precision (bf16-mixed, 16-mixed) initializing model parameters in half precision instead of fp32 (#21586)
    • Fixed device_mesh type hint in FSDPStrategy to accept a 2-element tuple via the CLI (#21581)

    Full commit list: 2.6.1 -> 2.6.4

    Contributors

    New 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:

    @AsherJingkongChen, @Borda, @bhimrazy, @deependujha, @justusschock, @littlebullGit, @ManasVardhan, @taha-yassine

  4. 2.6.1Lightning v2.6.12026-01-30 · 2026-01-30 14:57 UTC
    查看更新说明

    Changes in 2.6.1

    PyTorch Lightning

    • Added method chaining support to LightningModule.freeze() and LightningModule.unfreeze() by returning self (#21469)
    • Added litlogger integration(#21430)
    • Deprecated to_torchscript method 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_checkpoint to restore the datamodule subclass and hyperparameters (#21478)
    • Fixed ModelParallelStrategy single-file checkpointing when torch.compile wraps the model so optimizer states no longer raise KeyError during save (#21357)
    • Sanitize profiler filenames when saving to avoid crashes due to invalid characters (#21395)
    • Fixed StochasticWeightAveraging with infinite epochs (#21396)
    • Fixed _generate_seed_sequence_sampling function not producing unique seeds (#21399)
    • Fixed ThroughputMonitor callback emitting warnings too frequently (#21453)

    Lightning Fabric

    • Exposed weights_only argument for loading checkpoints in Fabric.load() and Fabric.load_raw() (#21470)
    • Fixed DistributedSamplerWrapper not forwarding set_epoch to 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

    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

  5. 2.6.0Lightning v2.6.02025-11-28 · 2025-11-28 09:33 UTC
    查看更新说明

    Changes in 2.6.0

    PyTorch Lightning

    • Added WeightAveraging callback that wraps the PyTorch AveragedModel class (#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 EarlyStopping callback (#21188)
    • Added support for variable batch size in ThroughputMonitor (#20236)
    • Added EMAWeightAveraging callback that wraps Lightning's WeightAveraging class (#21260)
    • Expose weights_only argument for Trainer.{fit,validate,test,predict} and let torch handle default value (#21072)
    • Default to RichProgressBar and RichModelSummary if the rich package is available. Fallback to TQDMProgressBar and ModelSummary otherwise (#20896)
    • Add MPS accelerator support for mixed precision (#21209)
    • Fixed edgecase when max_trials is reached in Tuner.scale_batch_size (#21187)
    • Fixed case where LightningCLI could not be initialized with trainer_default containing callbacks (#21192)
    • Fixed missing reset when ModelPruning is applied with lottery ticket hypothesis (#21191)
    • Fixed preventing recursive symlink creation iwhen save_last='link' and save_top_k=-1 (#21186)
    • Fixed last.ckpt being created and not linked to another checkpoint (#21244)
    • Fixed bug that prevented BackboneFinetuning from being used together with LearningRateFinder (#21224)
    • Fixed ModelPruning sparsity logging bug that caused incorrect sparsity percentages (#21223)
    • Fixed LightningCLI loading of hyperparameters from ckpt_path failing for subclass model mode (#21246)
    • Fixed check the init args only when the given frames are in __init__ method (#21227)
    • Fixed how ThroughputMonitor calculated 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

    • Expose weights_only argument for Trainer.{fit,validate,test,predict} and let torch handle default value (#21072)
    • Set _DeviceDtypeModuleMixin._device from torch's default device function (#21164)
    • Added kwargs-filtering for Fabric.call to su

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    The deep learning framework to pretrain and finetune AI models.

    Serving models? Use LitServe to build custom inference servers in pure Python.


    PyPI - Python Version PyPI Status PyPI - Downloads Conda codecov

    Discord GitHub commit activity license

     

     

    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.

    PT to PL

     


    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:

    TaskDescriptionRun
    Hello worldPretrain - Hello world example
    Image classificationFinetune - ResNet-34 model to classify images of cars
    Image segmentationFinetune - ResNet-50 model to segment images
    Object detectionFinetune - Faster R-CNN model to detect objects
    Text classificationFinetune - text classifier (BERT model)
    Text summarizationFinetune - text summarization (Hugging Face transformer model)
    Audio generationFinetune - audio generator (transformer model)
    LLM finetuningFinetune - LLM (Meta Llama 3.1 8B)
    Image generationPretrain - Image generator (diffusion model)
    Recommendation systemTrain - recommendation system (factorization and embedding)
    Time-series forecastingTrain - 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.132.02.1
    Linux py3.9 [GPUs]Build Status
    Linux (multiple Python versions)Test PyTorchTest PyTorchTest PyTorch
    OSX (multiple Python versions)Test PyTorchTest PyTorchTest PyTorch
    Windows (multiple Python versions)Test PyTorchTest PyTorchTest PyTorch

       

    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:

    1. Read the docs.
    2. Search through existing Discussions, or add a new question
    3. Join our discord.