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

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

    Methods:
        __init__: Initializes the Conv2d_BN with specified parameters.

    Args:
        a (int): Number of input channels.
        b (int): Number of output channels.
        ks (int): Kernel size for the convolution. Defaults to 1.
        stride (int): Stride for the convolution. Defaults to 1.
        pad (int): Padding for the convolution. Defaults to 0.
        dilation (int): Dilation factor for the convolution. Defaults to 1.
        groups (int): Number of groups for the convolution. Defaults to 1.
        bn_weight_init (float): Initial value for batch normalization weight. Defaults to 1.

    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)
       r   c	           
         sn   t    | dtjj|||||||dd tj|}	tjj|	j	| tjj|	j
d | d|	 dS )zWInitializes a sequential container with 2D convolution followed by batch normalization.cF)biasr   bnN)super__init__
add_moduletorchnnConv2dBatchNorm2dinit	constant_weightr   )
selfabksstridepaddilationgroupsbn_weight_initr	   	__class__ _/var/www/vscode/kcb/lib/python3.10/site-packages/ultralytics/models/sam/modules/tiny_encoder.pyr   4   s   
$zConv2d_BN.__init__)r   r   r   r   r   r   )__name__
__module____qualname____doc__r   __classcell__r   r   r   r    r      s    r   c                       (   e Zd ZdZ fddZdd Z  ZS )
PatchEmbeda  
    Embeds images into patches and projects them into a specified embedding 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.

    Methods:
        forward: Processes the input tensor through the patch embedding sequence.

    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)
    c              
      s   t    t|}|d d |d d f| _| jd | jd  | _|| _|| _|}tt	||d ddd| t	|d |ddd| _
dS )zcInitializes patch embedding with convolutional layers for image-to-patch conversion and projection.r      r         N)r
   r   r   patches_resolutionnum_patchesin_chans	embed_dimr   
Sequentialr   seq)r   r-   r.   
resolution
activationimg_sizenr   r   r    r   T   s   

zPatchEmbed.__init__c                 C   
   |  |S )z_Processes input tensor through patch embedding sequence, converting images to patch embeddings.)r0   r   xr   r   r    forwardc      
zPatchEmbed.forwardr!   r"   r#   r$   r   r8   r%   r   r   r   r    r'   >   s    r'   c                       r&   )MBConva   
    Mobile Inverted Bottleneck Conv (MBConv) layer, part of the EfficientNet architecture.

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

    Methods:
        forward: Performs the forward pass through the MBConv layer.

    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])
    c                    s   t    || _t|| | _|| _t|| jdd| _| | _t| j| jddd| jd| _	| | _
t| j|ddd| _| | _t | _dS )zcInitializes the MBConv layer with specified input/output channels, expansion ratio, and activation.r   )r   r*   r   r   r   r           )r   r   N)r
   r   r-   inthidden_chans	out_chansr   conv1act1conv2act2conv3act3r   Identity	drop_path)r   r-   r@   expand_ratior2   rH   r   r   r    r      s   
zMBConv.__init__c                 C   sR   |}|  |}| |}| |}| |}| |}| |}||7 }| |S )zQImplements the forward pass of MBConv, applying convolutions and skip connection.)rA   rB   rC   rD   rE   rH   rF   )r   r7   shortcutr   r   r    r8      s   






zMBConv.forwardr:   r   r   r   r    r;   h   s    r;   c                       r&   )PatchMerginga  
    Merges neighboring patches in the feature map and projects to a new dimension.

    This class implements a patch merging operation that combines spatial information and adjusts the feature
    dimension. It uses a series of convolutional layers with batch normalization to achieve this.

    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.

    Methods:
        forward: Applies the patch merging operation to the input tensor.

    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)
    c                    sr   t    || _|| _|| _| | _t||ddd| _|dv r!dnd}t||d|d|d| _t||ddd| _	dS )zcInitializes the PatchMerging module for merging and projecting neighboring patches in feature maps.r   r   >   @  @    r)   r*   )r   N)
r
   r   input_resolutiondimout_dimactr   rA   rC   rE   )r   rO   rP   rQ   r2   stride_cr   r   r    r      s   
zPatchMerging.__init__c                 C   s|   |j dkr| j\}}t|}||||ddddd}| |}| |}| |}| |}| |}|	d
ddS )zHApplies patch merging and dimension projection to the input feature map.r*   r   r   r)   )ndimrO   lenviewpermuterA   rR   rC   rE   flatten	transpose)r   r7   HWBr   r   r    r8      s   






zPatchMerging.forwardr:   r   r   r   r    rK      s    rK   c                       s4   e Zd ZdZ					d
 fdd	Zdd	 Z  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.

    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[Callable]): Function for downsampling the output.

    Methods:
        forward: Processes the input through the convolutional layers.

    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)
    r=   NF      @c
           
         sn   t    | _|| _|| _|| _t fddt|D | _	|du r,d| _
dS ||| d| _
dS )a  
        Initializes 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]): Drop path rate. Single float or a list of floats for each MBConv.
            downsample (Optional[nn.Module]): Function for downsampling the output. None to skip downsampling.
            use_checkpoint (bool): Whether to use gradient checkpointing to save memory.
            out_dim (Optional[int]): The dimensionality of the output. None means it will be the same as `dim`.
            conv_expand_ratio (float): Expansion ratio for the MBConv layers.

        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)
        c              
      s.   g | ]}t  ttr| nqS r   )r;   
isinstancelist.0ir2   conv_expand_ratiorP   rH   r   r    
<listcomp>!  s    z&ConvLayer.__init__.<locals>.<listcomp>NrP   rQ   r2   r
   r   rP   rO   depthuse_checkpointr   
ModuleListrangeblocks
downsample)
r   rP   rO   rj   r2   rH   ro   rk   rQ   rf   r   re   r    r      s   
#zConvLayer.__init__c                 C   >   | j D ]}| jrt||n||}q| jdu r|S | |S )z_Processes input through convolutional layers, applying MBConv blocks and optional downsampling.Nrn   rk   
checkpointro   r   r7   blkr   r   r    r8   4     
zConvLayer.forward)r=   NFNr_   r:   r   r   r   r    r^      s    >r^   c                       s4   e Zd ZdZddejdf fdd	Zdd Z  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.

    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.

    Methods:
        forward: Applies the MLP operations on the input tensor.

    Examples:
        >>> import torch
        >>> from torch import nn
        >>> mlp = Mlp(in_features=256, hidden_features=512, out_features=256, act_layer=nn.GELU, drop=0.1)
        >>> x = torch.randn(32, 100, 256)
        >>> output = mlp(x)
        >>> print(output.shape)
        torch.Size([32, 100, 256])
    Nr=   c                    sZ   t    |p|}|p|}t|| _t||| _t||| _| | _t	|| _
dS )z\Initializes a multi-layer perceptron with configurable input, hidden, and output dimensions.N)r
   r   r   	LayerNormnormLinearfc1fc2rR   Dropoutdrop)r   in_featureshidden_featuresout_features	act_layerr}   r   r   r    r   V  s   
zMlp.__init__c                 C   s<   |  |}| |}| |}| |}| |}| |S )z[Applies MLP operations: layer norm, FC layers, activation, and dropout to the input tensor.)rx   rz   rR   r}   r{   r6   r   r   r    r8   a  s   





zMlp.forward)	r!   r"   r#   r$   r   GELUr   r8   r%   r   r   r   r    rv   ;  s    rv   c                       sF   e Zd ZdZ			d fdd	Ze d fdd		Zd
d Z  Z	S )	Attentionag  
    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 (Tensor): Indices for attention biases.
        ab (Tensor): Cached attention biases for inference, deleted during training.

    Methods:
        train: Sets the module in training mode and handles the 'ab' attribute.
        forward: Performs the forward pass of the attention mechanism.

    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])
       r(      r   c                    st  t    t|trt|dksJ d|| _|d | _|| _||  | _}t	|| | _
t	|| | | _|| _| j|d  }t|| _t||| _t| j|| _ttt|d t|d }t|}	i }
g }|D ],}|D ]'}t|d |d  t|d |d  f}||
vrt|
|
|< ||
|  qsqotjt|t|
| _| jdt||	|	dd d	S )
a
  
        Initializes 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): Number of attention heads.
            attn_ratio (float): Attention ratio, affecting the dimensions of the value vectors.
            resolution (Tuple[int, int]): Spatial resolution of the input feature map.

        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])
        r)   z+'resolution' argument not tuple of length 2g      r   r   attention_bias_idxsF)
persistentN) r
   r   r`   tuplerV   	num_headsscalekey_dimnh_kdr>   ddh
attn_ratior   rw   rx   ry   qkvprojra   	itertoolsproductrm   absappendr   	Parameterzerosattention_biasesregister_buffer
LongTensorrW   )r   rP   r   r   r   r1   r   hpointsNattention_offsetsidxsp1p2offsetr   r   r    r     s4   

 ("zAttention.__init__Tc                    s<   t  | |rt| dr| `dS | jdd| jf | _dS )zTPerforms multi-head attention with spatial awareness and trainable attention biases.abN)r
   trainhasattrr   r   r   )r   moder   r   r    r     s   zAttention.trainc           
      C   s   |j \}}}| |}| |}|||| jdj| j| j| jgdd\}}}|dddd}|dddd}|dddd}| j	
| jj| _	||dd | j | jr_| jdd| jf n| j	 }	|	jdd}	|	| dd||| j}| |S )	zSApplies multi-head attention with spatial awareness and trainable attention biases.rT   r*   )rP   r   r)   r   N)shaperx   r   rW   r   splitr   r   rX   r   tor   devicerZ   r   trainingr   softmaxreshaper   r   )
r   r7   r]   r   _r   qkvattnr   r   r    r8     s   

.
zAttention.forward)r   r(   r   )T)
r!   r"   r#   r$   r   r   no_gradr   r8   r%   r   r   r   r    r   k  s    &:r   c                       sF   e Zd ZdZdddddejf fdd	Zdd	 Zd
efddZ	  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.

    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.

    Methods:
        forward: Processes the input through the TinyViT block.
        extra_repr: Returns a string with extra information about the block's parameters.

    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_   r=   r*   c
                    s   t    || _|| _|| _|dksJ d|| _|| _t | _	|| dks+J d|| }
||f}t
||
|d|d| _t|| }|	}t||||d| _|d }t|||d||d| _d	S )
aH  
        Initializes 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): Size of the attention window. Must be greater than 0.
            mlp_ratio (float): Ratio of MLP hidden dimension to embedding dimension.
            drop (float): Dropout rate.
            drop_path (float): Stochastic depth rate.
            local_conv_size (int): Kernel size of the local convolution.
            activation (torch.nn.Module): Activation function for MLP.

        Raises:
            AssertionError: If window_size is not greater than 0.
            AssertionError: If dim is not divisible by num_heads.

        Examples:
            >>> block = TinyViTBlock(dim=192, input_resolution=(14, 14), num_heads=3)
            >>> input_tensor = torch.randn(1, 196, 192)
            >>> output = block(input_tensor)
            >>> print(output.shape)
            torch.Size([1, 196, 192])
        r   z"window_size must be greater than 0z"dim must be divisible by num_headsr   )r   r1   )r~   r   r   r}   r)   r<   N)r
   r   rP   rO   r   window_size	mlp_ratior   rG   rH   r   r   r>   rv   mlpr   
local_conv)r   rP   rO   r   r   r   r}   rH   local_conv_sizer2   head_dimwindow_resolutionmlp_hidden_dimmlp_activationr   r   r   r    r     s"   
(
zTinyViTBlock.__init__c              	   C   s  | j \}}|j\}}}||| ksJ d|}|| jkr'|| jkr'| |}n|||||}| j|| j  | j }| j|| j  | j }	|dkpL|	dk}
|
r[t|ddd|	d|f}|| ||	 }}|| j }|| j }|||| j|| j|dd|| | | j| j |}| |}||||| j| j|dd||||}|
r|ddd|d|f 	 }||||}|| 
| }|dd||||}| |}||||dd}|| 
| | S )zRApplies self-attention, local convolution, and MLP operations to the input tensor.zinput feature has wrong sizer   r)   r*   Nr   )rO   r   r   r   rW   Fr   rZ   r   
contiguousrH   r   r   )r   r7   r   wr   hwr   res_xpad_bpad_rpaddingpHpWnHnWr   r   r    r8   H  s:   



,
zTinyViTBlock.forwardreturnc              
   C   s,   d| j  d| j d| j d| j d| j 
S )a  
        Returns 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=)rP   rO   r   r   r   r   r   r   r    
extra_reprr  s   zTinyViTBlock.extra_reprr!   r"   r#   r$   r   r   r   r8   strr   r%   r   r   r   r    r     s    "A*r   c                       sJ   e Zd ZdZddddddejdf fdd	Zd	d
 ZdefddZ	  Z
S )
BasicLayera  
    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.

    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.

    Methods:
        forward: Processes the input through the layer's blocks and optional downsampling.
        extra_repr: Returns a string with the layer's parameters for printing.

    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_   r=   NFr*   c                    sx   t    | _| _|| _|
| _t f	ddt|D | _	|	du r1d| _
dS |	| d| _
dS )a  
        Initializes 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): Ratio of MLP hidden dimension to embedding dimension.
            drop (float): Dropout rate.
            drop_path (float | List[float]): Stochastic depth rate. Can be a float or a list of floats for each block.
            downsample (nn.Module | None): Downsampling layer at the end of the layer. None to skip downsampling.
            use_checkpoint (bool): Whether to use gradient checkpointing to save memory.
            local_conv_size (int): Kernel size for the local convolution in each TinyViT block.
            activation (nn.Module): Activation function used in the MLP.
            out_dim (int | None): Output dimension after downsampling. None means it will be the same as `dim`.

        Raises:
            ValueError: If `drop_path` is a list and its length doesn't match `depth`.

        Examples:
            >>> layer = BasicLayer(dim=96, input_resolution=(56, 56), depth=2, num_heads=3, window_size=7)
            >>> x = torch.randn(1, 56 * 56, 96)
            >>> output = layer(x)
            >>> print(output.shape)
        c                    s8   g | ]}t ttr| n d 	qS ))	rP   rO   r   r   r   r}   rH   r   r2   )r   r`   ra   rb   	r2   rP   r}   rH   rO   r   r   r   r   r   r    rg     s    z'BasicLayer.__init__.<locals>.<listcomp>Nrh   ri   )r   rP   rO   rj   r   r   r   r}   rH   ro   rk   r   r2   rQ   r   r   r    r     s   
.zBasicLayer.__init__c                 C   rp   )zAProcesses input through TinyViT blocks and optional downsampling.Nrq   rs   r   r   r    r8     ru   zBasicLayer.forwardr   c                 C   s   d| j  d| j d| j S )z:Returns a string with the layer's parameters for printing.r   r   z, depth=)rP   rO   rj   r   r   r   r    r     s   zBasicLayer.extra_reprr   r   r   r   r    r     s    !Mr   c                       s   e Zd ZdZ										
						d fdd	Zdd Zedd Zej	j
dd Zdd Zdd ZddgfddZ  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.

    Attributes:
        img_size (int): Input image size.
        num_classes (int): Number of classification classes.
        depths (List[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.

    Methods:
        set_layer_lr_decay: Sets layer-wise learning rate decay.
        _init_weights: Initializes weights for linear and normalization layers.
        no_weight_decay_keywords: Returns keywords for parameters that should not use weight decay.
        forward_features: Processes input through the feature extraction layers.
        forward: Performs a forward pass through the entire network.

    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, 64, 64])
       r*     `      i  i   r)   r)      r)   r*   r         r   r   r   r   r_   r=   皙?F      ?c                    s
  t    || _|| _|| _t|| _|| _tj	}t
||d ||d| _| jj}|| _dd td|
t|D }t | _t| jD ]|}t|| |d d|dkrU|d n|  |d d|dkrd|d n|  f|| |t|d| t|d|d   || jd k rtnd||t|d t|d  |d	}|dkrtdd
|i|}ntd|| || | j|	|d|}| j| qCt|d | _|dkrt|d |ntj | _| | j |  | t!tj"|d ddddt#dtj"ddddddt#d| _$dS )a  
        Initializes 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): Size of the input image.
            in_chans (int): Number of input channels.
            num_classes (int): Number of classes for classification.
            embed_dims (Tuple[int, int, int, int]): Embedding dimensions for each stage.
            depths (Tuple[int, int, int, int]): Number of blocks in each stage.
            num_heads (Tuple[int, int, int, int]): Number of attention heads in each stage.
            window_sizes (Tuple[int, int, int, int]): Window sizes for each stage.
            mlp_ratio (float): Ratio of MLP hidden dim to embedding dim.
            drop_rate (float): Dropout rate.
            drop_path_rate (float): Stochastic depth rate.
            use_checkpoint (bool): Whether to use checkpointing to save memory.
            mbconv_expand_ratio (float): Expansion ratio for MBConv layer.
            local_conv_size (int): Kernel size for local convolutions.
            layer_lr_decay (float): Layer-wise learning rate decay factor.

        Examples:
            >>> model = TinyViT(img_size=224, num_classes=1000)
            >>> x = torch.randn(1, 3, 224, 224)
            >>> output = model(x)
            >>> print(output.shape)
            torch.Size([1, 1000])
        r   )r-   r.   r1   r2   c                 S   s   g | ]}|  qS r   )item)rc   r7   r   r   r    rg   \      z$TinyViT.__init__.<locals>.<listcomp>r)   r*   r   N)rP   rO   rj   rH   ro   rk   rQ   r2   rf   )r   r   r   r}   r   rT      F)kernel_sizer   )r   r   r   r   )%r
   r   r3   num_classesdepthsrV   
num_layersr   r   r   r'   patch_embedr+   r   linspacesumrl   layersrm   dictrK   minr^   r   r   rw   	norm_headry   rG   headapply_init_weightsset_layer_lr_decayr/   r   r   neck)r   r3   r-   r   
embed_dimsr   r   window_sizesr   	drop_ratedrop_path_raterk   mbconv_expand_ratior   layer_lr_decayr2   r+   dpri_layerkwargslayerr   r   r    r     sx   
.

&$

zTinyViT.__init__c                    s   |t | jfddtD dd  | j fdd d| jD ](}|jD ]}| fdd d	7 q,|jd
urO|j fdd q'ksVJ | j| j	fD ]}| fdd q\| 
 D ]\}}||_qmdd }| | d
S )zISets layer-wise learning rate decay for the TinyViT model based on depth.c                    s   g | ]
} | d   qS )r   r   rb   )
decay_raterj   r   r    rg     s    z.TinyViT.set_layer_lr_decay.<locals>.<listcomp>c                 S   s   |   D ]}||_qdS )zTSets the learning rate scale for each layer in the model based on the layer's depth.N)
parameterslr_scale)mr   pr   r   r    _set_lr_scale  s   z1TinyViT.set_layer_lr_decay.<locals>._set_lr_scalec                        | d S )Nr   r   r7   r  	lr_scalesr   r    <lambda>      z,TinyViT.set_layer_lr_decay.<locals>.<lambda>r   c                    s    |  S )Nr   r  r  rd   r
  r   r    r    r  r   Nc                    s    | d  S )Nr   r   r  r  r   r    r    s    c                    r  )NrT   r   r  r	  r   r    r    r  c                 S   s&   |   D ]}t|dsJ |jqdS )zNChecks if the learning rate scale attribute is present in module's parameters.r  N)r  r   
param_name)r  r  r   r   r    _check_lr_scale  s   z3TinyViT.set_layer_lr_decay.<locals>._check_lr_scale)r   r   rm   r   r   r   rn   ro   r   r   named_parametersr  )r   r   r   blockr  r   r  r  r   )r  r  rj   rd   r
  r    r     s(   




zTinyViT.set_layer_lr_decayc                 C   sb   t | tjr| jdurtj| jd dS dS t | tjr/tj| jd tj| jd dS dS )zMInitializes weights for linear and normalization layers in the TinyViT model.Nr   r   )r`   r   ry   r   r   r   rw   r   )r  r   r   r    r     s   
zTinyViT._init_weightsc                 C   s   dhS )zJReturns a set of keywords for parameters that should not use weight decay.r   r   r   r   r   r    no_weight_decay_keywords  s   z TinyViT.no_weight_decay_keywordsc                 C   s   |  |}| jd |}d}t|t| jD ]}| j| }||}q|j\}}}||| jd d | jd d |}|dddd}| |S )zNProcesses input through feature extraction layers, returning spatial features.r   r   r(   r*   r)   )	r   r   rm   rV   r   rW   r+   rX   r   )r   r7   start_ird   r   batchr   channelr   r   r    forward_features  s   


$
zTinyViT.forward_featuresc                 C   r5   )z^Performs the forward pass through the TinyViT model, extracting features from the input image.)r  r6   r   r   r    r8     r9   zTinyViT.forwardi   c                 C   s   dd |D }|| _ t| jD ]>\}}|d d|dkr|d n|  |d d|dkr.|d n|  f}||_|jdur?||j_t|trM|jD ]}||_qGqdS )zCSet image size to make model compatible with different image sizes.c                 S   s   g | ]}|d  qS )r(   r   )rc   sr   r   r    rg     r   z%TinyViT.set_imgsz.<locals>.<listcomp>r   r)   r*   r   N)r+   	enumerater   rO   ro   r`   r   rn   )r   imgszrd   r   rO   r   r   r   r    	set_imgsz  s   


zTinyViT.set_imgsz)r   r*   r   r   r   r   r   r_   r=   r   Fr_   r*   r   )r!   r"   r#   r$   r   r   staticmethodr   r   jitignorer  r  r8   r  r%   r   r   r   r    r     s2    $y#

r   )r   typingr   r   torch.nnr   torch.nn.functional
functionalr   torch.utils.checkpointutilsrr   ultralytics.nn.modulesr   ultralytics.utils.instancer   r/   r   Moduler'   r;   rK   r^   rv   r   r   r   r   r   r   r   r    <module>   s&   &*=9]0~ s