Ë
    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c mZ	 d dl
mZ dZd„ Zdd„Zd„ Zdd„Zdej"                  d	ej"                  d
ej"                  dej"                  dej"                  f
d„Zy)é    N)Úuniform_)Úinverse_sigmoidÚ#multi_scale_deformable_attn_pytorchc                 óŠ   — t        j                  t        |«      D �cg c]  }t        j                  | «      ‘Œ c}«      S c c}w )a©  Create a list of cloned modules from the given module.

    Args:
        module (nn.Module): The module to be cloned.
        n (int): Number of clones to create.

    Returns:
        (nn.ModuleList): A ModuleList containing n clones of the input module.

    Examples:
        >>> import torch.nn as nn
        >>> layer = nn.Linear(10, 10)
        >>> clones = _get_clones(layer, 3)
        >>> len(clones)
        3
    )ÚnnÚ
ModuleListÚrangeÚcopyÚdeepcopy)ÚmoduleÚnÚ_s      ú^/var/www/pod-logistic/pod-ai/venv/lib/python3.12/site-packages/ultralytics/nn/modules/utils.pyÚ_get_clonesr      s.   € ô" �=‰=¼¸q»ÖB°Aœ$Ÿ-™-¨Õ/ÒBÓCÐCùÒBs   �A c                 óL   — t        t        j                  d| z
  | z  «       «      S )a½  Initialize conv/fc bias value according to a given probability value.

    This function calculates the bias initialization value based on a prior probability using the inverse sigmoid
    (logit)
    function. It's commonly used in object detection models to initialize classification layers with a specific positive
    prediction probability.

    Args:
        prior_prob (float, optional): Prior probability for bias initialization.

    Returns:
        (float): Bias initialization value calculated from the prior probability.

    Examples:
        >>> bias = bias_init_with_prob(0.01)
        >>> print(f"Bias initialization value: {bias:.4f}")
        Bias initialization value: -4.5951
    é   )ÚfloatÚnpÚlog)Ú
prior_probs    r   Úbias_init_with_probr   #   s$   € ô& ”"—&‘&˜!˜j™.¨JÑ6Ó7Ð7Ó8Ð8ó    c                 óö   — dt        j                  | j                  j                  d   «      z  }t	        | j                  | |«       t        | d«      r&| j                  �t	        | j                  | |«       yyy)aº  Initialize the weights and biases of a linear module.

    This function initializes the weights of a linear module using a uniform distribution within bounds calculated from
    the output dimension. If the module has a bias, it is also initialized.

    Args:
        module (nn.Module): Linear module to initialize.

    Examples:
        >>> import torch.nn as nn
        >>> linear = nn.Linear(10, 5)
        >>> linear_init(linear)
    r   r   ÚbiasN)ÚmathÚsqrtÚweightÚshaper   Úhasattrr   )r   Úbounds     r   Úlinear_initr!   9   se   € ð ”—	‘	˜&Ÿ-™-×-Ñ-¨aÑ0Ó1Ñ1€EÜˆV�]‰]˜U˜F EÔ*Üˆv�vÔ 6§;¡;Ð#:Ü�—‘˜u˜f eÕ,ð $;Ðr   c                 ó¦   — | j                  dd¬«      } | j                  |¬«      }d| z
  j                  |¬«      }t        j                  ||z  «      S )aŠ  Calculate the inverse sigmoid function for a tensor.

    This function applies the inverse of the sigmoid function to a tensor, which is useful in various neural network
    operations, particularly in attention mechanisms and coordinate transformations.

    Args:
        x (torch.Tensor): Input tensor with values in range [0, 1].
        eps (float, optional): Small epsilon value to prevent numerical instability.

    Returns:
        (torch.Tensor): Tensor after applying the inverse sigmoid function.

    Examples:
        >>> x = torch.tensor([0.2, 0.5, 0.8])
        >>> inverse_sigmoid(x)
        tensor([-1.3863,  0.0000,  1.3863])
    r   r   )ÚminÚmax)r#   )ÚclampÚtorchr   )ÚxÚepsÚx1Úx2s       r   r   r   M   sM   € ð$ 	
�‰�A˜1ˆÓ€AØ	
�‰�SˆÓ	€BØ
ˆa‰%�‰˜3ˆÓ	€BÜ�9‰9�R˜"‘WÓÐr   ÚvalueÚvalue_spatial_shapesÚsampling_locationsÚattention_weightsÚreturnc                 ó:  — | j                   \  }}}}|j                   \  }}}}	}
}| j                  |D ��cg c]
  \  }}||z  ‘Œ c}}d¬«      }d|z  dz
  }g }t        |«      D ]›  \  }\  }}||   j                  d«      j	                  dd«      j                  ||z  |||«      }|dd…dd…dd…|f   j	                  dd«      j                  dd«      }t        j                  ||ddd¬	«      }|j                  |«       Œ� |j	                  dd«      j                  ||z  d||	|
z  «      }t        j                  |d
¬«      j                  d
«      |z  j                  d«      j                  |||z  |«      }|j	                  dd«      j                  «       S c c}}w )a¿  Implement multi-scale deformable attention in PyTorch.

    This function performs deformable attention across multiple feature map scales, allowing the model to attend to
    different spatial locations with learned offsets.

    Args:
        value (torch.Tensor): The value tensor with shape (bs, num_keys, num_heads, embed_dims).
        value_spatial_shapes (torch.Tensor): Spatial shapes of the value tensor with shape (num_levels, 2).
        sampling_locations (torch.Tensor): The sampling locations with shape (bs, num_queries, num_heads, num_levels,
            num_points, 2).
        attention_weights (torch.Tensor): The attention weights with shape (bs, num_queries, num_heads, num_levels,
            num_points).

    Returns:
        (torch.Tensor): The output tensor with shape (bs, num_queries, num_heads * embed_dims).

    References:
        https://github.com/IDEA-Research/detrex/blob/main/detrex/layers/multi_scale_deform_attn.py
    r   )Údimé   Nr   ÚbilinearÚzerosF)ÚmodeÚpadding_modeÚalign_cornerséþÿÿÿéÿÿÿÿ)r   ÚsplitÚ	enumerateÚflattenÚ	transposeÚreshapeÚFÚgrid_sampleÚappendr&   ÚstackÚsumÚviewÚ
contiguous)r+   r,   r-   r.   Úbsr   Ú	num_headsÚ
embed_dimsÚnum_queriesÚ
num_levelsÚ
num_pointsÚH_ÚW_Ú
value_listÚsampling_gridsÚsampling_value_listÚlevelÚvalue_l_Úsampling_grid_l_Úsampling_value_l_Úoutputs                        r   r   r   e   sº  € ð2 $)§;¡;Ñ €Bˆˆ9�jØ;M×;SÑ;SÑ8€A€{�I˜z¨:°qØ—‘Ð4H×I©&¨"¨b˜b 2›gÓIÈq�ÓQ€JØÐ+Ñ+¨aÑ/€NØÐÜ$Ð%9Ó:ò 6‰ˆ‰x��Bð
 ˜eÑ$×,Ñ,¨QÓ/×9Ñ9¸!¸QÓ?×GÑGÈÈYÉÐXbÐdfÐhjÓkˆð *ª!ªQ²°5¨.Ñ9×CÑCÀAÀqÓI×QÑQÐRSÐUVÓWÐäŸM™MØÐ&¨ZÀgÐ]bô
Ðð 	×"Ñ"Ð#4Õ5ð6ð$ *×3Ñ3°A°qÓ9×AÑAØ
ˆY‰˜˜;¨
°ZÑ(?óÐô 
�‰Ð(¨bÔ	1×	9Ñ	9¸"Ó	=Ð@QÑ	Qß	‰ˆR‹ß	‰ˆb�)˜jÑ(¨+Ó	6ð ð
 ×Ñ˜A˜qÓ!×,Ñ,Ó.Ð.ùó; Js   µF
)g{®Gáz„?)gñhãˆµøä>)r
   r   Únumpyr   r&   Útorch.nnr   Útorch.nn.functionalÚ
functionalr?   Útorch.nn.initr   Ú__all__r   r   r!   r   ÚTensorr   © r   r   ú<module>r^      s€   ðó Û ã Û Ý ß Ð Ý "à
B€òDó(9ò,-ó(ð08/Ø�<‰<ð8/àŸ,™,ð8/ð Ÿ™ð8/ð —|‘|ð	8/ð
 ‡\�\ô8/r   