





'''simple docstring'''






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




      def __init__(    self    :				str    ,    __snake_case    :				Any    ,    __snake_case    :				List[Any]=3    ,    __snake_case    :				Tuple=32    ,    __snake_case    :				str=3    ,    __snake_case    :				str=10    ,    __snake_case    :				int=[10, 20, 30, 40]    ,    __snake_case    :				Any=[1, 1, 2, 1]    ,    __snake_case    :				Any=True    ,    __snake_case    :				Union[str, Any]=True    ,    __snake_case    :				Union[str, Any]="relu"    ,    __snake_case    :				int=3    ,    __snake_case    :				Union[str, Any]=None    ,    )       ->   Tuple:
            _lowerCAmelCase							  =							parent
            _lowerCAmelCase							  =							batch_size
            _lowerCAmelCase							  =							image_size
            _lowerCAmelCase							  =							num_channels
            _lowerCAmelCase							  =							embeddings_size
            _lowerCAmelCase							  =							hidden_sizes
            _lowerCAmelCase							  =							depths
            _lowerCAmelCase							  =							is_training
            _lowerCAmelCase							  =							use_labels
            _lowerCAmelCase							  =							hidden_act
            _lowerCAmelCase							  =							num_labels
            _lowerCAmelCase							  =							scope
            _lowerCAmelCase							  =							len(__snake_case						)




      def        lowercase__					(    self    :				Tuple						)       ->   int:
            _lowerCAmelCase							  =							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

            _lowerCAmelCase							  =							self.get_config()

            return config, pixel_values




      def        lowercase__					(    self    :				Optional[int]						)       ->   int:
            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        lowercase__					(    self    :				Tuple    ,    __snake_case    :				Union[str, Any]    ,    __snake_case    :				Optional[Any]						)       ->   List[Any]:
            _lowerCAmelCase							  =							FlaxResNetModel(config=__snake_case						)
            _lowerCAmelCase							  =							model(__snake_case						)

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




      def        lowercase__					(    self    :				Optional[int]    ,    __snake_case    :				Union[str, Any]    ,    __snake_case    :				Optional[int]						)       ->   str:
            _lowerCAmelCase							  =							self.num_labels
            _lowerCAmelCase							  =							FlaxResNetForImageClassification(config=__snake_case						)
            _lowerCAmelCase							  =							model(__snake_case						)
            self.parent.assertEqual(result.logits.shape    ,    (self.batch_size, self.num_labels)						)




      def        lowercase__					(    self    :				List[Any]						)       ->   Any:
            _lowerCAmelCase							  =							self.prepare_config_and_inputs()
            _lowerCAmelCase  ,							_lowerCAmelCase							  =							config_and_inputs
            _lowerCAmelCase							  =							{"""pixel_values""": pixel_values}
            return config, inputs_dict




@require_flax
class 				UpperCAmelCase  (    snake_case_							,	unittest.TestCase     ):
      _lowercase:    Union[str, Any]		  =     (FlaxResNetModel, FlaxResNetForImageClassification) if is_flax_available() else ()

      _lowercase:    Tuple		  =     False
      _lowercase:    Tuple		  =     False
      _lowercase:    Union[str, Any]		  =     False




      def        lowercase__					(    self    :				Tuple						)       ->   None:
            _lowerCAmelCase							  =							FlaxResNetModelTester(self						)
            _lowerCAmelCase							  =							ConfigTester(self    ,    config_class=__snake_case    ,    has_text_modality=__snake_case						)




      def        lowercase__					(    self    :				Optional[int]						)       ->   str:
            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        lowercase__					(    self    :				Optional[Any]						)       ->   Dict:
            return




      def        lowercase__					(    self    :				Optional[int]						)       ->   List[Any]:
            _lowerCAmelCase							  =							self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*__snake_case						)




      def        lowercase__					(    self    :				Optional[Any]						)       ->   Optional[Any]:
            _lowerCAmelCase							  =							self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_image_classification(*__snake_case						)




      @unittest.skip(reason="""ResNet does not use inputs_embeds"""						)
      def        lowercase__					(    self    :				List[Any]						)       ->   List[Any]:
            pass




      @unittest.skip(reason="""ResNet does not support input and output embeddings"""						)
      def        lowercase__					(    self    :				Any						)       ->   int:
            pass




      def        lowercase__					(    self    :				Optional[Any]						)       ->   List[str]:
            _lowerCAmelCase  ,							_lowerCAmelCase							  =							self.model_tester.prepare_config_and_inputs_for_common()

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

                  _lowerCAmelCase							  =							["""pixel_values"""]
                  self.assertListEqual(arg_names[:1]    ,    __snake_case						)




      def        lowercase__					(    self    :				List[Any]						)       ->   Optional[Any]:
            def check_hidden_states_output(__snake_case    :				Optional[int]    ,    __snake_case    :				Optional[int]    ,    __snake_case    :				Tuple						):
                  _lowerCAmelCase							  =							model_class(__snake_case						)

                  _lowerCAmelCase							  =							model(**self._prepare_for_class(__snake_case    ,    __snake_case						)						)

                  _lowerCAmelCase							  =							outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                  _lowerCAmelCase							  =							self.model_tester.num_stages
                  self.assertEqual(len(__snake_case						)    ,    expected_num_stages + 1						)




      @unittest.skip(reason="""ResNet does not use feedforward chunking"""						)
      def        lowercase__					(    self    :				str						)       ->   Optional[Any]:
            pass




      def        lowercase__					(    self    :				List[str]						)       ->   Optional[int]:
            _lowerCAmelCase  ,							_lowerCAmelCase							  =							self.model_tester.prepare_config_and_inputs_for_common()

            for model_class in self.all_model_classes:
                  with self.subTest(model_class.__name__						):
                        _lowerCAmelCase							  =							self._prepare_for_class(__snake_case    ,    __snake_case						)
                        _lowerCAmelCase							  =							model_class(__snake_case						)

                        @jax.jit
                        def model_jitted(__snake_case    :				Union[str, Any]    ,    **__snake_case    :				List[Any]						):
                              return model(pixel_values=__snake_case    ,    **__snake_case						)

                        with self.subTest("""JIT Enabled"""						):
                              _lowerCAmelCase							  =							model_jitted(**__snake_case						).to_tuple()

                        with self.subTest("""JIT Disabled"""						):
                              with jax.disable_jit():
                                    _lowerCAmelCase							  =							model_jitted(**__snake_case						).to_tuple()

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




def      UpperCamelCase__   (	):





      """simple docstring"""


      _lowerCAmelCase							  =							Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""						)
      return image





@require_flax
class 				UpperCAmelCase  (    unittest.TestCase     ):




      @cached_property
      def        lowercase__					(    self    :				Tuple						)       ->   int:
            return AutoImageProcessor.from_pretrained("""microsoft/resnet-50"""						) if is_vision_available() else None




      @slow
      def        lowercase__					(    self    :				Dict						)       ->   str:
            _lowerCAmelCase							  =							FlaxResNetForImageClassification.from_pretrained("""microsoft/resnet-50"""						)

            _lowerCAmelCase							  =							self.default_image_processor
            _lowerCAmelCase							  =							prepare_img()
            _lowerCAmelCase							  =							image_processor(images=__snake_case    ,    return_tensors="""np"""						)

            _lowerCAmelCase							  =							model(**__snake_case						)

            # verify the logits
            _lowerCAmelCase							  =							(1, 10_00)
            self.assertEqual(outputs.logits.shape    ,    __snake_case						)

            _lowerCAmelCase							  =							jnp.array([-11.10_69, -9.78_77, -8.37_77]						)

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













'''simple docstring'''






import torch

from transformers import PreTrainedModel

from .custom_configuration import CustomConfig, NoSuperInitConfig




class 				UpperCAmelCase  (    snake_case_     ):
      _lowercase:    str		  =     CustomConfig




      def __init__(    self    :				Optional[int]    ,    __snake_case    :				Tuple						)       ->   Optional[Any]:
            super().__init__(__snake_case						)
            _lowerCAmelCase							  =							torch.nn.Linear(config.hidden_size    ,    config.hidden_size						)




      def        lowercase__					(    self    :				Dict    ,    __snake_case    :				List[Any]						)       ->   Dict:
            return self.linear(__snake_case						)




      def        lowercase__					(    self    :				List[Any]    ,    __snake_case    :				int						)       ->   Any:
            pass




class 				UpperCAmelCase  (    snake_case_     ):
      _lowercase:    List[str]		  =     NoSuperInitConfig




      def __init__(    self    :				List[str]    ,    __snake_case    :				List[str]						)       ->   int:
            super().__init__(__snake_case						)
            _lowerCAmelCase							  =							torch.nn.Linear(config.attribute    ,    config.attribute						)




      def        lowercase__					(    self    :				List[str]    ,    __snake_case    :				Dict						)       ->   Any:
            return self.linear(__snake_case						)




      def        lowercase__					(    self    :				Optional[int]    ,    __snake_case    :				List[Any]						)       ->   Dict:
            pass






