"""simple docstring"""






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 lowerCamelCase		:






					'''simple docstring'''


					def __init__(    self      :					Union[str, Any] ,			_snake_case      :					int ,			_snake_case      :					Tuple=13 ,			_snake_case      :					int=30 ,			_snake_case      :					str=2 ,			_snake_case      :					Dict=3 ,			_snake_case      :					Dict=True ,			_snake_case      :					Optional[Any]=True ,			_snake_case      :					Optional[Any]=32 ,			_snake_case      :					List[str]=2 ,			_snake_case      :					Any=4 ,			_snake_case      :					List[str]=37 ,			_snake_case      :					List[Any]="gelu" ,			_snake_case      :					Dict=0.1 ,			_snake_case      :					Tuple=0.1 ,			_snake_case      :					Dict=10 ,			_snake_case      :					Optional[int]=0.02 ,			_snake_case      :					int=3 ,			_snake_case      :					Tuple=0.6 ,			_snake_case      :					Tuple=None ,			)				->							Optional[Any]:
									SCREAMING_SNAKE_CASE__			=					parent
									SCREAMING_SNAKE_CASE__			=					batch_size
									SCREAMING_SNAKE_CASE__			=					image_size
									SCREAMING_SNAKE_CASE__			=					patch_size
									SCREAMING_SNAKE_CASE__			=					num_channels
									SCREAMING_SNAKE_CASE__			=					is_training
									SCREAMING_SNAKE_CASE__			=					use_labels
									SCREAMING_SNAKE_CASE__			=					hidden_size
									SCREAMING_SNAKE_CASE__			=					num_hidden_layers
									SCREAMING_SNAKE_CASE__			=					num_attention_heads
									SCREAMING_SNAKE_CASE__			=					intermediate_size
									SCREAMING_SNAKE_CASE__			=					hidden_act
									SCREAMING_SNAKE_CASE__			=					hidden_dropout_prob
									SCREAMING_SNAKE_CASE__			=					attention_probs_dropout_prob
									SCREAMING_SNAKE_CASE__			=					type_sequence_label_size
									SCREAMING_SNAKE_CASE__			=					initializer_range
									SCREAMING_SNAKE_CASE__			=					mask_ratio
									SCREAMING_SNAKE_CASE__			=					scope

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



					def       lowerCAmelCase_       (    self      :					int		)				->							int:
									SCREAMING_SNAKE_CASE__			=					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

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

									SCREAMING_SNAKE_CASE__			=					self.get_config()

									return config, pixel_values, labels



					def       lowerCAmelCase_       (    self      :					int		)				->							List[str]:
									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      :					Dict ,			_snake_case      :					Optional[Any] ,			_snake_case      :					Tuple ,			_snake_case      :					Union[str, Any]		)				->							List[str]:
									SCREAMING_SNAKE_CASE__			=					TFViTMAEModel(config=__UpperCAmelCase		)
									SCREAMING_SNAKE_CASE__			=					model(__UpperCAmelCase ,			training=__UpperCAmelCase		)
									self.parent.assertEqual(result.last_hidden_state.shape ,			(self.batch_size, self.seq_length, self.hidden_size)		)



					def       lowerCAmelCase_       (    self      :					int ,			_snake_case      :					Tuple ,			_snake_case      :					Any ,			_snake_case      :					str		)				->							Dict:
									SCREAMING_SNAKE_CASE__			=					TFViTMAEForPreTraining(__UpperCAmelCase		)
									SCREAMING_SNAKE_CASE__			=					model(__UpperCAmelCase ,			training=__UpperCAmelCase		)
									# expected sequence length = num_patches
									SCREAMING_SNAKE_CASE__			=					(self.image_size // self.patch_size) ** 2
									SCREAMING_SNAKE_CASE__			=					self.patch_size**2 * self.num_channels
									self.parent.assertEqual(result.logits.shape ,			(self.batch_size, num_patches, expected_num_channels)		)

									# test greyscale images
									SCREAMING_SNAKE_CASE__			=					1
									SCREAMING_SNAKE_CASE__			=					TFViTMAEForPreTraining(__UpperCAmelCase		)

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



					def       lowerCAmelCase_       (    self      :					Optional[Any]		)				->							str:
									SCREAMING_SNAKE_CASE__			=					self.prepare_config_and_inputs()
									(SCREAMING_SNAKE_CASE__)			=					config_and_inputs
									SCREAMING_SNAKE_CASE__			=					{'''pixel_values''': pixel_values}
									return config, inputs_dict



@require_tf
class lowerCamelCase		(_SCREAMING_SNAKE_CASE     ,     _SCREAMING_SNAKE_CASE     ,     unittest.TestCase   ):






					'''simple docstring'''


					a 						=		(TFViTMAEModel, TFViTMAEForPreTraining) if is_tf_available() else ()
					a 						=		{'''feature-extraction''': TFViTMAEModel} if is_tf_available() else {}

					a 						=		False
					a 						=		False
					a 						=		False
					a 						=		False



					def       lowerCAmelCase_       (    self      :					Optional[int]		)				->							Any:
									SCREAMING_SNAKE_CASE__			=					TFViTMAEModelTester(self		)
									SCREAMING_SNAKE_CASE__			=					ConfigTester(self ,			config_class=__UpperCAmelCase ,			has_text_modality=__UpperCAmelCase ,			hidden_size=37		)



					def       lowerCAmelCase_       (    self      :					List[Any]		)				->							Tuple:
									self.config_tester.run_common_tests()



					@unittest.skip(reason="ViTMAE does not use inputs_embeds"		)
					def       lowerCAmelCase_       (    self      :					Optional[int]		)				->							Tuple:
									pass



					def       lowerCAmelCase_       (    self      :					Optional[int]		)				->							Optional[int]:
									SCREAMING_SNAKE_CASE__			=					self.model_tester.prepare_config_and_inputs_for_common()

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



					def       lowerCAmelCase_       (    self      :					Optional[Any]		)				->							Dict:
									SCREAMING_SNAKE_CASE__			=					self.model_tester.prepare_config_and_inputs_for_common()

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

													SCREAMING_SNAKE_CASE__			=					['''pixel_values''']
													self.assertListEqual(arg_names[:1] ,			__UpperCAmelCase		)



					def       lowerCAmelCase_       (    self      :					int		)				->							str:
									SCREAMING_SNAKE_CASE__			=					self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*__UpperCAmelCase		)



					def       lowerCAmelCase_       (    self      :					Optional[Any]		)				->							str:
									SCREAMING_SNAKE_CASE__			=					self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_pretraining(*__UpperCAmelCase		)



					def       lowerCAmelCase_       (    self      :					List[str]		)				->							List[str]:
									# make the mask reproducible
									np.random.seed(2		)

									SCREAMING_SNAKE_CASE__			=					self.model_tester.prepare_config_and_inputs_for_common()

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

									for model_class in self.all_model_classes:
													SCREAMING_SNAKE_CASE__			=					model_class(__UpperCAmelCase		)
													SCREAMING_SNAKE_CASE__			=					self._prepare_for_class(__UpperCAmelCase ,			__UpperCAmelCase		)

													SCREAMING_SNAKE_CASE__			=					model(__UpperCAmelCase ,			noise=__UpperCAmelCase		)

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

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



					def       lowerCAmelCase_       (    self      :					Optional[Any]		)				->							Dict:
									# make the mask reproducible
									np.random.seed(2		)

									SCREAMING_SNAKE_CASE__			=					self.model_tester.prepare_config_and_inputs_for_common()

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

									def prepare_numpy_arrays(_snake_case      :					Dict		):
													SCREAMING_SNAKE_CASE__			=					{}
													for k, v in inputs_dict.items():
																	if tf.is_tensor(__UpperCAmelCase		):
																					SCREAMING_SNAKE_CASE__			=					v.numpy()
																	else:
																					SCREAMING_SNAKE_CASE__			=					np.array(__UpperCAmelCase		)

													return inputs_np_dict

									for model_class in self.all_model_classes:
													SCREAMING_SNAKE_CASE__			=					model_class(__UpperCAmelCase		)

													SCREAMING_SNAKE_CASE__			=					self._prepare_for_class(__UpperCAmelCase ,			__UpperCAmelCase		)
													SCREAMING_SNAKE_CASE__			=					prepare_numpy_arrays(__UpperCAmelCase		)

													SCREAMING_SNAKE_CASE__			=					model(__UpperCAmelCase ,			noise=__UpperCAmelCase		)
													SCREAMING_SNAKE_CASE__			=					model(**__UpperCAmelCase ,			noise=__UpperCAmelCase		)
													self.assert_outputs_same(__UpperCAmelCase ,			__UpperCAmelCase		)



					def       lowerCAmelCase_       (    self      :					int ,			_snake_case      :					Union[str, Any] ,			_snake_case      :					int ,			_snake_case      :					int		)				->							List[Any]:
									# make masks reproducible
									np.random.seed(2		)

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

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

									super().check_pt_tf_models(__UpperCAmelCase ,			__UpperCAmelCase ,			__UpperCAmelCase		)



					def       lowerCAmelCase_       (    self      :					Any		)				->							Any:
									# make mask reproducible
									np.random.seed(2		)

									SCREAMING_SNAKE_CASE__			=					self.model_tester.prepare_config_and_inputs_for_common()

									SCREAMING_SNAKE_CASE__			=					{
									    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		)
									}

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

									for main_layer_class in tf_main_layer_classes:
													SCREAMING_SNAKE_CASE__			=					main_layer_class(__UpperCAmelCase		)

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

													SCREAMING_SNAKE_CASE__			=					tf.keras.Model(__UpperCAmelCase ,			outputs=main_layer(__UpperCAmelCase		)		)
													SCREAMING_SNAKE_CASE__			=					model(__UpperCAmelCase		)

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



					@slow
					def       lowerCAmelCase_       (    self      :					Optional[int]		)				->							Tuple:
									# make mask reproducible
									np.random.seed(2		)

									SCREAMING_SNAKE_CASE__			=					self.model_tester.prepare_config_and_inputs_for_common()

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

									for model_class in self.all_model_classes:
													SCREAMING_SNAKE_CASE__			=					model_class(__UpperCAmelCase		)
													SCREAMING_SNAKE_CASE__			=					self._prepare_for_class(__UpperCAmelCase ,			__UpperCAmelCase		)
													SCREAMING_SNAKE_CASE__			=					model(__UpperCAmelCase ,			noise=__UpperCAmelCase		)

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

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

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

																	SCREAMING_SNAKE_CASE__			=					np.amax(np.abs(out_a - out_a		)		)
																	self.assertLessEqual(__UpperCAmelCase ,			1e-5		)



					def       lowerCAmelCase_       (    self      :					List[str]		)				->							List[Any]:
									# make mask reproducible
									np.random.seed(2		)

									SCREAMING_SNAKE_CASE__			=					self.model_tester.prepare_config_and_inputs_for_common()

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

									for model_class in self.all_model_classes:
													SCREAMING_SNAKE_CASE__			=					model_class(__UpperCAmelCase		)
													SCREAMING_SNAKE_CASE__			=					self._prepare_for_class(__UpperCAmelCase ,			__UpperCAmelCase		)

													SCREAMING_SNAKE_CASE__			=					model(__UpperCAmelCase ,			noise=__UpperCAmelCase		)
													SCREAMING_SNAKE_CASE__			=					model.get_config()
													# make sure that returned config is jsonifiable, which is required by keras
													json.dumps(__UpperCAmelCase		)
													SCREAMING_SNAKE_CASE__			=					model_class.from_config(model.get_config()		)
													# make sure it also accepts a normal config
													SCREAMING_SNAKE_CASE__			=					model_class.from_config(model.config		)
													SCREAMING_SNAKE_CASE__			=					new_model(__UpperCAmelCase		)  # Build model
													new_model.set_weights(model.get_weights()		)
													SCREAMING_SNAKE_CASE__			=					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\n    to get deterministic results."		)
					def       lowerCAmelCase_       (    self      :					Union[str, Any]		)				->							Dict:
									pass



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



					@slow
					def       lowerCAmelCase_       (    self      :					Any		)				->							Union[str, Any]:
									SCREAMING_SNAKE_CASE__			=					TFViTMAEModel.from_pretrained("google/vit-base-patch16-224"		)
									self.assertIsNotNone(__UpperCAmelCase		)




def     SCREAMING_SNAKE_CASE       (	)				-> str:
				SCREAMING_SNAKE_CASE__			=					Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"							)
				return image

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






					'''simple docstring'''


					@cached_property
					def       lowerCAmelCase_       (    self      :					Dict		)				->							str:
									return ViTImageProcessor.from_pretrained("facebook/vit-mae-base"		) if is_vision_available() else None



					@slow
					def       lowerCAmelCase_       (    self      :					int		)				->							List[Any]:
									# make random mask reproducible across the PT and TF model
									np.random.seed(2		)

									SCREAMING_SNAKE_CASE__			=					TFViTMAEForPreTraining.from_pretrained("facebook/vit-mae-base"		)

									SCREAMING_SNAKE_CASE__			=					self.default_image_processor
									SCREAMING_SNAKE_CASE__			=					prepare_img()
									SCREAMING_SNAKE_CASE__			=					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)
									SCREAMING_SNAKE_CASE__			=					ViTMAEConfig()
									SCREAMING_SNAKE_CASE__			=					int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2		)
									SCREAMING_SNAKE_CASE__			=					np.random.uniform(size=(1, num_patches)		)

									# forward pass
									SCREAMING_SNAKE_CASE__			=					model(**__UpperCAmelCase ,			noise=__UpperCAmelCase		)

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

									SCREAMING_SNAKE_CASE__			=					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		)







from ..utils import DummyObject, requires_backends







class 					__lowercase  (						metaclass=_SCREAMING_SNAKE_CASE				):





							"""simple docstring"""

							UpperCAmelCase_						:		Optional[Any]								=	['''speech''']




							def __init__(					self    ,						*__UpperCAmelCase    ,						**__UpperCAmelCase						)		->       Dict:
														requires_backends(self    ,						['''speech''']						)







class 					__lowercase  (						metaclass=_SCREAMING_SNAKE_CASE				):





							"""simple docstring"""

							UpperCAmelCase_						:		int								=	['''speech''']




							def __init__(					self    ,						*__UpperCAmelCase    ,						**__UpperCAmelCase						)		->       Tuple:
														requires_backends(self    ,						['''speech''']						)






