


import inspect
import unittest

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

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


if is_flax_available():
    import jax
    import jax.numpy as jnp

    from transformers.models.resnet.modeling_flax_resnet import FlaxResNetForImageClassification, FlaxResNetModel

if is_vision_available():
    from PIL import Image

    from transformers import AutoImageProcessor







class 					lowerCAmelCase__	(    unittest.TestCase):




     '''simple docstring'''


     def __init__(						self			,						__lowerCamelCase			,						__lowerCamelCase=3			,						__lowerCamelCase=3_2			,						__lowerCamelCase=3			,						__lowerCamelCase=1_0			,						__lowerCamelCase=[1_0, 2_0, 3_0, 4_0]			,						__lowerCamelCase=[1, 1, 2, 1]			,						__lowerCamelCase=True			,						__lowerCamelCase=True			,						__lowerCamelCase="relu"			,						__lowerCamelCase=3			,						__lowerCamelCase=None			,						)      ->    Dict:
            _A				:	List[Any]       =			parent
            _A				:	Union[str, Any]       =			batch_size
            _A				:	Any       =			image_size
            _A				:	Dict       =			num_channels
            _A				:	Union[str, Any]       =			embeddings_size
            _A				:	Tuple       =			hidden_sizes
            _A				:	Any       =			depths
            _A				:	List[Any]       =			is_training
            _A				:	List[str]       =			use_labels
            _A				:	str       =			hidden_act
            _A				:	Dict       =			num_labels
            _A				:	Dict       =			scope
            _A				:	Dict       =			len(__lowerCamelCase)


     def 			_lowerCamelCase			(						self)      ->    int:
            _A				:	Dict       =			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

            _A				:	str       =			self.get_config()

            return config, pixel_values


     def 			_lowerCamelCase			(						self)      ->    Union[str, Any]:
            return ResNetConfig(
                num_channels=self.num_channels			,						embeddings_size=self.embeddings_size			,						hidden_sizes=self.hidden_sizes			,						depths=self.depths			,						hidden_act=self.hidden_act			,						num_labels=self.num_labels			,						image_size=self.image_size			,						)


     def 			_lowerCamelCase			(						self			,						__lowerCamelCase			,						__lowerCamelCase)      ->    Optional[Any]:
            _A				:	Optional[Any]       =			FlaxResNetModel(config=__lowerCamelCase)
            _A				:	Optional[int]       =			model(__lowerCamelCase)

            # Output shape (b, c, h, w)
            self.parent.assertEqual(
                result.last_hidden_state.shape			,						(self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2)			,						)


     def 			_lowerCamelCase			(						self			,						__lowerCamelCase			,						__lowerCamelCase)      ->    Optional[Any]:
            _A				:	Tuple       =			self.num_labels
            _A				:	Any       =			FlaxResNetForImageClassification(config=__lowerCamelCase)
            _A				:	List[str]       =			model(__lowerCamelCase)
            self.parent.assertEqual(result.logits.shape			,						(self.batch_size, self.num_labels))


     def 			_lowerCamelCase			(						self)      ->    Tuple:
            _A				:	Union[str, Any]       =			self.prepare_config_and_inputs()
            _A				:	int       =			config_and_inputs
            _A				:	Optional[Any]       =			{"pixel_values": pixel_values}
            return config, inputs_dict







@require_flax
class 					lowerCAmelCase__	(    a					,   unittest.TestCase):




     '''simple docstring'''
     __SCREAMING_SNAKE_CASE        =			(FlaxResNetModel, FlaxResNetForImageClassification) if is_flax_available() else ()

     __SCREAMING_SNAKE_CASE        =			False
     __SCREAMING_SNAKE_CASE        =			False
     __SCREAMING_SNAKE_CASE        =			False


     def 			_lowerCamelCase			(						self)      ->    None:
            _A				:	Tuple       =			FlaxResNetModelTester(self)
            _A				:	str       =			ConfigTester(self			,						config_class=__lowerCamelCase			,						has_text_modality=__lowerCamelCase)


     def 			_lowerCamelCase			(						self)      ->    int:
            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)      ->    Dict:
            return


     def 			_lowerCamelCase			(						self)      ->    int:
            _A				:	int       =			self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*__lowerCamelCase)


     def 			_lowerCamelCase			(						self)      ->    str:
            _A				:	Optional[Any]       =			self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase)


     @unittest.skip(reason="ResNet does not use inputs_embeds")
     def 			_lowerCamelCase			(						self)      ->    Union[str, Any]:
            pass


     @unittest.skip(reason="ResNet does not support input and output embeddings")
     def 			_lowerCamelCase			(						self)      ->    Union[str, Any]:
            pass


     def 			_lowerCamelCase			(						self)      ->    Optional[int]:
            _A				:	int       =			self.model_tester.prepare_config_and_inputs_for_common()

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

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


     def 			_lowerCamelCase			(						self)      ->    Any:
            def check_hidden_states_output(__lowerCamelCase			,						__lowerCamelCase			,						__lowerCamelCase):
                   _A				:	Optional[int]       =			model_class(__lowerCamelCase)

                   _A				:	Any       =			model(**self._prepare_for_class(__lowerCamelCase			,						__lowerCamelCase))

                   _A				:	Dict       =			outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                   _A				:	List[str]       =			self.model_tester.num_stages
                   self.assertEqual(len(__lowerCamelCase)			,						expected_num_stages + 1)


     @unittest.skip(reason="ResNet does not use feedforward chunking")
     def 			_lowerCamelCase			(						self)      ->    Dict:
            pass


     def 			_lowerCamelCase			(						self)      ->    Dict:
            _A				:	Dict       =			self.model_tester.prepare_config_and_inputs_for_common()

            for model_class in self.all_model_classes:
                   with self.subTest(model_class.__name__):
                          _A				:	Optional[int]       =			self._prepare_for_class(__lowerCamelCase			,						__lowerCamelCase)
                          _A				:	Tuple       =			model_class(__lowerCamelCase)

                          @jax.jit
                          def model_jitted(__lowerCamelCase			,						**__lowerCamelCase):
                                 return model(pixel_values=__lowerCamelCase			,						**__lowerCamelCase)

                          with self.subTest("JIT Enabled"):
                                 _A				:	Dict       =			model_jitted(**__lowerCamelCase).to_tuple()

                          with self.subTest("JIT Disabled"):
                                 with jax.disable_jit():
                                        _A				:	str       =			model_jitted(**__lowerCamelCase).to_tuple()

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




def 							_UpperCAmelCase    ():
       _A				:	Tuple       =			Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"						)
       return image







@require_flax
class 					lowerCAmelCase__	(    unittest.TestCase):




     '''simple docstring'''


     @cached_property
     def 			_lowerCamelCase			(						self)      ->    Optional[Any]:
            return AutoImageProcessor.from_pretrained("microsoft/resnet-50") if is_vision_available() else None


     @slow
     def 			_lowerCamelCase			(						self)      ->    str:
            _A				:	Any       =			FlaxResNetForImageClassification.from_pretrained("microsoft/resnet-50")

            _A				:	List[Any]       =			self.default_image_processor
            _A				:	Union[str, Any]       =			prepare_img()
            _A				:	Union[str, Any]       =			image_processor(images=__lowerCamelCase			,						return_tensors="np")

            _A				:	Optional[int]       =			model(**__lowerCamelCase)

            # verify the logits
            _A				:	List[str]       =			(1, 1_0_0_0)
            self.assertEqual(outputs.logits.shape			,						__lowerCamelCase)

            _A				:	Tuple       =			jnp.array([-1_1.1_0_6_9, -9.7_8_7_7, -8.3_7_7_7])

            self.assertTrue(jnp.allclose(outputs.logits[0, :3]			,						__lowerCamelCase			,						atol=1e-4))




import unittest

import numpy as np

from transformers import BlipTextConfig
from transformers.testing_utils import require_torch, slow, torch_device
from transformers.utils import is_torch_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask


if is_torch_available():
    import torch

    from transformers import BlipTextModel
    from transformers.models.blip.modeling_blip import BLIP_PRETRAINED_MODEL_ARCHIVE_LIST







class 					lowerCAmelCase__	:




     '''simple docstring'''


     def __init__(						self			,						__lowerCamelCase			,						__lowerCamelCase=1_2			,						__lowerCamelCase=7			,						__lowerCamelCase=True			,						__lowerCamelCase=True			,						__lowerCamelCase=True			,						__lowerCamelCase=9_9			,						__lowerCamelCase=3_2			,						__lowerCamelCase=3_2			,						__lowerCamelCase=5			,						__lowerCamelCase=4			,						__lowerCamelCase=3_7			,						__lowerCamelCase=0.1			,						__lowerCamelCase=0.1			,						__lowerCamelCase=5_1_2			,						__lowerCamelCase=0.0_2			,						__lowerCamelCase=0			,						__lowerCamelCase=None			,						)      ->    str:
            _A				:	Optional[int]       =			parent
            _A				:	Optional[int]       =			batch_size
            _A				:	Optional[int]       =			seq_length
            _A				:	Dict       =			is_training
            _A				:	Union[str, Any]       =			use_input_mask
            _A				:	Optional[int]       =			use_labels
            _A				:	Any       =			vocab_size
            _A				:	Dict       =			hidden_size
            _A				:	Optional[Any]       =			projection_dim
            _A				:	Union[str, Any]       =			num_hidden_layers
            _A				:	Tuple       =			num_attention_heads
            _A				:	List[str]       =			intermediate_size
            _A				:	Any       =			dropout
            _A				:	List[str]       =			attention_dropout
            _A				:	str       =			max_position_embeddings
            _A				:	List[Any]       =			initializer_range
            _A				:	int       =			scope
            _A				:	List[str]       =			bos_token_id


     def 			_lowerCamelCase			(						self)      ->    List[str]:
            _A				:	Tuple       =			ids_tensor([self.batch_size, self.seq_length]			,						self.vocab_size)

            _A				:	str       =			None
            if self.use_input_mask:
                   _A				:	Union[str, Any]       =			random_attention_mask([self.batch_size, self.seq_length])

            if input_mask is not None:
                   _A   ,      _A				:	int       =			input_mask.shape
                   _A				:	Optional[Any]       =			np.random.randint(1			,						seq_length - 1			,						size=(batch_size,))
                   for batch_idx, start_index in enumerate(__lowerCamelCase):
                          _A				:	Tuple       =			1
                          _A				:	List[str]       =			0

            _A				:	str       =			self.get_config()

            return config, input_ids, input_mask


     def 			_lowerCamelCase			(						self)      ->    Optional[int]:
            return BlipTextConfig(
                vocab_size=self.vocab_size			,						hidden_size=self.hidden_size			,						projection_dim=self.projection_dim			,						num_hidden_layers=self.num_hidden_layers			,						num_attention_heads=self.num_attention_heads			,						intermediate_size=self.intermediate_size			,						dropout=self.dropout			,						attention_dropout=self.attention_dropout			,						max_position_embeddings=self.max_position_embeddings			,						initializer_range=self.initializer_range			,						bos_token_id=self.bos_token_id			,						)


     def 			_lowerCamelCase			(						self			,						__lowerCamelCase			,						__lowerCamelCase			,						__lowerCamelCase)      ->    List[str]:
            _A				:	int       =			BlipTextModel(config=__lowerCamelCase)
            model.to(__lowerCamelCase)
            model.eval()
            with torch.no_grad():
                   _A				:	int       =			model(__lowerCamelCase			,						attention_mask=__lowerCamelCase)
                   _A				:	List[str]       =			model(__lowerCamelCase)
            self.parent.assertEqual(result.last_hidden_state.shape			,						(self.batch_size, self.seq_length, self.hidden_size))
            self.parent.assertEqual(result.pooler_output.shape			,						(self.batch_size, self.hidden_size))


     def 			_lowerCamelCase			(						self)      ->    Any:
            _A				:	Dict       =			self.prepare_config_and_inputs()
            _A   ,      _A   ,      _A				:	str       =			config_and_inputs
            _A				:	List[str]       =			{"input_ids": input_ids, "attention_mask": input_mask}
            return config, inputs_dict







@require_torch
class 					lowerCAmelCase__	(    a					,   unittest.TestCase):




     '''simple docstring'''
     __SCREAMING_SNAKE_CASE        =			(BlipTextModel,) if is_torch_available() else ()
     __SCREAMING_SNAKE_CASE        =			False
     __SCREAMING_SNAKE_CASE        =			False
     __SCREAMING_SNAKE_CASE        =			False


     def 			_lowerCamelCase			(						self)      ->    Dict:
            _A				:	Optional[Any]       =			BlipTextModelTester(self)
            _A				:	List[str]       =			ConfigTester(self			,						config_class=__lowerCamelCase			,						hidden_size=3_7)


     def 			_lowerCamelCase			(						self)      ->    List[Any]:
            self.config_tester.run_common_tests()


     def 			_lowerCamelCase			(						self)      ->    Union[str, Any]:
            _A				:	Optional[Any]       =			self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*__lowerCamelCase)


     def 			_lowerCamelCase			(						self)      ->    Optional[Any]:
            pass


     def 			_lowerCamelCase			(						self)      ->    Dict:
            pass


     @unittest.skip(reason="Blip does not use inputs_embeds")
     def 			_lowerCamelCase			(						self)      ->    str:
            pass


     @unittest.skip(reason="BlipTextModel has no base class and is not available in MODEL_MAPPING")
     def 			_lowerCamelCase			(						self)      ->    Optional[Any]:
            pass


     @unittest.skip(reason="BlipTextModel has no base class and is not available in MODEL_MAPPING")
     def 			_lowerCamelCase			(						self)      ->    str:
            pass


     @slow
     def 			_lowerCamelCase			(						self)      ->    Optional[Any]:
            for model_name in BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   _A				:	Union[str, Any]       =			BlipTextModel.from_pretrained(__lowerCamelCase)
                   self.assertIsNotNone(__lowerCamelCase)


     def 			_lowerCamelCase			(						self)      ->    Optional[int]:
            super().test_pt_tf_model_equivalence(allow_missing_keys=__lowerCamelCase)
