{"id":23102637,"url":"https://github.com/dataxujing/co-detr-tensorrt","last_synced_at":"2025-08-16T14:32:58.782Z","repository":{"id":264614080,"uuid":"869840273","full_name":"DataXujing/Co-DETR-TensorRT","owner":"DataXujing","description":":fire: 全网首发，mmdetection Co-DETR TensorRT端到端推理加速","archived":false,"fork":false,"pushed_at":"2024-11-27T01:44:23.000Z","size":1494,"stargazers_count":27,"open_issues_count":2,"forks_count":5,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-04-04T13:23:09.913Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"C++","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/DataXujing.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-10-09T01:32:32.000Z","updated_at":"2025-03-03T03:35:06.000Z","dependencies_parsed_at":"2024-11-25T11:38:32.871Z","dependency_job_id":null,"html_url":"https://github.com/DataXujing/Co-DETR-TensorRT","commit_stats":null,"previous_names":["dataxujing/co-detr-tensorrt"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/DataXujing/Co-DETR-TensorRT","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DataXujing%2FCo-DETR-TensorRT","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DataXujing%2FCo-DETR-TensorRT/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DataXujing%2FCo-DETR-TensorRT/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DataXujing%2FCo-DETR-TensorRT/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/DataXujing","download_url":"https://codeload.github.com/DataXujing/Co-DETR-TensorRT/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DataXujing%2FCo-DETR-TensorRT/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":270723406,"owners_count":24634374,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-08-16T02:00:11.002Z","response_time":91,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-12-17T00:00:07.905Z","updated_at":"2025-08-16T14:32:58.402Z","avatar_url":"https://github.com/DataXujing.png","language":"C++","funding_links":[],"categories":[],"sub_categories":[],"readme":"## Co-DETR  TensorRT 模型端到端加速推理的C++实现\n\n徐静\n\n### 0. 环境配置说明\n\n+ Ubuntu16.04下安装mmdetection, mmdeploy, 其依赖mmcv和mmengine\n\n```shell\n# mmdetection==3.3.0\ngit clone -b 3.3.0 https://github.com/open-mmlab/mmdetection\npip install -v -e .\n\n# mmcv\npip install mmcv==2.0.0\n\n# mmdeploy\n# https://github.com/TommyZihao/MMDeploy_Tutorials  \ngit clone -b 1.3.1 https://github.com/open-mmlab/mmdeploy --recursive\n# 编译并安装 MMDeploy（耗时大约十分钟）\npython tools/scripts/build_ubuntu_x64_ort.py\n```\n\n+ windows TensorRT的环境\n  + TensorRT 8.5\n  + cuda 11.0, cudnn\n  + vs2017\n  + cmake version 3.22.1\n  + opencv\n\n\n\n### 1.Co-DETR 转ONNX\n\n1.修改模型配置文件，关闭测试过程中的soft-nms(后面用EfficientNMS Plugin代替)\n\n```python\n# mmdetection/projects/CO-DETR/configs/codino/co_dino_5scale_swin_l_16xb1_16e_o365tococo.py\n#mmdetection/projects/CO-DETR/configs/codino/co_dino_5scale_r50_lsj_8xb2_1x_coco.py\n\n    test_cfg=[\n        # # Deferent from the DINO, we use the NMS.\n        dict(\n            max_per_img=300,\n            # NMS can improve the mAP by 0.2.\n            # nms=dict(type='soft_nms', iou_threshold=0.8)),  # 关掉test过程中的soft nms\n        ),\n```\n\n2.修改mmdeploy中关于onnx的导出配置\n\n```python\n# mmdeploy/configs/_base_/onnx_config.py\nonnx_config = dict(\n    type='onnx',\n    export_params=True,\n    keep_initializers_as_inputs=False,\n    opset_version=11,  # opset 版本\n    save_file='end2end.onnx',  #转出onnx的保存名字\n    input_names=['input'],  # input的名字\n    output_names=['output'],  # output的名字\n    input_shape=None,\n    optimize=True)\n# mmdeploy/configs/mmdet/_base_/base_static.py\n\n_base_ = ['../../_base_/onnx_config.py']\n\nonnx_config = dict(output_names=['dets', 'labels'], input_shape=[640,640])  # static input的大小设置为640x640\ncodebase_config = dict(\n    type='mmdet',\n    task='ObjectDetection',\n    model_type='end2end',\n    post_processing=dict(\n        score_threshold=0.05,\n        confidence_threshold=0.005,  # for YOLOv3\n        iou_threshold=0.5,\n        max_output_boxes_per_class=200,\n        pre_top_k=5000,\n        keep_top_k=100,\n        background_label_id=-1,\n    ))\n\n# co-dino使用了多尺度训练，这里我们将test input的尺度设为640x640,减少计算量\n```\n\n3.mmdeploy转onnx\n\n```shell\npython mmdeploy/tools/deploy.py \\\n        mmdeploy/configs/mmdet/detection/detection_onnxruntime_static.py \\\n        mmdetection/projects/CO-DETR/configs/codino/co_dino_5scale_swin_l_16xb1_16e_o365tococo.py \\\n        mmdetection/checkpoints/co_dino_5scale_swin_large_16e_o365tococo-614254c9.pth \\\n        mmdetection/demo/demo.jpg \\\n        --work-dir mmdetection/checkpoints \\\n        --device cpu\n# 这个过程生成了end2end.onnx的，但是onnxruntime的时候或报错，报错的原因是grid_sampler算子onnxruntime和tensorrt均不支持，稍后会编译tensorrt plugin解决该伪问题\n```\n\n4.对onnx进行onnxsim和 fold constants\n\n```shell\npolygraphy surgeon sanitize end2end.onnx --fold-constants -o end2end_folded.onnx\npython -m onnxsim end2end_folded.onnx end2end_folded_sim.onnx\n```\n注意：\n\n```\n# 常量折叠和simplifier涉及到的库的版本\npolygraphy==0.49.0\nonnxruntime-gpu==1.19.2\nonnx-simplifier=0.4.36\n```\n\n\n\n### 2. Windows 下单独编译mmdeploy中仅涉及Co-DETR的TensorRT Plugin\n\n```CMakeLists\ncmake_minimum_required(VERSION 2.6)\n\nproject(mmdeploy_plugins)\n\nadd_definitions(-std=c++11)\nadd_definitions(-DAPI_EXPORTS)\noption(CUDA_USE_STATIC_CUDA_RUNTIME OFF)\nset(CMAKE_CXX_STANDARD 11)\nset(CMAKE_BUILD_TYPE Release)\nset(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS}  /O2\")\nadd_compile_definitions(WIN32_LEAN_AND_MEAN NOMINMAX)\n\nfind_package(CUDA REQUIRED)\n\n#if(WIN32)\n#enable_language(CUDA)\n#endif(WIN32)\n\n# cuda\nset(cuda_inc \"C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v11.0/include\")\nset(cuda_lib \"C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v11.0/lib/x64\")\ninclude_directories(${cuda_inc})\nlink_directories(${cuda_lib})\n#cub\nset(CUB_ROOT_DIR \"C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v11.0/include/cub\")\ninclude_directories(${CUB_ROOT_DIR})\n# tensorrt\nset(tensorrt_inc \"D:/trt_install/TensorRT-8.5.1.7/include\")\nset(tensorrt_lib \"D:/trt_install/TensorRT-8.5.1.7/lib\")\ninclude_directories(${tensorrt_inc})\nlink_directories(${tensorrt_lib})\n# opencv\n#include_directories(\"${PROJECT_SOURCE_DIR}/third_party/CV460_64/include\")\n#set(opencv_lib \"${PROJECT_SOURCE_DIR}/third_party/CV460_64/lib/opencv_world460.lib\")\n\n# common files，来源于mmdeploy\ninclude_directories(common)\n\nfile(GLOB grid_sampler_src ${PROJECT_SOURCE_DIR}/grid_sampler/*.cpp ${PROJECT_SOURCE_DIR}/grid_sampler/*.cu)\ncuda_add_library(trtgrid_sampler SHARED ${grid_sampler_src})\n#cuda_add_library(trtgrid_sampler STATIC ${grid_sampler_src})\ntarget_link_libraries(trtgrid_sampler nvinfer cudart)\n\n\nfile(GLOB topk_src ${PROJECT_SOURCE_DIR}/gather_topk/*.cpp ${PROJECT_SOURCE_DIR}/gather_topk/*.cu)\ncuda_add_library(trtgather_topk SHARED ${topk_src})\n#cuda_add_library(trtgather_topk STATIC ${topk_src})\ntarget_link_libraries(trtgather_topk nvinfer cudart)\n\n\nif(UNIX)\n    add_definitions(-O2 -pthread)\nendif(UNIX)\n```\n\n\n\n1. 打开vs studio 2017的终端`x64 Native Tools Command ...`，cd到项目的目录进行编译\n\n![](test_res/static/cmd.png)\n\n2.windows下编译TensorRT Plugin\n\n```bash\nmkdir build \u0026\u0026 cd build\ncmake -G ”NMake Makefiles“ ..\nnmake\n```\n\n在build文件夹下生成了`trtgrid_sampler.dll`和`trtgather_topk.dll`,下面我们会使用`trtgrid_sampler.dll`的plugin 。\n\n### 3.Co-DETR  ONNX Graph修改和编辑\n\n原始导出的不包含nms的graph\n\n![](test_res/static/v1.PNG)\n\n执行编辑onnx graph的脚本：\n\n```shell\npython co_detr_add_nms.py\n```\n\n模型结构变为：\n\n![](test_res/static/v2.PNG)\n\n### 4.Windows下序列化Co-DETR TensorRT engine\n\n```shell\ntrtexec --onnx=end2end_foled_sim_nms.onnx --saveEngine=test_1.plan --workspace=60000 --verbose --plugins=./trtgrid_sampler.dll\n```\n\n\n\n### 5.mmdetection中Co-DETR模型前处理实现的分析和C++重写\n\nmmdetection 3.3.0 co-dino的前处理：\n\n+ opencv读入BGR图像\n\n+ 等比例缩放，长边缩放到640，缩放方法bilinear\n\n+ normalize: \n\n          mean=[123.675, 116.28, 103.53],  # RGB\n          std=[58.395, 57.12, 57.375],  #RGB\n\n+ BGR2RGB\n\n+ 短边右下角填充为0\n\nC++实现如下：\n\n```c++\n//mmdetection3.3.0 co-detr前处理\nvoid codetr::preprocess(cv::Mat \u0026img, float data[]) {\n\tint w, h, x, y;\n\tfloat r_w = INPUT_W / (img.cols*1.0);\n\tfloat r_h = INPUT_H / (img.rows*1.0);\n\tif (r_h \u003e r_w) {\n\t\tw = INPUT_W;\n\t\th = r_w * img.rows;\n\t}\n\telse {\n\t\tw = r_h * img.cols;\n\t\th = INPUT_H;\n\t}\n\tcv::Mat re(h, w, CV_8UC3);\n\tcv::resize(img, re, re.size(), 0, 0, cv::INTER_LINEAR);\n\tcv::Mat out(INPUT_H, INPUT_W, CV_8UC3, cv::Scalar(103, 116, 123));  //(0,0,0)像素填充\n\tre.copyTo(out(cv::Rect(0, 0, re.cols, re.rows)));  //右下角\n\n\tint i = 0;\n\tfor (int row = 0; row \u003c INPUT_H; ++row) {\n\t\tuchar* uc_pixel = out.data + row * out.step;\n\t\tfor (int col = 0; col \u003c INPUT_W; ++col) {\n\t\t\tdata[i] = ((float)uc_pixel[2] - 123.675)/58.395;  //R\n\t\t\tdata[i + INPUT_H * INPUT_W] = ((float)uc_pixel[1] - 116.28) / 57.12;  //G\n\t\t\tdata[i + 2 * INPUT_H * INPUT_W] = ((float)uc_pixel[0] - 103.53)/ 57.375;  //B\n\n\t\t\tuc_pixel += 3;\n\t\t\t++i;\n\t\t}\n\t}\n}\n```\n\n\n\n### 6.Co-DETR TensorRT C++实现和测试\n\n注意C++加载自己定义的Plugin\n\n```c++\nbool didInitPlugins = initLibNvInferPlugins(nullptr, \"\");\nvoid* handle_grid_sampler = LoadLibrary(L\"trtgrid_sampler.dll\");\n```\n\nTensorRT C++的推理Demo:\n\n| bus.jpg                   | zidane.jpg              |\n| ------------------------- | ----------------------- |\n| ![](test_res/final_0.jpg) | ![](test_res/final.jpg) |\n\n### 7. Linux如何编译该程序\n\n+ 我提供了在Linux下编译Co-DETR进行端到端推理的代码，请参考`linux_cc/`,其中`plugin`为grid_sampler plugin的编译， `co_detr`为Co-DETR的TensorRT调用。\n\n\u003e [!NOTE]\\\n\u003e\n\u003e + Co-DETR TensorRT的实现，坑确实比较多，参考的网络资源基本没有\n\u003e + 我们将soft-nms算子删除，替换为TensorRT EfficientNMS Plugin\n\u003e + 我们在windows下编译了TensorRT Plugin grid_sampler\n\n最终成功实现了Co-DETR的端到端的TensorRT 模型推理异构计算加速推理！\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdataxujing%2Fco-detr-tensorrt","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdataxujing%2Fco-detr-tensorrt","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdataxujing%2Fco-detr-tensorrt/lists"}