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.

93 lines
3.7KB

  1. # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
  2. """
  3. Run YOLOv5 benchmarks on all supported export formats
  4. Format | `export.py --include` | Model
  5. --- | --- | ---
  6. PyTorch | - | yolov5s.pt
  7. TorchScript | `torchscript` | yolov5s.torchscript
  8. ONNX | `onnx` | yolov5s.onnx
  9. OpenVINO | `openvino` | yolov5s_openvino_model/
  10. TensorRT | `engine` | yolov5s.engine
  11. CoreML | `coreml` | yolov5s.mlmodel
  12. TensorFlow SavedModel | `saved_model` | yolov5s_saved_model/
  13. TensorFlow GraphDef | `pb` | yolov5s.pb
  14. TensorFlow Lite | `tflite` | yolov5s.tflite
  15. TensorFlow Edge TPU | `edgetpu` | yolov5s_edgetpu.tflite
  16. TensorFlow.js | `tfjs` | yolov5s_web_model/
  17. Requirements:
  18. $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime openvino-dev tensorflow-cpu # CPU
  19. $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime-gpu openvino-dev tensorflow # GPU
  20. Usage:
  21. $ python utils/benchmarks.py --weights yolov5s.pt --img 640
  22. """
  23. import argparse
  24. import sys
  25. import time
  26. from pathlib import Path
  27. import pandas as pd
  28. FILE = Path(__file__).resolve()
  29. ROOT = FILE.parents[1] # YOLOv5 root directory
  30. if str(ROOT) not in sys.path:
  31. sys.path.append(str(ROOT)) # add ROOT to PATH
  32. # ROOT = ROOT.relative_to(Path.cwd()) # relative
  33. import export
  34. import val
  35. from utils import notebook_init
  36. from utils.general import LOGGER, print_args
  37. def run(weights=ROOT / 'yolov5s.pt', # weights path
  38. imgsz=640, # inference size (pixels)
  39. batch_size=1, # batch size
  40. data=ROOT / 'data/coco128.yaml', # dataset.yaml path
  41. ):
  42. y, t = [], time.time()
  43. formats = export.export_formats()
  44. for i, (name, f, suffix) in formats.iterrows(): # index, (name, file, suffix)
  45. try:
  46. w = weights if f == '-' else export.run(weights=weights, imgsz=[imgsz], include=[f], device='cpu')[-1]
  47. assert suffix in str(w), 'export failed'
  48. result = val.run(data, w, batch_size, imgsz=imgsz, plots=False, device='cpu', task='benchmark')
  49. metrics = result[0] # metrics (mp, mr, map50, map, *losses(box, obj, cls))
  50. speeds = result[2] # times (preprocess, inference, postprocess)
  51. y.append([name, metrics[3], speeds[1]]) # mAP, t_inference
  52. except Exception as e:
  53. LOGGER.warning(f'WARNING: Benchmark failure for {name}: {e}')
  54. y.append([name, None, None]) # mAP, t_inference
  55. # Print results
  56. LOGGER.info('\n')
  57. parse_opt()
  58. notebook_init() # print system info
  59. py = pd.DataFrame(y, columns=['Format', 'mAP@0.5:0.95', 'Inference time (ms)'])
  60. LOGGER.info(f'\nBenchmarks complete ({time.time() - t:.2f}s)')
  61. LOGGER.info(str(py))
  62. return py
  63. def parse_opt():
  64. parser = argparse.ArgumentParser()
  65. parser.add_argument('--weights', type=str, default=ROOT / 'yolov5s.pt', help='weights path')
  66. parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='inference size (pixels)')
  67. parser.add_argument('--batch-size', type=int, default=1, help='batch size')
  68. parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path')
  69. opt = parser.parse_args()
  70. print_args(FILE.stem, opt)
  71. return opt
  72. def main(opt):
  73. run(**vars(opt))
  74. if __name__ == "__main__":
  75. opt = parse_opt()
  76. main(opt)