-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrt_conversion.py
68 lines (54 loc) · 2.29 KB
/
trt_conversion.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import tensorrt as trt
def convert(onnx_path, trt_path):
# Create a TensorRT builder and network with explicit batch flag
explicit_batch = 1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)
builder = trt.Builder(trt.Logger(trt.Logger.WARNING))
network = builder.create_network(explicit_batch)
# Parse the ONNX model
parser = trt.OnnxParser(network, trt.Logger(trt.Logger.WARNING))
with open(onnx_path, 'rb') as onnx:
if not parser.parse(onnx.read()):
for error in range(parser.num_errors):
print(parser.get_error(error))
raise ValueError("Failed to parse ONNX model!")
# Configure builder options
builder_config = builder.create_builder_config()
# Build TensorRT engine
engine = builder.build_serialized_network(network, builder_config)
# Save the serialized TensorRT engine
with open(trt_path, 'wb') as f:
f.write(engine)
def main():
# Parse the arguments.
parser = argparse.ArgumentParser(
description='Convert the X-Mobility ONNX to TRT engine.')
parser.add_argument('--onnx-path',
'-o',
type=str,
required=True,
help='The path to the input onnx file.')
parser.add_argument('--trt-path',
'-t',
type=str,
required=True,
help='The path to the output TRT engine.')
args = parser.parse_args()
# Run the conversion.
convert(args.onnx_path, args.trt_path)
if __name__ == '__main__':
main()