Ë
    Fêñi¬ ã                   óÊ  — 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	m
Z
 d dlmZ d dlmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZI d dlJmKZKmLZLmMZMmNZNmOZOmPZP d dlQmRZRmSZSmTZT d dlUmVZVmWZWmXZXmYZYmZZZm[Z[m\Z\ d d	l]m^Z^ d d
l_m`Z` d dlambZb d dlcmdZdmeZemfZfmgZgmhZhmiZimjZjmkZk  G d„ dej                  jØ                  «      Zm G d„ dem«      Zn G d„ den«      Zo G d„ den«      Zp G d„ den«      Zq G d„ dem«      Zr G d„ den«      Zs G d„ den«      Zt G d„ den«      Zu G d„ d euep«      Zv G d!„ d"ej                  jî                  «      Zxe jò                  d.d#„«       Zz G d$„ d%«      Z{ G d&„ d'ejø                  «      Z}d/d(„Z~d0d)„Zd1d*„Z€d+„ Z�d,„ Z‚d-„ Zƒy)2é    N)Údeepcopy)ÚPath)Úcheck_class_names)<ÚAIFIÚC1ÚC2ÚC2PSAÚC3ÚC3TRÚELAN1ÚOBBÚOBB26ÚPSAÚSPPÚSPPELANÚSPPFÚA2C2fÚAConvÚADownÚ
BottleneckÚBottleneckCSPÚC2fÚC2fAttnÚC2fCIBÚC2fPSAÚC3GhostÚC3k2ÚC3xÚCBFuseÚCBLinearÚClassifyÚConcatÚConvÚConv2ÚConvTransposeÚDetectÚDWConvÚDWConvTranspose2dÚFocusÚGhostBottleneckÚ	GhostConvÚHGBlockÚHGStemÚImagePoolingAttnÚIndexÚLRPCHeadÚPoseÚPose26ÚRepC3ÚRepConvÚRepNCSPELAN4ÚRepVGGDWÚResNetLayerÚRTDETRDecoderÚSCDownÚSegmentÚ	Segment26ÚTorchVisionÚWorldDetectÚYOLOEDetectÚYOLOESegmentÚYOLOESegment26Ú	v10Detect)ÚDEFAULT_CFG_DICTÚLOGGERÚWINDOWSÚYAMLÚcolorstrÚemojis)Úcheck_requirementsÚcheck_suffixÚ
check_yaml)ÚE2ELossÚ
PoseLoss26Úv8ClassificationLossÚv8DetectionLossÚ	v8OBBLossÚ
v8PoseLossÚv8SegmentationLoss)Úmake_divisible)Ú
torch_load)Úfeature_visualization)Úfuse_conv_and_bnÚfuse_deconv_and_bnÚinitialize_weightsÚintersect_dictsÚ
model_infoÚ	scale_imgÚsmart_inference_modeÚ	time_syncc                   ór   ‡ — e Zd ZdZd„ Zdd„Zdd„Zd„ Zd„ Zdd„Z	dd„Z
dd	„Zˆ fd
„Zdd„Zdd„Zd„ Zˆ xZS )Ú	BaseModela  Base class for all YOLO models in the Ultralytics family.

    This class provides common functionality for YOLO models including forward pass handling, model fusion, information
    display, and weight loading capabilities.

    Attributes:
        model (torch.nn.Sequential): The neural network model.
        save (list): List of layer indices to save outputs from.
        stride (torch.Tensor): Model stride values.

    Methods:
        forward: Perform forward pass for training or inference.
        predict: Perform inference on input tensor.
        fuse: Fuse Conv/BatchNorm layers and reparameterize for optimization.
        info: Print model information.
        load: Load weights into the model.
        loss: Compute loss for training.

    Examples:
        Create a BaseModel instance
        >>> model = BaseModel()
        >>> model.info()  # Display model information
    c                 óz   — t        |t        «      r | j                  |g|¢­i |¤ŽS  | j                  |g|¢­i |¤ŽS )a'  Perform forward pass of the model for either training or inference.

        If x is a dict, calculates and returns the loss for training. Otherwise, returns predictions for inference.

        Args:
            x (torch.Tensor | dict): Input tensor for inference, or dict with image tensor and labels for training.
            *args (Any): Variable length argument list.
            **kwargs (Any): Arbitrary keyword arguments.

        Returns:
            (torch.Tensor): Loss if x is a dict (training), or network predictions (inference).
        )Ú
isinstanceÚdictÚlossÚpredict)ÚselfÚxÚargsÚkwargss       úV/var/www/pod-logistic/pod-ai/venv/lib/python3.12/site-packages/ultralytics/nn/tasks.pyÚforwardzBaseModel.forward   sD   € ô �aœÔØ�4—9‘9˜QÐ0 Ò0¨Ñ0Ð0Øˆt�|‰|˜AÐ/ Ò/¨Ñ/Ð/ó    c                 óP   — |r| j                  |«      S | j                  ||||«      S )aø  Perform a forward pass through the network.

        Args:
            x (torch.Tensor): The input tensor to the model.
            profile (bool): Print the computation time of each layer if True.
            visualize (bool): Save the feature maps of the model if True.
            augment (bool): Augment image during prediction.
            embed (list, optional): A list of layer indices to return embeddings from.

        Returns:
            (torch.Tensor): The last output of the model.
        )Ú_predict_augmentÚ_predict_once)rd   re   ÚprofileÚ	visualizeÚaugmentÚembeds         rh   rc   zBaseModel.predict�   s/   € ñ Ø×(Ñ(¨Ó+Ð+Ø×!Ñ! ! W¨i¸Ó?Ð?rj   c                 óN  — g g g }}}|�t        |«      ndh}t        |«      }| j                  D �]n  }	|	j                  dk7  rMt	        |	j                  t
        «      r||	j                     n#|	j                  D �
cg c]  }
|
dk(  r|n||
   ‘Œ c}
}|r| j                  |	||«        |	|«      }|j                  |	j                  | j                  v r|nd«       |r#t        ||	j                  |	j                  |¬«       |	j                  |v sŒÜ|j                  t        j                  j                  j                  |d«      j!                  d«      j!                  d«      «       |	j                  |k(  s�ŒDt        j"                  t        j$                  |d«      d¬«      c S  |S c c}
w )a»  Perform a forward pass through the network.

        Args:
            x (torch.Tensor): The input tensor to the model.
            profile (bool): Print the computation time of each layer if True.
            visualize (bool): Save the feature maps of the model if True.
            embed (list, optional): A list of layer indices to return embeddings from.

        Returns:
            (torch.Tensor): The last output of the model.
        Néÿÿÿÿ©Úsave_dir©é   rw   rw   r   ©Údim©Ú	frozensetÚmaxÚmodelÚfr`   ÚintÚ_profile_one_layerÚappendÚiÚsaverT   ÚtypeÚtorchÚnnÚ
functionalÚadaptive_avg_pool2dÚsqueezeÚunbindÚcat)rd   re   rn   ro   rq   ÚyÚdtÚ
embeddingsÚmax_idxÚmÚjs              rh   rm   zBaseModel._predict_once¡   s[  € ð   Bˆzˆ2ˆØ$)Ð$5”	˜%Ô ¸B¸4ˆÜ�e“*ˆØ—‘ó 	IˆAØ�s‰s�bŠyÜ(¨¯©¬cÔ2�A�a—c‘c’FÐYZ×Y\ÑY\Ö8]ÐTU¸aÀ2ºg¹È1ÈQÉ4Ñ9OÒ8]�ÙØ×'Ñ'¨¨1¨bÔ1Ù�!“ˆAØ�H‰H˜!Ÿ#™# §¡Ñ*‘Q°Ô5ÙÜ% a¨¯©°·±¸yÕIØ�s‰s�eŠ|Ø×!Ñ!¤%§(¡(×"5Ñ"5×"IÑ"IÈ!ÈVÓ"T×"\Ñ"\Ð]_Ó"`×"hÑ"hÐikÓ"lÔmØ—3‘3˜'”>Ü Ÿ<™<¬¯	©	°*¸aÓ(@ÀaÔHÒHð	Ið ˆùò 9^s   Á8F"c                 ó|   — t        j                  | j                  j                  › d�«       | j	                  |«      S )zFPerform augmentations on input image x and return augmented inference.zR does not support 'augment=True' prediction. Reverting to single-scale prediction.)rC   ÚwarningÚ	__class__Ú__name__rm   )rd   re   s     rh   rl   zBaseModel._predict_augment¿   s;   € ä�‰Ø�~‰~×&Ñ&Ð'ð (4ð 5ô	
ð ×!Ñ! !Ó$Ð$rj   c           	      ó¼  — 	 ddl }|| j                  d   k(  xr t        |t        «      }|r0|j                  ||r|j                  «       n|gd¬«      d   dz  dz  nd}t        «       }t        d«      D ]  } ||r|j                  «       n|«       Œ |j                  t        «       |z
  d	z  «       || j                  d   k(  r!t        j                  d
d›ddd›ddd›d�«       t        j                  |d   d›d|d›d|j                  d›d|j                  › �«       |r+t        j                  t        |«      d›ddd›ddd›d�«       yy# t        $ r d}Y �ŒTw xY w)a/  Profile the computation time and FLOPs of a single layer of the model on a given input.

        Args:
            m (torch.nn.Module): The layer to be profiled.
            x (torch.Tensor): The input data to the layer.
            dt (list): A list to store the computation time of the layer.
        r   Nrs   F)ÚinputsÚverboseg    eÍÍAé   é
   éd   z	time (ms)z>10sú ÚGFLOPsÚparamsz  modulez10.2fú10.0fú  ú-z  Total)ÚthopÚImportErrorr}   r`   Úlistrn   Úcopyr\   Úranger�   rC   ÚinfoÚnpr„   Úsum)	rd   r�   re   r�   r¢   ÚcÚflopsÚtÚ_s	            rh   r€   zBaseModel._profile_one_layerÇ   sV  € ð	Ûð �—‘˜B‘ÑÒ7¤J¨q´$Ó$7ˆÙ^b�—‘˜Q±A¨¯©¬¸1Ð'=Àu�ÓMÈaÑPÐSVÑVÐYZÒZÐhiˆÜ‹KˆÜ�r“ò 	$ˆAÙ™!ˆa�f‰fŒh Õ#ð	$à
�	‰	”9“; ‘? cÑ)Ô*Ø�—
‘
˜1‘ÒÜ�K‰K˜; tÐ,¨A¨h°t¨_¸A¸hÀt¸_ÈHÐUÔVÜ�‰�r˜"‘v˜e�n A e¨E ]°!°A·D±D¸°<¸rÀ!Ç&Á&ÀÐJÔKÙÜ�K‰Kœ3˜r›7 5˜/¨¨3¨t¨*°A°c¸$°Z¸wÐGÕHð øô ò 	Ø‹Dð	ús   ‚E ÅEÅEc                 ó‚  — | j                  «       �s­| j                  j                  «       D �]}  }t        |t        t
        t        f«      rnt        |d«      rbt        |t
        «      r|j                  «        t        |j                  |j                  «      |_
        t        |d«       |j                  |_        t        |t        «      rNt        |d«      rBt!        |j"                  |j                  «      |_        t        |d«       |j                  |_        t        |t$        «      r!|j                  «        |j                  |_        t        |t&        «      r!|j)                  «        |j                  |_        t        |t*        «      s�Œ_t-        |dd«      s�Œn|j)                  «        �Œ€ | j/                  |¬«       | S )a  Fuse Conv/ConvTranspose and BatchNorm layers, and reparameterize RepConv/RepVGGDW for improved efficiency.

        Args:
            verbose (bool): Whether to print model information after fusion.

        Returns:
            (torch.nn.Module): The fused model is returned.
        ÚbnÚend2endF)r˜   )Úis_fusedr}   Úmodulesr`   r#   r$   r'   ÚhasattrÚ
fuse_convsrU   Úconvr¯   ÚdelattrÚforward_fuseri   r%   rV   Úconv_transposer4   r6   Úfuser&   Úgetattrr§   )rd   r˜   r�   s      rh   r¹   zBaseModel.fuseà   s1  € ð �}‰}�Ø—Z‘Z×'Ñ'Ó)ó �Ü˜a¤$¬¬vÐ!6Ô7¼GÀAÀtÔ<LÜ! !¤UÔ+ØŸ™œÜ-¨a¯f©f°a·d±dÓ;�A”FÜ˜A˜tÔ$Ø !§¡�A”IÜ˜a¤Ô/´G¸A¸tÔ4DÜ'9¸!×:JÑ:JÈAÏDÉDÓ'Q�AÔ$Ü˜A˜tÔ$Ø !§¡�A”IÜ˜a¤Ô)Ø—L‘L”NØ !§¡�A”IÜ˜a¤Ô*Ø—F‘F”HØ !§¡�A”IÜ˜a¤Ö(¬W°Q¸	À5Ö-IØ—F‘F–Hð%ð& �I‰I˜gˆIÔ&àˆrj   c                 ó¾   ‡— t        d„ t        j                  j                  j	                  «       D «       «      Št        ˆfd„| j                  «       D «       «      |k  S )aB  Check if the model has less than a certain threshold of normalization layers.

        Args:
            thresh (int, optional): The threshold number of normalization layers.

        Returns:
            (bool): True if the number of normalization layers in the model is less than the threshold, False otherwise.
        c              3   ó0   K  — | ]  \  }}d |v sŒ|–— Œ y­w)ÚNormN© )Ú.0ÚkÚvs      rh   ú	<genexpr>z%BaseModel.is_fused.<locals>.<genexpr>
  s   è ø€ ÒJ™˜˜A¸fÈºk”1ÑJùs   ‚�c              3   ó6   •K  — | ]  }t        |‰«      –— Œ y ­w©N)r`   )r¿   rÁ   r¯   s     €rh   rÂ   z%BaseModel.is_fused.<locals>.<genexpr>  s   øè ø€ Ò=¨”:˜a ×$Ñ=ùs   ƒ)Útupler…   r†   Ú__dict__Úitemsr©   r²   )rd   Úthreshr¯   s     @rh   r±   zBaseModel.is_fused  sD   ø€ ô ÑJ¤§¡×!2Ñ!2×!8Ñ!8Ó!:ÔJÓJˆÜÓ=¨d¯l©l«nÔ=Ó=ÀÑFÐFrj   c                 ó    — t        | |||¬«      S )a#  Print model information.

        Args:
            detailed (bool): If True, prints out detailed information about the model.
            verbose (bool): If True, prints out the model information.
            imgsz (int): The size of the image used for computing model information.
        )Údetailedr˜   Úimgsz)rY   )rd   rÊ   r˜   rË   s       rh   r§   zBaseModel.info  s   € ô ˜$¨¸7È%ÔPÐPrj   c                 óî   •— t         ‰| �  |«      } | j                  d   }t        |t        «      rE ||j
                  «      |_         ||j                  «      |_         ||j                  «      |_        | S )a  Apply a function to all tensors in the model, including Detect head attributes like stride and anchors.

        Args:
            fn (function): The function to apply to the model.

        Returns:
            (BaseModel): An updated BaseModel object.
        rs   )ÚsuperÚ_applyr}   r`   r&   ÚstrideÚanchorsÚstrides©rd   Úfnr�   r”   s      €rh   rÎ   zBaseModel._apply  sa   ø€ ô ‰w‰~˜bÓ!ˆØ�J‰J�r‰NˆÜØŒvô
ñ ˜!Ÿ(™(“|ˆAŒHÙ˜1Ÿ9™9›ˆAŒIÙ˜1Ÿ9™9›ˆAŒIØˆrj   c           	      ód  — t        |t        «      r|d   n|}|j                  «       j                  «       }t	        || j                  «       «      }| j                  |d¬«       t        |«      }d}| j                  «       }||vrm||v ri||   j                  \  }	}
}}||   j                  \  }}}}||k(  r<||k(  r7t        |	|«      t        |
|«      }
}	||   d|	…d|
…f   ||   d|	…d|
…f<   |dz  }|r>t        j                  d|› dt        | j                  j                  «       «      › d	�«       yy)
zÔLoad weights into the model.

        Args:
            weights (dict | torch.nn.Module): The pre-trained weights to be loaded.
            verbose (bool, optional): Whether to log the transfer progress.
        r}   F)Ústrictzmodel.0.conv.weightNrw   zTransferred ú/z items from pretrained weights)r`   ra   ÚfloatÚ
state_dictrX   Úload_state_dictÚlenÚshapeÚminrC   r§   r}   )rd   Úweightsr˜   r}   ÚcsdÚupdated_csdÚlen_updated_csdÚ
first_convrØ   Úc1Úc2ÚhÚwÚcc1Úcc2ÚchÚcws                    rh   ÚloadzBaseModel.load*  sA  € ô %/¨w¼Ô$=�˜Ò À7ˆØ�k‰k‹m×&Ñ&Ó(ˆÜ% c¨4¯?©?Ó+<Ó=ˆØ×Ñ˜[°ÐÔ7Ü˜kÓ*ˆØ*ˆ
à—_‘_Ó&ˆ
Ø˜[Ñ(¨Z¸:Ñ-EØ% jÑ1×7Ñ7‰LˆB��A�qØ" :™×4Ñ4ÑˆC��b˜"Ø�QŠw˜2 š7Ü˜R ›¤s¨2¨s£|�B�Ø36°z±?À3ÀBÀ3ÈÈÈÀ8Ñ3L�
˜:Ñ& s¨ s¨C¨R¨C xÑ0Ø 1Ñ$�ÙÜ�K‰K˜, Ð&7°q¼¸T¿Z¹Z×=RÑ=RÓ=TÓ9UÐ8VÐVtÐuÕvð rj   c                 ó–   — t        | dd«      €| j                  «       | _        |€| j                  |d   «      }| j                  ||«      S )ú§Compute loss.

        Args:
            batch (dict): Batch to compute loss on.
            preds (torch.Tensor | list[torch.Tensor], optional): Predictions.
        Ú	criterionNÚimg)rº   Úinit_criterionrí   ri   ©rd   ÚbatchÚpredss      rh   rb   zBaseModel.lossC  sK   € ô �4˜ dÓ+Ð3Ø!×0Ñ0Ó2ˆDŒNàˆ=Ø—L‘L  u¡Ó.ˆEØ�~‰~˜e UÓ+Ð+rj   c                 ó   — t        d«      ‚)z0Initialize the loss criterion for the BaseModel.z4compute_loss() needs to be implemented by task heads)ÚNotImplementedError©rd   s    rh   rï   zBaseModel.init_criterionQ  s   € ä!Ð"XÓYÐYrj   )FFFN)FFN©T)rš   )FTi€  rÄ   )r•   Ú
__module__Ú__qualname__Ú__doc__ri   rc   rm   rl   r€   r¹   r±   r§   rÎ   rê   rb   rï   Ú__classcell__©r”   s   @rh   r^   r^   f   sK   ø„ ñò00ó"@ó"ò<%òIó2óB
GóQôó&wó2,öZrj   r^   c                   ó†   ‡ — e Zd ZdZd
ˆ fd„	Zed„ «       Zej                  d„ «       Zd„ Zˆ fd„Z	e
dd„«       Zd„ Zd	„ Zˆ xZS )ÚDetectionModelaW  YOLO detection model.

    This class implements the YOLO detection architecture, handling model initialization, forward pass, augmented
    inference, and loss computation for object detection tasks.

    Attributes:
        yaml (dict): Model configuration dictionary.
        model (torch.nn.Sequential): The neural network model.
        save (list): List of layer indices to save outputs from.
        names (dict): Class names dictionary.
        inplace (bool): Whether to use inplace operations.
        end2end (bool): Whether the model uses end-to-end detection.
        stride (torch.Tensor): Model stride values.

    Methods:
        __init__: Initialize the YOLO detection model.
        _predict_augment: Perform augmented inference.
        _descale_pred: De-scale predictions following augmented inference.
        _clip_augmented: Clip YOLO augmented inference tails.
        init_criterion: Initialize the loss criterion.

    Examples:
        Initialize a detection model
        >>> model = DetectionModel("yolo26n.yaml", ch=3, nc=80)
        >>> results = model.predict(image_tensor)
    c           
      ó  •‡ — t         ‰
‰ �  «        t        |t        «      r|n
t	        |«      ‰ _        ‰ j
                  d   d   d   dk(  r*t        j                  d«       d‰ j
                  d   d   d<   |‰ j
                  d<   |rI|‰ j
                  d   k7  r7t        j                  d	‰ j
                  d   › d
|› �«       |‰ j
                  d<   t        t        ‰ j
                  «      ||¬«      \  ‰ _        ‰ _        t        ‰ j
                  d   «      D �ci c]  }||› “Œ c}‰ _        ‰ j
                  j                  dd«      ‰ _        ‰ j                  d   }t        |t"        «      rÉd}‰ j                   |_        ˆ fd„}‰ j                  j%                  «        d|_        t)        j*                   |t)        j,                  d|||«      «      D �	cg c]  }	||	j.                  d   z  ‘Œ c}	«      |_        |j0                  ‰ _        ‰ j                  j3                  «        |j5                  «        nt)        j6                  dg«      ‰ _        t9        ‰ «       |r&‰ j                  «        t        j                  d«       yyc c}w c c}	w )aQ  Initialize the YOLO detection model with the given config and parameters.

        Args:
            cfg (str | dict): Model configuration file path or dictionary.
            ch (int): Number of input channels.
            nc (int, optional): Number of classes.
            verbose (bool): Whether to display model information.
        Úbackboner   r™   ÚSilencez�YOLOv9 `Silence` module is deprecated in favor of torch.nn.Identity. Please delete local *.pt file and re-download the latest model checkpoint.znn.IdentityÚchannelsÚncúOverriding model.yaml nc=ú	 with nc=©rè   r˜   ÚinplaceTrs   é   c                 óR   •— ‰j                  | «      }‰j                  r|d   }|d   S )z_Perform a forward pass through the model, handling different Detect subclass types accordingly.Úone2manyÚfeats)ri   r°   )re   Úoutputrd   s     €rh   Ú_forwardz)DetectionModel.__init__.<locals>._forward“  s+   ø€ àŸ™ a›�Ø—<’<Ø# JÑ/�FØ˜g‘Ð&rj   rw   éþÿÿÿé    Ú N)rÍ   Ú__init__r`   ra   Úyaml_model_loadÚyamlrC   r“   r§   Úparse_modelr   r}   rƒ   r¦   ÚnamesÚgetr  r&   ÚevalÚtrainingr…   ÚtensorÚzerosrÛ   rÏ   ÚtrainÚ	bias_initÚTensorrW   )rd   Úcfgrè   r  r˜   r‚   r�   Úsr  re   r”   s   `         €rh   r  zDetectionModel.__init__r  s  ù€ ô 	‰ÑÔÜ% c¬4Ô0‘C´oÀcÓ6JˆŒ	Ø�9‰9�ZÑ  Ñ# AÑ&¨)Ò3Ü�N‰Nð]ôð +8ˆD�I‰I�jÑ! !Ñ$ QÑ'ð !#ˆ�	‰	�*ÑÙ�"˜Ÿ	™	 $™Ò'Ü�K‰KÐ3°D·I±I¸d±OÐ3DÀIÈbÈTÐRÔSØ ˆD�I‰I�d‰OÜ +¬H°T·Y±YÓ,?ÀBÐPWÔ XÑˆŒ
�D”IÜ).¨t¯y©y¸©Ó)?Ö@ A�a˜A˜3‘iÒ@ˆŒ
Ø—y‘y—}‘} Y°Ó5ˆŒð �J‰J�r‰NˆÜ�aœÔ ØˆAØŸ™ˆAŒIô'ð �J‰J�O‰OÔØˆAŒJÜ—|‘|¹hÄuÇ{Á{ÐSTÐVXÐZ[Ð]^ÓG_Ó>`Ö$a¸ Q¨¯©°©£_Ò$aÓbˆAŒHØŸ(™(ˆDŒKØ�J‰J×ÑÔØ�K‰K�MäŸ,™,¨ tÓ,ˆDŒKô 	˜4Ô ÙØ�I‰IŒKÜ�K‰K˜�Oð ùò7 Aùò$ %bs   ÄJÇJc                 ó6   — t        | j                  d   dd«      S )z<Return whether the model uses end-to-end NMS-free detection.rs   r°   F)rº   r}   rõ   s    rh   r°   zDetectionModel.end2end©  s   € ô �t—z‘z "‘~ y°%Ó8Ð8rj   c                 ó(   — | j                  |¬«       y)z'Override the end-to-end detection mode.)r°   N)Úset_head_attr)rd   Úvalues     rh   r°   zDetectionModel.end2end®  s   € ð 	×Ñ 5ÐÕ)rj   c                 ó¸   — | j                   d   }|j                  «       D ]8  \  }}t        ||«      st        j                  d|› d�«       Œ,t        |||«       Œ: y)zžSet attributes of the model head (last layer).

        Args:
            **kwargs (Any): Arbitrary keyword arguments representing attributes to set.
        rs   zHead has no attribute 'ú'.N)r}   rÇ   r³   rC   r“   Úsetattr)rd   rg   ÚheadrÀ   rÁ   s        rh   r!  zDetectionModel.set_head_attr³  sY   € ð �z‰z˜"‰~ˆØ—L‘L“Nò 	 ‰DˆAˆqÜ˜4 Ô#Ü—‘Ð!8¸¸¸2Ð>Ô?ØÜ�D˜!˜QÕñ		 rj   c           	      ó:  •— t        | dd«      s| j                  j                  dk7  r&t        j                  d«       | j                  |«      S |j                  dd }g d¢}g d¢}g }t        ||«      D ]~  \  }}t        |r|j                  |«      n||t        | j                  j                  «       «      ¬	«      }t        ‰
| �9  |«      d
   }	| j                  |	|||«      }	|j!                  |	«       Œ€ | j#                  |«      }t%        j&                  |d«      dfS )a  Perform augmentations on input image x and return augmented inference and train outputs.

        Args:
            x (torch.Tensor): Input image tensor.

        Returns:
            (tuple[torch.Tensor, None]): Augmented inference output and None for train output.
        r°   Frý   zLModel does not support 'augment=True', reverting to single-scale prediction.r  N)rw   g�Âõ(\�ê?gq=
×£på?)Né   N)Úgsr   rs   )rº   r”   r•   rC   r“   rm   rÛ   ÚziprZ   Úflipr   rÏ   r|   rÍ   rc   Ú_descale_predr�   Ú_clip_augmentedr…   r‹   )rd   re   Úimg_sizer  r~   rŒ   ÚsiÚfiÚxiÚyir”   s             €rh   rl   zDetectionModel._predict_augmentÀ  sþ   ø€ ô �4˜ EÔ*¨d¯n©n×.EÑ.EÐIYÒ.YÜ�N‰NÐiÔjØ×%Ñ% aÓ(Ð(Ø—7‘7˜2˜3�<ˆÚˆÚˆØˆÜ˜!˜Q“iò 	‰FˆB�Ü©˜1Ÿ6™6 "œ:°°B¼3¸t¿{¹{¿¹Ó?PÓ;QÔRˆBÜ‘‘ Ó$ QÑ'ˆBØ×#Ñ# B¨¨B°Ó9ˆBØ�H‰H�R�Lð		ð
 × Ñ  Ó#ˆÜ�y‰y˜˜BÓ Ð%Ð%rj   c                 óè   — | dd…dd…fxx   |z  cc<   | j                  ddd| j                  |   dz
  f|«      \  }}}}|dk(  r	|d   |z
  }n|dk(  r|d   |z
  }t        j                  ||||f|«      S )a³  De-scale predictions following augmented inference (inverse operation).

        Args:
            p (torch.Tensor): Predictions tensor.
            flips (int | None): Flip type (None=none, 2=ud, 3=lr).
            scale (float): Scale factor.
            img_size (tuple): Original image size (height, width).
            dim (int): Dimension to split at.

        Returns:
            (torch.Tensor): De-scaled predictions.
        Né   rw   r™   r   r(  )ÚsplitrÛ   r…   r‹   )	ÚpÚflipsÚscaler.  ry   re   rŒ   ÚwhÚclss	            rh   r,  zDetectionModel._descale_predØ  s‰   € ð 	
Š!ˆRˆaˆRˆ%‹�EÑ‹ØŸ™  A q¨!¯'©'°#©,¸Ñ*:Ð ;¸SÓA‰ˆˆ1ˆb�#Ø�AŠ:Ø˜‘˜a‘‰AØ�aŠZØ˜‘˜a‘ˆAÜ�y‰y˜!˜Q  C˜¨#Ó.Ð.rj   c                 óz  ‡— | j                   d   j                  Št        d„ t        ‰«      D «       «      }d}|d   j                  d   |z  t        d„ t        |«      D «       «      z  }|d   dd| …f   |d<   |d   j                  d   |z  t        ˆfd„t        |«      D «       «      z  }|d   d|d…f   |d<   |S )	zÊClip YOLO augmented inference tails.

        Args:
            y (list[torch.Tensor]): List of detection tensors.

        Returns:
            (list[torch.Tensor]): Clipped detection tensors.
        rs   c              3   ó&   K  — | ]	  }d |z  –— Œ y­w©r4  Nr¾   ©r¿   re   s     rh   rÂ   z1DetectionModel._clip_augmented.<locals>.<genexpr>ø  s   è ø€ Ò(˜��1•Ñ(ùó   ‚rw   r   c              3   ó&   K  — | ]	  }d |z  –— Œ y­wr=  r¾   r>  s     rh   rÂ   z1DetectionModel._clip_augmented.<locals>.<genexpr>ú  s   è ø€ Ò'?°¨¨1­Ñ'?ùr?  .Nc              3   ó4   •K  — | ]  }d ‰dz
  |z
  z  –— Œ y­w)r4  rw   Nr¾   )r¿   re   Únls     €rh   rÂ   z1DetectionModel._clip_augmented.<locals>.<genexpr>ü  s   øè ø€ Ò(M¸q¨¨r°A©v¸©zÕ):Ñ(Mùs   ƒ)r}   rB  r©   r¦   rÛ   )rd   rŒ   ÚgÚer‚   rB  s        @rh   r-  zDetectionModel._clip_augmentedî  s¼   ø€ ð �Z‰Z˜‰^×ÑˆÜÑ(œe B›iÔ(Ó(ˆØˆØˆq‰T�Z‰Z˜‰^˜qÑ ¤CÑ'?´e¸A³hÔ'?Ó$?Ñ?ˆØ�‰t�C˜˜1˜"˜�H‰~ˆˆ!‰Øˆr‰U�[‰[˜‰_ Ñ!¤SÓ(MÄEÈ!ÃHÔ(MÓ%MÑMˆØ�"‘�c˜1™2�g‘ˆˆ"‰Øˆrj   c                 óH   — t        | dd«      rt        | «      S t        | «      S )z5Initialize the loss criterion for the DetectionModel.r°   F)rº   rK   rN   rõ   s    rh   rï   zDetectionModel.init_criterion   s"   € ä '¨¨i¸Ô ?Œw�t‹}ÐZÄ_ÐUYÓEZÐZrj   )zyolo26n.yamlr(  NT)rw   )r•   r÷   rø   rù   r  Úpropertyr°   Úsetterr!  rl   Ústaticmethodr,  r-  rï   rú   rû   s   @rh   rý   rý   V  sc   ø„ ñõ65ðn ñ9ó ð9ð ‡^�^ñ*ó ð*ò ô&ð0 ò/ó ð/ò*ö$[rj   rý   c                   ó*   ‡ — e Zd ZdZdˆ fd„	Zd„ Zˆ xZS )ÚOBBModelað  YOLO Oriented Bounding Box (OBB) model.

    This class extends DetectionModel to handle oriented bounding box detection tasks, providing specialized loss
    computation for rotated object detection.

    Methods:
        __init__: Initialize YOLO OBB model.
        init_criterion: Initialize the loss criterion for OBB detection.

    Examples:
        Initialize an OBB model
        >>> model = OBBModel("yolo26n-obb.yaml", ch=3, nc=80)
        >>> results = model.predict(image_tensor)
    c                 ó,   •— t         ‰| �  ||||¬«       y)aC  Initialize YOLO OBB model with given config and parameters.

        Args:
            cfg (str | dict): Model configuration file path or dictionary.
            ch (int): Number of input channels.
            nc (int, optional): Number of classes.
            verbose (bool): Whether to display model information.
        ©r  rè   r  r˜   N©rÍ   r  ©rd   r  rè   r  r˜   r”   s        €rh   r  zOBBModel.__init__  ó   ø€ ô 	‰Ñ˜S R¨B¸ÐÕ@rj   c                 óR   — t        | dd«      rt        | t        «      S t        | «      S )z,Initialize the loss criterion for the model.r°   F)rº   rK   rO   rõ   s    rh   rï   zOBBModel.init_criterion   s&   € ä+2°4¸ÀEÔ+JŒw�tœYÓ'Ð_ÔPYÐZ^ÓP_Ð_rj   )zyolo26n-obb.yamlr(  NT©r•   r÷   rø   rù   r  rï   rú   rû   s   @rh   rJ  rJ    s   ø„ ñõ	Aö`rj   rJ  c                   ó*   ‡ — e Zd ZdZdˆ fd„	Zd„ Zˆ xZS )ÚSegmentationModela  YOLO segmentation model.

    This class extends DetectionModel to handle instance segmentation tasks, providing specialized loss computation for
    pixel-level object detection and segmentation.

    Methods:
        __init__: Initialize YOLO segmentation model.
        init_criterion: Initialize the loss criterion for segmentation.

    Examples:
        Initialize a segmentation model
        >>> model = SegmentationModel("yolo26n-seg.yaml", ch=3, nc=80)
        >>> results = model.predict(image_tensor)
    c                 ó,   •— t         ‰| �  ||||¬«       y)aX  Initialize Ultralytics YOLO segmentation model with given config and parameters.

        Args:
            cfg (str | dict): Model configuration file path or dictionary.
            ch (int): Number of input channels.
            nc (int, optional): Number of classes.
            verbose (bool): Whether to display model information.
        rL  NrM  rN  s        €rh   r  zSegmentationModel.__init__5  rO  rj   c                 óR   — t        | dd«      rt        | t        «      S t        | «      S )z8Initialize the loss criterion for the SegmentationModel.r°   F)rº   rK   rQ   rõ   s    rh   rï   z SegmentationModel.init_criterion@  s'   € ä4;¸DÀ)ÈUÔ4SŒw�tÔ/Ó0ÐqÔYkÐlpÓYqÐqrj   )zyolo26n-seg.yamlr(  NTrQ  rû   s   @rh   rS  rS  %  s   ø„ ñõ	Aörrj   rS  c                   ó*   ‡ — e Zd ZdZdˆ fd„	Zd„ Zˆ xZS )Ú	PoseModela^  YOLO pose model.

    This class extends DetectionModel to handle human pose estimation tasks, providing specialized loss computation for
    keypoint detection and pose estimation.

    Attributes:
        kpt_shape (tuple): Shape of keypoints data (num_keypoints, num_dimensions).

    Methods:
        __init__: Initialize YOLO pose model.
        init_criterion: Initialize the loss criterion for pose estimation.

    Examples:
        Initialize a pose model
        >>> model = PoseModel("yolo26n-pose.yaml", ch=3, nc=1, data_kpt_shape=(17, 3))
        >>> results = model.predict(image_tensor)
    c                 óò   •— t        |t        «      st        |«      }t        |«      r=t	        |«      t	        |d   «      k7  r#t        j                  d|d   › d|› �«       ||d<   t        ‰| �!  ||||¬«       y)al  Initialize Ultralytics YOLO Pose model.

        Args:
            cfg (str | dict): Model configuration file path or dictionary.
            ch (int): Number of input channels.
            nc (int, optional): Number of classes.
            data_kpt_shape (tuple): Shape of keypoints data.
            verbose (bool): Whether to display model information.
        Ú	kpt_shapez Overriding model.yaml kpt_shape=z with kpt_shape=rL  N)	r`   ra   r  Úanyr¤   rC   r§   rÍ   r  )rd   r  rè   r  Údata_kpt_shaper˜   r”   s         €rh   r  zPoseModel.__init__X  sz   ø€ ô ˜#œtÔ$Ü! #Ó&ˆCÜˆ~Ô¤4¨Ó#7¼4ÀÀKÑ@PÓ;QÒ#QÜ�K‰KÐ:¸3¸{Ñ;KÐ:LÐL\Ð]kÐ\lÐmÔnØ-ˆC�ÑÜ‰Ñ˜S R¨B¸ÐÕ@rj   c                 óR   — t        | dd«      rt        | t        «      S t        | «      S )z0Initialize the loss criterion for the PoseModel.r°   F)rº   rK   rL   rP   rõ   s    rh   rï   zPoseModel.init_criterioni  s&   € ä,3°D¸)ÀUÔ,KŒw�tœZÓ(ÐaÔQ[Ð\`ÓQaÐarj   )zyolo26n-pose.yamlr(  N©NNTrQ  rû   s   @rh   rW  rW  E  s   ø„ ñõ$Aö"brj   rW  c                   ó@   ‡ — e Zd ZdZdˆ fd„	Zd„ Zed„ «       Zd„ Zˆ xZ	S )ÚClassificationModelao  YOLO classification model.

    This class implements the YOLO classification architecture for image classification tasks, providing model
    initialization, configuration, and output reshaping capabilities.

    Attributes:
        yaml (dict): Model configuration dictionary.
        model (torch.nn.Sequential): The neural network model.
        stride (torch.Tensor): Model stride values.
        names (dict): Class names dictionary.

    Methods:
        __init__: Initialize ClassificationModel.
        _from_yaml: Set model configurations and define architecture.
        reshape_outputs: Update model to specified class count.
        init_criterion: Initialize the loss criterion.

    Examples:
        Initialize a classification model
        >>> model = ClassificationModel("yolo26n-cls.yaml", ch=3, nc=1000)
        >>> results = model.predict(image_tensor)
    c                 óJ   •— t         ‰| �  «        | j                  ||||«       y)a\  Initialize ClassificationModel with YAML, channels, number of classes, verbose flag.

        Args:
            cfg (str | dict): Model configuration file path or dictionary.
            ch (int): Number of input channels.
            nc (int, optional): Number of classes.
            verbose (bool): Whether to display model information.
        N)rÍ   r  Ú
_from_yamlrN  s        €rh   r  zClassificationModel.__init__†  s"   ø€ ô 	‰ÑÔØ�‰˜˜R  WÕ-rj   c                 óž  — t        |t        «      r|n
t        |«      | _        | j                  j	                  d|«      x}| j                  d<   |rJ|| j                  d   k7  r8t        j                  d| j                  d   › d|› �«       || j                  d<   n)|s'| j                  j	                  dd«      st        d«      ‚t        t        | j                  «      ||¬«      \  | _
        | _        t        j                  dg«      | _        t        | j                  d   «      D �ci c]  }||› “Œ c}| _        | j                  «        yc c}w )	aT  Set Ultralytics YOLO model configurations and define the model architecture.

        Args:
            cfg (str | dict): Model configuration file path or dictionary.
            ch (int): Number of input channels.
            nc (int, optional): Number of classes.
            verbose (bool): Whether to display model information.
        r  r  r  r  NzFnc not specified. Must specify nc in model.yaml or function arguments.r  rw   )r`   ra   r  r  r  rC   r§   Ú
ValueErrorr  r   r}   rƒ   r…   r  rÏ   r¦   r  )rd   r  rè   r  r˜   r‚   s         rh   ra  zClassificationModel._from_yaml’  s  € ô & c¬4Ô0‘C´oÀcÓ6JˆŒ	ð &*§Y¡Y§]¡]°:¸rÓ%BÐBˆˆT�Y‰Y�zÑ"Ù�"˜Ÿ	™	 $™Ò'Ü�K‰KÐ3°D·I±I¸d±OÐ3DÀIÈbÈTÐRÔSØ ˆD�I‰I�dŠOÙ˜DŸI™IŸM™M¨$°Ô5ÜÐeÓfÐfÜ +¬H°T·Y±YÓ,?ÀBÐPWÔ XÑˆŒ
�D”IÜ—l‘l A 3Ó'ˆŒÜ).¨t¯y©y¸©Ó)?Ö@ A�a˜A˜3‘iÒ@ˆŒ
Ø�	‰	�ùò As   Ä&E
c                 óf  — t        t        | d«      r| j                  n| j                  «       «      d   \  }}t	        |t
        «      rT|j                  j                  |k7  r:t        j                  j                  |j                  j                  |«      |_        yyt	        |t        j                  j                  «      rF|j                  |k7  r6t        | |t        j                  j                  |j                  |«      «       yyt	        |t        j                  j                  «      �r‚|D �cg c]  }t        |«      ‘Œ }}t        j                  j                  |v r‚t        |«      dz
  |ddd…   j!                  t        j                  j                  «      z
  }||   j                  |k7  r1t        j                  j                  ||   j                  |«      ||<   yyt        j                  j"                  |v r¯t        |«      dz
  |ddd…   j!                  t        j                  j"                  «      z
  }||   j$                  |k7  r^t        j                  j#                  ||   j&                  |||   j(                  ||   j*                  ||   j,                  du¬«      ||<   yyyyc c}w )zÅUpdate a TorchVision classification model to class count 'nc' if required.

        Args:
            model (torch.nn.Module): Model to update.
            nc (int): New number of classes.
        r}   rs   rw   N)Úbias)r¤   r³   r}   Únamed_childrenr`   r!   ÚlinearÚout_featuresr…   r†   ÚLinearÚin_featuresr%  Ú
Sequentialr„   rÚ   ÚindexÚConv2dÚout_channelsÚin_channelsÚkernel_sizerÏ   re  )r}   r  Únamer�   re   Útypesr‚   s          rh   Úreshape_outputsz#ClassificationModel.reshape_outputs©  s
  € ô ¤w¨u°gÔ'>˜ŸšÀE×YÑYÓ[Ó\Ð]_Ñ`‰ˆˆaÜ�aœÔ"Ø�x‰x×$Ñ$¨Ò*Ü Ÿ8™8Ÿ?™?¨1¯8©8×+?Ñ+?ÀÓD�•ð +ä˜œ5Ÿ8™8Ÿ?™?Ô+Ø�~‰~ Ò#Ü˜˜t¤U§X¡X§_¡_°Q·]±]ÀBÓ%GÕHð $ä˜œ5Ÿ8™8×.Ñ.Õ/Ø&'Ö( ”T˜!•WÐ(ˆEÐ(Ü�x‰x�‰ %Ñ'Ü˜“J ‘N U©4¨R¨4¡[×%6Ñ%6´u·x±x·±Ó%GÑG�Ø�Q‘4×$Ñ$¨Ò*Ü Ÿ8™8Ÿ?™?¨1¨Q©4×+;Ñ+;¸RÓ@�A�a’Dð +ä—‘—‘ EÑ)Ü˜“J ‘N U©4¨R¨4¡[×%6Ñ%6´u·x±x·±Ó%GÑG�Ø�Q‘4×$Ñ$¨Ò*Ü Ÿ8™8Ÿ?™?Ø˜!™×(Ñ(¨"¨a°©d×.>Ñ.>ÀÀ!ÁÇÁÐRSÐTUÑRV×R[ÑR[ÐcgÐRgð +ó �A�a’Dð +ð *ð 0ùÚ(s   Ä/J.c                 ó   — t        «       S )z:Initialize the loss criterion for the ClassificationModel.)rM   rõ   s    rh   rï   z"ClassificationModel.init_criterionÅ  s   € ä#Ó%Ð%rj   )zyolo26n-cls.yamlr(  NT)
r•   r÷   rø   rù   r  ra  rH  rs  rï   rú   rû   s   @rh   r_  r_  n  s+   ø„ ñõ.
.òð. ñó ðö6&rj   r_  c                   óD   ‡ — e Zd ZdZdˆ fd„	Zˆ fd„Zd„ Zdd„Zd	d„Zˆ xZ	S )
ÚRTDETRDetectionModelar  RTDETR (Real-time DEtection and Tracking using Transformers) Detection Model class.

    This class is responsible for constructing the RTDETR architecture, defining loss functions, and facilitating both
    the training and inference processes. RTDETR is an object detection and tracking model that extends from the
    DetectionModel base class.

    Attributes:
        nc (int): Number of classes for detection.
        criterion (RTDETRDetectionLoss): Loss function for training.

    Methods:
        __init__: Initialize the RTDETRDetectionModel.
        init_criterion: Initialize the loss criterion.
        loss: Compute loss for training.
        predict: Perform forward pass through the model.

    Examples:
        Initialize an RTDETR model
        >>> model = RTDETRDetectionModel("rtdetr-l.yaml", ch=3, nc=80)
        >>> results = model.predict(image_tensor)
    c                 ó,   •— t         ‰| �  ||||¬«       y)a.  Initialize the RTDETRDetectionModel.

        Args:
            cfg (str | dict): Configuration file name or path.
            ch (int): Number of input channels.
            nc (int, optional): Number of classes.
            verbose (bool): Print additional information during initialization.
        rL  NrM  rN  s        €rh   r  zRTDETRDetectionModel.__init__á  rO  rj   c                 ó    •— t         ‰| �  |«      } | j                  d   } ||j                  «      |_         ||j                  «      |_        | S )a  Apply a function to all tensors in the model, including decoder anchors and valid mask.

        Args:
            fn (function): The function to apply to the model.

        Returns:
            (RTDETRDetectionModel): An updated RTDETRDetectionModel object.
        rs   )rÍ   rÎ   r}   rÐ   Ú
valid_maskrÒ   s      €rh   rÎ   zRTDETRDetectionModel._applyì  sD   ø€ ô ‰w‰~˜bÓ!ˆØ�J‰J�r‰NˆÙ�q—y‘y“MˆŒ	Ù˜!Ÿ,™,Ó'ˆŒØˆrj   c                 ó6   — ddl m}  || j                  d¬«      S )z;Initialize the loss criterion for the RTDETRDetectionModel.r   )ÚRTDETRDetectionLossT)r  Úuse_vfl)Úultralytics.models.utils.lossr{  r  )rd   r{  s     rh   rï   z#RTDETRDetectionModel.init_criterionû  s   € åEá" d§g¡g°tÔ<Ð<rj   c                 ó„  — t        | d«      s| j                  «       | _        |d   }|j                  d   }|d   }t	        |«      D �cg c]#  }||k(  j                  «       j                  «       ‘Œ% }}|d   j                  |j                  t        j                  ¬«      j                  d«      |d   j                  |j                  ¬	«      |j                  |j                  t        j                  ¬«      j                  d«      |d
œ}|€| j                  ||¬«      }| j                  r|n|d   \  }	}
}}}|€d\  }}n<t        j                  |	|d   d¬«      \  }}	t        j                  |
|d   d¬«      \  }}
t        j                  |j!                  d«      |	g«      }	t        j                  |j!                  d«      |
g«      }
| j                  |	|
f||||¬«      }t        |j#                  «       «      t        j$                  dD �cg c]  }||   j'                  «       ‘Œ c}|j                  ¬	«      fS c c}w c c}w )aJ  Compute the loss for the given batch of data.

        Args:
            batch (dict): Dictionary containing image and label data.
            preds (tuple, optional): Precomputed model predictions.

        Returns:
            (torch.Tensor): Total loss value.
            (torch.Tensor): Main three losses in a tensor.
        rí   rî   r   Ú	batch_idxr:  )Údtypers   Úbboxes©Údevice)r:  r�  r  Ú	gt_groups)rñ   rw   r]  Údn_num_splitr™   rx   )Ú	dn_bboxesÚ	dn_scoresÚdn_meta)Ú	loss_giouÚ
loss_classÚ	loss_bbox)r³   rï   rí   rÛ   r¦   r©   ÚitemÚtorƒ  r…   ÚlongÚviewrc   r  r5  r‹   Ú	unsqueezeÚvaluesÚ	as_tensorÚdetach)rd   rñ   rò   rî   Úbsr  r‚   r„  ÚtargetsÚ
dec_bboxesÚ
dec_scoresÚ
enc_bboxesÚ
enc_scoresrˆ  r†  r‡  rb   rÀ   s                     rh   rb   zRTDETRDetectionModel.loss  s  € ô �t˜[Ô)Ø!×0Ñ0Ó2ˆDŒNà�E‰lˆà�Y‰Y�q‰\ˆØ˜+Ñ&ˆ	Ü<AÀ"»IÖF°q�i 1‘n×)Ñ)Ó+×0Ñ0Õ2ÐFˆ	ÐFà˜‘<—?‘? 3§:¡:´U·Z±Z�?Ó@×EÑEÀbÓIØ˜H‘o×(Ñ(°·
±
Ð(Ó;Ø"Ÿ™ c§j¡j¼¿
¹
˜ÓC×HÑHÈÓLØ"ñ	
ˆð ˆ=Ø—L‘L ¨G�LÓ4ˆEØKOÏ=Ê=Á%Ð^cÐdeÑ^fÑ?ˆ
�J 
¨J¸Øˆ?Ø#-Ñ ˆI‘yä$)§K¡K°
¸GÀNÑ<SÐYZÔ$[Ñ!ˆI�zÜ$)§K¡K°
¸GÀNÑ<SÐYZÔ$[Ñ!ˆI�zä—Y‘Y 
× 4Ñ 4°QÓ 7¸ÐDÓEˆ
Ü—Y‘Y 
× 4Ñ 4°QÓ 7¸ÐDÓEˆ
à�~‰~Ø˜Ð$ g¸ÈiÐahð ó 
ˆô �4—;‘;“=Ó!¤5§?¡?Ø'OÖP !ˆT�!‰W�^‰^ÕÒPÐY\×YcÑYcô$
ð 
ð 	
ùò1 Gùò2 Qs   Á(H8È
H=
c                 óÄ  — g g g }	}}|�t        |«      ndh}t        |«      }
| j                  dd D �]n  }|j                  dk7  rMt	        |j                  t
        «      r||j                     n#|j                  D �cg c]  }|dk(  r|n||   ‘Œ c}}|r| j                  |||«        ||«      }|j                  |j                  | j                  v r|nd«       |r#t        ||j                  |j                  |¬«       |j                  |v sŒÜ|	j                  t        j                  j                  j                  |d«      j!                  d«      j!                  d«      «       |j                  |
k(  s�ŒDt        j"                  t        j$                  |	d«      d¬«      c S  | j                  d   } ||j                  D �cg c]  }||   ‘Œ	 c}|«      }|S c c}w c c}w )aB  Perform a forward pass through the model.

        Args:
            x (torch.Tensor): The input tensor.
            profile (bool): If True, profile the computation time for each layer.
            visualize (bool): If True, save feature maps for visualization.
            batch (dict, optional): Ground truth data for evaluation.
            augment (bool): If True, perform data augmentation during inference.
            embed (list, optional): A list of layer indices to return embeddings from.

        Returns:
            (torch.Tensor): Model's output tensor.
        Nrs   rt   rv   rw   r   rx   rz   )rd   re   rn   ro   rñ   rp   rq   rŒ   r�   rŽ   r�   r�   r‘   r&  s                 rh   rc   zRTDETRDetectionModel.predict/  s’  € ð   Bˆzˆ2ˆØ$)Ð$5”	˜%Ô ¸B¸4ˆÜ�e“*ˆØ—‘˜C˜R�ó 	IˆAØ�s‰s�bŠyÜ(¨¯©¬cÔ2�A�a—c‘c’FÐYZ×Y\ÑY\Ö8]ÐTU¸aÀ2ºg¹È1ÈQÉ4Ñ9OÒ8]�ÙØ×'Ñ'¨¨1¨bÔ1Ù�!“ˆAØ�H‰H˜!Ÿ#™# §¡Ñ*‘Q°Ô5ÙÜ% a¨¯©°·±¸yÕIØ�s‰s�eŠ|Ø×!Ñ!¤%§(¡(×"5Ñ"5×"IÑ"IÈ!ÈVÓ"T×"\Ñ"\Ð]_Ó"`×"hÑ"hÐikÓ"lÔmØ—3‘3˜'”>Ü Ÿ<™<¬¯	©	°*¸aÓ(@ÀaÔHÒHð	Ið �z‰z˜"‰~ˆÙ §¡Ö'˜1�!�A“$Ò'¨Ó/ˆØˆùò 9^ùò (s   Á;GÇG)zrtdetr-l.yamlr(  NTrÄ   ©FFNFN)
r•   r÷   rø   rù   r  rÎ   rï   rb   rc   rú   rû   s   @rh   rv  rv  Ê  s#   ø„ ñõ,	Aôò=ó,
÷\ rj   rv  c                   óD   ‡ — e Zd ZdZdˆ fd„	Zdd„Zdd„Zd	d„Zd
d„Zˆ xZ	S )Ú
WorldModelap  YOLOv8 World Model.

    This class implements the YOLOv8 World model for open-vocabulary object detection, supporting text-based class
    specification and CLIP model integration for zero-shot detection capabilities.

    Attributes:
        txt_feats (torch.Tensor): Text feature embeddings for classes.
        clip_model (torch.nn.Module): CLIP model for text encoding.

    Methods:
        __init__: Initialize YOLOv8 world model.
        set_classes: Set classes for offline inference.
        get_text_pe: Get text positional embeddings.
        predict: Perform forward pass with text features.
        loss: Compute loss with text features.

    Examples:
        Initialize a world model
        >>> model = WorldModel("yolov8s-world.yaml", ch=3, nc=80)
        >>> model.set_classes(["person", "car", "bicycle"])
        >>> results = model.predict(image_tensor)
    c                 óz   •— t        j                  d|xs dd«      | _        d| _        t        ‰| �  ||||¬«       y)aG  Initialize YOLOv8 world model with given config and parameters.

        Args:
            cfg (str | dict): Model configuration file path or dictionary.
            ch (int): Number of input channels.
            nc (int, optional): Number of classes.
            verbose (bool): Whether to display model information.
        rw   éP   é   NrL  )r…   ÚrandnÚ	txt_featsÚ
clip_modelrÍ   r  rN  s        €rh   r  zWorldModel.__init__j  s:   ø€ ô Ÿ™ Q¨ª¨b°#Ó6ˆŒØˆŒÜ‰Ñ˜S R¨B¸ÐÕ@rj   c                 óp   — | j                  |||¬«      | _        t        |«      | j                  d   _        y)a$  Set classes in advance so that model could do offline-inference without clip model.

        Args:
            text (list[str]): List of class names.
            batch (int): Batch size for processing text tokens.
            cache_clip_model (bool): Whether to cache the CLIP model.
        )rñ   Úcache_clip_modelrs   N)Úget_text_per¢  rÚ   r}   r  )rd   Útextrñ   r¥  s       rh   Úset_classeszWorldModel.set_classesw  s2   € ð ×)Ñ)¨$°eÐN^Ð)Ó_ˆŒÜ ›Iˆ�
‰
�2‰Õrj   c                 ó  — ddl m} t        | j                  j	                  «       «      j
                  }t        | dd«      s|r |d|¬«      | _        |r| j                  n	 |d|¬«      }|j                  |«      }|j                  |«      D �cg c]!  }|j                  |«      j                  «       ‘Œ# }	}t        |	«      dk(  r|	d   nt        j                  |	d¬«      }	|	j                  d	t        |«      |	j                   d	   «      S c c}w )
aO  Get text positional embeddings using the CLIP model.

        Args:
            text (list[str]): List of class names.
            batch (int): Batch size for processing text tokens.
            cache_clip_model (bool): Whether to cache the CLIP model.

        Returns:
            (torch.Tensor): Text positional embeddings.
        r   ©Úbuild_text_modelr£  Nzclip:ViT-B/32r‚  rw   rx   rs   )Úultralytics.nn.text_modelr«  Únextr}   Ú
parametersrƒ  rº   r£  Útokenizer5  Úencode_textr“  rÚ   r…   r‹   ÚreshaperÛ   )
rd   r§  rñ   r¥  r«  rƒ  r}   Ú
text_tokenÚtokenr¢  s
             rh   r¦  zWorldModel.get_text_pe‚  sâ   € õ 	?ä�d—j‘j×+Ñ+Ó-Ó.×5Ñ5ˆÜ�t˜\¨4Ô0Ñ5Eá.¨ÀvÔNˆDŒOÙ#3�—’Ñ9IÈ/ÐbhÔ9iˆØ—^‘^ DÓ)ˆ
ØDN×DTÑDTÐUZÓD[Ö\¸5�U×&Ñ& uÓ-×4Ñ4Õ6Ð\ˆ	Ð\Ü$'¨	£N°aÒ$7�I˜a’L¼U¿Y¹YÀyÐVWÔ=Xˆ	Ø× Ñ  ¤S¨£Y°	·±ÀÑ0CÓDÐDùò ]s   Â&D	c                 ó&  — |€| j                   n|j                  |j                  |j                  ¬«      }|j                  d   |j                  d   k7  s| j
                  d   j                  r |j                  |j                  d   dd«      }|j                  «       }g g g }
}	}|�t        |«      ndh}t        |«      }| j
                  D �]½  }|j                  dk7  rMt        |j                  t        «      r||j                     n#|j                  D �cg c]  }|dk(  r|n||   ‘Œ c}}|r| j                  |||	«       t        |t        «      r
 |||«      }n<t        |t         «      r
 |||«      }n"t        |t"        «      r
 |||«      }n ||«      }|j%                  |j&                  | j(                  v r|nd«       |r#t+        ||j,                  |j&                  |¬«       |j&                  |v s�Œ+|
j%                  t.        j0                  j2                  j5                  |d«      j7                  d«      j7                  d«      «       |j&                  |k(  s�Œ“t/        j8                  t/        j:                  |
d«      d¬«      c S  |S c c}w )	aU  Perform a forward pass through the model.

        Args:
            x (torch.Tensor): The input tensor.
            profile (bool): If True, profile the computation time for each layer.
            visualize (bool): If True, save feature maps for visualization.
            txt_feats (torch.Tensor, optional): The text features, use it if it's given.
            augment (bool): If True, perform data augmentation during inference.
            embed (list, optional): A list of layer indices to return embeddings from.

        Returns:
            (torch.Tensor): Model's output tensor.
        N©rƒ  r€  r   rs   rt   rv   rw   rx   )r¢  r�  rƒ  r€  rÛ   r}   ÚexportÚexpandÚcloner{   r|   r~   r`   r   r€   r   r=   r.   r�   r‚   rƒ   rT   r„   r…   r†   r‡   rˆ   r‰   rŠ   r‹   )rd   re   rn   ro   r¢  rp   rq   Úori_txt_featsrŒ   r�   rŽ   r�   r�   r‘   s                 rh   rc   zWorldModel.predict™  s  € ð (1Ð'8�T—^’^¸i×KÑKÐST×S[ÑS[Ðcd×cjÑcjÐKÓkˆ	Ø�?‰?˜1Ñ §¡¨¡Ò+¨t¯z©z¸"©~×/DÒ/DØ!×(Ñ(¨¯©°©°R¸Ó<ˆIØ!Ÿ™Ó)ˆØ  Bˆzˆ2ˆØ$)Ð$5”	˜%Ô ¸B¸4ˆÜ�e“*ˆØ—‘ó 	IˆAØ�s‰s�bŠyÜ(¨¯©¬cÔ2�A�a—c‘c’FÐYZ×Y\ÑY\Ö8]ÐTU¸aÀ2ºg¹È1ÈQÉ4Ñ9OÒ8]�ÙØ×'Ñ'¨¨1¨bÔ1Ü˜!œWÔ%Ù�a˜“O‘Ü˜Aœ{Ô+Ù�a˜Ó'‘Ü˜AÔ/Ô0Ù˜a ›O‘	á�a“D�à�H‰H˜!Ÿ#™# §¡Ñ*‘Q°Ô5ÙÜ% a¨¯©°·±¸yÕIØ�s‰s�e‹|Ø×!Ñ!¤%§(¡(×"5Ñ"5×"IÑ"IÈ!ÈVÓ"T×"\Ñ"\Ð]_Ó"`×"hÑ"hÐikÓ"lÔmØ—3‘3˜'”>Ü Ÿ<™<¬¯	©	°*¸aÓ(@ÀaÔHÒHð)	Ið* ˆùò' 9^s   ÄJc                 óž   — t        | d«      s| j                  «       | _        |€| j                  |d   |d   ¬«      }| j                  ||«      S )rì   rí   rî   r¢  )r¢  )r³   rï   rí   ri   rð   s      rh   rb   zWorldModel.lossÅ  sO   € ô �t˜[Ô)Ø!×0Ñ0Ó2ˆDŒNàˆ=Ø—L‘L  u¡¸¸{Ñ9K�LÓLˆEØ�~‰~˜e UÓ+Ð+rj   )zyolov8s-world.yamlr(  NT)rŸ  Tr›  rÄ   )
r•   r÷   rø   rù   r  r¨  r¦  rc   rb   rú   rû   s   @rh   r�  r�  R  s$   ø„ ñõ.Aó	&óEó.*÷X,rj   r�  c                   ó„   ‡ — e Zd ZdZdˆ fd„	Z e«       dd„«       Z e«       d„ «       Zd„ Zd„ Z	d„ Z
d„ Z	 dd	„Zdd
„Zˆ xZS )Ú
YOLOEModelaÝ  YOLOE detection model.

    This class implements the YOLOE architecture for efficient object detection with text and visual prompts, supporting
    both prompt-based and prompt-free inference modes.

    Attributes:
        pe (torch.Tensor): Prompt embeddings for classes.
        clip_model (torch.nn.Module): CLIP model for text encoding.

    Methods:
        __init__: Initialize YOLOE model.
        get_text_pe: Get text positional embeddings.
        get_visual_pe: Get visual embeddings.
        set_vocab: Set vocabulary for prompt-free model.
        get_vocab: Get fused vocabulary layer.
        set_classes: Set classes for offline inference.
        get_cls_pe: Get class positional embeddings.
        predict: Perform forward pass with prompts.
        loss: Compute loss with prompts.

    Examples:
        Initialize a YOLOE model
        >>> model = YOLOEModel("yoloe-v8s.yaml", ch=3, nc=80)
        >>> results = model.predict(image_tensor, tpe=text_embeddings)
    c                 ón   •— t         ‰| �  ||||¬«       | j                  j                  dd«      | _        y)a@  Initialize YOLOE model with given config and parameters.

        Args:
            cfg (str | dict): Model configuration file path or dictionary.
            ch (int): Number of input channels.
            nc (int, optional): Number of classes.
            verbose (bool): Whether to display model information.
        rL  Ú
text_modelúmobileclip:bltN)rÍ   r  r  r  r¾  rN  s        €rh   r  zYOLOEModel.__init__ï  s2   ø€ ô 	‰Ñ˜S R¨B¸ÐÔ@ØŸ)™)Ÿ-™-¨Ð6FÓGˆ�rj   c                 ó´  — ddl m} t        | j                  j	                  «       «      j
                  }t        | dd«      s|r |t        | dd«      |¬«      | _        |r| j                  n |t        | dd«      |¬«      }|j                  |«      }|j                  |«      D �	cg c]!  }	|j                  |	«      j                  «       ‘Œ# }
}	t        |
«      dk(  r|
d   nt        j                  |
d¬	«      }
|
j                  d
t        |«      |
j                   d
   «      }
|r|
S | j                  d
   }t#        |t$        «      sJ ‚|j'                  |
«      S c c}	w )a¶  Get text positional embeddings using the CLIP model.

        Args:
            text (list[str]): List of class names.
            batch (int): Batch size for processing text tokens.
            cache_clip_model (bool): Whether to cache the CLIP model.
            without_reprta (bool): Whether to return text embeddings without reprta module processing.

        Returns:
            (torch.Tensor): Text positional embeddings.
        r   rª  r£  Nr¾  r¿  r‚  rw   rx   rs   )r¬  r«  r­  r}   r®  rƒ  rº   r£  r¯  r5  r°  r“  rÚ   r…   r‹   r±  rÛ   r`   r>   Úget_tpe)rd   r§  rñ   r¥  Úwithout_reprtar«  rƒ  r}   r²  r³  r¢  r&  s               rh   r¦  zYOLOEModel.get_text_peû  s5  € õ 	?ä�d—j‘j×+Ñ+Ó-Ó.×5Ñ5ˆÜ�t˜\¨4Ô0Ñ5Eá.¬w°t¸\ÐK[Ó/\ÐekÔlˆDŒOñ  ð �OŠOá!¤'¨$°Ð>NÓ"OÐX^Ô_ð 	ð
 —^‘^ DÓ)ˆ
ØDN×DTÑDTÐUZÓD[Ö\¸5�U×&Ñ& uÓ-×4Ñ4Õ6Ð\ˆ	Ð\Ü$'¨	£N°aÒ$7�I˜a’L¼U¿Y¹YÀyÐVWÔ=Xˆ	Ø×%Ñ% b¬#¨d«)°Y·_±_ÀRÑ5HÓIˆ	ÙØÐà�z‰z˜"‰~ˆÜ˜$¤Ô,Ð,Ð,Ø�|‰|˜IÓ&Ð&ùò ]s   Â$&Ec                 ó   —  | ||d¬«      S )zíGet visual positional embeddings.

        Args:
            img (torch.Tensor): Input image tensor.
            visual (torch.Tensor): Visual features.

        Returns:
            (torch.Tensor): Visual positional embeddings.
        T)ÚvpeÚ
return_vper¾   )rd   rî   Úvisuals      rh   Úget_visual_pezYOLOEModel.get_visual_pe  s   € ñ �C˜V°Ô5Ð5rj   c           
      ó<  — | j                   rJ ‚| j                  d   }t        |t        «      sJ ‚t	        | j                  «       «      j                  } | t        j                  dd| j                  d   | j                  d   «      j                  |«      «       t        |d|j                  «      }t        |d|j                  «      }t        j                  d„ t!        t#        |||«      «      D «       «      | j                  d   _        t#        |j                  |j                  «      D ]C  \  }}t        |t        j&                  «      sJ ‚t        |t        j&                  «      sJ ‚|d= |d= ŒE t)        |«      | j                  d   _        t-        |«      | _        y)	z²Set vocabulary for the prompt-free model.

        Args:
            vocab (nn.ModuleList): List of vocabulary items.
            names (list[str]): List of class names.
        rs   rw   r(  rË   Úone2one_cv3Úone2one_cv2c              3   óZ   K  — | ]#  \  }\  }}}t        ||d    |d    |dk7  ¬«      –— Œ% y­w)rs   r™   )ÚenabledN)r0   )r¿   r‚   r:  ÚpfÚlocs        rh   rÂ   z'YOLOEModel.set_vocab.<locals>.<genexpr>?  s9   è ø€ ò ,
Ù?P¸qÁ.À3ÈÈCŒH�S˜"˜R™& # b¡'°1¸±6×:Ð:ñ,
ùs   ‚)+N)r  r}   r`   r>   r­  r®  rƒ  r…   Úemptyrf   r�  rº   Úcv3Úcv2r†   Ú
ModuleListÚ	enumerater*  Úlrpcrk  rÚ   r  r   r  )	rd   Úvocabr  r&  rƒ  rÐ  rÑ  Úloc_headÚcls_heads	            rh   Ú	set_vocabzYOLOEModel.set_vocab,  sV  € ð —=’=Ð Ð Ø�z‰z˜"‰~ˆÜ˜$¤Ô,Ð,Ð,ô �d—o‘oÓ'Ó(×/Ñ/ˆÙŒU�[‰[˜˜A˜tŸy™y¨Ñ1°4·9±9¸WÑ3EÓF×IÑIÈ&ÓQÔRä�d˜M¨4¯8©8Ó4ˆÜ�d˜M¨4¯8©8Ó4ˆô !Ÿm™mñ ,
ÜT]Ô^aÐbgÐilÐnqÓ^rÓTsô,
ó 
ˆ�
‰
�2‰Ôô #& d§h¡h°·±Ó"9ò 	ÑˆH�hÜ˜h¬¯©Ô6Ð6Ð6Ü˜h¬¯©Ô6Ð6Ð6Ø˜�Ø˜‘ð		ô
   ›Jˆ�
‰
�2‰ÔÜ& uÓ-ˆ�
rj   c                 ó8  — | j                   rJ ‚| j                  d   }t        |t        «      sJ ‚|j                  rJ ‚| j                  |«      }| j                  ||«       t        | j                  j                  «       «      j                  }|j                  | j                  j                  |«      «       t        |d|j                  «      }t        j                   «       }|D ]2  }t        |t        j"                  «      sJ ‚|j%                  |d   «       Œ4 |S )zÁGet fused vocabulary layer from the model.

        Args:
            names (list[str]): List of class names.

        Returns:
            (nn.ModuleList): List of vocabulary modules.
        rs   rÉ  )r  r}   r`   r>   r±   r¦  r¨  r­  r®  rƒ  r¹   Úper�  rº   rÐ  r†   rÒ  rk  r�   )rd   r  r&  Útperƒ  rÐ  rÕ  r×  s           rh   Ú	get_vocabzYOLOEModel.get_vocabJ  sè   € ð —=’=Ð Ð Ø�z‰z˜"‰~ˆÜ˜$¤Ô,Ð,Ð,Ø—=’=Ð Ð à×Ñ˜uÓ%ˆØ×Ñ˜ Ô$Ü�d—j‘j×+Ñ+Ó-Ó.×5Ñ5ˆØ�	‰	�$—'‘'—*‘*˜VÓ$Ô%ä�d˜M¨4¯8©8Ó4ˆÜ—‘“ˆØò 	'ˆHÜ˜h¬¯©Ô6Ð6Ð6Ø�L‰L˜ "™Õ&ð	'ð ˆrj   c                 óÎ   — t        | j                  d   d«      rJ d«       ‚|j                  dk(  sJ ‚|| _        t	        |«      | j                  d   _        t        |«      | _        y)zÙSet classes in advance so that model could do offline-inference without clip model.

        Args:
            names (list[str]): List of class names.
            embeddings (torch.Tensor): Embeddings tensor.
        rs   rÔ  z^Prompt-free model does not support setting classes. Please try with Text/Visual prompt models.r(  N)r³   r}   ÚndimrÚ  rÚ   r  r   r  )rd   r  rŽ   s      rh   r¨  zYOLOEModel.set_classesd  sa   € ô ˜4Ÿ:™: b™>¨6Ô2ð 	
Øló	
Ð2ð �‰ !Ò#Ð#Ð#ØˆŒÜ ›Jˆ�
‰
�2‰ÔÜ& uÓ-ˆ�
rj   c                 ó*  — g }|�"|j                   dk(  sJ ‚|j                  |«       |�"|j                   dk(  sJ ‚|j                  |«       |s1|j                  t        | dt        j                  ddd«      «      «       t        j
                  |d¬«      S )a  Get class positional embeddings.

        Args:
            tpe (torch.Tensor | None): Text positional embeddings.
            vpe (torch.Tensor | None): Visual positional embeddings.

        Returns:
            (torch.Tensor): Class positional embeddings.
        r(  rÚ  rw   rŸ  r   rx   )rÞ  r�   rº   r…   r  r‹   )rd   rÛ  rÄ  Úall_pes       rh   Ú
get_cls_pezYOLOEModel.get_cls_pes  s�   € ð ˆØˆ?Ø—8‘8˜q’=Ð �=Ø�M‰M˜#ÔØˆ?Ø—8‘8˜q’=Ð �=Ø�M‰M˜#ÔÙØ�M‰Mœ' $¨¬e¯k©k¸!¸RÀÓ.EÓFÔGÜ�y‰y˜ QÔ'Ð'rj   c	                 ó  — g g g }}
}	|j                   d   }|�t        |«      ndh}t        |«      }| j                  D �];  }|j                  dk7  rMt        |j                  t        «      r|	|j                     n#|j                  D �cg c]  }|dk(  r|n|	|   ‘Œ c}}|r| j                  |||
«       t        |t        «      r¼|�|j                  ||«      nd}|r|€J ‚| j                  rJ ‚|c S | j                  |j                  |«      |«      j                  |d   j                  |d   j                  ¬«      }|j                   d   |k7  s|j                   r|j#                  |dd«      }|j%                  |«        ||«      }|	j%                  |j&                  | j(                  v r|nd«       |r#t+        ||j,                  |j&                  |¬«       |j&                  |v s�Œ©|j%                  t.        j0                  j2                  j5                  |d«      j7                  d«      j7                  d«      «       |j&                  |k(  s�Œt/        j8                  t/        j:                  |d«      d¬«      c S  |S c c}w )	a×  Perform a forward pass through the model.

        Args:
            x (torch.Tensor): The input tensor.
            profile (bool): If True, profile the computation time for each layer.
            visualize (bool): If True, save feature maps for visualization.
            tpe (torch.Tensor, optional): Text positional embeddings.
            augment (bool): If True, perform data augmentation during inference.
            embed (list, optional): A list of layer indices to return embeddings from.
            vpe (torch.Tensor, optional): Visual positional embeddings.
            return_vpe (bool): If True, return visual positional embeddings.

        Returns:
            (torch.Tensor): Model's output tensor.
        r   Nrs   rµ  rt   rv   rw   rx   )rÛ   r{   r|   r}   r~   r`   r   r€   r>   Úget_vper  rá  rÁ  r�  rƒ  r€  r¶  r·  r�   r‚   rƒ   rT   r„   r…   r†   r‡   rˆ   r‰   rŠ   r‹   )rd   re   rn   ro   rÛ  rp   rq   rÄ  rÅ  rŒ   r�   rŽ   Úbr�   r�   r‘   Úcls_pes                    rh   rc   zYOLOEModel.predictˆ  s  € ð$   Bˆzˆ2ˆØ�G‰G�A‰JˆØ$)Ð$5”	˜%Ô ¸B¸4ˆÜ�e“*ˆØ—‘ó 	IˆAØ�s‰s�bŠyÜ(¨¯©¬cÔ2�A�a—c‘c’FÐYZ×Y\ÑY\Ö8]ÐTU¸aÀ2ºg¹È1ÈQÉ4Ñ9OÒ8]�ÙØ×'Ñ'¨¨1¨bÔ1Ü˜!œ[Ô)Ø+.¨?�a—i‘i  3Ô'À�ÙØ˜?Ð*˜?Ø#Ÿ}š}Ð,Ð,Ø’JØŸ™¨¯©°3«¸Ó=×@Ñ@ÈÈ!ÉÏÉÐ[\Ð]^Ñ[_×[eÑ[eÐ@Óf�Ø—<‘< ‘? aÒ'¨1¯8ª8Ø#Ÿ]™]¨1¨b°"Ó5�FØ—‘˜Ô Ù�!“ˆAà�H‰H˜!Ÿ#™# §¡Ñ*‘Q°Ô5ÙÜ% a¨¯©°·±¸yÕIØ�s‰s�e‹|Ø×!Ñ!¤%§(¡(×"5Ñ"5×"IÑ"IÈ!ÈVÓ"T×"\Ñ"\Ð]_Ó"`×"hÑ"hÐikÓ"lÔmØ—3‘3˜'”>Ü Ÿ<™<¬¯	©	°*¸aÓ(@ÀaÔHÒHð/	Ið0 ˆùò- 9^s   ÂI>c                 ó`  — t        | d«      sRddlm} |j                  dd«      du}|r!t	        | dd«      rt        | |«      n || «      n| j                  «       | _        |€=| j                  |d   d|v rdn|j                  d	d«      |j                  dd«      ¬
«      }| j                  ||«      S )rì   rí   r   )ÚTVPDetectLossÚvisualsNr°   Frî   r¢  ©rÛ  rÄ  )	r³   Úultralytics.utils.lossrç  r  rº   rK   rï   rí   ri   )rd   rñ   rò   rç  Úvisual_prompts        rh   rb   zYOLOEModel.loss¸  s·   € ô �t˜[Ô)Ý<à!ŸI™I i°Ó6¸dÐBˆMñ !ô 29¸¸yÈ%Ô1P”˜˜}Ô-ÑVcÐdhÔVià×(Ñ(Ó*ð ŒNð
 ˆ=Ø—L‘LØ�e‘Ø%¨Ñ.‘D°E·I±I¸kÈ4Ó4PØ—I‘I˜i¨Ó.ð !ó ˆEð
 �~‰~˜e UÓ+Ð+rj   )zyoloe-v8s.yamlr(  NT)rŸ  FF)FFNFNNFrÄ   )r•   r÷   rø   rù   r  r[   r¦  rÇ  rØ  rÜ  r¨  rá  rc   rb   rú   rû   s   @rh   r¼  r¼  Ô  sc   ø„ ñõ4
Hñ Óò!'ó ð!'ñF Óñ
6ó ð
6ò.ò<ò4.ò(ð, lqó.÷`,rj   r¼  c                   ó,   ‡ — e Zd ZdZdˆ fd„	Zdd„Zˆ xZS )ÚYOLOESegModela+  YOLOE segmentation model.

    This class extends YOLOEModel to handle instance segmentation tasks with text and visual prompts, providing
    specialized loss computation for pixel-level object detection and segmentation.

    Methods:
        __init__: Initialize YOLOE segmentation model.
        loss: Compute loss with prompts for segmentation.

    Examples:
        Initialize a YOLOE segmentation model
        >>> model = YOLOESegModel("yoloe-v8s-seg.yaml", ch=3, nc=80)
        >>> results = model.predict(image_tensor, tpe=text_embeddings)
    c                 ó,   •— t         ‰| �  ||||¬«       y)aM  Initialize YOLOE segmentation model with given config and parameters.

        Args:
            cfg (str | dict): Model configuration file path or dictionary.
            ch (int): Number of input channels.
            nc (int, optional): Number of classes.
            verbose (bool): Whether to display model information.
        rL  NrM  rN  s        €rh   r  zYOLOESegModel.__init__á  rO  rj   c                 óT  — t        | d«      sRddlm} |j                  dd«      du}|r!t	        | dd«      rt        | |«      n || «      n| j                  «       | _        |€7| j                  |d   |j                  d	d«      |j                  dd«      ¬
«      }| j                  ||«      S )rì   rí   r   )ÚTVPSegmentLossrè  Nr°   Frî   r¢  ré  )	r³   rê  rð  r  rº   rK   rï   rí   ri   )rd   rñ   rò   rð  rë  s        rh   rb   zYOLOESegModel.lossì  s©   € ô �t˜[Ô)Ý=à!ŸI™I i°Ó6¸dÐBˆMñ !ô 3:¸$À	È5Ô2Q”˜˜~Ô.ÑWeÐfjÔWkà×(Ñ(Ó*ð ŒNð ˆ=Ø—L‘L  u¡°5·9±9¸[È$Ó3OÐUZ×U^ÑU^Ð_hÐjnÓUo�LÓpˆEØ�~‰~˜e UÓ+Ð+rj   )zyoloe-v8s-seg.yamlr(  NTrÄ   )r•   r÷   rø   rù   r  rb   rú   rû   s   @rh   rí  rí  Ñ  s   ø„ ñõ	A÷,rj   rí  c                   ó*   ‡ — e Zd ZdZˆ fd„Zdd„Zˆ xZS )ÚEnsemblea  Ensemble of models.

    This class allows combining multiple YOLO models into an ensemble for improved performance through model averaging
    or other ensemble techniques.

    Methods:
        __init__: Initialize an ensemble of models.
        forward: Generate predictions from all models in the ensemble.

    Examples:
        Create an ensemble of models
        >>> ensemble = Ensemble()
        >>> ensemble.append(model1)
        >>> ensemble.append(model2)
        >>> results = ensemble(image_tensor)
    c                 ó"   •— t         ‰| �  «        y)z!Initialize an ensemble of models.NrM  )rd   r”   s    €rh   r  zEnsemble.__init__  s   ø€ ä‰ÑÕrj   c           	      óv   — | D �cg c]  } |||||«      d   ‘Œ }}t        j                  |d«      }|dfS c c}w )aÏ  Run ensemble forward pass and concatenate predictions from all models.

        Args:
            x (torch.Tensor): Input tensor.
            augment (bool): Whether to augment the input.
            profile (bool): Whether to profile the model.
            visualize (bool): Whether to visualize the features.

        Returns:
            (torch.Tensor): Concatenated predictions from all models.
            (None): Always None for ensemble inference.
        r   r™   N)r…   r‹   )rd   re   rp   rn   ro   ÚmodulerŒ   s          rh   ri   zEnsemble.forward  sI   € ð FJÖJ¸6‰V�A�w ¨Ó3°AÓ6ÐJˆÐJô �I‰I�a˜‹OˆØ�$ˆwˆùò	 Ks   …6)FFF)r•   r÷   rø   rù   r  ri   rú   rû   s   @rh   rò  rò    s   ø„ ñô"÷rj   rò  c           
   #   óô  K  — | €i } |€i }ddl }ddlm} 	 |j                  «       D ]R  \  }}|j	                  dd«      \  }}|j	                  dd«      \  }}	t         ||«      |t         ||«      |	«      «       ŒT | j                  «       D ]  \  }} ||«      |j                  |<   Œ d–— | D ]  }||j                  v sŒ|j                  |= Œ  y# | D ]  }||j                  v sŒ|j                  |= Œ  w xY w­w)a‹  Context manager for temporarily adding or modifying modules in Python's module cache (`sys.modules`).

    This function can be used to change the module paths during runtime. It's useful when refactoring code, where you've
    moved a module from one location to another, but you still want to support the old import paths for backwards
    compatibility.

    Args:
        modules (dict, optional): A dictionary mapping old module paths to new module paths.
        attributes (dict, optional): A dictionary mapping old module attributes to new module attributes.

    Examples:
        >>> with temporary_modules({"old.module": "new.module"}, {"old.module.attribute": "new.module.attribute"}):
        >>> import old.module  # this will now import new.module
        >>> from old.module import attribute  # this will now import new.module.attribute

    Notes:
        The changes are only in effect inside the context manager and are undone once the context manager exits.
        Be aware that directly manipulating `sys.modules` can lead to unpredictable results, especially in larger
        applications or libraries. Use this function with caution.
    Nr   )Úimport_moduleú.rw   )ÚsysÚ	importlibr÷  rÇ   Úrsplitr%  rº   r²   )
r²   Ú
attributesrù  r÷  ÚoldÚnewÚ
old_moduleÚold_attrÚ
new_moduleÚnew_attrs
             rh   Útemporary_modulesr  /  s  è ø€ ð, €ØˆØÐØˆ
ÛÝ'ð%à"×(Ñ(Ó*ò 	g‰HˆC�Ø#&§:¡:¨c°1Ó#5Ñ ˆJ˜Ø#&§:¡:¨c°1Ó#5Ñ ˆJ˜Ü‘M *Ó-¨x¼ÁÈzÓAZÐ\dÓ9eÕfð	gð  Ÿ™›ò 	2‰HˆC�Ù,¨SÓ1ˆC�K‰K˜Òð	2ó 	ð ò 	%ˆCØ�c—k‘kÒ!Ø—K‘K Ñ$ñ	%ø�7ò 	%ˆCØ�c—k‘kÒ!Ø—K‘K Ñ$ñ	%üs)   ‚C8–BC Â,C8Ã C8ÃC5Ã%C5Ã5C8c                   ó   — e Zd ZdZd„ Zd„ Zy)Ú	SafeClasszAA placeholder class to replace unknown classes during unpickling.c                  ó   — y)z6Initialize SafeClass instance, ignoring all arguments.Nr¾   ©rd   rf   rg   s      rh   r  zSafeClass.__init__b  ó   € àrj   c                  ó   — y)z/Run SafeClass instance, ignoring all arguments.Nr¾   r  s      rh   Ú__call__zSafeClass.__call__f  r  rj   N)r•   r÷   rø   rù   r  r
  r¾   rj   rh   r  r  _  s   „ ÙKòórj   r  c                   ó"   ‡ — e Zd ZdZˆ fd„Zˆ xZS )ÚSafeUnpicklerz>Custom Unpickler that replaces unknown classes with SafeClass.c                 ó<   •— d}||v rt         ‰| �  ||«      S t        S )zêAttempt to find a class, returning SafeClass if not among safe modules.

        Args:
            module (str): Module name.
            name (str): Class name.

        Returns:
            (type): Found class or SafeClass.
        )r…   Úcollectionszcollections.abcÚbuiltinsÚmathÚnumpy)rÍ   Ú
find_classr  )rd   rõ  rq  Úsafe_modulesr”   s       €rh   r  zSafeUnpickler.find_classn  s,   ø€ ð
ˆð �\Ñ!Ü‘7Ñ% f¨dÓ3Ð3äÐrj   )r•   r÷   rø   rù   r  rú   rû   s   @rh   r  r  k  s   ø„ ÙH÷ð rj   r  c                 óŽ  — ddl m} t        | d¬«        || «      }	 t        ddddœd	d
ddœt        rddinddi¥¬«      5  |rKt        j                  d«      }t        |_        d„ |_	        t        |d«      5 }t        ||¬«      }ddd«       nt        |d¬«      }ddd«       t+        t,        «      s't%        j&                  d!| › d"�«       d#|j.                  i}||fS # 1 sw Y   ŒLxY w# 1 sw Y   ŒPxY w# t        $ rÅ}|j                  dk(  rt        t        d| › d�«      «      |‚|j                  dk(  r/t        t        d| › dt!        d«      j"                  › d�«      «      |‚t%        j&                  | › d|j                  › d|j                  › d �«       t)        |j                  «       t        |d¬«      }Y d}~�Œd}~ww xY w)$aã  Attempt to load a PyTorch model with the torch.load() function. If a ModuleNotFoundError is raised, it catches
    the error, logs a warning message, and attempts to install the missing module via the check_requirements()
    function. After installation, the function again attempts to load the model using torch.load().

    Args:
        weight (str | Path): The file path of the PyTorch model.
        safe_only (bool): If True, replace unknown classes with SafeClass during loading.

    Returns:
        (dict): The loaded model checkpoint.
        (str): The loaded filename.

    Examples:
        >>> from ultralytics.nn.tasks import torch_safe_load
        >>> ckpt, file = torch_safe_load("path/to/best.pt", safe_only=True)
    r   )Úattempt_download_assetz.pt)ÚfileÚsuffixzultralytics.utilszultralytics.models.yolozultralytics.data)zultralytics.yolo.utilszultralytics.yolo.v8zultralytics.yolo.dataztorch.nn.Identityz#ultralytics.nn.tasks.DetectionModelz$ultralytics.utils.loss.E2EDetectLoss)z$ultralytics.nn.modules.block.Silencez*ultralytics.nn.tasks.YOLOv10DetectionModelz$ultralytics.utils.loss.v10DetectLosszpathlib.PosixPathzpathlib.WindowsPath)r²   rü  Úsafe_picklec                 ó4   — t        | «      j                  «       S rÄ   )r  rê   )Úfile_objs    rh   ú<lambda>z!torch_safe_load.<locals>.<lambda>³  s   € ´MÀ(Ó4K×4PÑ4PÓ4R€ rj   Úrb)Úpickle_moduleNÚcpu)Úmap_locationÚmodelsu   ERROR â�Œï¸� aw   appears to be an Ultralytics YOLOv5 model originally trained with https://github.com/ultralytics/yolov5.
This model is NOT forwards compatible with YOLOv8 at https://github.com/ultralytics/ultralytics.
Recommend fixes are to train a new model using the latest 'ultralytics' package or to run a command with an official Ultralytics model, i.e. 'yolo predict model=yolo26n.pt'znumpy._corez( requires numpy>=1.26.1, however numpy==r  z is installed.z appears to require 'zK', which is not in Ultralytics requirements.
AutoInstall will run now for 'zÞ' but this feature will be removed in the future.
Recommend fixes are to train a new model using the latest 'ultralytics' package or to run a command with an official Ultralytics model, i.e. 'yolo predict model=yolo26n.pt'z
The file 'z€' appears to be improperly saved or formatted. For optimal results, use model.save('filename.pt') to correctly save YOLO models.r}   )Úultralytics.utils.downloadsr  rI   r  rD   rr  Ú
ModuleTyper  Ú	Unpicklerrê   ÚopenrS   ÚModuleNotFoundErrorrq  Ú	TypeErrorrG   Ú
__import__Ú__version__rC   r“   rH   r`   ra   r}   )ÚweightÚ	safe_onlyr  r  r  r~   ÚckptrD  s           rh   Útorch_safe_loadr,  ‡  s  € õ" Cä�f UÕ+Ù! &Ó)€Dð54Üà*=Ø'@Ø);ñð 9LØ>cØ8^ñ
õ ð )Ð*?Ñ@à/Ð1DÐEð
ô
ñ 	<ñ$ ä#×.Ñ.¨}Ó=�Ü(5�Ô%Ù#R�Ô Ü˜$ Ó%ð D¨Ü% a°{ÔC�D÷Dð Dô " $°UÔ;�÷5	<ôl �dœDÔ!ä�‰Ø˜˜ð !`ð aô	
ð ˜Ÿ™Ð$ˆà�ˆ:Ð÷ODð Dú÷/	<ð 	<ûô8 ò 4Ø�6‰6�XÒÜÜØ# F 8ð ,mð nóóð ðð �V‰V�}Ò$Ü%ÜØ# F 8Ð+SÔT^Ð_fÓTg×TsÑTsÐStð  uCð  Dóóð ð	ô
 	�‰ØˆhÐ+¨A¯F©F¨8ð 4/Ø/0¯v©v¨hð 7eðfô	
ô 	˜1Ÿ6™6Ô"Ü˜$¨UÔ3Žûð14úsH   �#C6 Á 7C*Á7CÂC*ÂC6 ÃC'	Ã#C*Ã*C3Ã/C6 Ã6	GÃ?B:F?Æ?Gc                 ó–  — t        | «      \  }} i t        ¥|j                  di «      ¥}|j                  d«      xs |d   j                  «       }||_        t        | «      |_        t        |dt        |«      «      |_	        t        |d«      st        j                  dg«      |_        |rt        |d«      r|j                  «       n|j                  «       j!                  |«      }|j#                  «       D ]O  }t        |d«      r||_        Œt'        |t        j(                  j*                  «      sŒ<t        |d	«      rŒId
|_        ŒQ ||fS )af  Load single model weights.

    Args:
        weight (str | Path): Model weight path.
        device (torch.device, optional): Device to load model to.
        inplace (bool): Whether to do inplace operations.
        fuse (bool): Whether to fuse model.

    Returns:
        (torch.nn.Module): Loaded model.
        (dict): Model checkpoint dictionary.
    Ú
train_argsÚemar}   ÚtaskrÏ   g      @@r¹   r  Úrecompute_scale_factorN)r,  rB   r  r×   rf   ÚstrÚpt_pathrº   Úguess_model_taskr0  r³   r…   r  rÏ   r¹   r  r�  r²   r  r`   r†   ÚUpsampler1  )r)  rƒ  r  r¹   r+  rf   r}   r�   s           rh   Úload_checkpointr6  Þ  s  € ô # 6Ó*�L€Dˆ&Ø?ÔÐ? 4§8¡8¨L¸"Ó#=Ð?€DØ�X‰X�e‹_Ò-  W¡×4Ñ4Ó6€Eð €E„JÜ˜“K€E„MÜ˜ Ô(8¸Ó(?Ó@€E„JÜ�5˜(Ô#Ü—|‘| T FÓ+ˆŒá!¤g¨e°VÔ&<ˆU�Z‰ZŒ\À%×MÑMÓO×RÑRÐSYÓZ€Eð �]‰]‹_ò ,ˆÜ�1�iÔ ØˆA�IÜ˜œ5Ÿ8™8×,Ñ,Õ-´g¸aÐAYÕ6ZØ'+ˆAÕ$ð	,ð �$ˆ;Ðrj   c                 ó€  ‡ ‡‡‡‡ — ddl }d}t        d«      }ˆ fd„dD «       \  }}}}	‰ j                  dd«      }
ˆ fd	„d
D «       \  }}}‰ j                  d«      }|rF|s;t        t	        |j                  «       «      «      }t        j                  d|› d�«       ||   \  }}}|r9t        |«      t        _
        |r#t        j                  t        d«      › d|› �«       |r)t        j                  ddd›dd›dd›dd›ddd›dd›�«       ‰gŠg g ‰d   }}}t        h t        ’t        ’t        ’t         ’t"        ’t$        ’t&        ’t(        ’t*        ’t,        ’t.        ’t0        ’t2        ’t4        ’t6        ’t8        ’t:        ’t<        ’t>        ’t@        ’tB        ’tD        ’tF        ’tH        ’tJ        ’tL        ’tN        jP                  jR                  ’tT        ’tV        ’tX        ’tZ        ’t\        ’t^        ’t`        ’«      }t        t2        t4        t6        t8        t:        tF        tH        tJ        tL        tV        tX        t*        t^        t,        t`        h«      }tc        ‰ d   ‰ d   z   «      D �]Œ  \  Š\  }}Š Šd ‰ v rte        tN        jP                  ‰ d!d «      n2d"‰ v r"te        tg        d#«      jh                  ‰ dd «      ntk        «       ‰    Š tc        ‰«      D ]e  \  }}tm        |tn        «      sŒtq        jr                  tt        «      5  |tw        «       v rtw        «       |   n|jy                  |«      ‰|<   ddd«       Œg |d$kD  rt{        t}        ||z  «      d$«      n|x}}‰ |v rö‰|   ‰d   }}||k7  rt        t�        ||«      |z  d%«      }‰ tF        u rft        t�        ‰d$   |d&z  «      |z  d%«      ‰d$<   tƒ        ‰d&   d$kD  r+t{        t}        t�        ‰d&   |d&z  d'z  «      «      |z  d$«      n‰d&   «      ‰d&<   ||g‰d$d ¢Š‰ |v r‰j…                  d&|«       d$}‰ t:        u rd(}|d)v rd‰d!<   ‰ t`        u rd(}|d*v r‰j‡                  d+«       ‰ t^        u �r‡d(}�nƒ‰ tˆ        u r
‰|   g‰¢Š�nq‰ t        tŠ        tŒ        h«      v r8‰|   ‰d   ‰d$   }}}|||g‰d&d ¢Š‰ tŒ        u �r8‰j…                  d,|«       d$}�n"‰ tŽ        u r‰d!   r‰d$   n‰d$   d,z  }�n‰ tN        jP                  j�                  u r‰|   gŠ�nâ‰ t’        u rt•        ˆfd-„|D «       «      }�nÄ‰ t        t–        t˜        tš        tœ        tž        t         t¢        t¤        t¦        t¨        tª        h«      v r¢‰j‡                  |
|	|D �cg c]  }‰|   ‘Œ	 c}g«       ‰ tœ        u s‰ t         u s‰ tž        u s‰ t¢        u rt        t�        ‰d&   |«      |z  d%«      ‰d&<   ‰ t–        tš        tœ        tž        t         t¢        t¤        t¦        t¨        tª        h
v ræ|‰ _V        nÞ‰ t®        u r#‰j±                  |D �cg c]  }‰|   ‘Œ	 c}«       n³‰ t²        u r$‰j…                  d$|D �cg c]  }‰|   ‘Œ	 c}«       n‡‰ t´        u r$‰j…                  d$|D �cg c]  }‰|   ‘Œ	 c}«       n[‰ t¶        u r‰d   }‰|   }||g‰d$d ¢Šn?‰ t¸        u r	‰|d      }n.‰ t        tº        t¼        h«      v r‰d   }‰|   }g ‰d$d ¢Šn‰|   }|d$kD  r/tO        jP                  j¾                  ˆˆ fd.„tÁ        |«      D «       Ž n ‰ ‰Ž }to        ‰ «      d%d/ jÃ                  d0d«      }t•        d1„ |jÅ                  «       D «       «      |_c        ‰||c|_d        |_e        |_f        |r2t        j                  ‰d›|d›|d›|jÆ                  d2›d|d›‰d›�«       |j‡                  ˆfd3„tm        |t‚        «      r|gn|D «       «       |j±                  |«       ‰dk(  rg Š‰j±                  |«       �Œ� tO        jP                  j¾                  |Ž tÏ        |«      fS # 1 sw Y   �ŒVxY wc c}w c c}w c c}w c c}w )4aO  Parse a YOLO model.yaml dictionary into a PyTorch model.

    Args:
        d (dict): Model dictionary.
        ch (int): Input channels.
        verbose (bool): Whether to print model details.

    Returns:
        (torch.nn.Sequential): PyTorch model.
        (list): Sorted list of layer indices whose outputs need to be saved.
    r   NTÚinfc              3   ó@   •K  — | ]  }‰j                  |«      –— Œ y ­wrÄ   ©r  ©r¿   re   Úds     €rh   rÂ   zparse_model.<locals>.<genexpr>  s   øè ø€ Ò\¨Q §¡ a§Ñ\ùs   ƒ)r  Ú
activationÚscalesr°   Úreg_maxé   c              3   óB   •K  — | ]  }‰j                  |d «      –— Œ y­w)g      ð?Nr:  r;  s     €rh   rÂ   zparse_model.<locals>.<genexpr>  s   øè ø€ Òh°˜qŸu™u Q¨Ÿ}Ñhùs   ƒ)Údepth_multipleÚwidth_multiplerY  r8  z'no model scale passed. Assuming scale='r$  zactivation:rœ   ú
r  z>3Úfromz>20Únrž   z>10r    rõ  z<45Ú	argumentsz<30rs   rÿ   r&  znn.r(  ztorchvision.ops.Útorchvisionrw   é   r™   r  FÚmlxÚlx)Tg333333ó?r4  c              3   ó(   •K  — | ]	  }‰|   –— Œ y ­wrÄ   r¾   )r¿   re   rè   s     €rh   rÂ   zparse_model.<locals>.<genexpr>�  s   øè ø€ Ò&˜q�R˜•UÑ&ùó   ƒc              3   ó(   •K  — | ]	  } ‰‰Ž –— Œ y ­wrÄ   r¾   )r¿   r­   rf   r�   s     €€rh   rÂ   zparse_model.<locals>.<genexpr>¸  s   øè ø€ Ò">°¡1 d¤8Ñ">ùrM  r  z	__main__.c              3   ó<   K  — | ]  }|j                  «       –— Œ y ­wrÄ   )Únumelr>  s     rh   rÂ   zparse_model.<locals>.<genexpr>º  s   è ø€ Ò7 !�A—G‘G—IÑ7ùs   ‚rŸ   c              3   ó4   •K  — | ]  }|d k7  sŒ	|‰z  –— Œ y­w)rs   Nr¾   )r¿   re   r‚   s     €rh   rÂ   zparse_model.<locals>.<genexpr>¾  s   øè ø€ ÒQ˜aÈÈbË�A˜•EÑQùs   ƒ
Ž
)hÚastr×   r  r­  ÚiterÚkeysrC   r“   r  r#   Údefault_actr§   rF   r{   r!   r%   r+   r   r*   r   r   r   r	   r'   r)   r   r   r   r   r   r5   r   r   r   r   r   r
   r   r   r…   r†   ÚConvTranspose2dr(   r   r3   r   r9   r   r   rÓ  rº   r'  ÚopsÚglobalsr`   r2  Ú
contextlibÚsuppressrc  ÚlocalsÚliteral_evalr|   ÚroundrR   rÜ   r   ÚinsertÚextendr   r-   r,   r7   ÚBatchNorm2dr"   r©   r&   r=   r>   r:   r;   r?   r@   r1   r2   r   r   ÚlegacyrA   r�   r.   r8   r    r   r<   r/   rk  r¦   Úreplacer®  r¨   r‚   r~   r„   Úsorted)!r<  rè   r˜   rR  ra  Úmax_channelsr  Úactr>  r°   r?  ÚdepthÚwidthrY  r8  Úlayersrƒ   rã   Úbase_modulesÚrepeat_modulesr~   rF  r‘   ÚaÚn_râ   Úcmre   Úm_r¬   rf   r‚   r�   s!   ``                            @@@rh   r  r    s©  ü€ ó ð €FÜ˜“<€LÛ\Ð2[Ô\Ñ€BˆˆV�WØ�e‰e�I˜rÓ"€GÛhÐ6gÔhÑ€Eˆ5�)Ø�E‰E�'‹N€EÙÙÜœ˜fŸk™k›mÓ,Ó-ˆEÜ�N‰NÐDÀUÀGÈ2ÐNÔOØ%+¨E¡]Ñ"ˆˆu�lá
Ü ›9ŒÔÙÜ�K‰Kœ8 MÓ2Ð3°1°S°EÐ:Ô;áÜ�‰�b˜˜B˜  s˜|¨C°¨8°H¸S°>ÀÀHÈSÀ>ÐR]Ð^aÐQbÐcÔdØ
ˆ€BØ˜2˜r "™v�"ˆD€FÜð#	
Üð#	
äð#	
ô ð#	
ô ð	#	
ô
 ð#	
ô ð#	
ô ð#	
ô ð#	
ô ð#	
ô ð#	
ô ð#	
ô ð#	
ô ð#	
ô ð#	
ô ð#	
ô  ð!#	
ô" ð##	
ô$ ð%#	
ô& ð'#	
ô( ð)#	
ô* ð+#	
ô, ð-#	
ô. ð/#	
ô0 ð1#	
ô2 ð3#	
ô4 ð5#	
ô6 �H‰H×$Ñ$ð7#	
ô8 ð9#	
ô: ð;#	
ô< ð=#	
ô> ð?#	
ô@ ðA#	
ôB ðC#	
ôD ðE#	
ó%€LôL äÜÜÜÜÜÜÜÜÜÜÜÜÜÜð	
ó€Nô& (¨¨*©¸¸&¹	Ñ(AÓBó bÑˆ‰?ˆAˆq�!�Tð ˜‰zô ”E—H‘H˜a  ˜eÔ$ð " QÑ&ô œ MÓ2×6Ñ6¸¸"¸#¸Ô?ä“˜1‘ð 	
ô ˜d“Oò 	T‰DˆAˆqÜ˜!œSÕ!Ü×(Ñ(¬Ó4ñ TØ-.´&³(©]œf›h qškÀ×@PÑ@PÐQRÓ@S�D˜‘G÷Tð Tð	Tð ./°ªU””U˜1˜u™9Ó% qÔ)¸Ð9ˆˆBØ�ÑØ˜‘U˜D ™G�ˆBØ�RŠxÜ#¤C¨¨LÓ$9¸EÑ$AÀ1ÓE�Ø”G‰|Ü(¬¨T°!©W°lÀaÑ6GÓ)HÈ5Ñ)PÐRSÓT��Q‘ÜÐ^bÐcdÑ^eÐhiÒ^iœc¤%¬¨D°©G°\ÀQÑ5FÈ"Ñ5LÓ(MÓ"NÐQVÑ"VÐXYÔZÐosÐtuÑovÓw��Q‘à˜Ð&˜T ! "˜XÐ&ˆDØ�NÑ"Ø—‘˜A˜qÔ!Ø�Ø”D‰yØ�Ø˜E‘>Ø"�D˜‘GØ”E‰zØ�Ø˜D‘=Ø—K‘K Ô,Ø”FŠ{Ø’Ø”$‰YØ�q‘E�>˜D�>ŠDØ”)œV¤WÐ-Ó.Ñ.Ø˜A™  Q¡¨¨a©�B�ˆBØ˜˜BÐ*  a b Ð*ˆDØ”GŠ|Ø—‘˜A˜qÔ!Ø’Ø”+ÑØ  šG��a’¨¨a©°1©ŠBØ”%—(‘(×&Ñ&Ñ&Ø�q‘E�7ŠDØ”&‰[ÜÓ& AÔ&Ó&ŠBØ”)äÜÜÜÜÜÜÜÜÜÜðó
ñ 
ð �K‰K˜ '¸1Ö+=°a¨B¨q«EÒ+=Ð>Ô?Ø”G‰|˜q¤LÑ0°A¼±NÀaÌ>ÑFYÜ(¬¨T°!©W°lÓ)CÀeÑ)KÈQÓO��Q‘Ø”Vœ[¬'´9¼lÌNÔ\`ÔbhÔjmÔotÐuÑuØ!�•Ø”)‰^Ø�K‰K¨Ö* 1˜˜A›Ò*Õ+ØÔ"Ñ"Ø�K‰K˜¨1Ö- a˜B˜q›EÒ-Õ.Ø”-ÑØ�K‰K˜¨1Ö- a˜B˜q›EÒ-Õ.Ø”(‰]Ø�a‘ˆBØ�A‘ˆBØ˜Ð&˜T ! "˜XÐ&‰DØ”&‰[Ø�A�b‘E‘‰BØ”)œ[¬%Ð0Ó1Ñ1Ø�a‘ˆBØ�A‘ˆBØ�T˜!˜"�X�;‰Dà�A‘ˆBàCDÀqÂ5ŒU�X‰X× Ñ Ô">´U¸1³XÔ">Ñ?ÉaÐQUÈhˆÜ�‹F�1�RˆL× Ñ  ¨bÓ1ˆÜÑ7 r§}¡}£Ô7Ó7ˆŒØ  AÐˆŒˆbŒd�B”GÙÜ�K‰K˜1˜R˜&  S 	¨"¨R¨°·±°u°¸RÀÀ#¸wÀtÈcÀlÐSÔTØ�‰ÓQ¬:°a¼Ô+= Q¡CÀ1ÔQÔQØ�‰�bÔØ�Š6ØˆBØ
�	‰	�"ŽðEbôF �8‰8×Ñ Ð'¬°«Ð5Ð5÷sTñ Tüòl ,>ùò +ùâ-ùâ-s$   Ì.`Õ*`,Ø`1
Ø>`6Ù*`;à`)c                 óæ  — t        | «      } | j                  d„ dD «       v ret        j                  dd| j                  «      }t	        j
                  d| j                  › d|› d�«       | j                  || j                  z   «      } t        j                  dd	t        | «      «      }t        |d
¬«      xs t        | «      }t        j                  |«      }t        | «      |d<   t        | «      |d<   |S )z•Load a YOLO model from a YAML file.

    Args:
        path (str | Path): Path to the YAML file.

    Returns:
        (dict): Model dictionary.
    c              3   ó:   K  — | ]  }d D ]  }d|› |› d�–— Œ Œ y­w))é   rI  ÚyolovÚ6Nr¾   r;  s      rh   rÂ   z"yaml_model_load.<locals>.<genexpr>Ð  s(   è ø€ ÒF¨¸vÒF¸!�u˜Q˜C ˜s !”_ÐF�_ÑFùs   ‚Únsmlxz(\d+)([nslmx])6(.+)?$z	\1\2-p6\3z8Ultralytics YOLO P6 models now use -p6 suffix. Renaming z to rø  z(\d+)([nslmx])(.+)?$z\1\3F)Úhardr8  Ú	yaml_file)r   ÚstemÚreÚsubrC   r“   Ú	with_namer  r2  rJ   rE   rê   Úguess_model_scale)ÚpathÚnew_stemÚunified_pathrv  r<  s        rh   r  r  Æ  sÐ   € ô �‹:€DØ‡y�yÑF¨gÔFÑFÜ—6‘6Ð2°LÀ$Ç)Á)ÓLˆÜ�‰ÐQÐRV×R[ÑR[ÐQ\Ð\`ÐaiÐ`jÐjkÐlÔmØ�~‰~˜h¨¯©Ñ4Ó5ˆä—6‘6Ð1°7¼CÀ»IÓF€LÜ˜<¨eÔ4ÒH¼
À4Ó8H€IÜ�	‰	�)Ó€AÜ" 4Ó(€A€g�JÜ˜“Y€A€k�NØ€Hrj   c                 ó’   — 	 t        j                  dt        | «      j                  «      j	                  d«      S # t
        $ r Y yw xY w)a%  Extract the size character n, s, m, l, or x of the model's scale from the model path.

    Args:
        model_path (str | Path): The path to the YOLO model's YAML file.

    Returns:
        (str): The size character of the model's scale (n, s, m, l, or x), or empty string if not found.
    zyolo(e-)?[v]?\d+([nslmx])r™   r  )rx  Úsearchr   rw  ÚgroupÚAttributeError)Ú
model_paths    rh   r{  r{  Ý  sB   € ðÜ�y‰yÐ5´t¸JÓ7G×7LÑ7LÓM×SÑSÐTUÓVÐVøÜò Ùðús   ‚7: º	AÁAc                 ó|  — d„ }t        | t        «      r+t        j                  t        «      5   || «      cddd«       S t        | t
        j                  j                  «      rúdD ]4  }t        j                  t        «      5  t        |«      d   cddd«       c S  dD ]7  }t        j                  t        «      5   |t        |«      «      cddd«       c S  | j                  «       D ]r  }t        |t        t        f«      r yt        |t        «      r yt        |t        «      r yt        |t        «      r y	t        |t        t         t"        t$        f«      sŒr y
 t        | t&        t(        f«      rŽt)        | «      } d| j*                  v sd| j,                  v ryd| j*                  v sd| j,                  v ryd| j*                  v sd| j,                  v ryd| j*                  v sd	| j,                  v ry	d
| j,                  v ry
t/        j0                  d«       y
# 1 sw Y   �ŒâxY w# 1 sw Y   �ŒÉxY w# 1 sw Y   �Œ�xY w)a,  Guess the task of a PyTorch model from its architecture or configuration.

    Args:
        model (torch.nn.Module | dict | str | Path): PyTorch model, model configuration dict, or model file path.

    Returns:
        (str): Task of the model ('detect', 'segment', 'classify', 'pose', 'obb').
    c                 óh   — | d   d   d   j                  «       }|dv ryd|v ryd|v ryd|v ryd	|v ry	y
)zGuess from YAML dictionary.r&  rs   r  >   Úfcr:  ÚclassifyÚ
classifierr‡  ÚdetectÚsegmentÚposeÚobbN)Úlower)r  r�   s     rh   Úcfg2taskz"guess_model_task.<locals>.cfg2taskö  sV   € à�‰K˜‰O˜BÑ×%Ñ%Ó'ˆØÐ7Ñ7ØØ�q‰=ØØ˜‰>ØØ�Q‰;ØØ�A‰:Øð rj   N)z
model.argszmodel.model.argszmodel.model.model.argsr0  )z
model.yamlzmodel.model.yamlzmodel.model.model.yamlrŠ  r‡  r‹  rŒ  r‰  z-segz-clsz-posez-obbz£Unable to automatically guess model task, assuming 'task=detect'. Explicitly define task for your model, i.e. 'task=detect', 'segment', 'classify','pose' or 'obb'.)r`   ra   rY  rZ  Ú	Exceptionr…   r†   ÚModuler  r²   r:   r?   r!   r1   r   r&   r=   r>   rA   r2  r   rw  ÚpartsrC   r“   )r}   rŽ  re   r�   s       rh   r4  r4  ì  sî  € òô �%œÔÜ× Ñ ¤Ó+ñ 	#Ù˜E“?÷	#ñ 	#ô �%œŸ™Ÿ™Ô)ØKò 	'ˆAÜ×$Ñ$¤YÓ/ñ 'Ü˜A“w˜v‘÷'ó 'ð	'ð Lò 	)ˆAÜ×$Ñ$¤YÓ/ñ )Ù¤ Q£Ó(÷)ó )ð	)ð —‘“ò 
	 ˆAÜ˜!œg¤|Ð4Ô5Ù Ü˜AœxÔ(Ù!Ü˜AœtÔ$ÙÜ˜AœsÔ#ÙÜ˜A¤¬´[Ä)ÐLÕMÙð
	 ô �%œ#œt˜Ô%Ü�U“ˆØ�U—Z‘ZÑ 9°·±Ñ#;ØØ�u—z‘zÑ! Z°5·;±;Ñ%>ØØ˜Ÿ
™
Ñ" f°·±Ñ&;ØØ�u—z‘zÑ! U¨e¯k©kÑ%9ØØ˜Ÿ™Ñ$Øô ‡N�Nð	lôð ÷S	#ñ 	#ú÷
'ñ 'ú÷)ñ )ús#   ­HÂH$Â:H1ÈH!È$H.	È1H;	r]  )F)NTFrö   )„rY  Úpicklerx  rr  r¥   r   Úpathlibr   r…   Útorch.nnr†   Úultralytics.nn.autobackendr   Úultralytics.nn.modulesr   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   Úultralytics.utilsrB   rC   rD   rE   rF   rG   Úultralytics.utils.checksrH   rI   rJ   rê  rK   rL   rM   rN   rO   rP   rQ   Úultralytics.utils.opsrR   Úultralytics.utils.patchesrS   Úultralytics.utils.plottingrT   Úultralytics.utils.torch_utilsrU   rV   rW   rX   rY   rZ   r[   r\   r�  r^   rý   rJ  rS  rW  r_  rv  r�  r¼  rí  rÒ  rò  Úcontextmanagerr  r  r#  r  r,  r6  r  r  r{  r4  r¾   rj   rh   ú<module>rž     sÀ  ðó Û Û 	Û Ý Ý ã Ý å 8÷=÷ =÷ =÷ =÷ =÷ =÷ =÷ =÷ =÷ =÷ =÷ =÷ =÷ =÷ =ó =÷| X× Wß QÑ Q÷÷ ñ õ 1Ý 0Ý <÷	÷ 	ó 	ômZ�—‘—‘ô mZô`l[�Yô l[ô^`ˆ~ô `ô@r˜ô rô@&b�ô &bôRY&˜)ô Y&ôxE˜>ô EôP,�ô ,ôDz,�ô z,ôz.,�JÐ 1ô .,ôb'ˆu�x‰x×"Ñ"ô 'ðZ ×Ñò,%ó ð,%÷^	ñ 	ô�F×$Ñ$ô ó8Tón"óJ@6òFò.óCrj   