



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     _A       (	unittest.TestCase    ):



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


           '''simple docstring'''

           __a						       =				parent
           __a						       =				vocab_size
           __a						       =				batch_size
           __a						       =				image_size
           __a						       =				patch_size
           __a						       =				num_channels
           __a						       =				is_training
           __a						       =				use_labels
           __a						       =				hidden_size
           __a						       =				num_hidden_layers
           __a						       =				num_attention_heads
           __a						       =				intermediate_size
           __a						       =				hidden_act
           __a						       =				hidden_dropout_prob
           __a						       =				attention_probs_dropout_prob
           __a						       =				type_sequence_label_size
           __a						       =				initializer_range

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



       def 		_lowerCamelCase			(		self							:     Any):


           '''simple docstring'''

           __a						       =				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

           __a						       =				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=__SCREAMING_SNAKE_CASE     ,		initializer_range=self.initializer_range     ,		)

           return config, pixel_values, labels



       def 		_lowerCamelCase			(		self							:     Tuple     ,		__SCREAMING_SNAKE_CASE							:     str     ,		__SCREAMING_SNAKE_CASE							:     List[Any]     ,		__SCREAMING_SNAKE_CASE							:     Optional[Any]):


           '''simple docstring'''

           __a						       =				FlaxBeitModel(config=__SCREAMING_SNAKE_CASE)
           __a						       =				model(__SCREAMING_SNAKE_CASE)
           self.parent.assertEqual(result.last_hidden_state.shape     ,		(self.batch_size, self.seq_length, self.hidden_size))



       def 		_lowerCamelCase			(		self							:     Tuple     ,		__SCREAMING_SNAKE_CASE							:     str     ,		__SCREAMING_SNAKE_CASE							:     Optional[int]     ,		__SCREAMING_SNAKE_CASE							:     Tuple):


           '''simple docstring'''

           __a						       =				FlaxBeitForMaskedImageModeling(config=__SCREAMING_SNAKE_CASE)
           __a						       =				model(__SCREAMING_SNAKE_CASE)
           self.parent.assertEqual(result.logits.shape     ,		(self.batch_size, self.seq_length - 1, self.vocab_size))



       def 		_lowerCamelCase			(		self							:     List[str]     ,		__SCREAMING_SNAKE_CASE							:     str     ,		__SCREAMING_SNAKE_CASE							:     Dict     ,		__SCREAMING_SNAKE_CASE							:     Optional[int]):


           '''simple docstring'''

           __a						       =				self.type_sequence_label_size
           __a						       =				FlaxBeitForImageClassification(config=__SCREAMING_SNAKE_CASE)
           __a						       =				model(__SCREAMING_SNAKE_CASE)
           self.parent.assertEqual(result.logits.shape     ,		(self.batch_size, self.type_sequence_label_size))

           # test greyscale images
           __a						       =				1
           __a						       =				FlaxBeitForImageClassification(__SCREAMING_SNAKE_CASE)

           __a						       =				floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
           __a						       =				model(__SCREAMING_SNAKE_CASE)





       def 		_lowerCamelCase			(		self							:     Dict):


           '''simple docstring'''

           __a						       =				self.prepare_config_and_inputs()
           (
               (
               __a
           )       ,   (
               __a
           )       ,   (
               __a
           )       ,   
           )						       =				config_and_inputs
           __a						       =				{'''pixel_values''': pixel_values}
           return config, inputs_dict


@require_flax
class     _A       (	__UpperCAmelCase      ,unittest.TestCase    ):
       UpperCamelCase__  :    Dict											=						(
           (FlaxBeitModel, FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling) if is_flax_available() else ()
       )



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


           '''simple docstring'''

           __a						       =				FlaxBeitModelTester(self)
           __a						       =				ConfigTester(self     ,		config_class=__SCREAMING_SNAKE_CASE     ,		has_text_modality=__SCREAMING_SNAKE_CASE     ,		hidden_size=37)



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


           '''simple docstring'''

           self.config_tester.run_common_tests()



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


           '''simple docstring'''

           __a       ,   __a						       =				self.model_tester.prepare_config_and_inputs_for_common()

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

               __a						       =				['''pixel_values''']
               self.assertListEqual(arg_names[:1]     ,		__SCREAMING_SNAKE_CASE)



       def 		_lowerCamelCase			(		self							:     str):


           '''simple docstring'''

           __a       ,   __a						       =				self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
               with self.subTest(model_class.__name__):
                   __a						       =				self._prepare_for_class(__SCREAMING_SNAKE_CASE     ,		__SCREAMING_SNAKE_CASE)
                   __a						       =				model_class(__SCREAMING_SNAKE_CASE)

                   @jax.jit
                   def model_jitted(__SCREAMING_SNAKE_CASE							:     int     ,		**__SCREAMING_SNAKE_CASE							:     Optional[int]):
                       return model(pixel_values=__SCREAMING_SNAKE_CASE     ,		**__SCREAMING_SNAKE_CASE)

                   with self.subTest('''JIT Enabled'''):
                       __a						       =				model_jitted(**__SCREAMING_SNAKE_CASE).to_tuple()

                   with self.subTest('''JIT Disabled'''):
                       with jax.disable_jit():
                           __a						       =				model_jitted(**__SCREAMING_SNAKE_CASE).to_tuple()

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



       def 		_lowerCamelCase			(		self							:     str):


           '''simple docstring'''

           __a						       =				self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE)



       def 		_lowerCamelCase			(		self							:     Dict):


           '''simple docstring'''

           __a						       =				self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_masked_lm(*__SCREAMING_SNAKE_CASE)



       def 		_lowerCamelCase			(		self							:     Tuple):


           '''simple docstring'''

           __a						       =				self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*__SCREAMING_SNAKE_CASE)





       @slow
       def 		_lowerCamelCase			(		self							:     Any):


           '''simple docstring'''

           for model_class_name in self.all_model_classes:
               __a						       =				model_class_name.from_pretrained('''microsoft/beit-base-patch16-224''')
               __a						       =				model(np.ones((1, 3, 224, 224)))
               self.assertIsNotNone(__SCREAMING_SNAKE_CASE)





def      __snake_case	(			):
    __a						       =				Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''				)
    return image

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



       @cached_property
       def 		_lowerCamelCase			(		self							:     Tuple):


           '''simple docstring'''

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



       @slow
       def 		_lowerCamelCase			(		self							:     Tuple):


           '''simple docstring'''

           __a						       =				FlaxBeitForMaskedImageModeling.from_pretrained('''microsoft/beit-base-patch16-224-pt22k''')

           __a						       =				self.default_image_processor
           __a						       =				prepare_img()
           __a						       =				image_processor(images=__SCREAMING_SNAKE_CASE     ,		return_tensors='''np''').pixel_values

           # prepare bool_masked_pos
           __a						       =				np.ones((1, 196)     ,		dtype=__SCREAMING_SNAKE_CASE)

           # forward pass
           __a						       =				model(pixel_values=__SCREAMING_SNAKE_CASE     ,		bool_masked_pos=__SCREAMING_SNAKE_CASE)
           __a						       =				outputs.logits

           # verify the logits
           __a						       =				(1, 196, 8_192)
           self.assertEqual(logits.shape     ,		__SCREAMING_SNAKE_CASE)

           __a						       =				np.array(
               [[-3.24_37, 0.50_72, -13.91_74], [-3.24_56, 0.49_48, -13.94_01], [-3.20_33, 0.51_21, -13.85_50]])

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



       @slow
       def 		_lowerCamelCase			(		self							:     Optional[Any]):


           '''simple docstring'''

           __a						       =				FlaxBeitForImageClassification.from_pretrained('''microsoft/beit-base-patch16-224''')

           __a						       =				self.default_image_processor
           __a						       =				prepare_img()
           __a						       =				image_processor(images=__SCREAMING_SNAKE_CASE     ,		return_tensors='''np''')

           # forward pass
           __a						       =				model(**__SCREAMING_SNAKE_CASE)
           __a						       =				outputs.logits

           # verify the logits
           __a						       =				(1, 1_000)
           self.assertEqual(logits.shape     ,		__SCREAMING_SNAKE_CASE)

           __a						       =				np.array([-1.23_85, -1.09_87, -1.01_08])

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

           __a						       =				281
           self.assertEqual(logits.argmax(-1).item()     ,		__SCREAMING_SNAKE_CASE)





       @slow
       def 		_lowerCamelCase			(		self							:     Tuple):


           '''simple docstring'''

           __a						       =				FlaxBeitForImageClassification.from_pretrained('''microsoft/beit-large-patch16-224-pt22k-ft22k''')

           __a						       =				self.default_image_processor
           __a						       =				prepare_img()
           __a						       =				image_processor(images=__SCREAMING_SNAKE_CASE     ,		return_tensors='''np''')

           # forward pass
           __a						       =				model(**__SCREAMING_SNAKE_CASE)
           __a						       =				outputs.logits

           # verify the logits
           __a						       =				(1, 21_841)
           self.assertEqual(logits.shape     ,		__SCREAMING_SNAKE_CASE)

           __a						       =				np.array([1.68_81, -0.27_87, 0.59_01])

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

           __a						       =				2_396
           self.assertEqual(logits.argmax(-1).item()     ,		__SCREAMING_SNAKE_CASE)










import unittest

from diffusers.pipelines.pipeline_utils import is_safetensors_compatible

class     _A       (	unittest.TestCase    ):



       def 		_lowerCamelCase			(		self							:     List[Any]):


           '''simple docstring'''

           __a						       =				[
               '''safety_checker/pytorch_model.bin''',
               '''safety_checker/model.safetensors''',
               '''vae/diffusion_pytorch_model.bin''',
               '''vae/diffusion_pytorch_model.safetensors''',
               '''text_encoder/pytorch_model.bin''',
               '''text_encoder/model.safetensors''',
               '''unet/diffusion_pytorch_model.bin''',
               '''unet/diffusion_pytorch_model.safetensors''',
           ]
           self.assertTrue(is_safetensors_compatible(__SCREAMING_SNAKE_CASE))



       def 		_lowerCamelCase			(		self							:     Optional[Any]):


           '''simple docstring'''

           __a						       =				[
               '''unet/diffusion_pytorch_model.bin''',
               '''unet/diffusion_pytorch_model.safetensors''',
           ]
           self.assertTrue(is_safetensors_compatible(__SCREAMING_SNAKE_CASE))



       def 		_lowerCamelCase			(		self							:     Optional[Any]):


           '''simple docstring'''

           __a						       =				[
               '''safety_checker/pytorch_model.bin''',
               '''safety_checker/model.safetensors''',
               '''vae/diffusion_pytorch_model.bin''',
               '''vae/diffusion_pytorch_model.safetensors''',
               '''text_encoder/pytorch_model.bin''',
               '''text_encoder/model.safetensors''',
               '''unet/diffusion_pytorch_model.bin''',
               # Removed: 'unet/diffusion_pytorch_model.safetensors',
           ]
           self.assertFalse(is_safetensors_compatible(__SCREAMING_SNAKE_CASE))



       def 		_lowerCamelCase			(		self							:     Dict):


           '''simple docstring'''

           __a						       =				[
               '''text_encoder/pytorch_model.bin''',
               '''text_encoder/model.safetensors''',
           ]
           self.assertTrue(is_safetensors_compatible(__SCREAMING_SNAKE_CASE))



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


           '''simple docstring'''

           __a						       =				[
               '''safety_checker/pytorch_model.bin''',
               '''safety_checker/model.safetensors''',
               '''vae/diffusion_pytorch_model.bin''',
               '''vae/diffusion_pytorch_model.safetensors''',
               '''text_encoder/pytorch_model.bin''',
               # Removed: 'text_encoder/model.safetensors',
               '''unet/diffusion_pytorch_model.bin''',
               '''unet/diffusion_pytorch_model.safetensors''',
           ]
           self.assertFalse(is_safetensors_compatible(__SCREAMING_SNAKE_CASE))



       def 		_lowerCamelCase			(		self							:     Tuple):


           '''simple docstring'''

           __a						       =				[
               '''safety_checker/pytorch_model.fp16.bin''',
               '''safety_checker/model.fp16.safetensors''',
               '''vae/diffusion_pytorch_model.fp16.bin''',
               '''vae/diffusion_pytorch_model.fp16.safetensors''',
               '''text_encoder/pytorch_model.fp16.bin''',
               '''text_encoder/model.fp16.safetensors''',
               '''unet/diffusion_pytorch_model.fp16.bin''',
               '''unet/diffusion_pytorch_model.fp16.safetensors''',
           ]
           __a						       =				'''fp16'''
           self.assertTrue(is_safetensors_compatible(__SCREAMING_SNAKE_CASE     ,		variant=__SCREAMING_SNAKE_CASE))



       def 		_lowerCamelCase			(		self							:     Dict):


           '''simple docstring'''

           __a						       =				[
               '''unet/diffusion_pytorch_model.fp16.bin''',
               '''unet/diffusion_pytorch_model.fp16.safetensors''',
           ]
           __a						       =				'''fp16'''
           self.assertTrue(is_safetensors_compatible(__SCREAMING_SNAKE_CASE     ,		variant=__SCREAMING_SNAKE_CASE))



       def 		_lowerCamelCase			(		self							:     Optional[Any]):


           '''simple docstring'''

           __a						       =				[
               '''unet/diffusion_pytorch_model.bin''',
               '''unet/diffusion_pytorch_model.safetensors''',
           ]
           __a						       =				'''fp16'''
           self.assertTrue(is_safetensors_compatible(__SCREAMING_SNAKE_CASE     ,		variant=__SCREAMING_SNAKE_CASE))



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


           '''simple docstring'''

           __a						       =				[
               '''safety_checker/pytorch_model.fp16.bin''',
               '''safety_checker/model.fp16.safetensors''',
               '''vae/diffusion_pytorch_model.fp16.bin''',
               '''vae/diffusion_pytorch_model.fp16.safetensors''',
               '''text_encoder/pytorch_model.fp16.bin''',
               '''text_encoder/model.fp16.safetensors''',
               '''unet/diffusion_pytorch_model.fp16.bin''',
               # Removed: 'unet/diffusion_pytorch_model.fp16.safetensors',
           ]
           __a						       =				'''fp16'''
           self.assertFalse(is_safetensors_compatible(__SCREAMING_SNAKE_CASE     ,		variant=__SCREAMING_SNAKE_CASE))



       def 		_lowerCamelCase			(		self							:     Dict):


           '''simple docstring'''

           __a						       =				[
               '''text_encoder/pytorch_model.fp16.bin''',
               '''text_encoder/model.fp16.safetensors''',
           ]
           __a						       =				'''fp16'''
           self.assertTrue(is_safetensors_compatible(__SCREAMING_SNAKE_CASE     ,		variant=__SCREAMING_SNAKE_CASE))



       def 		_lowerCamelCase			(		self							:     List[str]):


           '''simple docstring'''

           __a						       =				[
               '''text_encoder/pytorch_model.bin''',
               '''text_encoder/model.safetensors''',
           ]
           __a						       =				'''fp16'''
           self.assertTrue(is_safetensors_compatible(__SCREAMING_SNAKE_CASE     ,		variant=__SCREAMING_SNAKE_CASE))





       def 		_lowerCamelCase			(		self							:     List[str]):


           '''simple docstring'''

           __a						       =				[
               '''safety_checker/pytorch_model.fp16.bin''',
               '''safety_checker/model.fp16.safetensors''',
               '''vae/diffusion_pytorch_model.fp16.bin''',
               '''vae/diffusion_pytorch_model.fp16.safetensors''',
               '''text_encoder/pytorch_model.fp16.bin''',
               # 'text_encoder/model.fp16.safetensors',
               '''unet/diffusion_pytorch_model.fp16.bin''',
               '''unet/diffusion_pytorch_model.fp16.safetensors''',
           ]
           __a						       =				'''fp16'''
           self.assertFalse(is_safetensors_compatible(__SCREAMING_SNAKE_CASE     ,		variant=__SCREAMING_SNAKE_CASE))





