
    hv}              	      J   S r SSKJr  SSKrSSKrSSKrSSKrSSKrSSKrSSK	J
r
  SSKrSSKrSSKJrJr  SSKJrJr  SSKJr  SSKJrJrJrJrJrJrJrJrJ r J!r!  SS	K"J#r#J$r$J%r%J&r&J'r'  SS
K(J)r)  SSK*J+r+  SSK,J-r-J.r.  \ S-  SSSSSSSS4	S jr/ " S S5      r0 " S S5      r1g)a  
Benchmark a YOLO model formats for speed and accuracy.

Usage:
    from ultralytics.utils.benchmarks import ProfileModels, benchmark
    ProfileModels(['yolo11n.yaml', 'yolov8s.yaml']).run()
    benchmark(model='yolo11n.pt', imgsz=160)

Format                  | `format=argument`         | Model
---                     | ---                       | ---
PyTorch                 | -                         | yolo11n.pt
TorchScript             | `torchscript`             | yolo11n.torchscript
ONNX                    | `onnx`                    | yolo11n.onnx
OpenVINO                | `openvino`                | yolo11n_openvino_model/
TensorRT                | `engine`                  | yolo11n.engine
CoreML                  | `coreml`                  | yolo11n.mlpackage
TensorFlow SavedModel   | `saved_model`             | yolo11n_saved_model/
TensorFlow GraphDef     | `pb`                      | yolo11n.pb
TensorFlow Lite         | `tflite`                  | yolo11n.tflite
TensorFlow Edge TPU     | `edgetpu`                 | yolo11n_edgetpu.tflite
TensorFlow.js           | `tfjs`                    | yolo11n_web_model/
PaddlePaddle            | `paddle`                  | yolo11n_paddle_model/
MNN                     | `mnn`                     | yolo11n.mnn
NCNN                    | `ncnn`                    | yolo11n_ncnn_model/
IMX                     | `imx`                     | yolo11n_imx_model/
RKNN                    | `rknn`                    | yolo11n_rknn_model/
    )annotationsN)Path)YOLO	YOLOWorld)	TASK2DATATASK2METRIC)export_formats)
ARM64ASSETS
ASSETS_URL	IS_JETSONLINUXLOGGERMACOSTQDMWEIGHTS_DIRYAML)IS_PYTHON_3_13check_imgszcheck_requirements
check_yolois_rockchip)safe_download)	file_size)get_cpu_infoselect_devicez
yolo11n.pt   FcpuMbP? c	                F  ^% [        U5      n[        U[        5      (       a  US   US   :X  d   S5       e SSKn
U
R                  R                  S5        U
R                  R                  S5        U
R                  R                  S5        U
R                  R                  S5        U
R                  R                  S5        U
R                  R                  S5        [        USS	9n[        U [        [        45      (       a  [        U 5      n [        U R                   R                   S   S
S5      nU=(       d    ["        U R$                     n[&        U R$                     n/ n[(        R(                  " 5       nUR+                  5       nU(       a*  [-        [/        5       S   5      nUU;   d   SU SU S35       e[1        [/        5       R3                  5       6  GH  u  nnnnnnSu  nn U(       a  X:w  a  M  US:X  a  U R$                  S:w  d   S5       eORUS:X  a  [4        (       a  [6        (       a   S5       eO.US;   a(  [8        (       d  [4        (       a  [6        (       a   S5       eUS:X  a  [:        (       a   S5       eUS;   a  [        U [<        5      (       a   S5       eUS:X  ai  [        U [<        5      (       a   S5       eU R$                  S:w  d   S5       eU(       a   S5       e[4        (       a  [>        (       a  [8        (       d   S5       eUS :X  a  [        U [<        5      (       a   S!5       eUS":X  a  [        U [<        5      (       a   S#5       eUS$:X  aW  U(       a   e[        U [<        5      (       a   S%5       eU R$                  S&:X  d   S'5       eS(U RA                  5       ;   d   S)5       eUS*:X  aR  [        U [<        5      (       a   S+5       eU(       a   S,5       e[4        (       d   S-5       e[C        5       (       a   S.5       eS/URD                  ;   a  U(       d   S05       eS1URD                  ;   a  U(       d   S25       eUS3:X  a5  U RF                  =(       d    U RH                  =(       d    U RJ                  nU nOAU RL                  " ScX(X4XSS4.U	D6n[        UU R$                  S59nU[        U5      ;   d   S65       eS7nU R$                  S8:w  d  US:w  d   S95       eUS:;  d   S;5       eUS:w  d   [N        RP                  " 5       S<:X  d   S=5       eUS":X  a  U(       a   S>5       eURS                  [T        S?-  X%USS@9  URW                  USUSUUUSSASB9	nURX                  U   URZ                  SC   nn[]        SDUU-   -  SE5      nUR_                  USF[]        [a        U5      S5      []        USG5      []        USE5      U/5        GM     [k        USJ9  U
Rm                  USKSLSMUSNSO/SPSQ9nURo                  SRSSS9nURq                  U
Rs                  5       Ru                  U
Rv                  5      Ry                  S35      5      nU RJ                  n[(        R(                  " 5       U-
  n STn!SUU SVU SWU SXU SY SZU! S[U S[3n"[f        Rz                  " U"5        [}        S\S]S^S_S`9 n#U#R                  U"5        SSS5        U(       aN  [        U[        5      (       a9  UU   R                  5       n$Um%[s        U%4Sa jU$ 5       5      (       d
   SbT% 35       eU$ ! [b         ax  nU(       a  [E        U5      [d        L d   SHU SIU 35       e[f        Rh                  " SHU SIU 35        UR_                  UU[]        [a        U5      S5      SSS/5         SnAGM  SnAff = f! , (       d  f       N= f)daH  
Benchmark a YOLO model across different formats for speed and accuracy.

Args:
    model (str | Path): Path to the model file or directory.
    data (str | None): Dataset to evaluate on, inherited from TASK2DATA if not passed.
    imgsz (int): Image size for the benchmark.
    half (bool): Use half-precision for the model if True.
    int8 (bool): Use int8-precision for the model if True.
    device (str): Device to run the benchmark on, either 'cpu' or 'cuda'.
    verbose (bool | float): If True or a float, assert benchmarks pass with given metric.
    eps (float): Epsilon value for divide by zero prevention.
    format (str): Export format for benchmarking. If not supplied all formats are benchmarked.
    **kwargs (Any): Additional keyword arguments for exporter.

Returns:
    (polars.DataFrame): A polars DataFrame with benchmark results for each format, including file size, metric,
        and inference time.

Examples:
    Benchmark a YOLO model with default settings:
    >>> from ultralytics.utils.benchmarks import benchmark
    >>> benchmark(model="yolo11n.pt", imgsz=640)
r      Tz'benchmark() only supports square imgsz.NASCII_BORDERS_ONLY_CONDENSEDF)verboseend2endArgumentzExpected format to be one of z, but got 'z'.)   ❌Npbobbz.TensorFlow GraphDef not supported for OBB taskedgetpuz3Edge TPU export only supported on non-aarch64 Linux>   tfjscoremlzECoreML and TF.js export only supported on macOS and non-aarch64 Linuxr-   z#CoreML not supported on Python 3.13>   r)   r,   tfliter+   saved_modelz;YOLOWorldv2 TensorFlow exports not supported by onnx2tf yetpaddlez,YOLOWorldv2 Paddle exports not supported yetzBPaddle OBB bug https://github.com/PaddlePaddle/Paddle/issues/72024z3End-to-end models not supported by PaddlePaddle yetz3Windows and Jetson Paddle exports not supported yetmnnz)YOLOWorldv2 MNN exports not supported yetncnnz*YOLOWorldv2 NCNN exports not supported yetimxz%YOLOWorldv2 IMX exports not supporteddetectz%IMX only supported for detection taskC2fz*IMX only supported for YOLOv8n and YOLO11nrknnz*YOLOWorldv2 RKNN exports not supported yetz+End-to-end models not supported by RKNN yetzRKNN only supported on Linuxz1RKNN Inference only supported on Rockchip devicesr   zinference not supported on CPUcudazinference not supported on GPU-)imgszformathalfint8datadevicer%   )taskzexport failedu   ❎posez(GraphDef Pose inference is not supported>   r,   r+   zinference not supportedDarwinz(inference only supported on macOS>=10.13zHEnd-to-end torch.topk operation is not supported for NCNN prediction yetzbus.jpg)r9   r>   r;   r%   r   )	r=   batchr9   plotsr>   r;   r<   r%   conf	inference     u   ✅   zBenchmark failure for : )r>   Formatu	   Status❔z	Size (MB)zInference time (ms/im)FPSrow)schemaorient )offsetud   Benchmarks legend:  - ✅ Success  - ❎ Export passed but validation failed  - ❌️ Export failedz
Benchmarks complete for z on z
 at imgsz=z (z.2fzs)

zbenchmarks.logaignoreutf-8)errorsencodingc              3  h   >#    U  H'  n[         R                  " U5      (       a  M   UT:  v   M)     g 7fN)npisnan).0xfloors     V/home/james-whalen/.local/lib/python3.13/site-packages/ultralytics/utils/benchmarks.py	<genexpr>benchmark.<locals>.<genexpr>   s!     AgRXXa[91u9gs   22z%Benchmark failure: metric(s) < floor  )Br   
isinstancelistpolarsConfigset_tbl_colsset_tbl_rowsset_tbl_width_charsset_tbl_hide_column_data_typesset_tbl_hide_dataframe_shapeset_tbl_formattingr   strr   r   getattrmodelr   r?   r   timelower	frozensetr	   zipvaluesr   r
   r   r   r   r   __str__r   typept_path	ckpt_path
model_nameexportplatformsystempredictr   valresults_dictspeedroundappendr   	ExceptionAssertionErrorr   errorr   	DataFramewith_row_indexwith_columnsallcastString	fill_nullinfoopenwritefloatto_numpy)&rn   r=   r9   r;   r<   r>   r%   epsr:   kwargspl
is_end2endkeyyt0
format_argformatsnamesuffixr   gpu_emojifilenameexported_modelresultsmetricr   fpsedf
df_displaydtlegendsfmetricsr]   s&                                        @r^   	benchmarkr   5   sD   H E#-eT#:#:58uQxoFooDII2II2II!!"%II,,T2II**40II  !?@651F%#t%%U**2.	5AJ(9UZZ(D
ejj
!C
A	BJN,Z89 d$A'+V`Uaac"dd -0.2B2I2I2K-L)ffc3%xQ	Uj2 ~zzU*\,\\*9$uUUa,aa*U--uuu [5 !)>P+PP)KK%eY77v9vv7!%eY77g9gg7zzU*p,pp*%\'\\~iiEEp;pp9%eY77d9dd7%eY77e9ee7%%~%eY77`9``7zzX-V/VV-/]1]]/%eY77e9ee7%T'TT~u<<<u&==]*]](#<<<s$<<<s } ==OEOOOu?O?O!& << T4hmqw "&hUZZ!@X.??.E ::'6T>e;ee9!44O6OO4X%):h)FrHrrF%q'qq~""6I#5UX\fk"l %(( ) 
G $005w}}[7QEF,a0CHHdE58)<a#@%PQBRTYZ_abTcehij] .Ml f	a;SJbdi jsx	yB			3q		)Bryy!9!C!CC!HIJD	r	BsF
$TF$tfJugR3xtTZS[[]^h]iiklA
KKN	Hw	G1	
 
H :gu--S'""$AgAAArEjkpjqCrrA3  	UAw.0V4J4&PRSTRU2VV0LL1$r!=>HHdE58)<a#@$dSTT		U" 
H	Gs,   &\4O\^
^A,^

^
^ c                  T    \ rS rSrSrS rS
S jrSSS jjr\SS j5       r	SS jr
Srg	)RF100Benchmark   a  
Benchmark YOLO model performance across various formats for speed and accuracy.

This class provides functionality to benchmark YOLO models on the RF100 dataset collection.

Attributes:
    ds_names (list[str]): Names of datasets used for benchmarking.
    ds_cfg_list (list[Path]): List of paths to dataset configuration files.
    rf (Roboflow): Roboflow instance for accessing datasets.
    val_metrics (list[str]): Metrics used for validation.

Methods:
    set_key: Set Roboflow API key for accessing datasets.
    parse_dataset: Parse dataset links and download datasets.
    fix_yaml: Fix train and validation paths in YAML files.
    evaluate: Evaluate model performance on validation results.
c                @    / U l         / U l        SU l        / SQU l        g)zcInitialize the RF100Benchmark class for benchmarking YOLO model performance across various formats.Nclassimagestargets	precisionrecallmap50map95)ds_namesds_cfg_listrfval_metrics)selfs    r^   __init__RF100Benchmark.__init__   s     b    c                <    [        S5        SSKJn  U" US9U l        g)z
Set Roboflow API key for processing.

Args:
    api_key (str): The API key.

Examples:
    Set the Roboflow API key for accessing datasets:
    >>> benchmark = RF100Benchmark()
    >>> benchmark.set_key("your_roboflow_api_key")
roboflowr   )Roboflow)api_keyN)r   r   r   r   )r   r   r   s      r^   set_keyRF100Benchmark.set_key   s     	:&%7+r   c                   [         R                  R                  S5      (       a,  [        R                  " S5      [         R
                  " S5      4O[         R
                  " S5        [         R                  " S5        [         R
                  " S5        [        [         S35        [        USS9 nU GH  n [        R                  " SUR                  5       5      u  pEpgnU R                  R                  U5        U SU 3n	[        U	5      R                  5       (       dI  U R                   R#                  U5      R%                  U5      R'                  U5      R)                  S5        O[*        R,                  " S	5        U R.                  R                  [        R0                  " 5       U	-  S
-  5        GM     SSS5        U R                  U R.                  4$ ! [2         a     GM4  f = f! , (       d  f       N8= f)a  
Parse dataset links and download datasets.

Args:
    ds_link_txt (str): Path to the file containing dataset links.

Returns:
    ds_names (list[str]): List of dataset names.
    ds_cfg_list (list[Path]): List of paths to dataset configuration files.

Examples:
    >>> benchmark = RF100Benchmark()
    >>> benchmark.set_key("api_key")
    >>> benchmark.parse_dataset("datasets_links.txt")
zrf-100zultralytics-benchmarksz/datasets_links.txtrT   rV   z/+r8   yolov8zDataset already downloaded.z	data.yamlN)ospathexistsshutilrmtreemkdirchdirr   r   r   resplitstripr   r   r   r   	workspaceprojectversiondownloadr   r   r   cwdr   )
r   ds_link_txtfileliner   urlr   r   r   proj_versions
             r^   parse_datasetRF100Benchmark.parse_dataset	  su     :<9Q9Qx	 "((8"45WYW_W_`hWi

)*$789+0D
:<((4:V7AIMM((1&-Yay#9L-4466)))4<<WEMMgV__`hi$AB$$++DHHJ,E,ST  1 }}d.... !  10s1   /G*7C<G3G*
G'"G*&G''G**
G8c                p    [         R                  " U 5      nSUS'   SUS'   [         R                  " X5        g)z8Fix the train and validation paths in a given YAML file.ztrain/imagestrainzvalid/imagesr}   N)r   loaddump)r   	yaml_datas     r^   fix_yamlRF100Benchmark.fix_yaml.  s1     IIdO	+	')	%		)"r   c                Z  ^^^ / SQn[         R                  " U5      S   m[        USS9 nUR                  5       n/ nU H  m[	        U4S jU 5       5      (       a  M  TR                  S5      m[        [        S T5      5      mT V	s/ s H  oR                  S5      PM     sn	mUR                  UU4S	 jT 5       5        M     S
S
S
5        Sn
[        W5      S:  a0  [        R                  " S5        U H  nUS   S:X  d  M  US   n
M     O.[        R                  " S5        U Vs/ s H  oS   PM	     snS   n
[        USSS9 nUR                  U R                  U    SU
 S35        S
S
S
5        [        U
5      $ s  sn	f ! , (       d  f       N= fs  snf ! , (       d  f       N4= f)a9  
Evaluate model performance on validation results.

Args:
    yaml_path (str): Path to the YAML configuration file.
    val_log_file (str): Path to the validation log file.
    eval_log_file (str): Path to the evaluation log file.
    list_ind (int): Index of the current dataset in the list.

Returns:
    (float): The mean average precision (mAP) value for the evaluated model.

Examples:
    Evaluate a model on a specific dataset
    >>> benchmark = RF100Benchmark()
    >>> benchmark.evaluate("path/to/data.yaml", "path/to/val_log.txt", "path/to/eval_log.txt", 0)
)u   🚀u   ⚠️u   💡r(   namesrT   r   c              3  ,   >#    U  H	  oT;   v   M     g 7frX   ra   )r[   symbolr   s     r^   r_   *RF100Benchmark.evaluate.<locals>.<genexpr>N  s     AL&~Ls   rO   c                    U S:g  $ )Nr    ra   )r}   s    r^   <lambda>)RF100Benchmark.evaluate.<locals>.<lambda>Q  s    #)r   rQ   c           	   3     >#    U  HB  nUT;   d  US :X  d  M  ST;  d  M  ST;  d  M!  TS   TS   TS   TS   TS   TS   TS	   S
.v   MD     g7f)r   z(AP)z(AR)r   r"   rG      rH         r   Nra   )r[   r   class_namesentriess     r^   r_   r   S  s      " %K'AJ <B;P V\cjUj!(")!*#*1:%,QZ")!*!(!( %s   AAA&AN        r"   zMultiple dicts foundr   r   r   zSingle dict foundr   rR   rI   )r   r   r   	readlinesanyr   rc   filterr   extendlenr   r   r   r   r   )r   	yaml_pathval_log_fileeval_log_filelist_indskip_symbolsr   lines
eval_linesr   map_vallstresr   r   r   s                @@@r^   evaluateRF100Benchmark.evaluate6  sv   $ 9ii	*73,1QKKMEJALAAA**S/v&;WEF29:'Q774=':!! " %"   2, z?QKK./!w<5(!'lG " KK+,/9:z7|z:1=G-w71GGt}}X./r'"=> 8 W~7 ; 21< ;77s0   AF
F$#F*F	%FF
F
F*)r   r   r   r   N)r   rl   )zdatasets_links.txt)r   rl   )r   r   )r   rl   r   rl   r   rl   r   int)__name__
__module____qualname____firstlineno____doc__r   r   r   staticmethodr   r  __static_attributes__ra   r   r^   r   r      s1    $c,"#/J # #7r   r   c                     \ rS rSrSr       S               SS jjrS rS r\SS j5       r	\SSS jj5       r
SSS	 jjr\S
 5       rSSS jjr        SS jr\        SS j5       r\SS j5       rSrg)ProfileModelsip  a  
ProfileModels class for profiling different models on ONNX and TensorRT.

This class profiles the performance of different models, returning results such as model speed and FLOPs.

Attributes:
    paths (list[str]): Paths of the models to profile.
    num_timed_runs (int): Number of timed runs for the profiling.
    num_warmup_runs (int): Number of warmup runs before profiling.
    min_time (float): Minimum number of seconds to profile for.
    imgsz (int): Image size used in the models.
    half (bool): Flag to indicate whether to use FP16 half-precision for TensorRT profiling.
    trt (bool): Flag to indicate whether to profile using TensorRT.
    device (torch.device): Device used for profiling.

Methods:
    run: Profile YOLO models for speed and accuracy across various formats.
    get_files: Get all relevant model files.
    get_onnx_model_info: Extract metadata from an ONNX model.
    iterative_sigma_clipping: Apply sigma clipping to remove outliers.
    profile_tensorrt_model: Profile a TensorRT model.
    profile_onnx_model: Profile an ONNX model.
    generate_table_row: Generate a table row with model metrics.
    generate_results_dict: Generate a dictionary of profiling results.
    print_table: Print a formatted table of results.

Examples:
    Profile models and print results
    >>> from ultralytics.utils.benchmarks import ProfileModels
    >>> profiler = ProfileModels(["yolo11n.yaml", "yolov8s.yaml"], imgsz=640)
    >>> profiler.run()
Nc	                    Xl         X l        X0l        X@l        XPl        X`l        Xpl        [        U[        R                  5      (       a  Xl	        g[        U5      U l	        g)a  
Initialize the ProfileModels class for profiling models.

Args:
    paths (list[str]): List of paths of the models to be profiled.
    num_timed_runs (int): Number of timed runs for the profiling.
    num_warmup_runs (int): Number of warmup runs before the actual profiling starts.
    min_time (float): Minimum time in seconds for profiling a model.
    imgsz (int): Size of the image used during profiling.
    half (bool): Flag to indicate whether to use FP16 half-precision for TensorRT profiling.
    trt (bool): Flag to indicate whether to profile using TensorRT.
    device (torch.device | str | None): Device used for profiling. If None, it is determined automatically.

Notes:
    FP16 'half' argument option removed for ONNX as slower on CPU than FP32.

Examples:
    Initialize and profile models
    >>> from ultralytics.utils.benchmarks import ProfileModels
    >>> profiler = ProfileModels(["yolo11n.yaml", "yolov8s.yaml"], imgsz=640)
    >>> profiler.run()
N)pathsnum_timed_runsnum_warmup_runsmin_timer9   r;   trtrb   torchr>   r   )	r   r  r  r  r  r9   r;   r  r>   s	            r^   r   ProfileModels.__init__  sK    B 
,. 
	 *65<< @ @fmTZF[r   c           	        U R                  5       nU(       d  [        R                  " S5        / $ / n/ nU GH  nUR                  S5      nUR                  S;   a  [        [        U5      5      nUR                  5         UR                  5       nU R                  (       a`  U R                  R                  S:w  aF  UR                  5       (       d1  UR                  SU R                  U R                  U R                  SS9nUR                  SU R                  U R                  SS	9nO'UR                  S
:X  a  U R!                  U5      nUnOGM  U R#                  [        U5      5      n	U R%                  [        U5      5      n
UR'                  U R)                  UR*                  XU5      5        UR'                  U R-                  UR*                  XU5      5        GM     U R/                  U5        U$ )a  
Profile YOLO models for speed and accuracy across various formats including ONNX and TensorRT.

Returns:
    (list[dict]): List of dictionaries containing profiling results for each model.

Examples:
    Profile models and print results
    >>> from ultralytics.utils.benchmarks import ProfileModels
    >>> profiler = ProfileModels(["yolo11n.yaml", "yolov8s.yaml"])
    >>> results = profiler.run()
z'No matching *.pt or *.onnx files found.z.engine   .pt.yml.yamlr   engineF)r:   r;   r9   r>   r%   onnx)r:   r9   r>   r%   z.onnx)	get_filesr   warningwith_suffixr   r   rl   fuser   r  r>   ru   is_filery   r;   r9   get_onnx_model_infoprofile_tensorrt_modelprofile_onnx_modelr   generate_table_rowstemgenerate_results_dictprint_table)r   files
table_rowsoutputr   engine_filern   
model_info	onnx_filet_enginet_onnxs              r^   runProfileModels.run  s     NNDEI
D**95K{{66SY

"ZZ\
88 0 0E 9+BUBUBWBW"',,'!YY"jj#{{ % #/ #K "LL!**;;!	 ) 	 '!55d;
 	223{3CDH,,S^<Fd55diiS]^_MM$44TYYR\]^; > 	$r   c                h   / nU R                    H  n[        U5      nUR                  5       (       aR  / SQnUR                  U VVs/ s H-  n[        R                  " [        X$-  5      5        H  oUPM     M/     snn5        Mu  UR                  S;   a  UR                  [        U5      5        M  UR                  [        R                  " [        U5      5      5        M     [        R                  " S[        U5       35        [        U5       Vs/ s H  n[        U5      PM     sn$ s  snnf s  snf )z
Return a list of paths for all relevant model files given by the user.

Returns:
    (list[Path]): List of Path objects for the model files.
)z*.ptz*.onnxz*.yamlr  zProfiling: )r  r   is_dirr   globrl   r   r   r   r   sorted)r   r,  r   
extensionsextr   s         r^   r   ProfileModels.get_files  s     JJD:D{{}}9
j`jsTYYsSWS]E_TdE_dj`a 88SY'TYYs4y12  	k&-12'-e}5}tT
}55 a 6s   4D)D/c                    g)zWExtract metadata from an ONNX model file including parameters, GFLOPs, and input shape.)r   r   r   r   ra   )r1  s    r^   r%  !ProfileModels.get_onnx_model_info  s     "r   c                   [         R                  " U 5      n [        U5       Ha  n[         R                  " U 5      [         R                  " U 5      pTX XAU-  -
  :  XX-  -   :  -     n[        U5      [        U 5      :X  a    U $ Un Mc     U $ )aD  
Apply iterative sigma clipping to data to remove outliers.

Args:
    data (np.ndarray): Input data array.
    sigma (float): Number of standard deviations to use for clipping.
    max_iters (int): Maximum number of iterations for the clipping process.

Returns:
    (np.ndarray): Clipped data array with outliers removed.
)rY   arrayrangemeanstdr   )r=   sigma	max_itersr   rB  rC  clipped_datas          r^   iterative_sigma_clipping&ProfileModels.iterative_sigma_clipping  s     xx~y!Arvvd|#s{(:!:tU[FX?X YZL< CI-  D " r   c                   U R                   (       a  [        U5      R                  5       (       d  g[        U5      n[        R
                  " U R                  U R                  S4[        R                  S9nSn[        S5       H]  n[        R                  " 5       n[        U R                  5       H  nU" X@R                  SS9  M     [        R                  " 5       U-
  nM_     [        [        U R                  XR-   -  U R                  -  5      U R                  S-  5      n/ n	[        [        U5      US9 H5  nU" X@R                  SS9n
U	R!                  U
S	   R"                  S
   5        M7     U R%                  [        R&                  " U	5      SSS9n	[        R(                  " U	5      [        R*                  " U	5      4$ )av  
Profile YOLO model performance with TensorRT, measuring average run time and standard deviation.

Args:
    engine_file (str): Path to the TensorRT engine file.
    eps (float): Small epsilon value to prevent division by zero.

Returns:
    mean_time (float): Mean inference time in milliseconds.
    std_time (float): Standard deviation of inference time in milliseconds.
)r   r   r   )dtyper   F)r9   r%   2   descr   rE   rG   rD  rE  )r  r   r$  r   rY   zerosr9   uint8rA  ro   r  maxr   r  r  r   r   r   rG  r@  rB  rC  )r   r/  r   rn   
input_dataelapsedr   
start_timenum_runs	run_timesr   s              r^   r&  $ProfileModels.profile_tensorrt_model#  sb    xxtK088:: [!XXtzz4::q9J
 qAJ4//0j

EB 1iikJ.G	  uT]]gm<t?S?SSTVZViVilnVno 	eHoK8AJjj%HGWQZ--k:; 9 11"((92EQZ[1\	wwy!266)#444r   c                0    [        S U  5       5      (       + $ )z<Check whether the tensor shape in the ONNX model is dynamic.c              3  Z   #    U  H!  n[        U[        5      =(       a    US :  v   M#     g7f)r   N)rb   r  )r[   dims     r^   r_   .ProfileModels.check_dynamic.<locals>.<genexpr>M  s#     QLSz#s+8q8Ls   )+)r   )tensor_shapes    r^   check_dynamicProfileModels.check_dynamicJ  s     QLQQQQr   c                R   [        S/5        SSKnUR                  5       nUR                  R                  Ul        SUl        UR                  XS/S9n[        5       nUR                  5        GH  nUR                  nU R                  UR                  5      (       a  [        UR                  5      S:w  aH  U R                  UR                  SS 5      (       a%  [        S	UR                   S
UR                   35      e[        UR                  5      S:X  a  SSU R                   U R                   4OS/UR                  SS Q7n	OUR                  n	SU;   a  ["        R$                  n
OjSU;   a  ["        R&                  n
OSSU;   a  ["        R(                  n
O<SU;   a  ["        R*                  n
O%SU;   a  ["        R,                  n
O[        SU 35      e["        R.                  R0                  " U	6 R3                  U
5      nUR                  nUR5                  X05        GM     UR7                  5       S   R                  nSn[9        S5       H_  n[:        R:                  " 5       n[9        U R<                  5       H  nUR?                  U/U5        M     [:        R:                  " 5       U-
  nMa     [A        [C        U RD                  X-   -  U R<                  -  5      U RF                  5      n/ n[I        [9        U5      US9 HU  n[:        R:                  " 5       nUR?                  U/U5        URK                  [:        R:                  " 5       U-
  S-  5        MW     U RM                  ["        RN                  " U5      SSS9n["        RP                  " U5      ["        RR                  " U5      4$ )as  
Profile an ONNX model, measuring average inference time and standard deviation across multiple runs.

Args:
    onnx_file (str): Path to the ONNX model file.
    eps (float): Small epsilon value to prevent division by zero.

Returns:
    mean_time (float): Mean inference time in milliseconds.
    std_time (float): Standard deviation of inference time in milliseconds.
)onnxruntimezonnxruntime-gpur   N   CPUExecutionProvider)	providersrH   r"   zUnsupported dynamic shape z of r   float16r   doubleint64int32zUnsupported ONNX datatype r   rL  rF   rG   r   rN  )*r   r`  SessionOptionsGraphOptimizationLevelORT_ENABLE_ALLgraph_optimization_levelintra_op_num_threadsInferenceSessiondict
get_inputsru   r]  shaper   
ValueErrorr   r9   rY   rd  float32float64rf  rg  randomrandastypeupdateget_outputsrA  ro   r  r4  rQ  r   r  r  r   r   rG  r@  rB  rC  )r   r1  r   ortsess_optionssessinput_data_dictinput_tensor
input_typeinput_shapeinput_dtyperR  
input_nameoutput_namerS  r   rT  rU  rV  s                      r^   r'   ProfileModels.profile_onnx_modelO  s    	>?@! ))+030J0J0Y0Y-,-)##IH^G_#`& OO-L%**J!!,"4"455|))*a/D4F4F|GYGYZ[Z\G]4^4^$'A,BTBTAUUYZfZkZkYl%mnn69,:L:L6MQR6RQ4::tzz2YZXt]i]o]opqpr]sXt  +00 J& jjJ& jjZ' jjJ& hhJ& hh #=j\!JKK5<<[IJ%**J""J#;<7 .: &&(+00 qAJ4//0+8 1iikJ.G	  uT]]gm<t?S?SSTVZViVij 	eHoI6AJHHk]O4diikJ6$>? 7
 11"((92EQZ[1\	wwy!266)#444r   c                    Uu  pVpxSUS SU R                    SUS   S SUS   S S	US   S SUS   S S	US
-  S SUS S3$ )a  
Generate a table row string with model performance metrics.

Args:
    model_name (str): Name of the model.
    t_onnx (tuple): ONNX model inference time statistics (mean, std).
    t_engine (tuple): TensorRT engine inference time statistics (mean, std).
    model_info (tuple): Model information (layers, params, gradients, flops).

Returns:
    (str): Formatted table row string with model metrics.
z| 18sz | z | - | r   z.1f   ±r"   z ms | g    .Az |)r9   )	r   rx   r3  r2  r0  layersparams	gradientsflopss	            r^   r(   ProfileModels.generate_table_row  s~    & ,6(	C DJJ<wvayoRq	RUV\]efg]hil\mmo{3vfsl3%7s5+RI	
r   c                d    Uu  pEpgU U[        US5      [        US   S5      [        US   S5      S.$ )a}  
Generate a dictionary of profiling results.

Args:
    model_name (str): Name of the model.
    t_onnx (tuple): ONNX model inference time statistics (mean, std).
    t_engine (tuple): TensorRT engine inference time statistics (mean, std).
    model_info (tuple): Model information (layers, params, gradients, flops).

Returns:
    (dict): Dictionary containing profiling results.
r   r   )z
model/namezmodel/parameterszmodel/GFLOPszmodel/speed_ONNX(ms)zmodel/speed_TensorRT(ms))r   )rx   r3  r2  r0  r  r  r  r  s           r^   r*  #ProfileModels.generate_results_dict  sC    & ,6(	$ &!%O$)&)Q$7(-hqk1(=
 	
r   c                   [         R                  R                  5       (       a  [         R                  R                  S5      OSnSSSS[	        5        S3SU S	3S
S/nSSR                  S U 5       5      -   S-   nSSR                  S U 5       5      -   S-   n[        R                  " SU 35        [        R                  " U5        U  H  n[        R                  " U5        M     g)z}
Print a formatted table of model profiling results.

Args:
    table_rows (list[str]): List of formatted table row strings.
r   GPUModelzsize<br><sup>(pixels)zmAP<sup>val<br>50-95zSpeed<br><sup>CPU (z) ONNX<br>(ms)zSpeed<br><sup>z TensorRT<br>(ms)zparams<br><sup>(M)zFLOPs<br><sup>(B)|c              3  .   #    U  H  nS U S 3v   M     g7f)rO   Nra   r[   hs     r^   r_   ,ProfileModels.print_table.<locals>.<genexpr>  s     :'Q!A3a's   c              3  D   #    U  H  nS [        U5      S-   -  v   M     g7f)r8   rG   N)r   r  s     r^   r_   r    s     "Gw!3#a&1*#5ws    z

N)r  r7   is_availableget_device_namer   joinr   r   )r-  r   headersheader	separatorrL   s         r^   r+  ProfileModels.print_table  s     05zz/F/F/H/Hejj((+e#"!,.!1@SE!23 
 sxx:':::S@#(("Gw"GGG#M	d6(O$ICKK r   )r>   r;   r9   r  r  r  r  r  )d   
   <   i  TTN)r  	list[str]r  r  r  r  r  r   r9   r  r;   boolr  r  r>   ztorch.device | str | None)r1  rl   )rG   r   )r=   z
np.ndarrayrD  r   rE  r  )r   )r/  rl   r   r   )r1  rl   r   r   )rx   rl   r3  tuple[float, float]r2  r  r0  z!tuple[float, float, float, float])r-  r  )r  r	  r
  r  r  r   r4  r   r  r%  rG  r&  r]  r'  r(  r*  r+  r  ra   r   r^   r  r  p  sI   H "!,0(\(\ (\ 	(\
 (\ (\ (\ (\ *(\T5n6* " "  *%5N R RH5T

 $
 &	

 6
2 

#
 &
 6	
 
6  r   r  )2r  
__future__r   r8  r   rz   r   r   ro   pathlibr   numpyrY   
torch.cudar  ultralyticsr   r   ultralytics.cfgr   r   ultralytics.engine.exporterr	   ultralytics.utilsr
   r   r   r   r   r   r   r   r   r   ultralytics.utils.checksr   r   r   r   r   ultralytics.utils.downloadsr   ultralytics.utils.filesr   ultralytics.utils.torch_utilsr   r   r   r   r  ra   r   r^   <module>r     s   8 #  	  	      ' 2 6 q q q m m 5 - E 
$	
		fRO Odv vr   