ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

PyTorch Lightning 能力分级学习路线:从训练第一个模型到自定义分布式策略的官方进阶指南

PyTorch Lightning 能力分级学习路线:从训练第一个模型到自定义分布式策略的官方进阶指南 PyTorch Lightning 能力分级学习路线从训练第一个模型到自定义分布式策略的官方进阶指南【免费下载链接】pytorch-lightningPretrain, finetune ANY AI model of ANY size on 1 or 10,000 GPUs with zero code changes.项目地址: https://gitcode.com/gh_mirrors/py/pytorch-lightning本文依据 PyTorch Lightning 官方文档中的 Level up 能力分级体系docs/source-pytorch/expertise_levels.rst整理而成。该文档将 Lightning 的全部核心能力划分为Basic基础→ Intermediate进阶→ Advanced高级→ Expert专家四个层级、共 24 个递进关卡并逐一映射到官方教程、源码与测试。读完本文你将获得一张完整的 Lightning 技术能力地图知道什么阶段该学什么、去哪里学、底层源码如何佐证从而按自己的研究或岗位所需精准规划学习路径快速匹配对应水平的实战技能。分级体系总览expertise_levels.rst开篇即点明了这套学习路线的设计理念Learn enough Lightning to match the level of expertise required by your research or job.也就是说这套分级不是固定的新手教程而是按角色需求检索能力的目录。官方给出了每一层级的适用人群定位层级定位人群覆盖关卡核心能力方向Basic skills研究人员与机器学习工程师起点Level 1–6模型训练、验证/测试、预训练模型、脚本参数、调试可视化、推理预测Intermediate skills学术/工业研究实验室的规模化协作开发Level 7–13硬件加速、DataModule 模块化、模型理解、SOTA 缩放技巧、部署、训练提速、集群Advanced skills生产环境的高级配置场景Level 14–19可组合 YAML、自定义 Trainer、自持训练循环、高级 checkpoint、TPU、十亿参数模型Expert skills框架扩展者自定义硬件 / 分布式策略Level 21–24扩展 Lightning CLI、接入自定义集群、自研 Profiler、新增 Accelerator/Strategy说明官方在 Advanced 之后编号从 Level 19 直接跳到 Level 21源码树中不存在 Level 20 的关卡页docs/source-pytorch/levels/目录实际包含advanced_level_20.rst对应 Level 18 的 TPU 主题引用时请以各级关卡页内的实际标题为准。Basic skills打牢模型开发基本功官方定位Learn the basics of model development with Lightning. Researchers and machine learning engineers should start here.这一层级解决的是如何用 Lightning 把一个 PyTorch 模型完整地训练、评估并投入使用。Level 1训练一个模型Train a modelLearn the basics of training a model.这是所有人的起点。官方入口为 docs/source-pytorch/model/train_model_basic.rst核心心智模型是三层结构纯 PyTorch 的nn.Module只管网络结构本身不掺入任何训练逻辑如下例中的Encoder/Decoder。LightningModule把nn.Module的组织方式、配方写在这里——training_step定义前向与损失计算configure_optimizers定义优化器。Trainer接管全部工程化细节循环、分布式、精度等。官方给出的最小可运行示例节选自 train_model_basic.rstimport os import torch from torch import nn import torch.nn.functional as F from torchvision import transforms from torchvision.datasets import MNIST from torch.utils.data import DataLoader import lightning as L class Encoder(nn.Module): def __init__(self): super().__init__() self.l1 nn.Sequential(nn.Linear(28 * 28, 64), nn.ReLU(), nn.Linear(64, 3)) def forward(self, x): return self.l1(x) class Decoder(nn.Module): def __init__(self): super().__init__() self.l1 nn.Sequential(nn.Linear(3, 64), nn.ReLU(), nn.Linear(64, 28 * 28)) def forward(self, x): return self.l1(x) class LitAutoEncoder(L.LightningModule): def __init__(self, encoder, decoder): super().__init__() self.encoder encoder self.decoder decoder def training_step(self, batch, batch_idx): # training_step defines the train loop. 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) return loss def configure_optimizers(self): optimizer torch.optim.Adam(self.parameters(), lr1e-3) return optimizer dataset MNIST(os.getcwd(), downloadTrue, transformtransforms.ToTensor()) train_loader DataLoader(dataset) # model autoencoder LitAutoEncoder(Encoder(), Decoder()) # train model trainer L.Trainer() trainer.fit(modelautoencoder, train_dataloaderstrain_loader)文档还专门揭示了 Trainer 内部替你执行的等价朴素循环帮助理解 Lightning 的抽象边界autoencoder LitAutoEncoder(Encoder(), Decoder()) optimizer autoencoder.configure_optimizers() for batch_idx, batch in enumerate(train_loader): loss autoencoder.training_step(batch, batch_idx) loss.backward() optimizer.step() optimizer.zero_grad()源码佐证LightningModule与Trainer的实现在 src/lightning/pytorch/core/ 与 src/lightning/pytorch/trainer/仓库内置的完整可运行示例见 examples/pytorch/basics/autoencoder.py、examples/pytorch/basics/transformer.py。训练循环内部由 src/lightning/pytorch/loops/ 下的循环组件training/evaluation/prediction 三大循环驱动相关流程测试见 tests/tests_pytorch/loops/test_training_loop.py。Level 2加入验证集与测试集Add validation and test sets to avoid over/underfitting.本关要点见 docs/source-pytorch/levels/basic_level_2.rstValidate and test a model在LightningModule中实现validation_step/test_step并用Trainer.fit的val_dataloaders参数挂载验证集参考 docs/source-pytorch/common/evaluation_basic.rst。Save your model progress使用ModelCheckpoint回调在训练过程中持续保存模型状态参考 docs/source-pytorch/common/checkpointing_basic.rstSave a checkpoint 一节。Enable early stopping用EarlyStopping回调在验证指标不再提升时提前终止训练参考 docs/source-pytorch/common/early_stopping.rst。源码佐证这两个回调分别位于 src/lightning/pytorch/callbacks/ 下的early_stopping与model_checkpoint模块对应的行为测试见 tests/tests_pytorch/callbacks/test_early_stopping.py 与 tests/tests_pytorch/callbacks/test_model_checkpoint_edge_cases.py。其中EarlyStopping在训练循环中通过 src/lightning/pytorch/loops/ 的 epoch 级回调钩子被周期性触发。Level 3使用预训练模型Learn how to use pretrained models with Lightning.官方指向 docs/source-pytorch/advanced/transfer_learning.rst。核心模式是把torchvision.models等预训练权重加载进nn.Module放入LightningModule后即可复用 Trainer 的全部能力进行微调finetune。仓库中的落地示例可参考 examples/pytorch/domain_templates/computer_vision_fine_tuning.py它演示了标准的迁移学习/微调模板与本关主题直接对应。Level 4为脚本启用命令行参数Add parameters to your script so you can run from the commandline.本关主题是超参数管理官方文档为 docs/source-pytorch/common/hyperparameters.rst。进阶形态是官方推荐的LightningCLI——用声明式方式把模型、数据、优化器全部暴露为命令行参数并自动生成配置详见 docs/source-pytorch/cli/lightning_cli.rst。源码佐证CLI 实现位于 src/lightning/pytorch/cli.py配套的端到端测试见 tests/tests_pytorch/test_cli.pyLR 调参工具lr_finder的测试在 tests/tests_pytorch/tuner/test_lr_finder.py。Level 5理解并可视化你的模型Remove bottlenecks and visualize your model.官方入口 docs/source-pytorch/levels/basic_level_5.rst 拆出三个子任务Debug your model定位训练不收敛、NaN 等常见问题参考 docs/source-pytorch/debug/debugging_basic.rst。Find bottlenecks in training用 Profiler 找出训练循环的性能瓶颈参考 docs/source-pytorch/tuning/profiler_basic.rst。Visualize metrics, images, and text用 Logger 跟踪并可视化指标、图像与文本参考 docs/source-pytorch/visualize/logging_basic.rst。源码佐证仓库示例 examples/pytorch/basics/profiler_example.py 演示了 Profiler 的用法Profiler 家族Simple/PyTorch/Advanced/XLA 等实现在 src/lightning/pytorch/profilers/测试见 tests/tests_pytorch/profilers/test_profiler.py。Level 6用模型做预测Use your model for predictions.官方入口 docs/source-pytorch/levels/core_level_6.rst 的三个子任务Load model weights从 checkpoint 恢复模型参考 docs/source-pytorch/common/checkpointing_basic.rst 的 LightningModule from checkpoint 一节。Predict with LightningModule在 Lightning 体系内用predict流程做推理参考 docs/source-pytorch/deploy/production_basic.rst。Predict with pure PyTorch脱离 Lightning 依赖、仅用纯 PyTorch 加载权重做推理参考 docs/source-pytorch/deploy/production_intermediate.rst。源码佐证Trainer.predict由 src/lightning/pytorch/loops/ 中的PredictionLoop驱动相关流程测试见 tests/tests_pytorch/loops/test_prediction_loop.py面向生产暴露的ServableModule封装见 src/lightning/pytorch/serve/。Intermediate skills规模化与协作开发官方定位Learn to scale up your models and enable collaborative model development at academic or industry research labs.从本层开始你将接触多卡、多机、模块化与性能优化。Level 7硬件加速Learn how to access GPUs and TPUs on the cloud.官方入口 docs/source-pytorch/levels/intermediate_level_7.rstPrepare your code可选让代码可移植到任意硬件参考 docs/source-pytorch/accelerators/accelerator_prepare.rst。GPU Training单卡与多卡 GPU 训练基础参考 docs/source-pytorch/accelerators/gpu_basic.rst。TPU Training单核与多核 TPU 训练基础参考 docs/source-pytorch/accelerators/tpu_basic.rst。源码佐证加速器抽象基类与注册机制见 src/lightning/pytorch/accelerators/含 CPU/CUDA/MPS/XLA 等实现注册表测试见 tests/tests_pytorch/accelerators/test_registry.py。Level 8模块化你的项目Create DataModules to enable dataset reusability.官方入口 docs/source-pytorch/levels/intermediate_level_9.rst 的三个子任务Modularize your datasets用LightningDataModule把数据集处理逻辑下载、切分、transform、dataloader封装成可复用模块参考 docs/source-pytorch/data/datamodule.rst。Control it all from the CLI用 CLI 统一控制LightningModule与LightningDataModule参考 docs/source-pytorch/cli/lightning_cli_intermediate.rst。Mix models and datasets通过 Registry 注册模型、数据集、优化器与学习率调度器参考 docs/source-pytorch/cli/lightning_cli_intermediate_2.rst。源码佐证LightningDataModule实现在 src/lightning/pytorch/core/数据加载状态机由 src/lightning/pytorch/trainer/connectors/data_connector.py 管理该文件位于 src/lightning/pytorch/trainer/connectors/ 目录下DataModule 相关测试见 tests/tests_pytorch/core/test_datamodules.py。Level 9深入理解你的模型Use advanced visuals to find the best performing model.官方入口 docs/source-pytorch/levels/intermediate_level_10.rstAlter checkpoint behavior按指标条件化保存 checkpointmonitor 指标、save_top_k 等参考 docs/source-pytorch/common/checkpointing_intermediate.rst。Visualize more than metrics利用实验管理器的进阶可视化能力参考 docs/source-pytorch/visualize/logging_intermediate.rst。Granular control of logging对日志进行细粒度控制以优化速度参考 docs/source-pytorch/visualize/logging_advanced.rst。源码佐证ModelCheckpoint的监控/筛选逻辑实现在 src/lightning/pytorch/callbacks/model_checkpoint.py位于 src/lightning/pytorch/callbacks/ 下其按验证指标触发的行为有专门的测试覆盖见 tests/tests_pytorch/callbacks/test_model_checkpoint_step_interval_val_metric.py。Level 10探索 SOTA 缩放技术Explore SOTA techniques to help convergence, stability and scalability.官方入口 docs/source-pytorch/levels/intermediate_level_11.rstHalf precision training用不同浮点精度FP16/BF16/混合精度训练得更快、更省显存参考 docs/source-pytorch/common/precision_basic.rst。SOTA scaling techniques打开有助于收敛与缩放的进阶技巧梯度累积、SWA 等参考 docs/source-pytorch/advanced/training_tricks.rst。源码佐证精度插件体系PrecisionPlugin及 AMP/FP16/BF16/DS 等实现位于 src/lightning/pytorch/plugins/precision/对应测试见 tests/tests_pytorch/plugins/precision/。Level 11部署你的模型Learn how to deploy your models with optimizations like ONNX and torchscript.官方入口 docs/source-pytorch/levels/intermediate_level_12.rst主题是把训练好的模型导出为 ONNX / TorchScript 等优化格式用于生产部署。源码佐证仓库对这两种导出路径均有实测验证——tests/tests_pytorch/models/test_onnx.py 与 tests/tests_pytorch/models/test_torchscript.py相关的生产化部署专题文档见 docs/source-pytorch/deploy/production_advanced.rst。仓库还提供了面向推理服务的ServableModule参考实现src/lightning/pytorch/serve/验证测试见 tests/tests_pytorch/serve/test_servable_module_validator.py。Level 12优化训练速度Use advanced profilers to mixed precision to train bigger models, faster.官方入口 docs/source-pytorch/levels/intermediate_level_13.rst 给出四条提速路径Speed up models by compiling them用torch.compile在现代硬件上加速模型参考 docs/source-pytorch/advanced/compile.rst。Explore advanced mixed precision settings开启更先进的混合精度配置参考 docs/source-pytorch/common/precision_intermediate.rst。Enable advanced profilers用 Profiler 调优模型性能参考 docs/source-pytorch/tuning/profiler_basic.rst。Profile PyTorch operations定位 PyTorch 算子级瓶颈参考 docs/source-pytorch/tuning/profiler_intermediate.rst。源码佐证torch.compile在 Lightning 中的接入与测试见 tests/tests_pytorch/utilities/test_compile.py仓库还提供 FP8 分布式训练示例 examples/pytorch/fp8_distributed_transformer/train.py 供提速参考。Level 13在集群上运行Run on a custom on-prem cluster or SLURM cluster.官方入口 docs/source-pytorch/levels/intermediate_level_14.rst 覆盖四种运行场景Run single or multi-node on Lightning Studios云端免基础设施搭建参考 docs/source-pytorch/clouds/lightning_ai.rst。Run on an on-prem cluster在通用计算集群上训练参考 docs/source-pytorch/clouds/cluster_intermediate_1.rst。Run on a SLURM cluster在 SLURM 管理的集群上运行参考 docs/source-pytorch/clouds/cluster_advanced.rst。Run with Torch Distributed基于 torch.distributed 在集群上运行参考 docs/source-pytorch/clouds/cluster_intermediate_2.rst。源码佐证环境Environment抽象负责解析 SLURM/Torchelastic 等集群环境变量位于 src/lightning/pytorch/plugins/environments/多机 DDP 的启动与保活逻辑由 src/lightning/pytorch/strategies/ 与DDPSpawnLauncher等组件承担launcher 实现在 src/lightning/pytorch/strategies/launchers/。Advanced skills面向生产的高级配置官方定位Configure all aspects of Lightning for advanced usecases.本层解决生产级、规模化场景下的深度定制问题。Level 14定制生产配置Enable composable YAMLs.官方入口 docs/source-pytorch/levels/advanced_level_15.rst主题是用 LightningCLI 的--config机制把训练配置拆分为可组合的 YAML 文件支持配置的继承与拼接从而在多人协作与多实验之间复用配置。源码佐证配置解析全部由 src/lightning/pytorch/cli.py 中的LightningCLI承担进阶用法见 docs/source-pytorch/cli/lightning_cli_advanced.rst 与 docs/source-pytorch/cli/lightning_cli_advanced_2.rst仓库也提供了基于 YAML 配置的模型/训练参数样例tests/tests_pytorch/models/conf/。Level 15定制 TrainerInject custom code into the trainer and modify the progress bar.官方入口 docs/source-pytorch/levels/advanced_level_16.rst主题包括通过回调Callbacks在训练生命周期中注入自定义逻辑如自定义指标记录、动态调整超参以及定制进度条自定义ProgressBar或集成 Rich/TQDM。源码佐证回调体系实现在 src/lightning/pytorch/callbacks/进度条相关实现见 src/lightning/pytorch/callbacks/progress/回调钩子的返回值校验测试见 tests/tests_pytorch/callbacks/test_callback_hook_outputs.pyRich 进度条测试见 tests/tests_pytorch/callbacks/test_rich_model_summary.py。Level 16掌控训练循环Learn all the ways of owning your raw PyTorch loops with Lightning.官方入口 docs/source-pytorch/levels/advanced_level_17.rst 给出两条自持循环路径Enable manual optimization通过self.automatic_optimization False关闭自动优化在training_step中手动控制optimizer.step()、梯度缩放与清零参考 docs/source-pytorch/model/build_model_advanced.rst。Use Lightning Fabric完全不依赖 Trainer用 Fabric 在极薄抽象上自由编写训练循环同时保留多卡/精度等工程能力。源码佐证手动优化路径由 src/lightning/pytorch/loops/optimization/ 中的优化循环组件支撑LightningOptimizer相关测试见 tests/tests_pytorch/core/test_lightning_optimizer.pyFabric 的入口实现在 src/lightning/fabric/fabric.py仓库提供了完整的用 Fabric 自己写 Trainer示例examples/fabric/build_your_own_trainer/trainer.py 与 examples/fabric/build_your_own_trainer/run.py对应文档见 docs/source-fabric/。Level 17启用高级 CheckpointEnable composable or cloud based checkpoints.官方入口 docs/source-pytorch/levels/advanced_level_18.rst主题包括可组合 checkpoint把模型状态按需拆分/合并便于跨平台复用与云端 checkpoint直接读写远程文件系统。源码佐证checkpoint 的保存/加载核心见 docs/source-pytorch/common/checkpointing_advanced.rstTorch 原生保存机制的兼容性测试见 tests/tests_pytorch/checkpointing/test_torch_saving.pycheckpoint 内容合并consolidate工具及其测试见 tests/tests_pytorch/utilities/test_consolidate_checkpoint.py。Level 18精通 TPUMaster TPUs and run on cloud TPUs.官方入口 docs/source-pytorch/levels/advanced_level_20.rst覆盖 TPU 上的精度、性能与调优专题。源码佐证TPU/XLA 相关加速器与策略见 src/lightning/pytorch/accelerators/ 与 src/lightning/pytorch/strategies/ 中的 XLA 实现专题文档见 docs/source-pytorch/accelerators/tpu_advanced.rst测试见 tests/tests_pytorch/accelerators/test_xla.py。历史遗留的 TPU 实现被移入 src/lightning/pytorch/_graveyard/对应测试在 tests/tests_pytorch/graveyard/。Level 19训练十亿参数级模型Scale GPU training to models with billions of parameters.官方入口 docs/source-pytorch/levels/advanced_level_21.rstScale with distributed strategies学习不同分布式策略对模型参数量上限的影响参考 docs/source-pytorch/accelerators/gpu_intermediate.rst。Train models with billions of parameters在 GPU 上用FSDP、张量并行TP或 DeepSpeed把模型规模推到十亿参数级参考 docs/source-pytorch/advanced/model_parallel/index.rst。源码佐证三大并行策略的实现与文档一一对应——docs/source-pytorch/advanced/model_parallel/fsdp.rst、docs/source-pytorch/advanced/model_parallel/deepspeed.rst、docs/source-pytorch/advanced/model_parallel/tp.rst对应测试见 tests/tests_pytorch/strategies/test_fsdp.py 与 tests/tests_pytorch/strategies/test_deepspeed.py仓库还提供了开箱即用的张量并行示例 examples/pytorch/tensor_parallel/train.py配套 model.py、parallelism.py。Expert skills扩展 Lightning 本身官方定位Customize and extend Lightning for things like custom hardware or distributed strategies.本层面向框架开发者教你改框架、接新硬件、写新策略。Level 21扩展 Lightning CLIExtend the functionality of the Lightning CLI.官方入口 docs/source-pytorch/levels/expert_level_23.rst源码树中该文件为expert_level_22.rst页内标题即 Level 21: Extend the Lightning CLICustomize configs for complex projects用 Registry 把复杂项目中的各组件连接起来参考 docs/source-pytorch/cli/lightning_cli_advanced_3.rst。Extend the Lightning CLI定制 CLI 行为子命令、自定义类型转换、save/load 配置参考 docs/source-pytorch/cli/lightning_cli_expert.rst。源码佐证CLI 扩展点LightningCLI子类化、save_config_callback等全部集中在 src/lightning/pytorch/cli.py仓库的 CLI 端到端测试含子命令与配置保存见 tests/tests_pytorch/test_cli.py。Level 22集成自定义集群Integrate a custom cluster into Lightning.官方入口 docs/source-pytorch/levels/expert_level_24.rst主题是把自有调度系统如自研作业调度器接入 Lightning通过实现自定义ClusterEnvironment让 Lightning 理解你的集群拓扑与进程间通信rank、world_size、master_addr/port的解析。源码佐证ClusterEnvironment抽象与其现成实现SLURM、Torchelastic、LSF 等位于 src/lightning/pytorch/plugins/environments/专家级集群文档见 docs/source-pytorch/clouds/cluster_expert.rst。Level 23打造自己的 ProfilerMake your own profiler.官方入口 docs/source-pytorch/tuning/profiler_expert.rst教你继承BaseProfiler实现自定义性能剖析器自定义事件采集、输出格式或与第三方工具集成。源码佐证Profiler 基类与内置实现Simple/PyTorch/Advanced/XLA见 src/lightning/pytorch/profilers/其接口契约测试见 tests/tests_pytorch/profilers/test_profiler.py。Level 24新增 Accelerator 或 StrategyIntegrate a new accelerator or distributed strategy.官方入口对应 docs/source-pytorch/levels/expert_level_25.html注当前源码树docs/source-pytorch/levels/中该页面源文件尚未同步实际内容请以扩展专题为准主题是让 Lightning 支持全新硬件如自定义 ASIC或全新分布式策略如新的通信范式。源码佐证扩展规范分别见 docs/source-pytorch/extensions/accelerator.rst 与 docs/source-pytorch/extensions/strategy.rst插件注册机制的实现与测试见 tests/tests_pytorch/accelerators/test_registry.py 与 tests/tests_pytorch/strategies/test_registry.py自定义策略的完整范式测试见 tests/tests_pytorch/strategies/test_custom_strategy.py。如何使用这套学习路线按角色定位起点首次接触 Lightning 的研究者/工程师从Level 1顺序推进到 Level 6先跑通训练—验证—保存—预测全流程有单机经验后再进入 Intermediate 层。按任务检索关卡需要部署时直接看 Level 11需要提速看 Level 12需要扩大参数量看 Level 19——每个关卡页都自带下一步的细分文档链接可直接跳转。文档与源码对照阅读每个关卡对应的源码、示例与测试路径已在本文各节列出例如 Level 1 对照 examples/pytorch/basics/autoencoder.pyLevel 19 对照 examples/pytorch/tensor_parallel/train.py形成文档概念 → 源码实现 → 测试验证的闭环学习。以 Fabric 作为补充路径若你偏好完全掌控训练循环Intermediate 之后的关卡尤其是 Level 16可与 examples/fabric/ 下的 Fabric 示例、docs/source-fabric/ 文档交叉学习两条路线共享同一套底层工程抽象。这套从 Level up 扩展出的分级体系的价值在于它把 Lightning 庞大的功能面训练循环、回调、数据模块、精度、并行策略、CLI、集群、扩展机制拆解成 24 个边界清晰、可独立学习的知识点并让每一级都能直接落在当前仓库可验证的源码与测试之上——这正是按需取用、逐步深入地掌握 PyTorch Lightning 的最短路径。【免费下载链接】pytorch-lightningPretrain, finetune ANY AI model of ANY size on 1 or 10,000 GPUs with zero code changes.项目地址: https://gitcode.com/gh_mirrors/py/pytorch-lightning创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表