a
    d&                     @   s   d Z ddlZddlmZ ddlmZmZmZmZm	Z	 ddl
ZddlmZmZ ddlmZ eeZdd	iZd
did
didZd
diZG dd deZdS )zTokenization classes for LLaMA.    N)copyfile)AnyDictListOptionalTuple   )
AddedTokenPreTrainedTokenizer)logging
vocab_fileztokenizer.modelz#hf-internal-testing/llama-tokenizerzWhttps://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer.modelz]https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer_config.json)r   Ztokenizer_filei   c                       s   e Zd ZdZeZeZeZ	ddgZ
d(eeeef  d
 fddZdd Zdd Zedd Zdd Zdd Zdd Zdd Zdd Zd)ee ee dddZd*d d!Zd+ee eee  eee d" fd#d$Zd,ee eee  ee d%d&d'Z   Z!S )-LlamaTokenizerz
    Construct a Llama tokenizer. Based on byte-level Byte-Pair-Encoding.

    Args:
        vocab_file (`str`):
            Path to the vocabulary file.
    Z	input_idsZattention_mask<unk><s></s>NTF)sp_model_kwargsc
                    s   |d u ri n|| _ t|tr*t|dddn|}t|trFt|dddn|}t|trbt|dddn|}t|tr~t|dddn|}t jf ||||||| j |	d|
 || _|| _|| _t	j
f i | j | _| j| d S )NF)lstriprstrip)	bos_token	eos_token	unk_token	pad_tokenadd_bos_tokenadd_eos_tokenr   clean_up_tokenization_spaces)r   
isinstancestrr	   super__init__r   r   r   spmSentencePieceProcessorsp_modelLoad)selfr   r   r   r   r   r   r   r   r   kwargs	__class__ u/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/transformers/models/llama/tokenization_llama.pyr   ?   s,    	zLlamaTokenizer.__init__c                 C   s   | j  }d |d< |S )Nr!   )__dict__copy)r#   stater'   r'   r(   __getstate__b   s    
zLlamaTokenizer.__getstate__c                 C   s,   || _ tjf i | j| _| j| j d S N)r)   r   r    r   r!   r"   r   )r#   dr'   r'   r(   __setstate__g   s    zLlamaTokenizer.__setstate__c                 C   s
   | j  S )zReturns vocab size)r!   Zget_piece_sizer#   r'   r'   r(   
vocab_sizel   s    zLlamaTokenizer.vocab_sizec                    s(    fddt  jD }| j |S )zReturns vocab as a dictc                    s   i | ]}  ||qS r'   )Zconvert_ids_to_tokens).0ir0   r'   r(   
<dictcomp>s       z,LlamaTokenizer.get_vocab.<locals>.<dictcomp>)ranger1   updateZadded_tokens_encoder)r#   Zvocabr'   r0   r(   	get_vocabq   s    zLlamaTokenizer.get_vocabc                 C   s   | j j|tdS )zReturns a tokenized string.)Zout_type)r!   encoder   )r#   textr'   r'   r(   	_tokenizew   s    zLlamaTokenizer._tokenizec                 C   s   | j |S )z0Converts a token (str) in an id using the vocab.)r!   Zpiece_to_id)r#   tokenr'   r'   r(   _convert_token_to_id{   s    z#LlamaTokenizer._convert_token_to_idc                 C   s   | j |}|S )z=Converts an index (integer) in a token (str) using the vocab.)r!   Z	IdToPiece)r#   indexr<   r'   r'   r(   _convert_id_to_token   s    z#LlamaTokenizer._convert_id_to_tokenc                 C   s|   g }d}d}t |D ]R\}}|| jv rX|s:|dkr:|d7 }|| j|| 7 }d}g }q|| d}q|| j|7 }|S )z:Converts a sequence of tokens (string) in a single string. Fr    T)	enumerateZall_special_tokensr!   decodeappend)r#   tokensZcurrent_sub_tokensZ
out_stringZprev_is_specialr3   r<   r'   r'   r(   convert_tokens_to_string   s    

z'LlamaTokenizer.convert_tokens_to_string)filename_prefixreturnc                 C   s   t j|s"td| d dS t j||r6|d ndtd  }t j| jt j|krzt j	| jrzt
| j| nLt j	| jst|d$}| j }|| W d   n1 s0    Y  |fS )a  
        Save the vocabulary and special tokens file to a directory.

        Args:
            save_directory (`str`):
                The directory in which to save the vocabulary.

        Returns:
            `Tuple(str)`: Paths to the files saved.
        zVocabulary path (z) should be a directoryN-r@   r   wb)ospathisdirloggererrorjoinVOCAB_FILES_NAMESabspathr   isfiler   openr!   Zserialized_model_protowrite)r#   Zsave_directoryrG   Zout_vocab_filefiZcontent_spiece_modelr'   r'   r(   save_vocabulary   s    (
(zLlamaTokenizer.save_vocabularyc                 C   sL   | j r| jgng }| jr | jgng }|| | }|d urH|| | | }|S r-   )r   bos_token_idr   eos_token_idr#   token_ids_0token_ids_1rX   rY   outputr'   r'   r(    build_inputs_with_special_tokens   s    z/LlamaTokenizer.build_inputs_with_special_tokens)r[   r\   already_has_special_tokensrH   c                    s   |rt  j||ddS | jr"dgng }| jr2dgng }|du rT|dgt|  | S |dgt|  | | dgt|  | S )a  
        Retrieve 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` method.

        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\   r_      Nr   )r   get_special_tokens_maskr   r   len)r#   r[   r\   r_   rX   rY   r%   r'   r(   ra      s(    z&LlamaTokenizer.get_special_tokens_mask)r[   r\   rH   c                 C   s`   | j r| jgng }| jr | jgng }dgt|| |  }|dur\|dgt|| |  7 }|S )a  
        Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
        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, 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).
        r   Nr`   )r   rX   r   rY   rb   rZ   r'   r'   r(   $create_token_type_ids_from_sequences   s    z3LlamaTokenizer.create_token_type_ids_from_sequences)r   r   r   NNTFF)N)N)NF)N)"__name__
__module____qualname____doc__rQ   Zvocab_files_namesPRETRAINED_VOCAB_FILES_MAPZpretrained_vocab_files_map&PRETRAINED_POSITIONAL_EMBEDDINGS_SIZESZmax_model_input_sizesZmodel_input_namesr   r   r   r   r   r,   r/   propertyr1   r8   r;   r=   r?   rF   r   rW   r^   r   intboolra   rc   __classcell__r'   r'   r%   r(   r   1   sJ           #

 & r   )rg   rK   shutilr   typingr   r   r   r   r   Zsentencepiecer   Ztokenization_utilsr	   r
   utilsr   Z
get_loggerrd   rN   rQ   rh   ri   r   r'   r'   r'   r(   <module>   s    
	