




'''simple docstring'''





import logging
import os
from typing import Dict, List, Optional, Union

import torch
import torch.nn as nn

from accelerate.utils.imports import (
    is_abit_bnb_available,
    is_abit_bnb_available,
    is_bnb_available,
)

from ..big_modeling import dispatch_model, init_empty_weights
from .dataclasses import BnbQuantizationConfig
from .modeling import (
    find_tied_parameters,
    get_balanced_memory,
    infer_auto_device_map,
    load_checkpoint_in_model,
    offload_weight,
    set_module_tensor_to_device,
)


if is_bnb_available():
		import bitsandbytes as bnb

from copy import deepcopy


_SCREAMING_SNAKE_CASE							:   Optional[Any]      		= logging.getLogger(__name__)


def      UpperCamelCase_(	snake_case							:       torch.nn.Module							,				snake_case							:       BnbQuantizationConfig							,				snake_case							:       Union[str, os.PathLike] = None							,				snake_case							:       Optional[Dict[str, Union[int, str, torch.device]]] = None							,				snake_case							:       Optional[List[str]] = None							,				snake_case							:       Optional[Dict[Union[int, str], Union[int, str]]] = None							,				snake_case							:       Optional[Union[str, os.PathLike]] = None							,				snake_case							:       bool = False							,				):

							'''simple docstring'''






							snake_case_						=      bnb_quantization_config.load_in_abit
							snake_case_						=      bnb_quantization_config.load_in_abit

							if load_in_abit and not is_abit_bnb_available():
														raise ImportError(
														    "You have a version of `bitsandbytes` that is not compatible with 8bit quantization,"
														    " make sure you have the latest version of `bitsandbytes` installed."     )
							if load_in_abit and not is_abit_bnb_available():
														raise ValueError(
														    "You have a version of `bitsandbytes` that is not compatible with 4bit quantization,"
														    "make sure you have the latest version of `bitsandbytes` installed."     )

							snake_case_						=      []
							# custom device map
							if isinstance(snake_case							,				snake_case     ) and len(device_map.keys()     ) > 1:
														snake_case_						=      [key for key, value in device_map.items() if value in ["disk", "cpu"]]

							# We keep some modules such as the lm_head in their original dtype for numerical stability reasons
							if bnb_quantization_config.skip_modules is None:
														snake_case_						=      get_keys_to_not_convert(snake_case     )

							# add cpu modules to skip modules only for 4-bit modules
							if load_in_abit:
														bnb_quantization_config.skip_modules.extend(snake_case     )
							snake_case_						=      bnb_quantization_config.skip_modules

							# We add the modules we want to keep in full precision
							if bnb_quantization_config.keep_in_fpaa_modules is None:
														snake_case_						=      []
							snake_case_						=      bnb_quantization_config.keep_in_fpaa_modules
							modules_to_not_convert.extend(snake_case     )

							# compatibility with peft
							snake_case_						=      load_in_abit
							snake_case_						=      load_in_abit

							snake_case_						=      get_parameter_device(snake_case     )
							if model_device.type != "meta":
														# quantization of an already loaded model
														logger.warning(
														    "It is not recommended to quantize a loaded model. "
														    "The model should be instantiated under the `init_empty_weights` context manager."     )
														snake_case_						=      replace_with_bnb_layers(snake_case							,				snake_case							,				modules_to_not_convert=snake_case     )
														# convert param to the right dtype
														snake_case_						=      bnb_quantization_config.torch_dtype
														for name, param in model.state_dict().items():
																					if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules     ):
																												param.to(torch.floataa     )
																												if param.dtype != torch.floataa:
																																			snake_case_						=      name.replace(".weight"							,				""     ).replace(".bias"							,				""     )
																																			snake_case_						=      getattr(snake_case							,				snake_case							,				snake_case     )
																																			if param is not None:
																																										param.to(torch.floataa     )
																					elif torch.is_floating_point(snake_case     ):
																												param.to(snake_case     )
														if model_device.type == "cuda":
																					# move everything to cpu in the first place because we can't do quantization if the weights are already on cuda
																					model.cuda(torch.cuda.current_device()     )
																					torch.cuda.empty_cache()
														elif torch.cuda.is_available():
																					model.to(torch.cuda.current_device()     )
														else:
																					raise RuntimeError("No GPU found. A GPU is needed for quantization."     )
														logger.info(
														    f'The model device type is {model_device.type}. However, cuda is needed for quantization.'
														    "We move the model to cuda."     )
														return model

							elif weights_location is None:
														raise RuntimeError(
														    f'`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} '     )

							else:
														with init_empty_weights():
																					snake_case_						=      replace_with_bnb_layers(
																					    snake_case							,				snake_case							,				modules_to_not_convert=snake_case     )

														snake_case_						=      get_quantized_model_device_map(
														    snake_case							,				snake_case							,				snake_case							,				max_memory=snake_case							,				no_split_module_classes=snake_case							,				)
														if offload_state_dict is None and device_map is not None and "disk" in device_map.values():
																					snake_case_						=      True

														snake_case_						=      any(x in list(device_map.values()     ) for x in ["cpu", "disk"]     )

														load_checkpoint_in_model(
														    snake_case							,				snake_case							,				snake_case							,				dtype=bnb_quantization_config.torch_dtype							,				offload_folder=snake_case							,				offload_state_dict=snake_case							,				keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules							,				offload_abit_bnb=load_in_abit and offload							,				)
														return dispatch_model(snake_case							,				device_map=snake_case							,				offload_dir=snake_case     )


def      UpperCamelCase_(	snake_case							:       Union[str, Any]							,				snake_case							:       List[str]							,				snake_case							:       Optional[Any]=None							,				snake_case							:       Any=None							,				snake_case							:       Any=None     ):

							'''simple docstring'''






							if device_map is None:
														if torch.cuda.is_available():
																					snake_case_						=      {"": torch.cuda.current_device()}
														else:
																					raise RuntimeError("No GPU found. A GPU is needed for quantization."     )
														logger.info("The device_map was not initialized." "Setting device_map to `{'':torch.cuda.current_device()}`."     )

							if isinstance(snake_case							,				snake_case     ):
														if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]:
																					raise ValueError(
																					    "If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or "
																					    "'sequential'."     )

														snake_case_						=      {}
														special_dtypes.update(
														    {
														        name: bnb_quantization_config.torch_dtype
														        for name, _ in model.named_parameters()
														        if any(m in name for m in bnb_quantization_config.skip_modules     )
														    }     )
														special_dtypes.update(
														    {
														        name: torch.floataa
														        for name, _ in model.named_parameters()
														        if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules     )
														    }     )

														snake_case_						=      {}
														snake_case_						=      special_dtypes
														snake_case_						=      no_split_module_classes
														snake_case_						=      bnb_quantization_config.target_dtype

														# get max_memory for each device.
														if device_map != "sequential":
																					snake_case_						=      get_balanced_memory(
																					    snake_case							,				low_zero=(device_map == "balanced_low_0")							,				max_memory=snake_case							,				**snake_case							,				)

														snake_case_						=      max_memory
														snake_case_						=      infer_auto_device_map(snake_case							,				**snake_case     )

							if isinstance(snake_case							,				snake_case     ):
														# check if don't have any quantized module on the cpu
														snake_case_						=      bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules

														snake_case_						=      {
														    key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert
														}
														for device in ["cpu", "disk"]:
																					if device in device_map_without_some_modules.values():
																												if bnb_quantization_config.load_in_abit:
																																			raise ValueError(
																																			    "\n                        Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit\n                        the quantized model. If you want to dispatch the model on the CPU or the disk while keeping\n                        these modules in `torch_dtype`, you need to pass a custom `device_map` to\n                        `load_and_quantize_model`. Check\n                        https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk\n                        for more details.\n                        "     )
																												else:
																																			logger.info(
																																			    "Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit"     )
														del device_map_without_some_modules
							return device_map


def      UpperCamelCase_(	snake_case							:       Tuple							,				snake_case							:       str							,				snake_case							:       int=None							,				snake_case							:       Optional[Any]=None     ):

							'''simple docstring'''






							if modules_to_not_convert is None:
														snake_case_						=      []

							snake_case_					,      snake_case_						=      _replace_with_bnb_layers(
							    snake_case							,				snake_case							,				snake_case							,				snake_case     )
							if not has_been_replaced:
														logger.warning(
														    "You are loading your model in 8bit or 4bit but no linear modules were found in your model."
														    " this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers."
														    " Please double check your model architecture, or submit an issue on github if you think this is"
														    " a bug."     )
							return model


def      UpperCamelCase_(	snake_case							:       List[Any]							,				snake_case							:       Optional[int]							,				snake_case							:       int=None							,				snake_case							:       Any=None							,				):

							'''simple docstring'''






							snake_case_						=      False
							for name, module in model.named_children():
														if current_key_name is None:
																					snake_case_						=      []
														current_key_name.append(snake_case     )
														if isinstance(snake_case							,				nn.Linear     ) and name not in modules_to_not_convert:
																					# Check if the current key is not in the `modules_to_not_convert`
																					snake_case_						=      ".".join(snake_case     )
																					snake_case_						=      True
																					for key in modules_to_not_convert:
																												if (
																												    (key in current_key_name_str) and (key + "." in current_key_name_str)
																												) or key == current_key_name_str:
																																			snake_case_						=      False
																																			break
																					if proceed:
																												# Load bnb module with empty weight and replace ``nn.Linear` module
																												if bnb_quantization_config.load_in_abit:
																																			snake_case_						=      bnb.nn.LinearabitLt(
																																			    module.in_features							,				module.out_features							,				module.bias is not None							,				has_fpaa_weights=snake_case							,				threshold=bnb_quantization_config.llm_inta_threshold							,				)
																												elif bnb_quantization_config.load_in_abit:
																																			snake_case_						=      bnb.nn.Linearabit(
																																			    module.in_features							,				module.out_features							,				module.bias is not None							,				bnb_quantization_config.bnb_abit_compute_dtype							,				compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant							,				quant_type=bnb_quantization_config.bnb_abit_quant_type							,				)
																												else:
																																			raise ValueError("load_in_8bit and load_in_4bit can't be both False"     )
																												snake_case_						=      module.weight.data
																												if module.bias is not None:
																																			snake_case_						=      module.bias.data
																												bnb_module.requires_grad_(snake_case     )
																												setattr(snake_case							,				snake_case							,				snake_case     )
																												snake_case_						=      True
														if len(list(module.children()     )     ) > 0:
																					snake_case_					,      snake_case_						=      _replace_with_bnb_layers(
																					    snake_case							,				snake_case							,				snake_case							,				snake_case     )
																					snake_case_						=      has_been_replaced | _has_been_replaced
														# Remove the last key for recursion
														current_key_name.pop(-1     )
							return model, has_been_replaced


def      UpperCamelCase_(	snake_case							:       Optional[Any]     ):

							'''simple docstring'''






							with init_empty_weights():
														snake_case_						=      deepcopy(snake_case     )  # this has 0 cost since it is done inside `init_empty_weights` context manager`

							snake_case_						=      find_tied_parameters(snake_case     )
							# For compatibility with Accelerate < 0.18
							if isinstance(snake_case							,				snake_case     ):
														snake_case_						=      sum(list(tied_params.values()     )							,				[]     ) + list(tied_params.keys()     )
							else:
														snake_case_						=      sum(snake_case							,				[]     )
							snake_case_						=      len(snake_case     ) > 0

							# Check if it is a base model
							snake_case_						=      False
							if hasattr(snake_case							,				"base_model_prefix"     ):
														snake_case_						=      not hasattr(snake_case							,				model.base_model_prefix     )

							# Ignore this for base models (BertModel, GPT2Model, etc.)
							if (not has_tied_params) and is_base_model:
														return []

							# otherwise they have an attached head
							snake_case_						=      list(model.named_children()     )
							snake_case_						=      [list_modules[-1][0]]

							# add last module together with tied weights
							snake_case_						=      set(snake_case     ) - set(snake_case     )
							snake_case_						=      list(set(snake_case     )     ) + list(snake_case     )

							# remove ".weight" from the keys
							snake_case_						=      [".weight", ".bias"]
							snake_case_						=      []
							for name in list_untouched:
														for name_to_remove in names_to_remove:
																					if name_to_remove in name:
																												snake_case_						=      name.replace(snake_case							,				""     )
														filtered_module_names.append(snake_case     )

							return filtered_module_names


def      UpperCamelCase_(	snake_case							:       List[Any]     ):

							'''simple docstring'''






							for m in model.modules():
														if isinstance(snake_case							,				bnb.nn.Linearabit     ):
																					return True
							return False


def      UpperCamelCase_(	snake_case							:       nn.Module     ):

							'''simple docstring'''






							return next(parameter.parameters()     ).device




def      UpperCamelCase_(	snake_case							:       int							,				snake_case							:       Optional[Any]							,				snake_case							:       Union[str, Any]							,				snake_case							:       Optional[int]							,				snake_case							:       Dict							,				snake_case							:       int							,				snake_case							:       int     ):

							'''simple docstring'''






							if fpaa_statistics is None:
														set_module_tensor_to_device(snake_case							,				snake_case							,				0							,				dtype=snake_case							,				value=snake_case     )
														snake_case_						=      param_name
														snake_case_						=      model
														if "." in tensor_name:
																					snake_case_						=      tensor_name.split("."     )
																					for split in splits[:-1]:
																												snake_case_						=      getattr(snake_case							,				snake_case     )
																												if new_module is None:
																																			raise ValueError(f'{module} has no attribute {split}.'     )
																												snake_case_						=      new_module
																					snake_case_						=      splits[-1]
														# offload weights
														snake_case_						=      False
														offload_weight(module._parameters[tensor_name]							,				snake_case							,				snake_case							,				index=snake_case     )
														if hasattr(module._parameters[tensor_name]							,				"SCB"     ):
																					offload_weight(
																					    module._parameters[tensor_name].SCB							,				param_name.replace("weight"							,				"SCB"     )							,				snake_case							,				index=snake_case							,				)
							else:
														offload_weight(snake_case							,				snake_case							,				snake_case							,				index=snake_case     )
														offload_weight(snake_case							,				param_name.replace("weight"							,				"SCB"     )							,				snake_case							,				index=snake_case     )

							set_module_tensor_to_device(snake_case							,				snake_case							,				"meta"							,				dtype=snake_case							,				value=torch.empty(*param.size()     )     )








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


SCREAMING_SNAKE_CASE :    int									=				logging.getLogger(__name__)


SCREAMING_SNAKE_CASE :    Dict									=				list(MODEL_WITH_LM_HEAD_MAPPING.keys())
SCREAMING_SNAKE_CASE :    Any									=				tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)



@dataclass
class 			_UpperCAmelCase :






		'''simple docstring'''

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



@dataclass
class 			_UpperCAmelCase :






		'''simple docstring'''

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

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

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






def 		lowercase							(     _snake_case						:      DataTrainingArguments     ,   _snake_case						:      PreTrainedTokenizer     ,   _snake_case						:      bool = False     ,   _snake_case						:      Optional[str] = None     ,   )     ->Any:
	"""simple docstring"""





	def _dataset(_snake_case						:      List[Any]     ,   _snake_case						:      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=_snake_case     ,   file_path=_snake_case     ,   block_size=args.block_size     ,   ref_path=_snake_case     ,   )

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

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






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





	__snake_case	:						List[Any]						=				HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)     )
	__snake_case	,							__snake_case	,							__snake_case	:						Union[str, Any]						=				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'''     ,   _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:
		__snake_case	:						Optional[Any]						=				AutoConfig.from_pretrained(model_args.config_name     ,   cache_dir=model_args.cache_dir     )
	elif model_args.model_name_or_path:
		__snake_case	:						Optional[Any]						=				AutoConfig.from_pretrained(model_args.model_name_or_path     ,   cache_dir=model_args.cache_dir     )
	else:
		__snake_case	:						Tuple						=				CONFIG_MAPPING[model_args.model_type]()
		logger.warning('''You are instantiating a new config instance from scratch.'''     )

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

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

	# Get datasets

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

    # Initialize our Trainer
	__snake_case	:						Optional[int]						=				Trainer(
	    model=_snake_case     ,   args=_snake_case     ,   data_collator=_snake_case     ,   train_dataset=_snake_case     ,   eval_dataset=_snake_case     ,   prediction_loss_only=_snake_case     ,   )

	# Training
	if training_args.do_train:
		__snake_case	:						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=_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
	__snake_case	:						int						=				{}
	if training_args.do_eval:
		logger.info('''*** Evaluate ***'''     )

		__snake_case	:						Dict						=				trainer.evaluate()

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

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

		results.update(_snake_case     )

	return results






def 		lowercase							(     _snake_case						:      Optional[int]     )     ->Tuple:
	"""simple docstring"""





	main()


if __name__ == "__main__":
			main()





