# 梯度累积

**梯度累积**是一种训练技术：在单次优化器步进之前，先计算若干个小微批次的梯度并求和（再取平均），从而在无法一次性容纳该批量的硬件上模拟出更大的有效批量大小。优化步进基于累积梯度的平均值而非总和进行；对于等权重的微批次，且在其他依赖批量的效应不存在时，无论累积步数多少，这都会给出相同的更新。<sup>[1](https://nanotron-ultrascale-playbook.static.hf.space/index.html?section=gradient_accumulation)</sup>

| 关键事实 | 详情 |
|---|---|
| 计算内容 | 每个微批次进行前向与反向传播；梯度在优化器步进前被累积并取平均，对于等权重微批次，这使得更新与累积步数无关<sup>[1](https://nanotron-ultrascale-playbook.static.hf.space/index.html?section=gradient_accumulation)</sup> |
| 有效批量大小 | 单设备上，有效批量大小 = 微批次大小 × 累积步数；在 P 个设备的 DDP 下则为 P × N × K<sup>[1](https://nanotron-ultrascale-playbook.static.hf.space/index.html?section=gradient_accumulation)</sup><sup> • </sup><sup>[2](https://lightning.ai/docs/pytorch/stable/advanced/training_tricks.html)</sup> |
| 节省的内存 | 仅激活内存；模型、其梯度及优化器状态不变<sup>[3](https://self-supervised.cs.jhu.edu/fa2026/files/readings/07.training-practice.html)</sup> |
| 计算成本 | 总 FLOPs 不变，但每步多次串行前向/反向传播会拖慢训练<sup>[4](https://export.arxiv.org/pdf/1904.10631)</sup><sup> • </sup><sup>[1](https://nanotron-ultrascale-playbook.static.hf.space/index.html?section=gradient_accumulation)</sup> |
| 主要注意事项 | 批归一化统计量、随机失活掩码以及变长序列上的损失归一化会破坏与真实大批次的精确等价性<sup>[5](https://jhc.sjtu.edu.cn/~bjiang/papers/Huang_CCGrid2023_GA.pdf)</sup><sup> • </sup><sup>[6](https://huggingface.co/blog/gradient_accumulation)</sup> |
| 实测精度代价 | 在固定全局批量大小为 256 时，ResNet101 在 32 个累积步下精度损失 0.31%；BERT-Large 的 F1 未受显著影响<sup>[5](https://jhc.sjtu.edu.cn/~bjiang/papers/Huang_CCGrid2023_GA.pdf)</sup> |
| 2025 年变化 | Hugging Face 于 2025 年 4 月修复了一个长期存在的损失归一化缺陷，使默认损失函数能正确处理累积<sup>[6](https://huggingface.co/blog/gradient_accumulation)</sup> |

## 什么是梯度累积

当期望的批量大小无法放入 GPU 内存时，该批量会被拆分为微批次。每个微批次各自进行前向与反向传播，产生的梯度被加到一个聚合梯度向量上；优化器步进被推迟到所有微批次处理完毕之后。如果期望的批量大小 256 放不下而 64 放得下，那么在四个大小为 64 的批次上累积梯度，所得到的梯度等价于单个大小为 256 的批次。<sup>[7](https://lightning.ai/pages/blog/gradient-accumulation/)</sup><sup> • </sup><sup>[8](https://arxiv.org/html/2301.02691)</sup>

相对于一次性处理有效批量，该技术减少了激活内存，因为激活内存随批量大小增长，而同一时间只存在一个微批次的激活。<sup>[1](https://nanotron-ultrascale-playbook.static.hf.space/index.html?section=gradient_accumulation)</sup>

## 工作原理

机制很简单，但有几个细节决定正确性：

1. 对每个微批次，执行前向传播、计算损失并执行反向传播。梯度以累加方式存入参数的 `.grad` 缓冲区。
2. 将每个微批次的损失除以累积步数（或按词元总数归一化，见下文），使最终梯度是平均值而非总和。<sup>[1](https://nanotron-ultrascale-playbook.static.hf.space/index.html?section=gradient_accumulation)</sup>
3. 在最后一个微批次之后，调用优化器步进并将梯度清零。

一个常见的实现错误是将跨微批次的、与计算图相连的损失求和，只在最后调用一次反向传播；这会保留每一个计算图，从而抵消内存收益。反向传播必须按微批次调用。<sup>[3](https://self-supervised.cs.jhu.edu/fa2026/files/readings/07.training-practice.html)</sup>

在分布式数据并行训练中，全归约通常在每次反向传播后触发。有 N 个累积步时，只需在最后一次反向传播之后、优化器步进之前进行全归约；PyTorch 的 `no_sync()` 上下文管理器会禁用梯度同步，应包裹前 N−1 次迭代。<sup>[9](https://docs.pytorch.org/tutorials/recipes/recipes/tuning%5Fguide.html)</sup> 若不使用它，朴素的累积会在每次反向传播后触发全归约，这是次优的。<sup>[1](https://nanotron-ultrascale-playbook.static.hf.space/index.html?section=gradient_accumulation)</sup>

## 有效批量大小与配置

支配关系为：

\[ \text{gbs} = \text{mbs} \times \text{grad\_acc} \]

其中全局批量大小为微批次大小乘以累积步数。<sup>[1](https://nanotron-ultrascale-playbook.static.hf.space/index.html?section=gradient_accumulation)</sup> 在 P 个设备的 DistributedDataParallel 下，每个设备独立累积并在 `optimizer.step()` 时同步，因此有效批量大小为 P × N × K；在较旧的数据并行下（它将每个批次拆分到各设备），则为 N × K。<sup>[2](https://lightning.ai/docs/pytorch/stable/advanced/training_tricks.html)</sup>

一个具体的规模参考：在单张 80 GB H100 上以约 4K 上下文训练 7B 模型时，微批次 4 到 8 个序列通常是上限，而 32 到 256 个累积步可达到现代微调配方中使用的 256 到 1024 个样本的有效批量。<sup>[10](https://zeroentropy.dev/concepts/gradient-accumulation/)</sup>

## 内存与吞吐量：数据说话

累积只节省激活内存。模型参数、梯度缓冲区和优化器状态均不受影响：梯度与参数大小相同（G = P），Adam 的状态需要两倍于参数数量（O = 2P）。<sup>[3](https://self-supervised.cs.jhu.edu/fa2026/files/readings/07.training-practice.html)</sup><sup> • </sup><sup>[11](https://docs.pytorch.org/tutorials/intermediate/optimizer_step_in_backward_tutorial.html)</sup>

计算成本是延迟成本，而非 FLOPs 成本。微批处理以降低并行度换取内存减少，但不改变所需的总 FLOPs。<sup>[4](https://export.arxiv.org/pdf/1904.10631)</sup> 实践中，每次优化步进中多次连续的前向/反向传播会增加计算开销并拖慢训练，且权重更新频率降低。<sup>[1](https://nanotron-ultrascale-playbook.static.hf.space/index.html?section=gradient_accumulation)</sup><sup> • </sup><sup>[7](https://lightning.ai/pages/blog/gradient-accumulation/)</sup> 在多设备设置中，朴素的串行累积还会将梯度归约集中在最后一个微批次，损害通信重叠；有人提出了分层累积方案以将归约分散到各微批次。<sup>[12](https://ar5iv.labs.arxiv.org/html/2106.02679)</sup>

## 等价性与数值注意事项

**等价之处。** 在无批归一化的模型中，当损失被一致地归一化时，带梯度累积的微批处理可在数学上等价于标准训练；它对 DC-Transformer 未造成精度下降，在 FP16 实验中，模拟微批处理与真实微批处理之间的差异落在很小的界限内。<sup>[4](https://export.arxiv.org/pdf/1904.10631)</sup>

**不等价之处。** 若干机制会破坏精确等价性：

- 批归一化基于当前微批次而非概念上的完整批次计算统计量，因此较小的微批次给出的总体估计不够准确。以低至 10 的微批次大小训练在 WideResNet 上未造成精度损失，但统计量确实不同。<sup>[4](https://export.arxiv.org/pdf/1904.10631)</sup><sup> • </sup><sup>[5](https://jhc.sjtu.edu.cn/~bjiang/papers/Huang_CCGrid2023_GA.pdf)</sup> 将依赖批次的归一化替换为实例归一化或组归一化可缓解退化；[层归一化](https://www.edgepedia.org/zh/layer-normalization)是逐词元的，因此其统计量不受微批次大小影响。<sup>[5](https://jhc.sjtu.edu.cn/~bjiang/papers/Huang_CCGrid2023_GA.pdf)</sup><sup> • </sup><sup>[10](https://zeroentropy.dev/concepts/gradient-accumulation/)</sup>
- 随机失活掩码和浮点运算顺序在单个大批次与多个微批次之间存在差异，产生数值差异。<sup>[3](https://self-supervised.cs.jhu.edu/fa2026/files/readings/07.training-practice.html)</sup>
- 变长序列的损失归一化是影响最大的问题。对于因果语言模型训练这类词元级任务，正确的损失是累积步内所有批次的总损失除以非填充词元的总数，而非各批次平均损失的均值。[Hugging Face](https://www.edgepedia.org/zh/hugging-face) 发现，在开启和关闭累积的两次运行之间损失不一致，追溯到此归一化问题，并于 2025 年 4 月修复，使默认损失函数自动处理累积，并在 Trainer 中为自定义损失处理提供了 API。<sup>[6](https://huggingface.co/blog/gradient_accumulation)</sup> 同样的问题也出现在跨 GPU 场景中，GPU 不知道每一步其他 GPU 看到了多少样本；跨输入进行汇集可修复此问题，但会在每个累积步增加一次通信，相比单次反向归约大约使通信成本翻倍。<sup>[13](https://muellerzr.github.io/blog/gradient_accumulation_part2.html)</sup>
- 数值漂移随累积步数增长；FP32 累加器和 Kahan 求和可缓解但在极大步数下不能消除舍入误差。<sup>[14](https://marovi.ai/Gradient_Accumulation)</sup>

## 混合精度与损失缩放

使用混合精度时，累积缓冲区应保持为 FP32，与优化器的 FP32 主权重一致，而前向和反向传播以 FP16 或 BF16 运行；每个微批次的低精度梯度被即时上转型并累加，损失缩放按微批次应用并在优化器步进前反缩放。<sup>[10](https://zeroentropy.dev/concepts/gradient-accumulation/)</sup><sup> • </sup><sup>[14](https://marovi.ai/Gradient_Accumulation)</sup>

历史上的 FP16 陷阱：必须先将损失除以累积步数，再进行缩放，否则缩放后的梯度在逐微批次反向传播时会溢出。使用 BF16 则无需损失缩放，也不存在此问题。<sup>[10](https://zeroentropy.dev/concepts/gradient-accumulation/)</sup>

## 学习率与优化器交互

线性缩放规则——按批量大小成比例调整学习率——起源于更早的工作，但其经验极限并未被充分理解，在推广该规则的 ImageNet 研究发表时也未被广泛采用。<sup>[15](https://arxiv.org/pdf/1706.02677)</sup> 它与累积的交互直接相关：固定学习率而改变微批次大小（违反该规则）可导致高达 4% 的精度损失。<sup>[5](https://jhc.sjtu.edu.cn/~bjiang/papers/Huang_CCGrid2023_GA.pdf)</sup>

调度也会偏移。每轮的优化器步数按累积因子 k 缩减，因此以步数表示的预热时长必须调整。<sup>[14](https://marovi.ai/Gradient_Accumulation)</sup> 对于无累积的小批量训练，一项 NeurIPS 2025 研究提出在跨批量大小缩放时，将 Adam 二阶矩的半衰期固定在词元数而非步数上，并表明小批量结合 Adafactor 这类小状态优化器，可在与 LoRA 相近的内存占用下达到全量微调的性能。<sup>[16](https://proceedings.neurips.cc/paper_files/paper/2025/file/dabfbf500318462382aa70a95466ad85-Paper-Conference.pdf)</sup>

## 与其他节省内存技术的比较

- 激活（梯度）检查点保存选定的边界张量并在反向传播时重算中间结果，将激活内存降至层激活和检查点状态；一项被引用的方法报告计算量增加 33%。它可与累积组合使用，后者以额外计算换取更少的保存激活。<sup>[12](https://ar5iv.labs.arxiv.org/html/2106.02679)</sup><sup> • </sup><sup>[3](https://self-supervised.cs.jhu.edu/fa2026/files/readings/07.training-practice.html)</sup>
- ZeRO/FSDP 分片将参数、梯度和优化器状态分区到各设备。当分片方案释放累积需要保留的梯度时，标准累积可能与梯度内存缩减不兼容；Adam 累积（AdamA）将梯度直接整合进优化器状态，使其可在使用后立即释放。在 transformer 模型上，AdamA 相比梯度累积实现了高达 23% 的内存缩减，吞吐量退化低于 2%；在 DGX A100 上对 BERT-Large 相比梯度累积多节省 1.6 GB，且与步数无关；与 ZeRO-DP 结合后，相比 PyTorch 和 [DeepSpeed](https://www.edgepedia.org/zh/deepspeed) 基线可容纳 1.26 倍到 3.14 倍更大的模型；在 8 张 A100 GPU 上的组合吞吐量从 1401 降至 1337 样本/秒，约 5%。<sup>[17](https://ar5iv.labs.arxiv.org/html/2305.19982)</sup>
- 流水线并行依赖累积：累积对流水线并行至关重要，且常与其他并行技术一起使用，因为流水线并行允许微批次并行处理。<sup>[8](https://arxiv.org/html/2301.02691)</sup><sup> • </sup><sup>[12](https://ar5iv.labs.arxiv.org/html/2106.02679)</sup>
- 将优化器融合进反向传播可消除持有完整梯度缓冲区的需要，但主要针对梯度内存，在权重很小时（如 LoRA）收益较小。<sup>[11](https://docs.pytorch.org/tutorials/intermediate/optimizer_step_in_backward_tutorial.html)</sup>

## 框架支持与陷阱

- **PyTorch DDP**：仅在最后一次反向传播后全归约；在前 N−1 次迭代上使用 `no_sync()`。<sup>[9](https://docs.pytorch.org/tutorials/recipes/recipes/tuning%5Fguide.html)</sup>
- **DeepSpeed**：在 `gradient_accumulation_steps` 个微批次上累积梯度，在优化器步进前取平均；默认情况下 `backward()` 按配置的步数缩放损失和梯度，在非托管模式下反向次数可变时，用户必须传入 `scale_wrt_gas=False` 并自行对损失取平均。<sup>[18](https://deepspeed.readthedocs.io/en/stable/training.html)</sup>
- **Hugging Face Trainer/Accelerate**：自 2025 年 4 月起，默认损失函数自动处理累积，`num_items_in_batch` 实现了先求和再除以词元总数的归一化。<sup>[6](https://huggingface.co/blog/gradient_accumulation)</sup><sup> • </sup><sup>[13](https://muellerzr.github.io/blog/gradient_accumulation_part2.html)</sup>
- **FSDP**：`no_sync` 上下文管理器需要额外内存；在 8 张 A100-80GB GPU 上微调 Mixtral（47B 参数）时，即使 `gradient_accumulation_steps=2` 且启用 `no_sync` 也会内存不足。Accelerate 建议在内存密集的 FSDP 场景中，将 GradientAccumulationPlugin 中的 `sync_each_batch` 设为 True。<sup>[19](https://huggingface.co/docs/accelerate/concept_guides/gradient_synchronization)</sup>

## 争议与近期进展

两种可信立场在累积是否值得使用上存在分歧。一项 2023 年的测量研究发现，在固定全局批量大小为 256 时，ResNet101 在 32 个累积步下精度仅下降 0.31%，BERT-Large 的 F1 未受显著影响；该研究还认为，此前报道的更多累积步导致更高精度损失，更可能源于同步方案差异（同步与异步）而非累积本身。<sup>[5](https://jhc.sjtu.edu.cn/~bjiang/papers/Huang_CCGrid2023_GA.pdf)</sup> 一项 NeurIPS 2025 研究对语言模型得出了相反的实际结论：小至 1 的批量大小可稳定训练，对超参数选择始终更稳健，且每 FLOP 性能等于或优于更大批量，因此作者建议使用能最大化吞吐量的最小批量大小，并劝告大多数从业者不要使用梯度累积，仅在多设备多模型副本训练时才建议使用。<sup>[16](https://proceedings.neurips.cc/paper_files/paper/2025/file/dabfbf500318462382aa70a95466ad85-Paper-Conference.pdf)</sup> 两种立场部分可调和：测量研究固定全局批量，仅改变其拆分方式，而 2025 年研究质疑的是大有效批量是否根本必要。

自 2023 年以来，工具已发生实质性变化：2025 年 4 月 Hugging Face 的损失归一化修复解决了一个缺陷，即在开启和关闭累积的两次运行之间损失不一致；<sup>[6](https://huggingface.co/blog/gradient_accumulation)</sup> 针对 FSDP 的专门指南现已记录了 `no_sync` 的内存问题及 `sync_each_batch` 替代方案。<sup>[19](https://huggingface.co/docs/accelerate/concept_guides/gradient_synchronization)</sup>

## References

1. [The Ultra-Scale Playbook: Training LLMs on GPU Clusters (Hugging Face/Nanotron)](https://nanotron-ultrascale-playbook.static.hf.space/index.html?section=gradient_accumulation)
2. [Effective Training Techniques, PyTorch Lightning](https://lightning.ai/docs/pytorch/stable/advanced/training_tricks.html)
3. [Handout #7: Batching and Training Memory, CS 601.471/671, Johns Hopkins](https://self-supervised.cs.jhu.edu/fa2026/files/readings/07.training-practice.html)
4. [Low-Memory Neural Network Training (Dettmers & Zettlemoyer, 2019)](https://export.arxiv.org/pdf/1904.10631)
5. [Measuring the Impact of Gradient Accumulation on Training (CCGrid 2023)](https://jhc.sjtu.edu.cn/~bjiang/papers/Huang_CCGrid2023_GA.pdf)
6. [Fixing Gradient Accumulation (Hugging Face engineering blog, 2025)](https://huggingface.co/blog/gradient_accumulation)
7. [Finetuning LLMs on a Single GPU Using Gradient Accumulation (Lightning AI)](https://lightning.ai/pages/blog/gradient-accumulation/)
8. [Systems for Parallel and Distributed Large-Model Deep Learning Training](https://arxiv.org/html/2301.02691)
9. [Performance Tuning Guide, PyTorch documentation](https://docs.pytorch.org/tutorials/recipes/recipes/tuning%5Fguide.html)
10. [Gradient accumulation: simulating large batches on constrained GPUs (ZeroEntropy)](https://zeroentropy.dev/concepts/gradient-accumulation/)
11. [How to save memory by fusing the optimizer step into the backward pass, PyTorch](https://docs.pytorch.org/tutorials/intermediate/optimizer_step_in_backward_tutorial.html)
12. [Layered gradient accumulation and modular pipeline parallelism](https://ar5iv.labs.arxiv.org/html/2106.02679)
13. [PyTorch, Gradient Accumulation, and the dreaded lack of reproducability (Zach Mueller)](https://muellerzr.github.io/blog/gradient_accumulation_part2.html)
14. [Gradient Accumulation (Marovi AI)](https://marovi.ai/Gradient_Accumulation)
15. [Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour (Goyal et al., 2017)](https://arxiv.org/pdf/1706.02677)
16. [Small Batch Size Training for Language Models: When Vanilla SGD Works, and Why Gradient Accumulation Is Wasteful (NeurIPS 2025)](https://proceedings.neurips.cc/paper_files/paper/2025/file/dabfbf500318462382aa70a95466ad85-Paper-Conference.pdf)
17. [Adam Accumulation to Reduce Memory Footprints of both Activations and Gradients for Large-scale DNN Training](https://ar5iv.labs.arxiv.org/html/2305.19982)
18. [DeepSpeed Training API documentation](https://deepspeed.readthedocs.io/en/stable/training.html)
19. [Gradient synchronization, Hugging Face Accelerate documentation](https://huggingface.co/docs/accelerate/concept_guides/gradient_synchronization)

---
*Initially written Oct 15, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 现代人工智能：基础模型、生成式人工智能与人工智能产业 › Foundation-model methods and training

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/gradient-accumulation

English original: https://www.edgepedia.org/gradient-accumulation
