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

3 jaren geleden
Merge `develop` branch into `master` (#3518) * update ci-testing.yml (#3322) * update ci-testing.yml * update greetings.yml * bring back os matrix * update ci-testing.yml (#3322) * update ci-testing.yml * update greetings.yml * bring back os matrix * Enable direct `--weights URL` definition (#3373) * Enable direct `--weights URL` definition @KalenMike this PR will enable direct --weights URL definition. Example use case: ``` python train.py --weights https://storage.googleapis.com/bucket/dir/model.pt ``` * cleanup * bug fixes * weights = attempt_download(weights) * Update experimental.py * Update hubconf.py * return bug fix * comment mirror * min_bytes * Update tutorial.ipynb (#3368) add Open in Kaggle badge * `cv2.imread(img, -1)` for IMREAD_UNCHANGED (#3379) * Update datasets.py * comment Co-authored-by: Glenn Jocher <glenn.jocher@ultralytics.com> * COCO evolution fix (#3388) * COCO evolution fix * cleanup * update print * print fix * Create `is_pip()` function (#3391) Returns `True` if file is part of pip package. Useful for contextual behavior modification. ```python def is_pip(): # Is file in a pip package? return 'site-packages' in Path(__file__).absolute().parts ``` * Revert "`cv2.imread(img, -1)` for IMREAD_UNCHANGED (#3379)" (#3395) This reverts commit 21a9607e00f1365b21d8c4bd81bdbf5fc0efea24. * Update FLOPs description (#3422) * Update README.md * Changing FLOPS to FLOPs. Co-authored-by: BuildTools <unconfigured@null.spigotmc.org> * Parse URL authentication (#3424) * Parse URL authentication * urllib.parse.unquote() * improved error handling * improved error handling * remove %3F * update check_file() * Add FLOPs title to table (#3453) * Suppress jit trace warning + graph once (#3454) * Suppress jit trace warning + graph once Suppress harmless jit trace warning on TensorBoard add_graph call. Also fix multiple add_graph() calls bug, now only on batch 0. * Update train.py * Update MixUp augmentation `alpha=beta=32.0` (#3455) Per VOC empirical results https://github.com/ultralytics/yolov5/issues/3380#issuecomment-853001307 by @developer0hye * Add `timeout()` class (#3460) * Add `timeout()` class * rearrange order * Faster HSV augmentation (#3462) remove datatype conversion process that can be skipped * Add `check_git_status()` 5 second timeout (#3464) * Add check_git_status() 5 second timeout This should prevent the SSH Git bug that we were discussing @KalenMike * cleanup * replace timeout with check_output built-in timeout * Improved `check_requirements()` offline-handling (#3466) Improve robustness of `check_requirements()` function to offline environments (do not attempt pip installs when offline). * Add `output_names` argument for ONNX export with dynamic axes (#3456) * Add output names & dynamic axes for onnx export Add output_names and dynamic_axes names for all outputs in torch.onnx.export. The first four outputs of the model will have names output0, output1, output2, output3 * use first output only + cleanup Co-authored-by: Samridha Shrestha <samridha.shrestha@g42.ai> Co-authored-by: Glenn Jocher <glenn.jocher@ultralytics.com> * Revert FP16 `test.py` and `detect.py` inference to FP32 default (#3423) * fixed inference bug ,while use half precision * replace --use-half with --half * replace space and PEP8 in detect.py * PEP8 detect.py * update --half help comment * Update test.py * revert space Co-authored-by: Glenn Jocher <glenn.jocher@ultralytics.com> * Add additional links/resources to stale.yml message (#3467) * Update stale.yml * cleanup * Update stale.yml * reformat * Update stale.yml HUB URL (#3468) * Stale `github.actor` bug fix (#3483) * Explicit `model.eval()` call `if opt.train=False` (#3475) * call model.eval() when opt.train is False call model.eval() when opt.train is False * single-line if statement * cleanup Co-authored-by: Glenn Jocher <glenn.jocher@ultralytics.com> * check_requirements() exclude `opencv-python` (#3495) Fix for 3rd party or contrib versions of installed OpenCV as in https://github.com/ultralytics/yolov5/issues/3494. * Earlier `assert` for cpu and half option (#3508) * early assert for cpu and half option early assert for cpu and half option * Modified comment Modified comment * Update tutorial.ipynb (#3510) * Reduce test.py results spacing (#3511) * Update README.md (#3512) * Update README.md Minor modifications * 850 width * Update greetings.yml revert greeting change as PRs will now merge to master. Co-authored-by: Piotr Skalski <SkalskiP@users.noreply.github.com> Co-authored-by: SkalskiP <piotr.skalski92@gmail.com> Co-authored-by: Peretz Cohen <pizzaz93@users.noreply.github.com> Co-authored-by: tudoulei <34886368+tudoulei@users.noreply.github.com> Co-authored-by: chocosaj <chocosaj@users.noreply.github.com> Co-authored-by: BuildTools <unconfigured@null.spigotmc.org> Co-authored-by: Yonghye Kwon <developer.0hye@gmail.com> Co-authored-by: Sam_S <SamSamhuns@users.noreply.github.com> Co-authored-by: Samridha Shrestha <samridha.shrestha@g42.ai> Co-authored-by: edificewang <609552430@qq.com>
3 jaren geleden
Merge `develop` branch into `master` (#3518) * update ci-testing.yml (#3322) * update ci-testing.yml * update greetings.yml * bring back os matrix * update ci-testing.yml (#3322) * update ci-testing.yml * update greetings.yml * bring back os matrix * Enable direct `--weights URL` definition (#3373) * Enable direct `--weights URL` definition @KalenMike this PR will enable direct --weights URL definition. Example use case: ``` python train.py --weights https://storage.googleapis.com/bucket/dir/model.pt ``` * cleanup * bug fixes * weights = attempt_download(weights) * Update experimental.py * Update hubconf.py * return bug fix * comment mirror * min_bytes * Update tutorial.ipynb (#3368) add Open in Kaggle badge * `cv2.imread(img, -1)` for IMREAD_UNCHANGED (#3379) * Update datasets.py * comment Co-authored-by: Glenn Jocher <glenn.jocher@ultralytics.com> * COCO evolution fix (#3388) * COCO evolution fix * cleanup * update print * print fix * Create `is_pip()` function (#3391) Returns `True` if file is part of pip package. Useful for contextual behavior modification. ```python def is_pip(): # Is file in a pip package? return 'site-packages' in Path(__file__).absolute().parts ``` * Revert "`cv2.imread(img, -1)` for IMREAD_UNCHANGED (#3379)" (#3395) This reverts commit 21a9607e00f1365b21d8c4bd81bdbf5fc0efea24. * Update FLOPs description (#3422) * Update README.md * Changing FLOPS to FLOPs. Co-authored-by: BuildTools <unconfigured@null.spigotmc.org> * Parse URL authentication (#3424) * Parse URL authentication * urllib.parse.unquote() * improved error handling * improved error handling * remove %3F * update check_file() * Add FLOPs title to table (#3453) * Suppress jit trace warning + graph once (#3454) * Suppress jit trace warning + graph once Suppress harmless jit trace warning on TensorBoard add_graph call. Also fix multiple add_graph() calls bug, now only on batch 0. * Update train.py * Update MixUp augmentation `alpha=beta=32.0` (#3455) Per VOC empirical results https://github.com/ultralytics/yolov5/issues/3380#issuecomment-853001307 by @developer0hye * Add `timeout()` class (#3460) * Add `timeout()` class * rearrange order * Faster HSV augmentation (#3462) remove datatype conversion process that can be skipped * Add `check_git_status()` 5 second timeout (#3464) * Add check_git_status() 5 second timeout This should prevent the SSH Git bug that we were discussing @KalenMike * cleanup * replace timeout with check_output built-in timeout * Improved `check_requirements()` offline-handling (#3466) Improve robustness of `check_requirements()` function to offline environments (do not attempt pip installs when offline). * Add `output_names` argument for ONNX export with dynamic axes (#3456) * Add output names & dynamic axes for onnx export Add output_names and dynamic_axes names for all outputs in torch.onnx.export. The first four outputs of the model will have names output0, output1, output2, output3 * use first output only + cleanup Co-authored-by: Samridha Shrestha <samridha.shrestha@g42.ai> Co-authored-by: Glenn Jocher <glenn.jocher@ultralytics.com> * Revert FP16 `test.py` and `detect.py` inference to FP32 default (#3423) * fixed inference bug ,while use half precision * replace --use-half with --half * replace space and PEP8 in detect.py * PEP8 detect.py * update --half help comment * Update test.py * revert space Co-authored-by: Glenn Jocher <glenn.jocher@ultralytics.com> * Add additional links/resources to stale.yml message (#3467) * Update stale.yml * cleanup * Update stale.yml * reformat * Update stale.yml HUB URL (#3468) * Stale `github.actor` bug fix (#3483) * Explicit `model.eval()` call `if opt.train=False` (#3475) * call model.eval() when opt.train is False call model.eval() when opt.train is False * single-line if statement * cleanup Co-authored-by: Glenn Jocher <glenn.jocher@ultralytics.com> * check_requirements() exclude `opencv-python` (#3495) Fix for 3rd party or contrib versions of installed OpenCV as in https://github.com/ultralytics/yolov5/issues/3494. * Earlier `assert` for cpu and half option (#3508) * early assert for cpu and half option early assert for cpu and half option * Modified comment Modified comment * Update tutorial.ipynb (#3510) * Reduce test.py results spacing (#3511) * Update README.md (#3512) * Update README.md Minor modifications * 850 width * Update greetings.yml revert greeting change as PRs will now merge to master. Co-authored-by: Piotr Skalski <SkalskiP@users.noreply.github.com> Co-authored-by: SkalskiP <piotr.skalski92@gmail.com> Co-authored-by: Peretz Cohen <pizzaz93@users.noreply.github.com> Co-authored-by: tudoulei <34886368+tudoulei@users.noreply.github.com> Co-authored-by: chocosaj <chocosaj@users.noreply.github.com> Co-authored-by: BuildTools <unconfigured@null.spigotmc.org> Co-authored-by: Yonghye Kwon <developer.0hye@gmail.com> Co-authored-by: Sam_S <SamSamhuns@users.noreply.github.com> Co-authored-by: Samridha Shrestha <samridha.shrestha@g42.ai> Co-authored-by: edificewang <609552430@qq.com>
3 jaren geleden
4 jaren geleden
4 jaren geleden
4 jaren geleden
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. """Export a YOLOv5 *.pt model to TorchScript, ONNX, CoreML formats
  2. Usage:
  3. $ python path/to/export.py --weights yolov5s.pt --img 640 --batch 1
  4. """
  5. import argparse
  6. import sys
  7. import time
  8. from pathlib import Path
  9. import torch
  10. import torch.nn as nn
  11. from torch.utils.mobile_optimizer import optimize_for_mobile
  12. FILE = Path(__file__).absolute()
  13. sys.path.append(FILE.parents[0].as_posix()) # add yolov5/ to path
  14. from models.common import Conv
  15. from models.yolo import Detect
  16. from models.experimental import attempt_load
  17. from utils.activations import Hardswish, SiLU
  18. from utils.general import colorstr, check_img_size, check_requirements, file_size, set_logging
  19. from utils.torch_utils import select_device
  20. def run(weights='./yolov5s.pt', # weights path
  21. img_size=(640, 640), # image (height, width)
  22. batch_size=1, # batch size
  23. device='cpu', # cuda device, i.e. 0 or 0,1,2,3 or cpu
  24. include=('torchscript', 'onnx', 'coreml'), # include formats
  25. half=False, # FP16 half-precision export
  26. inplace=False, # set YOLOv5 Detect() inplace=True
  27. train=False, # model.train() mode
  28. optimize=False, # TorchScript: optimize for mobile
  29. dynamic=False, # ONNX: dynamic axes
  30. simplify=False, # ONNX: simplify model
  31. opset_version=12, # ONNX: opset version
  32. ):
  33. t = time.time()
  34. include = [x.lower() for x in include]
  35. img_size *= 2 if len(img_size) == 1 else 1 # expand
  36. # Load PyTorch model
  37. device = select_device(device)
  38. assert not (device.type == 'cpu' and half), '--half only compatible with GPU export, i.e. use --device 0'
  39. model = attempt_load(weights, map_location=device) # load FP32 model
  40. labels = model.names
  41. # Input
  42. gs = int(max(model.stride)) # grid size (max stride)
  43. img_size = [check_img_size(x, gs) for x in img_size] # verify img_size are gs-multiples
  44. img = torch.zeros(batch_size, 3, *img_size).to(device) # image size(1,3,320,192) iDetection
  45. # Update model
  46. if half:
  47. img, model = img.half(), model.half() # to FP16
  48. model.train() if train else model.eval() # training mode = no Detect() layer grid construction
  49. for k, m in model.named_modules():
  50. m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility
  51. if isinstance(m, Conv): # assign export-friendly activations
  52. if isinstance(m.act, nn.Hardswish):
  53. m.act = Hardswish()
  54. elif isinstance(m.act, nn.SiLU):
  55. m.act = SiLU()
  56. elif isinstance(m, Detect):
  57. m.inplace = inplace
  58. m.onnx_dynamic = dynamic
  59. # m.forward = m.forward_export # assign forward (optional)
  60. for _ in range(2):
  61. y = model(img) # dry runs
  62. print(f"\n{colorstr('PyTorch:')} starting from {weights} ({file_size(weights):.1f} MB)")
  63. # TorchScript export -----------------------------------------------------------------------------------------------
  64. if 'torchscript' in include or 'coreml' in include:
  65. prefix = colorstr('TorchScript:')
  66. try:
  67. print(f'\n{prefix} starting export with torch {torch.__version__}...')
  68. f = weights.replace('.pt', '.torchscript.pt') # filename
  69. ts = torch.jit.trace(model, img, strict=False)
  70. (optimize_for_mobile(ts) if optimize else ts).save(f)
  71. print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
  72. except Exception as e:
  73. print(f'{prefix} export failure: {e}')
  74. # ONNX export ------------------------------------------------------------------------------------------------------
  75. if 'onnx' in include:
  76. prefix = colorstr('ONNX:')
  77. try:
  78. import onnx
  79. print(f'{prefix} starting export with onnx {onnx.__version__}...')
  80. f = weights.replace('.pt', '.onnx') # filename
  81. torch.onnx.export(model, img, f, verbose=False, opset_version=opset_version,
  82. training=torch.onnx.TrainingMode.TRAINING if train else torch.onnx.TrainingMode.EVAL,
  83. do_constant_folding=not train,
  84. input_names=['images'],
  85. output_names=['output'],
  86. dynamic_axes={'images': {0: 'batch', 2: 'height', 3: 'width'}, # shape(1,3,640,640)
  87. 'output': {0: 'batch', 1: 'anchors'} # shape(1,25200,85)
  88. } if dynamic else None)
  89. # Checks
  90. model_onnx = onnx.load(f) # load onnx model
  91. onnx.checker.check_model(model_onnx) # check onnx model
  92. # print(onnx.helper.printable_graph(model_onnx.graph)) # print
  93. # Simplify
  94. if simplify:
  95. try:
  96. check_requirements(['onnx-simplifier'])
  97. import onnxsim
  98. print(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...')
  99. model_onnx, check = onnxsim.simplify(
  100. model_onnx,
  101. dynamic_input_shape=dynamic,
  102. input_shapes={'images': list(img.shape)} if dynamic else None)
  103. assert check, 'assert check failed'
  104. onnx.save(model_onnx, f)
  105. except Exception as e:
  106. print(f'{prefix} simplifier failure: {e}')
  107. print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
  108. except Exception as e:
  109. print(f'{prefix} export failure: {e}')
  110. # CoreML export ----------------------------------------------------------------------------------------------------
  111. if 'coreml' in include:
  112. prefix = colorstr('CoreML:')
  113. try:
  114. import coremltools as ct
  115. print(f'{prefix} starting export with coremltools {ct.__version__}...')
  116. assert train, 'CoreML exports should be placed in model.train() mode with `python export.py --train`'
  117. model = ct.convert(ts, inputs=[ct.ImageType('image', shape=img.shape, scale=1 / 255.0, bias=[0, 0, 0])])
  118. f = weights.replace('.pt', '.mlmodel') # filename
  119. model.save(f)
  120. print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
  121. except Exception as e:
  122. print(f'{prefix} export failure: {e}')
  123. # Finish
  124. print(f'\nExport complete ({time.time() - t:.2f}s). Visualize with https://github.com/lutzroeder/netron.')
  125. def parse_opt():
  126. parser = argparse.ArgumentParser()
  127. parser.add_argument('--weights', type=str, default='./yolov5s.pt', help='weights path')
  128. parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='image (height, width)')
  129. parser.add_argument('--batch-size', type=int, default=1, help='batch size')
  130. parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
  131. parser.add_argument('--include', nargs='+', default=['torchscript', 'onnx', 'coreml'], help='include formats')
  132. parser.add_argument('--half', action='store_true', help='FP16 half-precision export')
  133. parser.add_argument('--inplace', action='store_true', help='set YOLOv5 Detect() inplace=True')
  134. parser.add_argument('--train', action='store_true', help='model.train() mode')
  135. parser.add_argument('--optimize', action='store_true', help='TorchScript: optimize for mobile')
  136. parser.add_argument('--dynamic', action='store_true', help='ONNX: dynamic axes')
  137. parser.add_argument('--simplify', action='store_true', help='ONNX: simplify model')
  138. parser.add_argument('--opset-version', type=int, default=12, help='ONNX: opset version')
  139. opt = parser.parse_args()
  140. return opt
  141. def main(opt):
  142. set_logging()
  143. print(colorstr('export: ') + ', '.join(f'{k}={v}' for k, v in vars(opt).items()))
  144. run(**vars(opt))
  145. if __name__ == "__main__":
  146. opt = parse_opt()
  147. main(opt)