o
    Zh                    @   s  d Z ddl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ZddlmZ ddlmZmZmZmZmZ ddlmZmZ dd	lmZmZmZ dd
lmZm Z m!Z!m"Z" ddl#m$Z$m%Z%m&Z& e!'e(Z)dej*dej*fddZ+dej*dej*fddZ,eG dd deZ-G dd dej.Z/G dd dej.Z0G dd dej.Z1de0iZ2G dd dej.Z3G dd  d ej.Z4G d!d" d"ej.Z5G d#d$ d$ej.Z6G d%d& d&ej.Z7G d'd( d(ej.Z8	)dNd*ej.d+ej*d,ej*d-ej*d.eej* d/e9d0e9fd1d2Z:G d3d4 d4ej.Z;G d5d6 d6ej.Z<G d7d8 d8ej.Z=G d9d: d:ej.Z>G d;d< d<ej.Z?e G d=d> d>eZ@G d?d@ d@ej.ZAG dAdB dBe@ZBe dCdDG dEdF dFe@ZCG dGdH dHe@ZDG dIdJ dJe@ZEdOdKdLZFg dMZGdS )PzPyTorch AltCLIP model.    N)	dataclass)AnyCallableListOptionalTupleUnion   )ACT2FN)BaseModelOutput)BaseModelOutputWithPastAndCrossAttentionsBaseModelOutputWithPooling,BaseModelOutputWithPoolingAndCrossAttentions'BaseModelOutputWithPoolingAndProjection)ALL_ATTENTION_FUNCTIONSPreTrainedModel)apply_chunking_to_forward find_pruneable_heads_and_indicesprune_linear_layer)ModelOutputauto_docstringlogging	torch_int   )AltCLIPConfigAltCLIPTextConfigAltCLIPVisionConfiglogitsreturnc                 C   s   t j| tjt| | jdS )Ndevice)nn
functionalZcross_entropytorcharangelenr    )r    r&   [/var/www/auris/lib/python3.10/site-packages/transformers/models/altclip/modeling_altclip.pycontrastive_loss,   s   r(   
similarityc                 C   s    t | }t |  }|| d S )Ng       @)r(   t)r)   Zcaption_lossZ
image_lossr&   r&   r'   	clip_loss0   s   r+   c                   @   s   e Zd ZU dZdZeej ed< dZ	eej ed< dZ
eej ed< dZeej ed< dZeej ed< dZeed< dZeed	< d
ee fddZdS )AltCLIPOutputa  
    Args:
        loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
            Contrastive loss for image-text similarity.
        logits_per_image (`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
            The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
            similarity scores.
        logits_per_text (`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
            The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
            similarity scores.
        text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
            The text embeddings obtained by applying the projection layer to the pooled output of [`AltCLIPTextModel`].
        image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
            The image embeddings obtained by applying the projection layer to the pooled output of [`AltCLIPVisionModel`].
        text_model_output (`BaseModelOutputWithPooling`):
            The output of the [`AltCLIPTextModel`].
        vision_model_output (`BaseModelOutputWithPooling`):
            The output of the [`AltCLIPVisionModel`].
    Nlosslogits_per_imagelogits_per_texttext_embedsimage_embedstext_model_outputvision_model_outputr   c                    s   t  fdd  D S )Nc                 3   s.    | ]}|d vr | nt  | V  qdS ))r2   r3   N)getattrto_tuple).0kselfr&   r'   	<genexpr>V   s
    
z)AltCLIPOutput.to_tuple.<locals>.<genexpr>)tuplekeysr8   r&   r8   r'   r5   U   s   zAltCLIPOutput.to_tuple)__name__
__module____qualname____doc__r-   r   r#   FloatTensor__annotations__r.   r/   r0   r1   r2   r   r3   r   r   r5   r&   r&   r&   r'   r,   6   s   
 r,   c                       s4   e Zd ZdZ fddZ	d
ddZdd	 Z  ZS )AltRobertaEmbeddingszV
    Same as BertEmbeddings with a tiny tweak for positional embeddings indexing.
    c                    s   t    tj|j|j|jd| _t|j|j| _	t|j
|j| _tj|j|jd| _t|j| _t|dd| _| jdt|jddd | jd	tj| j tjd
dd |j| _tj|j|j| jd| _	d S )N)padding_idxZepsposition_embedding_typeabsoluteposition_idsr   F
persistenttoken_type_idsdtype)super__init__r!   	EmbeddingZ
vocab_sizehidden_sizeZpad_token_idword_embeddingsmax_position_embeddingsposition_embeddingsZtype_vocab_sizetoken_type_embeddings	LayerNormlayer_norm_epsDropouthidden_dropout_probdropoutr4   rF   register_bufferr#   r$   expandzerosrH   sizelongrD   r9   config	__class__r&   r'   rQ   c   s"   
zAltRobertaEmbeddings.__init__Nr   c                 C   s   |d u r|d urt || j|}n| |}|d ur| }n| d d }|d }|d u rTt| drI| jd d d |f }||d |}	|	}ntj|tj	| j
jd}|d u r]| |}| |}
||
 }| jdkrt| |}||7 }| |}| |}|S )NrJ   r   rM   r   rO   r    rG   )"create_position_ids_from_input_idsrD   &create_position_ids_from_inputs_embedsr`   hasattrrM   r^   r#   r_   ra   rH   r    rT   rW   rF   rV   rX   r\   )r9   	input_idsrM   rH   inputs_embedspast_key_values_lengthinput_shape
seq_lengthbuffered_token_type_ids buffered_token_type_ids_expandedrW   
embeddingsrV   r&   r&   r'   forward|   s0   








zAltRobertaEmbeddings.forwardc                 C   sN   |  dd }|d }tj| jd || j d tj|jd}|d|S )z
        We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.

        Args:
            inputs_embeds: torch.Tensor

        Returns: torch.Tensor
        NrJ   r   rf   r   )r`   r#   r$   rD   ra   r    	unsqueezer^   )r9   rk   rm   Zsequence_lengthrH   r&   r&   r'   rh      s   	z;AltRobertaEmbeddings.create_position_ids_from_inputs_embeds)NNNNr   )r=   r>   r?   r@   rQ   rr   rh   __classcell__r&   r&   rd   r'   rC   ]   s    
(rC   c                       s   e Zd Zd fdd	ZdejdejfddZ						dd	ejd
eej deej deej deej dee	e	ej   dee
 de	ej fddZ  ZS )AltRobertaSelfAttentionNc                    s   t    |j|j dkrt|dstd|j d|j d|j| _t|j|j | _| j| j | _t	
|j| j| _t	
|j| j| _t	
|j| j| _t	|j| _|p\t|dd| _| jdksh| jd	kry|j| _t	d
|j d | j| _|j| _d S )Nr   Zembedding_sizezThe hidden size (z6) is not a multiple of the number of attention heads ()rF   rG   relative_keyrelative_key_query   r   )rP   rQ   rS   num_attention_headsri   
ValueErrorintattention_head_sizeall_head_sizer!   LinearquerykeyvaluerZ   Zattention_probs_dropout_probr\   r4   rF   rU   rR   distance_embedding
is_decoderr9   rc   rF   rd   r&   r'   rQ      s*   

z AltRobertaSelfAttention.__init__xr   c                 C   s6   |  d d | j| jf }||}|ddddS )NrJ   r   ry   r   r	   )r`   rz   r}   viewpermute)r9   r   Znew_x_shaper&   r&   r'   transpose_for_scores   s   
z,AltRobertaSelfAttention.transpose_for_scoresFhidden_statesattention_mask	head_maskencoder_hidden_statesencoder_attention_maskpast_key_valueoutput_attentionsc                 C   s  |  |}|d u}	|	r|d ur|d }
|d }|}nP|	r/| | |}
| | |}|}n;|d urZ| | |}
| | |}tj|d |
gdd}
tj|d |gdd}n| | |}
| | |}| |}|d u}| jrz|
|f}t||
dd}| j	dks| j	dkr	|j
d |
j
d }}|rtj|d tj|jd	dd}ntj|tj|jd	dd}tj|tj|jd	dd}|| }| || j d }|j|jd
}| j	dkrtd||}|| }n| j	dkr	td||}td|
|}|| | }|t| j }|d ur|| }tjj|dd}| |}|d ur0|| }t||}|dddd }| d d | jf }||}|rX||fn|f}| jrd||f }|S )Nr   r   ry   dimrJ   rw   rx   rf   rN   zbhld,lrd->bhlrzbhrd,lrd->bhlrr	   ) r   r   r   r   r#   catr   matmul	transposerF   shapetensorra   r    r   r$   r   rU   torO   Zeinsummathsqrtr}   r!   r"   softmaxr\   r   
contiguousr`   r~   )r9   r   r   r   r   r   r   r   Zmixed_query_layerZis_cross_attentionZ	key_layerZvalue_layerZquery_layer	use_cacheZattention_scoresZquery_lengthZ
key_lengthZposition_ids_lZposition_ids_rZdistanceZpositional_embeddingZrelative_position_scoresZrelative_position_scores_queryZrelative_position_scores_keyZattention_probsZcontext_layerZnew_context_layer_shapeoutputsr&   r&   r'   rr      sn   









zAltRobertaSelfAttention.forwardNNNNNNF)r=   r>   r?   rQ   r#   Tensorr   r   rA   r   boolrr   rt   r&   r&   rd   r'   ru      s4    	ru   c                       8   e Zd Z fddZdejdejdejfddZ  ZS )AltRobertaSelfOutputc                    sB   t    t|j|j| _tj|j|jd| _t|j	| _
d S NrE   )rP   rQ   r!   r   rS   denserX   rY   rZ   r[   r\   rb   rd   r&   r'   rQ   ?     
zAltRobertaSelfOutput.__init__r   input_tensorr   c                 C   &   |  |}| |}| || }|S r   r   r\   rX   r9   r   r   r&   r&   r'   rr   E     

zAltRobertaSelfOutput.forwardr=   r>   r?   rQ   r#   r   rr   rt   r&   r&   rd   r'   r   >      $r   eagerc                       s   e Zd Zd fdd	Zdd Z						ddejdeej d	eej d
eej deej dee	e	ej   dee
 de	ej fddZ  ZS )AltRobertaAttentionNc                    s4   t    t|j ||d| _t|| _t | _d S )NrF   )	rP   rQ   "ALT_ROBERTA_SELF_ATTENTION_CLASSES_attn_implementationr9   r   outputsetpruned_headsr   rd   r&   r'   rQ   S  s   

zAltRobertaAttention.__init__c                 C   s   t |dkrd S t|| jj| jj| j\}}t| jj|| j_t| jj|| j_t| jj	|| j_	t| j
j|dd| j
_| jjt | | j_| jj| jj | j_| j|| _d S )Nr   r   r   )r%   r   r9   rz   r}   r   r   r   r   r   r   r   r~   union)r9   headsindexr&   r&   r'   prune_heads[  s   zAltRobertaAttention.prune_headsFr   r   r   r   r   r   r   r   c              	   C   s<   |  |||||||}| |d |}	|	f|dd   }
|
S )Nr   r   )r9   r   )r9   r   r   r   r   r   r   r   Zself_outputsattention_outputr   r&   r&   r'   rr   m  s   
	zAltRobertaAttention.forwardr   r   )r=   r>   r?   rQ   r   r#   r   r   rA   r   r   rr   rt   r&   r&   rd   r'   r   R  s4    	r   c                       2   e Zd Z fddZdejdejfddZ  ZS )AltRobertaIntermediatec                    sD   t    t|j|j| _t|jt	rt
|j | _d S |j| _d S r   )rP   rQ   r!   r   rS   intermediate_sizer   
isinstance
hidden_actstrr
   intermediate_act_fnrb   rd   r&   r'   rQ     s
   
zAltRobertaIntermediate.__init__r   r   c                 C   s   |  |}| |}|S r   )r   r   r9   r   r&   r&   r'   rr     s   

zAltRobertaIntermediate.forwardr   r&   r&   rd   r'   r     s    r   c                       r   )AltRobertaOutputc                    sB   t    t|j|j| _tj|j|jd| _t	|j
| _d S r   )rP   rQ   r!   r   r   rS   r   rX   rY   rZ   r[   r\   rb   rd   r&   r'   rQ     r   zAltRobertaOutput.__init__r   r   r   c                 C   r   r   r   r   r&   r&   r'   rr     r   zAltRobertaOutput.forwardr   r&   r&   rd   r'   r     r   r   c                       s   e Zd Z fddZ						ddejdeej deej deej d	eej d
eeeej   dee	 deej fddZ
dd Z  ZS )AltRobertaLayerc                    sr   t    |j| _d| _t|| _|j| _|j| _| jr-| js&t|  dt|dd| _	t
|| _t|| _d S )Nr   z> should be used as a decoder model if cross attention is addedrG   r   )rP   rQ   chunk_size_feed_forwardseq_len_dimr   	attentionr   add_cross_attentionr{   crossattentionr   intermediater   r   rb   rd   r&   r'   rQ     s   


zAltRobertaLayer.__init__NFr   r   r   r   r   r   r   r   c              	   C   s  |d ur
|d d nd }| j |||||d}	|	d }
| jr(|	dd }|	d }n|	dd  }d }| jro|d urot| dsDtd|  d|d urN|d	d  nd }| |
||||||}|d }
||dd  }|d }|| }t| j| j| j|
}|f| }| jr||f }|S )
Nry   )r   r   r   r   rJ   r   z'If `encoder_hidden_states` are passed, z` has to be instantiated with cross-attention layers by setting `config.add_cross_attention=True`r   )	r   r   ri   r{   r   r   feed_forward_chunkr   r   )r9   r   r   r   r   r   r   r   Zself_attn_past_key_valueZself_attention_outputsr   r   Zpresent_key_valueZcross_attn_present_key_valueZcross_attn_past_key_valueZcross_attention_outputslayer_outputr&   r&   r'   rr     sP   


	

zAltRobertaLayer.forwardc                 C   s   |  |}| ||}|S r   )r   r   )r9   r   Zintermediate_outputr   r&   r&   r'   r     s   
z"AltRobertaLayer.feed_forward_chunkr   )r=   r>   r?   rQ   r#   r   r   rA   r   r   rr   r   rt   r&   r&   rd   r'   r     s4    	
Ar   c                       s   e Zd Z fddZ									ddejdeej deej d	eej d
eej deeeej   dee	 dee	 dee	 dee	 de
eej ef fddZ  ZS )AltRobertaEncoderc                    :   t     | _t fddt jD | _d| _d S )Nc                       g | ]}t  qS r&   )r   r6   _rc   r&   r'   
<listcomp>       z.AltRobertaEncoder.__init__.<locals>.<listcomp>F)	rP   rQ   rc   r!   
ModuleListrangenum_hidden_layerslayergradient_checkpointingrb   rd   r   r'   rQ        
 
zAltRobertaEncoder.__init__NFTr   r   r   r   r   past_key_valuesr   r   output_hidden_statesreturn_dictr   c                 C   s^  |	rdnd }|r
dnd }|r| j jrdnd }| jr%| jr%|r%td d}|r)dnd }t| jD ]^\}}|	r;||f }|d urC|| nd }|d urM|| nd }| jrc| jrc| |j	|||||||}n
||||||||}|d }|rz||d f7 }|r||d f }| j jr||d f }q0|	r||f }|
st
dd	 |||||fD S t|||||d
S )Nr&   zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fr   rJ   r   ry   c                 s       | ]	}|d ur|V  qd S r   r&   r6   vr&   r&   r'   r:   E  s    z,AltRobertaEncoder.forward.<locals>.<genexpr>)last_hidden_stater   r   
attentionscross_attentions)rc   r   r   trainingloggerwarning_once	enumerater   _gradient_checkpointing_func__call__r;   r   )r9   r   r   r   r   r   r   r   r   r   r   Zall_hidden_statesZall_self_attentionsZall_cross_attentionsZnext_decoder_cacheiZlayer_moduleZlayer_head_maskr   layer_outputsr&   r&   r'   rr     sz   


zAltRobertaEncoder.forward)	NNNNNNFFT)r=   r>   r?   rQ   r#   r   r   rA   r   r   r   r   rr   rt   r&   r&   rd   r'   r     sD    		
r   c                       r   )AltRobertaPoolerc                    s*   t    t|j|j| _t | _d S r   )rP   rQ   r!   r   rS   r   ZTanh
activationrb   rd   r&   r'   rQ   [  s   
zAltRobertaPooler.__init__r   r   c                 C   s(   |d d df }|  |}| |}|S )Nr   )r   r   )r9   r   Zfirst_token_tensorpooled_outputr&   r&   r'   rr   `  s   

zAltRobertaPooler.forwardr   r&   r&   rd   r'   r   Z  s    r           moduler   r   r   r   scalingr\   c           
      K   s|   t ||dd| }|d ur|| }tjj|dt jd|j}tjj	||| j
d}t ||}	|	dd }	|	|fS )NrJ   r   )r   rO   )pr   r   ry   )r#   r   r   r!   r"   r   Zfloat32r   rO   r\   r   r   )
r   r   r   r   r   r   r\   kwargsattn_weightsattn_outputr&   r&   r'   eager_attention_forwardj  s   
r   c                       sh   e Zd ZdZ fddZ			ddejdeej deej d	ee d
e	ejeej f f
ddZ
  ZS )AltCLIPAttentionz=Multi-headed attention from 'Attention Is All You Need' paperc                    s   t    || _|j| _|j| _| j| j | _| j| j | jkr-td| j d| j d| jd | _	|j
| _d| _t| j| j| _t| j| j| _t| j| j| _t| j| j| _d S )Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: ).      F)rP   rQ   rc   rS   	embed_dimrz   	num_headshead_dimr{   scaleZattention_dropoutr\   	is_causalr!   r   k_projv_projq_projout_projrb   rd   r&   r'   rQ     s$   

zAltCLIPAttention.__init__NFr   r   causal_attention_maskr   r   c              
   C   sL  |j \}}}| |}| |}	| |}
|||| j| jdd}|	||| j| jdd}	|
||| j| jdd}
| jj	dkrY|durR|durR|| }n|durX|}n|du| _
t}| jj	dkrz| jj	dkrt|rttd nt| jj	 }|| ||	|
|| j
| j| jsdn| jd	\}}|||| }| |}|sd}||fS )
z#Input shape: Batch x Time x Channelr   ry   Zflash_attention_2Nr   Zsdpaz`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.r   )r   r   r\   )r   r  r  r  r   r   r   r   rc   r   r   r   r   r   r   r   r   r\   reshaper   r  )r9   r   r   r  r   
batch_sizern   r   Zqueriesr<   valuesZattention_interfacer   r   r&   r&   r'   rr     sH   	






zAltCLIPAttention.forward)NNF)r=   r>   r?   r@   rQ   r#   r   r   r   r   rr   rt   r&   r&   rd   r'   r     s"    r   c                       r   )
AltCLIPMLPc                    sD   t    || _t|j | _t|j|j	| _
t|j	|j| _d S r   )rP   rQ   rc   r
   r   activation_fnr!   r   rS   r   fc1fc2rb   rd   r&   r'   rQ     s
   
zAltCLIPMLP.__init__r   r   c                 C   s"   |  |}| |}| |}|S r   )r  r
  r  r   r&   r&   r'   rr     s   


zAltCLIPMLP.forwardr   r&   r&   rd   r'   r	    s    r	  c                       sT   e Zd Zdef fddZ	ddejdejdejdee d	e	ej
 f
d
dZ  ZS )AltCLIPEncoderLayerrc   c                    sR   t    |j| _t|| _tj| j|jd| _	t
|| _tj| j|jd| _d S r   )rP   rQ   rS   r   r   	self_attnr!   rX   rY   layer_norm1r	  mlplayer_norm2rb   rd   r&   r'   rQ     s   


zAltCLIPEncoderLayer.__init__Fr   r   r  r   r   c                 C   sd   |}|  |}| j||||d\}}|| }|}| |}| |}|| }|f}|r0||f7 }|S )aI  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`): attention mask of size
                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
                `(config.encoder_attention_heads,)`.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
        )r   r   r  r   )r  r  r  r  )r9   r   r   r  r   Zresidualr   r   r&   r&   r'   rr     s"   




zAltCLIPEncoderLayer.forwardF)r=   r>   r?   r   rQ   r#   r   r   r   r   rA   rr   rt   r&   r&   rd   r'   r    s    r  c                       st   e Zd ZdZdef fddZ					ddeej deej dee	 d	ee	 d
ee	 de
eef fddZ  ZS )AltCLIPEncoderz
    Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
    [`AltCLIPEncoderLayer`].

    Args:
        config: AltCLIPConfig
    rc   c                    r   )Nc                    r   r&   )r  r   r   r&   r'   r     r   z+AltCLIPEncoder.__init__.<locals>.<listcomp>F)	rP   rQ   rc   r!   r   r   r   layersr   rb   rd   r   r'   rQ     r   zAltCLIPEncoder.__init__Nr   r  r   r   r   r   c                 C   s   |dur|n| j j}|dur|n| j j}|dur|n| j j}|r"dnd}|r(dnd}|}	t| jD ]1\}
}|r<||	f }| jrM| jrM| |j	|	|||}n||	|||d}|d }	|rb||d f }q1|rj||	f }|sxt
dd |	||fD S t|	||dS )	a  
        Args:
            inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
                Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
                This is useful if you want more control over how to convert `input_ids` indices into associated vectors
                than the model's internal embedding lookup matrix.
            attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
                Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

                - 1 for tokens that are **not masked**,
                - 0 for tokens that are **masked**.

                [What are attention masks?](../glossary#attention-mask)
            causal_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
                Causal mask for the text model. Mask values selected in `[0, 1]`:

                - 1 for tokens that are **not masked**,
                - 0 for tokens that are **masked**.

                [What are attention masks?](../glossary#attention-mask)
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            output_hidden_states (`bool`, *optional*):
                Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
                for more detail.
            return_dict (`bool`, *optional*):
                Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
        Nr&   )r   r   r   c                 s   r   r   r&   r   r&   r&   r'   r:   l  s    z)AltCLIPEncoder.forward.<locals>.<genexpr>)r   r   r   )rc   r   r   use_return_dictr   r  r   r   r   r   r;   r   )r9   rk   r   r  r   r   r   Zencoder_statesZall_attentionsr   idxZencoder_layerr   r&   r&   r'   rr      sF   &

zAltCLIPEncoder.forward)NNNNN)r=   r>   r?   r@   r   rQ   r   r#   r   r   r   r   r   rr   rt   r&   r&   rd   r'   r    s*    	
r  c                       sX   e Zd Zdef fddZdejdededejfdd	Zddej	dejfddZ
  ZS )AltCLIPVisionEmbeddingsrc   c                    s   t    || _|j| _|j| _|j| _tt	
| j| _tj|j| j| j| jdd| _| j| j d | _| jd | _t| j| j| _| jdt	| jddd d S )NF)Zin_channelsZout_channelsZkernel_sizeZstridebiasry   r   rH   rI   rK   )rP   rQ   rc   rS   r   
image_size
patch_sizer!   	Parameterr#   Zrandnclass_embeddingZConv2dZnum_channelspatch_embeddingnum_patchesnum_positionsrR   position_embeddingr]   r$   r^   rb   rd   r&   r'   rQ   t  s"   
"z AltCLIPVisionEmbeddings.__init__rq   heightwidthr   c                 C   s  |j d d }| jjd}|j d d }tj s(||kr(||kr(| | jS |ddddf }|ddddf }|j d }	|| j }
|| j }t	|d }|
d|||	}|dddd}tjj||
|fdd	d
}|dddddd|	}tj||fddS )a   
        This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
        images. This method is also adapted to support torch.jit tracing.

        Adapted from:
        - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
        - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
        r   r   NrJ   g      ?r	   ry   ZbicubicF)r`   modeZalign_cornersr   )r   r   weightrs   r#   Zjit
is_tracingrH   r  r   r  r   r!   r"   Zinterpolater   r   )r9   rq   r!  r"  r  r   r  Zclass_pos_embedZpatch_pos_embedr   Z
new_heightZ	new_widthZsqrt_num_positionsr&   r&   r'   interpolate_pos_encoding  s*   



z0AltCLIPVisionEmbeddings.interpolate_pos_encodingFpixel_valuesc              
   C   s   |j \}}}}|s&|| jks|| jkr&td| d| d| j d| j d	| jjj}| |j|d}|ddd}| j	
|dd}	tj|	|gdd	}
|r[|
| |
|| }
|
S |
| | j }
|
S )
NzInput image size (*z) doesn't match model (r   rN   ry   r   rJ   r   )r   r  r{   r  r$  rO   r   flattenr   r  r^   r#   r   r&  r   rH   )r9   r'  r&  r  r   r!  r"  Ztarget_dtypeZpatch_embedsZclass_embedsrq   r&   r&   r'   rr     s    
zAltCLIPVisionEmbeddings.forwardr  )r=   r>   r?   r   rQ   r#   r   r|   r&  rA   rr   rt   r&   r&   rd   r'   r  s  s     )r  c                   @   s$   e Zd ZeZdZdZg Zdd ZdS )AltCLIPPreTrainedModelZaltclipTc                 C   s  | j j}t|tr:| j j}tjj|jd|jd | d tjj|j	j
|j j| d tjj|jj
|j j| d dS t|tr| j j}|jd d|j j d  | }|jd | }tjj|jj
|d tjj|jj
|d tjj|jj
|d tjj|jj
|d dS t|tr| j j}|j jd d|j j d  | }d|j j d | }tjj|jj
|d tjj|jj
|d dS t|trtjj|jj
|jd | j j d d|j_tjj|jj
|jd | j j d d|j_dS t|tjr|jj   |j
j!d dS t|tj"r%|j
jjd| j jd |jdur#|jj   dS dS t|tj#rH|j
jjd| j jd |j$durJ|j
j|j$    dS dS dS )	zInitialize the weightsr   r   )meanstd)r,  ry   Tg      ?N)%rc   Zinitializer_factorr   r  r!   initZnormal_r  r   r  r$  Zinitializer_ranger   r   r   r  r  r  r  r	  rS   r  r  AltCLIPModeltext_projectiontext_embed_dimZ_is_hf_initializedvisual_projectionvision_embed_dimrX   r  dataZzero_Zfill_r   rR   rD   )r9   r   factorZin_proj_stdZout_proj_stdZfc_stdr&   r&   r'   _init_weights  sZ   
 

 
z$AltCLIPPreTrainedModel._init_weightsN)	r=   r>   r?   r   config_classZbase_model_prefixZsupports_gradient_checkpointingZ_no_split_moduler5  r&   r&   r&   r'   r*    s    r*  c                       sr   e Zd Zdef fddZe					ddeej dee	 dee	 d	ee	 d
ee	 de
eef fddZ  ZS )AltCLIPVisionTransformerrc   c                    sR   t    || _|j}t|| _tj||jd| _	t
|| _tj||jd| _d S r   )rP   rQ   rc   rS   r  rq   r!   rX   rY   pre_layrnormr  encoderpost_layernorm)r9   rc   r   rd   r&   r'   rQ     s   


z!AltCLIPVisionTransformer.__init__NFr'  r   r   r   r&  r   c           
      C   s   |d ur|n| j j}|d ur|n| j j}|d ur|n| j j}|d u r&td| j||d}| |}| j||||d}|d }|d d dd d f }	| |	}	|s[||	f|dd   S t	||	|j
|jdS )Nz You have to specify pixel_values)r&  )rk   r   r   r   r   r   r   pooler_outputr   r   )rc   r   r   r  r{   rq   r8  r9  r:  r   r   r   )
r9   r'  r   r   r   r&  r   encoder_outputsr   r   r&   r&   r'   rr     s2   	

z AltCLIPVisionTransformer.forward)NNNNF)r=   r>   r?   r   rQ   r   r   r#   rA   r   r   r   r   rr   rt   r&   r&   rd   r'   r7    s*    

r7  c                       s   e Zd ZeZdZdef fddZdejfddZ	e
						ddeej d
ee dee dedee deeef fddZ  ZS )AltCLIPVisionModelr'  rc   c                    s"   t  | t|| _|   d S r   )rP   rQ   r7  vision_model	post_initrb   rd   r&   r'   rQ   5  s   
zAltCLIPVisionModel.__init__r   c                 C   
   | j jjS r   )r?  rq   r  r8   r&   r&   r'   get_input_embeddings;     
z'AltCLIPVisionModel.get_input_embeddingsNFr   r   r&  r   c                 C   s(   |dur|n| j j}| j|||||dS )a  
        Examples:

        ```python
        >>> from PIL import Image
        >>> import requests
        >>> 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"
        >>> image = Image.open(requests.get(url, stream=True).raw)

        >>> 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
        ```Nr'  r   r   r&  r   )rc   r  r?  )r9   r'  r   r   r&  r   r&   r&   r'   rr   >  s   zAltCLIPVisionModel.forwardNNNFN)r=   r>   r?   r   r6  Zmain_input_namerQ   r!   ModulerB  r   r   r#   rA   r   r   r   r   rr   rt   r&   r&   rd   r'   r>  1  s0    
r>  a(  
    The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
    cross-attention is added between the self-attention layers, 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.

    To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
    to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
    `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.

    .. _*Attention is all you need*: https://arxiv.org/abs/1706.03762
    )Zcustom_introc                        s   e Zd ZeZd fdd	Zdd Zdd Zdd	 Ze		
	
	
	
	
	
	
	
	
	
	
	
	
dde
ej de
ej de
ej de
ej de
ej de
ej de
ej de
ej de
eej  de
e de
e de
e de
e deeej ef fddZ  ZS )AltRobertaModelTc                    sD   t  | || _t|| _t|| _|rt|nd| _| 	  dS )zv
        add_pooling_layer (bool, *optional*, defaults to `True`):
            Whether to add a pooling layer
        N)
rP   rQ   rc   rC   rq   r   r9  r   poolerr@  )r9   rc   add_pooling_layerrd   r&   r'   rQ   x  s   

zAltRobertaModel.__init__c                 C   s   | j jS r   rq   rT   r8   r&   r&   r'   rB    s   z$AltRobertaModel.get_input_embeddingsc                 C   s   || j _d S r   rJ  r9   r   r&   r&   r'   set_input_embeddings     z$AltRobertaModel.set_input_embeddingsc                 C   s*   |  D ]\}}| jj| j| qdS )z
        Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
        class PreTrainedModel
        N)itemsr9  r   r   r   )r9   Zheads_to_pruner   r   r&   r&   r'   _prune_heads  s   zAltRobertaModel._prune_headsNrj   r   rM   rH   r   rk   r   r   r   r   r   r   r   r   c                 C   sP  |d ur|n| j j}|d ur|n| j j}|d ur|n| j j}| j jr-|
d ur(|
n| j j}
nd}
|d ur;|d ur;td|d urJ| || | }n|d urW| d d }ntd|\}}|d urf|j	n|j	}|	d urv|	d d j
d nd}|d u rtj||| f|d}|d u rt| jdr| jjd d d |f }|||}|}n	tj|tj|d	}| ||}| j jr|d ur| \}}}||f}|d u rtj||d}| |}nd }| || j j}| j|||||d
}| j||||||	|
|||d
}|d }| jd ur| |nd }|s||f|dd   S t|||j|j|j|jdS )NFzDYou cannot specify both input_ids and inputs_embeds at the same timerJ   z5You have to specify either input_ids or inputs_embedsr   ry   r   rM   rf   )rj   rH   rM   rk   rl   )	r   r   r   r   r   r   r   r   r   r   )r   r<  r   r   r   r   )rc   r   r   r  r   r   r{   Z%warn_if_padding_and_no_attention_maskr`   r    r   r#   Zonesri   rq   rM   r^   r_   ra   Zget_extended_attention_maskZinvert_attention_maskZget_head_maskr   r9  rH  r   r   r   r   r   )r9   rj   r   rM   rH   r   rk   r   r   r   r   r   r   r   rm   r  rn   r    rl   ro   rp   Zextended_attention_maskZencoder_batch_sizeZencoder_sequence_lengthr   Zencoder_hidden_shapeZencoder_extended_attention_maskZembedding_outputr=  sequence_outputr   r&   r&   r'   rr     s   
zAltRobertaModel.forward)T)NNNNNNNNNNNNN)r=   r>   r?   r   r6  rQ   rB  rL  rO  r   r   r#   r   r   rA   r   r   r   r   rr   rt   r&   r&   rd   r'   rG  f  sb    	
rG  c                       s   e Zd ZeZ fddZdejfddZdej	ddfdd	Z
dd
ee dej	f fddZe											ddeej deej deej deej deej deej deej deej dee dee dee deeef fddZ  ZS )AltCLIPTextModelc                    sL   t  | t|dd| _t|j|j| _tj	|j|j
d| _|   d S )NF)rI  rE   )rP   rQ   rG  robertar!   r   rS   project_dimtransformationrX   rY   pre_LNr@  rb   rd   r&   r'   rQ   
  s
   zAltCLIPTextModel.__init__r   c                 C   rA  r   rR  rq   rT   r8   r&   r&   r'   rB    rC  z%AltCLIPTextModel.get_input_embeddingsr   Nc                 C   s   || j j_d S r   rV  rK  r&   r&   r'   rL    s   z%AltCLIPTextModel.set_input_embeddingsnew_num_tokensc                    s   t  |S r   )rP   resize_token_embeddings)r9   rW  rd   r&   r'   rX    rM  z(AltCLIPTextModel.resize_token_embeddingsrj   r   rM   rH   r   rk   r   r   r   r   r   c                 C   s   |
dur|
n| j j}
| j|||||||||	||
d}|d }| |}| |}|dddf }|
s<||f|dd  S t|||j|jd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
        ```N)rj   r   rM   rH   r   rk   r   r   r   r   r   r   ry      r;  )rc   r  rR  rU  rT  r   r   r   )r9   rj   r   rM   rH   r   rk   r   r   r   r   r   r   rP  Zprojection_stater<  r&   r&   r'   rr     s4   !

zAltCLIPTextModel.forwardr   )NNNNNNNNNNN)r=   r>   r?   r   r6  rQ   r!   rF  rB  rR   rL  r   r|   rX  r   r#   r   r   r   r   r   rr   rt   r&   r&   rd   r'   rQ    sV    	

rQ  c                       sL  e Zd ZeZdef fddZe							ddeej	 deej	 deej	 dee
 d	ee
 d
ee
 dejfddZe					ddeej dee
 d	ee
 de
d
ee
 dejfddZe										ddeej deej deej	 deej deej	 dee
 dee
 d	ee
 de
d
ee
 deeef fddZ  ZS )r.  rc   c                    s   t  | t|jtstdt|j dt|jts(tdt|j d|j}|j}|j	| _	|j
| _|j| _t|| _t|| _tj| j| j	dd| _tj| j| j	dd| _tt| jj| _|   d S )NzRconfig.vision_config is expected to be of type AltCLIPVisionConfig but is of type .zNconfig.text_config is expected to be of type AltCLIPTextConfig but is of type F)r  )rP   rQ   r   vision_configr   	TypeErrortypetext_configr   Zprojection_dimrS  r0  rS   r2  rQ  
text_modelr7  r?  r!   r   r1  r/  r  r#   r   rc   Zlogit_scale_init_valuelogit_scaler@  )r9   rc   r^  r[  rd   r&   r'   rQ   c  s0   

zAltCLIPModel.__init__Nrj   r   rH   r   r   r   r   c              	   C   sj   |dur|n| j j}|dur|n| j j}|dur|n| j j}| j|||||||d}|d }	| |	}
|
S )a  
        Returns:
            text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
            applying the projection layer to the pooled output of [`AltCLIPTextModel`].

        Examples:

        ```python
        >>> 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")
        >>> text_features = model.get_text_features(**inputs)
        ```N)rj   r   rH   rM   r   r   r   r   )rc   r   r   r  r_  r/  )r9   rj   r   rH   rM   r   r   r   text_outputsr   Ztext_featuresr&   r&   r'   get_text_features  s    	
zAltCLIPModel.get_text_featuresFr'  r&  c           	      C   sf   |dur|n| j j}|dur|n| j j}|dur|n| j j}| j|||||d}|d }| |}|S )a*  
        Returns:
            image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by
            applying the projection layer to the pooled output of [`AltCLIPVisionModel`].

        Examples:

        ```python
        >>> from PIL import Image
        >>> import requests
        >>> from transformers import AutoProcessor, AltCLIPModel

        >>> model = AltCLIPModel.from_pretrained("BAAI/AltCLIP")
        >>> processor = AutoProcessor.from_pretrained("BAAI/AltCLIP")
        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> image = Image.open(requests.get(url, stream=True).raw)
        >>> inputs = processor(images=image, return_tensors="pt")
        >>> image_features = model.get_image_features(**inputs)
        ```NrD  r   )rc   r   r   r  r?  r1  )	r9   r'  r   r   r&  r   vision_outputsr   Zimage_featuresr&   r&   r'   get_image_features  s   
zAltCLIPModel.get_image_featuresrM   return_lossc              	   C   s(  |dur|n| j j}|dur|n| j j}|
dur|
n| j j}
| j|||||||
d}| j||||	|
d}|d }| |}|d }| |}||jdddd }||jdddd }| j	
 }t|| | }|j}d}|rtt|}|
s||||||f}|dur|f| S |S t|||||||d	S )
a  
        return_loss (`bool`, *optional*):
            Whether or not to return the contrastive loss.

        Examples:

        ```python
        >>> from PIL import Image
        >>> import requests
        >>> from transformers import AutoProcessor, AltCLIPModel

        >>> model = AltCLIPModel.from_pretrained("BAAI/AltCLIP")
        >>> processor = AutoProcessor.from_pretrained("BAAI/AltCLIP")
        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> image = Image.open(requests.get(url, stream=True).raw)
        >>> inputs = processor(
        ...     text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True
        ... )
        >>> 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
        ```N)rj   r   rM   rH   r   r   r   rD  r   ry   rJ   T)r   r   Zkeepdim)r-   r.   r/   r0   r1   r2   r3   )rc   r   r   r  r_  r?  r1  r/  Znormr`  expr#   r   r*   Tr+   r,   )r9   rj   r'  r   rH   rM   re  r   r   r&  r   ra  rc  r1   r0   r`  r/   r.   r-   r   r&   r&   r'   rr     sX   %



zAltCLIPModel.forward)NNNNNNNrE  )
NNNNNNNNFN)r=   r>   r?   r   r6  rQ   r   r   r#   r   r   rA   rb  rd  Z
LongTensorr   r   r,   rr   rt   r&   r&   rd   r'   r.  `  s    	./	

r.  c                 C   s6   |  | }tj|dd|| | }| | S )a  
    Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
    are ignored. This is modified from fairseq's `utils.make_positions`.

    Args:
        x: torch.Tensor x:

    Returns: torch.Tensor
    r   r   )ner|   r#   ZcumsumZtype_asra   )rj   rD   rl   maskZincremental_indicesr&   r&   r'   rg   A  s   rg   )r*  r>  rQ  r.  )r   )r   )Hr@   r   dataclassesr   typingr   r   r   r   r   r   r#   Ztorch.nnr!   Ztorch.utils.checkpointZactivationsr
   Zmodeling_outputsr   r   r   r   r   Zmodeling_utilsr   r   Zpytorch_utilsr   r   r   utilsr   r   r   r   Zconfiguration_altclipr   r   r   Z
get_loggerr=   r   r   r(   r+   r,   rF  rC   ru   r   r   r   r   r   r   r   r   floatr   r   r	  r  r  r  r*  r7  r>  rG  rQ  r.  rg   __all__r&   r&   r&   r'   <module>   s    
%Z 4W^
P2bS465 Y 
b