
"""simple docstring"""



import inspect
import unittest

from transformers import RegNetConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

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 RegNetForImageClassification, RegNetModel
    from transformers.models.regnet.modeling_regnet import REGNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
    from PIL import Image

    from transformers import AutoImageProcessor





class 				a			:



      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__	:      List[Any]     							=					parent
          UpperCAmelCase__	:      List[Any]     							=					batch_size
          UpperCAmelCase__	:      int     							=					image_size
          UpperCAmelCase__	:      int     							=					num_channels
          UpperCAmelCase__	:      Any     							=					embeddings_size
          UpperCAmelCase__	:      List[Any]     							=					hidden_sizes
          UpperCAmelCase__	:      Dict     							=					depths
          UpperCAmelCase__	:      Any     							=					is_training
          UpperCAmelCase__	:      Union[str, Any]     							=					use_labels
          UpperCAmelCase__	:      List[Any]     							=					hidden_act
          UpperCAmelCase__	:      Optional[int]     							=					num_labels
          UpperCAmelCase__	:      Optional[Any]     							=					scope
          UpperCAmelCase__	:      Optional[int]     							=					len(UpperCamelCase_      )



      def  __snake_case							(   self      ):
          UpperCAmelCase__	:      List[str]     							=					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

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

          UpperCAmelCase__	:      int     							=					self.get_config()

          return config, pixel_values, labels



      def  __snake_case							(   self      ):
          return RegNetConfig(
              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     ,	)



      def  __snake_case							(   self     ,	UpperCamelCase_     ,	UpperCamelCase_     ,	UpperCamelCase_      ):
          UpperCAmelCase__	:      Optional[Any]     							=					RegNetModel(config=UpperCamelCase_      )
          model.to(UpperCamelCase_      )
          model.eval()
          UpperCAmelCase__	:      Optional[int]     							=					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  __snake_case							(   self     ,	UpperCamelCase_     ,	UpperCamelCase_     ,	UpperCamelCase_      ):
          UpperCAmelCase__	:      Optional[Any]     							=					self.num_labels
          UpperCAmelCase__	:      List[Any]     							=					RegNetForImageClassification(UpperCamelCase_      )
          model.to(UpperCamelCase_      )
          model.eval()
          UpperCAmelCase__	:      Union[str, Any]     							=					model(UpperCamelCase_     ,	labels=UpperCamelCase_      )
          self.parent.assertEqual(result.logits.shape     ,	(self.batch_size, self.num_labels)      )



      def  __snake_case							(   self      ):
          UpperCAmelCase__	:      Union[str, Any]     							=					self.prepare_config_and_inputs()
          UpperCAmelCase__							,							UpperCAmelCase__							,							UpperCAmelCase__	:      Tuple     							=					config_and_inputs
          UpperCAmelCase__	:      Optional[Any]     							=					{'pixel_values': pixel_values}
          return config, inputs_dict





@require_torch
class 				a			(					lowercase						,		lowercase						,		unittest.TestCase      ):
      UpperCamelCase							:   Tuple           =     (RegNetModel, RegNetForImageClassification) if is_torch_available() else ()
      UpperCamelCase							:   List[Any]           =     (
          {"""feature-extraction""": RegNetModel, """image-classification""": RegNetForImageClassification}
          if is_torch_available()
          else {}
      )

      UpperCamelCase							:   Dict           =     False
      UpperCamelCase							:   Optional[Any]           =     False
      UpperCamelCase							:   Dict           =     False
      UpperCamelCase							:   Optional[Any]           =     False



      def  __snake_case							(   self      ):
          UpperCAmelCase__	:      Union[str, Any]     							=					RegNetModelTester(self      )
          UpperCAmelCase__	:      Any     							=					ConfigTester(self     ,	config_class=UpperCamelCase_     ,	has_text_modality=UpperCamelCase_      )



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



      @unittest.skip(reason='RegNet does not use inputs_embeds'      )
      def  __snake_case							(   self      ):
          pass



      @unittest.skip(reason='RegNet does not support input and output embeddings'      )
      def  __snake_case							(   self      ):
          pass



      def  __snake_case							(   self      ):
          UpperCAmelCase__							,							UpperCAmelCase__	:      int     							=					self.model_tester.prepare_config_and_inputs_for_common()

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

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



      def  __snake_case							(   self      ):
          UpperCAmelCase__	:      Dict     							=					self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*UpperCamelCase_      )



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

          for model_class in self.all_model_classes:
              UpperCAmelCase__	:      Union[str, Any]     							=					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  __snake_case							(   self      ):
          def check_hidden_states_output(UpperCamelCase_     ,	UpperCamelCase_     ,	UpperCamelCase_      ):
              UpperCAmelCase__	:      List[str]     							=					model_class(UpperCamelCase_      )
              model.to(UpperCamelCase_      )
              model.eval()

              with torch.no_grad():
                  UpperCAmelCase__	:      List[Any]     							=					model(**self._prepare_for_class(UpperCamelCase_     ,	UpperCamelCase_      )      )

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

              UpperCAmelCase__	:      List[Any]     							=					self.model_tester.num_stages
              self.assertEqual(len(UpperCamelCase_      )     ,	expected_num_stages + 1      )

              # RegNet'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 // 2, self.model_tester.image_size // 2]     ,	)

          UpperCAmelCase__							,							UpperCAmelCase__	:      List[Any]     							=					self.model_tester.prepare_config_and_inputs_for_common()
          UpperCAmelCase__	:      Union[str, Any]     							=					['basic', 'bottleneck']
          for model_class in self.all_model_classes:
              for layer_type in layers_type:
                  UpperCAmelCase__	:      str     							=					layer_type
                  UpperCAmelCase__	:      int     							=					True
                  check_hidden_states_output(UpperCamelCase_     ,	UpperCamelCase_     ,	UpperCamelCase_      )

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

                  check_hidden_states_output(UpperCamelCase_     ,	UpperCamelCase_     ,	UpperCamelCase_      )



      def  __snake_case							(   self      ):
          UpperCAmelCase__	:      Dict     							=					self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*UpperCamelCase_      )



      @slow
      def  __snake_case							(   self      ):
          for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              UpperCAmelCase__	:      Dict     							=					RegNetModel.from_pretrained(UpperCamelCase_      )
              self.assertIsNotNone(UpperCamelCase_      )




def 					lowerCamelCase   (     ):
    UpperCAmelCase__	:      int     							=					Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
    return image





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



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



      @slow
      def  __snake_case							(   self      ):
          UpperCAmelCase__	:      Optional[Any]     							=					RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]      ).to(UpperCamelCase_      )

          UpperCAmelCase__	:      int     							=					self.default_image_processor
          UpperCAmelCase__	:      int     							=					prepare_img()
          UpperCAmelCase__	:      List[str]     							=					image_processor(images=UpperCamelCase_     ,	return_tensors='pt'      ).to(UpperCamelCase_      )

          # forward pass
          with torch.no_grad():
              UpperCAmelCase__	:      List[Any]     							=					model(**UpperCamelCase_      )

          # verify the logits
          UpperCAmelCase__	:      Dict     							=					torch.Size((1, 1_000)      )
          self.assertEqual(outputs.logits.shape     ,	UpperCamelCase_      )

          UpperCAmelCase__	:      Optional[Any]     							=					torch.tensor([-0.4180, -1.5051, -3.4836]      ).to(UpperCamelCase_      )

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








'''simple docstring'''

from datasets.utils.patching import _PatchedModuleObj, patch_submodule

from . import _test_patching

def     __magic_name__							(				)    ->       Union[str, Any]:

   '''simple docstring'''







   import os as original_os
   from os import path as original_path
   from os import rename as original_rename
   from os.path import dirname as original_dirname
   from os.path import join as original_join

   assert _test_patching.os is original_os
   assert _test_patching.path is original_path
   assert _test_patching.join is original_join

   assert _test_patching.renamed_os is original_os
   assert _test_patching.renamed_path is original_path
   assert _test_patching.renamed_join is original_join

   __SCREAMING_SNAKE_CASE   				=							"""__test_patch_submodule_mock__"""
   with patch_submodule(_test_patching				,						"""os.path.join"""				,						__UpperCAmelCase   ):
      # Every way to access os.path.join must be patched, and the rest must stay untouched

      # check os.path.join
      assert isinstance(_test_patching.os				,						_PatchedModuleObj   )
      assert isinstance(_test_patching.os.path				,						_PatchedModuleObj   )
      assert _test_patching.os.path.join is mock

      # check path.join
      assert isinstance(_test_patching.path				,						_PatchedModuleObj   )
      assert _test_patching.path.join is mock

      # check join
      assert _test_patching.join is mock

      # check that the other attributes are untouched
      assert _test_patching.os.rename is original_rename
      assert _test_patching.path.dirname is original_dirname
      assert _test_patching.os.path.dirname is original_dirname

      # Even renamed modules or objects must be patched

      # check renamed_os.path.join
      assert isinstance(_test_patching.renamed_os				,						_PatchedModuleObj   )
      assert isinstance(_test_patching.renamed_os.path				,						_PatchedModuleObj   )
      assert _test_patching.renamed_os.path.join is mock

      # check renamed_path.join
      assert isinstance(_test_patching.renamed_path				,						_PatchedModuleObj   )
      assert _test_patching.renamed_path.join is mock

      # check renamed_join
      assert _test_patching.renamed_join is mock

      # check that the other attributes are untouched
      assert _test_patching.renamed_os.rename is original_rename
      assert _test_patching.renamed_path.dirname is original_dirname
      assert _test_patching.renamed_os.path.dirname is original_dirname

   # check that everthing is back to normal when the patch is over

   assert _test_patching.os is original_os
   assert _test_patching.path is original_path
   assert _test_patching.join is original_join

   assert _test_patching.renamed_os is original_os
   assert _test_patching.renamed_path is original_path
   assert _test_patching.renamed_join is original_join

def     __magic_name__							(				)    ->       Tuple:

   '''simple docstring'''







   assert _test_patching.open is open

   __SCREAMING_SNAKE_CASE   				=							"""__test_patch_submodule_builtin_mock__"""
   # _test_patching has "open" in its globals
   assert _test_patching.open is open
   with patch_submodule(_test_patching				,						"""open"""				,						__UpperCAmelCase   ):
      assert _test_patching.open is mock

   # check that everthing is back to normal when the patch is over

   assert _test_patching.open is open

def     __magic_name__							(				)    ->       Any:

   '''simple docstring'''







   __SCREAMING_SNAKE_CASE   				=							"""__test_patch_submodule_missing_mock__"""
   with patch_submodule(_test_patching				,						"""pandas.read_csv"""				,						__UpperCAmelCase   ):
      pass

def     __magic_name__							(				)    ->       Dict:

   '''simple docstring'''







   __SCREAMING_SNAKE_CASE   				=							"""__test_patch_submodule_missing_builtin_mock__"""
   # _test_patching doesn't have "len" in its globals
   assert getattr(_test_patching				,						"""len"""				,						__UpperCAmelCase   ) is None
   with patch_submodule(_test_patching				,						"""len"""				,						__UpperCAmelCase   ):
      assert _test_patching.len is mock
   assert _test_patching.len is len

def     __magic_name__							(				)    ->       Tuple:

   '''simple docstring'''







   __SCREAMING_SNAKE_CASE   				=							"""__test_patch_submodule_start_and_stop_mock__"""
   __SCREAMING_SNAKE_CASE   				=							patch_submodule(_test_patching				,						"""open"""				,						__UpperCAmelCase   )
   assert _test_patching.open is open
   patch.start()
   assert _test_patching.open is mock
   patch.stop()
   assert _test_patching.open is open

def     __magic_name__							(				)    ->       Union[str, Any]:

   '''simple docstring'''







   from os import rename as original_rename
   from os.path import dirname as original_dirname
   from os.path import join as original_join

   __SCREAMING_SNAKE_CASE   				=							"""__test_patch_submodule_successive_join__"""
   __SCREAMING_SNAKE_CASE   				=							"""__test_patch_submodule_successive_dirname__"""
   __SCREAMING_SNAKE_CASE   				=							"""__test_patch_submodule_successive_rename__"""
   assert _test_patching.os.path.join is original_join
   assert _test_patching.os.path.dirname is original_dirname
   assert _test_patching.os.rename is original_rename

   with patch_submodule(_test_patching				,						"""os.path.join"""				,						__UpperCAmelCase   ):
      with patch_submodule(_test_patching				,						"""os.rename"""				,						__UpperCAmelCase   ):
         with patch_submodule(_test_patching				,						"""os.path.dirname"""				,						__UpperCAmelCase   ):
            assert _test_patching.os.path.join is mock_join
            assert _test_patching.os.path.dirname is mock_dirname
            assert _test_patching.os.rename is mock_rename

    # try another order
   with patch_submodule(_test_patching				,						"""os.rename"""				,						__UpperCAmelCase   ):
      with patch_submodule(_test_patching				,						"""os.path.join"""				,						__UpperCAmelCase   ):
         with patch_submodule(_test_patching				,						"""os.path.dirname"""				,						__UpperCAmelCase   ):
            assert _test_patching.os.path.join is mock_join
            assert _test_patching.os.path.dirname is mock_dirname
            assert _test_patching.os.rename is mock_rename

   assert _test_patching.os.path.join is original_join
   assert _test_patching.os.path.dirname is original_dirname
   assert _test_patching.os.rename is original_rename







def     __magic_name__							(				)    ->       str:

   '''simple docstring'''







   __SCREAMING_SNAKE_CASE   				=							"""__test_patch_submodule_doesnt_exist_mock__"""
   with patch_submodule(_test_patching				,						"""__module_that_doesn_exist__.__attribute_that_doesn_exist__"""				,						__UpperCAmelCase   ):
      pass
   with patch_submodule(_test_patching				,						"""os.__attribute_that_doesn_exist__"""				,						__UpperCAmelCase   ):
      pass





