
    9i%1                        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 " S S\R0                  5      r " S S\R0                  5      r " S S\R0                  5      r " S S\R0                  5      r\
R:                  " \R<                  \R>                  S9 " S S\5      5       r g)    N)CrossEntropyLoss)ACT2FN)Models)MODELS)AttentionFillMaskModelOutput)logger)Tasks   )
SbertModelSbertPreTrainedModel)SbertConfigc                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )SbertPredictionHeadTransform#   c                 p  > [         TU ]  5         [        R                  " UR                  UR                  5      U l        [        UR                  [        5      (       a  [        UR                     U l
        OUR                  U l
        [        R                  " UR                  UR                  S9U l        g )N)eps)super__init__nnLinearhidden_sizedense
isinstance
hidden_actstrr   transform_act_fn	LayerNormlayer_norm_epsselfconfig	__class__s     j/var/www/html/land-doc-ocr/venv/lib/python3.13/site-packages/modelscope/models/nlp/structbert/fill_mask.pyr   %SbertPredictionHeadTransform.__init__%   s    YYv1163E3EF
f''--$*6+<+<$=D!$*$5$5D!F$9$9;    c                 l    U R                  U5      nU R                  U5      nU R                  U5      nU$ N)r   r   r   r    hidden_statess     r#   forward$SbertPredictionHeadTransform.forward/   s4    

=1--m<}5r%   )r   r   r   __name__
__module____qualname____firstlineno__r   r*   __static_attributes____classcell__r"   s   @r#   r   r   #   s    ; r%   r   c                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )SbertLMPredictionHead6   c                    > [         TU ]  5         [        U5      U l        [        R
                  " UR                  UR                  5      U l        g r'   )	r   r   r   	transformr   r   r   
vocab_sizedecoderr   s     r#   r   SbertLMPredictionHead.__init__8   s:    5f= yy!3!3V5F5FGr%   c                 J    U R                  U5      nU R                  U5      nU$ r'   )r8   r:   r(   s     r#   r*   SbertLMPredictionHead.forward@   s$    }5]3r%   )r:   r8   r,   r3   s   @r#   r5   r5   6   s    H r%   r5   c                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )SbertOnlyMLMHeadF   c                 B   > [         TU ]  5         [        U5      U l        g r'   )r   r   r5   predictionsr   s     r#   r   SbertOnlyMLMHead.__init__H   s    08r%   c                 (    U R                  U5      nU$ r'   rB   )r    sequence_outputprediction_scoress      r#   r*   SbertOnlyMLMHead.forwardL   s     ,,_=  r%   rE   r,   r3   s   @r#   r?   r?   F   s    9! !r%   r?   c                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )SbertPreTrainingHeadsQ   c                    > [         TU ]  5         [        U5      U l        [        R
                  " UR                  S5      U l        g )N   )r   r   r5   rB   r   r   r   seq_relationshipr   s     r#   r   SbertPreTrainingHeads.__init__S   s4    08 "		&*<*<a @r%   c                 L    U R                  U5      nU R                  U5      nX44$ r'   rB   rN   )r    rF   pooled_outputrG   seq_relationship_scores        r#   r*   SbertPreTrainingHeads.forwardX   s-     ,,_=!%!6!6}!E 88r%   rQ   r,   r3   s   @r#   rJ   rJ   Q   s    A
9 9r%   rJ   )module_namec                   |   ^  \ rS rSrSrS/rSS/rS\4U 4S jjrS r	S	 r
            SS
 jr SS jrSrU =r$ )SbertForMaskedLM^   aN  StructBERT 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 StructBERT, the preprocessor of this model
    is `modelscope.preprocessors.FillMaskTransformersPreprocessor`.

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position_idszpredictions.decoder.biasr!   c                    > [         TU ]  U5        UR                  (       a  [        R	                  S5        [        U5      U l        [        U5      U l        U R                  5         g )NzlIf you want to use `SbertForMaskedLM` make sure `config.is_decoder=False` for bi-directional self-attention.)
r   r   
is_decoderr   warningr   bertr?   clsinit_weights)r    r!   kwargsr"   s      r#   r   SbertForMaskedLM.__init__{   sP     NN12 v&	#F+r%   c                 B    U R                   R                  R                  $ r'   r_   rB   r:   )r    s    r#   get_output_embeddings&SbertForMaskedLM.get_output_embeddings   s    xx##+++r%   c                 8    XR                   R                  l        g r'   rd   )r    new_embeddingss     r#   set_output_embeddings&SbertForMaskedLM.set_output_embeddings   s    '5$r%   c                    Ub  UOU R                   R                  nU R                  UUUUUUUUU
UUS9nUS   nU R                  U5      nSnU	bF  [	        5       nU" UR                  SU R                   R                  5      U	R                  S5      5      nU(       d  U4USS -   nUb  U4U-   $ U$ [        UUUR                  UR                  US9$ )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.

        `What are input IDs? <../glossary.html#input-ids>`__

    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**.

        `What are attention masks? <../glossary.html#attention-mask>`__

    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.

        `What are token type IDs? <../glossary.html#token-type-ids>`_
    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 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, FillMaskTransformersPreprocessor
    >>> model = Model.from_pretrained('damo/nlp_structbert_fill-mask_chinese-large')
    >>> preprocessor = FillMaskTransformersPreprocessor('damo/nlp_structbert_fill-mask_chinese-large')
    >>> # 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_idsrZ   	head_maskinputs_embedsencoder_hidden_statesencoder_attention_maskoutput_attentionsoutput_hidden_statesreturn_dictr   rM   )losslogitsr)   
attentions	input_ids)
r!   use_return_dictr^   r_   r   viewr9   r   r)   rx   )r    ry   rl   rm   rZ   rn   ro   rp   rq   labelsrr   rs   rt   outputsrF   rG   masked_lm_lossloss_fctoutputs                      r#   r*   SbertForMaskedLM.forward   s   n &1%<k$++B]B]))))%'"7#9/!5#  
 "!* HH_5')H%!&&r4;;+A+ABB!N '*WQr]:F!/!; $& HAGH ,$!//))
 	
r%   c                    UR                   nUS   nU R                  R                  c   S5       eUR                  UR                   S   S45      n[        R
                  " X&/SS9n[        R                  " US4U R                  R                  [        R                  UR                  S9n[        R
                  " X/SS9nXS.$ )Nr   z.The PAD token should be defined for generationr
   ru   )dim)dtypedevice)ry   rl   )	shaper!   pad_token_id	new_zerostorchcatfulllongr   )r    ry   rl   model_kwargsinput_shapeeffective_batch_sizeattention_mask_zerodummy_tokens           r#   prepare_inputs_for_generation.SbertForMaskedLM.prepare_inputs_for_generation  s      oo*1~ {{''3e5ee3,66!!!$a(*N#H')+jj"6!:!%!9!9',zz(1(8(8: IIy6A>	&IIr%   )r^   r_   )NNNNNNNNNNNNr'   )r-   r.   r/   r0   __doc__"_keys_to_ignore_on_load_unexpected_keys_to_ignore_on_load_missingr   r   re   ri   r*   r   r1   r2   r3   s   @r#   rW   rW   ^   st    , +4&4'#{ ,6
 "#!{
~ 6:J Jr%   rW   )!r   torch.nnr   torch.utils.checkpointr   transformers.activationsr   modelscope.metainfor   modelscope.models.builderr   modelscope.outputsr   modelscope.utilsr   loggingmodelscope.utils.constantr	   backboner   r   configurationr   
get_loggerModuler   r5   r?   rJ   register_module	fill_mask
structbertrW    r%   r#   <module>r      s   $    % + & , ; . + 6 &				299 &BII  !ryy !
9BII 
9 V5F5FGJ+ J HJr%   