
    h''                        S SK Jr  S SKrS SKJr  S SKrS SKJrJr  S SK	J
r
  SSKJr  SS	/S
/S4               SS jjr           S                       SS jjrg)    )annotationsN)Path)	IS_JETSONLOGGER)	TORCH_2_4   )	torch2imx   imagesoutput0Fc           
         [         (       a  SS0O0 n[        R                  R                  " U UU4SUSUUU=(       d    SS.UD6  g)a8  
Export a PyTorch model to ONNX format.

Args:
    torch_model (torch.nn.Module): The PyTorch model to export.
    im (torch.Tensor): Example input tensor for the model.
    onnx_file (str): Path to save the exported ONNX file.
    opset (int): ONNX opset version to use for export.
    input_names (list[str]): List of input tensor names.
    output_names (list[str]): List of output tensor names.
    dynamic (bool | dict, optional): Whether to enable dynamic axes.

Notes:
    Setting `do_constant_folding=True` may cause issues with DNN inference for torch>=1.12.
dynamoFTN)verboseopset_versiondo_constant_foldinginput_namesoutput_namesdynamic_axes)r   torchonnxexport)torch_modelim	onnx_fileopsetr   r   dynamickwargss           [/home/james-whalen/.local/lib/python3.13/site-packages/ultralytics/utils/export/__init__.py
torch2onnxr      sV    0 #,)hF	JJ
  !_     c           
     l  ^^^! SSK m!U=(       d    [        U 5      R                  S5      nT!R                  T!R                  R                  5      nU
(       a%  T!R                  R
                  R                  Ul        T!R                  U5      nUR                  5       n[        T=(       d    SS-  5      n[        T!R                  R                  SS5      S   5      S:  nU(       a-  US:  a'  UR                  T!R                  R                  U5        OUS:  a  Xl        S[        T!R"                  R$                  5      -  nUR'                  U5      nUR(                  =(       a    UnUR*                  =(       a    UnTb  [,        (       d  [/        S5      e[0        R2                  " U S	T S
35        U(       d  U(       d  [/        S5      eT!R4                  R6                  Ul        [        T5      Ul        UR=                  T!R>                  R@                  5        T!RC                  UU5      nURE                  U 5      (       d  [G        SU  35      e[I        URJ                  5       Vs/ s H  nURM                  U5      PM     nn[I        URN                  5       Vs/ s H  nURQ                  U5      PM     nnU HB  n[0        R2                  " U SURR                   SURT                   SURV                   35        MD     U HB  n[0        R2                  " U SURR                   SURT                   SURV                   35        MD     U(       a~  URY                  5       nSUS   SS4n/ USS QU4S jUSS  5       Q7nU H  nUR[                  URR                  UUUS9  M!     UR]                  U5        U(       a  UR_                  U5        [0        R2                  " U SU(       a  SOSU(       a  SOS-    SU 35        U(       a  UR=                  T!R>                  R`                  5        T!Rb                  Rd                  Ul3         " UU!4S jST!Rh                  5      nU" U[k        [        U 5      R                  S5      5      S9Ul6        O,U(       a%  UR=                  T!R>                  Rn                  5        U(       a  URp                  OURr                  nU" UU5       n[u        US5       nU	b^  [v        Rx                  " U	5      n UR{                  [}        U 5      R                  S S!S"S#95        UR{                  U R                  5       5        UR{                  U(       a  UOUR                  5       5        SSS5        SSS5        gs  snf s  snf ! , (       d  f       N!= f! , (       d  f       g= f)$a  
Export a YOLO model to TensorRT engine format.

Args:
    onnx_file (str): Path to the ONNX file to be converted.
    engine_file (str, optional): Path to save the generated TensorRT engine file.
    workspace (int, optional): 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, optional): DLA core to use (Jetson devices only).
    dataset (ultralytics.data.build.InfiniteDataLoader, optional): Dataset for INT8 calibration.
    metadata (dict, optional): Metadata to include in the engine file.
    verbose (bool, optional): Enable verbose logging.
    prefix (str, optional): Prefix for log messages.

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.
r   Nz.enginei   @.r   
   z.DLA is only available on NVIDIA Jetson devicesz enabling DLA on core z...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 "       c              3  f   >#    U  H&  n[        [        S T=(       d    S 5      U-  5      v   M(     g7f)r&   N)intmax).0d	workspaces     r   	<genexpr>onnx2engine.<locals>.<genexpr>   s)     "VIq3s1in1'='A#B#BIs   .1)minoptr)   z
 building INT8FP1632z engine as c                  j   > \ rS rSrSr S   SU U4S jjjrSS jrSS jrSS jrSS jr	SS jr
S	rg
)%onnx2engine.<locals>.EngineCalibrator   aQ  
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                  > TR                   R                  U 5        Xl        [        U5      U l        Tb  TR
                  R                  OTR
                  R                  U l        UR                  U l
        [        U5      U l        g)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)selfr;   rD   dlatrts      r   r:   .onnx2engine.<locals>.EngineCalibrator.__init__   sq     ##,,T2&!%g  ++AA00CC 	
 %//
!%[
r    c                    U R                   $ )z%Get the calibration algorithm to use.)rA   rE   s    r   get_algorithm3onnx2engine.<locals>.EngineCalibrator.get_algorithm   s    yy r    c                ,    U R                   =(       d    S$ )z*Get the batch size to use for calibration.r   )rC   rJ   s    r   get_batch_size4onnx2engine.<locals>.EngineCalibrator.get_batch_size   s    zzQ&r    c                     [        U R                  5      S   S-  nUR                  R                  S:X  a  UR	                  S5      OUn[        UR                  5       5      /$ ! [         a     gf = f)zOGet the next batch to use for calibration, as a list of device memory pointers.imgg     o@cpucudaN)nextr=   devicetypetor(   data_ptrStopIteration)rE   namesim0ss      r   	get_batch/onnx2engine.<locals>.EngineCalibrator.get_batch   se     /6>D.2kk.>.>%.G4776?TD011$   s   A!A$ $
A10A1c                    U R                   R                  5       (       a5  U R                   R                  S:X  a  U R                   R                  5       $ gg)zSUse existing cache instead of calibrating again, otherwise, implicitly return None..cacheN)rD   existssuffix
read_bytesrJ   s    r   read_calibration_cache<onnx2engine.<locals>.EngineCalibrator.read_calibration_cache   sB    ::$$&&4::+<+<+H::0022 ,I&r    c                :    U R                   R                  U5      ng)z Write calibration cache to disk.N)rD   write_bytes)rE   rD   _s      r   write_calibration_cache=onnx2engine.<locals>.EngineCalibrator.write_calibration_cache   s    JJ**51r    )rA   rC   rD   r=   r;   N) )rD   strreturnNone)rl   ztrt.CalibrationAlgoType)rl   r(   )rl   zlist[int] | None)rl   zbytes | None)rD   bytesrl   rm   )__name__
__module____qualname____firstlineno____doc__r:   rK   rN   r\   rc   rh   __static_attributes__)rF   rG   s   r   EngineCalibratorr6      sD    0  ) ) 	) )"!' 3
2r    ru   r_   )r;   rD   wb   littleT)	byteordersigned)Btensorrtr   with_suffixLoggerINFOSeverityVERBOSEmin_severityBuildercreate_builder_configr(   __version__splitset_memory_pool_limitMemoryPoolType	WORKSPACEmax_workspace_sizeNetworkDefinitionCreationFlagEXPLICIT_BATCHcreate_networkplatform_has_fast_fp16platform_has_fast_int8r   
ValueErrorr   info
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_profiler1   ProfilingVerbosityDETAILEDprofiling_verbosityr9   rk   int8_calibratorFP16build_serialized_networkbuild_engineopenjsondumpswritelento_bytesencode	serialize)"r   engine_filer,   halfint8r   r   rF   r;   metadatar   prefixloggerbuilderconfigworkspace_bytesis_trt10flagnetworkparseriinputsoutputsinpoutprofile	min_shape	max_shaperu   buildenginetmetarG   s"     `    `                         @r   onnx2enginer   7   s   P Gi!<!<Y!GKZZ

(F!jj1199 kk&!G**,F9>g67O3??((a034:HOa'$$S%7%7%A%A?S	1	$3!C55DDEED$$T*G))2dD))2dD yMNNvh4SE=>D G  &)^^%7%7"c(445 ^^GV,F!!),,7	{CDD -2'2D2D,EF,Eqg",EFF.3G4G4G.HI.Hw!!!$.HGIvhhsxxjSYYKqTU vhizcii[#))UV  557a"b)	WeBQiW"VERSRTI"VW	CchhI5iP ''0**73
KK6(*tVSW9X$YYdepdqrs,,-%(%;%;%D%D"@	2 @	2s22 @	2F "2d9o11(;<"

 
,,- 19G,,g>R>RE	w	64T+Ba::h'DGGCI&&qHT&JKGGDKKM"	((8(8(:; ,C		G GID ,C+B		s1   'V
V"V%/B
V9V%
V"	V%%
V3)r   ztorch.nn.Moduler   ztorch.Tensorr   rk   r   r(   r   	list[str]r   r   r   zbool | dictrl   rm   )NNFFF)r        r   NNNFrj   )r   rk   r   z
str | Noner,   
int | Noner   boolr   r   r   r   r   ztuple[int, int, int, int]rF   r   r   zdict | Noner   r   r   rk   rl   rm   )
__future__r   r   pathlibr   r   ultralytics.utilsr   r   ultralytics.utils.torch_utilsr   imxr	   r   r    r    r   <module>r      s)   #    / 3  &Z(k $ $$ $ 	$
 $ $ $ 
$R # '7 {<{<{< {< 	{<
 {< {< %{< 
{< {< {< {< 
{<r    