a
    dd                     @   s  d Z ddlZddlmZmZmZ ddl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 ddlmZ ddlmZ dd	lmZmZmZ dd
lmZmZmZmZmZm Z  ddl!m"Z# g Z$dqddZ%drddZ&dsddZ'dtddZ(e)ee%ddddde%ddddde&dddddddd e&dddd!dddd e&dd!dd"dddd fdd#d$d$d%d&d'ee%dd(dd)e%dddd)e&dddd"ddd*e&dd!dd+ddd*e&dd"dd,ddd*fdd#d$d$d%d-d'ee%dd(dd)e%dddd)e&dd"dd,ddd*e&dd.dd/ddd*e&dd0dd1ddd*fdd#d$d$d%d2d'ee%dd(dd)e%dddd)e&dd"dd,ddd*e&dd.dd/ddd*e&dd0dd1ddd*fdd#d$d$d3e)d4d5d2d6e(de(d7e(d8e(de(d9e(d:e(dd;Z*eG d<d= d=ej+Z,G d>d? d?ej+Z-G d@dA dAej+Z.eG dBdC dCej+Z/edDe, edEe/ dudGdHZ0dvdIdJZ1dwdKdLZ2ee2dMdNe2dMdNe2dMdNe2dMdOdPe2dMdOdPe2dMdOdPe2dMdOdPe2dMdOdPe2dMdOdPe2dMdOdPe2dMdOdPe2dMdOdPe2dMdOdPe2dMdQdRddSe2dMdQdRddSe2dMdQdRddSdTZ3edxedUdVdWZ4edyedUdXdYZ5edzedUdZd[Z6ed{edUd\d]Z7ed|edUd^d_Z8ed}edUd`daZ9ed~edUdbdcZ:ededUdddeZ;ededUdfdgZ<ededUdhdiZ=ee>djdkdldmdndodp dS )a   MobileViT

Paper:
V1: `MobileViT: Light-weight, General-purpose, and Mobile-friendly Vision Transformer` - https://arxiv.org/abs/2110.02178
V2: `Separable Self-attention for Mobile Vision Transformers` - https://arxiv.org/abs/2206.02680

MobileVitBlock and checkpoints adapted from https://github.com/apple/ml-cvnets (original copyright below)
License: https://github.com/apple/ml-cvnets/blob/main/LICENSE (Apple open source)

Rest of code, ByobNet, and Transformer block hacked together by / Copyright 2022, Ross Wightman
    N)CallableTupleOptional)nn)	to_2tuplemake_divisible
GroupNorm1ConvMlpDropPathis_exportable   )build_model_with_cfg)register_notrace_module)register_modelgenerate_default_cfgsregister_model_deprecations)register_blockByoBlockCfgByoModelCfgByobNetLayerFn
num_groups)Block      @c                 C   s   t d| ||d|tddddS )NZbottler   T)Z	bottle_inZ
linear_out)typedcsgsbrblock_kwargs)r   dictr   r   r   r    r#   ^/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/timm/models/mobilevit.py_inverted_residual_block!   s    
r%      c                 C   s,   t | |||dtdd|dt|||ddfS )Nr"   	mobilevitr   )transformer_dimtransformer_depth
patch_size)r   r   r   r   r    r%   r   r!   r   r   r   r(   r)   r*   r   r#   r#   r$   _mobilevit_block(   s    r-             @      ?c                 C   s.   t | |||dtdd|d|dt||ddfS )Nr"   
mobilevit2r   )r)   r*   )r   r   r   r   r   r   r    r+   )r   r   r   r)   r*   r   Ztransformer_brr#   r#   r$   _mobilevitv2_block6   s    r2         ?c                    s   d} dkr"t  fdd|D }ttd|d dddtd	|d d	ddtd|d	 d	d	d
td|d d	dd
td|d d	dd
ftd  ddddd}|S )N)@           i   r3   c                    s   g | ]}t |  qS r#   )int).0r   
multiplierr#   r$   
<listcomp>F       z$_mobilevitv2_cfg.<locals>.<listcomp>r   r   r/   r"   r.   )r   r   r   r)      r&       3x3 silu)blocksstem_chs	stem_type	stem_pool
downsample	act_layer)tupler   r%   r2   r8   )r;   Zchscfgr#   r:   r$   _mobilevitv2_cfgC   s"    
rK      r"   r>      0   r4   r,   P   `   r@   rA   rB   i@  )rC   rD   rE   rF   rG   rH   num_featuresr?   )r   r   r   )r   r   r   r(   r)   r*   x      r7   r5            i  seg      ?)Zrd_ratio)rC   rD   rE   rF   rG   Z
attn_layerZattn_kwargsrQ   g      ?g      ?g      ?g      ?)mobilevit_xxsmobilevit_xsmobilevit_sZsemobilevit_smobilevitv2_050mobilevitv2_075mobilevitv2_125mobilevitv2_100mobilevitv2_150mobilevitv2_175mobilevitv2_200c                       s   e Zd ZdZdddddddddd	d
dddddejfeee eeeee e	eef eee eeeeee
eeed fddZejejdddZ  ZS )MobileVitBlockzS MobileViT block
        Paper: https://arxiv.org/abs/2110.02178?context=cs.LG
    Nr>   r   r3   r   r   r/   r.      r&           F)in_chsout_chskernel_sizestridebottle_ratio
group_sizedilation	mlp_ratior(   r)   r*   	num_heads	attn_dropdrop	no_fusiondrop_path_ratelayerstransformer_norm_layerc              	      s   t t|   pt t||}|p(|}p8t|| j||||||d d| _tj	|ddd| _
tj fddt|
D  | _| _j|ddd| _|rd | _nj|| ||dd| _t|| _| jd | jd  | _d S )	Nr   rh   ri   groupsrl   r   Frh   biasc                    s(   g | ] }t d  jd	qS )T)rm   rn   Zqkv_biasro   	proj_drop	drop_pathrH   
norm_layer)TransformerBlockactr9   _ro   rp   rr   rs   rm   rn   r(   rt   r#   r$   r<      s   z+MobileVitBlock.__init__.<locals>.<listcomp>rh   ri   )superrb   __init__r   r   r   conv_norm_actconv_kxkr   Conv2dconv_1x1
Sequentialrangetransformernorm	conv_projconv_fusionr   r*   
patch_area)selfrf   rg   rh   ri   rj   rk   rl   rm   r(   r)   r*   rn   ro   rp   rq   rr   rs   rt   kwargsrv   	__class__r   r$   r      s(    





zMobileVitBlock.__init__xreturnc                 C   s  |}|  |}| |}| j\}}|j\}}}}t|| | t|| |  }	}
|	| |
|  }}|| }d}|	|ks|
|krtj||	|
fddd}d}||| | |||	dd}||||| j
	dd|| j
 |d}| |}| |}| || j
|d}|	dd|| | |||}|	dd|||| || }|rntj|||fddd}| |}| jd ur| tj||fdd	}|S )
NFbilinearsizemodeZalign_cornersTr   r.   r>   dim)r   r   r*   shapemathceilFinterpolatereshapeZ	transposer   r   r   
contiguousviewr   r   torchcat)r   r   Zshortcutpatch_hpatch_wBCHWnew_hnew_wnum_patch_hnum_patch_wnum_patchesr   r#   r#   r$   forward   s2    


& *

  
zMobileVitBlock.forward)__name__
__module____qualname____doc__r   Z	LayerNormr8   r   floatr   boolr   r   r   r   Tensorr   __classcell__r#   r#   r   r$   rb      sN   
<rb   c                       s   e Zd ZdZdeeeedd fddZej	ej	dd	d
Z
ej dej	eej	 ej	dddZdej	eej	 ej	dddZ  ZS )LinearSelfAttentiona  
    This layer applies a self-attention with linear complexity, as described in `https://arxiv.org/abs/2206.02680`
    This layer can be used for self- as well as cross-attention.
    Args:
        embed_dim (int): :math:`C` from an expected input of size :math:`(N, C, H, W)`
        attn_drop (float): Dropout value for context scores. Default: 0.0
        bias (bool): Use bias in learnable layers. Default: True
    Shape:
        - Input: :math:`(N, C, P, N)` where :math:`N` is the batch size, :math:`C` is the input channels,
        :math:`P` is the number of pixels in the patch, and :math:`N` is the number of patches
        - Output: same as the input
    .. note::
        For MobileViTv2, we unfold the feature map [B, C, H, W] into [B, C, P, N] where P is the number of pixels
        in a patch and N is the number of patches. Because channel is the first dimension in this unfolded tensor,
        we use point-wise convolution (instead of a linear layer). This avoids a transpose operation (which may be
        expensive on resource-constrained devices) that may be required to convert the unfolded tensor from
        channel-first to channel-last format in case of a linear layer.
    re   TN)	embed_dimro   ry   rx   r   c                    s\   t    || _tj|dd|  |dd| _t|| _tj|||dd| _t|| _	d S )Nr   r.   )Zin_channelsZout_channelsrx   rh   )
r   r   r   r   r   qkv_projZDropoutro   out_projout_drop)r   r   ro   ry   rx   r   r#   r$   r   $  s     

zLinearSelfAttention.__init__r   c           	      C   s~   |  |}|jd| j| jgdd\}}}tj|dd}| |}|| jddd}t||| }| 	|}| 
|}|S )Nr   r   r   Tr   Zkeepdim)r   splitr   r   softmaxro   sumrelu	expand_asr   r   )	r   r   Zqkvquerykeyvaluecontext_scorescontext_vectoroutr#   r#   r$   _forward_self_attn=  s    



z&LinearSelfAttention._forward_self_attnr   x_prevr   c                 C   s  |j \}}}}|j dd  \}}||ks0J dtj|| jjd | jd  | jjd | jd  d}	|	jd| jgdd\}
}tj|| jj| jd  | jjd ur| jj| jd  nd d}tj|
dd}| 	|}|| j
ddd}t||| }| |}| |}|S )	NzJThe number of pixels in a patch for query and key_value should be the samer   )weightrx   r   r   Tr   )r   r   Zconv2dr   r   r   rx   r   r   ro   r   r   r   r   r   )r   r   r   Z
batch_sizeZin_dimZkv_patch_areaZkv_num_patchesZq_patch_areaZq_num_patchesZqkr   r   r   r   r   r   r#   r#   r$   _forward_cross_attnU  s0     


z'LinearSelfAttention._forward_cross_attnc                 C   s$   |d u r|  |S | j||dS d S )N)r   )r   r   )r   r   r   r#   r#   r$   r     s    
zLinearSelfAttention.forward)re   re   T)N)N)r   r   r   r   r8   r   r   r   r   r   r   Zjitignorer   r   r   r   r#   r#   r   r$   r     s       *r   c                       sP   e Zd ZdZdeeeeedd fddZdeje	ej ejdd	d
Z
  ZS )LinearTransformerBlockaF  
    This class defines the pre-norm transformer encoder with linear self-attention in `MobileViTv2 paper <>`_
    Args:
        embed_dim (int): :math:`C_{in}` from an expected input of size :math:`(B, C_{in}, P, N)`
        mlp_ratio (float): Inner dimension ratio of the FFN relative to embed_dim
        drop (float): Dropout rate. Default: 0.0
        attn_drop (float): Dropout rate for attention in multi-head attention. Default: 0.0
        drop_path (float): Stochastic depth rate Default: 0.0
        norm_layer (Callable): Normalization layer. Default: layer_norm_2d
    Shape:
        - Input: :math:`(B, C_{in}, P, N)` where :math:`B` is batch size, :math:`C_{in}` is input embedding dim,
            :math:`P` is number of pixels in a patch, and :math:`N` is number of patches,
        - Output: same shape as the input
    r/   re   N)r   rm   rp   ro   rz   r   c                    sr   t    |ptj}|pt}||| _t|||d| _t|| _	||| _
t|t|| ||d| _t|| _d S )N)r   ro   ry   )Zin_featuresZhidden_featuresrH   rp   )r   r   r   ZSiLUr   norm1r   attnr
   
drop_path1norm2r	   r8   mlp
drop_path2)r   r   rm   rp   ro   rz   rH   r{   r   r#   r$   r     s    






zLinearTransformerBlock.__init__r   c                 C   sj   |d u r$||  | | | }n(|}| |}| ||}|  || }|| | | | }|S )N)r   r   r   r   r   r   )r   r   r   resr#   r#   r$   r     s    
zLinearTransformerBlock.forward)r/   re   re   re   NN)N)r   r   r   r   r8   r   r   r   r   r   r   r   r#   r#   r   r$   r     s          r   c                       s   e Zd ZdZddddddddd	d
d
d
defeee eeee eeef eee eeeeee	e
d fddZejejdddZ  ZS )MobileVitV2Blockz8
    This class defines the `MobileViTv2 block <>`_
    Nr>   r3   r   rc   r/   r.   rd   re   )rf   rg   rh   rj   rk   rl   rm   r(   r)   r*   ro   rp   rr   rs   rt   c                    s   t t|   pt t||}|p(|}p8t|| j|||d||d d| _tj	|ddd| _
tj fddt|	D  | _| _j|dddd| _t|
| _| jd | jd  | _t | _d S )	Nr   r   ru   Frw   c                    s$   g | ]}t  jd qS ))rm   ro   rp   rz   rH   r{   )r   r}   r~   ro   rp   rr   rs   rm   r(   rt   r#   r$   r<     s   
z-MobileVitV2Block.__init__.<locals>.<listcomp>)rh   ri   Z	apply_act)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r*   r   r   coreml_exportable)r   rf   rg   rh   rj   rk   rl   rm   r(   r)   r*   ro   rp   rr   rs   rt   r   rv   r   r   r$   r     s$    






zMobileVitV2Block.__init__r   c                 C   s~  |j \}}}}| j\}}t|| | t|| |  }}	|| |	|  }
}|
| }||ksh|	|kr~tj|||	fddd}| |}| |}|j d }| jrtj	|||f||fd}n$|
|||
|||ddddd	d
}|
||d|}| |}| |}| jr4|
||| | |
|}tj||d}n<|
|||||
|ddd
d	dd}|
|||
| || }| |}|S )Nr   Tr   r   r   r   r>      r.   r&   r   )Zupscale_factor)r   r*   r   r   r   r   r   r   r   Zunfoldr   Zpermuter   r   Zpixel_shuffler   )r   r   r   r   r   r   r   r   r   r   r   r   r   r#   r#   r$   r     s.    
&


$

$
zMobileVitV2Block.forward)r   r   r   r   r   r8   r   r   r   r   r   r   r   r   r   r   r#   r#   r   r$   r     sB   
2r   r'   r1   Fc                 K   s0   t t| |f|st|  nt| tddd|S NT)Zflatten_sequential)Z	model_cfgZfeature_cfgr   r   
model_cfgsr!   variantZcfg_variant
pretrainedr   r#   r#   r$   _create_mobilevit#  s    r   c                 K   s0   t t| |f|st|  nt| tddd|S r   r   r   r#   r#   r$   _create_mobilevit2+  s    r   c                 K   s    | ddddddddd	d
d|S )Ni  )r>   r6   r6   )rd   rd   g?Zbicubic)re   re   re   )r3   r3   r3   z	stem.convzhead.fcF)urlZnum_classes
input_size	pool_sizecrop_pctinterpolationmeanZstdZ
first_conv
classifierZfixed_input_sizer#   )r   r   r#   r#   r$   _cfg3  s    r   ztimm/)	hf_hub_idg"~j?)r   r   )r>   r7   r7   )   r   )r   r   r   r   )zmobilevit_xxs.cvnets_in1kzmobilevit_xs.cvnets_in1kzmobilevit_s.cvnets_in1kzmobilevitv2_050.cvnets_in1kzmobilevitv2_075.cvnets_in1kzmobilevitv2_100.cvnets_in1kzmobilevitv2_125.cvnets_in1kzmobilevitv2_150.cvnets_in1kzmobilevitv2_175.cvnets_in1kzmobilevitv2_200.cvnets_in1k$mobilevitv2_150.cvnets_in22k_ft_in1k$mobilevitv2_175.cvnets_in22k_ft_in1k$mobilevitv2_200.cvnets_in22k_ft_in1k(mobilevitv2_150.cvnets_in22k_ft_in1k_384(mobilevitv2_175.cvnets_in22k_ft_in1k_384(mobilevitv2_200.cvnets_in22k_ft_in1k_384)r   c                 K   s   t dd| i|S )NrX   r   )rX   r   r   r   r#   r#   r$   rX   o  s    rX   c                 K   s   t dd| i|S )NrY   r   )rY   r   r   r#   r#   r$   rY   t  s    rY   c                 K   s   t dd| i|S )NrZ   r   )rZ   r   r   r#   r#   r$   rZ   y  s    rZ   c                 K   s   t dd| i|S )Nr[   r   )r[   r   r   r#   r#   r$   r[   ~  s    r[   c                 K   s   t dd| i|S )Nr\   r   )r\   r   r   r#   r#   r$   r\     s    r\   c                 K   s   t dd| i|S )Nr^   r   )r^   r   r   r#   r#   r$   r^     s    r^   c                 K   s   t dd| i|S )Nr]   r   )r]   r   r   r#   r#   r$   r]     s    r]   c                 K   s   t dd| i|S )Nr_   r   )r_   r   r   r#   r#   r$   r_     s    r_   c                 K   s   t dd| i|S )Nr`   r   )r`   r   r   r#   r#   r$   r`     s    r`   c                 K   s   t dd| i|S )Nra   r   )ra   r   r   r#   r#   r$   ra     s    ra   r   r   r   r   r   r   )Zmobilevitv2_150_in22ft1kZmobilevitv2_175_in22ft1kZmobilevitv2_200_in22ft1kZmobilevitv2_150_384_in22ft1kZmobilevitv2_175_384_in22ft1kZmobilevitv2_200_384_in22ft1k)r   )r&   r   )r.   r/   r0   )r3   )NF)NF)rA   )F)F)F)F)F)F)F)F)F)F)?r   r   typingr   r   r   r   Ztorch.nn.functionalr   Z
functionalr   Ztimm.layersr   r   r   r	   r
   r   Z_builderr   Z_features_fxr   	_registryr   r   r   Zbyobnetr   r   r   r   r   r   Zvision_transformerr   r|   __all__r%   r-   r2   rK   r!   r   Modulerb   r   r   r   r   r   r   Zdefault_cfgsrX   rY   rZ   r[   r\   r^   r]   r_   r`   ra   r   r#   r#   r#   r$   <module>   sd    



Lkw:]




1