U
    5Af,                     @   s   d Z ddlZddlmZmZmZ ddlmZ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eZddddZG dd deZdS )z&Fast Tokenization classes for RoBERTa.    N)ListOptionalTuple)pre_tokenizers
processors   )
AddedTokenBatchEncoding)PreTrainedTokenizerFast)logging   )RobertaTokenizerz
vocab.jsonz
merges.txtztokenizer.json)
vocab_filemerges_filetokenizer_filec                       s   e Zd ZdZeZddgZeZd fdd	Z	e
edddZejdd Zed fddZed fddZd eee ee dddZd!ddZd"ee eee  ee dddZ  ZS )#RobertaTokenizerFasta  
    Construct a "fast" RoBERTa tokenizer (backed by HuggingFace's *tokenizers* library), derived from the GPT-2
    tokenizer, using byte-level Byte-Pair-Encoding.

    This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
    be encoded differently whether it is at the beginning of the sentence (without space) or not:

    ```python
    >>> from transformers import RobertaTokenizerFast

    >>> tokenizer = RobertaTokenizerFast.from_pretrained("FacebookAI/roberta-base")
    >>> tokenizer("Hello world")["input_ids"]
    [0, 31414, 232, 2]

    >>> tokenizer(" Hello world")["input_ids"]
    [0, 20920, 232, 2]
    ```

    You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
    call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.

    <Tip>

    When used with `is_split_into_words=True`, this tokenizer needs to be instantiated with `add_prefix_space=True`.

    </Tip>

    This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
    refer to this superclass for more information regarding those methods.

    Args:
        vocab_file (`str`):
            Path to the vocabulary file.
        merges_file (`str`):
            Path to the merges file.
        errors (`str`, *optional*, defaults to `"replace"`):
            Paradigm to follow when decoding bytes to UTF-8. See
            [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
        bos_token (`str`, *optional*, defaults to `"<s>"`):
            The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.

            <Tip>

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

            </Tip>

        eos_token (`str`, *optional*, defaults to `"</s>"`):
            The end of sequence token.

            <Tip>

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

            </Tip>

        sep_token (`str`, *optional*, defaults to `"</s>"`):
            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.
        cls_token (`str`, *optional*, defaults to `"<s>"`):
            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.
        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.
        pad_token (`str`, *optional*, defaults to `"<pad>"`):
            The token used for padding, for example when batching sequences of different lengths.
        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.
        add_prefix_space (`bool`, *optional*, defaults to `False`):
            Whether or not to add an initial space to the input. This allows to treat the leading word just as any
            other word. (RoBERTa tokenizer detect beginning of words by the preceding space).
        trim_offsets (`bool`, *optional*, defaults to `True`):
            Whether the post processing step should trim offsets to avoid including whitespaces.
    Z	input_idsZattention_maskNreplace<s></s><unk><pad><mask>FTc                    sb  t |trt|ddddn|}t j||f|||||||	|
|||d| t| jj	 }|
d||krtt|d}||d< |f || j_|| _d}t| j|d }|r^t|	 }d|krt|d |d< d	|krt|d	 |d	< d}|
d||kr||d< d}|
d
||kr0||d
< d}|r^tt|d}|f |}t| j|| d S )NTF)lstriprstrip
normalized)r   errors	bos_token	eos_token	sep_token	cls_token	unk_token	pad_token
mask_tokenadd_prefix_spacetrim_offsetsr#   typeZpost_processorsepclsr$   )
isinstancestrr   super__init__jsonloadsZbackend_tokenizerZpre_tokenizer__getstate__getgetattrr   popr#   tupler   setattr)selfr   r   r   r   r   r   r   r   r    r!   r"   r#   r$   kwargsZpre_tok_stateZpre_tok_classZtokenizer_componentZtokenizer_component_instancestateZchanges_to_applyZcomponent_class	new_value	__class__ Y/tmp/pip-unpacked-wheel-zw5xktn0/transformers/models/roberta/tokenization_roberta_fast.pyr+   v   s^    
zRobertaTokenizerFast.__init__)returnc                 C   s(   | j dkr| jrtd dS t| j S )aA  
        `str`: Mask token, to use when training a model with masked-language modeling. Log an error if used while not
        having been set.

        Roberta tokenizer has a special mask token to be usable in the fill-mask pipeline. The mask token will greedily
        comprise the space before the *<mask>*.
        Nz(Using mask_token, but it is not set yet.)_mask_tokenverboseloggererrorr)   )r4   r:   r:   r;   r"      s
    	

zRobertaTokenizerFast.mask_tokenc                 C   s&   t |trt|dddn|}|| _dS )z
        Overriding the default behavior of the mask token to have it eat the space before it.

        This is needed to preserve backward compatibility with all the previously used models based on Roberta.
        TF)r   r   N)r(   r)   r   r=   )r4   valuer:   r:   r;   r"      s    	c                    s8   | dd}| js*|r*td| jj dt j||S Nis_split_into_wordsFzYou need to instantiate z? with add_prefix_space=True to use it with pretokenized inputs.)r/   r#   AssertionErrorr9   __name__r*   _batch_encode_plusr4   argsr5   rC   r8   r:   r;   rF      s
    z'RobertaTokenizerFast._batch_encode_plusc                    s8   | dd}| js*|r*td| jj dt j||S rB   )r/   r#   rD   r9   rE   r*   _encode_plusrG   r8   r:   r;   rI      s
    z!RobertaTokenizerFast._encode_plus)save_directoryfilename_prefixr<   c                 C   s   | j jj||d}t|S )N)name)
_tokenizermodelsaver2   )r4   rJ   rK   filesr:   r:   r;   save_vocabulary   s    z$RobertaTokenizerFast.save_vocabularyc                 C   s8   | j g| | jg }|d kr |S || jg | | jg S )N)Zbos_token_idZeos_token_id)r4   token_ids_0token_ids_1outputr:   r:   r;    build_inputs_with_special_tokens   s    z5RobertaTokenizerFast.build_inputs_with_special_tokens)rR   rS   r<   c                 C   sP   | j g}| jg}|dkr.t|| | dg S t|| | | | | dg S )a  
        Create a mask from the two sequences passed to be used in a sequence-pair classification task. RoBERTa does not
        make use of token type ids, therefore a list of zeros is returned.

        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 zeros.
        Nr   )Zsep_token_idZcls_token_idlen)r4   rR   rS   r&   r'   r:   r:   r;   $create_token_type_ids_from_sequences   s
    z9RobertaTokenizerFast.create_token_type_ids_from_sequences)NNNr   r   r   r   r   r   r   r   FT)N)N)N)rE   
__module____qualname____doc__VOCAB_FILES_NAMESZvocab_files_namesZmodel_input_namesr   Zslow_tokenizer_classr+   propertyr)   r"   setterr	   rF   rI   r   r   rQ   rU   r   intrW   __classcell__r:   r:   r8   r;   r   !   s@   P             I
	

  
r   )rZ   r,   typingr   r   r   Z
tokenizersr   r   Ztokenization_utils_baser   r	   Ztokenization_utils_fastr
   utilsr   Ztokenization_robertar   Z
get_loggerrE   r?   r[   r   r:   r:   r:   r;   <module>   s   
