




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






      def __init__( self   :  Any						,						lowercase__   :  Union[str, Any]						,						lowercase__   :  Tuple=3						,						lowercase__   :  Dict=32						,						lowercase__   :  List[str]=3						,						lowercase__   :  Optional[Any]=10						,						lowercase__   :  Optional[Any]=[10, 20, 30, 40]						,						lowercase__   :  Tuple=[1, 1, 2, 1]						,						lowercase__   :  List[Any]=True						,						lowercase__   :  int=True						,						lowercase__   :  Tuple="relu"						,						lowercase__   :  Optional[Any]=3						,						lowercase__   :  Tuple=None						,						):


           '''simple docstring'''

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






      def 							lowercase_						( self   :  List[Any]       ):


           '''simple docstring'''

           a_     :							Union[str, Any]     						=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

           a_     :							Any     						=  None
           if self.use_labels:
                a_     :							List[str]     						=  ids_tensor([self.batch_size]						,						self.num_labels       )

           a_     :							int     						=  self.get_config()

           return config, pixel_values, labels






      def 							lowercase_						( self   :  Optional[int]       ):


           '''simple docstring'''

           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 							lowercase_						( self   :  Any						,						lowercase__   :  Any						,						lowercase__   :  Dict						,						lowercase__   :  List[str]       ):


           '''simple docstring'''

           a_     :							str     						=  RegNetModel(config=lowercase__       )
           model.to(lowercase__       )
           model.eval()
           a_     :							str     						=  model(lowercase__       )
           # 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 							lowercase_						( self   :  Optional[int]						,						lowercase__   :  Dict						,						lowercase__   :  int						,						lowercase__   :  List[Any]       ):


           '''simple docstring'''

           a_     :							List[str]     						=  self.num_labels
           a_     :							List[Any]     						=  RegNetForImageClassification(lowercase__       )
           model.to(lowercase__       )
           model.eval()
           a_     :							str     						=  model(lowercase__						,						labels=lowercase__       )
           self.parent.assertEqual(result.logits.shape						,						(self.batch_size, self.num_labels)       )






      def 							lowercase_						( self   :  Tuple       ):


           '''simple docstring'''

           a_     :							Optional[int]     						=  self.prepare_config_and_inputs()
           a_						,     a_						,     a_     :							Optional[Any]     						=  config_and_inputs
           a_     :							Tuple     						=  {"""pixel_values""": pixel_values}
           return config, inputs_dict







@require_torch
class      SCREAMING_SNAKE_CASE    (						snake_case_							,      snake_case_							,      unittest.TestCase				):
      __magic_name__  :       Tuple   							=					(RegNetModel, RegNetForImageClassification) if is_torch_available() else ()
      __magic_name__  :       int   							=					(
          {'''feature-extraction''': RegNetModel, '''image-classification''': RegNetForImageClassification}
          if is_torch_available()
          else {}
      )

      __magic_name__  :       Dict   							=					False
      __magic_name__  :       Optional[int]   							=					False
      __magic_name__  :       Dict   							=					False
      __magic_name__  :       Any   							=					False






      def 							lowercase_						( self   :  Union[str, Any]       ):


           '''simple docstring'''

           a_     :							List[str]     						=  RegNetModelTester(self       )
           a_     :							Union[str, Any]     						=  ConfigTester(self						,						config_class=lowercase__						,						has_text_modality=lowercase__       )






      def 							lowercase_						( self   :  List[Any]       ):


           '''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 							lowercase_						( self   :  Tuple       ):


           '''simple docstring'''

           return






      @unittest.skip(reason="""RegNet does not use inputs_embeds"""       )
      def 							lowercase_						( self   :  List[str]       ):


           '''simple docstring'''

           pass






      @unittest.skip(reason="""RegNet does not support input and output embeddings"""       )
      def 							lowercase_						( self   :  int       ):


           '''simple docstring'''

           pass






      def 							lowercase_						( self   :  int       ):


           '''simple docstring'''

           a_						,     a_     :							Dict     						=  self.model_tester.prepare_config_and_inputs_for_common()

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

                a_     :							Optional[int]     						=  ["""pixel_values"""]
                self.assertListEqual(arg_names[:1]						,						lowercase__       )






      def 							lowercase_						( self   :  Any       ):


           '''simple docstring'''

           a_     :							Optional[int]     						=  self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*lowercase__       )






      def 							lowercase_						( self   :  Union[str, Any]       ):


           '''simple docstring'''

           a_						,     a_     :							List[str]     						=  self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                a_     :							str     						=  model_class(config=lowercase__       )
                for name, module in model.named_modules():
                     if isinstance(lowercase__						,						(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 							lowercase_						( self   :  Any       ):


           '''simple docstring'''

           def check_hidden_states_output(lowercase__   :  Union[str, Any]						,						lowercase__   :  Dict						,						lowercase__   :  Any       ):
                a_     :							str     						=  model_class(lowercase__       )
                model.to(lowercase__       )
                model.eval()

                with torch.no_grad():
                     a_     :							Optional[int]     						=  model(**self._prepare_for_class(lowercase__						,						lowercase__       )       )

                a_     :							int     						=  outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                a_     :							Dict     						=  self.model_tester.num_stages
                self.assertEqual(len(lowercase__       )						,						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]						,						)

           a_						,     a_     :							str     						=  self.model_tester.prepare_config_and_inputs_for_common()
           a_     :							str     						=  ["""basic""", """bottleneck"""]
           for model_class in self.all_model_classes:
                for layer_type in layers_type:
                     a_     :							Dict     						=  layer_type
                     a_     :							Optional[int]     						=  True
                     check_hidden_states_output(lowercase__						,						lowercase__						,						lowercase__       )

                     # check that output_hidden_states also work using config
                     del inputs_dict["output_hidden_states"]
                     a_     :							Union[str, Any]     						=  True

                     check_hidden_states_output(lowercase__						,						lowercase__						,						lowercase__       )






      def 							lowercase_						( self   :  Dict       ):


           '''simple docstring'''

           a_     :							Union[str, Any]     						=  self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*lowercase__       )






      @slow
      def 							lowercase_						( self   :  List[str]       ):


           '''simple docstring'''

           for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                a_     :							Tuple     						=  RegNetModel.from_pretrained(lowercase__       )
                self.assertIsNotNone(lowercase__       )



def  _SCREAMING_SNAKE_CASE     (      ):




     """simple docstring"""


     a_     :							List[str]     						=  Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""				)
     return image







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






      @cached_property
      def 							lowercase_						( self   :  List[Any]       ):


           '''simple docstring'''

           return (
               AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )
               if is_vision_available()
               else None
           )






      @slow
      def 							lowercase_						( self   :  Tuple       ):


           '''simple docstring'''

           a_     :							str     						=  RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]       ).to(lowercase__       )

           a_     :							Tuple     						=  self.default_image_processor
           a_     :							str     						=  prepare_img()
           a_     :							int     						=  image_processor(images=lowercase__						,						return_tensors="""pt"""       ).to(lowercase__       )

           # forward pass
           with torch.no_grad():
                a_     :							Tuple     						=  model(**lowercase__       )

           # verify the logits
           a_     :							Tuple     						=  torch.Size((1, 1000)       )
           self.assertEqual(outputs.logits.shape						,						lowercase__       )

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

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






'''simple docstring'''


from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_torch_available,
    is_vision_available,
)


lowerCAmelCase_      :  Optional[Any]				     =  {
    'configuration_mobilevit': ['MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MobileViTConfig', 'MobileViTOnnxConfig'],
}

try:
 if not is_vision_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 lowerCAmelCase_      :  int				     =  ['MobileViTFeatureExtractor']
 lowerCAmelCase_      :  int				     =  ['MobileViTImageProcessor']

try:
 if not is_torch_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 lowerCAmelCase_      :  str				     =  [
     'MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST',
     'MobileViTForImageClassification',
     'MobileViTForSemanticSegmentation',
     'MobileViTModel',
     'MobileViTPreTrainedModel',
 ]

try:
 if not is_tf_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 lowerCAmelCase_      :  Optional[Any]				     =  [
     'TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST',
     'TFMobileViTForImageClassification',
     'TFMobileViTForSemanticSegmentation',
     'TFMobileViTModel',
     'TFMobileViTPreTrainedModel',
 ]

if TYPE_CHECKING:
 from .configuration_mobilevit import MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileViTConfig, MobileViTOnnxConfig

 try:
  if not is_vision_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .feature_extraction_mobilevit import MobileViTFeatureExtractor
  from .image_processing_mobilevit import MobileViTImageProcessor

 try:
  if not is_torch_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_mobilevit import (
      MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST,
      MobileViTForImageClassification,
      MobileViTForSemanticSegmentation,
      MobileViTModel,
      MobileViTPreTrainedModel,
  )

 try:
  if not is_tf_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_tf_mobilevit import (
      TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST,
      TFMobileViTForImageClassification,
      TFMobileViTForSemanticSegmentation,
      TFMobileViTModel,
      TFMobileViTPreTrainedModel,
  )


else:
 import sys

 lowerCAmelCase_      :  List[Any]				     =  _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
