
    9iV.              
       `   S SK r S SKJr  S SKr S SKJrJr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  \R2                  " 5       r\
R4                  " \R6                  \R8                  S9\
R4                  " \R:                  \R8                  S9\
R4                  " \R<                  \R8                  S9\
R4                  " \R>                  \R8                  S9\
R4                  " \R@                  \R8                  S9 " S S\5      5       5       5       5       5       r!g)    N)BCEWithLogitsLossCrossEntropyLossMSELoss)Models)MODELS)&AttentionTextClassificationModelOutput)logger)Tasks   )compute_adv_loss)
SbertModelSbertPreTrainedModel)SbertConfig)module_namec                   ^   ^  \ rS rSrSrS\4U 4S jjrS r          S	S jrS r	Sr
U =r$ )
SbertForSequenceClassification#   a  StructBERT Model transformer with a sequence classification/regression head on top
(a linear layer on top of the pooled output) e.g. for GLUE 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 text classification model of StructBERT, the preprocessor of this model
    is `modelscope.preprocessors.TextClassificationTransformersPreprocessor`.

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.
configc                 0  > [         TU ]  U5        UR                  U l        Xl        U R                  R                  c  [
        R                  S5        [        US[        R                  5      [        l	        [        X R                  [        U5      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.base_model_prefix)super__init__
num_labelsr   adv_grad_factorr	   warninggetattrr   r   setattrr   classifier_dropouthidden_dropout_probnnDropoutdropoutLinearhidden_size
classifierinit_weights)selfr   kwargsr   	__class__s       t/var/www/html/land-doc-ocr/venv/lib/python3.13/site-packages/modelscope/models/nlp/structbert/text_classification.pyr   'SbertForSequenceClassification.__init__I   s      ++;;&&.NNDF <C'*<<<>&8 	,,j.@A)/)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 )
base_modelr"   r%   r(   )r'   r(   outputspooled_outputr.   s        r*   _forward_call,SbertForSequenceClassification._forward_call\   sJ    //+F+
]3/"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
                  " X40 UR                  D6$ )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.
    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).

Returns:
    Returns `modelscope.outputs.AttentionTextClassificationModelOutput`

Examples:
    >>> from modelscope.models import Model
    >>> from modelscope.preprocessors import Preprocessor
    >>> model = Model.from_pretrained('damo/nlp_structbert_sentence-similarity_chinese-base')
    >>> preprocessor = Preprocessor.from_pretrained('damo/nlp_structbert_sentence-similarity_chinese-base')
    >>> # Call the model, return some tensors
    >>> print(model(**preprocessor(('这是个测试', '这也是个测试'))))
    >>> # Call the pipeline
    >>> from modelscope.pipelines import pipeline
    >>> pipeline_ins = pipeline('text-classification', model=model, preprocessor=preprocessor)
    >>> print(pipeline_ins(('这是个测试', '这也是个测试')))
z+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_dict)r   use_return_dictr	   errorr3   compute_lossr(   )r'   r6   r7   r8   r9   r:   r;   labelsr<   r=   r>   argsr(   r1   s                 r*   forward&SbertForSequenceClassification.forwarde   sw    ^ &1%<k$++B]B]LLFG$$))%'/!5# % 	%   CGNNCCr,   c                    UR                   nUR                  nS nUGb  U R                  R                  c  U R                  S:X  a  SU R                  l        OoU R                  S:  aN  UR
                  [        R                  :X  d  UR
                  [        R                  :X  a  SU R                  l        OSU R                  l        U R                  R                  S:X  aK  [        5       nU R                  S:X  a'  U" UR                  5       UR                  5       5      nGOU" XB5      nGOU R                  R                  S:X  a  [        5       nU" UR                  SU R                  5      UR                  S5      5      nU R                  R                  bj  U R                  (       aY  [        SUU R                   UUU R                  R"                  U R                  R                  U R                  R$                  S.UD6nO,U R                  R                  S:X  a  ['        5       nU" XB5      n[)        UUUR*                  UR,                  S9$ )	Nr   
regressionsingle_label_classificationmulti_label_classification)	embeddingmodel
ori_logitsori_loss	adv_boundr   sigma)lossr.   hidden_states
attentionsr/   )r.   embedding_outputr   problem_typer   dtypetorchlongintr   squeezer   viewr   trainingr   r3   rO   rP   r   r   rR   rS   )r'   r1   rB   r(   r.   rT   rQ   loss_fcts           r*   rA   +SbertForSequenceClassification.compute_loss   s   "33{{''/??a'/;DKK,__q(fllejj.H171J/LDKK,/KDKK,{{''<7"9??a'#FNN$4fnn6FGD#F3D))-JJ+-KKDOO4fkk"oG;;..:t}}+ ""2"00#)!%"&++"7"7(,(C(C"kk//" !"D ))-II,./5!//))	
 	
r,   )r%   r   r"   r   )
NNNNNNNNNN)__name__
__module____qualname____firstlineno____doc__r   r   r3   rD   rA   __static_attributes____classcell__)r)   s   @r*   r   r   #   sK    8{ & ##!""&%) \D|+
 +
r,   r   )"rW   torch.nnr    torch.utils.checkpointr   r   r   modelscope.metainfor   modelscope.models.builderr   modelscope.outputsr   modelscope.utilsr	   loggingmodelscope.utils.constantr
   	adv_utilsr   backboner   r   configurationr   
get_loggerregister_moduletext_classification
structbertnlisentiment_classificationsentence_similarityzero_shot_classificationr   r/   r,   r*   <module>ry      s  $    A A & , E . + ' 6 &				 	6+<+<>		v/@/@A	""0A0AC	6+<+<>	""0A0ACB
%9 B
C>C B>B
r,   