


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


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


snake_case				:    Optional[Any]       				=     list(MODEL_WITH_LM_HEAD_MAPPING.keys())
snake_case				:    Optional[int]       				=     tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)







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







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

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

 SCREAMING_SNAKE_CASE__      =       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).'
         )
     }						,    )
 SCREAMING_SNAKE_CASE__      =       field(
     default=_snake_case						,    metadata={'help': 'Overwrite the cached training and evaluation sets'}							)







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




      """simple docstring"""





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

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

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




      """simple docstring"""





      a						:Optional[int] 							=       HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)						)
      a							,				a							,				a						:Optional[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''' ,  UpperCAmelCase_						)

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

      if model_args.tokenizer_name:
            a						:List[str] 							=       AutoTokenizer.from_pretrained(model_args.tokenizer_name ,  cache_dir=model_args.cache_dir						)
      elif model_args.model_name_or_path:
            a						:List[str] 							=       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						:List[str] 							=       AutoModelWithLMHead.from_pretrained(
                model_args.model_name_or_path ,  from_tf=bool('''.ckpt''' in model_args.model_name_or_path						) ,  config=UpperCAmelCase_ ,  cache_dir=model_args.cache_dir ,  )
      else:
            logger.info('''Training new model from scratch'''						)
            a						:List[Any] 							=       AutoModelWithLMHead.from_config(UpperCAmelCase_						)

      model.resize_token_embeddings(len(UpperCAmelCase_						)						)

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

      # Get datasets

      a						:Optional[int] 							=       (
          get_dataset(UpperCAmelCase_ ,  tokenizer=UpperCAmelCase_ ,  cache_dir=model_args.cache_dir						) if training_args.do_train else None
      )
      a						:str 							=       (
          get_dataset(UpperCAmelCase_ ,  tokenizer=UpperCAmelCase_ ,  evaluate=UpperCAmelCase_ ,  cache_dir=model_args.cache_dir						)
          if training_args.do_eval
          else None
      )
      if config.model_type == "xlnet":
            a						:Dict 							=       DataCollatorForPermutationLanguageModeling(
                tokenizer=UpperCAmelCase_ ,  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=UpperCAmelCase_ ,  mlm_probability=data_args.mlm_probability						)
            else:
                  a						:int 							=       DataCollatorForLanguageModeling(
                      tokenizer=UpperCAmelCase_ ,  mlm=data_args.mlm ,  mlm_probability=data_args.mlm_probability						)

    # Initialize our Trainer
      a						:List[Any] 							=       Trainer(
          model=UpperCAmelCase_ ,  args=UpperCAmelCase_ ,  data_collator=UpperCAmelCase_ ,  train_dataset=UpperCAmelCase_ ,  eval_dataset=UpperCAmelCase_ ,  prediction_loss_only=UpperCAmelCase_ ,  )

      # Training
      if training_args.do_train:
            a						:Dict 							=       (
                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=UpperCAmelCase_						)
            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						:Any 							=       trainer.evaluate()

            a						:Any 							=       math.exp(eval_output['''eval_loss''']						)
            a						:int 							=       {'''perplexity''': perplexity}

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

            results.update(UpperCAmelCase_						)

      return results
def 				__lowerCamelCase						( UpperCAmelCase_						:		Tuple						):




      """simple docstring"""





      main()


if __name__ == "__main__":
     main()









# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from pathlib import Path

import torch

from ...utils import is_npu_available, is_xpu_available
from .config_args import ClusterConfig, default_json_config_file
from .config_utils import SubcommandHelpFormatter


snake_case				:    int       				=     '''Create a default config file for Accelerate with only a few flags set.'''
def 				__lowerCamelCase						( UpperCAmelCase_						:		Optional[Any]="no" ,  UpperCAmelCase_						:		str = default_json_config_file ,  UpperCAmelCase_						:		bool = False						):




      """simple docstring"""





      a						:List[str] 							=       Path(UpperCAmelCase_						)
      path.parent.mkdir(parents=UpperCAmelCase_ ,  exist_ok=UpperCAmelCase_						)
      if path.exists():
            print(
                F'''Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`.'''						)
            return False
      a						:Optional[Any] 							=       mixed_precision.lower()
      if mixed_precision not in ["no", "fp16", "bf16", "fp8"]:
            raise ValueError(
                F'''`mixed_precision` should be one of \'no\', \'fp16\', \'bf16\', or \'fp8\'. Received {mixed_precision}'''						)
      a						:List[Any] 							=       {
          '''compute_environment''': '''LOCAL_MACHINE''',
          '''mixed_precision''': mixed_precision,
      }
      if torch.cuda.is_available():
            a						:Dict 							=       torch.cuda.device_count()
            a						:Tuple 							=       num_gpus
            a						:int 							=       False
            if num_gpus > 1:
                  a						:str 							=       '''MULTI_GPU'''
            else:
                  a						:List[Any] 							=       '''NO'''
      elif is_xpu_available() and use_xpu:
            a						:List[Any] 							=       torch.xpu.device_count()
            a						:Optional[int] 							=       num_xpus
            a						:List[Any] 							=       False
            if num_xpus > 1:
                  a						:int 							=       '''MULTI_XPU'''
            else:
                  a						:str 							=       '''NO'''
      elif is_npu_available():
            a						:List[str] 							=       torch.npu.device_count()
            a						:Any 							=       num_npus
            a						:Optional[int] 							=       False
            if num_npus > 1:
                  a						:List[str] 							=       '''MULTI_NPU'''
            else:
                  a						:Dict 							=       '''NO'''
      else:
            a						:str 							=       0
            a						:Optional[Any] 							=       True
            a						:Optional[Any] 							=       1
            a						:str 							=       '''NO'''
      a						:List[str] 							=       ClusterConfig(**UpperCAmelCase_						)
      config.to_json_file(UpperCAmelCase_						)
      return path
def 				__lowerCamelCase						( UpperCAmelCase_						:		List[str] ,  UpperCAmelCase_						:		Union[str, Any]						):




      """simple docstring"""





      a						:List[Any] 							=       parser.add_parser('''default''' ,  parents=UpperCAmelCase_ ,  help=UpperCAmelCase_ ,  formatter_class=UpperCAmelCase_						)
      parser.add_argument(
          '''--config_file''' ,  default=UpperCAmelCase_ ,  help=(
              '''The path to use to store the config file. Will default to a file named default_config.yaml in the cache '''
              '''location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have '''
              '''such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed '''
              '''with \'huggingface\'.'''
          ) ,  dest='''save_location''' ,  )

      parser.add_argument(
          '''--mixed_precision''' ,  choices=['''no''', '''fp16''', '''bf16'''] ,  type=UpperCAmelCase_ ,  help='''Whether or not to use mixed precision training. '''
          '''Choose between FP16 and BF16 (bfloat16) training. '''
          '''BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.''' ,  default='''no''' ,  )
      parser.set_defaults(func=UpperCAmelCase_						)
      return parser






def 				__lowerCamelCase						( UpperCAmelCase_						:		int						):




      """simple docstring"""





      a						:Optional[Any] 							=       write_basic_config(args.mixed_precision ,  args.save_location						)
      if config_file:
            print(F'''accelerate configuration saved at {config_file}'''						)





