benchmarks.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
  2. """
  3. Benchmark a YOLO model formats for speed and accuracy.
  4. Usage:
  5. from ultralytics.utils.benchmarks import ProfileModels, benchmark
  6. ProfileModels(['yolov8n.yaml', 'yolov8s.yaml']).profile()
  7. benchmark(model='yolov8n.pt', imgsz=160)
  8. Format | `format=argument` | Model
  9. --- | --- | ---
  10. PyTorch | - | yolov8n.pt
  11. TorchScript | `torchscript` | yolov8n.torchscript
  12. ONNX | `onnx` | yolov8n.onnx
  13. OpenVINO | `openvino` | yolov8n_openvino_model/
  14. TensorRT | `engine` | yolov8n.engine
  15. CoreML | `coreml` | yolov8n.mlpackage
  16. TensorFlow SavedModel | `saved_model` | yolov8n_saved_model/
  17. TensorFlow GraphDef | `pb` | yolov8n.pb
  18. TensorFlow Lite | `tflite` | yolov8n.tflite
  19. TensorFlow Edge TPU | `edgetpu` | yolov8n_edgetpu.tflite
  20. TensorFlow.js | `tfjs` | yolov8n_web_model/
  21. PaddlePaddle | `paddle` | yolov8n_paddle_model/
  22. MNN | `mnn` | yolov8n.mnn
  23. NCNN | `ncnn` | yolov8n_ncnn_model/
  24. """
  25. import glob
  26. import os
  27. import platform
  28. import re
  29. import shutil
  30. import time
  31. from pathlib import Path
  32. import numpy as np
  33. import torch.cuda
  34. import yaml
  35. from ultralytics import YOLO, YOLOWorld
  36. from ultralytics.cfg import TASK2DATA, TASK2METRIC
  37. from ultralytics.engine.exporter import export_formats
  38. from ultralytics.utils import ARM64, ASSETS, IS_JETSON, IS_RASPBERRYPI, LINUX, LOGGER, MACOS, TQDM, WEIGHTS_DIR
  39. from ultralytics.utils.checks import IS_PYTHON_3_12, check_requirements, check_yolo
  40. from ultralytics.utils.downloads import safe_download
  41. from ultralytics.utils.files import file_size
  42. from ultralytics.utils.torch_utils import get_cpu_info, select_device
  43. def benchmark(
  44. model=WEIGHTS_DIR / "yolo11n.pt",
  45. data=None,
  46. imgsz=160,
  47. half=False,
  48. int8=False,
  49. device="cpu",
  50. verbose=False,
  51. eps=1e-3,
  52. ):
  53. """
  54. Benchmark a YOLO model across different formats for speed and accuracy.
  55. Args:
  56. model (str | Path): Path to the model file or directory.
  57. data (str | None): Dataset to evaluate on, inherited from TASK2DATA if not passed.
  58. imgsz (int): Image size for the benchmark.
  59. half (bool): Use half-precision for the model if True.
  60. int8 (bool): Use int8-precision for the model if True.
  61. device (str): Device to run the benchmark on, either 'cpu' or 'cuda'.
  62. verbose (bool | float): If True or a float, assert benchmarks pass with given metric.
  63. eps (float): Epsilon value for divide by zero prevention.
  64. Returns:
  65. (pandas.DataFrame): A pandas DataFrame with benchmark results for each format, including file size, metric,
  66. and inference time.
  67. Examples:
  68. Benchmark a YOLO model with default settings:
  69. >>> from ultralytics.utils.benchmarks import benchmark
  70. >>> benchmark(model="yolo11n.pt", imgsz=640)
  71. """
  72. import pandas as pd # scope for faster 'import ultralytics'
  73. pd.options.display.max_columns = 10
  74. pd.options.display.width = 120
  75. device = select_device(device, verbose=False)
  76. if isinstance(model, (str, Path)):
  77. model = YOLO(model)
  78. is_end2end = getattr(model.model.model[-1], "end2end", False)
  79. y = []
  80. t0 = time.time()
  81. for i, (name, format, suffix, cpu, gpu, _) in enumerate(zip(*export_formats().values())):
  82. emoji, filename = "❌", None # export defaults
  83. try:
  84. # Checks
  85. if i == 7: # TF GraphDef
  86. assert model.task != "obb", "TensorFlow GraphDef not supported for OBB task"
  87. elif i == 9: # Edge TPU
  88. assert LINUX and not ARM64, "Edge TPU export only supported on non-aarch64 Linux"
  89. elif i in {5, 10}: # CoreML and TF.js
  90. assert MACOS or LINUX, "CoreML and TF.js export only supported on macOS and Linux"
  91. assert not IS_RASPBERRYPI, "CoreML and TF.js export not supported on Raspberry Pi"
  92. assert not IS_JETSON, "CoreML and TF.js export not supported on NVIDIA Jetson"
  93. if i in {5}: # CoreML
  94. assert not IS_PYTHON_3_12, "CoreML not supported on Python 3.12"
  95. if i in {6, 7, 8}: # TF SavedModel, TF GraphDef, and TFLite
  96. assert not isinstance(model, YOLOWorld), "YOLOWorldv2 TensorFlow exports not supported by onnx2tf yet"
  97. if i in {9, 10}: # TF EdgeTPU and TF.js
  98. assert not isinstance(model, YOLOWorld), "YOLOWorldv2 TensorFlow exports not supported by onnx2tf yet"
  99. if i == 11: # Paddle
  100. assert not isinstance(model, YOLOWorld), "YOLOWorldv2 Paddle exports not supported yet"
  101. assert not is_end2end, "End-to-end models not supported by PaddlePaddle yet"
  102. assert LINUX or MACOS, "Windows Paddle exports not supported yet"
  103. if i == 12: # MNN
  104. assert not isinstance(model, YOLOWorld), "YOLOWorldv2 MNN exports not supported yet"
  105. if i == 13: # NCNN
  106. assert not isinstance(model, YOLOWorld), "YOLOWorldv2 NCNN exports not supported yet"
  107. if i == 14: # IMX
  108. assert not is_end2end
  109. assert not isinstance(model, YOLOWorld), "YOLOWorldv2 IMX exports not supported"
  110. assert model.task == "detect", "IMX only supported for detection task"
  111. assert "C2f" in model.__str__(), "IMX only supported for YOLOv8"
  112. if "cpu" in device.type:
  113. assert cpu, "inference not supported on CPU"
  114. if "cuda" in device.type:
  115. assert gpu, "inference not supported on GPU"
  116. # Export
  117. if format == "-":
  118. filename = model.ckpt_path or model.cfg
  119. exported_model = model # PyTorch format
  120. else:
  121. filename = model.export(imgsz=imgsz, format=format, half=half, int8=int8, device=device, verbose=False)
  122. exported_model = YOLO(filename, task=model.task)
  123. assert suffix in str(filename), "export failed"
  124. emoji = "❎" # indicates export succeeded
  125. # Predict
  126. assert model.task != "pose" or i != 7, "GraphDef Pose inference is not supported"
  127. assert i not in {9, 10}, "inference not supported" # Edge TPU and TF.js are unsupported
  128. assert i != 5 or platform.system() == "Darwin", "inference only supported on macOS>=10.13" # CoreML
  129. if i in {13}:
  130. assert not is_end2end, "End-to-end torch.topk operation is not supported for NCNN prediction yet"
  131. exported_model.predict(ASSETS / "bus.jpg", imgsz=imgsz, device=device, half=half)
  132. # Validate
  133. data = data or TASK2DATA[model.task] # task to dataset, i.e. coco8.yaml for task=detect
  134. key = TASK2METRIC[model.task] # task to metric, i.e. metrics/mAP50-95(B) for task=detect
  135. results = exported_model.val(
  136. data=data, batch=1, imgsz=imgsz, plots=False, device=device, half=half, int8=int8, verbose=False
  137. )
  138. metric, speed = results.results_dict[key], results.speed["inference"]
  139. fps = round(1000 / (speed + eps), 2) # frames per second
  140. y.append([name, "✅", round(file_size(filename), 1), round(metric, 4), round(speed, 2), fps])
  141. except Exception as e:
  142. if verbose:
  143. assert type(e) is AssertionError, f"Benchmark failure for {name}: {e}"
  144. LOGGER.warning(f"ERROR ❌️ Benchmark failure for {name}: {e}")
  145. y.append([name, emoji, round(file_size(filename), 1), None, None, None]) # mAP, t_inference
  146. # Print results
  147. check_yolo(device=device) # print system info
  148. df = pd.DataFrame(y, columns=["Format", "Status❔", "Size (MB)", key, "Inference time (ms/im)", "FPS"])
  149. name = Path(model.ckpt_path).name
  150. s = f"\nBenchmarks complete for {name} on {data} at imgsz={imgsz} ({time.time() - t0:.2f}s)\n{df}\n"
  151. LOGGER.info(s)
  152. with open("benchmarks.log", "a", errors="ignore", encoding="utf-8") as f:
  153. f.write(s)
  154. if verbose and isinstance(verbose, float):
  155. metrics = df[key].array # values to compare to floor
  156. floor = verbose # minimum metric floor to pass, i.e. = 0.29 mAP for YOLOv5n
  157. assert all(x > floor for x in metrics if pd.notna(x)), f"Benchmark failure: metric(s) < floor {floor}"
  158. return df
  159. class RF100Benchmark:
  160. """Benchmark YOLO model performance across various formats for speed and accuracy."""
  161. def __init__(self):
  162. """Initialize the RF100Benchmark class for benchmarking YOLO model performance across various formats."""
  163. self.ds_names = []
  164. self.ds_cfg_list = []
  165. self.rf = None
  166. self.val_metrics = ["class", "images", "targets", "precision", "recall", "map50", "map95"]
  167. def set_key(self, api_key):
  168. """
  169. Set Roboflow API key for processing.
  170. Args:
  171. api_key (str): The API key.
  172. Examples:
  173. Set the Roboflow API key for accessing datasets:
  174. >>> benchmark = RF100Benchmark()
  175. >>> benchmark.set_key("your_roboflow_api_key")
  176. """
  177. check_requirements("roboflow")
  178. from roboflow import Roboflow
  179. self.rf = Roboflow(api_key=api_key)
  180. def parse_dataset(self, ds_link_txt="datasets_links.txt"):
  181. """
  182. Parse dataset links and download datasets.
  183. Args:
  184. ds_link_txt (str): Path to the file containing dataset links.
  185. Examples:
  186. >>> benchmark = RF100Benchmark()
  187. >>> benchmark.set_key("api_key")
  188. >>> benchmark.parse_dataset("datasets_links.txt")
  189. """
  190. (shutil.rmtree("rf-100"), os.mkdir("rf-100")) if os.path.exists("rf-100") else os.mkdir("rf-100")
  191. os.chdir("rf-100")
  192. os.mkdir("ultralytics-benchmarks")
  193. safe_download("https://github.com/ultralytics/assets/releases/download/v0.0.0/datasets_links.txt")
  194. with open(ds_link_txt) as file:
  195. for line in file:
  196. try:
  197. _, url, workspace, project, version = re.split("/+", line.strip())
  198. self.ds_names.append(project)
  199. proj_version = f"{project}-{version}"
  200. if not Path(proj_version).exists():
  201. self.rf.workspace(workspace).project(project).version(version).download("yolov8")
  202. else:
  203. print("Dataset already downloaded.")
  204. self.ds_cfg_list.append(Path.cwd() / proj_version / "data.yaml")
  205. except Exception:
  206. continue
  207. return self.ds_names, self.ds_cfg_list
  208. @staticmethod
  209. def fix_yaml(path):
  210. """
  211. Fixes the train and validation paths in a given YAML file.
  212. Args:
  213. path (str): Path to the YAML file to be fixed.
  214. Examples:
  215. >>> RF100Benchmark.fix_yaml("path/to/data.yaml")
  216. """
  217. with open(path) as file:
  218. yaml_data = yaml.safe_load(file)
  219. yaml_data["train"] = "train/images"
  220. yaml_data["val"] = "valid/images"
  221. with open(path, "w") as file:
  222. yaml.safe_dump(yaml_data, file)
  223. def evaluate(self, yaml_path, val_log_file, eval_log_file, list_ind):
  224. """
  225. Evaluate model performance on validation results.
  226. Args:
  227. yaml_path (str): Path to the YAML configuration file.
  228. val_log_file (str): Path to the validation log file.
  229. eval_log_file (str): Path to the evaluation log file.
  230. list_ind (int): Index of the current dataset in the list.
  231. Returns:
  232. (float): The mean average precision (mAP) value for the evaluated model.
  233. Examples:
  234. Evaluate a model on a specific dataset
  235. >>> benchmark = RF100Benchmark()
  236. >>> benchmark.evaluate("path/to/data.yaml", "path/to/val_log.txt", "path/to/eval_log.txt", 0)
  237. """
  238. skip_symbols = ["🚀", "⚠️", "💡", "❌"]
  239. with open(yaml_path) as stream:
  240. class_names = yaml.safe_load(stream)["names"]
  241. with open(val_log_file, encoding="utf-8") as f:
  242. lines = f.readlines()
  243. eval_lines = []
  244. for line in lines:
  245. if any(symbol in line for symbol in skip_symbols):
  246. continue
  247. entries = line.split(" ")
  248. entries = list(filter(lambda val: val != "", entries))
  249. entries = [e.strip("\n") for e in entries]
  250. eval_lines.extend(
  251. {
  252. "class": entries[0],
  253. "images": entries[1],
  254. "targets": entries[2],
  255. "precision": entries[3],
  256. "recall": entries[4],
  257. "map50": entries[5],
  258. "map95": entries[6],
  259. }
  260. for e in entries
  261. if e in class_names or (e == "all" and "(AP)" not in entries and "(AR)" not in entries)
  262. )
  263. map_val = 0.0
  264. if len(eval_lines) > 1:
  265. print("There's more dicts")
  266. for lst in eval_lines:
  267. if lst["class"] == "all":
  268. map_val = lst["map50"]
  269. else:
  270. print("There's only one dict res")
  271. map_val = [res["map50"] for res in eval_lines][0]
  272. with open(eval_log_file, "a") as f:
  273. f.write(f"{self.ds_names[list_ind]}: {map_val}\n")
  274. class ProfileModels:
  275. """
  276. ProfileModels class for profiling different models on ONNX and TensorRT.
  277. This class profiles the performance of different models, returning results such as model speed and FLOPs.
  278. Attributes:
  279. paths (List[str]): Paths of the models to profile.
  280. num_timed_runs (int): Number of timed runs for the profiling.
  281. num_warmup_runs (int): Number of warmup runs before profiling.
  282. min_time (float): Minimum number of seconds to profile for.
  283. imgsz (int): Image size used in the models.
  284. half (bool): Flag to indicate whether to use FP16 half-precision for TensorRT profiling.
  285. trt (bool): Flag to indicate whether to profile using TensorRT.
  286. device (torch.device): Device used for profiling.
  287. Methods:
  288. profile: Profiles the models and prints the result.
  289. Examples:
  290. Profile models and print results
  291. >>> from ultralytics.utils.benchmarks import ProfileModels
  292. >>> profiler = ProfileModels(["yolov8n.yaml", "yolov8s.yaml"], imgsz=640)
  293. >>> profiler.profile()
  294. """
  295. def __init__(
  296. self,
  297. paths: list,
  298. num_timed_runs=100,
  299. num_warmup_runs=10,
  300. min_time=60,
  301. imgsz=640,
  302. half=True,
  303. trt=True,
  304. device=None,
  305. ):
  306. """
  307. Initialize the ProfileModels class for profiling models.
  308. Args:
  309. paths (List[str]): List of paths of the models to be profiled.
  310. num_timed_runs (int): Number of timed runs for the profiling.
  311. num_warmup_runs (int): Number of warmup runs before the actual profiling starts.
  312. min_time (float): Minimum time in seconds for profiling a model.
  313. imgsz (int): Size of the image used during profiling.
  314. half (bool): Flag to indicate whether to use FP16 half-precision for TensorRT profiling.
  315. trt (bool): Flag to indicate whether to profile using TensorRT.
  316. device (torch.device | None): Device used for profiling. If None, it is determined automatically.
  317. Notes:
  318. FP16 'half' argument option removed for ONNX as slower on CPU than FP32.
  319. Examples:
  320. Initialize and profile models
  321. >>> from ultralytics.utils.benchmarks import ProfileModels
  322. >>> profiler = ProfileModels(["yolov8n.yaml", "yolov8s.yaml"], imgsz=640)
  323. >>> profiler.profile()
  324. """
  325. self.paths = paths
  326. self.num_timed_runs = num_timed_runs
  327. self.num_warmup_runs = num_warmup_runs
  328. self.min_time = min_time
  329. self.imgsz = imgsz
  330. self.half = half
  331. self.trt = trt # run TensorRT profiling
  332. self.device = device or torch.device(0 if torch.cuda.is_available() else "cpu")
  333. def profile(self):
  334. """Profiles YOLO models for speed and accuracy across various formats including ONNX and TensorRT."""
  335. files = self.get_files()
  336. if not files:
  337. print("No matching *.pt or *.onnx files found.")
  338. return
  339. table_rows = []
  340. output = []
  341. for file in files:
  342. engine_file = file.with_suffix(".engine")
  343. if file.suffix in {".pt", ".yaml", ".yml"}:
  344. model = YOLO(str(file))
  345. model.fuse() # to report correct params and GFLOPs in model.info()
  346. model_info = model.info()
  347. if self.trt and self.device.type != "cpu" and not engine_file.is_file():
  348. engine_file = model.export(
  349. format="engine",
  350. half=self.half,
  351. imgsz=self.imgsz,
  352. device=self.device,
  353. verbose=False,
  354. )
  355. onnx_file = model.export(
  356. format="onnx",
  357. imgsz=self.imgsz,
  358. device=self.device,
  359. verbose=False,
  360. )
  361. elif file.suffix == ".onnx":
  362. model_info = self.get_onnx_model_info(file)
  363. onnx_file = file
  364. else:
  365. continue
  366. t_engine = self.profile_tensorrt_model(str(engine_file))
  367. t_onnx = self.profile_onnx_model(str(onnx_file))
  368. table_rows.append(self.generate_table_row(file.stem, t_onnx, t_engine, model_info))
  369. output.append(self.generate_results_dict(file.stem, t_onnx, t_engine, model_info))
  370. self.print_table(table_rows)
  371. return output
  372. def get_files(self):
  373. """Returns a list of paths for all relevant model files given by the user."""
  374. files = []
  375. for path in self.paths:
  376. path = Path(path)
  377. if path.is_dir():
  378. extensions = ["*.pt", "*.onnx", "*.yaml"]
  379. files.extend([file for ext in extensions for file in glob.glob(str(path / ext))])
  380. elif path.suffix in {".pt", ".yaml", ".yml"}: # add non-existing
  381. files.append(str(path))
  382. else:
  383. files.extend(glob.glob(str(path)))
  384. print(f"Profiling: {sorted(files)}")
  385. return [Path(file) for file in sorted(files)]
  386. @staticmethod
  387. def get_onnx_model_info(onnx_file: str):
  388. """Extracts metadata from an ONNX model file including parameters, GFLOPs, and input shape."""
  389. return 0.0, 0.0, 0.0, 0.0 # return (num_layers, num_params, num_gradients, num_flops)
  390. @staticmethod
  391. def iterative_sigma_clipping(data, sigma=2, max_iters=3):
  392. """Applies iterative sigma clipping to data to remove outliers based on specified sigma and iteration count."""
  393. data = np.array(data)
  394. for _ in range(max_iters):
  395. mean, std = np.mean(data), np.std(data)
  396. clipped_data = data[(data > mean - sigma * std) & (data < mean + sigma * std)]
  397. if len(clipped_data) == len(data):
  398. break
  399. data = clipped_data
  400. return data
  401. def profile_tensorrt_model(self, engine_file: str, eps: float = 1e-3):
  402. """Profiles YOLO model performance with TensorRT, measuring average run time and standard deviation."""
  403. if not self.trt or not Path(engine_file).is_file():
  404. return 0.0, 0.0
  405. # Model and input
  406. model = YOLO(engine_file)
  407. input_data = np.zeros((self.imgsz, self.imgsz, 3), dtype=np.uint8) # use uint8 for Classify
  408. # Warmup runs
  409. elapsed = 0.0
  410. for _ in range(3):
  411. start_time = time.time()
  412. for _ in range(self.num_warmup_runs):
  413. model(input_data, imgsz=self.imgsz, verbose=False)
  414. elapsed = time.time() - start_time
  415. # Compute number of runs as higher of min_time or num_timed_runs
  416. num_runs = max(round(self.min_time / (elapsed + eps) * self.num_warmup_runs), self.num_timed_runs * 50)
  417. # Timed runs
  418. run_times = []
  419. for _ in TQDM(range(num_runs), desc=engine_file):
  420. results = model(input_data, imgsz=self.imgsz, verbose=False)
  421. run_times.append(results[0].speed["inference"]) # Convert to milliseconds
  422. run_times = self.iterative_sigma_clipping(np.array(run_times), sigma=2, max_iters=3) # sigma clipping
  423. return np.mean(run_times), np.std(run_times)
  424. def profile_onnx_model(self, onnx_file: str, eps: float = 1e-3):
  425. """Profiles an ONNX model, measuring average inference time and standard deviation across multiple runs."""
  426. check_requirements("onnxruntime")
  427. import onnxruntime as ort
  428. # Session with either 'TensorrtExecutionProvider', 'CUDAExecutionProvider', 'CPUExecutionProvider'
  429. sess_options = ort.SessionOptions()
  430. sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
  431. sess_options.intra_op_num_threads = 8 # Limit the number of threads
  432. sess = ort.InferenceSession(onnx_file, sess_options, providers=["CPUExecutionProvider"])
  433. input_tensor = sess.get_inputs()[0]
  434. input_type = input_tensor.type
  435. dynamic = not all(isinstance(dim, int) and dim >= 0 for dim in input_tensor.shape) # dynamic input shape
  436. input_shape = (1, 3, self.imgsz, self.imgsz) if dynamic else input_tensor.shape
  437. # Mapping ONNX datatype to numpy datatype
  438. if "float16" in input_type:
  439. input_dtype = np.float16
  440. elif "float" in input_type:
  441. input_dtype = np.float32
  442. elif "double" in input_type:
  443. input_dtype = np.float64
  444. elif "int64" in input_type:
  445. input_dtype = np.int64
  446. elif "int32" in input_type:
  447. input_dtype = np.int32
  448. else:
  449. raise ValueError(f"Unsupported ONNX datatype {input_type}")
  450. input_data = np.random.rand(*input_shape).astype(input_dtype)
  451. input_name = input_tensor.name
  452. output_name = sess.get_outputs()[0].name
  453. # Warmup runs
  454. elapsed = 0.0
  455. for _ in range(3):
  456. start_time = time.time()
  457. for _ in range(self.num_warmup_runs):
  458. sess.run([output_name], {input_name: input_data})
  459. elapsed = time.time() - start_time
  460. # Compute number of runs as higher of min_time or num_timed_runs
  461. num_runs = max(round(self.min_time / (elapsed + eps) * self.num_warmup_runs), self.num_timed_runs)
  462. # Timed runs
  463. run_times = []
  464. for _ in TQDM(range(num_runs), desc=onnx_file):
  465. start_time = time.time()
  466. sess.run([output_name], {input_name: input_data})
  467. run_times.append((time.time() - start_time) * 1000) # Convert to milliseconds
  468. run_times = self.iterative_sigma_clipping(np.array(run_times), sigma=2, max_iters=5) # sigma clipping
  469. return np.mean(run_times), np.std(run_times)
  470. def generate_table_row(self, model_name, t_onnx, t_engine, model_info):
  471. """Generates a table row string with model performance metrics including inference times and model details."""
  472. layers, params, gradients, flops = model_info
  473. return (
  474. f"| {model_name:18s} | {self.imgsz} | - | {t_onnx[0]:.1f}±{t_onnx[1]:.1f} ms | {t_engine[0]:.1f}±"
  475. f"{t_engine[1]:.1f} ms | {params / 1e6:.1f} | {flops:.1f} |"
  476. )
  477. @staticmethod
  478. def generate_results_dict(model_name, t_onnx, t_engine, model_info):
  479. """Generates a dictionary of profiling results including model name, parameters, GFLOPs, and speed metrics."""
  480. layers, params, gradients, flops = model_info
  481. return {
  482. "model/name": model_name,
  483. "model/parameters": params,
  484. "model/GFLOPs": round(flops, 3),
  485. "model/speed_ONNX(ms)": round(t_onnx[0], 3),
  486. "model/speed_TensorRT(ms)": round(t_engine[0], 3),
  487. }
  488. @staticmethod
  489. def print_table(table_rows):
  490. """Prints a formatted table of model profiling results, including speed and accuracy metrics."""
  491. gpu = torch.cuda.get_device_name(0) if torch.cuda.is_available() else "GPU"
  492. headers = [
  493. "Model",
  494. "size<br><sup>(pixels)",
  495. "mAP<sup>val<br>50-95",
  496. f"Speed<br><sup>CPU ({get_cpu_info()}) ONNX<br>(ms)",
  497. f"Speed<br><sup>{gpu} TensorRT<br>(ms)",
  498. "params<br><sup>(M)",
  499. "FLOPs<br><sup>(B)",
  500. ]
  501. header = "|" + "|".join(f" {h} " for h in headers) + "|"
  502. separator = "|" + "|".join("-" * (len(h) + 2) for h in headers) + "|"
  503. print(f"\n\n{header}")
  504. print(separator)
  505. for row in table_rows:
  506. print(row)