glenn-jocher commited on
Commit
0e5cfdb
1 Parent(s): 66cf5c2

Refactor models/export.py arguments (#3564)

Browse files

* Refactor models/export.py arguments

* cleanup

* cleanup

Files changed (1) hide show
  1. models/export.py +63 -45
models/export.py CHANGED
@@ -1,4 +1,4 @@
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
@@ -21,42 +21,39 @@ from utils.activations import Hardswish, SiLU
21
  from utils.general import colorstr, check_img_size, check_requirements, file_size, set_logging
22
  from utils.torch_utils import select_device
23
 
24
- if __name__ == '__main__':
25
- parser = argparse.ArgumentParser()
26
- parser.add_argument('--weights', type=str, default='./yolov5s.pt', help='weights path')
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')
34
- parser.add_argument('--optimize', action='store_true', help='optimize TorchScript for mobile') # TorchScript-only
35
- parser.add_argument('--dynamic', action='store_true', help='dynamic ONNX axes') # ONNX-only
36
- parser.add_argument('--simplify', action='store_true', help='simplify ONNX model') # ONNX-only
37
- parser.add_argument('--opset-version', type=int, default=12, help='ONNX opset version') # ONNX-only
38
- opt = parser.parse_args()
39
- opt.img_size *= 2 if len(opt.img_size) == 1 else 1 # expand
40
- opt.include = [x.lower() for x in opt.include]
41
- print(opt)
42
- set_logging()
43
  t = time.time()
 
 
44
 
45
  # Load PyTorch model
46
- device = select_device(opt.device)
47
- assert not (opt.device.lower() == 'cpu' and opt.half), '--half only compatible with GPU export, i.e. use --device 0'
48
- model = attempt_load(opt.weights, map_location=device) # load FP32 model
49
  labels = model.names
50
 
51
  # Input
52
  gs = int(max(model.stride)) # grid size (max stride)
53
- opt.img_size = [check_img_size(x, gs) for x in opt.img_size] # verify img_size are gs-multiples
54
- img = torch.zeros(opt.batch_size, 3, *opt.img_size).to(device) # image size(1,3,320,192) iDetection
55
 
56
  # Update model
57
- if opt.half:
58
  img, model = img.half(), model.half() # to FP16
59
- model.train() if opt.train else model.eval() # training mode = no Detect() layer grid construction
60
  for k, m in model.named_modules():
61
  m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility
62
  if isinstance(m, models.common.Conv): # assign export-friendly activations
@@ -65,42 +62,42 @@ if __name__ == '__main__':
65
  elif isinstance(m.act, nn.SiLU):
66
  m.act = SiLU()
67
  elif isinstance(m, models.yolo.Detect):
68
- m.inplace = opt.inplace
69
- m.onnx_dynamic = opt.dynamic
70
  # m.forward = m.forward_export # assign forward (optional)
71
 
72
  for _ in range(2):
73
  y = model(img) # dry runs
74
- print(f"\n{colorstr('PyTorch:')} starting from {opt.weights} ({file_size(opt.weights):.1f} MB)")
75
 
76
  # TorchScript export -----------------------------------------------------------------------------------------------
77
- if 'torchscript' in opt.include or 'coreml' in opt.include:
78
  prefix = colorstr('TorchScript:')
79
  try:
80
  print(f'\n{prefix} starting export with torch {torch.__version__}...')
81
- f = opt.weights.replace('.pt', '.torchscript.pt') # filename
82
  ts = torch.jit.trace(model, img, strict=False)
83
- (optimize_for_mobile(ts) if opt.optimize else ts).save(f)
84
  print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
85
  except Exception as e:
86
  print(f'{prefix} export failure: {e}')
87
 
88
  # ONNX export ------------------------------------------------------------------------------------------------------
89
- if 'onnx' in opt.include:
90
  prefix = colorstr('ONNX:')
91
  try:
92
  import onnx
93
 
94
  print(f'{prefix} starting export with onnx {onnx.__version__}...')
95
- f = opt.weights.replace('.pt', '.onnx') # filename
96
- torch.onnx.export(model, img, f, verbose=False, opset_version=opt.opset_version,
97
- training=torch.onnx.TrainingMode.TRAINING if opt.train else torch.onnx.TrainingMode.EVAL,
98
- do_constant_folding=not opt.train,
99
  input_names=['images'],
100
  output_names=['output'],
101
  dynamic_axes={'images': {0: 'batch', 2: 'height', 3: 'width'}, # shape(1,3,640,640)
102
  'output': {0: 'batch', 1: 'anchors'} # shape(1,25200,85)
103
- } if opt.dynamic else None)
104
 
105
  # Checks
106
  model_onnx = onnx.load(f) # load onnx model
@@ -108,7 +105,7 @@ if __name__ == '__main__':
108
  # print(onnx.helper.printable_graph(model_onnx.graph)) # print
109
 
110
  # Simplify
111
- if opt.simplify:
112
  try:
113
  check_requirements(['onnx-simplifier'])
114
  import onnxsim
@@ -116,8 +113,8 @@ if __name__ == '__main__':
116
  print(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...')
117
  model_onnx, check = onnxsim.simplify(
118
  model_onnx,
119
- dynamic_input_shape=opt.dynamic,
120
- input_shapes={'images': list(img.shape)} if opt.dynamic else None)
121
  assert check, 'assert check failed'
122
  onnx.save(model_onnx, f)
123
  except Exception as e:
@@ -127,15 +124,15 @@ if __name__ == '__main__':
127
  print(f'{prefix} export failure: {e}')
128
 
129
  # CoreML export ----------------------------------------------------------------------------------------------------
130
- if 'coreml' in opt.include:
131
  prefix = colorstr('CoreML:')
132
  try:
133
  import coremltools as ct
134
 
135
  print(f'{prefix} starting export with coremltools {ct.__version__}...')
136
- assert opt.train, 'CoreML exports should be placed in model.train() mode with `python export.py --train`'
137
  model = ct.convert(ts, inputs=[ct.ImageType('image', shape=img.shape, scale=1 / 255.0, bias=[0, 0, 0])])
138
- f = opt.weights.replace('.pt', '.mlmodel') # filename
139
  model.save(f)
140
  print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
141
  except Exception as e:
@@ -143,3 +140,24 @@ if __name__ == '__main__':
143
 
144
  # Finish
145
  print(f'\nExport complete ({time.time() - t:.2f}s). Visualize with https://github.com/lutzroeder/netron.')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Export 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
 
21
  from utils.general import colorstr, check_img_size, check_requirements, file_size, set_logging
22
  from utils.torch_utils import select_device
23
 
24
+
25
+ def export(weights='./yolov5s.pt', # weights path
26
+ img_size=(640, 640), # image (height, width)
27
+ batch_size=1, # batch size
28
+ device='cpu', # cuda device, i.e. 0 or 0,1,2,3 or cpu
29
+ include=('torchscript', 'onnx', 'coreml'), # include formats
30
+ half=False, # FP16 half-precision export
31
+ inplace=False, # set YOLOv5 Detect() inplace=True
32
+ train=False, # model.train() mode
33
+ optimize=False, # TorchScript: optimize for mobile
34
+ dynamic=False, # ONNX: dynamic axes
35
+ simplify=False, # ONNX: simplify model
36
+ opset_version=12, # ONNX: opset version
37
+ ):
 
 
 
 
 
38
  t = time.time()
39
+ include = [x.lower() for x in include]
40
+ img_size *= 2 if len(img_size) == 1 else 1 # expand
41
 
42
  # Load PyTorch model
43
+ device = select_device(device)
44
+ assert not (device.type == 'cpu' and opt.half), '--half only compatible with GPU export, i.e. use --device 0'
45
+ model = attempt_load(weights, map_location=device) # load FP32 model
46
  labels = model.names
47
 
48
  # Input
49
  gs = int(max(model.stride)) # grid size (max stride)
50
+ img_size = [check_img_size(x, gs) for x in img_size] # verify img_size are gs-multiples
51
+ img = torch.zeros(batch_size, 3, *img_size).to(device) # image size(1,3,320,192) iDetection
52
 
53
  # Update model
54
+ if half:
55
  img, model = img.half(), model.half() # to FP16
56
+ model.train() if train else model.eval() # training mode = no Detect() layer grid construction
57
  for k, m in model.named_modules():
58
  m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility
59
  if isinstance(m, models.common.Conv): # assign export-friendly activations
 
62
  elif isinstance(m.act, nn.SiLU):
63
  m.act = SiLU()
64
  elif isinstance(m, models.yolo.Detect):
65
+ m.inplace = inplace
66
+ m.onnx_dynamic = dynamic
67
  # m.forward = m.forward_export # assign forward (optional)
68
 
69
  for _ in range(2):
70
  y = model(img) # dry runs
71
+ print(f"\n{colorstr('PyTorch:')} starting from {weights} ({file_size(weights):.1f} MB)")
72
 
73
  # TorchScript export -----------------------------------------------------------------------------------------------
74
+ if 'torchscript' in include or 'coreml' in include:
75
  prefix = colorstr('TorchScript:')
76
  try:
77
  print(f'\n{prefix} starting export with torch {torch.__version__}...')
78
+ f = weights.replace('.pt', '.torchscript.pt') # filename
79
  ts = torch.jit.trace(model, img, strict=False)
80
+ (optimize_for_mobile(ts) if optimize else ts).save(f)
81
  print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
82
  except Exception as e:
83
  print(f'{prefix} export failure: {e}')
84
 
85
  # ONNX export ------------------------------------------------------------------------------------------------------
86
+ if 'onnx' in include:
87
  prefix = colorstr('ONNX:')
88
  try:
89
  import onnx
90
 
91
  print(f'{prefix} starting export with onnx {onnx.__version__}...')
92
+ f = weights.replace('.pt', '.onnx') # filename
93
+ torch.onnx.export(model, img, f, verbose=False, opset_version=opset_version,
94
+ training=torch.onnx.TrainingMode.TRAINING if train else torch.onnx.TrainingMode.EVAL,
95
+ do_constant_folding=not train,
96
  input_names=['images'],
97
  output_names=['output'],
98
  dynamic_axes={'images': {0: 'batch', 2: 'height', 3: 'width'}, # shape(1,3,640,640)
99
  'output': {0: 'batch', 1: 'anchors'} # shape(1,25200,85)
100
+ } if dynamic else None)
101
 
102
  # Checks
103
  model_onnx = onnx.load(f) # load onnx model
 
105
  # print(onnx.helper.printable_graph(model_onnx.graph)) # print
106
 
107
  # Simplify
108
+ if simplify:
109
  try:
110
  check_requirements(['onnx-simplifier'])
111
  import onnxsim
 
113
  print(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...')
114
  model_onnx, check = onnxsim.simplify(
115
  model_onnx,
116
+ dynamic_input_shape=dynamic,
117
+ input_shapes={'images': list(img.shape)} if dynamic else None)
118
  assert check, 'assert check failed'
119
  onnx.save(model_onnx, f)
120
  except Exception as e:
 
124
  print(f'{prefix} export failure: {e}')
125
 
126
  # CoreML export ----------------------------------------------------------------------------------------------------
127
+ if 'coreml' in include:
128
  prefix = colorstr('CoreML:')
129
  try:
130
  import coremltools as ct
131
 
132
  print(f'{prefix} starting export with coremltools {ct.__version__}...')
133
+ assert train, 'CoreML exports should be placed in model.train() mode with `python export.py --train`'
134
  model = ct.convert(ts, inputs=[ct.ImageType('image', shape=img.shape, scale=1 / 255.0, bias=[0, 0, 0])])
135
+ f = weights.replace('.pt', '.mlmodel') # filename
136
  model.save(f)
137
  print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
138
  except Exception as e:
 
140
 
141
  # Finish
142
  print(f'\nExport complete ({time.time() - t:.2f}s). Visualize with https://github.com/lutzroeder/netron.')
143
+
144
+
145
+ if __name__ == '__main__':
146
+ parser = argparse.ArgumentParser()
147
+ parser.add_argument('--weights', type=str, default='./yolov5s.pt', help='weights path')
148
+ parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='image (height, width)')
149
+ parser.add_argument('--batch-size', type=int, default=1, help='batch size')
150
+ parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
151
+ parser.add_argument('--include', nargs='+', default=['torchscript', 'onnx', 'coreml'], help='include formats')
152
+ parser.add_argument('--half', action='store_true', help='FP16 half-precision export')
153
+ parser.add_argument('--inplace', action='store_true', help='set YOLOv5 Detect() inplace=True')
154
+ parser.add_argument('--train', action='store_true', help='model.train() mode')
155
+ parser.add_argument('--optimize', action='store_true', help='TorchScript: optimize for mobile')
156
+ parser.add_argument('--dynamic', action='store_true', help='ONNX: dynamic axes')
157
+ parser.add_argument('--simplify', action='store_true', help='ONNX: simplify model')
158
+ parser.add_argument('--opset-version', type=int, default=12, help='ONNX: opset version')
159
+ opt = parser.parse_args()
160
+ print(opt)
161
+ set_logging()
162
+
163
+ export(**vars(opt))