You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

134 lines
6.1KB

  1. """Exports a YOLOv5 *.pt model to ONNX and TorchScript formats
  2. Usage:
  3. $ export PYTHONPATH="$PWD" && python models/export.py --weights yolov5s.pt --img 640 --batch 1
  4. """
  5. import argparse
  6. import sys
  7. import time
  8. from pathlib import Path
  9. sys.path.append(Path(__file__).parent.parent.absolute().__str__()) # to run '$ python *.py' files in subdirectories
  10. import torch
  11. import torch.nn as nn
  12. from torch.utils.mobile_optimizer import optimize_for_mobile
  13. import models
  14. from models.experimental import attempt_load
  15. from utils.activations import Hardswish, SiLU
  16. from utils.general import colorstr, check_img_size, check_requirements, file_size, set_logging
  17. from utils.torch_utils import select_device
  18. if __name__ == '__main__':
  19. parser = argparse.ArgumentParser()
  20. parser.add_argument('--weights', type=str, default='./yolov5s.pt', help='weights path')
  21. parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='image size') # height, width
  22. parser.add_argument('--batch-size', type=int, default=1, help='batch size')
  23. parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
  24. parser.add_argument('--half', action='store_true', help='FP16 half-precision export')
  25. parser.add_argument('--inplace', action='store_true', help='set YOLOv5 Detect() inplace=True')
  26. parser.add_argument('--dynamic', action='store_true', help='dynamic ONNX axes') # ONNX-only
  27. parser.add_argument('--simplify', action='store_true', help='simplify ONNX model') # ONNX-only
  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. device = select_device(opt.device)
  35. model = attempt_load(opt.weights, map_location=device) # load FP32 model
  36. labels = model.names
  37. # Checks
  38. gs = int(max(model.stride)) # grid size (max stride)
  39. opt.img_size = [check_img_size(x, gs) for x in opt.img_size] # verify img_size are gs-multiples
  40. assert not (opt.device.lower() == "cpu" and opt.half), '--half only compatible with GPU export, i.e. use --device 0'
  41. # Input
  42. img = torch.zeros(opt.batch_size, 3, *opt.img_size).to(device) # image size(1,3,320,192) iDetection
  43. # Update model
  44. if opt.half:
  45. img, model = img.half(), model.half() # to FP16
  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.inplace = opt.inplace
  55. m.onnx_dynamic = opt.dynamic
  56. # m.forward = m.forward_export # assign forward (optional)
  57. for _ in range(2):
  58. y = model(img) # dry runs
  59. print(f"\n{colorstr('PyTorch:')} starting from {opt.weights} ({file_size(opt.weights):.1f} MB)")
  60. # TorchScript export -----------------------------------------------------------------------------------------------
  61. prefix = colorstr('TorchScript:')
  62. try:
  63. print(f'\n{prefix} starting export with torch {torch.__version__}...')
  64. f = opt.weights.replace('.pt', '.torchscript.pt') # filename
  65. ts = torch.jit.trace(model, img, strict=False)
  66. ts = optimize_for_mobile(ts) # https://pytorch.org/tutorials/recipes/script_optimized.html
  67. ts.save(f)
  68. print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
  69. except Exception as e:
  70. print(f'{prefix} export failure: {e}')
  71. # ONNX export ------------------------------------------------------------------------------------------------------
  72. prefix = colorstr('ONNX:')
  73. try:
  74. import onnx
  75. print(f'{prefix} starting export with onnx {onnx.__version__}...')
  76. f = opt.weights.replace('.pt', '.onnx') # filename
  77. torch.onnx.export(model, img, f, verbose=False, opset_version=12, input_names=['images'],
  78. dynamic_axes={'images': {0: 'batch', 2: 'height', 3: 'width'}, # size(1,3,640,640)
  79. 'output': {0: 'batch', 2: 'y', 3: 'x'}} if opt.dynamic else None)
  80. # Checks
  81. model_onnx = onnx.load(f) # load onnx model
  82. onnx.checker.check_model(model_onnx) # check onnx model
  83. # print(onnx.helper.printable_graph(model_onnx.graph)) # print
  84. # Simplify
  85. if opt.simplify:
  86. try:
  87. check_requirements(['onnx-simplifier'])
  88. import onnxsim
  89. print(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...')
  90. model_onnx, check = onnxsim.simplify(model_onnx,
  91. dynamic_input_shape=opt.dynamic,
  92. input_shapes={'images': list(img.shape)} if opt.dynamic else None)
  93. assert check, 'assert check failed'
  94. onnx.save(model_onnx, f)
  95. except Exception as e:
  96. print(f'{prefix} simplifier failure: {e}')
  97. print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
  98. except Exception as e:
  99. print(f'{prefix} export failure: {e}')
  100. # CoreML export ----------------------------------------------------------------------------------------------------
  101. prefix = colorstr('CoreML:')
  102. try:
  103. import coremltools as ct
  104. print(f'{prefix} starting export with coremltools {ct.__version__}...')
  105. # convert model from torchscript and apply pixel scaling as per detect.py
  106. model = ct.convert(ts, inputs=[ct.ImageType(name='image', shape=img.shape, scale=1 / 255.0, bias=[0, 0, 0])])
  107. f = opt.weights.replace('.pt', '.mlmodel') # filename
  108. model.save(f)
  109. print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
  110. except Exception as e:
  111. print(f'{prefix} export failure: {e}')
  112. # Finish
  113. print(f'\nExport complete ({time.time() - t:.2f}s). Visualize with https://github.com/lutzroeder/netron.')