pytorch runtime_error ai_generated true

运行时错误:GradScaler 的 unscale_() 遇到了 None 梯度。请确保 loss.backward() 和 optimizer.step() 被正确调用。

RuntimeError: GradScaler unscale_() encountered None gradient. Ensure loss.backward() and optimizer.step() are called correctly.

ID: pytorch/grad-scale-unscale-error

其他格式: JSON · Markdown 中文 · English
88%修复率
85%置信度
1证据数
2023-07-15首次发现

版本兼容性

版本状态引入弃用备注
torch>=1.10 active
torch<=2.5.1 active

根因分析

GradScaler 的 unscale_() 方法被调用时某个参数的梯度为 None,通常是因为该参数在前向传播中未被使用或被排除在梯度计算之外。

English

GradScaler's unscale_() method was called on a parameter whose gradient is None, typically because the parameter was not used in the forward pass or was excluded from gradient computation.

generic

官方文档

https://pytorch.org/docs/stable/amp.html#torch.cuda.amp.GradScaler.unscale_

解决方案

  1. Exclude parameters that are not used in the forward pass from the optimizer. For example, if a submodule is conditionally used, filter its parameters: optimizer = torch.optim.SGD([p for p in model.parameters() if p.requires_grad and p.grad is not None], lr=0.01)
  2. Use torch.no_grad() context or set requires_grad=False on parameters that are not part of the computation graph to avoid gradient computation.

无效尝试

常见但无效的做法:

  1. Setting all parameters to require grad=True 60% 失败

    If a parameter is truly unused in the forward pass, setting requires_grad=True will still result in a None gradient after backward, because no gradient flows through it.

  2. Calling unscale_() multiple times to clear None gradients 80% 失败

    The GradScaler's internal state does not allow multiple unscale_() calls per optimizer step; it raises a different error about double unscale.