


from dataclasses import dataclass, field
from typing import Optional


@dataclass
class        _a							:
							_lowercase	:			Optional[str]        = field(
							    default='''codeparrot/codeparrot'''     ,	metadata={'''help''': '''Model name or path of model to be trained.'''}			)
							_lowercase	:			Optional[str]        = field(
							    default='''./'''     ,	metadata={'''help''': '''Save dir where model repo is cloned and models updates are saved to.'''}			)
							_lowercase	:			Optional[str]        = field(
							    default='''codeparrot/codeparrot-clean-train'''     ,	metadata={'''help''': '''Name or path of training dataset.'''}			)
							_lowercase	:			Optional[str]        = field(
							    default='''codeparrot/codeparrot-clean-valid'''     ,	metadata={'''help''': '''Name or path of validation dataset.'''}			)
							_lowercase	:			Optional[int]        = field(default=2     ,	metadata={'''help''': '''Batch size for training.'''}			)
							_lowercase	:			Optional[int]        = field(default=2     ,	metadata={'''help''': '''Batch size for evaluation.'''}			)
							_lowercase	:			Optional[float]        = field(default=0.1     ,	metadata={'''help''': '''Value of weight decay.'''}			)
							_lowercase	:			Optional[int]        = field(
							    default=10000     ,	metadata={'''help''': '''Size of buffer used to shuffle streaming dataset.'''}			)
							_lowercase	:			Optional[float]        = field(default=2e-4     ,	metadata={'''help''': '''Learning rate fo training.'''}			)
							_lowercase	:			Optional[str]        = field(default='''cosine'''     ,	metadata={'''help''': '''Learning rate.'''}			)
							_lowercase	:			Optional[int]        = field(
							    default=750     ,	metadata={'''help''': '''Number of warmup steps in the learning rate schedule.'''}			)
							_lowercase	:			Optional[int]        = field(
							    default=16     ,	metadata={'''help''': '''Number of gradient accumulation steps.'''}			)
							_lowercase	:			Optional[bool]        = field(
							    default=UpperCamelCase__     ,	metadata={'''help''': '''Use gradient checkpointing to reduce memory footprint.'''}			)
							_lowercase	:			Optional[int]        = field(default=50000     ,	metadata={'''help''': '''Maximum number of training steps.'''}			)
							_lowercase	:			Optional[int]        = field(
							    default=-1     ,	metadata={'''help''': '''Maximum number of evaluation steps. If -1 the full dataset is evaluated.'''}			)
							_lowercase	:			Optional[int]        = field(default=1024     ,	metadata={'''help''': '''Sequence lengths used for training.'''}			)
							_lowercase	:			Optional[int]        = field(default=1     ,	metadata={'''help''': '''Training seed.'''}			)
							_lowercase	:			Optional[int]        = field(
							    default=1024     ,	metadata={'''help''': '''Interval to save checkpoints. Measured as number of forward passes not training steps.'''}     ,	)
							_lowercase	:			Optional[str]        = field(
							    default=UpperCamelCase__     ,	metadata={'''help''': '''States path if the training should continue from a checkpoint folder.'''}			)
							_lowercase	:			Optional[bool]        = field(default=UpperCamelCase__     ,	metadata={'''help''': '''If True the data is pretokenized.'''}			)


@dataclass
class        _a							:
							_lowercase	:			Optional[str]        = field(
							    default='''codeparrot/codeparrot'''     ,	metadata={'''help''': '''Model name or path of model to be evaluated.'''}			)
							_lowercase	:			Optional[str]        = field(
							    default='''codeparrot/codeparrot-clean-valid'''     ,	metadata={'''help''': '''Name or path of validation dataset.'''}			)
							_lowercase	:			Optional[int]        = field(default=2     ,	metadata={'''help''': '''Batch size used for evaluation.'''}			)
							_lowercase	:			Optional[int]        = field(
							    default=-1     ,	metadata={'''help''': '''Maximum number of evaluation steps. If -1 the full dataset is evaluated.'''}			)
							_lowercase	:			Optional[int]        = field(default=1024     ,	metadata={'''help''': '''Length of sequences to be evaluated.'''}			)
							_lowercase	:			Optional[int]        = field(default=1     ,	metadata={'''help''': '''Random seed used for evaluation.'''}			)


@dataclass
class        _a							:
							_lowercase	:			Optional[str]        = field(
							    default='''codeparrot/codeparrot'''     ,	metadata={'''help''': '''Model name or path of model to be evaluated.'''}			)
							_lowercase	:			Optional[int]        = field(default=UpperCamelCase__     ,	metadata={'''help''': '''Number of workers used for code evaluation.'''}			)
							_lowercase	:			Optional[int]        = field(
							    default=UpperCamelCase__     ,	metadata={'''help''': '''The number of human-eval tasks to run. If not included all tasks are evaluated.'''}     ,	)
							_lowercase	:			Optional[bool]        = field(
							    default=UpperCamelCase__     ,	metadata={'''help''': '''Sample from the language model\'s output distribution.'''}			)
							_lowercase	:			Optional[float]        = field(default=0.2     ,	metadata={'''help''': '''Sampling temperature used for generation.'''}			)
							_lowercase	:			Optional[int]        = field(default=256     ,	metadata={'''help''': '''Maximum number of newly generated tokens.'''}			)
							_lowercase	:			Optional[int]        = field(default=0     ,	metadata={'''help''': '''Top-k parameter used for generation.'''}			)
							_lowercase	:			Optional[float]        = field(default=0.95     ,	metadata={'''help''': '''Top-p parameter used for nucleus sampling.'''}			)
							_lowercase	:			Optional[int]        = field(default=10     ,	metadata={'''help''': '''Number of generations to run in parallel.'''}			)
							_lowercase	:			Optional[int]        = field(
							    default=200     ,	metadata={'''help''': '''Number of completions to generate for each sample.'''}			)
							_lowercase	:			Optional[int]        = field(default=1     ,	metadata={'''help''': '''Random seed used for evaluation.'''}			)
							_lowercase	:			Optional[str]        = field(
							    default='''eval_results.json'''     ,	metadata={'''help''': '''Random seed used for evaluation.'''}			)
							_lowercase	:			Optional[str]        = field(
							    default='''0'''     ,	metadata={'''help''': '''Allow `code_eval` to execute Python code on machine'''}			)
							_lowercase	:			Optional[int]        = field(
							    default=-1     ,	metadata={
							        '''help''': (
							            '''Determine which device to run the `text-generation` Pipeline on. -1 is CPU and any zero or positive'''
							            ''' number corresponds to which GPU device id to run on.'''
							        )
							    }     ,	)


@dataclass
class        _a							:
							_lowercase	:			Optional[int]        = field(
							    default=UpperCamelCase__     ,	metadata={
							        '''help''': '''The number of CPU cores to use for parallel preprocessing. Default uses the maximum available.'''
							    }     ,	)
							_lowercase	:			Optional[str]        = field(
							    default='''transformersbook/codeparrot'''     ,	metadata={'''help''': '''Folder or name of dataset to process.'''}			)
							_lowercase	:			Optional[str]        = field(
							    default='''codeparrot-clean'''     ,	metadata={'''help''': '''Folder to save processed processed dataset.'''}			)
							_lowercase	:			Optional[int]        = field(
							    default=100000     ,	metadata={'''help''': '''Number of files to save per JSON output file.'''}			)
							_lowercase	:			Optional[str]        = field(default='''content'''     ,	metadata={'''help''': '''Column containing text data to process.'''}			)
							_lowercase	:			Optional[float]        = field(
							    default=1000     ,	metadata={'''help''': '''Maximum line length in file, otherwise file is filtered.'''}			)
							_lowercase	:			Optional[float]        = field(
							    default=100     ,	metadata={'''help''': '''Maximum mean line length in file, otherwise file is filtered.'''}			)
							_lowercase	:			Optional[float]        = field(
							    default=0.25     ,	metadata={'''help''': '''Maximum fraction of non-alphanumeric characters, otherwise file is filtered.'''}			)
							_lowercase	:			Optional[float]        = field(
							    default=1.5     ,	metadata={'''help''': '''Minimum character token ratio for the file, otherwise file is filtered.'''}			)
							_lowercase	:			Optional[float]        = field(
							    default=0.7     ,	metadata={'''help''': '''Probability for filtering config, test and uncommon files.'''}			)
							_lowercase	:			Optional[str]        = field(
							    default='''codeparrot/codeparrot'''     ,	metadata={'''help''': '''Name or path to the tokenizer.'''}     ,	)
							_lowercase	:			Optional[bool]        = field(
							    default=UpperCamelCase__     ,	metadata={'''help''': '''If True, near-duplicate samples are removed.'''}			)
							_lowercase	:			Optional[float]        = field(
							    default=0.85     ,	metadata={'''help''': '''Jaccard threshold for near-duplicate samples.'''}			)


@dataclass
class        _a							:
							_lowercase	:			Optional[str]        = field(
							    default='''gpt2'''     ,	metadata={'''help''': '''Base tokenizer to build new tokenizer from.'''}			)
							_lowercase	:			Optional[str]        = field(
							    default='''transformersbook/codeparrot-train'''     ,	metadata={'''help''': '''Dataset to train tokenizer on.'''}			)
							_lowercase	:			Optional[str]        = field(default='''content'''     ,	metadata={'''help''': '''Column containing text data to process.'''}			)
							_lowercase	:			Optional[int]        = field(default=200000     ,	metadata={'''help''': '''Number of examples to train tokenizer on.'''}			)
							_lowercase	:			Optional[int]        = field(
							    default=32768     ,	metadata={'''help''': '''Number of examples to train the tokenizer on.'''}			)
							_lowercase	:			Optional[str]        = field(default='''codeparrot'''     ,	metadata={'''help''': '''Name of new tokenizer.'''}			)
							_lowercase	:			Optional[bool]        = field(default=UpperCamelCase__     ,	metadata={'''help''': '''Push saved tokenizer to the hub.'''}			)


@dataclass
class        _a							:
							_lowercase	:			Optional[str]        = field(
							    default='''codeparrot/codeparrot'''     ,	metadata={'''help''': '''Name or path to the tokenizer.'''}			)
							_lowercase	:			Optional[str]        = field(
							    default='''codeparrot/codeparrot-clean-train'''     ,	metadata={'''help''': '''Name or path to the dataset to pretokenize.'''}			)
							_lowercase	:			Optional[str]        = field(
							    default='''tokenized-codeparrot-train'''     ,	metadata={'''help''': '''Repo name of the pretokenized data.'''}			)
							_lowercase	:			Optional[int]        = field(default=UpperCamelCase__     ,	metadata={'''help''': '''Number of workers used for code evaluation.'''}			)


@dataclass
class        _a							:
							_lowercase	:			Optional[str]        = field(
							    default='''gpt2-large'''     ,	metadata={'''help''': '''Configuration to use for model initialization.'''}			)
							_lowercase	:			Optional[str]        = field(
							    default='''codeparrot/codeparrot'''     ,	metadata={'''help''': '''Tokenizer attached to model.'''}			)
							_lowercase	:			Optional[str]        = field(default='''codeparrot'''     ,	metadata={'''help''': '''Name of the created model.'''}			)
							_lowercase	:			Optional[bool]        = field(default=UpperCamelCase__     ,	metadata={'''help''': '''Push saved tokenizer to the hub.'''}			)






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


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

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

							_lowercase	:			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).'''
							        )
							    }     ,	)
							_lowercase	:			bool        = field(
							    default=UpperCamelCase__     ,	metadata={'''help''': '''Overwrite the cached training and evaluation sets'''}			)
def 			_a (      SCREAMING_SNAKE_CASE						,				SCREAMING_SNAKE_CASE						,				SCREAMING_SNAKE_CASE = False						,				SCREAMING_SNAKE_CASE = None						,				):


		"""simple docstring"""




		def _dataset(SCREAMING_SNAKE_CASE						,				SCREAMING_SNAKE_CASE=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"""




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

		if model_args.tokenizer_name:
				lowercase__            =      AutoTokenizer.from_pretrained(model_args.tokenizer_name						,				cache_dir=model_args.cache_dir     )
		elif model_args.model_name_or_path:
				lowercase__            =      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:
				lowercase__            =      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'''     )
				lowercase__            =      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:
				lowercase__            =      tokenizer.max_len
				# Our input block size will be the max possible for the model
		else:
				lowercase__            =      min(data_args.block_size						,				tokenizer.max_len     )

		# Get datasets

		lowercase__            =      (
		    get_dataset(SCREAMING_SNAKE_CASE						,				tokenizer=SCREAMING_SNAKE_CASE						,				cache_dir=model_args.cache_dir     ) if training_args.do_train else None
		)
		lowercase__            =      (
		    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":
				lowercase__            =      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:
						lowercase__            =      DataCollatorForWholeWordMask(
						    tokenizer=SCREAMING_SNAKE_CASE						,				mlm_probability=data_args.mlm_probability     )
				else:
						lowercase__            =      DataCollatorForLanguageModeling(
						    tokenizer=SCREAMING_SNAKE_CASE						,				mlm=data_args.mlm						,				mlm_probability=data_args.mlm_probability     )

    # Initialize our Trainer
		lowercase__            =      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:
				lowercase__            =      (
				    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
		lowercase__            =      {}
		if training_args.do_eval:
				logger.info('''*** Evaluate ***'''     )

				lowercase__            =      trainer.evaluate()

				lowercase__            =      math.exp(eval_output['''eval_loss''']     )
				lowercase__            =      {'''perplexity''': perplexity}

				lowercase__            =      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     ):


		"""simple docstring"""




		main()


if __name__ == "__main__":
			main()


