






'''simple docstring'''







import collections
import inspect
import unittest
from typing import Dict, List, Tuple

from transformers import MaskFormerSwinConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device
from transformers.utils import is_torch_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
			import torch
			from torch import nn

			from transformers import MaskFormerSwinBackbone
			from transformers.models.maskformer import MaskFormerSwinModel

class _lowercase			:




							def __init__(							self:       Dict    ,							UpperCamelCase__:       List[Any]    ,							UpperCamelCase__:       Optional[Any]=13    ,							UpperCamelCase__:       Tuple=32    ,							UpperCamelCase__:       Optional[int]=2    ,							UpperCamelCase__:       int=3    ,							UpperCamelCase__:       Dict=16    ,							UpperCamelCase__:       str=[1, 2, 1]    ,							UpperCamelCase__:       Tuple=[2, 2, 4]    ,							UpperCamelCase__:       Dict=2    ,							UpperCamelCase__:       List[str]=2.0    ,							UpperCamelCase__:       List[Any]=True    ,							UpperCamelCase__:       List[str]=0.0    ,							UpperCamelCase__:       Tuple=0.0    ,							UpperCamelCase__:       str=0.1    ,							UpperCamelCase__:       List[Any]="gelu"    ,							UpperCamelCase__:       Any=False    ,							UpperCamelCase__:       str=True    ,							UpperCamelCase__:       Optional[int]=0.02    ,							UpperCamelCase__:       List[Any]=1e-5    ,							UpperCamelCase__:       Any=True    ,							UpperCamelCase__:       str=None    ,							UpperCamelCase__:       List[str]=True    ,							UpperCamelCase__:       Any=10    ,							UpperCamelCase__:       Tuple=8    ,							UpperCamelCase__:       Optional[int]=["stage1", "stage2", "stage3"]    ,							UpperCamelCase__:       Dict=[1, 2, 3]    ,							):
														lowerCamelCase__      :			Any 						= parent
														lowerCamelCase__      :			Dict 						= batch_size
														lowerCamelCase__      :			List[str] 						= image_size
														lowerCamelCase__      :			Dict 						= patch_size
														lowerCamelCase__      :			Optional[int] 						= num_channels
														lowerCamelCase__      :			Any 						= embed_dim
														lowerCamelCase__      :			Optional[int] 						= depths
														lowerCamelCase__      :			Union[str, Any] 						= num_heads
														lowerCamelCase__      :			Optional[int] 						= window_size
														lowerCamelCase__      :			str 						= mlp_ratio
														lowerCamelCase__      :			List[Any] 						= qkv_bias
														lowerCamelCase__      :			Tuple 						= hidden_dropout_prob
														lowerCamelCase__      :			Optional[int] 						= attention_probs_dropout_prob
														lowerCamelCase__      :			Any 						= drop_path_rate
														lowerCamelCase__      :			Optional[int] 						= hidden_act
														lowerCamelCase__      :			Union[str, Any] 						= use_absolute_embeddings
														lowerCamelCase__      :			str 						= patch_norm
														lowerCamelCase__      :			List[str] 						= layer_norm_eps
														lowerCamelCase__      :			Any 						= initializer_range
														lowerCamelCase__      :			List[str] 						= is_training
														lowerCamelCase__      :			List[Any] 						= scope
														lowerCamelCase__      :			List[str] 						= use_labels
														lowerCamelCase__      :			List[Any] 						= type_sequence_label_size
														lowerCamelCase__      :			Dict 						= encoder_stride
														lowerCamelCase__      :			Union[str, Any] 						= out_features
														lowerCamelCase__      :			Union[str, Any] 						= out_indices




							def 	lowerCamelCase_       (							self:       Any  ):
														lowerCamelCase__      :			List[Any] 						= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

														lowerCamelCase__      :			Tuple 						= None
														if self.use_labels:
																					lowerCamelCase__      :			int 						= ids_tensor([self.batch_size]    ,							self.type_sequence_label_size  )

														lowerCamelCase__      :			Union[str, Any] 						= self.get_config()

														return config, pixel_values, labels




							def 	lowerCamelCase_       (							self:       Any  ):
														return MaskFormerSwinConfig(
														    image_size=self.image_size    ,							patch_size=self.patch_size    ,							num_channels=self.num_channels    ,							embed_dim=self.embed_dim    ,							depths=self.depths    ,							num_heads=self.num_heads    ,							window_size=self.window_size    ,							mlp_ratio=self.mlp_ratio    ,							qkv_bias=self.qkv_bias    ,							hidden_dropout_prob=self.hidden_dropout_prob    ,							attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,							drop_path_rate=self.drop_path_rate    ,							hidden_act=self.hidden_act    ,							use_absolute_embeddings=self.use_absolute_embeddings    ,							path_norm=self.patch_norm    ,							layer_norm_eps=self.layer_norm_eps    ,							initializer_range=self.initializer_range    ,							encoder_stride=self.encoder_stride    ,							out_features=self.out_features    ,							out_indices=self.out_indices    ,							)




							def 	lowerCamelCase_       (							self:       Union[str, Any]    ,							UpperCamelCase__:       List[Any]    ,							UpperCamelCase__:       Optional[Any]    ,							UpperCamelCase__:       Any  ):
														lowerCamelCase__      :			int 						= MaskFormerSwinModel(config=UpperCamelCase__  )
														model.to(UpperCamelCase__  )
														model.eval()
														lowerCamelCase__      :			Tuple 						= model(UpperCamelCase__  )

														lowerCamelCase__      :			Optional[int] 						= ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths  ) - 1))
														lowerCamelCase__      :			Optional[int] 						= int(config.embed_dim * 2 ** (len(config.depths  ) - 1)  )

														self.parent.assertEqual(result.last_hidden_state.shape    ,							(self.batch_size, expected_seq_len, expected_dim)  )




							def 	lowerCamelCase_       (							self:       str    ,							UpperCamelCase__:       str    ,							UpperCamelCase__:       str    ,							UpperCamelCase__:       Union[str, Any]  ):
														lowerCamelCase__      :			Union[str, Any] 						= MaskFormerSwinBackbone(config=UpperCamelCase__  )
														model.to(UpperCamelCase__  )
														model.eval()
														lowerCamelCase__      :			Dict 						= model(UpperCamelCase__  )

														# verify feature maps
														self.parent.assertEqual(len(result.feature_maps  )    ,							len(config.out_features  )  )
														self.parent.assertListEqual(list(result.feature_maps[0].shape  )    ,							[13, 16, 16, 16]  )

														# verify channels
														self.parent.assertEqual(len(model.channels  )    ,							len(config.out_features  )  )
														self.parent.assertListEqual(model.channels    ,							[16, 32, 64]  )

														# verify ValueError
														with self.parent.assertRaises(UpperCamelCase__  ):
																					lowerCamelCase__      :			Dict 						= ["""stem"""]
																					lowerCamelCase__      :			Union[str, Any] 						= MaskFormerSwinBackbone(config=UpperCamelCase__  )




							def 	lowerCamelCase_       (							self:       Dict  ):
														lowerCamelCase__      :			str 						= self.prepare_config_and_inputs()
														lowerCamelCase__      :			List[Any] 						= config_and_inputs
														lowerCamelCase__      :			Dict 						= {"""pixel_values""": pixel_values}
														return config, inputs_dict



@require_torch
class _lowercase			(       _lowercase       ,   _lowercase       ,   unittest.TestCase	):
							a          = (
							    (
							        MaskFormerSwinModel,
							        MaskFormerSwinBackbone,
							    )
							    if is_torch_available()
							    else ()
							)
							a          = {"""feature-extraction""": MaskFormerSwinModel} if is_torch_available() else {}
							a          = False
							a          = False
							a          = False
							a          = False
							a          = False




							def 	lowerCamelCase_       (							self:       List[Any]  ):
														lowerCamelCase__      :			str 						= MaskFormerSwinModelTester(self  )
														lowerCamelCase__      :			List[str] 						= ConfigTester(self    ,							config_class=UpperCamelCase__    ,							embed_dim=37  )




							@require_torch_multi_gpu
							@unittest.skip(
							    reason=(
							        """`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn't work well with"""
							        """ `nn.DataParallel`"""
							    )  )
							def 	lowerCamelCase_       (							self:       Union[str, Any]  ):
														pass




							def 	lowerCamelCase_       (							self:       Union[str, Any]  ):
														self.create_and_test_config_common_properties()
														self.config_tester.create_and_test_config_to_json_string()
														self.config_tester.create_and_test_config_to_json_file()
														self.config_tester.create_and_test_config_from_and_save_pretrained()
														self.config_tester.create_and_test_config_with_num_labels()
														self.config_tester.check_config_can_be_init_without_params()
														self.config_tester.check_config_arguments_init()




							def 	lowerCamelCase_       (							self:       Tuple  ):
														return




							def 	lowerCamelCase_       (							self:       Optional[Any]  ):
														lowerCamelCase__      :			Union[str, Any] 						= self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_model(*UpperCamelCase__  )




							def 	lowerCamelCase_       (							self:       Any  ):
														lowerCamelCase__      :			List[Any] 						= self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_backbone(*UpperCamelCase__  )




							@unittest.skip("""Swin does not use inputs_embeds"""  )
							def 	lowerCamelCase_       (							self:       Union[str, Any]  ):
														pass




							@unittest.skip("""Swin does not support feedforward chunking"""  )
							def 	lowerCamelCase_       (							self:       Optional[Any]  ):
														pass




							def 	lowerCamelCase_       (							self:       Optional[Any]  ):
														lowerCamelCase__      :			Optional[int] 						= self.model_tester.prepare_config_and_inputs_for_common()

														for model_class in self.all_model_classes:
																					lowerCamelCase__      :			Union[str, Any] 						= model_class(UpperCamelCase__  )
																					self.assertIsInstance(model.get_input_embeddings()    ,							(nn.Module)  )
																					lowerCamelCase__      :			str 						= model.get_output_embeddings()
																					self.assertTrue(x is None or isinstance(UpperCamelCase__    ,							nn.Linear  )  )




							def 	lowerCamelCase_       (							self:       int  ):
														lowerCamelCase__      :			List[str] 						= self.model_tester.prepare_config_and_inputs_for_common()

														for model_class in self.all_model_classes:
																					lowerCamelCase__      :			str 						= model_class(UpperCamelCase__  )
																					lowerCamelCase__      :			List[Any] 						= inspect.signature(model.forward  )
																					# signature.parameters is an OrderedDict => so arg_names order is deterministic
																					lowerCamelCase__      :			Dict 						= [*signature.parameters.keys()]

																					lowerCamelCase__      :			List[Any] 						= ["""pixel_values"""]
																					self.assertListEqual(arg_names[:1]    ,							UpperCamelCase__  )




							@unittest.skip(reason="""MaskFormerSwin is only used as backbone and doesn't support output_attentions"""  )
							def 	lowerCamelCase_       (							self:       Any  ):
														pass




							@unittest.skip(reason="""MaskFormerSwin is only used as an internal backbone"""  )
							def 	lowerCamelCase_       (							self:       Optional[Any]  ):
														pass




							def 	lowerCamelCase_       (							self:       List[Any]    ,							UpperCamelCase__:       Optional[int]    ,							UpperCamelCase__:       Optional[int]    ,							UpperCamelCase__:       Tuple    ,							UpperCamelCase__:       Tuple  ):
														lowerCamelCase__      :			List[str] 						= model_class(UpperCamelCase__  )
														model.to(UpperCamelCase__  )
														model.eval()

														with torch.no_grad():
																					lowerCamelCase__      :			List[Any] 						= model(**self._prepare_for_class(UpperCamelCase__    ,							UpperCamelCase__  )  )

														lowerCamelCase__      :			Union[str, Any] 						= outputs.hidden_states

														lowerCamelCase__      :			Union[str, Any] 						= getattr(
														    self.model_tester    ,							"""expected_num_hidden_layers"""    ,							len(self.model_tester.depths  ) + 1  )
														self.assertEqual(len(UpperCamelCase__  )    ,							UpperCamelCase__  )

														# Swin has a different seq_length
														lowerCamelCase__      :			int 						= (
														    config.patch_size
														    if isinstance(config.patch_size    ,							collections.abc.Iterable  )
														    else (config.patch_size, config.patch_size)
														)

														lowerCamelCase__      :			Union[str, Any] 						= (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

														self.assertListEqual(
														    list(hidden_states[0].shape[-2:]  )    ,							[num_patches, self.model_tester.embed_dim]    ,							)




							def 	lowerCamelCase_       (							self:       Union[str, Any]  ):
														lowerCamelCase__      :			List[str] 						= self.model_tester.prepare_config_and_inputs_for_common()

														lowerCamelCase__      :			Optional[int] 						= (
														    self.model_tester.image_size
														    if isinstance(self.model_tester.image_size    ,							collections.abc.Iterable  )
														    else (self.model_tester.image_size, self.model_tester.image_size)
														)

														for model_class in self.all_model_classes:
																					lowerCamelCase__      :			Any 						= True
																					self.check_hidden_states_output(UpperCamelCase__    ,							UpperCamelCase__    ,							UpperCamelCase__    ,							UpperCamelCase__  )

																					# check that output_hidden_states also work using config
																					del inputs_dict["output_hidden_states"]
																					lowerCamelCase__      :			Any 						= True

																					self.check_hidden_states_output(UpperCamelCase__    ,							UpperCamelCase__    ,							UpperCamelCase__    ,							UpperCamelCase__  )




							def 	lowerCamelCase_       (							self:       Optional[Any]  ):
														lowerCamelCase__      :			int 						= self.model_tester.prepare_config_and_inputs_for_common()
														lowerCamelCase__      :			Tuple 						= 3

														lowerCamelCase__      :			Optional[int] 						= (
														    self.model_tester.image_size
														    if isinstance(self.model_tester.image_size    ,							collections.abc.Iterable  )
														    else (self.model_tester.image_size, self.model_tester.image_size)
														)
														lowerCamelCase__      :			Optional[int] 						= (
														    config.patch_size
														    if isinstance(config.patch_size    ,							collections.abc.Iterable  )
														    else (config.patch_size, config.patch_size)
														)

														lowerCamelCase__      :			List[Any] 						= image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
														lowerCamelCase__      :			int 						= image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

														for model_class in self.all_model_classes:
																					lowerCamelCase__      :			Dict 						= True
																					self.check_hidden_states_output(UpperCamelCase__    ,							UpperCamelCase__    ,							UpperCamelCase__    ,							(padded_height, padded_width)  )

																					# check that output_hidden_states also work using config
																					del inputs_dict["output_hidden_states"]
																					lowerCamelCase__      :			Dict 						= True
																					self.check_hidden_states_output(UpperCamelCase__    ,							UpperCamelCase__    ,							UpperCamelCase__    ,							(padded_height, padded_width)  )




							@unittest.skip(reason="""MaskFormerSwin doesn't have pretrained checkpoints"""  )
							def 	lowerCamelCase_       (							self:       List[str]  ):
														pass




							@unittest.skip(reason="""This will be fixed once MaskFormerSwin is replaced by native Swin"""  )
							def 	lowerCamelCase_       (							self:       Any  ):
														pass




							@unittest.skip(reason="""This will be fixed once MaskFormerSwin is replaced by native Swin"""  )
							def 	lowerCamelCase_       (							self:       Any  ):
														pass




							def 	lowerCamelCase_       (							self:       int  ):
														lowerCamelCase__      :			List[Any] 						= self.model_tester.prepare_config_and_inputs_for_common()

														def set_nan_tensor_to_zero(UpperCamelCase__:       int  ):
																					lowerCamelCase__      :			str 						= 0
																					return t

														def check_equivalence(UpperCamelCase__:       Optional[int]    ,							UpperCamelCase__:       Optional[Any]    ,							UpperCamelCase__:       Optional[int]    ,							UpperCamelCase__:       List[str]={}  ):
																					with torch.no_grad():
																												lowerCamelCase__      :			List[Any] 						= model(**UpperCamelCase__    ,							return_dict=UpperCamelCase__    ,							**UpperCamelCase__  )
																												lowerCamelCase__      :			Any 						= model(**UpperCamelCase__    ,							return_dict=UpperCamelCase__    ,							**UpperCamelCase__  ).to_tuple()

																												def recursive_check(UpperCamelCase__:       Optional[Any]    ,							UpperCamelCase__:       Optional[Any]  ):
																																			if isinstance(UpperCamelCase__    ,							(List, Tuple)  ):
																																										for tuple_iterable_value, dict_iterable_value in zip(UpperCamelCase__    ,							UpperCamelCase__  ):
																																																	recursive_check(UpperCamelCase__    ,							UpperCamelCase__  )
																																			elif isinstance(UpperCamelCase__    ,							UpperCamelCase__  ):
																																										for tuple_iterable_value, dict_iterable_value in zip(
																																										    tuple_object.values()    ,							dict_object.values()  ):
																																																	recursive_check(UpperCamelCase__    ,							UpperCamelCase__  )
																																			elif tuple_object is None:
																																										return
																																			else:
																																										self.assertTrue(
																																										    torch.allclose(
																																										        set_nan_tensor_to_zero(UpperCamelCase__  )    ,							set_nan_tensor_to_zero(UpperCamelCase__  )    ,							atol=1e-5  )    ,							msg=(
																																										        """Tuple and dict output are not equal. Difference:"""
																																										        F''' {torch.max(torch.abs(tuple_object - dict_object  )  )}. Tuple has `nan`:'''
																																										        F''' {torch.isnan(UpperCamelCase__  ).any()} and `inf`: {torch.isinf(UpperCamelCase__  )}. Dict has'''
																																										        F''' `nan`: {torch.isnan(UpperCamelCase__  ).any()} and `inf`: {torch.isinf(UpperCamelCase__  )}.'''
																																										    )    ,							)

																												recursive_check(UpperCamelCase__    ,							UpperCamelCase__  )

														for model_class in self.all_model_classes:
																					lowerCamelCase__      :			Tuple 						= model_class(UpperCamelCase__  )
																					model.to(UpperCamelCase__  )
																					model.eval()

																					lowerCamelCase__      :			Optional[int] 						= self._prepare_for_class(UpperCamelCase__    ,							UpperCamelCase__  )
																					lowerCamelCase__      :			int 						= self._prepare_for_class(UpperCamelCase__    ,							UpperCamelCase__  )
																					check_equivalence(UpperCamelCase__    ,							UpperCamelCase__    ,							UpperCamelCase__  )

																					lowerCamelCase__      :			str 						= self._prepare_for_class(UpperCamelCase__    ,							UpperCamelCase__    ,							return_labels=UpperCamelCase__  )
																					lowerCamelCase__      :			Optional[int] 						= self._prepare_for_class(UpperCamelCase__    ,							UpperCamelCase__    ,							return_labels=UpperCamelCase__  )
																					check_equivalence(UpperCamelCase__    ,							UpperCamelCase__    ,							UpperCamelCase__  )

																					lowerCamelCase__      :			Union[str, Any] 						= self._prepare_for_class(UpperCamelCase__    ,							UpperCamelCase__  )
																					lowerCamelCase__      :			str 						= self._prepare_for_class(UpperCamelCase__    ,							UpperCamelCase__  )
																					check_equivalence(UpperCamelCase__    ,							UpperCamelCase__    ,							UpperCamelCase__    ,							{"""output_hidden_states""": True}  )

																					lowerCamelCase__      :			List[str] 						= self._prepare_for_class(UpperCamelCase__    ,							UpperCamelCase__    ,							return_labels=UpperCamelCase__  )
																					lowerCamelCase__      :			int 						= self._prepare_for_class(UpperCamelCase__    ,							UpperCamelCase__    ,							return_labels=UpperCamelCase__  )
																					check_equivalence(UpperCamelCase__    ,							UpperCamelCase__    ,							UpperCamelCase__    ,							{"""output_hidden_states""": True}  )



@require_torch
class _lowercase			(       unittest.TestCase       ,   _lowercase	):
							a          = (MaskFormerSwinBackbone,) if is_torch_available() else ()
							a          = MaskFormerSwinConfig




							def 	lowerCamelCase_       (							self:       Optional[Any]  ):
														lowerCamelCase__      :			str 						= MaskFormerSwinModelTester(self  )




							def 	lowerCamelCase_       (							self:       Any  ):
														lowerCamelCase__      :			List[Any] 						= self.model_tester.prepare_config_and_inputs_for_common()
														lowerCamelCase__      :			Dict 						= inputs_dict["""pixel_values"""].shape[0]

														for backbone_class in self.all_model_classes:
																					lowerCamelCase__      :			Union[str, Any] 						= backbone_class(UpperCamelCase__  )
																					backbone.to(UpperCamelCase__  )
																					backbone.eval()

																					lowerCamelCase__      :			str 						= backbone(**UpperCamelCase__  )

																					# Test default outputs and verify feature maps
																					self.assertIsInstance(outputs.feature_maps    ,							UpperCamelCase__  )
																					self.assertTrue(len(outputs.feature_maps  ) == len(backbone.channels  )  )
																					for feature_map, n_channels in zip(outputs.feature_maps    ,							backbone.channels  ):
																												self.assertTrue(feature_map.shape[:2]    ,							(batch_size, n_channels)  )
																					self.assertIsNone(outputs.hidden_states  )
																					self.assertIsNone(outputs.attentions  )

																					# Test output_hidden_states=True
																					lowerCamelCase__      :			List[str] 						= backbone(**UpperCamelCase__    ,							output_hidden_states=UpperCamelCase__  )
																					self.assertIsNotNone(outputs.hidden_states  )
																					self.assertTrue(len(outputs.hidden_states  )    ,							len(backbone.stage_names  )  )
																					# We skip the stem layer
																					for hidden_states, n_channels in zip(outputs.hidden_states[1:]    ,							backbone.channels  ):
																												for hidden_state in hidden_states:
																																			# Hidden states are in the format (batch_size, (height * width), n_channels)
																																			lowerCamelCase__      :			Union[str, Any] 						= hidden_state.shape
																																			self.assertTrue((h_batch_size, h_n_channels)    ,							(batch_size, n_channels)  )

            # Test output_attentions=True
																					if self.has_attentions:
																												lowerCamelCase__      :			List[Any] 						= backbone(**UpperCamelCase__    ,							output_attentions=UpperCamelCase__  )
																												self.assertIsNotNone(outputs.attentions  )









'''simple docstring'''







import inspect
import math
import tempfile
import unittest

import numpy as np

from transformers import ViTMAEConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
			import torch
			from torch import nn

			from transformers import ViTMAEForPreTraining, ViTMAEModel
			from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
			from PIL import Image

			from transformers import ViTImageProcessor

class _lowercase			:




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

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




							def 	lowerCamelCase_       (							self:       Optional[int]  ):
														lowerCamelCase__      :			Tuple 						= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

														lowerCamelCase__      :			Optional[int] 						= None
														if self.use_labels:
																					lowerCamelCase__      :			List[str] 						= ids_tensor([self.batch_size]    ,							self.type_sequence_label_size  )

														lowerCamelCase__      :			Any 						= self.get_config()

														return config, pixel_values, labels




							def 	lowerCamelCase_       (							self:       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    ,							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:       List[Any]    ,							UpperCamelCase__:       Optional[int]    ,							UpperCamelCase__:       Optional[int]    ,							UpperCamelCase__:       int  ):
														lowerCamelCase__      :			Tuple 						= ViTMAEModel(config=UpperCamelCase__  )
														model.to(UpperCamelCase__  )
														model.eval()
														lowerCamelCase__      :			List[Any] 						= model(UpperCamelCase__  )
														self.parent.assertEqual(result.last_hidden_state.shape    ,							(self.batch_size, self.seq_length, self.hidden_size)  )




							def 	lowerCamelCase_       (							self:       str    ,							UpperCamelCase__:       Union[str, Any]    ,							UpperCamelCase__:       List[Any]    ,							UpperCamelCase__:       Dict  ):
														lowerCamelCase__      :			int 						= ViTMAEForPreTraining(UpperCamelCase__  )
														model.to(UpperCamelCase__  )
														model.eval()
														lowerCamelCase__      :			Optional[int] 						= model(UpperCamelCase__  )
														lowerCamelCase__      :			Any 						= (self.image_size // self.patch_size) ** 2
														lowerCamelCase__      :			str 						= self.patch_size**2 * self.num_channels
														self.parent.assertEqual(result.logits.shape    ,							(self.batch_size, num_patches, expected_num_channels)  )

														# test greyscale images
														lowerCamelCase__      :			Dict 						= 1
														lowerCamelCase__      :			Optional[int] 						= ViTMAEForPreTraining(UpperCamelCase__  )
														model.to(UpperCamelCase__  )
														model.eval()
														lowerCamelCase__      :			Dict 						= floats_tensor([self.batch_size, 1, self.image_size, self.image_size]  )
														lowerCamelCase__      :			Optional[Any] 						= model(UpperCamelCase__  )
														lowerCamelCase__      :			Tuple 						= self.patch_size**2
														self.parent.assertEqual(result.logits.shape    ,							(self.batch_size, num_patches, expected_num_channels)  )




							def 	lowerCamelCase_       (							self:       Any  ):
														lowerCamelCase__      :			Optional[int] 						= self.prepare_config_and_inputs()
														lowerCamelCase__						,	lowerCamelCase__						,	lowerCamelCase__      :			Any 						= config_and_inputs
														lowerCamelCase__      :			Optional[int] 						= {"""pixel_values""": pixel_values}
														return config, inputs_dict



@require_torch
class _lowercase			(       _lowercase       ,   _lowercase       ,   unittest.TestCase	):
							a          = (ViTMAEModel, ViTMAEForPreTraining) if is_torch_available() else ()
							a          = {"""feature-extraction""": ViTMAEModel} if is_torch_available() else {}

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




							def 	lowerCamelCase_       (							self:       Any  ):
														lowerCamelCase__      :			Tuple 						= ViTMAEModelTester(self  )
														lowerCamelCase__      :			Union[str, Any] 						= ConfigTester(self    ,							config_class=UpperCamelCase__    ,							has_text_modality=UpperCamelCase__    ,							hidden_size=37  )




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




							@unittest.skip(reason="""ViTMAE does not use inputs_embeds"""  )
							def 	lowerCamelCase_       (							self:       Dict  ):
														pass




							def 	lowerCamelCase_       (							self:       List[str]  ):
														lowerCamelCase__						,	lowerCamelCase__      :			str 						= self.model_tester.prepare_config_and_inputs_for_common()

														for model_class in self.all_model_classes:
																					lowerCamelCase__      :			str 						= model_class(UpperCamelCase__  )
																					self.assertIsInstance(model.get_input_embeddings()    ,							(nn.Module)  )
																					lowerCamelCase__      :			Optional[Any] 						= model.get_output_embeddings()
																					self.assertTrue(x is None or isinstance(UpperCamelCase__    ,							nn.Linear  )  )




							def 	lowerCamelCase_       (							self:       List[Any]  ):
														lowerCamelCase__						,	lowerCamelCase__      :			Union[str, Any] 						= self.model_tester.prepare_config_and_inputs_for_common()

														for model_class in self.all_model_classes:
																					lowerCamelCase__      :			Any 						= model_class(UpperCamelCase__  )
																					lowerCamelCase__      :			str 						= inspect.signature(model.forward  )
																					# signature.parameters is an OrderedDict => so arg_names order is deterministic
																					lowerCamelCase__      :			Any 						= [*signature.parameters.keys()]

																					lowerCamelCase__      :			List[str] 						= ["""pixel_values"""]
																					self.assertListEqual(arg_names[:1]    ,							UpperCamelCase__  )




							def 	lowerCamelCase_       (							self:       Union[str, Any]  ):
														lowerCamelCase__      :			Union[str, Any] 						= self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_model(*UpperCamelCase__  )




							def 	lowerCamelCase_       (							self:       Any  ):
														lowerCamelCase__      :			int 						= self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_for_pretraining(*UpperCamelCase__  )




							def 	lowerCamelCase_       (							self:       Optional[int]    ,							UpperCamelCase__:       Union[str, Any]    ,							UpperCamelCase__:       Dict    ,							UpperCamelCase__:       Optional[int]  ):
														# make masks reproducible
														np.random.seed(2  )

														lowerCamelCase__      :			Tuple 						= int((pt_model.config.image_size // pt_model.config.patch_size) ** 2  )
														lowerCamelCase__      :			List[str] 						= np.random.uniform(size=(self.model_tester.batch_size, num_patches)  )
														lowerCamelCase__      :			Tuple 						= torch.from_numpy(UpperCamelCase__  )

														# Add `noise` argument.
														# PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument
														lowerCamelCase__      :			Tuple 						= pt_noise

														super().check_pt_tf_models(UpperCamelCase__    ,							UpperCamelCase__    ,							UpperCamelCase__  )




							def 	lowerCamelCase_       (							self:       str  ):
														lowerCamelCase__						,	lowerCamelCase__      :			Optional[Any] 						= self.model_tester.prepare_config_and_inputs_for_common()

														for model_class in self.all_model_classes:
																					lowerCamelCase__      :			Union[str, Any] 						= model_class(UpperCamelCase__  )
																					model.to(UpperCamelCase__  )
																					model.eval()
																					# make random mask reproducible
																					torch.manual_seed(2  )
																					with torch.no_grad():
																												lowerCamelCase__      :			Optional[int] 						= model(**self._prepare_for_class(UpperCamelCase__    ,							UpperCamelCase__  )  )

																					lowerCamelCase__      :			Optional[int] 						= outputs[0].cpu().numpy()
																					lowerCamelCase__      :			List[str] 						= 0

																					with tempfile.TemporaryDirectory() as tmpdirname:
																												model.save_pretrained(UpperCamelCase__  )
																												lowerCamelCase__      :			List[str] 						= model_class.from_pretrained(UpperCamelCase__  )
																												model.to(UpperCamelCase__  )
																												# make random mask reproducible
																												torch.manual_seed(2  )
																												with torch.no_grad():
																																			lowerCamelCase__      :			Tuple 						= model(**self._prepare_for_class(UpperCamelCase__    ,							UpperCamelCase__  )  )

																												# Make sure we don't have nans
																												lowerCamelCase__      :			Dict 						= after_outputs[0].cpu().numpy()
																												lowerCamelCase__      :			Tuple 						= 0
																												lowerCamelCase__      :			Union[str, Any] 						= np.amax(np.abs(out_a - out_a  )  )
																												self.assertLessEqual(UpperCamelCase__    ,							1e-5  )




							@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:       int  ):
														pass




							@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:       Any  ):
														pass




							@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:       List[str]  ):
														pass




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




							@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""  )
							def 	lowerCamelCase_       (							self:       Optional[int]  ):
														pass




							@slow
							def 	lowerCamelCase_       (							self:       List[str]  ):
														for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																					lowerCamelCase__      :			Tuple 						= ViTMAEModel.from_pretrained(UpperCamelCase__  )
																					self.assertIsNotNone(UpperCamelCase__  )





def 				SCREAMING_SNAKE_CASE_ ()   -> List[Any]:
							lowerCamelCase__      :			Union[str, Any] 						= Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""   )
							return image



@require_torch
@require_vision
class _lowercase			(       unittest.TestCase	):




							@cached_property
							def 	lowerCamelCase_       (							self:       List[str]  ):
														return ViTImageProcessor.from_pretrained("""facebook/vit-mae-base"""  ) if is_vision_available() else None




							@slow
							def 	lowerCamelCase_       (							self:       Tuple  ):
														# make random mask reproducible across the PT and TF model
														np.random.seed(2  )

														lowerCamelCase__      :			str 						= ViTMAEForPreTraining.from_pretrained("""facebook/vit-mae-base"""  ).to(UpperCamelCase__  )

														lowerCamelCase__      :			Tuple 						= self.default_image_processor
														lowerCamelCase__      :			List[str] 						= prepare_img()
														lowerCamelCase__      :			int 						= image_processor(images=UpperCamelCase__    ,							return_tensors="""pt"""  ).to(UpperCamelCase__  )

														# 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)
														lowerCamelCase__      :			List[str] 						= ViTMAEConfig()
														lowerCamelCase__      :			int 						= int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2  )
														lowerCamelCase__      :			Any 						= np.random.uniform(size=(1, num_patches)  )

														# forward pass
														with torch.no_grad():
																					lowerCamelCase__      :			List[Any] 						= model(**UpperCamelCase__    ,							noise=torch.from_numpy(UpperCamelCase__  ).to(device=UpperCamelCase__  )  )

														# verify the logits
														lowerCamelCase__      :			List[str] 						= torch.Size((1, 196, 768)  )
														self.assertEqual(outputs.logits.shape    ,							UpperCamelCase__  )

														lowerCamelCase__      :			str 						= torch.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]]  )

														self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]    ,							expected_slice.to(UpperCamelCase__  )    ,							atol=1e-4  )  )

