



"""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	:      Dict	,      A	:      List[str]	,      A	:      List[str]=3	,      A	:      Any=3_2	,      A	:      int=3	,      A	:      str=1_0	,      A	:      Dict=[1_0, 2_0, 3_0, 4_0]	,      A	:      int=[1, 1, 2, 1]	,      A	:      Optional[Any]=True	,      A	:      str=True	,      A	:      List[Any]="relu"	,      A	:      Any=3	,      A	:      str=None	,      ):
           _UpperCAmelCase     :      Optional[Any]														=       parent
           _UpperCAmelCase     :      Dict														=       batch_size
           _UpperCAmelCase     :      Optional[int]														=       image_size
           _UpperCAmelCase     :      Tuple														=       num_channels
           _UpperCAmelCase     :      Union[str, Any]														=       embeddings_size
           _UpperCAmelCase     :      int														=       hidden_sizes
           _UpperCAmelCase     :      Dict														=       depths
           _UpperCAmelCase     :      Any														=       is_training
           _UpperCAmelCase     :      Optional[int]														=       use_labels
           _UpperCAmelCase     :      Any														=       hidden_act
           _UpperCAmelCase     :      List[str]														=       num_labels
           _UpperCAmelCase     :      Any														=       scope
           _UpperCAmelCase     :      Dict														=       len(_lowercase		)



      def 		snake_case_   (	self	:      str		):
           _UpperCAmelCase     :      List[Any]														=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

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

           _UpperCAmelCase     :      Optional[Any]														=       self.get_config()
           return config, pixel_values, labels



      def 		snake_case_   (	self	:      Optional[Any]		):
           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	:      int	,      A	:      int	,      A	:      List[str]	,      A	:      Optional[Any]		):
           _UpperCAmelCase     :      str														=       TFRegNetModel(config=_lowercase		)
           _UpperCAmelCase     :      Dict														=       model(_lowercase	,      training=_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 // 3_2, self.image_size // 3_2)	,      )



      def 		snake_case_   (	self	:      Dict	,      A	:      str	,      A	:      Optional[int]	,      A	:      str		):
           _UpperCAmelCase     :      Tuple														=       self.num_labels
           _UpperCAmelCase     :      str														=       TFRegNetForImageClassification(_lowercase		)
           _UpperCAmelCase     :      List[str]														=       model(_lowercase	,      labels=_lowercase	,      training=_lowercase		)
           self.parent.assertEqual(result.logits.shape	,      (self.batch_size, self.num_labels)		)



      def 		snake_case_   (	self	:      Any		):
           _UpperCAmelCase     :      Optional[Any]														=       self.prepare_config_and_inputs()
           _UpperCAmelCase							,			_UpperCAmelCase							,			_UpperCAmelCase     :      Tuple														=       config_and_inputs
           _UpperCAmelCase     :      List[Any]														=       {"pixel_values": pixel_values}
           return config, inputs_dict







@require_tf
class       UpperCAmelCase_    (							_UpperCamelCase			,     _UpperCamelCase			,     unittest.TestCase		):
      __SCREAMING_SNAKE_CASE		:  Dict						=					(TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
      __SCREAMING_SNAKE_CASE		:  str						=					(
          {"""feature-extraction""": TFRegNetModel, """image-classification""": TFRegNetForImageClassification}
          if is_tf_available()
          else {}
      )

      __SCREAMING_SNAKE_CASE		:  Union[str, Any]						=					False
      __SCREAMING_SNAKE_CASE		:  Dict						=					False
      __SCREAMING_SNAKE_CASE		:  List[Any]						=					False
      __SCREAMING_SNAKE_CASE		:  Optional[Any]						=					False
      __SCREAMING_SNAKE_CASE		:  Optional[Any]						=					False



      def 		snake_case_   (	self	:      Optional[int]		):
           _UpperCAmelCase     :      List[Any]														=       TFRegNetModelTester(self		)
           _UpperCAmelCase     :      Any														=       ConfigTester(self	,      config_class=_lowercase	,      has_text_modality=_lowercase		)



      def 		snake_case_   (	self	:      List[str]		):
           return



      @unittest.skip(reason="RegNet does not use inputs_embeds"		)
      def 		snake_case_   (	self	:      List[Any]		):
           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 		snake_case_   (	self	:      int		):
           super().test_keras_fit()



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



      def 		snake_case_   (	self	:      List[str]		):
           _UpperCAmelCase							,			_UpperCAmelCase     :      Dict														=       self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                _UpperCAmelCase     :      Union[str, Any]														=       model_class(_lowercase		)
                _UpperCAmelCase     :      List[str]														=       inspect.signature(model.call		)
                # signature.parameters is an OrderedDict => so arg_names order is deterministic
                _UpperCAmelCase     :      Tuple														=       [*signature.parameters.keys()]

                _UpperCAmelCase     :      Union[str, Any]														=       ["pixel_values"]
                self.assertListEqual(arg_names[:1]	,      _lowercase		)



      def 		snake_case_   (	self	:      List[Any]		):
           _UpperCAmelCase     :      List[str]														=       self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*_lowercase		)



      def 		snake_case_   (	self	:      Optional[Any]		):
           def check_hidden_states_output(A	:      Optional[Any]	,      A	:      str	,      A	:      List[str]		):
                _UpperCAmelCase     :      str														=       model_class(_lowercase		)
                _UpperCAmelCase     :      Any														=       model(**self._prepare_for_class(_lowercase	,      _lowercase		)	,      training=_lowercase		)

                _UpperCAmelCase     :      Optional[int]														=       outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                _UpperCAmelCase     :      int														=       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]	,      )

           _UpperCAmelCase							,			_UpperCAmelCase     :      Optional[int]														=       self.model_tester.prepare_config_and_inputs_for_common()
           _UpperCAmelCase     :      Optional[Any]														=       ["basic", "bottleneck"]
           for model_class in self.all_model_classes:
                for layer_type in layers_type:
                     _UpperCAmelCase     :      int														=       layer_type
                     _UpperCAmelCase     :      List[str]														=       True
                     check_hidden_states_output(_lowercase	,      _lowercase	,      _lowercase		)

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

                     check_hidden_states_output(_lowercase	,      _lowercase	,      _lowercase		)



      def 		snake_case_   (	self	:      Union[str, Any]		):
           _UpperCAmelCase							,			_UpperCAmelCase     :      Dict														=       self.model_tester.prepare_config_and_inputs_for_common()

           def check_equivalence(A	:      Any	,      A	:      List[str]	,      A	:      Optional[int]	,      A	:      Dict={}		):
                _UpperCAmelCase     :      Any														=       model(_lowercase	,      return_dict=_lowercase	,      **_lowercase		)
                _UpperCAmelCase     :      Dict														=       model(_lowercase	,      return_dict=_lowercase	,      **_lowercase		).to_tuple()

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

                     recursive_check(_lowercase	,      _lowercase		)

           for model_class in self.all_model_classes:
                _UpperCAmelCase     :      Dict														=       model_class(_lowercase		)

                _UpperCAmelCase     :      Dict														=       self._prepare_for_class(_lowercase	,      _lowercase		)
                _UpperCAmelCase     :      Optional[int]														=       self._prepare_for_class(_lowercase	,      _lowercase		)
                check_equivalence(_lowercase	,      _lowercase	,      _lowercase		)

                _UpperCAmelCase     :      Dict														=       self._prepare_for_class(_lowercase	,      _lowercase	,      return_labels=_lowercase		)
                _UpperCAmelCase     :      Union[str, Any]														=       self._prepare_for_class(_lowercase	,      _lowercase	,      return_labels=_lowercase		)
                check_equivalence(_lowercase	,      _lowercase	,      _lowercase		)

                _UpperCAmelCase     :      Optional[int]														=       self._prepare_for_class(_lowercase	,      _lowercase		)
                _UpperCAmelCase     :      List[Any]														=       self._prepare_for_class(_lowercase	,      _lowercase		)
                check_equivalence(_lowercase	,      _lowercase	,      _lowercase	,      {"output_hidden_states": True}		)

                _UpperCAmelCase     :      Optional[int]														=       self._prepare_for_class(_lowercase	,      _lowercase	,      return_labels=_lowercase		)
                _UpperCAmelCase     :      Dict														=       self._prepare_for_class(_lowercase	,      _lowercase	,      return_labels=_lowercase		)
                check_equivalence(_lowercase	,      _lowercase	,      _lowercase	,      {"output_hidden_states": True}		)



      def 		snake_case_   (	self	:      int		):
           _UpperCAmelCase     :      Tuple														=       self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*_lowercase		)



      @slow
      def 		snake_case_   (	self	:      Optional[int]		):
           for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                _UpperCAmelCase     :      Optional[int]														=       TFRegNetModel.from_pretrained(_lowercase		)
                self.assertIsNotNone(_lowercase		)







def 		__snake_case		( )    ->  str:





     '''simple docstring'''

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






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



      @cached_property
      def 		snake_case_   (	self	:      Optional[int]		):
           return (
               AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]		)
               if is_vision_available()
               else None
           )



      @slow
      def 		snake_case_   (	self	:      List[Any]		):
           _UpperCAmelCase     :      List[str]														=       TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]		)

           _UpperCAmelCase     :      str														=       self.default_image_processor
           _UpperCAmelCase     :      str														=       prepare_img()
           _UpperCAmelCase     :      Dict														=       image_processor(images=_lowercase	,      return_tensors="tf"		)

           # forward pass
           _UpperCAmelCase     :      List[Any]														=       model(**_lowercase	,      training=_lowercase		)

           # verify the logits
           _UpperCAmelCase     :      int														=       tf.TensorShape((1, 1_0_0_0)		)
           self.assertEqual(outputs.logits.shape	,      _lowercase		)

           _UpperCAmelCase     :      Optional[Any]														=       tf.constant([-0.4_180, -1.5_051, -3.4_836]		)

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



def 			lowerCAmelCase(      SCREAMING_SNAKE_CASE_			)->						list:



    """simple docstring"""






    if bit_count < 0:
        raise ValueError("The given input must be positive"			)

    # get the generated string sequence
    UpperCamelCase_			  =						gray_code_sequence_string(SCREAMING_SNAKE_CASE_			)
    #
    # convert them to integers
    for i in range(len(SCREAMING_SNAKE_CASE_			)			):
        UpperCamelCase_			  =						int(sequence[i]			,						2			)

    return sequence




def 			lowerCAmelCase(      SCREAMING_SNAKE_CASE_			)->						list:



    """simple docstring"""






    if bit_count == 0:
        return ["0"]

    if bit_count == 1:
        return ["0", "1"]

    UpperCamelCase_			  =						1 << bit_count  # defines the length of the sequence
    # 1<< n is equivalent to 2^n

    # recursive answer will generate answer for n-1 bits
    UpperCamelCase_			  =						gray_code_sequence_string(bit_count - 1			)

    UpperCamelCase_			  =						[]

    # append 0 to first half of the smaller sequence generated
    for i in range(seq_len // 2			):
        UpperCamelCase_			  =						"0" + smaller_sequence[i]
        sequence.append(SCREAMING_SNAKE_CASE_			)

    # append 1 to second half ... start from the end of the list
    for i in reversed(range(seq_len // 2			)			):
        UpperCamelCase_			  =						"1" + smaller_sequence[i]
        sequence.append(SCREAMING_SNAKE_CASE_			)

    return sequence


if __name__ == "__main__":
 import doctest

 doctest.testmod()
