o
    ߥi+                     @   s   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
 d dlmZ d dlmZ d d	lmZ d
dlmZ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e
jejejdG dd deZdS )    N)nn)CrossEntropyLoss)ACT2FN)Models)MODELS)AttentionFillMaskModelOutput)Tasks)
get_logger   )
PoNetModelPoNetPreTrainedModelc                       $   e Zd Z fddZdd Z  ZS )PoNetPredictionHeadTransformc                    sV   t    t|j|j| _t|jtrt	|j | _
n|j| _
tj|j|jd| _d S )N)eps)super__init__r   Linearhidden_sizedense
isinstance
hidden_actstrr   transform_act_fn	LayerNormlayer_norm_epsselfconfig	__class__ Y/home/ubuntu/.local/lib/python3.10/site-packages/modelscope/models/nlp/ponet/fill_mask.pyr   "   s   
z%PoNetPredictionHeadTransform.__init__c                 C   s"   |  |}| |}| |}|S N)r   r   r   r   hidden_statesr    r    r!   forward,   s   


z$PoNetPredictionHeadTransform.forward__name__
__module____qualname__r   r%   __classcell__r    r    r   r!   r       s    
r   c                       r   )PoNetLMPredictionHeadc                    sL   t    t|| _tj|j|jdd| _t	t
|j| _| j| j_d S )NF)bias)r   r   r   	transformr   r   r   
vocab_sizedecoder	Parametertorchzerosr,   r   r   r    r!   r   5   s   


zPoNetLMPredictionHead.__init__c                 C   s   |  |}| |}|S r"   )r-   r/   r#   r    r    r!   r%   C   s   

zPoNetLMPredictionHead.forwardr&   r    r    r   r!   r+   3   s    r+   c                       r   )PoNetOnlyMLMHeadc                    s   t    t|| _d S r"   )r   r   r+   predictionsr   r   r    r!   r   K   s   
zPoNetOnlyMLMHead.__init__c                 C   s   |  |}|S r"   )r4   )r   sequence_outputprediction_scoresr    r    r!   r%   O   s   
zPoNetOnlyMLMHead.forwardr&   r    r    r   r!   r3   I   s    r3   )module_namec                       sb   e Zd ZdZdgZddgZ fddZdd Zd	d
 Z													dddZ	  Z
S )PoNetForMaskedLMax  PoNet Model with a `language modeling` 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.

    Preprocessor:
        This is the fill_mask model of PoNet, the preprocessor of this model
        is `modelscope.preprocessors.FillMaskPoNetPreprocessor`.

    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.
    poolerposition_idszpredictions.decoder.biasc                    s@   t  | |jrtd t|dd| _t|| _| 	  d S )NzlIf you want to use `PoNetForMaskedLM` make sure `config.is_decoder=False` for bi-directional self-attention.F)add_pooling_layer)
r   r   
is_decoderloggerwarningr   ponetr3   clsinit_weights)r   r   kwargsr   r    r!   r   q   s   
zPoNetForMaskedLM.__init__c                 C   s
   | j jjS r"   r@   r4   r/   )r   r    r    r!   get_output_embeddings~   s   
z&PoNetForMaskedLM.get_output_embeddingsc                 C   s   || j j_d S r"   rC   )r   new_embeddingsr    r    r!   set_output_embeddings   s   z&PoNetForMaskedLM.set_output_embeddingsNc                 C   s   |dur|n| j j}| j|||||||||	|||d}|d }| |}d}|
dur;t }||d| j j|
d}|sQ|f|dd  }|durO|f| S |S t|||j|j	|dS )uD  
        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.
            labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
                Labels for computing the masked language modeling loss. Indices should be in ``[-100, 0, ...,
                config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are ignored
                (masked), the loss is only computed for the tokens with labels in ``[0, ..., config.vocab_size]``

        Returns:
            Returns `modelscope.outputs.AttentionFillMaskModelOutput`

        Examples:
            >>> from modelscope.models import Model
            >>> from modelscope.preprocessors import Preprocessor
            >>> model = Model.from_pretrained('damo/nlp_ponet_fill-mask_chinese-base')
            >>> preprocessor = Preprocessor.from_pretrained('damo/nlp_ponet_fill-mask_chinese-base')
            >>> # Call the model, return some tensors
            >>> print(model(**preprocessor('你师父差得动你，你师父可[MASK]不动我。')))
            >>> # Call the pipeline
            >>> from modelscope.pipelines import pipeline
            >>> pipeline_ins = pipeline('fill-mask', model=model, preprocessor=preprocessor)
            >>> print(pipeline_ins('你师父差得动你，你师父可[MASK]不动我。'))
        N)attention_masktoken_type_idssegment_idsr:   	head_maskinputs_embedsencoder_hidden_statesencoder_attention_maskoutput_attentionsoutput_hidden_statesreturn_dictr      )losslogitsr$   
attentions	input_ids)
r   use_return_dictr?   r@   r   viewr.   r   r$   rU   )r   rV   rG   rH   r:   rI   rJ   rK   rL   rM   labelsrN   rO   rP   outputsr5   r6   masked_lm_lossloss_fctoutputr    r    r!   r%      sN   S
zPoNetForMaskedLM.forward)NNNNNNNNNNNNN)r'   r(   r)   __doc__"_keys_to_ignore_on_load_unexpected_keys_to_ignore_on_load_missingr   rD   rF   r%   r*   r    r    r   r!   r8   T   s,    r8   )torch.utils.checkpointr1   r   torch.nnr   transformers.activationsr   modelscope.metainfor   modelscope.models.builderr   modelscope.outputsr   modelscope.utils.constantr   modelscope.utils.loggerr	   backboner   r   r=   Moduler   r+   r3   register_module	fill_maskr?   r8   r    r    r    r!   <module>   s    