o
    ߥi)                     @   s   d Z ddlZddlmZ ddlmZmZ ddlmZ ddl	m
Z
 ddlmZ e r0dd	lmZ ndZe Zd
ddZdi iZi Zi ZG dd de
ZdS )z*Fast Tokenization class for model DeBERTa.    N)copyfile)OptionalTuple)is_sentencepiece_available)PreTrainedTokenizerFast)logger   )DebertaV2Tokenizerz	spm.modelztokenizer.json)
vocab_filetokenizer_filer
   c                       s   e Zd ZdZeZeZeZ	e
ZeZ													d	d fddZdddZ		d fdd	Z	dddZ	ddedee d
ee fddZ  ZS )DebertaV2TokenizerFasta  
    Constructs a DeBERTa-v2 fast tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece)
    and [rjieba-py](https://github.com/messense/rjieba-py).

    Args:
        vocab_file (`str`):
            [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
            contains the vocabulary necessary to instantiate a tokenizer.
        do_lower_case (`bool`, *optional*, defaults to `False`):
            Whether or not to lowercase the input when tokenizing.
        bos_token (`string`, *optional*, defaults to `"[CLS]"`):
            The beginning of sequence token that was used during pre-training. Can be used a sequence classifier token.
            When building a sequence using special tokens, this is not the token that is used for the beginning of
            sequence. The token used is the `cls_token`.
        eos_token (`string`, *optional*, defaults to `"[SEP]"`):
            The end of sequence token. When building a sequence using special tokens, this is not the token that is
            used for the end of sequence. The token used is the `sep_token`.
        unk_token (`str`, *optional*, defaults to `"[UNK]"`):
            The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
            token instead.
        sep_token (`str`, *optional*, defaults to `"[SEP]"`):
            The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
            sequence classification or for a text and a question for question answering. It is also used as the last
            token of a sequence built with special tokens.
        pad_token (`str`, *optional*, defaults to `"[PAD]"`):
            The token used for padding, for example when batching sequences of different lengths.
        cls_token (`str`, *optional*, defaults to `"[CLS]"`):
            The classifier token which is used when doing sequence classification (classification of the whole sequence
            instead of per-token classification). It is the first token of the sequence when built with special tokens.
        mask_token (`str`, *optional*, defaults to `"[MASK]"`):
            The token used for masking values. This is the token used when training this model with masked language
            modeling. This is the token which the model will try to predict.
        sp_model_kwargs (`dict`, *optional*):
            Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
            SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
            to set:

            - `enable_sampling`: Enable subword regularization.
            - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.

              - `nbest_size = {0,1}`: No sampling is performed.
              - `nbest_size > 1`: samples from the nbest_size results.
              - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
                using forward-filtering-and-backward-sampling algorithm.

            - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
              BPE-dropout.
    NFT[CLS][SEP][UNK][PAD][MASK]returnc                    s^   t  j|f||||||	|
||||d| || _|| _|| _|| _| js*d| _d S d| _d S )N)r   do_lower_case	bos_token	eos_token	unk_token	sep_token	pad_token	cls_token
mask_tokensplit_by_punctsplit_chineseFT)super__init__r   r   r   r
   can_save_slow_tokenizer)selfr
   r   r   r   r   r   r   r   r   r   r   r   kwargs	__class__ f/home/ubuntu/.local/lib/python3.10/site-packages/modelscope/models/nlp/deberta_v2/tokenization_fast.pyr   e   s,   zDebertaV2TokenizerFast.__init__c                 C   s@   |du r| j g| | jg S | j g}| jg}|| | | | S )a  
        Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
        adding special tokens. A DeBERTa sequence has the following format:

        - single sequence: [CLS] X [SEP]
        - pair of sequences: [CLS] A [SEP] B [SEP]

        Args:
            token_ids_0 (`List[int]`):
                List of IDs to which the special tokens will be added.
            token_ids_1 (`List[int]`, *optional*):
                Optional second list of IDs for sequence pairs.

        Returns:
            `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
        N)cls_token_idsep_token_id)r    token_ids_0token_ids_1clssepr$   r$   r%    build_inputs_with_special_tokens   s
   z7DebertaV2TokenizerFast.build_inputs_with_special_tokensc                    sf   |rt  j||ddS |dur&dgdgt|  dg dgt|  dg S dgdgt|  dg S )a  
        Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
        special tokens using the tokenizer `prepare_for_model` or `encode_plus` methods.

        Args:
            token_ids_0 (`List[int]`):
                List of IDs.
            token_ids_1 (`List[int]`, *optional*):
                Optional second list of IDs for sequence pairs.
            already_has_special_tokens (`bool`, *optional*, defaults to `False`):
                Whether or not the token list is already formatted with special tokens for the model.

        Returns:
            `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
        T)r(   r)   already_has_special_tokensNr   r   )r   get_special_tokens_masklen)r    r(   r)   r-   r"   r$   r%   r.      s   z.DebertaV2TokenizerFast.get_special_tokens_maskc                 C   sV   | j g}| jg}|du rt|| | dg S t|| | dg t|| dg  S )a  
        Create a mask from the two sequences passed to be used in a sequence-pair classification task. A DeBERTa
        sequence pair mask has the following format:

        ```
        0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
        | first sequence    | second sequence |
        ```

        If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).

        Args:
            token_ids_0 (`List[int]`):
                List of IDs.
            token_ids_1 (`List[int]`, *optional*):
                Optional second list of IDs for sequence pairs.

        Returns:
            `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
        Nr   r   )r'   r&   r/   )r    r(   r)   r+   r*   r$   r$   r%   $create_token_type_ids_from_sequences   s   z;DebertaV2TokenizerFast.create_token_type_ids_from_sequencessave_directoryfilename_prefixc                 C   s~   | j stdtj|std| d d S tj||r"|d ndtd  }tj	| j
tj	|kr<t| j
| |fS )NzhYour fast tokenizer does not have the necessary information to save the vocabulary for a slow tokenizer.zVocabulary path (z) should be a directory- r
   )r   
ValueErrorospathisdirr   errorjoinVOCAB_FILES_NAMESabspathr
   r   )r    r1   r2   out_vocab_filer$   r$   r%   save_vocabulary   s"   
z&DebertaV2TokenizerFast.save_vocabulary)NNFFTr   r   r   r   r   r   r   )r   N)N)NF)__name__
__module____qualname____doc__r;   vocab_files_namesPRETRAINED_VOCAB_FILES_MAPpretrained_vocab_files_mapPRETRAINED_INIT_CONFIGURATIONpretrained_init_configuration&PRETRAINED_POSITIONAL_EMBEDDINGS_SIZESmax_model_input_sizesr	   slow_tokenizer_classr   r,   r.   r0   strr   r   r>   __classcell__r$   r$   r"   r%   r   -   sH    1
$!
 r   )rB   r6   shutilr   typingr   r   transformers.file_utilsr   $transformers.tokenization_utils_fastr   modelscope.utilsr   loggingtokenizationr	   
get_loggerr;   rD   rH   rF   r   r$   r$   r$   r%   <module>   s$   