# RuntimeError: MPS 后端不支持 float64，回退到 float32。请将张量显式转换为 float32。

- **ID:** `pytorch/mps-float64-cast-fallback`
- **领域:** pytorch
- **类别:** type_error
- **错误码:** `MPS_ERROR_UNSUPPORTED_DTYPE`
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

Apple Silicon 上的 Metal Performance Shaders (MPS) 后端不支持 float64（双精度）张量；任何涉及 float64 张量的操作会触发回退到 CPU 或导致错误，引起性能下降或崩溃。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| PyTorch 2.0.0 | active | — | — |
| PyTorch 2.1.0 | active | — | — |
| macOS 13 Ventura | active | — | — |
| macOS 14 Sonoma | active | — | — |
| Apple M1 | active | — | — |
| Apple M2 | active | — | — |
| Apple M3 | active | — | — |

## 解决方案

1. ```
   Cast all tensors to float32 explicitly before moving to MPS device: tensor = tensor.float().to('mps'). This ensures compatibility with MPS backend.
   ```
2. ```
   Set the default dtype to float32 at the start of the script: torch.set_default_dtype(torch.float32). This prevents accidental creation of float64 tensors from Python floats.
   ```
3. ```
   Use a custom wrapper function that checks dtype and casts if needed: def to_mps(tensor): return tensor.float().to('mps') if tensor.is_floating_point() else tensor.to('mps')
   ```

## 无效尝试

- **Set environment variable PYTORCH_MPS_HIGH_WATERMARK_RATIO=0.0 to disable MPS fallback** — This flag controls memory watermark, not dtype support. The float64 issue remains and will cause errors. (95% 失败率)
- **Use torch.set_default_dtype(torch.float64) to force double precision** — This makes the problem worse by creating more float64 tensors, increasing fallback frequency and memory usage. (90% 失败率)
- **Install PyTorch nightly build for better MPS support** — Nightly builds may have improvements but still do not support float64 on MPS as of current versions. (85% 失败率)
