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.

export.py 5.5KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  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. 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 colorstr, check_img_size, check_requirements, set_logging
  15. from utils.torch_utils import select_device
  16. if __name__ == '__main__':
  17. parser = argparse.ArgumentParser()
  18. parser.add_argument('--weights', type=str, default='./yolov5s.pt', help='weights path')
  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('--grid', action='store_true', help='export Detect() layer grid')
  22. parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
  23. parser.add_argument('--dynamic', action='store_true', help='dynamic ONNX axes') # ONNX-only
  24. parser.add_argument('--simplify', action='store_true', help='simplify ONNX model') # ONNX-only
  25. opt = parser.parse_args()
  26. opt.img_size *= 2 if len(opt.img_size) == 1 else 1 # expand
  27. print(opt)
  28. set_logging()
  29. t = time.time()
  30. # Load PyTorch model
  31. device = select_device(opt.device)
  32. model = attempt_load(opt.weights, map_location=device) # load FP32 model
  33. labels = model.names
  34. # Checks
  35. gs = int(max(model.stride)) # grid size (max stride)
  36. opt.img_size = [check_img_size(x, gs) for x in opt.img_size] # verify img_size are gs-multiples
  37. # Input
  38. img = torch.zeros(opt.batch_size, 3, *opt.img_size).to(device) # image size(1,3,320,192) iDetection
  39. # Update model
  40. for k, m in model.named_modules():
  41. m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility
  42. if isinstance(m, models.common.Conv): # assign export-friendly activations
  43. if isinstance(m.act, nn.Hardswish):
  44. m.act = Hardswish()
  45. elif isinstance(m.act, nn.SiLU):
  46. m.act = SiLU()
  47. # elif isinstance(m, models.yolo.Detect):
  48. # m.forward = m.forward_export # assign forward (optional)
  49. model.model[-1].export = not opt.grid # set Detect() layer grid export
  50. y = model(img) # dry run
  51. # TorchScript export -----------------------------------------------------------------------------------------------
  52. prefix = colorstr('TorchScript:')
  53. try:
  54. print(f'\n{prefix} starting export with torch {torch.__version__}...')
  55. f = opt.weights.replace('.pt', '.torchscript.pt') # filename
  56. ts = torch.jit.trace(model, img, strict=False)
  57. ts.save(f)
  58. print(f'{prefix} export success, saved as {f}')
  59. except Exception as e:
  60. print(f'{prefix} export failure: {e}')
  61. # ONNX export ------------------------------------------------------------------------------------------------------
  62. prefix = colorstr('ONNX:')
  63. try:
  64. import onnx
  65. print(f'{prefix} starting export with onnx {onnx.__version__}...')
  66. f = opt.weights.replace('.pt', '.onnx') # filename
  67. torch.onnx.export(model, img, f, verbose=False, opset_version=12, input_names=['images'],
  68. output_names=['classes', 'boxes'] if y is None else ['output'],
  69. dynamic_axes={'images': {0: 'batch', 2: 'height', 3: 'width'}, # size(1,3,640,640)
  70. 'output': {0: 'batch', 2: 'y', 3: 'x'}} if opt.dynamic else None)
  71. # Checks
  72. model_onnx = onnx.load(f) # load onnx model
  73. onnx.checker.check_model(model_onnx) # check onnx model
  74. # print(onnx.helper.printable_graph(model_onnx.graph)) # print
  75. # Simplify
  76. if opt.simplify:
  77. try:
  78. check_requirements(['onnx-simplifier'])
  79. import onnxsim
  80. print(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...')
  81. model_onnx, check = onnxsim.simplify(model_onnx,
  82. dynamic_input_shape=opt.dynamic,
  83. input_shapes={'images': list(img.shape)} if opt.dynamic else None)
  84. assert check, 'assert check failed'
  85. onnx.save(model_onnx, f)
  86. except Exception as e:
  87. print(f'{prefix} simplifier failure: {e}')
  88. print(f'{prefix} export success, saved as {f}')
  89. except Exception as e:
  90. print(f'{prefix} export failure: {e}')
  91. # CoreML export ----------------------------------------------------------------------------------------------------
  92. prefix = colorstr('CoreML:')
  93. try:
  94. import coremltools as ct
  95. print(f'{prefix} starting export with coremltools {onnx.__version__}...')
  96. # convert model from torchscript and apply pixel scaling as per detect.py
  97. model = ct.convert(ts, inputs=[ct.ImageType(name='image', shape=img.shape, scale=1 / 255.0, bias=[0, 0, 0])])
  98. f = opt.weights.replace('.pt', '.mlmodel') # filename
  99. model.save(f)
  100. print(f'{prefix} export success, saved as {f}')
  101. except Exception as e:
  102. print(f'{prefix} export failure: {e}')
  103. # Finish
  104. print(f'\nExport complete ({time.time() - t:.2f}s). Visualize with https://github.com/lutzroeder/netron.')