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.

101 lines
4.0KB

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