glenn-jocher commited on
Commit
442a7ab
1 Parent(s): 0cc7c58

Refactor `export.py` (#4080)

Browse files

* Refactor `export.py`

* cleanup

* Update check_requirements()

* Update export.py

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