o
    ߥi                    @   s<  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mZm Z 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- ej#.  e#/ Z0dZ1dZ2dZ3dd Z4dd Z5G dd dej6Z7G dd dej6Z8G dd dej6Z9G dd dej6Z:G dd  d ej6Z;G d!d" d"ej6Z<G d#d$ d$ej6Z=G d%d& d&ej6Z>G d'd( d(ej6Z?G d)d* d*ej6Z@G d+d, d,ej6ZAG d-d. d.ej6ZBG d/d0 d0ej6ZCG d1d2 d2ej6ZDG d3d4 d4ej6ZEG d5d6 d6ej6ZFG d7d8 d8eZGd9ZHd:ZIed;eHG d<d= d=eGZJG d>d? d?eGZKed@eHG dAdB dBeGZLG dCdD dDeGZMG dEdF dFeZNG dGdH dHeNZOG dIdJ dJeNZPG dKdL dLeNZQG dMdN dNeZRG dOdP dPeRZSG dQdR dReRZTdS )Sz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apply_chunking_to_forward find_pruneable_heads_and_indicesprune_linear_layer)logging)HiTeAConfigMPlugConfig)MViTv2MViTv2_Base_config)TextGenerator)	ModelFilez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 ))adam_vadam_mAdamWeightDecayOptimizerAdamWeightDecayOptimizer_1global_stepN ).0nr"   r"   f/home/ubuntu/.local/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+)kernelgammaweightoutput_biasbetabiasoutput_weightssquad
classifier      i_embeddingszPointer shape z and array shape z mismatchedzInitialize PyTorch weight {})renumpy
tensorflowImportErrorloggererrorospathabspathinfoformattrainlist_variablesload_variableappendzipsplitanyjoin	fullmatchgetattrAttributeErrorlenint	transposeshapeAssertionErrorargstorch
from_numpydata)modelconfigtf_checkpoint_pathr3   nptftf_path	init_varsnamesarraysnamerL   arraypointerm_namescope_namesnumer"   r"   r%   load_tf_weights_in_bert;   s   



rb   c                 C   sB   | j tjkrt|  rt| j jd }tj| | |d} | S )Ni  )minmax)dtyperO   float16isinfrD   finford   clamp)tensorclamp_valuer"   r"   r%   	clamp_inf   s   rl   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)padding_idxepsposition_ids)r1   position_embedding_typeabsolute)super__init__r   	Embedding
vocab_sizehidden_sizepad_token_idword_embeddingsmax_position_embeddingsposition_embeddingstype_vocab_sizetoken_type_embeddings	LayerNormlayer_norm_epsDropouthidden_dropout_probdropoutregister_bufferrO   arangeexpandrG   rs   rS   selfrS   	__class__r"   r%   rv      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 )Nrr   r1   re   r   rt   )sizerq   rO   zeroslongr   r{   r   rs   r}   r   r   )r   	input_idstoken_type_idsrq   inputs_embedspast_key_values_lengthinput_shape
seq_lengthr   
embeddingsr}   r"   r"   r%   forward   s0   







zBertEmbeddings.forward)NNNNr   )__name__
__module____qualname____doc__rv   r   __classcell__r"   r"   r   r%   rm      s    rm   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   embedding_sizezLThe hidden size (%d) is not a multiple of the number of attention heads (%d)rs   rt   relative_keyrelative_key_queryr0   r1   F)ru   rv   rS   ry   num_attention_headshasattr
ValueErrorrJ   attention_head_sizeall_head_sizer   Linearqueryencoder_widthkeyvaluer   attention_probs_dropout_probr   rG   rs   r|   rw   distance_embeddingsave_attentionr   rS   is_cross_attentionr   r"   r%   rv      sB   


zBertSelfAttention.__init__c                 C   
   || _ d S Nattn_gradients)r   r   r"   r"   r%   save_attn_gradients      
z%BertSelfAttention.save_attn_gradientsc                 C      | j S r   r   r   r"   r"   r%   get_attn_gradients      z$BertSelfAttention.get_attn_gradientsc                 C   r   r   attention_map)r   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 )Nrr   r   r0   r1      )r   r   r   viewpermute)r   x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   r0   dimr1   rr   r   r   r   re   zbhld,lrd->bhlrzbhrd,lrd->bhlrr   )!r   r   r   r   rO   catmatmulrK   rl   rs   r   r   r   r   r   r   r|   tore   einsummathsqrtr   r   Softmaxr   r   register_hookr   r   r   
contiguousr   )r   hidden_statesattention_mask	head_maskencoder_hidden_statesencoder_attention_maskpast_key_valueoutput_attentionsmixed_query_layerr   	key_layervalue_layerquery_layerattention_scoresr   position_ids_lposition_ids_rdistancepositional_embeddingrelative_position_scoresrelative_position_scores_queryrelative_position_scores_keyattention_probsattention_probs_droppedcontext_layernew_context_layer_shapeoutputsr"   r"   r%   r     s   











zBertSelfAttention.forwardNNNNNF)r   r   r   rv   r   r   r   r   r   r   r   r"   r"   r   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 Nro   )ru   rv   r   r   ry   denser   r   r   r   r   r   r   r"   r%   rv   j     
zBertSelfOutput.__init__c                 C   s&   |  |}| |}| || }|S r   )r   r   r   r   r   input_tensorr"   r"   r%   r   q  s   

zBertSelfOutput.forwardr   r   r   rv   r   r   r"   r"   r   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   )ru   rv   r   r   r   outputsetpruned_headsr   r   r"   r%   rv   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   r1   r   )rI   r   r   r   r   r   r   r   r   r   r   r   r   union)r   headsindexr"   r"   r%   prune_heads  s   

zBertAttention.prune_headsNc              	   C   s<   |  |||||||}| |d |}	|	f|dd   }
|
S )Nr   r1   )r   r   )r   r   r   r   r   r   r   r   self_outputsattention_outputr   r"   r"   r%   r     s   
	
zBertAttention.forward)Fr   )r   r   r   rv   r   r   r   r"   r"   r   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   )ru   rv   r   r   ry   intermediate_sizer   
isinstance
hidden_actstrr	   intermediate_act_fnr   r   r"   r%   rv     s
   
zBertIntermediate.__init__c                 C      |  |}| |}|S r   )r   r  r   r   r"   r"   r%   r        

zBertIntermediate.forwardr   r"   r"   r   r%   r     s    r   c                       r   )
BertOutputc                    sB   t    t|j|j| _tj|j|jd| _t	|j
| _d S r   )ru   rv   r   r   r   ry   r   r   r   r   r   r   r   r   r"   r%   rv     r   zBertOutput.__init__c                 C   s6   |  |}t|}| |}t|}| || }|S r   )r   rl   r   r   r   r"   r"   r%   r     s   

zBertOutput.forwardr   r"   r"   r   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   r1   Tr   )ru   rv   rS   rG   r  chunk_size_feed_forwardseq_len_dimr   	attentioncrossattentionr   intermediater  r   r   rS   	layer_numr   r"   r%   rv     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 )	Nr0   r   r   r   r1   rr   >encoder_hidden_states must be given for cross-attention layersr   r   )	r  r  r  rO   r   r   feed_forward_chunkr  r  )r   r   r   r   r   r   
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   r   r   intermediate_outputr  r"   r"   r%   r       
zFusionLayer.feed_forward_chunk)NNNNNNFr   r   r   rv   r   r  r   r"   r"   r   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 )Nr1   add_cross_attentionFTr
  )ru   rv   rS   r  r  r   r  rG   has_cross_attentionr  r   r  r  r   r  r   r"   r%   rv   !  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 )Nr0   r  r   r1   rr   r  r  )r  r$  typelistr  r  rS   fusion_layerrI   r   r  r  r  )r   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"   r   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rS   r"   r%   
<listcomp>      z*FusionEncoder.__init__.<locals>.<listcomp>r   )ru   rv   rS   r   
ModuleListrangenum_hidden_layerslayerrd   fusion_layersstart_layerr   r   r-  r%   rv   {  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	  r1   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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   rr   )rG   rS   r  rL   r1  r5  rI   r3  trainingr7   warningrO   utils
checkpointrC   )r   r   r   r   r   r   past_key_values	use_cacher   output_hidden_statesreturn_dictall_hidden_statesall_self_attentionsnext_decoder_cacheimage_lengthtext_lengthr,  layer_modulelayer_head_maskrD  layer_outputsencoder_hidden_states_newr"   r  r%   r     s~   






zFusionEncoder.forward	NNNNNNFFTr   r"   r"   r   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>)ru   rv   rS   r   r0  r1  r2  r3  r   r   r-  r%   rv     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"   r6  Fr7  c                    r8  )Nc                     r9  r   r:  r<  r>  r"   r%   r@    rA  zJBertEncoder.forward.<locals>.create_custom_forward.<locals>.custom_forwardr"   rB  r  rC  r%   rD     rE  z2BertEncoder.forward.<locals>.create_custom_forwardr   rr   r1   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_staterJ  r   
attentionscross_attentions)rS   r#  r1  rI   r3  rG   rF  r7   rG  rO   rH  rI  r;  r   )r   r   r   r   r   r   rJ  rK  r   rL  rM  rN  rO  all_cross_attentionsrP  r,  rS  rT  rD  rU  r"   r  r%   r     s   




zBertEncoder.forwardrW  r   r"   r"   r   r%   rX    s    rX  c                       r   )
BertPoolerc                    s*   t    t|j|j| _t | _d S r   )ru   rv   r   r   ry   r   Tanh
activationr   r   r"   r%   rv   3  s   
zBertPooler.__init__c                 C   s(   |d d df }|  |}| |}|S )Nr   )r   r`  )r   r   first_token_tensorpooled_outputr"   r"   r%   r   8  s   

zBertPooler.forwardr   r"   r"   r   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   )ru   rv   r   r   ry   r   r   r   r  r	   transform_act_fnr   r   r   r   r"   r%   rv   C  s   
z$BertPredictionHeadTransform.__init__c                 C   s"   |  |}| |}| |}|S r   )r   re  r   r  r"   r"   r%   r   M  s   


z#BertPredictionHeadTransform.forwardr   r"   r"   r   r%   rd  A  s    
rd  c                       r   )BertLMPredictionHeadc                    sL   t    t|| _tj|j|jdd| _t	t
|j| _| j| j_d S )NF)r,   )ru   rv   rd  	transformr   r   ry   rx   decoder	ParameterrO   r   r,   r   r   r"   r%   rv   V  s   


zBertLMPredictionHead.__init__c                 C   r  r   )rg  rh  r  r"   r"   r%   r   d  r  zBertLMPredictionHead.forwardr   r"   r"   r   r%   rf  T  s    rf  c                       r   )BertOnlyMLMHeadc                    s   t    t|| _d S r   )ru   rv   rf  predictionsr   r   r"   r%   rv   l  s   
zBertOnlyMLMHead.__init__c                 C      |  |}|S r   )rk  )r   sequence_outputprediction_scoresr"   r"   r%   r   p     
zBertOnlyMLMHead.forwardr   r"   r"   r   r%   rj  j      rj  c                       r   )BertOnlyNSPHeadc                    s   t    t|jd| _d S Nr0   )ru   rv   r   r   ry   seq_relationshipr   r   r"   r%   rv   w  s   
zBertOnlyNSPHead.__init__c                 C   rl  r   )rs  )r   rb  seq_relationship_scorer"   r"   r%   r   {  ro  zBertOnlyNSPHead.forwardr   r"   r"   r   r%   rq  u  rp  rq  c                       r   )BertPreTrainingHeadsc                    s(   t    t|| _t|jd| _d S rr  )ru   rv   rf  rk  r   r   ry   rs  r   r   r"   r%   rv     s   

zBertPreTrainingHeads.__init__c                 C   s   |  |}| |}||fS r   )rk  rs  )r   rm  rb  rn  rt  r"   r"   r%   r     s   

zBertPreTrainingHeads.forwardr   r"   r"   r   r%   ru    rc  ru  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.
    bertrq   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        )meanstd      ?N)r   r   r   rw   r)   rQ   normal_rS   initializer_ranger   r,   zero_fill_)r   r?  r"   r"   r%   _init_weights  s   z!BertPreTrainedModel._init_weightsN)r   r   r   r   r   config_classrb   load_tf_weightsbase_model_prefix_keys_to_ignore_on_load_missingr  r"   r"   r"   r%   rv    s    rv  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   )
ru   rv   rS   rm   r   rX  encoderr^  poolerinit_weightsr   rS   add_pooling_layerr   r"   r%   rv     s   

zBertModel.__init__c                 C      | j jS r   r   r{   r   r"   r"   r%   get_input_embeddings     zBertModel.get_input_embeddingsc                 C      || j _d S r   r  r   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itemsr  r3  r  r   r   heads_to_pruner3  r   r"   r"   r%   _prune_heads     zBertModel._prune_headsbatch_size, sequence_lengthbert-base-uncasedprocessor_classrI  output_typer  r   r   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   Nr0   r   r1   )r   re   rr   )axiszAWrong shape for input_ids (shape {}) or attention_mask (shape {})r   rz  g     r   rO   r   repeatr   re   rL   r   onesr   r=   r   r   r   r   r  extended_attention_mask
batch_sizer   seq_idscausal_mask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 timerr   GYou have to specify either input_ids or inputs_embeds or encoder_embedsr   r0   r  r   c                       g | ]}  |qS r"   invert_attention_maskr#   maskr   r"   r%   r.        z%BertModel.forward.<locals>.<listcomp>r   rq   r   r   r   	r   r   r   r   rJ  rK  r   rL  rM  r1   rZ  pooler_outputrJ  r   r[  r\  rS   r   rL  use_return_dictrK  r   r   r   rL   rO   r  r   r   r  r%  r&  r  get_head_maskr2  r   r  r  r   rJ  r   r[  r\  r   r   r   r   rq   r   r   encoder_embedsr   r   rJ  rK  r   rL  rM  r  r   r  r   r   r   r  encoder_batch_sizeencoder_sequence_length_encoder_hidden_shapeencoder_extended_attention_maskembedding_outputencoder_outputsrm  rb  r"   r   r%   r   T  s   (



zBertModel.forwardTNNNNNNNNNNNNNNFr   r   r   r   rv   r  r  r  r   BERT_INPUTS_DOCSTRINGr=   r
   _TOKENIZER_FOR_DOCr   _CONFIG_FOR_DOCr   r   rJ   r   boolr  r   r   r"   r"   r   r%   r    sP    	Hr  c                       r  )FusionModelr  Tc                    s:   t  | || _t|| _|rt|nd | _|   d S r   )ru   rv   rS   r)  r  r^  r  r  r  r   r"   r%   rv     s
   
zFusionModel.__init__c                 C   r  r   r  r   r"   r"   r%   r  
  r  z FusionModel.get_input_embeddingsc                 C   r  r   r  r  r"   r"   r%   r    r  z FusionModel.set_input_embeddingsc                 C   r  r  r  r  r"   r"   r%   r    r  zFusionModel._prune_headsr  r  r  r   r   r   r  r  c                 C   r  r  r  r  r"   r"   r%   r    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 )r  NFr  rr   r  r   r0   r  r   c                    r  r"   r  r  r   r"   r%   r.    r  z'FusionModel.forward.<locals>.<listcomp>r  r  r  r  r  r"   r   r%   r   g  s   &



zFusionModel.forwardr  r  r  r"   r"   r   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 )BertLMHeadModelr  rq   predictions.decoder.biasc                    0   t  | t|dd| _t|| _|   d S NFr  ru   rv   r  rw  rj  clsr  r   r   r"   r%   rv        
zBertLMHeadModel.__init__c                 C   
   | j jjS r   r  rk  rh  r   r"   r"   r%   get_output_embeddings  r   z%BertLMHeadModel.get_output_embeddingsc                 C      || j j_d S r   r  r   new_embeddingsr"   r"   r%   set_output_embeddings     z%BertLMHeadModel.set_output_embeddingsr  )r  r  NTrx  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   r   rq   r   r   r   r   rJ  rK  r   rL  rM  r  r   rr   r1   )	reductionr   r0   losslogitsrJ  r   r[  r\  )rS   r  rw  r  r   r   r   rx   r   sumrO   Flog_softmaxr   rJ  r   r[  r\  r   r   r   r   rq   r   r   r   r   labelsrJ  rK  r   rL  rM  r  r  soft_labelsalphareturn_logitsr   rm  rn  lm_lossshifted_prediction_scoresloss_fct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 )Nrr   r   r   T)r   r   rJ  r   r   r  )rL   new_onesget)r   r   pastr   model_kwargsr   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#   
past_statebeam_idxr"   r%   r&     s
    

z1BertLMHeadModel._reorder_cache.<locals>.<genexpr>r:  )r   r  r  reordered_past
layer_pastr"   r  r%   _reorder_cache  s   zBertLMHeadModel._reorder_cacheNNNNNNNNNNNNNNTrx  Nr   F)NN)r   r   r   "_keys_to_ignore_on_load_unexpectedr  rv   r  r  r   r  r=   r   r   r  r   r  r  r   r"   r"   r   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 )BertPrefixModelr  rq   r  c                    r  r  r  r   r   r"   r%   rv     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_embeddingsr  r  r  NTrx  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   rr   r1   r   r  r0   r  )rS   r  rw  r  r   r   r   rx   rO   r  r  r  rx  r   rJ  r   r[  r\  r  r"   r"   r%   r     sp   

zBertPrefixModel.forwardr   )r   r   r   r  r  rv   r  r  r   r  r=   r
   r  r   r  r   r   r"   r"   r   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  )ru   rv   rS   r   from_pretrainedr9   r:   rE   	model_dirr   
VOCAB_FILE	tokenizermodule_setting_initialize_clipvisual_encoderr  config_encodertext_encoderr  config_fusionfusion_encoderr   r   r"   r%   rv   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map_locationrR   r?  c                 S      i | ]\}}| d d|qS zmodel. replacer#   krY  r"   r"   r%   
<dictcomp>V      z)MPlug.from_pretrained.<locals>.<dictcomp>Fstrictzload checkpoint from %s)modelscope.utils.constantr  visual_question_answeringMPlugForVisualQuestionAnsweringimage_captioningMPlugForImageCaptionimage_text_retrievalMPlugForImageTextRetrievalr  from_yaml_filer9   r:   rE   CONFIG_NAMEr  taskr   TORCH_MODEL_BIN_FILErO   loadr  load_state_dictprint)r  r  r(  load_checkpointr  task_mappingrS   rR   checkpoint_pathrI  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 )	Nr1   r   rr   r   r0   bilinear)r   moder   )rL   rJ   r   r   rI   reshaper   re   r  interpolatefloatr   rO   r   )posemb
posemb_newntok_new
posemb_tokposemb_gridgs_oldgs_neworigr"   r"   r%   resize_pos_embedc  s(   
&


z0MPlug._initialize_clip.<locals>.resize_pos_embedr1   )clipzViT-B-16   i      i   r   )r@  load_from_config	clip_namerJ   	image_resr   ri  rO   r   r6  visualr   	unsqueezer)   )rS   num_patchesr?  r@  
clip_model	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=ro   ףp=
?)distillr	  visual_encoder_mr  r  text_encoder_mr  r  fusion_encoder_mr  config_decodertext_decoder_mr
  r  text_decodermodel_pairsry   vision_widthr   r   	visn_fc_mr   visn_layer_norm_mr   r   	dropout_mextendvisn_fcvisn_layer_normcopy_paramsmomentumr   r"   r"   r%   init_distill  s@   





zMPlug.init_distillc                 O      t r   NotImplementedErrorr   rN   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 )NTFrL  ro   )r9   r:   rE   r  bert_configr   from_json_filer  text_encoder_layersr2  r  rR  r#  text_decode_layerslargery   rV  r   r   r[  r   r\  r   r   r   r   rS   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   r1   FrU  rB   
parametersrQ   copy_requires_gradr   
model_pairparam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   r1   rz  rU  rB   rp  rQ   r^  rs  r"   r"   r%   _momentum_update     


zMPlug._momentum_updater1   c                 C   $   ||g}| j j||d\}}||fS Nout_sizebeam_generatortranslate_batchr   question_statesquestion_attsr  encoder_inputstopk_ids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   r1   c                       g | ]}   | qS r"   r   r+  init_dimn_tilerU   r"   r%   r.        zMPlug._tile.<locals>.<listcomp>r4   r   r   r  rO   
LongTensorconcatenater1  r  r   r   r   r   r  
repeat_idxorder_indexr"   r  r%   _tile     

zMPlug._tileNT)r1  r1   )r   r   r   r   r  rv   classmethodr  staticmethodr	  r_  r   r  rO   no_gradr]  r{  r  r  r   r"   r"   r   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   ru   rv   r  rR  rT  r   r  r_  r   r   r"   r%   rv        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skip_last_layerrr   r  r   rM  Fr  r   r   r   rM  r1   r   r   r   r   r  r   noner   r   r   r  rM  r  r  r   r   r   r  rM  r  )+r   nextrp  re   r
  rF  rj  r   r\  r[  rO   r  r   r   r   r   masked_fillr  rz   r  r   rZ  r  r   rL   	enumeratestackrN  r  r{  rO  rY  rX  rW  rP  rQ  rS  rT  r  softmaxr  r  r  )!r   imagequestionanswerr  r  weightsr>   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"   r   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   ru   rv   r  rR  rT  r   r  r   r   r"   r%   rv   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  rr   r   r  Fr  r1   r  )r
  rF  rj  r   r\  r[  rO   r  r   r   r   r   r  r   r   rZ  r  r   r  )r   r  r  r  r>   r  r  r  r  r  r  r  r  r  r  r  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r>   r  r   r  rr   r  r  r  )r  r   r  rp  re   r
  rF  rj  r   r\  r[  rO   r  r   r   r   r   r  r  rz   rT  r   r  r  )r   r  r  r  r>   r  scstr  r  r  r  r  r  r  r"   r"   r%   r     s@   
zMPlugForImageCaption.forwardNTr  NTr  Fr   r   r   rv   r  r   r   r"   r"   r   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 )Nr0   image_queue
text_queue	idx_queuer1   r  	queue_ptrr   r   r   )ru   rv   	embed_dimr   ri  rO   r  temp
queue_sizer^  r  r  ry   
text_widthr   vision_proj	text_projitm_headr   randnfullr   r   r  	normalizer  r  r_  r   r   r"   r%   rv     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 rK  )!rN  r	  rO  r  r  rP  r  r  rQ  r   r   r  r  vision_proj_mtext_proj_mr
  r  r  r  rU  ry   rV  rW  r   rX  r   r   rY  rZ  r[  r\  r]  r^  r   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"   )rO   	ones_like)r#   r  rj   r"   r%   r.    r  z^MPlugForImageTextRetrieval._dequeue_and_enqueue.<locals>.concat_all_gather.<locals>.<listcomp>F)async_opr   r   )rO   distributedis_initializedr1  get_world_size
all_gatherr   )rj   tensors_gatherr   r"   r  r%   concat_all_gather  s   

zJMPlugForImageTextRetrieval._dequeue_and_enqueue.<locals>.concat_all_gatherr   )rL   rJ   r  Tr  r  r  r  )
r   
image_feat	text_featidxr  image_feats
text_featsidxsr  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  rr   r   r   r   r  r1   )keepdimr0   Fr  )r   r   ):r
  rF  rj  r   r\  r[  rO   r  r   r   r   r   r  r  r  r  r   r   rZ  r  r   r   tr  clonedetacheqr6  r  r  r{  rO  rY  rX  rW  r  r  rP  r  r  rN  r  r  r  r  rx  r  r  r  masked_fill_r1  multinomialitemrA   r  r  r   cross_entropy)6r   r  textr  r>   r  r  r  r  r  r  idx_allpos_idxsim_targetsr  image_feat_mimage_feat_allr  text_feat_mtext_feat_all	sim_i2t_m	sim_t2i_msim_i2t_targetssim_t2i_targetssim_i2tsim_t2iloss_i2tloss_t2iloss_itar  
output_posbsweights_i2tweights_t2ir  image_embeds_negr  neg_idxtext_embeds_negtext_atts_negtext_embeds_alltext_atts_allimage_embeds_allimage_atts_all
output_negvl_embeddings	vl_outputones_tmp	zeros_tmp
itm_labelsloss_itm	image_attr   scoresr"   r"   r%   r   	  sr  
!





,


z"MPlugForImageTextRetrieval.forwardr  )
r   r   r   rv   r_  rO   r  r  r   r   r"   r"   r   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img_sizerS   
num_framesFr  )ru   rv   rS   r   r  r9   r:   rE   r  r   r  r  r  r   rE  r   r*  r
  r  r  r  r  r  r  r   r   r"   r%   rv   	  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  rR   r?  c                 S   r  r  r  r  r"   r"   r%   r  	  r  z)HiTeA.from_pretrained.<locals>.<dictcomp>Fr  )r  r  video_question_answeringHiTeAForVideoQuestionAnsweringvideo_captioningHiTeAForVideoCaptionr  r&  r9   r:   rE   r'  r  r(  r   r)  rO   r*  r  r+  )	r  r  r-  r  r.  rS   rR   r/  rI  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 )Nr(  Fr  rM  )rN  r   rE  r   r*  rO  r  r  rP  r  r  rQ  r  rR  rS  r
  r  rT  rU  r]  r^  r   r"   r"   r%   r_  	  s*   



zHiTeA.init_distillc                 O   r`  r   ra  rc  r"   r"   r%   r   	  re  zHiTeA.forwardc                 C   sZ   t j|j|j}t|| _| jj| j_	t|| _
t|| _d| j_| jj| j_	d S r  )r9   r:   rE   r  rf  r   rg  r  rh  r2  r  rR  r#  ri  rk  r"   r"   r%   r   
  s   zHiTeA.module_settingc                 C   rm  rn  ro  rs  r"   r"   r%   r]  	
  rw  zHiTeA.copy_paramsc                 C   rx  ry  rz  rs  r"   r"   r%   r{  
  r|  zHiTeA._momentum_updater1   c                 C   r}  r~  r  r  r"   r"   r%   r  
  r  zHiTeA.generationc                    r  )Nr   r1   c                    r  r"   r  r+  r  r"   r%   r.  (
  r  zHiTeA._tile.<locals>.<listcomp>r  r  r"   r  r%   r  
  r  zHiTeA._tiler  r  )r   r   r   r   r  rv   r  r  r_  r   r  rO   r  r]  r{  r  r  r  r   r"   r"   r   r%   r'  	  s    	


r'  c                       r  )	r,  c                    r  r   r  r   r   r"   r%   rv   .
  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   rr   r  Tr  Fr  r1   r   r  r   r  r  r  )#r   r  rp  re   r
  rO   r  r   r   r   r   r  r  rz   r  r   rZ  r  r   rL   r  r  rN  r  r{  rO  rP  rQ  rS  rT  r  r  r  r  r  )!r   videor  r  r  r  r  r>   video_embeds
video_attsr  r  r  r  video_outputr  r  r  r  r  r$   video_embeds_mr  r  r  r  r  r  r  r  r  r  r  r"   r"   r%   r   4
  s   



 
	

z&HiTeAForVideoQuestionAnswering.forwardr  r   r"   r"   r   r%   r,  ,
  r  r,  c                       r  )r.  c                    r  r   r  r   r   r"   r%   rv   
  r  zHiTeAForVideoCaption.__init__NTr  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 )	Nrr   r   Tr  Fr  r1   r  )r
  rO   r  r   r   r   r   r  r   r   rZ  r  r   r  )r   r/  r  r  r>   r  r0  r1  r  r  r  r2  r  r  r  r  r"   r"   r%   r  
  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 )NTr  r   rr   r  r  r  )r  r   r  rp  re   r
  rO   r  r   r   r   r   r  r  rz   rT  r   r  r  )r   r/  r  r  r>   r  r  r0  r1  r  r  r  r  r  r"   r"   r%   r   
  s8   

zHiTeAForVideoCaption.forwardr  r  r  r"   r"   r   r%   r.  
  s    
r.  )Ur   r   r9   typingr   rO   torch.nn.functionalr   
functionalr  torch.utils.checkpointtransformersr   r   torch.nnr   r   r   transformers.activationsr	   transformers.file_utilsr
   r   r   r   transformers.modeling_outputsr   r   r   transformers.modeling_utilsr   r   r   r   transformers.utilsr   7modelscope.models.multi_modal.mplug.configuration_mplugr   r   (modelscope.models.multi_modal.mplug.mvitr   r   -modelscope.models.multi_modal.mplug.predictorr   r  r   set_verbosity_error
get_loggerr7   r'  r  r  rb   rl   Modulerm   r   r   r   r   r  r  r"  r)  rX  r^  rd  rf  rj  rq  ru  rv  BERT_START_DOCSTRINGr  r  r  r  r  r  r!  r#  r%  r'  r,  r.  r"   r"   r"   r%   <module>   s   
JB 4QZ\\*     7m + K  q 
