

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

a__ :	Dict						= logging.get_logger(__name__)

a__ :	Optional[int]						= {"""vocab_file""": """tokenizer.model"""}

a__ :	Union[str, Any]						= {
    """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__ :	str						= {
    """hf-internal-testing/llama-tokenizer""": 2048,
}
a__ :	Any						= """▁"""

a__ :	List[str]						= """[INST]""", """[/INST]"""
a__ :	Tuple						= """<<SYS>>\n""", """\n<</SYS>>\n\n"""

# fmt: off
a__ :	Dict						= """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     (						UpperCAmelCase__       ):
						__snake_case 			=     VOCAB_FILES_NAMES
						__snake_case 			=     PRETRAINED_VOCAB_FILES_MAP
						__snake_case 			=     PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
						__snake_case 			=     ['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_     ,							)			->						Tuple:
											__lowercase												=			{} if sp_model_kwargs is None else sp_model_kwargs
											__lowercase												=			AddedToken(lowerCamelCase__     ,							lstrip=lowerCamelCase__     ,							rstrip=lowerCamelCase__							) if isinstance(lowerCamelCase__     ,							lowerCamelCase__							) else bos_token
											__lowercase												=			AddedToken(lowerCamelCase__     ,							lstrip=lowerCamelCase__     ,							rstrip=lowerCamelCase__							) if isinstance(lowerCamelCase__     ,							lowerCamelCase__							) else eos_token
											__lowercase												=			AddedToken(lowerCamelCase__     ,							lstrip=lowerCamelCase__     ,							rstrip=lowerCamelCase__							) if isinstance(lowerCamelCase__     ,							lowerCamelCase__							) else unk_token
											__lowercase												=			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'''							)
											__lowercase												=			legacy
											__lowercase												=			vocab_file
											__lowercase												=			add_bos_token
											__lowercase												=			add_eos_token
											__lowercase												=			spm.SentencePieceProcessor(**self.sp_model_kwargs							)
											self.sp_model.Load(lowerCamelCase__							)







						def __getstate__(self							)			->						Any:
											__lowercase												=			self.__dict__.copy()
											__lowercase												=			None
											__lowercase												=			self.sp_model.serialized_model_proto()
											return state







						def __setstate__(self     ,							UpperCAmelCase_							)			->						Tuple:
											__lowercase												=			d
											__lowercase												=			spm.SentencePieceProcessor(**self.sp_model_kwargs							)
											self.sp_model.LoadFromSerializedProto(self.sp_model_proto							)







						@property
						def        _UpperCamelCase    (self							)			->						str:
											return self.sp_model.get_piece_size()







						def        _UpperCamelCase    (self							)			->						Optional[int]:
											__lowercase												=			{self.convert_ids_to_tokens(lowerCamelCase__							): i for i in range(self.vocab_size							)}
											vocab.update(self.added_tokens_encoder							)
											return vocab







						def        _UpperCamelCase    (self     ,							UpperCAmelCase_     ,							**UpperCAmelCase_							)			->						List[str]:
											# 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:
																__lowercase												=			SPIECE_UNDERLINE + text.replace(lowerCamelCase__     ,							''' '''							)
											return super().tokenize(lowerCamelCase__     ,							**lowerCamelCase__							)







						def        _UpperCamelCase    (self     ,							UpperCAmelCase_							)			->						Optional[Any]:
											if not self.legacy:
																__lowercase												=			text.startswith(lowerCamelCase__							)
																if is_first:
																					__lowercase												=			text[1:]

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







						def        _UpperCamelCase    (self     ,							UpperCAmelCase_							)			->						List[Any]:
											return self.sp_model.piece_to_id(lowerCamelCase__							)







						def        _UpperCamelCase    (self     ,							UpperCAmelCase_							)			->						str:
											__lowercase												=			self.sp_model.IdToPiece(lowerCamelCase__							)
											return token







						def        _UpperCamelCase    (self     ,							UpperCAmelCase_							)			->						Optional[Any]:
											__lowercase												=			[]
											__lowercase												=			""
											__lowercase												=			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
																					__lowercase												=			True
																					__lowercase												=			[]
																else:
																					current_sub_tokens.append(lowerCamelCase__							)
																					__lowercase												=			False
											out_string += self.sp_model.decode(lowerCamelCase__							)
											return out_string







						def        _UpperCamelCase    (self     ,							UpperCAmelCase_     ,							UpperCAmelCase_ = None							)			->						str:
											if not os.path.isdir(lowerCamelCase__							):
																logger.error(f'''Vocabulary path ({save_directory}) should be a directory'''							)
																return
											__lowercase												=			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:
																					__lowercase												=			self.sp_model.serialized_model_proto()
																					fi.write(lowerCamelCase__							)

											return (out_vocab_file,)







						def        _UpperCamelCase    (self     ,							UpperCAmelCase_     ,							UpperCAmelCase_=None							)			->						Tuple:
											__lowercase												=			[self.bos_token_id] if self.add_bos_token else []
											__lowercase												=			[self.eos_token_id] if self.add_eos_token else []

											__lowercase												=			bos_token_id + token_ids_a + eos_token_id

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

											return output







						def        _UpperCamelCase    (self     ,							UpperCAmelCase_     ,							UpperCAmelCase_ = None     ,							UpperCAmelCase_ = False							)			->						Tuple:
											if already_has_special_tokens:
																return super().get_special_tokens_mask(
																    token_ids_a=lowerCamelCase__     ,							token_ids_a=lowerCamelCase__     ,							already_has_special_tokens=lowerCamelCase__							)

											__lowercase												=			[1] if self.add_bos_token else []
											__lowercase												=			[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        _UpperCamelCase    (self     ,							UpperCAmelCase_     ,							UpperCAmelCase_ = None							)			->						Optional[Any]:
											__lowercase												=			[self.bos_token_id] if self.add_bos_token else []
											__lowercase												=			[self.eos_token_id] if self.add_eos_token else []

											__lowercase												=			[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        _UpperCamelCase    (self     ,							UpperCAmelCase_							)			->						int:
											__lowercase												=			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...)'''							)

											__lowercase												=			[]
											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]:
																					__lowercase												=			(
																					    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]:
																__lowercase												=			(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 logging
import os
import sys
from dataclasses import dataclass, field
from typing import Optional

import transformers
from transformers import (
    AutoConfig,
    AutoModelForQuestionAnswering,
    AutoTokenizer,
    DataCollatorWithPadding,
    HfArgumentParser,
    SquadDataset,
    Trainer,
    TrainingArguments,
)
from transformers import SquadDataTrainingArguments as DataTrainingArguments
from transformers.trainer_utils import is_main_process


a__ :	List[Any]						= logging.getLogger(__name__)


@dataclass
class 			_snake_case     :
						__snake_case 			=     field(
						    metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'}       )
						__snake_case 			=     field(
						    default=UpperCamelCase						,			metadata={'help': 'Pretrained config name or path if not the same as model_name'}       )
						__snake_case 			=     field(
						    default=UpperCamelCase						,			metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'}       )
						__snake_case 			=     field(default=UpperCamelCase						,			metadata={'help': 'Set this flag to use fast tokenization.'}       )
						# If you want to tweak more attributes on your tokenizer, you should do it in a distinct script,
						# or just modify its tokenizer_config.json.
						__snake_case 			=     field(
						    default=UpperCamelCase						,			metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'}						,			)





def 				__UpperCamelCase   (    )				->			Union[str, Any]:




					"""simple docstring"""



					__lowercase												=			HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)			)

					if len(sys.argv			) == 2 and sys.argv[1].endswith('''.json'''			):
										# If we pass only one argument to the script and it's the path to a json file,
										# let's parse it to get our arguments.
										__lowercase						, __lowercase						, __lowercase												=			parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]			)			)
					else:
										__lowercase						, __lowercase						, __lowercase												=			parser.parse_args_into_dataclasses()

					if (
					    os.path.exists(training_args.output_dir			)
					    and os.listdir(training_args.output_dir			)
					    and training_args.do_train
					    and not training_args.overwrite_output_dir
					):
										raise ValueError(
										    f'''Output directory ({training_args.output_dir}) already exists and is not empty. Use'''
										    ''' --overwrite_output_dir to overcome.'''			)

					# Setup logging
					logging.basicConfig(
					    format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' ,	datefmt='''%m/%d/%Y %H:%M:%S''' ,	level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN ,	)
					logger.warning(
					    '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''' ,	training_args.local_rank ,	training_args.device ,	training_args.n_gpu ,	bool(training_args.local_rank != -1			) ,	training_args.fpaa ,	)
					# Set the verbosity to info of the Transformers logger (on main process only):
					if is_main_process(training_args.local_rank			):
										transformers.utils.logging.set_verbosity_info()
										transformers.utils.logging.enable_default_handler()
										transformers.utils.logging.enable_explicit_format()
					logger.info('''Training/evaluation parameters %s''' ,	a__			)

					# Prepare Question-Answering task
					# Load pretrained model and tokenizer
					#
					# Distributed training:
					# The .from_pretrained methods guarantee that only one local process can concurrently
					# download model & vocab.

					__lowercase												=			AutoConfig.from_pretrained(
					    model_args.config_name if model_args.config_name else model_args.model_name_or_path ,	cache_dir=model_args.cache_dir ,	)
					__lowercase												=			AutoTokenizer.from_pretrained(
					    model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path ,	cache_dir=model_args.cache_dir ,	use_fast=a__ ,	)
					__lowercase												=			AutoModelForQuestionAnswering.from_pretrained(
					    model_args.model_name_or_path ,	from_tf=bool('''.ckpt''' in model_args.model_name_or_path			) ,	config=a__ ,	cache_dir=model_args.cache_dir ,	)

					# Get datasets
					__lowercase												=			hasattr(model.config ,	'''lang2id'''			)
					__lowercase												=			(
					    SquadDataset(
					        a__ ,	tokenizer=a__ ,	is_language_sensitive=a__ ,	cache_dir=model_args.cache_dir			)
					    if training_args.do_train
					    else None
					)
					__lowercase												=			(
					    SquadDataset(
					        a__ ,	tokenizer=a__ ,	mode='''dev''' ,	is_language_sensitive=a__ ,	cache_dir=model_args.cache_dir ,	)
					    if training_args.do_eval
					    else None
					)

					# Data collator
					__lowercase												=			DataCollatorWithPadding(a__ ,	pad_to_multiple_of=8			) if training_args.fpaa else None

					# Initialize our Trainer
					__lowercase												=			Trainer(
					    model=a__ ,	args=a__ ,	train_dataset=a__ ,	eval_dataset=a__ ,	data_collator=a__ ,	)

					# Training
					if training_args.do_train:
										trainer.train(
										    model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path			) else None			)
										trainer.save_model()
										# For convenience, we also re-save the tokenizer to the same directory,
										# so that you can share your model easily on huggingface.co/models =)
										if trainer.is_world_master():
															tokenizer.save_pretrained(training_args.output_dir			)





def 				__UpperCamelCase   (    a__: Any			)				->			Any:




					"""simple docstring"""



					main()


if __name__ == "__main__":
							main()


