


from __future__ import annotations

import copy
import inspect
import json
import math
import os
import tempfile
import unittest
from importlib import import_module

import numpy as np

from transformers import ViTMAEConfig
from transformers.file_utils import cached_property, is_tf_available, is_vision_available
from transformers.testing_utils import require_tf, require_vision, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
			import tensorflow as tf

			from transformers import TFViTMAEForPreTraining, TFViTMAEModel


if is_vision_available():
			from PIL import Image

			from transformers import ViTImageProcessor


class        _a							:

							def __init__(							self:	int    ,						UpperCamelCase_:	Tuple    ,						UpperCamelCase_:	Optional[int]=13    ,						UpperCamelCase_:	Union[str, Any]=30    ,						UpperCamelCase_:	List[Any]=2    ,						UpperCamelCase_:	Tuple=3    ,						UpperCamelCase_:	Tuple=True    ,						UpperCamelCase_:	Optional[int]=True    ,						UpperCamelCase_:	Optional[Any]=32    ,						UpperCamelCase_:	Optional[Any]=2    ,						UpperCamelCase_:	List[Any]=4    ,						UpperCamelCase_:	Tuple=37    ,						UpperCamelCase_:	List[Any]="gelu"    ,						UpperCamelCase_:	List[str]=0.1    ,						UpperCamelCase_:	List[str]=0.1    ,						UpperCamelCase_:	int=10    ,						UpperCamelCase_:	Tuple=0.02    ,						UpperCamelCase_:	Optional[int]=3    ,						UpperCamelCase_:	Dict=0.6    ,						UpperCamelCase_:	int=None    ,						)			->   List[str]:





									"""simple docstring"""







									lowercase__            =      parent
									lowercase__            =      batch_size
									lowercase__            =      image_size
									lowercase__            =      patch_size
									lowercase__            =      num_channels
									lowercase__            =      is_training
									lowercase__            =      use_labels
									lowercase__            =      hidden_size
									lowercase__            =      num_hidden_layers
									lowercase__            =      num_attention_heads
									lowercase__            =      intermediate_size
									lowercase__            =      hidden_act
									lowercase__            =      hidden_dropout_prob
									lowercase__            =      attention_probs_dropout_prob
									lowercase__            =      type_sequence_label_size
									lowercase__            =      initializer_range
									lowercase__            =      mask_ratio
									lowercase__            =      scope

									# in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above
									# (we add 1 for the [CLS] token)
									lowercase__            =      (image_size // patch_size) ** 2
									lowercase__            =      int(math.ceil((1 - mask_ratio) * (num_patches + 1)							)							)

							def       lowerCamelCase_ (							self:	Tuple							)			->   Optional[Any]:





									"""simple docstring"""







									lowercase__            =      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

									lowercase__            =      None
									if self.use_labels:
											lowercase__            =      ids_tensor([self.batch_size]    ,						self.type_sequence_label_size							)

									lowercase__            =      self.get_config()

									return config, pixel_values, labels

							def       lowerCamelCase_ (							self:	str							)			->   List[str]:





									"""simple docstring"""







									return ViTMAEConfig(
									    image_size=self.image_size    ,						patch_size=self.patch_size    ,						num_channels=self.num_channels    ,						hidden_size=self.hidden_size    ,						num_hidden_layers=self.num_hidden_layers    ,						num_attention_heads=self.num_attention_heads    ,						intermediate_size=self.intermediate_size    ,						decoder_hidden_size=self.hidden_size    ,						decoder_num_hidden_layers=self.num_hidden_layers    ,						decoder_num_attention_heads=self.num_attention_heads    ,						decoder_intermediate_size=self.intermediate_size    ,						hidden_act=self.hidden_act    ,						hidden_dropout_prob=self.hidden_dropout_prob    ,						attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,						is_decoder=UpperCamelCase_    ,						initializer_range=self.initializer_range    ,						mask_ratio=self.mask_ratio    ,						)

							def       lowerCamelCase_ (							self:	Optional[int]    ,						UpperCamelCase_:	Union[str, Any]    ,						UpperCamelCase_:	Dict    ,						UpperCamelCase_:	Optional[Any]							)			->   List[Any]:





									"""simple docstring"""







									lowercase__            =      TFViTMAEModel(config=UpperCamelCase_							)
									lowercase__            =      model(UpperCamelCase_    ,						training=UpperCamelCase_							)
									self.parent.assertEqual(result.last_hidden_state.shape    ,						(self.batch_size, self.seq_length, self.hidden_size)							)

							def       lowerCamelCase_ (							self:	Optional[int]    ,						UpperCamelCase_:	int    ,						UpperCamelCase_:	str    ,						UpperCamelCase_:	int							)			->   Any:





									"""simple docstring"""







									lowercase__            =      TFViTMAEForPreTraining(UpperCamelCase_							)
									lowercase__            =      model(UpperCamelCase_    ,						training=UpperCamelCase_							)
									# expected sequence length = num_patches
									lowercase__            =      (self.image_size // self.patch_size) ** 2
									lowercase__            =      self.patch_size**2 * self.num_channels
									self.parent.assertEqual(result.logits.shape    ,						(self.batch_size, num_patches, expected_num_channels)							)

									# test greyscale images
									lowercase__            =      1
									lowercase__            =      TFViTMAEForPreTraining(UpperCamelCase_							)

									lowercase__            =      floats_tensor([self.batch_size, 1, self.image_size, self.image_size]							)
									lowercase__            =      model(UpperCamelCase_    ,						training=UpperCamelCase_							)
									lowercase__            =      self.patch_size**2
									self.parent.assertEqual(result.logits.shape    ,						(self.batch_size, num_patches, expected_num_channels)							)


							def       lowerCamelCase_ (							self:	Tuple							)			->   Union[str, Any]:





									"""simple docstring"""







									lowercase__            =      self.prepare_config_and_inputs()
									((lowercase__)     ,		(lowercase__)     ,		(lowercase__))            =      config_and_inputs
									lowercase__            =      {'''pixel_values''': pixel_values}
									return config, inputs_dict


@require_tf
class        _a							(			UpperCamelCase__     ,	UpperCamelCase__     ,	unittest.TestCase			):
							_lowercase	:			List[Any]        = (TFViTMAEModel, TFViTMAEForPreTraining) if is_tf_available() else ()
							_lowercase	:			Union[str, Any]        = {'''feature-extraction''': TFViTMAEModel} if is_tf_available() else {}

							_lowercase	:			str        = False
							_lowercase	:			int        = False
							_lowercase	:			Optional[int]        = False
							_lowercase	:			str        = False

							def       lowerCamelCase_ (							self:	List[str]							)			->   Union[str, Any]:





									"""simple docstring"""







									lowercase__            =      TFViTMAEModelTester(self							)
									lowercase__            =      ConfigTester(self    ,						config_class=UpperCamelCase_    ,						has_text_modality=UpperCamelCase_    ,						hidden_size=37							)

							def       lowerCamelCase_ (							self:	Union[str, Any]							)			->   str:





									"""simple docstring"""







									self.config_tester.run_common_tests()

							@unittest.skip(reason='''ViTMAE does not use inputs_embeds'''							)
							def       lowerCamelCase_ (							self:	int							)			->   Tuple:





									"""simple docstring"""







									pass

							def       lowerCamelCase_ (							self:	int							)			->   Tuple:





									"""simple docstring"""







									lowercase__     ,		lowercase__            =      self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
											lowercase__            =      model_class(UpperCamelCase_							)
											self.assertIsInstance(model.get_input_embeddings()    ,						(tf.keras.layers.Layer)							)
											lowercase__            =      model.get_output_embeddings()
											self.assertTrue(x is None or isinstance(UpperCamelCase_    ,						tf.keras.layers.Layer							)							)

							def       lowerCamelCase_ (							self:	Union[str, Any]							)			->   Tuple:





									"""simple docstring"""







									lowercase__     ,		lowercase__            =      self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
											lowercase__            =      model_class(UpperCamelCase_							)
											lowercase__            =      inspect.signature(model.call							)
											# signature.parameters is an OrderedDict => so arg_names order is deterministic
											lowercase__            =      [*signature.parameters.keys()]

											lowercase__            =      ['''pixel_values''']
											self.assertListEqual(arg_names[:1]    ,						UpperCamelCase_							)

							def       lowerCamelCase_ (							self:	List[Any]							)			->   List[str]:





									"""simple docstring"""







									lowercase__            =      self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*UpperCamelCase_							)

							def       lowerCamelCase_ (							self:	Tuple							)			->   Any:





									"""simple docstring"""







									lowercase__            =      self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_pretraining(*UpperCamelCase_							)

							def       lowerCamelCase_ (							self:	Union[str, Any]							)			->   str:





									"""simple docstring"""







									np.random.seed(2							)

									lowercase__     ,		lowercase__            =      self.model_tester.prepare_config_and_inputs_for_common()

									lowercase__            =      int((config.image_size // config.patch_size) ** 2							)
									lowercase__            =      np.random.uniform(size=(self.model_tester.batch_size, num_patches)							)

									for model_class in self.all_model_classes:
											lowercase__            =      model_class(UpperCamelCase_							)
											lowercase__            =      self._prepare_for_class(UpperCamelCase_    ,						UpperCamelCase_							)

											lowercase__            =      model(UpperCamelCase_    ,						noise=UpperCamelCase_							)

											lowercase__            =      copy.deepcopy(self._prepare_for_class(UpperCamelCase_    ,						UpperCamelCase_							)							)
											lowercase__            =      model(**UpperCamelCase_    ,						noise=UpperCamelCase_							)
											lowercase__            =      outputs_dict[0].numpy()
											lowercase__            =      outputs_keywords[0].numpy()

											self.assertLess(np.sum(np.abs(output_dict - output_keywords							)							)    ,						1E-6							)

							def       lowerCamelCase_ (							self:	Dict							)			->   Tuple:





									"""simple docstring"""







									np.random.seed(2							)

									lowercase__     ,		lowercase__            =      self.model_tester.prepare_config_and_inputs_for_common()

									lowercase__            =      int((config.image_size // config.patch_size) ** 2							)
									lowercase__            =      np.random.uniform(size=(self.model_tester.batch_size, num_patches)							)

									def prepare_numpy_arrays(UpperCamelCase_:	Union[str, Any]							):
											lowercase__            =      {}
											for k, v in inputs_dict.items():
													if tf.is_tensor(UpperCamelCase_							):
															lowercase__            =      v.numpy()
													else:
															lowercase__            =      np.array(UpperCamelCase_							)

											return inputs_np_dict

									for model_class in self.all_model_classes:
											lowercase__            =      model_class(UpperCamelCase_							)

											lowercase__            =      self._prepare_for_class(UpperCamelCase_    ,						UpperCamelCase_							)
											lowercase__            =      prepare_numpy_arrays(UpperCamelCase_							)

											lowercase__            =      model(UpperCamelCase_    ,						noise=UpperCamelCase_							)
											lowercase__            =      model(**UpperCamelCase_    ,						noise=UpperCamelCase_							)
											self.assert_outputs_same(UpperCamelCase_    ,						UpperCamelCase_							)

							def       lowerCamelCase_ (							self:	str    ,						UpperCamelCase_:	Tuple    ,						UpperCamelCase_:	List[str]    ,						UpperCamelCase_:	List[Any]							)			->   Union[str, Any]:





									"""simple docstring"""







									np.random.seed(2							)

									lowercase__            =      int((tf_model.config.image_size // tf_model.config.patch_size) ** 2							)
									lowercase__            =      np.random.uniform(size=(self.model_tester.batch_size, num_patches)							)
									lowercase__            =      tf.constant(UpperCamelCase_							)

									# Add `noise` argument.
									# PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument
									lowercase__            =      tf_noise

									super().check_pt_tf_models(UpperCamelCase_    ,						UpperCamelCase_    ,						UpperCamelCase_							)

							def       lowerCamelCase_ (							self:	str							)			->   int:





									"""simple docstring"""







									np.random.seed(2							)

									lowercase__     ,		lowercase__            =      self.model_tester.prepare_config_and_inputs_for_common()

									lowercase__            =      {
									    module_member
									    for model_class in self.all_model_classes
									    for module in (import_module(model_class.__module__							),)
									    for module_member_name in dir(UpperCamelCase_							)
									    if module_member_name.endswith('''MainLayer'''							)
									    # This condition is required, since `modeling_tf_clip.py` has 3 classes whose names end with `MainLayer`.
									    and module_member_name[: -len('''MainLayer'''							)] == model_class.__name__[: -len('''Model'''							)]
									    for module_member in (getattr(UpperCamelCase_    ,						UpperCamelCase_							),)
									    if isinstance(UpperCamelCase_    ,						UpperCamelCase_							)
									    and tf.keras.layers.Layer in module_member.__bases__
									    and getattr(UpperCamelCase_    ,						'''_keras_serializable'''    ,						UpperCamelCase_							)
									}

									lowercase__            =      int((config.image_size // config.patch_size) ** 2							)
									lowercase__            =      np.random.uniform(size=(self.model_tester.batch_size, num_patches)							)
									lowercase__            =      tf.convert_to_tensor(UpperCamelCase_							)
									inputs_dict.update({'''noise''': noise}							)

									for main_layer_class in tf_main_layer_classes:
											lowercase__            =      main_layer_class(UpperCamelCase_							)

											lowercase__            =      {
											    name: tf.keras.Input(tensor.shape[1:]    ,						dtype=tensor.dtype							) for name, tensor in inputs_dict.items()
											}

											lowercase__            =      tf.keras.Model(UpperCamelCase_    ,						outputs=main_layer(UpperCamelCase_							)							)
											lowercase__            =      model(UpperCamelCase_							)

											with tempfile.TemporaryDirectory() as tmpdirname:
													lowercase__            =      os.path.join(UpperCamelCase_    ,						'''keras_model.h5'''							)
													model.save(UpperCamelCase_							)
													lowercase__            =      tf.keras.models.load_model(
													    UpperCamelCase_    ,						custom_objects={main_layer_class.__name__: main_layer_class}							)
													assert isinstance(UpperCamelCase_    ,						tf.keras.Model							)
													lowercase__            =      model(UpperCamelCase_							)
													self.assert_outputs_same(UpperCamelCase_    ,						UpperCamelCase_							)

							@slow
							def       lowerCamelCase_ (							self:	Optional[int]							)			->   Tuple:





									"""simple docstring"""







									np.random.seed(2							)

									lowercase__     ,		lowercase__            =      self.model_tester.prepare_config_and_inputs_for_common()

									lowercase__            =      int((config.image_size // config.patch_size) ** 2							)
									lowercase__            =      np.random.uniform(size=(self.model_tester.batch_size, num_patches)							)

									for model_class in self.all_model_classes:
											lowercase__            =      model_class(UpperCamelCase_							)
											lowercase__            =      self._prepare_for_class(UpperCamelCase_    ,						UpperCamelCase_							)
											lowercase__            =      model(UpperCamelCase_    ,						noise=UpperCamelCase_							)

											if model_class.__name__ == "TFViTMAEModel":
													lowercase__            =      outputs.last_hidden_state.numpy()
													lowercase__            =      0
											else:
													lowercase__            =      outputs.logits.numpy()
													lowercase__            =      0

											with tempfile.TemporaryDirectory() as tmpdirname:
													model.save_pretrained(UpperCamelCase_    ,						saved_model=UpperCamelCase_							)
													lowercase__            =      model_class.from_pretrained(UpperCamelCase_							)
													lowercase__            =      model(UpperCamelCase_    ,						noise=UpperCamelCase_							)

													if model_class.__name__ == "TFViTMAEModel":
															lowercase__            =      after_outputs['''last_hidden_state'''].numpy()
															lowercase__            =      0
													else:
															lowercase__            =      after_outputs['''logits'''].numpy()
															lowercase__            =      0

													lowercase__            =      np.amax(np.abs(out_a - out_a							)							)
													self.assertLessEqual(UpperCamelCase_    ,						1E-5							)

							def       lowerCamelCase_ (							self:	Union[str, Any]							)			->   int:





									"""simple docstring"""







									np.random.seed(2							)

									lowercase__     ,		lowercase__            =      self.model_tester.prepare_config_and_inputs_for_common()

									lowercase__            =      int((config.image_size // config.patch_size) ** 2							)
									lowercase__            =      np.random.uniform(size=(self.model_tester.batch_size, num_patches)							)

									for model_class in self.all_model_classes:
											lowercase__            =      model_class(UpperCamelCase_							)
											lowercase__            =      self._prepare_for_class(UpperCamelCase_    ,						UpperCamelCase_							)

											lowercase__            =      model(UpperCamelCase_    ,						noise=UpperCamelCase_							)
											lowercase__            =      model.get_config()
											# make sure that returned config is jsonifiable, which is required by keras
											json.dumps(UpperCamelCase_							)
											lowercase__            =      model_class.from_config(model.get_config()							)
											# make sure it also accepts a normal config
											lowercase__            =      model_class.from_config(model.config							)
											lowercase__            =      new_model(UpperCamelCase_							)  # Build model
											new_model.set_weights(model.get_weights()							)
											lowercase__            =      new_model(UpperCamelCase_    ,						noise=UpperCamelCase_							)

											self.assert_outputs_same(UpperCamelCase_    ,						UpperCamelCase_							)

							@unittest.skip(
							    reason='''ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load
    to get deterministic results.'''							)
							def       lowerCamelCase_ (							self:	Tuple							)			->   str:





									"""simple docstring"""







									pass

							@unittest.skip(reason='''ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load'''							)
							def       lowerCamelCase_ (							self:	Union[str, Any]							)			->   List[str]:





									"""simple docstring"""







									pass


							@slow
							def       lowerCamelCase_ (							self:	str							)			->   List[str]:





									"""simple docstring"""







									lowercase__            =      TFViTMAEModel.from_pretrained('''google/vit-base-patch16-224'''							)
									self.assertIsNotNone(UpperCamelCase_							)
def 			_a (      ):


		"""simple docstring"""




		lowercase__            =      Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''     )
		return image


@require_tf
@require_vision
class        _a							(			unittest.TestCase			):

							@cached_property
							def       lowerCamelCase_ (							self:	List[str]							)			->   List[str]:





									"""simple docstring"""







									return ViTImageProcessor.from_pretrained('''facebook/vit-mae-base'''							) if is_vision_available() else None


							@slow
							def       lowerCamelCase_ (							self:	int							)			->   Optional[Any]:





									"""simple docstring"""







									np.random.seed(2							)

									lowercase__            =      TFViTMAEForPreTraining.from_pretrained('''facebook/vit-mae-base'''							)

									lowercase__            =      self.default_image_processor
									lowercase__            =      prepare_img()
									lowercase__            =      image_processor(images=UpperCamelCase_    ,						return_tensors='''tf'''							)

									# prepare a noise vector that will be also used for testing the TF model
									# (this way we can ensure that the PT and TF models operate on the same inputs)
									lowercase__            =      ViTMAEConfig()
									lowercase__            =      int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2							)
									lowercase__            =      np.random.uniform(size=(1, num_patches)							)

									# forward pass
									lowercase__            =      model(**UpperCamelCase_    ,						noise=UpperCamelCase_							)

									# verify the logits
									lowercase__            =      tf.convert_to_tensor([1, 196, 768]							)
									self.assertEqual(outputs.logits.shape    ,						UpperCamelCase_							)

									lowercase__            =      tf.convert_to_tensor(
									    [[-0.0548, -1.7023, -0.9325], [0.3721, -0.5670, -0.2233], [0.8235, -1.3878, -0.3524]]							)

									tf.debugging.assert_near(outputs.logits[0, :3, :3]    ,						UpperCamelCase_    ,						atol=1E-4							)






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


