o
    ߥi                     @   s  d Z ddlZddlm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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 e Zeej edkZ!dZ"dZ#d3ddZ$e"e#fddZ%e"e#fddZ&d4d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(Z0G d,d- d-ej(Z1G d.d/ d/eeZ2ej3ej4ej5d0G d1d2 d2e2Z6dS )5zPyTorch PoNet model.     N)LooseVersion)version)nn)ACT2FN)PreTrainedModelapply_chunking_to_forward find_pruneable_heads_and_indicesprune_linear_layer)Models)Model
TorchModel)MODELS)AttentionBackboneModelOutput)Tasks)
get_logger   )PoNetConfigz1.12.0e   f   c                 C   sB  t rt| j||d d d d d f | | ddd}nd|d d d d d f | }|  d }g | jd d | d | jd R }|dj	| }tj
| d | jdd d d d d f j	| }| dj	| }	|	||kt|	| jdd\}}
|dj	g |jd d	 |dR  }t|||j| jd
S )NamaxF)reduceinclude_selfr   devicedim   dtype)is_pytorch_12plustorch
zeros_likescatter_reduce	expand_asminshapemax	unsqueezeexpandaranger   masked_scatter	full_likeitemsizegathertor    )srcindexr   outdummy_scatter_index	min_valuedummpy_scatter_shapedummy_scatter_index_expandindex_reconstruct_expand
src_expand_dummy r=   X/home/ubuntu/.local/lib/python3.10/site-packages/modelscope/models/nlp/ponet/backbone.pysegment_max/   sF   




*r?   c                 C   sp   | |kj tjd| |kj tjd }|tjt|d d ddf |d d d df gdd }|jddd S )Nr   r   r   r   r   )r1   r"   longcatr#   cumsum	input_idscls_ideos_idmaskr=   r=   r>   get_segment_indexK   s   2rH   c                 C   s   | |k| |kB }|S Nr=   rC   r=   r=   r>   get_token_type_maskS   s   rJ      c                 C   s4   t j|d|d d}|| dddddd}|S )Nr   r   )stridepaddingr   )r   	MaxPool1dpermute)hidden_stateskernel_sizemr4   r=   r=   r>   get_win_maxX   s   rS   c                       s4   e Zd ZdZ fddZ					dddZ  ZS )	PoNetEmbeddingszGConstruct 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   r   z1.6.0token_type_idsr    r   F)
persistent)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getattrrX   register_bufferr"   r+   r*   r   parse__version__zerosrZ   r/   r@   r   selfconfig	__class__r=   r>   r_   a   sF   

zPoNetEmbeddings.__init__Nr   c                 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 )Nr   r   r[   r   r\   rY   )r/   rZ   hasattrr[   r*   r"   rr   r@   r   rd   rh   rX   rf   ri   rm   )rt   rD   r[   rZ   inputs_embedspast_key_values_lengthinput_shape
seq_lengthbuffered_token_type_ids buffered_token_type_ids_expandedrh   
embeddingsrf   r=   r=   r>   forward   s@   








zPoNetEmbeddings.forward)NNNNr   )__name__
__module____qualname____doc__r_   r   __classcell__r=   r=   rv   r>   rT   ^   s    "rT   c                       :   e Zd Z fddZdd Z						d	ddZ  ZS )
PoNetSelfAttentionc                    s   t    t|j|j| _t|j|j| _|j| _t|dd| _	t
|j|j | _| j| j | _t|j| j| _t|j| j| _t|j| j| _d S )NclsgsepgT)r^   r_   r   Linearrb   dense_localdense_segmentnum_attention_headsrn   r   intattention_head_sizeall_head_sizedense_qdense_kdense_ors   rv   r=   r>   r_      s   
zPoNetSelfAttention.__init__c                 C   s6   |  d d | j| jf }|j| }|ddddS )Nr   r   r   r   rK   )r/   r   r   viewrO   )rt   xnew_x_shaper=   r=   r>   transpose_for_scores   s
   
z'PoNetSelfAttention.transpose_for_scoresNFc
                 C   s&  |  | |}
|  | |}|}|  | |}|d ur(|dddk }|d urK|
|d |
jddt	|j
|
jd|djdd }n|
jdd}td||t|
jd  }|d urk||d }|jdd}td||}| |}| |}|d ur||dd	 ||dd	 | jrt||jddd	}t||d
}||jddd ||jddd n
t|}t||d
}|  |}|  |}|jdd| | | }|ddddjg |jd d dR  }|d ur||dd |	r||f}|S |f}|S )Nr   r           r   r   r   zbdh,bdlh -> bdlzbdlh,bdl->bdhi)r3   r   r   rK   )r   r   r   r   squeezer)   masked_fill_sumr"   	ones_liker1   r    masked_fillmeaneinsummathsqrtr'   softmaxr   r   r   rS   r?   rO   reshape)rt   rP   segment_indextoken_type_maskattention_mask	head_maskencoder_hidden_statesencoder_attention_maskpast_key_valueoutput_attentionscontext_layer_qcontext_layer_kcontext_layer_vcontext_layer_o_attention_maskqattatt_probvcontext_layer_segmentcontext_layer_localcontext_layeroutputsr=   r=   r>   r      s   






zPoNetSelfAttention.forwardNNNNNF)r   r   r   r_   r   r   r   r=   r=   rv   r>   r      s    r   c                       $   e Zd Z fddZdd Z  ZS )PoNetSelfOutputc                    sB   t    t|j|j| _tj|j|jd| _t|j	| _
d S NrV   )r^   r_   r   r   rb   denseri   rj   rk   rl   rm   rs   rv   r=   r>   r_        
zPoNetSelfOutput.__init__c                 C   &   |  |}| |}| || }|S rI   r   rm   ri   rt   rP   input_tensorr=   r=   r>   r        

zPoNetSelfOutput.forwardr   r   r   r_   r   r   r=   r=   rv   r>   r         r   c                       r   )PoNetIntermediatec                    sD   t    t|j|j| _t|jt	rt
|j | _d S |j| _d S rI   )r^   r_   r   r   rb   intermediate_sizer   
isinstance
hidden_actstrr   intermediate_act_fnrs   rv   r=   r>   r_   '  s
   
zPoNetIntermediate.__init__c                 C   s   |  |}| |}|S rI   )r   r   )rt   rP   r=   r=   r>   r   /  s   

zPoNetIntermediate.forwardr   r=   r=   rv   r>   r   %  s    r   c                       r   )PoNetOutputc                    sB   t    t|j|j| _tj|j|jd| _t	|j
| _d S r   )r^   r_   r   r   r   rb   r   ri   rj   rk   rl   rm   rs   rv   r=   r>   r_   7  r   zPoNetOutput.__init__c                 C   r   rI   r   r   r=   r=   r>   r   >  r   zPoNetOutput.forwardr   r=   r=   rv   r>   r   5  r   r   c                       r   )
PoNetAttentionc                    s*   t    t|| _t|| _t | _d S rI   )r^   r_   r   rt   r   outputsetpruned_headsrs   rv   r=   r>   r_   G  s   


zPoNetAttention.__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   rt   r   r   r   r	   querykeyvaluer   r   r   union)rt   headsr3   r=   r=   r>   prune_headsM  s   

zPoNetAttention.prune_headsNFc
                 C   s@   |  |||||||||		}
| |
d |}|f|
dd   }|S )Nr   r   )rt   r   )rt   rP   r   r   r   r   r   r   r   r   self_outputsattention_outputr   r=   r=   r>   r   `  s    
zPoNetAttention.forwardr   )r   r   r   r_   r   r   r   r=   r=   rv   r>   r   E  s    r   c                       s:   e Zd Z fddZ						d	ddZdd Z  ZS )

PoNetLayerc                    st   t    |j| _d| _t|| _d|_|j| _|j| _| jr.| js)J |  dt|| _t	|| _
t|| _d S )Nr   Fz> should be used as a decoder model if cross attention is added)r^   r_   chunk_size_feed_forwardseq_len_dimr   	attention
is_decoderadd_cross_attentioncrossattentionr   intermediater   r   rs   rv   r=   r>   r_     s   



zPoNetLayer.__init__NFc
              	   C   s  |d ur
|d d nd }
| j ||||||	|
d}|d }| jr*|dd }|d }n|dd  }d }| jrq|d urqt| dsFJ d|  d|d urP|d	d  nd }| |||||||	}|d }||dd  }|d }|| }t| j| j| j|}|f| }| jr||f }|S )
Nr   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`r   )r   r   rx   r   r   feed_forward_chunkr   r   )rt   rP   r   r   r   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_outputr=   r=   r>   r     sv   	

	

zPoNetLayer.forwardc                 C   s   |  |}| ||}|S rI   )r   r   )rt   r   intermediate_outputr   r=   r=   r>   r     s   
zPoNetLayer.feed_forward_chunkr   )r   r   r   r_   r   r   r   r=   r=   rv   r>   r   }  s    
Gr   c                       s8   e Zd Z fddZ									dddZ  ZS )	PoNetEncoderc                    s4   t     | _t fddt jD | _d S )Nc                    s   g | ]}t  qS r=   )r   ).0r;   ru   r=   r>   
<listcomp>  s    z)PoNetEncoder.__init__.<locals>.<listcomp>)r^   r_   ru   r   
ModuleListrangenum_hidden_layerslayerrs   rv   r   r>   r_     s
   

zPoNetEncoder.__init__NFTc                    sr  |rdnd } r
dnd } r| j jrdnd }|	rdnd }t| jD ]w\}}|r,||f }|d ur4|| nd }|d ur>|| nd t| j ddrk| jrk|	rSt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=   gradient_checkpointingFzh`use_cache=True` is incompatible with `config.gradient_checkpointing=True`. Setting `use_cache=False`...c                    s    fdd}|S )Nc                     s    g | R  S rI   r=   )inputs)moduler   r   r=   r>   custom_forward  s   zKPoNetEncoder.forward.<locals>.create_custom_forward.<locals>.custom_forwardr=   )r   r   r   )r   r>   create_custom_forward
  s   z3PoNetEncoder.forward.<locals>.create_custom_forwardr   r   r   r   c                 s   s    | ]	}|d ur|V  qd S rI   r=   )r   r   r=   r=   r>   	<genexpr>7  s    z'PoNetEncoder.forward.<locals>.<genexpr>)last_hidden_statepast_key_valuesrP   
attentionscross_attentions)ru   r   	enumerater   rn   trainingloggerwarningr"   utils
checkpointtupler   )rt   rP   r   r   r   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_outputsr=   r   r>   r     s   


zPoNetEncoder.forward)	NNNNNNFFTr   r=   r=   rv   r>   r     s    r   c                       r   )PoNetPoolerc                    s*   t    t|j|j| _t | _d S rI   )r^   r_   r   r   rb   r   Tanh
activationrs   rv   r=   r>   r_   I  s   
zPoNetPooler.__init__c                 C   s(   |d d df }|  |}| |}|S )Nr   )r   r  )rt   rP   first_token_tensorpooled_outputr=   r=   r>   r   N  s   

zPoNetPooler.forwardr   r=   r=   rv   r>   r  G  s    r  c                       sF   e Zd ZdZeZdZdgZ fddZdd Z	e
 fdd	Z  ZS )
PoNetPreTrainedModelzm
    A base class to handle weights initialization and a simple interface for loading pretrained models.
    ponetrZ   c                    s*   t  j|jfi | t t| | d S rI   )r^   r_   name_or_pathr   )rt   ru   kwargsrv   r=   r>   r_   `  s   zPoNetPreTrainedModel.__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 weightsr   )r   stdNg      ?)r   r   r   weightdatanormal_ru   initializer_rangebiaszero_r`   rU   ri   fill_)rt   r   r=   r=   r>   _init_weightsd  s$   

z"PoNetPreTrainedModel._init_weightsc                    sD   | dd }|d u rtdi |}| |}|S tt| j|d}|S )N	model_dir)pretrained_model_name_or_pathr=   )popr   r^   r   from_pretrained)clsr  r!  ponet_configmodelrv   r=   r>   _instantiatev  s   z!PoNetPreTrainedModel._instantiate)r   r   r   r   r   config_classbase_model_prefix_keys_to_ignore_on_load_missingr_   r   classmethodr(  r   r=   r=   rv   r>   r  W  s    r  )module_namec                       s`   e Zd ZdZd fdd	Zdd Zdd Zd	d
 Z														dddZ  Z	S )
PoNetModela&  The bare PoNet 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.ponet.PoNetConfig`):
            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.
    Tc                    sL   t  j|fi | || _t|| _t|| _|rt|nd | _| 	  d S rI   )
r^   r_   ru   rT   r   r   encoderr  poolerinit_weights)rt   ru   add_pooling_layerr  rv   r=   r>   r_     s   

zPoNetModel.__init__c                 C   s   | j jS rI   r   rd   )rt   r=   r=   r>   get_input_embeddings  s   zPoNetModel.get_input_embeddingsc                 C   s   || j _d S rI   r3  )rt   r   r=   r=   r>   set_input_embeddings  s   zPoNetModel.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   )rt   heads_to_pruner   r   r=   r=   r>   _prune_heads  s   zPoNetModel._prune_headsNc                  C   s6  |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rH| }|\}}n|durY| dd }|\}}ntd|durd|jn|j}|
durt|
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
}|du rt|n|}t|}| j||||||||
||||d}|d }| jdur| |nd}|s||f|dd  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.ponet.PoNetTokenizer`. 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.file_utils.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.AttentionBackboneModelOutput`

        Examples:
            >>> from modelscope.models import Model
            >>> from modelscope.preprocessors import Preprocessor
            >>> model = Model.from_pretrained('damo/nlp_ponet_fill-mask_chinese-base', task='backbone')
            >>> preprocessor = Preprocessor.from_pretrained('damo/nlp_ponet_fill-mask_chinese-base')
            >>> 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   r   r   r\   )rD   rZ   r[   ry   rz   )	r   r   r   r   r   r  r   r  r  r   )r   pooler_outputr   rP   r   r   )ru   r   r  use_return_dictr   r  
ValueErrorr/   r   r'   r"   onesrr   r@   get_extended_attention_maskinvert_attention_maskget_head_maskr   r   rH   rJ   r/  r0  r   r   rP   r   r   ) rt   rD   r   r[   segment_idsrZ   r   ry   r   r   r   r  r   r  r  r{   
batch_sizer|   r   rz   extended_attention_maskencoder_batch_sizeencoder_sequence_lengthr;   encoder_hidden_shapeencoder_extended_attention_maskembedding_outputr   r   encoder_outputssequence_outputr  r=   r=   r>   r     s   `


	
zPoNetModel.forward)T)NNNNNNNNNNNNNN)
r   r   r   r   r_   r4  r5  r8  r   r   r=   r=   rv   r>   r.    s*    
r.  )r   )rK   )7r   r   distutils.versionr   r"   torch.utils.checkpoint	packagingr   r   transformers.activationsr   transformers.modeling_utilsr   r   r   r	   modelscope.metainfor
   modelscope.modelsr   r   modelscope.models.builderr   modelscope.outputsr   modelscope.utils.constantr   modelscope.utils.loggerr   configurationr   r   rq   r!   CLS_IDEOS_IDr?   rH   rJ   rS   ModulerT   r   r   r   r   r   r   r   r  r  register_modulebackboner  r.  r=   r=   r=   r>   <module>   sH   

Oh8_k,