o
    ZhNQ                    @   s(  d Z ddlZddlmZ ddlmZ ddlmZmZm	Z	m
Z
 ddlZddlZddlmZ ddlmZ dd	lmZmZ dd
lmZmZmZmZmZ ddl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& e!'e(Z)dZ*eG dd deZ+eG dd deZ,G dd dej-Z.G dd dej-Z/G dd dej-Z0G dd dej-Z1G dd dej-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-Z7d)e7iZ8G d*d+ d+ej-Z9G d,d- d-ej-Z:G d.d/ d/ej-Z;G d0d1 d1ej-Z<G d2d3 d3ej-Z=dSd4d5Z>e G d6d7 d7eZ?G d8d9 d9e?Z@e d:d;G d<d= d=e?ZAe d>d;G d?d@ d@e?ZBG dAdB dBej-ZCG dCdD dDej-ZDG dEdF dFej-ZEe dGd;G dHdI dIe?ZFe dJd;G dKdL dLe?ZGG dMdN dNej-ZHe dOd;G dPdQ dQe?ZIg dRZJdS )TzPyTorch BridgeTower Model    N)OrderedDict)	dataclass)ListOptionalTupleUnion)nn)CrossEntropyLoss   )ACT2FNQuickGELUActivation))BaseModelOutputWithPastAndCrossAttentions,BaseModelOutputWithPoolingAndCrossAttentionsMaskedLMOutputModelOutputSequenceClassifierOutput)PreTrainedModelapply_chunking_to_forward) find_pruneable_heads_and_indicesprune_linear_layer)auto_docstringlogging	torch_int   )BridgeTowerConfigBridgeTowerTextConfigBridgeTowerVisionConfigZRobertaTokenizerc                   @   st   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ej  ed< dZeeej  ed< dS )BridgeTowerModelOutputa  
    Output type of [`BridgeTowerModel`].

    Args:
        text_features (`torch.FloatTensor` of shape `(batch_size, text_sequence_length, hidden_size)`):
            Sequence of hidden-states at the text output of the last layer of the model.
        image_features (`torch.FloatTensor` of shape `(batch_size, image_sequence_length, hidden_size)`):
            Sequence of hidden-states at the image output of the last layer of the model.
        pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size x 2)`):
            Concatenation of last layer hidden-state of the first token of the text and image sequence (classification
            token), respectively, after further processing through layers used for auxiliary pretraining tasks.
        hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
            one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of
            the model at the output of each layer plus the optional initial embedding outputs.
        attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.
    Ntext_featuresimage_featurespooler_outputhidden_states
attentions)__name__
__module____qualname____doc__r   r   torchFloatTensor__annotations__r   r    r!   r   r"    r*   r*   c/var/www/auris/lib/python3.10/site-packages/transformers/models/bridgetower/modeling_bridgetower.pyr   .   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ej  ed< dZeeej  ed< dZeeej  ed< dZeeej  ed< dZeeej  ed	< dS )
BridgeTowerContrastiveOutputaZ  
    Output type of ['BridgeTowerForContrastiveLearning']

    Args:
        loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`:
            Image-text contrastive loss.
        logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
            Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
        text_embeds (`torch.FloatTensor)`, *optional*, returned when model is initialized with `with_projection=True`):
            The text embeddings obtained by applying the projection layer to the pooler_output.
        image_embeds (`torch.FloatTensor)`, *optional*, returned when model is initialized with `with_projection=True`):
            The image embeddings obtained by applying the projection layer to the pooler_output.
        cross_embeds  (`torch.FloatTensor)`, *optional*, returned when model is initialized with `with_projection=True`):
            The text-image cross-modal embeddings obtained by applying the projection layer to the pooler_output.
        hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
            one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of
            the model at the output of each layer plus the optional initial embedding outputs.
        attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.
    Nlosslogitstext_embedsimage_embedscross_embedsr!   r"   )r#   r$   r%   r&   r-   r   r'   r(   r)   r.   r/   r   r0   r1   r!   r"   r*   r*   r*   r+   r,   N   s   
 r,   c                       sN   e Zd Z fddZdejdejfddZd
dejdeej fdd	Z  Z	S )BridgeTowerResidualAttentionc              
      s   t    t|j|jd | _tj|j|jd| _t	t
dt|j|jd fdt fdt|jd |jfg| _tj|j|jd| _d | _d S )N@   Zepsc_fc   Zgeluc_proj)super__init__r   ZMultiheadAttentionhidden_sizeattn	LayerNormlayer_norm_epsln_1Z
ModuleDictr   Linearr   mlpln_2	attn_maskselfconfig	__class__r*   r+   r9   q   s   
	
z%BridgeTowerResidualAttention.__init__hidden_stateattention_maskc                 C   sZ   |d ur|j tj|jd}| jd ur| jj |j|jdnd | _| j|||d| j|dd S )NdtypedeviceF)Zneed_weightsrB   Zkey_padding_maskr   )tor'   boolrL   rB   rK   r;   )rD   rH   rI   r*   r*   r+   	attention   s    
z&BridgeTowerResidualAttention.attentionNc                 C   sH   ||  | || }| |}| j D ]\}}||}q|| }|S N)rO   r>   rA   r@   items)rD   rH   rI   Zresidual_state_layerr*   r*   r+   forward   s   

z$BridgeTowerResidualAttention.forwardrP   )
r#   r$   r%   r9   r'   TensorrO   r   rT   __classcell__r*   r*   rF   r+   r2   p   s    $r2   c                       s8   e Zd Z fddZddejdeej fddZ  ZS )	BridgeTowerTransformerc                    sr   t     j| _ j| _ jr#t fddt| jd D | _nt fddt| jD | _ j	| _	d S )Nc                       g | ]}t  qS r*   r2   .0rR   rE   r*   r+   
<listcomp>       z3BridgeTowerTransformer.__init__.<locals>.<listcomp>r   c                    rX   r*   rY   rZ   r\   r*   r+   r]      r^   )
r8   r9   r:   num_hidden_layersZremove_last_layerr   
ModuleListrange	resblocksstop_gradientrC   rF   r\   r+   r9      s   
zBridgeTowerTransformer.__init__NrH   rI   c                 C   s>   g }| j D ]}|||}| jr||  q|| q|S rP   )rb   rc   appenddetach)rD   rH   rI   r!   blockr*   r*   r+   rT      s   

zBridgeTowerTransformer.forwardrP   )	r#   r$   r%   r9   r'   rU   r   rT   rV   r*   r*   rF   r+   rW      s    $rW   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 )BridgeTowerVisionEmbeddingsrE   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bias   r   position_idsr   
persistent)r8   r9   rE   r:   Z	embed_dim
image_size
patch_sizer   	Parameterr'   Zrandnclass_embeddingConv2dZnum_channelspatch_embeddingnum_patchesnum_positions	Embeddingposition_embeddingregister_bufferarangeexpandrC   rF   r*   r+   r9      s"   
"z$BridgeTowerVisionEmbeddings.__init__
embeddingsheightwidthreturnc                 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   Nrl         ?r
   ri   ZbicubicF)sizemodeZalign_cornersdim)shaperx   weight	unsqueezer'   Zjit
is_tracingrj   rp   r   Zreshapepermuter   
functionalinterpolateviewcat)rD   r|   r}   r~   ru   rx   rv   Zclass_pos_embedZpatch_pos_embedr   Z
new_heightZ	new_widthZsqrt_num_positionsr*   r*   r+   interpolate_pos_encoding   s*   



z4BridgeTowerVisionEmbeddings.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 (z).rK   ri   r   rl   r   )r   ro   
ValueErrorrt   r   rK   rM   flatten	transposerr   r{   r'   r   r   rx   rj   )rD   r   r   
batch_sizerR   r}   r~   Ztarget_dtypeZpatch_embedsZclass_embedsr|   r*   r*   r+   rT      s    
z#BridgeTowerVisionEmbeddings.forwardF)r#   r$   r%   r   r9   r'   rU   intr   r(   rT   rV   r*   r*   rF   r+   rg      s     )rg   c                       s\   e Zd Z fddZ	ddejdefddZ	ddejdefdd	Zd
ejfddZ	  Z
S )BridgeTowerVisionTransformerc                    s|   t    t | _tj j jd| _t	 | _
tj j jd| _ j| _ js<t fddt jD | _d S d S )Nr4   c                    s   g | ]}t j j jd qS )r4   )r   r<   r:   r=   rZ   r\   r*   r+   r]     s    z9BridgeTowerVisionTransformer.__init__.<locals>.<listcomp>)r8   r9   rg   r|   r   r<   r:   r=   ln_prerW   transformerln_postshare_layernormr`   ra   r_   ln_separaterC   rF   r\   r+   r9     s   



z%BridgeTowerVisionTransformer.__init__Fr   r   c                 C   s   |  ||}| |}|ddd}| ||}tj|dd}|dddd}| jr1| |}|S g }t|| j	D ]\}}||}|
| q9tj|dd}|S )Nr   r   ri   r   r
   )r|   r   r   r   r'   stackr   r   zipr   rd   )rD   r   rI   r   r!   Zhidden_states_stacklnr*   r*   r+   rT     s   

z$BridgeTowerVisionTransformer.forwardc                 C   s*   | j ||d}| |}|ddd}|S )Nr   r   r   ri   )r|   r   r   )rD   r   r   r!   r*   r*   r+   forward_pre3  s   
z(BridgeTowerVisionTransformer.forward_prerH   c                 C   s   | ddd}| |}|S )Nr   r   ri   )r   r   )rD   rH   Zvisual_output_postr*   r*   r+   forward_post>  s   
z)BridgeTowerVisionTransformer.forward_postr   )r#   r$   r%   r9   r'   rU   rN   rT   r   r   rV   r*   r*   rF   r+   r   
  s    

r   c                       $   e Zd Z fddZdd Z  ZS )BridgeTowerLinkTowerc                    s   t    |j| _|j| _|jdv r;|jdkr!ttd| _n|jdkr/ttd| _	tj
| j|jd| _
d S td|j d)	N)add
scaled_addr   r         ?r   r   r4   link_tower_type  is not implemented)r8   r9   link_tower_typer:   r   rq   r'   tensorscaled_factorbetar<   r=   NotImplementedErrorrC   rF   r*   r+   r9   E  s   



zBridgeTowerLinkTower.__init__c                 C   sp   | j dkr| || S | j dkr| || j | S | j dkr/| |d| j  || j  S td| j  d)Nr   r   r   r   r   r   )r   r<   r   r   r   )rD   r!   Zcross_modal_hidden_statesrI   r*   r*   r+   rT   R  s   


zBridgeTowerLinkTower.forwardr#   r$   r%   r9   rT   rV   r*   r*   rF   r+   r   D  s    r   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 )BridgeTowerSelfOutputc                    sB   t    t|j|j| _tj|j|jd| _t|j	| _
d S Nr4   )r8   r9   r   r?   r:   denser<   r=   Dropouthidden_dropout_probdropoutrC   rF   r*   r+   r9   _     
zBridgeTowerSelfOutput.__init__r!   input_tensorr   c                 C   &   |  |}| |}| || }|S rP   r   r   r<   rD   r!   r   r*   r*   r+   rT   e     

zBridgeTowerSelfOutput.forwardr#   r$   r%   r9   r'   rU   rT   rV   r*   r*   rF   r+   r   ^      $r   c                       2   e Zd Z fddZdejdejfddZ  ZS )BridgeTowerIntermediatec                    sD   t    t|j|j| _t|jt	rt
|j | _d S |j| _d S rP   )r8   r9   r   r?   r:   intermediate_sizer   
isinstance
hidden_actstrr   intermediate_act_fnrC   rF   r*   r+   r9   n  s
   
z BridgeTowerIntermediate.__init__r!   r   c                 C   s   |  |}| |}|S rP   )r   r   rD   r!   r*   r*   r+   rT   v  s   

zBridgeTowerIntermediate.forwardr   r*   r*   rF   r+   r   m  s    r   c                       r   )BridgeTowerOutputc                    sB   t    t|j|j| _tj|j|jd| _t	|j
| _d S r   )r8   r9   r   r?   r   r:   r   r<   r=   r   r   r   rC   rF   r*   r+   r9   ~  r   zBridgeTowerOutput.__init__r!   r   r   c                 C   r   rP   r   r   r*   r*   r+   rT     r   zBridgeTowerOutput.forwardr   r*   r*   rF   r+   r   }  r   r   c                       r   )BridgeTowerPoolerc                    s*   t    t|j|j| _t | _d S rP   )r8   r9   r   r?   r:   r   ZTanh
activationrC   rF   r*   r+   r9     s   
zBridgeTowerPooler.__init__r!   r   c                 C   s(   |d d df }|  |}| |}|S )Nr   )r   r   )rD   r!   Zfirst_token_tensorpooled_outputr*   r*   r+   rT     s   

zBridgeTowerPooler.forwardr   r*   r*   rF   r+   r     s    r   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 )BridgeTowerSelfAttentionNc                    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 ()position_embedding_typeabsoluterelative_keyrelative_key_queryri   r   )r8   r9   r:   num_attention_headshasattrr   r   attention_head_sizeall_head_sizer   r?   querykeyvaluer   Zattention_probs_dropout_probr   getattrr   max_position_embeddingsrw   distance_embedding
is_decoderrD   rE   r   rF   r*   r+   r9     s*   

z!BridgeTowerSelfAttention.__init__xr   c                 C   s6   |  d d | j| jf }||}|ddddS )Nrl   r   ri   r   r
   )r   r   r   r   r   )rD   r   Znew_x_shaper*   r*   r+   transpose_for_scores  s   
z-BridgeTowerSelfAttention.transpose_for_scoresFr!   rI   	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   ri   r   rl   r   r   rJ   r   zbhld,lrd->bhlrzbhrd,lrd->bhlrr
   ) r   r   r   r   r'   r   r   matmulr   r   r   r   longrL   r   rz   r   r   rM   rK   Zeinsummathsqrtr   r   r   Zsoftmaxr   r   
contiguousr   r   )rD   r!   rI   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+   rT     sn   









z BridgeTowerSelfAttention.forwardrP   NNNNNF)r#   r$   r%   r9   r'   rU   r   r   r(   r   rN   rT   rV   r*   r*   rF   r+   r     s4    	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 )BridgeTowerAttentionNc                    s4   t    t|j ||d| _t|| _t | _d S )Nr   )	r8   r9   #BRIDGE_TOWER_SELF_ATTENTION_CLASSESZ_attn_implementationrD   r   outputsetpruned_headsr   rF   r*   r+   r9   )  s   

zBridgeTowerAttention.__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   )lenr   rD   r   r   r   r   r   r   r   r   r   r   union)rD   headsindexr*   r*   r+   prune_heads1  s   z BridgeTowerAttention.prune_headsFr!   rI   r   r   r   r   r   r   c              	   C   s<   |  |||||||}| |d |}	|	f|dd   }
|
S )Nr   r   )rD   r   )rD   r!   rI   r   r   r   r   r   Zself_outputsattention_outputr   r*   r*   r+   rT   C  s   
	zBridgeTowerAttention.forwardrP   r   )r#   r$   r%   r9   r   r'   rU   r   r(   r   rN   rT   rV   r*   r*   rF   r+   r   (  s4    	r   c                       s8   e Zd Z fddZ					d	ddZdd Z  ZS )
BridgeTowerBertCrossLayerc                    sT   t    |j| _d| _t|| _|j| _|j| _t|| _t	|| _
t|| _d S )Nr   )r8   r9   chunk_size_feed_forwardseq_len_dimr   rO   r   add_cross_attentioncrossattentionr   intermediater   r   rC   rF   r*   r+   r9   \  s   



z"BridgeTowerBertCrossLayer.__init__NFc              	   C   sz   | j ||d |d d}|d }	|dd  }
| j|	||||||d}|d }	|
|dd  }
t| j| j| j|	}|f|
 }
|
S )N)rI   r   r   r   r   r   )rI   r   r   r   r   r   rl   )rO   r   r   feed_forward_chunkr   r   )rD   r!   r   rI   r   r   r   r   self_attention_outputsr   r   cross_attention_outputslayer_outputr*   r*   r+   rT   g  s2   	
z!BridgeTowerBertCrossLayer.forwardc                 C      |  |}| ||}|S rP   r   r   rD   r   Zintermediate_outputr  r*   r*   r+   r       
z,BridgeTowerBertCrossLayer.feed_forward_chunk)NNNNF)r#   r$   r%   r9   rT   r  rV   r*   r*   rF   r+   r   [  s    
,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 )BridgeTowerTextLayerc                    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 addedr   r   )r8   r9   r   r   r   rO   r   r   r   r   r   r   r   r   rC   rF   r*   r+   r9     s   


zBridgeTowerTextLayer.__init__NFr!   rI   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 )
Nri   )r   r   r   r   rl   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   )	rO   r   r   r   r   r   r  r   r   )rD   r!   rI   r   r   r   r   r   Zself_attn_past_key_valuer  r   r   Zpresent_key_valueZcross_attn_present_key_valueZcross_attn_past_key_valuer  r  r*   r*   r+   rT     sP   


	

zBridgeTowerTextLayer.forwardc                 C   r  rP   r  r  r*   r*   r+   r    r  z'BridgeTowerTextLayer.feed_forward_chunkr   )r#   r$   r%   r9   r'   rU   r   r(   r   rN   rT   r  rV   r*   r*   rF   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 )BridgeTowerTextEncoderc                    s:   t     | _t fddt jD | _d| _d S )Nc                    rX   r*   )r	  rZ   r\   r*   r+   r]     r^   z3BridgeTowerTextEncoder.__init__.<locals>.<listcomp>F)	r8   r9   rE   r   r`   ra   r_   rS   gradient_checkpointingrC   rF   r\   r+   r9     s   
 
zBridgeTowerTextEncoder.__init__NFTr!   rI   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   rl   r   ri   c                 s       | ]	}|d ur|V  qd S rP   r*   r[   vr*   r*   r+   	<genexpr>9  s    z1BridgeTowerTextEncoder.forward.<locals>.<genexpr>)last_hidden_stater  r!   r"   cross_attentions)rE   r   r  ZtrainingloggerZwarning_once	enumeraterS   Z_gradient_checkpointing_func__call__tupler   )rD   r!   rI   r   r   r   r  r   r   r  r  all_hidden_statesall_self_attentionsZall_cross_attentionsZnext_decoder_cacheiZlayer_moduleZlayer_head_maskr   Zlayer_outputsr*   r*   r+   rT     sz   


zBridgeTowerTextEncoder.forward)	NNNNNNFFT)r#   r$   r%   r9   r'   rU   r   r(   r   rN   r   r   rT   rV   r*   r*   rF   r+   r
    sD    		
r
  c                       s4   e Zd ZdZ fddZ	d
ddZdd	 Z  ZS )BridgeTowerTextEmbeddingszV
    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_idxr4   r   r   rj   rk   Frm   token_type_idsr   )r8   r9   r   rw   
vocab_sizer:   Zpad_token_idword_embeddingsr   position_embeddingsZtype_vocab_sizetoken_type_embeddingsr<   r=   r   r   r   r   r   ry   r'   rz   r{   zerosrj   r   r   r  rC   rF   r*   r+   r9   T  s"   
z"BridgeTowerTextEmbeddings.__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 )Nrl   r   r  r   rJ   r   )"create_position_ids_from_input_idsr  &create_position_ids_from_inputs_embedsr   r   r  r{   r'   r#  r   rj   rL   r   r"  r   r!  r<   r   )rD   	input_idsr  rj   inputs_embedspast_key_values_lengthinput_shape
seq_lengthbuffered_token_type_ids buffered_token_type_ids_expandedr"  r|   r!  r*   r*   r+   rT   m  s0   








z!BridgeTowerTextEmbeddings.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
        Nrl   r   rJ   r   )r   r'   rz   r  r   rL   r   r{   )rD   r'  r)  Zsequence_lengthrj   r*   r*   r+   r%    s   	z@BridgeTowerTextEmbeddings.create_position_ids_from_inputs_embeds)NNNNr   )r#   r$   r%   r&   r9   rT   r%  rV   r*   r*   rF   r+   r  N  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_asr   )r&  r  r(  maskZincremental_indicesr*   r*   r+   r$    s   r$  c                   @   s,   e Zd ZeZdZdZddgZdZdd Z	dS )	BridgeTowerPreTrainedModelbridgetowerFr   r2   r  c                 C   s  t |tr|jjjd d|jjj d  }|jjjd }d|jjj d }|jjjD ]=}tjj	|j
j|| jj d tjj	|j
jj|| jj d tjj	|jjj|| jj d tjj	|jjj|| jj d q*tjj	|jjj|| jj d tjj	|jjjj|| jj d n,t |tjtjtjfr|jjj	dd| jj d nt |tjr|jj  |jjd t |tjr|jd ur|jj  d S d S d S )Ng      ri   )stdg        g?)meanr1  r   )r   BridgeTowerVisionModelvisualr   r:   r_   rb   r   initZnormal_r;   Zin_proj_weightrE   Zinitializer_factorZout_projr   r@   r5   r7   r|   rr   rx   r?   rs   rw   datar<   rh   Zzero_Zfill_)rD   moduleZproj_stdZattn_stdZfc_stdrf   r*   r*   r+   _init_weights  s.   
 z(BridgeTowerPreTrainedModel._init_weightsN)
r#   r$   r%   r   config_classZbase_model_prefixZsupports_gradient_checkpointingZ_no_split_modulesZ_skip_keys_device_placementr8  r*   r*   r*   r+   r/    s    r/  c                       s6   e Zd ZeZ fddZedd Zd	ddZ  Z	S )
r3  c                    s   t  | t|| _d S rP   )r8   r9   r   r4  rC   rF   r*   r+   r9     s   zBridgeTowerVisionModel.__init__c                 C   s   | j jjjjS rP   )r4  r|   rt   r   rK   rD   r*   r*   r+   rK     s   zBridgeTowerVisionModel.dtypeNFc                 C   s   |  || j||S rP   )r4  typerK   )rD   imageZ
image_maskr   r*   r*   r+   rT     s   zBridgeTowerVisionModel.forward)NF)
r#   r$   r%   r   r9  r9   propertyrK   rT   rV   r*   r*   rF   r+   r3    s    
r3  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 )BridgeTowerTextModelTc                    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)
r8   r9   rE   r  r|   r
  encoderr   pooler	post_init)rD   rE   Zadd_pooling_layerrF   r*   r+   r9     s   

zBridgeTowerTextModel.__init__c                 C      | j jS rP   r|   r   r:  r*   r*   r+   get_input_embeddings     z)BridgeTowerTextModel.get_input_embeddingsc                 C      || j _d S rP   rC  rD   r   r*   r*   r+   set_input_embeddings     z)BridgeTowerTextModel.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)rQ   r?  rS   rO   r   )rD   Zheads_to_prunerS   r   r*   r*   r+   _prune_heads  s   z!BridgeTowerTextModel._prune_headsNr&  rI   r  rj   r   r'  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 timerl   z5You have to specify either input_ids or inputs_embedsr   ri   rL   r  rJ   )r&  rj   r  r'  r(  )	rI   r   r   r   r  r   r   r  r  r   )r  r    r  r!   r"   r  )rE   r   r  use_return_dictr   r   r   Z%warn_if_padding_and_no_attention_maskr   rL   r   r'   onesr   r|   r  r{   r#  r   get_extended_attention_maskZinvert_attention_maskZget_head_maskr_   r?  r@  r   r  r!   r"   r  )rD   r&  rI   r  rj   r   r'  r   r   r  r   r   r  r  r)  r   r*  rL   r(  r+  r,  Zextended_attention_maskZencoder_batch_sizeZencoder_sequence_lengthrR   Zencoder_hidden_shapeZencoder_extended_attention_maskZembedding_outputZencoder_outputsZsequence_outputr   r*   r*   r+   rT     s   
zBridgeTowerTextModel.forward)T)NNNNNNNNNNNNN)r#   r$   r%   r   r9  r9   rD  rH  rJ  r   r   r'   rU   r   r(   rN   r   r   r   rT   rV   r*   r*   rF   r+   r>    sb    	
r>  zv
    The bare BridgeTower Model transformer outputting BridgeTowerModelOutput object without any specific head on
    c                "       s   e Zd Z f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 dee dee dee deej	 dedeeej ef fddZdd Z  ZS )BridgeTowerModelc                    s  t     | _ j j jr%tj j| _	tj j| _
n"t fddt jD | _	t fddt jD | _
td j| _t| _t| _jsy jry| jjjD ]}| jjjjj|j_| jjjjj|j_qdtfddt jD | _tfddt jD | _t | _t | _ tj! j j"d| _#tj! j j"d| _$ j%rt& | _'t& | _(n$t fddt jd	 D | _'t fd
dt jd	 D | _(| )  d S )Nc                       g | ]
}t j jqS r*   r   r?   r:   rZ   )rE   text_configr*   r+   r]         z-BridgeTowerModel.__init__.<locals>.<listcomp>c                    rP  r*   rQ  rZ   )rE   vision_configr*   r+   r]     rS  ri   c                    rX   r*   r   rZ   rR  r*   r+   r]     r^   c                    rX   r*   rU  rZ   rV  r*   r+   r]     r^   r4   c                    rX   r*   r   rZ   r\   r*   r+   r]     r^   r   c                    rX   r*   rW  rZ   r\   r*   r+   r]     r^   )*r8   r9   rE   rT  rR  Z$share_cross_modal_transformer_layersr   r?   r:   cross_modal_text_transformcross_modal_image_transformr`   ra   r_   rw   r"  r3  vision_modelr>  
text_modelr   Z"init_layernorm_from_vision_encoderr4  Zcross_modal_ln_separater   r   r6  rh   cross_modal_image_layerscross_modal_text_layersr   cross_modal_image_poolercross_modal_text_poolerr<   r=   cross_modal_text_layernormcross_modal_image_layernormZshare_link_tower_layersr   cross_modal_text_link_towercross_modal_image_link_towerrA  )rD   rE   r   rF   )rE   rR  rT  r+   r9     sP   




zBridgeTowerModel.__init__c                 C   s
   | j  S rP   )r[  rD  r:  r*   r*   r+   rD    s   
z%BridgeTowerModel.get_input_embeddingsc                 C   s   | j | d S rP   )r[  rH  rG  r*   r*   r+   rH    s   z%BridgeTowerModel.set_input_embeddingsNFr&  rI   r  r   
pixel_maskr   r'  r0   image_token_type_idxr   r  r  labelsr   r   c           -      C   s  |
dur|
n| j j}
|dur|n| j j}|rdnd}|rdnd}|r$dnd}|r*dnd}|
r0dnd}|dur>|du r>td|durD|n| j j}|	rL|	nd}	| }| jj|d}|r`||f7 }|du rntj	|tj
|jd}| j|||j}t| jjj| j j d }| jjjd| D ]}|||d }|r||f7 }q|du r| jjj|| jj|d}n|ddd	}|r||f7 }| jjjjd| D ]}||}|r||f7 }q| jj|| jj}| |}| tjdtj
|jd|}| || }|  |}| tj!d
|	tj
|jd|}|| }| "|}tj	|d|dftj
|jd}| j|| |j}| j#d |||||
d} | d }!| j$d |||||
d}"|"d }#|ri||!|#ff7 }|
rw|| d |"d ff7 }d}$t%|t| jjjD ]}%| jjj|% ||d }| jjjj|% || jj}|  | jj|| }| j&|$ }&| j'|$ }'|&| || |!|}(|'||#|})| j#|$d  |(|)|||
d} | d }!| j$|$d  |)|(|||
d}"|"d }#|$d7 }$|r||f7 }||f7 }||!|#ff7 }|
r|| d |"d ff7 }q|!|#}*}+| (|*|+},|r&|||f}|s7t)dd |*|+|,||fD S t*|*|+|,||dS )a  
        image_embeds (`torch.FloatTensor` of shape `(batch_size, num_patches, hidden_size)`, *optional*):
            Optionally, instead of passing `pixel_values`, you can choose to directly pass an embedded representation.
            This is useful if you want more control over how to convert `pixel_values` into patch embeddings.
        image_token_type_idx (`int`, *optional*):
            - The token type ids for images.
        output_hidden_states (`bool`, *optional*):
            If set to `True`, hidden states are returned as a list containing the hidden states of text, image, and
            cross-modal components respectively. i.e. `(hidden_states_text, hidden_states_image,
            hidden_states_cross_modal)` where each element is a list of the hidden states of the corresponding
            modality. `hidden_states_txt/img` are a list of tensors corresponding to unimodal hidden states and
            `hidden_states_cross_modal` is a list of tuples containing `cross_modal_text_hidden_states` and
            `cross_modal_image_hidden_states` of each brdige layer.
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels are currently not supported.

        Examples:

        ```python
        >>> from transformers import BridgeTowerProcessor, BridgeTowerModel
        >>> from PIL import Image
        >>> import requests

        >>> # prepare image and text
        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> image = Image.open(requests.get(url, stream=True).raw)
        >>> text = "hello world"
        >>> processor = BridgeTowerProcessor.from_pretrained("BridgeTower/bridgetower-base")
        >>> model = BridgeTowerModel.from_pretrained("BridgeTower/bridgetower-base")

        >>> inputs = processor(image, text, return_tensors="pt")
        >>> outputs = model(**inputs)
        >>> outputs.keys()
        odict_keys(['text_features', 'image_features', 'pooler_output'])
        ```Nr*   zYBridgeTowerModel does not use `inputs_embeds`.  Make sure to pass in `input_ids` instead.r   )r&  rJ   r   r   ri   r   )rI   r   r   c                 s   r  rP   r*   r  r*   r*   r+   r    s    z+BridgeTowerModel.forward.<locals>.<genexpr>)r   r   r    r!   r"   )+rE   r   r  r   rL  r   r[  r|   r'   rM  r   rL   rN  rM   r   r?  rS   r_   rZ  r4  r   r;  rK   r   r   rb   r   rX  r"  r#  	expand_asr`  rY  fullra  r]  r\  ra   rb  rc  get_cls_featuresr  r   )-rD   r&  rI   r  r   rd  r   r'  r0   re  r   r  r  rf  r   Zall_hidden_states_textZall_hidden_states_imageZall_hidden_states_crossr  r  r)  r/   Zextend_text_masksZsplit_indexrS   rf   image_embeds_with_lnZcross_modal_textZtext_token_type_embeddingsimage_token_type_embeddingsZcross_modal_imageZextend_image_masksZlayer_outputs_textZcross_text_featuresZlayer_outputs_imageZcross_image_featuresZlink_layer_indexr  Ztext_link_towerZimage_link_towerZcross_text_features_Zcross_image_features_r   r   Zcls_featuresr*   r*   r+   rT     s  5












zBridgeTowerModel.forwardc                 C   s&   |  |}| |}tj||gddS )Nrl   r   )r_  r^  r'   r   )rD   r   r   Zcls_features_textZcls_features_imager*   r*   r+   rj    s   

z!BridgeTowerModel.get_cls_features)NNNNNNNNNNNNNF)r#   r$   r%   r9   rD  rH  r   r   r'   
LongTensorr(   r   rN   r   r   rU   r   rT   rj  rV   r*   r*   rF   r+   rO    sh    8	
 mrO  c                       r   )"BridgeTowerPredictionHeadTransformc                    sV   t    t|j|j| _t|jtrt	|j | _
n|j| _
tj|j|jd| _d S r   )r8   r9   r   r?   r:   r   r   r   r   r   transform_act_fnr<   r=   rC   rF   r*   r+   r9     s   
z+BridgeTowerPredictionHeadTransform.__init__c                 C   s"   |  |}| |}| |}|S rP   )r   ro  r<   r   r*   r*   r+   rT     s   


z*BridgeTowerPredictionHeadTransform.forwardr   r*   r*   rF   r+   rn    s    	rn  c                       s&   e Zd Zd fdd	Zdd Z  ZS )BridgeTowerMLMHeadNc                    s`   t    || _t|| _tj|j|jj	dd| _
tt|jj	| _|d ur.|| j
_d S d S )NF)rh   )r8   r9   rE   rn  	transformr   r?   r:   rR  r  decoderrq   r'   r#  rh   r   )rD   rE   r   rF   r*   r+   r9     s   

zBridgeTowerMLMHead.__init__c                 C   s   |  |}| || j }|S rP   )rq  rr  rh   )rD   r   	mlm_scorer*   r*   r+   rT     s   
zBridgeTowerMLMHead.forwardrP   r   r*   r*   rF   r+   rp    s    	rp  c                       r   )BridgeTowerITMHeadc                    s   t    t|d| _d S Nri   r8   r9   r   r?   fc)rD   r:   rF   r*   r+   r9        
zBridgeTowerITMHead.__init__c                 C   s   |  |}|S rP   rw  )rD   r   	itm_scorer*   r*   r+   rT        
zBridgeTowerITMHead.forwardr   r*   r*   rF   r+   rt        rt  z\
    BridgeTower Model with a language modeling head on top as done during pretraining.
    c                       s   e Zd ZdgZ f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 dee dee dee	j
 deeee	j f fddZ  ZS )BridgeTowerForMaskedLMzmlm_score.decoder.weightc                    s,   t  | t|| _t|| _|   d S rP   )r8   r9   rO  r0  rp  rs  rA  rC   rF   r*   r+   r9     s   

zBridgeTowerForMaskedLM.__init__c                 C   rB  rP   rs  rr  r:  r*   r*   r+   get_output_embeddings  rE  z,BridgeTowerForMaskedLM.get_output_embeddingsc                 C   rF  rP   r~  )rD   Znew_embeddingsr*   r*   r+   set_output_embeddings  rI  z,BridgeTowerForMaskedLM.set_output_embeddingsNr&  rI   r  r   rd  r   r'  r0   r   r  r  rf  r   c                 C   s   |dur|n| j j}| j|||||||||	|
|d}| |r!|jn|d }d}|durDt }||j}||d| j j	j
|d}|sUt|}|durS|f| S |S t|||j|jdS )a  
        image_embeds (`torch.FloatTensor` of shape `(batch_size, num_patches, hidden_size)`, *optional*):
            Optionally, instead of passing `pixel_values`, you can choose to directly pass an embedded representation.
            This is useful if you want more control over how to convert `pixel_values` into patch embeddings.
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
            config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
            loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`

        Examples:

        ```python
        >>> from transformers import BridgeTowerProcessor, BridgeTowerForMaskedLM
        >>> from PIL import Image
        >>> import requests

        >>> url = "http://images.cocodataset.org/val2017/000000360943.jpg"
        >>> image = Image.open(requests.get(url, stream=True).raw).convert("RGB")
        >>> text = "a <mask> looking out of the window"

        >>> processor = BridgeTowerProcessor.from_pretrained("BridgeTower/bridgetower-base-itm-mlm")
        >>> model = BridgeTowerForMaskedLM.from_pretrained("BridgeTower/bridgetower-base-itm-mlm")

        >>> # prepare inputs
        >>> encoding = processor(image, text, return_tensors="pt")

        >>> # forward pass
        >>> outputs = model(**encoding)

        >>> results = processor.decode(outputs.logits.argmax(dim=-1).squeeze(0).tolist())

        >>> print(results)
        .a cat looking out of the window.
        ```N
rI   r  r   rd  r   r'  r0   r   r  r  r   rl   r-   r.   r!   r"   )rE   rL  r0  rs  r   r	   rM   rL   r   rR  r  r  r   r!   r"   )rD   r&  rI   r  r   rd  r   r'  r0   r   r  r  rf  r   Z
mlm_logitsZmasked_lm_lossloss_fctr   r*   r*   r+   rT     s:   2zBridgeTowerForMaskedLM.forwardNNNNNNNNNNNN)r#   r$   r%   Z_tied_weights_keysr9   r  r  r   r   r'   rm  r(   rN   r   r   r   rT   rV   r*   r*   rF   r+   r}    sZ    		
r}  z
    BridgeTower Model transformer with a classifier head on top (a linear layer on top of the final hidden state of the
    [CLS] token) for image-to-text matching.
    c                       s   e Zd Z 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j de
eeej f fddZ  ZS )#BridgeTowerForImageAndTextRetrievalc                    s2   t  | t|| _t|jd | _|   d S ru  )r8   r9   rO  r0  rt  r:   rz  rA  rC   rF   r*   r+   r9   `  s   
z,BridgeTowerForImageAndTextRetrieval.__init__Nr&  rI   r  r   rd  r   r'  r0   r   r  r  rf  r   c                 C   s   |dur|n| j j}| j|||||||||	|
|d}|r|jn|d }| |}d}|dur<t }||j}|||}|sMt|}|durK|f| S |S t	|||j
|jdS )a  
        image_embeds (`torch.FloatTensor` of shape `(batch_size, num_patches, hidden_size)`, *optional*):
            Optionally, instead of passing `pixel_values`, you can choose to directly pass an embedded representation.
            This is useful if you want more control over how to convert `pixel_values` into patch embeddings.
        labels (`torch.LongTensor` of shape `(batch_size, 1)`, *optional*):
            Labels for computing the image-text matching loss. 0 means the pairs don't match and 1 means they match.
            The pairs with 0 will be skipped for calculation.

        Examples:

        ```python
        >>> from transformers import BridgeTowerProcessor, BridgeTowerForImageAndTextRetrieval
        >>> import requests
        >>> from PIL import Image

        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> image = Image.open(requests.get(url, stream=True).raw)
        >>> texts = ["An image of two cats chilling on a couch", "A football player scoring a goal"]

        >>> processor = BridgeTowerProcessor.from_pretrained("BridgeTower/bridgetower-base-itm-mlm")
        >>> model = BridgeTowerForImageAndTextRetrieval.from_pretrained("BridgeTower/bridgetower-base-itm-mlm")

        >>> # forward pass
        >>> scores = dict()
        >>> for text in texts:
        ...     # prepare inputs
        ...     encoding = processor(image, text, return_tensors="pt")
        ...     outputs = model(**encoding)
        ...     scores[text] = outputs.logits[0, 1].item()
        ```Nr  ri   r  )rE   rL  r0  r    rz  r	   rM   rL   r  r   r!   r"   )rD   r&  rI   r  r   rd  r   r'  r0   r   r  r  rf  r   r    r.   Zitm_lossr  r   r*   r*   r+   rT   j  s<   .

z+BridgeTowerForImageAndTextRetrieval.forwardr  )r#   r$   r%   r9   r   r   r'   rm  r(   rN   r   r   r   rT   rV   r*   r*   rF   r+   r  Y  sT    
	
r  c                       r   )BridgeTowerContrastiveHeadc                    s   t    t||| _d S rP   rv  )rD   r:   Z
embed_sizerF   r*   r+   r9     rx  z#BridgeTowerContrastiveHead.__init__c                 C   s   |  |}|S rP   ry  )rD   r   r*   r*   r+   rT     r{  z"BridgeTowerContrastiveHead.forwardr   r*   r*   rF   r+   r    r|  r  zl
    BridgeTower Model with a image-text contrastive head on top computing image-text contrastive loss.
    c                       s   e Zd Z 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	 de
eeej f fddZ  ZS )!BridgeTowerForContrastiveLearningc                    sl   t  | t|| _t|j|j| _t|j|j| _t|jd |j| _	t
t| jj| _|   d S ru  )r8   r9   rO  r0  r  r:   Zcontrastive_hidden_sizeitc_text_headitc_image_headitc_cross_modal_headr   rq   r'   r   rE   Zlogit_scale_init_valuelogit_scalerA  rC   rF   r*   r+   r9     s   
z*BridgeTowerForContrastiveLearning.__init__NTr&  rI   r  r   rd  r   r'  r0   r   r  r  return_lossr   c           !      C   sB  |dur|n| j j}| j|||||||||	d|d}|r|jn|d }|r(|jn|d \}}}|d }|d }| jjj|}| jt	j
ddt	j| jjjjd	|}| j|| }tjj| |ddd
ddf ddd}tjj| |ddd
ddf dddj|jd}tjj| |dddj|jd}t	j|||gdd}| j j|jd}t	|| | }t	|| | }t	|| | }d}|rt	jt||jd}tj||}tj||}tj||}|| | d }|s||||f|dd  } |dur|f|  S | S t||||||j|j dS )a  
        image_embeds (`torch.FloatTensor` of shape `(batch_size, num_patches, hidden_size)`, *optional*):
            Optionally, instead of passing `pixel_values`, you can choose to directly pass an embedded representation.
            This is useful if you want more control over how to convert `pixel_values` into patch embeddings.
        return_loss (`bool`, *optional*):
            Whether or not to return the contrastive loss.

        Examples:

        ```python
        >>> from transformers import BridgeTowerProcessor, BridgeTowerForContrastiveLearning
        >>> import requests
        >>> from PIL import Image
        >>> import torch

        >>> image_urls = [
        ...     "https://farm4.staticflickr.com/3395/3428278415_81c3e27f15_z.jpg",
        ...     "http://images.cocodataset.org/val2017/000000039769.jpg",
        ... ]
        >>> texts = ["two dogs in a car", "two cats sleeping on a couch"]
        >>> images = [Image.open(requests.get(url, stream=True).raw) for url in image_urls]

        >>> processor = BridgeTowerProcessor.from_pretrained("BridgeTower/bridgetower-large-itm-mlm-itc")
        >>> model = BridgeTowerForContrastiveLearning.from_pretrained("BridgeTower/bridgetower-large-itm-mlm-itc")

        >>> inputs = processor(images, texts, padding=True, return_tensors="pt")
        >>> loss = model(**inputs, return_loss=True).loss

        >>> inputs = processor(images, texts[::-1], padding=True, return_tensors="pt")
        >>> loss_swapped = model(**inputs, return_loss=True).loss

        >>> print("Loss", round(loss.item(), 4))
        Loss 0.0019

        >>> print("Loss with swapped images", round(loss_swapped.item(), 4))
        Loss with swapped images 2.126
        ```NTr  ri   r
   rl   rg  r   rJ   r   )r   prK  r   r   g      @)r-   r.   r/   r0   r1   r!   r"   )!rE   rL  r0  r    r!   rZ  r4  r   r"  r'   ri  r   r   rL   rh  rY  r   r   	normalizer  r  rM   r  r   r  expr   trz   r   Zcross_entropyr,   r"   )!rD   r&  rI   r  r   rd  r   r'  r0   r   r  r  r  r   r    Zhidden_states_txtZhidden_states_imgZhidden_states_cross_modalr/   rk  rl  r1   r.   r  Zlogits_text_to_imageZlogits_text_to_crossZlogits_image_to_crossZitc_lossrf  Ztext_to_image_lossZtext_to_cross_lossZimage_to_cross_lossr   r*   r*   r+   rT     sr   5**z)BridgeTowerForContrastiveLearning.forward)NNNNNNNNNTNN)r#   r$   r%   r9   r   r   r'   rm  r(   rN   r   r,   r   rT   rV   r*   r*   rF   r+   r    sT    	
r  )r  r  r}  rO  r/  )r   )Kr&   r   collectionsr   dataclassesr   typingr   r   r   r   r'   Ztorch.utils.checkpointr   Ztorch.nnr	   Zactivationsr   r   Zmodeling_outputsr   r   r   r   r   Zmodeling_utilsr   r   Zpytorch_utilsr   r   utilsr   r   r   Zconfiguration_bridgetowerr   r   r   Z
get_loggerr#   r  Z_TOKENIZER_FOR_DOCr   r,   Moduler2   rW   rg   r   r   r   r   r   r   r   r   r   r   r	  r
  r  r$  r/  r3  r>  rO  rn  rp  rt  r}  r  r  r  __all__r*   r*   r*   r+   <module>   s   
!,S: 3>W^
Z"   5
g`
 