§
    ezni«a  ã                   óz  — d dl mZmZmZmZ d dlZd dlZd dlm	Z	 d dl
m	c mZ d dlmZm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dej        dedeej        eeef         f         fd„Zdej        dedeeef         deeef         dej        f
d„Zdededej        dej        fd„Zdej        dej        dej        dej        deeef         deeef         dej        fd„Z G d„ d e	j        ¦  «        ZdS )!é    )ÚAnyÚOptionalÚTupleÚTypeN)ÚLayerNorm2dÚMLPBlockc            #       óþ   ‡ — e Zd ZdZddddddddd	ej        ej        d	d
d	ddfdedededededededede	de
ej                 de
ej                 de	de	de	dedeedf         ddf"ˆ fd „Zd!ej        dej        fd"„Zˆ xZS )#ÚImageEncoderViTa¼  
    An image encoder using Vision Transformer (ViT) architecture for encoding an image into a compact latent space. The
    encoder takes an image, splits it into patches, and processes these patches through a series of transformer blocks.
    The encoded patches are then processed through a neck to generate the final encoded representation.

    This class and its supporting functions below lightly adapted from the ViTDet backbone available at
    https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/vit.py.

    Attributes:
        img_size (int): Dimension of input images, assumed to be square.
        patch_embed (PatchEmbed): Module for patch embedding.
        pos_embed (nn.Parameter, optional): Absolute positional embedding for patches.
        blocks (nn.ModuleList): List of transformer blocks for processing patch embeddings.
        neck (nn.Sequential): Neck module to further process the output.
    i   é   é   é   é   ç      @é   TFr   © Úimg_sizeÚ
patch_sizeÚin_chansÚ	embed_dimÚdepthÚ	num_headsÚ	mlp_ratioÚ	out_chansÚqkv_biasÚ
norm_layerÚ	act_layerÚuse_abs_posÚuse_rel_posÚrel_pos_zero_initÚwindow_sizeÚglobal_attn_indexes.ÚreturnNc                 ó¤  •— t          ¦   «                              ¦   «          || _        t          ||f||f||¬¦  «        | _        d| _        |r4t          j        t          j	        d||z  ||z  |¦  «        ¦  «        | _        t          j
        ¦   «         | _        t          |¦  «        D ]C}t          ||||	|
|||||vr|nd||z  ||z  f¬¦
  «
        }| j                             |¦  «         ŒDt          j        t          j        ||dd¬¦  «        t#          |¦  «        t          j        ||ddd¬	¦  «        t#          |¦  «        ¦  «        | _        dS )
a  
        Args:
            img_size (int): Input image size.
            patch_size (int): Patch size.
            in_chans (int): Number of input image channels.
            embed_dim (int): Patch embedding dimension.
            depth (int): Depth of ViT.
            num_heads (int): Number of attention heads in each ViT block.
            mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
            qkv_bias (bool): If True, add a learnable bias to query, key, value.
            norm_layer (nn.Module): Normalization layer.
            act_layer (nn.Module): Activation layer.
            use_abs_pos (bool): If True, use absolute positional embeddings.
            use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
            rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
            window_size (int): Window size for window attention blocks.
            global_attn_indexes (list): Indexes for blocks using global attention.
        )Úkernel_sizeÚstrider   r   Né   r   )
Údimr   r   r   r   r   r   r   r    Ú
input_sizeF)r$   Úbiasr   )r$   Úpaddingr)   )ÚsuperÚ__init__r   Ú
PatchEmbedÚpatch_embedÚ	pos_embedÚnnÚ	ParameterÚtorchÚzerosÚ
ModuleListÚblocksÚrangeÚBlockÚappendÚ
SequentialÚConv2dr   Úneck)Úselfr   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   ÚiÚblockÚ	__class__s                      €ú‡/var/www/html/cool-property-finder/image-detection-backend/venv/lib/python3.11/site-packages/ultralytics/models/sam/modules/encoders.pyr,   zImageEncoderViT.__init__   s‘  ø€ õJ 	‰Œ×ÒÑÔÐØ ˆŒå%Ø# ZÐ0Ø 
Ð+ØØð	
ñ 
ô 
ˆÔð 26ˆŒØð 	uåœ\­%¬+°a¸ÀZÑ9OÐQYÐ]gÑQgÐirÑ*sÔ*sÑtÔtˆDŒNå”m‘o”oˆŒÝ�u‘”ð 	&ð 	&ˆAÝØØ#Ø#Ø!Ø%Ø#Ø'Ø"3Ø+,Ð4GÐ+GÐ+G˜K˜KÈQØ$¨
Ñ2°HÀ
Ñ4JÐKðñ ô ˆEð ŒK×Ò˜uÑ%Ô%Ð%Ð%å”MÝŒIØØØØð	ñ ô õ ˜	Ñ"Ô"ÝŒIØØØØØðñ ô õ ˜	Ñ"Ô"ñ
ô 
ˆŒ	ˆ	ˆ	ó    Úxc                 óÎ   — |                       |¦  «        }| j        �
|| j        z   }| j        D ]} ||¦  «        }Œ|                      |                     dddd¦  «        ¦  «        S )z†Processes input through patch embedding, applies positional embedding if present, and passes through blocks
        and neck.
        Nr   r   r&   é   )r.   r/   r5   r;   Úpermute)r<   rB   Úblks      r@   ÚforwardzImageEncoderViT.forwardt   so   € ð ×Ò˜QÑÔˆØŒ>Ð%Ø�D”NÑ"ˆAØ”;ð 	ð 	ˆCØ��A‘”ˆAˆAØ�yŠy˜Ÿš 1 a¨¨AÑ.Ô.Ñ/Ô/Ð/rA   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r0   Ú	LayerNormÚGELUÚintÚfloatÚboolr   ÚModuler   r,   r2   ÚTensorrG   Ú__classcell__©r?   s   @r@   r
   r
      s}  ø€ € € € € ðð ð$ !Ø ØØ ØØØ"Ø Ø!Ø*,¬,Ø)+¬Ø $Ø %Ø&*Ø Ø35ð#T
ð T
àðT
ð ðT
ð ð	T
ð
 ðT
ð ðT
ð ðT
ð ðT
ð ðT
ð ðT
ð ˜RœYœðT
ð ˜BœI”ðT
ð ðT
ð ðT
ð  $ðT
ð  ð!T
ð" "' s¨C x¤ð#T
ð$ 
ð%T
ð T
ð T
ð T
ð T
ð T
ðl	0˜œð 	0¨%¬,ð 	0ð 	0ð 	0ð 	0ð 	0ð 	0ð 	0ð 	0rA   r
   c                   ó6  ‡ — e Zd ZdZej        fdedeeef         deeef         dedeej	                 ddfˆ fd	„Z
dej        fd
„Zdej        dej        dedej        fd„Zdej        dej        fd„Zdej        dej        fd„Zdeeej        ej        f                  deej                 deej                 defd„Zdej        fd„Zdeeej        ej        f                  deej                 deej                 deej        ej        f         fd„Zˆ xZS )ÚPromptEncoderaø  
    Encodes different types of prompts, including points, boxes, and masks, for input to SAM's mask decoder. The encoder
    produces both sparse and dense embeddings for the input prompts.

    Attributes:
        embed_dim (int): Dimension of the embeddings.
        input_image_size (Tuple[int, int]): Size of the input image as (H, W).
        image_embedding_size (Tuple[int, int]): Spatial size of the image embedding as (H, W).
        pe_layer (PositionEmbeddingRandom): Module for random position embedding.
        num_point_embeddings (int): Number of point embeddings for different types of points.
        point_embeddings (nn.ModuleList): List of point embeddings.
        not_a_point_embed (nn.Embedding): Embedding for points that are not a part of any label.
        mask_input_size (Tuple[int, int]): Size of the input mask.
        mask_downscaling (nn.Sequential): Neural network for downscaling the mask.
        no_mask_embed (nn.Embedding): Embedding for cases where no mask is provided.
    r   Úimage_embedding_sizeÚinput_image_sizeÚmask_in_chansÚ
activationr"   Nc                 óæ  •‡— t          ¦   «                              ¦   «          ‰| _        || _        || _        t          ‰dz  ¦  «        | _        d| _        ˆfd„t          | j        ¦  «        D ¦   «         }t          j
        |¦  «        | _        t          j        d‰¦  «        | _        d|d         z  d|d         z  f| _        t          j        t          j        d|dz  dd¬¦  «        t#          |dz  ¦  «         |¦   «         t          j        |dz  |dd¬¦  «        t#          |¦  «         |¦   «         t          j        |‰d¬¦  «        ¦  «        | _        t          j        d‰¦  «        | _        dS )	a;  
        Encodes prompts for input to SAM's mask decoder.

        Args:
          embed_dim (int): The prompts' embedding dimension
          image_embedding_size (tuple(int, int)): The spatial size of the
            image embedding, as (H, W).
          input_image_size (int): The padded size of the image as input
            to the image encoder, as (H, W).
          mask_in_chans (int): The number of hidden channels used for
            encoding input masks.
          activation (nn.Module): The activation to use when encoding
            input masks.
        rD   é   c                 ó:   •— g | ]}t          j        d ‰¦  «        ‘ŒS )r&   )r0   Ú	Embedding)Ú.0Ú_r   s     €r@   ú
<listcomp>z*PromptEncoder.__init__.<locals>.<listcomp>¯   s%   ø€ ÐaÐaÐa¸1�BœL¨¨IÑ6Ô6ÐaÐaÐarA   r&   r   )r$   r%   )r$   N)r+   r,   r   rX   rW   ÚPositionEmbeddingRandomÚpe_layerÚnum_point_embeddingsr6   r0   r4   Úpoint_embeddingsr^   Únot_a_point_embedÚmask_input_sizer9   r:   r   Úmask_downscalingÚno_mask_embed)r<   r   rW   rX   rY   rZ   re   r?   s    `     €r@   r,   zPromptEncoder.__init__’   se  øø€ õ, 	‰Œ×ÒÑÔÐØ"ˆŒØ 0ˆÔØ$8ˆÔ!Ý/°	¸Q±Ñ?Ô?ˆŒà)*ˆÔ!ØaÐaÐaÐaÅÀdÔF_Ñ@`Ô@`ÐaÑaÔaÐÝ "¤Ð.>Ñ ?Ô ?ˆÔÝ!#¤¨a°Ñ!;Ô!;ˆÔà !Ð$8¸Ô$;Ñ ;¸QÐAUÐVWÔAXÑ=XÐYˆÔÝ "¤ÝŒI�a˜¨!Ñ+¸À1ÐEÑEÔEÝ˜¨Ñ*Ñ+Ô+ØˆJ‰LŒLÝŒI�m qÑ(¨-ÀQÈqÐQÑQÔQÝ˜Ñ&Ô&ØˆJ‰LŒLÝŒI�m Y¸AÐ>Ñ>Ô>ñ!
ô !
ˆÔõ  œ\¨!¨YÑ7Ô7ˆÔÐÐrA   c                 ó\   — |                       | j        ¦  «                             d¦  «        S )a  
        Returns the positional encoding used to encode point prompts, applied to a dense set of points the shape of the
        image encoding.

        Returns:
          torch.Tensor: Positional encoding with shape 1x(embed_dim)x(embedding_h)x(embedding_w)
        r   )rc   rW   Ú	unsqueeze©r<   s    r@   Úget_dense_pezPromptEncoder.get_dense_pe¿   s'   € ð �}Š}˜TÔ6Ñ7Ô7×AÒAÀ!ÑDÔDÐDrA   ÚpointsÚlabelsÚpadc                 ó6  — |dz   }|r‚t          j        |j        d         ddf|j        ¬¦  «        }t          j        |j        d         df|j        ¬¦  «         }t          j        ||gd¬¦  «        }t          j        ||gd¬¦  «        }| j                             || j        ¦  «        }d||dk    <   ||dk    xx         | j	        j
        z  cc<   ||dk    xx         | j        d         j
        z  cc<   ||dk    xx         | j        d         j
        z  cc<   |S )	zEmbeds point prompts.ç      à?r   r&   rD   ©Údevice©r'   ç        éÿÿÿÿ)r2   r3   Úshapert   ÚonesÚcatrc   Úforward_with_coordsrX   rf   Úweightre   )r<   rn   ro   rp   Úpadding_pointÚpadding_labelÚpoint_embeddings          r@   Ú_embed_pointszPromptEncoder._embed_pointsÉ   s8  € ð ˜#‘ˆØð 	?Ý!œK¨¬°a¬¸!¸QÐ(?ÈÌÐVÑVÔVˆMÝ"œZ¨¬°a¬¸!Ð(<ÀVÄ]ÐSÑSÔSÐSˆMÝ”Y ¨Ð6¸AÐ>Ñ>Ô>ˆFÝ”Y ¨Ð6¸AÐ>Ñ>Ô>ˆFØœ-×;Ò;¸FÀDÔDYÑZÔZˆØ(+ˆ˜ "šÑ%Ø˜ "šÐ%Ð%Ô%¨Ô)?Ô)FÑFÐ%Ð%Ñ%Ø˜ !šÐ$Ð$Ô$¨Ô(=¸aÔ(@Ô(GÑGÐ$Ð$Ñ$Ø˜ !šÐ$Ð$Ô$¨Ô(=¸aÔ(@Ô(GÑGÐ$Ð$Ñ$ØÐrA   Úboxesc                 ó  — |dz   }|                      ddd¦  «        }| j                             || j        ¦  «        }|dd…ddd…fxx         | j        d         j        z  cc<   |dd…ddd…fxx         | j        d         j        z  cc<   |S )zEmbeds box prompts.rr   rw   rD   Nr   r&   r   )Úreshaperc   r{   rX   re   r|   )r<   r�   ÚcoordsÚcorner_embeddings       r@   Ú_embed_boxeszPromptEncoder._embed_boxesÝ   s«   € à˜‘ˆØ—’˜r 1 aÑ(Ô(ˆØœ=×<Ò<¸VÀTÔEZÑ[Ô[ÐØ˜˜˜˜A˜q˜q˜q˜Ð!Ð!Ô! TÔ%:¸1Ô%=Ô%DÑDÐ!Ð!Ñ!Ø˜˜˜˜A˜q˜q˜q˜Ð!Ð!Ô! TÔ%:¸1Ô%=Ô%DÑDÐ!Ð!Ñ!ØÐrA   Úmasksc                 ó,   — |                       |¦  «        S )zEmbeds mask inputs.)rh   )r<   r‡   s     r@   Ú_embed_maskszPromptEncoder._embed_masksæ   s   € à×$Ò$ UÑ+Ô+Ð+rA   c                 ól   — |�|d         j         d         S |�|j         d         S |�|j         d         S dS )zLGets the batch size of the output given the batch size of the input prompts.Nr   r&   )rx   )r<   rn   r�   r‡   s       r@   Ú_get_batch_sizezPromptEncoder._get_batch_sizeê   sD   € ð ÐØ˜!”9”? 1Ô%Ð%ØÐØ”;˜q”>Ð!ØÐØ”;˜q”>Ð!à�1rA   c                 ó0   — | j         d         j        j        S )z@Returns the device of the first point embedding's weight tensor.r   )re   r|   rt   rl   s    r@   Ú_get_devicezPromptEncoder._get_deviceú   s   € àÔ$ QÔ'Ô.Ô5Ð5rA   c                 ó4  — |                       |||¦  «        }t          j        |d| j        f|                      ¦   «         ¬¦  «        }|�7|\  }}|                      |||du ¬¦  «        }t          j        ||gd¬¦  «        }|�-|                      |¦  «        }	t          j        ||	gd¬¦  «        }|�|                      |¦  «        }
nN| j	        j
                             dddd¦  «                             |d| j        d         | j        d         ¦  «        }
||
fS )a`  
        Embeds different types of prompts, returning both sparse and dense embeddings.

        Args:
          points (tuple(torch.Tensor, torch.Tensor), None): point coordinates and labels to embed.
          boxes (torch.Tensor, None): boxes to embed
          masks (torch.Tensor, None): masks to embed

        Returns:
          torch.Tensor: sparse embeddings for the points and boxes, with shape BxNx(embed_dim), where N is determined
            by the number of input points and boxes.
          torch.Tensor: dense embeddings for the masks, in the shape Bx(embed_dim)x(embed_H)x(embed_W)
        r   rs   N)rp   r&   ru   rw   )r‹   r2   Úemptyr   r�   r€   rz   r†   r‰   ri   r|   rƒ   ÚexpandrW   )r<   rn   r�   r‡   ÚbsÚsparse_embeddingsr„   ro   re   Úbox_embeddingsÚdense_embeddingss              r@   rG   zPromptEncoder.forwardþ   sI  € ð& ×!Ò! &¨%°Ñ7Ô7ˆÝ!œK¨¨Q°´Ð(?È×HXÒHXÑHZÔHZÐ[Ñ[Ô[ÐØÐØ#‰NˆF�FØ#×1Ò1°&¸&ÀuÐPTÀ}Ð1ÑVÔVÐÝ %¤	Ð+<Ð>NÐ*OÐUVÐ WÑ WÔ WÐØÐØ!×.Ò.¨uÑ5Ô5ˆNÝ %¤	Ð+<¸nÐ*MÐSTÐ UÑ UÔ UÐàÐØ#×0Ò0°Ñ7Ô7ÐÐà#Ô1Ô8×@Ò@ÀÀBÈØABñ Dô  DßDJÂFÈ2ÈrÐSWÔSlÐmnÔSoØKOÔKdÐefÔKgñEiô Eið ð !Ð"2Ð2Ð2rA   )rH   rI   rJ   rK   r0   rM   rN   r   r   rQ   r,   r2   rR   rm   rP   r€   r†   r‰   r   r‹   rt   r�   rG   rS   rT   s   @r@   rV   rV   €   s3  ø€ € € € € ðð ð. ')¤gð+8ð +8àð+8ð $ C¨ Hœoð+8ð    S œ/ð	+8ð
 ð+8ð ˜œ”Oð+8ð 
ð+8ð +8ð +8ð +8ð +8ð +8ðZE˜eœlð Eð Eð Eð Eðà”ðð ”ðð ð	ð
 
Œðð ð ð ð(  %¤,ð  °5´<ð  ð  ð  ð  ð, %¤,ð ,°5´<ð ,ð ,ð ,ð ,ðà˜˜uœ|¨U¬\Ð9Ô:Ô;ðð ˜œÔ%ðð ˜œÔ%ð	ð
 
ðð ð ð ð 6˜Uœ\ð 6ð 6ð 6ð 6ð$3à˜˜uœ|¨U¬\Ð9Ô:Ô;ð$3ð ˜œÔ%ð$3ð ˜œÔ%ð	$3ð
 
ˆuŒ|˜Uœ\Ð)Ô	*ð$3ð $3ð $3ð $3ð $3ð $3ð $3ð $3rA   rV   c                   óÄ   ‡ — e Zd ZdZddedee         ddfˆ fd„Zdej	        dej	        fd	„Z
d
eeef         dej	        fd„Zdej	        deeef         dej	        fd„Zˆ xZS )rb   z5Positional encoding using random spatial frequencies.é@   NÚnum_pos_featsÚscaler"   c                 ó
  •— t          ¦   «                              ¦   «          |�|dk    rd}|                      d|t          j        d|f¦  «        z  ¦  «         t          j        d¦  «         dt          j        j        _        dS )zBInitializes a position embedding using random spatial frequencies.Nrv   ç      ð?Ú#positional_encoding_gaussian_matrixrD   F)	r+   r,   Úregister_bufferr2   ÚrandnÚuse_deterministic_algorithmsÚbackendsÚcudnnÚdeterministic)r<   r—   r˜   r?   s      €r@   r,   z PositionEmbeddingRandom.__init__(  s~   ø€ å‰Œ×ÒÑÔÐØˆ=˜E SšL˜LØˆEØ×ÒÐBÀEÍEÌKÐYZÐ\iÐXjÑLkÔLkÑDkÑlÔlÐlõ 	Ô*¨5Ñ1Ô1Ð1Ø-2�ŒÔÔ*Ð*Ð*rA   r„   c                 óÂ   — d|z  dz
  }|| j         z  }dt          j        z  |z  }t          j        t          j        |¦  «        t          j        |¦  «        gd¬¦  «        S )z8Positionally encode points that are normalized to [0,1].rD   r&   rw   ru   )r›   ÚnpÚpir2   rz   ÚsinÚcos)r<   r„   s     r@   Ú_pe_encodingz$PositionEmbeddingRandom._pe_encoding3  s\   € ð �V‘˜a‘ˆØ˜$ÔBÑBˆØ•R”U‘˜VÑ#ˆåŒy�%œ) FÑ+Ô+­U¬Y°vÑ->Ô->Ð?ÀRÐHÑHÔHÐHrA   Úsizec                 óf  — |\  }}| j         j        }t          j        ||f|t          j        ¬¦  «        }|                     d¬¦  «        dz
  }|                     d¬¦  «        dz
  }||z  }||z  }|                      t          j        ||gd¬¦  «        ¦  «        }|                     ddd¦  «        S )z>Generate positional encoding for a grid of the specified size.)rt   Údtyper   ru   rr   r&   rw   rD   )	r›   rt   r2   ry   Úfloat32Úcumsumr§   ÚstackrE   )	r<   r¨   ÚhÚwrt   ÚgridÚy_embedÚx_embedÚpes	            r@   rG   zPositionEmbeddingRandom.forward<  s±   € à‰ˆˆ1ØÔ>ÔEˆÝŒz˜1˜a˜&¨µu´}ÐEÑEÔEˆØ—+’+ !�+Ñ$Ô$ sÑ*ˆØ—+’+ !�+Ñ$Ô$ sÑ*ˆØ˜A‘+ˆØ˜A‘+ˆà×Ò�uœ{¨G°WÐ+=À2ÐFÑFÔFÑGÔGˆØ�zŠz˜!˜Q Ñ"Ô"Ð"rA   Úcoords_inputÚ
image_sizec                 ó  — |                      ¦   «         }|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<   |                      |                     t          j        ¦  «        ¦  «        S )z<Positionally encode points that are not normalized to [0,1].Nr   r&   )Úcloner§   Útor2   rO   )r<   r´   rµ   r„   s       r@   r{   z+PositionEmbeddingRandom.forward_with_coordsI  s™   € à×#Ò#Ñ%Ô%ˆØ     A A A q œ/¨J°q¬MÑ9ˆˆqˆqˆq�!�!�!�Qˆw‰Ø     A A A q œ/¨J°q¬MÑ9ˆˆqˆqˆq�!�!�!�Qˆw‰Ø× Ò  §¢­5¬;Ñ!7Ô!7Ñ8Ô8Ð8rA   )r–   N)rH   rI   rJ   rK   rN   r   rO   r,   r2   rR   r§   r   rG   r{   rS   rT   s   @r@   rb   rb   %  sô   ø€ € € € € Ø?Ð?ð	3ð 	3 cð 	3°xÀ´ð 	3ÐRVð 	3ð 	3ð 	3ð 	3ð 	3ð 	3ðI 5¤<ð I°E´Lð Ið Ið Ið Ið#˜E # s (œOð #°´ð #ð #ð #ð #ð9°´ð 9È%ÐPSÐUXÐPXÌ/ð 9Ð^cÔ^jð 9ð 9ð 9ð 9ð 9ð 9ð 9ð 9rA   rb   c                   óâ   ‡ — e Zd ZdZddej        ej        ddddfdeded	ed
e	de
ej                 de
ej                 de	de	dedeeeef                  ddfˆ fd„Zdej        dej        fd„Zˆ xZS )r7   zTTransformer blocks with support of window attention and residual propagation blocks.r   TFr   Nr'   r   r   r   r   r   r   r   r    r(   r"   c           	      ó,  •— t          ¦   «                              ¦   «           ||¦  «        | _        t          ||||||	dk    r|
n|	|	f¬¦  «        | _         ||¦  «        | _        t          |t          ||z  ¦  «        |¬¦  «        | _        |	| _	        dS )ag  
        Args:
            dim (int): Number of input channels.
            num_heads (int): Number of attention heads in each ViT block.
            mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
            qkv_bias (bool): If True, add a learnable bias to query, key, value.
            norm_layer (nn.Module): Normalization layer.
            act_layer (nn.Module): Activation layer.
            use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
            rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
            window_size (int): Window size for window attention blocks. If it equals 0, then
                use global attention.
            input_size (tuple(int, int), None): Input resolution for calculating the relative
                positional parameter size.
        r   )r   r   r   r   r(   )Úembedding_dimÚmlp_dimÚactN)
r+   r,   Únorm1Ú	AttentionÚattnÚnorm2r   rN   Úmlpr    )r<   r'   r   r   r   r   r   r   r   r    r(   r?   s              €r@   r,   zBlock.__init__T  s§   ø€ õ8 	‰Œ×ÒÑÔÐØ�Z ‘_”_ˆŒ
ÝØØØØ#Ø/Ø%0°AÒ%5Ð%5�z�z¸KÈÐ;Uð
ñ 
ô 
ˆŒ	ð  �Z ‘_”_ˆŒ
Ý¨#µs¸3À¹?Ñ7KÔ7KÐQZÐ[Ñ[Ô[ˆŒà&ˆÔÐÐrA   rB   c                 ó|  — |}|                       |¦  «        }| j        dk    r2|j        d         |j        d         }}t          || j        ¦  «        \  }}|                      |¦  «        }| j        dk    rt          || j        |||f¦  «        }||z   }||                      |                      |¦  «        ¦  «        z   S )zhExecutes a forward pass through the transformer block with window attention and non-overlapping windows.r   r&   rD   )r¾   r    rx   Úwindow_partitionrÀ   Úwindow_unpartitionrÂ   rÁ   )r<   rB   ÚshortcutÚHÚWÚpad_hws         r@   rG   zBlock.forward€  s°   € àˆØ�JŠJ�q‰MŒMˆàÔ˜aÒÐØ”7˜1”:˜qœw qœzˆqˆAÝ(¨¨DÔ,<Ñ=Ô=‰IˆAˆvà�IŠI�a‰LŒLˆàÔ˜aÒÐÝ" 1 dÔ&6¸ÀÀAÀÑGÔGˆAà�q‰LˆØ�4—8’8˜DŸJšJ q™MœMÑ*Ô*Ñ*Ð*rA   )rH   rI   rJ   rK   r0   rL   rM   rN   rO   rP   r   rQ   r   r   r,   r2   rR   rG   rS   rT   s   @r@   r7   r7   Q  s  ø€ € € € € Ø^Ð^ð ØØ&(¤lØ%'¤WØ!Ø"&ØØ04ð*'ð *'àð*'ð ð*'ð ð	*'ð
 ð*'ð ˜œ”Oð*'ð ˜œ	”?ð*'ð ð*'ð  ð*'ð ð*'ð ˜U 3¨ 8œ_Ô-ð*'ð 
ð*'ð *'ð *'ð *'ð *'ð *'ðX+˜œð +¨%¬,ð +ð +ð +ð +ð +ð +ð +ð +rA   r7   c                   óŒ   ‡ — e Zd ZdZ	 	 	 	 	 ddededed	ed
edeeeef                  ddfˆ fd„Zde	j
        de	j
        fd„Zˆ xZS )r¿   z=Multi-head Attention block with relative position embeddings.é   TFNr'   r   r   r   r   r(   r"   c                 óþ  •— t          ¦   «                              ¦   «          || _        ||z  }|dz  | _        t	          j        ||dz  |¬¦  «        | _        t	          j        ||¦  «        | _        || _        | j        r~|€
J d¦   «         ‚t	          j	        t          j        d|d         z  dz
  |¦  «        ¦  «        | _        t	          j	        t          j        d|d         z  dz
  |¦  «        ¦  «        | _        dS dS )	aà  
        Initialize Attention module.

        Args:
            dim (int): Number of input channels.
            num_heads (int): Number of attention heads.
            qkv_bias (bool):  If True, add a learnable bias to query, key, value.
            rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
            input_size (tuple(int, int), None): Input resolution for calculating the relative
                positional parameter size.
        g      à¿r   )r)   NzBInput size must be provided if using relative positional encoding.rD   r   r&   )r+   r,   r   r˜   r0   ÚLinearÚqkvÚprojr   r1   r2   r3   Ú	rel_pos_hÚ	rel_pos_w)	r<   r'   r   r   r   r   r(   Úhead_dimr?   s	           €r@   r,   zAttention.__init__•  sö   ø€ õ( 	‰Œ×ÒÑÔÐØ"ˆŒØ˜)Ñ#ˆØ Ñ%ˆŒ
å”9˜S #¨¡'°Ð9Ñ9Ô9ˆŒÝ”I˜c 3Ñ'Ô'ˆŒ	à&ˆÔØÔð 	XØÐ*Ð*Ð-qÑ*Ô*Ð*åœ\­%¬+°a¸*ÀQ¼-Ñ6GÈ!Ñ6KÈXÑ*VÔ*VÑWÔWˆDŒNÝœ\­%¬+°a¸*ÀQ¼-Ñ6GÈ!Ñ6KÈXÑ*VÔ*VÑWÔWˆDŒNˆNˆNð		Xð 	XrA   rB   c           	      óª  — |j         \  }}}}|                      |¦  «                             |||z  d| j        d¦  «                             ddddd¦  «        }|                     d|| j        z  ||z  d¦  «                             d¦  «        \  }}}	|| j        z  |                     dd¦  «        z  }
| j        r"t          |
|| j
        | j        ||f||f¦  «        }
|
                     d¬¦  «        }
|
|	z                       || j        ||d¦  «                             ddddd¦  «                             |||d¦  «        }|                      |¦  «        S )	ziApplies the forward operation including attention, normalization, MLP, and indexing within window limits.r   rw   rD   r   r&   r\   éþÿÿÿru   )rx   rÎ   rƒ   r   rE   Úunbindr˜   Ú	transposer   Úadd_decomposed_rel_posrÐ   rÑ   ÚsoftmaxÚviewrÏ   )r<   rB   ÚBrÇ   rÈ   r`   rÎ   ÚqÚkÚvrÀ   s              r@   rG   zAttention.forward¸  sN  € à”W‰
ˆˆ1ˆa�à�hŠh�q‰kŒk×!Ò! ! Q¨¡U¨A¨t¬~¸rÑBÔB×JÒJÈ1ÈaÐQRÐTUÐWXÑYÔYˆà—+’+˜a  T¤^Ñ!3°Q¸±U¸BÑ?Ô?×FÒFÀqÑIÔI‰ˆˆ1ˆaà�D”J‘ !§+¢+¨b°"Ñ"5Ô"5Ñ5ˆàÔð 	cÝ)¨$°°4´>À4Ä>ÐTUÐWXÐSYÐ\]Ð_`Ð[aÑbÔbˆDà�|Š| ˆ|Ñ#Ô#ˆØ�A‰X�OŠO˜A˜tœ~¨q°!°RÑ8Ô8×@Ò@ÀÀAÀqÈ!ÈQÑOÔO×WÒWÐXYÐ[\Ð^_ÐacÑdÔdˆØ�yŠy˜‰|Œ|ÐrA   )rË   TFTN)rH   rI   rJ   rK   rN   rP   r   r   r,   r2   rR   rG   rS   rT   s   @r@   r¿   r¿   ’  sß   ø€ € € € € ØGÐGð
 ØØ!Ø"&Ø04ð!Xð !Xàð!Xð ð!Xð ð	!Xð
 ð!Xð  ð!Xð ˜U 3¨ 8œ_Ô-ð!Xð 
ð!Xð !Xð !Xð !Xð !Xð !XðF˜œð ¨%¬,ð ð ð ð ð ð ð ð rA   r¿   rB   r    r"   c           	      óx  — | j         \  }}}}|||z  z
  |z  }|||z  z
  |z  }|dk    s|dk    rt          j        | ddd|d|f¦  «        } ||z   ||z   }	}|                      |||z  ||	|z  ||¦  «        } |                      dddddd¦  «                             ¦   «                              d|||¦  «        }
|
||	ffS )aU  
    Partition into non-overlapping windows with padding if needed.
    Args:
        x (tensor): input tokens with [B, H, W, C].
        window_size (int): window size.

    Returns:
        windows: windows after partition with [B * num_windows, window_size, window_size, C].
        (Hp, Wp): padded height and width before partition
    r   r&   r   rD   r\   é   rw   )rx   ÚFrp   rÙ   rE   Ú
contiguous)rB   r    rÚ   rÇ   rÈ   ÚCÚpad_hÚpad_wÚHpÚWpÚwindowss              r@   rÄ   rÄ   Ê  sê   € ð ”�J€A€qˆ!ˆQà˜1˜{™?Ñ*¨kÑ9€EØ˜1˜{™?Ñ*¨kÑ9€EØˆq‚y€y�E˜A’I�IÝŒE�!�a˜˜A˜u a¨Ð/Ñ0Ô0ˆØ�‰Y˜˜E™	ˆ€Bà	�Šˆq�"˜Ñ# [°"¸Ñ2CÀ[ÐRSÑTÔT€AØ�iŠi˜˜1˜a  A qÑ)Ô)×4Ò4Ñ6Ô6×;Ò;¸BÀÈ[ÐZ[Ñ\Ô\€GØ�R˜�HÐÐrA   rç   rÉ   Úhwc                 ót  — |\  }}|\  }}| j         d         ||z  |z  |z  z  }|                      |||z  ||z  ||d¦  «        }	|	                     dddddd¦  «                             ¦   «                              |||d¦  «        }	||k    s||k    r&|	dd…d|…d|…dd…f                              ¦   «         }	|	S )	aœ  
    Window unpartition into original sequences and removing padding.

    Args:
        windows (tensor): input tokens with [B * num_windows, window_size, window_size, C].
        window_size (int): window size.
        pad_hw (Tuple): padded height and width (Hp, Wp).
        hw (Tuple): original height and width (H, W) before padding.

    Returns:
        x: unpartitioned sequences with [B, H, W, C].
    r   rw   r&   r   rD   r\   rß   N)rx   rÙ   rE   rá   )
rç   r    rÉ   rè   rå   ræ   rÇ   rÈ   rÚ   rB   s
             r@   rÅ   rÅ   â  sÙ   € ð �F€BˆØ�D€A€qØŒ�aÔ˜R "™W¨Ñ3°{ÑBÑC€AØ�Š�Q˜˜kÑ)¨2°Ñ+<¸kÈ;ÐXZÑ[Ô[€AØ	�	Š	�!�Q˜˜1˜a Ñ#Ô#×.Ò.Ñ0Ô0×5Ò5°a¸¸RÀÑDÔD€Aà	ˆA‚v€v��a’�Øˆaˆaˆa��!��R�a�R˜˜˜ˆlŒO×&Ò&Ñ(Ô(ˆØ€HrA   Úq_sizeÚk_sizeÚrel_posc                 ó–  — t          dt          | |¦  «        z  dz
  ¦  «        }|j        d         |k    rwt          j        |                     d|j        d         d¦  «                             ddd¦  «        |d¬¦  «        }|                     d|¦  «                             dd¦  «        }n|}t          j        | ¦  «        dd…df         t          || z  d¦  «        z  }t          j        |¦  «        ddd…f         t          | |z  d¦  «        z  }||z
  |dz
  t          | |z  d¦  «        z  z   }|| 	                    ¦   «                  S )	aU  
    Get relative positional embeddings according to the relative positions of query and key sizes.

    Args:
        q_size (int): size of query q.
        k_size (int): size of key k.
        rel_pos (Tensor): relative position embeddings (L, C).

    Returns:
        Extracted positional embeddings according to relative positions.
    rD   r&   r   rw   Úlinear)r¨   ÚmodeNrš   )
rN   Úmaxrx   rà   Úinterpolaterƒ   rE   r2   ÚarangeÚlong)rê   rë   rì   Úmax_rel_distÚrel_pos_resizedÚq_coordsÚk_coordsÚrelative_coordss           r@   Úget_rel_posrù   û  sK  € õ �q�3˜v vÑ.Ô.Ñ.°Ñ2Ñ3Ô3€Là„}�QÔ˜<Ò'Ð'åœ-Ø�OŠO˜A˜wœ}¨QÔ/°Ñ4Ô4×<Ò<¸QÀÀ1ÑEÔEØØð
ñ 
ô 
ˆð
 *×1Ò1°"°lÑCÔC×KÒKÈAÈqÑQÔQˆˆà!ˆõ Œ|˜FÑ#Ô# A A A t GÔ,­s°6¸F±?ÀCÑ/HÔ/HÑH€HÝŒ|˜FÑ#Ô# D¨!¨!¨! GÔ,­s°6¸F±?ÀCÑ/HÔ/HÑH€HØ (Ñ*¨v¸©z½SÀÈ&ÁÐRUÑ=VÔ=VÑ.VÑV€Oà˜?×/Ò/Ñ1Ô1Ô2Ð2rA   rÀ   rÛ   rÐ   rÑ   c                 ó¼  — |\  }}|\  }}	t          |||¦  «        }
t          ||	|¦  «        }|j        \  }}}|                     ||||¦  «        }t          j        d||
¦  «        }t          j        d||¦  «        }|                      |||||	¦  «        |dd…dd…dd…dd…df         z   |dd…dd…dd…ddd…f         z                        |||z  ||	z  ¦  «        } | S )a¸  
    Calculate decomposed Relative Positional Embeddings from mvitv2 paper at
    https://github.com/facebookresearch/mvit/blob/main/mvit/models/attention.py.

    Args:
        attn (Tensor): attention map.
        q (Tensor): query q in the attention layer with shape (B, q_h * q_w, C).
        rel_pos_h (Tensor): relative position embeddings (Lh, C) for height axis.
        rel_pos_w (Tensor): relative position embeddings (Lw, C) for width axis.
        q_size (Tuple): spatial sequence size of query q with (q_h, q_w).
        k_size (Tuple): spatial sequence size of key k with (k_h, k_w).

    Returns:
        attn (Tensor): attention map with added relative positional embeddings.
    zbhwc,hkc->bhwkzbhwc,wkc->bhwkN)rù   rx   rƒ   r2   ÚeinsumrÙ   )rÀ   rÛ   rÐ   rÑ   rê   rë   Úq_hÚq_wÚk_hÚk_wÚRhÚRwrÚ   r`   r'   Úr_qÚrel_hÚrel_ws                     r@   r×   r×     s  € ð. �H€CˆØ�H€CˆÝ	�S˜#˜yÑ	)Ô	)€BÝ	�S˜#˜yÑ	)Ô	)€Bà”�I€A€qˆ#Ø
�)Š)�A�s˜C Ñ
%Ô
%€CÝŒLÐ)¨3°Ñ3Ô3€EÝŒLÐ)¨3°Ñ3Ô3€Eà�IŠI�a˜˜c 3¨Ñ,Ô,¨u°Q°Q°Q¸¸¸¸1¸1¸1¸a¸a¸aÀÐ5EÔ/FÑFÈÈqÈqÈqÐRSÐRSÐRSÐUVÐUVÐUVÐX\Ð^_Ð^_Ð^_ÐO_ÔI`Ñ`×fÒfØ	ˆ3�‰9�c˜C‘iñ!ô !€Dð €KrA   c                   óœ   ‡ — e Zd ZdZ	 	 	 	 	 ddeeef         deeef         deeef         d	ed
eddfˆ fd„Zdej        dej        fd„Z	ˆ xZ
S )r-   zImage to Patch Embedding.©r   r   ©r   r   r   r   r$   r%   r*   r   r   r"   Nc                 ó„   •— t          ¦   «                              ¦   «          t          j        |||||¬¦  «        | _        dS )aw  
        Initialize PatchEmbed module.

        Args:
            kernel_size (Tuple): kernel size of the projection layer.
            stride (Tuple): stride of the projection layer.
            padding (Tuple): padding size of the projection layer.
            in_chans (int): Number of input image channels.
            embed_dim (int): Patch embedding dimension.
        )r$   r%   r*   N)r+   r,   r0   r:   rÏ   )r<   r$   r%   r*   r   r   r?   s         €r@   r,   zPatchEmbed.__init__F  s=   ø€ õ$ 	‰Œ×ÒÑÔÐå”I˜h¨	¸{ÐSYÐcjÐkÑkÔkˆŒ	ˆ	ˆ	rA   rB   c                 óX   — |                       |¦  «                             dddd¦  «        S )zRComputes patch embedding by applying convolution and transposing resulting tensor.r   rD   r   r&   )rÏ   rE   )r<   rB   s     r@   rG   zPatchEmbed.forward\  s&   € à�yŠy˜‰|Œ|×#Ò# A q¨!¨QÑ/Ô/Ð/rA   )r  r  r  r   r   )rH   rI   rJ   rK   r   rN   r,   r2   rR   rG   rS   rT   s   @r@   r-   r-   C  sÞ   ø€ € € € € Ø#Ð#ð ,4Ø&.Ø'-ØØ ðlð là˜s C˜xœðlð ˜#˜s˜(”Oðlð ˜3 ˜8”_ð	lð
 ðlð ðlð 
ðlð lð lð lð lð lð,0˜œð 0¨%¬,ð 0ð 0ð 0ð 0ð 0ð 0ð 0ð 0rA   r-   )Útypingr   r   r   r   Únumpyr£   r2   Útorch.nnr0   Útorch.nn.functionalÚ
functionalrà   Úultralytics.nn.modulesr   r   rQ   r
   rV   rb   r7   r¿   rR   rN   rÄ   rÅ   rù   r×   r-   r   rA   r@   ú<module>r     sâ  ðð .Ð -Ð -Ð -Ð -Ð -Ð -Ð -Ð -Ð -Ð -Ð -à Ð Ð Ð Ø €€€Ø Ð Ð Ð Ð Ð Ø Ð Ð Ð Ð Ð Ð Ð Ð à 8Ð 8Ð 8Ð 8Ð 8Ð 8Ð 8Ð 8ðp0ð p0ð p0ð p0ð p0�b”iñ p0ô p0ð p0ðfb3ð b3ð b3ð b3ð b3�B”Iñ b3ô b3ð b3ðJ)9ð )9ð )9ð )9ð )9˜bœiñ )9ô )9ð )9ðX>+ð >+ð >+ð >+ð >+ˆBŒIñ >+ô >+ð >+ðB5ð 5ð 5ð 5ð 5�”	ñ 5ô 5ð 5ðp˜œð °3ð ¸5ÀÄÈuÐUXÐZ]ÐU]ÌÐA^Ô;_ð ð ð ð ð0 ¤ð ¸3ð ÈÈcÐSVÈhÌð Ø   c œ?ðØ/4¬|ðð ð ð ð23˜ð 3 Sð 3°5´<ð 3ÀEÄLð 3ð 3ð 3ð 3ðB$Ø
Œ,ð$à„|ð$ð Œ|ð$ð Œ|ð	$ð
 �#�s�(ŒOð$ð �#�s�(ŒOð$ð „\ð$ð $ð $ð $ðN0ð 0ð 0ð 0ð 0�”ñ 0ô 0ð 0ð 0ð 0rA   