






"""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__       :			int=						logging.getLogger(__name__)
@dataclass
class  __lowerCamelCase     :
   a   :					str			    =field(
       metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}	)
   a   :					Union[str, Any]			    =field(
       default=_a				,						metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}	)
   a   :					List[str]			    =field(
       default=_a				,						metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""}	)
   a   :					Union[str, Any]			    =field(default=_a				,						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.
   a   :					Dict			    =field(
       default=_a				,						metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}				,						)







def 	lowerCAmelCase_(			)       ->						List[Any]:
    """simple docstring"""

    UpperCamelCase__								=     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.
        UpperCamelCase__							,    UpperCamelCase__							,    UpperCamelCase__								=     parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]       )       )
    else:
        UpperCamelCase__							,    UpperCamelCase__							,    UpperCamelCase__								=     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'			,						SCREAMING_SNAKE_CASE       )

    # 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.

    UpperCamelCase__								=     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			,						)
    UpperCamelCase__								=     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=SCREAMING_SNAKE_CASE			,						)
    UpperCamelCase__								=     AutoModelForQuestionAnswering.from_pretrained(
        model_args.model_name_or_path			,						from_tf=bool('.ckpt' in model_args.model_name_or_path       )			,						config=SCREAMING_SNAKE_CASE			,						cache_dir=model_args.cache_dir			,						)

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

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

    # Initialize our Trainer
    UpperCamelCase__								=     Trainer(
        model=SCREAMING_SNAKE_CASE			,						args=SCREAMING_SNAKE_CASE			,						train_dataset=SCREAMING_SNAKE_CASE			,						eval_dataset=SCREAMING_SNAKE_CASE			,						data_collator=SCREAMING_SNAKE_CASE			,						)

    # 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 	lowerCAmelCase_(			SCREAMING_SNAKE_CASE       )       ->						List[Any]:
    """simple docstring"""

    main()


if __name__ == "__main__":
  main()





"""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_:       Optional[Any]			     =       logging.get_logger(__name__)

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

lowerCAmelCase_:       Optional[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",
    },
}
lowerCAmelCase_:       Optional[int]			     =       {
    "hf-internal-testing/llama-tokenizer": 2_0_4_8,
}
lowerCAmelCase_:       str			     =       "▁"

lowerCAmelCase_     ,				lowerCAmelCase_:       str			     =       "[INST]", "[/INST]"
lowerCAmelCase_     ,				lowerCAmelCase_:       Dict			     =       "<<SYS>>\n", "\n<</SYS>>\n\n"

# fmt: off
lowerCAmelCase_:       List[Any]			     =       "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						):
   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,					):
        '''simple docstring'''



        lowercase__								=				{} if sp_model_kwargs is None else sp_model_kwargs
        lowercase__								=				AddedToken(_UpperCAmelCase,					lstrip=_UpperCAmelCase,					rstrip=_UpperCAmelCase	) if isinstance(_UpperCAmelCase,					_UpperCAmelCase	) else bos_token
        lowercase__								=				AddedToken(_UpperCAmelCase,					lstrip=_UpperCAmelCase,					rstrip=_UpperCAmelCase	) if isinstance(_UpperCAmelCase,					_UpperCAmelCase	) else eos_token
        lowercase__								=				AddedToken(_UpperCAmelCase,					lstrip=_UpperCAmelCase,					rstrip=_UpperCAmelCase	) if isinstance(_UpperCAmelCase,					_UpperCAmelCase	) else unk_token
        lowercase__								=				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"	)
        lowercase__								=				legacy
        lowercase__								=				vocab_file
        lowercase__								=				add_bos_token
        lowercase__								=				add_eos_token
        lowercase__								=				spm.SentencePieceProcessor(**self.sp_model_kwargs	)
        self.sp_model.Load(_UpperCAmelCase	)


   def __getstate__(  self	):
        '''simple docstring'''



        lowercase__								=				self.__dict__.copy()
        lowercase__								=				None
        lowercase__								=				self.sp_model.serialized_model_proto()
        return state


   def __setstate__(  self,					_UpperCAmelCase	):
        '''simple docstring'''



        lowercase__								=				d
        lowercase__								=				spm.SentencePieceProcessor(**self.sp_model_kwargs	)
        self.sp_model.LoadFromSerializedProto(self.sp_model_proto	)


   @property
   def 						snake_case__						(  self	):
        '''simple docstring'''



        return self.sp_model.get_piece_size()


   def 						snake_case__						(  self	):
        '''simple docstring'''



        lowercase__								=				{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	):
        '''simple docstring'''



        if not self.legacy:
             lowercase__								=				SPIECE_UNDERLINE + text.replace(_UpperCAmelCase,					" "	)
        return super().tokenize(_UpperCAmelCase,					**_UpperCAmelCase	)


   def 						snake_case__						(  self,					_UpperCAmelCase	):
        '''simple docstring'''



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

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


   def 						snake_case__						(  self,					_UpperCAmelCase	):
        '''simple docstring'''



        return self.sp_model.piece_to_id(_UpperCAmelCase	)


   def 						snake_case__						(  self,					_UpperCAmelCase	):
        '''simple docstring'''



        lowercase__								=				self.sp_model.IdToPiece(_UpperCAmelCase	)
        return token


   def 						snake_case__						(  self,					_UpperCAmelCase	):
        '''simple docstring'''



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


   def 						snake_case__						(  self,					_UpperCAmelCase,					_UpperCAmelCase = None	):
        '''simple docstring'''



        if not os.path.isdir(_UpperCAmelCase	):
             logger.error(F'''Vocabulary path ({save_directory}) should be a directory'''	)
             return
        lowercase__								=				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:
                  lowercase__								=				self.sp_model.serialized_model_proto()
                  fi.write(_UpperCAmelCase	)

        return (out_vocab_file,)


   def 						snake_case__						(  self,					_UpperCAmelCase,					_UpperCAmelCase=None	):
        '''simple docstring'''



        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 						snake_case__						(  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	)

        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(_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	):
        '''simple docstring'''



        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 						snake_case__						(  self,					_UpperCAmelCase	):
        '''simple docstring'''



        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(_UpperCAmelCase	) 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(_UpperCAmelCase	) 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=_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




