# RuntimeError: 尝试第二次反向传播，但缓冲已被释放。请在第一次调用 backward 时指定 retain_graph=True。

- **ID:** `pytorch/grad-accumulation-required-grad-false`
- **领域:** pytorch
- **类别:** autograd_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

在同一个计算图上第二次调用 backward() 而未设置 retain_graph=True，常见于梯度累积循环中重复使用计算图时。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 1.10 | active | — | — |
| 1.11 | active | — | — |
| 1.12 | active | — | — |
| 1.13 | active | — | — |
| 2.0 | active | — | — |
| 2.1 | active | — | — |
| 2.2 | active | — | — |
| 2.3 | active | — | — |

## 解决方案

1. ```
   Set retain_graph=True only on the first backward call when accumulating gradients over multiple steps: loss.backward(retain_graph=True) for all but the last step, then loss.backward() on the final step.
   ```
2. ```
   Use gradient accumulation with model.zero_grad() and loss.backward() only once per accumulation cycle, ensuring the graph is freed after each step.
   ```

## 无效尝试

- **** — Adding retain_graph=True every time hides the real issue of memory growth and can cause OOM. (40% 失败率)
- **** — This only works if the graph is re-used; if not, it just defers the error. (50% 失败率)
