o
    *j                    @   sD  d Z ddlZddlZddlmZ ddlZddlm  mZ	 ddl
ZddlZddlmZmZmZ ddlmZ ddlmZmZ ddlmZ ddlmZmZmZmZ dd	lmZmZmZ dd
lmZ ddlm Z  ddl!m"Z"m#Z# ddl$m%Z%m&Z& ddl'm(Z( ddl)m*Z* ddl+m,Z,m-Z-m.Z. ej /  e 0 Z1dZ2dZ3dZ4dd Z5dd Z6G dd dej7Z8G dd dej7Z9G dd dej7Z:G dd dej7Z;G d d! d!ej7Z<G d"d# d#ej7Z=G d$d% d%ej7Z>G d&d' d'ej7Z?G d(d) d)ej7Z@G d*d+ d+ej7ZAG d,d- d-ej7ZBG d.d/ d/ej7ZCG d0d1 d1ej7ZDG d2d3 d3ej7ZEG d4d5 d5ej7ZFG d6d7 d7ej7ZGG d8d9 d9eZHd:ZId;ZJed<eIG d=d> d>eHZKG d?d@ d@eHZLedAeIG dBdC dCeHZMG dDdE dEeHZNG dFdG dGeZOG dHdI dIeOZPG dJdK dKeOZQG dLdM dMeOZRG dNdO dOeZSG dPdQ dQeSZTG dRdS dSeSZUdS )TzPyTorch MPLUG model.     N)Tuple)Tensordevicenn)CrossEntropyLoss)
BertConfigBertTokenizer)ACT2FN)add_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardreplace_return_docstrings))BaseModelOutputWithPastAndCrossAttentions,BaseModelOutputWithPoolingAndCrossAttentions!CausalLMOutputWithCrossAttentions)PreTrainedModel)logging)HiTeAConfigMPlugConfig)MViTv2MViTv2_Base_config)TextGenerator)	ModelFile)apply_chunking_to_forward find_pruneable_heads_and_indicesprune_linear_layerzconfig.yamlr   r   c                 C   s  zddl }ddl}ddl}W n ty   td  w tj|}t	d
| |j|}g }g }	|D ]\}
}t	d
|
| |j||
}||
 |	| q6t||	D ]\}
}|
d}
tdd |
D rxt	d	
d|
 qZ| }|
D ]|}|d
|r|d|}n|g}|d dks|d dkrt|d}nH|d dks|d dkrt|d}n6|d dkrt|d}n*|d dkrt|d}nz	t||d }W n ty   t	d	
d|
 Y q|w t|dkrt|d }|| }q||dd dkrt|d}n
|dkr||}z|j|jks'J d|j d|j dW n tyA } z| j|j|jf7  _ d}~ww t	d
|
 t||_qZ| S )z'Load tf checkpoints in a pytorch model.r   NzLoading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.z(Converting TensorFlow checkpoint from {}z"Loading TF weight {} with shape {}/c                 s   s    | ]}|d v V  qdS ))Zadam_vZadam_mZAdamWeightDecayOptimizerZAdamWeightDecayOptimizer_1Zglobal_stepN ).0nr   r   s/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/modelscope/models/multi_modal/mplug/modeling_mplug.py	<genexpr>X   s    z*load_tf_weights_in_bert.<locals>.<genexpr>zSkipping {}z[A-Za-z]+_\d+z_(\d+)ZkernelgammaweightZoutput_biasbetabiasZoutput_weightsZsquadZ
classifier      iZ_embeddingszPointer shape z and array shape z mismatchedzInitialize PyTorch weight {})renumpyZ
tensorflowImportErrorloggererrorospathabspathinfoformattrainZlist_variablesZload_variableappendzipsplitanyjoin	fullmatchgetattrAttributeErrorlenint	transposeshapeAssertionErrorargstorchZ
from_numpydata)modelconfigZtf_checkpoint_pathr(   nptfZtf_pathZ	init_varsnamesZarraysnamer>   arraypointerZm_nameZscope_namesnumer   r   r    load_tf_weights_in_bert;   s   



rM   c                 C   sB   | j tjkrt|  rt| j jd }tj| | |d} | S )Ni  )minmax)dtyperA   Zfloat16isinfr6   ZfinforO   clamp)tensorZclamp_valuer   r   r    	clamp_inf   s   rT   c                       s4   e Zd ZdZ fddZ					dddZ  ZS )	BertEmbeddingszGConstruct the embeddings from word, position and token_type embeddings.c                    s   t    tj|j|j|jd| _t|j|j| _	t|j
|j| _tj|j|jd| _t|j| _| dt|jd t|dd| _|| _d S )N)Zpadding_idxepsposition_ids)r'   position_embedding_typeabsolute)super__init__r   	Embedding
vocab_sizehidden_sizepad_token_idword_embeddingsmax_position_embeddingsposition_embeddingsZtype_vocab_sizetoken_type_embeddings	LayerNormlayer_norm_epsDropouthidden_dropout_probdropoutregister_bufferrA   arangeexpandr9   rZ   rD   selfrD   	__class__r   r    r]      s2   

zBertEmbeddings.__init__Nr   c                 C   s   |d ur	|  }n|  d d }|d }|d u r&| jd d ||| f }|d u r5tj|tj| jjd}|d u r>| |}| |}|| }	| jdkrU| 	|}
|	|
7 }	| 
|	}	| |	}	|	S )NrY   r'   rP   r   r[   )sizerX   rA   zeroslongr   rb   re   rZ   rd   rf   rj   )ro   	input_idstoken_type_idsrX   inputs_embedspast_key_values_lengthinput_shape
seq_lengthre   
embeddingsrd   r   r   r    forward   s0   







zBertEmbeddings.forward)NNNNr   )__name__
__module____qualname____doc__r]   r}   __classcell__r   r   rp   r    rU      s    rU   c                       sZ   e Zd Z fddZdd Zdd Zdd Zd	d
 Zdd Z						dddZ	  Z
S )BertSelfAttentionc                    s"  t    || _|j|j dkrt|dstd|j|jf |j| _t|j|j | _| j| j | _	t
|j| j	| _|rQt
|j| j	| _t
|j| j	| _nt
|j| j	| _t
|j| j	| _t
|j| _t|dd| _| jdks{| jdkr|j| _t
d|j d	 | j| _d
| _d S )Nr   Zembedding_sizezLThe hidden size (%d) is not a multiple of the number of attention heads (%d)rZ   r[   relative_keyrelative_key_queryr&   r'   F)r\   r]   rD   r`   num_attention_headshasattr
ValueErrorr<   attention_head_sizeall_head_sizer   LinearqueryZencoder_widthkeyvaluerh   Zattention_probs_dropout_probrj   r9   rZ   rc   r^   distance_embeddingsave_attentionro   rD   is_cross_attentionrp   r   r    r]      sB   


zBertSelfAttention.__init__c                 C   
   || _ d S Nattn_gradients)ro   r   r   r   r    save_attn_gradients      
z%BertSelfAttention.save_attn_gradientsc                 C      | j S r   r   ro   r   r   r    get_attn_gradients      z$BertSelfAttention.get_attn_gradientsc                 C   r   r   attention_map)ro   r   r   r   r    save_attention_map   r   z$BertSelfAttention.save_attention_mapc                 C   r   r   r   r   r   r   r    get_attention_map   r   z#BertSelfAttention.get_attention_mapc                 C   s6   |  d d | j| jf }|j| }|ddddS )NrY   r   r&   r'      )rs   r   r   viewpermute)ro   xZnew_x_shaper   r   r    transpose_for_scores   s
   
z&BertSelfAttention.transpose_for_scoresNFc                 C   s  |  |}|d u}	|	r| | |}
| | |}|}n;|d urI| | |}
| | |}tj|d |
gdd}
tj|d |gdd}n| | |}
| | |}| |}|
|f}t||
dd}t|}| j	dksz| j	dkr|
 d }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rtd||}td|
|}|| | }|t| j }|d ur|| }tjdd|}|	r| jr| | || j | |}|d ur|| }t||}|dddd }|
 d d | j f }|j| }|r;||fn|f}||f }|S )Nr   r&   dimr'   rY   r   r   rr   rP   zbhld,lrd->bhlrzbhrd,lrd->bhlrr   )!r   r   r   r   rA   catmatmulr=   rT   rZ   rs   rl   ru   r   r   r   rc   torP   Zeinsummathsqrtr   r   ZSoftmaxr   r   register_hookr   rj   r   
contiguousr   )ro   hidden_statesattention_mask	head_maskencoder_hidden_statesencoder_attention_maskpast_key_valueoutput_attentionsZmixed_query_layerr   Z	key_layerZvalue_layerZquery_layerZattention_scoresr{   Zposition_ids_lZposition_ids_rZdistancepositional_embeddingZrelative_position_scoresZrelative_position_scores_queryZrelative_position_scores_keyZattention_probsZattention_probs_droppedZcontext_layerZnew_context_layer_shapeoutputsr   r   r    r}     s   











zBertSelfAttention.forwardNNNNNF)r~   r   r   r]   r   r   r   r   r   r}   r   r   r   rp   r    r      s    "	r   c                       $   e Zd Z fddZdd Z  ZS )BertSelfOutputc                    sB   t    t|j|j| _tj|j|jd| _t|j	| _
d S NrV   )r\   r]   r   r   r`   denserf   rg   rh   ri   rj   rn   rp   r   r    r]   j     
zBertSelfOutput.__init__c                 C   s&   |  |}| |}| || }|S r   )r   rj   rf   ro   r   Zinput_tensorr   r   r    r}   q  s   

zBertSelfOutput.forwardr~   r   r   r]   r}   r   r   r   rp   r    r   h      r   c                       s<   e Zd Zd	 fdd	Zdd Z						d
ddZ  ZS )BertAttentionFc                    s,   t    t||| _t|| _t | _d S r   )r\   r]   r   ro   r   outputsetpruned_headsr   rp   r   r    r]   z  s   

zBertAttention.__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   ro   r   r   r   r   r   r   r   r   r   r   union)ro   headsindexr   r   r    prune_heads  s   

zBertAttention.prune_headsNc              	   C   s<   |  |||||||}| |d |}	|	f|dd   }
|
S )Nr   r'   )ro   r   )ro   r   r   r   r   r   r   r   Zself_outputsattention_outputr   r   r   r    r}     s   
	
zBertAttention.forward)Fr   )r~   r   r   r]   r   r}   r   r   r   rp   r    r   x  s    r   c                       r   )BertIntermediatec                    sD   t    t|j|j| _t|jt	rt
|j | _d S |j| _d S r   )r\   r]   r   r   r`   intermediate_sizer   
isinstance
hidden_actstrr	   intermediate_act_fnrn   rp   r   r    r]     s
   
zBertIntermediate.__init__c                 C      |  |}| |}|S r   )r   r   ro   r   r   r   r    r}        

zBertIntermediate.forwardr   r   r   rp   r    r     s    r   c                       r   )
BertOutputc                    sB   t    t|j|j| _tj|j|jd| _t	|j
| _d S r   )r\   r]   r   r   r   r`   r   rf   rg   rh   ri   rj   rn   rp   r   r    r]     r   zBertOutput.__init__c                 C   s6   |  |}t|}| |}t|}| || }|S r   )r   rT   rj   rf   r   r   r   r    r}     s   

zBertOutput.forwardr   r   r   rp   r    r     r   r   c                       s<   e Zd Z fddZ							d	ddZdd Z  ZS )
FusionLayerc                    s^   t    || _t| jdd| _|j| _d| _t|| _t|dd| _	t
|| _t|| _d S )Nstride_layerd   r'   Tr   )r\   r]   rD   r9   r   chunk_size_feed_forwardseq_len_dimr   	attentioncrossattentionr   intermediater   r   ro   rD   	layer_numrp   r   r    r]     s   


zFusionLayer.__init__NFc	                 C   s2  |d ur
|d d nd }	|dks|| j  dkrO| j|||||	d}
|
d }|
dd }|
d }|d us7J d| j||||||d}|d }||dd  }n/|dkr~|| j  dkr~| jt||gdt||gd|||	d}
|
d }|
dd }|
d }t| j| j| j|}|f| }||d |d f }|S )	Nr&   r   r   r   r'   rY   >encoder_hidden_states must be given for cross-attention layersr   r   )	r   r   r   rA   r   r   feed_forward_chunkr   r   )ro   r   r   r   r   r   Z
layer_numsr   r   self_attn_past_key_valueself_attention_outputsr   r   present_key_valuecross_attention_outputslayer_outputr   r   r    r}     sb   
zFusionLayer.forwardc                 C      |  |}| ||}|S r   r   r   ro   r   Zintermediate_outputr   r   r   r    r        
zFusionLayer.feed_forward_chunk)NNNNNNFr~   r   r   r]   r}   r   r   r   r   rp   r    r     s    
=r   c                       s:   e Zd Z fddZ						d	ddZdd Z  ZS )
	BertLayerc                    sd   t    || _|j| _d| _t|| _t| jdd| _| jr&t|dd| _	t
|| _t|| _d S )Nr'   add_cross_attentionFTr   )r\   r]   rD   r   r   r   r   r9   has_cross_attentionr   r   r   r   r   r   rp   r   r    r]   !  s   


zBertLayer.__init__NFc              	   C   s*  |d ur
|d d nd }| j |||||d}	|	d }
|	dd }|	d }| jrz|d us/J dt|tkrc| j|
|||| j| jj t|  || j| jj t|  |d}|d }
||dd  }n| j|
|||||d}|d }
||dd  }t	| j
| j| j|
}|f| }||d |d f }|S )Nr&   r   r   r'   rY   r   r   )r   r   typelistr   r   rD   Zfusion_layerr;   r   r   r   r   )ro   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r}   0  sv   
zBertLayer.forwardc                 C   r   r   r   r   r   r   r    r   s  r   zBertLayer.feed_forward_chunkr   r   r   r   rp   r    r     s    
Cr   c                       8   e Zd Z fddZ									dddZ  ZS )	FusionEncoderc                    sH   t     | _t fddt jD | _td j j	 | _
d S )Nc                       g | ]}t  |qS r   )r   r   irD   r   r    
<listcomp>      z*FusionEncoder.__init__.<locals>.<listcomp>r   )r\   r]   rD   r   
ModuleListrangenum_hidden_layerslayerrO   Zfusion_layersstart_layerrn   rp   r   r    r]   {  s   


zFusionEncoder.__init__NFTc                    s  |	rdnd } r
dnd }|rdnd }t | jdd| _|jd }|jd }t| jt| jD ]}| j| }|	r;||f }|d urC|| nd }|d urM|| nd t | jddr|| jr||rbt	
d d} fdd	}tjj||||||||| j }n|||||||| j  }|d
 }|r||d f7 } r||d f }|jd || krt|||fd\}}||7 }q-|	r||f }||gS )Nr   r   r   r'   gradient_checkpointingFh`use_cache=True` is incompatible with `config.gradient_checkpointing=True`. Setting `use_cache=False`...c                        fdd}|S )Nc                        t  g | R  S r   tupleZinputsmoduler   r   r   r    custom_forward     zLFusionEncoder.forward.<locals>.create_custom_forward.<locals>.custom_forwardr   r	  r
  r   r	  r    create_custom_forward     z4FusionEncoder.forward.<locals>.create_custom_forwardr   rY   )r9   rD   r   r>   r   r   r;   r   trainingr+   warningrA   utils
checkpointr5   )ro   r   r   r   r   r   past_key_values	use_cacher   output_hidden_statesreturn_dictall_hidden_statesall_self_attentionsnext_decoder_cacheZimage_lengthtext_lengthr   layer_modulelayer_head_maskr  layer_outputsZencoder_hidden_states_newr   r   r    r}     s~   






zFusionEncoder.forward	NNNNNNFFTr   r   r   rp   r    r   y  s    
r   c                       r   )	BertEncoderc                    s4   t     | _t fddt jD | _d S )Nc                    r   r   )r   r   r   r   r    r     r   z(BertEncoder.__init__.<locals>.<listcomp>)r\   r]   rD   r   r   r   r   r   rn   rp   r   r    r]     s
   

zBertEncoder.__init__NFTc              	      s^  |	rdnd } r
dnd } r| j jrdnd }|rdnd }tt| jD ]k}| j| }|	r1||f }|d ur9|| nd }|d urC|| nd t| j ddrn| jrn|rXtd d} fdd}t	j
j|||||||}n
|||||| }|d }|r||d f7 } r||d	 f }q#|	r||f }|
std
d |||||fD S t|||||dS )Nr   r  Fr  c                    r  )Nc                     r  r   r  r  r  r   r    r
    r  zJBertEncoder.forward.<locals>.create_custom_forward.<locals>.custom_forwardr   r  r   r  r    r     r  z2BertEncoder.forward.<locals>.create_custom_forwardr   rY   r'   c                 s   s    | ]	}|d ur|V  qd S r   r   )r   vr   r   r    r!   !  s    z&BertEncoder.forward.<locals>.<genexpr>)last_hidden_stater  r   
attentionscross_attentions)rD   r   r   r;   r   r9   r  r+   r  rA   r  r  r  r   )ro   r   r   r   r   r   r  r  r   r  r  r  r  Zall_cross_attentionsr  r   r  r  r  r  r   r   r    r}     s   




zBertEncoder.forwardr  r   r   r   rp   r    r     s    r   c                       r   )
BertPoolerc                    s*   t    t|j|j| _t | _d S r   )r\   r]   r   r   r`   r   ZTanh
activationrn   rp   r   r    r]   3  s   
zBertPooler.__init__c                 C   s(   |d d df }|  |}| |}|S )Nr   )r   r&  )ro   r   Zfirst_token_tensorpooled_outputr   r   r    r}   8  s   

zBertPooler.forwardr   r   r   rp   r    r%  1      r%  c                       r   )BertPredictionHeadTransformc                    sV   t    t|j|j| _t|jtrt	|j | _
n|j| _
tj|j|jd| _d S r   )r\   r]   r   r   r`   r   r   r   r   r	   transform_act_fnrf   rg   rn   rp   r   r    r]   C  s   
z$BertPredictionHeadTransform.__init__c                 C   s"   |  |}| |}| |}|S r   )r   r*  rf   r   r   r   r    r}   M  s   


z#BertPredictionHeadTransform.forwardr   r   r   rp   r    r)  A  s    
r)  c                       r   )BertLMPredictionHeadc                    sL   t    t|| _tj|j|jdd| _t	t
|j| _| j| j_d S )NF)r%   )r\   r]   r)  	transformr   r   r`   r_   decoder	ParameterrA   rt   r%   rn   rp   r   r    r]   V  s   


zBertLMPredictionHead.__init__c                 C   r   r   )r,  r-  r   r   r   r    r}   d  r   zBertLMPredictionHead.forwardr   r   r   rp   r    r+  T  s    r+  c                       r   )BertOnlyMLMHeadc                    s   t    t|| _d S r   )r\   r]   r+  predictionsrn   rp   r   r    r]   l  s   
zBertOnlyMLMHead.__init__c                 C      |  |}|S r   )r0  )ro   sequence_outputprediction_scoresr   r   r    r}   p     
zBertOnlyMLMHead.forwardr   r   r   rp   r    r/  j      r/  c                       r   )BertOnlyNSPHeadc                    s   t    t|jd| _d S Nr&   )r\   r]   r   r   r`   seq_relationshiprn   rp   r   r    r]   w  s   
zBertOnlyNSPHead.__init__c                 C   r1  r   )r8  )ro   r'  seq_relationship_scorer   r   r    r}   {  r4  zBertOnlyNSPHead.forwardr   r   r   rp   r    r6  u  r5  r6  c                       r   )BertPreTrainingHeadsc                    s(   t    t|| _t|jd| _d S r7  )r\   r]   r+  r0  r   r   r`   r8  rn   rp   r   r    r]     s   

zBertPreTrainingHeads.__init__c                 C   s   |  |}| |}||fS r   )r0  r8  )ro   r2  r'  r3  r9  r   r   r    r}     s   

zBertPreTrainingHeads.forwardr   r   r   rp   r    r:    r(  r:  c                   @   s*   e Zd ZdZeZeZdZdgZ	dd Z
dS )BertPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    bertrX   c                 C   s~   t |tjtjfr|jjj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 )z Initialize the weights g        )meanZstd      ?N)r   r   r   r^   r#   rB   Znormal_rD   Zinitializer_rangerf   r%   Zzero_Zfill_)ro   r	  r   r   r    _init_weights  s   z!BertPreTrainedModel._init_weightsN)r~   r   r   r   r   config_classrM   Zload_tf_weightsZbase_model_prefix_keys_to_ignore_on_load_missingr?  r   r   r   r    r;    s    r;  a  
    This model inherits from :class:`~transformers.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 (:class:`~transformers.BertConfig`): 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 :meth:`~transformers.PreTrainedModel.from_pretrained` method to load the model
            weights.
a  
    Args:
        input_ids (:obj:`torch.LongTensor` of shape :obj:`({0})`):
            Indices of input sequence tokens in the vocabulary.
            Indices can be obtained using :class:`~transformers.BertTokenizer`. See
            :meth:`transformers.PreTrainedTokenizer.encode` and :meth:`transformers.PreTrainedTokenizer.__call__` for
            details.
            `What are input IDs? <../glossary.html#input-ids>`__
        attention_mask (:obj:`torch.FloatTensor` of shape :obj:`({0})`, `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.html#attention-mask>`__
        token_type_ids (:obj:`torch.LongTensor` of shape :obj:`({0})`, `optional`):
            Segment token indices to indicate first and second portions of the inputs. Indices are selected in ``[0,
            1]``:
            - 0 corresponds to a `sentence A` token,
            - 1 corresponds to a `sentence B` token.
            `What are token type IDs? <../glossary.html#token-type-ids>`_
        position_ids (:obj:`torch.LongTensor` of shape :obj:`({0})`, `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.html#position-ids>`_
        head_mask (:obj:`torch.FloatTensor` of shape :obj:`(num_heads,)` or :obj:`(num_layers, num_heads)`, `optional`):
            Mask to nullify selected heads of the self-attention modules. Mask values selected in ``[0, 1]``:
            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.
        inputs_embeds (:obj:`torch.FloatTensor` of shape :obj:`({0}, hidden_size)`, `optional`):
            Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded representation.
            This is useful if you want more control over how to convert :obj:`input_ids` indices into associated
            vectors than the model's internal embedding lookup matrix.
        output_attentions (:obj:`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 (:obj:`bool`, `optional`):
            Whether or not to return the hidden states of all layers. See ``hidden_states`` under returned tensors for
            more detail.
        return_dict (:obj:`bool`, `optional`):
            Whether or not to return a :class:`~transformers.file_utils.ModelOutput` instead of a plain tuple.
z^The bare Bert Model transformer outputting raw hidden-states without any specific head on top.c                          e Zd ZdZd fdd	Zdd Zdd Zd	d
 Zee	
deedeeddedee dededef
ddZ															dddZ  ZS )	BertModel=  
    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 <https://arxiv.org/abs/1706.03762>`__ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
    Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
    argument and :obj:`add_cross_attention` set to :obj:`True`; an :obj:`encoder_hidden_states` is then expected as an
    input to the forward pass.
    Tc                    sD   t  | || _t|| _t|| _|rt|nd | _| 	  d S r   )
r\   r]   rD   rU   r|   r   encoderr%  poolerinit_weightsro   rD   add_pooling_layerrp   r   r    r]     s   

zBertModel.__init__c                 C      | j jS r   r|   rb   r   r   r   r    get_input_embeddings     zBertModel.get_input_embeddingsc                 C      || j _d S r   rK  ro   r   r   r   r    set_input_embeddings     zBertModel.set_input_embeddingsc                 C   *   |  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itemsrE  r   r   r   ro   Zheads_to_pruner   r   r   r   r    _prune_heads     zBertModel._prune_headsbatch_size, sequence_lengthbert-base-uncasedZprocessor_classr  output_typer@  r   rz   r   
is_decoderreturnc                 C   X  |  dkr|dddddddf }n|  dkr|r|\}}tj||d}|ddddf ||d|ddddf k}	|	|j}	|	jd |jd k rl|jd |	jd  }
tjtj|||
f||	jd|	gdd}	|	dddddddf |ddddddf  }n|ddddddf }n	t	d	
||j|j| jd
}d| d }|S aW  
        Makes broadcastable attention and causal masks so that future and masked tokens are ignored.

        Arguments:
            attention_mask (:obj:`torch.Tensor`):
                Mask with ones indicating tokens to attend to, zeros for tokens to ignore.
            input_shape (:obj:`Tuple[int]`):
                The shape of the input to the model.
            device: (:obj:`torch.device`):
                The device of the input to the model.

        Returns:
            :obj:`torch.Tensor` The extended attention mask, with a the same dtype as :obj:`attention_mask.dtype`.
        r   Nr&   r   r'   )r   rP   rY   )ZaxiszAWrong shape for input_ids (shape {}) or attention_mask (shape {})r   r>  g     r   rA   rl   repeatr   rP   r>   r   onesr   r1   ro   r   rz   r   r]  extended_attention_mask
batch_sizer{   Zseq_idsZcausal_maskZprefix_seq_lenr   r   r    get_extended_attention_mask  s\   
	z%BertModel.get_extended_attention_maskNFc                    s  |dur|n j j}|dur|n j j}|dur|n j j}|r+|dur&|n j j}nd}|dur9|dur9td|durI| }|\}}|j}n,|dur]| dd }|\}}|j}n|durq| dd }|\}}|j}ntd|
dur|
d d jd nd}|du rt	j
||| f|d}|du rt	j|t	j|d	} ||||}|durt|tkr|d  \}}}n| \}}}||f}t|	tkrׇ fd
d|	D }n|	du rt	j
||d}	 |	}n |	}nd} | j j}|du r j|||||d}n|} j||||||
||||d
}|d } jdur( |nd}|s7||f|dd  S t|||j|j|j|jdS )~  
        encoder_hidden_states
        (:obj:`torch.FloatTensor` of shape :obj:`(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 (:obj:`torch.FloatTensor` of shape :obj:`(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
        (:obj:`tuple(tuple(torch.FloatTensor))` of length
         :obj:`config.n_layers` with each tuple having 4 tensors of shape
         :obj:`(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 :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids`
            (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)`
            instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.
        use_cache (:obj:`bool`, `optional`):
            If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
            decoding (see :obj:`past_key_values`).
        NFDYou cannot specify both input_ids and inputs_embeds at the same timerY   GYou have to specify either input_ids or inputs_embeds or encoder_embedsr   r&   ra  rr   c                       g | ]}  |qS r   invert_attention_maskr   maskr   r   r    r         z%BertModel.forward.<locals>.<listcomp>rv   rX   rw   rx   ry   	r   r   r   r   r  r  r   r  r  r'   r"  Zpooler_outputr  r   r#  r$  rD   r   r  use_return_dictr  r   rs   r   r>   rA   rd  rt   ru   rh  r   r   rn  Zget_head_maskr   r|   rE  rF  r   r  r   r#  r$  ro   rv   r   rw   rX   r   rx   encoder_embedsr   r   r  r  r   r  r  r]  rz   rg  r{   r   ry   rf  Zencoder_batch_sizeZencoder_sequence_length_Zencoder_hidden_shapeZencoder_extended_attention_maskZembedding_outputZencoder_outputsr2  r'  r   r   r    r}   T  s   (



zBertModel.forwardTNNNNNNNNNNNNNNFr~   r   r   r   r]   rL  rP  rW  r   BERT_INPUTS_DOCSTRINGr1   r
   _TOKENIZER_FOR_DOCr   _CONFIG_FOR_DOCr   r   r<   r   boolrh  r}   r   r   r   rp   r    rC    sP    	HrC  c                       rB  )FusionModelrD  Tc                    s:   t  | || _t|| _|rt|nd | _|   d S r   )r\   r]   rD   r   rE  r%  rF  rG  rH  rp   r   r    r]     s
   
zFusionModel.__init__c                 C   rJ  r   rK  r   r   r   r    rL  
  rM  z FusionModel.get_input_embeddingsc                 C   rN  r   rK  rO  r   r   r    rP    rQ  z FusionModel.set_input_embeddingsc                 C   rR  rS  rT  rV  r   r   r    rW    rX  zFusionModel._prune_headsrY  rZ  r[  r   rz   r   r]  r^  c                 C   r_  r`  rb  re  r   r   r    rh    s\   
	z'FusionModel.get_extended_attention_maskNFc                    s~  |dur|n j j}|dur|n j j}|dur|n j j}|r+|dur&|n j j}nd}|dur9|dur9td|durI| }|\}}|j}n,|dur]| dd }|\}}|j}n|durq| dd }|\}}|j}ntd|
dur|
d d jd nd}|du rt	j
||| f|d}|du rt	j|t	j|d	} ||||}|durt|tkr|d  \}}}n| \}}}||f}t|	tkrׇ fd
d|	D }n|	du rt	j
||d}	 |	}n |	}nd} | j j}|du r j|||||d}n|} j||||||
||||d
}|\}} jdur( |nd}|s1||gS t|||j|j|j|jdS )ri  NFrj  rY   rk  r   r&   ra  rr   c                    rl  r   rm  ro  r   r   r    r     rq  z'FusionModel.forward.<locals>.<listcomp>rr  rs  rt  ru  rw  r   r   r    r}   g  s   &



zFusionModel.forwardrz  r{  r|  r   r   rp   r    r    sP    	Gr  zGBert Model with a `language modeling` head on top for CLM fine-tuning. c                       s   e Zd ZdgZddgZ fddZdd Zdd	 Zee	
d
eeed																			dddZ		dddZdd Z  ZS )BertLMHeadModelrF  rX   predictions.decoder.biasc                    0   t  | t|dd| _t|| _|   d S NFrI  r\   r]   rC  r<  r/  clsrG  rn   rp   r   r    r]        
zBertLMHeadModel.__init__c                 C   
   | j jjS r   r  r0  r-  r   r   r   r    get_output_embeddings  r   z%BertLMHeadModel.get_output_embeddingsc                 C      || j j_d S r   r  ro   Znew_embeddingsr   r   r    set_output_embeddings     z%BertLMHeadModel.set_output_embeddingsrY  )r\  r@  NTr=  r   Fc                 C   s  |dur|n| j j}|	durd}| j|||||||||
|||||d}|d }| |}|r=|ddddddf  S d}|	dur}|ddddddf  }|	ddddf  }	t|d}||d| j j|	d}||dd	d}|durt
j	tj|dd| dd }||	d	k 	d}d| | ||  }|s|f|d
d  }|dur|f| S |S t|||j|j|j|jdS )av
  
        encoder_hidden_states
        (:obj:`torch.FloatTensor` of shape :obj:`(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 (:obj:`torch.FloatTensor` of shape :obj:`(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**.
        labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
            Labels for computing the left-to-right language modeling loss (next word prediction). 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 n ``[0, ..., config.vocab_size]``
        past_key_values
        (:obj:`tuple(tuple(torch.FloatTensor))` of length
         :obj:`config.n_layers` with each tuple having 4 tensors of shape
         :obj:`(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 :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids`
            (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)`
            instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.
        use_cache (:obj:`bool`, `optional`):
            If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
            decoding (see :obj:`past_key_values`).
        Returns:

        Example:
            >>> from transformers import BertTokenizer, BertLMHeadModel, BertConfig
            >>> import torch
            >>> tokenizer = BertTokenizer.from_pretrained('bert-base-cased')
            >>> config = BertConfig.from_pretrained("bert-base-cased")
            >>> model = BertLMHeadModel.from_pretrained('bert-base-cased', config=config)
            >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
            >>> outputs = model(**inputs)
            >>> prediction_logits = outputs.logits
        NFr   rw   rX   r   rx   r   r   r  r  r   r  r  r]  r   rY   r'   )	reductionr   r&   lossZlogitsr  r   r#  r$  )rD   rv  r<  r  r   r   r   r_   rs   sumrA   Flog_softmaxr   r  r   r#  r$  ro   rv   r   rw   rX   r   rx   r   r   labelsr  r  r   r  r  r]  r  soft_labelsalphareturn_logitsr   r2  r3  Zlm_lossZshifted_prediction_scoresZloss_fctZloss_distillr   r   r   r    r}   "  sr   @


zBertLMHeadModel.forwardc                 K   sV   |j }|d u r||}|d ur|d d dd f }||||dd |dd ddS )NrY   r   r   T)rv   r   r  r   r   r]  )r>   Znew_onesget)ro   rv   pastr   Zmodel_kwargsrz   r   r   r    prepare_inputs_for_generation  s   


z-BertLMHeadModel.prepare_inputs_for_generationc                    s.   d}|D ]}|t  fdd|D f7 }q|S )Nr   c                 3   s    | ]	}| d  V  qdS )r   N)index_select)r   Z
past_statebeam_idxr   r    r!     s
    

z1BertLMHeadModel._reorder_cache.<locals>.<genexpr>r  )ro   r  r  Zreordered_pastZ
layer_pastr   r  r    _reorder_cache  s   zBertLMHeadModel._reorder_cacheNNNNNNNNNNNNNNTr=  Nr   F)NN)r~   r   r   "_keys_to_ignore_on_load_unexpectedrA  r]   r  r  r   r}  r1   r   r   r  r}   r  r  r   r   r   rp   r    r  
  sL    x
r  c                       s   e Zd ZdgZddgZ fddZdd Zdd	 Zee	
d
eedeed																			dddZ  ZS )BertPrefixModelrF  rX   r  c                    r  r  r  rn   rp   r   r    r]     r  zBertPrefixModel.__init__c                 C   r  r   r  r   r   r   r    r    r   z%BertPrefixModel.get_output_embeddingsc                 C   r  r   r  r  r   r   r    r    r  z%BertPrefixModel.set_output_embeddingsrY  rZ  r[  NTr=  r   Fc                 C   sp  |d ur|n| j j}|	d urd}| j|||||||||
|||||d}|d }| |}|r=|d d d dd d f  S d }|	d uro|d d d dd d f  }|	d d dd f  }	t }||d| j j|	d}|d urtj	t
j|dd| dd }||	dk  }d| | ||  }|s|f|dd   }|d ur|f| S |S t|||j|j|j|jd	S )
NFr  r   rY   r'   r   r  r&   r  )rD   rv  r<  r  r   r   r   r_   rA   r  r  r  r=  r   r  r   r#  r$  r  r   r   r    r}     sp   

zBertPrefixModel.forwardr  )r~   r   r   r  rA  r]   r  r  r   r}  r1   r
   r~  r   r  r}   r   r   r   rp   r    r    sH    r  c                       s   e Zd ZeZ fddZedddZeddd	Z	d
d Z
dd Zdd Ze dd Ze dd ZdddZedd Z  ZS )MPlugc                    sf   t  | || _ttj|jt	j
| _| | | || _t| jdd| _t| jdd| _d S r  )r\   r]   rD   r   from_pretrainedr-   r.   r7   	model_dirr   
VOCAB_FILE	tokenizermodule_setting_initialize_clipvisual_encoderrC  config_encodertext_encoderr  config_fusionfusion_encoderrn   rp   r   r    r]   3  s   
zMPlug.__init__NTc                 C   s   ddl m} |jt|jt|jti}| j	t
j|t}||_|d u r&|j}|| |}|rgt
j|tj}tj|dd}	d|	v rE|	d }	d|	v rM|	d }	dd |	 D }	|j|	d	d
}
td|  t|
 |S )Nr   TaskscpuZmap_locationrC   r	  c                 S      i | ]\}}| d d|qS zmodel. replacer   kr!  r   r   r    
<dictcomp>V      z)MPlug.from_pretrained.<locals>.<dictcomp>Fstrictzload checkpoint from %s)modelscope.utils.constantr  Zvisual_question_answeringMPlugForVisualQuestionAnsweringZimage_captioningMPlugForImageCaptionZimage_text_retrievalMPlugForImageTextRetrievalr@  from_yaml_filer-   r.   r7   CONFIG_NAMEr  taskr   TORCH_MODEL_BIN_FILErA   loadrU  load_state_dictprint)r  r  r  load_checkpointr  task_mappingrD   rC   checkpoint_pathr  msgr   r   r    r  ?  s8   zMPlug.from_pretrained   c                 C   s   dd }ddl m } || }d| jv r,t| j| j d }tt|d d	 }nt| j| j d }tt|d d		 }||j
jd
|d
|_||j
_|S )Nc                 S   s   |j d }| d d d df | ddd f }}|d8 }ttt|}tt|}|d||ddddd}|j}tj	|
 ||fdd}||}|ddddd|| d}tj||gdd} | S )	Nr'   r   rY   r   r&   Zbilinear)rs   moder   )r>   r<   r   r   r;   Zreshaper   rP   r  Zinterpolatefloatr   rA   r   )ZposembZ
posemb_newZntok_newZ
posemb_tokZposemb_gridZgs_oldZgs_neworigr   r   r    resize_pos_embedc  s(   
&


z0MPlug._initialize_clip.<locals>.resize_pos_embedr'   )clipzViT-B-16   i      i   r   )r  Zload_from_configZ	clip_namer<   	image_resr   r.  rA   rt   r  visualr   Z	unsqueezer#   )rD   Znum_patchesr  r  Z
clip_modelZ	pos_embedr   r   r    r  `  s    

zMPlug._initialize_clipc                 C   s   |j | _ | j rq| || _t| jdd| _t| jdd| _t	| j
| _| j| jg| j| jg| j| jgg| _| jj|jkrht|j| jj| _tj| jjdd| _t| jj| _| j| j| jg| j| jgg |   d| _d S d S NFr  -q=rV   ףp=
?)distillr  visual_encoder_mrC  r  text_encoder_mr  r  fusion_encoder_mr  config_decodertext_decoder_mr  r  text_decodermodel_pairsr`   vision_widthr   r   	visn_fc_mrf   visn_layer_norm_mrh   ri   	dropout_mextendvisn_fcvisn_layer_normcopy_paramsmomentumrn   r   r   r    init_distill  s@   





zMPlug.init_distillc                 O      t r   NotImplementedErrorro   r@   kwargsr   r   r    r}        zMPlug.forwardc                 C   s   t j|j|j}t|| _| jj| j_	t|| _
t|| _d| j_| jj| j_	d| _| jj|jkrVt|j| jj| _tj| jjdd| _t| jj| _d| _d S d S )NTFr  rV   )r-   r.   r7   r  bert_configr   from_json_filer  text_encoder_layersr   r  r  r   text_decode_layerslarger`   r  r   r   r  rf   r  rh   ri   rj   ro   rD   Zbert_config_pathr   r   r    r    s$   
zMPlug.module_settingc                 C   H   | j D ]}t|d  |d  D ]\}}|j|j d|_qqd S Nr   r'   Fr  r4   
parametersrB   Zcopy_Zrequires_gradro   Z
model_pairparamZparam_mr   r   r    r       

zMPlug.copy_paramsc                 C   R   | j D ]#}t|d  |d  D ]\}}|j| j |jd| j   |_qqd S Nr   r'   r>  r  r4   r   rB   r  r  r   r   r    _momentum_update     


zMPlug._momentum_updater'   c                 C   $   ||g}| j j||d\}}||fS Nout_sizebeam_generatorZtranslate_batchro   question_statesquestion_attsr  Zencoder_inputstopk_idsZtopk_scoresr   r   r    
generation  
   
zMPlug.generationc                    n   dd l | | dg|   }||< | j| } t fddt D }t| ||	| j
S )Nr   r'   c                       g | ]}   | qS r   rl   r   Zinit_dimn_tilerE   r   r    r         zMPlug._tile.<locals>.<listcomp>r)   rs   r   rc  rA   Z
LongTensorZconcatenater   r  r   r   r   r   r  Z
repeat_idxZorder_indexr   r  r    _tile     

zMPlug._tileNT)r  r'   )r~   r   r   r   r@  r]   classmethodr  staticmethodr  r  r}   r  rA   no_gradr  r  r  r  r   r   r   rp   r    r  0  s"     '


r  c                       0   e Zd Z fddZ					dddZ  ZS )	r  c                    4   t  | t| j| _t|| j| _| | d S r   r\   r]   r  r  r  r   r  r  rn   rp   r   r    r]        z(MPlugForVisualQuestionAnswering.__init__Nr   Tc           !      C   s.  |j t|  jd}| jj|dd}| jr!| | | 	|}t
j| d d t
jd |j}	|r^	 |j|j| jjkd}
| j|j|jdd}|j}| j||j||	dd}|\}}t
||gd	}t
|	|jgd	}|d u r|d	g|jd
  }g }g }t|D ]\}}||| g| 7 }||| g| 7 }qt
|d
}t
|d
}| jr9t
 l |   | jj|dd}| jr| |  | !|}| j"|j|jdd}|j}| j#||j||	dd}|\}}t
||gd	}g }t|D ]\}}||| g| 7 }qt
|d
}| j$|j|j||dd}W d    n	1 sw   Y  | j%|j|j|||
dt&j'|dddd}n| j%|j|j|||
ddd}|d u rNd	}||j( }|) |d
 }|S | j|j|jdd}|j}| j||j||	dd}|\}}t
||gd	}t
|	|jgd	}| *||\}} || fS )Nr   TZskip_last_layerrY   r  r   r  Frx  r   r   r   r  r'   r   r   r   r   r  r   noner   r   r   r  r  r  r  r   r   r   r  r  r  )+r   nextr   rP   r  r  r  rj   r  r  rA   rd  rs   ru   r   rv   masked_fillr  ra   r  r   r"  r  r   r>   	enumeratestackr  r#  r  r  r  r  r  r  r  r  r  r  softmaxr  r  r  )!ro   imagequestionanswerr  r  weightsr2   image_embeds
image_attsanswer_targetstext_outputtext_embedsfusion_outputimage_outputquestion_outputmerge_text_attentionr  r  br   image_embeds_mtext_output_mtext_embeds_mfusion_output_mimage_output_mquestion_output_mquestion_states_mlogits_manswer_outputr  r  
topk_probsr   r   r    r}     s  

%
	

z'MPlugForVisualQuestionAnswering.forwardNr   NNTr   r   r   rp   r    r        	r  c                       >   e Zd Z fddZ			dddZ				dd	d
Z  ZS )r  c                    *   t  | t| j| _t|| j| _d S r   r\   r]   r  r  r  r   r  rn   rp   r   r    r]   m     zMPlugForImageCaption.__init__NT   c                 C   s   | j j|dd}| jr| | | |}tj| d d tj	d
|j}| j|j|jdd}|j}	| j|	|j||dd}
|
\}}t||gd}t||jgd}| j|||d	\}}||fS )
NTr(  rY   r   r)  Fr*  r'   r  )r  r  r  rj   r  r  rA   rd  rs   ru   r   r   r  rv   r   r"  r  r   r  )ro   r4  r5  r6  r2   r  r8  r9  r;  r<  r=  r>  r?  r@  r  rK  r   r   r    beam_searchr  s@   
z MPlugForImageCaption.beam_searchFc              	   C   s   |r| j |||d|dS |jt|  jd}| jj|dd}| jr-| | 	| 
|}tj| d d tjd|j}|r`|j|j| jjkd}	| j|j|j|||	ddd}
|
j}|S | ||\}}||fS )	NTr2   r  r   r(  rY   r  r,  r.  )rS  r   r/  r   rP   r  r  r  rj   r  r  rA   rd  rs   ru   r   rv   r0  r  ra   r  r   r  r  )ro   r4  r5  r6  r2   r  scstr8  r9  r:  rJ  r  r  rK  r   r   r    r}     s@   
zMPlugForImageCaption.forwardNTrR  NTrR  Fr~   r   r   r]   rS  r}   r   r   r   rp   r    r  k  s    
"r  c                       s>   e Zd Z fddZdd Ze dd Zdd	d
Z  Z	S )r  c                    s&  t  | |j| _ttg |j | _|j| _|j	| _	|j
| _
|j| _| jj| _|j| _t| j| j| _t| j| j| _t| jd| _| dt| j| j | dt| j| j | dtd| jfd | dtjdtjd tj| jd	d
| _tj| jd	d
| _| | d S )Nr&   image_queue
text_queue	idx_queuer'   r  	queue_ptrr   r   r   )r\   r]   	embed_dimr   r.  rA   rd  temp
queue_sizer  r  r  r`   
text_widthr   vision_proj	text_projitm_headrk   Zrandnfullrt   ru   r  	normalizerY  rZ  r  rn   rp   r   r    r]     s2   
z#MPlugForImageTextRetrieval.__init__c                 C   s  |j | _ | j r| || _t| jdd| _t| jdd| _t	
| j| j| _t	
| j| j| _| j| jg| j| jg| j| jg| j| jgg| _| jj|jkryt	
|j| jj| _t	j| jjdd| _t	| jj| _| j| j| jg| j| jgg |   d| _ d S d S r  )!r  r  r  rC  r  r  r  r  r  r   r   r`  r]  vision_proj_mtext_proj_mr  r  rb  ra  r  r`   r  r  rf   r  rh   ri   r  r  r  r  r  r  rn   r   r   r    r    sD   






z'MPlugForImageTextRetrieval.init_distillc           
      C   s   dd }||}||}||}|j d }t| j}	|j| jd d |	|	| f< |j| jd d |	|	| f< |j| jd d |	|	| f< |	| | j }	|	| jd< d S )Nc                    sN   t j s S  fddtt j D }t jj| dd t j|dd}|S )z
            Performs all_gather operation on the provided tensors.
            *** Warning ***: torch.distributed.all_gather has no gradient.
            c                    s   g | ]}t  qS r   )rA   Z	ones_like)r   ry  rS   r   r    r     rq  z^MPlugForImageTextRetrieval._dequeue_and_enqueue.<locals>.concat_all_gather.<locals>.<listcomp>F)Zasync_opr   r   )rA   distributedZis_initializedr   Zget_world_sizeZ
all_gatherr   )rS   Ztensors_gatherr   r   rh  r    concat_all_gather  s   

zJMPlugForImageTextRetrieval._dequeue_and_enqueue.<locals>.concat_all_gatherr   )r>   r<   r\  TrY  rZ  r[  r_  )
ro   
image_feat	text_featidxrj  Zimage_featsZ
text_featsZidxsrg  ptrr   r   r    _dequeue_and_enqueue  s   

z/MPlugForImageTextRetrieval._dequeue_and_enqueueNTc           6   	   C   s(  |r| j j|dd}| jr| | | |}tj| d d tj	d
|j}tj| |d d dd d f dd}| j|j|jdd}|j}	tj| |	d d dd d f dd}
|dd}tj| | j  gdd}t|| }||jddd	 }t  |   | jj|dd}| jr|  | !| "|}tj| #|d d dd d f dd}tj| | j$  gdd}| j%|j|jdd}tj| &|jd d dd d f dd}tj| | j'  gdd}| j(r)|| | j) }|| | j) }| j*tj+|dd d| j* |  }| j*tj+|dd d| j* |  }W d    n	1 s4w   Y  || | j) }|
| | j) }| j(rntjtj,|dd| dd-  }tjtj,|dd| dd-  }n"tjtj,|dd| dd-  }tjtj,|dd| dd-  }|| d
 }| .||| | j/|	|j||dd\}}t > |d}tj+|d d d |f dd} tj+|d d d |f dd}!t||j0}"| 1|"d |!1|"d W d    n	1 sw   Y  g }#t2|D ]}$t3|!|$ d4 }%|#5||%  qtj6|#dd}#g }&g }'t2|D ]}$t3| |$ d4 }%|&5|	|%  |'5|j|%  qtj6|&dd}&tj6|'dd}'tj|	|&gdd}(tj|j|'gdd})tj|#|gdd}*tj||gdd}+| j/|(|)|*|+dd\}},tj|d d dd d f |,d d dd d f gdd}-| 7|-}.tj|tj	d}/tj8d
| tj	d}0tj|/|0gdd
|j}1t9|.|1}2||2 S | j|j|jd}|j}
| j j|dd}| | |}tj| d d tj	|jd}3| j/|
|j||3dd\}}4| 7|4d d dd d f }5tj+|5dd}5|5S )NTr(  rY   r   r   r   r)  r'   )Zkeepdimr&   Fr*  )r   rr   ):r  r  r  rj   r  r  rA   rd  rs   ru   r   r   r  re  ra  r  rv   r   r"  rb  r   r   tr[  clonedetacheqr  r  r#  r  r  r  r  r  rf  rY  r  rg  rZ  r  r^  r  r3  r  r=  rp  r  rk  Zmasked_fill_r   Zmultinomialitemr3   r2  rc  rt   Zcross_entropy)6ro   r4  textrn  r2   r8  r9  rl  r;  r<  rm  Zidx_allZpos_idxZsim_targetsrB  Zimage_feat_mZimage_feat_allrC  Ztext_feat_mZtext_feat_allZ	sim_i2t_mZ	sim_t2i_mZsim_i2t_targetsZsim_t2i_targetsZsim_i2tZsim_t2iZloss_i2tZloss_t2iZloss_itary  Z
output_posbsZweights_i2tZweights_t2irp  Zimage_embeds_negrA  Zneg_idxZtext_embeds_negZtext_atts_negZtext_embeds_allZtext_atts_allZimage_embeds_allZimage_atts_allZ
output_negZvl_embeddingsZ	vl_outputZones_tmpZ	zeros_tmpZ
itm_labelsZloss_itmZ	image_attr   Zscoresr   r   r    r}   	  sr  
!





,


z"MPlugForImageTextRetrieval.forwardr  )
r~   r   r   r]   r  rA   r#  rp  r}   r   r   r   rp   r    r    s    
%r  c                       s|   e Zd ZeZ fddZedddZdd Zdd	 Z	d
d Z
e dd Ze dd ZdddZedd Z  ZS )HiTeAc                    sn   t  | || _ttj|jt	j
| _| | t|jt|jd| _t| jdd| _t| jdd| _d S )NZimg_sizerD   
num_framesFr  )r\   r]   rD   r   r  r-   r.   r7   r  r   r  r  r  r   r  r   rz  r  rC  r  r  r  r  r  rn   rp   r   r    r]   	  s"   
zHiTeA.__init__Tc           	      C   s   ddl m} |jt|jti}| jtj	
|t}||_||j |}|rTtj	
|tj}tj|dd}d|v r<|d }d|v rD|d }dd | D }|j|d	d
 |S )Nr   r  r  r  rC   r	  c                 S   r  r  r  r  r   r   r    r  	  r  z)HiTeA.from_pretrained.<locals>.<dictcomp>Fr  )r  r  Zvideo_question_answeringHiTeAForVideoQuestionAnsweringZvideo_captioningHiTeAForVideoCaptionr@  r  r-   r.   r7   r  r  r  r   r  rA   r  rU  r  )	r  r  r  r  r  rD   rC   r  r  r   r   r    r  	  s.   zHiTeA.from_pretrainedc                 C   s   |j | _ | j rBt|jt|jd| _t| jdd| _t	| j
dd| _t| j| _| j| jg| j| jg| j| jgg| _|   d| _d S d S )Nry  Fr  r  )r  r   r  r   rz  r  rC  r  r  r  r  r  r  r  r  r  r  r  r  r  r  rn   r   r   r    r  	  s*   



zHiTeA.init_distillc                 O   r  r   r  r  r   r   r    r}   	  r  zHiTeA.forwardc                 C   sZ   t j|j|j}t|| _| jj| j_	t|| _
t|| _d| j_| jj| j_	d S r  )r-   r.   r7   r  r  r   r  r  r  r   r  r  r   r  r  r   r   r    r   
  s   zHiTeA.module_settingc                 C   r  r  r  r  r   r   r    r  	
  r  zHiTeA.copy_paramsc                 C   r  r  r  r  r   r   r    r  
  r  zHiTeA._momentum_updater'   c                 C   r	  r
  r  r  r   r   r    r  
  r  zHiTeA.generationc                    r  )Nr   r'   c                    r  r   r  r   r  r   r    r   (
  r  zHiTeA._tile.<locals>.<listcomp>r  r  r   r  r    r  
  r  zHiTeA._tilerz  r   )r~   r   r   r   r@  r]   r!  r  r  r}   r  rA   r#  r  r  r  r"  r  r   r   r   rp   r    rx  	  s    	


rx  c                       r$  )	r{  c                    r%  r   r&  rn   rp   r   r    r]   .
  r'  z'HiTeAForVideoQuestionAnswering.__init__Nr   Tc           !      C   s  |j t|  jd}| |}tj| d d tjd |j	}	|r;	 |j
|j
| jjkd}
| j|j
|jdd}|j}| j||j||	dd}|\}}t||gd}t|	|jgd}|d u rkdg|jd	  }g }g }t|D ]\}}||| g| 7 }||| g| 7 }qst|d	}t|d	}| jrt [ |   | |}| j|j
|jdd}|j}| j||j||	dd}|\}}t||gd}g }t|D ]\}}||| g| 7 }qt|d	}| j|j
|j||dd
}W d    n1 sw   Y  | j|j
|j|||
dtj|dddd}n| j|j
|j|||
ddd}|d u r+d}||j  }|! |d	 }|S | j|j
|jdd}|j}| j||j||	dd}|\}}t||gd}t|	|jgd}| "||\}} || fS )Nr   rY   r  Tr)  Fr*  r'   r   r+  r   r,  r-  r.  )#r   r/  r   rP   r  rA   rd  rs   ru   r   rv   r0  r  ra   r  r   r"  r  r   r>   r1  r2  r  r#  r  r  r  r  r  r  r  r3  r  r  r  )!ro   videor5  r6  r  r  r7  r2   video_embeds
video_attsr:  r;  r<  r=  video_outputr?  r@  r  r  rA  r   Zvideo_embeds_mrC  rD  rE  rF  rG  rH  rI  rJ  r  r  rK  r   r   r    r}   4
  s   



 
	

z&HiTeAForVideoQuestionAnswering.forwardrL  r   r   r   rp   r    r{  ,
  rM  r{  c                       rN  )r|  c                    rO  r   rP  rn   rp   r   r    r]   
  rQ  zHiTeAForVideoCaption.__init__NTrR  c                 C   s   |  |}tj| d d tjd|j}| j|j|j	dd}|j
}	| j|	|j	||dd}
|
\}}t||gd}t||j	gd}| j|||d\}}||fS )	NrY   r   Tr)  Fr*  r'   r  )r  rA   rd  rs   ru   r   r   r  rv   r   r"  r  r   r  )ro   r}  r5  r6  r2   r  r~  r  r;  r<  r=  r  r?  r@  r  rK  r   r   r    rS  
  s8   

z HiTeAForVideoCaption.beam_searchFc              	   C   s   |r| j |||d|dS |jt|  jd}| |}tj| d d tj	d|j
}|rO|j|j| jjkd}	| j|j|j|||	ddd}
|
j}|S | ||\}}||fS )NTrT  r   rY   r  r,  r.  )rS  r   r/  r   rP   r  rA   rd  rs   ru   r   rv   r0  r  ra   r  r   r  r  )ro   r}  r5  r6  r2   r  rU  r~  r  r:  rJ  r  r  rK  r   r   r    r}   
  s8   

zHiTeAForVideoCaption.forwardrV  rW  rX  r   r   rp   r    r|  
  s    
r|  )Vr   r   r-   typingr   rA   Ztorch.nn.functionalr   Z
functionalr  Ztorch.utils.checkpointZtransformersr   r   Ztorch.nnr   r   r   Ztransformers.activationsr	   Ztransformers.file_utilsr
   r   r   r   Ztransformers.modeling_outputsr   r   r   Ztransformers.modeling_utilsr   Ztransformers.utilsr   Z7modelscope.models.multi_modal.mplug.configuration_mplugr   r   Z(modelscope.models.multi_modal.mplug.mvitr   r   Z-modelscope.models.multi_modal.mplug.predictorr   r  r   Zmodelscope.utils.torch_utilsr   r   r   Zset_verbosity_errorZ
get_loggerr+   r  r  r~  rM   rT   ModulerU   r   r   r   r   r   r   r   r   r   r%  r)  r+  r/  r6  r:  r;  ZBERT_START_DOCSTRINGr}  rC  r  r  r  r  r  r  r  rx  r{  r|  r   r   r   r    <module>   s   
JB 4QZ\\*     7m + K  q 
