
    jM6                       d dl m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 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dGd-ZdHd0ZdId2Z  G d3 d4ej        j                  Z!	 	 	 	 dJdKdFZ"dS )L    )annotationsN)Path)which)DetectPoseSegment)LOGGERWINDOWS)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).
      r2   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)selfr6   r7   	__class__s      a/home/longshao/multi-rider-rag/.venv/lib/python3.11/site-packages/ultralytics/utils/export/imx.pyr5   zFXModel.__init__I   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 r=    ).0jxys     r:   
<listcomp>z#FXModel.forward.<locals>.<listcomp>f   s*    8]8]8]TUa2gg1Q48]8]8]r;   c              3  B   K   | ]}|                     d d          V  dS )r      N)	transpose)rA   rC   s     r:   	<genexpr>z"FXModel.forward.<locals>.<genexpr>i   sD       ( ( KK1%%( ( ( ( ( (r;   c                J    g | ]}|j                             d           z   S r?   )stride	unsqueeze)rA   sms     r:   rE   z#FXModel.forward.<locals>.<listcomp>l   s.    "R"R"R!1qx'9'9"'='=#="R"R"Rr;   rG   )dimg      ?)r6   f
isinstanceintr   types
MethodType
_inferencer   torchcatr7   rK   anchorsstridestyper   pose_forwardforwardr   segment_forwardappend)r8   rC   rN   rD   s    `@@r:   r\   zFXModel.forwardV   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r;   )r1   __name__
__module____qualname____doc__r5   r\   __classcell__r9   s   @r:   r0   r0   =   sV        	 	           r;   r0   rC   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   rG      scores)decode_bboxesdflrX   rL   rY   rH   sigmoidpermute)r8   rC   dboxs      r:   rU   rU   x   s{    dhhqz22DL4J4J14M4MNNQUQ]]D>>!Q8!4!4!6!6!>!>q!Q!G!GGGr;   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 r?   )cv4view)rA   ibsnk_outr8   rC   s     r:   rE   z pose_forward.<locals>.<listcomp>   s?    TTT[TXa[1&&++B;;TTTr;   r=   rG   rk   N)shapegetattrnkrV   rW   rangenlhasattrru   rx   	kpt_shaper   r\   kpts_decoderp   )r8   rC   kptspatialpred_kptrz   r{   s   ``   @@r:   r[   r[   ~   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(((((r;   =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 r?   )rw   rx   nm)rA   ry   rz   r8   rC   s     r:   rE   z#segment_forward.<locals>.<listcomp>   sA    TTTKDHQK!%%**2tw;;TTTr;   rk   rG   )	protor}   rV   rW   r   r   r   r\   rH   )r8   rC   pmcrz   s   ``  @r:   r]   r]      s    

1Q4A	
B	TTTTTTU47^^TTTVW	X	XBtQA$A$r||Aq!!$1$$$r;   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   r6   torch.nn.Modulescore_thresholdfloatiou_thresholdmax_detectionsrR   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)r4   r5   r6   r   r   r   r   )r8   r6   r   r   r   r   r9   s         r:   r5   zNMSWrapper.__init__   sE    " 	
.*,			r;   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_indicesrG   )rj   rl   r   r   r   r   rk   r=   r      )'edgemdt_cl.pytorch.nms.nms_with_indicesr   r6   r   r   r   r   rV   gatherindicesrL   expandsizerj   rl   labelsn_valid)r8   imagesr   outputsrj   rl   nms_outputskptsout_kptsr   r   out_mcs               r:   r\   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]]]r;   )r   r   r   r   )
r6   r   r   r   r   r   r   rR   r   r   r_   re   s   @r:   r   r      sl        II
 "'"!      0^ ^ ^ ^ ^ ^ ^r;   r   F r6   r   file
Path | strconfr   ioumax_detrR   metadatadict | Nonegptqboolprefixr   c	           
        ddl }	ddl}
ddlm} t	          j        d| d|	j         d           |fd} |dd	
          }|	j                                        }t          d| 
                                v rdnd         | j                 }t          t          |                                                     |d         vrt          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                   }t=          t?          |                               |j!        d!                    }|"                    d"           |t=          t?          |j#                                       |j!        d#                    z  }tI                      5  |	j%        &                    |||$           ddd           n# 1 swxY w Y   |
'                    |          }|(                                D ]:\  }}|j)        *                                }|t?          |          c|_+        |_,        ;|
-                    ||           t=          t\          j/                  j0        }|tb          rd%nd&z  }|2                                stg          d&          }|sti          d'          tk          j6        t?          |          d(t?          |          d)t?          |          d*d+gd,           to          |d-z  d.d/0          5 }|8                    d1 | j9        (                                D                        ddd           n# 1 swxY w Y   |S )2a  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.
        file (Path | str): Output file path for the exported 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:
        (Path): 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, "model.imx", conf=0.25, iou=0.7, max_det=300)

    Notes:
        - Requires model_compression_toolkit, onnx, edgemdt_tpc, and edge-mdt-cl packages
        - Only supports YOLOv8n and YOLO11n models (detection, segmentation, pose, and classification tasks)
        - Output includes quantized ONNX model, IMX binary, and labels.txt file
    r   N) get_target_platform_capabilities
z0 starting export with model_compression_toolkit z...c              3  8   K   | D ]}|d         }|dz  }|gV  d S )Nimgg     o@r@   )
dataloaderbatchr   s      r:   representative_dataset_genz-torch2imx.<locals>.representative_dataset_gen   s>       	 	E,C+C%KKKK	 	r;   z4.0imx500)tpc_versiondevice_typeC2PSAr-   r.   r   z9IMX export only supported for YOLOv8n and YOLO11n models.r      
   )num_of_imagesT)concat_threshold_update)mixed_precision_configquantization_configbit_width_configr   )r   i  F)n_epochsuse_hessian_based_weightsuse_hessian_sample_attention)r6   representative_data_gentarget_resource_utilizationgptq_configcore_configtarget_platform_capabilities)	in_moduler   r   r   r   r   r   )r6   r   r   r   r   
_imx_model)exist_okz	_imx.onnx)r6   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)checkz
labels.txtwzutf-8)encodingc                    g | ]
\  }}| d S )r   r@   )rA   _names      r:   rE   ztorch2imx.<locals>.<listcomp>W  s"    HHHDDHHHr;   ):model_compression_toolkitonnxedgemdt_tpcr   r	   info__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   r   replacesuffixmkdirr   r   exporterpytorch_export_modelloaditemsmetadata_propsaddkeyvaluesavesys
executableparentr
   existsr   FileNotFoundError
subprocessrunopen
writelinesnames)r6   r   r   r   r   r   r   datasetr   mctr   r   r   tpcbit_cfg
mct_config
layer_nameconfigresource_utilizationquant_modelrP   
onnx_model
model_onnxkvmetabin_dirimxconvs                               r:   	torch2imxr     s8   Z ,+++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"
 
 
 	SYYt{L99::AGGTGT#di..00kJJKKKJ			 
 
))zHb 	* 	
 	
 	

 
 
 
 
 
 
 
 
 
 
 
 
 
 

 :&&J   ) )1(,,.. #a&&$**IIj*%%% 3>"")GWF)),GG>> &%% h fgggN	WtS__dCFF<TVjk    
a,g	6	6	6 J$HHEK4E4E4G4GHHHIIIJ J J J J J J J J J J J J J J Hs$   'KKK7QQQ)rC   rf   rg   rh   )rC   rr   rg   rs   )rC   rr   rg   r   )NFNr   )r6   r   r   r   r   r   r   r   r   rR   r   r   r   r   r   r   )#
__future__r   r  r  rS   pathlibr   shutilr   numpynprV   ultralytics.nn.modulesr   r   r   ultralytics.utilsr	   r
   ultralytics.utils.patchesr   ultralytics.utils.talr   ultralytics.utils.torch_utilsr   infr   nnModuler0   rU   r[   r]   r   r  r@   r;   r:   <module>r*     s   # " " " " "     



                   8 8 8 8 8 8 8 8 8 8 - - - - - - - - 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 !M M M M M M Mr;   