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

- **ID:** `pytorch/grad-scale-unscale-error`
- **领域:** pytorch
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 88%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| torch>=1.10 | active | — | — |
| torch<=2.5.1 | active | — | — |

## 解决方案

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.
   ```

## 无效尝试

- **Setting all parameters to require grad=True** — 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. (60% 失败率)
- **Calling unscale_() multiple times to clear None gradients** — The GradScaler's internal state does not allow multiple unscale_() calls per optimizer step; it raises a different error about double unscale. (80% 失败率)
