PyTorch 中的累积梯度

https://stackoverflow.com/questions/62067400/understanding-accumulated-gradients-in-pytorch

有一个小的计算图,两次前向梯度累积的结果,可以看到梯度是严格相等的。


代码:

复制代码
import numpy as np
import torch


class ExampleLinear(torch.nn.Module):

    def __init__(self):
        super().__init__()
        # Initialize the weight at 1
        self.weight = torch.nn.Parameter(torch.Tensor([1]).float(),
                                         requires_grad=True)

    def forward(self, x):
        return self.weight * x


model = ExampleLinear()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)


def calculate_loss(x: torch.Tensor) -> torch.Tensor:
    y = 2 * x
    y_hat = model(x)
    temp1 = (y - y_hat)
    temp2 = temp1**2
    return temp2


# With mulitple batches of size 1
batches = [torch.tensor([4.0]), torch.tensor([2.0])]

optimizer.zero_grad()
for i, batch in enumerate(batches):
    # The loss needs to be scaled, because the mean should be taken across the whole
    # dataset, which requires the loss to be divided by the number of batches.
    temp2 = calculate_loss(batch)
    loss = temp2 / len(batches)
    loss.backward()
    print(f"Batch size 1 (batch {i}) - grad: {model.weight.grad}")
    print(f"Batch size 1 (batch {i}) - weight: {model.weight}")
    print("="*50)

# Updating the model only after all batches
optimizer.step()
print(f"Batch size 1 (final) - grad: {model.weight.grad}")
print(f"Batch size 1 (final) - weight: {model.weight}")

运行结果

复制代码
Batch size 1 (batch 0) - grad: tensor([-16.])
Batch size 1 (batch 0) - weight: Parameter containing:
tensor([1.], requires_grad=True)
==================================================
Batch size 1 (batch 1) - grad: tensor([-20.])
Batch size 1 (batch 1) - weight: Parameter containing:
tensor([1.], requires_grad=True)
==================================================
Batch size 1 (final) - grad: tensor([-20.])
Batch size 1 (final) - weight: Parameter containing:
tensor([1.2000], requires_grad=True)

然而,如果训练一个真实的模型,结果没有这么理想,比如训练一个bert,𝐵=8,𝑁=1:没有梯度累积(累积每一步),

𝐵=2,𝑁=4:梯度累积(每 4 步累积一次)

使用带有梯度累积的 Batch Normalization 通常效果不佳,原因很简单,因为 BatchNorm 统计数据无法累积。更好的解决方案是使用 Group Normalization 而不是 BatchNorm。

https://ai.stackexchange.com/questions/21972/what-is-the-relationship-between-gradient-accumulation-and-batch-size

相关推荐
兔兔爱学习兔兔爱学习9 分钟前
读论文alexnet:ImageNet Classification with Deep Convolutional Neural Networks
人工智能
Johny_Zhao33 分钟前
VMware workstation 部署微软MDT系统
网络·人工智能·信息安全·微软·云计算·系统运维·mdt
亚里随笔1 小时前
AlphaEvolve:LLM驱动的算法进化革命与科学发现新范式
人工智能·算法·llm·大语言模型
Panesle1 小时前
基于对抗性后训练的快速文本到音频生成:stable-audio-open-small 模型论文速读
人工智能·机器学习·音视频
Linux猿1 小时前
华为云Flexus+DeepSeek征文|DeepSeek-V3/R1商用服务体验
人工智能·华为云·华为云征文·modelartsstudio·flexus+deepseek·deepseek-v3/r1
攻城狮7号1 小时前
一文解析13大神经网络算法模型架构
人工智能·深度学习·神经网络·机器学习
羽凌寒1 小时前
动态范围调整(SEF算法实现)
人工智能·深度学习·计算机视觉
zyhomepage2 小时前
科技的成就(六十八)
开发语言·人工智能·科技·算法·内容运营
数据库安全2 小时前
美创科技针对《银行保险机构数据安全管理办法》解读
大数据·人工智能·产品运营
漫谈网络2 小时前
Python logging模块使用指南
python·logging·日志