
"""simple docstring"""
from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import ResNetConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
    import tensorflow as tf

    from transformers import TFResNetForImageClassification, TFResNetModel
    from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
    from PIL import Image

    from transformers import AutoImageProcessor






class      _UpperCAmelCase				:
    def __init__(    self						,    snake_case_						,    snake_case_=3						,    snake_case_=32						,    snake_case_=3						,    snake_case_=10						,    snake_case_=[10, 20, 30, 40]						,    snake_case_=[1, 1, 2, 1]						,    snake_case_=True						,    snake_case_=True						,    snake_case_="relu"						,    snake_case_=3						,    snake_case_=None						,    ):
      _snake_case     :						Union[str, Any]						=   parent
      _snake_case     :						Tuple						=   batch_size
      _snake_case     :						Dict						=   image_size
      _snake_case     :						List[Any]						=   num_channels
      _snake_case     :						List[str]						=   embeddings_size
      _snake_case     :						Optional[Any]						=   hidden_sizes
      _snake_case     :						Tuple						=   depths
      _snake_case     :						int						=   is_training
      _snake_case     :						Optional[int]						=   use_labels
      _snake_case     :						Any						=   hidden_act
      _snake_case     :						Tuple						=   num_labels
      _snake_case     :						Union[str, Any]						=   scope
      _snake_case     :						Any						=   len(lowerCamelCase_     )
    def 					lowerCamelCase__	(    self     ):
      _snake_case     :						int						=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

      _snake_case     :						int						=   None
      if self.use_labels:
        _snake_case     :						Dict						=   ids_tensor([self.batch_size]						,    self.num_labels     )

      _snake_case     :						int						=   self.get_config()

      return config, pixel_values, labels
    def 					lowerCamelCase__	(    self     ):
      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						,    snake_case_						,    snake_case_						,    snake_case_     ):
      _snake_case     :						int						=   TFResNetModel(config=lowerCamelCase_     )
      _snake_case     :						Tuple						=   model(lowerCamelCase_     )
      # expected last hidden states: B, C, H // 32, W // 32
      self.parent.assertEqual(
          result.last_hidden_state.shape						,    (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)						,    )
    def 					lowerCamelCase__	(    self						,    snake_case_						,    snake_case_						,    snake_case_     ):
      _snake_case     :						List[Any]						=   self.num_labels
      _snake_case     :						List[Any]						=   TFResNetForImageClassification(lowerCamelCase_     )
      _snake_case     :						List[str]						=   model(lowerCamelCase_						,    labels=lowerCamelCase_     )
      self.parent.assertEqual(result.logits.shape						,    (self.batch_size, self.num_labels)     )


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






@require_tf
class      _UpperCAmelCase				(					a__		,					a__		,					unittest.TestCase):
    __lowercase							: Union[str, Any]  =					(TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
    __lowercase							: Any  =					(
        {"feature-extraction": TFResNetModel, "image-classification": TFResNetForImageClassification}
        if is_tf_available()
        else {}
    )

    __lowercase							: int  =					False
    __lowercase							: List[str]  =					False
    __lowercase							: str  =					False
    __lowercase							: Tuple  =					False
    __lowercase							: Union[str, Any]  =					False
    def 					lowerCamelCase__	(    self     ):
      _snake_case     :						List[Any]						=   TFResNetModelTester(self     )
      _snake_case     :						Any						=   ConfigTester(self						,    config_class=lowerCamelCase_						,    has_text_modality=lowerCamelCase_     )
    def 					lowerCamelCase__	(    self     ):
      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     ):
      return
    @unittest.skip(reason="ResNet does not use inputs_embeds"     )
    def 					lowerCamelCase__	(    self     ):
      pass
    @unittest.skip(reason="ResNet does not support input and output embeddings"     )
    def 					lowerCamelCase__	(    self     ):
      pass
    def 					lowerCamelCase__	(    self     ):
      _snake_case			,					_snake_case     :						Union[str, Any]						=   self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
        _snake_case     :						str						=   model_class(lowerCamelCase_     )
        _snake_case     :						Optional[int]						=   inspect.signature(model.call     )
        # signature.parameters is an OrderedDict => so arg_names order is deterministic
        _snake_case     :						List[str]						=   [*signature.parameters.keys()]

        _snake_case     :						Optional[int]						=   ["pixel_values"]
        self.assertListEqual(arg_names[:1]						,    lowerCamelCase_     )
    def 					lowerCamelCase__	(    self     ):
      _snake_case     :						str						=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*lowerCamelCase_     )
    def 					lowerCamelCase__	(    self     ):
      def check_hidden_states_output(snake_case_						,    snake_case_						,    snake_case_     ):
        _snake_case     :						Dict						=   model_class(lowerCamelCase_     )
        _snake_case     :						str						=   model(**self._prepare_for_class(lowerCamelCase_						,    lowerCamelCase_     )     )

        _snake_case     :						Optional[int]						=   outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

        _snake_case     :						Union[str, Any]						=   self.model_tester.num_stages
        self.assertEqual(len(lowerCamelCase_     )						,    expected_num_stages + 1     )

        # ResNet's feature maps are of shape (batch_size, num_channels, height, width)
        self.assertListEqual(
            list(hidden_states[0].shape[-2:]     )						,    [self.model_tester.image_size // 4, self.model_tester.image_size // 4]						,    )

      _snake_case			,					_snake_case     :						str						=   self.model_tester.prepare_config_and_inputs_for_common()
      _snake_case     :						Optional[int]						=   ["basic", "bottleneck"]
      for model_class in self.all_model_classes:
        for layer_type in layers_type:
          _snake_case     :						List[Any]						=   layer_type
          _snake_case     :						Optional[int]						=   True
          check_hidden_states_output(lowerCamelCase_						,    lowerCamelCase_						,    lowerCamelCase_     )

          # check that output_hidden_states also work using config
          del inputs_dict["output_hidden_states"]
          _snake_case     :						Any						=   True

          check_hidden_states_output(lowerCamelCase_						,    lowerCamelCase_						,    lowerCamelCase_     )
    def 					lowerCamelCase__	(    self     ):
      _snake_case     :						List[str]						=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*lowerCamelCase_     )


    @slow
    def 					lowerCamelCase__	(    self     ):
      for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        _snake_case     :						Dict						=   TFResNetModel.from_pretrained(lowerCamelCase_     )
        self.assertIsNotNone(lowerCamelCase_     )


def 				a__   (   ):

  """simple docstring"""







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






@require_tf
@require_vision
class      _UpperCAmelCase				(					unittest.TestCase):
    @cached_property
    def 					lowerCamelCase__	(    self     ):
      return (
          AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]     )
          if is_vision_available()
          else None
      )


    @slow
    def 					lowerCamelCase__	(    self     ):
      _snake_case     :						Optional[int]						=   TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]     )

      _snake_case     :						str						=   self.default_image_processor
      _snake_case     :						List[Any]						=   prepare_img()
      _snake_case     :						Union[str, Any]						=   image_processor(images=lowerCamelCase_						,    return_tensors="tf"     )

      # forward pass
      _snake_case     :						Tuple						=   model(**lowerCamelCase_     )

      # verify the logits
      _snake_case     :						Union[str, Any]						=   tf.TensorShape((1, 10_00)     )
      self.assertEqual(outputs.logits.shape						,    lowerCamelCase_     )

      _snake_case     :						str						=   tf.constant([-11.1069, -9.7877, -8.3777]     )

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



"""simple docstring"""
from ...configuration_utils import PretrainedConfig
from ...utils import logging


_a      :			Optional[int]					=							logging.get_logger(__name__)

_a      :			str					=							{"""openai-gpt""": """https://huggingface.co/openai-gpt/resolve/main/config.json"""}






class      _UpperCAmelCase				(					_snake_case):
    __lowercase							: Optional[Any]  =					"""openai-gpt"""
    __lowercase							: Dict  =					{
        """max_position_embeddings""": """n_positions""",
        """hidden_size""": """n_embd""",
        """num_attention_heads""": """n_head""",
        """num_hidden_layers""": """n_layer""",
    }
    def __init__(    self						,    snake_case_=4_04_78						,    snake_case_=5_12						,    snake_case_=7_68						,    snake_case_=12						,    snake_case_=12						,    snake_case_="gelu"						,    snake_case_=0.1						,    snake_case_=0.1						,    snake_case_=0.1						,    snake_case_=1E-5						,    snake_case_=0.02						,    snake_case_="cls_index"						,    snake_case_=True						,    snake_case_=None						,    snake_case_=True						,    snake_case_=0.1						,    **snake_case_						,    ):
      _snake_case     :						Tuple						=   vocab_size
      _snake_case     :						Dict						=   n_positions
      _snake_case     :						Any						=   n_embd
      _snake_case     :						Any						=   n_layer
      _snake_case     :						Optional[int]						=   n_head
      _snake_case     :						Union[str, Any]						=   afn
      _snake_case     :						Dict						=   resid_pdrop
      _snake_case     :						str						=   embd_pdrop
      _snake_case     :						Union[str, Any]						=   attn_pdrop
      _snake_case     :						str						=   layer_norm_epsilon
      _snake_case     :						Union[str, Any]						=   initializer_range
      _snake_case     :						Any						=   summary_type
      _snake_case     :						List[str]						=   summary_use_proj
      _snake_case     :						Optional[int]						=   summary_activation
      _snake_case     :						Union[str, Any]						=   summary_first_dropout
      _snake_case     :						Optional[int]						=   summary_proj_to_labels
      super().__init__(**snake_case_     )

