


"""simple docstring"""
import importlib.metadata
import warnings
from copy import deepcopy

from packaging import version

from ..utils import logging
from .import_utils import is_accelerate_available, is_bitsandbytes_available


if is_bitsandbytes_available():
			import bitsandbytes as bnb
			import torch
			import torch.nn as nn

			from ..pytorch_utils import ConvaD

if is_accelerate_available():
			from accelerate import init_empty_weights
			from accelerate.utils import find_tied_parameters

SCREAMING_SNAKE_CASE :    int									=				logging.get_logger(__name__)






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





	if "." in tensor_name:
		__snake_case	:						Optional[int]						=				tensor_name.split('''.'''     )
		for split in splits[:-1]:
			__snake_case	:						Dict						=				getattr(_snake_case     ,   _snake_case     )
			if new_module is None:
				raise ValueError(f"""{module} has no attribute {split}."""     )
			__snake_case	:						Tuple						=				new_module
		__snake_case	:						List[Any]						=				splits[-1]

	if tensor_name not in module._parameters and tensor_name not in module._buffers:
		raise ValueError(f"""{module} does not have a parameter or a buffer named {tensor_name}."""     )
	__snake_case	:						str						=				tensor_name in module._buffers
	__snake_case	:						Dict						=				getattr(_snake_case     ,   _snake_case     )

	if old_value.device == torch.device('''meta'''     ) and device not in ["meta", torch.device('''meta'''     )] and value is None:
		raise ValueError(f"""{tensor_name} is on the meta device, we need a `value` to put in on {device}."""     )

	__snake_case	:						List[str]						=				False
	__snake_case	:						Any						=				False
	if is_buffer or not is_bitsandbytes_available():
		__snake_case	:						Dict						=				False
		__snake_case	:						int						=				False
	else:
		__snake_case	:						List[str]						=				hasattr(bnb.nn     ,   '''Params4bit'''     ) and isinstance(module._parameters[tensor_name]     ,   bnb.nn.Paramsabit     )
		__snake_case	:						Optional[Any]						=				isinstance(module._parameters[tensor_name]     ,   bnb.nn.IntaParams     )

	if is_abit or is_abit:
		__snake_case	:						int						=				module._parameters[tensor_name]
		if param.device.type != "cuda":
			if value is None:
				__snake_case	:						Optional[int]						=				old_value.to(_snake_case     )
			elif isinstance(_snake_case     ,   torch.Tensor     ):
				__snake_case	:						Any						=				value.to('''cpu'''     )
				if value.dtype == torch.inta:
					__snake_case	:						List[Any]						=				version.parse(importlib.metadata.version('''bitsandbytes'''     )     ) > version.parse(
					    '''0.37.2'''     )
					if not is_abit_serializable:
						raise ValueError(
						    '''Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. '''
						    '''Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.'''     )
			else:
				__snake_case	:						Any						=				torch.tensor(_snake_case     ,   device='''cpu'''     )

			# Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization.
			# Since weights are saved in the correct "orientation", we skip transposing when loading.
			if issubclass(module.source_cls     ,   _snake_case     ) and fpaa_statistics is None:
				__snake_case	:						Optional[int]						=				new_value.T

			__snake_case	:						str						=				old_value.__dict__
			if is_abit:
				__snake_case	:						Optional[Any]						=				bnb.nn.IntaParams(_snake_case     ,   requires_grad=_snake_case     ,   **_snake_case     ).to(_snake_case     )
			elif is_abit:
				__snake_case	:						Dict						=				bnb.nn.Paramsabit(_snake_case     ,   requires_grad=_snake_case     ,   **_snake_case     ).to(_snake_case     )

			__snake_case	:						Union[str, Any]						=				new_value
			if fpaa_statistics is not None:
				setattr(module.weight     ,   '''SCB'''     ,   fpaa_statistics.to(_snake_case     )     )

	else:
		if value is None:
			__snake_case	:						Optional[Any]						=				old_value.to(_snake_case     )
		elif isinstance(_snake_case     ,   torch.Tensor     ):
			__snake_case	:						Union[str, Any]						=				value.to(_snake_case     )
		else:
			__snake_case	:						List[Any]						=				torch.tensor(_snake_case     ,   device=_snake_case     )

		if is_buffer:
			__snake_case	:						Union[str, Any]						=				new_value
		else:
			__snake_case	:						List[Any]						=				nn.Parameter(_snake_case     ,   requires_grad=old_value.requires_grad     )
			__snake_case	:						List[str]						=				new_value






def 		lowercase							(     _snake_case						:      List[Any]     ,   _snake_case						:      Tuple=None     ,   _snake_case						:      List[str]=None     ,   _snake_case						:      Optional[int]=None     ,   _snake_case						:      List[str]=False     )     ->List[Any]:
	"""simple docstring"""





	for name, module in model.named_children():
		if current_key_name is None:
			__snake_case	:						Optional[int]						=				[]
		current_key_name.append(_snake_case     )

		if (isinstance(_snake_case     ,   nn.Linear     ) or isinstance(_snake_case     ,   _snake_case     )) and name not in modules_to_not_convert:
			# Check if the current key is not in the `modules_to_not_convert`
			if not any(key in '''.'''.join(_snake_case     ) for key in modules_to_not_convert     ):
				with init_empty_weights():
					if isinstance(_snake_case     ,   _snake_case     ):
						__snake_case	,							__snake_case	:						List[Any]						=				module.weight.shape
					else:
						__snake_case	:						List[Any]						=				module.in_features
						__snake_case	:						Any						=				module.out_features

					if quantization_config.quantization_method() == "llm_int8":
						__snake_case	:						Any						=				bnb.nn.LinearabitLt(
						    _snake_case     ,   _snake_case     ,   module.bias is not None     ,   has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight     ,   threshold=quantization_config.llm_inta_threshold     ,   )
						__snake_case	:						List[str]						=				True
					else:
						if (
						    quantization_config.llm_inta_skip_modules is not None
						    and name in quantization_config.llm_inta_skip_modules
						):
							pass
						else:
							__snake_case	:						Optional[int]						=				bnb.nn.Linearabit(
							    _snake_case     ,   _snake_case     ,   module.bias is not None     ,   quantization_config.bnb_abit_compute_dtype     ,   compress_statistics=quantization_config.bnb_abit_use_double_quant     ,   quant_type=quantization_config.bnb_abit_quant_type     ,   )
							__snake_case	:						str						=				True
                    # Store the module class in case we need to transpose the weight later
					__snake_case	:						List[Any]						=				type(_snake_case     )
					# Force requires grad to False to avoid unexpected errors
					model._modules[name].requires_grad_(_snake_case     )
		if len(list(module.children()     )     ) > 0:
			__snake_case	,							__snake_case	:						Union[str, Any]						=				_replace_with_bnb_linear(
			    _snake_case     ,   _snake_case     ,   _snake_case     ,   _snake_case     ,   has_been_replaced=_snake_case     ,   )
		# Remove the last key for recursion
		current_key_name.pop(-1     )
	return model, has_been_replaced






def 		lowercase							(     _snake_case						:      Dict     ,   _snake_case						:      Union[str, Any]=None     ,   _snake_case						:      List[str]=None     ,   _snake_case						:      Any=None     )     ->int:
	"""simple docstring"""





	__snake_case	:						str						=				['''lm_head'''] if modules_to_not_convert is None else modules_to_not_convert
	__snake_case	,							__snake_case	:						Optional[Any]						=				_replace_with_bnb_linear(
	    _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.'''
		    ''' Please double check your model architecture, or submit an issue on github if you think this is'''
		    ''' a bug.'''     )

	return model






def 		lowercase							(     *_snake_case						:      Optional[Any]     ,   **_snake_case						:      List[str]     )     ->List[Any]:
	"""simple docstring"""





	warnings.warn(
	    '''`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead'''     ,   _snake_case     ,   )
	return replace_with_bnb_linear(*_snake_case     ,   **_snake_case     )






def 		lowercase							(     *_snake_case						:      Any     ,   **_snake_case						:      Dict     )     ->List[Any]:
	"""simple docstring"""





	warnings.warn(
	    '''`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead'''     ,   _snake_case     ,   )
	return set_module_quantized_tensor_to_device(*_snake_case     ,   **_snake_case     )






def 		lowercase							(     _snake_case						:      Union[str, Any]     )     ->Optional[int]:
	"""simple docstring"""





	__snake_case	:						List[str]						=				deepcopy(_snake_case     )  # this has 0 cost since it is done inside `init_empty_weights` context manager`
	tied_model.tie_weights()

	__snake_case	:						Optional[int]						=				find_tied_parameters(_snake_case     )
	# For compatibility with Accelerate < 0.18
	if isinstance(_snake_case     ,   _snake_case     ):
		__snake_case	:						str						=				sum(list(tied_params.values()     )     ,   []     ) + list(tied_params.keys()     )
	else:
		__snake_case	:						str						=				sum(_snake_case     ,   []     )
	__snake_case	:						Tuple						=				len(_snake_case     ) > 0

	# Check if it is a base model
	__snake_case	:						List[str]						=				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[str]						=				list(model.named_children()     )
	__snake_case	:						Optional[int]						=				[list_modules[-1][0]]

	# add last module together with tied weights
	__snake_case	:						Optional[int]						=				set(_snake_case     ) - set(_snake_case     )
	__snake_case	:						List[str]						=				list(set(_snake_case     )     ) + list(_snake_case     )

	# remove ".weight" from the keys
	__snake_case	:						int						=				['''.weight''', '''.bias''']
	__snake_case	:						str						=				[]
	for name in list_untouched:
		for name_to_remove in names_to_remove:
			if name_to_remove in name:
				__snake_case	:						Dict						=				name.replace(_snake_case     ,   ''''''     )
		filtered_module_names.append(_snake_case     )

	return filtered_module_names









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





