o
    Wh                     @   s   d dl mZmZmZmZ d dlZd dlmZ d dlm  m	Z
 d dlmZ ddlmZmZmZmZmZmZmZmZ G dd dejZG dd	 d	ejZG d
d dejZG dd dejZG dd dejZG dd dejZdS )    )ListOptionalTupleTypeN)LayerNorm2d   )BlockCXBlockFuserMaskDownSamplerMultiScaleBlock
PatchEmbedPositionEmbeddingRandomPositionEmbeddingSinec                #       s   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 d!Zd"ejdejfd#d$Z  ZS )%ImageEncoderViTa1  
    An image encoder using Vision Transformer (ViT) architecture for encoding images into a compact latent space.

    This class processes images by splitting them into patches, applying transformer blocks, and generating a final
    encoded representation through a neck module.

    Attributes:
        img_size (int): Dimension of input images, assumed to be square.
        patch_embed (PatchEmbed): Module for patch embedding.
        pos_embed (nn.Parameter | None): 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.

    Methods:
        forward: Processes input through patch embedding, positional embedding, blocks, and neck.

    Examples:
        >>> import torch
        >>> encoder = ImageEncoderViT(img_size=224, patch_size=16, embed_dim=768, depth=12, num_heads=12)
        >>> input_image = torch.randn(1, 3, 224, 224)
        >>> output = encoder(input_image)
        >>> print(output.shape)
             i      g      @   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                    s   t    || _t||f||f||d| _d| _|r*tt	d|| || || _t
 | _t|D ]"}t||||	|
|||||vrD|nd|| || fd
}| j| q3ttj||dddt|tj||dddd	t|| _dS )
a[  
        Initialize an ImageEncoderViT instance for encoding images using Vision Transformer architecture.

        Args:
            img_size (int): Input image size, assumed to be square.
            patch_size (int): Size of image patches.
            in_chans (int): Number of input image channels.
            embed_dim (int): Dimension of patch embeddings.
            depth (int): Number of transformer blocks.
            num_heads (int): Number of attention heads in each block.
            mlp_ratio (float): Ratio of MLP hidden dimension to embedding dimension.
            out_chans (int): Number of output channels from the neck module.
            qkv_bias (bool): If True, adds learnable bias to query, key, value projections.
            norm_layer (Type[nn.Module]): Type of normalization layer to use.
            act_layer (Type[nn.Module]): Type of activation layer to use.
            use_abs_pos (bool): If True, uses absolute positional embeddings.
            use_rel_pos (bool): If True, adds relative positional embeddings to attention maps.
            rel_pos_zero_init (bool): If True, initializes relative positional parameters to zero.
            window_size (int): Size of attention window for windowed attention blocks.
            global_attn_indexes (Tuple[int, ...]): Indices of blocks that use global attention.

        Examples:
            >>> encoder = ImageEncoderViT(img_size=224, patch_size=16, embed_dim=768, depth=12, num_heads=12)
            >>> input_image = torch.randn(1, 3, 224, 224)
            >>> output = encoder(input_image)
            >>> print(output.shape)
        )kernel_sizestrider   r   Nr   r   )
dimr   r   r   r    r!   r#   r$   r%   
input_sizeF)r(   biasr   )r(   paddingr,   )super__init__r   r   patch_embed	pos_embednn	Parametertorchzeros
ModuleListblocksranger   append
SequentialConv2dr   neck)selfr   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   iblock	__class__r   [/var/www/vscode/kcb/lib/python3.10/site-packages/ultralytics/models/sam/modules/encoders.pyr/   0   sV   
. 

zImageEncoderViT.__init__xc                 C   s   |  |}| jdur-| jdkr&tj| jdddd| jd dddddn| j}|| }| jD ]}||}q0| |ddddS )zaProcess input through patch embedding, positional embedding, transformer blocks, and neck module.Nr   r   r   r      )scale_factor)r0   r1   r   Finterpolatepermuter7   r<   )r=   rC   r1   blkr   r   rB   forward   s   


.

zImageEncoderViT.forward)__name__
__module____qualname____doc__r2   	LayerNormGELUintfloatboolr   Moduler   r/   r4   TensorrJ   __classcell__r   r   r@   rB   r      sl    	

_r   c                       s>  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	d
Z
dejfddZdejdejdedejfddZdejdejfddZdejdejfddZedeeejejf  deej deej defddZdejfd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dZ  ZS )PromptEncodera:  
    Encodes different types of prompts for input to SAM's mask decoder, producing sparse and dense embeddings.

    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 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.

    Methods:
        get_dense_pe: Returns the positional encoding used to encode point prompts.
        forward: Embeds different types of prompts, returning both sparse and dense embeddings.

    Examples:
        >>> prompt_encoder = PromptEncoder(256, (64, 64), (1024, 1024), 16)
        >>> points = (torch.rand(1, 5, 2), torch.randint(0, 4, (1, 5)))
        >>> boxes = torch.rand(1, 2, 2)
        >>> masks = torch.rand(1, 1, 256, 256)
        >>> sparse_embeddings, dense_embeddings = prompt_encoder(points, boxes, masks)
        >>> print(sparse_embeddings.shape, dense_embeddings.shape)
        torch.Size([1, 7, 256]) torch.Size([1, 256, 64, 64])
    r   image_embedding_sizeinput_image_sizemask_in_chans
activationr'   Nc                    s   t     | _|| _|| _t d | _d| _ fddt| jD }t	
|| _t	d | _d|d  d|d  f| _t	t	jd|d dddt|d | t	j|d |dddt|| t	j| dd| _t	d | _d	S )
a!  
        Initialize the PromptEncoder module for encoding various types of prompts.

        Args:
            embed_dim (int): The dimension of the embeddings.
            image_embedding_size (Tuple[int, int]): The spatial size of the image embedding as (H, W).
            input_image_size (Tuple[int, int]): The padded size of the input image as (H, W).
            mask_in_chans (int): The number of hidden channels used for encoding input masks.
            activation (Type[nn.Module]): The activation function to use when encoding input masks.

        Examples:
            >>> prompt_encoder = PromptEncoder(256, (64, 64), (1024, 1024), 16)
            >>> points = (torch.rand(1, 5, 2), torch.randint(0, 4, (1, 5)))
            >>> boxes = torch.rand(1, 2, 2)
            >>> masks = torch.rand(1, 1, 256, 256)
            >>> sparse_embeddings, dense_embeddings = prompt_encoder(points, boxes, masks)
            >>> print(sparse_embeddings.shape, dense_embeddings.shape)
            torch.Size([1, 7, 256]) torch.Size([1, 256, 64, 64])
        rD      c                    s   g | ]}t d  qS r   )r2   	Embedding).0_r   r   rB   
<listcomp>       z*PromptEncoder.__init__.<locals>.<listcomp>r   r   )r(   r)   r(   N)r.   r/   r   rY   rX   r   pe_layernum_point_embeddingsr8   r2   r6   point_embeddingsr^   not_a_point_embedmask_input_sizer:   r;   r   mask_downscalingno_mask_embed)r=   r   rX   rY   rZ   r[   rg   r@   ra   rB   r/      s(   

	zPromptEncoder.__init__c                 C   s   |  | jdS )a  
        Return the dense positional encoding used for encoding point prompts.

        Generate a positional encoding for a dense set of points matching the shape of the image
        encoding. The encoding is used to provide spatial information to the model when processing point prompts.

        Returns:
            (torch.Tensor): Positional encoding tensor with shape (1, embed_dim, H, W), where H and W are the
                height and width of the image embedding size, respectively.

        Examples:
            >>> prompt_encoder = PromptEncoder(256, (64, 64), (1024, 1024), 16)
            >>> dense_pe = prompt_encoder.get_dense_pe()
            >>> print(dense_pe.shape)
            torch.Size([1, 256, 64, 64])
        r   )re   rX   	unsqueezer=   r   r   rB   get_dense_pe   s   zPromptEncoder.get_dense_pepointslabelspadc                 C   s  |d }|r4t j|jd ddf|jd}t j|jd df|jd }t j||gdd}t j||gdd}| j|| j}d||dk< ||dk  | j	j
7  < ||dk  | jd j
7  < ||dk  | jd j
7  < ||dk  | jd j
7  < ||d	k  | jd	 j
7  < |S )
zREmbed point prompts by applying positional encoding and label-specific embeddings.      ?r   r   rD   devicer*           r   )r4   r5   shapert   onescatre   forward_with_coordsrY   rh   weightrg   )r=   ro   rp   rq   padding_pointpadding_labelpoint_embeddingr   r   rB   _embed_points  s   zPromptEncoder._embed_pointsboxesc                 C   sv   |d }| ddd}| j|| j}|dddddf  | jd j7  < |dddddf  | jd j7  < |S )zOEmbed box prompts by applying positional encoding and adding corner embeddings.rr   rw   rD   Nr   r   r   )reshapere   r{   rY   rg   r|   )r=   r   coordscorner_embeddingr   r   rB   _embed_boxes  s   &&zPromptEncoder._embed_boxesmasksc                 C   s
   |  |S )zMEmbed mask inputs by downscaling and processing through convolutional layers.)rj   )r=   r   r   r   rB   _embed_masks  s   
zPromptEncoder._embed_masksc                 C   s>   | dur| d j d S |dur|j d S |dur|j d S dS )zKGet the batch size of the output given the batch size of the input prompts.Nr   r   )rx   )ro   r   r   r   r   rB   _get_batch_size  s   

zPromptEncoder._get_batch_sizec                 C   s   | j d jjS )z?Return the device of the first point embedding's weight tensor.r   )rg   r|   rt   rm   r   r   rB   _get_device/  s   zPromptEncoder._get_devicec                 C   s   |  |||}tj|d| jf|  d}|dur/|\}}| j|||du d}tj||gdd}|durA| |}	tj||	gdd}|durN| |}
||
fS | j	j
dddd|d| jd | jd }
||
fS )a>  
        Embed different types of prompts, returning both sparse and dense embeddings.

        Args:
            points (Tuple[torch.Tensor, torch.Tensor] | None): Point coordinates and labels to embed. The first
                tensor contains coordinates with shape (B, N, 2), and the second tensor contains labels with
                shape (B, N).
            boxes (torch.Tensor | None): Boxes to embed with shape (B, M, 2, 2), where M is the number of boxes.
            masks (torch.Tensor | None): Masks to embed with shape (B, 1, H, W).

        Returns:
            (Tuple[torch.Tensor, torch.Tensor]): A tuple containing:
                - sparse_embeddings (torch.Tensor): Sparse embeddings for points and boxes with shape (B, N, embed_dim).
                - dense_embeddings (torch.Tensor): Dense embeddings for masks of shape (B, embed_dim, embed_H, embed_W).

        Examples:
            >>> encoder = PromptEncoder(256, (64, 64), (1024, 1024), 16)
            >>> points = (torch.rand(1, 5, 2), torch.randint(0, 4, (1, 5)))
            >>> boxes = torch.rand(1, 2, 2, 2)
            >>> masks = torch.rand(1, 1, 256, 256)
            >>> sparse_emb, dense_emb = encoder(points, boxes, masks)
            >>> print(sparse_emb.shape, dense_emb.shape)
            torch.Size([1, 7, 256]) torch.Size([1, 256, 64, 64])
        r   rs   N)rq   r   ru   rw   )r   r4   emptyr   r   r   rz   r   r   rk   r|   r   expandrX   )r=   ro   r   r   bssparse_embeddingsr   rp   rg   box_embeddingsdense_embeddingsr   r   rB   rJ   3  s    

zPromptEncoder.forward)rK   rL   rM   rN   r2   rP   rQ   r   r   rT   r/   r4   rU   rn   rS   r   r   r   staticmethodr   r   rt   r   rJ   rV   r   r   r@   rB   rW      sP    #

2 	rW   c                       sR   e Zd ZdZ	d fdd	Z	ddejdejded	eejejf fd
dZ	  Z
S )MemoryEncodera  
    Encode pixel features and masks into a memory representation for efficient image segmentation.

    This class processes pixel-level features and masks, fusing them to generate encoded memory representations
    suitable for downstream tasks in image segmentation models like SAM (Segment Anything Model).

    Attributes:
        mask_downsampler (MaskDownSampler): Module for downsampling input masks.
        pix_feat_proj (nn.Conv2d): Convolutional layer for projecting pixel features.
        fuser (Fuser): Module for fusing pixel features and masks.
        position_encoding (PositionEmbeddingSine): Module for adding positional encoding to features.
        out_proj (nn.Module): Output projection layer, either nn.Identity or nn.Conv2d.

    Methods:
        forward: Process input pixel features and masks to generate encoded memory representations.

    Examples:
        >>> import torch
        >>> encoder = MemoryEncoder(out_dim=256, in_dim=256)
        >>> pix_feat = torch.randn(1, 256, 64, 64)
        >>> masks = torch.randn(1, 1, 64, 64)
        >>> encoded_feat, pos = encoder(pix_feat, masks)
        >>> print(encoded_feat.shape, pos.shape)
        torch.Size([1, 256, 64, 64]) torch.Size([1, 128, 64, 64])
    r   c                    sx   t    tdddd| _tj||dd| _ttdddd| _	t
d	d
| _t | _||kr:tj||dd| _dS dS )ah  
        Initialize the MemoryEncoder for encoding pixel features and masks into memory representations.

        This encoder processes pixel-level features and masks, fusing them to generate encoded memory representations
        suitable for downstream tasks in image segmentation models like SAM (Segment Anything Model).

        Args:
            out_dim (int): Output dimension of the encoded features.
            in_dim (int): Input dimension of the pixel features. Default is 256.

        Examples:
            >>> encoder = MemoryEncoder(out_dim=256, in_dim=256)
            >>> pix_feat = torch.randn(1, 256, 64, 64)
            >>> masks = torch.randn(1, 1, 64, 64)
            >>> encoded_feat, pos = encoder(pix_feat, masks)
            >>> print(encoded_feat.shape, pos.shape)
            torch.Size([1, 256, 64, 64]) torch.Size([1, 128, 64, 64])
        r   rD   r   )r(   r)   r-   rd   r   ru   )
num_layers@   num_pos_featsN)r.   r/   r   mask_downsamplerr2   r;   pix_feat_projr
   r	   fuserr   position_encodingIdentityout_proj)r=   out_dimin_dimr@   r   rB   r/     s   

zMemoryEncoder.__init__Fpix_featr   skip_mask_sigmoidr'   c                 C   sh   |st |}| |}||j}| |}|| }| |}| |}| ||j	}||gdS )z]Process pixel features and masks to generate encoded memory representations for segmentation.)vision_featuresvision_pos_enc)
rF   sigmoidr   tort   r   r   r   r   dtype)r=   r   r   r   rC   posr   r   rB   rJ     s   




zMemoryEncoder.forward)r   )F)rK   rL   rM   rN   r/   r4   rU   rS   r   rJ   rV   r   r   r@   rB   r   e  s    &r   c                       sF   e Zd ZdZ	ddejdejdef fddZdej	fd	d
Z
  ZS )ImageEncodera  
    Encode images using a trunk-neck architecture, producing multiscale features and positional encodings.

    This class combines a trunk network for feature extraction with a neck network for feature refinement
    and positional encoding generation. It can optionally discard the lowest resolution features.

    Attributes:
        trunk (nn.Module): The trunk network for initial feature extraction.
        neck (nn.Module): The neck network for feature refinement and positional encoding generation.
        scalp (int): Number of lowest resolution feature levels to discard.

    Methods:
        forward: Process the input image through the trunk and neck networks.

    Examples:
        >>> trunk = SomeTrunkNetwork()
        >>> neck = SomeNeckNetwork()
        >>> encoder = ImageEncoder(trunk, neck, scalp=1)
        >>> image = torch.randn(1, 3, 224, 224)
        >>> output = encoder(image)
        >>> print(output.keys())
        dict_keys(['vision_features', 'vision_pos_enc', 'backbone_fpn'])
    r   trunkr<   scalpc                    sN   t    || _|| _|| _| jj| jjks%J d| jj d| jj ddS )a  
        Initialize the ImageEncoder with trunk and neck networks for feature extraction and refinement.

        This encoder combines a trunk network for feature extraction with a neck network for feature refinement
        and positional encoding generation. It can optionally discard the lowest resolution features.

        Args:
            trunk (nn.Module): The trunk network for initial feature extraction.
            neck (nn.Module): The neck network for feature refinement and positional encoding generation.
            scalp (int): Number of lowest resolution feature levels to discard.

        Examples:
            >>> trunk = SomeTrunkNetwork()
            >>> neck = SomeNeckNetwork()
            >>> encoder = ImageEncoder(trunk, neck, scalp=1)
            >>> image = torch.randn(1, 3, 224, 224)
            >>> output = encoder(image)
            >>> print(output.keys())
            dict_keys(['vision_features', 'vision_pos_enc', 'backbone_fpn'])
        zChannel dims of trunk z
 and neck z do not match.N)r.   r/   r   r<   r   channel_listbackbone_channel_list)r=   r   r<   r   r@   r   rB   r/     s   
zImageEncoder.__init__samplec                 C   sT   |  | |\}}| jdkr |d| j  |d| j  }}|d }|||dS )z`Encode input through patch embedding, positional embedding, transformer blocks, and neck module.r   Nrw   )r   r   backbone_fpn)r<   r   r   )r=   r   featuresr   srcr   r   rB   rJ     s   
"zImageEncoder.forward)r   )rK   rL   rM   rN   r2   rT   rQ   r/   r4   rU   rJ   rV   r   r   r@   rB   r     s    "r   c                       sp   e Zd ZdZ						ddedee d	ed
ededededeee  f fddZdee	j
 fddZ  ZS )FpnNecka  
    A Feature Pyramid Network (FPN) neck variant for multiscale feature fusion in object detection models.

    This FPN variant removes the output convolution and uses bicubic interpolation for feature resizing,
    similar to ViT positional embedding interpolation.

    Attributes:
        position_encoding (PositionEmbeddingSine): Sinusoidal positional encoding module.
        convs (nn.ModuleList): List of convolutional layers for each backbone level.
        backbone_channel_list (List[int]): List of channel dimensions from the backbone.
        fpn_interp_model (str): Interpolation mode for FPN feature resizing.
        fuse_type (str): Type of feature fusion, either 'sum' or 'avg'.
        fpn_top_down_levels (List[int]): Levels to have top-down features in outputs.

    Methods:
        forward: Perform forward pass through the FPN neck.

    Examples:
        >>> backbone_channels = [64, 128, 256, 512]
        >>> fpn_neck = FpnNeck(256, backbone_channels)
        >>> inputs = [torch.rand(1, c, 32, 32) for c in backbone_channels]
        >>> outputs, positions = fpn_neck(inputs)
        >>> print(len(outputs), len(positions))
        4 4
    r   r   bilinearsumNd_modelr   r(   r)   r-   fpn_interp_model	fuse_typefpn_top_down_levelsc	                    s   t    tdd| _t | _|| _|D ]}	t }
|
	dtj
|	||||d | j|
 q|| _|dv s9J || _|du rGtt| j}t|| _dS )a  
        Initializes a modified Feature Pyramid Network (FPN) neck.

        This FPN variant removes the output convolution and uses bicubic interpolation for feature resizing,
        similar to ViT positional embedding interpolation.

        Args:
            d_model (int): Dimension of the model.
            backbone_channel_list (List[int]): List of channel dimensions from the backbone.
            kernel_size (int): Kernel size for the convolutional layers.
            stride (int): Stride for the convolutional layers.
            padding (int): Padding for the convolutional layers.
            fpn_interp_model (str): Interpolation mode for FPN feature resizing.
            fuse_type (str): Type of feature fusion, either 'sum' or 'avg'.
            fpn_top_down_levels (Optional[List[int]]): Levels to have top-down features in outputs.

        Examples:
            >>> backbone_channels = [64, 128, 256, 512]
            >>> fpn_neck = FpnNeck(256, backbone_channels)
            >>> print(fpn_neck)
        r   r   conv)in_channelsout_channelsr(   r)   r-   >   avgr   N)r.   r/   r   r   r2   r6   convsr   r:   
add_moduler;   r9   r   r   r8   lenlistr   )r=   r   r   r(   r)   r-   r   r   r   r*   currentr@   r   rB   r/     s.   
 
zFpnNeck.__init__xsc                 C   s   dgt | j }dgt | j }t |t | jksJ d}t | jd }t|ddD ]P}|| }| j||  |}|| jv rg|durgtj|jtjdd| j	| j	dkrTdnddd}	||	 }| j
d	krf|d
 }n|}|}
|
||< | |
|
j||< q*||fS )aZ  
        Performs forward pass through the Feature Pyramid Network (FPN) neck.

        This method processes a list of input tensors from the backbone through the FPN, applying lateral connections
        and top-down feature fusion. It generates output feature maps and corresponding positional encodings.

        Args:
            xs (List[torch.Tensor]): List of input tensors from the backbone, each with shape (B, C, H, W).

        Returns:
            (Tuple[List[torch.Tensor], List[torch.Tensor]]): A tuple containing:
                - out (List[torch.Tensor]): List of output feature maps after FPN processing, each with shape
                  (B, d_model, H, W).
                - pos (List[torch.Tensor]): List of positional encodings corresponding to each output feature map.

        Examples:
            >>> fpn_neck = FpnNeck(d_model=256, backbone_channel_list=[64, 128, 256, 512])
            >>> inputs = [torch.rand(1, c, 32, 32) for c in [64, 128, 256, 512]]
            >>> outputs, positions = fpn_neck(inputs)
            >>> print(len(outputs), len(positions))
            4 4
        Nr   rw   )r          @nearestF)rE   modealign_corners	antialiasr   rD   )r   r   r8   r   rF   rG   r   r4   float32r   r   r   r   )r=   r   outr   prev_featuresnr>   rC   lateral_featurestop_down_featuresx_outr   r   rB   rJ   ^  s2   
zFpnNeck.forward)r   r   r   r   r   N)rK   rL   rM   rN   rQ   r   strr   r/   r4   rU   rJ   rV   r   r   r@   rB   r     s4    
	?r   c                       s   e Zd ZdZ											
		d"dededededeeef deedf dededeeef deedf deedf f fddZdeeef dej	fddZ
dej	deej	 fd d!Z  ZS )#Hieraa  
    Hierarchical vision transformer for efficient multiscale feature extraction in image processing tasks.

    This class implements a Hiera model, which is a hierarchical vision transformer architecture designed for
    efficient multiscale feature extraction. It uses a series of transformer blocks organized into stages,
    with optional pooling and global attention mechanisms.

    Attributes:
        window_spec (Tuple[int, ...]): Window sizes for each stage.
        q_stride (Tuple[int, int]): Downsampling stride between stages.
        stage_ends (List[int]): Indices of the last block in each stage.
        q_pool_blocks (List[int]): Indices of blocks where pooling is applied.
        return_interm_layers (bool): Whether to return intermediate layer outputs.
        patch_embed (PatchEmbed): Module for patch embedding.
        global_att_blocks (Tuple[int, ...]): Indices of blocks with global attention.
        window_pos_embed_bkg_spatial_size (Tuple[int, int]): Spatial size for window positional embedding background.
        pos_embed (nn.Parameter): Positional embedding for the background.
        pos_embed_window (nn.Parameter): Positional embedding for the window.
        blocks (nn.ModuleList): List of MultiScaleBlock modules.
        channel_list (List[int]): List of output channel dimensions for each stage.

    Methods:
        _get_pos_embed: Generate positional embeddings by interpolating and combining window and background embeddings.
        forward: Perform the forward pass through the Hiera model.

    Examples:
        >>> model = Hiera(embed_dim=96, num_heads=1, stages=(2, 3, 16, 3))
        >>> input_tensor = torch.randn(1, 3, 224, 224)
        >>> output_features = model(input_tensor)
        >>> for feat in output_features:
        ...     print(feat.shape)
    `   r   rv   r   rD   rD   rD   r   r   r   r      r      r\   r      r   r      Tr   r   drop_path_rateq_poolq_stridestages.dim_mulhead_mul!window_pos_embed_bkg_spatial_sizewindow_specglobal_att_blocksc              	      s
  t    tt|
ksJ |
 _t}| _fddtdtd D  _d|  kr<t jdd ks?J  J dd  jdd D d|  _| _	t
|dd	d
d _| _|	 _ttjd|g jR   _ttd| jd  jd  _dd td||D }d}t  _t|D ]L}|} j|d  } jdur| jv rdn|}|d  jv rt|| }t|| }|d7 }t||||| | jv rو jnd|d}|} j| q|r fdd jddd D  _dS  jd jg _dS )a  
        Initialize a Hiera model, a hierarchical vision transformer for efficient multiscale feature extraction.

        Hiera is a hierarchical vision transformer architecture designed for efficient multiscale feature extraction
        in image processing tasks. It uses a series of transformer blocks organized into stages, with optional
        pooling and global attention mechanisms.

        Args:
            embed_dim (int): Initial embedding dimension for the model.
            num_heads (int): Initial number of attention heads.
            drop_path_rate (float): Stochastic depth rate.
            q_pool (int): Number of query pooling stages.
            q_stride (Tuple[int, int]): Downsampling stride between stages.
            stages (Tuple[int, ...]): Number of blocks per stage.
            dim_mul (float): Dimension multiplier factor at stage transitions.
            head_mul (float): Head multiplier factor at stage transitions.
            window_pos_embed_bkg_spatial_size (Tuple[int, int]): Spatial size for window positional embedding background.
            window_spec (Tuple[int, ...]): Window sizes for each stage when not using global attention.
            global_att_blocks (Tuple[int, ...]): Indices of blocks that use global attention.
            return_interm_layers (bool): Whether to return intermediate layer outputs.

        Examples:
            >>> model = Hiera(embed_dim=96, num_heads=1, stages=(2, 3, 16, 3))
            >>> input_tensor = torch.randn(1, 3, 224, 224)
            >>> output_features = model(input_tensor)
            >>> for feat in output_features:
            ...     print(feat.shape)
        c                    s    g | ]}t  d | d qS )Nr   )r   r_   r>   )r   r   rB   rb     s     z"Hiera.__init__.<locals>.<listcomp>r   r   Nrw   c                 S   s   g | ]}|d  qS r]   r   r_   rC   r   r   rB   rb         )r   r   )r\   r\   )r   r   )r   r(   r)   r-   c                 S   s   g | ]}|  qS r   )itemr   r   r   rB   rb     r   )r*   dim_outr   	drop_pathr   r%   c                    s   g | ]} j | jqS r   )r7   r   r   rm   r   rB   rb   '  rc   )r.   r/   r   r   r   r   r8   
stage_endsq_pool_blocksreturn_interm_layersr   r0   r   r   r2   r3   r4   r5   r1   pos_embed_windowlinspacer6   r7   rQ   r   r9   r   r   )r=   r   r   r   r   r   r   r   r   r   r   r   r   r   dpr	cur_stager>   r   r%   r?   r@   )r=   r   rB   r/     s\   
6"*"$

	zHiera.__init__hwr'   c                 C   sZ   |\}}| j }tj| j||fdd}||dd t|j|jD  }|dddd}|S )	z_Generate positional embeddings by interpolating and combining window and background embeddings.bicubic)sizer   c                 S   s   g | ]\}}|| qS r   r   )r_   rC   yr   r   rB   rb   1  rc   z(Hiera._get_pos_embed.<locals>.<listcomp>r   rD   r   r   )r   rF   rG   r1   tileziprx   rH   )r=   r   hwwindow_embedr1   r   r   rB   _get_pos_embed,  s   "zHiera._get_pos_embedrC   c                 C   s~   |  |}|| |jdd  }g }t| jD ]$\}}||}|| jd ks/|| jv r<| jr<|dddd}|| q|S )a  
        Perform forward pass through Hiera model, extracting multiscale features from input images.

        Args:
            x (torch.Tensor): Input tensor with shape (B, C, H, W) representing a batch of images.

        Returns:
            (List[torch.Tensor]): List of feature maps at different scales, each with shape (B, C_i, H_i, W_i), where
                C_i is the channel dimension and H_i, W_i are the spatial dimensions at scale i. The list is ordered
                from highest resolution (fine features) to lowest resolution (coarse features) if return_interm_layers
                is True, otherwise contains only the final output.

        Examples:
            >>> model = Hiera(embed_dim=96, num_heads=1, stages=(2, 3, 16, 3))
            >>> input_tensor = torch.randn(1, 3, 224, 224)
            >>> output_features = model(input_tensor)
            >>> for feat in output_features:
            ...     print(feat.shape)
        r   r   rw   r   rD   )	r0   r   rx   	enumerater7   r   r   rH   r9   )r=   rC   outputsr>   rI   featsr   r   rB   rJ   5  s   

zHiera.forward)r   r   rv   r   r   r   r   r   r   r   r   T)rK   rL   rM   rN   rQ   rR   r   r/   r4   rU   r   r   rJ   rV   r   r   r@   rB   r     sN    #

	



v"	r   )typingr   r   r   r   r4   torch.nnr2   torch.nn.functional
functionalrF   ultralytics.nn.modulesr   r7   r   r	   r
   r   r   r   r   r   rT   r   rW   r   r   r   r   r   r   r   rB   <module>   s   (  HUJ 