o
    ߥi[(                     @   s   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 d dl	m
Z
 d dlmZ d dlmZ dd	lmZmZ e Zejejejd
ejejejd
ejejejd
G dd deZdS )    N)CrossEntropyLoss)Models)MODELS)'AttentionTokenClassificationModelOutput)logger)Tasks   )MGeoMGeoPreTrainedModel)module_namec                       sT   e Zd ZdZdgZd
def fddZ														ddd	Z  ZS )MGeoForTokenClassificationa
  Bert Model with a token classification head on top (a linear layer on top of
    the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks, word-segmentation.

    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 Bert, the preprocessor of this model
        is `modelscope.preprocessors.TokenClassificationTransformersPreprocessor`.

    Trainer:
        This model is a normal PyTorch model, and can be trained by variable trainers, like EpochBasedTrainer,
        NlpEpochBasedTrainer, or trainers from other frameworks.
        The preferred trainer in ModelScope is NlpEpochBasedTrainer.

    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.
    poolersingle-modalfinetune_modec                    sl   t  | |j| _t| | jt||dd |jd ur|jn|j}t	|| _
t|j|j| _|   d S )NF)add_pooling_layer)super__init__
num_labelssetattrbase_model_prefixr	   classifier_dropouthidden_dropout_probnnDropoutdropoutLinearhidden_size
classifier	post_init)selfconfigr   kwargsr   	__class__ k/home/ubuntu/.local/lib/python3.10/site-packages/modelscope/models/multi_modal/mgeo/token_classification.pyr   B   s   z#MGeoForTokenClassification.__init__Nc                 C   s  |
dur|
n| j j}
| j||||||||	|
||d}|d }| |}| |}d}|durgt }|durZ|ddk}|d| j}t	||dt
|j|}|||}n||d| j|d}|
s}|f|dd  }|dur{|f| S |S t|||j|j||dS )a  
        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.
        labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`,
        `optional`):
            Labels for computing the sequence classification/regression loss.
            Indices should be in :obj:`[0, ..., config.num_labels - 1]`. If
            :obj:`config.num_labels == 1` a regression loss is computed
            (Mean-Square loss), If :obj:`config.num_labels > 1` a classification
            loss is computed (Cross-Entropy).
        offset_mapping (:obj:`torch.FloatTensor` of shape :obj:`(batch_size,
        sequence_length)`, `optional`):
            Indices of positions of each input sequence tokens in the sentence.
            Selected in the range ``[0, sequence_length - 1]``.
        label_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**.

        Returns:
            Returns `modelscope.outputs.AttentionTokenClassificationModelOutput`

        Examples:
            >>> from modelscope.models import Model
            >>> from modelscope.preprocessors import Preprocessor
            >>> model = Model.from_pretrained('damo/nlp_bert_word-segmentation_chinese-base')
            >>> preprocessor = Preprocessor.from_pretrained('damo/nlp_bert_word-segmentation_chinese-base')
            >>> print(model(**preprocessor(('This is a test', 'This is also a test'))))
        N)
attention_masktoken_type_idsposition_ids	head_maskinputs_embedsoutput_attentionsoutput_hidden_statesreturn_dictgis_listgis_tpr   r      )losslogitshidden_states
attentionsoffset_mapping
label_mask)r    use_return_dictbertr   r   r   viewr   torchwheretensorignore_indextype_asr   r4   r5   )r   	input_idsr&   r'   r(   r)   r*   labelsr+   r,   r-   r6   r7   r.   r/   outputssequence_outputr3   r2   loss_fctactive_lossactive_logitsactive_labelsoutputr$   r$   r%   forwardQ   sT   f


z"MGeoForTokenClassification.forward)r   )NNNNNNNNNNNNNN)	__name__
__module____qualname____doc__"_keys_to_ignore_on_load_unexpectedstrr   rI   __classcell__r$   r$   r"   r%   r   !   s&    r   )r;   torch.nnr   torch.utils.checkpointr   modelscope.metainfor   modelscope.models.builderr   modelscope.outputsr   modelscope.utilsr   loggingmodelscope.utils.constantr   backboner	   r
   
get_loggerregister_moduletoken_classificationmgeopart_of_speechword_segmentationr   r$   r$   r$   r%   <module>   s   