


import collections
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import (
    is_pt_flax_cross_test,
    require_flax,
    require_torch,
    require_vision,
    slow,
    torch_device,
)
from transformers.utils import is_flax_available, is_torch_available, is_vision_available

from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask
from ..bert.test_modeling_flax_bert import FlaxBertModelTester
from ..clip.test_modeling_flax_clip import FlaxCLIPVisionModelTester
from ..vit.test_modeling_flax_vit import FlaxViTModelTester


if is_flax_available():
		from transformers import (
		    FlaxBertModel,
		    FlaxCLIPVisionModel,
		    FlaxVisionTextDualEncoderModel,
		    FlaxViTModel,
		    VisionTextDualEncoderConfig,
		    VisionTextDualEncoderProcessor,
		)
		from transformers.modeling_flax_pytorch_utils import (
		    convert_pytorch_state_dict_to_flax,
		    load_flax_weights_in_pytorch_model,
		)


if is_torch_available():
		import torch

		from transformers import VisionTextDualEncoderModel

if is_vision_available():
		from PIL import Image

def 			lowerCAmelCase__					(     a__:						Any			)    ->						Union[str, Any]:


							'''simple docstring'''





							if isinstance(a__     ,    collections.abc.Iterable			):
														return x
							return (x, x)

@require_flax
class 						__a :
		def       UpperCAmelCase__							(     self     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		)					->			str:




									"""simple docstring"""





									pass
		def       UpperCAmelCase__							(     self		)					->			Optional[int]:




									"""simple docstring"""





									pass
		def       UpperCAmelCase__							(     self		)					->			Tuple:




									"""simple docstring"""





									pass
		def       UpperCAmelCase__							(     self     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		)					->			str:




									"""simple docstring"""





									_UpperCAmelCase											=     np.abs((a - b)		).max()
									self.assertLessEqual(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       f'''Difference between torch and flax is {diff} (>= {tol}).'''		)
		def       UpperCAmelCase__							(     self     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE=None     ,       **_SCREAMING_SNAKE_CASE		)					->			List[str]:




									"""simple docstring"""





									_UpperCAmelCase											=     VisionTextDualEncoderConfig.from_vision_text_configs(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		)

									_UpperCAmelCase											=     FlaxVisionTextDualEncoderModel(_SCREAMING_SNAKE_CASE		)

									_UpperCAmelCase											=     model(input_ids=_SCREAMING_SNAKE_CASE     ,       pixel_values=_SCREAMING_SNAKE_CASE     ,       attention_mask=_SCREAMING_SNAKE_CASE		)

									self.assertEqual(output['text_embeds'].shape     ,       (input_ids.shape[0], config.projection_dim)		)
									self.assertEqual(output['image_embeds'].shape     ,       (pixel_values.shape[0], config.projection_dim)		)
		def       UpperCAmelCase__							(     self     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE=None     ,       **_SCREAMING_SNAKE_CASE		)					->			Optional[int]:




									"""simple docstring"""





									_UpperCAmelCase						,			_UpperCAmelCase											=     self.get_vision_text_model(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		)
									_UpperCAmelCase											=     {'vision_model': vision_model, 'text_model': text_model}
									_UpperCAmelCase											=     FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**_SCREAMING_SNAKE_CASE		)

									_UpperCAmelCase											=     model(input_ids=_SCREAMING_SNAKE_CASE     ,       pixel_values=_SCREAMING_SNAKE_CASE     ,       attention_mask=_SCREAMING_SNAKE_CASE		)

									self.assertEqual(output['text_embeds'].shape     ,       (input_ids.shape[0], model.config.projection_dim)		)
									self.assertEqual(output['image_embeds'].shape     ,       (pixel_values.shape[0], model.config.projection_dim)		)
		def       UpperCAmelCase__							(     self     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE=None     ,       **_SCREAMING_SNAKE_CASE		)					->			int:




									"""simple docstring"""





									_UpperCAmelCase						,			_UpperCAmelCase											=     self.get_vision_text_model(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		)
									_UpperCAmelCase											=     {'vision_model': vision_model, 'text_model': text_model}
									_UpperCAmelCase											=     FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**_SCREAMING_SNAKE_CASE		)

									_UpperCAmelCase											=     model(input_ids=_SCREAMING_SNAKE_CASE     ,       pixel_values=_SCREAMING_SNAKE_CASE     ,       attention_mask=_SCREAMING_SNAKE_CASE		)
									_UpperCAmelCase											=     output[0]

									with tempfile.TemporaryDirectory() as tmpdirname:
																model.save_pretrained(_SCREAMING_SNAKE_CASE		)
																_UpperCAmelCase											=     FlaxVisionTextDualEncoderModel.from_pretrained(_SCREAMING_SNAKE_CASE		)

																_UpperCAmelCase											=     model(input_ids=_SCREAMING_SNAKE_CASE     ,       pixel_values=_SCREAMING_SNAKE_CASE     ,       attention_mask=_SCREAMING_SNAKE_CASE		)
																_UpperCAmelCase											=     after_output[0]
																_UpperCAmelCase											=     np.amax(np.abs(out_a - out_a		)		)
																self.assertLessEqual(_SCREAMING_SNAKE_CASE     ,       1e-3		)
		def       UpperCAmelCase__							(     self     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE=None     ,       **_SCREAMING_SNAKE_CASE		)					->			Any:




									"""simple docstring"""





									_UpperCAmelCase						,			_UpperCAmelCase											=     self.get_vision_text_model(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		)
									_UpperCAmelCase											=     {'vision_model': vision_model, 'text_model': text_model}
									_UpperCAmelCase											=     FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**_SCREAMING_SNAKE_CASE		)

									_UpperCAmelCase											=     model(
									    input_ids=_SCREAMING_SNAKE_CASE     ,       pixel_values=_SCREAMING_SNAKE_CASE     ,       attention_mask=_SCREAMING_SNAKE_CASE     ,       output_attentions=_SCREAMING_SNAKE_CASE		)

									_UpperCAmelCase											=     output.vision_model_output.attentions
									self.assertEqual(len(_SCREAMING_SNAKE_CASE		)     ,       vision_config.num_hidden_layers		)

									# in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token)
									_UpperCAmelCase											=     to_atuple(vision_model.config.image_size		)
									_UpperCAmelCase											=     to_atuple(vision_model.config.patch_size		)
									_UpperCAmelCase											=     (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
									_UpperCAmelCase											=     num_patches + 1
									self.assertEqual(vision_attentions[0].shape[-3:]     ,       (vision_config.num_attention_heads, seq_len, seq_len)		)

									_UpperCAmelCase											=     output.text_model_output.attentions
									self.assertEqual(len(_SCREAMING_SNAKE_CASE		)     ,       text_config.num_hidden_layers		)

									self.assertEqual(
									    text_attentions[0].shape[-3:]     ,       (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1])     ,       )
		def       UpperCAmelCase__							(     self     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		)					->			Any:




									"""simple docstring"""





									pt_model.to(_SCREAMING_SNAKE_CASE		)
									pt_model.eval()

									# prepare inputs
									_UpperCAmelCase											=     inputs_dict
									_UpperCAmelCase											=     {k: torch.tensor(v.tolist()		) for k, v in flax_inputs.items()}

									with torch.no_grad():
																_UpperCAmelCase											=     pt_model(**_SCREAMING_SNAKE_CASE		).to_tuple()

									_UpperCAmelCase											=     fx_model(**_SCREAMING_SNAKE_CASE		).to_tuple()
									self.assertEqual(len(_SCREAMING_SNAKE_CASE		)     ,       len(_SCREAMING_SNAKE_CASE		)     ,       'Output lengths differ between Flax and PyTorch'		)
									for fx_output, pt_output in zip(fx_outputs[:4]     ,       pt_outputs[:4]		):
																self.assert_almost_equals(_SCREAMING_SNAKE_CASE     ,       pt_output.numpy()     ,       4e-2		)

									# PT -> Flax
									with tempfile.TemporaryDirectory() as tmpdirname:
																pt_model.save_pretrained(_SCREAMING_SNAKE_CASE		)
																_UpperCAmelCase											=     FlaxVisionTextDualEncoderModel.from_pretrained(_SCREAMING_SNAKE_CASE     ,       from_pt=_SCREAMING_SNAKE_CASE		)

									_UpperCAmelCase											=     fx_model_loaded(**_SCREAMING_SNAKE_CASE		).to_tuple()
									self.assertEqual(len(_SCREAMING_SNAKE_CASE		)     ,       len(_SCREAMING_SNAKE_CASE		)     ,       'Output lengths differ between Flax and PyTorch'		)
									for fx_output_loaded, pt_output in zip(fx_outputs_loaded[:4]     ,       pt_outputs[:4]		):
																self.assert_almost_equals(_SCREAMING_SNAKE_CASE     ,       pt_output.numpy()     ,       4e-2		)

									# Flax -> PT
									with tempfile.TemporaryDirectory() as tmpdirname:
																fx_model.save_pretrained(_SCREAMING_SNAKE_CASE		)
																_UpperCAmelCase											=     VisionTextDualEncoderModel.from_pretrained(_SCREAMING_SNAKE_CASE     ,       from_flax=_SCREAMING_SNAKE_CASE		)

									pt_model_loaded.to(_SCREAMING_SNAKE_CASE		)
									pt_model_loaded.eval()

									with torch.no_grad():
																_UpperCAmelCase											=     pt_model_loaded(**_SCREAMING_SNAKE_CASE		).to_tuple()

									self.assertEqual(len(_SCREAMING_SNAKE_CASE		)     ,       len(_SCREAMING_SNAKE_CASE		)     ,       'Output lengths differ between Flax and PyTorch'		)
									for fx_output, pt_output_loaded in zip(fx_outputs[:4]     ,       pt_outputs_loaded[:4]		):
																self.assert_almost_equals(_SCREAMING_SNAKE_CASE     ,       pt_output_loaded.numpy()     ,       4e-2		)
		def       UpperCAmelCase__							(     self     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		)					->			Optional[int]:




									"""simple docstring"""





									_UpperCAmelCase											=     VisionTextDualEncoderConfig.from_vision_text_configs(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		)

									_UpperCAmelCase											=     VisionTextDualEncoderModel(_SCREAMING_SNAKE_CASE		)
									_UpperCAmelCase											=     FlaxVisionTextDualEncoderModel(_SCREAMING_SNAKE_CASE		)

									_UpperCAmelCase											=     convert_pytorch_state_dict_to_flax(pt_model.state_dict()     ,       _SCREAMING_SNAKE_CASE		)
									_UpperCAmelCase											=     fx_state

									self.check_pt_flax_equivalence(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		)
		def       UpperCAmelCase__							(     self     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		)					->			List[Any]:




									"""simple docstring"""





									_UpperCAmelCase											=     VisionTextDualEncoderConfig.from_vision_text_configs(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		)

									_UpperCAmelCase											=     VisionTextDualEncoderModel(_SCREAMING_SNAKE_CASE		)
									_UpperCAmelCase											=     FlaxVisionTextDualEncoderModel(_SCREAMING_SNAKE_CASE		)

									_UpperCAmelCase											=     load_flax_weights_in_pytorch_model(_SCREAMING_SNAKE_CASE     ,       fx_model.params		)

									self.check_pt_flax_equivalence(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		)
		def       UpperCAmelCase__							(     self		)					->			int:




									"""simple docstring"""





									_UpperCAmelCase											=     self.prepare_config_and_inputs()
									self.check_model_from_pretrained_configs(**_SCREAMING_SNAKE_CASE		)
		def       UpperCAmelCase__							(     self		)					->			int:




									"""simple docstring"""





									_UpperCAmelCase											=     self.prepare_config_and_inputs()
									self.check_vision_text_dual_encoder_from_pretrained(**_SCREAMING_SNAKE_CASE		)
		def       UpperCAmelCase__							(     self		)					->			int:




									"""simple docstring"""





									_UpperCAmelCase											=     self.prepare_config_and_inputs()
									self.check_save_load(**_SCREAMING_SNAKE_CASE		)
		def       UpperCAmelCase__							(     self		)					->			str:




									"""simple docstring"""





									_UpperCAmelCase											=     self.prepare_config_and_inputs()
									self.check_vision_text_output_attention(**_SCREAMING_SNAKE_CASE		)
		@is_pt_flax_cross_test
		def       UpperCAmelCase__							(     self		)					->			int:




									"""simple docstring"""





									_UpperCAmelCase											=     self.prepare_config_and_inputs()
									_UpperCAmelCase											=     config_inputs_dict.pop('vision_config'		)
									_UpperCAmelCase											=     config_inputs_dict.pop('text_config'		)

									_UpperCAmelCase											=     config_inputs_dict

									self.check_equivalence_pt_to_flax(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		)
									self.check_equivalence_flax_to_pt(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		)






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




									"""simple docstring"""





									_UpperCAmelCase						,			_UpperCAmelCase											=     self.get_pretrained_model_and_inputs()

									_UpperCAmelCase											=     model_a(**_SCREAMING_SNAKE_CASE		)
									_UpperCAmelCase											=     outputs[0]

									with tempfile.TemporaryDirectory() as tmp_dirname:
																model_a.save_pretrained(_SCREAMING_SNAKE_CASE		)
																_UpperCAmelCase											=     FlaxVisionTextDualEncoderModel.from_pretrained(_SCREAMING_SNAKE_CASE		)

																_UpperCAmelCase											=     model_a(**_SCREAMING_SNAKE_CASE		)
																_UpperCAmelCase											=     after_outputs[0]
																_UpperCAmelCase											=     np.amax(np.abs(out_a - out_a		)		)
																self.assertLessEqual(_SCREAMING_SNAKE_CASE     ,       1e-5		)



@require_flax
class 						__a (							UpperCAmelCase       , unittest.TestCase     ):
		def       UpperCAmelCase__							(     self		)					->			Any:




									"""simple docstring"""





									_UpperCAmelCase											=     FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
									    'hf-internal-testing/tiny-random-vit'     ,       'hf-internal-testing/tiny-bert'     ,       vision_from_pt=_SCREAMING_SNAKE_CASE     ,       text_from_pt=_SCREAMING_SNAKE_CASE     ,       )
									_UpperCAmelCase											=     13
									_UpperCAmelCase											=     floats_tensor(
									    [
									        batch_size,
									        model.config.vision_config.num_channels,
									        model.config.vision_config.image_size,
									        model.config.vision_config.image_size,
									    ]		)
									_UpperCAmelCase											=     ids_tensor([batch_size, 4]     ,       model.config.text_config.vocab_size		)
									_UpperCAmelCase											=     random_attention_mask([batch_size, 4]		)
									_UpperCAmelCase											=     {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

									return model, inputs
		def       UpperCAmelCase__							(     self     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		)					->			Dict:




									"""simple docstring"""





									_UpperCAmelCase											=     FlaxViTModel(_SCREAMING_SNAKE_CASE		)
									_UpperCAmelCase											=     FlaxBertModel(_SCREAMING_SNAKE_CASE		)
									return vision_model, text_model






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




									"""simple docstring"""





									_UpperCAmelCase											=     FlaxViTModelTester(self		)
									_UpperCAmelCase											=     FlaxBertModelTester(self		)
									_UpperCAmelCase											=     vit_model_tester.prepare_config_and_inputs()
									_UpperCAmelCase											=     bert_model_tester.prepare_config_and_inputs()

									_UpperCAmelCase						,			_UpperCAmelCase											=     vision_config_and_inputs

									_UpperCAmelCase						,			_UpperCAmelCase						,			_UpperCAmelCase						,			_UpperCAmelCase											=     text_config_and_inputs

									# make sure that cross attention layers are added
									return {
									    "text_config": text_config,
									    "vision_config": vision_config,
									    "pixel_values": pixel_values,
									    "attention_mask": attention_mask,
									    "input_ids": input_ids,
									    "token_type_ids": token_type_ids,
									}



@require_torch
class 						__a (							UpperCAmelCase       , unittest.TestCase     ):
		def       UpperCAmelCase__							(     self		)					->			Tuple:




									"""simple docstring"""





									_UpperCAmelCase											=     FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
									    'hf-internal-testing/tiny-random-clip'     ,       'hf-internal-testing/tiny-bert'     ,       vision_from_pt=_SCREAMING_SNAKE_CASE     ,       text_from_pt=_SCREAMING_SNAKE_CASE     ,       )
									_UpperCAmelCase											=     13
									_UpperCAmelCase											=     floats_tensor(
									    [
									        batch_size,
									        model.config.vision_config.num_channels,
									        model.config.vision_config.image_size,
									        model.config.vision_config.image_size,
									    ]		)
									_UpperCAmelCase											=     ids_tensor([batch_size, 4]     ,       model.config.text_config.vocab_size		)
									_UpperCAmelCase											=     random_attention_mask([batch_size, 4]		)
									_UpperCAmelCase											=     {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

									return model, inputs
		def       UpperCAmelCase__							(     self     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		)					->			List[Any]:




									"""simple docstring"""





									_UpperCAmelCase											=     FlaxCLIPVisionModel(_SCREAMING_SNAKE_CASE		)
									_UpperCAmelCase											=     FlaxBertModel(_SCREAMING_SNAKE_CASE		)
									return vision_model, text_model






		def       UpperCAmelCase__							(     self		)					->			List[Any]:




									"""simple docstring"""





									_UpperCAmelCase											=     FlaxCLIPVisionModelTester(self		)
									_UpperCAmelCase											=     FlaxBertModelTester(self		)
									_UpperCAmelCase											=     clip_model_tester.prepare_config_and_inputs()
									_UpperCAmelCase											=     bert_model_tester.prepare_config_and_inputs()

									_UpperCAmelCase						,			_UpperCAmelCase											=     vision_config_and_inputs

									_UpperCAmelCase						,			_UpperCAmelCase						,			_UpperCAmelCase						,			_UpperCAmelCase											=     text_config_and_inputs

									# make sure that cross attention layers are added
									return {
									    "text_config": text_config,
									    "vision_config": vision_config,
									    "pixel_values": pixel_values,
									    "attention_mask": attention_mask,
									    "input_ids": input_ids,
									    "token_type_ids": token_type_ids,
									}



@require_flax
@require_vision
class 						__a (							unittest.TestCase     ):
		@slow
		def       UpperCAmelCase__							(     self		)					->			Tuple:




									"""simple docstring"""





									_UpperCAmelCase											=     FlaxVisionTextDualEncoderModel.from_pretrained('clip-italian/clip-italian'     ,       logit_scale_init_value=1.0		)
									_UpperCAmelCase											=     VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian'		)

									_UpperCAmelCase											=     Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'		)
									_UpperCAmelCase											=     processor(
									    text=['una foto di un gatto', 'una foto di un cane']     ,       images=_SCREAMING_SNAKE_CASE     ,       padding=_SCREAMING_SNAKE_CASE     ,       return_tensors='np'		)

									_UpperCAmelCase											=     model(**_SCREAMING_SNAKE_CASE		)

									# verify the logits
									self.assertEqual(outputs.logits_per_image.shape     ,       (inputs.pixel_values.shape[0], inputs.input_ids.shape[0])		)
									self.assertEqual(
									    outputs.logits_per_text.shape     ,       (inputs.input_ids.shape[0], inputs.pixel_values.shape[0])     ,       )

									_UpperCAmelCase											=     np.array([[1.2284727, 0.3104122]]		)

									self.assertTrue(np.allclose(outputs.logits_per_image     ,       _SCREAMING_SNAKE_CASE     ,       atol=1e-3		)		)




import logging
import os
import sys
from dataclasses import dataclass, field
from typing import Optional

import torch
from datasets import load_dataset
from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor
from torchvision.transforms.functional import InterpolationMode

import transformers
from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    ViTImageProcessor,
    ViTMAEConfig,
    ViTMAEForPreTraining,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
lowerCAmelCase__    :List[str]       =				logging.getLogger(__name__)

# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version('''4.31.0''')

require_version('''datasets>=1.8.0''', '''To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt''')

@dataclass
class 						__a :
		_a      :    Optional[str]           =      field(
		    default='cifar10'       , metadata={'help': 'Name of a dataset from the datasets package'}     )
		_a      :    Optional[str]           =      field(
		    default=UpperCAmelCase       , metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'}     )
		_a      :    Optional[str]           =      field(
		    default=UpperCAmelCase       , metadata={'help': 'The column name of the images in the files.'}     )
		_a      :    Optional[str]           =      field(default=UpperCAmelCase       , metadata={'help': 'A folder containing the training data.'}     )
		_a      :    Optional[str]           =      field(default=UpperCAmelCase       , metadata={'help': 'A folder containing the validation data.'}     )
		_a      :    Optional[float]           =      field(
		    default=0.1_5       , metadata={'help': 'Percent to split off of train for validation.'}     )
		_a      :    Optional[int]           =      field(
		    default=UpperCAmelCase       , metadata={
		        'help': (
		            'For debugging purposes or quicker training, truncate the number of training examples to this '
		            'value if set.'
		        )
		    }       , )
		_a      :    Optional[int]           =      field(
		    default=UpperCAmelCase       , metadata={
		        'help': (
		            'For debugging purposes or quicker training, truncate the number of evaluation examples to this '
		            'value if set.'
		        )
		    }       , )
		def       UpperCAmelCase__							(     self		)					->			List[Any]:




									"""simple docstring"""





									_UpperCAmelCase											=     {}
									if self.train_dir is not None:
																_UpperCAmelCase											=     self.train_dir
									if self.validation_dir is not None:
																_UpperCAmelCase											=     self.validation_dir
									_UpperCAmelCase											=     data_files if data_files else None



@dataclass
class 						__a :
		_a      :    str           =      field(
		    default=UpperCAmelCase       , metadata={
		        'help': (
		            'The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.'
		        )
		    }       , )
		_a      :    Optional[str]           =      field(
		    default=UpperCAmelCase       , metadata={'help': 'Pretrained config name or path if not the same as model_name_or_path'}     )
		_a      :    Optional[str]           =      field(
		    default=UpperCAmelCase       , metadata={
		        'help': (
		            'Override some existing default config settings when a model is trained from scratch. Example: '
		            'n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index'
		        )
		    }       , )
		_a      :    Optional[str]           =      field(
		    default=UpperCAmelCase       , metadata={'help': 'Where do you want to store the pretrained models downloaded from s3'}     )
		_a      :    str           =      field(
		    default='main'       , metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'}       , )
		_a      :    str           =      field(default=UpperCAmelCase       , metadata={'help': 'Name or path of preprocessor config.'}     )
		_a      :    bool           =      field(
		    default=UpperCAmelCase       , metadata={
		        'help': (
		            'Will use the token generated when running `huggingface-cli login` (necessary to use this script '
		            'with private models).'
		        )
		    }       , )
		_a      :    float           =      field(
		    default=0.7_5       , metadata={'help': 'The ratio of the number of masked tokens in the input sequence.'}     )
		_a      :    bool           =      field(
		    default=UpperCAmelCase       , metadata={'help': 'Whether or not to train with normalized pixel values as target.'}     )



@dataclass
class 						__a (							UpperCAmelCase     ):
		_a      :    float           =      field(
		    default=1E-3       , metadata={'help': 'Base learning rate: absolute_lr = base_lr * total_batch_size / 256.'}     )



def 			lowerCAmelCase__					(     a__:						Optional[Any]			)    ->						Union[str, Any]:


							'''simple docstring'''





							_UpperCAmelCase											=     torch.stack([example['pixel_values'] for example in examples]			)
							return {"pixel_values": pixel_values}

def 			lowerCAmelCase__					(     )    ->						Tuple:


							'''simple docstring'''





							_UpperCAmelCase											=     HfArgumentParser((ModelArguments, DataTrainingArguments, CustomTrainingArguments)			)
							if len(sys.argv			) == 2 and sys.argv[1].endswith('.json'			):
														# If we pass only one argument to the script and it's the path to a json file,
														# let's parse it to get our arguments.
														_UpperCAmelCase						,			_UpperCAmelCase						,			_UpperCAmelCase											=     parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]			)			)
							else:
														_UpperCAmelCase						,			_UpperCAmelCase						,			_UpperCAmelCase											=     parser.parse_args_into_dataclasses()

							# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
							# information sent is the one passed as arguments along with your Python/PyTorch versions.
							send_example_telemetry('run_mae'     ,    a__     ,    a__			)

							# Setup logging
							logging.basicConfig(
							    format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'     ,    datefmt='%m/%d/%Y %H:%M:%S'     ,    handlers=[logging.StreamHandler(sys.stdout			)]     ,    )

							if training_args.should_log:
														# The default of training_args.log_level is passive, so we set log level at info here to have that default.
														transformers.utils.logging.set_verbosity_info()

							_UpperCAmelCase											=     training_args.get_process_log_level()
							logger.setLevel(a__			)
							transformers.utils.logging.set_verbosity(a__			)
							transformers.utils.logging.enable_default_handler()
							transformers.utils.logging.enable_explicit_format()

							# Log on each process the small summary:
							logger.warning(
							    F'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}'''
							    + F'''distributed training: {bool(training_args.local_rank != -1			)}, 16-bits training: {training_args.fpaa}'''			)
							logger.info(F'''Training/evaluation parameters {training_args}'''			)

							# Detecting last checkpoint.
							_UpperCAmelCase											=     None
							if os.path.isdir(training_args.output_dir			) and training_args.do_train and not training_args.overwrite_output_dir:
														_UpperCAmelCase											=     get_last_checkpoint(training_args.output_dir			)
														if last_checkpoint is None and len(os.listdir(training_args.output_dir			)			) > 0:
																					raise ValueError(
																					    F'''Output directory ({training_args.output_dir}) already exists and is not empty. '''
																					    'Use --overwrite_output_dir to overcome.'			)
														elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
																					logger.info(
																					    F'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '''
																					    'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'			)

    # Initialize our dataset.
							_UpperCAmelCase											=     load_dataset(
							    data_args.dataset_name     ,    data_args.dataset_config_name     ,    data_files=data_args.data_files     ,    cache_dir=model_args.cache_dir     ,    use_auth_token=True if model_args.use_auth_token else None     ,    )

							# If we don't have a validation split, split off a percentage of train as validation.
							_UpperCAmelCase											=     None if 'validation' in ds.keys() else data_args.train_val_split
							if isinstance(data_args.train_val_split     ,    a__			) and data_args.train_val_split > 0.0:
														_UpperCAmelCase											=     ds['train'].train_test_split(data_args.train_val_split			)
														_UpperCAmelCase											=     split['train']
														_UpperCAmelCase											=     split['test']

							# Load pretrained model and image processor
							#
							# Distributed training:
							# The .from_pretrained methods guarantee that only one local process can concurrently
							# download model & vocab.
							_UpperCAmelCase											=     {
							    'cache_dir': model_args.cache_dir,
							    'revision': model_args.model_revision,
							    'use_auth_token': True if model_args.use_auth_token else None,
							}
							if model_args.config_name:
														_UpperCAmelCase											=     ViTMAEConfig.from_pretrained(model_args.config_name     ,    **a__			)
							elif model_args.model_name_or_path:
														_UpperCAmelCase											=     ViTMAEConfig.from_pretrained(model_args.model_name_or_path     ,    **a__			)
							else:
														_UpperCAmelCase											=     ViTMAEConfig()
														logger.warning('You are instantiating a new config instance from scratch.'			)
														if model_args.config_overrides is not None:
																					logger.info(F'''Overriding config: {model_args.config_overrides}'''			)
																					config.update_from_string(model_args.config_overrides			)
																					logger.info(F'''New config: {config}'''			)

    # adapt config
							config.update(
							    {
							        'mask_ratio': model_args.mask_ratio,
							        'norm_pix_loss': model_args.norm_pix_loss,
							    }			)

							# create image processor
							if model_args.image_processor_name:
														_UpperCAmelCase											=     ViTImageProcessor.from_pretrained(model_args.image_processor_name     ,    **a__			)
							elif model_args.model_name_or_path:
														_UpperCAmelCase											=     ViTImageProcessor.from_pretrained(model_args.model_name_or_path     ,    **a__			)
							else:
														_UpperCAmelCase											=     ViTImageProcessor()

							# create model
							if model_args.model_name_or_path:
														_UpperCAmelCase											=     ViTMAEForPreTraining.from_pretrained(
														    model_args.model_name_or_path     ,    from_tf=bool('.ckpt' in model_args.model_name_or_path			)     ,    config=a__     ,    cache_dir=model_args.cache_dir     ,    revision=model_args.model_revision     ,    use_auth_token=True if model_args.use_auth_token else None     ,    )
							else:
														logger.info('Training new model from scratch'			)
														_UpperCAmelCase											=     ViTMAEForPreTraining(a__			)

							if training_args.do_train:
														_UpperCAmelCase											=     ds['train'].column_names
							else:
														_UpperCAmelCase											=     ds['validation'].column_names

							if data_args.image_column_name is not None:
														_UpperCAmelCase											=     data_args.image_column_name
							elif "image" in column_names:
														_UpperCAmelCase											=     'image'
							elif "img" in column_names:
														_UpperCAmelCase											=     'img'
							else:
														_UpperCAmelCase											=     column_names[0]

							# transformations as done in original MAE paper
							# source: https://github.com/facebookresearch/mae/blob/main/main_pretrain.py
							if "shortest_edge" in image_processor.size:
														_UpperCAmelCase											=     image_processor.size['shortest_edge']
							else:
														_UpperCAmelCase											=     (image_processor.size['height'], image_processor.size['width'])
							_UpperCAmelCase											=     Compose(
							    [
							        Lambda(lambda a__			: img.convert('RGB'			) if img.mode != "RGB" else img			),
							        RandomResizedCrop(a__     ,    scale=(0.2, 1.0)     ,    interpolation=InterpolationMode.BICUBIC			),
							        RandomHorizontalFlip(),
							        ToTensor(),
							        Normalize(mean=image_processor.image_mean     ,    std=image_processor.image_std			),
							    ]			)

							def preprocess_images(a__:						Optional[int]			):
														_UpperCAmelCase											=     [transforms(a__			) for image in examples[image_column_name]]
														return examples

							if training_args.do_train:
														if "train" not in ds:
																					raise ValueError('--do_train requires a train dataset'			)
														if data_args.max_train_samples is not None:
																					_UpperCAmelCase											=     ds['train'].shuffle(seed=training_args.seed			).select(range(data_args.max_train_samples			)			)
														# Set the training transforms
														ds["train"].set_transform(a__			)

							if training_args.do_eval:
														if "validation" not in ds:
																					raise ValueError('--do_eval requires a validation dataset'			)
														if data_args.max_eval_samples is not None:
																					_UpperCAmelCase											=     (
																					    ds['validation'].shuffle(seed=training_args.seed			).select(range(data_args.max_eval_samples			)			)
																					)
														# Set the validation transforms
														ds["validation"].set_transform(a__			)

							# Compute absolute learning rate
							_UpperCAmelCase											=     (
							    training_args.train_batch_size * training_args.gradient_accumulation_steps * training_args.world_size
							)
							if training_args.base_learning_rate is not None:
														_UpperCAmelCase											=     training_args.base_learning_rate * total_train_batch_size / 2_5_6

							# Initialize our trainer
							_UpperCAmelCase											=     Trainer(
							    model=a__     ,    args=a__     ,    train_dataset=ds['train'] if training_args.do_train else None     ,    eval_dataset=ds['validation'] if training_args.do_eval else None     ,    tokenizer=a__     ,    data_collator=a__     ,    )

							# Training
							if training_args.do_train:
														_UpperCAmelCase											=     None
														if training_args.resume_from_checkpoint is not None:
																					_UpperCAmelCase											=     training_args.resume_from_checkpoint
														elif last_checkpoint is not None:
																					_UpperCAmelCase											=     last_checkpoint
														_UpperCAmelCase											=     trainer.train(resume_from_checkpoint=a__			)
														trainer.save_model()
														trainer.log_metrics('train'     ,    train_result.metrics			)
														trainer.save_metrics('train'     ,    train_result.metrics			)
														trainer.save_state()

							# Evaluation
							if training_args.do_eval:
														_UpperCAmelCase											=     trainer.evaluate()
														trainer.log_metrics('eval'     ,    a__			)
														trainer.save_metrics('eval'     ,    a__			)

							# Write model card and (optionally) push to hub
							_UpperCAmelCase											=     {
							    'tasks': 'masked-auto-encoding',
							    'dataset': data_args.dataset_name,
							    'tags': ['masked-auto-encoding'],
							}
							if training_args.push_to_hub:
														trainer.push_to_hub(**a__			)
							else:
														trainer.create_model_card(**a__			)

def 			lowerCAmelCase__					(     a__:						Tuple			)    ->						Optional[Any]:


							'''simple docstring'''





							main()


if __name__ == "__main__":
		main()
