├── LICENSE ├── README.md ├── onnx-tensorrt.py ├── requirements.txt ├── torch-onnx.py └── utils ├── engine.py └── inference.py /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # simple_tensorrt_dynamic 2 | a simple example to learn tensorrt with dynamic shapes 3 | 4 | # 依赖环境 5 | - Ubuntu 18.04 6 | - pytorch>=1.4 7 | - onnx 1.10 8 | - tensorrt 7.2.2 9 | 10 | # 实现功能 11 | 以resnet18为例,实现了dynamic和static下engine的生成,并提供一个可用重复使用的框架,便于常见torch->onnx->tensorrt方案的实现。 12 | 13 | # 如何运行? 14 | 1. 生成onnx文件 15 | ``` 16 | python torch-onnx.py 17 | ``` 18 | 2. 生成engine文件并推理 19 | ``` 20 | python onnx-tensorrt.py 21 | ``` 22 | -------------------------------------------------------------------------------- /onnx-tensorrt.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import tensorrt as trt 3 | import pycuda.driver as cuda 4 | import pycuda.autoinit 5 | # Utility functions 6 | import utils.inference as inference_utils # TRT/TF inference wrappers 7 | 8 | if __name__ == '__main__': 9 | 10 | # Precision command line argument -> TRT Engine datatype 11 | TRT_PRECISION_TO_DATATYPE = { 12 | 16: trt.DataType.HALF, 13 | 32: trt.DataType.FLOAT 14 | } 15 | # datatype: float 32 16 | trt_engine_datatype = TRT_PRECISION_TO_DATATYPE[32] 17 | 18 | max_batch_size = 1 19 | # create engine 20 | dynamic_shapes={"input": ((1, 3, 224, 224), (3, 3, 224, 224), (32, 3, 224, 224))} 21 | trt_inference_wrapper = inference_utils.TRTInference( 22 | "./resnet18_dynamic.trt", "./resnet18_dynamic.onnx", 23 | trt_engine_datatype, max_batch_size, dynamic_shapes 24 | ) 25 | 26 | # input 27 | dynamic_batch = 6 28 | input_data = np.ones((dynamic_batch, 3, 224, 224), dtype=np.float32) 29 | # At runtime you need to set an optimization profile before setting input dimensions. 30 | # trt_inference_wrapper.context.active_optimization_profile = 0 31 | # specifying runtime dimensions 32 | trt_inference_wrapper.context.set_binding_shape(0, input_data.shape) 33 | # output 34 | output_shapes = [(dynamic_batch, 1000)] 35 | 36 | trt_outputs = trt_inference_wrapper.infer(input_data, output_shapes) 37 | 38 | print(trt_outputs[0].shape) 39 | 40 | # ----------------------- static batch size -------------------- # 41 | max_batch_size = 2 42 | trt_inference_static_wrapper = inference_utils.TRTInference( 43 | "./resnet18_static.trt", "./resnet18_static.onnx", 44 | trt_engine_datatype, max_batch_size 45 | ) 46 | input_data = np.ones((2, 3, 224, 224), dtype=np.float32) 47 | output_shapes = [(2, 1000)] 48 | trt_outputs = trt_inference_static_wrapper.infer(input_data, output_shapes) 49 | 50 | print(trt_outputs[0].shape) 51 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | numpy==1.13.3 2 | opencv_python==4.5.3.56 3 | torch==1.8.0+cu111 4 | torchvision==0.9.0+cu111 5 | tensorrt==7.2.2.3 6 | pycuda==2021.1 7 | -------------------------------------------------------------------------------- /torch-onnx.py: -------------------------------------------------------------------------------- 1 | from torchvision import models 2 | import torch 3 | 4 | if __name__ == "__main__": 5 | net = models.resnet18(pretrained=True) 6 | net.eval() 7 | dummy_input = torch.rand((2, 3, 224, 224)) 8 | dynamic_axes = {"input": {0: "batch"}, "output":{0:"batch"}} 9 | torch.onnx.export(net, dummy_input, "resnet18_dynamic.onnx", 10 | input_names=["input"], output_names=["output"], 11 | export_params=True, dynamic_axes=dynamic_axes, 12 | opset_version=11) 13 | # static batch size 14 | torch.onnx.export(net, dummy_input, "resnet18_static.onnx", 15 | input_names=["input"], output_names=["output"], 16 | export_params=True, 17 | opset_version=11) -------------------------------------------------------------------------------- /utils/engine.py: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright 1993-2019 NVIDIA Corporation. All rights reserved. 3 | # 4 | # NOTICE TO LICENSEE: 5 | # 6 | # This source code and/or documentation ("Licensed Deliverables") are 7 | # subject to NVIDIA intellectual property rights under U.S. and 8 | # international Copyright laws. 9 | # 10 | # These Licensed Deliverables contained herein is PROPRIETARY and 11 | # CONFIDENTIAL to NVIDIA and is being provided under the terms and 12 | # conditions of a form of NVIDIA software license agreement by and 13 | # between NVIDIA and Licensee ("License Agreement") or electronically 14 | # accepted by Licensee. Notwithstanding any terms or conditions to 15 | # the contrary in the License Agreement, reproduction or disclosure 16 | # of the Licensed Deliverables to any third party without the express 17 | # written consent of NVIDIA is prohibited. 18 | # 19 | # NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE 20 | # LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE 21 | # SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS 22 | # PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. 23 | # NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED 24 | # DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, 25 | # NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. 26 | # NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE 27 | # LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY 28 | # SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY 29 | # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, 30 | # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS 31 | # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 32 | # OF THESE LICENSED DELIVERABLES. 33 | # 34 | # U.S. Government End Users. These Licensed Deliverables are a 35 | # "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT 36 | # 1995), consisting of "commercial computer software" and "commercial 37 | # computer software documentation" as such terms are used in 48 38 | # C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government 39 | # only as a commercial end item. Consistent with 48 C.F.R.12.212 and 40 | # 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all 41 | # U.S. Government End Users acquire the Licensed Deliverables with 42 | # only those rights set forth herein. 43 | # 44 | # Any use of the Licensed Deliverables in individual and commercial 45 | # software must include, in the user documentation and internal 46 | # comments to the code, the above Disclaimer and U.S. Government End 47 | # Users Notice. 48 | # 49 | 50 | # Utility functions for building/saving/loading TensorRT Engine 51 | import os 52 | 53 | import tensorrt as trt 54 | import pycuda.driver as cuda 55 | 56 | 57 | # Simple helper data class that's a little nicer to use than a 2-tuple. 58 | class HostDeviceMem(object): 59 | def __init__(self, host_mem, device_mem): 60 | self.host = host_mem 61 | self.device = device_mem 62 | 63 | def __str__(self): 64 | return "Host:\n" + str(self.host) + "\nDevice:\n" + str(self.device) 65 | 66 | def __repr__(self): 67 | return self.__str__() 68 | 69 | 70 | def allocate_buffers(engine, context): 71 | """Allocates host and device buffer for TRT engine inference. 72 | 73 | This function is similair to the one in ../../common.py, but 74 | converts network outputs (which are np.float32) appropriately 75 | before writing them to Python buffer. This is needed, since 76 | TensorRT plugins doesn't support output type description, and 77 | in our particular case, we use NMS plugin as network output. 78 | 79 | Args: 80 | engine (trt.ICudaEngine): TensorRT engine 81 | 82 | Returns: 83 | inputs [HostDeviceMem]: engine input memory 84 | outputs [HostDeviceMem]: engine output memory 85 | bindings [int]: buffer to device bindings 86 | stream (cuda.Stream): cuda stream for engine inference synchronization 87 | """ 88 | inputs = [] 89 | outputs = [] 90 | bindings = [] 91 | stream = cuda.Stream() 92 | 93 | # Current NMS implementation in TRT only supports DataType.FLOAT but 94 | # it may change in the future, which could brake this sample here 95 | # when using lower precision [e.g. NMS output would not be np.float32 96 | # anymore, even though this is assumed in binding_to_type] 97 | 98 | for binding in range(engine.num_bindings): 99 | size = trt.volume(context.get_binding_shape(binding)) 100 | # size = trt.volume(engine.get_binding_shape(binding)) 101 | dtype = trt.nptype(engine.get_binding_dtype(binding)) 102 | # Allocate host and device buffers 103 | host_mem = cuda.pagelocked_empty(size, dtype) 104 | device_mem = cuda.mem_alloc(host_mem.nbytes) 105 | # Append the device buffer to device bindings. 106 | bindings.append(int(device_mem)) 107 | # Append to the appropriate list. 108 | if engine.binding_is_input(binding): 109 | inputs.append(HostDeviceMem(host_mem, device_mem)) 110 | else: 111 | outputs.append(HostDeviceMem(host_mem, device_mem)) 112 | return inputs, outputs, bindings, stream 113 | 114 | 115 | def build_engine(onnx_file_path, trt_logger, trt_engine_datatype=trt.DataType.FLOAT, batch_size=1, silent=False, dynamic_shapes={}): 116 | """Takes an ONNX file and creates a TensorRT engine to run inference with""" 117 | EXPLICIT_BATCH = [] if trt.__version__[0] < '7' else [1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)] 118 | with trt.Builder(trt_logger) as builder, builder.create_network(*EXPLICIT_BATCH) as network, trt.OnnxParser(network, 119 | trt_logger) as parser: 120 | builder.max_batch_size = batch_size 121 | config = builder.create_builder_config() 122 | config.max_workspace_size = 1 << 30 # work space 123 | if trt_engine_datatype == trt.DataType.HALF: # float 16 124 | config.set_flag(trt.BuilderFlag.FP16) 125 | 126 | # Parse model file 127 | if not os.path.exists(onnx_file_path): 128 | print('ONNX file {} not found, please run yolov3_to_onnx.py first to generate it.'.format(onnx_file_path)) 129 | exit(0) 130 | 131 | print('Loading ONNX file from path {}...'.format(onnx_file_path)) 132 | with open(onnx_file_path, 'rb') as model: 133 | print('Beginning ONNX file parsing') 134 | if not parser.parse(model.read()): 135 | print('ERROR: Failed to parse the ONNX file.') 136 | for error in range(parser.num_errors): 137 | print(parser.get_error(error)) 138 | return None 139 | 140 | print('Completed parsing of ONNX file') 141 | if not silent: 142 | print('Building an engine from file {}; this may take a while...'.format(onnx_file_path)) 143 | # dynamic batch_size 144 | if len(dynamic_shapes) > 0: 145 | print("===> using dynamic shapes!") 146 | profile = builder.create_optimization_profile() 147 | 148 | for binding_name, dynamic_shape in dynamic_shapes.items(): 149 | min_shape, opt_shape, max_shape = dynamic_shape 150 | profile.set_shape(binding_name, min_shape, opt_shape, max_shape) 151 | 152 | config.add_optimization_profile(profile) 153 | 154 | return builder.build_engine(network, config) 155 | 156 | 157 | def save_engine(engine, engine_dest_path): 158 | buf = engine.serialize() 159 | with open(engine_dest_path, 'wb') as f: 160 | f.write(buf) 161 | 162 | 163 | def load_engine(trt_runtime, engine_path): 164 | with open(engine_path, 'rb') as f: 165 | engine_data = f.read() 166 | engine = trt_runtime.deserialize_cuda_engine(engine_data) 167 | return engine 168 | -------------------------------------------------------------------------------- /utils/inference.py: -------------------------------------------------------------------------------- 1 | # Utility functions for performing image inference 2 | # 3 | # Copyright 1993-2019 NVIDIA Corporation. All rights reserved. 4 | # 5 | # NOTICE TO LICENSEE: 6 | # 7 | # This source code and/or documentation ("Licensed Deliverables") are 8 | # subject to NVIDIA intellectual property rights under U.S. and 9 | # international Copyright laws. 10 | # 11 | # These Licensed Deliverables contained herein is PROPRIETARY and 12 | # CONFIDENTIAL to NVIDIA and is being provided under the terms and 13 | # conditions of a form of NVIDIA software license agreement by and 14 | # between NVIDIA and Licensee ("License Agreement") or electronically 15 | # accepted by Licensee. Notwithstanding any terms or conditions to 16 | # the contrary in the License Agreement, reproduction or disclosure 17 | # of the Licensed Deliverables to any third party without the express 18 | # written consent of NVIDIA is prohibited. 19 | # 20 | # NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE 21 | # LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE 22 | # SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS 23 | # PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. 24 | # NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED 25 | # DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, 26 | # NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. 27 | # NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE 28 | # LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY 29 | # SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY 30 | # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, 31 | # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS 32 | # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 33 | # OF THESE LICENSED DELIVERABLES. 34 | # 35 | # U.S. Government End Users. These Licensed Deliverables are a 36 | # "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT 37 | # 1995), consisting of "commercial computer software" and "commercial 38 | # computer software documentation" as such terms are used in 48 39 | # C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government 40 | # only as a commercial end item. Consistent with 48 C.F.R.12.212 and 41 | # 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all 42 | # U.S. Government End Users acquire the Licensed Deliverables with 43 | # only those rights set forth herein. 44 | # 45 | # Any use of the Licensed Deliverables in individual and commercial 46 | # software must include, in the user documentation and internal 47 | # comments to the code, the above Disclaimer and U.S. Government End 48 | # Users Notice. 49 | 50 | import os 51 | import sys 52 | import time 53 | # from PIL import Image 54 | import tensorrt as trt 55 | import pycuda.driver as cuda 56 | import pycuda.autoinit 57 | import numpy as np 58 | import utils.engine as engine_utils # TRT Engine creation/save/load utils 59 | import cv2 60 | 61 | # TensorRT logger singleton 62 | TRT_LOGGER = trt.Logger(trt.Logger.WARNING) 63 | 64 | 65 | class TRTInference(object): 66 | """Manages TensorRT objects for model inference.""" 67 | 68 | def __init__(self, trt_engine_path, onnx_model_path, trt_engine_datatype=trt.DataType.FLOAT, batch_size=1, dynamic_shapes={}): 69 | """Initializes TensorRT objects needed for model inference. 70 | 71 | Args: 72 | trt_engine_path (str): path where TensorRT engine should be stored 73 | uff_model_path (str): path of .uff model 74 | trt_engine_datatype (trt.DataType): 75 | requested precision of TensorRT engine used for inference 76 | batch_size (int): batch size for which engine 77 | should be optimized for 78 | """ 79 | 80 | # Initialize runtime needed for loading TensorRT engine from file 81 | self.trt_runtime = trt.Runtime(TRT_LOGGER) 82 | # TRT engine placeholder 83 | self.trt_engine = None 84 | 85 | # Display requested engine settings to stdout 86 | print("TensorRT inference engine settings:") 87 | print(" * Inference precision - {}".format(trt_engine_datatype)) 88 | print(" * Max batch size - {}\n".format(batch_size)) 89 | 90 | # If engine is not cached, we need to build it 91 | if not os.path.exists(trt_engine_path): 92 | # This function uses supplied .uff file 93 | # alongside with UffParser to build TensorRT 94 | # engine. For more details, check implmentation 95 | self.trt_engine = engine_utils.build_engine( 96 | onnx_model_path, TRT_LOGGER, 97 | trt_engine_datatype=trt_engine_datatype, 98 | batch_size=batch_size, dynamic_shapes=dynamic_shapes) 99 | # Save the engine to file 100 | print("Completed creating Engine") 101 | engine_utils.save_engine(self.trt_engine, trt_engine_path) 102 | 103 | # If we get here, the file with engine exists, so we can load it 104 | if not self.trt_engine: 105 | print("Loading cached TensorRT engine from {}".format( 106 | trt_engine_path)) 107 | self.trt_engine = engine_utils.load_engine( 108 | self.trt_runtime, trt_engine_path) 109 | 110 | # Execution context is needed for inference 111 | self.context = self.trt_engine.create_execution_context() 112 | 113 | def infer(self, input_data, output_shapes): 114 | """Infers model on given image. 115 | 116 | Args: 117 | image_path (str): image to run object detection model on 118 | """ 119 | 120 | # This allocates memory for network inputs/outputs on both CPU and GPU 121 | self.inputs, self.outputs, self.bindings, self.stream = \ 122 | engine_utils.allocate_buffers(self.trt_engine, self.context) 123 | 124 | input_data = np.array(input_data, dtype=np.float32, order='C') 125 | 126 | np.copyto(self.inputs[0].host, input_data.ravel()) 127 | 128 | # Fetch output from the model 129 | trt_outputs = do_inference_v2( 130 | self.context, bindings=self.bindings, inputs=self.inputs, 131 | outputs=self.outputs, stream=self.stream) 132 | 133 | # Before doing post-processing, we need to reshape the outputs as the common.do_inference will 134 | # give us flat arrays. 135 | outputs = [output.reshape(shape) for output, shape in zip(trt_outputs, output_shapes)] 136 | # And return results 137 | return outputs 138 | 139 | 140 | # This function is generalized for multiple inputs/outputs for full dimension networks. 141 | # inputs and outputs are expected to be lists of HostDeviceMem objects. 142 | def do_inference_v2(context, bindings, inputs, outputs, stream): 143 | 144 | # Transfer input data to the GPU. 145 | [cuda.memcpy_htod_async(inp.device, inp.host, stream) for inp in inputs] 146 | # Run inference. 147 | context.execute_async_v2(bindings=bindings, stream_handle=stream.handle) 148 | # Transfer predictions back from the GPU. 149 | [cuda.memcpy_dtoh_async(out.host, out.device, stream) for out in outputs] 150 | # Synchronize the stream 151 | stream.synchronize() 152 | # Return only the host outputs. 153 | return [out.host for out in outputs] 154 | --------------------------------------------------------------------------------