o
    ߥi                     @   s  d Z ddlZddlmZ ddlmZmZ ddlZddlm	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%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Z0eG d%d& d&eZ1ej2ej3ej4d'G d(d) d)e0Z5dS )*zRPyTorch StructBERT model. mainly copied from :module:`~transformers.modeling_bert`    N)	dataclass)OptionalUnion)version)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   )SbertConfigc                       s6   e Zd ZdZ fddZ						d	ddZ  ZS )
SbertEmbeddingszGConstruct 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| _t|dd| _| dt|jd ttjtdkri| jdtj| j tj| jjd	d
d d S d S )N)padding_idxepsposition_embedding_typeabsoluteposition_ids)r   z1.6.0token_type_idsdtypedeviceF)
persistent)super__init__nn	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getattrr   register_buffertorcharangeexpandr   parse__version__zerosr   sizelongr    selfconfig	__class__ ]/home/ubuntu/.local/lib/python3.10/site-packages/modelscope/models/nlp/structbert/backbone.pyr#   0   sF   

zSbertEmbeddings.__init__Nr   Fc                 C   s  |d ur	|  }n|  d d }|d }|d u r&| jd d ||| f }|d u rPt| drE| jd d d |f }	|	|d |}
|
}ntj|tj| jjd}|d u rY| 	|}| 
|}|| }| jdkrp| |}||7 }| |}| |}|s~|S ||fS )Nr   r   r   r   r   r   )r;   r   hasattrr   r7   r5   r:   r<   r    r)   r-   r   r+   r.   r2   )r>   	input_idsr   r   inputs_embedspast_key_values_lengthreturn_inputs_embedsinput_shape
seq_lengthbuffered_token_type_ids buffered_token_type_ids_expandedr-   
embeddingsr+   rB   rB   rC   forwardQ   sD   








zSbertEmbeddings.forward)NNNNr   F)__name__
__module____qualname____doc__r#   rN   __classcell__rB   rB   r@   rC   r   -   s    "r   c                       :   e Zd Z fddZdd Z						d	ddZ  ZS )
SbertSelfAttentionc                    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| _t|dd| _| jdksf| jd	krw|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_headsrD   
ValueErrorintattention_head_sizeall_head_sizer$   Linearquerykeyvaluer0   attention_probs_dropout_probr2   r3   r   r*   r%   distance_embedding
is_decoderr=   r@   rB   rC   r#      s:   

zSbertSelfAttention.__init__c                 C   s6   |  d d | j| jf }|j| }|ddddS )Nr   r   rZ   r      )r;   r[   r^   viewpermute)r>   xnew_x_shaperB   rB   rC   transpose_for_scores   s
   
z'SbertSelfAttention.transpose_for_scoresNFc                 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dd|}| |}|d ur|| }t||}|dddd }|
 d d | jf }|j| }|r9||fn|f}| jrE||f }|S )Nr   r   rZ   dimr   rX   rY   r   )r   zbhld,lrd->bhlrzbhrd,lrd->bhlrrg   )ra   rl   rb   rc   r5   catrf   matmul	transposer   r;   r6   r<   r    rh   re   r*   tor   einsummathsqrtr^   r$   Softmaxr2   ri   
contiguousr_   )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_scoresrJ   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outputsrB   rB   rC   rN      s   










zSbertSelfAttention.forwardNNNNNF)rO   rP   rQ   r#   rl   rN   rS   rB   rB   r@   rC   rU      s    	rU   c                       $   e Zd Z fddZdd Z  ZS )SbertSelfOutputc                    sB   t    t|j|j| _tj|j|jd| _t|j	| _
d S Nr   )r"   r#   r$   r`   r'   denser.   r/   r0   r1   r2   r=   r@   rB   rC   r#        
zSbertSelfOutput.__init__c                 C   &   |  |}| |}| || }|S Nr   r2   r.   r>   ry   input_tensorrB   rB   rC   rN         

zSbertSelfOutput.forwardrO   rP   rQ   r#   rN   rS   rB   rB   r@   rC   r         r   c                       rT   )
SbertAttentionc                    s*   t    t|| _t|| _t | _d S r   )r"   r#   rU   r>   r   outputsetpruned_headsr=   r@   rB   rC   r#   )  s   


zSbertAttention.__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   rm   )lenr	   r>   r[   r^   r   r
   ra   rb   rc   r   r   r_   union)r>   headsindexrB   rB   rC   prune_heads/  s   

zSbertAttention.prune_headsNFc              	   C   s<   |  |||||||}| |d |}	|	f|dd   }
|
S )Nr   r   )r>   r   )r>   ry   rz   r{   r|   r}   r~   r   self_outputsattention_outputr   rB   rB   rC   rN   B  s   
	
zSbertAttention.forwardr   )rO   rP   rQ   r#   r   rN   rS   rB   rB   r@   rC   r   '  s    r   c                       r   )SbertIntermediatec                    sD   t    t|j|j| _t|jt	rt
|j | _d S |j| _d S r   )r"   r#   r$   r`   r'   intermediate_sizer   
isinstance
hidden_actstrr   intermediate_act_fnr=   r@   rB   rC   r#   ]  s
   
zSbertIntermediate.__init__c                 C   s   |  |}| |}|S r   )r   r   )r>   ry   rB   rB   rC   rN   e  s   

zSbertIntermediate.forwardr   rB   rB   r@   rC   r   [  s    r   c                       r   )SbertOutputc                    sB   t    t|j|j| _tj|j|jd| _t	|j
| _d S r   )r"   r#   r$   r`   r   r'   r   r.   r/   r0   r1   r2   r=   r@   rB   rC   r#   m  r   zSbertOutput.__init__c                 C   r   r   r   r   rB   rB   rC   rN   t  r   zSbertOutput.forwardr   rB   rB   r@   rC   r   k  r   r   c                       s:   e Zd Z fddZ						d	ddZdd Z  ZS )

SbertLayerc                    sn   t    |j| _d| _t|| _|j| _|j| _| jr+| js&t|  dt|| _	t
|| _t|| _d S )Nr   z> should be used as a decoder model if cross attention is added)r"   r#   chunk_size_feed_forwardseq_len_dimr   	attentionrf   add_cross_attentionr\   crossattentionr   intermediater   r   r=   r@   rB   rC   r#   }  s   



zSbertLayer.__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 )
NrZ   r   r~   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`ro   )	r   rf   rD   r\   r   r   feed_forward_chunkr   r   )r>   ry   rz   r{   r|   r}   r~   r   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_outputrB   rB   rC   rN     sp   


	

zSbertLayer.forwardc                 C   s   |  |}| ||}|S r   )r   r   )r>   r   intermediate_outputr   rB   rB   rC   r     s   
zSbertLayer.feed_forward_chunkr   )rO   rP   rQ   r#   rN   r   rS   rB   rB   r@   rC   r   {  s    
Er   c                       s8   e Zd Z fddZ									dddZ  ZS )	SbertEncoderc                    s:   t     | _t fddt jD | _d| _d S )Nc                    s   g | ]}t  qS rB   )r   ).0_r?   rB   rC   
<listcomp>  s    z)SbertEncoder.__init__.<locals>.<listcomp>F)	r"   r#   r?   r$   
ModuleListrangenum_hidden_layerslayergradient_checkpointingr=   r@   r   rC   r#     s   

zSbertEncoder.__init__NFTc              	      sb  |	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 )NrB   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   rB   )inputs)moduler   r~   rB   rC   custom_forward  s   zKSbertEncoder.forward.<locals>.create_custom_forward.<locals>.custom_forwardrB   )r   r   r   )r   rC   create_custom_forward  s   z3SbertEncoder.forward.<locals>.create_custom_forwardr   r   r   rZ   c                 s   s    | ]	}|d ur|V  qd S r   rB   )r   vrB   rB   rC   	<genexpr>-  s    z'SbertEncoder.forward.<locals>.<genexpr>)last_hidden_statepast_key_valuesry   
attentionscross_attentions)r?   r   	enumerater   r   trainingloggerwarningr5   utils
checkpointtupler   )r>   ry   rz   r{   r|   r}   r   	use_cacher   output_hidden_statesreturn_dictall_hidden_statesall_self_attentionsall_cross_attentionsnext_decoder_cacheilayer_modulelayer_head_maskr   layer_outputsrB   r   rC   rN     s   
	


zSbertEncoder.forward)	NNNNNNFFTr   rB   rB   r@   rC   r     s    
r   c                       r   )SbertPoolerc                    s*   t    t|j|j| _t | _d S r   )r"   r#   r$   r`   r'   r   Tanh
activationr=   r@   rB   rC   r#   ?  s   
zSbertPooler.__init__c                 C   s(   |d d df }|  |}| |}|S )Nr   )r   r   )r>   ry   first_token_tensorpooled_outputrB   rB   rC   rN   D  s   

zSbertPooler.forwardr   rB   rB   r@   rC   r   =  s    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 )SbertPreTrainedModelz
    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@   rB   rC   r#   X  s   zSbertPreTrainedModel.__init__c                 C   s   t |tjr |jjjd| jjd |jdur|jj	  dS dS t |tj
rC|jjjd| jjd |jdurA|jj|j 	  dS dS t |tjrX|jj	  |jjd dS dS )zInitialize the weightsg        )meanstdNg      ?)r   r$   r`   weightdatanormal_r?   initializer_rangebiaszero_r%   r   r.   fill_)r>   r   rB   rB   rC   _init_weights\  s$   

z"SbertPreTrainedModel._init_weightsFc                 C   s   t |tr
||_d S d S r   )r   r   r   )r>   r   rc   rB   rB   rC   _set_gradient_checkpointingn  s   

z0SbertPreTrainedModel._set_gradient_checkpointingc                    sj   | dd}| dd}t||fi |}|du r&tdi |}| |}|S tt| jdd|i|}|S )al  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 is not input.
                    label2id: An optional label2id mapping, which will cover the label2id in configuration (if exists).

        Returns:
            The loaded model, which is initialized by transformers.PreTrainedModel.from_pretrained
        	model_dirNcfgpretrained_model_name_or_pathrB   )popr   r   r"   r   from_pretrained)clsr   r   r   
model_argsr?   modelr@   rB   rC   _instantiater  s   z!SbertPreTrainedModel._instantiate)F)rO   rP   rQ   rR   r   config_classbase_model_prefixsupports_gradient_checkpointing_keys_to_ignore_on_load_missingr#   r   r   classmethodr  rS   rB   rB   r@   rC   r   M  s    
r   c                   @   sB   e Zd ZU dZejed< dZee	e
ejf  ed< dZeed< dS ))AttentionBackboneModelOutputWithEmbeddingNembedding_outputlogitsr   )rO   rP   rQ   r  r5   FloatTensor__annotations__r  r   r   r   r   dictrB   rB   rB   rC   r
    s   
 r
  )module_namec                       sd   e Zd ZdZddef fddZdd Zdd	 Zd
d Z													dddZ	  Z
S )
SbertModela+  The StructBERT Model transformer outputting raw hidden-states without any specific head on top.

    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:`~modelscope.models.nlp.structbert.SbertConfig`): 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.

    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 :obj:`is_decoder` argument of the configuration
    set to :obj:`True`. To be used in a Seq2Seq model, the model needs to initialized with both :obj:`is_decoder`
    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.
    Tr?   c                    sD   t  | || _t|| _t|| _|rt|nd | _| 	  d S r   )
r"   r#   r?   r   rM   r   encoderr   poolerinit_weights)r>   r?   add_pooling_layerr   r@   rB   rC   r#     s   

zSbertModel.__init__c                 C   s   | j jS r   rM   r)   )r>   rB   rB   rC   get_input_embeddings  s   zSbertModel.get_input_embeddingsc                 C   s   || j _d S r   r  )r>   rc   rB   rB   rC   set_input_embeddings  s   zSbertModel.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   rB   rB   rC   _prune_heads  s   zSbertModel._prune_headsNc           !      K   sT  |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d	r| jjddd|f }|||}|}n	t
j|t
j|d
}| |||}| j jr|dur| \}}}||f}|du rt
j||d}| |}nd}| || j j}| j|||||dd\}}| j||||||	|
|||d
}|d }| jdur	| |nd} |s|| f|dd  |f S t|| |j|j|j|j|dS )u  
        Args:
            input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`):
                Indices of input sequence tokens in the vocabulary.

                Indices can be obtained using :class:`~modelscope.models.nlp.structbert.SbertTokenizer`. See
                :meth:`transformers.PreTrainedTokenizer.encode` and :meth:`transformers.PreTrainedTokenizer.__call__`
                for details.

            attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(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**.

            token_type_ids (:obj:`torch.LongTensor` of shape :obj:`(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.

            position_ids (:obj:`torch.LongTensor` of shape :obj:`(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]``.

            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:`(batch_size, sequence_length, 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.ModelOutput` instead of a plain tuple.
            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`).

        Returns:
            Returns `modelscope.outputs.AttentionBackboneModelOutputWithEmbedding`

        Examples:
            >>> from modelscope.models import Model
            >>> from modelscope.preprocessors import Preprocessor
            >>> model = Model.from_pretrained('damo/nlp_structbert_backbone_base_std', task='backbone')
            >>> preprocessor = Preprocessor.from_pretrained('damo/nlp_structbert_backbone_base_std')
            >>> print(model(**preprocessor('这是个测试')))
        NFzDYou cannot specify both input_ids and inputs_embeds at the same timer   z5You have to specify either input_ids or inputs_embedsr   rZ   )r    r   r   T)rE   r   r   rF   rG   rH   )	rz   r{   r|   r}   r   r   r   r   r   r   )r   pooler_outputr   ry   r   r   r  )r?   r   r   use_return_dictrf   r   r\   r;   r    shaper5   onesrD   rM   r   r7   r:   r<   get_extended_attention_maskinvert_attention_maskget_head_maskr   r  r  r
  r   ry   r   r   )!r>   rE   rz   r   r   r{   rF   r|   r}   r   r   r   r   r   r   rI   
batch_sizerJ   r    rG   rK   rL   extended_attention_maskencoder_batch_sizeencoder_sequence_lengthr   encoder_hidden_shapeencoder_extended_attention_maskr  original_embedsencoder_outputssequence_outputr   rB   rB   rC   rN     s   ^



zSbertModel.forward)T)NNNNNNNNNNNNN)rO   rP   rQ   rR   r   r#   r  r  r  rN   rS   rB   rB   r@   rC   r    s(    	r  )6rR   ru   dataclassesr   typingr   r   r5   torch.nnr$   torch.utils.checkpoint	packagingr   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   Moduler   rU   r   r   r   r   r   r   r   r   r
  register_modulebackbone
structbertr  rB   rB   rB   rC   <module>   sD   W 4]eA