Cristi Fati glenn-jocher commited on
Commit
d9b4e6b
1 Parent(s): bd6f6a7

Add `--include torchscript onnx coreml` argument (#3137)

Browse files

* Allow users to skip exporting in formats that they don't care about

* Correct comments

* Update export.py

renamed --skip-format to --exclude

* Switched format from exclude to include (as instructed by

@glenn-jocher

)

* cleanup

Co-authored-by: Glenn Jocher <[email protected]>

Files changed (1) hide show
  1. models/export.py +61 -55
models/export.py CHANGED
@@ -1,7 +1,7 @@
1
- """Exports a YOLOv5 *.pt model to ONNX and TorchScript formats
2
 
3
  Usage:
4
- $ export PYTHONPATH="$PWD" && python models/export.py --weights yolov5s.pt --img 640 --batch 1
5
  """
6
 
7
  import argparse
@@ -27,6 +27,7 @@ if __name__ == '__main__':
27
  parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='image size') # height, width
28
  parser.add_argument('--batch-size', type=int, default=1, help='batch size')
29
  parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
 
30
  parser.add_argument('--half', action='store_true', help='FP16 half-precision export')
31
  parser.add_argument('--inplace', action='store_true', help='set YOLOv5 Detect() inplace=True')
32
  parser.add_argument('--train', action='store_true', help='model.train() mode')
@@ -35,6 +36,7 @@ if __name__ == '__main__':
35
  parser.add_argument('--simplify', action='store_true', help='simplify ONNX model') # ONNX-only
36
  opt = parser.parse_args()
37
  opt.img_size *= 2 if len(opt.img_size) == 1 else 1 # expand
 
38
  print(opt)
39
  set_logging()
40
  t = time.time()
@@ -47,7 +49,7 @@ if __name__ == '__main__':
47
  # Checks
48
  gs = int(max(model.stride)) # grid size (max stride)
49
  opt.img_size = [check_img_size(x, gs) for x in opt.img_size] # verify img_size are gs-multiples
50
- assert not (opt.device.lower() == "cpu" and opt.half), '--half only compatible with GPU export, i.e. use --device 0'
51
 
52
  # Input
53
  img = torch.zeros(opt.batch_size, 3, *opt.img_size).to(device) # image size(1,3,320,192) iDetection
@@ -74,62 +76,66 @@ if __name__ == '__main__':
74
  print(f"\n{colorstr('PyTorch:')} starting from {opt.weights} ({file_size(opt.weights):.1f} MB)")
75
 
76
  # TorchScript export -----------------------------------------------------------------------------------------------
77
- prefix = colorstr('TorchScript:')
78
- try:
79
- print(f'\n{prefix} starting export with torch {torch.__version__}...')
80
- f = opt.weights.replace('.pt', '.torchscript.pt') # filename
81
- ts = torch.jit.trace(model, img, strict=False)
82
- (optimize_for_mobile(ts) if opt.optimize else ts).save(f)
83
- print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
84
- except Exception as e:
85
- print(f'{prefix} export failure: {e}')
 
86
 
87
  # ONNX export ------------------------------------------------------------------------------------------------------
88
- prefix = colorstr('ONNX:')
89
- try:
90
- import onnx
91
-
92
- print(f'{prefix} starting export with onnx {onnx.__version__}...')
93
- f = opt.weights.replace('.pt', '.onnx') # filename
94
- torch.onnx.export(model, img, f, verbose=False, opset_version=12, input_names=['images'],
95
- dynamic_axes={'images': {0: 'batch', 2: 'height', 3: 'width'}, # size(1,3,640,640)
96
- 'output': {0: 'batch', 2: 'y', 3: 'x'}} if opt.dynamic else None)
97
-
98
- # Checks
99
- model_onnx = onnx.load(f) # load onnx model
100
- onnx.checker.check_model(model_onnx) # check onnx model
101
- # print(onnx.helper.printable_graph(model_onnx.graph)) # print
102
-
103
- # Simplify
104
- if opt.simplify:
105
- try:
106
- check_requirements(['onnx-simplifier'])
107
- import onnxsim
108
-
109
- print(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...')
110
- model_onnx, check = onnxsim.simplify(model_onnx,
111
- dynamic_input_shape=opt.dynamic,
112
- input_shapes={'images': list(img.shape)} if opt.dynamic else None)
113
- assert check, 'assert check failed'
114
- onnx.save(model_onnx, f)
115
- except Exception as e:
116
- print(f'{prefix} simplifier failure: {e}')
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
 
121
  # CoreML export ----------------------------------------------------------------------------------------------------
122
- prefix = colorstr('CoreML:')
123
- try:
124
- import coremltools as ct
125
-
126
- print(f'{prefix} starting export with coremltools {ct.__version__}...')
127
- model = ct.convert(ts, inputs=[ct.ImageType(name='image', shape=img.shape, scale=1 / 255.0, bias=[0, 0, 0])])
128
- f = opt.weights.replace('.pt', '.mlmodel') # filename
129
- model.save(f)
130
- print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
131
- except Exception as e:
132
- print(f'{prefix} export failure: {e}')
 
133
 
134
  # Finish
135
  print(f'\nExport complete ({time.time() - t:.2f}s). Visualize with https://github.com/lutzroeder/netron.')
 
1
+ """Exports a YOLOv5 *.pt model to TorchScript, ONNX, CoreML formats
2
 
3
  Usage:
4
+ $ python path/to/models/export.py --weights yolov5s.pt --img 640 --batch 1
5
  """
6
 
7
  import argparse
 
27
  parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='image size') # height, width
28
  parser.add_argument('--batch-size', type=int, default=1, help='batch size')
29
  parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
30
+ parser.add_argument('--include', nargs='+', default=['torchscript', 'onnx', 'coreml'], help='include formats')
31
  parser.add_argument('--half', action='store_true', help='FP16 half-precision export')
32
  parser.add_argument('--inplace', action='store_true', help='set YOLOv5 Detect() inplace=True')
33
  parser.add_argument('--train', action='store_true', help='model.train() mode')
 
36
  parser.add_argument('--simplify', action='store_true', help='simplify ONNX model') # ONNX-only
37
  opt = parser.parse_args()
38
  opt.img_size *= 2 if len(opt.img_size) == 1 else 1 # expand
39
+ opt.include = [x.lower() for x in opt.include]
40
  print(opt)
41
  set_logging()
42
  t = time.time()
 
49
  # Checks
50
  gs = int(max(model.stride)) # grid size (max stride)
51
  opt.img_size = [check_img_size(x, gs) for x in opt.img_size] # verify img_size are gs-multiples
52
+ assert not (opt.device.lower() == 'cpu' and opt.half), '--half only compatible with GPU export, i.e. use --device 0'
53
 
54
  # Input
55
  img = torch.zeros(opt.batch_size, 3, *opt.img_size).to(device) # image size(1,3,320,192) iDetection
 
76
  print(f"\n{colorstr('PyTorch:')} starting from {opt.weights} ({file_size(opt.weights):.1f} MB)")
77
 
78
  # TorchScript export -----------------------------------------------------------------------------------------------
79
+ if 'torchscript' in opt.include or 'coreml' in opt.include:
80
+ prefix = colorstr('TorchScript:')
81
+ try:
82
+ print(f'\n{prefix} starting export with torch {torch.__version__}...')
83
+ f = opt.weights.replace('.pt', '.torchscript.pt') # filename
84
+ ts = torch.jit.trace(model, img, strict=False)
85
+ (optimize_for_mobile(ts) if opt.optimize else ts).save(f)
86
+ print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
87
+ except Exception as e:
88
+ print(f'{prefix} export failure: {e}')
89
 
90
  # ONNX export ------------------------------------------------------------------------------------------------------
91
+ if 'onnx' in opt.include:
92
+ prefix = colorstr('ONNX:')
93
+ try:
94
+ import onnx
95
+
96
+ print(f'{prefix} starting export with onnx {onnx.__version__}...')
97
+ f = opt.weights.replace('.pt', '.onnx') # filename
98
+ torch.onnx.export(model, img, f, verbose=False, opset_version=12, input_names=['images'],
99
+ dynamic_axes={'images': {0: 'batch', 2: 'height', 3: 'width'}, # size(1,3,640,640)
100
+ 'output': {0: 'batch', 2: 'y', 3: 'x'}} if opt.dynamic else None)
101
+
102
+ # Checks
103
+ model_onnx = onnx.load(f) # load onnx model
104
+ onnx.checker.check_model(model_onnx) # check onnx model
105
+ # print(onnx.helper.printable_graph(model_onnx.graph)) # print
106
+
107
+ # Simplify
108
+ if opt.simplify:
109
+ try:
110
+ check_requirements(['onnx-simplifier'])
111
+ import onnxsim
112
+
113
+ print(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...')
114
+ model_onnx, check = onnxsim.simplify(
115
+ model_onnx,
116
+ dynamic_input_shape=opt.dynamic,
117
+ input_shapes={'images': list(img.shape)} if opt.dynamic else None)
118
+ assert check, 'assert check failed'
119
+ onnx.save(model_onnx, f)
120
+ except Exception as e:
121
+ print(f'{prefix} simplifier failure: {e}')
122
+ print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
123
+ except Exception as e:
124
+ print(f'{prefix} export failure: {e}')
125
 
126
  # CoreML export ----------------------------------------------------------------------------------------------------
127
+ if 'coreml' in opt.include:
128
+ prefix = colorstr('CoreML:')
129
+ try:
130
+ import coremltools as ct
131
+
132
+ print(f'{prefix} starting export with coremltools {ct.__version__}...')
133
+ model = ct.convert(ts, inputs=[ct.ImageType('image', shape=img.shape, scale=1 / 255.0, bias=[0, 0, 0])])
134
+ f = opt.weights.replace('.pt', '.mlmodel') # filename
135
+ model.save(f)
136
+ print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
137
+ except Exception as e:
138
+ print(f'{prefix} export failure: {e}')
139
 
140
  # Finish
141
  print(f'\nExport complete ({time.time() - t:.2f}s). Visualize with https://github.com/lutzroeder/netron.')