o
    Vh}                     @   s  U d dl Z d dl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Zd dlmZ ddlmZmZ ddlmZmZ ddlmZ d	d
lmZmZmZ d	dlmZ d	dlmZmZ g dZ G dd de
Z!G dd deZ"G dd dej#Z$G dd dej#Z%G dd dej#Z&de'de'de'de'de'dee de(ded e&fd!d"Z)d#eiZ*ee+ef e,d$< i e*d%d&d'Z-G d(d) d)eZ.G d*d+ d+eZ/G d,d- d-eZ0G d.d/ d/eZ1G d0d1 d1eZ2e ed2e.j3fd3dd4d5dee. de(ded e&fd6d7Z4e ed2e/j3fd3dd4d5dee/ de(ded e&fd8d9Z5e ed2e0j3fd3dd4d5dee0 de(ded e&fd:d;Z6e ed2e1j3fd3dd4d5dee1 de(ded e&fd<d=Z7e ed>d3dd4d5dee2 de(ded e&fd?d@Z8	A	BdJdCe'de'dDdEdFe+dGe(d dEfdHdIZ9dS )K    N)OrderedDict)partial)AnyCallableDictList
NamedTupleOptional   )Conv2dNormActivationMLP)ImageClassificationInterpolationMode)_log_api_usage_once   )register_modelWeightsWeightsEnum)_IMAGENET_CATEGORIES)_ovewrite_named_paramhandle_legacy_interface)VisionTransformerViT_B_16_WeightsViT_B_32_WeightsViT_L_16_WeightsViT_L_32_WeightsViT_H_14_Weightsvit_b_16vit_b_32vit_l_16vit_l_32vit_h_14c                   @   sV   e Zd ZU eed< eed< eed< ejZedej	f ed< ej
Zedej	f ed< dS )ConvStemConfigout_channelskernel_sizestride.
norm_layeractivation_layerN)__name__
__module____qualname__int__annotations__nnBatchNorm2dr&   r   ModuleReLUr'    r1   r1   Y/var/www/vscode/kcb/lib/python3.10/site-packages/torchvision/models/vision_transformer.pyr"       s   
 r"   c                       s>   e Zd ZdZdZdededef fddZ fdd	Z  Z	S )
MLPBlockzTransformer MLP block.r
   in_dimmlp_dimdropoutc                    sd   t  j|||gtjd |d |  D ]}t|tjr/tj|j	 |j
d ur/tjj|j
dd qd S )N)r'   inplacer6   ư>std)super__init__r-   GELUmodules
isinstanceLinearinitxavier_uniform_weightbiasnormal_)selfr4   r5   r6   m	__class__r1   r2   r<   -   s   
zMLPBlock.__init__c              	      s   | dd }|d u s|dk r<tdD ])}	dD ]$}
| d|	d  d|
 }| d|	  d|
 }||v r:||||< qqt ||||||| d S )Nversionr
   )rC   rD   linear_r   .   )getrangepopr;   _load_from_state_dict)rF   
state_dictprefixlocal_metadatastrictmissing_keysunexpected_keys
error_msgsrJ   itypeold_keynew_keyrH   r1   r2   rQ   6   s&   
zMLPBlock._load_from_state_dict)
r(   r)   r*   __doc___versionr+   floatr<   rQ   __classcell__r1   r1   rH   r2   r3   (   s
    	r3   c                       sd   e Zd ZdZeejddfdededededed	e	d
e
jjf f fddZde
jfddZ  ZS )EncoderBlockzTransformer encoder block.r8   eps	num_heads
hidden_dimr5   r6   attention_dropoutr&   .c                    sV   t    || _||| _tj|||dd| _t|| _||| _	t
|||| _d S )NT)r6   batch_first)r;   r<   rd   ln_1r-   MultiheadAttentionself_attentionDropoutr6   ln_2r3   mlp)rF   rd   re   r5   r6   rf   r&   rH   r1   r2   r<   Y   s   
	

zEncoderBlock.__init__inputc                 C   sj   t | dkd|j  | |}| j|||dd\}}| |}|| }| |}| |}|| S )NrM   2Expected (batch_size, seq_length, hidden_dim) got F)need_weights)	torch_assertdimshaperh   rj   r6   rl   rm   )rF   rn   x_yr1   r1   r2   forwardn   s   



zEncoderBlock.forwardr(   r)   r*   r]   r   r-   	LayerNormr+   r_   r   rq   r/   r<   Tensorrx   r`   r1   r1   rH   r2   ra   V   s"    	ra   c                       sl   e Zd ZdZeejddfdededededed	ed
ede	de
jjf f fddZde
jfddZ  ZS )Encoderz?Transformer Model Encoder for sequence to sequence translation.r8   rb   
seq_length
num_layersrd   re   r5   r6   rf   r&   .c	                    s~   t    ttd||jdd| _t|| _	t
 }	t|D ]}
t|||||||	d|
 < q!t|	| _||| _d S )Nr   g{Gz?r9   encoder_layer_)r;   r<   r-   	Parameterrq   emptyrE   pos_embeddingrk   r6   r   rO   ra   
Sequentiallayersln)rF   r}   r~   rd   re   r5   r6   rf   r&   r   rY   rH   r1   r2   r<   }   s   
zEncoder.__init__rn   c                 C   s<   t | dkd|j  || j }| | | |S )NrM   ro   )rq   rr   rs   rt   r   r   r   r6   )rF   rn   r1   r1   r2   rx      s   
zEncoder.forwardry   r1   r1   rH   r2   r|   z   s*    	r|   c                       s   e Zd ZdZddddeejdddfdeded	ed
edededededede	e de
dejjf de	ee  f fddZdejdejfddZdejfddZ  ZS )r   z;Vision Transformer as per https://arxiv.org/abs/2010.11929.        i  Nr8   rb   
image_size
patch_sizer~   rd   re   r5   r6   rf   num_classesrepresentation_sizer&   .conv_stem_configsc                    s  t    t|  t|| dkd || _|| _|| _|| _|| _	|| _
|	| _|
| _|| _|d urjt }d}t|D ]\}}|d| t||j|j|j|j|jd |j}q<|dtj||dd || _n
tjd|||d	| _|| d
 }ttdd|| _|d7 }t||||||||| _|| _t }|
d u rt ||	|d< nt ||
|d< t! |d< t |
|	|d< t|| _"t#| jtjr| jj$| jjd  | jjd  }tj%j&| jj't()d| d | jj*d urtj%+| jj* n5| jj,d ur.t#| jj,tjr.tj%j-| jj,j'dt()d| jj,j d | jj,j*d ur.tj%+| jj,j* t.| j"dr\t#| j"j/tj r\| j"j/j0}tj%j&| j"j/j't()d| d tj%+| j"j/j* t#| j"j1tj rytj%+| j"j1j' tj%+| j"j1j* d S d S )Nr   z&Input shape indivisible by patch size!rM   conv_bn_relu_)in_channelsr#   r$   r%   r&   r'   	conv_lastr   )r   r#   r$   )r   r#   r$   r%   r
   head
pre_logitsactr9   r   g       @)meanr:   )2r;   r<   r   rq   rr   r   r   re   r5   rf   r6   r   r   r&   r-   r   	enumerate
add_moduler   r#   r$   r%   r'   Conv2d	conv_projr   zerosclass_tokenr|   encoderr}   r   r@   Tanhheadsr?   r   rA   trunc_normal_rC   mathsqrtrD   zeros_r   rE   hasattrr   in_featuresr   )rF   r   r   r~   rd   re   r5   r6   rf   r   r   r&   r   seq_projprev_channelsrY   conv_stem_layer_configr}   heads_layersfan_inrH   r1   r2   r<      s   

   
 zVisionTransformer.__init__ru   returnc           	      C   s   |j \}}}}| j}t|| jkd| j d| d t|| jkd| j d| d || }|| }| |}||| j|| }|ddd}|S )NzWrong image height! Expected z	 but got !zWrong image width! Expected r   r
   r   )	rt   r   rq   rr   r   r   reshapere   permute)	rF   ru   nchwpn_hn_wr1   r1   r2   _process_input  s   ""
z VisionTransformer._process_inputc                 C   s^   |  |}|jd }| j|dd}tj||gdd}| |}|d d df }| |}|S )Nr   r   rs   )r   rt   r   expandrq   catr   r   )rF   ru   r   batch_class_tokenr1   r1   r2   rx   !  s   



zVisionTransformer.forward)r(   r)   r*   r]   r   r-   rz   r+   r_   r	   r   rq   r/   r   r"   r<   r{   r   rx   r`   r1   r1   rH   r2   r      sF    
	

ir   r   r~   rd   re   r5   weightsprogresskwargsr   c           
   	   K   s   |d ur*t |dt|jd  |jd d |jd d ksJ t |d|jd d  |dd}td|| ||||d|}	|rJ|	|j|d	d
 |	S )Nr   
categoriesmin_sizer   r   r      )r   r   r~   rd   re   r5   T)r   
check_hashr1   )r   lenmetarP   r   load_state_dictget_state_dict)
r   r~   rd   re   r5   r   r   r   r   modelr1   r1   r2   _vision_transformer4  s$   
 
r   r   _COMMON_METAz(https://github.com/facebookresearch/SWAGz:https://github.com/facebookresearch/SWAG/blob/main/LICENSE)recipelicensec                   @   s   e Zd Zedeeddi edddddd	d
idddddZedeeddej	di e
dddddd
idddddZedeeddej	di e
ddddddd
idddd dZeZd!S )"r   z9https://download.pytorch.org/models/vit_b_16-c867db91.pthr   	crop_sizei(r   r   zNhttps://github.com/pytorch/vision/tree/main/references/classification#vit_b_16ImageNet-1KgS㥛DT@g1ZW@zacc@1zacc@5gMb1@g(\t@
                These weights were trained from scratch by using a modified version of `DeIT
                <https://arxiv.org/abs/2012.12877>`_'s training recipe.
            
num_paramsr   r   _metrics_ops
_file_size_docsurl
transformsr   z>https://download.pytorch.org/models/vit_b_16_swag-9ac1b537.pth  r   resize_sizeinterpolationi^-)r   r   g~jtSU@giX@gˡEK@g|?5^t@
                These weights are learnt via transfer learning by end-to-end fine-tuning the original
                `SWAG <https://arxiv.org/abs/2201.08371>`_ weights on ImageNet-1K data.
            r   r   r   r   r   r   zAhttps://download.pytorch.org/models/vit_b_16_lc_swag-4e70ced5.pth+https://github.com/pytorch/vision/pull/5793gbX9xT@gQX@
                These weights are composed of the original frozen `SWAG <https://arxiv.org/abs/2201.08371>`_ trunk
                weights and a linear classifier learnt on top of them trained on ImageNet-1K data.
            r   r   r   r   r   r   r   Nr(   r)   r*   r   r   r   r   IMAGENET1K_V1r   BICUBIC_COMMON_SWAG_METAIMAGENET1K_SWAG_E2E_V1IMAGENET1K_SWAG_LINEAR_V1DEFAULTr1   r1   r1   r2   r   _  s    
r   c                   @   H   e Zd Zedeeddi edddddd	d
idddddZeZdS )r   z9https://download.pytorch.org/models/vit_b_32-d86f8d99.pthr   r   i1Br   zNhttps://github.com/pytorch/vision/tree/main/references/classification#vit_b_32r   g|?5^R@gW@r   gA`Т@gl	u@r   r   r   N	r(   r)   r*   r   r   r   r   r   r   r1   r1   r1   r2   r     *    
r   c                   @   s   e Zd Zedeedddi eddddd	d
didddddZedeeddej	di e
ddddddidddddZedeeddej	di e
dddddddiddd d!dZeZd"S )#r   z9https://download.pytorch.org/models/vit_l_16-852ce7e3.pthr      )r   r   i#r   zNhttps://github.com/pytorch/vision/tree/main/references/classification#vit_l_16r   g|?5^S@gFԨW@r   gףp=
N@g;O$@a  
                These weights were trained from scratch by using a modified version of TorchVision's
                `new training recipe
                <https://pytorch.org/blog/how-to-train-state-of-the-art-models-using-torchvision-latest-primitives/>`_.
            r   r   z>https://download.pytorch.org/models/vit_l_16_swag-4f3808c9.pth   r   i0)r   r   gjtV@gT㥛ĠX@gƟv@gy&11@r   r   zAhttps://download.pytorch.org/models/vit_l_16_lc_swag-4d563306.pthr   gMbXIU@g^I[X@r   r   Nr   r1   r1   r1   r2   r     s    r   c                   @   r   )r   z9https://download.pytorch.org/models/vit_l_32-c7638314.pthr   r   i[Er   zNhttps://github.com/pytorch/vision/tree/main/references/classification#vit_l_32r   g|?5>S@gGzDW@r   gK7.@gE@r   r   r   Nr   r1   r1   r1   r2   r     r   r   c                   @   s   e Zd Zedeeddejdi edddddd	id
ddddZ	edeeddejdi eddddddd	idddddZ
e	ZdS )r   z>https://download.pytorch.org/models/vit_h_14_swag-80465313.pth  r   i%)r   r   r   gS#V@g#~jX@r   g~jŏ@gK7I@r   r   r   zAhttps://download.pytorch.org/models/vit_h_14_lc_swag-c1eb923e.pthr   r   i@%r   gZd;OmU@gQnX@g=
ףpd@gIk֢@r   r   N)r(   r)   r*   r   r   r   r   r   r   r   r   r   r1   r1   r1   r2   r   2  sb    r   
pretrained)r   T)r   r   c              
   K   (   t | } tdddddd| |d|S )a  
    Constructs a vit_b_16 architecture from
    `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale <https://arxiv.org/abs/2010.11929>`_.

    Args:
        weights (:class:`~torchvision.models.ViT_B_16_Weights`, optional): The pretrained
            weights to use. See :class:`~torchvision.models.ViT_B_16_Weights`
            below for more details and possible values. By default, no pre-trained weights are used.
        progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True.
        **kwargs: parameters passed to the ``torchvision.models.vision_transformer.VisionTransformer``
            base class. Please refer to the `source code
            <https://github.com/pytorch/vision/blob/main/torchvision/models/vision_transformer.py>`_
            for more details about this class.

    .. autoclass:: torchvision.models.ViT_B_16_Weights
        :members:
                r   r~   rd   re   r5   r   r   Nr1   )r   verifyr   r   r   r   r1   r1   r2   r   k     
r   c              
   K   r   )a  
    Constructs a vit_b_32 architecture from
    `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale <https://arxiv.org/abs/2010.11929>`_.

    Args:
        weights (:class:`~torchvision.models.ViT_B_32_Weights`, optional): The pretrained
            weights to use. See :class:`~torchvision.models.ViT_B_32_Weights`
            below for more details and possible values. By default, no pre-trained weights are used.
        progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True.
        **kwargs: parameters passed to the ``torchvision.models.vision_transformer.VisionTransformer``
            base class. Please refer to the `source code
            <https://github.com/pytorch/vision/blob/main/torchvision/models/vision_transformer.py>`_
            for more details about this class.

    .. autoclass:: torchvision.models.ViT_B_32_Weights
        :members:
        r   r   r   r   Nr1   )r   r   r   r   r1   r1   r2   r     r   r   c              
   K   s(   t | } tdddddd| |d|S )a  
    Constructs a vit_l_16 architecture from
    `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale <https://arxiv.org/abs/2010.11929>`_.

    Args:
        weights (:class:`~torchvision.models.ViT_L_16_Weights`, optional): The pretrained
            weights to use. See :class:`~torchvision.models.ViT_L_16_Weights`
            below for more details and possible values. By default, no pre-trained weights are used.
        progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True.
        **kwargs: parameters passed to the ``torchvision.models.vision_transformer.VisionTransformer``
            base class. Please refer to the `source code
            <https://github.com/pytorch/vision/blob/main/torchvision/models/vision_transformer.py>`_
            for more details about this class.

    .. autoclass:: torchvision.models.ViT_L_16_Weights
        :members:
    r            r   Nr1   )r   r   r   r   r1   r1   r2   r     r   r   c              
   K   (   t | } tdddddd| |d|S )	a  
    Constructs a vit_l_32 architecture from
    `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale <https://arxiv.org/abs/2010.11929>`_.

    Args:
        weights (:class:`~torchvision.models.ViT_L_32_Weights`, optional): The pretrained
            weights to use. See :class:`~torchvision.models.ViT_L_32_Weights`
            below for more details and possible values. By default, no pre-trained weights are used.
        progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True.
        **kwargs: parameters passed to the ``torchvision.models.vision_transformer.VisionTransformer``
            base class. Please refer to the `source code
            <https://github.com/pytorch/vision/blob/main/torchvision/models/vision_transformer.py>`_
            for more details about this class.

    .. autoclass:: torchvision.models.ViT_L_32_Weights
        :members:
    r   r   r   r   r   r   Nr1   )r   r   r   r   r1   r1   r2   r      r   r    )r   Nc              
   K   r   )	a  
    Constructs a vit_h_14 architecture from
    `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale <https://arxiv.org/abs/2010.11929>`_.

    Args:
        weights (:class:`~torchvision.models.ViT_H_14_Weights`, optional): The pretrained
            weights to use. See :class:`~torchvision.models.ViT_H_14_Weights`
            below for more details and possible values. By default, no pre-trained weights are used.
        progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True.
        **kwargs: parameters passed to the ``torchvision.models.vision_transformer.VisionTransformer``
            base class. Please refer to the `source code
            <https://github.com/pytorch/vision/blob/main/torchvision/models/vision_transformer.py>`_
            for more details about this class.

    .. autoclass:: torchvision.models.ViT_H_14_Weights
        :members:
       r   r   i   i   r   Nr1   )r   r   r   r   r1   r1   r2   r!     r   r!   bicubicFr   model_statezOrderedDict[str, torch.Tensor]interpolation_modereset_headsc                 C   s`  |d }|j \}}}|dkrtd|j  | | d d }	|	|kr|d8 }|	d8 }	|ddddddf }
|ddddddf }|ddd}tt|}|| |krdtd||  d| |d|||}| | }tjj	|||d	d
}|d||	}|ddd}t
j|
|gdd}||d< |rt }| D ]\}}|ds|||< q|}|S )a  This function helps interpolate positional embeddings during checkpoint loading,
    especially when you want to apply a pre-trained model on images with different resolution.

    Args:
        image_size (int): Image size of the new model.
        patch_size (int): Patch size of the new model.
        model_state (OrderedDict[str, torch.Tensor]): State dict of the pre-trained model.
        interpolation_mode (str): The algorithm used for upsampling. Default: bicubic.
        reset_heads (bool): If true, not copying the state of heads. Default: False.

    Returns:
        OrderedDict[str, torch.Tensor]: A state dict which can be loaded into the new model.
    zencoder.pos_embeddingr   z%Unexpected position embedding shape: r
   Nr   zPseq_length is not a perfect square! Instead got seq_length_1d * seq_length_1d = z and seq_length = T)sizemodealign_cornersr   r   )rt   
ValueErrorr   r+   r   r   r   r-   
functionalinterpolaterq   r   r   items
startswith)r   r   r   r   r   r   r   r}   re   new_seq_lengthpos_embedding_tokenpos_embedding_imgseq_length_1dnew_seq_length_1dnew_pos_embedding_imgnew_pos_embeddingmodel_state_copykvr1   r1   r2   interpolate_embeddings  sH   
r  )r   F):r   collectionsr   	functoolsr   typingr   r   r   r   r   r	   rq   torch.nnr-   ops.miscr   r   transforms._presetsr   r   utilsr   _apir   r   r   _metar   _utilsr   r   __all__r"   r3   r/   ra   r|   r   r+   boolr   r   strr,   r   r   r   r   r   r   r   r   r   r   r    r!   r  r1   r1   r1   r2   <module>   s   
  .$& 	
!OP9* * * * *$