





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    ,							UpperCAmelCase    ,							UpperCAmelCase=3    ,							UpperCAmelCase=32    ,							UpperCAmelCase=3    ,							UpperCAmelCase=10    ,							UpperCAmelCase=[10, 20, 30, 40]    ,							UpperCAmelCase=[1, 1, 2, 1]    ,							UpperCAmelCase=True    ,							UpperCAmelCase=True    ,							UpperCAmelCase="relu"    ,							UpperCAmelCase=3    ,							UpperCAmelCase=None    ,							)->   List[Any]:
     __A    =  parent
     __A    =  batch_size
     __A    =  image_size
     __A    =  num_channels
     __A    =  embeddings_size
     __A    =  hidden_sizes
     __A    =  depths
     __A    =  is_training
     __A    =  use_labels
     __A    =  hidden_act
     __A    =  num_labels
     __A    =  scope
     __A    =  len(lowerCamelCase_      )

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Union[str, Any]:
     __A    =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

     __A    =  self.get_config()

     return config, pixel_values

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Dict:
     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 						SCREAMING_SNAKE_CASE__			(   self    ,							UpperCAmelCase    ,							UpperCAmelCase      )->   Any:
     __A    =  FlaxResNetModel(config=lowerCamelCase_      )
     __A    =  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 // 32, self.image_size // 32)    ,							)

  def 						SCREAMING_SNAKE_CASE__			(   self    ,							UpperCAmelCase    ,							UpperCAmelCase      )->   Optional[int]:
     __A    =  self.num_labels
     __A    =  FlaxResNetForImageClassification(config=lowerCamelCase_      )
     __A    =  model(lowerCamelCase_      )
     self.parent.assertEqual(result.logits.shape    ,							(self.batch_size, self.num_labels)      )





  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Any:
     __A    =  self.prepare_config_and_inputs()
     __A    =  config_and_inputs
     __A    =  {'pixel_values': pixel_values}
     return config, inputs_dict







@require_flax
class 		_lowerCAmelCase(		__lowerCamelCase						,       unittest.TestCase):

  """simple docstring"""







  lowerCamelCase__     	=       (FlaxResNetModel, FlaxResNetForImageClassification) if is_flax_available() else ()

  lowerCamelCase__     	=       False
  lowerCamelCase__     	=       False
  lowerCamelCase__     	=       False

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   List[Any]:
     __A    =  FlaxResNetModelTester(self      )
     __A    =  ConfigTester(self    ,							config_class=lowerCamelCase_    ,							has_text_modality=lowerCamelCase_      )

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   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 						SCREAMING_SNAKE_CASE__			(   self      )->   str:
     return

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Optional[int]:
     __A    =  self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*lowerCamelCase_      )

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Optional[Any]:
     __A    =  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 						SCREAMING_SNAKE_CASE__			(   self      )->   List[str]:
     pass

  @unittest.skip(reason='''ResNet does not support input and output embeddings'''      )
  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Optional[Any]:
     pass

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   int:
     __A    =  self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
        __A    =  model_class(lowerCamelCase_      )
        __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]    ,							lowerCamelCase_      )

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   str:






     def check_hidden_states_output(UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase      ):
        __A    =  model_class(lowerCamelCase_      )

        __A    =  model(**self._prepare_for_class(lowerCamelCase_    ,							lowerCamelCase_      )      )

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

        __A    =  self.model_tester.num_stages
        self.assertEqual(len(lowerCamelCase_      )    ,							expected_num_stages + 1      )

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





  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Union[str, Any]:
     __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(lowerCamelCase_    ,							lowerCamelCase_      )
           __A    =  model_class(lowerCamelCase_      )

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

           with self.subTest('''JIT Enabled'''      ):
              __A    =  model_jitted(**lowerCamelCase_      ).to_tuple()

           with self.subTest('''JIT Disabled'''      ):
              with jax.disable_jit():
                 __A    =  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    (						)    ->		Any:


   '''simple docstring'''







   __A    =  Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''      )
   return image







@require_flax
class 		_lowerCAmelCase(		unittest.TestCase):

  """simple docstring"""







  @cached_property
  def 						SCREAMING_SNAKE_CASE__			(   self      )->   str:
     return AutoImageProcessor.from_pretrained('''microsoft/resnet-50'''      ) if is_vision_available() else None





  @slow
  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Union[str, Any]:
     __A    =  FlaxResNetForImageClassification.from_pretrained('''microsoft/resnet-50'''      )

     __A    =  self.default_image_processor
     __A    =  prepare_img()
     __A    =  image_processor(images=lowerCamelCase_    ,							return_tensors='''np'''      )

     __A    =  model(**lowerCamelCase_      )

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

     __A    =  jnp.array([-11.1069, -9.7877, -8.3777]      )

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


"""simple docstring"""







from __future__ import annotations

import re


def   __lowerCAmelCase(		__UpperCAmelCase      ):






	"""simple docstring"""





	def alphanum_key(__UpperCAmelCase      ):
		return [int(__UpperCAmelCase      ) if s.isdigit() else s.lower() for s in re.split('([0-9]+)'  ,__UpperCAmelCase      )]

	return sorted(__UpperCAmelCase  ,key=__UpperCAmelCase      )


if __name__ == "__main__":
						import doctest

						doctest.testmod()



