Ë
    Fêñi±­  ã                  ó¼  — d dl mZ d dlZd dlZd dlmZ d dlZd dlZd dl	m
c 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
e
j8                  «      Z G d„ de
j8                  «      Z G d„ de
j8                  «      Z G d„ de
j8                  «      Z  G d„ de«      Z! G d„ de«      Z" G d„ de«      Z#d&d'd„Z$ G d„ de
j8                  «      Z% G d„ de
j8                  «      Z& G d„ de
j8                  «      Z' G d„ de
j8                  «      Z( G d „ d!e
j8                  «      Z) G d"„ d#e
j8                  «      Z* G d$„ d%e
j8                  «      Z+y)(é    )ÚannotationsN)Úpartial)ÚTensorÚnn)ÚMLPÚLayerNorm2dÚMLPBlocké   )Ú	AttentionÚTwoWayAttentionBlockÚTwoWayTransformer)Úadd_decomposed_rel_posÚapply_rotary_encÚcompute_axial_cisÚwindow_partitionÚwindow_unpartitionc                  ó.   ‡ — e Zd ZdZddˆ fd„Zdd„Zˆ x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)
    c                ó>   •— t         ‰| �  «        || _        || _        y)zOInitialize DropPath module for stochastic depth regularization during training.N)ÚsuperÚ__init__Ú	drop_probÚscale_by_keep)Úselfr   r   Ú	__class__s      €úg/var/www/pod-logistic/pod-ai/venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/blocks.pyr   zDropPath.__init__#   s   ø€ ä‰ÑÔØ"ˆŒØ*ˆÕó    c                ó.  — | j                   dk(  s| j                  s|S d| j                   z
  }|j                  d   fd|j                  dz
  z  z   }|j	                  |«      j                  |«      }|dkD  r| j                  r|j                  |«       ||z  S )zNApply stochastic depth to input tensor during training, with optional scaling.ç        r
   r   )r
   )r   ÚtrainingÚshapeÚndimÚ	new_emptyÚ
bernoulli_r   Údiv_)r   ÚxÚ	keep_probr!   Úrandom_tensors        r   ÚforwardzDropPath.forward)   s‰   € à�>‰>˜SÒ ¨¯ªØˆHØ˜Ÿ™Ñ&ˆ	Ø—‘˜‘� ¨¯©°©
Ñ 3Ñ3ˆØŸ™ EÓ*×5Ñ5°iÓ@ˆØ�sŠ?˜t×1Ò1Ø×Ñ˜yÔ)Ø�=Ñ Ð r   )r   T)r   Úfloatr   Úbool©r&   r   Úreturnr   ©Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r)   Ú__classcell__©r   s   @r   r   r      s   ø„ ñö+÷	!r   r   c                  ój   ‡ — e Zd ZdZdddddej
                  df	 	 	 	 	 	 	 	 	 	 	 	 	 d	ˆ fd„Zd
d„Zˆ x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   é   Nc           
     óV  •— t         ‰| �  «        t        t        j                  |«      t        j                  |«      z  «      }||z  |k(  sJ ‚t        j                  «       | _        d\  }	}
t        |«      D ]ƒ  }|	|dz  z  }
| j                  j                  t        j                  |	|
|||¬«      «       | j                  j                  t        |
«      «       | j                  j                   |«       «       |
}	Œ… | j                  j                  t        j                  |
|d¬«      «       || _        | j                  �it        | j                  t        t        f«      sJ dt!        | j                  «      › d�«       ‚t        |«      | _        t#        | j                  «      dk(  sJ ‚yy)	zXInitialize a mask downsampler module for progressive downsampling and channel expansion.)r
   r
   é   )Úkernel_sizeÚstrideÚpaddingr
   ©r<   NzUnsupported type z. Should be a list or tuple.)r   r   ÚintÚmathÚlog2r   Ú
SequentialÚencoderÚrangeÚappendÚConv2dr   Úinterpol_sizeÚ
isinstanceÚlistÚtupleÚtypeÚlen)r   Ú	embed_dimr<   r=   r>   Útotal_strideÚ
activationrH   Ú
num_layersÚmask_in_chansÚmask_out_chansÚ_r   s               €r   r   zMaskDownSampler.__init__J   sx  ø€ ô 	‰ÑÔÜœŸ™ <Ó0´D·I±I¸fÓ4EÑEÓFˆ
Ø�zÑ! \Ò1Ð1Ð1Ü—}‘}“ˆŒØ(,Ñ%ˆ�~Ü�zÓ"ò 	+ˆAØ*¨f°a©iÑ8ˆNØ�L‰L×ÑÜ—	‘	Ø!Ø"Ø +Ø!Ø#ôôð �L‰L×Ñ¤¨NÓ ;Ô<Ø�L‰L×Ñ¡
£Ô-Ø*‰Mð	+ð 	�‰×ÑœBŸI™I n°iÈQÔOÔPØ*ˆÔØ×ÑÐ)Ü˜d×0Ñ0´4¼°-Ô@ð Ø#¤D¨×);Ñ);Ó$<Ð#=Ð=YÐZóÐ@ô "& mÓ!4ˆDÔÜ�t×)Ñ)Ó*¨aÒ/Ð/Ñ/ð *r   c                ó  — | j                   �p| j                   t        |j                  dd «      k7  rKt        j                  |j                  «       | j                   ddd¬«      j                  |j                  «      }| j                  |«      S )zbDownsample and encode input mask to embed_dim channels using convolutional layers and LayerNorm2d.NéþÿÿÿFÚbilinearT)ÚsizeÚalign_cornersÚmodeÚ	antialias)	rH   rJ   r!   ÚFÚinterpolater*   ÚtoÚdtyperD   ©r   r&   s     r   r)   zMaskDownSampler.forwardr   sw   € à×ÑÐ)¨d×.@Ñ.@ÄDÈÏÉÐQSÐQTÈÓDVÒ.VÜ—‘Ø—‘“	Ø×'Ñ'Ø#ØØô÷ ‰b�—‘‹kð ð �|‰|˜A‹Ðr   )rN   r@   r<   r@   r=   r@   r>   r@   rO   r@   rP   útype[nn.Module]rH   útuple[int, int] | Noner,   ©	r/   r0   r1   r2   r   ÚGELUr   r)   r3   r4   s   @r   r6   r6   5   sr   ø„ ñð, ØØØØØ&(§g¡gØ04ð&0àð&0ð ð&0ð ð	&0ð
 ð&0ð ð&0ð $ð&0ð .õ&0÷P
r   r6   c                  óN   ‡ — e Zd ZdZ	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 dˆ fd„Zdd„Zˆ xZS )ÚCXBlockaY  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])
    c                ó  •— t         ‰| �  «        t        j                  |||||r|nd¬«      | _        t        |d¬«      | _        t        j                  |d|z  «      | _        t        j                  «       | _
        t        j                  d|z  |«      | _        |dkD  r-t        j                  |t        j                  |«      z  d¬«      nd	| _        |d
kD  rt!        |«      | _        y	t        j"                  «       | _        y	)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.
        r
   )r<   r>   Úgroupsç�íµ ÷Æ°>©Úepsr8   r   T)Úrequires_gradNr   )r   r   r   rG   Údwconvr   ÚnormÚLinearÚpwconv1rd   ÚactÚpwconv2Ú	ParameterÚtorchÚonesÚgammar   ÚIdentityÚ	drop_path)r   Údimr<   r>   rx   Úlayer_scale_init_valueÚ
use_dwconvr   s          €r   r   zCXBlock.__init__š   sÏ   ø€ ô, 	‰ÑÔÜ—i‘iØØØ#ØÙ$‘3¨!ô
ˆŒô   ¨Ô.ˆŒ	Ü—y‘y  a¨#¡gÓ.ˆŒÜ—7‘7“9ˆŒÜ—y‘y  S¡¨#Ó.ˆŒð &¨Ò)ô �L‰LÐ/´%·*±*¸S³/ÑAÐQUÕVàð 	Œ
ð
 1:¸C²œ )Ó,ˆ�ÄRÇ[Á[Ã]ˆ�r   c                ób  — |}| j                  |«      }| j                  |«      }|j                  dddd«      }| j                  |«      }| j	                  |«      }| j                  |«      }| j                  �| j                  |z  }|j                  dddd«      }|| j                  |«      z   }|S )z`Apply ConvNeXt block operations to input tensor, including convolutions and residual connection.r   r;   é   r
   )rm   rn   Úpermuterp   rq   rr   rv   rx   )r   r&   Úinputs      r   r)   zCXBlock.forwardÃ   sŸ   € àˆØ�K‰K˜‹NˆØ�I‰I�a‹LˆØ�I‰I�a˜˜A˜qÓ!ˆØ�L‰L˜‹OˆØ�H‰H�Q‹KˆØ�L‰L˜‹OˆØ�:‰:Ð!Ø—
‘
˜Q‘ˆAØ�I‰I�a˜˜A˜qÓ!ˆà�D—N‘N 1Ó%Ñ%ˆØˆr   )é   r}   r   ri   T)ry   r@   r<   r@   r>   r@   rx   r*   rz   r*   r{   r+   r,   r.   r4   s   @r   rf   rf      se   ø„ ñð: ØØØ(,Øð'Sàð'Sð ð'Sð ð	'Sð
 ð'Sð !&ð'Sð õ'S÷Rr   rf   c                  ó.   ‡ — e Zd ZdZddˆ fd„Zdd„Zˆ x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])
    c                ó.  •— t         ‰| �  «        t        j                  «       | _        t        j
                  t        |«      D �cg c]  }t        j                  |«      ‘Œ c}«      | _	        |r"|€J ‚t        j                  ||d¬«      | _        yyc c}w )aê  Initialize 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.
        Nr
   r?   )r   r   r   rw   ÚprojÚ
ModuleListrE   ÚcopyÚdeepcopyÚlayersrG   )r   ÚlayerrQ   ry   Úinput_projectionrT   r   s         €r   r   zFuser.__init__é   sr   ø€ ô 	‰ÑÔÜ—K‘K“MˆŒ	Ü—m‘mÄ5ÈÓCTÖ$U¸a¤T§]¡]°5Õ%9Ò$UÓVˆŒáØ�?Ð"�?ÜŸ	™	 # s¸Ô:ˆD�Ið ùò %Vs   ÁBc                óZ   — | j                  |«      }| j                  D ]
  } ||«      }Œ |S )zMApply a series of layers to the input tensor, optionally projecting it first.)r„   rˆ   )r   r&   r‰   s      r   r)   zFuser.forwardü   s0   € à�I‰I�a‹LˆØ—[‘[ò 	ˆEÙ�a“‰Að	àˆr   )NF)r‰   ú	nn.ModulerQ   r@   ry   z
int | NonerŠ   r+   r,   r.   r4   s   @r   r‚   r‚   Ô   s   ø„ ñö(;÷&r   r‚   c                  ó\   ‡ — e Zd ZdZdej
                  ddf	 	 	 	 	 	 	 	 	 	 	 	 	 dˆ fd„Zˆ x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;   Fc                óX   •— t         ‰| �  ||||||«       t        |||d|¬«      | _        y)av  Initialize 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.
        r;   ©rQ   rq   N)r   r   r   Úmlp)r   Úembedding_dimÚ	num_headsÚmlp_dimrP   Úattention_downsample_rateÚskip_first_layer_per   s          €r   r   z!SAM2TwoWayAttentionBlock.__init__   s3   ø€ ô. 	‰Ñ˜¨	°7¸JÐHaÐcvÔwÜ�} g¨}ÈÐPZÔ[ˆ�r   )r’   r@   r“   r@   r”   r@   rP   ra   r•   r@   r–   r+   r-   ÚNone©r/   r0   r1   r2   r   ÚReLUr   r3   r4   s   @r   rŽ   rŽ     sq   ø„ ñð> Ø&(§g¡gØ)*Ø$)ð\àð\ð ð\ð ð	\ð
 $ð\ð $'ð\ð "ð\ð 
÷\ñ \r   rŽ   c                  óX   ‡ — e Zd ZdZej
                  df	 	 	 	 	 	 	 	 	 	 	 	 	 dˆ fd„Zˆ x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;   c                óÚ   •— t         ‰| �  ||||||«       t        j                  «       | _        t        |«      D ]/  }| j                  j                  t        ||||||dk(  ¬«      «       Œ1 y)a  Initialize 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.
        r   )r’   r“   r”   rP   r•   r–   N)r   r   r   r…   rˆ   rE   rF   rŽ   )	r   Údepthr’   r“   r”   rP   r•   Úir   s	           €r   r   zSAM2TwoWayTransformer.__init__W  sm   ø€ ô, 	‰Ñ˜ ¨y¸'À:ÐOhÔiÜ—m‘m“oˆŒÜ�u“ò 
	ˆAØ�K‰K×ÑÜ(Ø"/Ø'Ø#Ø)Ø.GØ)*¨a©ôõ	ñ
	r   )r�   r@   r’   r@   r“   r@   r”   r@   rP   ra   r•   r@   r-   r—   r˜   r4   s   @r   r›   r›   ;  sc   ø„ ñðB ')§g¡gØ)*ð"àð"ð ð"ð ð	"ð
 ð"ð $ð"ð $'ð"ð 
÷"ñ "r   r›   c                  óB   ‡ — e Zd ZdZddddœ	 	 	 	 	 dˆ fd„Zd	d
d„Zˆ x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 (torch.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)é    r¡   )Ú
rope_thetaÚrope_k_repeatÚ
feat_sizesc               óÎ   •— t        ‰| �  |i |¤Ž t        t        | j                  | j
                  z  |¬«      | _        | j                  |d   |d   ¬«      }|| _        || _        y)zYInitialize RoPEAttention with rotary position encoding for enhanced positional awareness.)ry   Úthetar   r
   ©Úend_xÚend_yN)	r   r   r   r   Úinternal_dimr“   Úcompute_cisÚ	freqs_cisr£   )r   r¢   r£   r¤   ÚargsÚkwargsr¬   r   s          €r   r   zRoPEAttention.__init__”  se   ø€ ô 	‰Ñ˜$Ð) &Ò)ä"Ô#4¸$×:KÑ:KÈtÏ~É~Ñ:]ÐeoÔpˆÔØ×$Ñ$¨:°a©=À
È1ÁÐ$ÓNˆ	Ø"ˆŒØ*ˆÕr   c                óÔ  — | j                  |«      }| j                  |«      }| j                  |«      }| j                  || j                  «      }| j                  || j                  «      }| j                  || j                  «      }t        j                  |j                  d   «      x}}| j                  j                  |j                  «      | _        | j                  j                  d   |j                  d   k7  r1| j                  ||¬«      j                  |j                  «      | _        |j                  d   |j                  d   k7  r| j                  sJ ‚|j                  d«      |z
  }t        ||dd…dd…d|…f   | j                  | j                  ¬«      \  }|dd…dd…d|…f<   t        j                   |||«      }| j#                  |«      }| j%                  |«      }|S )z[Apply rotary position encoding and compute attention between query, key, and value tensors.rV   r   r§   N)r¬   Úrepeat_freqs_k)Úq_projÚk_projÚv_projÚ_separate_headsr“   rA   Úsqrtr!   r¬   r^   Údevicer«   r£   rX   r   r\   Úscaled_dot_product_attentionÚ_recombine_headsÚout_proj)	r   ÚqÚkÚvÚnum_k_exclude_ropeÚwÚhÚ
num_k_ropeÚouts	            r   r)   zRoPEAttention.forward¤  s¡  € à�K‰K˜‹NˆØ�K‰K˜‹NˆØ�K‰K˜‹Nˆð × Ñ   D§N¡NÓ3ˆØ× Ñ   D§N¡NÓ3ˆØ× Ñ   D§N¡NÓ3ˆô —	‘	˜!Ÿ'™' "™+Ó&Ð&ˆˆAØŸ™×*Ñ*¨1¯8©8Ó4ˆŒØ�>‰>×Ñ Ñ" a§g¡g¨b¡kÒ1Ø!×-Ñ-°A¸QÐ-Ó?×BÑBÀ1Ç8Á8ÓLˆDŒNØ�7‰7�2‰;˜!Ÿ'™' "™+Ò%Ø×%Ò%Ð%Ð%à—V‘V˜B“ZÐ"4Ñ4ˆ
Ü"2ØØŠa’�K�Z�KÐÑ Ø—n‘nØ×-Ñ-ô	#
Ñˆˆ1ŠQ’�;�J�;ÐÑô ×,Ñ,¨Q°°1Ó5ˆà×#Ñ# CÓ(ˆØ�m‰m˜CÓ ˆàˆ
r   )r¢   r*   r£   r+   r¤   útuple[int, int])r   )
rº   útorch.Tensorr»   rÃ   r¼   rÃ   r½   r@   r-   rÃ   r.   r4   s   @r   r    r    |  s@   ø„ ñð4 $Ø#Ø&.ñ+ð ð+ð ð	+ð
 $õ+÷ !ð !r   r    c                ó‚   — |€| S | j                  dddd«      }  || «      } | j                  dddd«      } |r || «      } | S )z^Apply pooling and optional normalization to a tensor, handling spatial dimension permutations.r   r}   r
   r;   )r~   )r&   Úpoolrn   s      r   Údo_poolrÆ   È  sN   € à€|Øˆà	�	‰	�!�Q˜˜1Ó€AÙˆQ‹€Aà	�	‰	�!�Q˜˜1Ó€AÙÙ�‹Gˆà€Hr   c                  ó>   ‡ — e Zd ZdZ	 d	 	 	 	 	 	 	 dˆ fd„Zdd„Zˆ xZS )ÚMultiScaleAttentiona‘  Implements multiscale self-attention with optional query pooling for efficient feature extraction.

    This class provides a flexible implementation of multiscale attention, allowing for optional downsampling of query
    features through pooling. It's designed to enhance the model's ability to capture multiscale 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 multiscale 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])
    c                óê   •— t         ‰| �  «        || _        || _        || _        ||z  }|dz  | _        || _        t        j                  ||dz  «      | _	        t        j                  ||«      | _
        y)z]Initialize multiscale attention with optional query pooling for efficient feature extraction.ç      à¿r}   N)r   r   ry   Údim_outr“   ÚscaleÚq_poolr   ro   Úqkvr„   )r   ry   rË   r“   rÍ   Úhead_dimr   s         €r   r   zMultiScaleAttention.__init__ô  si   ø€ ô 	‰ÑÔàˆŒØˆŒà"ˆŒØ˜iÑ'ˆØ˜t‘^ˆŒ
àˆŒÜ—9‘9˜S '¨A¡+Ó.ˆŒÜ—I‘I˜g wÓ/ˆ�	r   c                óˆ  — |j                   \  }}}}| j                  |«      j                  |||z  d| j                  d«      }t	        j
                  |d«      \  }}}	| j                  r[t        |j                  |||d«      | j                  «      }|j                   dd \  }}|j                  |||z  | j                  d«      }t        j                  |j                  dd«      |j                  dd«      |	j                  dd«      «      }|j                  dd«      }|j                  |||d«      }| j                  |«      }|S )zVApply multiscale attention with optional query pooling to extract multiscale features.r}   éÿÿÿÿr;   r
   )r!   rÎ   Úreshaper“   rt   ÚunbindrÍ   rÆ   r\   r·   Ú	transposer„   )
r   r&   ÚBÚHÚWrT   rÎ   rº   r»   r¼   s
             r   r)   zMultiScaleAttention.forward	  s  € à—W‘W‰
ˆˆ1ˆa�à�h‰h�q‹k×!Ñ! ! Q¨¡U¨A¨t¯~©~¸rÓBˆä—,‘,˜s AÓ&‰ˆˆ1ˆað �;Š;Ü˜Ÿ	™	 ! Q¨¨2Ó.°·±Ó<ˆAØ—7‘7˜1˜Q�<‰DˆAˆqØ—	‘	˜!˜Q ™U D§N¡N°BÓ7ˆAô ×*Ñ*Ø�K‰K˜˜1ÓØ�K‰K˜˜1ÓØ�K‰K˜˜1Óó
ˆð �K‰K˜˜1ÓˆØ�I‰I�a˜˜A˜rÓ"ˆà�I‰I�a‹Lˆàˆr   ©N)ry   r@   rË   r@   r“   r@   rÍ   rŒ   ©r&   rÃ   r-   rÃ   r.   r4   s   @r   rÈ   rÈ   ×  s>   ø„ ñðB !ð0àð0ð ð0ð ð	0ð
 õ0÷*r   rÈ   c                  óp   ‡ — e Zd ZdZddddej
                  df	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d	ˆ fd„Zd
d„Zˆ xZS )ÚMultiScaleBlocka  A multiscale attention block with window partitioning and query pooling for efficient vision transformers.

    This class implements a multiscale 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 multiscale 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   c
                óX  •— t         ‰
| �  «        t        |t        «      rt	        t        t        |«      d¬«      }|| _        || _         ||«      | _	        |	| _
        d|c| _        | _        | j                  rt        j                  ||d¬«      | _        t        |||| j                  ¬«      | _        |dkD  rt!        |«      nt        j"                  «       | _         ||«      | _        t)        |t+        ||z  «      |d|¬	«      | _        ||k7  rt        j.                  ||«      | _        yy)
z\Initialize a multiscale attention block with window partitioning and optional query pooling.ri   rj   NF)r<   r=   Ú	ceil_mode)r“   rÍ   r   r;   r�   )r   r   rI   Ústrr   Úgetattrr   ry   rË   Únorm1Úwindow_sizerÅ   Úq_strideÚ	MaxPool2drÈ   Úattnr   rw   rx   Únorm2r   r@   r‘   ro   r„   )r   ry   rË   r“   Ú	mlp_ratiorx   Ú
norm_layerrä   Ú	act_layerrã   r   s             €r   r   zMultiScaleBlock.__init__D  s  ø€ ô 	‰ÑÔä�j¤#Ô&Ü ¤¬¨ZÓ!8¸dÔCˆJàˆŒØˆŒÙ “_ˆŒ
à&ˆÔà#'¨Ð ˆŒ	�4”=Ø�=Š=ÜŸ™°À(ÐV[Ô\ˆDŒIä'ØØØØ—9‘9ô	
ˆŒ	ð 1:¸C²œ )Ô,ÄRÇ[Á[Ã]ˆŒá Ó(ˆŒ
ÜØÜ�˜)Ñ#Ó$ØØØô
ˆŒð �'Š>ÜŸ	™	 # wÓ/ˆD�Ið r   c                óÄ  — |}| j                  |«      }| j                  | j                  k7  r%t        | j	                  |«      | j
                  «      }| j                  }|dkD  r-|j                  d   |j                  d   }}t        ||«      \  }}| j                  |«      }| j                  rN| j                  | j                  d   z  }|j                  dd \  }}|||z  z
  |z  }|||z  z
  |z  }||z   ||z   f}| j                  dkD  rt        ||f«      }|| j                  |«      z   }|| j                  | j                  | j                  |«      «      «      z   }|S )z]Process input through multiscale attention and MLP, with optional windowing and downsampling.r   r
   r;   r}   )râ   ry   rË   rÆ   r„   rÅ   rã   r!   r   ræ   rä   r   rx   r‘   rç   )	r   r&   Úshortcutrã   rÖ   r×   Úpad_hwÚpad_hÚpad_ws	            r   r)   zMultiScaleBlock.forwardt  sV  € àˆØ�J‰J�q‹Mˆð �8‰8�t—|‘|Ò#Ü˜tŸy™y¨›|¨T¯Y©YÓ7ˆHð ×&Ñ&ˆØ˜Š?Ø—7‘7˜1‘:˜qŸw™w q™zˆqˆAÜ(¨¨KÓ8‰IˆAˆvð �I‰I�a‹LˆØ�=Š=à×*Ñ*¨d¯m©m¸AÑ.>Ñ>ˆKØ—>‘> ! AÐ&‰DˆAˆqà  1 {¡?Ñ2°kÑAˆEØ  1 {¡?Ñ2°kÑAˆEØ˜%‘i  U¡Ð+ˆFð ×Ñ˜aÒÜ" 1 k°6¸A¸q¸6ÓBˆAà�t—~‘~ aÓ(Ñ(ˆà�—‘˜tŸx™x¨¯
©
°1«Ó6Ó7Ñ7ˆØˆr   )ry   r@   rË   r@   r“   r@   rè   r*   rx   r*   ré   znn.Module | strrä   rb   rê   ra   rã   r@   rÙ   rc   r4   s   @r   rÛ   rÛ   &  s„   ø„ ñðD ØØ&1Ø+/Ø%'§W¡WØð.0àð.0ð ð.0ð ð	.0ð
 ð.0ð ð.0ð $ð.0ð )ð.0ð #ð.0ð õ.0÷`!r   rÛ   c                  óÖ   ‡ — e Zd ZdZ	 	 	 d	 	 	 	 	 	 	 dˆ fd„Zd	d„Z ej                  «       d
d„«       ZeZ	 ej                  «       dd„«       Z
 ej                  «       dd„«       Zˆ x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])
    c                óÔ   •— t         ‰| �  «        |dz  dk(  sJ d«       ‚|dz  | _        || _        || _        |�|st        d«      ‚|€dt        j                  z  }|| _        i | _	        y)z>Initialize 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_featsÚtemperatureÚ	normalizeÚ
ValueErrorrA   ÚpirÌ   Úcache)r   ró   rô   rõ   rÌ   r   s        €r   r   zPositionEmbeddingSine.__init__³  sy   ø€ ô 	‰ÑÔØ˜qÑ  AÒ%ÐCÐ'CÓCÐ%Ø*¨aÑ/ˆÔØ&ˆÔØ"ˆŒØÐ¡YÜÐJÓKÐKØˆ=ØœŸ™‘KˆEØˆŒ
àˆ�
r   c                ó  — t        |«      t        |«      k(  r"|j                  |j                  cxk(  rdk(  sJ ‚ J ‚|| j                  z  }|| j                  z  }t        j                  | j
                  t        j                  |j                  ¬«      }| j                  d|dz  z  | j
                  z  z  }|dd…df   |z  }|dd…df   |z  }t        j                  |dd…ddd…f   j                  «       |dd…ddd…f   j                  «       fd¬«      j                  d«      }t        j                  |dd…ddd…f   j                  «       |dd…ddd…f   j                  «       fd¬«      j                  d«      }||fS )zVEncode 2D positions using sine/cosine functions for transformer positional embeddings.r
   ©r_   r¶   r;   Nr   ©ry   )rM   r"   rÌ   rt   Úarangeró   Úfloat32r¶   rô   ÚstackÚsinÚcosÚflatten)r   r&   ÚyÚx_embedÚy_embedÚdim_tÚpos_xÚpos_ys           r   Ú
_encode_xyz PositionEmbeddingSine._encode_xyÈ  sa  € ä�1‹vœ˜Q›Ò A§F¡F¨a¯f©fÔ$9¸Ò$9Ð9Ð9Ð$9Ð9Ð9Ø�d—j‘j‘.ˆØ�d—j‘j‘.ˆä—‘˜T×/Ñ/´u·}±}ÈQÏXÉXÔVˆØ× Ñ  Q¨%°1©*Ñ%5¸×8JÑ8JÑ%JÑKˆàš˜4˜Ñ  5Ñ(ˆØš˜4˜Ñ  5Ñ(ˆÜ—‘˜U¢1 a d¨ d 7™^×/Ñ/Ó1°5º¸A¸D¸q¸D¸±>×3EÑ3EÓ3GÐHÈaÔP×XÑXÐYZÓ[ˆÜ—‘˜U¢1 a d¨ d 7™^×/Ñ/Ó1°5º¸A¸D¸q¸D¸±>×3EÑ3EÓ3GÐHÈaÔP×XÑXÐYZÓ[ˆØ�eˆ|Ðr   c                ó~   — | j                  ||«      \  }}t        j                  |||dd…df   |dd…df   fd¬«      S )zOEncode box coordinates and dimensions into positional embeddings for detection.Nr
   rû   )r  rt   Úcat)r   r&   r  r¾   r¿   r  r  s          r   Úencode_boxesz"PositionEmbeddingSine.encode_boxes×  sB   € ð —‘ q¨!Ó,‰ˆˆuÜ�y‰y˜% ¨ª!¨T¨'©
°A²a¸°g±JÐ?ÀQÔGÐGr   c                ó€  — |j                   |j                   |j                   c\  }}\  }}\  }}	||k(  r||k(  r
||k(  r||	k(  sJ ‚| j                  |j                  «       |j                  «       «      \  }
}|
j                  ||d«      |j                  ||d«      }}
t	        j
                  ||
|dd…dd…df   fd¬«      S )z>Encode 2D points with sinusoidal embeddings and append labels.rÑ   Nr;   rû   )r!   r  r  rÒ   rt   r
  )r   r&   r  ÚlabelsÚbxÚnxÚbyÚnyÚblÚnlr  r  s               r   Úencode_pointsz#PositionEmbeddingSine.encode_pointsß  s±   € ð ()§w¡w°·±¸¿¹Ð$‰ˆˆR‘(�2�r™H˜R Ø�RŠx˜B "šH¨¨rª°b¸B²hÐ>Ð>Ø—‘ q§y¡y£{°A·I±I³KÓ@‰ˆˆuØ—}‘} R¨¨RÓ0°%·-±-ÀÀBÈÓ2KˆuˆÜ�y‰y˜% ¨ªq²!°T¨zÑ(:Ð;ÀÔCÐCr   c           
     ó^  — |j                   d   |j                   d   f}|| j                  v r1| j                  |   d   j                  |j                   d   ddd«      S t        j                  d|j                   d   dz   t        j
                  |j                  ¬«      j                  ddd«      j                  |j                   d   d|j                   d   «      }t        j                  d|j                   d   dz   t        j
                  |j                  ¬«      j                  ddd«      j                  |j                   d   |j                   d   d«      }| j                  rDd}||dd…dd…dd…f   |z   z  | j                  z  }||dd…dd…dd…f   |z   z  | j                  z  }t        j                  | j                  t        j
                  |j                  ¬«      }| j                  d|dz  z  | j                  z  z  }|dd…dd…dd…df   |z  }|dd…dd…dd…df   |z  }t        j                  |dd…dd…dd…ddd…f   j                  «       |dd…dd…dd…ddd…f   j                  «       fd	¬
«      j                  d«      }t        j                  |dd…dd…dd…ddd…f   j                  «       |dd…dd…dd…ddd…f   j                  «       fd	¬
«      j                  d«      }t        j                   ||fd¬
«      j#                  dddd«      }	|	d   | j                  |<   |	S )zBGenerate sinusoidal position embeddings for 2D inputs like images.rV   rÑ   Nr   r
   rú   ri   r;   r8   rû   r}   )r!   rø   Úrepeatrt   rü   rý   r¶   Úviewrõ   rÌ   ró   rô   rþ   rÿ   r   r  r
  r~   )
r   r&   Ú	cache_keyr  r  rk   r  r  r  Úposs
             r   r)   zPositionEmbeddingSine.forwardè  s¿  € ð —W‘W˜R‘[ !§'¡'¨"¡+Ð.ˆ	Ø˜Ÿ
™
Ñ"Ø—:‘:˜iÑ(¨Ñ.×5Ñ5°a·g±g¸a±jÀ!ÀQÈÓJÐJä�L‰L˜˜AŸG™G B™K¨!™O´5·=±=ÈÏÉÔRß‰T�!�R˜‹^ß‰V�A—G‘G˜A‘J  1§7¡7¨2¡;Ó/ð 	ô �L‰L˜˜AŸG™G B™K¨!™O´5·=±=ÈÏÉÔRß‰T�!�Q˜‹^ß‰V�A—G‘G˜A‘J §¡¨¡¨QÓ/ð 	ð �>Š>ØˆCØ ª¨B©C²¨Ñ!3°cÑ!9Ñ:¸T¿Z¹ZÑGˆGØ ªªA¨r©s¨Ñ!3°cÑ!9Ñ:¸T¿Z¹ZÑGˆGä—‘˜T×/Ñ/´u·}±}ÈQÏXÉXÔVˆØ× Ñ  Q¨%°1©*Ñ%5¸×8JÑ8JÑ%JÑKˆàšš1ša ˜Ñ&¨Ñ.ˆØšš1ša ˜Ñ&¨Ñ.ˆÜ—‘˜U¢1¢aª¨A¨D¨q¨D =Ñ1×5Ñ5Ó7¸ºqÂ!ÂQÈÈÈ1È¸}Ñ9M×9QÑ9QÓ9SÐTÐZ[Ô\×dÑdÐefÓgˆÜ—‘˜U¢1¢aª¨A¨D¨q¨D =Ñ1×5Ñ5Ó7¸ºqÂ!ÂQÈÈÈ1È¸}Ñ9M×9QÑ9QÓ9SÐTÐZ[Ô\×dÑdÐefÓgˆÜ�i‰i˜ ˜¨AÔ.×6Ñ6°q¸!¸QÀÓBˆØ # A¡ˆ�
‰
�9ÑØˆ
r   )i'  TN)ró   r@   rô   r@   rõ   r+   rÌ   úfloat | None)r&   rÃ   r  rÃ   r-   z!tuple[torch.Tensor, torch.Tensor])
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   r   r  rt   Úno_gradr  Úencoder  r)   r3   r4   s   @r   rñ   rñ   ˜  s    ø„ ñð: !ØØ"ðàðð ðð ð	ð
 õó*ð €U‡]�]ƒ_òHó ðHð
 €Fà€U‡]�]ƒ_òDó ðDð €U‡]�]ƒ_òó ôr   rñ   c                  ó>   ‡ — e Zd ZdZddˆ fd„Zdd„Zd	d„Zd
d„Zˆ xZS )ÚPositionEmbeddingRandomaQ  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])
    c                óð   •— t         ‰| �  «        |�|dk  rd}| j                  d|t        j                  d|f«      z  «       t        j
                  d«       dt        j                  j                  _        y)zHInitialize random spatial frequency position embedding for transformers.Nr   g      ð?Ú#positional_encoding_gaussian_matrixr;   F)	r   r   Úregister_bufferrt   ÚrandnÚuse_deterministic_algorithmsÚbackendsÚcudnnÚdeterministic)r   ró   rÌ   r   s      €r   r   z PositionEmbeddingRandom.__init__   sf   ø€ ä‰ÑÔØˆ=˜E SšLØˆEØ×ÑÐBÀEÌEÏKÉKÐYZÐ\iÐXjÓLkÑDkÔlô 	×*Ñ*¨5Ô1Ø-2Œ�‰×ÑÕ*r   c                óÚ   — d|z  dz
  }|| j                   z  }dt        j                  z  |z  }t        j                  t        j
                  |«      t        j                  |«      gd¬«      S )zEEncode normalized [0,1] coordinates using random spatial frequencies.r;   r
   rÑ   rû   )r   Únpr÷   rt   r
  rÿ   r   )r   Úcoordss     r   Ú_pe_encodingz$PositionEmbeddingRandom._pe_encoding+  s[   € ð �V‘˜a‘ˆØ˜$×BÑBÑBˆØ”R—U‘U‘˜VÑ#ˆä�y‰yœ%Ÿ)™) FÓ+¬U¯Y©Y°vÓ->Ð?ÀRÔHÐHr   c                ón  — |\  }}t        j                  ||f| j                  j                  | j                  j                  ¬«      }|j                  d¬«      dz
  }|j                  d¬«      dz
  }||z  }||z  }| j                  t        j                  ||gd¬«      «      }|j                  ddd«      S )zIGenerate positional encoding for a grid using random spatial frequencies.)r¶   r_   r   rû   g      à?r
   rÑ   r;   )	rt   ru   r   r¶   r_   Úcumsumr*  rþ   r~   )r   rX   r¿   r¾   Úgridr  r  Úpes           r   r)   zPositionEmbeddingRandom.forward4  s¯   € à‰ˆˆ1Ü�z‰zØ�ˆFØ×;Ñ;×BÑBØ×:Ñ:×@Ñ@ô
ˆð
 —+‘+ !�+Ó$ sÑ*ˆØ—+‘+ !�+Ó$ sÑ*ˆØ˜A‘+ˆØ˜A‘+ˆà×ÑœuŸ{™{¨G°WÐ+=À2ÔFÓGˆØ�z‰z˜!˜Q Ó"Ð"r   c                ó´   — |j                  «       }|dd…dd…df   |d   z  |dd…dd…df<   |dd…dd…df   |d   z  |dd…dd…df<   | j                  |«      S )z_Positionally encode input coordinates, normalizing them to [0,1] based on the given image size.Nr   r
   )Úcloner*  )r   Úcoords_inputÚ
image_sizer)  s       r   Úforward_with_coordsz+PositionEmbeddingRandom.forward_with_coordsD  se   € à×#Ñ#Ó%ˆØ ¢¢A q ™/¨J°q©MÑ9ˆŠq’!�Qˆw‰Ø ¢¢A q ™/¨J°q©MÑ9ˆŠq’!�Qˆw‰Ø× Ñ  Ó(Ð(r   )é@   N)ró   r@   rÌ   r  r-   r—   )r)  rÃ   r-   rÃ   )rX   rÂ   r-   rÃ   )r1  rÃ   r2  rÂ   r-   rÃ   )	r/   r0   r1   r2   r   r*  r)   r3  r3   r4   s   @r   r  r  
  s   ø„ ñö*	3óIó#÷ )r   r  c                  ó�   ‡ — e Zd ZdZddej
                  ej                  ddddf	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d	ˆ fd„Zd
d„Zˆ x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   Nc           	     óà   •— t         ‰| �  «         ||«      | _        t        ||||||	dk(  r|
n|	|	f¬«      | _         ||«      | _        t        |t        ||z  «      |¬«      | _        |	| _	        y)að  Initialize 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 (tuple[int, int] | None): Input resolution for calculating relative positional parameter size.
        r   )r“   Úqkv_biasÚuse_rel_posÚrel_pos_zero_initÚ
input_size)r’   r”   rq   N)
r   r   râ   ÚREAttentionræ   rç   r	   r@   r‘   rã   )r   ry   r“   rè   r8  ré   rê   r9  r:  rã   r;  r   s              €r   r   zBlock.__init__f  sv   ø€ ô> 	‰ÑÔÙ “_ˆŒ
ÜØØØØ#Ø/Ø%0°AÒ%5‘z¸KÈÐ;Uô
ˆŒ	ñ   “_ˆŒ
Ü¨#´s¸3À¹?Ó7KÐQZÔ[ˆŒà&ˆÕr   c                óx  — |}| j                  |«      }| j                  dkD  r7|j                  d   |j                  d   }}t        || j                  «      \  }}| j	                  |«      }| j                  dkD  rt        || j                  f«      }||z   }|| j                  | j                  |«      «      z   S )zfProcess input through transformer block with optional windowed self-attention and residual connection.r   r
   r;   )râ   rã   r!   r   ræ   r   r‘   rç   )r   r&   rì   rÖ   r×   rí   s         r   r)   zBlock.forward•  s«   € àˆØ�J‰J�q‹Mˆà×Ñ˜aÒØ—7‘7˜1‘:˜qŸw™w q™zˆqˆAÜ(¨¨D×,<Ñ,<Ó=‰IˆAˆvà�I‰I�a‹Lˆà×Ñ˜aÒÜ" 1 d×&6Ñ&6¸ÀÀAÀÓGˆAà�q‰LˆØ�4—8‘8˜DŸJ™J q›MÓ*Ñ*Ð*r   )ry   r@   r“   r@   rè   r*   r8  r+   ré   ra   rê   ra   r9  r+   r:  r+   rã   r@   r;  rb   r-   r—   rÙ   )
r/   r0   r1   r2   r   rÝ   rd   r   r)   r3   r4   s   @r   r6  r6  L  s¡   ø„ ñð: ØØ&(§l¡lØ%'§W¡WØ!Ø"&ØØ-1ð-'àð-'ð ð-'ð ð	-'ð
 ð-'ð $ð-'ð #ð-'ð ð-'ð  ð-'ð ð-'ð +ð-'ð 
õ-'÷^+r   r6  c                  óR   ‡ — e Zd ZdZ	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 dˆ fd„Zdd„Zˆ xZS )r<  aV  Relative Position Attention module for efficient self-attention in transformer architectures.

    This class implements a multi-head attention mechanism with relative positional embeddings, designed for use in
    vision transformer models.

    Attributes:
        num_heads (int): Number of attention heads.
        scale (float): Scaling factor for attention computation.
        qkv (nn.Linear): Linear projection for query, key, and value.
        proj (nn.Linear): Output projection layer.
        use_rel_pos (bool): Whether to use relative positional embeddings.
        rel_pos_h (nn.Parameter): Relative positional embeddings for height dimension.
        rel_pos_w (nn.Parameter): Relative positional embeddings for width dimension.

    Methods:
        forward: Applies multi-head attention with optional relative positional encoding to input tensor.

    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])
    c                óÚ  •— t         ‰| �  «        || _        ||z  }|dz  | _        t	        j
                  ||dz  |¬«      | _        t	        j
                  ||«      | _        || _        | j                  rx|€J d«       ‚t	        j                  t        j                  d|d   z  dz
  |«      «      | _        t	        j                  t        j                  d|d   z  dz
  |«      «      | _        yy)	a2  Initialize 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.
            qkv_bias (bool): If True, adds a learnable bias to query, key, value projections.
            use_rel_pos (bool): If True, uses relative positional encodings.
            rel_pos_zero_init (bool): If True, initializes relative positional parameters to zero.
            input_size (tuple[int, int] | None): Input resolution for calculating relative positional parameter size.
                Required if use_rel_pos is True.
        rÊ   r}   )ÚbiasNzBInput size must be provided if using relative positional encoding.r;   r   r
   )r   r   r“   rÌ   r   ro   rÎ   r„   r9  rs   rt   ÚzerosÚ	rel_pos_hÚ	rel_pos_w)	r   ry   r“   r8  r9  r:  r;  rÏ   r   s	           €r   r   zREAttention.__init__Á  sÐ   ø€ ô. 	‰ÑÔØ"ˆŒØ˜)Ñ#ˆØ˜t‘^ˆŒ
ä—9‘9˜S #¨¡'°Ô9ˆŒÜ—I‘I˜c 3Ó'ˆŒ	à&ˆÔØ×ÒØÐ)ÐoÐ+oÓoÐ)äŸ\™\¬%¯+©+°a¸*ÀQ¹-Ñ6GÈ!Ñ6KÈXÓ*VÓWˆDŒNÜŸ\™\¬%¯+©+°a¸*ÀQ¹-Ñ6GÈ!Ñ6KÈXÓ*VÓWˆD�Nð	 r   c           	     óš  — |j                   \  }}}}| j                  |«      j                  |||z  d| j                  d«      j	                  ddddd«      }|j                  d|| j                  z  ||z  d«      j                  d«      \  }}}	|| j                  z  |j                  dd«      z  }
| j                  r(t        |
|| j                  | j                  ||f||f«      }
|
j                  d¬«      }
|
|	z  j                  || j                  ||d«      j	                  ddddd«      j                  |||d«      }| j                  |«      S )	zVApply multi-head attention with optional relative positional encoding to input tensor.r}   rÑ   r;   r   r
   r8   rV   rû   )r!   rÎ   rÒ   r“   r~   rÓ   rÌ   rÔ   r9  r   rB  rC  Úsoftmaxr  r„   )r   r&   rÕ   rÖ   r×   rT   rÎ   rº   r»   r¼   ræ   s              r   r)   zREAttention.forwardç  s7  € à—W‘W‰
ˆˆ1ˆa�à�h‰h�q‹k×!Ñ! ! Q¨¡U¨A¨t¯~©~¸rÓB×JÑJÈ1ÈaÐQRÐTUÐWXÓYˆà—+‘+˜a  T§^¡^Ñ!3°Q¸±U¸BÓ?×FÑFÀqÓI‰ˆˆ1ˆaà�D—J‘J‘ !§+¡+¨b°"Ó"5Ñ5ˆà×ÒÜ)¨$°°4·>±>À4Ç>Á>ÐTUÐWXÐSYÐ\]Ð_`Ð[aÓbˆDà�|‰| ˆ|Ó#ˆØ�A‰X�O‰O˜A˜tŸ~™~¨q°!°RÓ8×@Ñ@ÀÀAÀqÈ!ÈQÓO×WÑWÐXYÐ[\Ð^_ÐacÓdˆØ�y‰y˜‹|Ðr   )é   TFTN)ry   r@   r“   r@   r8  r+   r9  r+   r:  r+   r;  rb   r-   r—   rÙ   r.   r4   s   @r   r<  r<  §  sp   ø„ ñð8 ØØ!Ø"&Ø-1ð$Xàð$Xð ð$Xð ð	$Xð
 ð$Xð  ð$Xð +ð$Xð 
õ$X÷Lr   r<  c                  óT   ‡ — e Zd ZdZ	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 dˆ fd„Zdd„Zˆ x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])
    c                ób   •— t         ‰| �  «        t        j                  ||||||¬«      | _        y)aÿ  Initialize 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.
            bias (bool): Whether to include a bias term in the convolutional layer.
        )r<   r=   r>   r@  N)r   r   r   rG   r„   )r   r<   r=   r>   Úin_chansrN   r@  r   s          €r   r   zPatchEmbed.__init__  s-   ø€ ô, 	‰ÑÔä—I‘I˜h¨	¸{ÐSYÐcjÐquÔvˆ�	r   c                óH   — | j                  |«      j                  dddd«      S )zQCompute patch embedding by applying convolution and transposing resulting tensor.r   r;   r}   r
   )r„   r~   r`   s     r   r)   zPatchEmbed.forward(  s!   € à�y‰y˜‹|×#Ñ# A q¨!¨QÓ/Ð/r   )©r9   r9   rL  )r   r   r}   i   T)r<   rÂ   r=   rÂ   r>   rÂ   rJ  r@   rN   r@   r@  r+   r-   r—   rÙ   r.   r4   s   @r   rH  rH  ù  sr   ø„ ñð, (0Ø"*Ø#)ØØØðwà$ðwð  ðwð !ð	wð
 ðwð ðwð ðwð 
õw÷40r   rH  rØ   )r&   rÃ   rÅ   rŒ   rn   rŒ   r-   rÃ   ),Ú
__future__r   r†   rA   Ú	functoolsr   Únumpyr(  rt   Útorch.nn.functionalr   Ú
functionalr\   r   Úultralytics.nn.modulesr   r   r	   Útransformerr   r   r   Úutilsr   r   r   r   r   ÚModuler   r6   rf   r‚   rŽ   r›   r    rÆ   rÈ   rÛ   rñ   r  r6  r<  rH  © r   r   ú<module>rW     s,  ðå "ã Û Ý ã Û ß Ð ß ç =Ñ =ç KÑ Kß tÕ tô!ˆr�y‰yô !ôDG�b—i‘iô GôTRˆb�i‰iô Rôj-ˆB�I‰Iô -ô`4\Ð3ô 4\ôn>Ð-ô >ôBI�Iô IôXôL˜"Ÿ)™)ô Lô^o�b—i‘iô oôdo˜BŸI™Iô oôd?)˜bŸi™iô ?)ôDX+ˆB�I‰Iô X+ôvO�"—)‘)ô Oôd10�—‘õ 10r   