






"""simple docstring"""




import inspect
import unittest

from transformers import ResNetConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
      import torch
      from torch import nn

      from transformers import ResNetBackbone, ResNetForImageClassification, ResNetModel
      from transformers.models.resnet.modeling_resnet import RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
      from PIL import Image

      from transformers import AutoImageProcessor







class 					_UpperCamelCase		:






    def __init__(self						,      lowerCamelCase__						,      lowerCamelCase__=3						,      lowerCamelCase__=3_2						,      lowerCamelCase__=3						,      lowerCamelCase__=1_0						,      lowerCamelCase__=[1_0, 2_0, 3_0, 4_0]						,      lowerCamelCase__=[1, 1, 2, 1]						,      lowerCamelCase__=True						,      lowerCamelCase__=True						,      lowerCamelCase__="relu"						,      lowerCamelCase__=3						,      lowerCamelCase__=None						,      lowerCamelCase__=["stage2", "stage3", "stage4"]						,      lowerCamelCase__=[2, 3, 4]						,      ):


      """simple docstring"""
      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__   )
      A__											=							out_features
      A__											=							out_indices






    def  A    (self   ):


      """simple docstring"""
      A__											=							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

      A__											=							None
      if self.use_labels:
        A__											=							ids_tensor([self.batch_size]						,      self.num_labels   )

      A__											=							self.get_config()

      return config, pixel_values, labels






    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						,      out_features=self.out_features						,      out_indices=self.out_indices						,      )






    def  A    (self						,      lowerCamelCase__						,      lowerCamelCase__						,      lowerCamelCase__   ):


      """simple docstring"""
      A__											=							ResNetModel(config=lowerCamelCase__   )
      model.to(lowerCamelCase__   )
      model.eval()
      A__											=							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 // 3_2, self.image_size // 3_2)						,      )






    def  A    (self						,      lowerCamelCase__						,      lowerCamelCase__						,      lowerCamelCase__   ):


      """simple docstring"""
      A__											=							self.num_labels
      A__											=							ResNetForImageClassification(lowerCamelCase__   )
      model.to(lowerCamelCase__   )
      model.eval()
      A__											=							model(lowerCamelCase__						,      labels=lowerCamelCase__   )
      self.parent.assertEqual(result.logits.shape						,      (self.batch_size, self.num_labels)   )






    def  A    (self						,      lowerCamelCase__						,      lowerCamelCase__						,      lowerCamelCase__   ):


      """simple docstring"""
      A__											=							ResNetBackbone(config=lowerCamelCase__   )
      model.to(lowerCamelCase__   )
      model.eval()
      A__											=							model(lowerCamelCase__   )

      # verify feature maps
      self.parent.assertEqual(len(result.feature_maps   )						,      len(config.out_features   )   )
      self.parent.assertListEqual(list(result.feature_maps[0].shape   )						,      [self.batch_size, self.hidden_sizes[1], 4, 4]   )

      # verify channels
      self.parent.assertEqual(len(model.channels   )						,      len(config.out_features   )   )
      self.parent.assertListEqual(model.channels						,      config.hidden_sizes[1:]   )

      # verify backbone works with out_features=None
      A__											=							None
      A__											=							ResNetBackbone(config=lowerCamelCase__   )
      model.to(lowerCamelCase__   )
      model.eval()
      A__											=							model(lowerCamelCase__   )

      # verify feature maps
      self.parent.assertEqual(len(result.feature_maps   )						,      1   )
      self.parent.assertListEqual(list(result.feature_maps[0].shape   )						,      [self.batch_size, self.hidden_sizes[-1], 1, 1]   )

      # verify channels
      self.parent.assertEqual(len(model.channels   )						,      1   )
      self.parent.assertListEqual(model.channels						,      [config.hidden_sizes[-1]]   )






    def  A    (self   ):


      """simple docstring"""
      A__											=							self.prepare_config_and_inputs()
      A__											=							config_and_inputs
      A__											=							{"pixel_values": pixel_values}
      return config, inputs_dict







@require_torch
class 					_UpperCamelCase		( A__						, A__						, unittest.TestCase):
    __lowerCamelCase         =  (
        (
            ResNetModel,
            ResNetForImageClassification,
            ResNetBackbone,
        )
        if is_torch_available()
        else ()
    )
    __lowerCamelCase         =  (
        {'''feature-extraction''': ResNetModel, '''image-classification''': ResNetForImageClassification}
        if is_torch_available()
        else {}
    )

    __lowerCamelCase         =  True
    __lowerCamelCase         =  False
    __lowerCamelCase         =  False
    __lowerCamelCase         =  False
    __lowerCamelCase         =  False






    def  A    (self   ):


      """simple docstring"""
      A__											=							ResNetModelTester(self   )
      A__											=							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






    @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"""
      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.forward   )
        # 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  A    (self   ):


      """simple docstring"""
      A__											=							self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*lowerCamelCase__   )






    def  A    (self   ):


      """simple docstring"""
      A__											=							self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_backbone(*lowerCamelCase__   )






    def  A    (self   ):


      """simple docstring"""
      A__											=							self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
        A__											=							model_class(config=lowerCamelCase__   )
        for name, module in model.named_modules():
          if isinstance(lowerCamelCase__						,      (nn.BatchNormad, nn.GroupNorm)   ):
            self.assertTrue(
                torch.all(module.weight == 1   )						,      msg=F"""Parameter {name} of model {model_class} seems not properly initialized"""						,      )
            self.assertTrue(
                torch.all(module.bias == 0   )						,      msg=F"""Parameter {name} of model {model_class} seems not properly initialized"""						,      )






    def  A    (self   ):


      """simple docstring"""






      def check_hidden_states_output(lowerCamelCase__						,      lowerCamelCase__						,      lowerCamelCase__   ):
        A__											=							model_class(lowerCamelCase__   )
        model.to(lowerCamelCase__   )
        model.eval()

        with torch.no_grad():
          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   )

        # 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]						,      )

      A__											=							self.model_tester.prepare_config_and_inputs_for_common()
      A__											=							["basic", "bottleneck"]
      for model_class in self.all_model_classes:
        for layer_type in layers_type:
          A__											=							layer_type
          A__											=							True
          check_hidden_states_output(lowerCamelCase__						,      lowerCamelCase__						,      lowerCamelCase__   )

          # check that output_hidden_states also work using config
          del inputs_dict["output_hidden_states"]
          A__											=							True

          check_hidden_states_output(lowerCamelCase__						,      lowerCamelCase__						,      lowerCamelCase__   )






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


      """simple docstring"""
      pass






    def  A    (self   ):


      """simple docstring"""
      A__											=							self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__   )






    @slow
    def  A    (self   ):


      """simple docstring"""






      for model_name in RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        A__											=							ResNetModel.from_pretrained(lowerCamelCase__   )
        self.assertIsNotNone(lowerCamelCase__   )






def 						_SCREAMING_SNAKE_CASE							( ):
  A__											=							Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""    )
  return image







@require_torch
@require_vision
class 					_UpperCamelCase		( unittest.TestCase):






    @cached_property
    def  A    (self   ):


      """simple docstring"""
      return (
          AutoImageProcessor.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]   )
          if is_vision_available()
          else None
      )






    @slow
    def  A    (self   ):


      """simple docstring"""
      A__											=							ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]   ).to(lowerCamelCase__   )

      A__											=							self.default_image_processor
      A__											=							prepare_img()
      A__											=							image_processor(images=lowerCamelCase__						,      return_tensors="""pt"""   ).to(lowerCamelCase__   )

      # forward pass
      with torch.no_grad():
        A__											=							model(**lowerCamelCase__   )

      # verify the logits
      A__											=							torch.Size((1, 1_0_0_0)   )
      self.assertEqual(outputs.logits.shape						,      lowerCamelCase__   )

      A__											=							torch.tensor([-1_1.1_0_6_9, -9.7_8_7_7, -8.3_7_7_7]   ).to(lowerCamelCase__   )

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







@require_torch
class 					_UpperCamelCase		( A__						, unittest.TestCase):
    __lowerCamelCase         =  (ResNetBackbone,) if is_torch_available() else ()
    __lowerCamelCase         =  False
    __lowerCamelCase         =  ResNetConfig






    def  A    (self   ):


      """simple docstring"""
      A__											=							ResNetModelTester(self   )








"""simple docstring"""




from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


lowerCamelCase__			=   logging.get_logger(__name__)

lowerCamelCase__			=   {
    "google/electra-small-generator": "https://huggingface.co/google/electra-small-generator/resolve/main/config.json",
    "google/electra-base-generator": "https://huggingface.co/google/electra-base-generator/resolve/main/config.json",
    "google/electra-large-generator": "https://huggingface.co/google/electra-large-generator/resolve/main/config.json",
    "google/electra-small-discriminator": (
        "https://huggingface.co/google/electra-small-discriminator/resolve/main/config.json"
    ),
    "google/electra-base-discriminator": (
        "https://huggingface.co/google/electra-base-discriminator/resolve/main/config.json"
    ),
    "google/electra-large-discriminator": (
        "https://huggingface.co/google/electra-large-discriminator/resolve/main/config.json"
    ),
}







class 					_UpperCamelCase		( __snake_case):
    __lowerCamelCase         =  "electra"






    def __init__(self						,      lowerCamelCase__=3_0_5_2_2						,      lowerCamelCase__=1_2_8						,      lowerCamelCase__=2_5_6						,      lowerCamelCase__=1_2						,      lowerCamelCase__=4						,      lowerCamelCase__=1_0_2_4						,      lowerCamelCase__="gelu"						,      lowerCamelCase__=0.1						,      lowerCamelCase__=0.1						,      lowerCamelCase__=5_1_2						,      lowerCamelCase__=2						,      lowerCamelCase__=0.0_2						,      lowerCamelCase__=1E-12						,      lowerCamelCase__="first"						,      lowerCamelCase__=True						,      lowerCamelCase__="gelu"						,      lowerCamelCase__=0.1						,      lowerCamelCase__=0						,      lowerCamelCase__="absolute"						,      lowerCamelCase__=True						,      lowerCamelCase__=None						,      **lowerCamelCase__						,      ):


      """simple docstring"""
      super().__init__(pad_token_id=lowerCamelCase__						,      **lowerCamelCase__   )

      A__											=							vocab_size
      A__											=							embedding_size
      A__											=							hidden_size
      A__											=							num_hidden_layers
      A__											=							num_attention_heads
      A__											=							intermediate_size
      A__											=							hidden_act
      A__											=							hidden_dropout_prob
      A__											=							attention_probs_dropout_prob
      A__											=							max_position_embeddings
      A__											=							type_vocab_size
      A__											=							initializer_range
      A__											=							layer_norm_eps

      A__											=							summary_type
      A__											=							summary_use_proj
      A__											=							summary_activation
      A__											=							summary_last_dropout
      A__											=							position_embedding_type
      A__											=							use_cache
      A__											=							classifier_dropout







class 					_UpperCamelCase		( __snake_case):






    @property
    def  A    (self   ):


      """simple docstring"""
      if self.task == "multiple-choice":
        A__											=							{0: """batch""", 1: """choice""", 2: """sequence"""}
      else:
        A__											=							{0: """batch""", 1: """sequence"""}
      return OrderedDict(
          [
              ("""input_ids""", dynamic_axis),
              ("""attention_mask""", dynamic_axis),
              ("""token_type_ids""", dynamic_axis),
          ]   )




