pytorch转onnx报错: Failed to export an ONNX attribute ‘onnx::Gather’, since it’s not constant

在尝试将PyTorch模型转换为ONNX格式时,遇到一个错误,提示FailedtoexportanONNXattributeonnx::Gather,sinceit’snotconstant。错误发生在torch/onnx/symbolic_helper.py文件的第84行。问题根源在于ONNX不支持动态的tensor形状信息。解决方案是将tensor的shape转换为常量,例如通过将shape转换为int列表。经过修改,模型转换成功,不再出现该错误。
Qwen3-32B-Chat 私有部署镜像 | RTX4090D 24G 显存 CUDA12.4 优化版

Qwen3-32B-Chat 私有部署镜像 | RTX4090D 24G 显存 CUDA12.4 优化版

Qwen
文本生成
Qwen3

本镜像基于 RTX 4090D 24GB 显存 + CUDA 12.4 + 驱动 550.90.07 深度优化,内置完整运行环境与 Qwen3-32B 模型依赖,开箱即用。

在这里插入图片描述

pytorch转onnx报错, Failed to export an ONNX attribute ‘onnx::Gather’, since it’s not constant, please try to make things (e.g., kernel size) static if possible

报错信息

RuntimeError: Failed to export an ONNX attribute ‘onnx::Gather’, since it’s not constant, please try to make things (e.g., kernel size) static if possible

直接从报错信息上无法定位到具体的算子

定位方法

通过查看详细的错误信息

  File "/home/ubuntu/anaconda3/envs/profiler/lib/python3.9/site-packages/torch/onnx/symbolic_helper.py", line 167, in wrapper
    args = [_parse_arg(arg, arg_desc, arg_name, fn_name)  # type: ignore[assignment]
  File "/home/ubuntu/anaconda3/envs/profiler/lib/python3.9/site-packages/torch/onnx/symbolic_helper.py", line 167, in <listcomp>
    args = [_parse_arg(arg, arg_desc, arg_name, fn_name)  # type: ignore[assignment]
  File "/home/ubuntu/anaconda3/envs/profiler/lib/python3.9/site-packages/torch/onnx/symbolic_helper.py", line 84, in _parse_arg
    raise RuntimeError("Failed to export an ONNX attribute '" + v.node().kind() +

发现异常在“torch/onnx/symbolic_helper.py", line 84”抛出

在torch源码的该位置增加print信息:

print(v.node())

重新运行转模型代码,发现报错信息多了实际引起该错误信息的代码位置

%37 : Long(device=cpu) = onnx::Gather[axis=0](%34, %36) # /×××/pytorch_profiler/torch2onnx.py:18:0
        
        shape = x.shape()[1:]

解决方法

分析原因,是tensor的size()或shape方法无法被onnx识别,需要修改为常量。

修改方式有很多,比如使用List结果报错tensor的shape信息:

shape = [int(e) for e in x.shape[1:]]

修改后,再次运行转模型代码,不会出现该错误

您可能感兴趣的与本文相关的镜像

Qwen3-32B-Chat 私有部署镜像 | RTX4090D 24G 显存 CUDA12.4 优化版

Qwen3-32B-Chat 私有部署镜像 | RTX4090D 24G 显存 CUDA12.4 优化版

Qwen
文本生成
Qwen3

本镜像基于 RTX 4090D 24GB 显存 + CUDA 12.4 + 驱动 550.90.07 深度优化,内置完整运行环境与 Qwen3-32B 模型依赖,开箱即用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值