From 61d67f4163af24d8eb9f610204e7b48e9d85daf3 Mon Sep 17 00:00:00 2001 From: CristiFati Date: Wed, 12 May 2021 15:07:20 +0300 Subject: [PATCH 1/5] Allow users to skip exporting in formats that they don't care about --- models/export.py | 111 +++++++++++++++++++++++++---------------------- 1 file changed, 59 insertions(+), 52 deletions(-) diff --git a/models/export.py b/models/export.py index 3415088c787a..86f3eda8425f 100644 --- a/models/export.py +++ b/models/export.py @@ -33,8 +33,10 @@ parser.add_argument('--optimize', action='store_true', help='optimize TorchScript for mobile') # TorchScript-only parser.add_argument('--dynamic', action='store_true', help='dynamic ONNX axes') # ONNX-only parser.add_argument('--simplify', action='store_true', help='simplify ONNX model') # ONNX-only + parser.add_argument('--skip-format', action='append', dest="skipped_formats", help='exclude output format') opt = parser.parse_args() opt.img_size *= 2 if len(opt.img_size) == 1 else 1 # expand + opt.skipped_formats = [i.lower() for i in opt.skipped_formats] if opt.skipped_formats else [] print(opt) set_logging() t = time.time() @@ -74,62 +76,67 @@ print(f"\n{colorstr('PyTorch:')} starting from {opt.weights} ({file_size(opt.weights):.1f} MB)") # TorchScript export ----------------------------------------------------------------------------------------------- - prefix = colorstr('TorchScript:') - try: - print(f'\n{prefix} starting export with torch {torch.__version__}...') - f = opt.weights.replace('.pt', '.torchscript.pt') # filename - ts = torch.jit.trace(model, img, strict=False) - (optimize_for_mobile(ts) if opt.optimize else ts).save(f) - print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)') - except Exception as e: - print(f'{prefix} export failure: {e}') + if "torchscript" not in opt.skipped_formats: + prefix = colorstr('TorchScript:') + try: + print(f'\n{prefix} starting export with torch {torch.__version__}...') + f = opt.weights.replace('.pt', '.torchscript.pt') # filename + ts = torch.jit.trace(model, img, strict=False) + (optimize_for_mobile(ts) if opt.optimize else ts).save(f) + print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)') + except Exception as e: + print(f'{prefix} export failure: {e}') # ONNX export ------------------------------------------------------------------------------------------------------ - prefix = colorstr('ONNX:') - try: - import onnx - - print(f'{prefix} starting export with onnx {onnx.__version__}...') - f = opt.weights.replace('.pt', '.onnx') # filename - torch.onnx.export(model, img, f, verbose=False, opset_version=12, input_names=['images'], - dynamic_axes={'images': {0: 'batch', 2: 'height', 3: 'width'}, # size(1,3,640,640) - 'output': {0: 'batch', 2: 'y', 3: 'x'}} if opt.dynamic else None) - - # Checks - model_onnx = onnx.load(f) # load onnx model - onnx.checker.check_model(model_onnx) # check onnx model - # print(onnx.helper.printable_graph(model_onnx.graph)) # print - - # Simplify - if opt.simplify: - try: - check_requirements(['onnx-simplifier']) - import onnxsim - - print(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...') - model_onnx, check = onnxsim.simplify(model_onnx, - dynamic_input_shape=opt.dynamic, - input_shapes={'images': list(img.shape)} if opt.dynamic else None) - assert check, 'assert check failed' - onnx.save(model_onnx, f) - except Exception as e: - print(f'{prefix} simplifier failure: {e}') - print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)') - except Exception as e: - print(f'{prefix} export failure: {e}') + if "onnx" not in opt.skipped_formats: + prefix = colorstr('ONNX:') + try: + import onnx + + print(f'{prefix} starting export with onnx {onnx.__version__}...') + f = opt.weights.replace('.pt', '.onnx') # filename + torch.onnx.export(model, img, f, verbose=False, opset_version=12, input_names=['images'], + dynamic_axes={'images': {0: 'batch', 2: 'height', 3: 'width'}, # size(1,3,640,640) + 'output': {0: 'batch', 2: 'y', 3: 'x'}} if opt.dynamic else None) + + # Checks + model_onnx = onnx.load(f) # load onnx model + onnx.checker.check_model(model_onnx) # check onnx model + # print(onnx.helper.printable_graph(model_onnx.graph)) # print + + # Simplify + if opt.simplify: + try: + check_requirements(['onnx-simplifier']) + import onnxsim + + print(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...') + model_onnx, check = onnxsim.simplify( + model_onnx, + dynamic_input_shape=opt.dynamic, + input_shapes={'images': list(img.shape)} if opt.dynamic else None) + assert check, 'assert check failed' + onnx.save(model_onnx, f) + except Exception as e: + print(f'{prefix} simplifier failure: {e}') + print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)') + except Exception as e: + print(f'{prefix} export failure: {e}') # CoreML export ---------------------------------------------------------------------------------------------------- - prefix = colorstr('CoreML:') - try: - import coremltools as ct - - print(f'{prefix} starting export with coremltools {ct.__version__}...') - model = ct.convert(ts, inputs=[ct.ImageType(name='image', shape=img.shape, scale=1 / 255.0, bias=[0, 0, 0])]) - f = opt.weights.replace('.pt', '.mlmodel') # filename - model.save(f) - print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)') - except Exception as e: - print(f'{prefix} export failure: {e}') + if "coreml" not in opt.skipped_formats: + prefix = colorstr('CoreML:') + try: + import coremltools as ct + + print(f'{prefix} starting export with coremltools {ct.__version__}...') + model = ct.convert(ts, inputs=[ct.ImageType(name='image', shape=img.shape, scale=1 / 255.0, + bias=[0, 0, 0])]) + f = opt.weights.replace('.pt', '.mlmodel') # filename + model.save(f) + print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)') + except Exception as e: + print(f'{prefix} export failure: {e}') # Finish print(f'\nExport complete ({time.time() - t:.2f}s). Visualize with https://github.com/lutzroeder/netron.') From 7a25cf8db67962af057bc8457ef750a26d392b86 Mon Sep 17 00:00:00 2001 From: CristiFati Date: Wed, 12 May 2021 15:11:53 +0300 Subject: [PATCH 2/5] Correct comments --- models/export.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/models/export.py b/models/export.py index 86f3eda8425f..ed6a48f8fb3b 100644 --- a/models/export.py +++ b/models/export.py @@ -1,7 +1,7 @@ -"""Exports a YOLOv5 *.pt model to ONNX and TorchScript formats +"""Exports a YOLOv5 *.pt model to TorchScript, ONNX, CoreML formats Usage: - $ export PYTHONPATH="$PWD" && python models/export.py --weights yolov5s.pt --img 640 --batch 1 + $ python path/to/models/export.py --weights yolov5s.pt --img 640 --batch 1 """ import argparse From 99e7d1ca238278e1ec9c705a1a8f9c93ea2367e2 Mon Sep 17 00:00:00 2001 From: Glenn Jocher Date: Wed, 12 May 2021 17:26:40 +0200 Subject: [PATCH 3/5] Update export.py renamed --skip-format to --exclude --- models/export.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/models/export.py b/models/export.py index ed6a48f8fb3b..390997673651 100644 --- a/models/export.py +++ b/models/export.py @@ -33,10 +33,10 @@ parser.add_argument('--optimize', action='store_true', help='optimize TorchScript for mobile') # TorchScript-only parser.add_argument('--dynamic', action='store_true', help='dynamic ONNX axes') # ONNX-only parser.add_argument('--simplify', action='store_true', help='simplify ONNX model') # ONNX-only - parser.add_argument('--skip-format', action='append', dest="skipped_formats", help='exclude output format') + parser.add_argument('--exclude', action='append', default=[], help='exclude [onnx, torchscript, coreml] exports') opt = parser.parse_args() opt.img_size *= 2 if len(opt.img_size) == 1 else 1 # expand - opt.skipped_formats = [i.lower() for i in opt.skipped_formats] if opt.skipped_formats else [] + opt.exclude = [x.lower() for x in opt.exclude] print(opt) set_logging() t = time.time() @@ -49,7 +49,7 @@ # Checks gs = int(max(model.stride)) # grid size (max stride) opt.img_size = [check_img_size(x, gs) for x in opt.img_size] # verify img_size are gs-multiples - assert not (opt.device.lower() == "cpu" and opt.half), '--half only compatible with GPU export, i.e. use --device 0' + assert not (opt.device.lower() == 'cpu' and opt.half), '--half only compatible with GPU export, i.e. use --device 0' # Input img = torch.zeros(opt.batch_size, 3, *opt.img_size).to(device) # image size(1,3,320,192) iDetection @@ -76,7 +76,7 @@ print(f"\n{colorstr('PyTorch:')} starting from {opt.weights} ({file_size(opt.weights):.1f} MB)") # TorchScript export ----------------------------------------------------------------------------------------------- - if "torchscript" not in opt.skipped_formats: + if 'torchscript' not in opt.exclude: prefix = colorstr('TorchScript:') try: print(f'\n{prefix} starting export with torch {torch.__version__}...') @@ -88,7 +88,7 @@ print(f'{prefix} export failure: {e}') # ONNX export ------------------------------------------------------------------------------------------------------ - if "onnx" not in opt.skipped_formats: + if 'onnx' not in opt.exclude: prefix = colorstr('ONNX:') try: import onnx @@ -124,7 +124,7 @@ print(f'{prefix} export failure: {e}') # CoreML export ---------------------------------------------------------------------------------------------------- - if "coreml" not in opt.skipped_formats: + if 'coreml' not in opt.exclude: prefix = colorstr('CoreML:') try: import coremltools as ct From d2fb5ee64bbddba471e09245fdbf2677b6d6cce8 Mon Sep 17 00:00:00 2001 From: CristiFati Date: Wed, 12 May 2021 19:47:00 +0300 Subject: [PATCH 4/5] Switched format from exclude to include (as instructed by @glenn-jocher) --- models/export.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/models/export.py b/models/export.py index 390997673651..a2ca6e875cd5 100644 --- a/models/export.py +++ b/models/export.py @@ -33,10 +33,10 @@ parser.add_argument('--optimize', action='store_true', help='optimize TorchScript for mobile') # TorchScript-only parser.add_argument('--dynamic', action='store_true', help='dynamic ONNX axes') # ONNX-only parser.add_argument('--simplify', action='store_true', help='simplify ONNX model') # ONNX-only - parser.add_argument('--exclude', action='append', default=[], help='exclude [onnx, torchscript, coreml] exports') + parser.add_argument('--include', nargs='+', default=['onnx', 'torchscript', 'coreml'], help='include formats') opt = parser.parse_args() opt.img_size *= 2 if len(opt.img_size) == 1 else 1 # expand - opt.exclude = [x.lower() for x in opt.exclude] + opt.include = [x.lower() for x in opt.include] print(opt) set_logging() t = time.time() @@ -76,7 +76,7 @@ print(f"\n{colorstr('PyTorch:')} starting from {opt.weights} ({file_size(opt.weights):.1f} MB)") # TorchScript export ----------------------------------------------------------------------------------------------- - if 'torchscript' not in opt.exclude: + if 'torchscript' in opt.include: prefix = colorstr('TorchScript:') try: print(f'\n{prefix} starting export with torch {torch.__version__}...') @@ -88,7 +88,7 @@ print(f'{prefix} export failure: {e}') # ONNX export ------------------------------------------------------------------------------------------------------ - if 'onnx' not in opt.exclude: + if 'onnx' in opt.include: prefix = colorstr('ONNX:') try: import onnx @@ -124,7 +124,7 @@ print(f'{prefix} export failure: {e}') # CoreML export ---------------------------------------------------------------------------------------------------- - if 'coreml' not in opt.exclude: + if 'coreml' in opt.include: prefix = colorstr('CoreML:') try: import coremltools as ct From 7ed3e4c051dd57229738bb12d719fec278f676ac Mon Sep 17 00:00:00 2001 From: Glenn Jocher Date: Wed, 12 May 2021 19:40:09 +0200 Subject: [PATCH 5/5] cleanup --- models/export.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/models/export.py b/models/export.py index a2ca6e875cd5..662509b3ea78 100644 --- a/models/export.py +++ b/models/export.py @@ -27,13 +27,13 @@ parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='image size') # height, width parser.add_argument('--batch-size', type=int, default=1, help='batch size') parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') + parser.add_argument('--include', nargs='+', default=['torchscript', 'onnx', 'coreml'], help='include formats') parser.add_argument('--half', action='store_true', help='FP16 half-precision export') parser.add_argument('--inplace', action='store_true', help='set YOLOv5 Detect() inplace=True') parser.add_argument('--train', action='store_true', help='model.train() mode') parser.add_argument('--optimize', action='store_true', help='optimize TorchScript for mobile') # TorchScript-only parser.add_argument('--dynamic', action='store_true', help='dynamic ONNX axes') # ONNX-only parser.add_argument('--simplify', action='store_true', help='simplify ONNX model') # ONNX-only - parser.add_argument('--include', nargs='+', default=['onnx', 'torchscript', 'coreml'], help='include formats') opt = parser.parse_args() opt.img_size *= 2 if len(opt.img_size) == 1 else 1 # expand opt.include = [x.lower() for x in opt.include] @@ -76,7 +76,7 @@ print(f"\n{colorstr('PyTorch:')} starting from {opt.weights} ({file_size(opt.weights):.1f} MB)") # TorchScript export ----------------------------------------------------------------------------------------------- - if 'torchscript' in opt.include: + if 'torchscript' in opt.include or 'coreml' in opt.include: prefix = colorstr('TorchScript:') try: print(f'\n{prefix} starting export with torch {torch.__version__}...') @@ -130,8 +130,7 @@ import coremltools as ct print(f'{prefix} starting export with coremltools {ct.__version__}...') - model = ct.convert(ts, inputs=[ct.ImageType(name='image', shape=img.shape, scale=1 / 255.0, - bias=[0, 0, 0])]) + model = ct.convert(ts, inputs=[ct.ImageType('image', shape=img.shape, scale=1 / 255.0, bias=[0, 0, 0])]) f = opt.weights.replace('.pt', '.mlmodel') # filename model.save(f) print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')