Closed
[Bug]: PyTorch 2.13 以下版本 torch.random.fork_rng 默认使用 CUDA 导致 NPU 场景执行失败 #5247
JesseAdd on  Sep 29Closed at  Oct 8
Jesse
JesseCollaborators
Sep 29 Create

在提交新问题之前,请确保您已经在社区中搜索过相关问题,并使用了社区中提供的资源/工具后,仍未找到满意的解决方式。

⚠️ 安全信息提醒:请仔细检查提供的文本内容,确保其不包含敏感数据信息,包括但不限于:

  • API 令牌或密钥
  • 密码或身份验证凭证
  • 私有网址或接口地址
  • 个人或机密数据
  • ...

在分享配置信息或代码示例时,请将敏感信息脱敏处理,或使用 <TOKEN> 等占位符替代原有内容。

环境信息

PyTorch 2.12 及以下版本

🐛 问题描述

问题分析

PyTorch 2.13 以下版本中,torch.random.fork_rng 未指定 device_type 时默认使用 CUDA。

在仅安装 CPU 版 PyTorch 和 torch_npu 的 NPU 环境中,调用方未显式传入 device_type="npu" 时,接口会错误进入 CUDA RNG 初始化流程,可能触发 Torch not compiled with CUDA enabled 异常。

其根因是 fork_rng 不会根据 devices 参数推断设备类型,而是直接根据 device_type 获取对应的设备模块。社区2.13/2.14版本上已修复该问题,通过torch.accelerator.current_accelerator()获取设备信息,import torch_npu时会注册type为npu

def fork_rng(
    devices=None,
    enabled=True,
    _caller="fork_rng",
    _devices_kw="devices",
    device_type=None,
) -> Generator:

    ...
    
    acc = torch.accelerator.current_accelerator()
    # Default to cuda instead of CPU since CPU rng is always forked
    device_type = device_type or (acc.type if acc is not None else "cuda")

修改方案

在 torch_npu 初始化过程中,对 PyTorch 2.13 以下版本的 torch.random.fork_rng 增加兼容性代理:

  1. 保存原始接口为 _original_fork_rng。
  2. 新增 _npu_fork_rng 代理函数。
  3. 未传入 device_type 或显式传入 None 时,默认设置为 npu。
  4. 显式指定其他设备类型时,保持用户传参和原有行为。
  5. PyTorch 2.13 及以上版本不应用该兼容性修改。

欢迎加入社区,感谢您对社区的贡献 🎉!

likedislike
JesseJesseCollaborators
Sep 29 Added label: bug
TorchNPU-BotTorchNPU-BotCollaborators
Sep 29 Added label: triage-reviewmodule: usability
TorchNPU-Bot
TorchNPU-BotCollaborators
Sep 29 Comments:

无报错,属功能建议/需求;主题为 torch.random.fork_rng 兼容性改进,涉及 API 使用与版本兼容
添加分类标签:module: usability。
当前分类由社区bot提供,如分类有误请在评论中回复。

likedislike
JesseJesseCollaborators
Sep 29 Associated milestone: v26.2.0
TorchNPU-BotTorchNPU-BotCollaborators
Sep 29 Added label: bot-triaged; Removed label: triage-review
TorchNPU-Bot
TorchNPU-BotCollaborators
Sep 29 Comments:

检测到当前 issue 已关联 PR,自动添加标签:bot-triaged

likedislike
JesseJesseCollaborators
Sep 29 Associated pull request
11 event messages are collapsed here。 See more
JesseJesseCollaborators
Sep 30 Modify description of issue
chenrayray
chenrayrayCollaborators
Oct 8 Comments:

因为本单相关实施 PR 已全部结束(12 个已合入、0 个已关闭),按照本轮 issue 整理规则,先关闭此单。master 的回退 PR !47507 说明该分支已跟随 PyTorch 2.13/2.14,无需旧版兼容补丁;旧版分支的相关修复已合入。

核对的 PR:

如仍有问题或需要继续推进,请重新打开,并补充当前 PyTorch / TorchNPU / CANN 版本、硬件环境、复现步骤及相关日志;需求类请补充尚未完成的具体内容。

likedislike
chenrayraychenrayrayCollaborators
Oct 8 Close issue
chenrayraychenrayrayCollaborators
Oct 8 changed custom state from TODO to DONE
ascend-robotascend-robotCollaborators
Oct 8 Added label: resolved