





'''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      UpperCamelCase__					:




					"""simple docstring"""


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

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				int		=			parent
							SCREAMING_SNAKE_CASE :				Any		=			batch_size
							SCREAMING_SNAKE_CASE :				Optional[int]		=			image_size
							SCREAMING_SNAKE_CASE :				str		=			patch_size
							SCREAMING_SNAKE_CASE :				Union[str, Any]		=			num_channels
							SCREAMING_SNAKE_CASE :				Union[str, Any]		=			is_training
							SCREAMING_SNAKE_CASE :				List[str]		=			use_labels
							SCREAMING_SNAKE_CASE :				Optional[int]		=			hidden_size
							SCREAMING_SNAKE_CASE :				str		=			num_hidden_layers
							SCREAMING_SNAKE_CASE :				str		=			num_attention_heads
							SCREAMING_SNAKE_CASE :				Dict		=			intermediate_size
							SCREAMING_SNAKE_CASE :				str		=			hidden_act
							SCREAMING_SNAKE_CASE :				Any		=			hidden_dropout_prob
							SCREAMING_SNAKE_CASE :				Optional[Any]		=			attention_probs_dropout_prob
							SCREAMING_SNAKE_CASE :				Optional[int]		=			type_sequence_label_size
							SCREAMING_SNAKE_CASE :				List[str]		=			initializer_range
							SCREAMING_SNAKE_CASE :				str		=			mask_ratio
							SCREAMING_SNAKE_CASE :				str		=			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 :				List[str]		=			(image_size // patch_size) ** 2
							SCREAMING_SNAKE_CASE :				int		=			int(math.ceil((1 - mask_ratio) * (num_patches + 1)						)						)


					def lowerCamelCase_			(						self				:			Tuple						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				List[str]		=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

							SCREAMING_SNAKE_CASE :				List[Any]		=			None
							if self.use_labels:
									SCREAMING_SNAKE_CASE :				str		=			ids_tensor([self.batch_size]      ,						self.type_sequence_label_size						)

							SCREAMING_SNAKE_CASE :				Optional[int]		=			self.get_config()

							return config, pixel_values, labels


					def lowerCamelCase_			(						self				:			Dict						):

							'''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=lowerCamelCase_      ,						initializer_range=self.initializer_range      ,						mask_ratio=self.mask_ratio      ,						)


					def lowerCamelCase_			(						self				:			Tuple      ,						lowerCamelCase_				:			Dict      ,						lowerCamelCase_				:			Optional[int]      ,						lowerCamelCase_				:			str						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				int		=			TFViTMAEModel(config=lowerCamelCase_						)
							SCREAMING_SNAKE_CASE :				Union[str, Any]		=			model(lowerCamelCase_      ,						training=lowerCamelCase_						)
							self.parent.assertEqual(result.last_hidden_state.shape      ,						(self.batch_size, self.seq_length, self.hidden_size)						)


					def lowerCamelCase_			(						self				:			Dict      ,						lowerCamelCase_				:			Optional[Any]      ,						lowerCamelCase_				:			Dict      ,						lowerCamelCase_				:			str						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				Dict		=			TFViTMAEForPreTraining(lowerCamelCase_						)
							SCREAMING_SNAKE_CASE :				Union[str, Any]		=			model(lowerCamelCase_      ,						training=lowerCamelCase_						)
							# expected sequence length = num_patches
							SCREAMING_SNAKE_CASE :				Optional[int]		=			(self.image_size // self.patch_size) ** 2
							SCREAMING_SNAKE_CASE :				List[Any]		=			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 :				List[str]		=			1
							SCREAMING_SNAKE_CASE :				List[str]		=			TFViTMAEForPreTraining(lowerCamelCase_						)

							SCREAMING_SNAKE_CASE :				Optional[Any]		=			floats_tensor([self.batch_size, 1, self.image_size, self.image_size]						)
							SCREAMING_SNAKE_CASE :				Union[str, Any]		=			model(lowerCamelCase_      ,						training=lowerCamelCase_						)
							SCREAMING_SNAKE_CASE :				int		=			self.patch_size**2
							self.parent.assertEqual(result.logits.shape      ,						(self.batch_size, num_patches, expected_num_channels)						)



					def lowerCamelCase_			(						self				:			Dict						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				int		=			self.prepare_config_and_inputs()
							((SCREAMING_SNAKE_CASE),							(SCREAMING_SNAKE_CASE),							(SCREAMING_SNAKE_CASE)) :				Any		=			config_and_inputs
							SCREAMING_SNAKE_CASE :				Dict		=			{"""pixel_values""": pixel_values}
							return config, inputs_dict







@require_tf
class      UpperCamelCase__					(					lowercase_						,					lowercase_						,					unittest.TestCase			):




					"""simple docstring"""
					SCREAMING_SNAKE_CASE__				=	(TFViTMAEModel, TFViTMAEForPreTraining) if is_tf_available() else ()
					SCREAMING_SNAKE_CASE__				=	{'''feature-extraction''': TFViTMAEModel} if is_tf_available() else {}

					SCREAMING_SNAKE_CASE__				=	False
					SCREAMING_SNAKE_CASE__				=	False
					SCREAMING_SNAKE_CASE__				=	False
					SCREAMING_SNAKE_CASE__				=	False


					def lowerCamelCase_			(						self				:			Optional[int]						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				List[Any]		=			TFViTMAEModelTester(self						)
							SCREAMING_SNAKE_CASE :				Optional[int]		=			ConfigTester(self      ,						config_class=lowerCamelCase_      ,						has_text_modality=lowerCamelCase_      ,						hidden_size=37						)


					def lowerCamelCase_			(						self				:			Tuple						):

							'''simple docstring'''



							self.config_tester.run_common_tests()


					@unittest.skip(reason="""ViTMAE does not use inputs_embeds"""						)
					def lowerCamelCase_			(						self				:			List[str]						):

							'''simple docstring'''



							pass


					def lowerCamelCase_			(						self				:			Optional[int]						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE,							SCREAMING_SNAKE_CASE :				Dict		=			self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
									SCREAMING_SNAKE_CASE :				Union[str, Any]		=			model_class(lowerCamelCase_						)
									self.assertIsInstance(model.get_input_embeddings()      ,						(tf.keras.layers.Layer)						)
									SCREAMING_SNAKE_CASE :				str		=			model.get_output_embeddings()
									self.assertTrue(x is None or isinstance(lowerCamelCase_      ,						tf.keras.layers.Layer						)						)


					def lowerCamelCase_			(						self				:			Optional[int]						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE,							SCREAMING_SNAKE_CASE :				Tuple		=			self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
									SCREAMING_SNAKE_CASE :				List[str]		=			model_class(lowerCamelCase_						)
									SCREAMING_SNAKE_CASE :				Optional[Any]		=			inspect.signature(model.call						)
									# signature.parameters is an OrderedDict => so arg_names order is deterministic
									SCREAMING_SNAKE_CASE :				Tuple		=			[*signature.parameters.keys()]

									SCREAMING_SNAKE_CASE :				Dict		=			["""pixel_values"""]
									self.assertListEqual(arg_names[:1]      ,						lowerCamelCase_						)


					def lowerCamelCase_			(						self				:			Dict						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				int		=			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*lowerCamelCase_						)


					def lowerCamelCase_			(						self				:			int						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				Tuple		=			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_pretraining(*lowerCamelCase_						)


					def lowerCamelCase_			(						self				:			int						):

							'''simple docstring'''



							np.random.seed(2						)

							SCREAMING_SNAKE_CASE,							SCREAMING_SNAKE_CASE :				Optional[Any]		=			self.model_tester.prepare_config_and_inputs_for_common()

							SCREAMING_SNAKE_CASE :				Optional[int]		=			int((config.image_size // config.patch_size) ** 2						)
							SCREAMING_SNAKE_CASE :				Any		=			np.random.uniform(size=(self.model_tester.batch_size, num_patches)						)

							for model_class in self.all_model_classes:
									SCREAMING_SNAKE_CASE :				Any		=			model_class(lowerCamelCase_						)
									SCREAMING_SNAKE_CASE :				Optional[int]		=			self._prepare_for_class(lowerCamelCase_      ,						lowerCamelCase_						)

									SCREAMING_SNAKE_CASE :				List[Any]		=			model(lowerCamelCase_      ,						noise=lowerCamelCase_						)

									SCREAMING_SNAKE_CASE :				Any		=			copy.deepcopy(self._prepare_for_class(lowerCamelCase_      ,						lowerCamelCase_						)						)
									SCREAMING_SNAKE_CASE :				List[Any]		=			model(**lowerCamelCase_      ,						noise=lowerCamelCase_						)
									SCREAMING_SNAKE_CASE :				int		=			outputs_dict[0].numpy()
									SCREAMING_SNAKE_CASE :				Tuple		=			outputs_keywords[0].numpy()

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


					def lowerCamelCase_			(						self				:			Optional[int]						):

							'''simple docstring'''



							np.random.seed(2						)

							SCREAMING_SNAKE_CASE,							SCREAMING_SNAKE_CASE :				List[str]		=			self.model_tester.prepare_config_and_inputs_for_common()

							SCREAMING_SNAKE_CASE :				Dict		=			int((config.image_size // config.patch_size) ** 2						)
							SCREAMING_SNAKE_CASE :				List[str]		=			np.random.uniform(size=(self.model_tester.batch_size, num_patches)						)

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

									return inputs_np_dict

							for model_class in self.all_model_classes:
									SCREAMING_SNAKE_CASE :				Any		=			model_class(lowerCamelCase_						)

									SCREAMING_SNAKE_CASE :				Union[str, Any]		=			self._prepare_for_class(lowerCamelCase_      ,						lowerCamelCase_						)
									SCREAMING_SNAKE_CASE :				Union[str, Any]		=			prepare_numpy_arrays(lowerCamelCase_						)

									SCREAMING_SNAKE_CASE :				int		=			model(lowerCamelCase_      ,						noise=lowerCamelCase_						)
									SCREAMING_SNAKE_CASE :				int		=			model(**lowerCamelCase_      ,						noise=lowerCamelCase_						)
									self.assert_outputs_same(lowerCamelCase_      ,						lowerCamelCase_						)


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

							'''simple docstring'''



							np.random.seed(2						)

							SCREAMING_SNAKE_CASE :				Union[str, Any]		=			int((tf_model.config.image_size // tf_model.config.patch_size) ** 2						)
							SCREAMING_SNAKE_CASE :				Optional[int]		=			np.random.uniform(size=(self.model_tester.batch_size, num_patches)						)
							SCREAMING_SNAKE_CASE :				str		=			tf.constant(lowerCamelCase_						)

							# Add `noise` argument.
							# PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument
							SCREAMING_SNAKE_CASE :				Optional[Any]		=			tf_noise

							super().check_pt_tf_models(lowerCamelCase_      ,						lowerCamelCase_      ,						lowerCamelCase_						)


					def lowerCamelCase_			(						self				:			Tuple						):

							'''simple docstring'''



							np.random.seed(2						)

							SCREAMING_SNAKE_CASE,							SCREAMING_SNAKE_CASE :				List[str]		=			self.model_tester.prepare_config_and_inputs_for_common()

							SCREAMING_SNAKE_CASE :				Union[str, Any]		=			{
							    module_member
							    for model_class in self.all_model_classes
							    for module in (import_module(model_class.__module__						),)
							    for module_member_name in dir(lowerCamelCase_						)
							    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(lowerCamelCase_      ,						lowerCamelCase_						),)
							    if isinstance(lowerCamelCase_      ,						lowerCamelCase_						)
							    and tf.keras.layers.Layer in module_member.__bases__
							    and getattr(lowerCamelCase_      ,						"""_keras_serializable"""      ,						lowerCamelCase_						)
							}

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

							for main_layer_class in tf_main_layer_classes:
									SCREAMING_SNAKE_CASE :				int		=			main_layer_class(lowerCamelCase_						)

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

									SCREAMING_SNAKE_CASE :				List[Any]		=			tf.keras.Model(lowerCamelCase_      ,						outputs=main_layer(lowerCamelCase_						)						)
									SCREAMING_SNAKE_CASE :				Optional[int]		=			model(lowerCamelCase_						)

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


					@slow
					def lowerCamelCase_			(						self				:			Tuple						):

							'''simple docstring'''



							np.random.seed(2						)

							SCREAMING_SNAKE_CASE,							SCREAMING_SNAKE_CASE :				str		=			self.model_tester.prepare_config_and_inputs_for_common()

							SCREAMING_SNAKE_CASE :				List[Any]		=			int((config.image_size // config.patch_size) ** 2						)
							SCREAMING_SNAKE_CASE :				int		=			np.random.uniform(size=(self.model_tester.batch_size, num_patches)						)

							for model_class in self.all_model_classes:
									SCREAMING_SNAKE_CASE :				Optional[int]		=			model_class(lowerCamelCase_						)
									SCREAMING_SNAKE_CASE :				Any		=			self._prepare_for_class(lowerCamelCase_      ,						lowerCamelCase_						)
									SCREAMING_SNAKE_CASE :				str		=			model(lowerCamelCase_      ,						noise=lowerCamelCase_						)

									if model_class.__name__ == "TFViTMAEModel":
											SCREAMING_SNAKE_CASE :				Optional[Any]		=			outputs.last_hidden_state.numpy()
											SCREAMING_SNAKE_CASE :				Tuple		=			0
									else:
											SCREAMING_SNAKE_CASE :				str		=			outputs.logits.numpy()
											SCREAMING_SNAKE_CASE :				List[Any]		=			0

									with tempfile.TemporaryDirectory() as tmpdirname:
											model.save_pretrained(lowerCamelCase_      ,						saved_model=lowerCamelCase_						)
											SCREAMING_SNAKE_CASE :				str		=			model_class.from_pretrained(lowerCamelCase_						)
											SCREAMING_SNAKE_CASE :				Any		=			model(lowerCamelCase_      ,						noise=lowerCamelCase_						)

											if model_class.__name__ == "TFViTMAEModel":
													SCREAMING_SNAKE_CASE :				Dict		=			after_outputs["""last_hidden_state"""].numpy()
													SCREAMING_SNAKE_CASE :				List[str]		=			0
											else:
													SCREAMING_SNAKE_CASE :				str		=			after_outputs["""logits"""].numpy()
													SCREAMING_SNAKE_CASE :				List[Any]		=			0

											SCREAMING_SNAKE_CASE :				str		=			np.amax(np.abs(out_a - out_a						)						)
											self.assertLessEqual(lowerCamelCase_      ,						1e-5						)


					def lowerCamelCase_			(						self				:			str						):

							'''simple docstring'''



							np.random.seed(2						)

							SCREAMING_SNAKE_CASE,							SCREAMING_SNAKE_CASE :				Optional[int]		=			self.model_tester.prepare_config_and_inputs_for_common()

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

							for model_class in self.all_model_classes:
									SCREAMING_SNAKE_CASE :				int		=			model_class(lowerCamelCase_						)
									SCREAMING_SNAKE_CASE :				Union[str, Any]		=			self._prepare_for_class(lowerCamelCase_      ,						lowerCamelCase_						)

									SCREAMING_SNAKE_CASE :				Tuple		=			model(lowerCamelCase_      ,						noise=lowerCamelCase_						)
									SCREAMING_SNAKE_CASE :				List[Any]		=			model.get_config()
									# make sure that returned config is jsonifiable, which is required by keras
									json.dumps(lowerCamelCase_						)
									SCREAMING_SNAKE_CASE :				int		=			model_class.from_config(model.get_config()						)
									# make sure it also accepts a normal config
									SCREAMING_SNAKE_CASE :				Tuple		=			model_class.from_config(model.config						)
									SCREAMING_SNAKE_CASE :				Any		=			new_model(lowerCamelCase_						)  # Build model
									new_model.set_weights(model.get_weights()						)
									SCREAMING_SNAKE_CASE :				str		=			new_model(lowerCamelCase_      ,						noise=lowerCamelCase_						)

									self.assert_outputs_same(lowerCamelCase_      ,						lowerCamelCase_						)


					@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				:			Union[str, Any]						):

							'''simple docstring'''



							pass


					@unittest.skip(reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load"""						)
					def lowerCamelCase_			(						self				:			Any						):

							'''simple docstring'''



							pass



					@slow
					def lowerCamelCase_			(						self				:			Union[str, Any]						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				Any		=			TFViTMAEModel.from_pretrained("""google/vit-base-patch16-224"""						)
							self.assertIsNotNone(lowerCamelCase_						)







def 		__A		(  ):


		"""simple docstring"""



		SCREAMING_SNAKE_CASE :				int		=			Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""	)
		return image




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




					"""simple docstring"""


					@cached_property
					def lowerCamelCase_			(						self				:			Optional[int]						):

							'''simple docstring'''



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



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

							'''simple docstring'''



							np.random.seed(2						)

							SCREAMING_SNAKE_CASE :				List[Any]		=			TFViTMAEForPreTraining.from_pretrained("""facebook/vit-mae-base"""						)

							SCREAMING_SNAKE_CASE :				List[Any]		=			self.default_image_processor
							SCREAMING_SNAKE_CASE :				Optional[Any]		=			prepare_img()
							SCREAMING_SNAKE_CASE :				List[Any]		=			image_processor(images=lowerCamelCase_      ,						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 :				str		=			ViTMAEConfig()
							SCREAMING_SNAKE_CASE :				Union[str, Any]		=			int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2						)
							SCREAMING_SNAKE_CASE :				Dict		=			np.random.uniform(size=(1, num_patches)						)

							# forward pass
							SCREAMING_SNAKE_CASE :				Dict		=			model(**lowerCamelCase_      ,						noise=lowerCamelCase_						)

							# verify the logits
							SCREAMING_SNAKE_CASE :				Union[str, Any]		=			tf.convert_to_tensor([1, 1_96, 7_68]						)
							self.assertEqual(outputs.logits.shape      ,						lowerCamelCase_						)

							SCREAMING_SNAKE_CASE :				str		=			tf.convert_to_tensor(
							    [[-0.0_548, -1.7_023, -0.9_325], [0.3_721, -0.5_670, -0.2_233], [0.8_235, -1.3_878, -0.3_524]]						)

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










'''simple docstring'''




import shutil
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import (
    is_pt_tf_cross_test,
    require_tf,
    require_torch,
    require_torchvision,
    require_vision,
)
from transformers.utils import is_tf_available, is_torch_available, is_vision_available


if is_vision_available():
							from PIL import Image

							from transformers import AutoProcessor, SamImageProcessor, SamProcessor

if is_torch_available():
							import torch

if is_tf_available():
							import tensorflow as tf




@require_vision
@require_torchvision
class      UpperCamelCase__					(					unittest.TestCase			):




					"""simple docstring"""


					def lowerCamelCase_			(						self				:			Any						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				Union[str, Any]		=			tempfile.mkdtemp()
							SCREAMING_SNAKE_CASE :				List[Any]		=			SamImageProcessor()
							SCREAMING_SNAKE_CASE :				Optional[Any]		=			SamProcessor(lowerCamelCase_						)
							processor.save_pretrained(self.tmpdirname						)


					def lowerCamelCase_			(						self				:			Dict      ,						**lowerCamelCase_				:			List[str]						):

							'''simple docstring'''



							return AutoProcessor.from_pretrained(self.tmpdirname      ,						**lowerCamelCase_						).image_processor


					def lowerCamelCase_			(						self				:			Dict						):

							'''simple docstring'''



							shutil.rmtree(self.tmpdirname						)


					def lowerCamelCase_			(						self				:			str						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				Optional[int]		=			[np.random.randint(2_55      ,						size=(3, 30, 4_00)      ,						dtype=np.uinta						)]

							SCREAMING_SNAKE_CASE :				Optional[int]		=			[Image.fromarray(np.moveaxis(lowerCamelCase_      ,						0      ,						-1						)						) for x in image_inputs]

							return image_inputs


					def lowerCamelCase_			(						self				:			Any						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				List[Any]		=			SamProcessor(image_processor=self.get_image_processor()						)
							processor.save_pretrained(self.tmpdirname						)

							SCREAMING_SNAKE_CASE :				int		=			self.get_image_processor(do_normalize=lowerCamelCase_      ,						padding_value=1.0						)

							SCREAMING_SNAKE_CASE :				Tuple		=			SamProcessor.from_pretrained(self.tmpdirname      ,						do_normalize=lowerCamelCase_      ,						padding_value=1.0						)

							self.assertEqual(processor.image_processor.to_json_string()      ,						image_processor_add_kwargs.to_json_string()						)
							self.assertIsInstance(processor.image_processor      ,						lowerCamelCase_						)


					def lowerCamelCase_			(						self				:			Tuple						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				Optional[Any]		=			self.get_image_processor()

							SCREAMING_SNAKE_CASE :				List[Any]		=			SamProcessor(image_processor=lowerCamelCase_						)

							SCREAMING_SNAKE_CASE :				Optional[int]		=			self.prepare_image_inputs()

							SCREAMING_SNAKE_CASE :				List[str]		=			image_processor(lowerCamelCase_      ,						return_tensors="""np"""						)
							SCREAMING_SNAKE_CASE :				Dict		=			processor(images=lowerCamelCase_      ,						return_tensors="""np"""						)

							input_feat_extract.pop("""original_sizes"""						)  # pop original_sizes as it is popped in the processor
							input_feat_extract.pop("""reshaped_input_sizes"""						)  # pop original_sizes as it is popped in the processor

							for key in input_feat_extract.keys():
									self.assertAlmostEqual(input_feat_extract[key].sum()      ,						input_processor[key].sum()      ,						delta=1e-2						)



					@require_torch
					def lowerCamelCase_			(						self				:			int						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				List[str]		=			self.get_image_processor()

							SCREAMING_SNAKE_CASE :				Optional[Any]		=			SamProcessor(image_processor=lowerCamelCase_						)
							SCREAMING_SNAKE_CASE :				Any		=			[torch.ones((1, 3, 5, 5)						)]

							SCREAMING_SNAKE_CASE :				int		=			[[17_64, 26_46]]

							SCREAMING_SNAKE_CASE :				Any		=			[[6_83, 10_24]]
							SCREAMING_SNAKE_CASE :				str		=			processor.post_process_masks(lowerCamelCase_      ,						lowerCamelCase_      ,						lowerCamelCase_						)
							self.assertEqual(masks[0].shape      ,						(1, 3, 17_64, 26_46)						)

							SCREAMING_SNAKE_CASE :				str		=			processor.post_process_masks(
							    lowerCamelCase_      ,						torch.tensor(lowerCamelCase_						)      ,						torch.tensor(lowerCamelCase_						)						)
							self.assertEqual(masks[0].shape      ,						(1, 3, 17_64, 26_46)						)

							# should also work with np
							SCREAMING_SNAKE_CASE :				Optional[int]		=			[np.ones((1, 3, 5, 5)						)]
							SCREAMING_SNAKE_CASE :				Optional[int]		=			processor.post_process_masks(lowerCamelCase_      ,						np.array(lowerCamelCase_						)      ,						np.array(lowerCamelCase_						)						)

							self.assertEqual(masks[0].shape      ,						(1, 3, 17_64, 26_46)						)

							SCREAMING_SNAKE_CASE :				Tuple		=			[[1, 0], [0, 1]]
							with self.assertRaises(lowerCamelCase_						):
									SCREAMING_SNAKE_CASE :				Tuple		=			processor.post_process_masks(lowerCamelCase_      ,						np.array(lowerCamelCase_						)      ,						np.array(lowerCamelCase_						)						)







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




					"""simple docstring"""


					def lowerCamelCase_			(						self				:			Tuple						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				Union[str, Any]		=			tempfile.mkdtemp()
							SCREAMING_SNAKE_CASE :				Optional[Any]		=			SamImageProcessor()
							SCREAMING_SNAKE_CASE :				Optional[int]		=			SamProcessor(lowerCamelCase_						)
							processor.save_pretrained(self.tmpdirname						)


					def lowerCamelCase_			(						self				:			Any      ,						**lowerCamelCase_				:			str						):

							'''simple docstring'''



							return AutoProcessor.from_pretrained(self.tmpdirname      ,						**lowerCamelCase_						).image_processor


					def lowerCamelCase_			(						self				:			List[Any]						):

							'''simple docstring'''



							shutil.rmtree(self.tmpdirname						)


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

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				Any		=			[np.random.randint(2_55      ,						size=(3, 30, 4_00)      ,						dtype=np.uinta						)]

							SCREAMING_SNAKE_CASE :				str		=			[Image.fromarray(np.moveaxis(lowerCamelCase_      ,						0      ,						-1						)						) for x in image_inputs]

							return image_inputs


					def lowerCamelCase_			(						self				:			List[Any]						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				Union[str, Any]		=			SamProcessor(image_processor=self.get_image_processor()						)
							processor.save_pretrained(self.tmpdirname						)

							SCREAMING_SNAKE_CASE :				Optional[Any]		=			self.get_image_processor(do_normalize=lowerCamelCase_      ,						padding_value=1.0						)

							SCREAMING_SNAKE_CASE :				List[Any]		=			SamProcessor.from_pretrained(self.tmpdirname      ,						do_normalize=lowerCamelCase_      ,						padding_value=1.0						)

							self.assertEqual(processor.image_processor.to_json_string()      ,						image_processor_add_kwargs.to_json_string()						)
							self.assertIsInstance(processor.image_processor      ,						lowerCamelCase_						)


					def lowerCamelCase_			(						self				:			Optional[Any]						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				str		=			self.get_image_processor()

							SCREAMING_SNAKE_CASE :				Dict		=			SamProcessor(image_processor=lowerCamelCase_						)

							SCREAMING_SNAKE_CASE :				int		=			self.prepare_image_inputs()

							SCREAMING_SNAKE_CASE :				Optional[Any]		=			image_processor(lowerCamelCase_      ,						return_tensors="""np"""						)
							SCREAMING_SNAKE_CASE :				List[Any]		=			processor(images=lowerCamelCase_      ,						return_tensors="""np"""						)

							input_feat_extract.pop("""original_sizes"""						)  # pop original_sizes as it is popped in the processor
							input_feat_extract.pop("""reshaped_input_sizes"""						)  # pop reshaped_input_sizes as it is popped in the processor

							for key in input_feat_extract.keys():
									self.assertAlmostEqual(input_feat_extract[key].sum()      ,						input_processor[key].sum()      ,						delta=1e-2						)



					@require_tf
					def lowerCamelCase_			(						self				:			Dict						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				Dict		=			self.get_image_processor()

							SCREAMING_SNAKE_CASE :				Tuple		=			SamProcessor(image_processor=lowerCamelCase_						)
							SCREAMING_SNAKE_CASE :				Union[str, Any]		=			[tf.ones((1, 3, 5, 5)						)]

							SCREAMING_SNAKE_CASE :				Dict		=			[[17_64, 26_46]]

							SCREAMING_SNAKE_CASE :				Any		=			[[6_83, 10_24]]
							SCREAMING_SNAKE_CASE :				str		=			processor.post_process_masks(lowerCamelCase_      ,						lowerCamelCase_      ,						lowerCamelCase_      ,						return_tensors="""tf"""						)
							self.assertEqual(masks[0].shape      ,						(1, 3, 17_64, 26_46)						)

							SCREAMING_SNAKE_CASE :				Optional[int]		=			processor.post_process_masks(
							    lowerCamelCase_      ,						tf.convert_to_tensor(lowerCamelCase_						)      ,						tf.convert_to_tensor(lowerCamelCase_						)      ,						return_tensors="""tf"""      ,						)
							self.assertEqual(masks[0].shape      ,						(1, 3, 17_64, 26_46)						)

							# should also work with np
							SCREAMING_SNAKE_CASE :				Optional[int]		=			[np.ones((1, 3, 5, 5)						)]
							SCREAMING_SNAKE_CASE :				List[str]		=			processor.post_process_masks(
							    lowerCamelCase_      ,						np.array(lowerCamelCase_						)      ,						np.array(lowerCamelCase_						)      ,						return_tensors="""tf"""						)

							self.assertEqual(masks[0].shape      ,						(1, 3, 17_64, 26_46)						)

							SCREAMING_SNAKE_CASE :				str		=			[[1, 0], [0, 1]]
							with self.assertRaises(tf.errors.InvalidArgumentError						):
									SCREAMING_SNAKE_CASE :				Tuple		=			processor.post_process_masks(
									    lowerCamelCase_      ,						np.array(lowerCamelCase_						)      ,						np.array(lowerCamelCase_						)      ,						return_tensors="""tf"""						)







@require_vision
@require_torchvision
class      UpperCamelCase__					(					unittest.TestCase			):




					"""simple docstring"""


					def lowerCamelCase_			(						self				:			Tuple						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				int		=			tempfile.mkdtemp()
							SCREAMING_SNAKE_CASE :				int		=			SamImageProcessor()
							SCREAMING_SNAKE_CASE :				str		=			SamProcessor(lowerCamelCase_						)
							processor.save_pretrained(self.tmpdirname						)


					def lowerCamelCase_			(						self				:			Tuple      ,						**lowerCamelCase_				:			List[Any]						):

							'''simple docstring'''



							return AutoProcessor.from_pretrained(self.tmpdirname      ,						**lowerCamelCase_						).image_processor


					def lowerCamelCase_			(						self				:			int						):

							'''simple docstring'''



							shutil.rmtree(self.tmpdirname						)


					def lowerCamelCase_			(						self				:			Dict						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				Optional[int]		=			[np.random.randint(2_55      ,						size=(3, 30, 4_00)      ,						dtype=np.uinta						)]

							SCREAMING_SNAKE_CASE :				Dict		=			[Image.fromarray(np.moveaxis(lowerCamelCase_      ,						0      ,						-1						)						) for x in image_inputs]

							return image_inputs


					@is_pt_tf_cross_test
					def lowerCamelCase_			(						self				:			Optional[Any]						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				str		=			self.get_image_processor()

							SCREAMING_SNAKE_CASE :				Dict		=			SamProcessor(image_processor=lowerCamelCase_						)
							SCREAMING_SNAKE_CASE :				Any		=			np.random.randint(0      ,						2      ,						size=(1, 3, 5, 5)						).astype(np.floataa						)
							SCREAMING_SNAKE_CASE :				str		=			[tf.convert_to_tensor(lowerCamelCase_						)]
							SCREAMING_SNAKE_CASE :				Union[str, Any]		=			[torch.tensor(lowerCamelCase_						)]

							SCREAMING_SNAKE_CASE :				Tuple		=			[[17_64, 26_46]]

							SCREAMING_SNAKE_CASE :				Optional[Any]		=			[[6_83, 10_24]]
							SCREAMING_SNAKE_CASE :				Tuple		=			processor.post_process_masks(
							    lowerCamelCase_      ,						lowerCamelCase_      ,						lowerCamelCase_      ,						return_tensors="""tf"""						)
							SCREAMING_SNAKE_CASE :				Any		=			processor.post_process_masks(
							    lowerCamelCase_      ,						lowerCamelCase_      ,						lowerCamelCase_      ,						return_tensors="""pt"""						)

							self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy()						)						)



					@is_pt_tf_cross_test
					def lowerCamelCase_			(						self				:			Tuple						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				Union[str, Any]		=			self.get_image_processor()

							SCREAMING_SNAKE_CASE :				Union[str, Any]		=			SamProcessor(image_processor=lowerCamelCase_						)

							SCREAMING_SNAKE_CASE :				Any		=			self.prepare_image_inputs()

							SCREAMING_SNAKE_CASE :				int		=			image_processor(lowerCamelCase_      ,						return_tensors="""pt"""						)["""pixel_values"""].numpy()
							SCREAMING_SNAKE_CASE :				Tuple		=			processor(images=lowerCamelCase_      ,						return_tensors="""pt"""						)["""pixel_values"""].numpy()

							SCREAMING_SNAKE_CASE :				Dict		=			image_processor(lowerCamelCase_      ,						return_tensors="""tf"""						)["""pixel_values"""].numpy()
							SCREAMING_SNAKE_CASE :				Dict		=			processor(images=lowerCamelCase_      ,						return_tensors="""tf"""						)["""pixel_values"""].numpy()

							self.assertTrue(np.allclose(lowerCamelCase_      ,						lowerCamelCase_						)						)
							self.assertTrue(np.allclose(lowerCamelCase_      ,						lowerCamelCase_						)						)
							self.assertTrue(np.allclose(lowerCamelCase_      ,						lowerCamelCase_						)						)



