o
    *j                     @   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 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mZ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)Models)Model
TorchModel)MODELS)AttentionBackboneModelOutput)Tasks)
get_logger)parse_labels_in_order)apply_chunking_to_forward find_pruneable_heads_and_indicesprune_linear_layer   )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)Zpadding_idxposition_ids)r   position_embedding_typeabsolute)super__init__r   	EmbeddingZ
vocab_sizehidden_sizeZpad_token_idword_embeddingsmax_position_embeddingsposition_embeddingsZtype_vocab_sizetoken_type_embeddingsDropouthidden_dropout_probdropoutZregister_buffertorcharangeexpandgetattrr   selfconfig	__class__ m/var/www/html/Deteccion_Ine/venv/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longr0   r   r   r   r   r!   )r'   	input_idstoken_type_idsr   inputs_embedspast_key_values_lengthinput_shape
seq_lengthr   
embeddingsr   r+   r+   r,   forwardH   s.   






zMegatronBertEmbeddings.forward)NNNNr   )	__name__
__module____qualname____doc__r   r"   Tensorr;   __classcell__r+   r+   r)   r,   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   Z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   Zattention_probs_dropout_probr!   r%   r   r   r   distance_embedding
is_decoder)r'   r(   r   r)   r+   r,   r   r   s8   

z"MegatronBertSelfAttention.__init__xr-   c                 C   s6   |  d d | j| jf }||}|ddddS )Nr   r   rF   r      )r1   rG   rK   viewpermute)r'   rS   Znew_x_shaper+   r+   r,   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   rF   dimr   rD   rE   r.   )r/   zbhld,lrd->bhlrzbhrd,lrd->bhlrrT   )rN   rW   rO   rP   r"   catrR   matmulZ	transposer   r1   r#   r3   r0   rU   rQ   r   tor/   ZeinsummathsqrtrK   r   Z
functionalZsoftmaxr!   rV   
contiguousrL   )r'   hidden_statesattention_mask	head_maskencoder_hidden_statesencoder_attention_maskpast_key_valueoutput_attentionsZmixed_query_layerZis_cross_attentionZ	key_layerZvalue_layerZquery_layerZattention_scoresr9   Zposition_ids_lZposition_ids_rZdistanceZpositional_embeddingZrelative_position_scoresZrelative_position_scores_queryZrelative_position_scores_keyZattention_probsZcontext_layerZnew_context_layer_shapeoutputsr+   r+   r,   r;      s   










z!MegatronBertSelfAttention.forwardNNNNNNF)	r<   r=   r>   r   r"   r@   rW   r;   rA   r+   r+   r)   r,   rB   p   s    	rB   c                       $   e Zd Z fddZdd Z  ZS )MegatronBertSelfOutputc                    s.   t    t|j|j| _t|j| _d S ri   )	r   r   r   rM   r   denser   r    r!   r&   r)   r+   r,   r        
zMegatronBertSelfOutput.__init__c                 C      |  |}| |}|| S ri   rm   r!   )r'   ra   Zresidualr+   r+   r,   r;   
  s   

zMegatronBertSelfOutput.forwardr<   r=   r>   r   r;   rA   r+   r+   r)   r,   rl         rl   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lnrB   r'   rl   outputsetpruned_headsr&   r)   r+   r,   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   rX   )lenr   r'   rG   rK   r{   r   rN   rO   rP   ry   rm   rL   union)r'   headsindexr+   r+   r,   prune_heads  s   

z!MegatronBertAttention.prune_headsNFc              	   C   sF   |  |}| |||||||}	| |	d |}
|
f|	dd   }|S )Nr   r   )rx   r'   ry   )r'   ra   rb   rc   rd   re   rf   rg   Z
ln_outputsZself_outputsattention_outputrh   r+   r+   r,   r;   -  s   

	
zMegatronBertAttention.forwardrj   )r<   r=   r>   r   r   r;   rA   r+   r+   r)   r,   rs     s    rs   c                       rk   )MegatronBertIntermediatec                    sD   t    t|j|j| _t|jt	rt
|j | _d S |j| _d S ri   )r   r   r   rM   r   intermediate_sizerm   
isinstanceZ
hidden_actstrr   intermediate_act_fnr&   r)   r+   r,   r   J  s
   
z!MegatronBertIntermediate.__init__c                 C   s   |  |}| |}|S ri   )rm   r   )r'   ra   r+   r+   r,   r;   R  s   

z MegatronBertIntermediate.forwardrq   r+   r+   r)   r,   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 ri   )
r   r   r   rM   r   r   rm   r   r    r!   r&   r)   r+   r,   r   [  rn   zMegatronBertOutput.__init__ra   input_tensorr-   c                 C   ro   ri   rp   )r'   ra   r   r+   r+   r,   r;   `  s   

zMegatronBertOutput.forward)r<   r=   r>   r   r"   r@   r;   rA   r+   r+   r)   r,   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 addedrt   )r   r   chunk_size_feed_forwardseq_len_dimrs   	attentionrR   add_cross_attention	TypeErrorcrossattentionr   rv   r   rw   rx   r   intermediater   ry   r&   r)   r+   r,   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 )
NrF   rg   rf   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`rZ   )	r   rR   rH   AttributeErrorr   r   feed_forward_chunkr   r   )r'   ra   rb   rc   rd   re   rf   rg   Zself_attn_past_key_valueZself_attention_outputsr   rh   Zpresent_key_valueZcross_attn_present_key_valueZcross_attn_past_key_valueZcross_attention_outputslayer_outputr+   r+   r,   r;   {  sp   


	

zMegatronBertLayer.forwardc                 C   s$   |  |}| |}| ||}|S ri   )rx   r   ry   )r'   r   Z	ln_outputZintermediate_outputr   r+   r+   r,   r     s   

z$MegatronBertLayer.feed_forward_chunkrj   )r<   r=   r>   r   r;   r   rA   r+   r+   r)   r,   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 r+   )r   ).0_r(   r+   r,   
<listcomp>  s    z0MegatronBertEncoder.__init__.<locals>.<listcomp>rt   F)r   r   r(   r   Z
ModuleListrangenum_hidden_layerslayerrv   r   rw   rx   gradient_checkpointingr&   r)   r   r,   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 )Nr+   zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fc                    s    fdd}|S )Nc                     s    g | R  S ri   r+   )Zinputs)modulerg   rf   r+   r,   custom_forward  s   zRMegatronBertEncoder.forward.<locals>.create_custom_forward.<locals>.custom_forwardr+   )r   r   r   )r   r,   create_custom_forward  s   z:MegatronBertEncoder.forward.<locals>.create_custom_forwardr   r   r   rF   c                 s   s    | ]	}|d ur|V  qd S ri   r+   )r   vr+   r+   r,   	<genexpr>'  s    z.MegatronBertEncoder.forward.<locals>.<genexpr>)last_hidden_statepast_key_valuesra   
attentionscross_attentions)r(   r   	enumerater   r   Ztrainingloggerwarningr"   utils
checkpointrx   tupler	   )r'   ra   rb   rc   rd   re   r   	use_cacherg   output_hidden_statesreturn_dictZall_hidden_statesZall_self_attentionsZall_cross_attentionsZnext_decoder_cacheiZlayer_moduleZlayer_head_maskr   Zlayer_outputsr+   r   r,   r;     s   
	


zMegatronBertEncoder.forward)	NNNNNNFFTrq   r+   r+   r)   r,   r     s    r   c                       rk   )MegatronBertPoolerc                    s*   t    t|j|j| _t | _d S ri   )r   r   r   rM   r   rm   ZTanh
activationr&   r)   r+   r,   r   :  s   
zMegatronBertPooler.__init__c                 C   s(   |d d df }|  |}| |}|S )Nr   )rm   r   )r'   ra   Zfirst_token_tensorpooled_outputr+   r+   r,   r;   ?  s   

zMegatronBertPooler.forwardrq   r+   r+   r)   r,   r   8  rr   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.
    ZbertTr   c                    s*   t  j|jfi | t t| | d S ri   )r   r   Zname_or_pathr   )r'   r(   kwargsr)   r+   r,   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        )meanZstdg      ?N)r   r   rM   r   weightdataZnormal_r(   Zinitializer_rangerv   ZbiasZzero_Zfill_)r'   r   r+   r+   r,   _init_weightsW  s   z)MegatronBertPreTrainedModel._init_weightsFc                 C   s   t |tr
||_d S d S ri   )r   r   r   )r'   r   rP   r+   r+   r,   _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cfgZpretrained_model_name_or_pathr+   )popr   r   r   r   Zfrom_pretrainedr   )clsr   r   r   Z
model_argsr(   modelr)   r+   r,   _instantiateh  s   
z(MegatronBertPreTrainedModel._instantiate)F)r<   r=   r>   r?   r   Zconfig_classZbase_model_prefixZsupports_gradient_checkpointingZ_keys_to_ignore_on_load_missingr   r   r   classmethodr   rA   r+   r+   r)   r,   r   H  s    
r   )Z	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 ri   )
r   r   r(   r   r:   r   encoderr   poolerZ	post_init)r'   r(   Zadd_pooling_layerr)   r+   r,   r     s   

zMegatronBertModel.__init__c                 C   s   | j jS ri   r:   r   )r'   r+   r+   r,   get_input_embeddings  s   z&MegatronBertModel.get_input_embeddingsc                 C   s   || j _d S ri   r   )r'   rP   r+   r+   r,   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'   Zheads_to_pruner   r~   r+   r+   r,   _prune_heads  s   zMegatronBertModel._prune_headsNr-   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   rF   )r0   r.   )r4   r   r5   r6   r7   )	rb   rc   rd   re   r   r   rg   r   r   r   )r   Zpooler_outputr   ra   r   r   )r(   rg   r   Zuse_return_dictrR   r   rI   r1   r0   shaper"   Zonesr2   r3   Zget_extended_attention_maskZinvert_attention_maskZget_head_maskr   r:   r   r   r	   r   ra   r   r   )r'   r4   rb   r5   r   rc   r6   rd   re   r   r   rg   r   r   r   r8   Z
batch_sizer9   r0   r7   Zextended_attention_maskZencoder_batch_sizeZencoder_sequence_lengthr   Zencoder_hidden_shapeZencoder_extended_attention_maskZembedding_outputZencoder_outputsZsequence_outputr   r+   r+   r,   r;     s   d


zMegatronBertModel.forward)T)NNNNNNNNNNNNN)r<   r=   r>   r?   r   r   r   r   r	   r;   rA   r+   r+   r)   r,   r     s,    	r   )/r?   r^   r"   Ztorch.utils.checkpointr   Ztransformers.activationsr   Ztransformers.modeling_utilsr   Zmodelscope.metainfor   Zmodelscope.modelsr   r   Zmodelscope.models.builderr   Zmodelscope.outputsr	   Zmodelscope.utils.constantr
   Zmodelscope.utils.loggerr   Zmodelscope.utils.nlp.utilsr   Zmodelscope.utils.torch_utilsr   r   r   configurationr   r   Z_CONFIG_FOR_DOCModuler   rB   rl   rs   r   r   r   r   r   r   Zregister_moduleZbackboneZmegatron_bertr   r+   r+   r+   r,   <module>   sB   E 7_q<