快速结论:该报错发生在 Apple Silicon Mac 上使用 MPS 后端运行 RT-DETRv2 模型推理时,根本原因是模型内部的 build_2d_sinusoidal_position_embedding 函数硬编码了 torch.float64,而 MPS 不支持 float64。优先排查该函数内部的所有张量创建是否都使用了传入的 dtype 参数。
适用环境:transformers 5.9.0、macOS(Apple Silicon)、Python 3.13、启用 MPS 的 PyTorch 构建、docling 2.95.0、docling-ibm-models 3.13.2。推测 CUDA 环境下不会触发此问题。
最快修复方案:暂无官方发布的一步修复版本;可优先尝试将 build_2d_sinusoidal_position_embedding 函数体内所有 torch.float64 替换为传入的 dtype 参数(默认 torch.float32)。
注意事项:该函数在 modeling_vit_mae.py 中是源码,并在生成的 modeling_rt_detr.py 和 modeling_rt_detr_v2.py 中被内联,需要同步修改三处文件;如果使用生成流程,需修复源码后重新生成。
问题场景
在 Apple Silicon Mac 上通过 docling → docling-ibm-models → transformers 链路运行 RTDetrV2ForObjectDetection 推理时触发。可直接用 PekingU/rtdetr_v2_r18vd 模型复现,崩溃点位于 modeling_rt_detr_v2.py 第 988 行的 build_2d_sinusoidal_position_embedding 函数。
报错原文
TypeError: Cannot convert a MPS Tensor to float64 dtype as the MPS framework doesn't support float64. Please use float32 instead.
原因分析
可能原因:build_2d_sinusoidal_position_embedding 函数虽然接受 dtype 参数(默认 torch.float32),但函数体内所有张量创建都硬编码为 torch.float64,完全忽略了传入的 dtype。Apple 的 MPS 框架不实现 float64,因此在创建第一个 float64 张量时(第 988 行的 torch.arange)就会崩溃。CUDA 支持 float64,因此该问题在非 Mac 平台上不易暴露。
环境排查
- 确认 transformers 版本是否为 5.9.0 或包含
float64硬编码的版本 - 确认是否在 Apple Silicon Mac 上使用 MPS 后端
- 确认 Python 版本(Issue 中为 3.13)
- 确认 PyTorch 是否为启用 MPS 的构建
- 检查
modeling_rt_detr_v2.py中build_2d_sinusoidal_position_embedding函数体是否硬编码torch.float64
解决步骤
- 在
build_2d_sinusoidal_position_embedding函数体内,将所有torch.arange(pos_dim, dtype=torch.float64, ...)替换为torch.arange(pos_dim, dtype=dtype, ...) - 将
grid_h和grid_w的创建同样改为使用dtype:torch.arange(height, dtype=dtype, device=device)和torch.arange(width, dtype=dtype, device=device) - 将
torch.cat中的torch.zeros(1, embed_dim, dtype=torch.float64, ...)改为dtype=dtype - 同步修改
modeling_vit_mae.py(源码)、modeling_rt_detr.py和modeling_rt_detr_v2.py(生成文件)三处;或修复源码后重新生成生成文件 - 更新函数 docstring,移除“frequency arithmetic uses float64 internally”的错误说明
验证方法
修复后,在 Apple Silicon Mac 上使用 MPS 设备重新运行 RT-DETRv2 推理。Issue 作者验证结果:修复前崩溃,修复后得到 logits shape: torch.Size([1, 300, 80]),推理正常完成。完整测试套件本地运行结果为 95 个测试全部通过。
参考来源
huggingface/transformers #46159
AI 工具推荐
想把多个 AI 模型放在一个入口?
GamsGo AI 集成 ChatGPT、DeepSeek、Gemini、Claude、Midjourney、Veo 等常用模型,适合写作、绘图、视频和日常 AI 工作流。
推广链接:通过此链接购买,我可能获得佣金,不影响你的价格。
这个方案解决了吗?
可以继续搜索完整报错,或查看同一工具的其他排查指南。


