
    h                     .   d dl Z d dlmZmZmZmZ d dlZd dlmZ d dl	mc m
Z d dlmZ d dlmZ  G d dej                  j                         Z G d dej$                        Z G d	 d
ej$                        Z G d dej$                        Z G d dej$                        Z G d dej$                        Z G d dej                  j$                        Z G d dej$                        Z G d dej$                        Z G d dej$                        Zy)    N)ListOptionalTupleUnion)LayerNorm2d)	to_2tuplec                   R     e Zd ZdZ	 	 	 	 	 	 ddededededededed	ef fd
Z xZS )	Conv2d_BNa  
    A sequential container that performs 2D convolution followed by batch normalization.

    This module combines a 2D convolution layer with batch normalization, providing a common building block
    for convolutional neural networks. The batch normalization weights and biases are initialized to specific
    values for optimal training performance.

    Attributes:
        c (torch.nn.Conv2d): 2D convolution layer.
        bn (torch.nn.BatchNorm2d): Batch normalization layer.

    Examples:
        >>> conv_bn = Conv2d_BN(3, 64, ks=3, stride=1, pad=1)
        >>> input_tensor = torch.randn(1, 3, 224, 224)
        >>> output = conv_bn(input_tensor)
        >>> print(output.shape)
        torch.Size([1, 64, 224, 224])
    abksstridepaddilationgroupsbn_weight_initc	                    t         
|           | j                  dt        j                  j                  |||||||d             t        j                  j                  |      }	t        j                  j                  j                  |	j                  |       t        j                  j                  j                  |	j                  d       | j                  d|	       y)a  
        Initialize a sequential container with 2D convolution followed by batch normalization.

        Args:
            a (int): Number of input channels.
            b (int): Number of output channels.
            ks (int, optional): Kernel size for the convolution.
            stride (int, optional): Stride for the convolution.
            pad (int, optional): Padding for the convolution.
            dilation (int, optional): Dilation factor for the convolution.
            groups (int, optional): Number of groups for the convolution.
            bn_weight_init (float, optional): Initial value for batch normalization weight.
        cF)biasr   bnN)super__init__
add_moduletorchnnConv2dBatchNorm2dinit	constant_weightr   )selfr   r   r   r   r   r   r   r   r   	__class__s             i/var/www/html/eduruby.in/venv/lib/python3.12/site-packages/ultralytics/models/sam/modules/tiny_encoder.pyr   zConv2d_BN.__init__+   s    0 	UXX__Q2vsHf[`_abXX!!!$		>:+b!    )   r%   r   r%   r%   r%   )__name__
__module____qualname____doc__intfloatr   __classcell__r"   s   @r#   r
   r
      st    .  !"" " 	"
 " " " " " "r$   r
   c                   h     e Zd ZdZdededef fdZdej                  dej                  fdZ xZ	S )	
PatchEmbeda  
    Embed images into patches and project them into a specified embedding dimension.

    This module converts input images into patch embeddings using a sequence of convolutional layers,
    effectively downsampling the spatial dimensions while increasing the channel dimension.

    Attributes:
        patches_resolution (Tuple[int, int]): Resolution of the patches after embedding.
        num_patches (int): Total number of patches.
        in_chans (int): Number of input channels.
        embed_dim (int): Dimension of the embedding.
        seq (nn.Sequential): Sequence of convolutional and activation layers for patch embedding.

    Examples:
        >>> import torch
        >>> patch_embed = PatchEmbed(in_chans=3, embed_dim=96, resolution=224, activation=nn.GELU)
        >>> x = torch.randn(1, 3, 224, 224)
        >>> output = patch_embed(x)
        >>> print(output.shape)
        torch.Size([1, 96, 56, 56])
    in_chans	embed_dim
resolutionc                 L   t         |           t        |      }|d   dz  |d   dz  f| _        | j                  d   | j                  d   z  | _        || _        || _        |}t        j                  t        ||dz  ddd       |       t        |dz  |ddd            | _
        y)a}  
        Initialize patch embedding with convolutional layers for image-to-patch conversion and projection.

        Args:
            in_chans (int): Number of input channels.
            embed_dim (int): Dimension of the embedding.
            resolution (int): Input image resolution.
            activation (nn.Module): Activation function to use between convolutions.
        r      r%         N)r   r   r   patches_resolutionnum_patchesr0   r1   r   
Sequentialr
   seq)r!   r0   r1   r2   
activationimg_sizenr"   s          r#   r   zPatchEmbed.__init__b   s     	$-j$9#+A;!#3Xa[A5E"F22158O8OPQ8RR "==hQ1a0La1faAq)
r$   xreturnc                 $    | j                  |      S )z]Process input tensor through patch embedding sequence, converting images to patch embeddings.)r:   r!   r>   s     r#   forwardzPatchEmbed.forwardy   s    xx{r$   )
r&   r'   r(   r)   r*   r   r   TensorrB   r,   r-   s   @r#   r/   r/   K   s=    ,
 
 
# 
. %,, r$   r/   c                   l     e Zd ZdZdedededef fdZdej                  dej                  fd	Z	 xZ
S )
MBConva  
    Mobile Inverted Bottleneck Conv (MBConv) layer, part of the EfficientNet architecture.

    This module implements the mobile inverted bottleneck convolution with expansion, depthwise convolution,
    and projection phases, along with residual connections for improved gradient flow.

    Attributes:
        in_chans (int): Number of input channels.
        hidden_chans (int): Number of hidden channels after expansion.
        out_chans (int): Number of output channels.
        conv1 (Conv2d_BN): First convolutional layer for channel expansion.
        act1 (nn.Module): First activation function.
        conv2 (Conv2d_BN): Depthwise convolutional layer.
        act2 (nn.Module): Second activation function.
        conv3 (Conv2d_BN): Final convolutional layer for projection.
        act3 (nn.Module): Third activation function.
        drop_path (nn.Module): Drop path layer (Identity for inference).

    Examples:
        >>> in_chans, out_chans = 32, 64
        >>> mbconv = MBConv(in_chans, out_chans, expand_ratio=4, activation=nn.ReLU, drop_path=0.1)
        >>> x = torch.randn(1, in_chans, 56, 56)
        >>> output = mbconv(x)
        >>> print(output.shape)
        torch.Size([1, 64, 56, 56])
    r0   	out_chansexpand_ratio	drop_pathc                    t         |           || _        t        ||z        | _        || _        t        || j                  d      | _         |       | _        t        | j                  | j                  ddd| j                        | _	         |       | _
        t        | j                  |dd      | _         |       | _        t        j                         | _        y)a  
        Initialize the MBConv layer with specified input/output channels, expansion ratio, and activation.

        Args:
            in_chans (int): Number of input channels.
            out_chans (int): Number of output channels.
            expand_ratio (float): Channel expansion ratio for the hidden layer.
            activation (nn.Module): Activation function to use.
            drop_path (float): Drop path rate for stochastic depth.
        r%   )r   r6   r   r   r   r           )r   r   N)r   r   r0   r*   hidden_chansrF   r
   conv1act1conv2act2conv3act3r   IdentityrH   )r!   r0   rF   rG   r;   rH   r"   s         r#   r   zMBConv.__init__   s     	 < 78"x):):qA
L	t00$2C2CRSYZcgctctu
L	t00)RUV
L	 r$   r>   r?   c                     |}| j                  |      }| j                  |      }| j                  |      }| j                  |      }| j	                  |      }| j                  |      }||z  }| j                  |      S )zPImplement the forward pass of MBConv, applying convolutions and skip connection.)rM   rN   rO   rP   rQ   rH   rR   )r!   r>   shortcuts      r#   rB   zMBConv.forward   sm    JJqMIIaLJJqMIIaLJJqMNN1	Xyy|r$   )r&   r'   r(   r)   r*   r+   r   r   rC   rB   r,   r-   s   @r#   rE   rE   ~   sE    6' ' 'E 'bg ':
 
%,, 
r$   rE   c                   r     e Zd ZdZdeeef   dedef fdZdej                  dej                  fdZ	 xZ
S )	PatchMerginga  
    Merge neighboring patches in the feature map and project to a new dimension.

    This class implements a patch merging operation that combines spatial information and adjusts the feature
    dimension using a series of convolutional layers with batch normalization. It effectively reduces spatial
    resolution while potentially increasing channel dimensions.

    Attributes:
        input_resolution (Tuple[int, int]): The input resolution (height, width) of the feature map.
        dim (int): The input dimension of the feature map.
        out_dim (int): The output dimension after merging and projection.
        act (nn.Module): The activation function used between convolutions.
        conv1 (Conv2d_BN): The first convolutional layer for dimension projection.
        conv2 (Conv2d_BN): The second convolutional layer for spatial merging.
        conv3 (Conv2d_BN): The third convolutional layer for final projection.

    Examples:
        >>> input_resolution = (56, 56)
        >>> patch_merging = PatchMerging(input_resolution, dim=64, out_dim=128, activation=nn.ReLU)
        >>> x = torch.randn(4, 64, 56, 56)
        >>> output = patch_merging(x)
        >>> print(output.shape)
        torch.Size([4, 3136, 128])
    input_resolutiondimout_dimc                     t         |           || _        || _        || _         |       | _        t        ||ddd      | _        |dv rdnd}t        ||d|d|      | _        t        ||ddd      | _	        y)a  
        Initialize the PatchMerging module for merging and projecting neighboring patches in feature maps.

        Args:
            input_resolution (Tuple[int, int]): The input resolution (height, width) of the feature map.
            dim (int): The input dimension of the feature map.
            out_dim (int): The output dimension after merging and projection.
            activation (nn.Module): The activation function used between convolutions.
        r%   r   >   @  @    r5   r6   )r   N)
r   r   rX   rY   rZ   actr
   rM   rO   rQ   )r!   rX   rY   rZ   r;   stride_cr"   s         r#   r   zPatchMerging.__init__   s{     	 0<sGQ15
?21wHaP
wAq9
r$   r>   r?   c                    |j                   dk(  r@| j                  \  }}t        |      }|j                  |||d      j	                  dddd      }| j                  |      }| j                  |      }| j                  |      }| j                  |      }| j                  |      }|j                  d      j                  dd      S )zFApply patch merging and dimension projection to the input feature map.r6   r   r%   r5   )ndimrX   lenviewpermuterM   r_   rO   rQ   flatten	transpose)r!   r>   HWBs        r#   rB   zPatchMerging.forward   s    66Q;((DAqAAq!Q#++Aq!Q7AJJqMHHQKJJqMHHQKJJqMyy|%%a++r$   )r&   r'   r(   r)   r   r*   r   r   rC   rB   r,   r-   s   @r#   rW   rW      sE    2:sCx :s :S :*, ,%,, ,r$   rW   c                        e Zd ZdZ	 	 	 	 	 ddedeeef   dedeeee   f   de	e
j                     dede	e   d	ef fd
Zdej                  dej                  fdZ xZS )	ConvLayera  
    Convolutional Layer featuring multiple MobileNetV3-style inverted bottleneck convolutions (MBConv).

    This layer optionally applies downsample operations to the output and supports gradient checkpointing
    for memory efficiency during training.

    Attributes:
        dim (int): Dimensionality of the input and output.
        input_resolution (Tuple[int, int]): Resolution of the input image.
        depth (int): Number of MBConv layers in the block.
        use_checkpoint (bool): Whether to use gradient checkpointing to save memory.
        blocks (nn.ModuleList): List of MBConv layers.
        downsample (Optional[nn.Module]): Function for downsampling the output.

    Examples:
        >>> input_tensor = torch.randn(1, 64, 56, 56)
        >>> conv_layer = ConvLayer(64, (56, 56), depth=3, activation=nn.ReLU)
        >>> output = conv_layer(input_tensor)
        >>> print(output.shape)
        torch.Size([1, 3136, 128])
    rY   rX   depthrH   
downsampleuse_checkpointrZ   conv_expand_ratioc
                 @   t         |           || _        || _        || _        || _        t        j                  t        |      D 
cg c]&  }
t        |||	|t        |t              r||
   n|      ( c}
      | _        |d| _        y |||||      | _        yc c}
w )aY  
        Initialize the ConvLayer with the given dimensions and settings.

        This layer consists of multiple MobileNetV3-style inverted bottleneck convolutions (MBConv) and
        optionally applies downsampling to the output.

        Args:
            dim (int): The dimensionality of the input and output.
            input_resolution (Tuple[int, int]): The resolution of the input image.
            depth (int): The number of MBConv layers in the block.
            activation (nn.Module): Activation function applied after each convolution.
            drop_path (float | List[float], optional): Drop path rate. Single float or a list of floats for each MBConv.
            downsample (Optional[nn.Module], optional): Function for downsampling the output. None to skip downsampling.
            use_checkpoint (bool, optional): Whether to use gradient checkpointing to save memory.
            out_dim (Optional[int], optional): The dimensionality of the output. None means it will be the same as `dim`.
            conv_expand_ratio (float, optional): Expansion ratio for the MBConv layers.
        NrY   rZ   r;   )r   r   rY   rX   rn   rp   r   
ModuleListrangerE   
isinstancelistblocksro   )r!   rY   rX   rn   r;   rH   ro   rp   rZ   rq   ir"   s              r#   r   zConvLayer.__init__  s    : 	 0
, mm u	  %$.y$$?IaLY	
  !  	 ,#wS]^ 		s   +Br>   r?   c                     | j                   D ]6  }| j                  r t        j                  j	                  ||      n ||      }8 | j
                  |S | j                  |      S )z]Process input through convolutional layers, applying MBConv blocks and optional downsampling.rx   rp   r   utils
checkpointro   r!   r>   blks      r#   rB   zConvLayer.forwardS  X    ;; 	RC262E2E&&sA.3q6A	ROO+qC1CCr$   )rK   NFN      @)r&   r'   r(   r)   r*   r   r   r+   r   r   r   Moduleboolr   r   rC   rB   r,   r-   s   @r#   rm   rm     s    8 03*.$!%#&6
6
  S/6
 	6
 U+,6
 RYY'6
 6
 #6
 !6
pD D%,, Dr$   rm   c            	            e Zd ZdZddej
                  dfdedee   dee   def fdZ	d	e
j                  d
e
j                  fdZ xZS )MLPa  
    Multi-layer Perceptron (MLP) module for transformer architectures.

    This module applies layer normalization, two fully-connected layers with an activation function in between,
    and dropout. It is commonly used in transformer-based architectures for processing token embeddings.

    Attributes:
        norm (nn.LayerNorm): Layer normalization applied to the input.
        fc1 (nn.Linear): First fully-connected layer.
        fc2 (nn.Linear): Second fully-connected layer.
        act (nn.Module): Activation function applied after the first fully-connected layer.
        drop (nn.Dropout): Dropout layer applied after the activation function.

    Examples:
        >>> import torch
        >>> from torch import nn
        >>> mlp = MLP(in_features=256, hidden_features=512, out_features=256, activation=nn.GELU, drop=0.1)
        >>> x = torch.randn(32, 100, 256)
        >>> output = mlp(x)
        >>> print(output.shape)
        torch.Size([32, 100, 256])
    NrK   in_featureshidden_featuresout_featuresdropc                 &   t         |           |xs |}|xs |}t        j                  |      | _        t        j
                  ||      | _        t        j
                  ||      | _         |       | _        t        j                  |      | _
        y)a  
        Initialize a multi-layer perceptron with configurable input, hidden, and output dimensions.

        Args:
            in_features (int): Number of input features.
            hidden_features (Optional[int], optional): Number of hidden features.
            out_features (Optional[int], optional): Number of output features.
            activation (nn.Module): Activation function applied after the first fully-connected layer.
            drop (float, optional): Dropout probability.
        N)r   r   r   	LayerNormnormLinearfc1fc2r_   Dropoutr   )r!   r   r   r   r;   r   r"   s         r#   r   zMLP.__init__r  sq    $ 	#2{)8[LL-	99[/:99_l;<JJt$	r$   r>   r?   c                     | j                  |      }| j                  |      }| j                  |      }| j                  |      }| j	                  |      }| j                  |      S )zYApply MLP operations: layer norm, FC layers, activation, and dropout to the input tensor.)r   r   r_   r   r   rA   s     r#   rB   zMLP.forward  sQ    IIaLHHQKHHQKIIaLHHQKyy|r$   )r&   r'   r(   r)   r   GELUr*   r   r+   r   r   rC   rB   r,   r-   s   @r#   r   r   Z  sh    4 *.&*77%% "#% sm	% %6 %,, r$   r   c                        e Zd ZdZ	 	 	 ddededededeeef   f
 fdZ ej                         dde
f fd	       Zd
ej                  dej                  fdZ xZS )	Attentiona  
    Multi-head attention module with spatial awareness and trainable attention biases.

    This module implements a multi-head attention mechanism with support for spatial awareness, applying
    attention biases based on spatial resolution. It includes trainable attention biases for each unique
    offset between spatial positions in the resolution grid.

    Attributes:
        num_heads (int): Number of attention heads.
        scale (float): Scaling factor for attention scores.
        key_dim (int): Dimensionality of the keys and queries.
        nh_kd (int): Product of num_heads and key_dim.
        d (int): Dimensionality of the value vectors.
        dh (int): Product of d and num_heads.
        attn_ratio (float): Attention ratio affecting the dimensions of the value vectors.
        norm (nn.LayerNorm): Layer normalization applied to input.
        qkv (nn.Linear): Linear layer for computing query, key, and value projections.
        proj (nn.Linear): Linear layer for final projection.
        attention_biases (nn.Parameter): Learnable attention biases.
        attention_bias_idxs (torch.Tensor): Indices for attention biases.
        ab (torch.Tensor): Cached attention biases for inference, deleted during training.

    Examples:
        >>> attn = Attention(dim=256, key_dim=64, num_heads=8, resolution=(14, 14))
        >>> x = torch.randn(1, 196, 256)
        >>> output = attn(x)
        >>> print(output.shape)
        torch.Size([1, 196, 256])
    rY   key_dim	num_heads
attn_ratior2   c           	          t         |           t        |t              rt	        |      dk(  sJ d       || _        |dz  | _        || _        ||z  x| _        }t        ||z        | _
        t        ||z        |z  | _        || _        | j                  |dz  z   }t        j                  |      | _        t        j                   ||      | _        t        j                   | j                  |      | _        t'        t)        j*                  t-        |d         t-        |d                     }t	        |      }	i }
g }|D ]W  }|D ]P  }t/        |d   |d   z
        t/        |d   |d   z
        f}||
vrt	        |
      |
|<   |j1                  |
|          R Y t2        j                  j5                  t3        j6                  |t	        |
                  | _        | j;                  dt3        j<                  |      j?                  |	|	      d       y	)
a$  
        Initialize the Attention module for multi-head attention with spatial awareness.

        This module implements a multi-head attention mechanism with support for spatial awareness, applying
        attention biases based on spatial resolution. It includes trainable attention biases for each unique
        offset between spatial positions in the resolution grid.

        Args:
            dim (int): The dimensionality of the input and output.
            key_dim (int): The dimensionality of the keys and queries.
            num_heads (int, optional): Number of attention heads.
            attn_ratio (float, optional): Attention ratio, affecting the dimensions of the value vectors.
            resolution (Tuple[int, int], optional): Spatial resolution of the input feature map.
        r5   z+'resolution' argument not tuple of length 2g      r   r%   attention_bias_idxsF)
persistentN) r   r   rv   tuplerd   r   scaler   nh_kdr*   ddhr   r   r   r   r   qkvprojrw   	itertoolsproductru   absappendr   	Parameterzerosattention_biasesregister_buffer
LongTensorre   )r!   rY   r   r   r   r2   r   hpointsNattention_offsetsidxsp1p2offsetr"   s                  r#   r   zAttention.__init__  s   , 	*e,ZA1EtGttE"d]
$y00
UZ')*j7*+i7$GGeaiLL%	99S!$IIdggs+	i''jm(<eJqM>RSTK 	7B 7bebem,c"Q%"Q%-.@A!22034E0F%f--f56	7	7 !& 2 25;;y#N_J`3a b2E4D4DT4J4O4OPQST4Ubghr$   modec                     t         |   |       |rt        | d      r| `y| j                  dd| j
                  f   | _        y)zZSet the module in training mode and handle the 'ab' attribute for cached attention biases.abN)r   trainhasattrr   r   r   )r!   r   r"   s     r#   r   zAttention.train  s?     	dGD$'++At/G/G,GHDGr$   r>   r?   c                 D   |j                   \  }}}| j                  |      }| j                  |      }|j                  ||| j                  d      j                  | j                  | j                  | j                  gd      \  }}}|j                  dddd      }|j                  dddd      }|j                  dddd      }| j                  j                  | j                  j                        | _	        ||j                  dd      z  | j                  z  | j                  r| j                  dd| j                   f   n| j                  z   }	|	j#                  d      }	|	|z  j                  dd      j%                  ||| j&                        }| j)                  |      S )	zQApply multi-head attention with spatial awareness and trainable attention biases.rb   r6   )rY   r   r5   r%   N)shaper   r   re   r   splitr   r   rf   r   tor   devicerh   r   trainingr   softmaxreshaper   r   )
r!   r>   rk   r   _r   qkvattns
             r#   rB   zAttention.forward  sb   ''1a IIaLhhqk((1a4::DLL$,,X\X^X^;_ef:g1aIIaAq!IIaAq!IIaAq!''**T2299:AKKB''4::5BF--D!!!T%=%="=>UYU\U\
 |||#AX  A&..q!TWW=yy|r$   )   r4   )   r   )T)r&   r'   r(   r)   r*   r+   r   r   r   no_gradr   r   rC   rB   r,   r-   s   @r#   r   r     s    D &.1i1i 1i 	1i
 1i #s(O1if U]]_I$ I I %,, r$   r   c                        e Zd ZdZdddddej
                  fdedeeef   ded	ed
edededef fdZ	de
j                  de
j                  fdZdefdZ xZS )TinyViTBlocka  
    TinyViT Block that applies self-attention and a local convolution to the input.

    This block is a key component of the TinyViT architecture, combining self-attention mechanisms with
    local convolutions to process input features efficiently. It supports windowed attention for
    computational efficiency and includes residual connections.

    Attributes:
        dim (int): The dimensionality of the input and output.
        input_resolution (Tuple[int, int]): Spatial resolution of the input feature map.
        num_heads (int): Number of attention heads.
        window_size (int): Size of the attention window.
        mlp_ratio (float): Ratio of MLP hidden dimension to embedding dimension.
        drop_path (nn.Module): Stochastic depth layer, identity function during inference.
        attn (Attention): Self-attention module.
        mlp (MLP): Multi-layer perceptron module.
        local_conv (Conv2d_BN): Depth-wise local convolution layer.

    Examples:
        >>> input_tensor = torch.randn(1, 196, 192)
        >>> block = TinyViTBlock(dim=192, input_resolution=(14, 14), num_heads=3)
        >>> output = block(input_tensor)
        >>> print(output.shape)
        torch.Size([1, 196, 192])
       r   rK   r6   rY   rX   r   window_size	mlp_ratior   rH   local_conv_sizec
                    t         |           || _        || _        || _        |dkD  sJ d       || _        || _        t        j                         | _	        ||z  dk(  sJ d       ||z  }
||f}t        ||
|d|      | _        t        ||z        }|	}t        ||||      | _        |dz  }t        |||d||      | _        y	)
a  
        Initialize a TinyViT block with self-attention and local convolution.

        This block is a key component of the TinyViT architecture, combining self-attention mechanisms with
        local convolutions to process input features efficiently.

        Args:
            dim (int): Dimensionality of the input and output features.
            input_resolution (Tuple[int, int]): Spatial resolution of the input feature map (height, width).
            num_heads (int): Number of attention heads.
            window_size (int, optional): Size of the attention window. Must be greater than 0.
            mlp_ratio (float, optional): Ratio of MLP hidden dimension to embedding dimension.
            drop (float, optional): Dropout rate.
            drop_path (float, optional): Stochastic depth rate.
            local_conv_size (int, optional): Kernel size of the local convolution.
            activation (nn.Module): Activation function for MLP.
        r   z"window_size must be greater than 0z"dim must be divisible by num_headsr%   )r   r2   )r   r   r;   r   r5   rJ   N)r   r   rY   rX   r   r   r   r   rS   rH   r   r   r*   r   mlpr
   
local_conv)r!   rY   rX   r   r   r   r   rH   r   r;   head_dimwindow_resolutionmlp_hidden_dimmlp_activationr   r"   s                  r#   r   zTinyViTBlock.__init__%  s    : 	 0"QD DD&" Y!#I%II#)#(+6c8Y1Qbc	S9_-#3Sahlm"#CPS\_`r$   r>   r?   c           	      >   | j                   \  }}|j                  \  }}}|||z  k(  sJ d       |}|| j                  k(  r"|| j                  k(  r| j                  |      }n|j	                  ||||      }| j                  || j                  z  z
  | j                  z  }| j                  || j                  z  z
  | j                  z  }	|dkD  xs |	dkD  }
|
rt        j                  |ddd|	d|f      }||z   ||	z   }}|| j                  z  }|| j                  z  }|j	                  ||| j                  || j                  |      j                  dd      j                  ||z  |z  | j                  | j                  z  |      }| j                  |      }|j	                  |||| j                  | j                  |      j                  dd      j                  ||||      }|
r|ddd|d|f   j                         }|j	                  |||      }|| j                  |      z   }|j                  dd      j                  ||||      }| j                  |      }|j	                  |||      j                  dd      }|| j                  | j                  |            z   S )zPApply self-attention, local convolution, and MLP operations to the input tensor.zinput feature has wrong sizer   r5   r6   Nr%   )rX   r   r   r   re   Fr   rh   r   
contiguousrH   r   r   )r!   r>   r   wr   hwr   res_xpad_bpad_rpaddingpHpWnHnWs                  r#   rB   zTinyViTBlock.forward[  s   $$1772qQU{:::{   Q$*:*:%:		!Aq!Q"A%%D,<,<(<<@P@PPE%%D,<,<(<<@P@PPEai,519GEE!aAua78YE	Bt'''Bt'''B q"d..D4D4DaH1aR"d&6&69I9I&I1M 
 		!A q"b$"2"2D4D4DaHRRSTVWX``abdfhjlmnAa!RaRiL++-q"a ADNN1%%KK1%%aAq1OOAFF1a&&q!,4>>$((1+...r$   c           
          d| j                    d| j                   d| j                   d| j                   d| j                   
S )a  
        Return a string representation of the TinyViTBlock's parameters.

        This method provides a formatted string containing key information about the TinyViTBlock, including its
        dimension, input resolution, number of attention heads, window size, and MLP ratio.

        Returns:
            (str): A formatted string containing the block's parameters.

        Examples:
            >>> block = TinyViTBlock(dim=192, input_resolution=(14, 14), num_heads=3, window_size=7, mlp_ratio=4.0)
            >>> print(block.extra_repr())
            dim=192, input_resolution=(14, 14), num_heads=3, window_size=7, mlp_ratio=4.0
        dim=, input_resolution=z, num_heads=z, window_size=z, mlp_ratio=)rY   rX   r   r   r   r!   s    r#   
extra_reprzTinyViTBlock.extra_repr  sS      488*/0E0E/FlSWSaSaRb c++,L8HJ	
r$   )r&   r'   r(   r)   r   r   r*   r   r+   r   r   rC   rB   strr   r,   r-   s   @r#   r   r   
  s    >  774a4a  S/4a 	4a
 4a 4a 4a 4a 4al(/ (/%,, (/T
C 
r$   r   c                        e Zd ZdZddddddej
                  dfdedeeef   d	ed
edededede	ee
e   f   deej                     dededee   f fdZdej                   dej                   fdZdefdZ xZS )
BasicLayeraK  
    A basic TinyViT layer for one stage in a TinyViT architecture.

    This class represents a single layer in the TinyViT model, consisting of multiple TinyViT blocks
    and an optional downsampling operation. It processes features at a specific resolution and
    dimensionality within the overall architecture.

    Attributes:
        dim (int): The dimensionality of the input and output features.
        input_resolution (Tuple[int, int]): Spatial resolution of the input feature map.
        depth (int): Number of TinyViT blocks in this layer.
        use_checkpoint (bool): Whether to use gradient checkpointing to save memory.
        blocks (nn.ModuleList): List of TinyViT blocks that make up this layer.
        downsample (nn.Module | None): Downsample layer at the end of the layer, if specified.

    Examples:
        >>> input_tensor = torch.randn(1, 3136, 192)
        >>> layer = BasicLayer(dim=192, input_resolution=(56, 56), depth=2, num_heads=3, window_size=7)
        >>> output = layer(input_tensor)
        >>> print(output.shape)
        torch.Size([1, 784, 384])
    r   rK   NFr6   rY   rX   rn   r   r   r   r   rH   ro   rp   r   rZ   c                 J   t         |           || _        || _        || _        |
| _        t        j                  t        |      D cg c]+  }t        ||||||t        |t              r||   n|||	      - c}      | _        |	d| _        y |	||||      | _        yc c}w )a  
        Initialize a BasicLayer in the TinyViT architecture.

        This layer consists of multiple TinyViT blocks and an optional downsampling operation. It is designed to
        process feature maps at a specific resolution and dimensionality within the TinyViT model.

        Args:
            dim (int): Dimensionality of the input and output features.
            input_resolution (Tuple[int, int]): Spatial resolution of the input feature map (height, width).
            depth (int): Number of TinyViT blocks in this layer.
            num_heads (int): Number of attention heads in each TinyViT block.
            window_size (int): Size of the local window for attention computation.
            mlp_ratio (float, optional): Ratio of MLP hidden dimension to embedding dimension.
            drop (float, optional): Dropout rate.
            drop_path (float | List[float], optional): Stochastic depth rate. Can be a float or a list of floats for each block.
            downsample (nn.Module | None, optional): Downsampling layer at the end of the layer. None to skip downsampling.
            use_checkpoint (bool, optional): Whether to use gradient checkpointing to save memory.
            local_conv_size (int, optional): Kernel size for the local convolution in each TinyViT block.
            activation (nn.Module): Activation function used in the MLP.
            out_dim (int | None, optional): Output dimension after downsampling. None means it will be the same as `dim`.
        )	rY   rX   r   r   r   r   rH   r   r;   Nrs   )r   r   rY   rX   rn   rp   r   rt   ru   r   rv   rw   rx   ro   )r!   rY   rX   rn   r   r   r   r   rH   ro   rp   r   r;   rZ   ry   r"   s                  r#   r   zBasicLayer.__init__  s    J 	 0
, mm u  %5' +'.8D.Iily$3)

( !  	 ,#wS]^ 	#s   0B r>   r?   c                     | j                   D ]6  }| j                  r t        j                  j	                  ||      n ||      }8 | j
                  |S | j                  |      S )z?Process input through TinyViT blocks and optional downsampling.r{   r~   s      r#   rB   zBasicLayer.forward  r   r$   c                 T    d| j                    d| j                   d| j                   S )z9Return a string with the layer's parameters for printing.r   r   z, depth=)rY   rX   rn   r   s    r#   r   zBasicLayer.extra_repr  s/    dhhZ243H3H2IRVR\R\Q]^^r$   )r&   r'   r(   r)   r   r   r*   r   r+   r   r   r   r   r   r   r   rC   rB   r   r   r,   r-   s   @r#   r   r     s    < /2*.$ 77!%B
B
  S/B
 	B

 B
 B
 B
 B
 U+,B
 RYY'B
 B
 B
 #B
HD D%,, D_C _r$   r   c                       e Zd ZdZ	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddedededeeeeef   deeeeef   deeeeef   deeeeef   d	ed
edededededef fdZdefdZ	e
d        Zej                  j                  d        Zdej                   dej                   fdZdej                   dej                   fdZddgfdee   fdZ xZS )TinyViTa  
    TinyViT: A compact vision transformer architecture for efficient image classification and feature extraction.

    This class implements the TinyViT model, which combines elements of vision transformers and convolutional
    neural networks for improved efficiency and performance on vision tasks. It features hierarchical processing
    with patch embedding, multiple stages of attention and convolution blocks, and a feature refinement neck.

    Attributes:
        img_size (int): Input image size.
        num_classes (int): Number of classification classes.
        depths (Tuple[int, int, int, int]): Number of blocks in each stage.
        num_layers (int): Total number of layers in the network.
        mlp_ratio (float): Ratio of MLP hidden dimension to embedding dimension.
        patch_embed (PatchEmbed): Module for patch embedding.
        patches_resolution (Tuple[int, int]): Resolution of embedded patches.
        layers (nn.ModuleList): List of network layers.
        norm_head (nn.LayerNorm): Layer normalization for the classifier head.
        head (nn.Linear): Linear layer for final classification.
        neck (nn.Sequential): Neck module for feature refinement.

    Examples:
        >>> model = TinyViT(img_size=224, num_classes=1000)
        >>> x = torch.randn(1, 3, 224, 224)
        >>> features = model.forward_features(x)
        >>> print(features.shape)
        torch.Size([1, 256, 56, 56])
    r<   r0   num_classes
embed_dimsdepthsr   window_sizesr   	drop_ratedrop_path_raterp   mbconv_expand_ratior   layer_lr_decayc                    t         |           || _        || _        || _        t        |      | _        || _        t        j                  }t        ||d   ||      | _        | j                  j                  }|| _        t        j                  d|
t        |            D cg c]  }|j!                          }}t        j"                         | _        t'        | j                        D ]  }t)        ||   |d   d|dk(  r|dz
  n|z  z  |d   d|dk(  r|dz
  n|z  z  f||   |t        |d|       t        |d|dz           || j                  dz
  k  rt*        nd||t-        |dz   t        |      dz
           |      }|dk(  rt/        dd|i|}n!t1        d||   ||   | j                  |	|d	|}| j$                  j3                  |        t        j4                  |d
         | _        |dkD  rt        j8                  |d
   |      nt        j                  j;                         | _        | j?                  | j@                         | jC                  |       t        jD                  t        jF                  |d
   ddd      tI        d      t        jF                  ddddd      tI        d            | _%        yc c}w )a_  
        Initialize the TinyViT model.

        This constructor sets up the TinyViT architecture, including patch embedding, multiple layers of
        attention and convolution blocks, and a classification head.

        Args:
            img_size (int, optional): Size of the input image.
            in_chans (int, optional): Number of input channels.
            num_classes (int, optional): Number of classes for classification.
            embed_dims (Tuple[int, int, int, int], optional): Embedding dimensions for each stage.
            depths (Tuple[int, int, int, int], optional): Number of blocks in each stage.
            num_heads (Tuple[int, int, int, int], optional): Number of attention heads in each stage.
            window_sizes (Tuple[int, int, int, int], optional): Window sizes for each stage.
            mlp_ratio (float, optional): Ratio of MLP hidden dim to embedding dim.
            drop_rate (float, optional): Dropout rate.
            drop_path_rate (float, optional): Stochastic depth rate.
            use_checkpoint (bool, optional): Whether to use checkpointing to save memory.
            mbconv_expand_ratio (float, optional): Expansion ratio for MBConv layer.
            local_conv_size (int, optional): Kernel size for local convolutions.
            layer_lr_decay (float, optional): Layer-wise learning rate decay factor.
        r   )r0   r1   r2   r;   r5   r6   r%   N)rY   rX   rn   rH   ro   rp   rZ   r;   rq   )r   r   r   r   r   rb      F)kernel_sizer   )r   r   r    )&r   r   r<   r   r   rd   
num_layersr   r   r   r/   patch_embedr7   r   linspacesumitemrt   layersru   dictrW   minrm   r   r   r   	norm_headr   rS   headapply_init_weightsset_layer_lr_decayr9   r   r   neck)r!   r<   r0   r   r   r   r   r   r   r   r   rp   r   r   r   r;   r7   r>   dpri_layerkwargslayerr"   s                         r#   r   zTinyViT.__init__  s   N 	 &f+"WW
%A8Xb
 "--@@"4 "'>3v;!OPAqvvxPP mmoT__- 	&Gw'&q)a7a<GaKU\.]^&q)a7a<GaKU\.]^" Woc&'"23c&7Q;:O6PQ,3doo6I,I<PT-"3w{C
Oa4G#HI%F !|!R4GR6R" '0 ,W 5"nn"$3  KKu%7	&< jn5>IAoBIIjnk:SXS[S[SdSdSf	 	

4%%&/MMII2	 II 
	Q Qs   "J<c                 z   |}t        | j                        }t        |      D cg c]  }|||z
  dz
  z   c}d | j                  j	                  fd       d| j
                  D ][  }|j                  D ]  }|j	                  fd       dz   |j                  <|j                  j	                  fd       ] |k(  sJ | j                  | j                  hD ]  }|j	                  fd        | j                         D ]  \  }}	||	_         d	 }
| j	                  |
       yc c}w )
zHSet layer-wise learning rate decay for the TinyViT model based on depth.r%   c                 <    | j                         D ]	  }||_         y)zSSet the learning rate scale for each layer in the model based on the layer's depth.N)
parameterslr_scale)mr   ps      r#   _set_lr_scalez1TinyViT.set_layer_lr_decay.<locals>._set_lr_scale  s    \\^ #"
#r$   c                      | d         S )Nr   r   r>   r  	lr_scaless    r#   <lambda>z,TinyViT.set_layer_lr_decay.<locals>.<lambda>  s    q)A,)G r$   r   c                      |          S )Nr   r>   r  ry   r  s    r#   r  z,TinyViT.set_layer_lr_decay.<locals>.<lambda>  s    mAy|&D r$   Nc                 "     | dz
           S )Nr%   r   r  s    r#   r  z,TinyViT.set_layer_lr_decay.<locals>.<lambda>  s    q)APQEBR1S r$   c                      | d         S )Nrb   r   r  s    r#   r  z,TinyViT.set_layer_lr_decay.<locals>.<lambda>  s    mAy}= r$   c                 h    | j                         D ]  }t        |d      rJ |j                          y)zMCheck if the learning rate scale attribute is present in module's parameters.r  N)r  r   
param_name)r  r  s     r#   _check_lr_scalez3TinyViT.set_layer_lr_decay.<locals>._check_lr_scale  s0    \\^ <q*-;q||;-<r$   )r   r   ru   r   r  r  rx   ro   r  r  named_parametersr  )r!   r   
decay_ratern   ry   r  blockr  r   r  r  r  r  s       `      @@r#   r  zTinyViT.set_layer_lr_decay  s0   #
 DKK <A%LIqZEAIM2I		#
 	GH[[ 	UE DEQ +  &&'ST	U Ezz..$)), 	?AGG=>	? ))+ 	DAqAL		<
 	

?#7 Js   D8c                    t        | t        j                        r8| j                  +t        j                  j                  | j                  d       yyt        | t        j                        rUt        j                  j                  | j                  d       t        j                  j                  | j                  d       yy)zLInitialize weights for linear and normalization layers in the TinyViT model.Nr         ?)rv   r   r   r   r   r   r   r    )r  s    r#   r  zTinyViT._init_weights  s~     a# vv!!!!&&!, "2<<(GGaffa(GGahh, )r$   c                     dhS )zIReturn a set of keywords for parameters that should not use weight decay.r   r   r   s    r#   no_weight_decay_keywordsz TinyViT.no_weight_decay_keywords  s     ###r$   r>   r?   c                    | j                  |      } | j                  d   |      }d}t        |t        | j                              D ]  }| j                  |   } ||      } |j                  \  }}}|j                  || j                  d   dz  | j                  d   dz  |      }|j                  dddd      }| j                  |      S )zLProcess input through feature extraction layers, returning spatial features.r   r%   r4   r6   r5   )	r   r  ru   rd   r   re   r7   rf   r	  )r!   r>   start_iry   r  batchr   channels           r#   forward_featureszTinyViT.forward_features  s    QDKKN1wDKK 01 	AKKNEaA	 GGq'FF5$11!494;R;RST;UYZ;Z\cdIIaAq!yy|r$   c                 $    | j                  |      S )z]Perform the forward pass through the TinyViT model, extracting features from the input image.)r+  rA   s     r#   rB   zTinyViT.forward  s    $$Q''r$   i   imgszc                 h   |D cg c]  }|dz  	 }}|| _         t        | j                        D ]|  \  }}|d   d|dk(  r|dz
  n|z  z  |d   d|dk(  r|dz
  n|z  z  f}||_        |j                  ||j                  _        t        |t              se|j                  D ]	  }||_         ~ yc c}w )zCSet image size to make model compatible with different image sizes.r4   r   r5   r6   r%   N)r7   	enumerater  rX   ro   rv   r   rx   )r!   r-  sry   r  rX   r   s          r#   	set_imgszzTinyViT.set_imgsz  s    !&'Aa''"'!$++. 
	:HAuaQAF1q5:;aQAF1q5:;  &6E"+4D  1%, :A)9A&:
	: (s   B/)   r6   i  )`      i  i   )r5   r5      r5   )r6   r5        )r   r   r   r   r   rK   g?Fr   r6   r$  )r&   r'   r(   r)   r*   r   r+   r   r   r  staticmethodr  r   jitignorer&  rC   r+  rB   r   r1  r,   r-   s   @r#   r   r     s   < 0C,8/=2? #$%(  #p
p
 p
 	p

 #sC,-p
 c3S()p
 c3+,p
 Cc3./p
 p
 p
 p
 p
 #p
 p
 p
d!$ !$F 	- 	- YY$ $%,, 5<< ( (%,, ( -1$< :tCy :r$   r   )r   typingr   r   r   r   r   torch.nnr   torch.nn.functional
functionalr   ultralytics.nn.modulesr   ultralytics.utils.instancer   r9   r
   r   r/   rE   rW   rm   r   r   r   r   r   r   r$   r#   <module>rA     s     / /     . 01"## 1"h0 0fCRYY CL=,299 =,@SD		 SDl:")) :zp pfM
299 M
`d_ d_Nd:bii d:r$   