You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

运行旧版torch/torchtext代码报无tensor_type参数等错如何解决?

适配旧版torch/torchtext与OpenNMT测试流程解决方案

方案1:最小改动适配当前环境(优先选择,无需替换依赖)

第一个TypeError: __init__() got an unexpected keyword argument 'tensor_type'报错根因为当前环境的torchtext版本已将Field类的tensor_type参数重命名为dtype,仅需简单调整即可跑通测试:

  • 找到/onmt/io/TextDataset.py第218行,将参数中的tensor_type改为dtype
  • 若当前torchtext版本≥0.9.0,把OpenNMT代码中所有import torchtext.data.xxx的语句替换为import torchtext.legacy.data.xxx,即可解决ModuleNotFoundError: No module named 'torchtext.legacy'报错

如果不想修改OpenNMT源码,可直接在测试脚本translate_mm.py最开头加入猴子补丁代码兼容参数:

# 放在所有import onmt的代码之前执行
try:
    from torchtext.legacy.data import Field
except ImportError:
    from torchtext.data import Field

original_field_init = Field.__init__
def patched_field_init(self, *args, **kwargs):
    if 'tensor_type' in kwargs:
        kwargs['dtype'] = kwargs.pop('tensor_type')
    original_field_init(self, *args, **kwargs)
Field.__init__ = patched_field_init

方案2:安装经过验证的无冲突依赖版本

如果不想改代码,直接安装匹配的版本组合即可,该组合不存在_dl模块缺失问题,也完全适配旧版OpenNMT的API:

  • 版本组合:Python 3.7/3.8 + PyTorch 1.6.0 + torchtext 0.7.0
  • CPU版本安装命令:
    conda install pytorch==1.6.0 torchtext==0.7.0 cpuonly -c pytorch
  • GPU版本安装命令(适配cuda10.2):
    conda install pytorch==1.6.0 torchtext==0.7.0 cudatoolkit=10.2 -c pytorch
    该版本组合中的torchtext原生支持tensor_type参数,无需引入torchtext.legacy,PyTorch 1.6.0也内置了_dl模块,不会触发缺失报错。

内容的提问来源于stack exchange,提问作者U. Iceman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 19:15:03