ImportError: cannot import name ‘DTensor’ from ‘torch.distributed.tensor’

用户在安装了 PyTorch 2.4.0 和最新版 `transformers` 后,尝试导入 `from transformers.distributed.sharding_utils import DtensorShardOperation` 时触发。该问题还会级联影响到所有间接导入 `shar

ImportError: cannot import name 'DTensor' from 'torch.distributed.tensor'

ImportError: cannot import name ‘DTensor’ from ‘torch.distributed.tensor’

快速结论:此报错通常发生在使用 PyTorch 2.4 及更早版本,但 `transformers` 版本是最新 `main` 分支时。优先排查你的 PyTorch 版本,并对 `torch.distributed.tensor.DTensor` 的导入进行兼容性处理。

问题场景

用户在安装了 PyTorch 2.4.0 和最新版 `transformers` 后,尝试导入 `from transformers.distributed.sharding_utils import DtensorShardOperation` 时触发。该问题还会级联影响到所有间接导入 `sharding_utils.py` 的模块,如 `core_model_loading.py`、`conversion_mapping.py`、`activations.py`、`modeling_bert.py` 等,导致任何测试或任务都无法运行。

报错原文

ImportError: cannot import name 'DTensor' from 'torch.distributed.tensor'

原因分析

在 PyTorch 2.4 及更早版本中,`torch.distributed.tensor` 模块并不包含 `DTensor` 这个类(它是 PyTorch 2.5 版本引入的)。但 `transformers` 源码中的 `src/transformers/distributed/sharding_utils.py` 第 28 行无条件地执行了 `from torch.distributed.tensor import DTensor`,导致在旧版 PyTorch 上导入失败。该文件虽然已经使用了 `from __future__ import annotations`(第 14 行)来延迟类型注解的解析,但运行时导入语句仍会立即执行。

环境排查

  • PyTorch 版本:确认当前安装的 PyTorch 版本是否低于 2.5(例如 2.4.0 或更低)。
  • Transformers 版本:确认 `transformers` 是否为最新 `main` 分支或包含无条件导入 `DTensor` 的版本。

解决步骤

  1. 升级 PyTorch(推荐):将 PyTorch 升级到 v2.5 或更高版本,该版本正式引入了 `DTensor`。
  2. 降级 Transformers:如果暂时无法升级 PyTorch,可以将 `transformers` 回退到不包含无条件导入 `DTensor` 的稳定版本。
  3. 或等待官方修复(可优先尝试):社区已提出修复方案(PR #47481),核心思路是将 `sharding_utils.py` 中的导入语句包裹在 `try/except` 中,当 `DTensor` 不可用时优雅降级。建议等待该修复合入后更新 `transformers`。

注意:以上步骤均基于 Issue 中的讨论,修复代码实际实现可能略有不同,但思路一致。

验证方法

完成上述修复后,重新执行最初的导入命令:
from transformers.distributed.sharding_utils import DtensorShardOperation
如果不再抛出 `ImportError`,则问题已解决。同时建议运行 `accelerate` CI 或你自己的测试用例,确保下游模块不受影响。

参考来源

huggingface/transformers #47479

GamsGo AI

AI 工具推荐

想把多个 AI 模型放在一个入口?

GamsGo AI 集成 ChatGPT、DeepSeek、Gemini、Claude、Midjourney、Veo 等常用模型,适合写作、绘图、视频和日常 AI 工作流。

了解 GamsGo AI

推广链接:通过此链接购买,我可能获得佣金,不影响你的价格。

celebrityanime
celebrityanime
文章: 14816

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注