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







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

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







			def 	SCREAMING_SNAKE_CASE_     (	self				:  Optional[int]    ):
										lowercase_					:			Optional[int]										=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

										lowercase_					:			Optional[Any]										=       None
										if self.use_labels:
																	lowercase_					:			Tuple										=       ids_tensor([self.batch_size]				,			self.type_sequence_label_size    )

										lowercase_					:			int										=       self.get_config()

										return config, pixel_values, labels







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







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

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







			def 	SCREAMING_SNAKE_CASE_     (	self				:  Any    ):
										lowercase_					:			List[Any]										=       self.prepare_config_and_inputs()
										((lowercase_)						,						(lowercase_)						,						(lowercase_))					:			Optional[int]										=       config_and_inputs
										lowercase_					:			List[str]										=       {"""pixel_values""": pixel_values}
										return config, inputs_dict





@require_tf
class     __magic_name__						(    lowerCamelCase__,     lowerCamelCase__,     unittest.TestCase):
			UpperCamelCase__				=       (TFViTMAEModel, TFViTMAEForPreTraining) if is_tf_available() else ()
			UpperCamelCase__				=       {'feature-extraction': TFViTMAEModel} if is_tf_available() else {}

			UpperCamelCase__				=       False
			UpperCamelCase__				=       False
			UpperCamelCase__				=       False
			UpperCamelCase__				=       False







			def 	SCREAMING_SNAKE_CASE_     (	self				:  Optional[Any]    ):
										lowercase_					:			Union[str, Any]										=       TFViTMAEModelTester(self    )
										lowercase_					:			Any										=       ConfigTester(self				,			config_class=lowercase__				,			has_text_modality=lowercase__				,			hidden_size=37    )







			def 	SCREAMING_SNAKE_CASE_     (	self				:  str    ):
										self.config_tester.run_common_tests()







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







			def 	SCREAMING_SNAKE_CASE_     (	self				:  Optional[Any]    ):
										lowercase_						,						lowercase_					:			Dict										=       self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
																	lowercase_					:			Dict										=       model_class(lowercase__    )
																	self.assertIsInstance(model.get_input_embeddings()				,			(tf.keras.layers.Layer)    )
																	lowercase_					:			List[str]										=       model.get_output_embeddings()
																	self.assertTrue(x is None or isinstance(lowercase__				,			tf.keras.layers.Layer    )    )







			def 	SCREAMING_SNAKE_CASE_     (	self				:  List[Any]    ):
										lowercase_						,						lowercase_					:			str										=       self.model_tester.prepare_config_and_inputs_for_common()

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

																	lowercase_					:			Optional[Any]										=       ["""pixel_values"""]
																	self.assertListEqual(arg_names[:1]				,			lowercase__    )







			def 	SCREAMING_SNAKE_CASE_     (	self				:  List[Any]    ):
										lowercase_					:			Tuple										=       self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*lowercase__    )







			def 	SCREAMING_SNAKE_CASE_     (	self				:  str    ):
										lowercase_					:			List[str]										=       self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_pretraining(*lowercase__    )







			def 	SCREAMING_SNAKE_CASE_     (	self				:  str    ):
										# make the mask reproducible
										np.random.seed(2    )

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

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

										for model_class in self.all_model_classes:
																	lowercase_					:			int										=       model_class(lowercase__    )
																	lowercase_					:			str										=       self._prepare_for_class(lowercase__				,			lowercase__    )

																	lowercase_					:			Optional[Any]										=       model(lowercase__				,			noise=lowercase__    )

																	lowercase_					:			List[str]										=       copy.deepcopy(self._prepare_for_class(lowercase__				,			lowercase__    )    )
																	lowercase_					:			Union[str, Any]										=       model(**lowercase__				,			noise=lowercase__    )
																	lowercase_					:			List[Any]										=       outputs_dict[0].numpy()
																	lowercase_					:			List[str]										=       outputs_keywords[0].numpy()

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







			def 	SCREAMING_SNAKE_CASE_     (	self				:  int    ):
										# make the mask reproducible
										np.random.seed(2    )

										lowercase_						,						lowercase_					:			Union[str, Any]										=       self.model_tester.prepare_config_and_inputs_for_common()

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

										def prepare_numpy_arrays(lowercase_				:  Dict    ):
																	lowercase_					:			str										=       {}
																	for k, v in inputs_dict.items():
																								if tf.is_tensor(lowercase__    ):
																															lowercase_					:			Union[str, Any]										=       v.numpy()
																								else:
																															lowercase_					:			Any										=       np.array(lowercase__    )

																	return inputs_np_dict

										for model_class in self.all_model_classes:
																	lowercase_					:			Optional[int]										=       model_class(lowercase__    )

																	lowercase_					:			Union[str, Any]										=       self._prepare_for_class(lowercase__				,			lowercase__    )
																	lowercase_					:			List[Any]										=       prepare_numpy_arrays(lowercase__    )

																	lowercase_					:			Tuple										=       model(lowercase__				,			noise=lowercase__    )
																	lowercase_					:			List[str]										=       model(**lowercase__				,			noise=lowercase__    )
																	self.assert_outputs_same(lowercase__				,			lowercase__    )







			def 	SCREAMING_SNAKE_CASE_     (	self				:  Union[str, Any]				,			lowercase_				:  int				,			lowercase_				:  Tuple				,			lowercase_				:  Any    ):
										# make masks reproducible
										np.random.seed(2    )

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

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

										super().check_pt_tf_models(lowercase__				,			lowercase__				,			lowercase__    )







			def 	SCREAMING_SNAKE_CASE_     (	self				:  Any    ):
										# make mask reproducible
										np.random.seed(2    )

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

										lowercase_					:			Dict										=       {
										    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__    )
										}

										lowercase_					:			List[str]										=       int((config.image_size // config.patch_size) ** 2    )
										lowercase_					:			Tuple										=       np.random.uniform(size=(self.model_tester.batch_size, num_patches)    )
										lowercase_					:			List[str]										=       tf.convert_to_tensor(lowercase__    )
										inputs_dict.update({"""noise""": noise}    )

										for main_layer_class in tf_main_layer_classes:
																	lowercase_					:			str										=       main_layer_class(lowercase__    )

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

																	lowercase_					:			Any										=       tf.keras.Model(lowercase__				,			outputs=main_layer(lowercase__    )    )
																	lowercase_					:			Any										=       model(lowercase__    )

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







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

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

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

										for model_class in self.all_model_classes:
																	lowercase_					:			int										=       model_class(lowercase__    )
																	lowercase_					:			str										=       self._prepare_for_class(lowercase__				,			lowercase__    )
																	lowercase_					:			str										=       model(lowercase__				,			noise=lowercase__    )

																	if model_class.__name__ == "TFViTMAEModel":
																								lowercase_					:			Optional[int]										=       outputs.last_hidden_state.numpy()
																								lowercase_					:			Tuple										=       0
																	else:
																								lowercase_					:			Dict										=       outputs.logits.numpy()
																								lowercase_					:			Any										=       0

																	with tempfile.TemporaryDirectory() as tmpdirname:
																								model.save_pretrained(lowercase__				,			saved_model=lowercase__    )
																								lowercase_					:			Any										=       model_class.from_pretrained(lowercase__    )
																								lowercase_					:			Any										=       model(lowercase__				,			noise=lowercase__    )

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

																								lowercase_					:			Optional[Any]										=       np.amax(np.abs(out_a - out_a    )    )
																								self.assertLessEqual(lowercase__				,			1E-5    )







			def 	SCREAMING_SNAKE_CASE_     (	self				:  List[Any]    ):
										# make mask reproducible
										np.random.seed(2    )

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

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

										for model_class in self.all_model_classes:
																	lowercase_					:			str										=       model_class(lowercase__    )
																	lowercase_					:			int										=       self._prepare_for_class(lowercase__				,			lowercase__    )

																	lowercase_					:			Any										=       model(lowercase__				,			noise=lowercase__    )
																	lowercase_					:			Any										=       model.get_config()
																	# make sure that returned config is jsonifiable, which is required by keras
																	json.dumps(lowercase__    )
																	lowercase_					:			List[Any]										=       model_class.from_config(model.get_config()    )
																	# make sure it also accepts a normal config
																	lowercase_					:			Optional[int]										=       model_class.from_config(model.config    )
																	lowercase_					:			Any										=       new_model(lowercase__    )  # Build model
																	new_model.set_weights(model.get_weights()    )
																	lowercase_					:			int										=       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 	SCREAMING_SNAKE_CASE_     (	self				:  Any    ):
										pass







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







			@slow
			def 	SCREAMING_SNAKE_CASE_     (	self				:  Union[str, Any]    ):
										lowercase_					:			List[Any]										=       TFViTMAEModel.from_pretrained("""google/vit-base-patch16-224"""    )
										self.assertIsNotNone(lowercase__    )




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





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







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







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

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

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

										# forward pass
										lowercase_					:			int										=       model(**lowercase__				,			noise=lowercase__    )

										# verify the logits
										lowercase_					:			List[str]										=       tf.convert_to_tensor([1, 196, 768]    )
										self.assertEqual(outputs.logits.shape				,			lowercase__    )

										lowercase_					:			Optional[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    )








'''simple docstring'''






from __future__ import annotations


def 		_A     (    A__      ):






 """simple docstring"""



 __lowercase							  = len(A__      )
 # We need to create solution object to save path.
 __lowercase							  = [[0 for _ in range(A__      )] for _ in range(A__      )]
 __lowercase							  = run_maze(A__     ,				0     ,				0     ,				A__      )
 if solved:
  print('''\n'''.join(str(A__      ) for row in solutions      )      )
 else:
  print('''No solution exists!'''      )
 return solved


def 		_A     (    A__     ,				A__     ,				A__     ,				A__      ):






 """simple docstring"""



 __lowercase							  = len(A__      )
 # Final check point.
 if i == j == (size - 1):
  __lowercase							  = 1
  return True

 __lowercase							  = (not i < 0) and (not j < 0)  # Check lower bounds
 __lowercase							  = (i < size) and (j < size)  # Check upper bounds

 if lower_flag and upper_flag:
  # check for already visited and block points.
  __lowercase							  = (not solutions[i][j]) and (not maze[i][j])
  if block_flag:
   # check visited
   __lowercase							  = 1

   # check for directions
   if (
       run_maze(A__     ,				i + 1     ,				A__     ,				A__      )
       or run_maze(A__     ,				A__     ,				j + 1     ,				A__      )
       or run_maze(A__     ,				i - 1     ,				A__     ,				A__      )
       or run_maze(A__     ,				A__     ,				j - 1     ,				A__      )
   ):
    return True

   __lowercase							  = 0
   return False
 return False


if __name__ == "__main__":
 import doctest

 doctest.testmod()

