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.

95 lines
3.6KB

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