

'''simple docstring'''



from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import RegNetConfig
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 TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel


if is_vision_available():
  from PIL import Image

  from transformers import AutoImageProcessor







class 		lowerCAmelCase__  :



 """simple docstring"""



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


      """simple docstring"""




      __SCREAMING_SNAKE_CASE      = parent
      __SCREAMING_SNAKE_CASE      = batch_size
      __SCREAMING_SNAKE_CASE      = image_size
      __SCREAMING_SNAKE_CASE      = num_channels
      __SCREAMING_SNAKE_CASE      = embeddings_size
      __SCREAMING_SNAKE_CASE      = hidden_sizes
      __SCREAMING_SNAKE_CASE      = depths
      __SCREAMING_SNAKE_CASE      = is_training
      __SCREAMING_SNAKE_CASE      = use_labels
      __SCREAMING_SNAKE_CASE      = hidden_act
      __SCREAMING_SNAKE_CASE      = num_labels
      __SCREAMING_SNAKE_CASE      = scope
      __SCREAMING_SNAKE_CASE      = len(__SCREAMING_SNAKE_CASE     )
 def  UpperCAmelCase__						(						self   :			Union[str, Any]     )    ->					Tuple:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE      = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

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

      __SCREAMING_SNAKE_CASE      = self.get_config()
      return config, pixel_values, labels
 def  UpperCAmelCase__						(						self   :			Dict     )    ->					Any:


      """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  UpperCAmelCase__						(						self   :			List[str]   ,				__SCREAMING_SNAKE_CASE   :			Union[str, Any]   ,				__SCREAMING_SNAKE_CASE   :			Dict   ,				__SCREAMING_SNAKE_CASE   :			List[Any]     )    ->					List[str]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE      = TFRegNetModel(config=__SCREAMING_SNAKE_CASE     )
      __SCREAMING_SNAKE_CASE      = model(__SCREAMING_SNAKE_CASE   ,				training=__SCREAMING_SNAKE_CASE     )
      # 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   :			Tuple   ,				__SCREAMING_SNAKE_CASE   :			Union[str, Any]   ,				__SCREAMING_SNAKE_CASE   :			Optional[int]   ,				__SCREAMING_SNAKE_CASE   :			Dict     )    ->					int:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE      = self.num_labels
      __SCREAMING_SNAKE_CASE      = TFRegNetForImageClassification(__SCREAMING_SNAKE_CASE     )
      __SCREAMING_SNAKE_CASE      = model(__SCREAMING_SNAKE_CASE   ,				labels=__SCREAMING_SNAKE_CASE   ,				training=__SCREAMING_SNAKE_CASE     )
      self.parent.assertEqual(result.logits.shape   ,				(self.batch_size, self.num_labels)     )


 def  UpperCAmelCase__						(						self   :			List[Any]     )    ->					int:


      """simple docstring"""




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







@require_tf
class 		lowerCAmelCase__  ( a					,   a					,   unittest.TestCase   ):



 """simple docstring"""



 lowerCAmelCase__       = (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
 lowerCAmelCase__       = (
     {"feature-extraction": TFRegNetModel, "image-classification": TFRegNetForImageClassification}
     if is_tf_available()
     else {}
 )

 lowerCAmelCase__       = False
 lowerCAmelCase__       = False
 lowerCAmelCase__       = False
 lowerCAmelCase__       = False
 lowerCAmelCase__       = False
 def  UpperCAmelCase__						(						self   :			List[str]     )    ->					Tuple:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE      = TFRegNetModelTester(self     )
      __SCREAMING_SNAKE_CASE      = ConfigTester(self   ,				config_class=__SCREAMING_SNAKE_CASE   ,				has_text_modality=__SCREAMING_SNAKE_CASE     )
 def  UpperCAmelCase__						(						self   :			int     )    ->					Optional[int]:


      """simple docstring"""




      return
 @unittest.skip(reason="""RegNet does not use inputs_embeds"""     )
 def  UpperCAmelCase__						(						self   :			Dict     )    ->					Optional[Any]:


      """simple docstring"""




      pass
 @unittest.skipIf(
     not is_tf_available() or len(tf.config.list_physical_devices("""GPU"""     )     ) == 0   ,				reason="""TF does not support backprop for grouped convolutions on CPU."""   ,				)
 @slow
 def  UpperCAmelCase__						(						self   :			Optional[Any]     )    ->					Any:


      """simple docstring"""




      super().test_keras_fit()
 @unittest.skip(reason="""RegNet does not support input and output embeddings"""     )
 def  UpperCAmelCase__						(						self   :			List[str]     )    ->					Dict:


      """simple docstring"""




      pass
 def  UpperCAmelCase__						(						self   :			str     )    ->					List[str]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE  ,     __SCREAMING_SNAKE_CASE      = self.model_tester.prepare_config_and_inputs_for_common()

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

           __SCREAMING_SNAKE_CASE      = ["""pixel_values"""]
           self.assertListEqual(arg_names[:1]   ,				__SCREAMING_SNAKE_CASE     )
 def  UpperCAmelCase__						(						self   :			Any     )    ->					str:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE      = self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE     )
 def  UpperCAmelCase__						(						self   :			Union[str, Any]     )    ->					Optional[int]:


      """simple docstring"""




      def check_hidden_states_output(__SCREAMING_SNAKE_CASE   :			Any   ,				__SCREAMING_SNAKE_CASE   :			Union[str, Any]   ,				__SCREAMING_SNAKE_CASE   :			Tuple     ):
           __SCREAMING_SNAKE_CASE      = model_class(__SCREAMING_SNAKE_CASE     )
           __SCREAMING_SNAKE_CASE      = model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE   ,				__SCREAMING_SNAKE_CASE     )   ,				training=__SCREAMING_SNAKE_CASE     )

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

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

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

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

                check_hidden_states_output(__SCREAMING_SNAKE_CASE   ,				__SCREAMING_SNAKE_CASE   ,				__SCREAMING_SNAKE_CASE     )
 def  UpperCAmelCase__						(						self   :			Any     )    ->					Union[str, Any]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE  ,     __SCREAMING_SNAKE_CASE      = self.model_tester.prepare_config_and_inputs_for_common()

      def check_equivalence(__SCREAMING_SNAKE_CASE   :			Optional[int]   ,				__SCREAMING_SNAKE_CASE   :			Tuple   ,				__SCREAMING_SNAKE_CASE   :			Optional[Any]   ,				__SCREAMING_SNAKE_CASE   :			Tuple={}     ):
           __SCREAMING_SNAKE_CASE      = model(__SCREAMING_SNAKE_CASE   ,				return_dict=__SCREAMING_SNAKE_CASE   ,				**__SCREAMING_SNAKE_CASE     )
           __SCREAMING_SNAKE_CASE      = model(__SCREAMING_SNAKE_CASE   ,				return_dict=__SCREAMING_SNAKE_CASE   ,				**__SCREAMING_SNAKE_CASE     ).to_tuple()

           def recursive_check(__SCREAMING_SNAKE_CASE   :			int   ,				__SCREAMING_SNAKE_CASE   :			Optional[int]     ):
                if isinstance(__SCREAMING_SNAKE_CASE   ,				(List, Tuple)     ):
                     for tuple_iterable_value, dict_iterable_value in zip(__SCREAMING_SNAKE_CASE   ,				__SCREAMING_SNAKE_CASE     ):
                          recursive_check(__SCREAMING_SNAKE_CASE   ,				__SCREAMING_SNAKE_CASE     )
                elif tuple_object is None:
                     return
                else:
                     self.assertTrue(
                         all(tf.equal(__SCREAMING_SNAKE_CASE   ,				__SCREAMING_SNAKE_CASE     )     )   ,				msg=(
                             """Tuple and dict output are not equal. Difference:"""
                             f' {tf.math.reduce_max(tf.abs(tuple_object - dict_object     )     )}'
                         )   ,				)

                recursive_check(__SCREAMING_SNAKE_CASE   ,				__SCREAMING_SNAKE_CASE     )

      for model_class in self.all_model_classes:
           __SCREAMING_SNAKE_CASE      = model_class(__SCREAMING_SNAKE_CASE     )

           __SCREAMING_SNAKE_CASE      = self._prepare_for_class(__SCREAMING_SNAKE_CASE   ,				__SCREAMING_SNAKE_CASE     )
           __SCREAMING_SNAKE_CASE      = self._prepare_for_class(__SCREAMING_SNAKE_CASE   ,				__SCREAMING_SNAKE_CASE     )
           check_equivalence(__SCREAMING_SNAKE_CASE   ,				__SCREAMING_SNAKE_CASE   ,				__SCREAMING_SNAKE_CASE     )

           __SCREAMING_SNAKE_CASE      = self._prepare_for_class(__SCREAMING_SNAKE_CASE   ,				__SCREAMING_SNAKE_CASE   ,				return_labels=__SCREAMING_SNAKE_CASE     )
           __SCREAMING_SNAKE_CASE      = self._prepare_for_class(__SCREAMING_SNAKE_CASE   ,				__SCREAMING_SNAKE_CASE   ,				return_labels=__SCREAMING_SNAKE_CASE     )
           check_equivalence(__SCREAMING_SNAKE_CASE   ,				__SCREAMING_SNAKE_CASE   ,				__SCREAMING_SNAKE_CASE     )

           __SCREAMING_SNAKE_CASE      = self._prepare_for_class(__SCREAMING_SNAKE_CASE   ,				__SCREAMING_SNAKE_CASE     )
           __SCREAMING_SNAKE_CASE      = self._prepare_for_class(__SCREAMING_SNAKE_CASE   ,				__SCREAMING_SNAKE_CASE     )
           check_equivalence(__SCREAMING_SNAKE_CASE   ,				__SCREAMING_SNAKE_CASE   ,				__SCREAMING_SNAKE_CASE   ,				{"""output_hidden_states""": True}     )

           __SCREAMING_SNAKE_CASE      = self._prepare_for_class(__SCREAMING_SNAKE_CASE   ,				__SCREAMING_SNAKE_CASE   ,				return_labels=__SCREAMING_SNAKE_CASE     )
           __SCREAMING_SNAKE_CASE      = self._prepare_for_class(__SCREAMING_SNAKE_CASE   ,				__SCREAMING_SNAKE_CASE   ,				return_labels=__SCREAMING_SNAKE_CASE     )
           check_equivalence(__SCREAMING_SNAKE_CASE   ,				__SCREAMING_SNAKE_CASE   ,				__SCREAMING_SNAKE_CASE   ,				{"""output_hidden_states""": True}     )
 def  UpperCAmelCase__						(						self   :			Any     )    ->					int:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE      = self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*__SCREAMING_SNAKE_CASE     )


 @slow
 def  UpperCAmelCase__						(						self   :			List[str]     )    ->					Any:


      """simple docstring"""




      for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           __SCREAMING_SNAKE_CASE      = TFRegNetModel.from_pretrained(__SCREAMING_SNAKE_CASE     )
           self.assertIsNotNone(__SCREAMING_SNAKE_CASE     )







def   a__			(    ):




     """simple docstring"""


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







@require_tf
@require_vision
class 		lowerCAmelCase__  ( unittest.TestCase   ):



 """simple docstring"""



 @cached_property
 def  UpperCAmelCase__						(						self   :			Optional[Any]     )    ->					str:


      """simple docstring"""




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


 @slow
 def  UpperCAmelCase__						(						self   :			Optional[int]     )    ->					str:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE      = TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]     )

      __SCREAMING_SNAKE_CASE      = self.default_image_processor
      __SCREAMING_SNAKE_CASE      = prepare_img()
      __SCREAMING_SNAKE_CASE      = image_processor(images=__SCREAMING_SNAKE_CASE   ,				return_tensors="""tf"""     )

      # forward pass
      __SCREAMING_SNAKE_CASE      = model(**__SCREAMING_SNAKE_CASE   ,				training=__SCREAMING_SNAKE_CASE     )

      # verify the logits
      __SCREAMING_SNAKE_CASE      = tf.TensorShape((1, 1_000)     )
      self.assertEqual(outputs.logits.shape   ,				__SCREAMING_SNAKE_CASE     )

      __SCREAMING_SNAKE_CASE      = tf.constant([-0.4180, -1.5051, -3.4836]     )

      tf.debugging.assert_near(outputs.logits[0, :3]   ,				__SCREAMING_SNAKE_CASE   ,				atol=1E-4     )









'''simple docstring'''



from typing import Optional, Union

import torch
from torch import nn

from ...configuration_utils import ConfigMixin, register_to_config
from ...models.modeling_utils import ModelMixin







class 		lowerCAmelCase__  ( a					,   a   ):



 """simple docstring"""



 @register_to_config
 def __init__(						self   :			int   ,				__SCREAMING_SNAKE_CASE   :			int = 768   ,				)    ->					int:


      """simple docstring"""




      super().__init__()

      __SCREAMING_SNAKE_CASE      = nn.Parameter(torch.zeros(1   ,				__SCREAMING_SNAKE_CASE     )     )
      __SCREAMING_SNAKE_CASE      = nn.Parameter(torch.ones(1   ,				__SCREAMING_SNAKE_CASE     )     )
 def  UpperCAmelCase__						(						self   :			Any   ,				__SCREAMING_SNAKE_CASE   :			Optional[Union[str, torch.device]] = None   ,				__SCREAMING_SNAKE_CASE   :			Optional[torch.dtype] = None   ,				)    ->					List[str]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE      = nn.Parameter(self.mean.to(__SCREAMING_SNAKE_CASE     ).to(__SCREAMING_SNAKE_CASE     )     )
      __SCREAMING_SNAKE_CASE      = nn.Parameter(self.std.to(__SCREAMING_SNAKE_CASE     ).to(__SCREAMING_SNAKE_CASE     )     )
      return self
 def  UpperCAmelCase__						(						self   :			Optional[Any]   ,				__SCREAMING_SNAKE_CASE   :			Optional[int]     )    ->					Optional[int]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE      = (embeds - self.mean) * 1.0 / self.std
      return embeds


 def  UpperCAmelCase__						(						self   :			Tuple   ,				__SCREAMING_SNAKE_CASE   :			Any     )    ->					Optional[int]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE      = (embeds * self.std) + self.mean
      return embeds






