


"""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       SCREAMING_SNAKE_CASE__				:
       """simple docstring"""


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


@dataclass
class       SCREAMING_SNAKE_CASE__				:
       """simple docstring"""


       a  :				Optional[str]   =field(
           default=lowercase   ,    metadata={"help": "The input training data file (a text file)."}				)
       a  :				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"
               )
           }   ,    )
       a  :				Optional[str]   =field(
           default=lowercase   ,    metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."}   ,    )
       a  :				Optional[str]   =field(
           default=lowercase   ,    metadata={"help": "An optional input train ref data file for whole word mask in Chinese."}   ,    )
       a  :				Optional[str]   =field(
           default=lowercase   ,    metadata={"help": "An optional input eval ref data file for whole word mask in Chinese."}   ,    )
       a  :				bool   =field(
           default=lowercase   ,    metadata={"help": "Whether distinct lines of text in the dataset are to be handled as distinct sequences."}   ,    )

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

       a  :				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)."
               )
           }   ,    )
       a  :				bool   =field(
           default=lowercase   ,    metadata={"help": "Overwrite the cached training and evaluation sets"}				)

def 					a__			(				SCREAMING_SNAKE_CASE    :    DataTrainingArguments				,      SCREAMING_SNAKE_CASE    :    PreTrainedTokenizer				,      SCREAMING_SNAKE_CASE    :    bool = False				,      SCREAMING_SNAKE_CASE    :    Optional[str] = None				,      ):


  '''simple docstring'''







  def _dataset(SCREAMING_SNAKE_CASE    :    Optional[int]				,      SCREAMING_SNAKE_CASE    :    List[str]=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=SCREAMING_SNAKE_CASE				,      file_path=SCREAMING_SNAKE_CASE				,      block_size=args.block_size				,      ref_path=SCREAMING_SNAKE_CASE				,      )

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

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


  '''simple docstring'''







  lowerCAmelCase     :     int								=							HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)				)
  lowerCAmelCase						,  lowerCAmelCase						,  lowerCAmelCase     :     Dict								=							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"				,      SCREAMING_SNAKE_CASE				)

  # 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:
    lowerCAmelCase     :     int								=							AutoConfig.from_pretrained(model_args.config_name				,      cache_dir=model_args.cache_dir				)
  elif model_args.model_name_or_path:
    lowerCAmelCase     :     Union[str, Any]								=							AutoConfig.from_pretrained(model_args.model_name_or_path				,      cache_dir=model_args.cache_dir				)
  else:
    lowerCAmelCase     :     Optional[Any]								=							CONFIG_MAPPING[model_args.model_type]()
    logger.warning("You are instantiating a new config instance from scratch."				)

  if model_args.tokenizer_name:
    lowerCAmelCase     :     Any								=							AutoTokenizer.from_pretrained(model_args.tokenizer_name				,      cache_dir=model_args.cache_dir				)
  elif model_args.model_name_or_path:
    lowerCAmelCase     :     Dict								=							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:
    lowerCAmelCase     :     Dict								=							AutoModelWithLMHead.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				,      )
  else:
    logger.info("Training new model from scratch"				)
    lowerCAmelCase     :     int								=							AutoModelWithLMHead.from_config(SCREAMING_SNAKE_CASE				)

  model.resize_token_embeddings(len(SCREAMING_SNAKE_CASE				)				)

  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:
    lowerCAmelCase     :     Dict								=							tokenizer.max_len
    # Our input block size will be the max possible for the model
  else:
    lowerCAmelCase     :     Optional[int]								=							min(data_args.block_size				,      tokenizer.max_len				)

  # Get datasets

  lowerCAmelCase     :     List[Any]								=							(
      get_dataset(SCREAMING_SNAKE_CASE				,      tokenizer=SCREAMING_SNAKE_CASE				,      cache_dir=model_args.cache_dir				) if training_args.do_train else None
  )
  lowerCAmelCase     :     Union[str, Any]								=							(
      get_dataset(SCREAMING_SNAKE_CASE				,      tokenizer=SCREAMING_SNAKE_CASE				,      evaluate=SCREAMING_SNAKE_CASE				,      cache_dir=model_args.cache_dir				)
      if training_args.do_eval
      else None
  )
  if config.model_type == "xlnet":
    lowerCAmelCase     :     int								=							DataCollatorForPermutationLanguageModeling(
        tokenizer=SCREAMING_SNAKE_CASE				,      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:
      lowerCAmelCase     :     Any								=							DataCollatorForWholeWordMask(
          tokenizer=SCREAMING_SNAKE_CASE				,      mlm_probability=data_args.mlm_probability				)
    else:
      lowerCAmelCase     :     List[str]								=							DataCollatorForLanguageModeling(
          tokenizer=SCREAMING_SNAKE_CASE				,      mlm=data_args.mlm				,      mlm_probability=data_args.mlm_probability				)

    # Initialize our Trainer
  lowerCAmelCase     :     Any								=							Trainer(
      model=SCREAMING_SNAKE_CASE				,      args=SCREAMING_SNAKE_CASE				,      data_collator=SCREAMING_SNAKE_CASE				,      train_dataset=SCREAMING_SNAKE_CASE				,      eval_dataset=SCREAMING_SNAKE_CASE				,      prediction_loss_only=SCREAMING_SNAKE_CASE				,      )

  # Training
  if training_args.do_train:
    lowerCAmelCase     :     List[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=SCREAMING_SNAKE_CASE				)
    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
  lowerCAmelCase     :     str								=							{}
  if training_args.do_eval:
    logger.info("*** Evaluate ***"				)

    lowerCAmelCase     :     List[str]								=							trainer.evaluate()

    lowerCAmelCase     :     Union[str, Any]								=							math.exp(eval_output["eval_loss"]				)
    lowerCAmelCase     :     Tuple								=							{"perplexity": perplexity}

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

    results.update(SCREAMING_SNAKE_CASE				)

  return results
def 					a__			(				SCREAMING_SNAKE_CASE    :    Optional[Any]				):


  '''simple docstring'''







  main()


if __name__ == "__main__":
     main()









'''simple docstring'''



A__		:					Optional[int]												=  """ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"""



def 			UpperCAmelCase__					(	UpperCAmelCase_    :				bytes							)     ->		bytes:
     # Make sure the supplied data is a bytes-like object
     if not isinstance(UpperCAmelCase_      ,    UpperCAmelCase_							):
          __lowerCamelCase   :	Dict								=		F'a bytes-like object is required, not \'{data.__class__.__name__}\''
          raise TypeError(UpperCAmelCase_							)

     __lowerCamelCase   :	Optional[int]								=		''.join(bin(UpperCAmelCase_							)[2:].zfill(8							) for byte in data							)

     __lowerCamelCase   :	Any								=		len(UpperCAmelCase_							) % 6 != 0

     if padding_needed:
          # The padding that will be added later
          __lowerCamelCase   :	int								=		B'=' * ((6 - len(UpperCAmelCase_							) % 6) // 2)

          # Append binary_stream with arbitrary binary digits (0's by default) to make its
          # length a multiple of 6.
          binary_stream += "0" * (6 - len(UpperCAmelCase_							) % 6)
     else:
          __lowerCamelCase   :	str								=		B''

     # Encode every 6 binary digits to their corresponding Base64 character
     return (
         "".join(
             B64_CHARSET[int(binary_stream[index : index + 6]      ,    2							)]
             for index in range(0      ,    len(UpperCAmelCase_							)      ,    6							)							).encode()
         + padding
     )



def 			UpperCAmelCase__					(	UpperCAmelCase_    :				str							)     ->		bytes:
     # Make sure encoded_data is either a string or a bytes-like object
     if not isinstance(UpperCAmelCase_      ,    UpperCAmelCase_							) and not isinstance(UpperCAmelCase_      ,    UpperCAmelCase_							):
          __lowerCamelCase   :	Dict								=		(
              'argument should be a bytes-like object or ASCII string, '
              F'not \'{encoded_data.__class__.__name__}\''
          )
          raise TypeError(UpperCAmelCase_							)

     # In case encoded_data is a bytes-like object, make sure it contains only
     # ASCII characters so we convert it to a string object
     if isinstance(UpperCAmelCase_      ,    UpperCAmelCase_							):
          try:
               __lowerCamelCase   :	int								=		encoded_data.decode('utf-8'							)
          except UnicodeDecodeError:
               raise ValueError('base64 encoded data should only contain ASCII characters'							)

     __lowerCamelCase   :	Union[str, Any]								=		encoded_data.count('='							)

     # Check if the encoded string contains non base64 characters
     if padding:
          assert all(
              char in B64_CHARSET for char in encoded_data[:-padding]							), "Invalid base64 character(s) found."
     else:
          assert all(
              char in B64_CHARSET for char in encoded_data							), "Invalid base64 character(s) found."

     # Check the padding
     assert len(UpperCAmelCase_							) % 4 == 0 and padding < 3, "Incorrect padding"

     if padding:
          # Remove padding if there is one
          __lowerCamelCase   :	Any								=		encoded_data[:-padding]

          __lowerCamelCase   :	Optional[Any]								=		''.join(
              bin(B64_CHARSET.index(UpperCAmelCase_							)							)[2:].zfill(6							) for char in encoded_data							)[: -padding * 2]
     else:
          __lowerCamelCase   :	Any								=		''.join(
              bin(B64_CHARSET.index(UpperCAmelCase_							)							)[2:].zfill(6							) for char in encoded_data							)

     __lowerCamelCase   :	str								=		[
         int(binary_stream[index : index + 8]      ,    2							)
         for index in range(0      ,    len(UpperCAmelCase_							)      ,    8							)
     ]

     return bytes(UpperCAmelCase_							)


if __name__ == "__main__":
      import doctest

      doctest.testmod()






