当前位置: 首页 > news >正文

PyTorch 中的累积梯度

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

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

在这里插入图片描述
在这里插入图片描述

代码:

import numpy as np
import torchclass ExampleLinear(torch.nn.Module):def __init__(self):super().__init__()# Initialize the weight at 1self.weight = torch.nn.Parameter(torch.Tensor([1]).float(),requires_grad=True)def forward(self, x):return self.weight * xmodel = ExampleLinear()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)def calculate_loss(x: torch.Tensor) -> torch.Tensor:y = 2 * xy_hat = model(x)temp1 = (y - y_hat)temp2 = temp1**2return 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

http://www.lryc.cn/news/106780.html

相关文章:

  • 【面试精品】运维工程师需要具备的核心能力有哪些?
  • 微服务实战项目-学成在线-选课学习(支付与学习中心)模块
  • postman和jmeter的区别何在?
  • maven安装(windows)
  • 自学安全卷不动,是放弃还是继续?
  • Django实现音乐网站 ⑶
  • (13) Qt事件系统(two)
  • PHP的知识概要
  • JSON格式Python,Java,PHP等封装根据商品ID获取快手商品详情数据方法
  • 【ASP.NET MVC】MYSQL安装配置(4)
  • 前端框架学习-Vue(二)
  • sublime配置less的一些坑(1)
  • 解码“平台工程”,VMware 有备而来
  • 2023年第四届华数杯数学建模A题B题C题D题思路代码分析
  • java版直播商城平台规划及常见的营销模式+电商源码+小程序+三级分销+二次开发 bbc
  • windows物理机 上安装centos ,ubuntu,等多个操作系统的要点
  • FSDirectory 与 RAMDirectory
  • 小程序开发:开发框架与工具的使用指南
  • 【LeetCode】探索杨辉三角模型
  • Qt 中引入ffmpeg 动态库
  • 工程师是怎样对待开源 qt
  • Maven中Servlet的坐标为什么要添加<scope>provided</scope>
  • 联发科CEO:未获准向华为供货,换机潮已过去,手机需求不会更差
  • 2023年DevOps和云趋势报告!
  • 怎么学习CSS相关技术知识? - 易智编译EaseEditing
  • Qt 2. QSerialPortInfo显示串口信息
  • linux or mac 查看进程的pid和占有的端口
  • 8.2Jmeter5.1:察看结果树的响应结果乱码
  • vscode 快捷键
  • Python pillow扩展库图像编程