
    9iB+                        S SK r S SKJr  S SKr S SKJr  S SKJr  S SKJr  S SK	J
r
  S SKJr  S SKJr  SS	KJr  SS
KJrJr  SSKJr  \R.                  " 5       r\R0                  " \R2                  \R4                  S9\R0                  " \R6                  \R4                  S9\R0                  " \R8                  \R4                  S9 " S S\5      5       5       5       rg)    N)CrossEntropyLoss)Models)MODELS)'AttentionTokenClassificationModelOutput)logger)Tasks   )compute_adv_loss)
SbertModelSbertPreTrainedModel)SbertConfig)module_namec                   b   ^  \ rS rSrSrS/rS\4U 4S jjrS r            S	S jr	Sr
U =r$ )
SbertForTokenClassification#   a  StructBERT 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.

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 token-classification model of StructBERT, 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configc           	        > [         TU ]  U5        UR                  U l        Xl        U R                  R                  c  [
        R                  S5        [        X R                  [        USS95        UR                  b  UR                  OUR                  n[        R                  " U5      U l        [        R                  " UR                   UR                  5      U l        U R%                  5         g )Nz2Adv parameters not set, skipping compute_adv_loss.F)add_pooling_layer)super__init__
num_labelsr   adv_grad_factorr   warningsetattrbase_model_prefixr   classifier_dropouthidden_dropout_probnnDropoutdropoutLinearhidden_size
classifierinit_weights)selfr   kwargsr   	__class__s       u/var/www/html/land-doc-ocr/venv/lib/python3.13/site-packages/modelscope/models/nlp/structbert/token_classification.pyr   $SbertForTokenClassification.__init__F   s      ++;;&&.NNDF,,6U;	= *0)B)B)NF%%++ 	 zz"45))F$6$68I8IJ    c                     U R                   " S0 UD6nUS   nU R                  U5      nU R                  U5      nXBS'   Xl        U$ )Nr   logits )bertr!   r$   r'   )r&   r'   outputssequence_outputr-   s        r)   _forward_call)SbertForTokenClassification._forward_callW   sJ    ))%f%!!*,,71"r+   c                    U
b  U
OU R                   R                  n
U
(       d  [        R                  S5        U R	                  UUUUUUUU	U
S9	nUR
                  nUR                  nSnUGb[  [        5       nUb  UR                  S5      S:H  nUR                  SU R                  5      n[        R                  " UUR                  S5      [        R                  " UR                  5      R                  U5      5      nU" UU5      nO2U" UR                  SU R                  5      UR                  S5      5      nU R                   R                  bw  U R                   (       af  [#        SUU R                  UUU R                   R$                  U R                   R                  U R                   R&                  USLS.UR(                  D6n[+        UUUR,                  UR.                  UUS9$ )	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, sequence_length)`, `optional`):
        Labels for computing the token classification loss. Indices should be in
        ``[0, ..., config.num_labels - 1]``.
    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_structbert_word-segmentation_chinese-base')
    >>> preprocessor = Preprocessor.from_pretrained('damo/nlp_structbert_word-segmentation_chinese-base')
    >>> print(model(**preprocessor(('This is a test', 'This is also a test'))))
Nz+Return tuple in sbert is not supported now.)		input_idsattention_masktoken_type_idsposition_ids	head_maskinputs_embedsoutput_attentionsoutput_hidden_statesreturn_dictr	   )	embeddingmodel
ori_logitsori_loss	adv_boundr   sigmawith_attention_mask)lossr-   hidden_states
attentionsoffset_mapping
label_maskr.   )r   use_return_dictr   errorr2   r-   embedding_outputr   viewr   torchwheretensorignore_indextype_asr   trainingr
   rC   rD   r'   r   rG   rH   )r&   r5   r6   r7   r8   r9   r:   labelsr;   r<   r=   rI   rJ   r0   r-   rM   rF   loss_fctactive_lossactive_logitsactive_labelss                        r)   forward#SbertForTokenClassification.forward`   s   h &1%<k$++B]B]LLFG$$))%'/!5# % 	% "33')H),11"5: &B @ %RLL!6!67??G!I  }=KKDOO4fkk"oG{{**64==' 	&.,,%!"kk33$(KK$?$?++++(6d(B	& nn	& 7!//)))!
 	
r+   )r$   r   r!   r   )NNNNNNNNNNNN)__name__
__module____qualname____firstlineno____doc__"_keys_to_ignore_on_load_unexpectedr   r   r2   rZ   __static_attributes____classcell__)r(   s   @r)   r   r   #   sU    
8 +4&{ " !F
 F
r+   r   )rO   torch.nnr   torch.utils.checkpointr   modelscope.metainfor   modelscope.models.builderr   modelscope.outputsr   modelscope.utilsr   loggingmodelscope.utils.constantr   	adv_utilsr
   backboner   r   configurationr   
get_loggerregister_moduletoken_classification
structbertword_segmentationpart_of_speechr   r.   r+   r)   <module>ru      s   $    % & , F . + ' 6 &				 	F,=,=?//V=N=NO,,&:K:KL
"6 
 M P?
r+   