



"""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     UpperCAmelCase    :



   def __init__(       self    :	int							,       __lowerCamelCase    :	Optional[int]							,       __lowerCamelCase    :	List[str]=3							,       __lowerCamelCase    :	Optional[Any]=3_2							,       __lowerCamelCase    :	Optional[int]=3							,       __lowerCamelCase    :	str=1_0							,       __lowerCamelCase    :	List[str]=[1_0, 2_0, 3_0, 4_0]							,       __lowerCamelCase    :	Optional[int]=[1, 1, 2, 1]							,       __lowerCamelCase    :	Tuple=True							,       __lowerCamelCase    :	Dict=True							,       __lowerCamelCase    :	Optional[Any]="relu"							,       __lowerCamelCase    :	Optional[int]=3							,       __lowerCamelCase    :	Optional[int]=None							,       ):



     """simple docstring"""
     _snake_case   	=      parent
     _snake_case   	=      batch_size
     _snake_case   	=      image_size
     _snake_case   	=      num_channels
     _snake_case   	=      embeddings_size
     _snake_case   	=      hidden_sizes
     _snake_case   	=      depths
     _snake_case   	=      is_training
     _snake_case   	=      use_labels
     _snake_case   	=      hidden_act
     _snake_case   	=      num_labels
     _snake_case   	=      scope
     _snake_case   	=      len(__lowerCamelCase				)



   def    __UpperCAmelCase    (       self    :	Dict				):



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

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

     _snake_case   	=      self.get_config()
     return config, pixel_values, labels



   def    __UpperCAmelCase    (       self    :	List[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    :	Optional[int]							,       __lowerCamelCase    :	str							,       __lowerCamelCase    :	List[Any]							,       __lowerCamelCase    :	List[str]				):



     """simple docstring"""
     _snake_case   	=      TFRegNetModel(config=__lowerCamelCase				)
     _snake_case   	=      model(__lowerCamelCase							,       training=__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    __UpperCAmelCase    (       self    :	List[Any]							,       __lowerCamelCase    :	Optional[int]							,       __lowerCamelCase    :	Union[str, Any]							,       __lowerCamelCase    :	str				):



     """simple docstring"""
     _snake_case   	=      self.num_labels
     _snake_case   	=      TFRegNetForImageClassification(__lowerCamelCase				)
     _snake_case   	=      model(__lowerCamelCase							,       labels=__lowerCamelCase							,       training=__lowerCamelCase				)
     self.parent.assertEqual(result.logits.shape							,       (self.batch_size, self.num_labels)				)





   def    __UpperCAmelCase    (       self    :	Dict				):



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



@require_tf
class     UpperCAmelCase    (	__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE,unittest.TestCase  ):
   A__		:	Dict           =  (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
   A__		:	int           =  (
       {'''feature-extraction''': TFRegNetModel, '''image-classification''': TFRegNetForImageClassification}
       if is_tf_available()
       else {}
   )

   A__		:	Optional[Any]           =  False
   A__		:	Optional[Any]           =  False
   A__		:	Union[str, Any]           =  False
   A__		:	Optional[int]           =  False
   A__		:	List[Any]           =  False



   def    __UpperCAmelCase    (       self    :	int				):



     """simple docstring"""
     _snake_case   	=      TFRegNetModelTester(self				)
     _snake_case   	=      ConfigTester(self							,       config_class=__lowerCamelCase							,       has_text_modality=__lowerCamelCase				)



   def    __UpperCAmelCase    (       self    :	List[str]				):



     """simple docstring"""
     return



   @unittest.skip(reason='''RegNet does not use inputs_embeds'''				)
   def    __UpperCAmelCase    (       self    :	List[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    :	Union[str, Any]				):



     """simple docstring"""
     super().test_keras_fit()



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



     """simple docstring"""
     pass



   def    __UpperCAmelCase    (       self    :	int				):



     """simple docstring"""
     _snake_case	,     _snake_case   	=      self.model_tester.prepare_config_and_inputs_for_common()

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

       _snake_case   	=      ['''pixel_values''']
       self.assertListEqual(arg_names[:1]							,       __lowerCamelCase				)



   def    __UpperCAmelCase    (       self    :	Optional[int]				):



     """simple docstring"""
     _snake_case   	=      self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*__lowerCamelCase				)



   def    __UpperCAmelCase    (       self    :	Tuple				):



     """simple docstring"""
     def check_hidden_states_output(__lowerCamelCase    :	Any							,       __lowerCamelCase    :	List[Any]							,       __lowerCamelCase    :	Tuple				):
       _snake_case   	=      model_class(__lowerCamelCase				)
       _snake_case   	=      model(**self._prepare_for_class(__lowerCamelCase							,       __lowerCamelCase				)							,       training=__lowerCamelCase				)

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

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

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

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

         check_hidden_states_output(__lowerCamelCase							,       __lowerCamelCase							,       __lowerCamelCase				)



   def    __UpperCAmelCase    (       self    :	Dict				):



     """simple docstring"""
     _snake_case	,     _snake_case   	=      self.model_tester.prepare_config_and_inputs_for_common()

     def check_equivalence(__lowerCamelCase    :	List[str]							,       __lowerCamelCase    :	str							,       __lowerCamelCase    :	Union[str, Any]							,       __lowerCamelCase    :	Optional[Any]={}				):
       _snake_case   	=      model(__lowerCamelCase							,       return_dict=__lowerCamelCase							,       **__lowerCamelCase				)
       _snake_case   	=      model(__lowerCamelCase							,       return_dict=__lowerCamelCase							,       **__lowerCamelCase				).to_tuple()

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

         recursive_check(__lowerCamelCase							,       __lowerCamelCase				)

     for model_class in self.all_model_classes:
       _snake_case   	=      model_class(__lowerCamelCase				)

       _snake_case   	=      self._prepare_for_class(__lowerCamelCase							,       __lowerCamelCase				)
       _snake_case   	=      self._prepare_for_class(__lowerCamelCase							,       __lowerCamelCase				)
       check_equivalence(__lowerCamelCase							,       __lowerCamelCase							,       __lowerCamelCase				)

       _snake_case   	=      self._prepare_for_class(__lowerCamelCase							,       __lowerCamelCase							,       return_labels=__lowerCamelCase				)
       _snake_case   	=      self._prepare_for_class(__lowerCamelCase							,       __lowerCamelCase							,       return_labels=__lowerCamelCase				)
       check_equivalence(__lowerCamelCase							,       __lowerCamelCase							,       __lowerCamelCase				)

       _snake_case   	=      self._prepare_for_class(__lowerCamelCase							,       __lowerCamelCase				)
       _snake_case   	=      self._prepare_for_class(__lowerCamelCase							,       __lowerCamelCase				)
       check_equivalence(__lowerCamelCase							,       __lowerCamelCase							,       __lowerCamelCase							,       {'''output_hidden_states''': True}				)

       _snake_case   	=      self._prepare_for_class(__lowerCamelCase							,       __lowerCamelCase							,       return_labels=__lowerCamelCase				)
       _snake_case   	=      self._prepare_for_class(__lowerCamelCase							,       __lowerCamelCase							,       return_labels=__lowerCamelCase				)
       check_equivalence(__lowerCamelCase							,       __lowerCamelCase							,       __lowerCamelCase							,       {'''output_hidden_states''': True}				)



   def    __UpperCAmelCase    (       self    :	Tuple				):



     """simple docstring"""
     _snake_case   	=      self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase				)





   @slow
   def    __UpperCAmelCase    (       self    :	Any				):



     """simple docstring"""
     for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       _snake_case   	=      TFRegNetModel.from_pretrained(__lowerCamelCase				)
       self.assertIsNotNone(__lowerCamelCase				)




def 			snake_case		(		)						->				int:
  _snake_case   	=      Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''	)
  return image







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



   @cached_property
   def    __UpperCAmelCase    (       self    :	str				):



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





   @slow
   def    __UpperCAmelCase    (       self    :	Tuple				):



     """simple docstring"""
     _snake_case   	=      TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]				)

     _snake_case   	=      self.default_image_processor
     _snake_case   	=      prepare_img()
     _snake_case   	=      image_processor(images=__lowerCamelCase							,       return_tensors='''tf'''				)

     # forward pass
     _snake_case   	=      model(**__lowerCamelCase							,       training=__lowerCamelCase				)

     # verify the logits
     _snake_case   	=      tf.TensorShape((1, 1_0_0_0)				)
     self.assertEqual(outputs.logits.shape							,       __lowerCamelCase				)

     _snake_case   	=      tf.constant([-0.4_1_8_0, -1.5_0_5_1, -3.4_8_3_6]				)

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










"""simple docstring"""






def 			snake_case		(		lowerCAmelCase_  ,						lowerCAmelCase_	)						->				int:
  return 1 if input_a == input_a else 0




def 			snake_case		(		)						->				None:
  assert xnor_gate(0  ,						0	) == 1
  assert xnor_gate(0  ,						1	) == 0
  assert xnor_gate(1  ,						0	) == 0
  assert xnor_gate(1  ,						1	) == 1


if __name__ == "__main__":
     print(xnor_gate(0, 0))
     print(xnor_gate(0, 1))
     print(xnor_gate(1, 0))
     print(xnor_gate(1, 1))





