a
    d^                     @   s  d Z ddlZddlmZ ddl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 ddlmZmZ dd	lmZmZmZ d
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"dleje#e$dddZ%dd Z&dmddZ'dnd d!Z(ee( e( e( e(d"d#d$e(d"d%d&d'e( e(d"d(d$e(d"d)d&d'e(d"d*d+d,d-d.d/d0e(d"d1d+d,d-d.d2e(ee	d3e(d"d4ee	d5e(d"d6ee	d5e(d"d7ee	d5e(d"d8ee	d5e(d"d9ee	d5e(d"d:ee	d5e(d"d;ee	d5e(d"d<ee	d5e(d"d=ee	d5e(d"d>ee	d5e(d"d?ee	d5e(d"d@ee	d5e( e(d"dAd$e( dBZ)edoe"dCdDdEZ*edpe"dCdFdGZ+edqe"dCdHdIZ,edre"dCdJdKZ-edse"dCdLdMZ.edte"dCdNdOZ/edue"dCdPdQZ0edve"dCdRdSZ1edwe"dCdTdUZ2edxe"dCdVdWZ3edye"dCdXdYZ4edze"dCdZd[Z5ed{e"dCd\d]Z6ed|e"dCd^d_Z7ed}e"dCd`daZ8ee9dbdcdddedfdgdhdidjdUdWdk dS )~uj   MLP-Mixer, ResMLP, and gMLP in PyTorch

This impl originally based on MLP-Mixer paper.

Official JAX impl: https://github.com/google-research/vision_transformer/blob/linen/vit_jax/models_mixer.py

Paper: 'MLP-Mixer: An all-MLP Architecture for Vision' - https://arxiv.org/abs/2105.01601

@article{tolstikhin2021,
  title={MLP-Mixer: An all-MLP Architecture for Vision},
  author={Tolstikhin, Ilya and Houlsby, Neil and Kolesnikov, Alexander and Beyer, Lucas and Zhai, Xiaohua and Unterthiner,
        Thomas and Yung, Jessica and Keysers, Daniel and Uszkoreit, Jakob and Lucic, Mario and Dosovitskiy, Alexey},
  journal={arXiv preprint arXiv:2105.01601},
  year={2021}
}

Also supporting ResMlp, and a preliminary (not verified) implementations of gMLP

Code: https://github.com/facebookresearch/deit
Paper: `ResMLP: Feedforward networks for image classification...` - https://arxiv.org/abs/2105.03404
@misc{touvron2021resmlp,
      title={ResMLP: Feedforward networks for image classification with data-efficient training},
      author={Hugo Touvron and Piotr Bojanowski and Mathilde Caron and Matthieu Cord and Alaaeldin El-Nouby and
        Edouard Grave and Armand Joulin and Gabriel Synnaeve and Jakob Verbeek and Hervé Jégou},
      year={2021},
      eprint={2105.03404},
}

Paper: `Pay Attention to MLPs` - https://arxiv.org/abs/2105.08050
@misc{liu2021pay,
      title={Pay Attention to MLPs},
      author={Hanxiao Liu and Zihang Dai and David R. So and Quoc V. Le},
      year={2021},
      eprint={2105.08050},
}

A thank you to paper authors for releasing code and weights.

Hacked together by / Copyright 2021 Ross Wightman
    N)partial)IMAGENET_DEFAULT_MEANIMAGENET_DEFAULT_STD)
PatchEmbedMlpGluMlpGatedMlpDropPathlecun_normal_	to_2tuple   )build_model_with_cfg)named_applycheckpoint_seq)generate_default_cfgsregister_modelregister_model_deprecations
MixerBlockMlpMixerc                       sB   e Zd ZdZdeeejddejddf fdd	Z	dd	 Z
  ZS )
r   z Residual Block w/ token mixing and channel MLPs
    Based on: 'MLP-Mixer: An all-MLP Architecture for Vision' - https://arxiv.org/abs/2105.01601
          ?      @ư>Zeps        c	                    sz   t     fddt|D \}	}
| | _|||	||d| _|dkrPt|nt | _| | _	| |
||d| _
d S )Nc                    s   g | ]}t |  qS  )int).0xdimr   ^/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/timm/models/mlp_mixer.py
<listcomp>H       z'MixerBlock.__init__.<locals>.<listcomp>	act_layerdropr   )super__init__r   norm1
mlp_tokensr	   nnIdentity	drop_pathnorm2mlp_channels)selfr    seq_len	mlp_ratio	mlp_layer
norm_layerr%   r&   r-   Z
tokens_dimZchannels_dim	__class__r   r!   r(   <   s    


zMixerBlock.__init__c              	   C   sH   ||  | | |dddd }||  | | | }|S Nr      )r-   r*   r)   	transposer/   r.   r0   r   r   r   r!   forwardO   s    *zMixerBlock.forward)__name__
__module____qualname____doc__r   r   r+   	LayerNormGELUr(   r;   __classcell__r   r   r5   r!   r   8   s   c                       s$   e Zd Z fddZdd Z  ZS )Affinec                    s>   t    ttdd|f| _ttdd|f| _d S )Nr   )	r'   r(   r+   	Parametertorchonesalphazerosbeta)r0   r    r5   r   r!   r(   V   s    
zAffine.__init__c                 C   s   t | j| j|S N)rE   ZaddcmulrI   rG   r:   r   r   r!   r;   [   s    zAffine.forward)r<   r=   r>   r(   r;   rB   r   r   r5   r!   rC   U   s   rC   c                       s:   e Zd ZdZdeeejdddf fdd	Zdd Z	  Z
S )	ResBlockz Residual MLP block w/ LayerScale and Affine 'norm'

    Based on: `ResMLP: Feedforward networks for image classification...` - https://arxiv.org/abs/2105.03404
       g-C6?r   c
                    s   t    t|| }
||| _t||| _|	dkr>t|	nt | _	||| _
|||
||d| _t|t| | _t|t| | _d S )Nr   r$   )r'   r(   r   r)   r+   Linearlinear_tokensr	   r,   r-   r.   r/   rD   rE   rF   ls1ls2)r0   r    r1   r2   r3   r4   r%   init_valuesr&   r-   channel_dimr5   r   r!   r(   d   s    


zResBlock.__init__c              
   C   sT   ||  | j| | |dddd  }||  | j| | |  }|S r7   )r-   rO   rN   r)   r9   rP   r/   r.   r:   r   r   r!   r;   z   s    0 zResBlock.forward)r<   r=   r>   r?   r   rC   r+   rA   r(   r;   rB   r   r   r5   r!   rK   _   s   rK   c                       s6   e Zd ZdZejf fdd	Zdd Zdd Z  Z	S )SpatialGatingUnitzc Spatial Gating Unit

    Based on: `Pay Attention to MLPs` - https://arxiv.org/abs/2105.08050
    c                    s.   t    |d }||| _t||| _d S )Nr8   )r'   r(   normr+   rM   proj)r0   r    r1   r4   Zgate_dimr5   r   r!   r(      s    

zSpatialGatingUnit.__init__c                 C   s(   t jj| jjdd t j| jj d S )Nr   std)r+   initnormal_rU   weightones_biasr0   r   r   r!   init_weights   s    zSpatialGatingUnit.init_weightsc                 C   s>   |j ddd\}}| |}| |dd}||dd S )Nr8   r   )chunkrT   rU   r9   )r0   r   uvr   r   r!   r;      s    
zSpatialGatingUnit.forward)
r<   r=   r>   r?   r+   r@   r(   r^   r;   rB   r   r   r5   r!   rS      s   rS   c                       sB   e Zd ZdZdeeejddejddf fdd	Z	dd	 Z
  ZS )
SpatialGatingBlockzp Residual Block w/ Spatial Gating

    Based on: `Pay Attention to MLPs` - https://arxiv.org/abs/2105.08050
    rL   r   r   r   c	                    s^   t    t|| }	||| _tt|d}
|||	||
|d| _|dkrPt|nt	 | _
d S )N)r1   )r%   Z
gate_layerr&   r   )r'   r(   r   rT   r   rS   r/   r	   r+   r,   r-   )r0   r    r1   r2   r3   r4   r%   r&   r-   rR   Zsgur5   r   r!   r(      s    

zSpatialGatingBlock.__init__c                 C   s   ||  | | | }|S rJ   )r-   r/   rT   r:   r   r   r!   r;      s    zSpatialGatingBlock.forward)r<   r=   r>   r?   r   r   r+   r@   rA   r(   r;   rB   r   r   r5   r!   rd      s   rd   c                       s   e Zd Zdddddddeeeejdd	ejd
d
d
dddf fdd	Z	e
jjd"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                    r   r   r   r   Favgc              
      s   t    |_|_ __d_t||||r:nd d_t	j
 f	ddt|D  __t	|_|dkrt	jnt	 _j|d d S )NF)img_size
patch_sizein_chans	embed_dimr4   c                    s(   g | ] }j j d qS ))r3   r4   r%   r&   r-   )stemZnum_patches)r   _	r%   block_layerdrop_path_ratero   r3   r2   r4   proj_drop_rater0   r   r!   r"      s   z%MlpMixer.__init__.<locals>.<listcomp>r   )nlhb)r'   r(   num_classesglobal_poolZnum_featuresro   grad_checkpointingr   rp   r+   Z
SequentialrangeblocksrT   ZDropout	head_droprM   r,   headr^   )r0   rw   rl   rn   rm   
num_blocksro   r2   rs   r3   r4   r%   Z	drop_rateru   rt   rv   Z	stem_normrx   r5   rr   r!   r(      s&    



 zMlpMixer.__init__c                 C   s.   |rt | j nd}ttt|d| d d S )Nr   )	head_bias)module)mathlogrw   r   r   _init_weights)r0   rv   r   r   r   r!   r^      s    zMlpMixer.init_weightsc                 C   s   t dddgdS )Nz^stem)z^blocks\.(\d+)N)z^norm)i )rp   r{   )dict)r0   Zcoarser   r   r!   group_matcher   s    zMlpMixer.group_matcherTc                 C   s
   || _ d S rJ   )ry   )r0   enabler   r   r!   set_grad_checkpointing   s    zMlpMixer.set_grad_checkpointingc                 C   s   | j S rJ   )r}   r]   r   r   r!   get_classifier   s    zMlpMixer.get_classifierNc                 C   sD   || _ |d ur |dv sJ || _|dkr6t| j|nt | _d S )N) rk   r   )rw   rx   r+   rM   ro   r,   r}   )r0   rw   rx   r   r   r!   reset_classifier   s
    zMlpMixer.reset_classifierc                 C   s@   |  |}| jr(tj s(t| j|}n
| |}| |}|S rJ   )rp   ry   rE   jitZis_scriptingr   r{   rT   r:   r   r   r!   forward_features  s    


zMlpMixer.forward_features)
pre_logitsc                 C   s2   | j dkr|jdd}| |}|r(|S | |S )Nrk   r   r   )rx   meanr|   r}   )r0   r   r   r   r   r!   forward_head  s    

zMlpMixer.forward_headc                 C   s   |  |}| |}|S rJ   )r   r   r:   r   r   r!   r;     s    

zMlpMixer.forward)F)F)T)N)F)r<   r=   r>   r   r   r   r+   r@   rA   r(   rE   r   ignorer^   r   r   r   r   r   boolr   r;   rB   r   r   r5   r!   r      s<   4

	r   F)r   namer   c                 C   s   t | tjr|dr6tj| j tj| j| nj|r^t	| j | jdurtj| j nBtj
| j | jdurd|v rtjj| jdd ntj| j nzt | tjrt	| j | jdurtj| j nJt | tjtjtjfrtj| j tj| j nt| dr|   dS )zA Mixer weight initialization (trying to match Flax defaults)
    r}   NZmlpr   rV   r^   )
isinstancer+   rM   
startswithrX   Zzeros_rZ   Z	constant_r\   r
   Zxavier_uniform_rY   ZConv2dr@   ZBatchNorm2dZ	GroupNormr[   hasattrr^   )r   r   r   Zflaxr   r   r!   r     s,    





r   c                 C   s   d| v r|i }|   D ]b\}}|dd}|dd}|dd}|dd	}|d
s`|drn|ddd}|||< q|S | S )z Remap checkpoints if needed zpatch_embed.proj.weightzpatch_embed.zstem.zattn.zlinear_tokens.zmlp.zmlp_channels.Zgamma_Zlsz.alphaz.betar   r_   )itemsreplaceendswithZreshape)Z
state_dictmodelZout_dictkrc   r   r   r!   checkpoint_filter_fn;  s    
r   c                 K   s0   | dd rtdtt| |fdti|}|S )NZfeatures_onlyz3features_only not implemented for MLP-Mixer models.Zpretrained_filter_fn)getRuntimeErrorr   r   r   )variant
pretrainedkwargsr   r   r   r!   _create_mixerL  s    r   r   c                 K   s    | ddd dddddddd	|S )
Nre   )rg   rf   rf         ?ZbicubicT)r   r   r   z	stem.projr}   )urlrw   Z
input_sizeZ	pool_sizecrop_pctinterpolationZfixed_input_sizer   rW   Z
first_conv
classifierr   )r   r   r   r   r!   _cfgZ  s    r   ztimm/zlhttps://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_mixer_b16_224-76587d61.pth)	hf_hub_idr   zrhttps://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_mixer_b16_224_in21k-617b3de2.pthiSU  )r   r   rw   zlhttps://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_mixer_l16_224-92f9adc4.pthzrhttps://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_mixer_l16_224_in21k-846aa33c.pthzvhttps://github.com/rwightman/pytorch-image-models/releases/download/v0.1-tresnet/mixer_b16_224_miil_in21k-2a558a71.pth)r   r   r   )      ?r   r   r   Zbilineari+  )r   r   r   rW   r   r   rw   zphttps://github.com/rwightman/pytorch-image-models/releases/download/v0.1-tresnet/mixer_b16_224_miil-9229a591.pth)r   r   r   rW   r   r   )r   rW   zohttps://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/gmixer_24_224_raa-7daf7ae6.pth)r   r   r   rW   z9https://dl.fbaipublicfiles.com/deit/resmlp_12_no_dist.pthz9https://dl.fbaipublicfiles.com/deit/resmlp_24_no_dist.pthz9https://dl.fbaipublicfiles.com/deit/resmlp_36_no_dist.pthz:https://dl.fbaipublicfiles.com/deit/resmlpB_24_no_dist.pthz6https://dl.fbaipublicfiles.com/deit/resmlp_12_dist.pthz6https://dl.fbaipublicfiles.com/deit/resmlp_24_dist.pthz6https://dl.fbaipublicfiles.com/deit/resmlp_36_dist.pthz7https://dl.fbaipublicfiles.com/deit/resmlpB_24_dist.pthz6https://dl.fbaipublicfiles.com/deit/resmlpB_24_22k.pthz6https://dl.fbaipublicfiles.com/deit/resmlp_12_dino.pthz6https://dl.fbaipublicfiles.com/deit/resmlp_24_dino.pthznhttps://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/gmlp_s16_224_raa-10536d42.pth)zmixer_s32_224.untrainedzmixer_s16_224.untrainedzmixer_b32_224.untrained mixer_b16_224.goog_in21k_ft_in1kzmixer_b16_224.goog_in21kzmixer_l32_224.untrained mixer_l16_224.goog_in21k_ft_in1kzmixer_l16_224.goog_in21kmixer_b16_224.miil_in21k mixer_b16_224.miil_in21k_ft_in1kzgmixer_12_224.untrainedzgmixer_24_224.ra3_in1kzresmlp_12_224.fb_in1kzresmlp_24_224.fb_in1kzresmlp_36_224.fb_in1kzresmlp_big_24_224.fb_in1kresmlp_12_224.fb_distilled_in1kresmlp_24_224.fb_distilled_in1kresmlp_36_224.fb_distilled_in1k#resmlp_big_24_224.fb_distilled_in1k"resmlp_big_24_224.fb_in22k_ft_in1kzresmlp_12_224.fb_dinozresmlp_24_224.fb_dinozgmlp_ti16_224.untrainedzgmlp_s16_224.ra3_in1kzgmlp_b16_224.untrained)returnc                 K   s,   t f dddd|}tdd| i|}|S )zv Mixer-S/32 224x224
    Paper: 'MLP-Mixer: An all-MLP Architecture for Vision' - https://arxiv.org/abs/2105.01601
        ri   rj   rm   r~   ro   mixer_s32_224r   )r   r   r   r   r   Z
model_argsr   r   r   r!   r     s    r   c                 K   s,   t f dddd|}tdd| i|}|S )zw Mixer-S/16 224x224
    Paper:  'MLP-Mixer: An all-MLP Architecture for Vision' - https://arxiv.org/abs/2105.01601
    rh   ri   rj   r   mixer_s16_224r   )r   r   r   r   r   r!   r     s    r   c                 K   s,   t f dddd|}tdd| i|}|S )zw Mixer-B/32 224x224
    Paper:  'MLP-Mixer: An all-MLP Architecture for Vision' - https://arxiv.org/abs/2105.01601
    r         r   mixer_b32_224r   )r   r   r   r   r   r!   r     s    r   c                 K   s,   t f dddd|}tdd| i|}|S )z Mixer-B/16 224x224. ImageNet-1k pretrained weights.
    Paper:  'MLP-Mixer: An all-MLP Architecture for Vision' - https://arxiv.org/abs/2105.01601
    rh   r   r   r   mixer_b16_224r   )r   r   r   r   r   r!   r     s    r   c                 K   s,   t f dddd|}tdd| i|}|S )zx Mixer-L/32 224x224.
    Paper:  'MLP-Mixer: An all-MLP Architecture for Vision' - https://arxiv.org/abs/2105.01601
    r         r   mixer_l32_224r   )r   r   r   r   r   r!   r     s    r   c                 K   s,   t f dddd|}tdd| i|}|S )z Mixer-L/16 224x224. ImageNet-1k pretrained weights.
    Paper:  'MLP-Mixer: An all-MLP Architecture for Vision' - https://arxiv.org/abs/2105.01601
    rh   r   r   r   mixer_l16_224r   )r   r   r   r   r   r!   r     s    r   c              	   K   s4   t f ddddttjd|}tdd| i|}|S )	zV Glu-Mixer-12 224x224
    Experiment by Ross Wightman, adding SwiGLU to MLP-Mixer
    rh   r     r   r   rm   r~   ro   r2   r3   r%   gmixer_12_224r   )r   r   r   r+   ZSiLUr   r   r   r   r!   r     s    r   c              	   K   s4   t f ddddttjd|}tdd| i|}|S )	zV Glu-Mixer-24 224x224
    Experiment by Ross Wightman, adding SwiGLU to MLP-Mixer
    rh   r   r   r   r   gmixer_24_224r   )r   r   r   r   r   r!   r     s    r   c              	   K   s2   t f ddddttd|}tdd| i|}|S )	zx ResMLP-12
    Paper: `ResMLP: Feedforward networks for image classification...` - https://arxiv.org/abs/2105.03404
    rh   r   r   rL   rm   r~   ro   r2   rs   r4   resmlp_12_224r   )r   )r   rK   rC   r   r   r   r   r!   r     s    r   c              
   K   s:   t f ddddttddtd|}td
d	| i|}|S )zx ResMLP-24
    Paper: `ResMLP: Feedforward networks for image classification...` - https://arxiv.org/abs/2105.03404
    rh   r   r   rL   gh㈵>rQ   r   resmlp_24_224r   )r   r   r   rK   rC   r   r   r   r   r!   r   (  s    r   c              
   K   s:   t f ddddttddtd|}td
d	| i|}|S )zx ResMLP-36
    Paper: `ResMLP: Feedforward networks for image classification...` - https://arxiv.org/abs/2105.03404
    rh   $   r   rL   r   r   r   resmlp_36_224r   )r   r   r   r   r   r!   r   4  s    r   c              
   K   s:   t f ddddttddtd|}td
d	| i|}|S )zz ResMLP-B-24
    Paper: `ResMLP: Feedforward networks for image classification...` - https://arxiv.org/abs/2105.03404
    ri   r   r   rL   r   r   r   resmlp_big_24_224r   )r   r   r   r   r   r!   r   @  s    r   c              	   K   s2   t f ddddttd|}tdd| i|}|S )	zU gMLP-Tiny
    Paper: `Pay Attention to MLPs` - https://arxiv.org/abs/2105.08050
    rh            rm   r~   ro   r2   rs   r3   gmlp_ti16_224r   )r   r   rd   r   r   r   r   r   r!   r   L  s    
r   c              	   K   s2   t f ddddttd|}tdd| i|}|S )	zV gMLP-Small
    Paper: `Pay Attention to MLPs` - https://arxiv.org/abs/2105.08050
    rh   r      r   r   gmlp_s16_224r   )r   r   r   r   r   r!   r   X  s    
r   c              	   K   s2   t f ddddttd|}tdd| i|}|S )	zU gMLP-Base
    Paper: `Pay Attention to MLPs` - https://arxiv.org/abs/2105.08050
    rh   r   rj   r   r   gmlp_b16_224r   )r   r   r   r   r   r!   r   d  s    
r   r   r   r   r   r   r   r   r   r   )Zmixer_b16_224_in21kZmixer_l16_224_in21kZmixer_b16_224_miilZmixer_b16_224_miil_in21kZresmlp_12_distilled_224Zresmlp_24_distilled_224Zresmlp_36_distilled_224Zresmlp_big_24_distilled_224Zresmlp_big_24_224_in22ft1kZresmlp_12_224_dinoZresmlp_24_224_dino)r   F)F)r   )F)F)F)F)F)F)F)F)F)F)F)F)F)F)F):r?   r   	functoolsr   rE   Ztorch.nnr+   Z	timm.datar   r   Ztimm.layersr   r   r   r   r	   r
   r   Z_builderr   Z_manipulater   r   	_registryr   r   r   __all__Moduler   rC   rK   rS   rd   r   strfloatr   r   r   r   Zdefault_cfgsr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r<   r   r   r   r!   <module>   sH  ($
!f"



d						
