模型转换推理报错汇总

在将ONNX模型转换为TRT模型时,遇到输入和输出形状不匹配的问题,特别是输出从1x256变为1x-1。通过设置动态轴并在导出ONNX模型时指定batch大小,以及使用onnxsim简化模型来去除不必要的identity层,成功解决了转换和推理错误。
摘要由CSDN通过智能技术生成

1.onnx转trt
onnx模型是单batch:1x3x256x128,输出是1x256
转trt时变成了1x-1,导致后边推理报错。
Input shape is -1 x 3 x 256 x 128
[2023-03-29 10:04:55][info][trt_builder.cpp:559]:Set max batch size = 16
[2023-03-29 10:04:55][info][trt_builder.cpp:560]:Set max workspace size = 1024.00 MB
[2023-03-29 10:04:56][info][trt_builder.cpp:561]:Base device: [ID 0]<NVIDIA GeForce GTX 1080 Ti>[arch 6.1][GMEM 10.43 GB/10.92 GB]
[2023-03-29 10:04:56][info][trt_builder.cpp:564]:Network has 1 inputs:
[2023-03-29 10:04:56][info][trt_builder.cpp:570]: 0.[images] shape is -1 x 3 x 256 x 128
[2023-03-29 10:04:56][info][trt_builder.cpp:576]:Network has 1 outputs:
[2023-03-29 10:04:56][info][trt_builder.cpp:581]: 0.[output] shape is 1 x -1
[2023-03-29 10:04:56][info][trt_builder.cpp:585]:Network has 120 layers:
[2023-03-29 10:04:56][info][trt_builder.cpp:652]:Building engine…
[fatal][trt_tensor.cpp:391]:Assert failed, ndims == shape_.size()
解决:导出onnx时使用多batch

torch.onnx.export(
    model.cpu() if dynamic else model,  # --dynamic only compatible with cpu
    im.cpu() if dynamic else im,
    f,
    verbose=False,
    opset_version=opset,
    training=torch.onnx.TrainingMode.TRAINING if train else torch.onnx.TrainingMode.EVAL,
    do_constant_folding=not train,
    input_names=['images'],
    output_names=['output'],
    dynamic_axes={
        'images': {
            0: 'batch',
        },  # shape(x,3,256,128)
        'output': {
            0: 'batch',
        }  # shape(x,2048)
    } if dynamic else None
)

只这样导出多出一些identity,再转trt的时候又报其他错。
在这里插入图片描述
这些identity需要用onnxsim.simplify去掉

model_onnx, check = onnxsim.simplify(
    model_onnx,
    # dynamic_input_shape=dynamic,
    # input_shapes={'t0': list(im.shape)} if dynamic else None
    )

再次转化和推理就正确了。
2.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值