Ë
    Fêñiò1  ã                  ó  — d dl mZ d dlZd dlZd dlmZ d dlZd dlmZm	Z	m
Z
mZmZmZ d dlmZmZ d dlmZmZ d
dd„Z e«       	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd„«       Z	 	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd	„Zy)é    )ÚannotationsN)ÚPath)Ú	IS_JETSONÚLOGGERÚTORCH_VERSIONÚThreadingLockedÚis_dgxÚ	is_jetson)Úcheck_tensorrtÚcheck_version)Ú	TORCH_2_4Ú	TORCH_2_9c                ó~  — t         rKt        j                  j                  j                  j
                  dz
  }t        rt        |d«      }|rO|dz  }nIdj                  t        j                  d«      dd «      }ddddd	d
d
d
d
d
ddddddœj                  |d«      }t        || j                  j                  «       «      S )z@Return max ONNX opset for this torch version with ONNX fallback.é   é   é   ú.Né   é   é   é   é   é   )z1.8z1.9z1.10z1.11z1.12z1.13z2.0z2.1z2.2z2.3z2.4z2.5z2.6z2.7z2.8)r   ÚtorchÚonnxÚutilsÚ
_constantsÚONNX_MAX_OPSETr   ÚminÚjoinr   ÚsplitÚgetÚdefsÚonnx_opset_version)r   ÚcudaÚopsetÚversions       úa/var/www/pod-logistic/pod-ai/venv/lib/python3.12/site-packages/ultralytics/utils/export/engine.pyÚbest_onnx_opsetr)      sÀ   € åÜ—
‘
× Ñ ×+Ñ+×:Ñ:¸QÑ>ˆÝÜ˜˜r“NˆEÙØ�Q‰J‰Eà—(‘(œ=×.Ñ.¨sÓ3°B°QÐ7Ó8ˆàØØØØØØØØØØØØØØñ
÷  ‰#ˆg�rÓ
ð! 	ô" ˆu�d—i‘i×2Ñ2Ó4Ó5Ð5ó    c           
     ó–   — |€dg}|€dg}t         rddini }t        j                  j                  | ||fd|d|||dœ|¤Ž t	        |«      S )a  Export a PyTorch model to ONNX format.

    Args:
        model (torch.nn.Module): The PyTorch model to export.
        im (torch.Tensor | tuple[torch.Tensor, ...]): Example input tensor(s) for tracing.
        output_file (Path | str): Path to save the exported ONNX file.
        opset (int): ONNX opset version to use for export.
        input_names (list[str] | None): List of input tensor names. Defaults to ``["images"]``.
        output_names (list[str] | None): List of output tensor names. Defaults to ``["output0"]``.
        dynamic (dict | None): Dictionary specifying dynamic axes for inputs and outputs.

    Returns:
        (str): Path to the exported ONNX file.

    Notes:
        Setting `do_constant_folding=True` may cause issues with DNN inference for torch>=1.12.
    ÚimagesÚoutput0ÚdynamoFT)ÚverboseÚopset_versionÚdo_constant_foldingÚinput_namesÚoutput_namesÚdynamic_axes)r   r   r   ÚexportÚstr)ÚmodelÚimÚoutput_filer&   r2   r3   ÚdynamicÚkwargss           r(   Ú
torch2onnxr<   .   sw   € ð6 ÐØ�jˆØÐØ!�{ˆÝ"+ˆh˜Ñ°€FÜ	‡J�J×ÑØØ
Øðð ØØ ØØ!Øñð òô ˆ{ÓÐr*   c           
     óL  ‡‡‡ — t        d¬«      s
t        «       rt        d«       	 ddlŠ t        ‰ j                  dd¬«       t        ‰ j                  d	d
¬«       t        j                  d|› d‰ j                  › d�«       |xs t        | «      j                  d«      }‰ j                  ‰ j                  j                  «      }|
r%‰ j                  j                  j                  |_        ‰ j!                  |«      }|j#                  «       }t%        ‰xs ddz  «      }t%        ‰ j                  j'                  dd«      d   «      dk\  }|r,|dkD  r'|j)                  ‰ j*                  j,                  |«       n|dkD  r||_        dt%        ‰ j0                  j2                  «      z  }|j5                  |«      }|j6                  xr |}|j8                  xr |}‰�‹t:        st=        d«      ‚t        j                  |› d‰› d�«       |s|st=        d«      ‚‰ j>                  j@                  |_!        t%        ‰«      |_"        |jG                  ‰ jH                  jJ                  «       ‰ jM                  ||«      }|jO                  | «      stQ        d| › �«      ‚tS        |jT                  «      D �cg c]  }|jW                  |«      ‘Œ }}tS        |jX                  «      D �cg c]  }|j[                  |«      ‘Œ }}|D ]@  }t        j                  |› d|j\                  › d|j^                  › d|j`                  › �«       ŒB |D ]@  }t        j                  |› d|j\                  › d|j^                  › d|j`                  › �«       ŒB |r{|jc                  «       }d|d   ddf}g |dd ¢ˆfd„|dd D «       ¢­}|D ]!  }|je                  |j\                  |||¬«       Œ# |jg                  |«       |r|s|ji                  |«       t        j                  |› d |rd!nd"|rd#nd$z   › d%|› �«       |r‰|jG                  ‰ jH                  jj                  «       ‰ jl                  jn                  |_8         G ˆˆ fd&„d'‰ jr                  «      } ||tu        t        | «      j                  d(«      «      ¬)«      |_;        n'|r%|jG                  ‰ jH                  jx                  «       |r²|j{                  ||«      }|€tQ        d*«      ‚t}        |d+«      5 }|	�`t        j€                  |	«      }|jƒ                  t…        |«      j‡                  d,d-d¬.«      «       |jƒ                  |j‰                  «       «       |jƒ                  |«       ddd«       tu        |«      S |j‹                  ||«      5 }t}        |d+«      5 }|	�`t        j€                  |	«      }|jƒ                  t…        |«      j‡                  d,d-d¬.«      «       |jƒ                  |j‰                  «       «       |jƒ                  |j�                  «       «       ddd«       ddd«       tu        |«      S # t        $ r t        «        ddlŠ Y �Œ6w xY wc c}w c c}w # 1 sw Y   tu        |«      S xY w# 1 sw Y   ŒZxY w# 1 sw Y   tu        |«      S xY w)/am  Export a YOLO model to TensorRT engine format.

    Args:
        onnx_file (str): Path to the ONNX file to be converted.
        output_file (Path | str | None): Path to save the generated TensorRT engine file.
        workspace (int | None): Workspace size in GB for TensorRT.
        half (bool, optional): Enable FP16 precision.
        int8 (bool, optional): Enable INT8 precision.
        dynamic (bool, optional): Enable dynamic input shapes.
        shape (tuple[int, int, int, int], optional): Input shape (batch, channels, height, width).
        dla (int | None): DLA core to use (Jetson devices only).
        dataset (ultralytics.data.build.InfiniteDataLoader, optional): Dataset for INT8 calibration.
        metadata (dict | None): Metadata to include in the engine file.
        verbose (bool, optional): Enable verbose logging.
        prefix (str, optional): Prefix for log messages.

    Returns:
        (str): Path to the exported engine file.

    Raises:
        ValueError: If DLA is enabled on non-Jetson devices or required precision is not set.
        RuntimeError: If the ONNX file cannot be parsed.

    Notes:
        TensorRT version compatibility is handled for workspace size and engine building.
        INT8 calibration requires a dataset and generates a calibration cache.
        Metadata is serialized and written to the engine file if provided.
    é   )Újetpackz10.15r   Nz>=7.0.0T)Úhardz!=10.1.0z5https://github.com/ultralytics/ultralytics/pull/14239)Úmsgú
z starting export with TensorRT z...z.enginei   @r   r   é
   z.DLA is only available on NVIDIA Jetson devicesz enabling DLA on core ztDLA requires either 'half=True' (FP16) or 'int8=True' (INT8) to be enabled. Please enable one of them and try again.zfailed to load ONNX file: z input "z" with shapeú z	 output "é    r   c              3  óV   •K  — | ]   }t        t        d ‰xs d «      |z  «      –— Œ" y­w)r   N)ÚintÚmax)Ú.0ÚdÚ	workspaces     €r(   ú	<genexpr>zonnx2engine.<locals>.<genexpr>Æ   s&   øè ø€ Ò"VÀq¤3¤s¨1¨iªn¸1Ó'=ÀÑ'A×#BÑ"Vùs   ƒ&))r   ÚoptrH   z
 building ÚINT8ÚFPÚ16Ú32z engine as c                  óR   •— e Zd ZdZ	 d		 	 	 d
ˆ ˆfd„Zdd„Zdd„Zdd„Zdd„Zdd„Z	y)ú%onnx2engine.<locals>.EngineCalibratora  Custom INT8 calibrator for TensorRT engine optimization.

            This calibrator provides the necessary interface for TensorRT to perform INT8 quantization calibration using
            a dataset. It handles batch generation, caching, and calibration algorithm selection.

            Attributes:
                dataset: Dataset for calibration.
                data_iter: Iterator over the calibration dataset.
                algo (trt.CalibrationAlgoType): Calibration algorithm type.
                batch (int): Batch size for calibration.
                cache (Path): Path to save the calibration cache.

            Methods:
                get_algorithm: Get the calibration algorithm to use.
                get_batch_size: Get the batch size to use for calibration.
                get_batch: Get the next batch to use for calibration.
                read_calibration_cache: Use existing cache instead of calibrating again.
                write_calibration_cache: Write calibration cache to disk.
            c                ó  •— ‰j                   j                  | «       || _        t        |«      | _        ‰�‰j
                  j                  n‰j
                  j                  | _        |j                  | _
        t        |«      | _        y)z;Initialize the INT8 calibrator with dataset and cache path.N)ÚIInt8CalibratorÚ__init__ÚdatasetÚiterÚ	data_iterÚCalibrationAlgoTypeÚENTROPY_CALIBRATION_2ÚMINMAX_CALIBRATIONÚalgoÚ
batch_sizeÚbatchr   Úcache)ÚselfrW   r`   ÚdlaÚtrts      €€r(   rV   z.onnx2engine.<locals>.EngineCalibrator.__init__ç   ss   ø€ ð ×#Ñ#×,Ñ,¨TÔ2Ø&�”Ü!% g£�”ð �ð ×+Ñ+×AÒAà×0Ñ0×CÑCð ”	ð
 %×/Ñ/�”
Ü! %›[�•
r*   c                ó   — | j                   S )z%Get the calibration algorithm to use.)r]   ©ra   s    r(   Úget_algorithmz3onnx2engine.<locals>.EngineCalibrator.get_algorithmø   s   € à—y‘yÐ r*   c                ó"   — | j                   xs dS )z*Get the batch size to use for calibration.r   )r_   re   s    r(   Úget_batch_sizez4onnx2engine.<locals>.EngineCalibrator.get_batch_sizeü   s   € à—z‘z’ QÐ&r*   c                óä   — 	 t        | j                  «      d   dz  }|j                  j                  dk(  r|j	                  d«      n|}t        |j                  «       «      gS # t        $ r Y yw xY w)zOGet the next batch to use for calibration, as a list of device memory pointers.Úimgg     ào@Úcpur%   N)ÚnextrY   ÚdeviceÚtypeÚtorG   Údata_ptrÚStopIteration)ra   ÚnamesÚim0ss      r(   Ú	get_batchz/onnx2engine.<locals>.EngineCalibrator.get_batch   se   € ð Ü §¡Ó/°Ñ6¸Ñ>�DØ.2¯k©k×.>Ñ.>À%Ò.G˜4Ÿ7™7 6œ?ÈT�DÜ §¡£Ó0Ð1Ð1øÜ$ò  áð ús   ‚A A# Á#	A/Á.A/c                ó    — | j                   j                  «       r4| j                   j                  dk(  r| j                   j                  «       S yy)zSUse existing cache instead of calibrating again, otherwise, implicitly return None.ú.cacheN)r`   ÚexistsÚsuffixÚ
read_bytesre   s    r(   Úread_calibration_cachez<onnx2engine.<locals>.EngineCalibrator.read_calibration_cache
  s?   € à—:‘:×$Ñ$Ô&¨4¯:©:×+<Ñ+<ÀÒ+HØŸ:™:×0Ñ0Ó2Ð2ð ,IÐ&r*   c                ó:   — | j                   j                  |«      }y)z Write calibration cache to disk.N)r`   Úwrite_bytes)ra   r`   Ú_s      r(   Úwrite_calibration_cachez=onnx2engine.<locals>.EngineCalibrator.write_calibration_cache  s   € à—J‘J×*Ñ*¨5Ó1‘r*   N)Ú )r`   r6   ÚreturnÚNone)r€   ztrt.CalibrationAlgoType)r€   rG   )r€   zlist[int] | None)r€   zbytes | None)r`   Úbytesr€   r�   )
Ú__name__Ú
__module__Ú__qualname__Ú__doc__rV   rf   rh   rt   rz   r~   )rb   rc   s   €€r(   ÚEngineCalibratorrS   Ò   s?   ø„ ñð.  ð)ð ð)ð ö	)ó"!ó'ó ó3ô
2r*   r‡   rv   )rW   r`   z3TensorRT engine build failed, check logs for errorsÚwbé   Úlittle)Ú	byteorderÚsigned)Gr
   r	   r   ÚtensorrtÚImportErrorr   Ú__version__r   Úinfor   Úwith_suffixÚLoggerÚINFOÚSeverityÚVERBOSEÚmin_severityÚBuilderÚcreate_builder_configrG   r!   Úset_memory_pool_limitÚMemoryPoolTypeÚ	WORKSPACEÚmax_workspace_sizeÚNetworkDefinitionCreationFlagÚEXPLICIT_BATCHÚcreate_networkÚplatform_has_fast_fp16Úplatform_has_fast_int8r   Ú
ValueErrorÚ
DeviceTypeÚDLAÚdefault_device_typeÚDLA_coreÚset_flagÚBuilderFlagÚGPU_FALLBACKÚ
OnnxParserÚparse_from_fileÚRuntimeErrorÚrangeÚ
num_inputsÚ	get_inputÚnum_outputsÚ
get_outputÚnameÚshapeÚdtypeÚcreate_optimization_profileÚ	set_shapeÚadd_optimization_profileÚset_calibration_profilerN   ÚProfilingVerbosityÚDETAILEDÚprofiling_verbosityrU   r6   Úint8_calibratorÚFP16Úbuild_serialized_networkÚopenÚjsonÚdumpsÚwriteÚlenÚto_bytesÚencodeÚbuild_engineÚ	serialize)!Ú	onnx_filer9   rK   ÚhalfÚint8r:   r³   rb   rW   Úmetadatar/   ÚprefixÚloggerÚbuilderÚconfigÚworkspace_bytesÚis_trt10ÚflagÚnetworkÚparserÚiÚinputsÚoutputsÚinpÚoutÚprofileÚ	min_shapeÚ	max_shaper‡   ÚengineÚtÚmetarc   s!     `    `                        @r(   Úonnx2enginerà   ]   sæ  ú€ ôX ˜ÕœvœxÜ�wÔðÛô �#—/‘/ 9°4Õ8Ü�#—/‘/ :Ð3jÕkä
‡K�K�"�V�HÐ;¸C¿O¹OÐ;LÈCÐPÔQØÒG¤ i£×!<Ñ!<¸YÓ!G€Kà�Z‰Z˜Ÿ
™
Ÿ™Ó(€FÙØ!Ÿj™j×1Ñ1×9Ñ9ˆÔð �k‰k˜&Ó!€GØ×*Ñ*Ó,€FÜ˜9š>¨¨gÑ6Ó7€OÜ�3—?‘?×(Ñ(¨¨aÓ0°Ñ3Ó4¸Ñ:€HÙ�O aÒ'Ø×$Ñ$ S×%7Ñ%7×%AÑ%AÀ?ÕSØ	˜1Ò	Ø$3ˆÔ!Ø”�C×5Ñ5×DÑDÓEÑE€DØ×$Ñ$ TÓ*€GØ×)Ñ)Ò2¨d€DØ×)Ñ)Ò2¨d€Dð €ÝÜÐMÓNÐNÜ�‰�v�hÐ4°S°E¸Ð=Ô>Ù™DÜð Góð ð &)§^¡^×%7Ñ%7ˆÔ"Ü˜c›(ˆŒØ�‰˜Ÿ™×4Ñ4Ô5ð �^‰^˜G VÓ,€FØ×!Ñ! )Ô,ÜÐ7¸	°{ÐCÓDÐDô -2°'×2DÑ2DÓ,EÖF qˆg×Ñ Õ"ÐF€FÐFÜ.3°G×4GÑ4GÓ.HÖI¨ˆw×!Ñ! !Õ$ÐI€GÐIØò VˆÜ�‰�v�h˜h s§x¡x j°¸S¿Y¹Y¸KÀqÈÏÉÈÐTÕUðVàò WˆÜ�‰�v�h˜i¨¯© z°¸c¿i¹i¸[ÈÈ#Ï)É)ÈÐUÕVðWñ Ø×5Ñ5Ó7ˆØ˜˜a™ " bÐ)ˆ	ØW�e˜B˜Q�iÐWÓ"VÈEÐRSÐRTÈIÔ"VÑWˆ	Øò 	QˆCØ×Ñ˜cŸh™h¨I¸5ÀiÐÕPð	Qà×'Ñ'¨Ô0Ù™Ø×*Ñ*¨7Ô3ä
‡K�K�6�(˜*©t¡V¸ÉÁÐSWÑ9XÐ$YÐYdÐepÐdqÐrÔsÙØ�‰˜Ÿ™×,Ñ,Ô-Ø%(×%;Ñ%;×%DÑ%DˆÔ"÷?	2˜s×2Ñ2ô ?	2ñD "2ØÜ”d˜9“o×1Ñ1°(Ó;Ó<ô"
ˆÕñ
 
Ø�‰˜Ÿ™×,Ñ,Ô-ñ à×1Ñ1°'¸6ÓBˆØˆ>ÜÐTÓUÐUÜ�+˜tÓ$ð 	¨ØÐ#Ü—z‘z (Ó+�Ø—‘œ˜D›	×*Ñ*¨1¸ÈÐ*ÓNÔOØ—‘˜Ÿ™›Ô&Ø�G‰G�FŒO÷	ô ˆ{ÓÐð ×!Ñ! '¨6Ó2ð 	(°f¼dÀ;ÐPTÓ>Uð 	(ÐYZØÐ#Ü—z‘z (Ó+�Ø—‘œ˜D›	×*Ñ*¨1¸ÈÐ*ÓNÔOØ—‘˜Ÿ™›Ô&Ø�G‰G�F×$Ñ$Ó&Ô'÷	(÷ 	(ô ˆ{ÓÐøôC ò ÜÔÞðüò\ GùÚI÷J	ô ˆ{ÓÐú÷	(ð 	(ú÷ 	(ô ˆ{ÓÐúsO   ¦Y Ê*Y$ËY)ÔA4Y.ÖZÖ)BZØ+ZÙY!Ù Y!Ù.ZÚZ	Ú	ZÚZ#)F)r   ztypes.ModuleTyper%   Úboolr€   rG   )r   NNN)r7   ztorch.nn.Moduler8   z'torch.Tensor | tuple[torch.Tensor, ...]r9   z
Path | strr&   rG   r2   úlist[str] | Noner3   râ   r:   údict | Noner€   r6   )NNFFF)r   é   é€  rå   NNNFr   )rÈ   r6   r9   zPath | str | NonerK   ú
int | NonerÉ   rá   rÊ   rá   r:   rá   r³   ztuple[int, int, int, int]rb   ræ   rË   rã   r/   rá   rÌ   r6   r€   r6   )Ú
__future__r   rÀ   ÚtypesÚpathlibr   r   Úultralytics.utilsr   r   r   r   r	   r
   Úultralytics.utils.checksr   r   Úultralytics.utils.torch_utilsr   r   r)   r<   rà   © r*   r(   ú<module>rî      sB  ðõ #ã Û Ý ã ç b× bß Bß >ô6ñ< Óð
 Ø$(Ø%)Øð+Øð+à/ð+ð ð+ð ð	+ð
 "ð+ð #ð+ð ð+ð 	ò+ó ð+ð` &*Ø ØØØØ'7ØØØ ØØðRØðRà"ðRð ðRð ð	Rð
 ðRð ðRð %ðRð 
ðRð ðRð ðRð ðRð 	ôRr*   