
import os
from shutil import copyfile
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


if TYPE_CHECKING:
      from transformers.pipelines.conversational import Conversation

_A							=       logging.get_logger(__name__)

_A							=       {'''vocab_file''': '''tokenizer.model'''}

_A							=       {
    '''vocab_file''': {
        '''hf-internal-testing/llama-tokenizer''': '''https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer.model''',
    },
    '''tokenizer_file''': {
        '''hf-internal-testing/llama-tokenizer''': '''https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer_config.json''',
    },
}
_A							=       {
    '''hf-internal-testing/llama-tokenizer''': 2_048,
}
_A							=       '''▁'''

_A	,    _A							=       '''[INST]''', '''[/INST]'''
_A	,    _A							=       '''<<SYS>>\n''', '''\n<</SYS>>\n\n'''

# fmt: off
_A							=       '''You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your\
answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\
that your responses are socially unbiased and positive in nature.

If a question does not make any sense, or is not factually coherent, explain why instead of answering something not\
correct. If you don\'t know the answer to a question, please don\'t share false information.'''

class 		lowercase_							(							__SCREAMING_SNAKE_CASE					):
 A__    :					Optional[int]    =     VOCAB_FILES_NAMES
 A__    :					Optional[int]    =     PRETRAINED_VOCAB_FILES_MAP
 A__    :					List[Any]    =     PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 A__    :					Dict    =     ["""input_ids""", """attention_mask"""]

 def __init__(   self  ,						__UpperCamelCase  ,						__UpperCamelCase="<unk>"  ,						__UpperCamelCase="<s>"  ,						__UpperCamelCase="</s>"  ,						__UpperCamelCase=None  ,						__UpperCamelCase = None  ,						__UpperCamelCase=True  ,						__UpperCamelCase=False  ,						__UpperCamelCase=False  ,						__UpperCamelCase=True  ,						**__UpperCamelCase  ,						):




        """simple docstring"""


        UpperCamelCase_											=							{} if sp_model_kwargs is None else sp_model_kwargs
        UpperCamelCase_											=							AddedToken(__UpperCamelCase  ,						lstrip=__UpperCamelCase  ,						rstrip=__UpperCamelCase  ) if isinstance(__UpperCamelCase  ,						__UpperCamelCase  ) else bos_token
        UpperCamelCase_											=							AddedToken(__UpperCamelCase  ,						lstrip=__UpperCamelCase  ,						rstrip=__UpperCamelCase  ) if isinstance(__UpperCamelCase  ,						__UpperCamelCase  ) else eos_token
        UpperCamelCase_											=							AddedToken(__UpperCamelCase  ,						lstrip=__UpperCamelCase  ,						rstrip=__UpperCamelCase  ) if isinstance(__UpperCamelCase  ,						__UpperCamelCase  ) else unk_token
        UpperCamelCase_											=							AddedToken(__UpperCamelCase  ,						lstrip=__UpperCamelCase  ,						rstrip=__UpperCamelCase  ) if isinstance(__UpperCamelCase  ,						__UpperCamelCase  ) else pad_token
        super().__init__(
            bos_token=__UpperCamelCase  ,						eos_token=__UpperCamelCase  ,						unk_token=__UpperCamelCase  ,						pad_token=__UpperCamelCase  ,						add_bos_token=__UpperCamelCase  ,						add_eos_token=__UpperCamelCase  ,						sp_model_kwargs=self.sp_model_kwargs  ,						clean_up_tokenization_spaces=__UpperCamelCase  ,						legacy=__UpperCamelCase  ,						**__UpperCamelCase  ,						)
        if legacy:
               logger.warning_once(
                   f'''You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to'''
                   """ read the related pull request available at https://github.com/huggingface/transformers/pull/24565"""  )
        UpperCamelCase_											=							legacy
        UpperCamelCase_											=							vocab_file
        UpperCamelCase_											=							add_bos_token
        UpperCamelCase_											=							add_eos_token
        UpperCamelCase_											=							spm.SentencePieceProcessor(**self.sp_model_kwargs  )
        self.sp_model.Load(__UpperCamelCase  )

 def __getstate__(   self  ):




        """simple docstring"""


        UpperCamelCase_											=							self.__dict__.copy()
        UpperCamelCase_											=							None
        UpperCamelCase_											=							self.sp_model.serialized_model_proto()
        return state

 def __setstate__(   self  ,						__UpperCamelCase  ):




        """simple docstring"""


        UpperCamelCase_											=							d
        UpperCamelCase_											=							spm.SentencePieceProcessor(**self.sp_model_kwargs  )
        self.sp_model.LoadFromSerializedProto(self.sp_model_proto  )

 @property
 def lowerCamelCase_					(   self  ):




        """simple docstring"""


        return self.sp_model.get_piece_size()

 def lowerCamelCase_					(   self  ):




        """simple docstring"""


        UpperCamelCase_											=							{self.convert_ids_to_tokens(__UpperCamelCase  ): i for i in range(self.vocab_size  )}
        vocab.update(self.added_tokens_encoder  )
        return vocab

 def lowerCamelCase_					(   self  ,						__UpperCamelCase  ,						**__UpperCamelCase  ):




        """simple docstring"""


        if not self.legacy:
               UpperCamelCase_											=							SPIECE_UNDERLINE + text.replace(__UpperCamelCase  ,						""" """  )
        return super().tokenize(__UpperCamelCase  ,						**__UpperCamelCase  )

 def lowerCamelCase_					(   self  ,						__UpperCamelCase  ):




        """simple docstring"""


        if not self.legacy:
               UpperCamelCase_											=							text.startswith(__UpperCamelCase  )
               if is_first:
                      UpperCamelCase_											=							text[1:]

        UpperCamelCase_											=							self.sp_model.encode(__UpperCamelCase  ,						out_type=__UpperCamelCase  )

        if not self.legacy and not is_first and not text.startswith(""" """  ) and tokens[0].startswith(__UpperCamelCase  ):
               UpperCamelCase_											=							([tokens[0][1:]] if len(tokens[0]  ) > 1 else []) + tokens[1:]
        return tokens

 def lowerCamelCase_					(   self  ,						__UpperCamelCase  ):




        """simple docstring"""


        return self.sp_model.piece_to_id(__UpperCamelCase  )

 def lowerCamelCase_					(   self  ,						__UpperCamelCase  ):




        """simple docstring"""


        UpperCamelCase_											=							self.sp_model.IdToPiece(__UpperCamelCase  )
        return token

 def lowerCamelCase_					(   self  ,						__UpperCamelCase  ):




        """simple docstring"""


        UpperCamelCase_											=							[]
        UpperCamelCase_											=							""""""
        UpperCamelCase_											=							False
        for i, token in enumerate(__UpperCamelCase  ):
               # make sure that special tokens are not decoded using sentencepiece model
               if token in self.all_special_tokens:
                      if not prev_is_special and i != 0:
                             out_string += " "
                      out_string += self.sp_model.decode(__UpperCamelCase  ) + token
                      UpperCamelCase_											=							True
                      UpperCamelCase_											=							[]
               else:
                      current_sub_tokens.append(__UpperCamelCase  )
                      UpperCamelCase_											=							False
        out_string += self.sp_model.decode(__UpperCamelCase  )
        return out_string

 def lowerCamelCase_					(   self  ,						__UpperCamelCase  ,						__UpperCamelCase = None  ):




        """simple docstring"""


        if not os.path.isdir(__UpperCamelCase  ):
               logger.error(f'''Vocabulary path ({save_directory}) should be a directory'''  )
               return
        UpperCamelCase_											=							os.path.join(
            __UpperCamelCase  ,						(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]  )

        if os.path.abspath(self.vocab_file  ) != os.path.abspath(__UpperCamelCase  ) and os.path.isfile(self.vocab_file  ):
               copyfile(self.vocab_file  ,						__UpperCamelCase  )
        elif not os.path.isfile(self.vocab_file  ):
               with open(__UpperCamelCase  ,						"""wb"""  ) as fi:
                      UpperCamelCase_											=							self.sp_model.serialized_model_proto()
                      fi.write(__UpperCamelCase  )

        return (out_vocab_file,)

 def lowerCamelCase_					(   self  ,						__UpperCamelCase  ,						__UpperCamelCase=None  ):




        """simple docstring"""


        UpperCamelCase_											=							[self.bos_token_id] if self.add_bos_token else []
        UpperCamelCase_											=							[self.eos_token_id] if self.add_eos_token else []

        UpperCamelCase_											=							bos_token_id + token_ids_a + eos_token_id

        if token_ids_a is not None:
               UpperCamelCase_											=							output + bos_token_id + token_ids_a + eos_token_id

        return output

 def lowerCamelCase_					(   self  ,						__UpperCamelCase  ,						__UpperCamelCase = None  ,						__UpperCamelCase = False  ):




        """simple docstring"""


        if already_has_special_tokens:
               return super().get_special_tokens_mask(
                   token_ids_a=__UpperCamelCase  ,						token_ids_a=__UpperCamelCase  ,						already_has_special_tokens=__UpperCamelCase  )

        UpperCamelCase_											=							[1] if self.add_bos_token else []
        UpperCamelCase_											=							[1] if self.add_eos_token else []

        if token_ids_a is None:
               return bos_token_id + ([0] * len(__UpperCamelCase  )) + eos_token_id
        return (
            bos_token_id
            + ([0] * len(__UpperCamelCase  ))
            + eos_token_id
            + bos_token_id
            + ([0] * len(__UpperCamelCase  ))
            + eos_token_id
        )

 def lowerCamelCase_					(   self  ,						__UpperCamelCase  ,						__UpperCamelCase = None  ):




        """simple docstring"""


        UpperCamelCase_											=							[self.bos_token_id] if self.add_bos_token else []
        UpperCamelCase_											=							[self.eos_token_id] if self.add_eos_token else []

        UpperCamelCase_											=							[0] * len(bos_token_id + token_ids_a + eos_token_id  )

        if token_ids_a is not None:
               output += [1] * len(bos_token_id + token_ids_a + eos_token_id  )

        return output

 def lowerCamelCase_					(   self  ,						__UpperCamelCase  ):




        """simple docstring"""


        UpperCamelCase_											=							list(conversation.iter_texts()  )
        if not all([is_user for is_user, msg in dialogue[::2]]  ) or not all(
            [not is_user for is_user, msg in dialogue[1::2]]  ):
               raise ValueError(
                   """The model only supports 'user' and 'assistant' roles, starting with user and alternating (u/a/u/a/u...)"""  )

        UpperCamelCase_											=							[]
        if len(conversation.past_user_inputs  ) > 0:
               if not conversation.past_user_inputs[0].startswith(__UpperCamelCase  ) or E_SYS not in conversation.past_user_inputs[0]:
                      UpperCamelCase_											=							(
                          B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + conversation.past_user_inputs[0]
                      )
        elif not dialogue[0][1].startswith(__UpperCamelCase  ) or E_SYS not in dialogue[0][1]:
               UpperCamelCase_											=							(dialogue[0][0], B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + dialogue[0][1])

        dialog_tokens += sum(
            [
                [self.bos_token_id]
                + self.encode(
                    f'''{B_INST} {(prompt[1]).strip()} {E_INST} {(answer[1]).strip()} '''  ,						add_special_tokens=__UpperCamelCase  )
                + [self.eos_token_id]
                for prompt, answer in zip(dialogue[::2]  ,						dialogue[1::2]  )
            ]  ,						[]  ,						)
        if not (dialogue[-1][0]):
               raise ValueError(f'''Last message must be from user, got {dialogue[-1]["role"]}'''  )
        dialog_tokens += [self.bos_token_id] + self.encode(
            f'''{B_INST} {(dialogue[-1][1]).strip()} {E_INST}'''  ,						add_special_tokens=__UpperCamelCase  )
        return dialog_tokens





from ...configuration_utils import PretrainedConfig
from ...utils import logging


_A							=       logging.get_logger(__name__)

_A							=       {
    '''facebook/opt-125m''': '''https://huggingface.co/facebook/opt-125m/blob/main/config.json''',
    '''facebook/opt-350m''': '''https://huggingface.co/facebook/opt-350m/blob/main/config.json''',
    '''facebook/opt-1.3b''': '''https://huggingface.co/facebook/opt-1.3b/blob/main/config.json''',
    '''facebook/opt-2.7b''': '''https://huggingface.co/facebook/opt-2.7b/blob/main/config.json''',
    '''facebook/opt-6.7b''': '''https://huggingface.co/facebook/opt-6.7b/blob/main/config.json''',
    '''facebook/opt-13b''': '''https://huggingface.co/facebook/opt-13b/blob/main/config.json''',
}

class 		lowercase_							(							__SCREAMING_SNAKE_CASE					):
 A__    :					Dict    =     """opt"""
 A__    :					int    =     ["""past_key_values"""]

 def __init__(   self  ,						__UpperCamelCase=5_0_2_7_2  ,						__UpperCamelCase=7_6_8  ,						__UpperCamelCase=1_2  ,						__UpperCamelCase=3_0_7_2  ,						__UpperCamelCase=2_0_4_8  ,						__UpperCamelCase=True  ,						__UpperCamelCase=False  ,						__UpperCamelCase=None  ,						__UpperCamelCase=0.1  ,						__UpperCamelCase=0.0  ,						__UpperCamelCase=1_2  ,						__UpperCamelCase="relu"  ,						__UpperCamelCase=0.0  ,						__UpperCamelCase=0.02  ,						__UpperCamelCase=True  ,						__UpperCamelCase=1  ,						__UpperCamelCase=2  ,						__UpperCamelCase=2  ,						__UpperCamelCase=True  ,						__UpperCamelCase=True  ,						**__UpperCamelCase  ,						):




        """simple docstring"""


        super().__init__(
            pad_token_id=__UpperCamelCase  ,						bos_token_id=__UpperCamelCase  ,						eos_token_id=__UpperCamelCase  ,						**__UpperCamelCase  ,						)
        UpperCamelCase_											=							vocab_size
        UpperCamelCase_											=							max_position_embeddings
        UpperCamelCase_											=							num_attention_heads
        UpperCamelCase_											=							word_embed_proj_dim if word_embed_proj_dim is not None else hidden_size
        UpperCamelCase_											=							ffn_dim
        UpperCamelCase_											=							hidden_size
        UpperCamelCase_											=							num_hidden_layers
        UpperCamelCase_											=							dropout
        UpperCamelCase_											=							attention_dropout
        UpperCamelCase_											=							activation_function
        UpperCamelCase_											=							init_std
        UpperCamelCase_											=							layerdrop
        UpperCamelCase_											=							use_cache
        UpperCamelCase_											=							do_layer_norm_before
        # We keep these variables at `True` for backward compatibility.
        UpperCamelCase_											=							enable_bias
        UpperCamelCase_											=							layer_norm_elementwise_affine

        # Note that the only purpose of `_remove_final_layer_norm` is to keep backward compatibility
        # with checkpoints that have been fine-tuned before transformers v4.20.1
        # see https://github.com/facebookresearch/metaseq/pull/164
        UpperCamelCase_											=							_remove_final_layer_norm



