"""simple docstring"""







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

lowerCamelCase      : Dict       =logging.get_logger(__name__)

lowerCamelCase      : Optional[Any]       ={'''vocab_file''': '''tokenizer.model'''}

lowerCamelCase      : Dict       ={
    '''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''',
    },
}
lowerCamelCase      : int       ={
    '''hf-internal-testing/llama-tokenizer''': 20_48,
}
lowerCamelCase      : Any       ='''▁'''

lowerCamelCase     , lowerCamelCase      : Union[str, Any]       ='''[INST]''', '''[/INST]'''
lowerCamelCase     , lowerCamelCase      : int       ='''<<SYS>>\n''', '''\n<</SYS>>\n\n'''

# fmt: off
lowerCamelCase      : Tuple       ='''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 							__snake_case(					A_	):


    '''simple docstring'''





    _UpperCAmelCase       =			VOCAB_FILES_NAMES
    _UpperCAmelCase       =			PRETRAINED_VOCAB_FILES_MAP
    _UpperCAmelCase       =			PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
    _UpperCAmelCase       =			["input_ids", "attention_mask"]
    def __init__(  self					,       __lowerCamelCase					,       __lowerCamelCase="<unk>"					,       __lowerCamelCase="<s>"					,       __lowerCamelCase="</s>"					,       __lowerCamelCase=None					,       __lowerCamelCase = None					,       __lowerCamelCase=True					,       __lowerCamelCase=False					,       __lowerCamelCase=False					,       __lowerCamelCase=True					,       **__lowerCamelCase					,       ):




         '''simple docstring'''



         __A					:					Optional[int]								=		{} if sp_model_kwargs is None else sp_model_kwargs
         __A					:					Optional[Any]								=		AddedToken(__lowerCamelCase					,       lstrip=__lowerCamelCase					,       rstrip=__lowerCamelCase	) if isinstance(__lowerCamelCase					,       __lowerCamelCase	) else bos_token
         __A					:					Tuple								=		AddedToken(__lowerCamelCase					,       lstrip=__lowerCamelCase					,       rstrip=__lowerCamelCase	) if isinstance(__lowerCamelCase					,       __lowerCamelCase	) else eos_token
         __A					:					Union[str, Any]								=		AddedToken(__lowerCamelCase					,       lstrip=__lowerCamelCase					,       rstrip=__lowerCamelCase	) if isinstance(__lowerCamelCase					,       __lowerCamelCase	) else unk_token
         __A					:					Any								=		AddedToken(__lowerCamelCase					,       lstrip=__lowerCamelCase					,       rstrip=__lowerCamelCase	) if isinstance(__lowerCamelCase					,       __lowerCamelCase	) else pad_token
         super().__init__(
             bos_token=__lowerCamelCase					,       eos_token=__lowerCamelCase					,       unk_token=__lowerCamelCase					,       pad_token=__lowerCamelCase					,       add_bos_token=__lowerCamelCase					,       add_eos_token=__lowerCamelCase					,       sp_model_kwargs=self.sp_model_kwargs					,       clean_up_tokenization_spaces=__lowerCamelCase					,       legacy=__lowerCamelCase					,       **__lowerCamelCase					,       )
         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'	)
         __A					:					int								=		legacy
         __A					:					Optional[int]								=		vocab_file
         __A					:					Optional[int]								=		add_bos_token
         __A					:					Dict								=		add_eos_token
         __A					:					Any								=		spm.SentencePieceProcessor(**self.sp_model_kwargs	)
         self.sp_model.Load(__lowerCamelCase	)
    def __getstate__(  self	):




         '''simple docstring'''



         __A					:					List[str]								=		self.__dict__.copy()
         __A					:					Union[str, Any]								=		None
         __A					:					List[str]								=		self.sp_model.serialized_model_proto()
         return state
    def __setstate__(  self					,       __lowerCamelCase	):




         '''simple docstring'''



         __A					:					Dict								=		d
         __A					:					Union[str, Any]								=		spm.SentencePieceProcessor(**self.sp_model_kwargs	)
         self.sp_model.LoadFromSerializedProto(self.sp_model_proto	)
    @property
    def 						_a							(  self	):




         '''simple docstring'''



         return self.sp_model.get_piece_size()
    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					Dict								=		{self.convert_ids_to_tokens(__lowerCamelCase	): i for i in range(self.vocab_size	)}
         vocab.update(self.added_tokens_encoder	)
         return vocab
    def 						_a							(  self					,       __lowerCamelCase					,       **__lowerCamelCase	):




         '''simple docstring'''



         if not self.legacy:
              __A					:					Optional[int]								=		SPIECE_UNDERLINE + text.replace(__lowerCamelCase					,       ' '	)
         return super().tokenize(__lowerCamelCase					,       **__lowerCamelCase	)
    def 						_a							(  self					,       __lowerCamelCase	):




         '''simple docstring'''



         if not self.legacy:
              __A					:					List[str]								=		text.startswith(__lowerCamelCase	)
              if is_first:
                   __A					:					str								=		text[1:]

         __A					:					Optional[Any]								=		self.sp_model.encode(__lowerCamelCase					,       out_type=__lowerCamelCase	)

         if not self.legacy and not is_first and not text.startswith(' '	) and tokens[0].startswith(__lowerCamelCase	):
              __A					:					List[Any]								=		([tokens[0][1:]] if len(tokens[0]	) > 1 else []) + tokens[1:]
         return tokens
    def 						_a							(  self					,       __lowerCamelCase	):




         '''simple docstring'''



         return self.sp_model.piece_to_id(__lowerCamelCase	)
    def 						_a							(  self					,       __lowerCamelCase	):




         '''simple docstring'''



         __A					:					int								=		self.sp_model.IdToPiece(__lowerCamelCase	)
         return token
    def 						_a							(  self					,       __lowerCamelCase	):




         '''simple docstring'''



         __A					:					int								=		[]
         __A					:					Optional[Any]								=		''
         __A					:					List[Any]								=		False
         for i, token in enumerate(__lowerCamelCase	):
              # 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(__lowerCamelCase	) + token
                   __A					:					Optional[int]								=		True
                   __A					:					Union[str, Any]								=		[]
              else:
                   current_sub_tokens.append(__lowerCamelCase	)
                   __A					:					str								=		False
         out_string += self.sp_model.decode(__lowerCamelCase	)
         return out_string
    def 						_a							(  self					,       __lowerCamelCase					,       __lowerCamelCase = None	):




         '''simple docstring'''



         if not os.path.isdir(__lowerCamelCase	):
              logger.error(F'Vocabulary path ({save_directory}) should be a directory'	)
              return
         __A					:					Optional[int]								=		os.path.join(
             __lowerCamelCase					,       (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']	)

         if os.path.abspath(self.vocab_file	) != os.path.abspath(__lowerCamelCase	) and os.path.isfile(self.vocab_file	):
              copyfile(self.vocab_file					,       __lowerCamelCase	)
         elif not os.path.isfile(self.vocab_file	):
              with open(__lowerCamelCase					,       'wb'	) as fi:
                   __A					:					List[str]								=		self.sp_model.serialized_model_proto()
                   fi.write(__lowerCamelCase	)

         return (out_vocab_file,)
    def 						_a							(  self					,       __lowerCamelCase					,       __lowerCamelCase=None	):




         '''simple docstring'''



         __A					:					Optional[Any]								=		[self.bos_token_id] if self.add_bos_token else []
         __A					:					Optional[int]								=		[self.eos_token_id] if self.add_eos_token else []

         __A					:					List[Any]								=		bos_token_id + token_ids_a + eos_token_id

         if token_ids_a is not None:
              __A					:					List[Any]								=		output + bos_token_id + token_ids_a + eos_token_id

         return output
    def 						_a							(  self					,       __lowerCamelCase					,       __lowerCamelCase = None					,       __lowerCamelCase = False	):




         '''simple docstring'''



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

         __A					:					int								=		[1] if self.add_bos_token else []
         __A					:					Dict								=		[1] if self.add_eos_token else []

         if token_ids_a is None:
              return bos_token_id + ([0] * len(__lowerCamelCase	)) + eos_token_id
         return (
             bos_token_id
             + ([0] * len(__lowerCamelCase	))
             + eos_token_id
             + bos_token_id
             + ([0] * len(__lowerCamelCase	))
             + eos_token_id
         )
    def 						_a							(  self					,       __lowerCamelCase					,       __lowerCamelCase = None	):




         '''simple docstring'''



         __A					:					Dict								=		[self.bos_token_id] if self.add_bos_token else []
         __A					:					Any								=		[self.eos_token_id] if self.add_eos_token else []

         __A					:					Optional[Any]								=		[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 						_a							(  self					,       __lowerCamelCase	):




         '''simple docstring'''



         __A					:					Dict								=		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...)'	)

         __A					:					List[int]								=		[]
         if len(conversation.past_user_inputs	) > 0:
              if not conversation.past_user_inputs[0].startswith(__lowerCamelCase	) or E_SYS not in conversation.past_user_inputs[0]:
                   __A					:					List[str]								=		(
                       B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + conversation.past_user_inputs[0]
                   )
         elif not dialogue[0][1].startswith(__lowerCamelCase	) or E_SYS not in dialogue[0][1]:
              __A					:					Optional[int]								=		(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=__lowerCamelCase	)
                 + [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=__lowerCamelCase	)
         return dialog_tokens




"""simple docstring"""







from typing import Dict, Optional, Tuple

import torch




def 						_lowercase				(  _SCREAMING_SNAKE_CASE				:				torch.Tensor						)    ->     torch.Tensor:







     '''simple docstring'''


     __A					:					List[str]								=		boundaries[1] - boundaries[0]
     __A					:					int								=		boundaries + step / 2
     __A					:					Union[str, Any]								=		torch.cat([bin_centers, (bin_centers[-1] + step).unsqueeze(-1						)]  ,       dim=0						)
     return bin_centers




def 						_lowercase				(  _SCREAMING_SNAKE_CASE				:				torch.Tensor  ,       _SCREAMING_SNAKE_CASE				:				torch.Tensor  ,       )    ->     Tuple[torch.Tensor, torch.Tensor]:







     '''simple docstring'''


     __A					:					str								=		_calculate_bin_centers(_SCREAMING_SNAKE_CASE						)
     return (
         torch.sum(aligned_distance_error_probs * bin_centers  ,       dim=-1						),
         bin_centers[-1],
     )




def 						_lowercase				(  _SCREAMING_SNAKE_CASE				:				torch.Tensor  ,       _SCREAMING_SNAKE_CASE				:				int = 31  ,       _SCREAMING_SNAKE_CASE				:				int = 64  ,       **_SCREAMING_SNAKE_CASE				:				Optional[Any]  ,       )    ->     Dict[str, torch.Tensor]:







     '''simple docstring'''


     __A					:					int								=		torch.linspace(0  ,       _SCREAMING_SNAKE_CASE  ,       steps=(no_bins - 1)  ,       device=logits.device						)

     __A					:					Any								=		torch.nn.functional.softmax(_SCREAMING_SNAKE_CASE  ,       dim=-1						)
     __A						,		__A					:					Tuple								=		_calculate_expected_aligned_error(
         alignment_confidence_breaks=_SCREAMING_SNAKE_CASE  ,       aligned_distance_error_probs=_SCREAMING_SNAKE_CASE  ,       )

     return {
         "aligned_confidence_probs": aligned_confidence_probs,
         "predicted_aligned_error": predicted_aligned_error,
         "max_predicted_aligned_error": max_predicted_aligned_error,
     }




def 						_lowercase				(  _SCREAMING_SNAKE_CASE				:				torch.Tensor  ,       _SCREAMING_SNAKE_CASE				:				Optional[torch.Tensor] = None  ,       _SCREAMING_SNAKE_CASE				:				int = 31  ,       _SCREAMING_SNAKE_CASE				:				int = 64  ,       _SCREAMING_SNAKE_CASE				:				float = 1E-8  ,       **_SCREAMING_SNAKE_CASE				:				Union[str, Any]  ,       )    ->     torch.Tensor:







     '''simple docstring'''


     if residue_weights is None:
          __A					:					Optional[int]								=		logits.new_ones(logits.shape[-2]						)

     __A					:					List[str]								=		torch.linspace(0  ,       _SCREAMING_SNAKE_CASE  ,       steps=(no_bins - 1)  ,       device=logits.device						)

     __A					:					Tuple								=		_calculate_bin_centers(_SCREAMING_SNAKE_CASE						)
     torch.sum(_SCREAMING_SNAKE_CASE						)
     __A					:					int								=		logits.shape[-2]
     __A					:					str								=		max(_SCREAMING_SNAKE_CASE  ,       19						)

     __A					:					Tuple								=		1.24 * (clipped_n - 15) ** (1.0 / 3) - 1.8

     __A					:					Tuple								=		torch.nn.functional.softmax(_SCREAMING_SNAKE_CASE  ,       dim=-1						)

     __A					:					List[str]								=		1.0 / (1 + (bin_centers**2) / (da**2))
     __A					:					int								=		torch.sum(probs * tm_per_bin  ,       dim=-1						)

     __A					:					Any								=		residue_weights / (eps + residue_weights.sum())
     __A					:					List[Any]								=		torch.sum(predicted_tm_term * normed_residue_mask  ,       dim=-1						)

     __A					:					int								=		per_alignment * residue_weights

     __A					:					Optional[int]								=		(weighted == torch.max(_SCREAMING_SNAKE_CASE						)).nonzero()[0]
     return per_alignment[tuple(_SCREAMING_SNAKE_CASE						)]



