a
    yf                     @   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eeeeeeeee	e
ej e
ej e	e	e	eeedf dd fddZejejd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    .N)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returnc                    s   t    || _t||f||f||d| _d| _|rTtt	d|| || || _t
 | _t|D ]D}t||||	|
|||||vr|nd|| || fd
}| j| qfttj||dddt|tj||dddd	t|| _dS )
a  
        Initializes 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.

        Attributes:
            img_size (int): Dimension of input images.
            patch_embed (PatchEmbed): Module for patch embedding.
            pos_embed (nn.Parameter | None): Absolute positional embedding for patches.
            blocks (nn.ModuleList): List of transformer blocks.
            neck (nn.Sequential): Neck module for final processing.

        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%   Z
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   c/var/www/html/django/DPS/env/lib/python3.9/site-packages/ultralytics/models/sam/modules/encoders.pyr.   0   sV    5
 
zImageEncoderViT.__init__xr'   c                 C   s   |  |}| jdurZ| jdkrLtj| jdddd| jd dddddn| j}|| }| jD ]}||}q`| |ddddS )zcProcesses input through patch embedding, positional embedding, transformer blocks, and neck module.Nr   r   r   r      )scale_factor)r/   r0   r   Finterpolatepermuter6   r;   )r<   rC   r0   blkr   r   rA   forward   s    

0

zImageEncoderViT.forward)__name__
__module____qualname____doc__r1   Z	LayerNormGELUintfloatboolr   Moduler   r.   r3   TensorrJ   __classcell__r   r   r?   rA   r      sJ   
fr   c                       s  e Zd ZdZejfeeeef eeef eeej	 dd fddZ
ejdddZejejeejd	d
dZejejdddZejejdddZeeeejejf  eej eej edddZejdddZeeejejf  eej eej eejejf d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])
    N)r   image_embedding_sizeinput_image_sizemask_in_chans
activationr'   c                    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  
        Initializes the PromptEncoder module for encoding various types of prompts.

        This module encodes different types of prompts (points, boxes, masks) for input to SAM's mask decoder,
        producing both sparse and dense embeddings.

        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.

        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.

        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   )r1   	Embedding).0_r   r   rA   
<listcomp>       z*PromptEncoder.__init__.<locals>.<listcomp>r   r   )r(   r)   r(   N)r-   r.   r   rX   rW   r   pe_layerZnum_point_embeddingsr7   r1   r5   point_embeddingsr]   not_a_point_embedZmask_input_sizer9   r:   r   mask_downscalingno_mask_embed)r<   r   rW   rX   rY   rZ   re   r?   r`   rA   r.      s(    )

	zPromptEncoder.__init__)r'   c                 C   s   |  | jdS )a  
        Returns the dense positional encoding used for encoding point prompts.

        This method generates 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   )rd   rW   Z	unsqueezer<   r   r   rA   get_dense_pe  s    zPromptEncoder.get_dense_pe)pointslabelspadr'   c                 C   s  |d }|rht 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 )
zSEmbeds point prompts by applying positional encoding and label-specific embeddings.      ?r   r   rD   devicer*           r   )r3   r4   shaperp   Zonescatrd   forward_with_coordsrX   rf   weightre   )r<   rk   rl   rm   Zpadding_pointZpadding_labelZpoint_embeddingr   r   rA   _embed_points  s    zPromptEncoder._embed_points)boxesr'   c                 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 )zPEmbeds box prompts by applying positional encoding and adding corner embeddings.rn   rs   rD   Nr   r   r   )reshaperd   rv   rX   re   rw   )r<   ry   coordsZcorner_embeddingr   r   rA   _embed_boxes'  s    &&zPromptEncoder._embed_boxes)masksr'   c                 C   s
   |  |S )zNEmbeds mask inputs by downscaling and processing through convolutional layers.)rg   )r<   r}   r   r   rA   _embed_masks0  s    zPromptEncoder._embed_masks)rk   ry   r}   r'   c                 C   sB   | dur| d j d S |dur(|j d S |dur:|j d S dS dS )zLGets the batch size of the output given the batch size of the input prompts.Nr   r   )rt   )rk   ry   r}   r   r   rA   _get_batch_size4  s    

zPromptEncoder._get_batch_sizec                 C   s   | j d jjS )z@Returns the device of the first point embedding's weight tensor.r   )re   rw   rp   ri   r   r   rA   _get_deviceD  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r| |}	tj||	gdd}|dur| |}
n,| 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. 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   ro   N)rm   r   rq   rs   )r   r3   emptyr   r   rx   ru   r|   r~   rh   rw   rz   expandrW   )r<   rk   ry   r}   bsZsparse_embeddingsr{   rl   re   Zbox_embeddingsZdense_embeddingsr   r   rA   rJ   H  s    
zPromptEncoder.forward)rK   rL   rM   rN   r1   rO   rP   r   r   rS   r.   r3   rT   rj   rR   rx   r|   r~   staticmethodr   r   rp   r   rJ   rU   r   r   r?   rA   rV      s4   #

@	rV   c                       sH   e Zd ZdZd	 fdd	Zd
ejejeeejejf dddZ	  Z
S )MemoryEncodera  
    Encodes 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: Processes 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                    st   t    tdddd| _tj||dd| _ttdddd| _	t
d	d
| _t | _||krptj||dd| _dS )z`Initializes the MemoryEncoder for encoding pixel features and masks into memory representations.r   rD   r   )r(   r)   r,   rc   r   rq   )Z
num_layers@   Znum_pos_featsN)r-   r.   r   mask_downsamplerr1   r:   pix_feat_projr
   r	   fuserr   position_encodingZIdentityout_proj)r<   Zout_dimZin_dimr?   r   rA   r.     s    

zMemoryEncoder.__init__F)pix_featr}   skip_mask_sigmoidr'   c                 C   sh   |st |}| |}||j}| |}|| }| |}| |}| ||j	}||gdS )z_Processes pixel features and masks to generate encoded memory representations for segmentation.)vision_featuresvision_pos_enc)
rF   Zsigmoidr   torp   r   r   r   r   dtype)r<   r   r}   r   rC   posr   r   rA   rJ     s    




zMemoryEncoder.forward)r   )F)rK   rL   rM   rN   r.   r3   rT   rR   r   rJ   rU   r   r   r?   rA   r   z  s     r   c                       s@   e Zd ZdZd	ejejed fddZej	dddZ
  ZS )
ImageEncodera  
    Encodes 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: Processes 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sJJ d| jj d| jj ddS )z`Initializes the ImageEncoder with trunk and neck networks for feature extraction and refinement.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   rA   r.     s    
zImageEncoder.__init__)samplec                 C   sT   |  | |\}}| jdkr@|d| j  |d| j   }}|d }|||dS )zaEncodes input through patch embedding, positional embedding, transformer blocks, and neck module.r   Nrs   )r   r   Zbackbone_fpn)r;   r   r   )r<   r   featuresr   srcr   r   rA   rJ     s    
"zImageEncoder.forward)r   )rK   rL   rM   rN   r1   rS   rP   r.   r3   rT   rJ   rU   r   r   r?   rA   r     s    r   c                       sV   e Zd ZdZdeee eeeeeeee  d fdd	Zee	j
 d
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: Performs 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 ]4}	t }
|
	dtj
|	||||d | j|
 q*|| _|dv srJ || _|du rt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)Zin_channelsZout_channelsr(   r)   r,   >   r   avgN)r-   r.   r   r   r1   r5   convsr   r9   Z
add_moduler:   r8   r   r   r7   lenlistr   )r<   r   r   r(   r)   r,   r   r   r   r*   currentr?   r   rA   r.     s.     

zFpnNeck.__init__)xsc                 C   s   dgt | j }dgt | j }t |t | jks6J d}t | jd }t|ddD ]}|| }| j||  |}|| jv r|durtj|jtjdd| j	| j	dkrdnddd}	||	 }| j
d	kr|d
 }n|}|}
|
||< | |
|
j||< qT||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   rs   )r          @ZnearestF)rE   modeZalign_cornersZ	antialiasr   rD   )r   r   r7   r   rF   rG   r   r3   Zfloat32r   r   r   r   )r<   r   outr   Zprev_featuresnr=   rC   Zlateral_featuresZtop_down_featuresZx_outr   r   rA   rJ   O  s0    

zFpnNeck.forward)r   r   r   r   r   N)rK   rL   rM   rN   rP   r   strr   r.   r3   rT   rJ   rU   r   r   r?   rA   r     s$         
?r   c                       s   e Zd ZdZdeeeeeeef eedf eeeeef eedf eedf d fddZeeef ej	dddZ
ej	eej	 d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: Generates positional embeddings by interpolating and combining window and background embeddings.
        forward: Performs 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   rr   r   rD   rD   rD   r   r   r   r      r      r[   r      r   r      T.)r   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rvt jdd ks|n 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 ]}|} j|d  } jdurh| jv rddn|}|d  jv rt|| }t|| }|d7 }t||||| | jv r jnd|d}|} j| q2|r fdd jddd D n jd jg _dS )zZInitializes the Hiera model, configuring its hierarchical vision transformer architecture.c                    s    g | ]}t  d | d qS )Nr   )r   r^   r=   )r   r   rA   ra     rb   z"Hiera.__init__.<locals>.<listcomp>r   r   Nrs   c                 S   s   g | ]}|d  qS r\   r   r^   rC   r   r   rA   ra     rb   )r   r   )r[   r[   )r   r   )r   r(   r)   r,   c                 S   s   g | ]}|  qS r   )itemr   r   r   rA   ra     rb   )r*   dim_outr   Z	drop_pathr   r%   c                    s   g | ]} j | jqS r   )r6   r   r   ri   r   rA   ra     rb   )r-   r.   r   r   r   r   r7   
stage_endsZq_pool_blocksreturn_interm_layersr   r/   r   r   r1   r2   r3   r4   r0   pos_embed_windowZlinspacer5   r6   rP   r   r8   r   r   )r<   r   r   r   r   r   r   r   r   r   r   r   r   r   ZdprZ	cur_stager=   r   r%   r>   r?   )r<   r   rA   r.     sZ    
"("$
	"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`Generates positional embeddings by interpolating and combining window and background embeddings.Zbicubic)sizer   c                 S   s   g | ]\}}|| qS r   r   )r^   rC   yr   r   rA   ra     rb   z(Hiera._get_pos_embed.<locals>.<listcomp>r   rD   r   r   )r   rF   rG   r0   Ztileziprt   rH   )r<   r   hwZwindow_embedr0   r   r   rA   _get_pos_embed  s    "zHiera._get_pos_embedrB   c                 C   s~   |  |}|| |jdd  }g }t| jD ]H\}}||}|| jd ks^|| jv r0| jr0|dddd}|| q0|S )z\Performs forward pass through Hiera model, extracting multiscale features from input images.r   r   rs   r   rD   )	r/   r   rt   	enumerater6   r   r   rH   r8   )r<   rC   outputsr=   rI   Zfeatsr   r   rA   rJ     s    
zHiera.forward)r   r   rr   r   r   r   r   r   r   r   r   T)rK   rL   rM   rN   rP   rQ   r   r.   r3   rT   r   r   rJ   rU   r   r   r?   rA   r     s8   #            




[	r   )typingr   r   r   r   r3   Ztorch.nnr1   Ztorch.nn.functionalZ
functionalrF   Zultralytics.nn.modulesr   r6   r   r	   r
   r   r   r   r   r   rS   r   rV   r   r   r   r   r   r   r   rA   <module>   s   (  VD7 