# 运行时错误：半精度期望 float16 类型，但得到 float32

- **ID:** `pytorch/amp-gradscaler-dtype`
- **领域:** pytorch
- **类别:** type_error
- **验证级别:** ai_generated
- **修复率:** 78%

## 根因

将类型不正确的张量（float32 而非 float16）传递给了期望半精度输入的操作，例如在 torch.cuda.amp.autocast 和 GradScaler 中使用时。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| torch>=2.0.0 | active | — | — |
| CUDA>=11.8 | active | — | — |

## 解决方案

1. ```
   Explicitly cast inputs to half precision before the operation, or ensure the model uses half precision layers correctly with GradScaler.
   ```
2. ```
   Check for custom operations that do not support autocast and manually cast inputs to float16.
   ```

## 无效尝试

- **** — Disabling autocast entirely removes the error but defeats the purpose of mixed precision training. (60% 失败率)
- **** — Manually converting all tensors to float16 can cause numerical instability and does not fix the root cause of incorrect dtype propagation. (70% 失败率)
