
    ^j                        d Z ddlZddlmZmZmZmZmZmZm	Z	m
Z
 ddlZddlmZ ddlmc mZ ddlmZmZ ddlmZmZmZmZmZmZ ddlmZ ddlmZ dd	lm Z  dd
l!m"Z"m#Z# dgZ$ G d dejJ                        Z& G d dejJ                        Z' G d dejJ                        Z( G d dejJ                        Z) G d dejJ                        Z* G d dejJ                        Z+de,dedejJ                  fdZ-dYdee.df   de/de.dee.e.e.e.f   fd Z0 G d! d"ejJ                        Z1 G d# d$ejJ                        Z2	 	 	 	 	 	 	 	 	 	 dZd%ed&e.d'e.d(ee.   d)e.d*e.d+e.d,e.d-e/d.e3d/e/d0e/dedejh                  fd1Z5	 	 	 	 d[d%ed&e.d'e.d(ee.   d)e.d-e/d.e3d/e/d0e/dedejh                  fd2Z6 G d3 dejJ                        Z7d\d4e,d5e3dede7fd6Z8d]d7e,dedee,ef   fd8Z9 e# e9d9d:d;<       e9d9d=d>d?@       e9d9dAd;<       e9d9dBd>d?@       e9d9dCd;<       e9d9dDd>dE@       e9d9dFd;<       e9d9dGdHdE@       e9d9dId;<       e9d9dJdHdE@       e9d9dKdHdL@      dM      Z:e"d\d5e3dede7fdN       Z;e"d\d5e3dede7fdO       Z<e"d\d5e3dede7fdP       Z=e"d\d5e3dede7fdQ       Z>e"d\d5e3dede7fdR       Z?e"d\d5e3dede7fdS       Z@e"d\d5e3dede7fdT       ZAe"d\d5e3dede7fdU       ZBe"d\d5e3dede7fdV       ZCe"d\d5e3dede7fdW       ZDe"d\d5e3dede7fdX       ZEy)^a5   Vision OutLOoker (VOLO) implementation

Paper: `VOLO: Vision Outlooker for Visual Recognition` - https://arxiv.org/abs/2106.13112

Code adapted from official impl at https://github.com/sail-sg/volo, original copyright in comment below

Modifications and additions for timm by / Copyright 2022, Ross Wightman
    N)AnyCallableDictListOptionalTupleUnionTypeIMAGENET_DEFAULT_MEANIMAGENET_DEFAULT_STD)DropPathMlp	to_2tuple	to_ntupletrunc_normal_use_fused_attn   )build_model_with_cfg)feature_take_indices)
checkpoint)register_modelgenerate_default_cfgsVOLOc                        e Zd ZdZ	 	 	 	 	 	 	 	 ddededededededed	ef fd
Zdej                  dej                  fdZ
 xZS )OutlookAttentionz,Outlook attention mechanism for VOLO models.dim	num_headskernel_sizepaddingstrideqkv_bias	attn_drop	proj_dropc                    |	|
d}t         |           ||z  }|| _        || _        || _        || _        |dz  | _        t        j                  ||fd|i|| _	        t        j                  ||dz  |z  fi || _
        t        j                  |      | _        t        j                  ||fi || _        t        j                  |      | _        t        j                  |||      | _        t        j"                  ||d      | _        y)	a  Initialize OutlookAttention.

        Args:
            dim: Input feature dimension.
            num_heads: Number of attention heads.
            kernel_size: Kernel size for attention computation.
            padding: Padding for attention computation.
            stride: Stride for attention computation.
            qkv_bias: Whether to use bias in linear layers.
            attn_drop: Attention dropout rate.
            proj_drop: Projection dropout rate.
        devicedtype      bias   )r   r    r!   T)r   r!   	ceil_modeN)super__init__r   r   r    r!   scalennLinearvattnDropoutr#   projr$   Unfoldunfold	AvgPool2dpool)selfr   r   r   r    r!   r"   r#   r$   r'   r(   ddhead_dim	__class__s                [/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/timm/models/volo.pyr.   zOutlookAttention.__init__*   s    2 /)#"&%
39(9b9IIc;!#3i#?F2F	I.IIc3-"-	I.iiKQWXLLVFdS	    xreturnc                    |j                   \  }}}}| j                  |      j                  dddd      }t        j                  || j
                  z        t        j                  || j
                  z        }}| j                  |      j                  || j                  || j                  z  | j                  | j                  z  ||z        j                  ddddd      }| j                  |j                  dddd            j                  dddd      }	| j                  |	      j                  |||z  | j                  | j                  | j                  z  | j                  | j                  z        j                  ddddd      }	|	| j                  z  }	|	j                  d      }	| j                  |	      }	|	|z  j                  ddddd      j                  ||| j                  z  | j                  z  ||z        }t        j                   |||f| j                  | j"                  | j
                        }| j%                  |j                  dddd            }| j'                  |      }|S )	Forward pass.

        Args:
            x: Input tensor of shape (B, H, W, C).

        Returns:
            Output tensor of shape (B, H, W, C).
        r      r      r+   r   )output_sizer   r    r!   )shaper2   permutemathceilr!   r7   reshaper   r   r9   r3   r/   softmaxr#   Ffoldr    r5   r$   )
r:   r@   BHWCr2   hwr3   s
             r>   forwardzOutlookAttention.forwardV   s!    WW
1aFF1IaAq)yyT[[)499Q_+E1KKN""t~~qDNN2t///Q88?1aA8N 	
 yy1aA./771aCyy&&q1udnnd&6&69I9I&It///118Aq!Q1G 	 djj |||#~~d#AXq!Q1-55aT=M=M9MPTP`P`9`bcfgbghFF11a&d6F6FPTP\P\eiepepqIIaii1a+,NN1r?   )rD   r   r   F        rX   NN)__name__
__module____qualname____doc__intboolfloatr.   torchTensorrW   __classcell__r=   s   @r>   r   r   '   s    6  !"!!*T*T *T 	*T
 *T *T *T *T *TX   %,,  r?   r   c                        e Zd ZdZdddddej
                  ej                  dddf
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f fdZdej                  dej                  fdZ xZS )	Outlookerz9Outlooker block that combines outlook attention with MLP.r         @rX   FNr   r   r    r!   r   	mlp_ratior#   	drop_path	act_layer
norm_layerr"   c           	         ||d}t         |            |
|fi || _        t        ||f|||||d|| _        |dkD  rt        |      nt        j                         | _         |
|fi || _	        t        d|t        ||z        |	d|| _        |dkD  rt        |      | _        yt        j                         | _        y)af  Initialize Outlooker block.

        Args:
            dim: Input feature dimension.
            kernel_size: Kernel size for outlook attention.
            padding: Padding for outlook attention.
            stride: Stride for outlook attention.
            num_heads: Number of attention heads.
            mlp_ratio: Ratio for MLP hidden dimension.
            attn_drop: Attention dropout rate.
            drop_path: Stochastic depth drop rate.
            act_layer: Activation layer type.
            norm_layer: Normalization layer type.
            qkv_bias: Whether to use bias in linear layers.
        r&   )r   r    r!   r"   r#   rX   in_featureshidden_featuresri   N )r-   r.   norm1r   r3   r   r0   Identity
drop_path1norm2r   r]   mlp
drop_path2)r:   r   r   r    r!   r   rg   r#   rh   ri   rj   r"   r'   r(   r;   r=   s                  r>   r.   zOutlooker.__init__|   s    > /*r*
$	
 $	
 	
	 2;R(9-R[[]*r*
 
i0
 	
 2;R(9-R[[]r?   r@   rA   c                     || j                  | j                  | j                  |                  z   }|| j                  | j	                  | j                  |                  z   }|S zoForward pass.

        Args:
            x: Input tensor.

        Returns:
            Output tensor.
        rr   r3   rp   ru   rt   rs   r:   r@   s     r>   rW   zOutlooker.forward   Q     		$**Q- 899A 788r?   )rY   rZ   r[   r\   r0   GELU	LayerNormr]   r_   r
   Moduler^   r.   r`   ra   rW   rb   rc   s   @r>   re   re   y   s    C !!!)+*,,,"5S5S 5S 	5S
 5S 5S 5S 5S 5S BII5S RYY5S 5Sn %,, r?   re   c                        e Zd ZU dZej
                  j                  e   ed<   	 	 	 	 	 	 dde	de	dede
de
f
 fdZd	ej                  d
ej                  fdZ xZS )	Attentionz!Multi-head self-attention module.
fused_attnr   r   r"   r#   r$   c                 X   ||d}t         
|           || _        ||z  }	|	dz  | _        t	               | _        t        j                  ||dz  fd|i|| _        t        j                  |      | _
        t        j                  ||fi || _        t        j                  |      | _        y)a,  Initialize Attention module.

        Args:
            dim: Input feature dimension.
            num_heads: Number of attention heads.
            qkv_bias: Whether to use bias in QKV projection.
            attn_drop: Attention dropout rate.
            proj_drop: Projection dropout rate.
        r&   r)   rD   r*   N)r-   r.   r   r/   r   r   r0   r1   qkvr4   r#   r5   r$   )r:   r   r   r"   r#   r$   r'   r(   r;   r<   r=   s             r>   r.   zAttention.__init__   s    & /")#%
(*99S#'??B?I.IIc3-"-	I.r?   r@   rA   c                    |j                   \  }}}}| j                  |      j                  |||z  d| j                  || j                  z        j	                  ddddd      }|j                  d      \  }}}	| j                  r<t        j                  |||	| j                  r| j                  j                  nd      }nL|| j                  z  }||j                  dd	      z  }
|
j                  d	
      }
| j                  |
      }
|
|	z  }|j                  dd      j                  ||||      }| j                  |      }| j!                  |      }|S )rC   rD   rE   r   r   r+   rX   )	dropout_prF   rG   )rI   r   rM   r   rJ   unbindr   rO   scaled_dot_product_attentiontrainingr#   pr/   	transposerN   r5   r$   )r:   r@   rQ   rR   rS   rT   r   qkr2   r3   s              r>   rW   zAttention.forward   s0    WW
1ahhqk!!!QUAt~~qDNN?RS[[\]_`bcefhij**Q-1a??..1a.2mm$..**A
 DJJAq{{2r**D<<B<'D>>$'DqAKK1%%aAq1IIaLNN1r?   )   FrX   rX   NN)rY   rZ   r[   r\   r`   jitFinalr^   __annotations__r]   r_   r.   ra   rW   rb   rc   s   @r>   r   r      s}    +		%%
 "!!// / 	/
 / /> %,, r?   r   c                        e Zd ZdZddddej
                  ej                  ddfdededed	e	d
edede
ej                     de
ej                     f fdZdej                  dej                  fdZ xZS )Transformerz9Transformer block with multi-head self-attention and MLP.      @FrX   Nr   r   rg   r"   r#   rh   ri   rj   c                 ~   |	|
d}t         |            ||fi || _        t        |f|||d|| _        |dkD  rt        |      nt        j                         | _         ||fi || _	        t        d|t        ||z        |d|| _        |dkD  rt        |      | _        yt        j                         | _        y)a  Initialize Transformer block.

        Args:
            dim: Input feature dimension.
            num_heads: Number of attention heads.
            mlp_ratio: Ratio for MLP hidden dimension.
            qkv_bias: Whether to use bias in QKV projection.
            attn_drop: Attention dropout rate.
            drop_path: Stochastic depth drop rate.
            act_layer: Activation layer type.
            norm_layer: Normalization layer type.
        r&   )r   r"   r#   rX   rl   Nro   )r-   r.   rp   r   r3   r   r0   rq   rr   rs   r   r]   rt   ru   )r:   r   r   rg   r"   r#   rh   ri   rj   r'   r(   r;   r=   s               r>   r.   zTransformer.__init__  s    2 /*r*
ceYU^ebde	1:R(9-R[[]*r*
h3C)O8LXahegh1:R(9-R[[]r?   r@   rA   c                     || j                  | j                  | j                  |                  z   }|| j                  | j	                  | j                  |                  z   }|S rw   rx   ry   s     r>   rW   zTransformer.forward+  rz   r?   )rY   rZ   r[   r\   r0   r{   r|   r]   r_   r^   r
   r}   r.   r`   ra   rW   rb   rc   s   @r>   r   r     s    C  ""!!)+*,,,!S!S !S 	!S
 !S !S !S BII!S RYY!SF %,, r?   r   c                        e Zd ZdZ	 	 	 	 	 	 	 ddededee   dededef fdZd	e	j                  d
e	j                  fdZ xZS )ClassAttentionz6Class attention mechanism for class token interaction.r   r   r<   r"   r#   r$   c	                 "   ||d}	t         
|           || _        ||| _        n||z  }|| _        |dz  | _        t        j                  || j                  | j                  z  dz  fd|i|	| _        t        j                  || j                  | j                  z  fd|i|	| _        t        j                  |      | _
        t        j                  | j                  | j                  z  |fi |	| _        t        j                  |      | _        y)a{  Initialize ClassAttention.

        Args:
            dim: Input feature dimension.
            num_heads: Number of attention heads.
            head_dim: Dimension per head. If None, computed as dim // num_heads.
            qkv_bias: Whether to use bias in QKV projection.
            attn_drop: Attention dropout rate.
            proj_drop: Projection dropout rate.
        r&   Nr)   rE   r*   )r-   r.   r   r<   r/   r0   r1   kvr   r4   r#   r5   r$   )r:   r   r   r<   r"   r#   r$   r'   r(   r;   r=   s             r>   r.   zClassAttention.__init__<  s    * /"$DMi'H$DM%
))C!?!!CY(YVXY3 >TXTQSTI.IIdmmdnn<cHRH	I.r?   r@   rA   c                    |j                   \  }}}| j                  |      j                  ||d| j                  | j                        j                  ddddd      }|j                  d      \  }}| j                  |ddddddf         j                  || j                  d| j                        | j                  z  }||j                  dd      z  }	|	j                  d	      }	| j                  |	      }	|	|z  j                  dd      j                  |d| j                  | j                  z        }
| j                  |
      }
| j                  |
      }
|
S )
zForward pass.

        Args:
            x: Input tensor of shape (B, N, C) where first token is class token.

        Returns:
            Class token output of shape (B, 1, C).
        rE   r   rD   r   r+   Nr   rF   rG   )rI   r   rM   r   r<   rJ   r   r   r/   r   rN   r#   r5   r$   )r:   r@   rQ   NrT   r   r   r2   r   r3   	cls_embeds              r>   rW   zClassAttention.forwarda  s)    ''1aWWQZ1aGOOPQSTVWYZ\]^yy|1FF1QAX;''4>>1dmmLtzzY1;;r2&&|||#~~d#AX((A.66q!T]]T^^=[\	IIi(	NN9-	r?   )r   NFrX   rX   NN)rY   rZ   r[   r\   r]   r   r^   r_   r.   r`   ra   rW   rb   rc   s   @r>   r   r   9  s|    @
 &*"!!#/#/ #/ sm	#/
 #/ #/ #/J %,, r?   r   c                        e Zd ZdZddddddej
                  ej                  ddf
dededee   d	e	d
e
de	de	de	deej                     deej                     f fdZdej                  dej                  fdZ xZS )
ClassBlockz3Class block that combines class attention with MLP.Nr   FrX   r   r   r<   rg   r"   dropr#   rh   ri   rj   c           	         ||d}t         |            |
|fi || _        t        |f|||||d|| _        |dkD  rt        |      nt        j                         | _         |
|fi || _	        t        d|t        ||z        |	|d|| _        |dkD  rt        |      | _        yt        j                         | _        y)a1  Initialize ClassBlock.

        Args:
            dim: Input feature dimension.
            num_heads: Number of attention heads.
            head_dim: Dimension per head. If None, computed as dim // num_heads.
            mlp_ratio: Ratio for MLP hidden dimension.
            qkv_bias: Whether to use bias in QKV projection.
            drop: Dropout rate.
            attn_drop: Attention dropout rate.
            drop_path: Stochastic depth drop rate.
            act_layer: Activation layer type.
            norm_layer: Normalization layer type.
        r&   )r   r<   r"   r#   r$   rX   )rm   rn   ri   r   Nro   )r-   r.   rp   r   r3   r   r0   rq   rr   rs   r   r]   rt   ru   )r:   r   r   r<   rg   r"   r   r#   rh   ri   rj   r'   r(   r;   r=   s                 r>   r.   zClassBlock.__init__}  s    : /*r*
"

 
	 2;R(9-R[[]*r*
 
i0	

 
 2;R(9-R[[]r?   r@   rA   c                 $   |ddddf   }|| j                  | j                  | j                  |                  z   }|| j                  | j	                  | j                  |                  z   }t        j                  ||ddddf   gd      S )zForward pass.

        Args:
            x: Input tensor of shape (B, N, C) where first token is class token.

        Returns:
            Output tensor with updated class token.
        Nr   rG   )rr   r3   rp   ru   rt   rs   r`   cat)r:   r@   r   s      r>   rW   zClassBlock.forward  s~     a!eH			$**Q-0H II	I9N0O PP	yy)Qq!"uX.A66r?   )rY   rZ   r[   r\   r0   r{   r|   r]   r   r_   r^   r
   r}   r.   r`   ra   rW   rb   rc   s   @r>   r   r   z  s    = '+!"!!)+*,,,3S3S 3S sm	3S
 3S 3S 3S 3S 3S BII3S RYY3Sj7 7%,, 7r?   r   
block_typekwargsrA   c                 6    | dk(  rt        di |S J d|         )zGet block based on type.

    Args:
        block_type: Type of block ('ca' for ClassBlock).
        **kwargs: Additional keyword arguments for block.

    Returns:
        The requested block module.
    cazInvalid block type: ro   )r   )r   r   s     r>   	get_blockr     s,     T#F##9,ZL99ur?   size.lamr/   c                    | d   |z  }| d   |z  }t        j                  |t         j                        }t        j                  |t         j                        }t        j                  d|z
        }||z  j	                         }||z  j	                         }	t        j
                  d|d      }
t        j
                  d|d      }t        j                  |
|dz  z
  d|      }t        j                  ||	dz  z
  d|      }t        j                  |
|dz  z   d|      }t        j                  ||	dz  z   d|      }|j                         |j                         |j                         |j                         fS )a1  Get random bounding box for token labeling.

    Reference: https://github.com/zihangJiang/TokenLabeling

    Args:
        size: Input tensor size tuple.
        lam: Lambda parameter for cutmix.
        scale: Scaling factor.

    Returns:
        Bounding box coordinates (bbx1, bby1, bbx2, bby2).
    r   rE   )r(         ?r   r   )r`   tensorfloat32sqrtr]   randintclampitem)r   r   r/   rS   rR   W_tH_tcut_ratcut_wcut_hcxcybbx1bby1bbx2bby2s                   r>   	rand_bboxr     s3    	Q5AQ5A
,,q
.C
,,q
.Cjjc"G7]!E7]!E 
q!T	"B	q!T	"B;;rEQJ1-D;;rEQJ1-D;;rEQJ1-D;;rEQJ1-D99;		TYY[$))+==r?   c                        e Zd ZdZ	 	 	 	 	 	 	 	 	 ddededededededef fd	Zd
ej                  dej                  fdZ	 xZ
S )
PatchEmbedz6Image to patch embedding with multi-layer convolution.img_size	stem_convstem_stride
patch_sizein_chans
hidden_dim	embed_dimc
                    ||	d}
t         |           |dv sJ |rt        j                  t        j                  ||fd|ddd|
t        j
                  |fi |
t        j                  d      t        j                  ||fdd	d	dd|
t        j
                  |fi |
t        j                  d      t        j                  ||fdd	d	dd|
t        j
                  |fi |
t        j                  d      	      | _        nd
| _        t        j                  ||f||z  ||z  d|
| _        ||z  ||z  z  | _	        y
)a  Initialize PatchEmbed.

        Different from ViT which uses 1 conv layer, VOLO uses multiple conv layers for patch embedding.

        Args:
            img_size: Input image size.
            stem_conv: Whether to use stem convolution layers.
            stem_stride: Stride for stem convolution.
            patch_size: Patch size (must be 4, 8, or 16).
            in_chans: Number of input channels.
            hidden_dim: Hidden dimension for stem convolution.
            embed_dim: Output embedding dimension.
        r&   )r+   r         rD   F)r   r!   r    r*   T)inplacer   Nr   r!   )
r-   r.   r0   
SequentialConv2dBatchNorm2dReLUconvr5   num_patches)r:   r   r   r   r   r   r   r   r'   r(   r;   r=   s              r>   r.   zPatchEmbed.__init__  sN   2 /Z'''		(JoAk[\cholnoz0R0%		*jgaST[`gdfgz0R0%		*jgaST[`gdfgz0R0%
DI DIII
 #k1,	

 
	 %
2x:7MNr?   r@   rA   c                 b    | j                   | j                  |      }| j                  |      }|S )zForward pass.

        Args:
            x: Input tensor of shape (B, C, H, W).

        Returns:
            Output tensor of shape (B, embed_dim, H', W').
        )r   r5   ry   s     r>   rW   zPatchEmbed.forward)  s-     99 		!AIIaLr?   )	   Fr   r   rD   @     NN)rY   rZ   r[   r\   r]   r^   r.   r`   ra   rW   rb   rc   s   @r>   r   r     s    @  #   2O2O 2O 	2O
 2O 2O 2O 2Oh %,, r?   r   c                   p     e Zd ZdZ	 	 	 d	dededef fdZdej                  dej                  fdZ xZ	S )

Downsamplez#Downsampling module between stages.in_embed_dimout_embed_dimr   c                 j    t         |           ||d}t        j                  ||f||d|| _        y)zInitialize Downsample.

        Args:
            in_embed_dim: Input embedding dimension.
            out_embed_dim: Output embedding dimension.
            patch_size: Patch size for downsampling.
        r&   r   N)r-   r.   r0   r   r5   )r:   r   r   r   r'   r(   r;   r=   s          r>   r.   zDownsample.__init__;  s:     	/IIlMkzZdkhjk	r?   r@   rA   c                 x    |j                  dddd      }| j                  |      }|j                  dddd      }|S )zForward pass.

        Args:
            x: Input tensor of shape (B, H, W, C).

        Returns:
            Output tensor of shape (B, H', W', C').
        r   rD   r   rE   )rJ   r5   ry   s     r>   rW   zDownsample.forwardN  s>     IIaAq!IIaLIIaAq!r?   )rE   NN)
rY   rZ   r[   r\   r]   r.   r`   ra   rW   rb   rc   s   @r>   r   r   8  sQ    -  ll l 	l& %,, r?   r   block_fnindexr   layersr   r   r    r!   rg   r"   r#   drop_path_ratec                     g }t        ||         D ]H  }||t        |d|       z   z  t        |      dz
  z  }|j                   | |f||||||	|
|||d
|       J t        j                  | }|S )a  Generate outlooker layers for stage 1.

    Args:
        block_fn: Block function to use (typically Outlooker).
        index: Index of current stage.
        dim: Feature dimension.
        layers: List of layer counts for each stage.
        num_heads: Number of attention heads.
        kernel_size: Kernel size for outlook attention.
        padding: Padding for outlook attention.
        stride: Stride for outlook attention.
        mlp_ratio: Ratio for MLP hidden dimension.
        qkv_bias: Whether to use bias in QKV projection.
        attn_drop: Attention dropout rate.
        drop_path_rate: Stochastic depth drop rate.
        **kwargs: Additional keyword arguments.

    Returns:
        Sequential module containing outlooker blocks.
    Nr   )
r   r    r!   r   rg   r"   r#   rh   r'   r(   rangesumappendr0   r   )r   r   r   r   r   r   r    r!   rg   r"   r#   r   r'   r(   r   blocks	block_idx	block_dprs                     r>   outlooker_blocksr   ]  s    J F6%=) 	"i#fVen2E&EF#f+XY/Z	h
#
 
 	  ]]F#FMr?   c	                     g }
t        ||         D ]C  }||t        |d|       z   z  t        |      dz
  z  }|
j                   | ||f||||d|	       E t        j                  |
 }
|
S )ae  Generate transformer layers for stage 2.

    Args:
        block_fn: Block function to use (typically Transformer).
        index: Index of current stage.
        dim: Feature dimension.
        layers: List of layer counts for each stage.
        num_heads: Number of attention heads.
        mlp_ratio: Ratio for MLP hidden dimension.
        qkv_bias: Whether to use bias in QKV projection.
        attn_drop: Attention dropout rate.
        drop_path_rate: Stochastic depth drop rate.
        **kwargs: Additional keyword arguments.

    Returns:
        Sequential module containing transformer blocks.
    Nr   )rg   r"   r#   rh   r   )r   r   r   r   r   rg   r"   r#   r   r   r   r   r   s                r>   transformer_blocksr     s    : F6%=) 
	"i#fVen2E&EF#f+XY/Z	h
  
 
 	
 ]]F#FMr?   c            -           e Zd ZdZddddddddd	d	d
dddddej
                  ddddddfdee   dedededededede	ee      de	ee      de
edf   de
edf   dedededed ed!ed"eej                     d#e	e
edf      d$ed%ed&ef, fd'Zd(ej                  d)dfd*Zej$                  j&                  d)efd+       Zej$                  j&                  dCd,ed)eeef   fd-       Zej$                  j&                  dDd.ed)dfd/       Zej$                  j&                  d)ej                  fd0       ZdEdede	e   d)dfd1Zd2ej8                  d)ej8                  fd3Zd2ej8                  d)ej8                  fd4Zd2ej8                  d)eej8                  e
ej8                  ej8                  e
eeeef   f   f   fd5Z 	 	 	 	 	 dFd2ej8                  d6e	eeee   f      d7ed8ed9ed:ed)eeej8                     e
ej8                  eej8                     f   f   fd;Z!	 	 	 dGd6eeee   f   d<ed=ed)ee   fd>Z"d2ej8                  d)ej8                  fd?Z#dCd2ej8                  d@ed)ej8                  fdAZ$d2ej8                  d)ej8                  fdBZ% xZ&S )Hr   zVision Outlooker (VOLO) model.r   rD     tokenr   r   N)TFFFrf   FrX   )r   r   TrE   r   r   r   num_classesglobal_poolr   stem_hidden_dim
embed_dimsr   downsamples.outlook_attentionrg   r"   	drop_ratepos_drop_rateattn_drop_rater   rj   post_layersuse_aux_headuse_mix_tokenpooling_scalec                    t         !|           ||d}t        |      } t        |      |      }t	        |      }|| _        || _        || _        || _        || _	        |d   x| _
        | _        |rd| _        |dk(  sJ d       d| _        t        ddd||||d	   d
|| _        |}|d	   |z  |z  |d   |z  |z  f}t!        j"                  t%        j&                  d|d	   |d   |d   fi |      | _        t!        j*                  |      | _        g | _        g | _        g }d	}t3        t        |            D ]  }||   r#t5        t6        |||   ||	|   f||   |||d|} n#t9        t:        |||   ||	|   f||   ||||d|} |j=                  |        | j.                  j=                  |       | j0                  j=                  t?        ||   |d|              |dz  }|
|   s|j=                  tA        ||   ||dz      dfi |       |dz  }|dz  } t!        jB                  |      | _"        d| _#        |t!        jB                  t3        t        |            D cg c]"  }tI        ||   f|d   |	d   |d   ||d|d|$ c}      | _#        t!        j"                  t%        j&                  dd|d   fi |      | _%        tM        | jJ                  d       |r@|d	kD  r!t!        jN                  | j                  |fi |nt!        jP                         | _)        nd| _)         || j                  fi || _*        t!        j*                  |      | _+        |d	kD  r!t!        jN                  | j                  |fi |nt!        jP                         | _,        tM        | j(                  d       | j[                  | j\                         yc c}w )a/  Initialize VOLO model.

        Args:
            layers: Number of blocks in each stage.
            img_size: Input image size.
            in_chans: Number of input channels.
            num_classes: Number of classes for classification.
            global_pool: Global pooling type ('token', 'avg', or '').
            patch_size: Patch size for patch embedding.
            stem_hidden_dim: Hidden dimension for stem convolution.
            embed_dims: List of embedding dimensions for each stage.
            num_heads: List of number of attention heads for each stage.
            downsamples: Whether to downsample between stages.
            outlook_attention: Whether to use outlook attention in each stage.
            mlp_ratio: Ratio for MLP hidden dimension.
            qkv_bias: Whether to use bias in QKV projection.
            drop_rate: Dropout rate.
            pos_drop_rate: Position embedding dropout rate.
            attn_drop_rate: Attention dropout rate.
            drop_path_rate: Stochastic depth drop rate.
            norm_layer: Normalization layer type.
            post_layers: Post-processing layer types.
            use_aux_head: Whether to use auxiliary head.
            use_mix_token: Whether to use token mixing for training.
            pooling_scale: Pooling scale factor.
        r&   rF   r   r   z)return all tokens if mix_token is enabledFTrE   r   )r   r   r   r   r   r   r   )r   )rg   r"   r#   rj   )rg   r"   r   r#   rj   znetwork.)num_chs	reductionmoduleNrX   )r   r   rg   r"   r#   rh   rj   {Gz?stdro   )/r-   r.   lenr   r   r   r   r   	mix_tokenr   num_featureshead_hidden_sizebetagrad_checkpointingr   patch_embedr0   	Parameterr`   zeros	pos_embedr4   pos_drop
stage_endsfeature_infor   r   re   r   r   r   dictr   
ModuleListnetworkpost_networkr   	cls_tokenr   r1   rq   aux_headnorm	head_dropheadapply_init_weights)"r:   r   r   r   r   r   r   r   r   r   r   r   rg   r"   r   r   r   r   rj   r   r   r   r   r'   r(   r;   
num_layersr
patch_gridr  r   istager=   s"                                    r>   r.   zVOLO.__init__  s$   j 	/[
)Ij))4	X&& &&*4>rNBD1DI')V+VV)"'% 
!& m
 
  qkZ/=@(1+Q[B[_lBlm
ekk!Z]JqMS]^`Sa&heg&hi

]3 	s6{# &	A #(qMaL (l%,)  +qMaL (l%#1,)  NN5!OO""9-$$T*Q-1W_`i_jUk%lmNI1~z*Q-AE9JATQSTUQQ	M&	P }}W- !" " s;/0/  N
"2'm'm%, )
 
/ !D  \\%++aJrN*Qb*QRDN$..c2 OZ]^BIId&7&7KKdfdododqDM DMt007B7	 I.GRUVBIId//CC\^\g\g\i	dnn#.

4%%&;/s   %'OmrA   c                    t        |t        j                        rjt        |j                  d       t        |t        j                        r8|j
                  +t        j                  j                  |j
                  d       yyyy)z\Initialize weights for modules.

        Args:
            m: Module to initialize.
        r   r  Nr   )
isinstancer0   r1   r   weightr*   init	constant_)r:   r   s     r>   r  zVOLO._init_weightsn  s\     a#!((,!RYY'AFF,>!!!&&!, -?' $r?   c                 
    ddhS )zwGet set of parameters that should not have weight decay.

        Returns:
            Set of parameter names.
        r  r  ro   r:   s    r>   no_weight_decayzVOLO.no_weight_decayy  s     [))r?   coarsec                 &    t        dddgg d      S )zGet parameter grouping for optimizer.

        Args:
            coarse: Whether to use coarse grouping.

        Returns:
            Parameter grouping dictionary.
        z ^cls_token|pos_embed|patch_embed)z^network\.(\d+)\.(\d+)N)z^network\.(\d+)r   ))z
^cls_tokenr+  )z^post_network\.(\d+)N)z^norm)i )stemr   blocks2)r  )r:   r)  s     r>   group_matcherzVOLO.group_matcher  s$     41*
 	
r?   enablec                     || _         y)zqSet gradient checkpointing.

        Args:
            enable: Whether to enable gradient checkpointing.
        N)r  )r:   r/  s     r>   set_grad_checkpointingzVOLO.set_grad_checkpointing  s     #)r?   c                     | j                   S )zYGet classifier module.

        Returns:
            The classifier head module.
        )r  r'  s    r>   get_classifierzVOLO.get_classifier  s     yyr?   c                 "   || _         ||| _        t        | j                  d      r | j                  j                  j
                  nd}t        | j                  d      r | j                  j                  j                  nd}|dkD  r#t        j                  | j                  |||      nt        j                         | _        | j                  B|dkD  r#t        j                  | j                  |||      nt        j                         | _        yy)zReset classifier head.

        Args:
            num_classes: Number of classes for new classifier.
            global_pool: Global pooling type.
        Nr#  r   r&   )r   r   hasattrr  r#  r'   r(   r0   r1   r  rq   r  )r:   r   r   r'   r(   s        r>   reset_classifierzVOLO.reset_classifier  s     '"*D,3DIIx,H!!((d*1$))X*F		  &&DKVYZ? II{6H`b`k`k`m 		==$OZ]^ II!!;vULdfdododq M %r?   r@   c                 P   t        | j                        D ]i  \  }}|dk(  r || j                  z   }| j                  |      }| j                  r+t
        j                  j                         st        ||      }b ||      }k |j                  \  }}}}|j                  |d|      }|S )zForward pass through token processing stages.

        Args:
            x: Input tensor of shape (B, H, W, C).

        Returns:
            Token tensor of shape (B, N, C).
        rE   rF   )	enumerater  r  r  r  r`   r   is_scriptingr   rI   rM   )r:   r@   idxblockrQ   rR   rS   rT   s           r>   forward_tokenszVOLO.forward_tokens  s     $DLL1 	JCax&MM!$&&uyy/E/E/Gua(!H	 WW
1aIIaQr?   c                 2   |j                   \  }}}| j                  j                  |dd      }t        j                  ||gd      }| j
                  D ]A  }| j                  r+t        j                  j                         st        ||      }: ||      }C |S )zForward pass through class attention blocks.

        Args:
            x: Input token tensor of shape (B, N, C).

        Returns:
            Output tensor with class token of shape (B, N+1, C).
        rF   r   rG   )
rI   r  expandr`   r   r  r  r   r9  r   )r:   r@   rQ   r   rT   
cls_tokensr;  s          r>   forward_clszVOLO.forward_cls  s     ''1a^^**1b"5
IIz1o1-&& 	E&&uyy/E/E/Gua(!H		
 r?   c                    	 | j                  |      }|j                  dddd      }| j                  r0| j                  r#t        j
                  j                  | j                  | j                        j                         }|j                  d   | j                  z  |j                  d   | j                  z  }}t        |j                         || j                        \  }}}}|j                         }	| j                  |z  | j                  |z  }}
| j                  |z  | j                  |z  }}|j                  d      dd|
|||ddf   |	dd|
|||ddf<   |	}nd\  }}}}| j                  |      }| j                   | j#                  |      }| j%                  |      }| j&                  dk(  r|j)                  d	      }n| j&                  d
k(  r
|dddf   }n|}| j*                  |S | j+                  |ddddf         }| j                  s|d|j-                  d      d   z  z   S | j                  r| j                  r|j/                  |j                  d   |j                  d         }|j                         }	|j                  d      dd||||ddf   |	dd||||ddf<   |	}|j/                  |j                  d   ||z  |j                  d         }||||||ffS )a  Forward pass for training with mix token support.

        Args:
            x: Input tensor of shape (B, C, H, W).

        Returns:
            If training with mix_token: tuple of (class_token, aux_tokens, bbox).
            Otherwise: class_token tensor.
        r   rE   rD   r   )r/   N)r   r   r   r   avgrG   r         ?rF   )r	  rJ   r  r   r`   distributionsBetar  samplerI   r   r   r   cloneflipr<  r  r@  r  r   meanr  maxrM   )r:   r@   r   patch_hpatch_wr   r   r   r   temp_xsbbx1sbby1sbbx2sbby2x_clsx_auxs                   r>   forward_trainzVOLO.forward_train  s   	 QIIaAq! >>dmm%%**499dii@GGIC wwqzT-?-??tOaOaAaWG%.qvvxDDVDV%W"D$dWWYF--4d6H6H46O5E--4d6H6H46O5E56VVAYq%+uUZ{\]?]5^F1eEk5;12A%/"D$d " (  #AIIaLu$FFqFME(adGEE== La12h'}}31a000>>dmmMM%++a.'7EKKPROTE[[]F16Aq$t)TRVYXY?Y1ZF1d4idA-.EMM%++a.'G2CU[[QS_UE edD$555r?   indicesr  
stop_early
output_fmtintermediates_onlyc           	         |dv sJ d       g }t        t        | j                        |      \  }}	|D 
cg c]  }
| j                  |
    }}
| j                  |	   }	|j                  \  }}}}| j	                  |      j                  dddd      }t        j                  j                         s|s| j                  }n| j                  d|	dz    }t        |      D ]  \  }}|dk(  r || j                  z   }| j                  |      }| j                  r+t        j                  j                         st        ||      }n ||      }||v so|r|dk\  r| j                  |      }n|}|j!                  |j                  dddd              |r|S |j                  \  }}}}|j#                  |d|      }| j$                  | j'                  |      }| j                  |      }||fS c c}
w )	a   Forward features that returns intermediates.

        Args:
            x: Input image tensor
            indices: Take last n blocks if int, all if None, select matching indices if sequence
            norm: Apply norm layer to all intermediates
            stop_early: Stop iterating over blocks when last desired intermediate hit
            output_fmt: Shape of intermediate feature outputs
            intermediates_only: Only return intermediate features
        Returns:

        )NCHWzOutput format must be NCHW.r   rE   rD   r   NrF   )r   r  r  rI   r	  rJ   r`   r   r9  r  r8  r  r  r  r   r  r   rM   r  r@  )r:   r@   rU  r  rV  rW  rX  intermediatestake_indices	max_indexr  rQ   _heightwidthr  r:  r;  x_interrR   rS   rT   s                         r>   forward_intermediateszVOLO.forward_intermediates$  s   * Y&E(EE&"6s4??7KW"Ui4@Aq*AAOOI.	  gg1feQ''1a3 99!!#:llGll>IM2G#G, 	BJCax&MM!$&&uyy/E/E/Gua(!Hl"C1H"iilGG$$W__Q1a%@A	B     WW
1aIIaQ(  #AIIaL-O Bs   G"
prune_norm
prune_headc                 (   	 t        t        | j                        |      \  }}| j                  |   }| j                  d|dz    | _        |rt	        j
                         | _        |r+t	        j                         | _        | j                  dd       |S )aH  Prune layers not required for specified intermediates.

        Args:
            indices: Indices of intermediate layers to keep.
            prune_norm: Whether to prune normalization layer.
            prune_head: Whether to prune classification head.

        Returns:
            List of kept intermediate indices.
        Nr   r    )
r   r  r  r  r0   rq   r  r  r  r6  )r:   rU  rc  rd  r\  r]  s         r>   prune_intermediate_layerszVOLO.prune_intermediate_layerse  s|     	"6s4??7KW"UiOOI.	||NY]3DI "D!!!R(r?   c                     | j                  |      j                  dddd      }| j                  |      }| j                  | j	                  |      }| j                  |      }|S )zForward pass through feature extraction.

        Args:
            x: Input tensor of shape (B, C, H, W).

        Returns:
            Feature tensor.
        r   rE   rD   r   )r	  rJ   r<  r  r@  r  ry   s     r>   forward_featureszVOLO.forward_features  sg     Q''1a3 " (  #AIIaLr?   
pre_logitsc                 L   | j                   dk(  r|j                  d      }n| j                   dk(  r
|dddf   }n|}| j                  |      }|r|S | j                  |      }| j                  4| j	                  |ddddf         }|d|j                  d      d   z  z   }|S )zForward pass through classification head.

        Args:
            x: Input feature tensor.
            pre_logits: Whether to return pre-logits features.

        Returns:
            Classification logits or pre-logits features.
        rB  r   rG   r   Nr   rC  )r   rI  r  r  r  rJ  )r:   r@   rj  outauxs        r>   forward_headzVOLO.forward_head  s     u$&&Q&-C(AqD'CCNN1Jiin==$--!QR%)Ccggajm++C
r?   c                 L    	 | j                  |      }| j                  |      }|S )zForward pass (simplified, without mix token training).

        Args:
            x: Input tensor of shape (B, C, H, W).

        Returns:
            Classification logits.
        )ri  rn  ry   s     r>   rW   zVOLO.forward  s-     	@!!!$a r?   F)T)N)NFFrZ  F)r   FT)'rY   rZ   r[   r\   r0   r|   r   r]   strr   r   r^   r_   r
   r}   r.   r  r`   r   ignoresetr(  r   r   r.  r1  r3  r6  ra   r<  r@  r	   rT  rb  rg  ri  rn  rW   rb   rc   s   @r>   r   r     s7   (
  #&#%.2-1,G2M""!#%$&$&*,,,5A!%"'!"3e'Ie' e' 	e'
 e' e' e' !e' !c+e'  S	*e' tSy)e'  %T3Y/e' e' e' e'  !!e'" "#e'$ "%e'& RYY'e'( "%S/2)e'* +e',  -e'. /e'N	-ryy 	-T 	- YY* * * YY
D 
T#s(^ 
 
, YY)T )T ) ) YY		  rC rhsm rW[ r$  .U\\ ell &;6u|| ;6ellE%,,X]XdXdfkloqtvy{~l~fJ  EA  7A  1B ;6@ 8<$$',? ||?  eCcN34?  	? 
 ?  ?  !%?  
tELL!5tELL7I)I#JJ	K? F ./$#	3S	>*  	
 
c8%,, 5<< (ell   4 %,, r?   variant
pretrainedc                 d    |j                  dd      }t        t        | |fdt        |d      i|S )zCreate VOLO model.

    Args:
        variant: Model variant name.
        pretrained: Whether to load pretrained weights.
        **kwargs: Additional model arguments.

    Returns:
        VOLO model instance.
    out_indicesrD   feature_cfggetter)rw  feature_cls)popr   r   r  )rt  ru  r   rw  s       r>   _create_volor|    sE     **]A.K [hG	
  r?   urlc                 4    | ddddddt         t        ddd	d
|S )zCreate model configuration.

    Args:
        url: URL for pretrained weights.
        **kwargs: Additional configuration options.

    Returns:
        Model configuration dictionary.
    r   )rD   r   r   NQ?bicubicTzpatch_embed.conv.0)r  r  z
apache-2.0)r}  r   
input_size	pool_sizecrop_pctinterpolationfixed_input_sizerI  r  
first_conv
classifierlicenser   )r}  r   s     r>   _cfgr    s8     =t)%.B*:N  r?   ztimm/zLhttps://github.com/sail-sg/volo/releases/download/volo_1/d1_224_84.2.pth.tarr  )	hf_hub_idr}  r  zLhttps://github.com/sail-sg/volo/releases/download/volo_1/d1_384_85.2.pth.tarr   )rD   r   r   )r  r}  r  r  zLhttps://github.com/sail-sg/volo/releases/download/volo_1/d2_224_85.2.pth.tarzLhttps://github.com/sail-sg/volo/releases/download/volo_1/d2_384_86.0.pth.tarzLhttps://github.com/sail-sg/volo/releases/download/volo_1/d3_224_85.4.pth.tarzLhttps://github.com/sail-sg/volo/releases/download/volo_1/d3_448_86.3.pth.tar)rD     r  zLhttps://github.com/sail-sg/volo/releases/download/volo_1/d4_224_85.7.pth.tarzMhttps://github.com/sail-sg/volo/releases/download/volo_1/d4_448_86.79.pth.targffffff?zMhttps://github.com/sail-sg/volo/releases/download/volo_1/d5_224_86.10.pth.tarzLhttps://github.com/sail-sg/volo/releases/download/volo_1/d5_448_87.0.pth.tarzMhttps://github.com/sail-sg/volo/releases/download/volo_1/d5_512_87.07.pth.tar)rD      r  )zvolo_d1_224.sail_in1kzvolo_d1_384.sail_in1kzvolo_d2_224.sail_in1kzvolo_d2_384.sail_in1kzvolo_d3_224.sail_in1kzvolo_d3_448.sail_in1kzvolo_d4_224.sail_in1kzvolo_d4_448.sail_in1kzvolo_d5_224.sail_in1kzvolo_d5_448.sail_in1kzvolo_d5_512.sail_in1kc                 >    t        ddddd|}t        dd| i|}|S )VOLO-D1 model, Params: 27M.r+   r+   r   rE      r   r   r         r  r  r   r   r   ru  ro   )volo_d1_224r  r|  ru  r   
model_argsmodels       r>   r  r    4     p\6JVepiopJL:LLELr?   c                 >    t        ddddd|}t        dd| i|}|S )r  r  r  r  r  ru  ro   )volo_d1_384r  r  s       r>   r  r     r  r?   c                 >    t        ddddd|}t        dd| i|}|S )VOLO-D2 model, Params: 59M.r  r+   
   r+      r  r  r  r   r   r   r   r  ru  ro   )volo_d2_224r  r  s       r>   r  r  (  4     q]7KWfqjpqJL:LLELr?   c                 >    t        ddddd|}t        dd| i|}|S )r  r  r  r  r  ru  ro   )volo_d2_384r  r  s       r>   r  r  0  r  r?   c                 >    t        ddddd|}t        dd| i|}|S )VOLO-D3 model, Params: 86M.r   r   r   r+   r  r  r  ru  ro   )volo_d3_224r  r  s       r>   r  r  8  r  r?   c                 >    t        ddddd|}t        dd| i|}|S )r  r  r  r  r  ru  ro   )volo_d3_448r  r  s       r>   r  r  @  r  r?   c                 >    t        ddddd|}t        dd| i|}|S )VOLO-D4 model, Params: 193M.r  r      r  r  r  r   r   r   r  ru  ro   )volo_d4_224r  r  s       r>   r  r  H  4     r]7KWgrkqrJL:LLELr?   c                 >    t        ddddd|}t        dd| i|}|S )r  r  r  r  r  ru  ro   )volo_d4_448r  r  s       r>   r  r  P  r  r?   c           	      B    t        ddddddd|}t        d	d| i|}|S )
jVOLO-D5 model, Params: 296M.

    stem_hidden_dim=128, the dim in patch embedding is 128 for VOLO-D5.
    r  r     r+   r  r  r+      r   r   r   rg   r   ru  ro   )volo_d5_224r  r  s       r>   r  r  X  B      4+?K[S4,24J L:LLELr?   c           	      B    t        ddddddd|}t        d	d| i|}|S )
r  r  r  r  r+   r  r  ru  ro   )volo_d5_448r  r  s       r>   r  r  e  r  r?   c           	      B    t        ddddddd|}t        d	d| i|}|S )
r  r  r  r  r+   r  r  ru  ro   )volo_d5_512r  r  s       r>   r  r  r  r  r?   r   )
r   rD   r   rE   rf   Fr   rX   NN)rf   Fr   rX   rp  )rf  )Fr\   rK   typingr   r   r   r   r   r   r	   r
   r`   torch.nnr0   torch.nn.functional
functionalrO   	timm.datar   r   timm.layersr   r   r   r   r   r   _builderr   	_featuresr   _manipulater   	_registryr   r   __all__r}   r   re   r   r   r   r   rq  r   r]   r_   r   r   r   r^   r   r   r   r   r|  r  default_cfgsr  r  r  r  r  r  r  r  r  r  r  ro   r?   r>   <module>r     sm  *  J J J     A Z Z * + # <(Oryy OdE		 EPA		 AH1")) 1h>RYY >BD7 D7N:# : : : >E#s(O >% > >E#sTWY\J\D] >BC CL" "T  "777 7 S		7
 7 7 7 7 7 7 7 7 7  ]]!7@  "*** * S		*
 * * * * * * ]]*Zw299 wt# 4 3 4 *c # $sCx. * %!Z "Z0 "Z "Z0 "Z "Z0 "Z "[-1 "[ "Z-1 "[-1S-& -` D C D   D C D   D C D   D C D   D C D   D C D   D C D   D C D   	D 	C 	D 	 	 	D 	C 	D 	 	 	D 	C 	D 	 	r?   