
    |h'                     J   d dl Z d dlmZ d dlmZmZmZmZmZ d dl	Z	d dl
mZmZ ddgdgdfd	e	j                  j                  d
e	j                  dededee   dee   deeef   ddfdZ	 	 	 	 	 	 	 	 	 	 	 ddedee   dee   dedededeeeeef   dee   dee   dededdfdZy)    N)Path)DictListOptionalTupleUnion)	IS_JETSONLOGGER   imagesoutput0Ftorch_modelim	onnx_fileopsetinput_namesoutput_namesdynamicreturnc                 \    t         j                  j                  | ||d|d|||xs d	       y)ah  
    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.
    FTN)verboseopset_versiondo_constant_foldingr   r   dynamic_axes)torchonnxexport)r   r   r   r   r   r   r   s          W/var/www/html/test/engine/venv/lib/python3.12/site-packages/ultralytics/utils/export.pyexport_onnxr      s:    0 
JJ
 !_  
    engine_file	workspacehalfint8shapedlametadatar   prefixc           
      
    ddl  |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         j"                  j$                        z  }|j'                  |      }|j(                  xr |}|j*                  xr |}t,        st/        d      t1        j2                  | d	 d
       |s|st/        d       j4                  j6                  |_        t              |_        |j=                   j>                  j@                          jC                  ||      }|jE                  |       stG        d|        tI        |jJ                        D cg c]  }|jM                  |       }}tI        |jN                        D cg c]  }|jQ                  |       }}|D ]@  }t1        j2                  | d|jR                   d|jT                   d|jV                          B |D ]@  }t1        j2                  | d|jR                   d|jT                   d|jV                          B |r|d   dk  rt1        jX                  | d       |j[                         }d|d   ddf}g |dd fd|dd D        }|D ]!  }|j]                  |jR                  |||       # |j_                  |       |r|ja                  |       t1        j2                  | d|rdnd|rdndz    d|        |r|j=                   j>                  jb                          jd                  jf                  |_4         G  fdd jj                        } ||tm        t        |       j                  d                  |_7        n'|r%|j=                   j>                  jp                         |r|jr                  n|jt                  } |||      5 }tw        |d       5 }|	`ty        jz                  |	      }|j}                  t        |      j                  d!d"d#$             |j}                  |j                                |j}                  |r|n|j                                ddd       ddd       yc c}w c c}w # 1 sw Y   xY w# 1 sw Y   yxY w)%a8  
    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   @.   
   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 "z> 'dynamic=True' model requires max batch size, i.e. 'batch=16'       c              3   V   K   | ]   }t        t        d xs d       |z         " yw)r/   N)intmax).0dr"   s     r   	<genexpr>z export_engine.<locals>.<genexpr>   s&     "Vq3s1in1'='A#B"Vs   &))minoptr2   z
 building INT8FP1632z engine as c                       e Zd ZdZ	 ddeddf fdZdW j                  fdZdefdZ	de
ee      fdZde
e   fd	Zdeddfd
Zy)'export_engine.<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.
            cacher   Nc                    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   r>   )selfrB   r>   r&   trts      r   rA   z0export_engine.<locals>.EngineCalibrator.__init__   ss     ##,,T2&!%g  ++AA00CC 	
 %//
!%[
r    c                     | j                   S )z%Get the calibration algorithm to use.)rH   rK   s    r   get_algorithmz5export_engine.<locals>.EngineCalibrator.get_algorithm   s    yy r    c                 "    | j                   xs dS )z*Get the batch size to use for calibration.r+   )rJ   rN   s    r   get_batch_sizez6export_engine.<locals>.EngineCalibrator.get_batch_size   s    zz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@cpucudaN)nextrD   devicetypetor1   data_ptrStopIteration)rK   namesim0ss      r   	get_batchz1export_engine.<locals>.EngineCalibrator.get_batch   se     /6>D.2kk.>.>%.G4776?TD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_bytesrN   s    r   read_calibration_cachez>export_engine.<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)rK   r>   _s      r   write_calibration_cachez?export_engine.<locals>.EngineCalibrator.write_calibration_cache   s    JJ**51r    ) )__name__
__module____qualname____doc__strrA   rE   rO   r1   rQ   r   r   r^   bytesrd   rh   )r&   rL   s   r   EngineCalibratorr=      s|    0  ) ) 	)"!s'>'> !' ' (49*=  3 3
2U 2t 2r    rp   r`   )rB   r>   wb   littleT)	byteordersigned)Ctensorrtr   with_suffixLoggerINFOSeverityVERBOSEmin_severityBuildercreate_builder_configr1   __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namer%   dtypewarningcreate_optimization_profile	set_shapeadd_optimization_profileset_calibration_profiler8   ProfilingVerbosityDETAILEDprofiling_verbosityr@   rn   int8_calibratorFP16build_serialized_networkbuild_engineopenjsondumpswritelento_bytesencode	serialize)!r   r!   r"   r#   r$   r   r%   r&   rB   r'   r   r(   loggerbuilderconfigis_trt10flagnetworkparseriinputsoutputsinpoutprofile	min_shape	max_shaperp   buildenginetmetarL   s!     `    `                        @r   export_enginer   1   s   P Gi!<!<Y!GKZZ

(F!jj1199 kk&!G**,FY^!01I3??((a034:HIM$$S%7%7%A%A9M	Q$-!C55DDEED$$T*G))2dD))2dD MNNvh4SE=>D G  &)^^%7%7"c(445 ^^GV,F!!),7	{CDD -2'2D2D,EFqg"FFF.3G4G4G.HIw!!!$IGI VvhhsxxjSYYKqTUV Wvhizcii[#))UVW 8q=NNfX%cde557a"b)	WeBQiW"VERSRTI"VW	 	QCchhI5iP	Q''0**73
KK6(*tVSW9X$YYdepdqrs,,-%(%;%;%D%D"@	2s22 @	2F "2d9o11(;<"

 
,,- 19G,,g>R>RE	w	 <64T+B <a::h'DGGCI&&qHT&JKGGDKKM"	((8(8(:;< < <K GIH< < < <s1   2U#UU,BU2UU	UU")NNFFF)r+        r   NNNFri   )r   pathlibr   typingr   r   r   r   r   r   ultralytics.utilsr	   r
   nnModuleTensorrn   r1   boolr   r    r    r   <module>r      sa     5 5  / &Z(k!&""" " 	"
 c" s)" 4:" 
"N "&#'7#}<}<#}< }}< 	}<
 }< }< c3#$}< 
#}< tn}< }< }< 
}<r    