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 , __lowercase , __lowercase=13 , __lowercase=30 , __lowercase=2 , __lowercase=3 , __lowercase=True , __lowercase=True , __lowercase=32 , __lowercase=2 , __lowercase=4 , __lowercase=37 , __lowercase="gelu" , __lowercase=0.1 , __lowercase=0.1 , __lowercase=10 , __lowercase=0.02 , __lowercase=3 , __lowercase=0.6 , __lowercase=None , )       ->	Tuple:
        __UpperCamelCase     :List[str]			  =		parent
        __UpperCamelCase     :List[Any]			  =		batch_size
        __UpperCamelCase     :str			  =		image_size
        __UpperCamelCase     :List[Any]			  =		patch_size
        __UpperCamelCase     :List[str]			  =		num_channels
        __UpperCamelCase     :Union[str, Any]			  =		is_training
        __UpperCamelCase     :List[str]			  =		use_labels
        __UpperCamelCase     :Tuple			  =		hidden_size
        __UpperCamelCase     :str			  =		num_hidden_layers
        __UpperCamelCase     :List[Any]			  =		num_attention_heads
        __UpperCamelCase     :Optional[Any]			  =		intermediate_size
        __UpperCamelCase     :List[str]			  =		hidden_act
        __UpperCamelCase     :str			  =		hidden_dropout_prob
        __UpperCamelCase     :List[str]			  =		attention_probs_dropout_prob
        __UpperCamelCase     :Union[str, Any]			  =		type_sequence_label_size
        __UpperCamelCase     :List[str]			  =		initializer_range
        __UpperCamelCase     :Optional[int]			  =		mask_ratio
        __UpperCamelCase     :Optional[int]			  =		scope

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







    def 			UpperCamelCase__   (	self)       ->	Union[str, Any]:
        __UpperCamelCase     :Optional[Any]			  =		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

        __UpperCamelCase     :List[Any]			  =		self.get_config()

        return config, pixel_values, labels







    def 			UpperCamelCase__   (	self)       ->	Tuple:
        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=__lowercase , initializer_range=self.initializer_range , mask_ratio=self.mask_ratio , )







    def 			UpperCamelCase__   (	self , __lowercase , __lowercase , __lowercase)       ->	Any:
        __UpperCamelCase     :Any			  =		TFViTMAEModel(config=__lowercase)
        __UpperCamelCase     :Union[str, Any]			  =		model(__lowercase , training=__lowercase)
        self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size))







    def 			UpperCamelCase__   (	self , __lowercase , __lowercase , __lowercase)       ->	List[str]:
        __UpperCamelCase     :str			  =		TFViTMAEForPreTraining(__lowercase)
        __UpperCamelCase     :str			  =		model(__lowercase , training=__lowercase)
        # expected sequence length = num_patches
        __UpperCamelCase     :List[str]			  =		(self.image_size // self.patch_size) ** 2
        __UpperCamelCase     :Union[str, 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
        __UpperCamelCase     :List[str]			  =		1
        __UpperCamelCase     :List[str]			  =		TFViTMAEForPreTraining(__lowercase)

        __UpperCamelCase     :int			  =		floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
        __UpperCamelCase     :Dict			  =		model(__lowercase , training=__lowercase)
        __UpperCamelCase     :List[str]			  =		self.patch_size**2
        self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels))







    def 			UpperCamelCase__   (	self)       ->	List[Any]:
        __UpperCamelCase     :Optional[int]			  =		self.prepare_config_and_inputs()
        ((__UpperCamelCase)  ,       (__UpperCamelCase)  ,       (__UpperCamelCase))     :List[str]			  =		config_and_inputs
        __UpperCamelCase     :Dict			  =		{'''pixel_values''': pixel_values}
        return config, inputs_dict


@require_tf
class 	lowerCamelCase_     (   UpperCAmelCase_						,	UpperCAmelCase_						,	unittest.TestCase ):






    '''simple docstring'''






    a__	:						str						=      (TFViTMAEModel, TFViTMAEForPreTraining) if is_tf_available() else ()
    a__	:						Dict						=      {"""feature-extraction""": TFViTMAEModel} if is_tf_available() else {}

    a__	:						Tuple						=      False
    a__	:						str						=      False
    a__	:						Optional[Any]						=      False
    a__	:						Union[str, Any]						=      False







    def 			UpperCamelCase__   (	self)       ->	Union[str, Any]:
        __UpperCamelCase     :List[str]			  =		TFViTMAEModelTester(self)
        __UpperCamelCase     :List[str]			  =		ConfigTester(self , config_class=__lowercase , has_text_modality=__lowercase , hidden_size=37)







    def 			UpperCamelCase__   (	self)       ->	Tuple:
        self.config_tester.run_common_tests()







    @unittest.skip(reason='''ViTMAE does not use inputs_embeds''')
    def 			UpperCamelCase__   (	self)       ->	str:
        pass







    def 			UpperCamelCase__   (	self)       ->	Any:
        __UpperCamelCase  ,       __UpperCamelCase     :int			  =		self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
            __UpperCamelCase     :List[Any]			  =		model_class(__lowercase)
            self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer))
            __UpperCamelCase     :Optional[Any]			  =		model.get_output_embeddings()
            self.assertTrue(x is None or isinstance(__lowercase , tf.keras.layers.Layer))







    def 			UpperCamelCase__   (	self)       ->	Dict:
        __UpperCamelCase  ,       __UpperCamelCase     :List[Any]			  =		self.model_tester.prepare_config_and_inputs_for_common()

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

            __UpperCamelCase     :Any			  =		['''pixel_values''']
            self.assertListEqual(arg_names[:1] , __lowercase)







    def 			UpperCamelCase__   (	self)       ->	Any:
        __UpperCamelCase     :List[str]			  =		self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__lowercase)







    def 			UpperCamelCase__   (	self)       ->	List[Any]:
        __UpperCamelCase     :str			  =		self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_pretraining(*__lowercase)







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

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

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

        for model_class in self.all_model_classes:
            __UpperCamelCase     :str			  =		model_class(__lowercase)
            __UpperCamelCase     :Optional[int]			  =		self._prepare_for_class(__lowercase , __lowercase)

            __UpperCamelCase     :Dict			  =		model(__lowercase , noise=__lowercase)

            __UpperCamelCase     :int			  =		copy.deepcopy(self._prepare_for_class(__lowercase , __lowercase))
            __UpperCamelCase     :Union[str, Any]			  =		model(**__lowercase , noise=__lowercase)
            __UpperCamelCase     :Tuple			  =		outputs_dict[0].numpy()
            __UpperCamelCase     :Union[str, Any]			  =		outputs_keywords[0].numpy()

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







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

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

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

        def prepare_numpy_arrays(__lowercase):
            __UpperCamelCase     :Optional[int]			  =		{}
            for k, v in inputs_dict.items():
                if tf.is_tensor(__lowercase):
                    __UpperCamelCase     :Optional[Any]			  =		v.numpy()
                else:
                    __UpperCamelCase     :Optional[int]			  =		np.array(__lowercase)

            return inputs_np_dict

        for model_class in self.all_model_classes:
            __UpperCamelCase     :int			  =		model_class(__lowercase)

            __UpperCamelCase     :Tuple			  =		self._prepare_for_class(__lowercase , __lowercase)
            __UpperCamelCase     :Any			  =		prepare_numpy_arrays(__lowercase)

            __UpperCamelCase     :Any			  =		model(__lowercase , noise=__lowercase)
            __UpperCamelCase     :Tuple			  =		model(**__lowercase , noise=__lowercase)
            self.assert_outputs_same(__lowercase , __lowercase)







    def 			UpperCamelCase__   (	self , __lowercase , __lowercase , __lowercase)       ->	List[Any]:
        # make masks reproducible
        np.random.seed(2)

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

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

        super().check_pt_tf_models(__lowercase , __lowercase , __lowercase)







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

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

        __UpperCamelCase     :Optional[int]			  =		{
            module_member
            for model_class in self.all_model_classes
            for module in (import_module(model_class.__module__),)
            for module_member_name in dir(__lowercase)
            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(__lowercase , __lowercase),)
            if isinstance(__lowercase , __lowercase)
            and tf.keras.layers.Layer in module_member.__bases__
            and getattr(__lowercase , '''_keras_serializable''' , __lowercase)
        }

        __UpperCamelCase     :Union[str, Any]			  =		int((config.image_size // config.patch_size) ** 2)
        __UpperCamelCase     :List[str]			  =		np.random.uniform(size=(self.model_tester.batch_size, num_patches))
        __UpperCamelCase     :str			  =		tf.convert_to_tensor(__lowercase)
        inputs_dict.update({'''noise''': noise})

        for main_layer_class in tf_main_layer_classes:
            __UpperCamelCase     :Optional[int]			  =		main_layer_class(__lowercase)

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

            __UpperCamelCase     :Dict			  =		tf.keras.Model(__lowercase , outputs=main_layer(__lowercase))
            __UpperCamelCase     :str			  =		model(__lowercase)

            with tempfile.TemporaryDirectory() as tmpdirname:
                __UpperCamelCase     :str			  =		os.path.join(__lowercase , '''keras_model.h5''')
                model.save(__lowercase)
                __UpperCamelCase     :List[Any]			  =		tf.keras.models.load_model(
                    __lowercase , custom_objects={main_layer_class.__name__: main_layer_class})
                assert isinstance(__lowercase , tf.keras.Model)
                __UpperCamelCase     :Optional[Any]			  =		model(__lowercase)
                self.assert_outputs_same(__lowercase , __lowercase)







    @slow
    def 			UpperCamelCase__   (	self)       ->	Dict:
        # make mask reproducible
        np.random.seed(2)

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

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

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

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

            with tempfile.TemporaryDirectory() as tmpdirname:
                model.save_pretrained(__lowercase , saved_model=__lowercase)
                __UpperCamelCase     :Optional[int]			  =		model_class.from_pretrained(__lowercase)
                __UpperCamelCase     :List[str]			  =		model(__lowercase , noise=__lowercase)

                if model_class.__name__ == "TFViTMAEModel":
                    __UpperCamelCase     :List[Any]			  =		after_outputs['''last_hidden_state'''].numpy()
                    __UpperCamelCase     :List[Any]			  =		0
                else:
                    __UpperCamelCase     :Any			  =		after_outputs['''logits'''].numpy()
                    __UpperCamelCase     :Tuple			  =		0

                __UpperCamelCase     :Any			  =		np.amax(np.abs(out_a - out_a))
                self.assertLessEqual(__lowercase , 1E-5)







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

        __UpperCamelCase  ,       __UpperCamelCase     :Any			  =		self.model_tester.prepare_config_and_inputs_for_common()

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

        for model_class in self.all_model_classes:
            __UpperCamelCase     :Tuple			  =		model_class(__lowercase)
            __UpperCamelCase     :Any			  =		self._prepare_for_class(__lowercase , __lowercase)

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

            self.assert_outputs_same(__lowercase , __lowercase)







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







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







    @slow
    def 			UpperCamelCase__   (	self)       ->	Any:
        __UpperCamelCase     :List[Any]			  =		TFViTMAEModel.from_pretrained('''google/vit-base-patch16-224''')
        self.assertIsNotNone(__lowercase)



def lowerCamelCase  (   ):
    '''simple docstring'''







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


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






    '''simple docstring'''






    @cached_property
    def 			UpperCamelCase__   (	self)       ->	Optional[Any]:
        return ViTImageProcessor.from_pretrained('''facebook/vit-mae-base''') if is_vision_available() else None







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

        __UpperCamelCase     :Optional[Any]			  =		TFViTMAEForPreTraining.from_pretrained('''facebook/vit-mae-base''')

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

        # forward pass
        __UpperCamelCase     :int			  =		model(**__lowercase , noise=__lowercase)

        # verify the logits
        __UpperCamelCase     :Optional[int]			  =		tf.convert_to_tensor([1, 196, 768])
        self.assertEqual(outputs.logits.shape , __lowercase)

        __UpperCamelCase     :List[Any]			  =		tf.convert_to_tensor(
            [[-0.05_48, -1.70_23, -0.93_25], [0.37_21, -0.56_70, -0.22_33], [0.82_35, -1.38_78, -0.35_24]])

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









from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowerCAmelCase__      		= logging.get_logger(__name__)

lowerCAmelCase__      		= {
    'facebook/vit-mae-base': 'https://huggingface.co/facebook/vit-mae-base/resolve/main/config.json',
    # See all ViT MAE models at https://huggingface.co/models?filter=vit-mae
}







class      lowerCAmelCase__       (				a):




     '''simple docstring'''
     __SCREAMING_SNAKE_CASE  			= "vit_mae"


     def __init__(						self ,						__lowerCamelCase=7_6_8 ,						__lowerCamelCase=1_2 ,						__lowerCamelCase=1_2 ,						__lowerCamelCase=3_0_7_2 ,						__lowerCamelCase="gelu" ,						__lowerCamelCase=0.0 ,						__lowerCamelCase=0.0 ,						__lowerCamelCase=0.0_2 ,						__lowerCamelCase=1e-12 ,						__lowerCamelCase=2_2_4 ,						__lowerCamelCase=1_6 ,						__lowerCamelCase=3 ,						__lowerCamelCase=True ,						__lowerCamelCase=1_6 ,						__lowerCamelCase=5_1_2 ,						__lowerCamelCase=8 ,						__lowerCamelCase=2_0_4_8 ,						__lowerCamelCase=0.7_5 ,						__lowerCamelCase=False ,						**__lowerCamelCase ,						)			->				int:
            super().__init__(**__lowerCamelCase)

            _A      :       int				    = hidden_size
            _A      :       List[str]				    = num_hidden_layers
            _A      :       List[Any]				    = num_attention_heads
            _A      :       Optional[Any]				    = intermediate_size
            _A      :       Optional[int]				    = hidden_act
            _A      :       List[Any]				    = hidden_dropout_prob
            _A      :       List[Any]				    = attention_probs_dropout_prob
            _A      :       Union[str, Any]				    = initializer_range
            _A      :       str				    = layer_norm_eps
            _A      :       Any				    = image_size
            _A      :       int				    = patch_size
            _A      :       int				    = num_channels
            _A      :       Dict				    = qkv_bias
            _A      :       Tuple				    = decoder_num_attention_heads
            _A      :       Tuple				    = decoder_hidden_size
            _A      :       List[str]				    = decoder_num_hidden_layers
            _A      :       Optional[Any]				    = decoder_intermediate_size
            _A      :       List[str]				    = mask_ratio
            _A      :       Union[str, Any]				    = norm_pix_loss
