
    .h,                    $   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	 d dl
mZ d dlmZ d dlmZ  G d d	ej                   j"                        Zdd
ZddZ G d dej                   j"                        Z	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZy)    )annotationsN)Path)DetectPose)LOGGER)make_anchors)	copy_attrc                  *     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.
    c                j    t         |           t        | |       |j                  | _        || _        y)z
        Initialize 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      Z/var/www/html/ai-service/venv/lib/python3.12/site-packages/ultralytics/utils/export/imx.pyr   zFXModel.__init__   s,     	$[[

    c                   g }| j                   D ]K  }|j                  dk7  rMt        |j                  t              r||j                     n#|j                  D cg c]  }|dk(  r|n||    c}}t        |t              rt        j                  t        |      |_        d t        t        j                  | j                  D cg c]   }||j                  j                  d      z  " c}d      |j                  d      D        \  |_        |_        t!        |      t"        u rt        j                  t$        |      |_         ||      }|j)                  |       N |S c c}w c c}w )aa  
        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              3  @   K   | ]  }|j                  d d        yw)r      N)	transpose).0xs     r   	<genexpr>z"FXModel.forward.<locals>.<genexpr>?   s#      ( KK1%(s   r   )dimg      ?)r   f
isinstanceintr   types
MethodType
_inferencer   torchcatr   stride	unsqueezeanchorsstridestyper   pose_forwardforwardappend)r   r   ymjss         r   r,   zFXModel.forward+   s&     	Assby(c2AaccFYZY\Y\8]TUa2g1Q49O8]!V$$//
A>()		tzz"R!1qxx'9'9"'=#="RXYZ\]\d\dfi($	19 Aw$!,,\1=	!AHHQK	   9^ #Ss   E %E%))  r2   __name__
__module____qualname____doc__r   r,   __classcell__r   s   @r   r   r      s    	r   r   c           
        t        j                  |D cg c]/  }|j                  |d   j                  d   | j                  d      1 c}d      }|j                  | j                  dz  | j                  fd      \  }}| j                  | j                  |      | j                  j                  d            | j                  z  }|j                  dd      |j                         j                  ddd      fS c c}w )z5Decode boxes and cls scores for imx object detection.r   r         r   )r$   r%   viewshapenosplitreg_maxncdecode_bboxesdflr(   r'   r)   r   sigmoidpermute)r   r   xix_catboxclsdboxs          r   r#   r#   L   s    IIQGrrwwqtzz!}dggr:GKE{{DLL1,dgg6:HCdhhsmT\\-C-CA-FG$,,VD>>!Q!6!6q!Q!??? Hs   4C8c           
        |d   j                   d   }t        j                  t        | j                        D cg c]5  } | j
                  |   ||         j                  || j                  d      7 c}d      }t        j                  | |      }| j                  ||      }g ||j                  ddd      S c c}w )zBForward pass for imx pose estimation, including keypoint decoding.r   r   r;   r   )r>   r$   r%   rangenlcv4r=   nkr   r,   kpts_decoderF   )r   r   bsikptpred_kpts         r   r+   r+   T   s    	
1AB
))eDGGnU[TXXa[1&++B<UWY
ZCtQAC(H*Q*  Aq)** Vs   :B;c                  F     e Zd ZdZ	 	 	 	 d	 	 	 	 	 	 	 	 	 d fdZd Z xZS )
NMSWrapperzFWrap PyTorch Module with multiclass_nms layer from sony_custom_layers.c                h    t         |           || _        || _        || _        || _        || _        y)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, either 'detect' or 'pose'.
        N)r   r   r   score_thresholdiou_thresholdmax_detectionstask)r   r   rY   rZ   r[   r\   r   s         r   r   zNMSWrapper.__init__`   s6    $ 	
.*,	r   c                   ddl m} | j                  |      }|d   |d   }} |||| j                  | j                  | j
                        }| j                  dk(  ry|d   }t        j                  |d|j                  j                  d      j                  dd|j                  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_indicesr   )boxesscoresrY   rZ   r[   poser;   r   )sony_custom_layers.pytorchr^   r   rY   rZ   r[   r\   r$   gatherindicesr'   expandsizer_   r`   labelsn_valid)	r   imagesr^   outputsr_   r`   nms_outputskptsout_kptss	            r   r,   zNMSWrapper.forwardy   s    J **V$
GAJv1 00,,..
 991:D||D![-@-@-J-J2-N-U-UVXZ\^b^g^ghj^k-lmH$$k&8&8+:L:LhVV  +"4"4k6H6H+J]J]]]r   )MbP?gffffff?i,  detect)
r   torch.nn.ModulerY   floatrZ   rq   r[   r    r\   strr3   r9   s   @r   rW   rW   ]   sO    P
 "'"!  	
  2^r   rW   c	           
        ddl }	ddl}
ddlm} t	        j
                  d| d|	j                   d       |fd} |dd	
      }|	j                  j                         }d| j                         v r0| j                  dk(  r	g d}d}d}nG| j                  dk(  r8g d}d}d}n/| j                  dk(  r	g d}d}d}n| j                  dk(  rg d}d}d}t        t        | j                                     k7  rt        d      D ]B  }|j                  |	j                  j                   j"                  j%                  |      gd       D |	j                  j'                  |	j                  j)                  d      |	j                  j+                  d      |       }|	j                  j-                  !      }|r@|	j.                  j1                  | |||	j.                  j3                  d"d#d#$      ||%      d   n"|	j4                  j7                  | ||||&      d   }t9        ||xs d'||| j                  (      }t;        t=        |      j?                  |j@                  d)            }|jC                  d*       |t;        t=        |jD                        j?                  |j@                  d+            z  }|	jF                  jI                  |||,       |
jK                  |      }|jM                         D ]7  \  }}|jN                  jQ                         }|t=        |      c|_)        |_*        9 |
jW                  ||       tY        jZ                  d-d.t=        |      d/t=        |      d0d1gd2       t]        |d3z  d4d56      5 }|j_                  | j`                  jM                         D cg c]
  \  }}| d c}}       ddd       |S c c}}w # 1 sw Y   |S xY w)7a  
    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 and pose estimation 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:
        f (Path): Path to the exported IMX model directory

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

    Example:
        >>> from ultralytics import YOLO
        >>> model = YOLO("yolo11n.pt")
        >>> path, _ = export_imx(model, "model.imx", conf=0.25, iou=0.45, max_det=300)

    Note:
        - Requires model_compression_toolkit, onnx, edgemdt_tpc, and sony_custom_layers packages
        - Only supports YOLOv8n and YOLO11n models (detection and pose 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  y w)Nimgg     o@ )
dataloaderbatchrw   s      r   representative_dataset_genz-torch2imx.<locals>.representative_dataset_gen   s.      	E,C+C%K	s   z4.0imx500)tpc_versiondevice_typeC2PSAro   )submul_2add_14cat_21g~8CA   ra   )r   r   r   cat_22cat_23mul_4add_15g\EBAi  )r   muladd_6cat_17gffffuCA   )add_7r   cat_19r   r   r   cat_18gBA   z9IMX export only supported for YOLOv8n and YOLO11n models.   
   )num_of_imagesT)concat_threshold_update)mixed_precision_configquantization_configbit_width_config)weights_memoryi  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   rn   )r   rY   rZ   r[   r\   
_imx_model)exist_okz	_imx.onnx)r   save_model_pathrepr_datasetz
imxconv-ptz-iz-oz--no-input-persistencyz--overwrite-output)checkz
labels.txtwzutf-8)encoding)1model_compression_toolkitonnxedgemdt_tpcrt   r   info__version__coreBitWidthConfig__str__r\   lenlistmodules
ValueErrorset_manual_activation_bit_widthcommonnetwork_editorsNodeNameFilter
CoreConfig MixedPrecisionQuantizationConfigQuantizationConfigResourceUtilizationgptq+pytorch_gradient_post_training_quantizationget_pytorch_gptq_configptq"pytorch_post_training_quantizationrW   r   rr   replacesuffixmkdirnameexporterpytorch_export_modelloaditemsmetadata_propsaddkeyvaluesave
subprocessrunopen
writelinesnames)r   fileconfioumax_detmetadatar   datasetprefixmctr   rt   r{   tpcbit_cfglayer_namesr   n_layers
layer_nameconfigresource_utilizationquant_modelr   
onnx_model
model_onnxkvmeta_r   s                                 r   	torch2imxr      s   \ ,<
KK"VHLS__L]]`ab.5  +u(
SChh%%'G%--/!::!>K)NHZZ6![K'NH::!;K&NHZZ6!WK'NH 4 !X-TUU! r
//1P1P1_1_`j1k0lnpqr XX  "xxHHWYHZHH77PT7U  ! F 8877~7V  	<<$>(<88]b 9  ), 	= 		
 		 WW77$>(<), 8 
  * ZZK 	SYt{{L9:AGGTGT#dii.00kJKKJLL%%:D^ &  :&J  )1((,,. #a&$*) 	IIj*%NN	tS_dCF<TVjk 
a,g	6 J$EKK4E4E4GHDD6HIJ H IJ Hs   >)O'O6OOO)r   list[torch.Tensor]returnztuple[torch.Tensor])r   r   r   z/tuple[torch.Tensor, torch.Tensor, torch.Tensor])NFN )r   rp   r   z
Path | strr   rq   r   rq   r   r    r   zdict | Noner   boolr   rr   )
__future__r   r   r!   pathlibr   r$   ultralytics.nn.modulesr   r   ultralytics.utilsr   ultralytics.utils.talr   ultralytics.utils.torch_utilsr	   nnModuler   r#   r+   rW   r   rx   r   r   <module>r      s    #     / $ . 38ehhoo 8v@+.^ .^n !SS
S S 
	S
 S S S Sr   