U
    4Af0                    @   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	 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 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Z(dZ)dZ*dZ+dZ,dZ-e
j.e
j.dddZ/e
j.e
j.dddZ0eG dd deZ1G dd dej2Z3G dd dej2Z4G dd  d ej2Z5d!e4iZ6G d"d# d#ej2Z7G d$d% d%ej2Z8G d&d' d'ej2Z9G d(d) d)ej2Z:G d*d+ d+ej2Z;G d,d- d-ej2Z<G d.d/ d/ej2Z=G d0d1 d1ej2Z>G d2d3 d3ej2Z?G d4d5 d5ej2Z@G d6d7 d7ej2ZAG d8d9 d9eZBG d:d; d;ej2ZCG d<d= d=eBZDG d>d? d?eBZEG d@dA dAeBZFG dBdC dCeBZGdFdDdEZHdS )GzPyTorch AltCLIP model.    N)	dataclass)AnyListOptionalTupleUnion   )ACT2FN)BaseModelOutput)BaseModelOutputWithPastAndCrossAttentionsBaseModelOutputWithPooling,BaseModelOutputWithPoolingAndCrossAttentions'BaseModelOutputWithPoolingAndProjection)PreTrainedModel)apply_chunking_to_forward find_pruneable_heads_and_indicesprune_linear_layer)ModelOutput%add_start_docstrings_to_model_forwardloggingreplace_return_docstrings   )AltCLIPConfigAltCLIPTextConfigAltCLIPVisionConfigzBAAI/AltCLIPr   a=  
    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    Parameters:
        config ([`CLIPConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
a  
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
            it.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        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)
        position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.max_position_embeddings - 1]`.

            [What are position IDs?](../glossary#position-ids)
        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.
aE  
    Args:
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
            [`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
        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.
a  
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
            it.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        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)
        position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.max_position_embeddings - 1]`.

            [What are position IDs?](../glossary#position-ids)
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
            [`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
        return_loss (`bool`, *optional*):
            Whether or not to return the contrastive loss.
        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.
)logitsreturnc                 C   s   t j| tjt| | jdS )Ndevice)nn
functionalZcross_entropytorcharangelenr   )r    r$   P/tmp/pip-unpacked-wheel-zw5xktn0/transformers/models/altclip/modeling_altclip.pycontrastive_loss   s    r&   )
similarityr   c                 C   s    t | }t |  }|| d S )Ng       @)r&   t)r'   Zcaption_lossZ
image_lossr$   r$   r%   	clip_loss   s    r)   c                   @   s   e Zd ZU dZdZeej ed< dZ	ejed< dZ
ejed< dZejed< dZejed< dZeed< dZeed	< ee d
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_outputr   c                    s   t  fdd  D S )Nc                 3   s,   | ]$}|d kr | nt  | V  qdS ))r0   r1   N)getattrto_tuple).0kselfr$   r%   	<genexpr>   s   z)AltCLIPOutput.to_tuple.<locals>.<genexpr>)tuplekeysr7   r$   r7   r%   r4      s    zAltCLIPOutput.to_tuple)__name__
__module____qualname____doc__r+   r   r!   FloatTensor__annotations__r,   r-   r.   r/   r0   r   r1   r   r   r4   r$   r$   r$   r%   r*      s   
r*   c                       s2   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dropoutr3   rE   register_bufferr!   r"   expandzerosrG   sizelongrC   r8   config	__class__r$   r%   rP      s.    
      zAltRobertaEmbeddings.__init__Nr   c                 C   s   |d kr*|d k	r t || j|}n
| |}|d k	r<| }n| d d }|d }|d krt| dr| jd d d |f }||d |}	|	}ntj|tj	| j
jd}|d kr| |}| |}
||
 }| jdkr| |}||7 }| |}| |}|S )NrI   r   rL   r   rN   r   rF   )"create_position_ids_from_input_idsrC   &create_position_ids_from_inputs_embedsr_   hasattrrL   r]   r!   r^   r`   rG   r   rS   rV   rE   rU   rW   r[   )r8   	input_idsrL   rG   inputs_embedspast_key_values_lengthinput_shape
seq_lengthbuffered_token_type_ids buffered_token_type_ids_expandedrV   
embeddingsrU   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
        NrI   r   re   r   )r_   r!   r"   rC   r`   r   Z	unsqueezer]   )r8   rj   rl   Zsequence_lengthrG   r$   r$   r%   rg     s    	   z;AltRobertaEmbeddings.create_position_ids_from_inputs_embeds)NNNNr   )r<   r=   r>   r?   rP   rq   rg   __classcell__r$   r$   rc   r%   rB      s            
(rB   c                
       s   e Zd Zd fdd	ZejejdddZdejeej eej eej eej ee	e	ej   ee
 e	ej d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| _|pt|dd| _| jdks| jd	kr|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 ()rE   rF   relative_keyrelative_key_query   r   )rO   rP   rR   num_attention_headsrh   
ValueErrorintattention_head_sizeall_head_sizer   LinearquerykeyvaluerY   Zattention_probs_dropout_probr[   r3   rE   rT   rQ   distance_embedding
is_decoderr8   rb   rE   rc   r$   r%   rP     s*    
  z AltRobertaSelfAttention.__init__)xr   c                 C   s6   |  d d | j| jf }||}|ddddS )NrI   r   rw   r   r   )r_   rx   r{   viewpermute)r8   r   Znew_x_shaper$   r$   r%   transpose_for_scores9  s    
z,AltRobertaSelfAttention.transpose_for_scoresFhidden_statesattention_mask	head_maskencoder_hidden_statesencoder_attention_maskpast_key_valueoutput_attentionsr   c                 C   s  |  |}|d k	}	|	r4|d k	r4|d }
|d }|}n|	r^| | |}
| | |}|}nv|d k	r| | |}
| | |}tj|d |
gdd}
tj|d |gdd}n | | |}
| | |}| |}|d k	}| jr|
|f}t||
dd}| j	dks | j	dkr|j
d |
j
d  }}|r^t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||}|| }n4| j	dkrtd||}td|
|}|| | }|t| j }|d k	r:|| }tjj|dd}| |}|d k	rf|| }t||}|dddd }| d d | jf }||}|r||fn|f}| jr||f }|S )Nr   r   rw   dimrI   ru   rv   re   rM   zbhld,lrd->bhlrzbhrd,lrd->bhlrr   ) r~   r   r   r   r!   catr   matmul	transposerE   shapetensorr`   r   r   r"   r   rT   torN   Zeinsummathsqrtr{   r   r    softmaxr[   r   
contiguousr_   r|   )r8   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%   rq   >  sp    


 





zAltRobertaSelfAttention.forward)N)NNNNNF)r<   r=   r>   rP   r!   Tensorr   r   r@   r   boolrq   rr   r$   r$   rc   r%   rs     s$         rs   c                       s4   e Zd Z fddZejejejdddZ  ZS )AltRobertaSelfOutputc                    sB   t    t|j|j| _tj|j|jd| _t|j	| _
d S NrD   )rO   rP   r   r}   rR   denserW   rX   rY   rZ   r[   ra   rc   r$   r%   rP     s    
zAltRobertaSelfOutput.__init__r   input_tensorr   c                 C   s&   |  |}| |}| || }|S Nr   r[   rW   r8   r   r   r$   r$   r%   rq     s    

zAltRobertaSelfOutput.forwardr<   r=   r>   rP   r!   r   rq   rr   r$   r$   rc   r%   r     s   r   eagerc                
       sv   e Zd Zd
 fdd	Zdd Zdejeej eej eej eej ee	e	ej   ee
 e	ej ddd	Z  ZS )AltRobertaAttentionNc                    s4   t    t|j ||d| _t|| _t | _d S )NrE   )	rO   rP   "ALT_ROBERTA_SELF_ATTENTION_CLASSESZ_attn_implementationr8   r   outputsetpruned_headsr   rc   r$   r%   rP     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   r8   rx   r{   r   r   r~   r   r   r   r   r|   union)r8   headsindexr$   r$   r%   prune_heads  s       zAltRobertaAttention.prune_headsFr   c              	   C   s<   |  |||||||}| |d |}	|	f|dd   }
|
S )Nr   r   )r8   r   )r8   r   r   r   r   r   r   r   Zself_outputsattention_outputr   r$   r$   r%   rq     s    
	zAltRobertaAttention.forward)N)NNNNNF)r<   r=   r>   rP   r   r!   r   r   r@   r   r   rq   rr   r$   r$   rc   r%   r     s$         r   c                       s0   e Zd Z fddZejejdddZ  ZS )AltRobertaIntermediatec                    sB   t    t|j|j| _t|jt	r6t
|j | _n|j| _d S r   )rO   rP   r   r}   rR   intermediate_sizer   
isinstance
hidden_actstrr	   intermediate_act_fnra   rc   r$   r%   rP     s
    
zAltRobertaIntermediate.__init__r   r   c                 C   s   |  |}| |}|S r   )r   r   r8   r   r$   r$   r%   rq     s    

zAltRobertaIntermediate.forwardr   r$   r$   rc   r%   r     s   r   c                       s4   e Zd Z fddZejejejdddZ  ZS )AltRobertaOutputc                    sB   t    t|j|j| _tj|j|jd| _t	|j
| _d S r   )rO   rP   r   r}   r   rR   r   rW   rX   rY   rZ   r[   ra   rc   r$   r%   rP     s    
zAltRobertaOutput.__init__r   c                 C   s&   |  |}| |}| || }|S r   r   r   r$   r$   r%   rq     s    

zAltRobertaOutput.forwardr   r$   r$   rc   r%   r     s   r   c                
       st   e Zd Z fddZd
ejeej eej eej eej eeeej   ee	 eej dddZ
dd	 Z  ZS )AltRobertaLayerc                    sr   t    |j| _d| _t|| _|j| _|j| _| jrZ| jsLt|  dt|dd| _	t
|| _t|| _d S )Nr   z> should be used as a decoder model if cross attention is addedrF   r   )rO   rP   chunk_size_feed_forwardseq_len_dimr   	attentionr   add_cross_attentionry   crossattentionr   intermediater   r   ra   rc   r$   r%   rP     s    


zAltRobertaLayer.__init__NFr   c              	   C   s  |d k	r|d d nd }| j |||||d}	|	d }
| jrP|	dd }|	d }n|	dd  }d }| jr|d k	rt| dstd|  d|d k	r|d	d  nd }| |
||||||}|d }
||dd  }|d }|| }t| j| j| j|
}|f| }| jr||f }|S )
Nrw   )r   r   r   r   rI   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   rh   ry   r   r   feed_forward_chunkr   r   )r8   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%   rq     sV    


	   

zAltRobertaLayer.forwardc                 C   s   |  |}| ||}|S r   )r   r   )r8   r   Zintermediate_outputr   r$   r$   r%   r   \  s    
z"AltRobertaLayer.feed_forward_chunk)NNNNNF)r<   r=   r>   rP   r!   r   r   r@   r   r   rq   r   rr   r$   r$   rc   r%   r     s$         Ar   c                       s   e Zd Z fddZd	ejeej eej eej eej eeeej   ee	 ee	 ee	 ee	 e
eej ef dddZ  ZS )
AltRobertaEncoderc                    s:   t     | _t fddt jD | _d| _d S )Nc                    s   g | ]}t  qS r$   )r   r5   _rb   r$   r%   
<listcomp>g  s     z.AltRobertaEncoder.__init__.<locals>.<listcomp>F)	rO   rP   rb   r   
ModuleListrangenum_hidden_layerslayergradient_checkpointingra   rc   r   r%   rP   d  s    
 zAltRobertaEncoder.__init__NFT)r   r   r   r   r   past_key_valuesr   r   output_hidden_statesreturn_dictr   c                 C   sb  |	rdnd }|rdnd }|r(| j jr(dnd }| jrJ| jrJ|rJtd d}|rRdnd }t| jD ]\}}|	rv||f }|d k	r|| nd }|d k	r|| nd }| jr| jr| |j	|||||||}n||||||||}|d }|r||d f7 }|r`||d f }| j jr`||d f }q`|	r.||f }|
sPt
dd	 |||||fD S t|||||d
S )Nr$   zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fr   rI   r   rw   c                 s   s   | ]}|d k	r|V  qd S r   r$   r5   vr$   r$   r%   r9     s   z,AltRobertaEncoder.forward.<locals>.<genexpr>)last_hidden_stater   r   
attentionscross_attentions)rb   r   r   trainingloggerZwarning_once	enumerater   _gradient_checkpointing_func__call__r:   r   )r8   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%   rq   j  sx    


zAltRobertaEncoder.forward)	NNNNNNFFT)r<   r=   r>   rP   r!   r   r   r@   r   r   r   r   rq   rr   r$   r$   rc   r%   r   c  s.   	         r   c                       s0   e Zd Z fddZejejdddZ  ZS )AltRobertaPoolerc                    s*   t    t|j|j| _t | _d S r   )rO   rP   r   r}   rR   r   ZTanh
activationra   rc   r$   r%   rP     s    
zAltRobertaPooler.__init__r   c                 C   s(   |d d df }|  |}| |}|S )Nr   )r   r   )r8   r   Zfirst_token_tensorpooled_outputr$   r$   r%   rq     s    

zAltRobertaPooler.forwardr   r$   r$   rc   r%   r     s   r   c                	       sn   e Zd ZdZ fddZejeedddZdeje	ej e	ej e	e
 eeje	ej f d	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rZtd| j d| j d| jd | _	|j
| _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`: z).      )rO   rP   rb   rR   	embed_dimrx   	num_headshead_dimry   scaleZattention_dropoutr[   r   r}   k_projv_projq_projout_projra   rc   r$   r%   rP     s    
zAltCLIPAttention.__init__)r   seq_lenbszc                 C   s    | ||| j| jdd S )Nr   rw   )r   r   r   r   r   )r8   r   r   r   r$   r$   r%   _shape  s    zAltCLIPAttention._shapeNFr   r   causal_attention_maskr   r   c                 C   s  |  \}}}| || j }| | |d|}	| | |d|}
|| j d| jf}| |||j| }|	j| }	|
j| }
|	 d}t	
||	dd}|  || j ||fkrtd|| j ||f d|   |dk	rD|  |d||fkrtd|d||f d|   ||| j||| }||| j ||}|dk	r|  |d||fkrtd|d||f d|   ||| j||| }||| j ||}tjj|dd}|r||| j||}||| j ||}nd}tjj|| j| jd	}t	
||
}|  || j || jfkrRtd
|| j|| jf d|   ||| j|| j}|dd}||||}| |}||fS )z#Input shape: Batch x Time x ChannelrI   r   rw   z$Attention weights should be of size z	, but is Nz!Attention mask should be of size r   )pr   z `attn_output` should be of size )r_   r   r   r   r   r   r   r   r   r!   Zbmmr   ry   r   r    r   r[   r   Zreshaper   )r8   r   r   r   r   r   Ztgt_lenr   Zquery_statesZ
key_statesZvalue_statesZ
proj_shapeZsrc_lenattn_weightsZattn_weights_reshapedZ
attn_probsZattn_outputr$   r$   r%   rq     sX    	





zAltCLIPAttention.forward)NNF)r<   r=   r>   r?   rP   r!   r   rz   r   r   r   r   rq   rr   r$   r$   rc   r%   r     s      r   c                       s0   e Zd Z fddZejejdddZ  ZS )
AltCLIPMLPc                    sD   t    || _t|j | _t|j|j	| _
t|j	|j| _d S r   )rO   rP   rb   r	   r   activation_fnr   r}   rR   r   fc1fc2ra   rc   r$   r%   rP   ;  s
    
zAltCLIPMLP.__init__r   c                 C   s"   |  |}| |}| |}|S r   )r   r   r   r   r$   r$   r%   rq   B  s    


zAltCLIPMLP.forwardr   r$   r$   rc   r%   r   :  s   r   c                       sJ   e Zd Zed fddZdejejejee e	ej
 dddZ  ZS )	AltCLIPEncoderLayerr   c                    sR   t    |j| _t|| _tj| j|jd| _	t
|| _tj| j|jd| _d S r   )rO   rP   rR   r   r   	self_attnr   rW   rX   layer_norm1r   mlplayer_norm2ra   rc   r$   r%   rP   J  s    


zAltCLIPEncoderLayer.__init__Fr   c                 C   sd   |}|  |}| j||||d\}}|| }|}| |}| |}|| }|f}|r`||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   )r8   r   r   r   r   Zresidualr   r   r$   r$   r%   rq   R  s"    




zAltCLIPEncoderLayer.forward)F)r<   r=   r>   r   rP   r!   r   r   r   r   r@   rq   rr   r$   r$   rc   r%   r   I  s    r   c                	       s`   e Zd ZdZed fddZd	eej eej ee	 ee	 ee	 e
eef d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
    r   c                    s:   t     | _t fddt jD | _d| _d S )Nc                    s   g | ]}t  qS r$   )r   r   r   r$   r%   r     s     z+AltCLIPEncoder.__init__.<locals>.<listcomp>F)	rO   rP   rb   r   r   r   r   layersr   ra   rc   r   r%   rP     s    
 zAltCLIPEncoder.__init__N)r   r   r   r   r   r   c                 C   s   |dk	r|n| j j}|dk	r |n| j j}|dk	r4|n| j j}|rDdnd}|rPdnd}|}	t| jD ]b\}
}|rx||	f }| jr| jr| |j	|	|||}n||	|||d}|d }	|rb||d f }qb|r||	f }|st
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   s   | ]}|d k	r|V  qd S r   r$   r   r$   r$   r%   r9     s      z)AltCLIPEncoder.forward.<locals>.<genexpr>)r   r   r   )rb   r   r   use_return_dictr   r   r   r   r   r   r:   r
   )r8   rj   r   r   r   r   r   Zencoder_statesZall_attentionsr   idxZencoder_layerr   r$   r$   r%   rq     sH    &

  zAltCLIPEncoder.forward)NNNNN)r<   r=   r>   r?   r   rP   r   r!   r   r   r   r   r
   rq   rr   r$   r$   rc   r%   r   {  s   	     
r   c                       s6   e Zd Zed fddZejejdddZ  Z	S )AltCLIPVisionEmbeddingsr   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biasrw   r   rG   rH   rJ   )rO   rP   rb   rR   r   Z
image_sizeZ
patch_sizer   	Parameterr!   Zrandnclass_embeddingZConv2dZnum_channelspatch_embeddingZnum_patchesZnum_positionsrQ   position_embeddingr\   r"   r]   ra   rc   r$   r%   rP     s"    
z AltCLIPVisionEmbeddings.__init__)pixel_valuesr   c                 C   sn   |j d }| jjj}| |j|d}|ddd}| j|dd}t	j
||gdd}|| | j }|S )Nr   rM   rw   r   rI   r   )r   r  weightrN   r   flattenr   r  r]   r!   r   r  rG   )r8   r  
batch_sizeZtarget_dtypeZpatch_embedsZclass_embedsrp   r$   r$   r%   rq     s    

zAltCLIPVisionEmbeddings.forward)
r<   r=   r>   r   rP   r!   r@   r   rq   rr   r$   r$   rc   r%   r    s   r  c                   @   s(   e Zd ZdZeZdZdZg Zdd Z	dS )AltCLIPPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    ZaltclipTc                 C   s  | j j}t|trt| 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 n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 nt|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 n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_nt|tjr|jj   |j
j!d nt|tj"rF|j
jjd| j jd |jdk	r|jj   nBt|tj#r|j
jjd| j jd |j$dk	r|j
j|j$    dS )	zInitialize the weightsg        r   )Zmeanstd)r  rw   Tg      ?N)%rb   Zinitializer_factorr   r  r   initZnormal_r  r   r  r	  Zinitializer_ranger  r   r   r   r   r   r   r   rR   r   r   AltCLIPModeltext_projectiontext_embed_dimZ_is_hf_initializedvisual_projectionvision_embed_dimrW   r  dataZzero_Zfill_r}   rQ   rC   )r8   moduleZfactorZin_proj_stdZout_proj_stdZfc_stdr$   r$   r%   _init_weights  sT    
  
z$AltCLIPPreTrainedModel._init_weightsN)
r<   r=   r>   r?   r   config_classZbase_model_prefixZsupports_gradient_checkpointingZ_no_split_moduler  r$   r$   r$   r%   r     s   r  c                
       sh   e Zd Zed fddZeeeeedd	e	e
j e	e e	e e	e eeef dddZ  ZS )
AltCLIPVisionTransformerr   c                    sR   t    || _|j}t|| _tj||jd| _	t
|| _tj||jd| _d S r   )rO   rP   rb   rR   r  rp   r   rW   rX   pre_layrnormr   encoderpost_layernorm)r8   rb   r   rc   r$   r%   rP   :  s    


z!AltCLIPVisionTransformer.__init__output_typer  Nr  r   r   r   r   c           	      C   s   |dk	r|n| j j}|dk	r |n| j j}|dk	r4|n| j j}|dkrLtd| |}| |}| j||||d}|d }|dddddf }| |}|s||f|dd  S t	|||j
|jdS )z
        Returns:

        Nz You have to specify pixel_values)rj   r   r   r   r   r   r   pooler_outputr   r   )rb   r   r   r   ry   rp   r  r  r  r   r   r   )	r8   r  r   r   r   r   encoder_outputsr   r   r$   r$   r%   rq   D  s2    


z AltCLIPVisionTransformer.forward)NNNN)r<   r=   r>   r   rP   r   ALTCLIP_VISION_INPUTS_DOCSTRINGr   r   r   r!   r@   r   r   r   rq   rr   r$   r$   rc   r%   r  9  s   

    
r  c                
       s   e Zd ZeZdZed fddZejdddZ	e
eeeeddeej ee ee ee eeef d
ddZ  ZS )AltCLIPVisionModelr  r   c                    s"   t  | t|| _|   d S r   )rO   rP   r  vision_model	post_initra   rc   r$   r%   rP   w  s    
zAltCLIPVisionModel.__init__r2   c                 C   s
   | j jjS r   )r$  rp   r  r7   r$   r$   r%   get_input_embeddings}  s    z'AltCLIPVisionModel.get_input_embeddingsr  Nr  c                 C   s&   |dk	r|n| j j}| j||||dS )a  
        Returns:

        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   )rb   r   r$  )r8   r  r   r   r   r$   r$   r%   rq     s    zAltCLIPVisionModel.forward)NNNN)r<   r=   r>   r   r  Zmain_input_namerP   r   Moduler&  r   r"  r   r   r   r!   r@   r   r   r   rq   rr   r$   r$   rc   r%   r#  s  s"   
    
r#  c                       s   e Zd ZdZeZd fdd	Zdd Zdd Zd	d
 Z	de
ej e
ej e
ej e
ej e
ej e
ej e
ej e
ej e
eej  e
e e
e e
e e
e eeej ef dddZ  ZS )AltRobertaModela*  

    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

    Tc                    sD   t  | || _t|| _t|| _|r2t|nd | _| 	  d S r   )
rO   rP   rb   rB   rp   r   r  r   poolerr%  )r8   rb   add_pooling_layerrc   r$   r%   rP     s    

zAltRobertaModel.__init__c                 C   s   | j jS r   rp   rS   r7   r$   r$   r%   r&    s    z$AltRobertaModel.get_input_embeddingsc                 C   s   || j _d S r   r,  r8   r   r$   r$   r%   set_input_embeddings  s    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)itemsr  r   r   r   )r8   Zheads_to_pruner   r   r$   r$   r%   _prune_heads  s    zAltRobertaModel._prune_headsN)ri   r   rL   rG   r   rj   r   r   r   r   r   r   r   r   c                 C   s^  |dk	r|n| j j}|dk	r |n| j j}|dk	r4|n| j j}| j jrZ|
dk	rP|
n| j j}
nd}
|dk	rx|dk	rxtdn@|dk	r| || | }n"|dk	r| dd }ntd|\}}|dk	r|j	n|j	}|	dk	r|	d d j
d nd}|dkrtj||| f|d}|dkrft| jd	rT| jjddd|f }|||}|}ntj|tj|d
}| ||}| j jr|dk	r| \}}}||f}|dkrtj||d}| |}nd}| || j j}| j|||||d}| j||||||	|
|||d
}|d }| jdk	r$| |nd}|sB||f|dd  S t|||j|j|j|jdS )a  
        encoder_hidden_states  (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
            the model is configured as a decoder.
        encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
            the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.
        past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
            Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.

            If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
            don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
            `decoder_input_ids` of shape `(batch_size, sequence_length)`.
        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`).
        NFzDYou cannot specify both input_ids and inputs_embeds at the same timerI   z5You have to specify either input_ids or inputs_embedsr   rw   r   rL   re   )ri   rG   rL   rj   rk   )	r   r   r   r   r   r   r   r   r   r   )r   r   r   r   r   r   )rb   r   r   r   r   r   ry   Z%warn_if_padding_and_no_attention_maskr_   r   r   r!   Zonesrh   rp   rL   r]   r^   r`   Zget_extended_attention_maskZinvert_attention_maskZget_head_maskr   r  r*  r   r   r   r   r   )r8   ri   r   rL   rG   r   rj   r   r   r   r   r   r   r   rl   r  rm   r   rk   rn   ro   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%   rq     s    $




zAltRobertaModel.forward)T)NNNNNNNNNNNNN)r<   r=   r>   r?   r   r  rP   r&  r.  r0  r   r!   r   r   r@   r   r   r   r   rq   rr   r$   r$   rc   r%   r)    sF                r)  c                       s   e Zd ZeZ fddZejdddZej	dddd	Z
dee ej	d
 fddZeeeeeddeej eej eej eej eej eej eej eej ee ee ee eeef dddZ  ZS )AltCLIPTextModelc                    sL   t  | t|dd| _t|j|j| _tj	|j|j
d| _|   d S )NF)r+  rD   )rO   rP   r)  robertar   r}   rR   project_dimtransformationrW   rX   pre_LNr%  ra   rc   r$   r%   rP   ]  s
    zAltCLIPTextModel.__init__r2   c                 C   s
   | j jjS r   r3  rp   rS   r7   r$   r$   r%   r&  d  s    z%AltCLIPTextModel.get_input_embeddingsN)r   r   c                 C   s   || j j_d S r   r7  r-  r$   r$   r%   r.  g  s    z%AltCLIPTextModel.set_input_embeddings)new_num_tokensr   c                    s   t  |S r   )rO   resize_token_embeddings)r8   r8  rc   r$   r%   r9  j  s    z(AltCLIPTextModel.resize_token_embeddingsr  )ri   r   rL   rG   r   rj   r   r   r   r   r   r   c                 C   s   |
dk	r|
n| j j}
| j|||||||||	||
d}|d }| |}| |}|dddf }|
sx||f|dd  S t|||j|jdS )a=  
        Returns:

        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)ri   r   rL   rG   r   rj   r   r   r   r   r   r   rw      r  )rb   r   r3  r6  r5  r   r   r   )r8   ri   r   rL   rG   r   rj   r   r   r   r   r   r   r1  Zprojection_stater   r$   r$   r%   rq   m  s4    $

zAltCLIPTextModel.forward)N)NNNNNNNNNNN)r<   r=   r>   r   r  rP   r   r(  r&  rQ   r.  r   rz   r9  r   ALTCLIP_TEXT_INPUTS_DOCSTRINGr   r   r!   r   r   r   r   rq   rr   r$   r$   rc   r%   r2  Z  s@   
           
r2  c                       s
  e Zd ZeZed fddZeedee	j
 ee	j
 ee	j
 ee ee ee e	jdddZeedee	j ee ee ee e	jdd	d
Zeeeeeddee	j ee	j ee	j
 ee	j ee	j
 ee ee ee ee eeef d
ddZ  ZS )r  r   c                    s   t  | t|jts.tdt|j dt|jtsPt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  )rO   rP   r   vision_configr   	TypeErrortypetext_configr   Zprojection_dimr4  r  rR   r  r2  
text_modelr  r$  r   r}   r  r  r  r!   r   rb   Zlogit_scale_init_valuelogit_scaler%  )r8   rb   r@  r=  rc   r$   r%   rP     s(    

zAltCLIPModel.__init__N)ri   r   rG   r   r   r   r   c              	   C   sj   |dk	r|n| j j}|dk	r |n| j j}|dk	r4|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)ri   r   rG   rL   r   r   r   r   )rb   r   r   r   rA  r  )r8   ri   r   rG   rL   r   r   r   text_outputsr   Ztext_featuresr$   r$   r%   get_text_features  s     	
zAltCLIPModel.get_text_featuresr  c                 C   sd   |dk	r|n| j j}|dk	r |n| j j}|dk	r4|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)
        ```Nr'  r   )rb   r   r   r   r$  r  )r8   r  r   r   r   vision_outputsr   Zimage_featuresr$   r$   r%   get_image_features  s    
zAltCLIPModel.get_image_featuresr  )
ri   r  r   rG   rL   return_lossr   r   r   r   c
              	   C   s*  |dk	r|n| j j}|dk	r |n| j j}|	dk	r4|	n| j j}	| j|||||||	d}
| j||||	d}|d }| |}|
d }| |}||jdddd }||jdddd }| j	
 }t|| | }|j}d}|rt|}|	s|||||
|f}|dk	r|f| S |S t||||||
|d	S )
al  
        Returns:

        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)ri   r   rL   rG   r   r   r   r'  r   rw   rI   T)r   r   Zkeepdim)r+   r,   r-   r.   r/   r0   r1   )rb   r   r   r   rA  r$  r  r  ZnormrB  expr!   r   r(   Tr)   r*   )r8   ri   r  r   rG   rL   rG  r   r   r   rC  rE  r/   r.   rB  r-   r,   r+   r   r$   r$   r%   rq   5  sV    $



zAltCLIPModel.forward)NNNNNNN)NNNN)	NNNNNNNNN)r<   r=   r>   r   r  rP   r   r;  r   r!   r   r   r@   rD  r"  rF  ALTCLIP_INPUTS_DOCSTRINGr   r*   Z
LongTensorr   r   rq   rr   r$   r$   rc   r%   r    sl          .    -
         
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   )nerz   r!   ZcumsumZtype_asr`   )ri   rC   rk   maskZincremental_indicesr$   r$   r%   rf     s    rf   )r   )Ir?   r   Zdataclassesr   typingr   r   r   r   r   r!   Ztorch.nnr   Ztorch.utils.checkpointZactivationsr	   Zmodeling_outputsr
   r   r   r   r   Zmodeling_utilsr   Zpytorch_utilsr   r   r   utilsr   r   r   r   Zconfiguration_altclipr   r   r   Z
get_loggerr<   r   Z_CHECKPOINT_FOR_DOCZ_CONFIG_FOR_DOCZALTCLIP_START_DOCSTRINGr;  r"  rJ  r   r&   r)   r*   r(  rB   rs   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r#  r)  r2  r  rf   r$   r$   r$   r%   <module>   sd   
 (%Z  4W^i2b#9:6 2\ ^