
'''simple docstring'''







import logging
import math
import os
from dataclasses import dataclass, field
from glob import glob
from typing import Optional

from torch.utils.data import ConcatDataset

import transformers
from transformers import (
    CONFIG_MAPPING,
    MODEL_WITH_LM_HEAD_MAPPING,
    AutoConfig,
    AutoModelWithLMHead,
    AutoTokenizer,
    DataCollatorForLanguageModeling,
    DataCollatorForPermutationLanguageModeling,
    DataCollatorForWholeWordMask,
    HfArgumentParser,
    LineByLineTextDataset,
    LineByLineWithRefDataset,
    PreTrainedTokenizer,
    TextDataset,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import is_main_process


__lowerCAmelCase         =    logging.getLogger(__name__)


__lowerCAmelCase         =    list(MODEL_WITH_LM_HEAD_MAPPING.keys())
__lowerCAmelCase         =    tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)







@dataclass
class UpperCAmelCase__	:





  """simple docstring"""

  __UpperCAmelCase				:				Optional[str]   =					field(
      default=lowercase__    ,				metadata={
          '''help''': (
              '''The model checkpoint for weights initialization. Leave None if you want to train a model from'''
              ''' scratch.'''
          )
      }    ,				)
  __UpperCAmelCase				:				Optional[str]   =					field(
      default=lowercase__    ,				metadata={'''help''': '''If training from scratch, pass a model type from the list: ''' + ''', '''.join(lowercase__	)}    ,				)
  __UpperCAmelCase				:				Optional[str]   =					field(
      default=lowercase__    ,				metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''}	)
  __UpperCAmelCase				:				Optional[str]   =					field(
      default=lowercase__    ,				metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''}	)
  __UpperCAmelCase				:				Optional[str]   =					field(
      default=lowercase__    ,				metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''}    ,				)







@dataclass
class UpperCAmelCase__	:





  """simple docstring"""

  __UpperCAmelCase				:				Optional[str]   =					field(
      default=lowercase__    ,				metadata={'''help''': '''The input training data file (a text file).'''}	)
  __UpperCAmelCase				:				Optional[str]   =					field(
      default=lowercase__    ,				metadata={
          '''help''': (
              '''The input training data files (multiple files in glob format). '''
              '''Very often splitting large files to smaller files can prevent tokenizer going out of memory'''
          )
      }    ,				)
  __UpperCAmelCase				:				Optional[str]   =					field(
      default=lowercase__    ,				metadata={'''help''': '''An optional input evaluation data file to evaluate the perplexity on (a text file).'''}    ,				)
  __UpperCAmelCase				:				Optional[str]   =					field(
      default=lowercase__    ,				metadata={'''help''': '''An optional input train ref data file for whole word mask in Chinese.'''}    ,				)
  __UpperCAmelCase				:				Optional[str]   =					field(
      default=lowercase__    ,				metadata={'''help''': '''An optional input eval ref data file for whole word mask in Chinese.'''}    ,				)
  __UpperCAmelCase				:				bool   =					field(
      default=lowercase__    ,				metadata={'''help''': '''Whether distinct lines of text in the dataset are to be handled as distinct sequences.'''}    ,				)

  __UpperCAmelCase				:				bool   =					field(
      default=lowercase__    ,				metadata={'''help''': '''Train with masked-language modeling loss instead of language modeling.'''}	)
  __UpperCAmelCase				:				bool   =					field(default=lowercase__    ,				metadata={'''help''': '''Whether ot not to use whole word mask.'''}	)
  __UpperCAmelCase				:				float   =					field(
      default=0.1_5    ,				metadata={'''help''': '''Ratio of tokens to mask for masked language modeling loss'''}	)
  __UpperCAmelCase				:				float   =					field(
      default=1 / 6    ,				metadata={
          '''help''': (
              '''Ratio of length of a span of masked tokens to surrounding context length for permutation language'''
              ''' modeling.'''
          )
      }    ,				)
  __UpperCAmelCase				:				int   =					field(
      default=5    ,				metadata={'''help''': '''Maximum length of a span of masked tokens for permutation language modeling.'''}	)

  __UpperCAmelCase				:				int   =					field(
      default=-1    ,				metadata={
          '''help''': (
              '''Optional input sequence length after tokenization.'''
              '''The training dataset will be truncated in block of this size for training.'''
              '''Default to the model max input length for single sentence inputs (take into account special tokens).'''
          )
      }    ,				)
  __UpperCAmelCase				:				bool   =					field(
      default=lowercase__    ,				metadata={'''help''': '''Overwrite the cached training and evaluation sets'''}	)





def 					UpperCAmelCase_		(__a      :    DataTrainingArguments ,	__a      :    PreTrainedTokenizer ,	__a      :    bool = False ,	__a      :    Optional[str] = None ,	):






   """simple docstring"""

   def _dataset(__a      :    Any ,	__a      :    int=None ):
      if args.line_by_line:
         if ref_path is not None:
            if not args.whole_word_mask or not args.mlm:
               raise ValueError('You need to set world whole masking and mlm to True for Chinese Whole Word Mask' )
            return LineByLineWithRefDataset(
                tokenizer=__a ,	file_path=__a ,	block_size=args.block_size ,	ref_path=__a ,	)

         return LineByLineTextDataset(tokenizer=__a ,	file_path=__a ,	block_size=args.block_size )
      else:
         return TextDataset(
             tokenizer=__a ,	file_path=__a ,	block_size=args.block_size ,	overwrite_cache=args.overwrite_cache ,	cache_dir=__a ,	)

   if evaluate:
      return _dataset(args.eval_data_file ,	args.eval_ref_file )
   elif args.train_data_files:
      return ConcatDataset([_dataset(__a ) for f in glob(args.train_data_files )] )
   else:
      return _dataset(args.train_data_file ,	args.train_ref_file )





def 					UpperCAmelCase_		():






   """simple docstring"""

   _a				:	Any			=   HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) )
   _a,  _a,  _a				:	int			=   parser.parse_args_into_dataclasses()

   if data_args.eval_data_file is None and training_args.do_eval:
      raise ValueError(
          'Cannot do evaluation without an evaluation data file. Either supply a file to --eval_data_file '
          'or remove the --do_eval argument.' )
   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 )

   # Set seed
   set_seed(training_args.seed )

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

   if model_args.config_name:
      _a				:	List[Any]			=   AutoConfig.from_pretrained(model_args.config_name ,	cache_dir=model_args.cache_dir )
   elif model_args.model_name_or_path:
      _a				:	List[str]			=   AutoConfig.from_pretrained(model_args.model_name_or_path ,	cache_dir=model_args.cache_dir )
   else:
      _a				:	Tuple			=   CONFIG_MAPPING[model_args.model_type]()
      logger.warning('You are instantiating a new config instance from scratch.' )

   if model_args.tokenizer_name:
      _a				:	int			=   AutoTokenizer.from_pretrained(model_args.tokenizer_name ,	cache_dir=model_args.cache_dir )
   elif model_args.model_name_or_path:
      _a				:	Any			=   AutoTokenizer.from_pretrained(model_args.model_name_or_path ,	cache_dir=model_args.cache_dir )
   else:
      raise ValueError(
          'You are instantiating a new tokenizer from scratch. This is not supported, but you can do it from another'
          ' script, save it,and load it from here, using --tokenizer_name' )

   if model_args.model_name_or_path:
      _a				:	Any			=   AutoModelWithLMHead.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 ,	)
   else:
      logger.info('Training new model from scratch' )
      _a				:	Tuple			=   AutoModelWithLMHead.from_config(__a )

   model.resize_token_embeddings(len(__a ) )

   if config.model_type in ["bert", "roberta", "distilbert", "camembert"] and not data_args.mlm:
      raise ValueError(
          'BERT and RoBERTa-like models do not have LM heads but masked LM heads. They must be run using the'
          '--mlm flag (masked language modeling).' )

   if data_args.block_size <= 0:
      _a				:	List[Any]			=   tokenizer.max_len
      # Our input block size will be the max possible for the model
   else:
      _a				:	Any			=   min(data_args.block_size ,	tokenizer.max_len )

   # Get datasets

   _a				:	List[str]			=   (
       get_dataset(__a ,	tokenizer=__a ,	cache_dir=model_args.cache_dir ) if training_args.do_train else None
   )
   _a				:	int			=   (
       get_dataset(__a ,	tokenizer=__a ,	evaluate=__a ,	cache_dir=model_args.cache_dir )
       if training_args.do_eval
       else None
   )
   if config.model_type == "xlnet":
      _a				:	Any			=   DataCollatorForPermutationLanguageModeling(
          tokenizer=__a ,	plm_probability=data_args.plm_probability ,	max_span_length=data_args.max_span_length ,	)
   else:
      if data_args.mlm and data_args.whole_word_mask:
         _a				:	Optional[int]			=   DataCollatorForWholeWordMask(
             tokenizer=__a ,	mlm_probability=data_args.mlm_probability )
      else:
         _a				:	int			=   DataCollatorForLanguageModeling(
             tokenizer=__a ,	mlm=data_args.mlm ,	mlm_probability=data_args.mlm_probability )

    # Initialize our Trainer
   _a				:	Dict			=   Trainer(
       model=__a ,	args=__a ,	data_collator=__a ,	train_dataset=__a ,	eval_dataset=__a ,	prediction_loss_only=__a ,	)

   # Training
   if training_args.do_train:
      _a				:	str			=   (
          model_args.model_name_or_path
          if model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path )
          else None
      )
      trainer.train(model_path=__a )
      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 )

    # Evaluation
   _a				:	Optional[int]			=   {}
   if training_args.do_eval:
      logger.info('*** Evaluate ***' )

      _a				:	int			=   trainer.evaluate()

      _a				:	Optional[Any]			=   math.exp(eval_output['eval_loss'] )
      _a				:	List[Any]			=   {'perplexity': perplexity}

      _a				:	List[str]			=   os.path.join(training_args.output_dir ,	'eval_results_lm.txt' )
      if trainer.is_world_master():
         with open(__a ,	'w' ) as writer:
            logger.info('***** Eval results *****' )
            for key in sorted(result.keys() ):
               logger.info('  %s = %s' ,	__a ,	str(result[key] ) )
               writer.write('%s = %s\n' % (key, str(result[key] )) )

      results.update(__a )

   return results





def 					UpperCAmelCase_		(__a      :    Optional[int] ):






   """simple docstring"""

   main()


if __name__ == "__main__":
  main()





'''simple docstring'''







import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


__lowerCAmelCase         =    logging.get_logger(__name__)

__lowerCAmelCase         =    """▁"""

__lowerCAmelCase         =    {"""vocab_file""": """sentencepiece.bpe.model""", """monolingual_vocab_file""": """dict.txt"""}

__lowerCAmelCase         =    {
    """vocab_file""": {
        """vinai/bartpho-syllable""": """https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model""",
    },
    """monolingual_vocab_file""": {
        """vinai/bartpho-syllable""": """https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt""",
    },
}

__lowerCAmelCase         =    {"""vinai/bartpho-syllable""": 1_0_2_4}







class UpperCAmelCase__	( lowercase__	):





  """simple docstring"""

  __UpperCAmelCase				:				Optional[Any]   =					VOCAB_FILES_NAMES
  __UpperCAmelCase				:				Dict   =					PRETRAINED_VOCAB_FILES_MAP
  __UpperCAmelCase				:				Optional[int]   =					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  __UpperCAmelCase				:				Dict   =					['''input_ids''', '''attention_mask''']


  def __init__(		self      :     str							,_a      :     str							,_a      :     Any							,_a      :     Any="<s>"							,_a      :     Dict="</s>"							,_a      :     int="</s>"							,_a      :     Union[str, Any]="<s>"							,_a      :     List[Any]="<unk>"							,_a      :     Optional[Any]="<pad>"							,_a      :     List[str]="<mask>"							,_a      :     Optional[Dict[str, Any]] = None							,**_a      :     int							,):


     '''simple docstring'''






     _a				:	Any			=   AddedToken(_a							,lstrip=_a							,rstrip=_a       ) if isinstance(_a							,_a       ) else mask_token

     _a				:	Optional[Any]			=   {} if sp_model_kwargs is None else sp_model_kwargs

     super().__init__(
         bos_token=_a							,eos_token=_a							,unk_token=_a							,sep_token=_a							,cls_token=_a							,pad_token=_a							,mask_token=_a							,sp_model_kwargs=self.sp_model_kwargs							,**_a							,)

     _a				:	Optional[int]			=   vocab_file
     _a				:	Union[str, Any]			=   monolingual_vocab_file
     _a				:	List[Any]			=   spm.SentencePieceProcessor(**self.sp_model_kwargs       )
     self.sp_model.Load(str(_a       )       )

     # Load the reduced vocab

     # Keep order of special tokens for backward compatibility
     _a				:	Union[str, Any]			=   {}
     _a				:	int			=   0
     for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]:
        if str(_a       ) not in self.fairseq_tokens_to_ids:
           _a				:	int			=   cnt
           cnt += 1
     with open(_a							,'r'							,encoding='utf-8'       ) as f:
        for line in f.readlines():
           _a				:	str			=   line.strip().split()[0]
           _a				:	Tuple			=   len(self.fairseq_tokens_to_ids       )
     if str(_a       ) not in self.fairseq_tokens_to_ids:
        _a				:	List[str]			=   len(self.fairseq_tokens_to_ids       )

     _a				:	Tuple			=   {v: k for k, v in self.fairseq_tokens_to_ids.items()}


  def __getstate__(		self      :     Union[str, Any]       ):


     '''simple docstring'''






     _a				:	int			=   self.__dict__.copy()
     _a				:	str			=   None
     _a				:	Optional[Any]			=   self.sp_model.serialized_model_proto()
     return state


  def __setstate__(		self      :     Tuple							,_a      :     Tuple       ):


     '''simple docstring'''






     _a				:	Tuple			=   d

     # for backward compatibility
     if not hasattr(self							,'sp_model_kwargs'       ):
        _a				:	List[str]			=   {}

     _a				:	List[Any]			=   spm.SentencePieceProcessor(**self.sp_model_kwargs       )
     self.sp_model.LoadFromSerializedProto(self.sp_model_proto       )


  def   __lowercase		(		self      :     Dict							,_a      :     List[int]							,_a      :     Optional[List[int]] = None       ):


     '''simple docstring'''






     if token_ids_a is None:
        return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
     _a				:	Dict			=   [self.cls_token_id]
     _a				:	int			=   [self.sep_token_id]
     return cls + token_ids_a + sep + sep + token_ids_a + sep


  def   __lowercase		(		self      :     int							,_a      :     List[int]							,_a      :     Optional[List[int]] = None							,_a      :     bool = False       ):


     '''simple docstring'''






     if already_has_special_tokens:
        return super().get_special_tokens_mask(
            token_ids_a=_a							,token_ids_a=_a							,already_has_special_tokens=_a       )

     if token_ids_a is None:
        return [1] + ([0] * len(_a       )) + [1]
     return [1] + ([0] * len(_a       )) + [1, 1] + ([0] * len(_a       )) + [1]


  def   __lowercase		(		self      :     Tuple							,_a      :     List[int]							,_a      :     Optional[List[int]] = None       ):


     '''simple docstring'''






     _a				:	List[str]			=   [self.sep_token_id]
     _a				:	List[str]			=   [self.cls_token_id]

     if token_ids_a is None:
        return len(cls + token_ids_a + sep       ) * [0]
     return len(cls + token_ids_a + sep + sep + token_ids_a + sep       ) * [0]


  @property
  def   __lowercase		(		self      :     Dict       ):


     '''simple docstring'''






     return len(self.fairseq_ids_to_tokens       )


  def   __lowercase		(		self      :     Dict       ):


     '''simple docstring'''






     _a				:	List[str]			=   {self.convert_ids_to_tokens(_a       ): i for i in range(self.vocab_size       )}
     vocab.update(self.added_tokens_encoder       )
     return vocab


  def   __lowercase		(		self      :     Tuple							,_a      :     str       ):


     '''simple docstring'''






     return self.sp_model.encode(_a							,out_type=_a       )


  def   __lowercase		(		self      :     Union[str, Any]							,_a      :     Union[str, Any]       ):


     '''simple docstring'''






     if token in self.fairseq_tokens_to_ids:
        return self.fairseq_tokens_to_ids[token]
     else:
        return self.unk_token_id


  def   __lowercase		(		self      :     Any							,_a      :     int       ):


     '''simple docstring'''






     return self.fairseq_ids_to_tokens[index]


  def   __lowercase		(		self      :     Tuple							,_a      :     Union[str, Any]       ):


     '''simple docstring'''






     _a				:	str			=   ''.join(_a       ).replace(_a							,' '       ).strip()
     return out_string


  def   __lowercase		(		self      :     Union[str, Any]							,_a      :     str							,_a      :     Optional[str] = None       ):


     '''simple docstring'''






     if not os.path.isdir(_a       ):
        logger.error(F"""Vocabulary path ({save_directory}) should be a directory"""       )
        return
     _a				:	int			=   os.path.join(
         _a							,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']       )
     _a				:	int			=   os.path.join(
         _a							,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['monolingual_vocab_file']							,)

     if os.path.abspath(self.vocab_file       ) != os.path.abspath(_a       ) and os.path.isfile(self.vocab_file       ):
        copyfile(self.vocab_file							,_a       )
     elif not os.path.isfile(self.vocab_file       ):
        with open(_a							,'wb'       ) as fi:
           _a				:	List[Any]			=   self.sp_model.serialized_model_proto()
           fi.write(_a       )

     if os.path.abspath(self.monolingual_vocab_file       ) != os.path.abspath(
         _a       ) and os.path.isfile(self.monolingual_vocab_file       ):
        copyfile(self.monolingual_vocab_file							,_a       )
     elif not os.path.isfile(self.monolingual_vocab_file       ):
        with open(_a							,'w'							,encoding='utf-8'       ) as fp:
           for token in self.fairseq_tokens_to_ids:
              if token not in self.all_special_tokens:
                 fp.write(F"""{str(_a       )} \n"""       )

     return out_vocab_file, out_monolingual_vocab_file



