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 3.8KB

4 jaren geleden
4 jaren geleden
4 jaren geleden
4 jaren geleden
4 jaren geleden
4 jaren geleden
4 jaren geleden
4 jaren geleden
4 jaren geleden
4 jaren geleden
4 jaren geleden
4 jaren geleden
4 jaren geleden
4 jaren geleden
4 jaren geleden
4 jaren geleden
4 jaren geleden
4 jaren geleden
4 jaren geleden
4 jaren geleden
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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('--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): # assign export-friendly activations
  37. if isinstance(m.act, nn.Hardswish):
  38. m.act = Hardswish()
  39. elif isinstance(m.act, nn.SiLU):
  40. m.act = SiLU()
  41. # elif isinstance(m, models.yolo.Detect):
  42. # m.forward = m.forward_export # assign forward (optional)
  43. model.model[-1].export = True # set Detect() layer export=True
  44. y = model(img) # dry run
  45. # TorchScript export
  46. try:
  47. print('\nStarting TorchScript export with torch %s...' % torch.__version__)
  48. f = opt.weights.replace('.pt', '.torchscript.pt') # filename
  49. ts = torch.jit.trace(model, img)
  50. ts.save(f)
  51. print('TorchScript export success, saved as %s' % f)
  52. except Exception as e:
  53. print('TorchScript export failure: %s' % e)
  54. # ONNX export
  55. try:
  56. import onnx
  57. print('\nStarting ONNX export with onnx %s...' % onnx.__version__)
  58. f = opt.weights.replace('.pt', '.onnx') # filename
  59. torch.onnx.export(model, img, f, verbose=False, opset_version=12, input_names=['images'],
  60. output_names=['classes', 'boxes'] if y is None else ['output'])
  61. # Checks
  62. onnx_model = onnx.load(f) # load onnx model
  63. onnx.checker.check_model(onnx_model) # check onnx model
  64. # print(onnx.helper.printable_graph(onnx_model.graph)) # print a human readable model
  65. print('ONNX export success, saved as %s' % f)
  66. except Exception as e:
  67. print('ONNX export failure: %s' % e)
  68. # CoreML export
  69. try:
  70. import coremltools as ct
  71. print('\nStarting CoreML export with coremltools %s...' % ct.__version__)
  72. # convert model from torchscript and apply pixel scaling as per detect.py
  73. model = ct.convert(ts, inputs=[ct.ImageType(name='image', shape=img.shape, scale=1 / 255.0, bias=[0, 0, 0])])
  74. f = opt.weights.replace('.pt', '.mlmodel') # filename
  75. model.save(f)
  76. print('CoreML export success, saved as %s' % f)
  77. except Exception as e:
  78. print('CoreML export failure: %s' % e)
  79. # Finish
  80. print('\nExport complete (%.2fs). Visualize with https://github.com/lutzroeder/netron.' % (time.time() - t))