


'''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__     						=  logging.get_logger(__name__)

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

lowerCamelCase__     						=  {
    '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__     						=  {
    'hf-internal-testing/llama-tokenizer': 2_048,
}
lowerCamelCase__     						=  '▁'

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

# fmt: off
lowerCamelCase__     						=  'You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your\\nanswers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\\nthat your responses are socially unbiased and positive in nature.\n\nIf a question does not make any sense, or is not factually coherent, explain why instead of answering something not\\ncorrect. If you don\'t know the answer to a question, please don\'t share false information.'






class 						lowerCAmelCase__      (      UpperCAmelCase__						):
			lowerCAmelCase			:						List[str]							 =  VOCAB_FILES_NAMES
			lowerCAmelCase			:						Union[str, Any]							 =  PRETRAINED_VOCAB_FILES_MAP
			lowerCAmelCase			:						Optional[Any]							 =  PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
			lowerCAmelCase			:						List[Any]							 =  ["input_ids", "attention_mask"]




			def __init__(		self	:  List[Any]						,	lowerCamelCase__	:  Union[str, Any]						,	lowerCamelCase__	:  List[Any]="<unk>"						,	lowerCamelCase__	:  Dict="<s>"						,	lowerCamelCase__	:  Tuple="</s>"						,	lowerCamelCase__	:  Tuple=None						,	lowerCamelCase__	:  Optional[Dict[str, Any]] = None						,	lowerCamelCase__	:  Dict=True						,	lowerCamelCase__	:  List[str]=False						,	lowerCamelCase__	:  List[str]=False						,	lowerCamelCase__	:  Dict=True						,	**lowerCamelCase__	:  Optional[int]						,	) ->Any:



					'''simple docstring'''







					_UpperCAmelCase		:							List[str]             =   {} if sp_model_kwargs is None else sp_model_kwargs
					_UpperCAmelCase		:							Any             =   AddedToken(lowerCamelCase__						,	lstrip=lowerCamelCase__						,	rstrip=lowerCamelCase__			) if isinstance(lowerCamelCase__						,	lowerCamelCase__			) else bos_token
					_UpperCAmelCase		:							Any             =   AddedToken(lowerCamelCase__						,	lstrip=lowerCamelCase__						,	rstrip=lowerCamelCase__			) if isinstance(lowerCamelCase__						,	lowerCamelCase__			) else eos_token
					_UpperCAmelCase		:							List[str]             =   AddedToken(lowerCamelCase__						,	lstrip=lowerCamelCase__						,	rstrip=lowerCamelCase__			) if isinstance(lowerCamelCase__						,	lowerCamelCase__			) else unk_token
					_UpperCAmelCase		:							Optional[int]             =   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"			)
					_UpperCAmelCase		:							int             =   legacy
					_UpperCAmelCase		:							Optional[int]             =   vocab_file
					_UpperCAmelCase		:							str             =   add_bos_token
					_UpperCAmelCase		:							Tuple             =   add_eos_token
					_UpperCAmelCase		:							int             =   spm.SentencePieceProcessor(**self.sp_model_kwargs			)
					self.sp_model.Load(lowerCamelCase__			)




			def __getstate__(		self	:  Optional[int]			) ->List[Any]:



					'''simple docstring'''







					_UpperCAmelCase		:							List[str]             =   self.__dict__.copy()
					_UpperCAmelCase		:							Dict             =   None
					_UpperCAmelCase		:							Any             =   self.sp_model.serialized_model_proto()
					return state




			def __setstate__(		self	:  Optional[Any]						,	lowerCamelCase__	:  Tuple			) ->int:



					'''simple docstring'''







					_UpperCAmelCase		:							Optional[int]             =   d
					_UpperCAmelCase		:							Any             =   spm.SentencePieceProcessor(**self.sp_model_kwargs			)
					self.sp_model.LoadFromSerializedProto(self.sp_model_proto			)




			@property
			def 				lowerCAmelCase__     (		self	:  Union[str, Any]			) ->Optional[int]:



					'''simple docstring'''







					return self.sp_model.get_piece_size()




			def 				lowerCAmelCase__     (		self	:  Optional[Any]			) ->List[str]:



					'''simple docstring'''







					_UpperCAmelCase		:							Dict             =   {self.convert_ids_to_tokens(lowerCamelCase__			): i for i in range(self.vocab_size			)}
					vocab.update(self.added_tokens_encoder			)
					return vocab




			def 				lowerCAmelCase__     (		self	:  int						,	lowerCamelCase__	:  List[Any]						,	**lowerCamelCase__	:  Any			) ->List[str]:



					'''simple docstring'''







					if not self.legacy:
							_UpperCAmelCase		:							List[str]             =   SPIECE_UNDERLINE + text.replace(lowerCamelCase__						,	" "			)
					return super().tokenize(lowerCamelCase__						,	**lowerCamelCase__			)




			def 				lowerCAmelCase__     (		self	:  Any						,	lowerCamelCase__	:  Optional[Any]			) ->List[Any]:



					'''simple docstring'''







					if not self.legacy:
							_UpperCAmelCase		:							str             =   text.startswith(lowerCamelCase__			)
							if is_first:
									_UpperCAmelCase		:							Dict             =   text[1:]

					_UpperCAmelCase		:							Dict             =   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__			):
							_UpperCAmelCase		:							Tuple             =   ([tokens[0][1:]] if len(tokens[0]			) > 1 else []) + tokens[1:]
					return tokens




			def 				lowerCAmelCase__     (		self	:  int						,	lowerCamelCase__	:  Any			) ->Optional[Any]:



					'''simple docstring'''







					return self.sp_model.piece_to_id(lowerCamelCase__			)




			def 				lowerCAmelCase__     (		self	:  List[str]						,	lowerCamelCase__	:  List[Any]			) ->Optional[int]:



					'''simple docstring'''







					_UpperCAmelCase		:							List[Any]             =   self.sp_model.IdToPiece(lowerCamelCase__			)
					return token




			def 				lowerCAmelCase__     (		self	:  List[str]						,	lowerCamelCase__	:  int			) ->Dict:



					'''simple docstring'''







					_UpperCAmelCase		:							Any             =   []
					_UpperCAmelCase		:							Dict             =   ""
					_UpperCAmelCase		:							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
									_UpperCAmelCase		:							int             =   True
									_UpperCAmelCase		:							Any             =   []
							else:
									current_sub_tokens.append(lowerCamelCase__			)
									_UpperCAmelCase		:							Dict             =   False
					out_string += self.sp_model.decode(lowerCamelCase__			)
					return out_string




			def 				lowerCAmelCase__     (		self	:  List[str]						,	lowerCamelCase__	:  Any						,	lowerCamelCase__	:  Optional[str] = None			) ->Tuple[str]:



					'''simple docstring'''







					if not os.path.isdir(lowerCamelCase__			):
							logger.error(F"""Vocabulary path ({save_directory}) should be a directory"""			)
							return
					_UpperCAmelCase		:							str             =   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:
									_UpperCAmelCase		:							Union[str, Any]             =   self.sp_model.serialized_model_proto()
									fi.write(lowerCamelCase__			)

					return (out_vocab_file,)




			def 				lowerCAmelCase__     (		self	:  Tuple						,	lowerCamelCase__	:  Union[str, Any]						,	lowerCamelCase__	:  Optional[int]=None			) ->Any:



					'''simple docstring'''







					_UpperCAmelCase		:							str             =   [self.bos_token_id] if self.add_bos_token else []
					_UpperCAmelCase		:							List[str]             =   [self.eos_token_id] if self.add_eos_token else []

					_UpperCAmelCase		:							int             =   bos_token_id + token_ids_a + eos_token_id

					if token_ids_a is not None:
							_UpperCAmelCase		:							Dict             =   output + bos_token_id + token_ids_a + eos_token_id

					return output




			def 				lowerCAmelCase__     (		self	:  Dict						,	lowerCamelCase__	:  List[int]						,	lowerCamelCase__	:  Optional[List[int]] = None						,	lowerCamelCase__	:  bool = False			) ->List[int]:



					'''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__			)

					_UpperCAmelCase		:							Optional[int]             =   [1] if self.add_bos_token else []
					_UpperCAmelCase		:							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 				lowerCAmelCase__     (		self	:  str						,	lowerCamelCase__	:  List[int]						,	lowerCamelCase__	:  Optional[List[int]] = None			) ->List[int]:



					'''simple docstring'''







					_UpperCAmelCase		:							List[str]             =   [self.bos_token_id] if self.add_bos_token else []
					_UpperCAmelCase		:							int             =   [self.eos_token_id] if self.add_eos_token else []

					_UpperCAmelCase		:							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 				lowerCAmelCase__     (		self	:  Union[str, Any]						,	lowerCamelCase__	:  "Conversation"			) ->List[int]:



					'''simple docstring'''







					_UpperCAmelCase		:							str             =   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		:							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]:
									_UpperCAmelCase		:							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]:
							_UpperCAmelCase		:							Tuple             =   (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'''


import torch
from torch import autograd






class 						lowerCAmelCase__      (      autograd.Function						):




			@staticmethod
			def 				lowerCAmelCase__     (		lowerCamelCase__	:  Optional[int]						,	lowerCamelCase__	:  torch.tensor						,	lowerCamelCase__	:  float						,	lowerCamelCase__	:  bool			) ->Optional[Any]:



					'''simple docstring'''







					_UpperCAmelCase		:							Optional[int]             =   inputs.numel()
					_UpperCAmelCase		:							Any             =   int(0.0_0_5 * nb_elems			) + 1
					if sigmoid:
							_UpperCAmelCase		:							List[str]             =   (torch.sigmoid(lowerCamelCase__			) > threshold).type(inputs.type()			)
					else:
							_UpperCAmelCase		:							List[Any]             =   (inputs > threshold).type(inputs.type()			)
					if mask.sum() < nb_min:
							# We limit the pruning so that at least 0.5% (half a percent) of the weights are remaining
							_UpperCAmelCase		:							str             =   inputs.flatten().kthvalue(max(nb_elems - nb_min						,	1			)			).values
							_UpperCAmelCase		:							str             =   (inputs > k_threshold).type(inputs.type()			)
					return mask






			@staticmethod
			def 				lowerCAmelCase__     (		lowerCamelCase__	:  List[Any]						,	lowerCamelCase__	:  Optional[int]			) ->Dict:



					'''simple docstring'''







					return gradOutput, None, None






class 						lowerCAmelCase__      (      autograd.Function						):




			@staticmethod
			def 				lowerCAmelCase__     (		lowerCamelCase__	:  Optional[int]						,	lowerCamelCase__	:  torch.tensor						,	lowerCamelCase__	:  float			) ->List[str]:



					'''simple docstring'''







					_UpperCAmelCase		:							Optional[int]             =   inputs.clone()
					_UpperCAmelCase       ,     _UpperCAmelCase		:							Tuple             =   inputs.flatten().sort(descending=lowerCamelCase__			)
					_UpperCAmelCase		:							Optional[int]             =   int(threshold * inputs.numel()			)

					# flat_out and mask access the same memory.
					_UpperCAmelCase		:							str             =   mask.flatten()
					_UpperCAmelCase		:							Optional[int]             =   0
					_UpperCAmelCase		:							Optional[Any]             =   1
					return mask






			@staticmethod
			def 				lowerCAmelCase__     (		lowerCamelCase__	:  Optional[int]						,	lowerCamelCase__	:  Any			) ->Union[str, Any]:



					'''simple docstring'''







					return gradOutput, None






class 						lowerCAmelCase__      (      UpperCAmelCase__						):




			@staticmethod
			def 				lowerCAmelCase__     (		lowerCamelCase__	:  torch.tensor						,	lowerCamelCase__	:  float			) ->Tuple:



					'''simple docstring'''







					_UpperCAmelCase		:							List[Any]             =   inputs.clone()
					_UpperCAmelCase       ,     _UpperCAmelCase		:							Optional[Any]             =   inputs.abs().flatten().sort(descending=lowerCamelCase__			)
					_UpperCAmelCase		:							int             =   int(threshold * inputs.numel()			)

					# flat_out and mask access the same memory.
					_UpperCAmelCase		:							int             =   mask.flatten()
					_UpperCAmelCase		:							List[Any]             =   0
					_UpperCAmelCase		:							int             =   1
					return mask



