

"""simple docstring"""


import inspect
import unittest

import numpy as np

from transformers import BeitConfig
from transformers.testing_utils import require_flax, require_vision, slow
from transformers.utils import cached_property, is_flax_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor


if is_flax_available():
			import jax

			from transformers import FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel

if is_vision_available():
			from PIL import Image

			from transformers import BeitImageProcessor





class     snake_case	(				unittest.TestCase  ):

				def __init__(	self							:				List[Any]     ,  UpperCamelCase__							:				Any     ,  UpperCamelCase__							:				Tuple=1_0_0     ,  UpperCamelCase__							:				int=1_3     ,  UpperCamelCase__							:				Union[str, Any]=3_0     ,  UpperCamelCase__							:				Optional[int]=2     ,  UpperCamelCase__							:				Any=3     ,  UpperCamelCase__							:				Any=True     ,  UpperCamelCase__							:				List[str]=True     ,  UpperCamelCase__							:				str=3_2     ,  UpperCamelCase__							:				List[str]=5     ,  UpperCamelCase__							:				int=4     ,  UpperCamelCase__							:				List[Any]=3_7     ,  UpperCamelCase__							:				int="gelu"     ,  UpperCamelCase__							:				int=0.1     ,  UpperCamelCase__							:				str=0.1     ,  UpperCamelCase__							:				List[str]=1_0     ,  UpperCamelCase__							:				Optional[int]=0.02     ,  UpperCamelCase__							:				Dict=3     ,  )->   List[str]:



						'''simple docstring'''


						__lowerCAmelCase:       Optional[int]          =			parent
						__lowerCAmelCase:       Optional[Any]          =			vocab_size
						__lowerCAmelCase:       str          =			batch_size
						__lowerCAmelCase:       Tuple          =			image_size
						__lowerCAmelCase:       Any          =			patch_size
						__lowerCAmelCase:       Union[str, Any]          =			num_channels
						__lowerCAmelCase:       int          =			is_training
						__lowerCAmelCase:       Optional[Any]          =			use_labels
						__lowerCAmelCase:       List[Any]          =			hidden_size
						__lowerCAmelCase:       Optional[int]          =			num_hidden_layers
						__lowerCAmelCase:       Union[str, Any]          =			num_attention_heads
						__lowerCAmelCase:       Any          =			intermediate_size
						__lowerCAmelCase:       Union[str, Any]          =			hidden_act
						__lowerCAmelCase:       str          =			hidden_dropout_prob
						__lowerCAmelCase:       List[Any]          =			attention_probs_dropout_prob
						__lowerCAmelCase:       Optional[int]          =			type_sequence_label_size
						__lowerCAmelCase:       int          =			initializer_range

						# in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
						__lowerCAmelCase:       Optional[Any]          =			(image_size // patch_size) ** 2
						__lowerCAmelCase:       Dict          =			num_patches + 1

				def 							lowercase_     (	self							:				Optional[Any])->   List[Any]:



						'''simple docstring'''


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

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

						__lowerCAmelCase:       Any          =			BeitConfig(
						    vocab_size=self.vocab_size     ,  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     ,  )

						return config, pixel_values, labels

				def 							lowercase_     (	self							:				int     ,  UpperCamelCase__							:				Optional[Any]     ,  UpperCamelCase__							:				Optional[Any]     ,  UpperCamelCase__							:				List[str])->   Optional[int]:



						'''simple docstring'''


						__lowerCAmelCase:       Tuple          =			FlaxBeitModel(config=UpperCamelCase__)
						__lowerCAmelCase:       List[str]          =			model(UpperCamelCase__)
						self.parent.assertEqual(result.last_hidden_state.shape     ,  (self.batch_size, self.seq_length, self.hidden_size))

				def 							lowercase_     (	self							:				Tuple     ,  UpperCamelCase__							:				Optional[int]     ,  UpperCamelCase__							:				Optional[Any]     ,  UpperCamelCase__							:				Tuple)->   Optional[int]:



						'''simple docstring'''


						__lowerCAmelCase:       List[Any]          =			FlaxBeitForMaskedImageModeling(config=UpperCamelCase__)
						__lowerCAmelCase:       Union[str, Any]          =			model(UpperCamelCase__)
						self.parent.assertEqual(result.logits.shape     ,  (self.batch_size, self.seq_length - 1, self.vocab_size))

				def 							lowercase_     (	self							:				str     ,  UpperCamelCase__							:				int     ,  UpperCamelCase__							:				str     ,  UpperCamelCase__							:				str)->   List[str]:



						'''simple docstring'''


						__lowerCAmelCase:       Optional[Any]          =			self.type_sequence_label_size
						__lowerCAmelCase:       Tuple          =			FlaxBeitForImageClassification(config=UpperCamelCase__)
						__lowerCAmelCase:       int          =			model(UpperCamelCase__)
						self.parent.assertEqual(result.logits.shape     ,  (self.batch_size, self.type_sequence_label_size))

						# test greyscale images
						__lowerCAmelCase:       List[str]          =			1
						__lowerCAmelCase:       List[str]          =			FlaxBeitForImageClassification(UpperCamelCase__)

						__lowerCAmelCase:       Optional[Any]          =			floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
						__lowerCAmelCase:       Union[str, Any]          =			model(UpperCamelCase__)




				def 							lowercase_     (	self							:				Any)->   Union[str, Any]:



						'''simple docstring'''


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





@require_flax
class     snake_case	(				__snake_case,							unittest.TestCase  ):
				SCREAMING_SNAKE_CASE_   :      List[str]         =  (
				    (FlaxBeitModel, FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling) if is_flax_available() else ()
				)

				def 							lowercase_     (	self							:				Union[str, Any])->   None:



						'''simple docstring'''


						__lowerCAmelCase:       int          =			FlaxBeitModelTester(self)
						__lowerCAmelCase:       Dict          =			ConfigTester(self     ,  config_class=UpperCamelCase__     ,  has_text_modality=UpperCamelCase__     ,  hidden_size=3_7)

				def 							lowercase_     (	self							:				Tuple)->   List[Any]:



						'''simple docstring'''


						self.config_tester.run_common_tests()

				def 							lowercase_     (	self							:				List[str])->   str:



						'''simple docstring'''


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

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

								__lowerCAmelCase:       Union[str, Any]          =			["pixel_values"]
								self.assertListEqual(arg_names[:1]     ,  UpperCamelCase__)

				def 							lowercase_     (	self							:				Dict)->   Any:



						'''simple docstring'''


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

						for model_class in self.all_model_classes:
								with self.subTest(model_class.__name__):
										__lowerCAmelCase:       Union[str, Any]          =			self._prepare_for_class(UpperCamelCase__     ,  UpperCamelCase__)
										__lowerCAmelCase:       Dict          =			model_class(UpperCamelCase__)

										@jax.jit
										def model_jitted(UpperCamelCase__							:				int     ,  **UpperCamelCase__							:				str):
												return model(pixel_values=UpperCamelCase__     ,  **UpperCamelCase__)

										with self.subTest("JIT Enabled"):
												__lowerCAmelCase:       int          =			model_jitted(**UpperCamelCase__).to_tuple()

										with self.subTest("JIT Disabled"):
												with jax.disable_jit():
														__lowerCAmelCase:       Optional[Any]          =			model_jitted(**UpperCamelCase__).to_tuple()

										self.assertEqual(len(UpperCamelCase__)     ,  len(UpperCamelCase__))
										for jitted_output, output in zip(UpperCamelCase__     ,  UpperCamelCase__):
												self.assertEqual(jitted_output.shape     ,  output.shape)

				def 							lowercase_     (	self							:				List[Any])->   Union[str, Any]:



						'''simple docstring'''


						__lowerCAmelCase:       Any          =			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*UpperCamelCase__)

				def 							lowercase_     (	self							:				str)->   List[str]:



						'''simple docstring'''


						__lowerCAmelCase:       Optional[Any]          =			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_masked_lm(*UpperCamelCase__)

				def 							lowercase_     (	self							:				Dict)->   Dict:



						'''simple docstring'''


						__lowerCAmelCase:       int          =			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__)




				@slow
				def 							lowercase_     (	self							:				int)->   List[Any]:



						'''simple docstring'''


						for model_class_name in self.all_model_classes:
								__lowerCAmelCase:       List[str]          =			model_class_name.from_pretrained("microsoft/beit-base-patch16-224")
								__lowerCAmelCase:       List[str]          =			model(np.ones((1, 3, 2_2_4, 2_2_4)))
								self.assertIsNotNone(UpperCamelCase__)






def     a__    (    )	->	Optional[Any]:
		__lowerCAmelCase:       Tuple          =			Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
		return image





@require_vision
@require_flax
class     snake_case	(				unittest.TestCase  ):

				@cached_property
				def 							lowercase_     (	self							:				Optional[int])->   Optional[int]:



						'''simple docstring'''


						return BeitImageProcessor.from_pretrained("microsoft/beit-base-patch16-224") if is_vision_available() else None

				@slow
				def 							lowercase_     (	self							:				Any)->   str:



						'''simple docstring'''


						__lowerCAmelCase:       Optional[int]          =			FlaxBeitForMaskedImageModeling.from_pretrained("microsoft/beit-base-patch16-224-pt22k")

						__lowerCAmelCase:       List[Any]          =			self.default_image_processor
						__lowerCAmelCase:       Union[str, Any]          =			prepare_img()
						__lowerCAmelCase:       Tuple          =			image_processor(images=UpperCamelCase__     ,  return_tensors="np").pixel_values

						# prepare bool_masked_pos
						__lowerCAmelCase:       Dict          =			np.ones((1, 1_9_6)     ,  dtype=UpperCamelCase__)

						# forward pass
						__lowerCAmelCase:       Any          =			model(pixel_values=UpperCamelCase__     ,  bool_masked_pos=UpperCamelCase__)
						__lowerCAmelCase:       Dict          =			outputs.logits

						# verify the logits
						__lowerCAmelCase:       Any          =			(1, 1_9_6, 8_1_9_2)
						self.assertEqual(logits.shape     ,  UpperCamelCase__)

						__lowerCAmelCase:       List[Any]          =			np.array(
						    [[-3.2437, 0.5072, -13.9174], [-3.2456, 0.4948, -13.9401], [-3.2033, 0.5121, -13.8550]])

						self.assertTrue(np.allclose(logits[bool_masked_pos][:3, :3]     ,  UpperCamelCase__     ,  atol=1e-2))

				@slow
				def 							lowercase_     (	self							:				Tuple)->   Dict:



						'''simple docstring'''


						__lowerCAmelCase:       Optional[int]          =			FlaxBeitForImageClassification.from_pretrained("microsoft/beit-base-patch16-224")

						__lowerCAmelCase:       Optional[int]          =			self.default_image_processor
						__lowerCAmelCase:       Dict          =			prepare_img()
						__lowerCAmelCase:       Tuple          =			image_processor(images=UpperCamelCase__     ,  return_tensors="np")

						# forward pass
						__lowerCAmelCase:       int          =			model(**UpperCamelCase__)
						__lowerCAmelCase:       Dict          =			outputs.logits

						# verify the logits
						__lowerCAmelCase:       Optional[int]          =			(1, 1_0_0_0)
						self.assertEqual(logits.shape     ,  UpperCamelCase__)

						__lowerCAmelCase:       int          =			np.array([-1.2385, -1.0987, -1.0108])

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

						__lowerCAmelCase:       int          =			2_8_1
						self.assertEqual(logits.argmax(-1).item()     ,  UpperCamelCase__)




				@slow
				def 							lowercase_     (	self							:				Union[str, Any])->   Optional[int]:



						'''simple docstring'''


						__lowerCAmelCase:       Union[str, Any]          =			FlaxBeitForImageClassification.from_pretrained("microsoft/beit-large-patch16-224-pt22k-ft22k")

						__lowerCAmelCase:       Union[str, Any]          =			self.default_image_processor
						__lowerCAmelCase:       Any          =			prepare_img()
						__lowerCAmelCase:       str          =			image_processor(images=UpperCamelCase__     ,  return_tensors="np")

						# forward pass
						__lowerCAmelCase:       Union[str, Any]          =			model(**UpperCamelCase__)
						__lowerCAmelCase:       Dict          =			outputs.logits

						# verify the logits
						__lowerCAmelCase:       Tuple          =			(1, 2_1_8_4_1)
						self.assertEqual(logits.shape     ,  UpperCamelCase__)

						__lowerCAmelCase:       str          =			np.array([1.6881, -0.2787, 0.5901])

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

						__lowerCAmelCase:       str          =			2_3_9_6
						self.assertEqual(logits.argmax(-1).item()     ,  UpperCamelCase__)





"""simple docstring"""


from __future__ import annotations






def     a__    (    __SCREAMING_SNAKE_CASE )	->	bool:
		__lowerCAmelCase:       Tuple          =			str(__SCREAMING_SNAKE_CASE )
		return len(__SCREAMING_SNAKE_CASE ) == 9 and set(__SCREAMING_SNAKE_CASE ) == set("123456789" )






def     a__    (    )	->	int | None:
		for base_num in range(9_9_9_9					, 4_9_9_9					, -1 ):
				__lowerCAmelCase:       Tuple          =			1_0_0_0_0_2 * base_num
				if is_9_pandigital(__SCREAMING_SNAKE_CASE ):
						return candidate

		for base_num in range(3_3_3					, 9_9					, -1 ):
				__lowerCAmelCase:       int          =			1_0_0_2_0_0_3 * base_num
				if is_9_pandigital(__SCREAMING_SNAKE_CASE ):
						return candidate

		return None


if __name__ == "__main__":
			print(F'''{solution() = }''')


