mirror of
https://github.com/ultralytics/yolov5.git
synced 2025-06-03 14:49:29 +08:00
* Add license line to .github/ISSUE_TEMPLATE/bug-report.yml * Add license line to .github/ISSUE_TEMPLATE/config.yml * Add license line to .github/ISSUE_TEMPLATE/feature-request.yml * Add license line to .github/ISSUE_TEMPLATE/question.yml * Add license line to .github/dependabot.yml * Add license line to .github/workflows/ci-testing.yml * Add license line to .github/workflows/cla.yml * Add license line to .github/workflows/codeql-analysis.yml * Add license line to .github/workflows/docker.yml * Add license line to .github/workflows/format.yml * Add license line to .github/workflows/greetings.yml * Add license line to .github/workflows/links.yml * Add license line to .github/workflows/merge-main-into-prs.yml * Add license line to .github/workflows/stale.yml * Add license line to benchmarks.py * Add license line to classify/predict.py * Add license line to classify/train.py * Add license line to classify/val.py * Add license line to data/Argoverse.yaml * Add license line to data/GlobalWheat2020.yaml * Add license line to data/ImageNet.yaml * Add license line to data/ImageNet10.yaml * Add license line to data/ImageNet100.yaml * Add license line to data/ImageNet1000.yaml * Add license line to data/Objects365.yaml * Add license line to data/SKU-110K.yaml * Add license line to data/VOC.yaml * Add license line to data/VisDrone.yaml * Add license line to data/coco.yaml * Add license line to data/coco128-seg.yaml * Add license line to data/coco128.yaml * Add license line to data/hyps/hyp.Objects365.yaml * Add license line to data/hyps/hyp.VOC.yaml * Add license line to data/hyps/hyp.no-augmentation.yaml * Add license line to data/hyps/hyp.scratch-high.yaml * Add license line to data/hyps/hyp.scratch-low.yaml * Add license line to data/hyps/hyp.scratch-med.yaml * Add license line to data/xView.yaml * Add license line to detect.py * Add license line to export.py * Add license line to hubconf.py * Add license line to models/common.py * Add license line to models/experimental.py * Add license line to models/hub/anchors.yaml * Add license line to models/hub/yolov3-spp.yaml * Add license line to models/hub/yolov3-tiny.yaml * Add license line to models/hub/yolov3.yaml * Add license line to models/hub/yolov5-bifpn.yaml * Add license line to models/hub/yolov5-fpn.yaml * Add license line to models/hub/yolov5-p2.yaml * Add license line to models/hub/yolov5-p34.yaml * Add license line to models/hub/yolov5-p6.yaml * Add license line to models/hub/yolov5-p7.yaml * Add license line to models/hub/yolov5-panet.yaml * Add license line to models/hub/yolov5l6.yaml * Add license line to models/hub/yolov5m6.yaml * Add license line to models/hub/yolov5n6.yaml * Add license line to models/hub/yolov5s-LeakyReLU.yaml * Add license line to models/hub/yolov5s-ghost.yaml * Add license line to models/hub/yolov5s-transformer.yaml * Add license line to models/hub/yolov5s6.yaml * Add license line to models/hub/yolov5x6.yaml * Add license line to models/segment/yolov5l-seg.yaml * Add license line to models/segment/yolov5m-seg.yaml * Add license line to models/segment/yolov5n-seg.yaml * Add license line to models/segment/yolov5s-seg.yaml * Add license line to models/segment/yolov5x-seg.yaml * Add license line to models/tf.py * Add license line to models/yolo.py * Add license line to models/yolov5l.yaml * Add license line to models/yolov5m.yaml * Add license line to models/yolov5n.yaml * Add license line to models/yolov5s.yaml * Add license line to models/yolov5x.yaml * Add license line to pyproject.toml * Add license line to segment/predict.py * Add license line to segment/train.py * Add license line to segment/val.py * Add license line to train.py * Add license line to utils/__init__.py * Add license line to utils/activations.py * Add license line to utils/augmentations.py * Add license line to utils/autoanchor.py * Add license line to utils/autobatch.py * Add license line to utils/aws/resume.py * Add license line to utils/callbacks.py * Add license line to utils/dataloaders.py * Add license line to utils/downloads.py * Add license line to utils/flask_rest_api/example_request.py * Add license line to utils/flask_rest_api/restapi.py * Add license line to utils/general.py * Add license line to utils/google_app_engine/app.yaml * Add license line to utils/loggers/__init__.py * Add license line to utils/loggers/clearml/clearml_utils.py * Add license line to utils/loggers/clearml/hpo.py * Add license line to utils/loggers/comet/__init__.py * Add license line to utils/loggers/comet/comet_utils.py * Add license line to utils/loggers/comet/hpo.py * Add license line to utils/loggers/wandb/wandb_utils.py * Add license line to utils/loss.py * Add license line to utils/metrics.py * Add license line to utils/plots.py * Add license line to utils/segment/augmentations.py * Add license line to utils/segment/dataloaders.py * Add license line to utils/segment/general.py * Add license line to utils/segment/loss.py * Add license line to utils/segment/metrics.py * Add license line to utils/segment/plots.py * Add license line to utils/torch_utils.py * Add license line to utils/triton.py * Add license line to val.py * Auto-format by https://ultralytics.com/actions * Update ImageNet1000.yaml Signed-off-by: Glenn Jocher <glenn.jocher@ultralytics.com> * Auto-format by https://ultralytics.com/actions --------- Signed-off-by: Glenn Jocher <glenn.jocher@ultralytics.com> Co-authored-by: Glenn Jocher <glenn.jocher@ultralytics.com>
177 lines
7.9 KiB
Python
177 lines
7.9 KiB
Python
# Ultralytics YOLOv5 🚀, AGPL-3.0 license
|
|
"""
|
|
Run YOLOv5 benchmarks on all supported export formats.
|
|
|
|
Format | `export.py --include` | Model
|
|
--- | --- | ---
|
|
PyTorch | - | yolov5s.pt
|
|
TorchScript | `torchscript` | yolov5s.torchscript
|
|
ONNX | `onnx` | yolov5s.onnx
|
|
OpenVINO | `openvino` | yolov5s_openvino_model/
|
|
TensorRT | `engine` | yolov5s.engine
|
|
CoreML | `coreml` | yolov5s.mlmodel
|
|
TensorFlow SavedModel | `saved_model` | yolov5s_saved_model/
|
|
TensorFlow GraphDef | `pb` | yolov5s.pb
|
|
TensorFlow Lite | `tflite` | yolov5s.tflite
|
|
TensorFlow Edge TPU | `edgetpu` | yolov5s_edgetpu.tflite
|
|
TensorFlow.js | `tfjs` | yolov5s_web_model/
|
|
|
|
Requirements:
|
|
$ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime openvino-dev tensorflow-cpu # CPU
|
|
$ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime-gpu openvino-dev tensorflow # GPU
|
|
$ pip install -U nvidia-tensorrt --index-url https://pypi.ngc.nvidia.com # TensorRT
|
|
|
|
Usage:
|
|
$ python benchmarks.py --weights yolov5s.pt --img 640
|
|
"""
|
|
|
|
import argparse
|
|
import platform
|
|
import sys
|
|
import time
|
|
from pathlib import Path
|
|
|
|
import pandas as pd
|
|
|
|
FILE = Path(__file__).resolve()
|
|
ROOT = FILE.parents[0] # YOLOv5 root directory
|
|
if str(ROOT) not in sys.path:
|
|
sys.path.append(str(ROOT)) # add ROOT to PATH
|
|
# ROOT = ROOT.relative_to(Path.cwd()) # relative
|
|
|
|
import export
|
|
from models.experimental import attempt_load
|
|
from models.yolo import SegmentationModel
|
|
from segment.val import run as val_seg
|
|
from utils import notebook_init
|
|
from utils.general import LOGGER, check_yaml, file_size, print_args
|
|
from utils.torch_utils import select_device
|
|
from val import run as val_det
|
|
|
|
|
|
def run(
|
|
weights=ROOT / "yolov5s.pt", # weights path
|
|
imgsz=640, # inference size (pixels)
|
|
batch_size=1, # batch size
|
|
data=ROOT / "data/coco128.yaml", # dataset.yaml path
|
|
device="", # cuda device, i.e. 0 or 0,1,2,3 or cpu
|
|
half=False, # use FP16 half-precision inference
|
|
test=False, # test exports only
|
|
pt_only=False, # test PyTorch only
|
|
hard_fail=False, # throw error on benchmark failure
|
|
):
|
|
y, t = [], time.time()
|
|
device = select_device(device)
|
|
model_type = type(attempt_load(weights, fuse=False)) # DetectionModel, SegmentationModel, etc.
|
|
for i, (name, f, suffix, cpu, gpu) in export.export_formats().iterrows(): # index, (name, file, suffix, CPU, GPU)
|
|
try:
|
|
assert i not in (9, 10), "inference not supported" # Edge TPU and TF.js are unsupported
|
|
assert i != 5 or platform.system() == "Darwin", "inference only supported on macOS>=10.13" # CoreML
|
|
if "cpu" in device.type:
|
|
assert cpu, "inference not supported on CPU"
|
|
if "cuda" in device.type:
|
|
assert gpu, "inference not supported on GPU"
|
|
|
|
# Export
|
|
if f == "-":
|
|
w = weights # PyTorch format
|
|
else:
|
|
w = export.run(
|
|
weights=weights, imgsz=[imgsz], include=[f], batch_size=batch_size, device=device, half=half
|
|
)[-1] # all others
|
|
assert suffix in str(w), "export failed"
|
|
|
|
# Validate
|
|
if model_type == SegmentationModel:
|
|
result = val_seg(data, w, batch_size, imgsz, plots=False, device=device, task="speed", half=half)
|
|
metric = result[0][7] # (box(p, r, map50, map), mask(p, r, map50, map), *loss(box, obj, cls))
|
|
else: # DetectionModel:
|
|
result = val_det(data, w, batch_size, imgsz, plots=False, device=device, task="speed", half=half)
|
|
metric = result[0][3] # (p, r, map50, map, *loss(box, obj, cls))
|
|
speed = result[2][1] # times (preprocess, inference, postprocess)
|
|
y.append([name, round(file_size(w), 1), round(metric, 4), round(speed, 2)]) # MB, mAP, t_inference
|
|
except Exception as e:
|
|
if hard_fail:
|
|
assert type(e) is AssertionError, f"Benchmark --hard-fail for {name}: {e}"
|
|
LOGGER.warning(f"WARNING ⚠️ Benchmark failure for {name}: {e}")
|
|
y.append([name, None, None, None]) # mAP, t_inference
|
|
if pt_only and i == 0:
|
|
break # break after PyTorch
|
|
|
|
# Print results
|
|
LOGGER.info("\n")
|
|
parse_opt()
|
|
notebook_init() # print system info
|
|
c = ["Format", "Size (MB)", "mAP50-95", "Inference time (ms)"] if map else ["Format", "Export", "", ""]
|
|
py = pd.DataFrame(y, columns=c)
|
|
LOGGER.info(f"\nBenchmarks complete ({time.time() - t:.2f}s)")
|
|
LOGGER.info(str(py if map else py.iloc[:, :2]))
|
|
if hard_fail and isinstance(hard_fail, str):
|
|
metrics = py["mAP50-95"].array # values to compare to floor
|
|
floor = eval(hard_fail) # minimum metric floor to pass, i.e. = 0.29 mAP for YOLOv5n
|
|
assert all(x > floor for x in metrics if pd.notna(x)), f"HARD FAIL: mAP50-95 < floor {floor}"
|
|
return py
|
|
|
|
|
|
def test(
|
|
weights=ROOT / "yolov5s.pt", # weights path
|
|
imgsz=640, # inference size (pixels)
|
|
batch_size=1, # batch size
|
|
data=ROOT / "data/coco128.yaml", # dataset.yaml path
|
|
device="", # cuda device, i.e. 0 or 0,1,2,3 or cpu
|
|
half=False, # use FP16 half-precision inference
|
|
test=False, # test exports only
|
|
pt_only=False, # test PyTorch only
|
|
hard_fail=False, # throw error on benchmark failure
|
|
):
|
|
y, t = [], time.time()
|
|
device = select_device(device)
|
|
for i, (name, f, suffix, gpu) in export.export_formats().iterrows(): # index, (name, file, suffix, gpu-capable)
|
|
try:
|
|
w = (
|
|
weights
|
|
if f == "-"
|
|
else export.run(weights=weights, imgsz=[imgsz], include=[f], device=device, half=half)[-1]
|
|
) # weights
|
|
assert suffix in str(w), "export failed"
|
|
y.append([name, True])
|
|
except Exception:
|
|
y.append([name, False]) # mAP, t_inference
|
|
|
|
# Print results
|
|
LOGGER.info("\n")
|
|
parse_opt()
|
|
notebook_init() # print system info
|
|
py = pd.DataFrame(y, columns=["Format", "Export"])
|
|
LOGGER.info(f"\nExports complete ({time.time() - t:.2f}s)")
|
|
LOGGER.info(str(py))
|
|
return py
|
|
|
|
|
|
def parse_opt():
|
|
"""Parses command-line arguments for YOLOv5 model inference configuration."""
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("--weights", type=str, default=ROOT / "yolov5s.pt", help="weights path")
|
|
parser.add_argument("--imgsz", "--img", "--img-size", type=int, default=640, help="inference size (pixels)")
|
|
parser.add_argument("--batch-size", type=int, default=1, help="batch size")
|
|
parser.add_argument("--data", type=str, default=ROOT / "data/coco128.yaml", help="dataset.yaml path")
|
|
parser.add_argument("--device", default="", help="cuda device, i.e. 0 or 0,1,2,3 or cpu")
|
|
parser.add_argument("--half", action="store_true", help="use FP16 half-precision inference")
|
|
parser.add_argument("--test", action="store_true", help="test exports only")
|
|
parser.add_argument("--pt-only", action="store_true", help="test PyTorch only")
|
|
parser.add_argument("--hard-fail", nargs="?", const=True, default=False, help="Exception on error or < min metric")
|
|
opt = parser.parse_args()
|
|
opt.data = check_yaml(opt.data) # check YAML
|
|
print_args(vars(opt))
|
|
return opt
|
|
|
|
|
|
def main(opt):
|
|
"""Executes a test run if `opt.test` is True, otherwise starts training or inference with provided options."""
|
|
test(**vars(opt)) if opt.test else run(**vars(opt))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
opt = parse_opt()
|
|
main(opt)
|