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

__SCREAMING_SNAKE_CASE		:  str        =      logging.get_logger(__name__)

__SCREAMING_SNAKE_CASE		:  Tuple        =      {"""vocab_file""": """tokenizer.model"""}

__SCREAMING_SNAKE_CASE		:  int        =      {
    """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""",
    },
}
__SCREAMING_SNAKE_CASE		:  Union[str, Any]        =      {
    """hf-internal-testing/llama-tokenizer""": 2_048,
}
__SCREAMING_SNAKE_CASE		:  List[Any]        =      """▁"""

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

# fmt: off
__SCREAMING_SNAKE_CASE		:  Optional[int]        =      """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  SCREAMING_SNAKE_CASE__       (  __UpperCamelCase   ):
	lowercase__	    =							VOCAB_FILES_NAMES
	lowercase__	    =							PRETRAINED_VOCAB_FILES_MAP
	lowercase__	    =							PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
	lowercase__	    =							["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'''






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



					'''simple docstring'''






					__a       :     Union[str, Any]								=	self.__dict__.copy()
					__a       :     Optional[int]								=	None
					__a       :     Optional[Any]								=	self.sp_model.serialized_model_proto()
					return state
	def __setstate__(				self  ,    __UpperCamelCase			):



					'''simple docstring'''






					__a       :     List[Any]								=	d
					__a       :     List[Any]								=	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'''






					__a       :     Union[str, Any]								=	{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:
									__a       :     str								=	SPIECE_UNDERLINE + text.replace(UpperCAmelCase_  ,    """ """			)
					return super().tokenize(UpperCAmelCase_  ,    **UpperCAmelCase_			)
	def __lowerCamelCase    (				self  ,    __UpperCamelCase			):



					'''simple docstring'''






					if not self.legacy:
									__a       :     Any								=	text.startswith(UpperCAmelCase_			)
									if is_first:
													__a       :     str								=	text[1:]

					__a       :     Dict								=	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_			):
									__a       :     List[str]								=	([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'''






					__a       :     List[str]								=	self.sp_model.IdToPiece(UpperCAmelCase_			)
					return token
	def __lowerCamelCase    (				self  ,    __UpperCamelCase			):



					'''simple docstring'''






					__a       :     List[Any]								=	[]
					__a       :     Dict								=	""""""
					__a       :     List[Any]								=	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
													__a       :     Optional[Any]								=	True
													__a       :     str								=	[]
									else:
													current_sub_tokens.append(UpperCAmelCase_			)
													__a       :     Optional[Any]								=	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
					__a       :     str								=	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:
													__a       :     List[Any]								=	self.sp_model.serialized_model_proto()
													fi.write(UpperCAmelCase_			)

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



					'''simple docstring'''






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

					__a       :     Union[str, Any]								=	bos_token_id + token_ids_a + eos_token_id

					if token_ids_a is not None:
									__a       :     int								=	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_			)

					__a       :     Tuple								=	[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(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'''






					__a       :     Union[str, Any]								=	[self.bos_token_id] if self.add_bos_token else []
					__a       :     str								=	[self.eos_token_id] if self.add_eos_token else []

					__a       :     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  ,    __UpperCamelCase			):



					'''simple docstring'''






					__a       :     Tuple								=	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(UpperCAmelCase_			) or E_SYS not in conversation.past_user_inputs[0]:
													__a       :     Optional[int]								=	(
													    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]:
									__a       :     List[str]								=	(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




"""simple docstring"""







import os
import pickle
import unittest
from collections import UserDict, namedtuple

import torch

from accelerate.test_utils.testing import require_cuda, require_torch_min_version
from accelerate.test_utils.training import RegressionModel
from accelerate.utils import (
    convert_outputs_to_fpaa,
    extract_model_from_parallel,
    find_device,
    listify,
    patch_environment,
    recursively_apply,
    send_to_device,
)


UpperCAmelCase:  Union[str, Any]			     =				namedtuple("""ExampleNamedTuple""", """a b c""")





class   UpperCamelCase	(     unittest.TestCase       ):




	"""simple docstring"""






	def    lowerCamelCase__					(     self   ):
			_lowercase				: List[Any]     =   torch.randn(5				,2   )
			_lowercase				: List[Any]     =   torch.device("""cuda"""   ) if torch.cuda.is_available() else torch.device("""cpu"""   )

			_lowercase				: int     =   send_to_device(UpperCAmelCase_				,UpperCAmelCase_   )
			self.assertTrue(torch.equal(resulta.cpu()				,UpperCAmelCase_   )   )

			_lowercase				: int     =   send_to_device((tensor, [tensor, tensor], 1)				,UpperCAmelCase_   )
			self.assertIsInstance(UpperCAmelCase_				,UpperCAmelCase_   )
			self.assertTrue(torch.equal(resulta[0].cpu()				,UpperCAmelCase_   )   )
			self.assertIsInstance(resulta[1]				,UpperCAmelCase_   )
			self.assertTrue(torch.equal(resulta[1][0].cpu()				,UpperCAmelCase_   )   )
			self.assertTrue(torch.equal(resulta[1][1].cpu()				,UpperCAmelCase_   )   )
			self.assertEqual(resulta[2]				,1   )

			_lowercase				: Any     =   send_to_device({"""a""": tensor, """b""": [tensor, tensor], """c""": 1}				,UpperCAmelCase_   )
			self.assertIsInstance(UpperCAmelCase_				,UpperCAmelCase_   )
			self.assertTrue(torch.equal(resulta["""a"""].cpu()				,UpperCAmelCase_   )   )
			self.assertIsInstance(resulta["""b"""]				,UpperCAmelCase_   )
			self.assertTrue(torch.equal(resulta["""b"""][0].cpu()				,UpperCAmelCase_   )   )
			self.assertTrue(torch.equal(resulta["""b"""][1].cpu()				,UpperCAmelCase_   )   )
			self.assertEqual(resulta["""c"""]				,1   )

			_lowercase				: Optional[int]     =   send_to_device(ExampleNamedTuple(a=UpperCAmelCase_				,b=[tensor, tensor]				,c=1   )				,UpperCAmelCase_   )
			self.assertIsInstance(UpperCAmelCase_				,UpperCAmelCase_   )
			self.assertTrue(torch.equal(resulta.a.cpu()				,UpperCAmelCase_   )   )
			self.assertIsInstance(resulta.b				,UpperCAmelCase_   )
			self.assertTrue(torch.equal(resulta.b[0].cpu()				,UpperCAmelCase_   )   )
			self.assertTrue(torch.equal(resulta.b[1].cpu()				,UpperCAmelCase_   )   )
			self.assertEqual(resulta.c				,1   )

			_lowercase				: str     =   send_to_device(UserDict({"""a""": tensor, """b""": [tensor, tensor], """c""": 1}   )				,UpperCAmelCase_   )
			self.assertIsInstance(UpperCAmelCase_				,UpperCAmelCase_   )
			self.assertTrue(torch.equal(resulta["""a"""].cpu()				,UpperCAmelCase_   )   )
			self.assertIsInstance(resulta["""b"""]				,UpperCAmelCase_   )
			self.assertTrue(torch.equal(resulta["""b"""][0].cpu()				,UpperCAmelCase_   )   )
			self.assertTrue(torch.equal(resulta["""b"""][1].cpu()				,UpperCAmelCase_   )   )
			self.assertEqual(resulta["""c"""]				,1   )






	def    lowerCamelCase__					(     self   ):
			with self.assertRaises(UpperCAmelCase_   ) as cm:
					_lowercase				: str     =   recursively_apply(torch.tensor				,(torch.tensor(1   ), 1)				,error_on_other_type=UpperCAmelCase_   )
			self.assertEqual(
			    str(cm.exception   )				,"""Unsupported types (<class 'int'>) passed to `tensor`. Only nested list/tuple/dicts of objects that are valid for `is_torch_tensor` should be passed."""				,)






	def    lowerCamelCase__					(     self   ):
			_lowercase				: Optional[int]     =   torch.tensor([1, 2, 3, 4, 5]   )
			self.assertEqual(listify(UpperCAmelCase_   )				,[1, 2, 3, 4, 5]   )

			_lowercase				: Optional[int]     =   torch.tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]   )
			self.assertEqual(listify(UpperCAmelCase_   )				,[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]   )

			_lowercase				: Optional[Any]     =   torch.tensor([[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]], [[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]]   )
			self.assertEqual(
			    listify(UpperCAmelCase_   )				,[[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]], [[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]]   )






	def    lowerCamelCase__					(     self   ):
			with patch_environment(aa=1				,BB=2   ):
					self.assertEqual(os.environ.get("""AA"""   )				,"""1"""   )
					self.assertEqual(os.environ.get("""BB"""   )				,"""2"""   )

			self.assertNotIn("""AA"""				,os.environ   )
			self.assertNotIn("""BB"""				,os.environ   )






	def    lowerCamelCase__					(     self   ):
			_lowercase				: Optional[Any]     =   RegressionModel()
			_lowercase				: List[Any]     =   model.forward
			_lowercase				: Optional[Any]     =   convert_outputs_to_fpaa(model.forward   )
			_lowercase				: Any     =   extract_model_from_parallel(UpperCAmelCase_				,keep_fpaa_wrapper=UpperCAmelCase_   )
			_lowercase				: Tuple     =   pickle.dumps(UpperCAmelCase_   )






	@require_cuda
	def    lowerCamelCase__					(     self   ):
			_lowercase				: str     =   RegressionModel()
			_lowercase				: Any     =   model.forward
			_lowercase				: Any     =   torch.cuda.amp.autocast(dtype=torch.floataa   )(model.forward   )
			_lowercase				: Optional[Any]     =   convert_outputs_to_fpaa(model.forward   )
			_lowercase				: Any     =   extract_model_from_parallel(UpperCAmelCase_				,keep_fpaa_wrapper=UpperCAmelCase_   )
			_lowercase				: Tuple     =   pickle.dumps(UpperCAmelCase_   )






	@require_cuda
	@require_torch_min_version(version="""2.0"""   )
	def    lowerCamelCase__					(     self   ):
			_lowercase				: str     =   RegressionModel()
			_lowercase				: Any     =   model.forward
			_lowercase				: Union[str, Any]     =   torch.cuda.amp.autocast(dtype=torch.floataa   )(model.forward   )
			_lowercase				: Optional[Any]     =   convert_outputs_to_fpaa(model.forward   )
			_lowercase				: Union[str, Any]     =   torch.compile(model.forward				,backend="""inductor"""   )
			_lowercase				: Any     =   torch.randn(4				,10   ).cuda()
			_lowercase				: int     =   model(UpperCAmelCase_   )






	def    lowerCamelCase__					(     self   ):
			_lowercase				: List[str]     =   RegressionModel()
			# could also do a test with DistributedDataParallel, but difficult to run on CPU or single GPU
			_lowercase				: Any     =   torch.nn.parallel.DataParallel(UpperCAmelCase_   )
			_lowercase				: List[Any]     =   extract_model_from_parallel(UpperCAmelCase_   )

			self.assertEqual(UpperCAmelCase_				,UpperCAmelCase_   )






	@require_torch_min_version(version="""2.0"""   )
	def    lowerCamelCase__					(     self   ):
			_lowercase				: int     =   RegressionModel()
			_lowercase				: List[str]     =   torch.compile(UpperCAmelCase_   )

			# could also do a test with DistributedDataParallel, but difficult to run on CPU or single GPU
			_lowercase				: Optional[int]     =   torch.nn.parallel.DataParallel(UpperCAmelCase_   )
			_lowercase				: int     =   torch.compile(UpperCAmelCase_   )
			_lowercase				: Dict     =   extract_model_from_parallel(UpperCAmelCase_   )

			self.assertEqual(compiled_model._orig_mod				,compiled_model_unwrapped._orig_mod   )






	def    lowerCamelCase__					(     self   ):
			self.assertEqual(find_device([1, """a""", torch.tensor([1, 2, 3]   )]   )				,torch.device("""cpu"""   )   )
			self.assertEqual(find_device({"""a""": 1, """b""": torch.tensor([1, 2, 3]   )}   )				,torch.device("""cpu"""   )   )
			self.assertIsNone(find_device([1, """a"""]   )   )



