Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

142 lines
6.7KB

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