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.

146 lines
7.2KB

  1. """Exports a YOLOv5 *.pt model to TorchScript, ONNX, CoreML formats
  2. Usage:
  3. $ python path/to/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('--include', nargs='+', default=['torchscript', 'onnx', 'coreml'], help='include formats')
  25. parser.add_argument('--half', action='store_true', help='FP16 half-precision export')
  26. parser.add_argument('--inplace', action='store_true', help='set YOLOv5 Detect() inplace=True')
  27. parser.add_argument('--train', action='store_true', help='model.train() mode')
  28. parser.add_argument('--optimize', action='store_true', help='optimize TorchScript for mobile') # TorchScript-only
  29. parser.add_argument('--dynamic', action='store_true', help='dynamic ONNX axes') # ONNX-only
  30. parser.add_argument('--simplify', action='store_true', help='simplify ONNX model') # ONNX-only
  31. parser.add_argument('--opset-version', type=int, default=12, help='ONNX opset version') # ONNX-only
  32. opt = parser.parse_args()
  33. opt.img_size *= 2 if len(opt.img_size) == 1 else 1 # expand
  34. opt.include = [x.lower() for x in opt.include]
  35. print(opt)
  36. set_logging()
  37. t = time.time()
  38. # Load PyTorch model
  39. device = select_device(opt.device)
  40. assert not (opt.device.lower() == 'cpu' and opt.half), '--half only compatible with GPU export, i.e. use --device 0'
  41. model = attempt_load(opt.weights, map_location=device) # load FP32 model
  42. labels = model.names
  43. # Input
  44. gs = int(max(model.stride)) # grid size (max stride)
  45. opt.img_size = [check_img_size(x, gs) for x in opt.img_size] # verify img_size are gs-multiples
  46. img = torch.zeros(opt.batch_size, 3, *opt.img_size).to(device) # image size(1,3,320,192) iDetection
  47. # Update model
  48. if opt.half:
  49. img, model = img.half(), model.half() # to FP16
  50. model.train() if opt.train else model.eval() # training mode = no Detect() layer grid construction
  51. for k, m in model.named_modules():
  52. m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility
  53. if isinstance(m, models.common.Conv): # assign export-friendly activations
  54. if isinstance(m.act, nn.Hardswish):
  55. m.act = Hardswish()
  56. elif isinstance(m.act, nn.SiLU):
  57. m.act = SiLU()
  58. elif isinstance(m, models.yolo.Detect):
  59. m.inplace = opt.inplace
  60. m.onnx_dynamic = opt.dynamic
  61. # m.forward = m.forward_export # assign forward (optional)
  62. for _ in range(2):
  63. y = model(img) # dry runs
  64. print(f"\n{colorstr('PyTorch:')} starting from {opt.weights} ({file_size(opt.weights):.1f} MB)")
  65. # TorchScript export -----------------------------------------------------------------------------------------------
  66. if 'torchscript' in opt.include or 'coreml' in opt.include:
  67. prefix = colorstr('TorchScript:')
  68. try:
  69. print(f'\n{prefix} starting export with torch {torch.__version__}...')
  70. f = opt.weights.replace('.pt', '.torchscript.pt') # filename
  71. ts = torch.jit.trace(model, img, strict=False)
  72. (optimize_for_mobile(ts) if opt.optimize else ts).save(f)
  73. print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
  74. except Exception as e:
  75. print(f'{prefix} export failure: {e}')
  76. # ONNX export ------------------------------------------------------------------------------------------------------
  77. if 'onnx' in opt.include:
  78. prefix = colorstr('ONNX:')
  79. try:
  80. import onnx
  81. print(f'{prefix} starting export with onnx {onnx.__version__}...')
  82. f = opt.weights.replace('.pt', '.onnx') # filename
  83. torch.onnx.export(model, img, f, verbose=False, opset_version=opt.opset_version,
  84. training=torch.onnx.TrainingMode.TRAINING if opt.train else torch.onnx.TrainingMode.EVAL,
  85. do_constant_folding=not opt.train,
  86. input_names=['images'],
  87. output_names=['output'],
  88. dynamic_axes={'images': {0: 'batch', 2: 'height', 3: 'width'}, # shape(1,3,640,640)
  89. 'output': {0: 'batch', 1: 'anchors'} # shape(1,25200,85)
  90. } if opt.dynamic else None)
  91. # Checks
  92. model_onnx = onnx.load(f) # load onnx model
  93. onnx.checker.check_model(model_onnx) # check onnx model
  94. # print(onnx.helper.printable_graph(model_onnx.graph)) # print
  95. # Simplify
  96. if opt.simplify:
  97. try:
  98. check_requirements(['onnx-simplifier'])
  99. import onnxsim
  100. print(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...')
  101. model_onnx, check = onnxsim.simplify(
  102. model_onnx,
  103. dynamic_input_shape=opt.dynamic,
  104. input_shapes={'images': list(img.shape)} if opt.dynamic else None)
  105. assert check, 'assert check failed'
  106. onnx.save(model_onnx, f)
  107. except Exception as e:
  108. print(f'{prefix} simplifier failure: {e}')
  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. # CoreML export ----------------------------------------------------------------------------------------------------
  113. if 'coreml' in opt.include:
  114. prefix = colorstr('CoreML:')
  115. try:
  116. import coremltools as ct
  117. print(f'{prefix} starting export with coremltools {ct.__version__}...')
  118. assert opt.train, 'CoreML exports should be placed in model.train() mode with `python export.py --train`'
  119. model = ct.convert(ts, inputs=[ct.ImageType('image', shape=img.shape, scale=1 / 255.0, bias=[0, 0, 0])])
  120. f = opt.weights.replace('.pt', '.mlmodel') # filename
  121. model.save(f)
  122. print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
  123. except Exception as e:
  124. print(f'{prefix} export failure: {e}')
  125. # Finish
  126. print(f'\nExport complete ({time.time() - t:.2f}s). Visualize with https://github.com/lutzroeder/netron.')