

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


  '''simple docstring'''







  def __init__(self       ,					_lowerCamelCase       ,					_lowerCamelCase=3       ,					_lowerCamelCase=32       ,					_lowerCamelCase=3       ,					_lowerCamelCase=10       ,					_lowerCamelCase=[10, 20, 30, 40]       ,					_lowerCamelCase=[1, 1, 2, 1]       ,					_lowerCamelCase=True       ,					_lowerCamelCase=True       ,					_lowerCamelCase="relu"       ,					_lowerCamelCase=3       ,					_lowerCamelCase=None       ,					):


        """simple docstring"""

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



  def    _a			(self  ):


        """simple docstring"""

        UpperCAmelCase__ :       Tuple						=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

        UpperCAmelCase__ :       Tuple						=						self.get_config()

        return config, pixel_values



  def    _a			(self  ):


        """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    _a			(self       ,					_lowerCamelCase       ,					_lowerCamelCase  ):


        """simple docstring"""

        UpperCAmelCase__ :       List[Any]						=						FlaxResNetModel(config=_lowerCAmelCase  )
        UpperCAmelCase__ :       Dict						=						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    _a			(self       ,					_lowerCamelCase       ,					_lowerCamelCase  ):


        """simple docstring"""

        UpperCAmelCase__ :       Optional[Any]						=						self.num_labels
        UpperCAmelCase__ :       Optional[Any]						=						FlaxResNetForImageClassification(config=_lowerCAmelCase  )
        UpperCAmelCase__ :       Optional[Any]						=						model(_lowerCAmelCase  )
        self.parent.assertEqual(result.logits.shape       ,					(self.batch_size, self.num_labels)  )




  def    _a			(self  ):


        """simple docstring"""

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




@require_flax
class 			lowerCamelCase  (					__lowerCamelCase				,				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    _a			(self  ):


        """simple docstring"""

        UpperCAmelCase__ :       Optional[Any]						=						FlaxResNetModelTester(self  )
        UpperCAmelCase__ :       Optional[int]						=						ConfigTester(self       ,					config_class=_lowerCAmelCase       ,					has_text_modality=_lowerCAmelCase  )



  def    _a			(self  ):


        """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    _a			(self  ):


        """simple docstring"""

        return



  def    _a			(self  ):


        """simple docstring"""

        UpperCAmelCase__ :       Optional[Any]						=						self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*_lowerCAmelCase  )



  def    _a			(self  ):


        """simple docstring"""

        UpperCAmelCase__ :       List[str]						=						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    _a			(self  ):


        """simple docstring"""

        pass



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


        """simple docstring"""

        pass



  def    _a			(self  ):


        """simple docstring"""

        UpperCAmelCase__ :       List[Any]						=						self.model_tester.prepare_config_and_inputs_for_common()

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

              UpperCAmelCase__ :       Optional[Any]						=						["""pixel_values"""]
              self.assertListEqual(arg_names[:1]       ,					_lowerCAmelCase  )



  def    _a			(self  ):


        """simple docstring"""

        def check_hidden_states_output(_lowerCamelCase       ,					_lowerCamelCase       ,					_lowerCamelCase  ):
              UpperCAmelCase__ :       Union[str, Any]						=						model_class(_lowerCAmelCase  )

              UpperCAmelCase__ :       List[str]						=						model(**self._prepare_for_class(_lowerCAmelCase       ,					_lowerCAmelCase  )  )

              UpperCAmelCase__ :       str						=						outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

              UpperCAmelCase__ :       str						=						self.model_tester.num_stages
              self.assertEqual(len(_lowerCAmelCase  )       ,					expected_num_stages + 1  )



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


        """simple docstring"""

        pass




  def    _a			(self  ):


        """simple docstring"""

        UpperCAmelCase__ :       Tuple						=						self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
              with self.subTest(model_class.__name__  ):
                    UpperCAmelCase__ :       List[Any]						=						self._prepare_for_class(_lowerCAmelCase       ,					_lowerCAmelCase  )
                    UpperCAmelCase__ :       Union[str, Any]						=						model_class(_lowerCAmelCase  )

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

                    with self.subTest("""JIT Enabled"""  ):
                          UpperCAmelCase__ :       Union[str, Any]						=						model_jitted(**_lowerCAmelCase  ).to_tuple()

                    with self.subTest("""JIT Disabled"""  ):
                          with jax.disable_jit():
                                UpperCAmelCase__ :       Any						=						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 				a__	(	)  ->   Tuple:
      UpperCAmelCase__ :       Tuple						=						Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""						)
      return image





@require_flax
class 			lowerCamelCase  (					unittest.TestCase      ):


  '''simple docstring'''







  @cached_property
  def    _a			(self  ):


        """simple docstring"""

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




  @slow
  def    _a			(self  ):


        """simple docstring"""

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

        UpperCAmelCase__ :       Tuple						=						self.default_image_processor
        UpperCAmelCase__ :       Any						=						prepare_img()
        UpperCAmelCase__ :       Union[str, Any]						=						image_processor(images=_lowerCAmelCase       ,					return_tensors="""np"""  )

        UpperCAmelCase__ :       Any						=						model(**_lowerCAmelCase  )

        # verify the logits
        UpperCAmelCase__ :       Tuple						=						(1, 1000)
        self.assertEqual(outputs.logits.shape       ,					_lowerCAmelCase  )

        UpperCAmelCase__ :       Tuple						=						jnp.array([-11.1069, -9.7_877, -8.3_777]  )

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




"""simple docstring"""
from typing import TYPE_CHECKING

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


_A						=     {
    """configuration_gpt2""": ["""GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GPT2Config""", """GPT2OnnxConfig"""],
    """tokenization_gpt2""": ["""GPT2Tokenizer"""],
}

try:
    if not is_tokenizers_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    _A						=     ["""GPT2TokenizerFast"""]

try:
    if not is_torch_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    _A						=     [
        """GPT2_PRETRAINED_MODEL_ARCHIVE_LIST""",
        """GPT2DoubleHeadsModel""",
        """GPT2ForQuestionAnswering""",
        """GPT2ForSequenceClassification""",
        """GPT2ForTokenClassification""",
        """GPT2LMHeadModel""",
        """GPT2Model""",
        """GPT2PreTrainedModel""",
        """load_tf_weights_in_gpt2""",
    ]

try:
    if not is_tf_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    _A						=     [
        """TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST""",
        """TFGPT2DoubleHeadsModel""",
        """TFGPT2ForSequenceClassification""",
        """TFGPT2LMHeadModel""",
        """TFGPT2MainLayer""",
        """TFGPT2Model""",
        """TFGPT2PreTrainedModel""",
    ]

try:
    if not is_keras_nlp_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    _A						=     ["""TFGPT2Tokenizer"""]

try:
    if not is_flax_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    _A						=     ["""FlaxGPT2LMHeadModel""", """FlaxGPT2Model""", """FlaxGPT2PreTrainedModel"""]

if TYPE_CHECKING:
    from .configuration_gpta import GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTaConfig, GPTaOnnxConfig
    from .tokenization_gpta import GPTaTokenizer

    try:
        if not is_tokenizers_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .tokenization_gpta_fast import GPTaTokenizerFast

    try:
        if not is_torch_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_gpta import (
            GPT2_PRETRAINED_MODEL_ARCHIVE_LIST,
            GPTaDoubleHeadsModel,
            GPTaForQuestionAnswering,
            GPTaForSequenceClassification,
            GPTaForTokenClassification,
            GPTaLMHeadModel,
            GPTaModel,
            GPTaPreTrainedModel,
            load_tf_weights_in_gpta,
        )

    try:
        if not is_tf_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_tf_gpta import (
            TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST,
            TFGPTaDoubleHeadsModel,
            TFGPTaForSequenceClassification,
            TFGPTaLMHeadModel,
            TFGPTaMainLayer,
            TFGPTaModel,
            TFGPTaPreTrainedModel,
        )

    try:
        if not is_keras_nlp_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .tokenization_gpta_tf import TFGPTaTokenizer

    try:
        if not is_flax_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_flax_gpta import FlaxGPTaLMHeadModel, FlaxGPTaModel, FlaxGPTaPreTrainedModel

else:
    import sys

    _A						=     _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)

