
'''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 		snake_case_       :



   """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			,   UpperCamelCase=["stage2", "stage3", "stage4"]			,   UpperCamelCase=[2, 3, 4]			,   ):
          lowerCamelCase__				   =      parent
          lowerCamelCase__				   =      batch_size
          lowerCamelCase__				   =      image_size
          lowerCamelCase__				   =      num_channels
          lowerCamelCase__				   =      embeddings_size
          lowerCamelCase__				   =      hidden_sizes
          lowerCamelCase__				   =      depths
          lowerCamelCase__				   =      is_training
          lowerCamelCase__				   =      use_labels
          lowerCamelCase__				   =      hidden_act
          lowerCamelCase__				   =      num_labels
          lowerCamelCase__				   =      scope
          lowerCamelCase__				   =      len(UpperCamelCase)
          lowerCamelCase__				   =      out_features
          lowerCamelCase__				   =      out_indices







   def     __UpperCAmelCase      ( self):
          lowerCamelCase__				   =      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

          lowerCamelCase__				   =      self.get_config()

          return config, pixel_values, labels







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







   def     __UpperCAmelCase      ( self			,   UpperCamelCase			,   UpperCamelCase			,   UpperCamelCase):
          lowerCamelCase__				   =      ResNetModel(config=UpperCamelCase)
          model.to(UpperCamelCase)
          model.eval()
          lowerCamelCase__				   =      model(UpperCamelCase)
          # 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     __UpperCAmelCase      ( self			,   UpperCamelCase			,   UpperCamelCase			,   UpperCamelCase):
          lowerCamelCase__				   =      self.num_labels
          lowerCamelCase__				   =      ResNetForImageClassification(UpperCamelCase)
          model.to(UpperCamelCase)
          model.eval()
          lowerCamelCase__				   =      model(UpperCamelCase			,   labels=UpperCamelCase)
          self.parent.assertEqual(result.logits.shape			,   (self.batch_size, self.num_labels))







   def     __UpperCAmelCase      ( self			,   UpperCamelCase			,   UpperCamelCase			,   UpperCamelCase):
          lowerCamelCase__				   =      ResNetBackbone(config=UpperCamelCase)
          model.to(UpperCamelCase)
          model.eval()
          lowerCamelCase__				   =      model(UpperCamelCase)

          # 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
          lowerCamelCase__				   =      None
          lowerCamelCase__				   =      ResNetBackbone(config=UpperCamelCase)
          model.to(UpperCamelCase)
          model.eval()
          lowerCamelCase__				   =      model(UpperCamelCase)

          # 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     __UpperCAmelCase      ( self):
          lowerCamelCase__				   =      self.prepare_config_and_inputs()
          lowerCamelCase__   ,		lowerCamelCase__   ,		lowerCamelCase__				   =      config_and_inputs
          lowerCamelCase__				   =      {"pixel_values": pixel_values}
          return config, inputs_dict







@require_torch
class 		snake_case_       (						A__		,	A__		,	unittest.TestCase						):



   """simple docstring"""





   __lowerCAmelCase	:							int								=(
       (
           ResNetModel,
           ResNetForImageClassification,
           ResNetBackbone,
       )
       if is_torch_available()
       else ()
   )
   __lowerCAmelCase	:							List[str]								=(
       {'''feature-extraction''': ResNetModel, '''image-classification''': ResNetForImageClassification}
       if is_torch_available()
       else {}
   )

   __lowerCAmelCase	:							Tuple								=True
   __lowerCAmelCase	:							Tuple								=False
   __lowerCAmelCase	:							Any								=False
   __lowerCAmelCase	:							Any								=False
   __lowerCAmelCase	:							Union[str, Any]								=False







   def     __UpperCAmelCase      ( self):
          lowerCamelCase__				   =      ResNetModelTester(self)
          lowerCamelCase__				   =      ConfigTester(self			,   config_class=UpperCamelCase			,   has_text_modality=UpperCamelCase)







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







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







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







   def     __UpperCAmelCase      ( self):
          lowerCamelCase__   ,		lowerCamelCase__				   =      self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
                 lowerCamelCase__				   =      model_class(UpperCamelCase)
                 lowerCamelCase__				   =      inspect.signature(model.forward)
                 # signature.parameters is an OrderedDict => so arg_names order is deterministic
                 lowerCamelCase__				   =      [*signature.parameters.keys()]

                 lowerCamelCase__				   =      ["pixel_values"]
                 self.assertListEqual(arg_names[:1]			,   UpperCamelCase)







   def     __UpperCAmelCase      ( self):
          lowerCamelCase__				   =      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*UpperCamelCase)







   def     __UpperCAmelCase      ( self):
          lowerCamelCase__				   =      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_backbone(*UpperCamelCase)







   def     __UpperCAmelCase      ( self):
          lowerCamelCase__   ,		lowerCamelCase__				   =      self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
                 lowerCamelCase__				   =      model_class(config=UpperCamelCase)
                 for name, module in model.named_modules():
                        if isinstance(UpperCamelCase			,   (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     __UpperCAmelCase      ( self):
          def check_hidden_states_output(UpperCamelCase			,   UpperCamelCase			,   UpperCamelCase):
                 lowerCamelCase__				   =      model_class(UpperCamelCase)
                 model.to(UpperCamelCase)
                 model.eval()

                 with torch.no_grad():
                        lowerCamelCase__				   =      model(**self._prepare_for_class(UpperCamelCase			,   UpperCamelCase))

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

                 lowerCamelCase__				   =      self.model_tester.num_stages
                 self.assertEqual(len(UpperCamelCase)			,   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]			,   )

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

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

                        check_hidden_states_output(UpperCamelCase			,   UpperCamelCase			,   UpperCamelCase)







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







   def     __UpperCAmelCase      ( self):
          lowerCamelCase__				   =      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*UpperCamelCase)







   @slow
   def     __UpperCAmelCase      ( self):
          for model_name in RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 lowerCamelCase__				   =      ResNetModel.from_pretrained(UpperCamelCase)
                 self.assertIsNotNone(UpperCamelCase)







def   lowerCAmelCase(  ):







       '''simple docstring'''






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







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



   """simple docstring"""





   @cached_property
   def     __UpperCAmelCase      ( self):
          return (
              AutoImageProcessor.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0])
              if is_vision_available()
              else None
          )







   @slow
   def     __UpperCAmelCase      ( self):
          lowerCamelCase__				   =      ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]).to(UpperCamelCase)

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

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

          # verify the logits
          lowerCamelCase__				   =      torch.Size((1, 10_00))
          self.assertEqual(outputs.logits.shape			,   UpperCamelCase)

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

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







@require_torch
class 		snake_case_       (						A__		,	unittest.TestCase						):



   """simple docstring"""





   __lowerCAmelCase	:							List[Any]								=(ResNetBackbone,) if is_torch_available() else ()
   __lowerCAmelCase	:							Dict								=False
   __lowerCAmelCase	:							Optional[Any]								=ResNetConfig







   def     __UpperCAmelCase      ( self):
          lowerCamelCase__				   =      ResNetModelTester(self)



'''simple docstring'''







from ..utils import DummyObject, requires_backends







class 		snake_case_       (						metaclass=A__						):



   """simple docstring"""





   __lowerCAmelCase	:							List[str]								=['''torch''', '''librosa''']







   def __init__( self			,   *UpperCamelCase			,   **UpperCamelCase):
          requires_backends(self			,   ["torch", "librosa"])







   @classmethod
   def     __UpperCAmelCase      ( cls			,   *UpperCamelCase			,   **UpperCamelCase):
          requires_backends(cls			,   ["torch", "librosa"])







   @classmethod
   def     __UpperCAmelCase      ( cls			,   *UpperCamelCase			,   **UpperCamelCase):
          requires_backends(cls			,   ["torch", "librosa"])







class 		snake_case_       (						metaclass=A__						):



   """simple docstring"""





   __lowerCAmelCase	:							Union[str, Any]								=['''torch''', '''librosa''']







   def __init__( self			,   *UpperCamelCase			,   **UpperCamelCase):
          requires_backends(self			,   ["torch", "librosa"])







   @classmethod
   def     __UpperCAmelCase      ( cls			,   *UpperCamelCase			,   **UpperCamelCase):
          requires_backends(cls			,   ["torch", "librosa"])







   @classmethod
   def     __UpperCAmelCase      ( cls			,   *UpperCamelCase			,   **UpperCamelCase):
          requires_backends(cls			,   ["torch", "librosa"])

