a
    yf_                     @   s  d dl Z d dlZd dlmZ d dlmZmZmZmZm	Z	 d dl
Zd dlZd dlm  mZ d dlmZmZ d dlmZmZmZ ddlmZmZmZ ddlmZmZmZmZmZ G d	d
 d
ej Z!G dd dej Z"G dd dej Z#G dd dej Z$G dd deZ%G dd deZ&G dd deZ'd(ejej ej ejdddZ(G dd dej Z)G dd dej Z*G dd dej Z+G d d! d!ej Z,G d"d# d#ej Z-G d$d% d%ej Z.G d&d' d'ej Z/dS ))    N)partial)AnyOptionalTupleTypeUnion)Tensornn)MLPLayerNorm2dMLPBlock   )	AttentionTwoWayAttentionBlockTwoWayTransformer)add_decomposed_rel_posapply_rotary_enccompute_axial_ciswindow_partitionwindow_unpartitionc                       s*   e Zd ZdZd fdd	Zdd Z  ZS )	DropPatha  
    Implements stochastic depth regularization for neural networks during training.

    Attributes:
        drop_prob (float): Probability of dropping a path during training.
        scale_by_keep (bool): Whether to scale the output by the keep probability.

    Methods:
        forward: Applies stochastic depth to input tensor during training, with optional scaling.

    Examples:
        >>> drop_path = DropPath(drop_prob=0.2, scale_by_keep=True)
        >>> x = torch.randn(32, 64, 224, 224)
        >>> output = drop_path(x)
            Tc                    s   t    || _|| _dS )zOInitialize DropPath module for stochastic depth regularization during training.N)super__init__	drop_probscale_by_keep)selfr   r   	__class__ a/var/www/html/django/DPS/env/lib/python3.9/site-packages/ultralytics/models/sam/modules/blocks.pyr   $   s    
zDropPath.__init__c                 C   sh   | j dks| js|S d| j  }|jd fd|jd   }|||}|dkr`| jr`|| || S )zPApplies stochastic depth to input tensor during training, with optional scaling.r   r   r   )r   )r   ZtrainingshapendimZ	new_emptyZ
bernoulli_r   Zdiv_)r   xZ	keep_probr!   Zrandom_tensorr   r   r    forward*   s    

zDropPath.forward)r   T__name__
__module____qualname____doc__r   r$   __classcell__r   r   r   r    r      s   r   c                       s8   e Zd ZdZdddddejf fdd	Zdd	 Z  ZS )
MaskDownSamplera  
    A mask downsampling and embedding module for efficient processing of input masks.

    This class implements a mask downsampler that progressively reduces the spatial dimensions of input masks
    while expanding their channel dimensions using convolutional layers, layer normalization, and activation
    functions.

    Attributes:
        encoder (nn.Sequential): A sequential container of convolutional layers, layer normalization, and
            activation functions for downsampling and embedding masks.

    Methods:
        forward: Downsamples and encodes input mask to embed_dim channels.

    Examples:
        >>> mask_downsampler = MaskDownSampler(embed_dim=256, kernel_size=4, stride=4, padding=0, total_stride=16)
        >>> input_mask = torch.randn(1, 1, 256, 256)
        >>> output = mask_downsampler(input_mask)
        >>> print(output.shape)
        torch.Size([1, 256, 16, 16])
          r      c              
      s   t    tt|t| }|| |ks2J t | _d\}}	t|D ]N}
||d  }	| j	tj
||	|||d | j	t|	 | j	|  |	}qL| j	tj
|	|dd dS )zYInitializes a mask downsampler module for progressive downsampling and channel expansion.)r   r      kernel_sizestridepaddingr   r1   N)r   r   intmathlog2r	   Z
SequentialencoderrangeappendConv2dr   )r   	embed_dimr1   r2   r3   Ztotal_stride
activation
num_layersZmask_in_chansZmask_out_chans_r   r   r    r   M   s(    


	zMaskDownSampler.__init__c                 C   s
   |  |S )zdDownsamples and encodes input mask to embed_dim channels using convolutional layers and LayerNorm2d.)r8   r   r#   r   r   r    r$   m   s    zMaskDownSampler.forward)	r&   r'   r(   r)   r	   GELUr   r$   r*   r   r   r   r    r+   6   s    r+   c                       s*   e Zd ZdZd fdd	Zd	d
 Z  ZS )CXBlocka^  
    ConvNeXt Block for efficient feature extraction in convolutional neural networks.

    This block implements a modified version of the ConvNeXt architecture, offering improved performance and
    flexibility in feature extraction.

    Attributes:
        dwconv (nn.Conv2d): Depthwise or standard 2D convolution layer.
        norm (LayerNorm2d): Layer normalization applied to channels.
        pwconv1 (nn.Linear): First pointwise convolution implemented as a linear layer.
        act (nn.GELU): GELU activation function.
        pwconv2 (nn.Linear): Second pointwise convolution implemented as a linear layer.
        gamma (nn.Parameter | None): Learnable scale parameter for layer scaling.
        drop_path (nn.Module): DropPath layer for stochastic depth regularization.

    Methods:
        forward: Processes the input tensor through the ConvNeXt block.

    Examples:
        >>> import torch
        >>> x = torch.randn(1, 64, 56, 56)
        >>> block = CXBlock(dim=64, kernel_size=7, padding=3)
        >>> output = block(x)
        >>> print(output.shape)
        torch.Size([1, 64, 56, 56])
          r   ư>Tc                    s   t    tj|||||r|ndd| _t|dd| _t|d| | _t	 | _
td| || _|dkrtj|t| ddnd	| _|d
krt|nt | _d	S )a  
        Initialize a ConvNeXt Block for efficient feature extraction in convolutional neural networks.

        This block implements a modified version of the ConvNeXt architecture, offering improved performance and
        flexibility in feature extraction.

        Args:
            dim (int): Number of input channels.
            kernel_size (int): Size of the convolutional kernel.
            padding (int): Padding size for the convolution.
            drop_path (float): Stochastic depth rate.
            layer_scale_init_value (float): Initial value for Layer Scale.
            use_dwconv (bool): Whether to use depthwise convolution.

        Examples:
            >>> block = CXBlock(dim=64, kernel_size=7, padding=3)
            >>> x = torch.randn(1, 64, 32, 32)
            >>> output = block(x)
            >>> print(output.shape)
            torch.Size([1, 64, 32, 32])
        r   )r1   r3   groupsrE   epsr-   r   T)Zrequires_gradNr   )r   r   r	   r;   dwconvr   normLinearpwconv1rA   actpwconv2	Parametertorchonesgammar   Identity	drop_path)r   dimr1   r3   rT   Zlayer_scale_init_valueZ
use_dwconvr   r   r    r      s"    


zCXBlock.__init__c                 C   s|   |}|  |}| |}|dddd}| |}| |}| |}| jdurZ| j| }|dddd}|| | }|S )zbApplies ConvNeXt block operations to input tensor, including convolutions and residual connection.r   r/   rD   r   N)rI   rJ   permuterL   rM   rN   rR   rT   )r   r#   inputr   r   r    r$      s    






zCXBlock.forward)rC   rD   r   rE   Tr%   r   r   r   r    rB   r   s        1rB   c                       s*   e Zd ZdZd fdd	Zdd Z  ZS )	Fusera  
    A module for fusing features through multiple layers of a neural network.

    This class applies a series of identical layers to an input tensor, optionally projecting the input first.

    Attributes:
        proj (nn.Module): An optional input projection layer. Identity if no projection is needed.
        layers (nn.ModuleList): A list of identical layers to be applied sequentially.

    Methods:
        forward: Applies the fuser to an input tensor.

    Examples:
        >>> layer = CXBlock(dim=256)
        >>> fuser = Fuser(layer, num_layers=3, dim=256, input_projection=True)
        >>> x = torch.randn(1, 256, 32, 32)
        >>> output = fuser(x)
        >>> print(output.shape)
        torch.Size([1, 256, 32, 32])
    NFc                    sX   t    t | _t fddt|D | _|rT|dusBJ tj||dd| _dS )a  
        Initializes the Fuser module for feature fusion through multiple layers.

        This module creates a sequence of identical layers and optionally applies an input projection.

        Args:
            layer (nn.Module): The layer to be replicated in the fuser.
            num_layers (int): The number of times to replicate the layer.
            dim (int | None): The dimension for input projection, if used.
            input_projection (bool): Whether to use input projection.

        Examples:
            >>> layer = nn.Linear(64, 64)
            >>> fuser = Fuser(layer, num_layers=3, dim=64, input_projection=True)
            >>> input_tensor = torch.randn(1, 64)
            >>> output = fuser(input_tensor)
        c                    s   g | ]}t  qS r   )copydeepcopy).0r?   layerr   r    
<listcomp>       z"Fuser.__init__.<locals>.<listcomp>Nr   r4   )	r   r   r	   rS   proj
ModuleListr9   layersr;   )r   r]   r>   rU   Zinput_projectionr   r\   r    r      s    

zFuser.__init__c                 C   s"   |  |}| jD ]}||}q|S )zOApplies a series of layers to the input tensor, optionally projecting it first.)r`   rb   )r   r#   r]   r   r   r    r$      s    


zFuser.forward)NFr%   r   r   r   r    rX      s   rX   c                	       sD   e Zd ZdZdejddfeeeeej ee	dd fddZ
  ZS )	SAM2TwoWayAttentionBlocka  
    A two-way attention block for performing self-attention and cross-attention in both directions.

    This block extends the TwoWayAttentionBlock and consists of four main components: self-attention on
    sparse inputs, cross-attention from sparse to dense inputs, an MLP block on sparse inputs, and
    cross-attention from dense to sparse inputs.

    Attributes:
        self_attn (Attention): Self-attention layer for queries.
        norm1 (nn.LayerNorm): Layer normalization after the first attention block.
        cross_attn_token_to_image (Attention): Cross-attention layer from queries to keys.
        norm2 (nn.LayerNorm): Layer normalization after the second attention block.
        mlp (MLP): MLP block for transforming query embeddings.
        norm3 (nn.LayerNorm): Layer normalization after the MLP block.
        norm4 (nn.LayerNorm): Layer normalization after the third attention block.
        cross_attn_image_to_token (Attention): Cross-attention layer from keys to queries.
        skip_first_layer_pe (bool): Flag to skip positional encoding in the first layer.

    Methods:
        forward: Processes input through the attention blocks and MLP.

    Examples:
        >>> block = SAM2TwoWayAttentionBlock(embedding_dim=256, num_heads=8)
        >>> sparse_input = torch.randn(1, 100, 256)
        >>> dense_input = torch.randn(1, 256, 16, 16)
        >>> sparse_output, dense_output = block(sparse_input, dense_input)
    i   r/   FN)embedding_dim	num_headsmlp_dimr=   attention_downsample_rateskip_first_layer_pereturnc                    s.   t  |||||| t|||d|d| _dS )a  
        Initializes a SAM2TwoWayAttentionBlock for performing self-attention and cross-attention in two directions.

        This block extends the TwoWayAttentionBlock and consists of four main components: self-attention on sparse
        inputs, cross-attention from sparse to dense inputs, an MLP block on sparse inputs, and cross-attention
        from dense to sparse inputs.

        Args:
            embedding_dim (int): The channel dimension of the embeddings.
            num_heads (int): The number of heads in the attention layers.
            mlp_dim (int): The hidden dimension of the MLP block.
            activation (Type[nn.Module]): The activation function of the MLP block.
            attention_downsample_rate (int): The downsample rate for attention computations.
            skip_first_layer_pe (bool): Whether to skip the positional encoding in the first layer.

        Examples:
            >>> block = SAM2TwoWayAttentionBlock(embedding_dim=256, num_heads=8, mlp_dim=2048)
            >>> sparse_inputs = torch.randn(1, 100, 256)
            >>> dense_inputs = torch.randn(1, 256, 32, 32)
            >>> sparse_outputs, dense_outputs = block(sparse_inputs, dense_inputs)
        r/   r>   rM   N)r   r   r
   mlp)r   rd   re   rf   r=   rg   rh   r   r   r    r   %  s    z!SAM2TwoWayAttentionBlock.__init__)r&   r'   r(   r)   r	   ReLUr5   r   Moduleboolr   r*   r   r   r   r    rc     s    rc   c                	       s@   e Zd ZdZejdfeeeeeej edd fddZ	  Z
S )SAM2TwoWayTransformera  
    A Two-Way Transformer module for simultaneous attention to image and query points.

    This class extends the TwoWayTransformer, implementing a specialized transformer decoder that attends to an
    input image using queries with supplied positional embeddings. It is particularly useful for tasks like
    object detection, image segmentation, and point cloud processing.

    Attributes:
        depth (int): Number of layers in the transformer.
        embedding_dim (int): Channel dimension for input embeddings.
        num_heads (int): Number of heads for multihead attention.
        mlp_dim (int): Internal channel dimension for the MLP block.
        layers (nn.ModuleList): List of SAM2TwoWayAttentionBlock layers comprising the transformer.
        final_attn_token_to_image (Attention): Final attention layer from queries to image.
        norm_final_attn (nn.LayerNorm): Layer normalization applied to final queries.

    Methods:
        forward: Processes input image embeddings and query embeddings through the transformer.

    Examples:
        >>> transformer = SAM2TwoWayTransformer(depth=5, embedding_dim=256, num_heads=8, mlp_dim=2048)
        >>> image_embedding = torch.randn(1, 256, 64, 64)
        >>> query_embedding = torch.randn(1, 100, 256)
        >>> output = transformer(image_embedding, query_embedding)
        >>> print(output[0].shape, output[1].shape)
        torch.Size([1, 100, 256]) torch.Size([1, 256, 64, 64])
    r/   N)depthrd   re   rf   r=   rg   ri   c                    sR   t  |||||| t | _t|D ]$}| jt||||||dkd q(dS )a  
        Initializes a SAM2TwoWayTransformer instance.

        This transformer decoder attends to an input image using queries with supplied positional embeddings.
        It is designed for tasks like object detection, image segmentation, and point cloud processing.

        Args:
            depth (int): Number of layers in the transformer.
            embedding_dim (int): Channel dimension for the input embeddings.
            num_heads (int): Number of heads for multihead attention. Must divide embedding_dim.
            mlp_dim (int): Channel dimension internal to the MLP block.
            activation (Type[nn.Module]): Activation function to use in the MLP block.
            attention_downsample_rate (int): Downsampling rate for attention computations.

        Examples:
            >>> transformer = SAM2TwoWayTransformer(depth=5, embedding_dim=256, num_heads=8, mlp_dim=2048)
            >>> transformer
            SAM2TwoWayTransformer(
              (layers): ModuleList(
                (0-4): 5 x SAM2TwoWayAttentionBlock(...)
              )
              (final_attn_token_to_image): Attention(...)
              (norm_final_attn): LayerNorm(...)
            )
        r   )rd   re   rf   r=   rg   rh   N)r   r   r	   ra   rb   r9   r:   rc   )r   rp   rd   re   rf   r=   rg   ir   r   r    r   d  s    "
zSAM2TwoWayTransformer.__init__)r&   r'   r(   r)   r	   rl   r5   r   rm   r   r*   r   r   r   r    ro   G  s   "ro   c                       sB   e Zd ZdZdddd fdd
Zdeeeeed	d
dZ  ZS )RoPEAttentiona  
    Implements rotary position encoding for attention mechanisms in transformer architectures.

    This class extends the base Attention class by incorporating Rotary Position Encoding (RoPE) to enhance
    the positional awareness of the attention mechanism.

    Attributes:
        compute_cis (Callable): Function to compute axial complex numbers for rotary encoding.
        freqs_cis (Tensor): Precomputed frequency tensor for rotary encoding.
        rope_k_repeat (bool): Flag to repeat query RoPE to match key length for cross-attention to memories.

    Methods:
        forward: Applies rotary position encoding and computes attention between query, key, and value tensors.

    Examples:
        >>> rope_attn = RoPEAttention(embedding_dim=256, num_heads=8, rope_theta=10000.0, feat_sizes=(32, 32))
        >>> q = torch.randn(1, 1024, 256)
        >>> k = torch.randn(1, 1024, 256)
        >>> v = torch.randn(1, 1024, 256)
        >>> output = rope_attn(q, k, v)
        >>> print(output.shape)
        torch.Size([1, 1024, 256])
    g     @F)    rs   )
rope_thetarope_k_repeat
feat_sizesc                   sP   t  j|i | tt| j| j |d| _| j|d |d d}|| _|| _dS )zZInitializes RoPEAttention with rotary position encoding for enhanced positional awareness.)rU   thetar   r   Zend_xZend_yN)	r   r   r   r   Zinternal_dimre   compute_cis	freqs_cisru   )r   rt   ru   rv   argskwargsrz   r   r   r    r     s
    	zRoPEAttention.__init__r   )qkvnum_k_exclude_roperi   c                 C   sh  |  |}| |}| |}| || j}| || j}| || j}t|jd  }}| j	|j
| _| jjd |jd kr| j||d	|j
| _|jd |jd kr| jsJ |d| }t||ddddd|f | j| jd\}|ddddd|f< |j\}}}}	||dddd }
|
t|	 }
tj|
d	d
}
|
| }| |}| |}|S )z^Applies rotary position encoding and computes attention between query, key, and value tensors.r   rx   N)rz   Zrepeat_freqs_kr   rD   r/   rU   )Zq_projZk_projZv_projZ_separate_headsre   r6   sqrtr!   rz   todevicery   ru   sizer   rV   rP   softmaxZ_recombine_headsZout_proj)r   r}   r~   r   r   whZ
num_k_roper?   Z
c_per_headattnoutr   r   r    r$     s6    



 

zRoPEAttention.forward)r   )	r&   r'   r(   r)   r   r   r5   r$   r*   r   r   r   r    rr     s   rr   )r#   poolrJ   ri   c                 C   sD   |du r| S |  dddd} || } |  dddd} |r@|| } | S )z`Applies pooling and optional normalization to a tensor, handling spatial dimension permutations.Nr   rD   r   r/   )rV   )r#   r   rJ   r   r   r    do_pool  s    r   c                       sD   e Zd ZdZd	eeeejd fddZej	ej	dddZ
  ZS )
MultiScaleAttentiona  
    Implements multi-scale self-attention with optional query pooling for efficient feature extraction.

    This class provides a flexible implementation of multi-scale attention, allowing for optional
    downsampling of query features through pooling. It's designed to enhance the model's ability to
    capture multi-scale information in visual tasks.

    Attributes:
        dim (int): Input dimension of the feature map.
        dim_out (int): Output dimension of the attention module.
        num_heads (int): Number of attention heads.
        scale (float): Scaling factor for dot-product attention.
        q_pool (nn.Module | None): Optional pooling module for query features.
        qkv (nn.Linear): Linear projection for query, key, and value.
        proj (nn.Linear): Output projection.

    Methods:
        forward: Applies multi-scale attention to the input tensor.

    Examples:
        >>> import torch
        >>> from torch import nn
        >>> x = torch.randn(1, 64, 64, 256)
        >>> msa = MultiScaleAttention(dim=256, dim_out=256, num_heads=8)
        >>> output = msa(x)
        >>> print(output.shape)
        torch.Size([1, 64, 64, 256])
    N)rU   dim_outre   q_poolc                    sX   t    || _|| _|| _|| }|d | _|| _t||d | _	t||| _
dS )z_Initializes multi-scale attention with optional query pooling for efficient feature extraction.      rD   N)r   r   rU   r   re   scaler   r	   rK   qkvr`   )r   rU   r   re   r   head_dimr   r   r    r     s    

zMultiScaleAttention.__init__r#   ri   c           
      C   s   |j \}}}}| |||| d| jd}t|d\}}}	| jrt||||d| j}|j dd \}}|||| | jd}t	|
dd|
dd|	
dd}|
dd}||||d}| |}|S )zZApplies multi-scale attention with optional query pooling to extract multi-scale features.rD   r   r/   r   )r!   r   reshapere   rP   unbindr   r   FZscaled_dot_product_attention	transposer`   )
r   r#   BHWr?   r   r}   r~   r   r   r   r    r$   *  s     



zMultiScaleAttention.forward)N)r&   r'   r(   r)   r5   r	   rm   r   rP   r   r$   r*   r   r   r   r    r     s   " r   c                       sn   e Zd ZdZddddejdfeeeeeeej	e
f eeef ej	ed	 fdd	Zejejd
ddZ  ZS )MultiScaleBlocka  
    A multi-scale attention block with window partitioning and query pooling for efficient vision transformers.

    This class implements a multi-scale attention mechanism with optional window partitioning and downsampling,
    designed for use in vision transformer architectures.

    Attributes:
        dim (int): Input dimension of the block.
        dim_out (int): Output dimension of the block.
        norm1 (nn.Module): First normalization layer.
        window_size (int): Size of the window for partitioning.
        pool (nn.Module | None): Pooling layer for query downsampling.
        q_stride (Tuple[int, int] | None): Stride for query pooling.
        attn (MultiScaleAttention): Multi-scale attention module.
        drop_path (nn.Module): Drop path layer for regularization.
        norm2 (nn.Module): Second normalization layer.
        mlp (MLP): Multi-layer perceptron module.
        proj (nn.Linear | None): Projection layer for dimension mismatch.

    Methods:
        forward: Processes input tensor through the multi-scale block.

    Examples:
        >>> block = MultiScaleBlock(dim=256, dim_out=512, num_heads=8, window_size=7)
        >>> x = torch.randn(1, 56, 56, 256)
        >>> output = block(x)
        >>> print(output.shape)
        torch.Size([1, 28, 28, 512])
          @r   	LayerNormNr   )	rU   r   re   	mlp_ratiorT   
norm_layerq_stride	act_layerwindow_sizec
           
         s   t    t|tr&ttt|dd}|| _|| _||| _	|	| _
d| | _| _| jrhtj||dd| _t|||| jd| _|dkrt|nt | _||| _t|t|| |d|d	| _||krt||| _dS )
z^Initializes a multi-scale attention block with window partitioning and optional query pooling.rE   rG   NF)r1   r2   Z	ceil_mode)re   r   r   r/   rj   )r   r   
isinstancestrr   getattrr	   rU   r   norm1r   r   r   Z	MaxPool2dr   r   r   rS   rT   norm2r
   r5   rk   rK   r`   )
r   rU   r   re   r   rT   r   r   r   r   r   r   r    r   f  s6    




zMultiScaleBlock.__init__r   c           	      C   s  |}|  |}| j| jkr,t| || j}| j}|dkr^|jd |jd  }}t||\}}| 	|}| j
r| j| j
d  }|jdd \}}|||  | }|||  | }|| || f}| jdkrt|||||f}|| | }|| | | | }|S )z`Processes input through multi-scale attention and MLP, with optional windowing and downsampling.r   r   r/   rD   )r   rU   r   r   r`   r   r   r!   r   r   r   r   rT   rk   r   )	r   r#   shortcutr   r   r   pad_hwZpad_hZpad_wr   r   r    r$     s(    


zMultiScaleBlock.forward)r&   r'   r(   r)   r	   rA   r5   floatr   rm   r   r   r   rP   r   r$   r*   r   r   r   r    r   G  s&   #
0r   c                       st   e Zd ZdZdeeee d fddZdd	 Z	e
 d
d ZeZe
 dd Ze
 e
jdddZ  ZS )PositionEmbeddingSinea  
    A module for generating sinusoidal positional embeddings for 2D inputs like images.

    This class implements sinusoidal position encoding for 2D spatial positions, which can be used in
    transformer-based models for computer vision tasks.

    Attributes:
        num_pos_feats (int): Number of positional features (half of the embedding dimension).
        temperature (int): Temperature parameter for the sinusoidal functions.
        normalize (bool): Whether to normalize the positional embeddings.
        scale (float): Scaling factor for the embeddings when normalize is True.
        cache (Dict): Cache for storing precomputed embeddings.

    Methods:
        _encode_xy: Encodes 2D positions using sine and cosine functions.
        encode_boxes: Encodes box coordinates and dimensions into positional embeddings.
        encode_points: Encodes 2D point coordinates with sinusoidal positional embeddings.
        forward: Generates sinusoidal position embeddings for 2D inputs.

    Examples:
        >>> pos_emb = PositionEmbeddingSine(num_pos_feats=128)
        >>> x = torch.randn(1, 3, 224, 224)
        >>> embeddings = pos_emb(x)
        >>> print(embeddings.shape)
        torch.Size([1, 256, 224, 224])
    '  TN)temperature	normalizer   c                    sj   t    |d dksJ d|d | _|| _|| _|durH|sHtd|du rZdtj }|| _i | _	dS )z?Initializes sinusoidal position embeddings for 2D image inputs.r/   r   zExpecting even model widthNz+normalize should be True if scale is passed)
r   r   num_pos_featsr   r   
ValueErrorr6   pir   cache)r   r   r   r   r   r   r   r    r     s    


zPositionEmbeddingSine.__init__c                 C   s(  t |t |kr*|j|j  kr(dks.n J || j }|| j }tj| jtj|jd}| jd|d  | j  }|dddf | }|dddf | }tj	|dddddf 
 |dddddf  fddd}tj	|dddddf 
 |dddddf  fddd}||fS )zWEncodes 2D positions using sine/cosine functions for transformer positional embeddings.r   dtyper   r/   Nr   r   )lenr"   r   rP   aranger   float32r   r   stacksincosflatten)r   r#   yx_embedy_embeddim_tpos_xpos_yr   r   r    
_encode_xy  s    .

DDz PositionEmbeddingSine._encode_xyc                 C   s>   |  ||\}}tj|||dddf |dddf fddS )zPEncodes box coordinates and dimensions into positional embeddings for detection.Nr   r   )r   rP   cat)r   r#   r   r   r   r   r   r   r   r    encode_boxes  s    z"PositionEmbeddingSine.encode_boxesc                 C   s   |j |j |j   \}}\}}\}}	||krB||krB||krB||	ksFJ | | | \}
}|
||d|||d }
}tj||
|dddddf fddS )z@Encodes 2D points with sinusoidal embeddings and appends labels.r   Nr/   r   )r!   r   r   r   rP   r   )r   r#   r   labelsbxnxZbynyblnlr   r   r   r   r    encode_points  s
    "$z#PositionEmbeddingSine.encode_points)r#   c           
   	   C   sp  |j d |j d f}|| jv r>| j| d |j d dddS tjd|j d d tj|jdddd|j d d|j d }tjd|j d d tj|jdddd|j d |j d d}| jrd}||ddddddf |  | j	 }||ddddddf |  | j	 }tj| j
tj|jd}| jd|d  | j
  }|dddddddf | }|dddddddf | }tj|dddddddddf  |dddddddddf  fd	d
d}tj|dddddddddf  |dddddddddf  fd	d
d}tj||fdd
dddd}	|	d | j|< |	S )zCGenerates sinusoidal position embeddings for 2D inputs like images.r   r   Nr   r   r   rE   r/   r-   r   rD   )r!   r   repeatrP   r   r   r   viewr   r   r   r   r   r   r   r   r   rV   )
r   r#   	cache_keyr   r   rH   r   r   r   posr   r   r    r$     s8    
   ((  \\zPositionEmbeddingSine.forward)r   TN)r&   r'   r(   r)   r5   rn   r   r   r   r   rP   Zno_gradr   encoder   r   r$   r*   r   r   r   r    r     s"      

r   c                       s|   e Zd ZdZdeee dd fddZej	ej	ddd	Z
eeef ej	d
ddZej	eeef ej	dddZ  ZS )PositionEmbeddingRandomaV  
    Positional encoding using random spatial frequencies.

    This class generates positional embeddings for input coordinates using random spatial frequencies. It is
    particularly useful for transformer-based models that require position information.

    Attributes:
        positional_encoding_gaussian_matrix (torch.Tensor): A buffer containing random values for encoding.

    Methods:
        _pe_encoding: Positionally encodes points that are normalized to [0,1].
        forward: Generates positional encoding for a grid of the specified size.
        forward_with_coords: Positionally encodes points that are not normalized to [0,1].

    Examples:
        >>> pe = PositionEmbeddingRandom(num_pos_feats=64)
        >>> size = (32, 32)
        >>> encoding = pe(size)
        >>> print(encoding.shape)
        torch.Size([128, 32, 32])
    @   N)r   r   ri   c                    sP   t    |du s|dkrd}| d|td|f  td dtjj_dS )zIInitializes random spatial frequency position embedding for transformers.Nr   g      ?#positional_encoding_gaussian_matrixr/   F)	r   r   Zregister_bufferrP   ZrandnZuse_deterministic_algorithmsbackendsZcudnnZdeterministic)r   r   r   r   r   r    r   D  s    

z PositionEmbeddingRandom.__init__)coordsri   c                 C   sB   d| d }|| j  }dtj | }tjt|t|gddS )zFEncodes normalized [0,1] coordinates using random spatial frequencies.r/   r   r   r   )r   npr   rP   r   r   r   )r   r   r   r   r    _pe_encodingO  s    
z$PositionEmbeddingRandom._pe_encoding)r   ri   c           	      C   s|   |\}}| j j}tj||f|tjd}|jddd }|jddd }|| }|| }| tj||gdd}|dddS )zJGenerates positional encoding for a grid using random spatial frequencies.)r   r   r   r   g      ?r   r   r/   )	r   r   rP   rQ   r   Zcumsumr   r   rV   )	r   r   r   r   r   gridr   r   per   r   r    r$   X  s    zPositionEmbeddingRandom.forward)coords_input
image_sizeri   c                 C   sz   |  }|dddddf |d  |dddddf< |dddddf |d  |dddddf< | |tjS )z`Positionally encodes input coordinates, normalizing them to [0,1] based on the given image size.Nr   r   )cloner   r   rP   r   )r   r   r   r   r   r   r    forward_with_coordse  s    00z+PositionEmbeddingRandom.forward_with_coords)r   N)r&   r'   r(   r)   r5   r   r   r   rP   r   r   r   r$   r   r*   r   r   r   r    r   -  s
   	r   c                       s|   e Zd ZdZddejejddddfeeee	e
ej e
ej e	e	eeeeef  dd fdd	Zejejd
ddZ  ZS )Blocka  
    Transformer block with support for window attention and residual propagation.

    This class implements a transformer block that can use either global or windowed self-attention,
    followed by a feed-forward network. It supports relative positional embeddings and is designed
    for use in vision transformer architectures.

    Attributes:
        norm1 (nn.Module): First normalization layer.
        attn (REAttention): Self-attention layer with optional relative positional encoding.
        norm2 (nn.Module): Second normalization layer.
        mlp (MLPBlock): Multi-layer perceptron block.
        window_size (int): Size of attention window. If 0, global attention is used.

    Methods:
        forward: Processes input through the transformer block.

    Examples:
        >>> import torch
        >>> block = Block(dim=256, num_heads=8, window_size=7)
        >>> x = torch.randn(1, 56, 56, 256)
        >>> output = block(x)
        >>> print(output.shape)
        torch.Size([1, 56, 56, 256])
    r   TFr   N)rU   re   r   qkv_biasr   r   use_rel_posrel_pos_zero_initr   
input_sizeri   c                    sf   t    ||| _t||||||	dkr,|
n|	|	fd| _||| _t|t|| |d| _|	| _	dS )a  
        Initializes a transformer block with optional window attention and relative positional embeddings.

        This constructor sets up a transformer block that can use either global or windowed self-attention,
        followed by a feed-forward network. It supports relative positional embeddings and is designed
        for use in vision transformer architectures.

        Args:
            dim (int): Number of input channels.
            num_heads (int): Number of attention heads in the self-attention layer.
            mlp_ratio (float): Ratio of mlp hidden dimension to embedding dimension.
            qkv_bias (bool): If True, adds a learnable bias to query, key, value projections.
            norm_layer (Type[nn.Module]): Type of normalization layer to use.
            act_layer (Type[nn.Module]): Type of activation function to use in the MLP block.
            use_rel_pos (bool): If True, uses relative positional embeddings in attention.
            rel_pos_zero_init (bool): If True, initializes relative positional parameters to zero.
            window_size (int): Size of attention window. If 0, uses global attention.
            input_size (Optional[Tuple[int, int]]): Input resolution for calculating relative positional parameter size.

        Examples:
            >>> block = Block(dim=256, num_heads=8, window_size=7)
            >>> x = torch.randn(1, 56, 56, 256)
            >>> output = block(x)
            >>> print(output.shape)
            torch.Size([1, 56, 56, 256])
        r   )re   r   r   r   r   )rd   rf   rM   N)
r   r   r   REAttentionr   r   r   r5   rk   r   )r   rU   re   r   r   r   r   r   r   r   r   r   r   r    r     s    '

	
zBlock.__init__r   c                 C   s   |}|  |}| jdkr>|jd |jd  }}t|| j\}}| |}| jdkrft|| j|||f}|| }|| | | S )zhProcesses input through transformer block with optional windowed self-attention and residual connection.r   r   r/   )r   r   r!   r   r   r   rk   r   )r   r#   r   r   r   r   r   r   r    r$     s    



zBlock.forward)r&   r'   r(   r)   r	   r   rA   r5   r   rn   r   rm   r   r   r   rP   r   r$   r*   r   r   r   r    r   m  s.   7r   c                
       sT   e Zd ZdZdeeeeeeeeef  dd fddZe	j
e	j
d	d
dZ  ZS )r   a  
    Rotary Embedding Attention module for efficient self-attention in transformer architectures.

    This class implements a multi-head attention mechanism with rotary positional embeddings, designed
    for use in vision transformer models. It supports optional query pooling and window partitioning
    for efficient processing of large inputs.

    Attributes:
        compute_cis (Callable): Function to compute axial complex numbers for rotary encoding.
        freqs_cis (Tensor): Precomputed frequency tensor for rotary encoding.
        rope_k_repeat (bool): Flag to repeat query RoPE to match key length for cross-attention to memories.
        q_proj (nn.Linear): Linear projection for query.
        k_proj (nn.Linear): Linear projection for key.
        v_proj (nn.Linear): Linear projection for value.
        out_proj (nn.Linear): Output projection.
        num_heads (int): Number of attention heads.
        internal_dim (int): Internal dimension for attention computation.

    Methods:
        forward: Applies rotary position encoding and computes attention between query, key, and value tensors.

    Examples:
        >>> rope_attn = REAttention(embedding_dim=256, num_heads=8, rope_theta=10000.0, feat_sizes=(32, 32))
        >>> q = torch.randn(1, 1024, 256)
        >>> k = torch.randn(1, 1024, 256)
        >>> v = torch.randn(1, 1024, 256)
        >>> output = rope_attn(q, k, v)
        >>> print(output.shape)
        torch.Size([1, 1024, 256])
       TFN)rU   re   r   r   r   r   ri   c                    s   t    || _|| }|d | _tj||d |d| _t||| _|| _| jr|dusbJ dt	t
d|d  d || _t	t
d|d  d || _dS )	a  
        Initializes a Relative Position Attention module for transformer-based architectures.

        This module implements multi-head attention with optional relative positional encodings, designed
        specifically for vision tasks in transformer models.

        Args:
            dim (int): Number of input channels.
            num_heads (int): Number of attention heads. Default is 8.
            qkv_bias (bool): If True, adds a learnable bias to query, key, value projections. Default is True.
            use_rel_pos (bool): If True, uses relative positional encodings. Default is False.
            rel_pos_zero_init (bool): If True, initializes relative positional parameters to zero. Default is True.
            input_size (Tuple[int, int] | None): Input resolution for calculating relative positional parameter size.
                Required if use_rel_pos is True. Default is None.

        Examples:
            >>> attention = REAttention(dim=256, num_heads=8, input_size=(32, 32))
            >>> x = torch.randn(1, 32, 32, 256)
            >>> output = attention(x)
            >>> print(output.shape)
            torch.Size([1, 32, 32, 256])
        r   rD   )ZbiasNzBInput size must be provided if using relative positional encoding.r/   r   r   )r   r   re   r   r	   rK   r   r`   r   rO   rP   Zzeros	rel_pos_h	rel_pos_w)r   rU   re   r   r   r   r   r   r   r   r    r     s    

 zREAttention.__init__r   c                 C   s   |j \}}}}| |||| d| jdddddd}|d|| j || dd\}}}	|| j |dd }
| jrt	|
|| j
| j||f||f}
|
jdd}
|
|	 || j||dddddd|||d}| |S )	zXApplies multi-head attention with optional relative positional encoding to input tensor.rD   r   r/   r   r   r-   r   r   )r!   r   r   re   rV   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$     s    ,&2zREAttention.forward)r   TFTN)r&   r'   r(   r)   r5   rn   r   r   r   rP   r   r$   r*   r   r   r   r    r     s    "     .r   c                       s^   e Zd ZdZdeeef eeef eeef eedd fdd	Zejejd
ddZ	  Z
S )
PatchEmbeda   
    Image to Patch Embedding module for vision transformer architectures.

    This module converts an input image into a sequence of patch embeddings using a convolutional layer.
    It is commonly used as the first layer in vision transformer architectures to transform image data
    into a suitable format for subsequent transformer blocks.

    Attributes:
        proj (nn.Conv2d): Convolutional layer for projecting image patches to embeddings.

    Methods:
        forward: Applies patch embedding to the input tensor.

    Examples:
        >>> patch_embed = PatchEmbed(kernel_size=(16, 16), stride=(16, 16), in_chans=3, embed_dim=768)
        >>> x = torch.randn(1, 3, 224, 224)
        >>> output = patch_embed(x)
        >>> print(output.shape)
        torch.Size([1, 768, 14, 14])
    r.   r.   r   r   rD      N)r1   r2   r3   in_chansr<   ri   c                    s$   t    tj|||||d| _dS )a  
        Initializes the PatchEmbed module for converting image patches to embeddings.

        This module is typically used as the first layer in vision transformer architectures to transform
        image data into a suitable format for subsequent transformer blocks.

        Args:
            kernel_size (Tuple[int, int]): Size of the convolutional kernel for patch extraction.
            stride (Tuple[int, int]): Stride of the convolutional operation.
            padding (Tuple[int, int]): Padding applied to the input before convolution.
            in_chans (int): Number of input image channels.
            embed_dim (int): Dimensionality of the output patch embeddings.

        Examples:
            >>> patch_embed = PatchEmbed(kernel_size=(16, 16), stride=(16, 16), in_chans=3, embed_dim=768)
            >>> x = torch.randn(1, 3, 224, 224)
            >>> output = patch_embed(x)
            >>> print(output.shape)
            torch.Size([1, 768, 14, 14])
        r0   N)r   r   r	   r;   r`   )r   r1   r2   r3   r   r<   r   r   r    r   G  s    
zPatchEmbed.__init__r   c                 C   s   |  |ddddS )zRComputes patch embedding by applying convolution and transposing resulting tensor.r   r/   rD   r   )r`   rV   r@   r   r   r    r$   g  s    zPatchEmbed.forward)r   r   r   rD   r   )r&   r'   r(   r)   r   r5   r   rP   r   r$   r*   r   r   r   r    r   1  s        


 r   )N)0rY   r6   	functoolsr   typingr   r   r   r   r   numpyr   rP   Ztorch.nn.functionalr	   Z
functionalr   r   Zultralytics.nn.modulesr
   r   r   Ztransformerr   r   r   utilsr   r   r   r   r   rm   r   r+   rB   rX   rc   ro   rr   r   r   r   r   r   r   r   r   r   r   r   r    <module>   s2   #<^8?NSPss@d`