export.py 4.3 KB

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