
    j1                        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/d0d            Z	 	 	 	 	 	 	 	 	 	 	 d1d2d,ZdS )3    )annotationsN)Path)	IS_JETSONLOGGERTORCH_VERSIONThreadingLockedis_dgx	is_jetson)check_tensorrtcheck_version)	TORCH_2_4	TORCH_2_9Fonnxtypes.ModuleTypecudaboolreturnintc                   t           r=t          j        j        j        j        dz
  }t          rt          |d          }|r|dz  }nUd                    t          j
        d          dd                   }ddddd	d
d
d
d
d
dddddd                    |d          }t          || 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   torchr   utils
_constantsONNX_MAX_OPSETr   minjoinr   splitgetdefsonnx_opset_version)r   r   opsetversions       b/var/www/html/Carbon-Document/venv/lib/python3.11/site-packages/ultralytics/utils/export/engine.pybest_onnx_opsetr-      s     
 +:Q> 	#rNNE 	QJE((=.s33BQB788
 
  #gr

! 	" udi2244555    r   modeltorch.nn.Moduleim'torch.Tensor | tuple[torch.Tensor, ...]output_file
Path | strr*   input_nameslist[str] | Noneoutput_namesdynamicdict | Nonestrc           
         |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.
    Nimagesoutput0dynamoFT)verboseopset_versiondo_constant_foldingr5   r7   dynamic_axes)r   r    r   exportr:   )r/   r1   r3   r*   r5   r7   r8   kwargss           r,   
torch2onnxrE   .   s    6 j!{"+3hF	J
  !     {r.   r        rH    	onnx_filePath | str | None	workspace
int | Nonehalfint8shapetuple[int, int, int, int]dlametadatar?   prefixc           
     4   t          d          st                      rt          d           	 ddln"# t          $ r t                       ddlY nw xY wt          j        dd           t          j        d	d
           t          j        d| dj         d           |p!t          |           
                    d          }                    j        j                  }|
rj        j        j        |_                            |          }|                                }t%          pddz            }t%          j                            dd          d                   dk    }|r'|dk    r!|                    j        j        |           n|dk    r||_        dt%          j        j                  z  }|                    |          |j        o|}|j        o|}t:          st=          d          t          j        | d d           |s|st=          d          j        j         |_!        t%                    |_"        |#                    j$        j%                   &                    |          }|'                    |           stQ          d|            fdtS          j*                  D             }fdtS          j+                  D             }|D ]0}t          j        | d|j,         d|j-         d|j.                    1|D ]0}t          j        | d|j,         d|j-         d|j.                    1|r|/                                }d|d         ddf}g |dd         fd |dd         D             R }|D ] }|0                    |j,        |||!           !|1                    |           |r|s|2                    |           t          j        | d"|rd#nd$|rd%nd&z    d'|            |r|#                    j$        j3                   j4        j5        |_6         G fd(d)j7                  } ||tq          t          |           
                    d*                    +          |_9        n!|r|#                    j$        j:                   |r|;                    |          }|tQ          d,          ty          |d-          5 }|	st{          j>        |	          }|?                    t          |          A                    d.d/d0                     |?                    |B                                           |?                    |           ddd           n# 1 swxY w Y   n|C                    |          5 }ty          |d-          5 }|	st{          j>        |	          }|?                    t          |          A                    d.d/d0                     |?                    |B                                           |?                    |D                                           ddd           n# 1 swxY w Y   ddd           n# 1 swxY w Y   tq          |          S )1am  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.2.0z5https://github.com/ultralytics/ultralytics/pull/24367)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: c                :    g | ]}                     |          S  )	get_input.0inetworks     r,   
<listcomp>zonnx2engine.<locals>.<listcomp>   s'    FFFqg""FFFr.   c                :    g | ]}                     |          S r]   )
get_outputr_   s     r,   rc   zonnx2engine.<locals>.<listcomp>   s'    IIIw!!!$$IIIr.   z input "z" with shape z	 output "    r   c              3  \   K   | ]&}t          t          d pd           |z            V  'dS )r   N)r   max)r`   drL   s     r,   	<genexpr>zonnx2engine.<locals>.<genexpr>   s>      "V"Vq3s1in1'='='A#B#B"V"V"V"V"V"Vr.   )r$   optri   z
 building INT8FP1632z engine as c                  N    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	dS )%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.
            rI   cacher:   r   Nonec                    j                             |            || _        t          |          | _        j        j        nj        j        | _        |j	        | _
        t          |          | _        dS )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   rs   )selfrx   rs   rR   trts      r,   rw   z.onnx2engine.<locals>.EngineCalibrator.__init__   sr     #,,T222&!%g  +AA0C 	
 %/
!%[[


r.   trt.CalibrationAlgoTypec                    | j         S )z%Get the calibration algorithm to use.)r~   r   s    r,   get_algorithmz3onnx2engine.<locals>.EngineCalibrator.get_algorithm   s
    y r.   r   c                    | j         pdS )z*Get the batch size to use for calibration.r   )r   r   s    r,   get_batch_sizez4onnx2engine.<locals>.EngineCalibrator.get_batch_size   s    zQ&r.   list[int] | Nonec                    	 t          | j                  d         dz  }|j        j        dk    r|                    d          n|}t          |                                          gS # t          $ r Y dS w xY w)zOGet the next batch to use for calibration, as a list of device memory pointers.imgg     o@cpur   N)nextrz   devicetypetor   data_ptrStopIteration)r   namesim0ss      r,   	get_batchz/onnx2engine.<locals>.EngineCalibrator.get_batch   s}     //6>D.2k.>%.G.G4776???TD0011$      44 s   A%A( (
A65A6bytes | Nonec                    | j                                         r)| j         j        dk    r| j                                         S dS dS )zSUse existing cache instead of calibrating again, otherwise, implicitly return None..cacheN)rs   existssuffix
read_bytesr   s    r,   read_calibration_cachez<onnx2engine.<locals>.EngineCalibrator.read_calibration_cache
  sK    :$$&& 34:+<+H+H:002223 3+H+Hr.   bytesc                :    | j                             |          }dS )z Write calibration cache to disk.N)rs   write_bytes)r   rs   _s      r,   write_calibration_cachez=onnx2engine.<locals>.EngineCalibrator.write_calibration_cache  s    J**511r.   N)rI   )rs   r:   r   rt   )r   r   )r   r   )r   r   )r   r   )rs   r   r   rt   )
__name__
__module____qualname____doc__rw   r   r   r   r   r   )rR   r   s   r,   EngineCalibratorrr      s         .  ) ) ) ) ) ) ) )"! ! ! !' ' ' '       3 3 3 3
2 2 2 2 2 2r.   r   r   )rx   rs   z3TensorRT engine build failed, check logs for errorswb   little)	byteordersigned)Er
   r	   r   tensorrtImportErrorr   __version__r   infor   with_suffixLoggerINFOSeverityVERBOSEmin_severityBuildercreate_builder_configr   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num_outputsnamerP   dtypecreate_optimization_profile	set_shapeadd_optimization_profileset_calibration_profilerm   ProfilingVerbosityDETAILEDprofiling_verbosityrv   r:   int8_calibratorFP16build_serialized_networkopenjsondumpswritelento_bytesencodebuild_engine	serialize) rJ   r3   rL   rN   rO   r8   rP   rR   rx   rS   r?   rT   loggerbuilderconfigworkspace_bytesis_trt10flagparserinputsoutputsinpoutprofile	min_shape	max_shaper   enginetmetarb   r   s      `    `                      @@r,   onnx2enginer   ]   s   X   vxx  w    #/948888#/:3jkkkk
KPVPPCOPPPQQQGi!<!<Y!G!GKZZ
((F :!j19 kk&!!G**,,F9>g677O3?((a00344:H 4Oa''$$S%7%A?SSSS	1		$3!C5DEEED$$T**G)2dD)2dD  	OMNNNv==S===>>> 	D 	 G   &)^%7"c((4555 ^^GV,,F!!),, EC	CCDDD GFFFE'2D,E,EFFFFIIIIeG4G.H.HIIIG V VvTTsxTTSYTTTTUUUU W WvUUUUciUU#)UUVVVV 45577a"b)	WeBQBiW"V"V"V"VERSRTRTI"V"V"VWW	 	Q 	QCchI5iPPPP''000 	4 	4**7333
K6rrt%XVVAWSW9Xrreprrsss L.,---%(%;%D"?	2 ?	2 ?	2 ?	2 ?	2 ?	2 ?	2 ?	2s2 ?	2 ?	2 ?	2D "2!1d9oo11(;;<<"
 "
 "

 
 .,---  (11'6BB>TUUU+t$$ 	#z(++D		**1*NNOOO&&&GGFOOO	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 !!'622 	(fd;PT>U>U 	(YZ#z(++D		**1*NNOOO&&&GGF$$&&'''	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( {sY   8 AA6BVVV/Z  BY)Z )Y-	-Z 0Y-	1Z  ZZ)F)r   r   r   r   r   r   )r   NNN)r/   r0   r1   r2   r3   r4   r*   r   r5   r6   r7   r6   r8   r9   r   r:   )NNFFFrF   NNNFrI   )rJ   r:   r3   rK   rL   rM   rN   r   rO   r   r8   r   rP   rQ   rR   rM   rS   r9   r?   r   rT   r:   r   r:   )
__future__r   r   typespathlibr   r    ultralytics.utilsr   r   r   r   r	   r
   ultralytics.utils.checksr   r   ultralytics.utils.torch_utilsr   r   r-   rE   r   r]   r.   r,   <module>r      sI   # " " " " "          b b b b b b b b b b b b b b b b B B B B B B B B > > > > > > > >6 6 6 6 6< 
 $(%)+ + + + +` &* '7 R R R R R R Rr.   