a
    d]                     @   s  d Z ddlmZ ddl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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 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$G dd de	jZ%dDddZ&dEddZ'ee'dde'dde'dde'dde'dde'dde'ddd dd!d"e'ddd dd!d"e'ddd dd!d"e'ddd dd!d"e'dd!d#e'ddd#d$Z(e%d%d&d'Z)dFd)d*Z*edGe%d+d,d-Z+edHe%d+d.d/Z,edIe%d+d0d1Z-edJe%d+d2d3Z.edKe%d+d4d5Z/edLe%d+d6d7Z0edMe%d+d8d9Z1edNe%d+d:d;Z2edOe%d+d<d=Z3edPe%d+d>d?Z4edQe%d+d@dAZ5edRe%d+dBdCZ6dS )Sa[   FocalNet

As described in `Focal Modulation Networks` - https://arxiv.org/abs/2203.11926

Significant modifications and refactoring from the original impl at https://github.com/microsoft/FocalNet

This impl is/has:
* fully convolutional, NCHW tensor layout throughout, seemed to have minimal performance impact but more flexible
* re-ordered downsample / layer so that striding always at beginning of layer (stage)
* no input size constraints or input resolution/H/W tracking through the model
* torchscript fixed and a number of quirks cleaned up
* feature extraction support via `features_only=True`
    )partial)CallableOptionalTupleNIMAGENET_DEFAULT_MEANIMAGENET_DEFAULT_STD)MlpDropPathLayerNorm2dtrunc_normal_ClassifierHeadNormMlpClassifierHead   )build_model_with_cfg)named_apply)generate_default_cfgsregister_modelFocalNetc                
       sF   e Zd Zdddddefeeeeeeeed fddZdd	 Z	  Z
S )
FocalModulation   TF        )dimfocal_levelfocal_factorbiasuse_post_normnormalize_modulator	proj_drop
norm_layerc
                    s&  t    || _|| _|| _|| _|| _|| _||| jd g| _t	j
|d| | jd  d|d| _t	j
||d|d| _t	 | _t	j
||dd| _t	|| _t	 | _g | _t| jD ]N}
| j|
 | j }| jt	t	j
|||||d ddt	  | j| q| jr|	|nt	 | _d S )Nr   r   )kernel_sizer   )r    F)r    groupspaddingr   )super__init__r   focal_windowr   r   r   r   input_splitnnConv2dfhGELUactprojZDropoutr   
ModuleListfocal_layersZkernel_sizesrangeappend
SequentialIdentitynorm)selfr   r%   r   r   r   r   r   r   r   kr    	__class__ ]/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/timm/models/focalnet.pyr$   %   s.    
"


zFocalModulation.__init__c           
      C   s   |  |}t|| jd\}}}d}t| jD ]0\}}||}|||d d ||d f   }q.| |jddd}|||d d | jd f   }| j	r|| jd  }|| 
| }	| |	}	| |	}	| |	}	|	S )Nr   r   )r      T)Zkeepdim)r)   torchsplitr&   	enumerater/   r,   meanr   r   r*   r4   r-   r   )
r5   xqctxZgatesZctx_alllZfocal_layerZ
ctx_globalZx_outr9   r9   r:   forwardM   s    
"


zFocalModulation.forward)__name__
__module____qualname__r   intboolfloatr   r$   rD   __classcell__r9   r9   r7   r:   r   $   s"   (r   c                       s&   e Zd Zd fdd	Zdd Z  ZS )LayerScale2dh㈵>Fc                    s*   t    || _t|t| | _d S N)r#   r$   inplacer'   	Parameterr<   Zonesgamma)r5   r   Zinit_valuesrO   r7   r9   r:   r$   i   s    
zLayerScale2d.__init__c                 C   s*   | j dddd}| jr"||S || S )Nr   )rQ   viewrO   mul_)r5   r@   rQ   r9   r9   r:   rD   n   s    zLayerScale2d.forward)rM   F)rE   rF   rG   r$   rD   rK   r9   r9   r7   r:   rL   h   s   rL   c                       s^   e Zd ZdZdddddddddejefeeeee	e	e	eeee
e
d fd	d
Zdd Z  ZS )FocalNetBlockz% Focal Modulation Network Block.
          @r   r;   F-C6?r   )r   	mlp_ratior   r%   r   use_post_norm_in_modulationr   layerscale_valuer   	drop_path	act_layerr   c              	      s(  t    || _|| _|| _|| _|| _|s4||nt | _	t
||| j|||	|d| _|rd||nt | _|durt||nt | _|
dkrt|
nt | _|s||nt | _t|t|| ||	dd| _|r||nt | _|durt||nt | _|
dkrt|
nt | _dS )ap  
        Args:
            dim: Number of input channels.
            mlp_ratio: Ratio of mlp hidden dim to embedding dim.
            focal_level: Number of focal levels.
            focal_window: Focal window size at first focal level.
            use_post_norm: Whether to use layer norm after modulation.
            use_post_norm_in_modulation: Whether to use layer norm in modulation.
            layerscale_value: Initial layerscale value.
            proj_drop: Dropout rate.
            drop_path: Stochastic depth rate.
            act_layer: Activation layer.
            norm_layer: Normalization layer.
        )r%   r   r   r   r   r   Nr   T)Zin_featuresZhidden_featuresr\   ZdropZuse_conv)r#   r$   r   rX   r%   r   r   r'   r3   norm1r   
modulation
norm1_postrL   ls1r
   
drop_path1norm2r	   rH   mlp
norm2_postls2
drop_path2)r5   r   rX   r   r%   r   rY   r   rZ   r   r[   r\   r   r7   r9   r:   r$   w   s<    
	
zFocalNetBlock.__init__c                 C   s`   |}|  |}| |}| |}|| | | }|| | | | | 	| }|S rN   )
r]   r^   r_   ra   r`   rf   re   rd   rc   rb   )r5   r@   Zshortcutr9   r9   r:   rD      s    


&zFocalNetBlock.forward)rE   rF   rG   __doc__r'   r+   r   rH   rJ   rI   r   r$   rD   rK   r9   r9   r7   r:   rU   s   s6   ?rU   c                       sv   e Zd ZdZdddddddddddefeeeeeeeeeeeeeeed fd	d
Z	e
jjdddZdd Z  ZS )FocalNetStagez4 A basic Focal Transformer layer for one stage.
    rV   Tr   FrW   r   r   out_dimdepthrX   
downsampler   r%   use_overlap_downr   rY   r   rZ   r   r[   r   c                    sv   t    || _|| _d| _|r6t|d|d| _n
t | _t	 	
fddt
|D | _dS )a8  
        Args:
            dim: Number of input channels.
            out_dim: Number of output channels.
            depth: Number of blocks.
            mlp_ratio: Ratio of mlp hidden dim to embedding dim.
            downsample: Downsample layer at start of the layer.
            focal_level: Number of focal levels
            focal_window: Focal window size at first focal level
            use_overlap_down: User overlapped convolution in downsample layer.
            use_post_norm: Whether to use layer norm after modulation.
            use_post_norm_in_modulation: Whether to use layer norm in modulation.
            layerscale_value: Initial layerscale value
            proj_drop: Dropout rate for projections.
            drop_path: Stochastic depth rate.
            norm_layer: Normalization layer.
        Fr   in_chsout_chsstrideoverlapr   c                    s<   g | ]4}t 	
t tr. | n d qS ))r   rX   r   r%   r   rY   r   rZ   r   r[   r   )rU   
isinstancelist.0ir[   r   r%   rZ   rX   r   r   rj   r   r   rY   r9   r:   
<listcomp>   s   z*FocalNetStage.__init__.<locals>.<listcomp>N)r#   r$   r   rk   grad_checkpointing
Downsamplerl   r'   r3   r.   r0   blocks)r5   r   rj   rk   rX   rl   r   r%   rm   r   rY   r   rZ   r   r[   r   r7   rx   r:   r$      s     #


"zFocalNetStage.__init__c                 C   s
   || _ d S rN   )rz   )r5   enabler9   r9   r:   set_grad_checkpointing  s    z$FocalNetStage.set_grad_checkpointingc                 C   s@   |  |}| jD ]*}| jr2tj s2t||}q||}q|S rN   )rl   r|   rz   r<   jitZis_scripting
checkpoint)r5   r@   Zblkr9   r9   r:   rD     s    


zFocalNetStage.forward)T)rE   rF   rG   rg   r   rH   rJ   rI   r   r$   r<   r   ignorer~   rD   rK   r9   r9   r7   r:   rh      sB   Drh   c                       s8   e Zd Zd	eeeeee d fddZdd Z  Z	S )
r{      FNrn   c                    s~   t    || _d}|}|rJ|dv s(J |dkr:d\}}n|dkrJd\}}tj|||||d| _|durp||nt | _dS )	a  

        Args:
            in_chs: Number of input image channels.
            out_chs: Number of linear projection output channels.
            stride: Downsample stride.
            overlap: Use overlapping convolutions if True.
            norm_layer: Normalization layer.
        r   )r   r   r   )   r   r   )r;   r   )r    rq   r"   N)r#   r$   rq   r'   r(   r-   r3   r4   )r5   ro   rp   rq   rr   r   r"   r    r7   r9   r:   r$     s    

zDownsample.__init__c                 C   s   |  |}| |}|S rN   )r-   r4   r5   r@   r9   r9   r:   rD   ;  s    

zDownsample.forward)r   FN)
rE   rF   rG   rH   rI   r   r   r$   rD   rK   r9   r9   r7   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dddddeeddfeeeeeedf e	eedf eedf e
e
e
e
ee e	ee	 e
e
e
ed fddZejjdd Zejjd'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   z," Focal Modulation Networks (FocalNets)
    r;     avg`   r   r      r   rV   )r   r   r   r   r;   r;   r;   r;   FN      ?r   g?rM   )Zeps.)in_chansnum_classesglobal_pool	embed_dimdepthsrX   focal_levelsfocal_windowsrm   r   rY   r   head_hidden_sizehead_init_scalerZ   	drop_rateproj_drop_ratedrop_path_rater   c                    s  t    t|| _ fddt| jD  || _ | _ d | _g | _t	| d |	|d| _
 d }dd td|t|D }g }t| jD ]} | }t|||| ||dk|| || |	|
|||||t|d| t|d|d   |d	}|}||g7 }|  jt|d
d|  d| dg7  _qtj| | _|rdt | _t| j|||||d| _n || j| _t| j|||d| _ttt|d|  dS )a`  
        Args:
            in_chans: Number of input image channels.
            num_classes: Number of classes for classification head.
            embed_dim: Patch embedding dimension.
            depths: Depth of each Focal Transformer layer.
            mlp_ratio: Ratio of mlp hidden dim to embedding dim.
            focal_levels: How many focal levels at all stages. Note that this excludes the finest-grain level.
            focal_windows: The focal window size at all stages.
            use_overlap_down: Whether to use convolutional embedding.
            use_post_norm: Whether to use layernorm after modulation (it helps stablize training of large models)
            layerscale_value: Value for layer scale.
            drop_rate: Dropout rate.
            drop_path_rate: Stochastic depth rate.
            norm_layer: Normalization layer.
        c                    s   g | ]} d |  qS )r   r9   ru   r   r9   r:   ry   n      z%FocalNet.__init__.<locals>.<listcomp>rR   r   )ro   rp   rr   r   c                 S   s   g | ]}|  qS r9   )item)rv   r@   r9   r9   r:   ry   }  r   Nr   ri   r   r   layers.)Znum_chsZ	reductionmodule)Zhidden_size	pool_typer   r   )r   r   )r   )r#   r$   lenZ
num_layersr0   r   r   Znum_featuresZfeature_infor{   stemr<   Zlinspacesumrh   dictr'   r2   layersr3   r4   r   headr   r   r   _init_weights)r5   r   r   r   r   r   rX   r   r   rm   r   rY   r   r   r   rZ   r   r   r   r   Zin_dimZdprr   Zi_layerrj   Zlayerr7   r   r:   r$   E  sr    &


&
*

	zFocalNet.__init__c                 C   s   dhS )N r9   r5   r9   r9   r:   no_weight_decay  s    zFocalNet.no_weight_decayc                 C   s   t d|rddgng ddS )Nz^stem)z^layers\.(\d+)Nz^norm)i ))z^layers\.(\d+).downsample)r   )z^layers\.(\d+)\.\w+\.(\d+)Nr   )r   r|   )r   )r5   Zcoarser9   r9   r:   group_matcher  s    zFocalNet.group_matcherTc                 C   s"   || _ | jD ]}|j|d qd S )N)r}   )rz   r   r~   )r5   r}   rC   r9   r9   r:   r~     s    
zFocalNet.set_grad_checkpointingc                 C   s   | j jS rN   )r   Zfcr   r9   r9   r:   get_classifier  s    zFocalNet.get_classifierc                 C   s   | j j||d d S )N)r   )r   reset)r5   r   r   r9   r9   r:   reset_classifier  s    zFocalNet.reset_classifierc                 C   s"   |  |}| |}| |}|S rN   )r   r   r4   r   r9   r9   r:   forward_features  s    


zFocalNet.forward_features
pre_logitsc                 C   s   | j ||dS )Nr   )r   )r5   r@   r   r9   r9   r:   forward_head  s    zFocalNet.forward_headc                 C   s   |  |}| |}|S rN   )r   r   r   r9   r9   r:   rD     s    

zFocalNet.forward)F)T)N)F)rE   rF   rG   rg   r   r   rH   strr   rJ   rI   r   r   r$   r<   r   r   r   r   r~   r   r   r   r   rD   rK   r9   r9   r7   r:   r   A  sj   



h


r   c                 C   s   t | tjr4t| jdd | jd urtj| j nZt | tjrt| jdd | jd urftj| j |rd|v r| jj	
| | jj	
| d S )Ng{Gz?)stdhead.fc)rs   r'   r(   r   Zweightr   initZzeros_ZLineardatarT   )r   namer   r9   r9   r:   r     s    

r   r   c                 K   s    | dddddt tdddd	|S )
Nr   )r;      r   )r   r   g?Zbicubicz	stem.projr   Zmit)urlr   
input_size	pool_sizecrop_pctinterpolationr?   r   Z
first_conv
classifierlicenser   )r   kwargsr9   r9   r:   _cfg  s    r   ztimm/)	hf_hub_id)r;     r   )   r   iRU  )r   r   r   r   r   )r   r   )zfocalnet_tiny_srf.ms_in1kzfocalnet_small_srf.ms_in1kzfocalnet_base_srf.ms_in1kzfocalnet_tiny_lrf.ms_in1kzfocalnet_small_lrf.ms_in1kzfocalnet_base_lrf.ms_in1kzfocalnet_large_fl3.ms_in22kzfocalnet_large_fl4.ms_in22kzfocalnet_xlarge_fl3.ms_in22kzfocalnet_xlarge_fl4.ms_in22kzfocalnet_huge_fl3.ms_in22kzfocalnet_huge_fl4.ms_in22k)modelc                 C   s   |  d| } d| v r| S dd l}i }| }|  D ]\}}|dd|}|dd}|dd	d
 |}d|v r||vr|dd|}|dd}|dd}||v r||  | kr|| j|jkr||| j}|||< q4|S )Nr   zstem.proj.weightr   zgamma_([0-9])z
ls\1.gammaZpatch_embedr   zlayers.(\d+).downsamplec                 S   s   dt | dd  dS )Nr   r   z.downsample)rH   group)r@   r9   r9   r:   <lambda>!  r   z&checkpoint_filter_fn.<locals>.<lambda>r4   znorm([0-9])znorm\1_postzln.znorm.r   r   )	getre
state_dictitemssubreplaceZnumelshapeZreshape)r   r   r   Zout_dictZ	dest_dictr6   vr9   r9   r:   checkpoint_filter_fn  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 rN   r9   )rv   rw   _r9   r9   r:   	<genexpr>-  r   z#_create_focalnet.<locals>.<genexpr>r   )r   r   r;   r   out_indicesT)Zflatten_sequentialr   )Zpretrained_filter_fnZfeature_cfg)tupler>   r   popr   r   r   r   )variant
pretrainedr   Zdefault_out_indicesr   r   r9   r9   r:   _create_focalnet,  s    
r   )returnc                 K   s*   t f g ddd|}tdd| i|S )Nr   r   r   r   focalnet_tiny_srfr   )r   r   r   r   r   Zmodel_kwargsr9   r9   r:   r   8  s    r   c                 K   s*   t f g ddd|}tdd| i|S )Nr   r      r   r   r   focalnet_small_srfr   )r   r   r   r9   r9   r:   r   >  s    r   c                 K   s*   t f g ddd|}tdd| i|S )Nr      r   focalnet_base_srfr   )r   r   r   r9   r9   r:   r   D  s    r   c                 K   s0   t f g ddg dd|}tdd| i|S )Nr   r   r   r   r   r   focalnet_tiny_lrfr   )r   r   r   r9   r9   r:   r   J  s    r   c                 K   s0   t f g ddg dd|}tdd| i|S )Nr   r   r   r   focalnet_small_lrfr   )r   r   r   r9   r9   r:   r   P  s    r   c                 K   s0   t f g ddg dd|}tdd| i|S )Nr   r   r   r   focalnet_base_lrfr   )r   r   r   r9   r9   r:   r   V  s    r   c              
   K   s>   t f g ddg ddgd dddd|}tdd
| i|S )Nr      r      r   TrW   r   r   r   r   r   rm   rZ   focalnet_large_fl3r   )r   r   r   r9   r9   r:   r   ]  s    r   c              	   K   s6   t f g ddg ddddd|}td	d| i|S )
Nr   r   r   r   r   r   TrW   r   r   r   r   rm   rZ   focalnet_large_fl4r   )r   r   r   r9   r9   r:   r   e  s    r   c              
   K   s>   t f g ddg ddgd dddd|}tdd
| i|S )Nr      r   r   r   TrW   r   focalnet_xlarge_fl3r   )r   r   r   r9   r9   r:   r   m  s    r   c              	   K   s6   t f g ddg ddddd|}td	d| i|S )
Nr   r   r   TrW   r   focalnet_xlarge_fl4r   )r   r   r   r9   r9   r:   r   u  s    r   c                 K   s@   t f g ddg ddgd ddddd|}tdd
| i|S )Nr   `  r   r;   r   TrW   )r   r   r   r   r   rY   rm   rZ   focalnet_huge_fl3r   )r   r   r   r9   r9   r:   r   }  s    r   c              
   K   s8   t f g ddg dddddd|}td	d| i|S )
Nr   r   r   TrW   )r   r   r   r   rY   rm   rZ   focalnet_huge_fl4r   )r   r   r   r9   r9   r:   r     s    r   )Nr   )r   )F)F)F)F)F)F)F)F)F)F)F)F)F)7rg   	functoolsr   typingr   r   r   r<   Ztorch.nnr'   Ztorch.utils.checkpointutilsr   Z	timm.datar   r   Ztimm.layersr	   r
   r   r   r   r   Z_builderr   Z_manipulater   	_registryr   r   __all__Moduler   rL   rU   rh   r{   r   r   r   Zdefault_cfgsr   r   r   r   r   r   r   r   r   r   r   r   r   r   r9   r9   r9   r:   <module>   s    DRV& 

#
