MMDetection系列之(PTYORCH TO ONNX)

尝试新的MMDeploy来部署你的模型(Pytorch -> ONNX -> TensorRT)

Open Neural Network Exchange(ONNX,开放神经网络交换)格式,是一个用于表示深度学习模型的标准,可使模型在不同框架之间进行转移。

ONNX是一种针对机器学习所设计的开放式的文件格式,用于存储训练好的模型。它使得不同的人工智能框架(如Pytorch, MXNet)可以采用相同格式存储模型数据并交互。 ONNX的规范及代码主要由微软,亚马逊 ,Facebook 和 IBM 等公司共同开发,以开放源代码的方式托管在Github上。

目前官方支持加载ONNX模型并进行推理的深度学习框架有: Caffe2, PyTorch, MXNet,ML.NET,TensorRT 和 Microsoft CNTK,并且 TensorFlow 也非官方的支持ONNX。

假设一个场景:现在某组织因为主要开发用TensorFlow为基础的框架,现在有一个深度算法,需要将其部署在移动设备上,以观测变现。传统地我们需要用caffe2重新将模型写好,然后再训练参数;试想下这将是一个多么耗时耗力的过程。

此时,ONNX便应运而生,Caffe2,PyTorch,Microsoft Cognitive Toolkit,Apache MXNet等主流框架都对ONNX有着不同程度的支持。这就便于了我们的算法及模型在不同的框架之间的迁移。

ONNX

开放式神经网络交换(ONNX)是迈向开放式生态系统的第一步,它使AI开发人员能够随着项目的发展选择合适的工具。 ONNX为AI模型提供开源格式。 它定义了可扩展的计算图模型,以及内置运算符和标准数据类型的定义。 最初的ONNX专注于推理(评估)所需的功能。 ONNX解释计算图的可移植,它使用graph的序列化格式。 它不一定是框架选择在内部使用和操作计算的形式。 例如,如果在优化过程中操作更有效,则实现可以在存储器中以不同方式表示模型。

如何转换模型从Pytorch到ONNX

Usage

python tools/deployment/pytorch2onnx.py \
    ${CONFIG_FILE} \
    ${CHECKPOINT_FILE} \
    --output-file ${OUTPUT_FILE} \
    --input-img ${INPUT_IMAGE_PATH} \
    --shape ${IMAGE_SHAPE} \
    --test-img ${TEST_IMAGE_PATH} \
    --opset-version ${OPSET_VERSION} \
    --cfg-options ${CFG_OPTIONS}
    --dynamic-export \
    --show \
    --verify \
    --simplify \

所有参数的描述

config : The path of a model config file.(模型配置文件的路径)

checkpoint : The path of a model checkpoint file.(模型检查点文件的路径)

–output-file: The path of output ONNX model. If not specified, it will be set to tmp.onnx.输出ONNX模型的路径。如果没有指定,它将被设置为tmp.onnx。

–input-img: The path of an input image for tracing and conversion. By default, it will be set to tests/data/color.jpg.(用于跟踪和转换的输入图像的路径。默认情况下,它将被设置为tests/data/color.jpg。)

–shape: The height and width of input tensor to the model. If not specified, it will be set to 800 1216.(模型输入张量的高度和宽度。如果不指定,则将其设置为800 1216。)

–test-img : The path of an image to verify the exported ONNX model. By default, it will be set to None, meaning it will use --input-img for verification.用于验证导出的ONNX模型的图像路径。默认情况下,它将被设置为None,这意味着它将使用——input-img进行验证

–opset-version : The opset version of ONNX. If not specified, it will be set to 11.ONNX的opset版本。如果未指定,则将其设置为11。

–dynamic-export: Determines whether to export ONNX model with dynamic input and output shapes. If not specified, it will be set to False.确定是否导出带有动态输入和输出形状的ONNX模型。如果没有指定,它将被设置为False。

–show: Determines whether to print the architecture of the exported model and whether to show detection outputs when --verify is set to True. If not specified, it will be set to False.决定是否打印导出模型的架构,以及当——verify设置为True时是否显示检测输出。如果没有指定,它将被设置为False。

–verify: Determines whether to verify the correctness of an exported model. If not specified, it will be set to False.是否验证导出模型的正确性。如果没有指定,它将被设置为False。

–simplify: Determines whether to simplify the exported ONNX model. If not specified, it will be set to False.是否简化导出的ONNX模型。如果没有指定,它将被设置为False。

–cfg-options: Override some settings in the used config file, the key-value pair in xxx=yyy format will be merged into config file.
如果覆盖已使用的配置文件中的某些设置,则格式为xxx=yyy的键值对将被合并到配置文件中。

–skip-postprocess: Determines whether export model without post process. If not specified, it will be set to False. Notice: This is an experimental option. Only work for some single stage models. Users need to implement the post-process by themselves. We do not guarantee the correctness of the exported model

Example

python tools/deployment/pytorch2onnx.py \
    configs/yolo/yolov3_d53_mstrain-608_273e_coco.py \
    checkpoints/yolo/yolov3_d53_mstrain-608_273e_coco.pth \
    --output-file checkpoints/yolo/yolov3_d53_mstrain-608_273e_coco.onnx \
    --input-img demo/demo.jpg \
    --test-img tests/data/color.jpg \
    --shape 608 608 \
    --show \
    --verify \
    --dynamic-export \
    --cfg-options \
      model.test_cfg.deploy_nms_pre=-1 \

如何评估导出的模型

我们准备了一个工具tools/ deploy /test.py来使用ONNXRuntime和TensorRT评估ONNX模型

Usage

python tools/deployment/test.py \
    ${CONFIG_FILE} \
    ${MODEL_FILE} \
    --out ${OUTPUT_FILE} \
    --backend ${BACKEND} \
    --format-only ${FORMAT_ONLY} \
    --eval ${EVALUATION_METRICS} \
    --show-dir ${SHOW_DIRECTORY} \
    ----show-score-thr ${SHOW_SCORE_THRESHOLD} \
    ----cfg-options ${CFG_OPTIONS} \
    ----eval-options ${EVALUATION_OPTIONS} \

Description of all arguments

config: The path of a model config file.

model: The path of an input model file.

–out: The path of output result file in pickle format.

–backend: Backend for input model to run and should be onnxruntime or tensorrt.

–format-only : Format the output results without perform evaluation. It is useful when you want to format the result to a specific format and submit it to the test server. If not specified, it will be set to False.

–eval: Evaluation metrics, which depends on the dataset, e.g., “bbox”, “segm”, “proposal” for COCO, and “mAP”, “recall” for PASCAL VOC.

–show-dir: Directory where painted images will be saved

–show-score-thr: Score threshold. Default is set to 0.3.

–cfg-options: Override some settings in the used config file, the key-value pair in xxx=yyy format will be merged into config file.

–eval-options: Custom options for evaluation, the key-value pair in xxx=yyy format will be kwargs for dataset.evaluate() function

Notes

Notes:

If the deployed backend platform is TensorRT, please add environment variables before running the file:

export ONNX_BACKEND=MMCVTensorRT
If you want to use the --dynamic-export parameter in the TensorRT backend to export ONNX, please remove the --simplify parameter, and vice versa.

Results and Models

Model	Config	Metric	PyTorch	ONNX Runtime	TensorRT
FCOS	configs/fcos/fcos_r50_caffe_fpn_gn-head_4x4_1x_coco.py	Box AP	36.6	36.5	36.3
FSAF	configs/fsaf/fsaf_r50_fpn_1x_coco.py	Box AP	36.0	36.0	35.9
RetinaNet	configs/retinanet/retinanet_r50_fpn_1x_coco.py	Box AP	36.5	36.4	36.3
SSD	configs/ssd/ssd300_coco.py	Box AP	25.6	25.6	25.6
YOLOv3	configs/yolo/yolov3_d53_mstrain-608_273e_coco.py	Box AP	33.5	33.5	33.5
Faster R-CNN	configs/faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py	Box AP	37.4	37.4	37.0
Cascade R-CNN	configs/cascade_rcnn/cascade_rcnn_r50_fpn_1x_coco.py	Box AP	40.3	40.3	40.1
Mask R-CNN	configs/mask_rcnn/mask_rcnn_r50_fpn_1x_coco.py	Box AP	38.2	38.1	37.7
Mask AP	34.7	33.7	33.3
Cascade Mask R-CNN	configs/cascade_rcnn/cascade_mask_rcnn_r50_fpn_1x_coco.py	Box AP	41.2	41.2	40.9
Mask AP	35.9	34.8	34.5
CornerNet	configs/cornernet/cornernet_hourglass104_mstest_10x5_210e_coco.py	Box AP	40.6	40.4	-
DETR	configs/detr/detr_r50_8x2_150e_coco.py	Box AP	40.1	40.1	-
PointRend	configs/point_rend/point_rend_r50_caffe_fpn_mstrain_1x_coco.py	Box AP	38.4	38.4	-
Mask AP	36.3	35.2	-

所有ONNX模型在coco数据集上使用动态形状进行评估,并根据原始配置文件对图像进行预处理。请注意,在评估过程中没有使用测试时间翻转,因为目前ONNX Runtime只支持单尺度评估。
掩码R-CNN的掩码AP在ONNXRuntime中下降了1%。主要原因是预测的掩码在PyTorch中直接插值到原始图像中,而先插值到预处理后的模型输入图像中,然后在其他后端再插值到原始图像中

支持导出到ONNX的模型列表

下表列出了保证可以导出到ONNX并在ONNX运行时中运行的模型。

Model	Config	Dynamic Shape	Batch Inference	Note
FCOS	configs/fcos/fcos_r50_caffe_fpn_gn-head_4x4_1x_coco.py	Y	Y	
FSAF	configs/fsaf/fsaf_r50_fpn_1x_coco.py	Y	Y	
RetinaNet	configs/retinanet/retinanet_r50_fpn_1x_coco.py	Y	Y	
SSD	configs/ssd/ssd300_coco.py	Y	Y	
YOLOv3	configs/yolo/yolov3_d53_mstrain-608_273e_coco.py	Y	Y	
Faster R-CNN	configs/faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py	Y	Y	
Cascade R-CNN	configs/cascade_rcnn/cascade_rcnn_r50_fpn_1x_coco.py	Y	Y	
Mask R-CNN	configs/mask_rcnn/mask_rcnn_r50_fpn_1x_coco.py	Y	Y	
Cascade Mask R-CNN	configs/cascade_rcnn/cascade_mask_rcnn_r50_fpn_1x_coco.py	Y	Y	
CornerNet	configs/cornernet/cornernet_hourglass104_mstest_10x5_210e_coco.py	Y	N	no flip, no batch inference, tested with torch==1.7.0 and onnxruntime==1.5.1.
DETR	configs/detr/detr_r50_8x2_150e_coco.py	Y	Y	batch inference is not recommended
PointRend	configs/point_rend/point_rend_r50_caffe_fpn_mstrain_1x_coco.py	Y	Y	

•虽然支持,但不推荐在onnxruntime中对DETR使用批推理,因为ONNX和火炬模型之间有巨大的性能差距(例如,onnxruntime和火炬上的mAP分别为33.5和39.9)。造成差距的主要原因是,在ONNX的批处理推断期间,这些对预测回归有不可忽视的影响,因为预测坐标是由img_shape(没有填充)标准化的,应该转换为绝对格式,但是img_shape不是动态可跟踪的,因此使用填充的img_shape_for_onnx。
目前ONNX运行时只支持单尺度评估,mmcv::SoftNonMaxSuppression目前只支持单个图像。

ONNX导出非最大抑制参数

在导出ONNX模型的过程中,我们为NMS op设置了一些参数来控制输出边界框的数量。下面将介绍NMS操作在支持的型号下的参数设置。您可以通过——cfg-options设置这些参数。
nms_pre: The number of boxes before NMS. The default setting is 1000.在NMS之前的盒子数量。缺省值为1000。

deploy_nms_pre: The number of boxes before NMS when exporting to ONNX model. The default setting is 0.导出到ONNX模型时,在NMS前面的框数。缺省值为0。

max_per_img: The number of boxes to be kept after NMS. The default setting is 100.NMS后需要保留的盒子数量。默认值为100。

max_output_boxes_per_class: Maximum number of output boxes per class of NMS. The default setting is 200

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
MMDetection转换为ONNX模型后,可以使用ONNX推理引擎进行推理。下面是一个简单的步骤来进行ONNX模型推理: 1. 导入必要的库:首先,需要导入相关的库,包括`onnx`、`onnxruntime`和`numpy`。 2. 加载ONNX模型:使用ONNX Runtime库中的`InferenceSession`类,加载从MMDetection转换得到的ONNX模型。 3. 准备输入数据:根据模型输入要求,准备输入数据,并将其转换为numpy数组的格式。 4. 执行推理:使用`InferenceSession`对象的`run`方法,传入输入数据,执行推理操作。 5. 解码输出结果:根据模型的输出设置,解析推理结果,并对其进行后处理。 下面是一个示例代码,用于演示如何使用ONNX模型进行推理: ```python import onnx import onnxruntime as ort import numpy as np # 加载ONNX模型 model_path = 'path_to_onnx_model.onnx' onnx_model = onnx.load(model_path) session = ort.InferenceSession(onnx_model.SerializeToString()) # 准备输入数据 input_name = session.get_inputs()[0].name input_data = np.random.randn(1, 3, 224, 224).astype(np.float32) # 执行推理 output_name = session.get_outputs()[0].name output = session.run([output_name], {input_name: input_data}) # 解码输出结果 output = output[0] # 进行后处理操作 ``` 在这个示例代码中,首先使用`onnx`库加载ONNX模型,然后使用`onnxruntime`库创建一个`InferenceSession`对象。接下来,准备输入数据,并使用`InferenceSession`对象的`run`方法进行推理。最后,可以根据模型的输出设置,对推理结果进行解码和后处理操作。 以上就是使用ONNX推理引擎进行MMDetection转换为ONNX模型的简单步骤。具体的推理过程会因模型结构和输入数据要求而有所不同,可以根据实际情况进行适配。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值