# 运行时错误：试图第二次反向传播，但已保存的中间值已被释放。请在第一次调用backward时指定retain_graph=True。

- **ID:** `pytorch/strided-gradient-issue`
- **领域:** pytorch
- **类别:** autograd_error
- **验证级别:** ai_generated
- **修复率:** 95%

## 根因

在同一个计算图上两次调用backward()，而没有设置retain_graph=True，导致第一次反向传播后中间缓冲区被释放。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| torch>=1.0.0 | active | — | — |

## 解决方案

1. ```
   loss.backward(retain_graph=True)
# Then later
loss.backward()  # This now works
   ```
2. ```
   loss1.backward(retain_graph=True)
loss2.backward()
optimizer.step()
# Or compute both losses together
   ```

## 无效尝试

- **Setting requires_grad=False on all tensors** — This disables gradient computation entirely, which is not the intended fix. The error is about graph retention, not about needing gradients. (90% 失败率)
- **Calling zero_grad() between backward passes** — zero_grad() only resets gradients to zero, it does not retain the computation graph. The intermediate values are still freed after the first backward. (70% 失败率)
- **Recreating the model and optimizer after each backward** — This is extremely inefficient and does not address the root cause. The graph is still freed after the first backward unless retain_graph is set. (80% 失败率)
