a
    dZ                     @   sl  d Z ddlmZ ddlmZ ddlZddlmZ ddlm  m	Z
 ddlmZ ddlmZmZ ddlmZmZmZmZmZmZmZ ddl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 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(eee)e)f dddZ*eeee)e)f e)e)ddd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&d' Z0d>d)d*Z1d?d,d-Z2e e2d.d/e2d.d/e2d.d/e2 e2 e2 d0Z3e!d@e/d1d2d3Z4e!dAe/d1d4d5Z5e!dBe/d1d6d7Z6e!dCe/d1d8d9Z7e!dDe/d1d:d;Z8e!dEe/d1d<d=Z9dS )Faf   DaViT: Dual Attention Vision Transformers

As described in https://arxiv.org/abs/2204.03645

Input size invariant transformer architecture that combines channel and spacial
attention in each block. The attention mechanisms used are linear in complexity.

DaViT model defs and weights adapted from https://github.com/dingmyu/davit, original copyright below

    )partial)TupleN)TensorIMAGENET_DEFAULT_MEANIMAGENET_DEFAULT_STD)DropPath	to_2tupletrunc_normal_MlpLayerNorm2dget_norm_layeruse_fused_attn)NormMlpClassifierHeadClassifierHead   )build_model_with_cfg)register_notrace_function)checkpoint_seq)generate_default_cfgsregister_modelDaVitc                       s6   e Zd Zd	eeed fddZedddZ  ZS )

ConvPosEnc   Fdimkactc                    sD   t t|   tj|||d|d |d| _|r6t nt | _d S )Nr      )groups)	superr   __init__nnConv2dprojGELUIdentityr   )selfr   r   r   	__class__ Z/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/timm/models/davit.pyr!   "   s    zConvPosEnc.__init__xc                 C   s   |  |}|| | }|S N)r$   r   )r'   r-   Zfeatr*   r*   r+   forward(   s    
zConvPosEnc.forward)r   F)	__name__
__module____qualname__intboolr!   r   r/   __classcell__r*   r*   r(   r+   r   !   s   r   c                       s8   e Zd ZdZdddef fdd	Zeddd	Z  ZS )
Stemz Size-agnostic implementation of 2D image to patch embedding,
        allowing input size to be adjusted during model forward operation
    r   `      c                    sX   t    t|}|| _|| _|| _|d dks4J tj||d|dd| _||| _	d S )Nr   r8      r   Zkernel_sizestridepadding)
r    r!   r	   r;   in_chsout_chsr"   r#   convnorm)r'   r=   r>   r;   
norm_layerr(   r*   r+   r!   3   s    
zStem.__init__r,   c              
   C   s   |j \}}}}t|d| jd || jd   | jd  f}t|ddd| jd || jd   | jd  f}| |}| |}|S )Nr   r   )shapeFpadr;   r?   r@   r'   r-   BCHWr*   r*   r+   r/   I   s    .2

zStem.forward)	r0   r1   r2   __doc__r   r!   r   r/   r5   r*   r*   r(   r+   r6   .   s   r6   c                       s.   e Zd Zef fdd	ZedddZ  ZS )
Downsamplec                    s:   t    || _|| _||| _tj||dddd| _d S )Nr   r   r:   )r    r!   r=   r>   r@   r"   r#   r?   )r'   r=   r>   rA   r(   r*   r+   r!   S   s    

zDownsample.__init__r,   c              	   C   sb   |j \}}}}| |}t|dd|d  d f}t|dddd|d  d f}| |}|S )Nr   r   )rB   r@   rC   rD   r?   rE   r*   r*   r+   r/   f   s    
 
zDownsample.forward)r0   r1   r2   r   r!   r   r/   r5   r*   r*   r(   r+   rK   R   s   rK   c                       s,   e Zd Zd fdd	ZedddZ  ZS )	ChannelAttention   Fc                    sJ   t    || _|| }|d | _tj||d |d| _t||| _d S )N      r   bias)r    r!   	num_headsscaler"   Linearqkvr$   )r'   r   rQ   qkv_biashead_dimr(   r*   r+   r!   q   s    

zChannelAttention.__init__r,   c           
      C   s   |j \}}}| |||d| j|| j ddddd}|d\}}}|| j }|dd| }	|	jdd}	|	|dd dd}|dd|||}| 	|}|S )	Nr   r   r   r   r8   r   )
rB   rT   reshaperQ   permuteunbindrR   	transposesoftmaxr$   )
r'   r-   rF   NrG   rT   qr   vZ	attentionr*   r*   r+   r/   z   s    .

zChannelAttention.forward)rM   F)r0   r1   r2   r!   r   r/   r5   r*   r*   r(   r+   rL   o   s   	rL   c                       s>   e Zd Zdddejejddf fdd	Zeddd	Z  Z	S )
ChannelBlock      @F        Tc
           
         s   t    t|d|	d| _|| _||| _t|||d| _|dkrJt|nt	
 | _t|d|	d| _| jr||| _t|t|| |d| _|dkrt|nt	
 | _nd | _d | _d | _d S Nr   r   )rQ   rU   rd   )Zin_featuresZhidden_features	act_layer)r    r!   r   cpe1ffnnorm1rL   attnr   r"   r&   
drop_path1cpe2norm2r   r3   mlp
drop_path2)
r'   r   rQ   	mlp_ratiorU   	drop_pathrf   rA   rh   cpe_actr(   r*   r+   r!      s$    



zChannelBlock.__init__r,   c                 C   s   |j \}}}}| |ddd}| |}| |}|| | }| |dd||||}| j	d ur|ddd}|| 
| 	| | }|dd||||}|S )Nr   r   )rB   rg   flattenr]   ri   rj   rk   rl   viewrn   ro   rm   )r'   r-   rF   rG   rH   rI   curr*   r*   r+   r/      s    


zChannelBlock.forward)
r0   r1   r2   r"   r%   	LayerNormr!   r   r/   r5   r*   r*   r(   r+   rb      s   "rb   )r-   window_sizec                 C   sj   | j \}}}}| |||d  |d ||d  |d |} | dddddd d|d |d |}|S )z
    Args:
        x: (B, H, W, C)
        window_size (int): window size
    Returns:
        windows: (num_windows*B, window_size, window_size, C)
    r   r   r   r   r8      rW   rB   rt   r[   
contiguous)r-   rw   rF   rH   rI   rG   windowsr*   r*   r+   window_partition   s    ,,r|   )r{   rw   rH   rI   c                 C   s^   | j d }| d||d  ||d  |d |d |}|dddddd d|||}|S )z
    Args:
        windows: (num_windows*B, window_size, window_size, C)
        window_size (int): Window size
        H (int): Height of image
        W (int): Width of image
    Returns:
        x: (B, H, W, C)
    rW   r   r   r   r   r8   rx   ry   )r{   rw   rH   rI   rG   r-   r*   r*   r+   window_reverse   s    
,$r}   c                       sB   e Zd ZU dZejje ed< d	 fdd	Z	e
dddZ  ZS )
WindowAttentiona   Window based multi-head self attention (W-MSA) module with relative position bias.
    It supports both of shifted and non-shifted window.
    Args:
        dim (int): Number of input channels.
        window_size (tuple[int]): The height and width of the window.
        num_heads (int): Number of attention heads.
        qkv_bias (bool, optional):  If True, add a learnable bias to query, key, value. Default: True
    
fused_attnTc                    sl   t    || _|| _|| _|| }|d | _t | _tj	||d |d| _
t	||| _tjdd| _d S )NrN   r   rO   rW   rY   )r    r!   r   rw   rQ   rR   r   r   r"   rS   rT   r$   ZSoftmaxr^   )r'   r   rw   rQ   rU   rV   r(   r*   r+   r!      s    

zWindowAttention.__init__r,   c           
      C   s   |j \}}}| |||d| j|| j ddddd}|d\}}}| jr`t|||}n,|| j	 }||
dd }	| |	}	|	| }|
dd|||}| |}|S )Nr   r   r   r   r8   rX   rW   )rB   rT   rZ   rQ   r[   r\   r   rC   Zscaled_dot_product_attentionrR   r]   r^   r$   )
r'   r-   ZB_r_   rG   rT   r`   r   ra   rj   r*   r*   r+   r/      s    .


zWindowAttention.forward)T)r0   r1   r2   rJ   torchjitFinalr4   __annotations__r!   r   r/   r5   r*   r*   r(   r+   r~      s   
r~   c                       sD   e Zd ZdZddddejejddf fdd	Zed	d
dZ	  Z
S )SpatialBlocka<   Windows Block.
    Args:
        dim (int): Number of input channels.
        num_heads (int): Number of attention heads.
        window_size (int): Window size.
        mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
        qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
        drop_path (float, optional): Stochastic depth rate. Default: 0.0
        act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
        norm_layer (nn.Module, optional): Normalization layer.  Default: nn.LayerNorm
    r9   rc   Trd   Fc                    s   t    || _|	| _|| _t|| _|| _t|d|
d| _	||| _
t|| j||d| _|dkrjt|nt | _t|d|
d| _| jr||| _t|| }t|||d| _|dkrt|nt | _nd | _d | _d | _d S re   )r    r!   r   rh   rQ   r	   rw   rp   r   rg   ri   r~   rj   r   r"   r&   rk   rl   rm   r3   r   rn   ro   )r'   r   rQ   rw   rp   rU   rq   rf   rA   rh   rr   Zmlp_hidden_dimr(   r*   r+   r!     s8    



zSpatialBlock.__init__r,   c              	   C   s  |j \}}}}| |ddd}| |}|||||}d }}| jd || jd   | jd  }	| jd || jd   | jd  }
t|dd||	||
f}|j \}}}}t	|| j}|d| jd | jd  |}| 
|}|d| jd | jd |}t|| j||}|d d d |d |d d f  }|||| |}|| | }| |dd||||}| jd ur|ddd}|| | | | }|dd||||}|S )Nr   r   r   rW   )rB   rg   rs   r]   ri   rt   rw   rC   rD   r|   rj   r}   rz   rk   rl   rn   ro   rm   )r'   r-   rF   rG   rH   rI   ZshortcutZpad_lZpad_tZpad_rZpad_b_ZHpZWpZ	x_windowsZattn_windowsr*   r*   r+   r/   E  s.    
""
$zSpatialBlock.forward)r0   r1   r2   rJ   r"   r%   rv   r!   r   r/   r5   r*   r*   r(   r+   r     s   -r   c                       sX   e Zd Zddddddddeejddf fd	d
	Zejj	dddZ
edddZ  ZS )
DaVitStager   Tspatialchannelr   r9   r8   )r   r   Fc                    s   t    d| _|r&t|||d| _n
t | _g }t|D ]}g }t|D ]`\}}|dkr|	t
||||	|
| ||||d	 qL|dkrL|	t||||	|
| |||d qL|	tj|  q<tj| | _d S )NFrA   r   )	r   rQ   rp   rU   rq   rA   rh   rr   rw   r   )r   rQ   rp   rU   rq   rA   rh   rr   )r    r!   grad_checkpointingrK   
downsampler"   r&   range	enumerateappendr   rb   
Sequentialblocks)r'   r=   r>   depthr   
attn_typesrQ   rw   rp   rU   drop_path_ratesrA   norm_layer_clrh   rr   Zstage_blocksZ	block_idxZdual_attention_blockZattn_idxZ	attn_typer(   r*   r+   r!   n  sD    

	


zDaVitStage.__init__c                 C   s
   || _ d S r.   )r   )r'   enabler*   r*   r+   set_grad_checkpointing  s    z!DaVitStage.set_grad_checkpointingr,   c                 C   s6   |  |}| jr(tj s(t| j|}n
| |}|S r.   )r   r   r   r   is_scriptingr   r   r'   r-   r*   r*   r+   r/     s
    

zDaVitStage.forward)T)r0   r1   r2   r   r"   rv   r!   r   r   ignorer   r   r/   r5   r*   r*   r(   r+   r   m  s    @r   c                       sv   e Zd ZdZd# fdd	Zdd Zejjd$ddZ	ejjdd Z
d%ddZdd Zd&eddd Zd!d" Z  ZS )'r   a   DaViT
        A PyTorch implementation of `DaViT: Dual Attention Vision Transformers`  - https://arxiv.org/abs/2204.03645
        Supports arbitrary input sizes and pyramid feature extraction
        
    Args:
        in_chans (int): Number of input image channels. Default: 3
        num_classes (int): Number of classes for classification head. Default: 1000
        depths (tuple(int)): Number of blocks in each stage. Default: (1, 1, 3, 1)
        embed_dims (tuple(int)): Patch embedding dimension. Default: (96, 192, 384, 768)
        num_heads (tuple(int)): Number of attention heads in different layers. Default: (3, 6, 12, 24)
        window_size (int): Window size. Default: 7
        mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4
        qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True
        drop_path_rate (float): Stochastic depth rate. Default: 0.1
        norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.
    r   r   r   r   r   r7           r            r9   r8   Tlayernorm2d	layernormh㈵>r   Frd     avgc                    s  t    t|}|t|  kr.t|ks4n J tt||
d}tt|	|
d}	|| _|d | _|| _d| _g | _	t
||d |d| _|d }dd td|t||D }g }t|D ]n}|| }t|||| |dk||| ||||| ||	||d}|}|| |  j	t|d	d
| dg7  _	qtj| | _|rf|| j| _t| j||| jd| _n"t | _t| j||| j|d| _| | j d S )N)ZepsrW   Fr   r   c                 S   s   g | ]}|  qS r*   )tolist).0r-   r*   r*   r+   
<listcomp>      z"DaVit.__init__.<locals>.<listcomp>)r   r   r   rQ   rw   rp   rU   r   rA   r   rh   rr   r   zstages.)Znum_chsZ	reductionmodule)	pool_type	drop_rate)r   r   rA   )r    r!   lenr   r   num_classesZnum_featuresr   r   Zfeature_infor6   stemr   Zlinspacesumsplitr   r   r   dictr"   r   stagesnorm_prer   headr&   r   apply_init_weights)r'   Zin_chansdepths
embed_dimsrQ   rw   rp   rU   rA   r   Znorm_epsr   rh   rr   r   Zdrop_path_rater   global_poolZhead_norm_firstZ
num_stagesr=   Zdprr   Z	stage_idxr>   stager(   r*   r+   r!     sj    
"
"
"

zDaVit.__init__c                 C   sD   t |tjr@t|jdd t |tjr@|jd ur@tj|jd d S )Ng{Gz?)stdr   )
isinstancer"   rS   r
   ZweightrP   initZ	constant_)r'   mr*   r*   r+   r      s    zDaVit._init_weightsc                 C   s"   || _ | jD ]}|j|d qd S )N)r   )r   r   r   )r'   r   r   r*   r*   r+   r   &  s    
zDaVit.set_grad_checkpointingc                 C   s   | j jS r.   )r   fc)r'   r*   r*   r+   get_classifier,  s    zDaVit.get_classifierNc                 C   s   | j j||d d S )N)r   )r   reset)r'   r   r   r*   r*   r+   reset_classifier0  s    zDaVit.reset_classifierc                 C   s@   |  |}| jr(tj s(t| j|}n
| |}| |}|S r.   )r   r   r   r   r   r   r   r   r   r*   r*   r+   forward_features3  s    


zDaVit.forward_features)
pre_logitsc                 C   sD   | j |}| j |}| j |}| j |}|r8|S | j |S r.   )r   r   r@   rs   Zdropr   )r'   r-   r   r*   r*   r+   forward_head<  s
    zDaVit.forward_headc                 C   s   |  |}| |}|S r.   )r   r   r   r*   r*   r+   r/   C  s    

zDaVit.forward)r   r   r   r   r9   r8   Tr   r   r   r   TFrd   rd   r   r   F)T)N)F)r0   r1   r2   rJ   r!   r   r   r   r   r   r   r   r   r4   r   r/   r5   r*   r*   r(   r+   r     s:                     S

	c                 C   s   d| v r| S d| v r| d } ddl }i }|  D ]t\}}|dd|}|dd|}|d	d
}|dd}|dd}|dd}|dd}|dd}|||< q0|S )z  Remap MSFT checkpoints -> timm zhead.fc.weight
state_dictr   Nzpatch_embeds.([0-9]+)zstages.\1.downsamplezmain_blocks.([0-9]+)zstages.\1.blockszdownsample.projzdownsample.convzstages.0.downsampler   zhead.zhead.fc.znorms.z
head.norm.zcpe.0rg   zcpe.1rl   )reitemssubreplace)r   modelr   Zout_dictr   ra   r*   r*   r+   checkpoint_filter_fnI  s"    
r   Fc                 K   sP   t dd t|ddD }|d|}tt| |fttd|dd|}|S )	Nc                 s   s   | ]\}}|V  qd S r.   r*   )r   ir   r*   r*   r+   	<genexpr>a  r   z _create_davit.<locals>.<genexpr>r   r   out_indicesT)Zflatten_sequentialr   )Zpretrained_filter_fnZfeature_cfg)tupler   getpopr   r   r   r   )variant
pretrainedkwargsZdefault_out_indicesr   r   r*   r*   r+   _create_davit`  s    
r    c                 K   s   | dddddt tddd
|S )	Nr   )r      r   )r9   r9   gffffff?Zbicubicz	stem.convzhead.fc)
urlr   Z
input_sizeZ	pool_sizeZcrop_pctinterpolationmeanr   Z
first_conv
classifierr   )r   r   r*   r*   r+   _cfgo  s    r   ztimm/)Z	hf_hub_id)zdavit_tiny.msft_in1kzdavit_small.msft_in1kzdavit_base.msft_in1kdavit_large
davit_hugedavit_giant)returnc                 K   s(   t f dddd|}tdd| i|S )Nr   r   r   r   r   rQ   
davit_tinyr   )r   r   r   r   r   Zmodel_kwargsr*   r*   r+   r     s    r   c                 K   s(   t f dddd|}tdd| i|S )Nr   r   	   r   r   r   r   davit_smallr   )r   r   r   r*   r*   r+   r     s    r   c                 K   s(   t f dddd|}tdd| i|S )Nr   )            )r8   rM          r   
davit_baser   )r   r   r   r*   r*   r+   r     s    r   c                 K   s(   t f dddd|}tdd| i|S )Nr   )r   r   r      )r   r   r   0   r   r   r   )r   r   r   r*   r*   r+   r     s    r   c                 K   s(   t f dddd|}tdd| i|S )Nr   )r   r   r   i   )rM   r   r   @   r   r   r   )r   r   r   r*   r*   r+   r     s    r   c                 K   s(   t f dddd|}tdd| i|S )N)r   r   r   r   )r   r   r   i   )r   r   r   r7   r   r   r   )r   r   r   r*   r*   r+   r     s    r   )F)r   )F)F)F)F)F)F):rJ   	functoolsr   typingr   r   Ztorch.nnr"   Ztorch.nn.functionalZ
functionalrC   r   Z	timm.datar   r   Ztimm.layersr   r	   r
   r   r   r   r   r   r   Z_builderr   Z_features_fxr   Z_manipulater   	_registryr   r   __all__Moduler   r6   rK   rL   rb   r3   r|   r}   r~   r   r   r   r   r   r   Zdefault_cfgsr   r   r   r   r   r   r*   r*   r*   r+   <module>   sp   $$7,bN 

