# Copyright (c) 2024 Justin Davis (davisjustin302@gmail.com)## MIT License# mypy: disable-error-code="import-untyped"from__future__importannotationsimportcontextlibfrompathlibimportPathwithcontextlib.suppress(ImportError):importtensorrtastrtfromtrtutils._configimportCONFIGfromtrtutils._logimportLOG
[docs]defread_onnx(onnx:Path|str,workspace:float=4.0,)->tuple[trt.INetworkDefinition,trt.IBuilder,trt.IBuilderConfig,trt.IOnnxParser,]:""" Open an ONNX model and generate TensorRT network, builder, config, and parser. Parameters ---------- onnx : Path, str The path to the onnx model. workspace : float The size of the workspace in gigabytes. Default is 4.0 GiB. Returns ------- tuple[trt.INetworkDefinition, trt.IBuilder, trt.IBuilderConfig, trt.IOnnxParser] The network, builder, config, and parser. Raises ------ FileNotFoundError If the onnx model does not exist IsADirectoryError If the onnx model path is a directory ValueError If the onnx model path does not have .onnx extension RuntimeError If the ONNX model cannot be parsed """# load libnvinfer pluginsCONFIG.load_plugins()onnx_path=Path(onnx).resolve()ifnotonnx_path.exists():err_msg=f"Could not find ONNX model at: {onnx_path}"raiseFileNotFoundError(err_msg)ifonnx_path.is_dir():err_msg=f"Path given is a directory: {onnx_path}"raiseIsADirectoryError(err_msg)ifonnx_path.suffix!=".onnx":err_msg="File does not have .onnx extension"raiseValueError(err_msg)builder=trt.Builder(LOG)config=builder.create_builder_config()# setup the workspace sizeworkspace_bytes=int(workspace*(1<<30))ifhasattr(config,"max_workspace_size"):config.max_workspace_size=workspace_byteselse:config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE,workspace_bytes)# make networknetwork=builder.create_network(1<<int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH),)# setup parserparser=trt.OnnxParser(network,LOG)withonnx_path.open("rb")asf:ifnotparser.parse(f.read()):forerrorinrange(parser.num_errors):LOG.error(parser.get_error(error))err_msg="Cannot parse ONNX file"raiseRuntimeError(err_msg)returnnetwork,builder,config,parser