export.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. """Exports a YOLOv5 *.pt model to ONNX and TorchScript formats
  2. Usage:
  3. $ export PYTHONPATH="$PWD" && python models/export.py --weights ./weights/yolov5s.pt --img 640 --batch 1
  4. """
  5. import argparse
  6. import sys
  7. import time
  8. sys.path.append('./') # to run '$ python *.py' files in subdirectories
  9. import torch
  10. import torch.nn as nn
  11. import models
  12. from models.experimental import attempt_load
  13. from utils.activations import Hardswish, SiLU
  14. from utils.general import set_logging, check_img_size
  15. import onnx
  16. if __name__ == '__main__':
  17. parser = argparse.ArgumentParser()
  18. parser.add_argument('--weights', type=str, default='./yolov5s.pt', help='weights path') # from yolov5/models/
  19. parser.add_argument('--img_size', nargs='+', type=int, default=[640, 640], help='image size') # height, width
  20. parser.add_argument('--batch_size', type=int, default=1, help='batch size')
  21. parser.add_argument('--dynamic', action='store_true', default=False, help='enable dynamic axis in onnx model')
  22. parser.add_argument('--onnx2pb', action='store_true', default=False, help='export onnx to pb')
  23. parser.add_argument('--onnx_infer', action='store_true', default=True, help='onnx infer test')
  24. #=======================TensorRT=================================
  25. parser.add_argument('--onnx2trt', action='store_true', default=False, help='export onnx to tensorrt')
  26. parser.add_argument('--fp16_trt', action='store_true', default=False, help='fp16 infer')
  27. #================================================================
  28. opt = parser.parse_args()
  29. opt.img_size *= 2 if len(opt.img_size) == 1 else 1 # expand
  30. print(opt)
  31. set_logging()
  32. t = time.time()
  33. # Load PyTorch model
  34. model = attempt_load(opt.weights, map_location=torch.device('cpu')) # load FP32 model
  35. delattr(model.model[-1], 'anchor_grid')
  36. model.model[-1].anchor_grid=[torch.zeros(1)] * 3 # nl=3 number of detection layers
  37. model.model[-1].export_cat = True
  38. model.eval()
  39. labels = model.names
  40. # Checks
  41. gs = int(max(model.stride)) # grid size (max stride)
  42. opt.img_size = [check_img_size(x, gs) for x in opt.img_size] # verify img_size are gs-multiples
  43. # Input
  44. img = torch.zeros(opt.batch_size, 3, *opt.img_size) # image size(1,3,320,192) iDetection
  45. # Update model
  46. for k, m in model.named_modules():
  47. m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility
  48. if isinstance(m, models.common.Conv): # assign export-friendly activations
  49. if isinstance(m.act, nn.Hardswish):
  50. m.act = Hardswish()
  51. elif isinstance(m.act, nn.SiLU):
  52. m.act = SiLU()
  53. # elif isinstance(m, models.yolo.Detect):
  54. # m.forward = m.forward_export # assign forward (optional)
  55. if isinstance(m, models.common.ShuffleV2Block):#shufflenet block nn.SiLU
  56. for i in range(len(m.branch1)):
  57. if isinstance(m.branch1[i], nn.SiLU):
  58. m.branch1[i] = SiLU()
  59. for i in range(len(m.branch2)):
  60. if isinstance(m.branch2[i], nn.SiLU):
  61. m.branch2[i] = SiLU()
  62. if isinstance(m, models.common.BlazeBlock):#shufflenet block nn.SiLU
  63. if isinstance(m.relu, nn.SiLU):
  64. m.relu = SiLU()
  65. if isinstance(m, models.common.DoubleBlazeBlock):#shufflenet block nn.SiLU
  66. if isinstance(m.relu, nn.SiLU):
  67. m.relu = SiLU()
  68. for i in range(len(m.branch1)):
  69. if isinstance(m.branch1[i], nn.SiLU):
  70. m.branch1[i] = SiLU()
  71. # for i in range(len(m.branch2)):
  72. # if isinstance(m.branch2[i], nn.SiLU):
  73. # m.branch2[i] = SiLU()
  74. y = model(img) # dry run
  75. # ONNX export
  76. print('\nStarting ONNX export with onnx %s...' % onnx.__version__)
  77. f = opt.weights.replace('.pt', '.onnx') # filename
  78. model.fuse() # only for ONNX
  79. input_names=['input']
  80. output_names=['output']
  81. #tensorrt 7
  82. # grid = model.model[-1].anchor_grid
  83. # model.model[-1].anchor_grid = [a[..., :1, :1, :] for a in grid]
  84. #tensorrt 7
  85. torch.onnx.export(model, img, f, verbose=False, opset_version=12,
  86. input_names=input_names,
  87. output_names=output_names,
  88. dynamic_axes = {'input': {0: 'batch'},
  89. 'output': {0: 'batch'}
  90. } if opt.dynamic else None)
  91. # model.model[-1].anchor_grid = grid
  92. # Checks
  93. onnx_model = onnx.load(f) # load onnx model
  94. onnx.checker.check_model(onnx_model) # check onnx model
  95. print('ONNX export success, saved as %s' % f)
  96. # Finish
  97. print('\nExport complete (%.2fs). Visualize with https://github.com/lutzroeder/netron.' % (time.time() - t))
  98. # onnx infer
  99. if opt.onnx_infer:
  100. import onnxruntime
  101. import numpy as np
  102. providers = ['CPUExecutionProvider']
  103. session = onnxruntime.InferenceSession(f, providers=providers)
  104. im = img.cpu().numpy().astype(np.float32) # torch to numpy
  105. y_onnx = session.run([session.get_outputs()[0].name], {session.get_inputs()[0].name: im})[0]
  106. print("pred's shape is ",y_onnx.shape)
  107. print("max(|torch_pred - onnx_pred|) =",abs(y.cpu().numpy()-y_onnx).max())
  108. # TensorRT export
  109. if opt.onnx2trt:
  110. from torch2trt.trt_model import ONNX_to_TRT
  111. print('\nStarting TensorRT...')
  112. ONNX_to_TRT(onnx_model_path=f,trt_engine_path=f.replace('.onnx', '.trt'),fp16_mode=opt.fp16_trt)
  113. # PB export
  114. if opt.onnx2pb:
  115. print('download the newest onnx_tf by https://github.com/onnx/onnx-tensorflow/tree/master/onnx_tf')
  116. from onnx_tf.backend import prepare
  117. import tensorflow as tf
  118. outpb = f.replace('.onnx', '.pb') # filename
  119. # strict=True maybe leads to KeyError: 'pyfunc_0', check: https://github.com/onnx/onnx-tensorflow/issues/167
  120. tf_rep = prepare(onnx_model, strict=False) # prepare tf representation
  121. tf_rep.export_graph(outpb) # export the model
  122. out_onnx = tf_rep.run(img) # onnx output
  123. # check pb
  124. with tf.Graph().as_default():
  125. graph_def = tf.GraphDef()
  126. with open(outpb, "rb") as f:
  127. graph_def.ParseFromString(f.read())
  128. tf.import_graph_def(graph_def, name="")
  129. with tf.Session() as sess:
  130. init = tf.global_variables_initializer()
  131. input_x = sess.graph.get_tensor_by_name(input_names[0]+':0') # input
  132. outputs = []
  133. for i in output_names:
  134. outputs.append(sess.graph.get_tensor_by_name(i+':0'))
  135. out_pb = sess.run(outputs, feed_dict={input_x: img})
  136. print(f'out_pytorch {y}')
  137. print(f'out_onnx {out_onnx}')
  138. print(f'out_pb {out_pb}')