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

Ubuntu运行Deformable-DETR遇_NewEmptyTensorOp导入错误求助

解决Deformable-DETR的torchvision导入错误问题

环境与问题背景

  • 系统:Ubuntu 20.04.6 LTS
  • Python版本:3.10.9
  • 运行命令:
./configs/r50_deformable_detr_plus_iterative_bbox_refinement_plus_plus_two_stage.sh --resume ./pre-trained models/r50_deformable_detr_plus_iterative_bbox_refinement_plus_plus_two_stage-checkpoint.pth --eval

已按要求配置预训练模型与COCO验证集目录,运行后触发以下错误:

ImportError: cannot import name '_NewEmptyTensorOp' from 'torchvision.ops.misc'

当前环境依赖:torch 2.0.1、torchvision 0.15.2。已尝试的操作:

  • 执行pip install torch torchvision --upgrade升级,错误未解决
  • 降级torchvision至0.13.2,出现from .torchvision_datasets import CocoDetection as TvCocoDetection导入错误

可行解决方案

方案1:手动补充缺失的类定义(无需修改依赖版本)

_NewEmptyTensorOp在高版本torchvision中已被移除,直接在项目代码中补充该类:

  1. 打开util/misc.py,注释或删除原导入行:
# from torchvision.ops.misc import _NewEmptyTensorOp
  1. 在该文件中添加以下类定义:
class _NewEmptyTensorOp(torch.autograd.Function):
    @staticmethod
    def forward(ctx, x, new_shape):
        ctx.shape = x.shape
        return x.new_empty(new_shape)

    @staticmethod
    def backward(ctx, grad):
        shape = ctx.shape
        return grad.new_empty(shape), None

修改后重新运行命令即可绕过版本兼容问题。

方案2:使用官方推荐的稳定依赖版本

Deformable-DETR官方验证的兼容版本组合:

  • torch == 1.9.0
  • torchvision == 0.10.0
  • torchaudio == 0.9.0

执行以下命令强制安装(CUDA环境需对应版本):

# CPU版本
pip install torch==1.9.0 torchvision==0.10.0 torchaudio==0.9.0 --force-reinstall

# CUDA 11.1版本
pip install torch==1.9.0+cu111 torchvision==0.10.0+cu111 torchaudio==0.9.0 -f https://download.pytorch.org/whl/torch_stable.html

方案3:适配低版本torchvision的数据集导入逻辑

若坚持使用torchvision 0.13.2,修改datasets/coco.py的导入与类初始化:

  1. 替换导入语句:
    将
from .torchvision_datasets import CocoDetection as TvCocoDetection

改为

from torchvision.datasets import CocoDetection as TvCocoDetection
  1. 调整CocoDetection类的初始化参数(移除官方torchvision不支持的参数):
class CocoDetection(TvCocoDetection):
    def __init__(self, img_folder, ann_file, transforms, return_masks, cache_mode=False, local_rank=0, local_size=1):
        super(CocoDetection, self).__init__(img_folder, ann_file)
        self._transforms = transforms
        self.prepare = ConvertCocoPolysToMask(return_masks)

内容的提问来源于stack exchange,提问作者Pascual

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 05:32:48