





'''simple docstring'''







import importlib
import importlib.metadata
import os
import warnings
from distutils.util import strtobool
from functools import lru_cache

import torch
from packaging import version
from packaging.version import parse

from .environment import parse_flag_from_env
from .versions import compare_versions, is_torch_version


try:
					import torch_xla.core.xla_model as xm  # noqa: F401

					snake_case_  :							Union[str, Any]            =	True
except ImportError:
					snake_case_  :							List[str]            =	False


# Cache this result has it's a C FFI call which can be pretty time-consuming
snake_case_  :							Dict            =	torch.distributed.is_available()





def 							lowerCamelCase_   (	SCREAMING_SNAKE_CASE__   :      int )			->						Tuple:
						# Check we're not importing a "pkg_name" directory somewhere but the actual library by trying to grab the version
						UpperCAmelCase_      :   Optional[int]      =	importlib.util.find_spec(SCREAMING_SNAKE_CASE__ ) is not None
						if package_exists:
												try:
																		UpperCAmelCase_      :   Tuple      =	importlib.metadata.metadata(SCREAMING_SNAKE_CASE__ )
																		return True
												except importlib.metadata.PackageNotFoundError:
																		return False





def 							lowerCamelCase_   (	)			->						bool:
						return _torch_distributed_available





def 							lowerCamelCase_   (	)			->						Any:
						try:
												pass
						except ImportError:
												print(
												    '''Intel(R) oneCCL Bindings for PyTorch* is required to run DDP on Intel(R) GPUs, but it is not'''
												    ''' detected. If you see \"ValueError: Invalid backend: \'ccl\'\" error, please install Intel(R) oneCCL'''
												    ''' Bindings for PyTorch*.''' )
						return (
						    importlib.util.find_spec('''torch_ccl''' ) is not None
						    or importlib.util.find_spec('''oneccl_bindings_for_pytorch''' ) is not None
						)





def 							lowerCamelCase_   (	)			->						Tuple:
						return importlib.metadata.version('''oneccl_bind_pt''' )





def 							lowerCamelCase_   (	)			->						int:
						return _is_package_available('''transformer_engine''' )





@lru_cache
def 							lowerCamelCase_   (	SCREAMING_SNAKE_CASE__   :      Optional[int]=True )			->						Dict:
						# Due to bugs on the amp series GPUs, we disable torch-xla on them
						if torch.cuda.is_available():
												return False
						if _tpu_available and check_device:
												try:
																		# Will raise a RuntimeError if no XLA configuration is found
																		UpperCAmelCase_      :   List[str]      =	xm.xla_device()
																		return True
												except RuntimeError:
																		return False
						return _tpu_available





def 							lowerCamelCase_   (	)			->						List[Any]:
						return _is_package_available('''deepspeed''' )





def 							lowerCamelCase_   (	SCREAMING_SNAKE_CASE__   :      Optional[Any]=False )			->						Union[str, Any]:
						if is_tpu_available():
												return not ignore_tpu
						if torch.cuda.is_available():
												return torch.cuda.is_bfaa_supported()
						if is_npu_available():
												return False
						return True





def 							lowerCamelCase_   (	)			->						Tuple:
						UpperCAmelCase_      :   List[str]      =	_is_package_available('''bitsandbytes''' )
						if package_exists:
												UpperCAmelCase_      :   Optional[int]      =	version.parse(importlib.metadata.version('''bitsandbytes''' ) )
												return compare_versions(SCREAMING_SNAKE_CASE__,      '''>=''',      '''0.39.0''' )
						return False





def 							lowerCamelCase_   (	)			->						Union[str, Any]:
						UpperCAmelCase_      :   List[Any]      =	_is_package_available('''bitsandbytes''' )
						if package_exists:
												UpperCAmelCase_      :   Any      =	version.parse(importlib.metadata.version('''bitsandbytes''' ) )
												return compare_versions(SCREAMING_SNAKE_CASE__,      '''>=''',      '''0.37.2''' )
						return False





def 							lowerCamelCase_   (	)			->						int:
						return _is_package_available('''bitsandbytes''' )





def 							lowerCamelCase_   (	)			->						Optional[int]:
						if strtobool(os.environ.get('''ACCELERATE_USE_MEGATRON_LM''',      '''False''' ) ) == 1:
												UpperCAmelCase_      :   Dict      =	importlib.util.find_spec('''megatron''' ) is not None
												if package_exists:
																		try:
																								UpperCAmelCase_      :   List[str]      =	parse(importlib.metadata.version('''megatron-lm''' ) )
																								return compare_versions(SCREAMING_SNAKE_CASE__,      '''>=''',      '''2.2.0''' )
																		except Exception as e:
																								warnings.warn(F"""Parse Megatron version failed. Exception:{e}""" )
																								return False





def 							lowerCamelCase_   (	)			->						Dict:
						return _is_package_available('''safetensors''' )





def 							lowerCamelCase_   (	)			->						List[str]:
						return _is_package_available('''transformers''' )





def 							lowerCamelCase_   (	)			->						str:
						return _is_package_available('''datasets''' )





def 							lowerCamelCase_   (	)			->						Any:
						return _is_package_available('''aim''' )





def 							lowerCamelCase_   (	)			->						List[Any]:
						return _is_package_available('''tensorboard''' ) or _is_package_available('''tensorboardX''' )





def 							lowerCamelCase_   (	)			->						Tuple:
						return _is_package_available('''wandb''' )





def 							lowerCamelCase_   (	)			->						Any:
						return _is_package_available('''comet_ml''' )





def 							lowerCamelCase_   (	)			->						List[Any]:
						return _is_package_available('''boto3''' )





def 							lowerCamelCase_   (	)			->						Union[str, Any]:
						if _is_package_available('''rich''' ):
												if "ACCELERATE_DISABLE_RICH" in os.environ:
																		warnings.warn(
																		    '''`ACCELERATE_DISABLE_RICH` is deprecated and will be removed in v0.22.0 and deactivated by default. Please use `ACCELERATE_ENABLE_RICH` if you wish to use `rich`.''' )
																		return not parse_flag_from_env('''ACCELERATE_DISABLE_RICH''',      SCREAMING_SNAKE_CASE__ )
												return parse_flag_from_env('''ACCELERATE_ENABLE_RICH''',      SCREAMING_SNAKE_CASE__ )
						return False





def 							lowerCamelCase_   (	)			->						Union[str, Any]:
						return _is_package_available('''sagemaker''' )





def 							lowerCamelCase_   (	)			->						List[Any]:
						return _is_package_available('''tqdm''' )





def 							lowerCamelCase_   (	)			->						List[Any]:
						return _is_package_available('''mlflow''' )





def 							lowerCamelCase_   (	)			->						Union[str, Any]:
						return is_torch_version('''>=''',      '''1.12''' ) and torch.backends.mps.is_available() and torch.backends.mps.is_built()





def 							lowerCamelCase_   (	)			->						Union[str, Any]:
						def get_major_and_minor_from_version(SCREAMING_SNAKE_CASE__   :      str ):
												return str(version.parse(SCREAMING_SNAKE_CASE__ ).major ) + "." + str(version.parse(SCREAMING_SNAKE_CASE__ ).minor )

						UpperCAmelCase_      :   List[Any]      =	importlib.metadata.version('''torch''' )
						if importlib.util.find_spec('''intel_extension_for_pytorch''' ) is None:
												return False
						UpperCAmelCase_      :   Dict      =	'''N/A'''
						try:
												UpperCAmelCase_      :   Union[str, Any]      =	importlib.metadata.version('''intel_extension_for_pytorch''' )
						except importlib.metadata.PackageNotFoundError:
												return False
						UpperCAmelCase_      :   List[str]      =	get_major_and_minor_from_version(_torch_version )
						UpperCAmelCase_      :   str      =	get_major_and_minor_from_version(_ipex_version )
						if torch_major_and_minor != ipex_major_and_minor:
												warnings.warn(
												    F"""Intel Extension for PyTorch {ipex_major_and_minor} needs to work with PyTorch {ipex_major_and_minor}.*,"""
												    F""" but PyTorch {_torch_version} is found. Please switch to the matching version and run again.""" )
												return False
						return True





@lru_cache
def 							lowerCamelCase_   (	SCREAMING_SNAKE_CASE__   :      Dict=False )			->						Any:
						if importlib.util.find_spec('''torch''' ) is None or importlib.util.find_spec('''torch_npu''' ) is None:
												return False

						import torch
						import torch_npu  # noqa: F401

						if check_device:
												try:
																		# Will raise a RuntimeError if no NPU is found
																		UpperCAmelCase_      :   List[str]      =	torch.npu.device_count()
																		return torch.npu.is_available()
												except RuntimeError:
																		return False
						return hasattr(SCREAMING_SNAKE_CASE__,      '''npu''' ) and torch.npu.is_available()





@lru_cache
def 							lowerCamelCase_   (	SCREAMING_SNAKE_CASE__   :      List[Any]=False )			->						int:
						if not parse_flag_from_env('''ACCELERATE_USE_XPU''',      default=SCREAMING_SNAKE_CASE__ ):
												return False
						if is_ipex_available():
												import torch

												if is_torch_version('''<=''',      '''1.12''' ):
																		return False
						else:
												return False

						import intel_extension_for_pytorch  # noqa: F401

						if check_device:
												try:
																		# Will raise a RuntimeError if no XPU  is found
																		UpperCAmelCase_      :   Optional[int]      =	torch.xpu.device_count()
																		return torch.xpu.is_available()
												except RuntimeError:
																		return False
						return hasattr(SCREAMING_SNAKE_CASE__,      '''xpu''' ) and torch.xpu.is_available()













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': 2048,
}
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\\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 				__a				(	__A    ):





		'''simple docstring'''



		UpperCAmelCase__   :					Optional[int]					     =    VOCAB_FILES_NAMES
		UpperCAmelCase__   :					Dict					     =    PRETRAINED_VOCAB_FILES_MAP
		UpperCAmelCase__   :					int					     =    PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
		UpperCAmelCase__   :					Union[str, Any]					     =    ["""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__			,     ):
						SCREAMING_SNAKE_CASE_ :						str    				= {} if sp_model_kwargs is None else sp_model_kwargs
						SCREAMING_SNAKE_CASE_ :						Optional[int]    				= AddedToken(UpperCamelCase__			,     lstrip=UpperCamelCase__			,     rstrip=UpperCamelCase__							) if isinstance(UpperCamelCase__			,     UpperCamelCase__							) else bos_token
						SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= AddedToken(UpperCamelCase__			,     lstrip=UpperCamelCase__			,     rstrip=UpperCamelCase__							) if isinstance(UpperCamelCase__			,     UpperCamelCase__							) else eos_token
						SCREAMING_SNAKE_CASE_ :						str    				= AddedToken(UpperCamelCase__			,     lstrip=UpperCamelCase__			,     rstrip=UpperCamelCase__							) if isinstance(UpperCamelCase__			,     UpperCamelCase__							) else unk_token
						SCREAMING_SNAKE_CASE_ :						int    				= 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'							)
						SCREAMING_SNAKE_CASE_ :						List[Any]    				= legacy
						SCREAMING_SNAKE_CASE_ :						Dict    				= vocab_file
						SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= add_bos_token
						SCREAMING_SNAKE_CASE_ :						Union[str, Any]    				= add_eos_token
						SCREAMING_SNAKE_CASE_ :						Any    				= spm.SentencePieceProcessor(**self.sp_model_kwargs							)
						self.sp_model.Load(UpperCamelCase__							)


		def __getstate__(    self							):
						SCREAMING_SNAKE_CASE_ :						List[str]    				= self.__dict__.copy()
						SCREAMING_SNAKE_CASE_ :						List[Any]    				= None
						SCREAMING_SNAKE_CASE_ :						Any    				= self.sp_model.serialized_model_proto()
						return state


		def __setstate__(    self			,     UpperCamelCase__							):
						SCREAMING_SNAKE_CASE_ :						str    				= d
						SCREAMING_SNAKE_CASE_ :						str    				= spm.SentencePieceProcessor(**self.sp_model_kwargs							)
						self.sp_model.LoadFromSerializedProto(self.sp_model_proto							)


		@property
		def 	__snake_case      (    self							):
						return self.sp_model.get_piece_size()


		def 	__snake_case      (    self							):
						SCREAMING_SNAKE_CASE_ :						Tuple    				= {self.convert_ids_to_tokens(UpperCamelCase__							): i for i in range(self.vocab_size							)}
						vocab.update(self.added_tokens_encoder							)
						return vocab


		def 	__snake_case      (    self			,     UpperCamelCase__			,     **UpperCamelCase__							):
						# Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at
						# the beginning of the text
						if not self.legacy:
										SCREAMING_SNAKE_CASE_ :						List[str]    				= SPIECE_UNDERLINE + text.replace(UpperCamelCase__			,     ' '							)
						return super().tokenize(UpperCamelCase__			,     **UpperCamelCase__							)


		def 	__snake_case      (    self			,     UpperCamelCase__							):
						if not self.legacy:
										SCREAMING_SNAKE_CASE_ :						Any    				= text.startswith(UpperCamelCase__							)
										if is_first:
														SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= text[1:]

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


		def 	__snake_case      (    self			,     UpperCamelCase__							):
						return self.sp_model.piece_to_id(UpperCamelCase__							)


		def 	__snake_case      (    self			,     UpperCamelCase__							):
						SCREAMING_SNAKE_CASE_ :						Optional[int]    				= self.sp_model.IdToPiece(UpperCamelCase__							)
						return token


		def 	__snake_case      (    self			,     UpperCamelCase__							):
						SCREAMING_SNAKE_CASE_ :						List[str]    				= []
						SCREAMING_SNAKE_CASE_ :						int    				= ''
						SCREAMING_SNAKE_CASE_ :						List[str]    				= 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
														SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= True
														SCREAMING_SNAKE_CASE_ :						str    				= []
										else:
														current_sub_tokens.append(UpperCamelCase__							)
														SCREAMING_SNAKE_CASE_ :						int    				= False
						out_string += self.sp_model.decode(UpperCamelCase__							)
						return out_string


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

						return (out_vocab_file,)


		def 	__snake_case      (    self			,     UpperCamelCase__			,     UpperCamelCase__=None							):
						SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= [self.bos_token_id] if self.add_bos_token else []
						SCREAMING_SNAKE_CASE_ :						List[str]    				= [self.eos_token_id] if self.add_eos_token else []

						SCREAMING_SNAKE_CASE_ :						int    				= bos_token_id + token_ids_a + eos_token_id

						if token_ids_a is not None:
										SCREAMING_SNAKE_CASE_ :						int    				= output + bos_token_id + token_ids_a + eos_token_id

						return output


		def 	__snake_case      (    self			,     UpperCamelCase__			,     UpperCamelCase__ = None			,     UpperCamelCase__ = False							):
						if already_has_special_tokens:
										return super().get_special_tokens_mask(
										    token_ids_a=UpperCamelCase__			,     token_ids_a=UpperCamelCase__			,     already_has_special_tokens=UpperCamelCase__							)

						SCREAMING_SNAKE_CASE_ :						Union[str, Any]    				= [1] if self.add_bos_token else []
						SCREAMING_SNAKE_CASE_ :						Union[str, Any]    				= [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 	__snake_case      (    self			,     UpperCamelCase__			,     UpperCamelCase__ = None							):
						SCREAMING_SNAKE_CASE_ :						Any    				= [self.bos_token_id] if self.add_bos_token else []
						SCREAMING_SNAKE_CASE_ :						Tuple    				= [self.eos_token_id] if self.add_eos_token else []

						SCREAMING_SNAKE_CASE_ :						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 	__snake_case      (    self			,     UpperCamelCase__							):
						SCREAMING_SNAKE_CASE_ :						int    				= 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...)'							)

						SCREAMING_SNAKE_CASE_ :						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]:
														SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= (
														    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]:
										SCREAMING_SNAKE_CASE_ :						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=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