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
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.
官方文档
https://pytorch.org/docs/stable/amp.html#torch.cuda.amp.GradScaler.unscale_解决方案
-
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)
-
Use torch.no_grad() context or set requires_grad=False on parameters that are not part of the computation graph to avoid gradient computation.
无效尝试
常见但无效的做法:
-
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.
-
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.