




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






      def __init__(   self      :     List[Any]	,	lowercase__      :     int	,	lowercase__      :     int=3	,	lowercase__      :     Any=32	,	lowercase__      :     List[Any]=3	,	lowercase__      :     int=10	,	lowercase__      :     int=[10, 20, 30, 40]	,	lowercase__      :     Dict=[1, 1, 2, 1]	,	lowercase__      :     Any=True	,	lowercase__      :     str=True	,	lowercase__      :     Optional[Any]="relu"	,	lowercase__      :     Optional[int]=3	,	lowercase__      :     Optional[int]=None	,	):


           '''simple docstring'''

           a_    :       Any    	=     parent
           a_    :       Dict    	=     batch_size
           a_    :       List[str]    	=     image_size
           a_    :       Optional[int]    	=     num_channels
           a_    :       Union[str, Any]    	=     embeddings_size
           a_    :       Any    	=     hidden_sizes
           a_    :       Union[str, Any]    	=     depths
           a_    :       Dict    	=     is_training
           a_    :       int    	=     use_labels
           a_    :       Union[str, Any]    	=     hidden_act
           a_    :       List[str]    	=     num_labels
           a_    :       Dict    	=     scope
           a_    :       Optional[Any]    	=     len(lowercase__					)






      def        lowercase_	(   self      :     List[Any]					):


           '''simple docstring'''

           a_    :       Union[str, Any]    	=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

           a_    :       List[str]    	=     self.get_config()

           return config, pixel_values






      def        lowercase_	(   self      :     int					):


           '''simple docstring'''

           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      :     Union[str, Any]	,	lowercase__      :     Union[str, Any]	,	lowercase__      :     List[Any]					):


           '''simple docstring'''

           a_    :       int    	=     FlaxResNetModel(config=lowercase__					)
           a_    :       int    	=     model(lowercase__					)

           # 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      :     List[str]	,	lowercase__      :     Any	,	lowercase__      :     List[str]					):


           '''simple docstring'''

           a_    :       Dict    	=     self.num_labels
           a_    :       List[Any]    	=     FlaxResNetForImageClassification(config=lowercase__					)
           a_    :       Union[str, Any]    	=     model(lowercase__					)
           self.parent.assertEqual(result.logits.shape	,	(self.batch_size, self.num_labels)					)






      def        lowercase_	(   self      :     List[str]					):


           '''simple docstring'''

           a_    :       List[Any]    	=     self.prepare_config_and_inputs()
           a_	,    a_    :       List[Any]    	=     config_and_inputs
           a_    :       Union[str, Any]    	=     {"""pixel_values""": pixel_values}
           return config, inputs_dict







@require_flax
class     SCREAMING_SNAKE_CASE						(	snake_case_       ,			unittest.TestCase							):
      __magic_name__     :					int             =				(FlaxResNetModel, FlaxResNetForImageClassification) if is_flax_available() else ()

      __magic_name__     :					Tuple             =				False
      __magic_name__     :					Dict             =				False
      __magic_name__     :					Union[str, Any]             =				False






      def        lowercase_	(   self      :     str					):


           '''simple docstring'''

           a_    :       Any    	=     FlaxResNetModelTester(self					)
           a_    :       Union[str, Any]    	=     ConfigTester(self	,	config_class=lowercase__	,	has_text_modality=lowercase__					)






      def        lowercase_	(   self      :     List[Any]					):


           '''simple docstring'''

           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[int]					):


           '''simple docstring'''

           return






      def        lowercase_	(   self      :     Tuple					):


           '''simple docstring'''

           a_    :       List[Any]    	=     self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*lowercase__					)






      def        lowercase_	(   self      :     Any					):


           '''simple docstring'''

           a_    :       List[str]    	=     self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*lowercase__					)






      @unittest.skip(reason="""ResNet does not use inputs_embeds"""					)
      def        lowercase_	(   self      :     str					):


           '''simple docstring'''

           pass






      @unittest.skip(reason="""ResNet does not support input and output embeddings"""					)
      def        lowercase_	(   self      :     str					):


           '''simple docstring'''

           pass






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


           '''simple docstring'''

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

           for model_class in self.all_model_classes:
                a_    :       int    	=     model_class(lowercase__					)
                a_    :       List[str]    	=     inspect.signature(model.__call__					)
                # signature.parameters is an OrderedDict => so arg_names order is deterministic
                a_    :       Tuple    	=     [*signature.parameters.keys()]

                a_    :       Any    	=     ["""pixel_values"""]
                self.assertListEqual(arg_names[:1]	,	lowercase__					)






      def        lowercase_	(   self      :     List[Any]					):


           '''simple docstring'''

           def check_hidden_states_output(lowercase__      :     int	,	lowercase__      :     Tuple	,	lowercase__      :     Optional[int]					):
                a_    :       Tuple    	=     model_class(lowercase__					)

                a_    :       Dict    	=     model(**self._prepare_for_class(lowercase__	,	lowercase__					)					)

                a_    :       Any    	=     outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                a_    :       int    	=     self.model_tester.num_stages
                self.assertEqual(len(lowercase__					)	,	expected_num_stages + 1					)






      @unittest.skip(reason="""ResNet does not use feedforward chunking"""					)
      def        lowercase_	(   self      :     Tuple					):


           '''simple docstring'''

           pass






      def        lowercase_	(   self      :     Any					):


           '''simple docstring'''

           a_	,    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_    :       Tuple    	=     self._prepare_for_class(lowercase__	,	lowercase__					)
                     a_    :       Union[str, Any]    	=     model_class(lowercase__					)

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

                     with self.subTest("""JIT Enabled"""					):
                          a_    :       List[Any]    	=     model_jitted(**lowercase__					).to_tuple()

                     with self.subTest("""JIT Disabled"""					):
                          with jax.disable_jit():
                               a_    :       Any    	=     model_jitted(**lowercase__					).to_tuple()

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



def    _SCREAMING_SNAKE_CASE    (			):




     """simple docstring"""


     a_    :       Optional[int]    	=     Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""							)
     return image







@require_flax
class     SCREAMING_SNAKE_CASE						(	unittest.TestCase							):






      @cached_property
      def        lowercase_	(   self      :     int					):


           '''simple docstring'''

           return AutoImageProcessor.from_pretrained("""microsoft/resnet-50"""					) if is_vision_available() else None






      @slow
      def        lowercase_	(   self      :     Optional[int]					):


           '''simple docstring'''

           a_    :       Optional[int]    	=     FlaxResNetForImageClassification.from_pretrained("""microsoft/resnet-50"""					)

           a_    :       List[str]    	=     self.default_image_processor
           a_    :       Dict    	=     prepare_img()
           a_    :       Any    	=     image_processor(images=lowercase__	,	return_tensors="""np"""					)

           a_    :       Union[str, Any]    	=     model(**lowercase__					)

           # verify the logits
           a_    :       Any    	=     (1, 1000)
           self.assertEqual(outputs.logits.shape	,	lowercase__					)

           a_    :       Tuple    	=     jnp.array([-11.1069, -9.7877, -8.3777]					)

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






'''simple docstring'''


from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


lowerCAmelCase_			:     int							    =     {
    'configuration_dpr': ['DPR_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DPRConfig'],
    'tokenization_dpr': [
        'DPRContextEncoderTokenizer',
        'DPRQuestionEncoderTokenizer',
        'DPRReaderOutput',
        'DPRReaderTokenizer',
    ],
}


try:
 if not is_tokenizers_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 lowerCAmelCase_			:     Union[str, Any]							    =     [
     'DPRContextEncoderTokenizerFast',
     'DPRQuestionEncoderTokenizerFast',
     'DPRReaderTokenizerFast',
 ]

try:
 if not is_torch_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 lowerCAmelCase_			:     List[str]							    =     [
     'DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST',
     'DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST',
     'DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST',
     'DPRContextEncoder',
     'DPRPretrainedContextEncoder',
     'DPRPreTrainedModel',
     'DPRPretrainedQuestionEncoder',
     'DPRPretrainedReader',
     'DPRQuestionEncoder',
     'DPRReader',
 ]

try:
 if not is_tf_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 lowerCAmelCase_			:     Dict							    =     [
     'TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST',
     'TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST',
     'TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST',
     'TFDPRContextEncoder',
     'TFDPRPretrainedContextEncoder',
     'TFDPRPretrainedQuestionEncoder',
     'TFDPRPretrainedReader',
     'TFDPRQuestionEncoder',
     'TFDPRReader',
 ]


if TYPE_CHECKING:
 from .configuration_dpr import DPR_PRETRAINED_CONFIG_ARCHIVE_MAP, DPRConfig
 from .tokenization_dpr import (
     DPRContextEncoderTokenizer,
     DPRQuestionEncoderTokenizer,
     DPRReaderOutput,
     DPRReaderTokenizer,
 )

 try:
  if not is_tokenizers_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .tokenization_dpr_fast import (
      DPRContextEncoderTokenizerFast,
      DPRQuestionEncoderTokenizerFast,
      DPRReaderTokenizerFast,
  )

 try:
  if not is_torch_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_dpr import (
      DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
      DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
      DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST,
      DPRContextEncoder,
      DPRPretrainedContextEncoder,
      DPRPreTrainedModel,
      DPRPretrainedQuestionEncoder,
      DPRPretrainedReader,
      DPRQuestionEncoder,
      DPRReader,
  )

 try:
  if not is_tf_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_tf_dpr import (
      TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
      TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
      TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST,
      TFDPRContextEncoder,
      TFDPRPretrainedContextEncoder,
      TFDPRPretrainedQuestionEncoder,
      TFDPRPretrainedReader,
      TFDPRQuestionEncoder,
      TFDPRReader,
  )

else:
 import sys

 lowerCAmelCase_			:     int							    =     _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
