
    j;                       d dl mZ d dlZd dlZd dlZd dlZd dlmZ d dlm	Z	 d dl
Zd dlZd dlmZmZm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 d d	lmZ d d
lm Z  g ddddhdg ddddhdg ej!        dhdg ddddhddg ddddhdg ddd d!hdg ej!        d"hdg d#d$d%d&hddd'Z" G d( d)ej#        j$                  Z%dHd.Z&dId1Z'dJd3Z( G d4 d5ej#        j$                  Z)	 	 	 	 dKdLdGZ*dS )M    )annotationsN)Path)which)DetectPoseSegment)IS_DEBIAN_BOOKWORMIS_DEBIAN_TRIXIEIS_RASPBERRYPI	IS_UBUNTULOGGERWINDOWS)check_apt_requirementscheck_requirements)onnx_export_patch)make_anchors)	copy_attr)submul_2add_14cat_19g~8CA      )layer_namesweights_memoryn_layers)r   r   r   cat_21cat_22mul_4add_15g\EBAi  i  p   )r   r   r   r   gffffBAi	  i
  )detectposeclassifysegment)r   muladd_6cat_15gffffuCA      )add_7r   cat_17r&   r   r'   cat_18gBA      I   )r   r&   r'   r,   g    .CA      )YOLO11YOLOv8c                  *     e Zd ZdZd fd	Zd Z xZS )FXModela  A custom model class for torch.fx compatibility.

    This class extends `torch.nn.Module` and is designed to ensure compatibility with torch.fx for tracing and graph
    manipulation. It copies attributes from an existing model and explicitly sets the model attribute to ensure proper
    copying.

    Attributes:
        model (nn.Module): The original model's layers.
        imgsz (tuple[int, int]): The input image size (height, width).
      r8   c                    t                                                       t          | |           |j        | _        || _        dS )zInitialize the FXModel.

        Args:
            model (nn.Module): The original model to wrap for torch.fx compatibility.
            imgsz (tuple[int, int]): The input image size (height, width). Default is (640, 640).
        N)super__init__r   modelimgsz)selfr<   r=   	__class__s      _/var/www/html/Carbon-Document/venv/lib/python3.11/site-packages/ultralytics/utils/export/imx.pyr;   zFXModel.__init__K   s?     	$[



    c                   g | j         D ]Yj        dk    r;t          j        t                    rj                 nfdj        D             t          t                    rqt          j        t                    _        d t          t          j
        fd| j        D             d          j        d          D             \  _        _        t                    t           u rt          j        t"                    _        t                    t&          u rt          j        t(                    _                                                  [S )aX  Forward pass through the model.

        This method performs the forward pass through the model, handling the dependencies between layers and saving
        intermediate outputs.

        Args:
            x (torch.Tensor): The input tensor to the model.

        Returns:
            (torch.Tensor): The output tensor from the model.
        c                0    g | ]}|d k    rn|         S rC    ).0jxys     r@   
<listcomp>z#FXModel.forward.<locals>.<listcomp>h   s*    8]8]8]TUa2gg1Q48]8]8]rA   c              3  B   K   | ]}|                     d d          V  dS )r      N)	transpose)rG   rI   s     r@   	<genexpr>z"FXModel.forward.<locals>.<genexpr>k   sD       ( ( KK1%%( ( ( ( ( (rA   c                J    g | ]}|j                             d           z   S rE   )stride	unsqueeze)rG   sms     r@   rK   z#FXModel.forward.<locals>.<listcomp>n   s.    "R"R"R!1qx'9'9"'='=#="R"R"RrA   rM   )dimg      ?)r<   f
isinstanceintr   types
MethodType
_inferencer   torchcatr=   rQ   anchorsstridestyper   pose_forwardforwardr   segment_forwardappend)r>   rI   rT   rJ   s    `@@r@   rb   zFXModel.forwardX   s[     	 	Asbyy(c22]AacFF8]8]8]8]8]YZY\8]8]8]!V$$ $/
A>>( ()	"R"R"R"Rtz"R"R"RXYZZZ\]\dfi ( ( ($	19 Aww$!,\1==	Aww'!!!,_a@@	!AHHQKKKKrA   )r7   __name__
__module____qualname____doc__r;   rb   __classcell__r?   s   @r@   r6   r6   ?   sV        	 	           rA   r6   rI   dict[str, torch.Tensor]return!tuple[torch.Tensor, torch.Tensor]c                *   |                      |                     |d                   | j                            d                    | j        z  }|                    dd          |d                                                             ddd          fS )z5Decode boxes and cls scores for imx object detection.boxesr   rM      scores)decode_bboxesdflr^   rR   r_   rN   sigmoidpermute)r>   rI   dboxs      r@   r[   r[   z   s{    dhhqz22DL4J4J14M4MNNQUQ]]D>>!Q8!4!4!6!6!>!>q!Q!G!GGGrA   list[torch.Tensor]/tuple[torch.Tensor, torch.Tensor, torch.Tensor]c                p    d         j         d         t           d j                  t          j         fdt           j                  D             d          }t           d          r~ j         j        k    rn|j         d         }|	                     j
        d          j
        d         dz   |          }|ddddddddf         }|	                     j        |          }t          j                                        |          }g |                    ddd          R S )	zBForward pass for imx pose estimation, including keypoint decoding.r   	nk_outputc                r    g | ]3} j         |         |                                       d           4S rE   )cv4view)rG   ibsnk_outr>   rI   s     r@   rK   z pose_forward.<locals>.<listcomp>   s?    TTT[TXa[1&&++B;;TTTrA   rC   rM   rq   N)shapegetattrnkr\   r]   rangenlhasattrr{   r~   	kpt_shaper   rb   kpts_decoderv   )r>   rI   kptspatialpred_kptr   r   s   ``   @@r@   ra   ra      s9   	
1ABT;00F
)TTTTTTTU47^^TTTVX
Y
YC t[!! -dn&?&?)B-hhr4>!,dnQ.?!.CWMM!!!QQQQQQ,hhr47G,,tQA$$H(A(x1a(((((rA   =tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]c                &                          d                   }|j        d         t          j         fdt	           j                  D             d          }t          j                   g |                    dd          |R S )z"Forward pass for imx segmentation.r   c                |    g | ]8} j         |         |                                       j        d           9S rE   )r}   r~   nm)rG   r   r   r>   rI   s     r@   rK   z#segment_forward.<locals>.<listcomp>   sA    TTTKDHQK!%%**2tw;;TTTrA   rq   rM   )	protor   r\   r]   r   r   r   rb   rN   )r>   rI   pmcr   s   ``  @r@   rc   rc      s    

1Q4A	
B	TTTTTTU47^^TTTVW	X	XBtQA$A$r||Aq!!$1$$$rA   c                  4     e Zd ZdZ	 	 	 	 dd fdZd Z xZS )
NMSWrapperz?Wrap PyTorch Module with multiclass_nms layer from edge-mdt-cl.MbP?ffffff?,  r"   r<   torch.nn.Modulescore_thresholdfloatiou_thresholdmax_detectionsrX   taskstrc                    t                                                       || _        || _        || _        || _        || _        dS )a  Initialize NMSWrapper with PyTorch Module and NMS parameters.

        Args:
            model (torch.nn.Module): Model instance.
            score_threshold (float): Score threshold for non-maximum suppression.
            iou_threshold (float): Intersection over union threshold for non-maximum suppression.
            max_detections (int): The number of detections to return.
            task (str): Task type, one of 'detect', 'pose', or 'segment'.
        N)r:   r;   r<   r   r   r   r   )r>   r<   r   r   r   r   r?   s         r@   r;   zNMSWrapper.__init__   sE    " 	
.*,			rA   c                   ddl m} |                     |          }|d         |d         }} |||| j        | j        | j                  }| j        dk    rs|d         }t          j        |d|j	        
                    d                              dd|                    d                              }|j        |j        |j        |fS | j        dk    r||d         |d	         }
}	t          j        |	d|j	        
                    d                              dd|	                    d                              }|j        |j        |j        ||
fS |j        |j        |j        |j        fS )
z:Forward pass with model inference and NMS post-processing.r   )multiclass_nms_with_indicesrM   )rp   rr   r   r   r   r#   rq   rC   r%      )'edgemdt_cl.pytorch.nms.nms_with_indicesr   r<   r   r   r   r   r\   gatherindicesrR   expandsizerp   rr   labelsn_valid)r>   imagesr   outputsrp   rr   nms_outputskptsout_kptsr   r   out_mcs               r@   rb   zNMSWrapper.forward   s{   WWWWWW **V$$
GAJv11 0,.
 
 
 91:D|D![-@-J-J2-N-N-U-UVXZ\^b^g^ghj^k^k-l-lmmH$k&8+:LhVV9	!!
GAJB\"a)<)F)Fr)J)J)Q)QRTVXZ\ZaZabdZeZe)f)fggF$k&8+:LfV[[[ +"4k6H+J]]]rA   )r   r   r   r"   )
r<   r   r   r   r   r   r   rX   r   r   re   rk   s   @r@   r   r      sl        II
 "'"!      0^ ^ ^ ^ ^ ^ ^rA   r   F r<   r   
output_dir
Path | strconfr   ioumax_detrX   metadatadict | Nonegptqboolprefixr   c	           
     
   	 t          j        ddgdd          j                                        }	t	          j        d|	          }
|
r"t          |
                    d                    nd}|dk    s
J d	            n# t          t           j	        t          f$ rp t          st          r)t          j        d
| d           t          dg           n6t           st"          r(t          j        d
| d           t          dg           Y nw xY wt%          d           t%          d           t'          |          r
 |            n|}ddl}ddl}ddlm} t          j        d
| d|j         d           |fd} |dd          }|j                                        }t6          d|                                 v rdnd         | j                 }t=          t?          |                                                      |d         vrtC          d          |d         D ];}|"                    |j        j#        j$        %                    |          gd           <|j        &                    |j        '                    d !          |j        (                    d"          |#          }|j        )                    |d$         %          }|rA|j*        +                    | |||j*        ,                    d&d'd'(          ||)          d         n$|j-        .                    | ||||*          d         }| j        d+k    rt_          ||pd,||| j        -          }ta          |          }|1                    dd.           |d/z  }te                      5  |j3        4                    |||0           ddd           n# 1 swxY w Y   |5                    |          }|pi 6                                D ]:\  }}|j7        8                                }|ts          |          c|_:        |_;        ;|<                    ||           ta          tz          j>                  j?        }|t          rd1nd2z  }|A                                st          d2          }|st          d3          t          j        ts          |          d4ts          |          d5ts          |          d6d7gd8           t          |d9z  d:d;<          5 }|D                    d= | jE        6                                D                        ddd           n# 1 swxY w Y   ts          |          S )>a  Export YOLO model to IMX format for deployment on Sony IMX500 devices.

    This function quantizes a YOLO model using Model Compression Toolkit (MCT) and exports it to IMX format compatible
    with Sony IMX500 edge devices. It supports both YOLOv8n and YOLO11n models for detection, segmentation, pose
    estimation, and classification tasks.

    Args:
        model (torch.nn.Module): The YOLO model to export. Must be YOLOv8n or YOLO11n.
        output_dir (Path | str): Directory to save the exported IMX model.
        conf (float): Confidence threshold for NMS post-processing.
        iou (float): IoU threshold for NMS post-processing.
        max_det (int): Maximum number of detections to return.
        metadata (dict | None, optional): Metadata to embed in the ONNX model. Defaults to None.
        gptq (bool, optional): Whether to use Gradient-Based Post Training Quantization. If False, uses standard Post
            Training Quantization. Defaults to False.
        dataset (optional): Representative dataset for quantization calibration. Defaults to None.
        prefix (str, optional): Logging prefix string. Defaults to "".

    Returns:
        (str): Path to the exported IMX model directory.

    Raises:
        ValueError: If the model is not a supported YOLOv8n or YOLO11n variant.

    Examples:
        >>> from ultralytics import YOLO
        >>> model = YOLO("yolo11n.pt")
        >>> path = torch2imx(model, "output_dir/", conf=0.25, iou=0.7, max_det=300)

    Notes:
        - Auto-installs Java>=17, model-compression-toolkit, imx500-converter, and related packages if not present
        - Only supports YOLOv8n and YOLO11n models (detection, segmentation, pose, and classification tasks)
        - Output includes quantized ONNX model, IMX binary, and labels.txt file
    javaz	--versionT)checkcapture_outputz(?:openjdk|java) (\d+)rM   r      zJava version too old
z! installing Java 21 for Ubuntu...zopenjdk-21-jrez2 installing Java 17 for Raspberry Pi or Debian ...zopenjdk-17-jre)z model-compression-toolkit>=2.4.1zedge-mdt-cl<1.1.0zedge-mdt-tpc>=1.2.0zpydantic<2.12zimx500-converter[pt]>=3.17.3N) get_target_platform_capabilitiesz0 starting export with model_compression_toolkit z...c              3  8   K   | D ]}|d         }|dz  }|gV  d S )Nimgg     o@rF   )
dataloaderbatchr   s      r@   representative_dataset_genz-torch2imx.<locals>.representative_dataset_gen  s>       	 	E,C+C%KKKK	 	rA   z4.0imx500)tpc_versiondevice_typeC2PSAr3   r4   r   z9IMX export only supported for YOLOv8n and YOLO11n models.r      
   )num_of_images)concat_threshold_update)mixed_precision_configquantization_configbit_width_configr   )r   i  F)n_epochsuse_hessian_based_weightsuse_hessian_sample_attention)r<   representative_data_gentarget_resource_utilizationgptq_configcore_configtarget_platform_capabilities)	in_moduler   r   r   r   r$   r   )r<   r   r   r   r   )parentsexist_okzmodel_imx.onnx)r<   save_model_pathrepr_datasetzimxconv-pt.exez
imxconv-ptzDimxconv-pt not found. Install with: pip install imx500-converter[pt]z-iz-oz--no-input-persistencyz--overwrite-output)r   z
labels.txtwzutf-8)encodingc                    g | ]
\  }}| d S )r   rF   )rG   _names      r@   rK   ztorch2imx.<locals>.<listcomp>r  s"    OOO44OOOrA   )F
subprocessrunstdoutdecoderesearchrX   groupFileNotFoundErrorCalledProcessErrorAssertionErrorr   r
   r   infor   r   r	   r   callablemodel_compression_toolkitonnxedgemdt_tpcr   __version__coreBitWidthConfig
MCT_CONFIG__str__r   lenlistmodules
ValueErrorset_manual_activation_bit_widthcommonnetwork_editorsNodeNameFilter
CoreConfig MixedPrecisionQuantizationConfigQuantizationConfigResourceUtilizationr   +pytorch_gradient_post_training_quantizationget_pytorch_gptq_configptq"pytorch_post_training_quantizationr   r   mkdirr   exporterpytorch_export_modelloaditemsmetadata_propsaddr   keyvaluesavesys
executableparentr   existsr   open
writelinesnames)r<   r   r   r   r   r   r   datasetr   java_outputversion_matchjava_versionmctr   r   r   tpcbit_cfg
mct_config
layer_nameconfigresource_utilizationquant_model
onnx_model
model_onnxkvmetabin_dirimxconvlabels_files                                  r@   	torch2imxr/     s   \7 nfk%:$W[\\\cjjll	";[II6CJs=..q11222r!!!#9!!!!z<nM 7 7 7 	7( 	7KFVFFFGGG"$4#56666 	71 	7KWVWWWXXX"$4#56667 	
   5666#G,,9ggiii'G++++KKK<<<<<<
KaVaaS_aaabbb.5     +
*u(
S
S
SCh%%''G5==??(B(BHHQRWR\]J 4  !!J)???TUUU / r r
//1P1_1_`j1k1k0lnpqqqqX  "xHHWYHZZH77PT7UU  !  F 877zRbGc7dd 	<<$>(<88]b 9   ), 	= 		
 		
 		 		 W77$>(<), 8 
 
  * zZ  ME"
 
 
 j!!JTD111..J			 
 
))zHb 	* 	
 	
 	

 
 
 
 
 
 
 
 
 
 
 
 
 
 

 :&&JR&&(( ) )1(,,.. #a&&$**IIj*%%% 3>"")GWF)),GG>> &%% h fgggN	WtS__dC
OOE]_st    
j<'w	?	?	? Q;OO5;;L;L;N;NOOOPPPQ Q Q Q Q Q Q Q Q Q Q Q Q Q Q z??s7   A;A> >B	D
	D
N99N= N=97T<<U U )rI   rl   rm   rn   )rI   rx   rm   ry   )rI   rx   rm   r   )NFNr   )r<   r   r   r   r   r   r   r   r   rX   r   r   r   r   r   r   rm   r   )+
__future__r   r   r   r  rY   pathlibr   shutilr   numpynpr\   ultralytics.nn.modulesr   r   r   ultralytics.utilsr	   r
   r   r   r   r   ultralytics.utils.checksr   r   ultralytics.utils.patchesr   ultralytics.utils.talr   ultralytics.utils.torch_utilsr   infr   nnModuler6   r[   ra   rc   r   r/  rF   rA   r@   <module>r>     s   # " " " " " 				     



                   8 8 8 8 8 8 8 8 8 8 n n n n n n n n n n n n n n n n O O O O O O O O 7 7 7 7 7 7 . . . . . . 3 3 3 3 3 3 @??*c

 
 ]\\(c

 

 %'"&seTT???'c

 
 ( =<<'c

 
 YXX(c

 

 %'"&rdSS<<<'c

 
 '% %
P8 8 8 8 8eho 8 8 8vH H H H) ) ) )"% % % %1^ 1^ 1^ 1^ 1^ 1^ 1^ 1^t !f f f f f f frA   