|
| 1 | + |
| 2 | +import os |
| 3 | +import os.path as osp |
| 4 | +import cv2 |
| 5 | +import numpy as np |
| 6 | +import logging |
| 7 | +import argparse |
| 8 | + |
| 9 | +import tensorrt as trt |
| 10 | +import pycuda.driver as cuda |
| 11 | +import pycuda.autoinit |
| 12 | + |
| 13 | + |
| 14 | +parser = argparse.ArgumentParser() |
| 15 | +subparsers = parser.add_subparsers(dest="command") |
| 16 | +compile_parser = subparsers.add_parser('compile') |
| 17 | +compile_parser.add_argument('--onnx') |
| 18 | +compile_parser.add_argument('--quant', default='fp32') |
| 19 | +compile_parser.add_argument('--savepth', default='./model.trt') |
| 20 | +run_parser = subparsers.add_parser('run') |
| 21 | +run_parser.add_argument('--mdpth') |
| 22 | +run_parser.add_argument('--impth') |
| 23 | +run_parser.add_argument('--outpth', default='./res.png') |
| 24 | +args = parser.parse_args() |
| 25 | + |
| 26 | + |
| 27 | +np.random.seed(123) |
| 28 | +in_datatype = trt.nptype(trt.float32) |
| 29 | +out_datatype = trt.nptype(trt.int32) |
| 30 | +palette = np.random.randint(0, 256, (256, 3)).astype(np.uint8) |
| 31 | + |
| 32 | +ctx = pycuda.autoinit.context |
| 33 | +trt.init_libnvinfer_plugins(None, "") |
| 34 | +TRT_LOGGER = trt.Logger() |
| 35 | + |
| 36 | + |
| 37 | + |
| 38 | +def get_image(impth, size): |
| 39 | + mean = np.array([0.485, 0.456, 0.406], dtype=np.float32)[:, None, None] |
| 40 | + var = np.array([0.229, 0.224, 0.225], dtype=np.float32)[:, None, None] |
| 41 | + iH, iW = size[0], size[1] |
| 42 | + img = cv2.imread(impth)[:, :, ::-1] |
| 43 | + orgH, orgW, _ = img.shape |
| 44 | + img = cv2.resize(img, (iW, iH)).astype(np.float32) |
| 45 | + img = img.transpose(2, 0, 1) / 255. |
| 46 | + img = (img - mean) / var |
| 47 | + return img, (orgH, orgW) |
| 48 | + |
| 49 | + |
| 50 | + |
| 51 | +def allocate_buffers(engine): |
| 52 | + h_input = cuda.pagelocked_empty( |
| 53 | + trt.volume(engine.get_binding_shape(0)), dtype=in_datatype) |
| 54 | + print(engine.get_binding_shape(0)) |
| 55 | + d_input = cuda.mem_alloc(h_input.nbytes) |
| 56 | + h_outputs, d_outputs = [], [] |
| 57 | + n_outs = 1 |
| 58 | + for i in range(n_outs): |
| 59 | + h_output = cuda.pagelocked_empty( |
| 60 | + trt.volume(engine.get_binding_shape(i+1)), |
| 61 | + dtype=out_datatype) |
| 62 | + d_output = cuda.mem_alloc(h_output.nbytes) |
| 63 | + h_outputs.append(h_output) |
| 64 | + d_outputs.append(d_output) |
| 65 | + stream = cuda.Stream() |
| 66 | + return ( |
| 67 | + stream, |
| 68 | + h_input, |
| 69 | + d_input, |
| 70 | + h_outputs, |
| 71 | + d_outputs, |
| 72 | + ) |
| 73 | + |
| 74 | + |
| 75 | +def build_engine_from_onnx(onnx_file_path): |
| 76 | + engine = None ## add this to avoid return deleted engine |
| 77 | + EXPLICIT_BATCH = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH) |
| 78 | + with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, builder.create_builder_config() as config, trt.OnnxParser(network, TRT_LOGGER) as parser, trt.Runtime(TRT_LOGGER) as runtime: |
| 79 | + |
| 80 | + # Parse model file |
| 81 | + print(f'Loading ONNX file from path {onnx_file_path}...') |
| 82 | + assert os.path.exists(onnx_file_path), f'cannot find {onnx_file_path}' |
| 83 | + with open(onnx_file_path, 'rb') as fr: |
| 84 | + if not parser.parse(fr.read()): |
| 85 | + print ('ERROR: Failed to parse the ONNX file.') |
| 86 | + for error in range(parser.num_errors): |
| 87 | + print (parser.get_error(error)) |
| 88 | + assert False |
| 89 | + |
| 90 | + # build settings |
| 91 | + builder.max_batch_size = 128 |
| 92 | + config.max_workspace_size = 1 << 30 # 1G |
| 93 | + if args.quant == 'fp16': |
| 94 | + config.set_flag(trt.BuilderFlag.FP16) |
| 95 | + |
| 96 | + print("Start to build Engine") |
| 97 | + plan = builder.build_serialized_network(network, config) |
| 98 | + engine = runtime.deserialize_cuda_engine(plan) |
| 99 | + return engine |
| 100 | + |
| 101 | + |
| 102 | +def serialize_engine_to_file(engine, savepth): |
| 103 | + plan = engine.serialize() |
| 104 | + with open(savepth, "wb") as fw: |
| 105 | + fw.write(plan) |
| 106 | + |
| 107 | + |
| 108 | +def deserialize_engine_from_file(savepth): |
| 109 | + with open(savepth, 'rb') as fr, trt.Runtime(TRT_LOGGER) as runtime: |
| 110 | + engine = runtime.deserialize_cuda_engine(fr.read()) |
| 111 | + return engine |
| 112 | + |
| 113 | + |
| 114 | +def main(): |
| 115 | + if args.command == 'compile': |
| 116 | + engine = build_engine_from_onnx(args.onnx) |
| 117 | + serialize_engine_to_file(engine, args.savepth) |
| 118 | + |
| 119 | + elif args.command == 'run': |
| 120 | + engine = deserialize_engine_from_file(args.mdpth) |
| 121 | + |
| 122 | + ishape = engine.get_binding_shape(0) |
| 123 | + img, (orgH, orgW) = get_image(args.impth, ishape[2:]) |
| 124 | + |
| 125 | + ## create engine and allocate bffers |
| 126 | + ( |
| 127 | + stream, |
| 128 | + h_input, |
| 129 | + d_input, |
| 130 | + h_outputs, |
| 131 | + d_outputs, |
| 132 | + ) = allocate_buffers(engine) |
| 133 | + ctx.push() |
| 134 | + context = engine.create_execution_context() |
| 135 | + ctx.pop() |
| 136 | + bds = [int(d_input), ] + [int(el) for el in d_outputs] |
| 137 | + |
| 138 | + h_input = np.ascontiguousarray(img) |
| 139 | + cuda.memcpy_htod_async(d_input, h_input, stream) |
| 140 | + context.execute_async( |
| 141 | + bindings=bds, stream_handle=stream.handle) |
| 142 | + for h_output, d_output in zip(h_outputs, d_outputs): |
| 143 | + cuda.memcpy_dtoh_async(h_output, d_output, stream) |
| 144 | + stream.synchronize() |
| 145 | + |
| 146 | + out = palette[h_outputs[0]] |
| 147 | + outshape = engine.get_binding_shape(1) |
| 148 | + H, W = outshape[1], outshape[2] |
| 149 | + out = out.reshape(H, W, 3) |
| 150 | + out = cv2.resize(out, (orgW, orgH)) |
| 151 | + cv2.imwrite(args.outpth, out) |
| 152 | + |
| 153 | + |
| 154 | + |
| 155 | +if __name__ == '__main__': |
| 156 | + main() |
| 157 | + |
0 commit comments