
    ^jDN                        d Z ddlZddl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dl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 ddlmZmZmZ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)m*Z*m+Z+m,Z,m-Z- ddl.m/Z/m0Z0m1Z1m2Z2m3Z3  ed      e G d de!                    Z4 ed      e G d de"                    Z5 ed      e G d de                     Z6 G d de(      Z7 G d de/      Z8 G d de      Z9 G d  d!e3      Z: G d" d#e      Z; G d$ d%e0      Z< G d& d'e1      Z= G d( d)e      Z> G d* d+e&      Z? G d, d-e2      Z@ G d. d/e%      ZA G d0 d1e$      ZB G d2 d3e'      ZC G d4 d5e&      ZD G d6 d7e*      ZE G d8 d9e)      ZF G d: d;e+      ZG ed<=       G d> d?eF             ZH G d@ dAeF      ZI G dB dCeeF      ZJg dDZKy)EzPyTorch AltCLIP model.    N)strict   )initialization)create_bidirectional_mask)BaseModelOutputWithPooling'BaseModelOutputWithPoolingAndProjection)PreTrainedModel)Unpack)TransformersKwargsauto_docstringcan_return_tuple)merge_with_config_defaults)capture_outputs   )ChineseCLIPModelChineseCLIPTextAttentionChineseCLIPTextLayerChineseCLIPTextSelfAttention)
CLIPConfigCLIPTextConfigCLIPVisionConfig)
CLIPMLPCLIPAttentionCLIPEncoderCLIPEncoderLayer
CLIPOutputCLIPPreTrainedModelCLIPVisionEmbeddingsCLIPVisionModel_get_vector_normimage_text_contrastive_loss)RobertaEmbeddingsRobertaIntermediateRobertaOutputRobertaPoolerRobertaSelfOutputzBAAI/AltCLIP)
checkpointc                      e Zd ZU dZdZeed<   dZeed<   dZeed<   dZ	eed	<   d
Z
eed<   dZeed<   dZeez  ed<   dZeez  ed<   dZeed<   dZeed<   dZeed<   dZedz  ed<   dZedz  ed<   dZedz  ed<   dZeed<    e       Z e       Zy)AltCLIPTextConfigaR  
    project_dim (`int`, *optional*, defaults to 768):
        The dimensions of the teacher model before the mapping layer.

    Examples:

    ```python
    >>> from transformers import AltCLIPTextModel, AltCLIPTextConfig

    >>> # Initializing a AltCLIPTextConfig with BAAI/AltCLIP style configuration
    >>> configuration = AltCLIPTextConfig()

    >>> # Initializing a AltCLIPTextModel (with random weights) from the BAAI/AltCLIP style configuration
    >>> model = AltCLIPTextModel(configuration)

    >>> # Accessing the model configuration
    >>> configuration = model.config
    ```i 
vocab_sizei   hidden_size   num_hidden_layers   num_attention_headsi   intermediate_sizegelu
hidden_actg?hidden_dropout_probr   attention_probs_dropout_probi  max_position_embeddings   type_vocab_sizeg{Gz?initializer_factorNpad_token_idbos_token_idr   eos_token_id   project_dim)__name__
__module____qualname____doc__r*   int__annotations__r+   r-   r/   r0   r2   strr3   floatr4   r5   r7   r8   r9   r:   r;   r=   AttributeErrorprojection_dimattention_dropout     v/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/altclip/modular_altclip.pyr)   r)   :   s    & JKs!!!s!J'*u*01 #+1#&S&OS $$ L#*  L#*  L#* K#%N&(rJ   r)   c                       e Zd ZdZy)AltCLIPVisionConfiga  
    Example:

    ```python
    >>> from transformers import AltCLIPVisionConfig, AltCLIPVisionModel

    >>> # Initializing a AltCLIPVisionConfig with BAAI/AltCLIP style configuration
    >>> configuration = AltCLIPVisionConfig()

    >>> # Initializing a AltCLIPVisionModel (with random weights) from the BAAI/AltCLIP style configuration
    >>> model = AltCLIPVisionModel(configuration)

    >>> # Accessing the model configuration
    >>> configuration = model.config
    ```N)r>   r?   r@   rA   rI   rJ   rK   rM   rM   c   s    rJ   rM   c                        e Zd ZU dZdZeed<   y)AltCLIPConfiga  
    Example:

    ```python
    >>> from transformers import AltCLIPConfig, AltCLIPModel

    >>> # Initializing a AltCLIPConfig with BAAI/AltCLIP style configuration
    >>> configuration = AltCLIPConfig()

    >>> # Initializing a AltCLIPModel (with random weights) from the BAAI/AltCLIP style configuration
    >>> model = AltCLIPModel(configuration)

    >>> # Accessing the model configuration
    >>> configuration = model.config

    >>> # We can also initialize a AltCLIPConfig from a AltCLIPTextConfig and a AltCLIPVisionConfig

    >>> # Initializing a AltCLIPText and AltCLIPVision configuration
    >>> config_text = AltCLIPTextConfig()
    >>> config_vision = AltCLIPVisionConfig()

    >>> config = AltCLIPConfig(text_config=config_text, vision_config=config_vision)
    ```r<   rG   N)r>   r?   r@   rA   rG   rB   rC   rI   rJ   rK   rO   rO   w   s    0 NCrJ   rO   c                       e Zd Zy)AltCLIPOutputNr>   r?   r@   rI   rJ   rK   rQ   rQ          rJ   rQ   c                       e Zd Zy)AltRobertaEmbeddingsNrR   rI   rJ   rK   rU   rU      rS   rJ   rU   c                        e Zd Z fdZ xZS )AltRobertaSelfAttentionc                 2    t         |   |       d| _        y )NF)super__init__	is_causalselfconfig	__class__s     rK   rZ   z AltRobertaSelfAttention.__init__   s     rJ   r>   r?   r@   rZ   __classcell__r_   s   @rK   rW   rW      s     rJ   rW   c                       e Zd Zy)AltRobertaSelfOutputNrR   rI   rJ   rK   rd   rd      rS   rJ   rd   c                        e Zd Z fdZ xZS )AltRobertaAttentionc                 b    t         |           t        |      | _        t	        |      | _        y N)rY   rZ   rW   r]   rd   outputr\   s     rK   rZ   zAltRobertaAttention.__init__   s&    +F3	*62rJ   r`   rb   s   @rK   rf   rf      s    3 3rJ   rf   c                       e Zd Zy)AltRobertaIntermediateNrR   rI   rJ   rK   rk   rk      rS   rJ   rk   c                       e Zd Zy)AltRobertaOutputNrR   rI   rJ   rK   rm   rm      rS   rJ   rm   c                        e Zd Z fdZ xZS )AltRobertaLayerc                     t         |           t        |      | _        t	        |      | _        t        |      | _        y rh   )rY   rZ   rf   	attentionrk   intermediaterm   ri   r\   s     rK   rZ   zAltRobertaLayer.__init__   s3    ,V426:&v.rJ   r`   rb   s   @rK   ro   ro      s    / /rJ   ro   c                   (     e Zd ZdZdef fdZ xZS )AltRobertaEncoderz
    Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
    [`AltRobertaEncoderLayer`].

    Args:
        config: AltCLIPTextConfig
    r^   c                     t         |   |       t        j                  t	        |j
                        D cg c]  }t        |       c}      | _        y c c}w rh   )rY   rZ   nn
ModuleListranger-   ro   layers)r]   r^   _r_   s      rK   rZ   zAltRobertaEncoder.__init__   s>     mmeFLdLdFe$f_V%<$fg$fs   A)r>   r?   r@   rA   r)   rZ   ra   rb   s   @rK   rt   rt      s    h0 h hrJ   rt   c                       e Zd Zy)AltRobertaPoolerNrR   rI   rJ   rK   r|   r|      rS   rJ   r|   c                       e Zd Zy)AltCLIPAttentionNrR   rI   rJ   rK   r~   r~      rS   rJ   r~   c                       e Zd Zy)
AltCLIPMLPNrR   rI   rJ   rK   r   r      rS   rJ   r   c                   $     e Zd Zdef fdZ xZS )AltCLIPEncoderLayerr^   c                 $    t         |   |       y rh   )rY   rZ   r\   s     rK   rZ   zAltCLIPEncoderLayer.__init__   s     rJ   )r>   r?   r@   rM   rZ   ra   rb   s   @rK   r   r      s    !2 ! !rJ   r   c                       e Zd Zy)AltCLIPEncoderNrR   rI   rJ   rK   r   r      rS   rJ   r   c                       e Zd Zy)AltCLIPVisionEmbeddingsNrR   rI   rJ   rK   r   r      rS   rJ   r   c                   L    e Zd Zg dZeedZ ej                         d        Z	y)AltCLIPPreTrainedModel)rU   ro   r   r   hidden_states
attentionsc                    t        j                  | |       | j                  j                  }t	        |t
              rt        j                  |j                  d|j                  dz  |z         t        j                  |j                  j                  |j                  j                  |z         t        j                  |j                  j                  |j                  j                  |z         t        j                  |j                  t!        j"                  |j$                        j'                  d             yt	        |t(              r|j                  dz  d|j                  j*                  z  dz  z  |z  }|j                  dz  |z  }t        j                  |j,                  j                  |       t        j                  |j.                  j                  |       t        j                  |j0                  j                  |       t        j                  |j2                  j                  |       yt	        |t4              r|j                  j6                  dz  d|j                  j*                  z  dz  z  |z  }d|j                  j6                  z  dz  |z  }t        j                  |j8                  j                  |       t        j                  |j:                  j                  |       yt	        |t<              rwt        j                  |j>                  j                  |j@                  dz  |z         t        j                  |jB                  j                  |jD                  dz  |z         yt	        |tF              ryt        j                  |j                  t!        j"                  |j                  jH                  d         j'                  d             t        jJ                  |jL                         yy)	zInitialize the weightsg        g      )meanstd)r   )r6   r   r   N)'r	   _init_weightsr^   r8   
isinstancer   initnormal_class_embedding	embed_dimpatch_embeddingweightinitializer_rangeposition_embeddingcopy_position_idstorcharangenum_positionsexpandr~   r-   q_projk_projv_projout_projr   r+   fc1fc2AltCLIPModeltext_projectiontext_embed_dimvisual_projectionvision_embed_dimrU   shapezeros_token_type_ids)r]   modulefactorin_proj_stdout_proj_stdfc_stds         rK   r   z$AltCLIPPreTrainedModel._init_weights   s    	%%dF3//f56LL//cv?O?OQU?UX^?^_LL//66FMM<[<[^d<deLL2299v}}?^?^ag?ghJJv**ELL9M9M,N,U,UV],^_ 01!++T1q6==;Z;Z7Z_c6cdgmmK",,d2f<LLL--;?LL--;?LL--;?LL//\B
+!==44d:FMMDcDc@chl?lmpvvK&--333<vEFLL**7LL**<-LL&&--))4/&8 LL((//++T1F:  45JJv**ELL9L9L9R9RSU9V,W,^,^_f,ghKK--. 6rJ   N)
r>   r?   r@   _no_split_modulesr   r~   _can_record_outputsr   no_gradr   rI   rJ   rK   r   r      s2    u,&
 U]]_ /  /rJ   r   c                        e Zd Z fdZ xZS )AltCLIPVisionModelc                 "    t        |   di |S )a  
        Examples:

        ```python
        >>> import httpx
        >>> from io import BytesIO
        >>> from PIL import Image
        >>> from transformers import AutoProcessor, AltCLIPVisionModel

        >>> model = AltCLIPVisionModel.from_pretrained("BAAI/AltCLIP")
        >>> processor = AutoProcessor.from_pretrained("BAAI/AltCLIP")

        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> with httpx.stream("GET", url) as response:
        ...     image = Image.open(BytesIO(response.read()))

        >>> inputs = processor(images=image, return_tensors="pt")

        >>> outputs = model(**inputs)
        >>> last_hidden_state = outputs.last_hidden_state
        >>> pooled_output = outputs.pooler_output  # pooled CLS states
        ```rI   )rY   forwardr]   super_kwargsr_   s     rK   r   zAltCLIPVisionModel.forward  s    . w...rJ   )r>   r?   r@   r   ra   rb   s   @rK   r   r     s    / /rJ   r   aE  
    The model behaves as an encoder following the architecture described in *Attention is
    all you need*_ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz
    Kaiser and Illia Polosukhin.

    .. _*Attention is all you need*: https://huggingface.co/papers/1706.03762
    )custom_introc                       e Zd ZU eed<   dZdZeedZ	d fd	Z
eee	 	 	 	 	 ddej                  dz  dej                  dz  d	ej                  dz  d
ej                  dz  dej                  dz  dee   deez  fd                     Z xZS )AltRobertaModelr^   textword_embeddingsr   c                     t         |   |       t        |      | _        t	        |      | _        |rt        |      nd| _        | j                          y)zv
        add_pooling_layer (bool, *optional*, defaults to `True`):
            Whether to add a pooling layer
        N)	rY   rZ   rU   
embeddingsrt   encoderr|   pooler	post_init)r]   r^   add_pooling_layerr_   s      rK   rZ   zAltRobertaModel.__init__>  sE    
 	 .v6(02C&v.rJ   N	input_idsattention_maskr   r   inputs_embedskwargsreturnc                    |du |duz  rt        d      | j                  ||||      }t        | j                  ||      } | j                  |fd|i|}|d   }| j
                  | j                  |      nd}	t        ||	      S )aK  
        Examples:

        ```python
        >>> from transformers import AutoTokenizer, AltRobertaModel

        >>> model = AltRobertaModel.from_pretrained("openai/alt_roberta-vit-base-patch32")
        >>> tokenizer = AutoTokenizer.from_pretrained("openai/alt_roberta-vit-base-patch32")

        >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")

        >>> outputs = model(**inputs)
        >>> last_hidden_state = outputs.last_hidden_state
        >>> pooled_output = outputs.pooler_output  # pooled (EOS token) states
        ```Nz:You must specify exactly one of input_ids or inputs_embeds)r   r   r   r   )r^   r   r   r   r   )last_hidden_statepooler_output)
ValueErrorr   r   r^   r   r   r   )
r]   r   r   r   r   r   r   encoder_outputssequence_outputpooled_outputs
             rK   r   zAltRobertaModel.forwardJ  s    6 -t";<YZZ%)'	 ( 
 3;;')
 '$,,
)
 

 *!,8<8OO4UY)-'
 	
rJ   )TNNNNN)r>   r?   r@   r)   rC   input_modalities_input_embed_layerro   rW   r   rZ   r   r   r   r   Tensorr
   r   tupler   r   ra   rb   s   @rK   r   r   +  s      *(-

   *..2.2,0-13
<<$&3
 t+3
 t+	3

 llT)3
 ||d*3
 +,3
 
+	+3
    3
rJ   r   c                       e Zd ZU eed<   dZdZdZ fdZe	e
	 	 	 	 	 ddej                  dz  dej                  dz  d	ej                  dz  d
ej                  dz  dej                  dz  dee   deez  fd              Z xZS )AltCLIPTextModelr^   r   r   robertac                 &   t         |   |       t        |d      | _        t	        j
                  |j                  |j                        | _        t	        j                  |j                  |j                        | _        | j                          y )NF)r   )eps)rY   rZ   r   r   rv   Linearr+   r=   transformation	LayerNormlayer_norm_epspre_LNr   r\   s     rK   rZ   zAltCLIPTextModel.__init__  se     &vG ii(:(:F<N<NOll6#5#56;P;PQrJ   Nr   r   r   r   r   r   r   c           	           | j                   d|||||d|}|d   }| j                  |      }| j                  |      }	|	dddf   }
t        |	|
|j                  |j
                        S )a+  
        Examples:

        ```python
        >>> from transformers import AutoProcessor, AltCLIPTextModel

        >>> model = AltCLIPTextModel.from_pretrained("BAAI/AltCLIP")
        >>> processor = AutoProcessor.from_pretrained("BAAI/AltCLIP")

        >>> texts = ["it's a cat", "it's a dog"]

        >>> inputs = processor(text=texts, padding=True, return_tensors="pt")

        >>> outputs = model(**inputs)
        >>> last_hidden_state = outputs.last_hidden_state
        >>> pooled_output = outputs.pooler_output  # pooled CLS states
        ```)r   r   r   r   r   r   N)r   r   r   r   rI   )r   r   r   r   r   r   )r]   r   r   r   r   r   r   outputsr   projection_stater   s              rK   r   zAltCLIPTextModel.forward  s    : $,, 
))%'
 
 "!* ++o6  ..?(A.6.'!//))	
 	
rJ   r   )r>   r?   r@   r)   rC   r   r   base_model_prefixrZ   r   r   r   r   r
   r   r   r   r   ra   rb   s   @rK   r   r     s     *!  *..2.2,0-13
<<$&3
 t+3
 t+	3

 llT)3
 ||d*3
 +,3
 
8	83
  3
rJ   r   c                       e Zd ZU eed<   def fdZ fdZ fdZ	 	 	 	 	 	 	 ddej                  dz  dej                  dz  dej                  dz  d	ej                  dz  d
ej                  dz  dedz  dedee   deez  fdZ xZS )r   r^   c                    t         |   |       |j                  }|j                  | _        t
        j                  | j                  j                        | _        t        j                  | j                  j                        | _        y rh   )rY   rZ   text_configr=   r   r   _from_configr^   
text_modelr   vision_configvision_model)r]   r^   r   r_   s      rK   rZ   zAltCLIPModel.__init__  sb     (()55*778O8OP.;;DKK<U<UVrJ   c                 "    t        |   di |S )a  
        Examples:

        ```python
        >>> import torch
        >>> from transformers import AutoProcessor, AltCLIPModel

        >>> model = AltCLIPModel.from_pretrained("BAAI/AltCLIP")
        >>> processor = AutoProcessor.from_pretrained("BAAI/AltCLIP")

        >>> inputs = processor(text=["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
        >>> with torch.inference_mode():
        ...     text_features = model.get_text_features(**inputs)
        ```rI   )rY   get_text_featuresr   s     rK   r   zAltCLIPModel.get_text_features  s     w(8<88rJ   c                 "    t        |   di |S )ao  
        Examples:

        ```python
        >>> import torch
        >>> from transformers import AutoProcessor, AltCLIPModel
        >>> from transformers.image_utils import load_image

        >>> model = AltCLIPModel.from_pretrained("BAAI/AltCLIP")
        >>> processor = AutoProcessor.from_pretrained("BAAI/AltCLIP")

        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> image = load_image(url)

        >>> inputs = processor(images=image, return_tensors="pt")
        >>> with torch.inference_mode():
        ...     image_features = model.get_image_features(**inputs)
        ```rI   )rY   get_image_featuresr   s     rK   r   zAltCLIPModel.get_image_features  s    & w)9L99rJ   Nr   pixel_valuesr   r   r   return_lossinterpolate_pos_encodingr   r   c           	      2    | j                   d||d|}	 | j                  d||||d|}
|	d   }| j                  |      }|
d   }| j                  |      }|t	        |      z  }|t	        |      z  }t        j                  ||j                         j                  |j                              }|| j                  j                         j                  |j                        z  }|j                         }d}|rt        |      }t        ||||||
|	      S )u  
        return_loss (`bool`, *optional*):
            Whether or not to return the contrastive loss.

        Examples:

        ```python
        >>> import torch
        >>> from transformers import AutoProcessor, AltCLIPModel
        >>> from transformers.image_utils import load_image

        >>> model = AltCLIPModel.from_pretrained("OFA-Sys/chinese-clip-vit-base-patch16")
        >>> processor = AutoProcessor.from_pretrained("OFA-Sys/chinese-clip-vit-base-patch16")

        >>> url = "https://clip-cn-beijing.oss-cn-beijing.aliyuncs.com/pokemon.jpeg"
        >>> image = load_image(url)

        >>> inputs = processor(text=["杰尼龟", "妙蛙种子", "小火龙", "皮卡丘"], images=image, return_tensors="pt", padding=True)

        >>> with torch.inference_mode():
        ...     outputs = model(**inputs)
        >>> logits_per_image = outputs.logits_per_image  # this is the image-text similarity score
        >>> probs = logits_per_image.softmax(dim=1)  # we can take the softmax to get the label probabilities
        ```)r   r   )r   r   r   r   r6   N)losslogits_per_imagelogits_per_texttext_embedsimage_embedstext_model_outputvision_model_outputrI   )r   r   r   r   r    r   matmulttodevicelogit_scaleexpr!   rQ   )r]   r   r   r   r   r   r   r   r   vision_outputstext_outputsr   r   r   r   r   s                   rK   r   zAltCLIPModel.forward  sG   F +** 
%%=
 
 't 
))%	

 
 &a(--l;"1o**;7 $&6|&DD!$4[$AA  ,,{LNN4D4G4GHZHZ4[\)D,<,<,@,@,B,E,EkFXFX,YY*,,..?D-+#%* .
 	
rJ   )NNNNNNF)r>   r?   r@   rO   rC   rZ   r   r   r   
LongTensorFloatTensorr   boolr
   r   r   rQ   r   ra   rb   s   @rK   r   r     s    W} W9":. .215.2.204#').L
##d*L
 ''$.L
 t+	L

 t+L
 &&-L
 D[L
 #'L
 +,L
 
	L
rJ   r   )r   r   r   r   r)   rM   rO   )LrA   r   torch.nnrv   huggingface_hub.dataclassesr    r   r   masking_utilsr   modeling_outputsr   r   modeling_utilsr	   processing_utilsr
   utilsr   r   r   utils.genericr   utils.output_capturingr   "chinese_clip.modeling_chinese_clipr   r   r   r   clip.configuration_clipr   r   r   clip.modeling_clipr   r   r   r   r   r   r   r   r    r!   roberta.modeling_robertar"   r#   r$   r%   r&   r)   rM   rO   rQ   rU   rW   rd   rf   rk   rm   ro   rt   r|   r~   r   r   r   r   r   r   r   r   r   __all__rI   rJ   rK   <module>r     s      . & 6 . & I I 7 5  S R    >*$) $)  +$)N >**   +$ >*J   +8	J 		, 	: 	, 	32 3	0 		} 	/* /h h	} 		} 		 	!* !
	[ 		2 	(/0 (/V/ /6 L
, L
L
^B
- B
J|
#%; |
~rJ   