o
    ߥi                     @   s  d Z ddlZddlZddlZddlmZ ddlmZ ddlmZm	Z	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 dd
lmZ ddlmZ ddlmZ ddlmZ e ZdZG dd dejZ G dd dejZ!G dd dejZ"G dd dejZ#G dd dejZ$G dd dejZ%G dd dejZ&G dd dejZ'G d d! d!ejZ(G d"d# d#eeZ)ej*ej+ej,d$G d%d& d&e)Z-dS )'z PyTorch MegatronBERT model.    N)nn)ACT2FN)PreTrainedModelapply_chunking_to_forward find_pruneable_heads_and_indicesprune_linear_layer)Models)Model
TorchModel)MODELS)AttentionBackboneModelOutput)Tasks)
get_logger)parse_labels_in_order   )MegatronBertConfigr   c                       s<   e Zd ZdZ fddZ					d	dejfddZ  ZS )
MegatronBertEmbeddingszGConstruct 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| _| dt|jd t|dd| _d S )N)padding_idxposition_ids)r   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Dropouthidden_dropout_probdropoutregister_buffertorcharangeexpandgetattrr   selfconfig	__class__ `/home/ubuntu/.local/lib/python3.10/site-packages/modelscope/models/nlp/megatron_bert/backbone.pyr   .   s*   

zMegatronBertEmbeddings.__init__Nr   returnc                 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 )Nr   r   dtypedevicer   )sizer   r'   zeroslongr5   r   r"   r   r    r%   )r,   	input_idstoken_type_idsr   inputs_embedspast_key_values_lengthinput_shape
seq_lengthr"   
embeddingsr    r0   r0   r1   forwardH   s.   






zMegatronBertEmbeddings.forward)NNNNr   )	__name__
__module____qualname____doc__r   r'   Tensorr@   __classcell__r0   r0   r.   r1   r   +   s    r   c                       sJ   e Zd Zd fdd	ZdejdejfddZ						dd	d
Z  ZS )MegatronBertSelfAttentionNc                    s   t    |j|j dkrt|dstd|j d|j d|j| _t|j|j | _| j| j | _t	
|j| j| _t	
|j| j| _t	
|j| j| _t	|j| _|p\t|dd| _| jdksh| jd	kry|j| _t	d
|j d | j| _|j| _d S )Nr   embedding_sizezThe hidden size (z6) is not a multiple of the number of attention heads ()r   r   relative_keyrelative_key_query   r   )r   r   r   num_attention_headshasattr
ValueErrorintattention_head_sizeall_head_sizer   Linearquerykeyvaluer#   attention_probs_dropout_probr%   r*   r   r   r   distance_embedding
is_decoder)r,   r-   r   r.   r0   r1   r   r   s8   

z"MegatronBertSelfAttention.__init__xr2   c                 C   s6   |  d d | j| jf }||}|ddddS )Nr   r   rL   r      )r6   rM   rQ   viewpermute)r,   rZ   new_x_shaper0   r0   r1   transpose_for_scores   s
   
z.MegatronBertSelfAttention.transpose_for_scoresFc                 C   s  |  |}|d u}	|	r|d ur|d }
|d }|}nP|	r/| | |}
| | |}|}n;|d urZ| | |}
| | |}tj|d |
gdd}
tj|d |gdd}n| | |}
| | |}| |}| jrv|
|f}t||
dd}| j	dks| 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j|dd}| |}|d ur|| }t||}|dddd }|
 d d | jf }||}|r9||fn|f}| jrE||f }|S )Nr   r   rL   dimr   rJ   rK   r3   )r4   zbhld,lrd->bhlrzbhrd,lrd->bhlrr[   )rT   r_   rU   rV   r'   catrY   matmul	transposer   r6   r(   r8   r5   r\   rX   r   tor4   einsummathsqrtrQ   r   
functionalsoftmaxr%   r]   
contiguousrR   )r,   hidden_statesattention_mask	head_maskencoder_hidden_statesencoder_attention_maskpast_key_valueoutput_attentionsmixed_query_layeris_cross_attention	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context_layernew_context_layer_shapeoutputsr0   r0   r1   r@      s   










z!MegatronBertSelfAttention.forwardNNNNNNF)	rA   rB   rC   r   r'   rE   r_   r@   rF   r0   r0   r.   r1   rG   p   s    	rG   c                       $   e Zd Z fddZdd Z  ZS )MegatronBertSelfOutputc                    s.   t    t|j|j| _t|j| _d S r   )	r   r   r   rS   r   denser#   r$   r%   r+   r.   r0   r1   r        
zMegatronBertSelfOutput.__init__c                 C      |  |}| |}|| S r   r   r%   )r,   rm   residualr0   r0   r1   r@   
  s   

zMegatronBertSelfOutput.forwardrA   rB   rC   r   r@   rF   r0   r0   r.   r1   r         r   c                       s:   e Zd Z fddZdd Z						d	ddZ  ZS )
MegatronBertAttentionc                    s>   t    tj|j|jd| _t|| _t	|| _
t | _d S )Neps)r   r   r   	LayerNormr   layer_norm_epslnrG   r,   r   outputsetpruned_headsr+   r.   r0   r1   r     s
   


zMegatronBertAttention.__init__c                 C   s   t |dkrd S t|| jj| jj| j\}}t| jj|| j_t| jj|| j_t| jj	|| j_	t| j
j|dd| j
_| jjt | | j_| jj| jj | j_| j|| _d S )Nr   r   r`   )lenr   r,   rM   rQ   r   r   rT   rU   rV   r   r   rR   union)r,   headsindexr0   r0   r1   prune_heads  s   

z!MegatronBertAttention.prune_headsNFc              	   C   sF   |  |}| |||||||}	| |	d |}
|
f|	dd   }|S )Nr   r   )r   r,   r   )r,   rm   rn   ro   rp   rq   rr   rs   
ln_outputsself_outputsattention_outputr   r0   r0   r1   r@   -  s   

	
zMegatronBertAttention.forwardr   )rA   rB   rC   r   r   r@   rF   r0   r0   r.   r1   r     s    r   c                       r   )MegatronBertIntermediatec                    sD   t    t|j|j| _t|jt	rt
|j | _d S |j| _d S r   )r   r   r   rS   r   intermediate_sizer   
isinstance
hidden_actstrr   intermediate_act_fnr+   r.   r0   r1   r   J  s
   
z!MegatronBertIntermediate.__init__c                 C   s   |  |}| |}|S r   )r   r   )r,   rm   r0   r0   r1   r@   R  s   

z MegatronBertIntermediate.forwardr   r0   r0   r.   r1   r   H  s    r   c                       s8   e Zd Z fddZdejdejdejfddZ  ZS )MegatronBertOutputc                    s.   t    t|j|j| _t|j| _	d S r   )
r   r   r   rS   r   r   r   r#   r$   r%   r+   r.   r0   r1   r   [  r   zMegatronBertOutput.__init__rm   input_tensorr2   c                 C   r   r   r   )r,   rm   r   r0   r0   r1   r@   `  s   

zMegatronBertOutput.forward)rA   rB   rC   r   r'   rE   r@   rF   r0   r0   r.   r1   r   Y  s    r   c                       s:   e Zd Z fddZ						d	ddZdd Z  ZS )
MegatronBertLayerc                    s   t    |j| _d| _t|| _|j| _|j| _| jr+| js&t|  dt|| _	t
j|j|jd| _t|| _t|| _d S )Nr   z> should be used as a decoder model if cross attention is addedr   )r   r   chunk_size_feed_forwardseq_len_dimr   	attentionrY   add_cross_attention	TypeErrorcrossattentionr   r   r   r   r   r   intermediater   r   r+   r.   r0   r1   r   j  s   



zMegatronBertLayer.__init__NFc              	   C   s  |d ur
|d d nd }| j |||||d}	|	d }
| jr(|	dd }|	d }n|	dd  }d }| jro|d urot| dsDtd|  d|d urN|d	d  nd }| |
||||||}|d }
||dd  }|d }|| }t| j| j| j|
}|f| }| jr||f }|S )
NrL   rs   rr   r   r   r   r   z'If `encoder_hidden_states` are passed, z` has to be instantiated with cross-attention layers by setting `config.add_cross_attention=True`rb   )	r   rY   rN   AttributeErrorr   r   feed_forward_chunkr   r   )r,   rm   rn   ro   rp   rq   rr   rs   self_attn_past_key_valueself_attention_outputsr   r   present_key_valuecross_attn_present_key_valuecross_attn_past_key_valuecross_attention_outputslayer_outputr0   r0   r1   r@   {  sp   


	

zMegatronBertLayer.forwardc                 C   s$   |  |}| |}| ||}|S r   )r   r   r   )r,   r   	ln_outputintermediate_outputr   r0   r0   r1   r     s   

z$MegatronBertLayer.feed_forward_chunkr   )rA   rB   rC   r   r@   r   rF   r0   r0   r.   r1   r   h  s    
Er   c                       s8   e Zd Z fddZ									dddZ  ZS )	MegatronBertEncoderc                    sN   t     | _t fddt jD | _tj j	 j
d| _d| _d S )Nc                    s   g | ]}t  qS r0   )r   ).0_r-   r0   r1   
<listcomp>  s    z0MegatronBertEncoder.__init__.<locals>.<listcomp>r   F)r   r   r-   r   
ModuleListrangenum_hidden_layerslayerr   r   r   r   gradient_checkpointingr+   r.   r   r1   r     s   


zMegatronBertEncoder.__init__NFTc              	      sl  |	rdnd } r
dnd } r| j jrdnd }|rdnd }t| jD ]o\}}|	r,||f }|d ur4|| nd }|d ur>|| nd | jre| jre|rOtd d} fdd}tj	j

|||||||}n
|||||| }|d }|r|||d f7 } r||d f }| j jr||d	 f }q!| |}|	r||f }|
std
d |||||fD S t|||||dS )Nr0   zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fc                    s    fdd}|S )Nc                     s    g | R  S r   r0   )inputs)modulers   rr   r0   r1   custom_forward  s   zRMegatronBertEncoder.forward.<locals>.create_custom_forward.<locals>.custom_forwardr0   )r   r   r   )r   r1   create_custom_forward  s   z:MegatronBertEncoder.forward.<locals>.create_custom_forwardr   r   r   rL   c                 s   s    | ]	}|d ur|V  qd S r   r0   )r   vr0   r0   r1   	<genexpr>'  s    z.MegatronBertEncoder.forward.<locals>.<genexpr>)last_hidden_statepast_key_valuesrm   
attentionscross_attentions)r-   r   	enumerater   r   trainingloggerwarningr'   utils
checkpointr   tupler   )r,   rm   rn   ro   rp   rq   r   	use_cachers   output_hidden_statesreturn_dictall_hidden_statesall_self_attentionsall_cross_attentionsnext_decoder_cacheilayer_modulelayer_head_maskr   layer_outputsr0   r   r1   r@     s   
	


zMegatronBertEncoder.forward)	NNNNNNFFTr   r0   r0   r.   r1   r     s    r   c                       r   )MegatronBertPoolerc                    s*   t    t|j|j| _t | _d S r   )r   r   r   rS   r   r   Tanh
activationr+   r.   r0   r1   r   :  s   
zMegatronBertPooler.__init__c                 C   s(   |d d df }|  |}| |}|S )Nr   )r   r   )r,   rm   first_token_tensorpooled_outputr0   r0   r1   r@   ?  s   

zMegatronBertPooler.forwardr   r0   r0   r.   r1   r   8  r   r   c                       sT   e Zd ZdZeZdZdZdgZ fddZ	dd Z
dd
dZe fddZ  ZS )MegatronBertPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    bertTr   c                    s*   t  j|jfi | t t| | d S r   )r   r   name_or_pathr	   )r,   r-   kwargsr.   r0   r1   r   S  s   z$MegatronBertPreTrainedModel.__init__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 weightsg        )meanstdg      ?N)r   r   rS   r   weightdatanormal_r-   initializer_ranger   biaszero_fill_)r,   r   r0   r0   r1   _init_weightsW  s   z)MegatronBertPreTrainedModel._init_weightsFc                 C   s   t |tr
||_d S d S r   )r   r   r   )r,   r   rV   r0   r0   r1   _set_gradient_checkpointingd  s   

z7MegatronBertPreTrainedModel._set_gradient_checkpointingc                    sn   | dd}| dd}t||fi |}|du r%tdi |}| |}ntt| jdd|i|}||_|S )ah  Instantiate the model.

        Args:
            kwargs: Input args.
                    model_dir: The model dir used to load the checkpoint and the label information.
                    num_labels: An optional arg to tell the model how many classes to initialize.
                                    Method will call utils.parse_label_mapping if num_labels not supplied.
                                    If num_labels is not found, the model will use the default setting (2 classes).

        Returns:
            The loaded model, which is initialized by transformers.PreTrainedModel.from_pretrained
        	model_dirNcfgpretrained_model_name_or_pathr0   )popr   r   r   r	   from_pretrainedr   )clsr   r   r   
model_argsr-   modelr.   r0   r1   _instantiateh  s   
z(MegatronBertPreTrainedModel._instantiate)F)rA   rB   rC   rD   r   config_classbase_model_prefixsupports_gradient_checkpointing_keys_to_ignore_on_load_missingr   r   r   classmethodr   rF   r0   r0   r.   r1   r   H  s    
r   )	group_keymodule_namec                       sd   e Zd ZdZd fdd	Zdd Zdd Zd	d
 Z													ddefddZ	  Z
S )MegatronBertModela  The bare MegatronBert Model transformer outputting raw hidden-states without any specific head on top.",

    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

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

    Parameters:
        config ([`MegatronBertConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.

    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.

    To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
    to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
    `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
    Tc                    sD   t  | || _t|| _t|| _|rt|nd | _| 	  d S r   )
r   r   r-   r   r?   r   encoderr   pooler	post_init)r,   r-   add_pooling_layerr.   r0   r1   r     s   

zMegatronBertModel.__init__c                 C   s   | j jS r   r?   r   )r,   r0   r0   r1   get_input_embeddings  s   z&MegatronBertModel.get_input_embeddingsc                 C   s   || j _d S r   r  )r,   rV   r0   r0   r1   set_input_embeddings  s   z&MegatronBertModel.set_input_embeddingsc                 C   s*   |  D ]\}}| jj| j| qdS )z
        Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
        class PreTrainedModel
        N)itemsr  r   r   r   )r,   heads_to_pruner   r   r0   r0   r1   _prune_heads  s   zMegatronBertModel._prune_headsNr2   c                 K   s  |dur|n| j j}|dur|n| j j}|dur|n| j j}| j jr-|
dur(|
n| j j}
nd}
|dur;|dur;td|durD| }n|durQ| dd }ntd|\}}|dur`|jn|j}|	durp|	d d j	d nd}|du rt
j||| f|d}|du rt
j|t
j|d	}| |||}| j jr|dur| \}}}||f}|du rt
j||d}| |}nd}| || j j}| j|||||d
}| j||||||	|
|||d
}|d }| jdur| |nd}|s||f|dd  S t|||j|j|j|jdS )a4  
        Args:
            input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
                Indices of input sequence tokens in the vocabulary.

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

                [What are input IDs?](../glossary#input-ids)
            attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
                Mask to avoid performing attention on padding token indices. Mask
                values selected in `[0, 1]`:

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

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

                [What are position IDs?](../glossary#position-ids)
            head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(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 (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`,
                *optional*):
                Optionally, instead of passing `input_ids` you can choose to
                directly pass an embedded representation. This is useful if you want
                more control over how to convert `input_ids` indices into associated
                vectors than the model's internal embedding lookup matrix.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention
                layers. See `attentions` under returned tensors for more detail.
            output_hidden_states (`bool`, *optional*):
                Whether or not to return the hidden states of all layers. See
                `hidden_states` under returned tensors for more detail.
            return_dict (`bool`, *optional*):
                Whether or not to return a [`~file_utils.ModelOutput`] instead of a
                plain tuple.
            encoder_hidden_states  (`torch.FloatTensor` of shape `(batch_size,
                sequence_length, hidden_size)`, *optional*):
                Sequence of hidden-states at the output of the last layer of the
                encoder. Used in the cross-attention if the model is configured as a
                decoder.
            encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size,
                sequence_length)`, *optional*):
                Mask to avoid performing attention on the padding token indices of
                the encoder input. This mask is used in the cross-attention if the
                model is configured as a decoder. Mask values selected in `[0, 1]`:

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

                If `past_key_values` are used, the user can optionally input only
                the last `decoder_input_ids` (those that don't have their past key
                value states given to this model) of shape `(batch_size, 1)` instead
                of all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
            use_cache (`bool`, *optional*):
                If set to `True`, `past_key_values` key value states are returned
                and can be used to speed up decoding (see `past_key_values`).
            Others (**kwargs)
                some additional parameters might passed in from upstream pipeline,
                which not influence the results.
        NFzDYou cannot specify both input_ids and inputs_embeds at the same timer   z5You have to specify either input_ids or inputs_embedsr   rL   )r5   r3   )r9   r   r:   r;   r<   )	rn   ro   rp   rq   r   r   rs   r   r   r   )r   pooler_outputr   rm   r   r   )r-   rs   r   use_return_dictrY   r   rO   r6   r5   shaper'   onesr7   r8   get_extended_attention_maskinvert_attention_maskget_head_maskr   r?   r  r	  r   r   rm   r   r   )r,   r9   rn   r:   r   ro   r;   rp   rq   r   r   rs   r   r   r   r=   
batch_sizer>   r5   r<   extended_attention_maskencoder_batch_sizeencoder_sequence_lengthr   encoder_hidden_shapeencoder_extended_attention_maskembedding_outputencoder_outputssequence_outputr   r0   r0   r1   r@     s   d


zMegatronBertModel.forward)T)NNNNNNNNNNNNN)rA   rB   rC   rD   r   r  r  r  r   r@   rF   r0   r0   r.   r1   r    s,    	r  ).rD   rh   r'   torch.utils.checkpointr   transformers.activationsr   transformers.modeling_utilsr   r   r   r   modelscope.metainfor   modelscope.modelsr	   r
   modelscope.models.builderr   modelscope.outputsr   modelscope.utils.constantr   modelscope.utils.loggerr   modelscope.utils.nlp.utilsr   configurationr   r   _CONFIG_FOR_DOCModuler   rG   r   r   r   r   r   r   r   r   register_modulebackbonemegatron_bertr  r0   r0   r0   r1   <module>   s@   E 7_q<