

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



    """simple docstring"""



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






         """simple docstring"""


         A__										=  parent
         A__										=  batch_size
         A__										=  image_size
         A__										=  num_channels
         A__										=  embeddings_size
         A__										=  hidden_sizes
         A__										=  depths
         A__										=  is_training
         A__										=  use_labels
         A__										=  hidden_act
         A__										=  num_labels
         A__										=  scope
         A__										=  len(UpperCamelCase       )

    def 				UpperCamelCase	(     self: Optional[int]       ):






         """simple docstring"""


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

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

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

    def 				UpperCamelCase	(     self: List[str]       ):






         """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: Any    ,						UpperCamelCase: Optional[Any]    ,						UpperCamelCase: str    ,						UpperCamelCase: int       ):






         """simple docstring"""


         A__										=  TFRegNetModel(config=UpperCamelCase       )
         A__										=  model(UpperCamelCase    ,						training=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 				UpperCamelCase	(     self: List[str]    ,						UpperCamelCase: str    ,						UpperCamelCase: List[Any]    ,						UpperCamelCase: Optional[Any]       ):






         """simple docstring"""


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





    def 				UpperCamelCase	(     self: Any       ):






         """simple docstring"""


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



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



    """simple docstring"""



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

    UpperCAmelCase						 =					False
    UpperCAmelCase						 =					False
    UpperCAmelCase						 =					False
    UpperCAmelCase						 =					False
    UpperCAmelCase						 =					False

    def 				UpperCamelCase	(     self: List[str]       ):






         """simple docstring"""


         A__										=  TFRegNetModelTester(self       )
         A__										=  ConfigTester(self    ,						config_class=UpperCamelCase    ,						has_text_modality=UpperCamelCase       )

    def 				UpperCamelCase	(     self: List[str]       ):






         """simple docstring"""


         return

    @unittest.skip(reason="""RegNet does not use inputs_embeds"""       )
    def 				UpperCamelCase	(     self: Tuple       ):






         """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: int       ):






         """simple docstring"""


         super().test_keras_fit()

    @unittest.skip(reason="""RegNet does not support input and output embeddings"""       )
    def 				UpperCamelCase	(     self: List[Any]       ):






         """simple docstring"""


         pass

    def 				UpperCamelCase	(     self: Tuple       ):






         """simple docstring"""


         A__			,				A__										=  self.model_tester.prepare_config_and_inputs_for_common()

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

              A__										=  ["""pixel_values"""]
              self.assertListEqual(arg_names[:1]    ,						UpperCamelCase       )

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






         """simple docstring"""


         A__										=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*UpperCamelCase       )

    def 				UpperCamelCase	(     self: Tuple       ):






         """simple docstring"""


         def check_hidden_states_output(UpperCamelCase: List[str]    ,						UpperCamelCase: str    ,						UpperCamelCase: Optional[int]       ):
              A__										=  model_class(UpperCamelCase       )
              A__										=  model(**self._prepare_for_class(UpperCamelCase    ,						UpperCamelCase       )    ,						training=UpperCamelCase       )

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

              A__										=  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]    ,						)

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

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

                   check_hidden_states_output(UpperCamelCase    ,						UpperCamelCase    ,						UpperCamelCase       )

    def 				UpperCamelCase	(     self: Any       ):






         """simple docstring"""


         A__			,				A__										=  self.model_tester.prepare_config_and_inputs_for_common()

         def check_equivalence(UpperCamelCase: int    ,						UpperCamelCase: int    ,						UpperCamelCase: Any    ,						UpperCamelCase: Union[str, Any]={}       ):
              A__										=  model(UpperCamelCase    ,						return_dict=UpperCamelCase    ,						**UpperCamelCase       )
              A__										=  model(UpperCamelCase    ,						return_dict=UpperCamelCase    ,						**UpperCamelCase       ).to_tuple()

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

                   recursive_check(UpperCamelCase    ,						UpperCamelCase       )

         for model_class in self.all_model_classes:
              A__										=  model_class(UpperCamelCase       )

              A__										=  self._prepare_for_class(UpperCamelCase    ,						UpperCamelCase       )
              A__										=  self._prepare_for_class(UpperCamelCase    ,						UpperCamelCase       )
              check_equivalence(UpperCamelCase    ,						UpperCamelCase    ,						UpperCamelCase       )

              A__										=  self._prepare_for_class(UpperCamelCase    ,						UpperCamelCase    ,						return_labels=UpperCamelCase       )
              A__										=  self._prepare_for_class(UpperCamelCase    ,						UpperCamelCase    ,						return_labels=UpperCamelCase       )
              check_equivalence(UpperCamelCase    ,						UpperCamelCase    ,						UpperCamelCase       )

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

              A__										=  self._prepare_for_class(UpperCamelCase    ,						UpperCamelCase    ,						return_labels=UpperCamelCase       )
              A__										=  self._prepare_for_class(UpperCamelCase    ,						UpperCamelCase    ,						return_labels=UpperCamelCase       )
              check_equivalence(UpperCamelCase    ,						UpperCamelCase    ,						UpperCamelCase    ,						{"""output_hidden_states""": True}       )

    def 				UpperCamelCase	(     self: Tuple       ):






         """simple docstring"""


         A__										=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*UpperCamelCase       )





    @slow
    def 				UpperCamelCase	(     self: int       ):






         """simple docstring"""


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





def  _snake_case     (    ):
     A__										=  Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""			)
     return image



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



    """simple docstring"""



    @cached_property
    def 				UpperCamelCase	(     self: Optional[int]       ):






         """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]       ):






         """simple docstring"""


         A__										=  TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )

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

         # forward pass
         A__										=  model(**UpperCamelCase    ,						training=UpperCamelCase       )

         # verify the logits
         A__										=  tf.TensorShape((1, 10_00)       )
         self.assertEqual(outputs.logits.shape    ,						UpperCamelCase       )

         A__										=  tf.constant([-0.4_180, -1.5_051, -3.4_836]       )

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









"""simple docstring"""



from collections.abc import Callable





def  _snake_case     (    UpperCAmelCase_  :					Callable[[float], float]					,   UpperCAmelCase_  :					float					,   UpperCAmelCase_  :					float			):
     A__										=  a
     A__										=  b
     if function(UpperCAmelCase_			) == 0:  # one of the a or b is a root for the function
          return a
     elif function(UpperCAmelCase_			) == 0:
          return b
     elif (
         function(UpperCAmelCase_			) * function(UpperCAmelCase_			) > 0
     ):  # if none of these are root and they are both positive or negative,
          # then this algorithm can't find the root
          raise ValueError("""could not find root in given interval."""			)
     else:
          A__										=  start + (end - start) / 2.0
          while abs(start - mid			) > 10**-7:  # until precisely equals to 10^-7
               if function(UpperCAmelCase_			) == 0:
                    return mid
               elif function(UpperCAmelCase_			) * function(UpperCAmelCase_			) < 0:
                    A__										=  mid
               else:
                    A__										=  mid
               A__										=  start + (end - start) / 2.0
          return mid





def  _snake_case     (    UpperCAmelCase_  :					float			):
     return x**3 - 2 * x - 5


if __name__ == "__main__":
 print(bisection(f, 1, 1_0_0_0))

 import doctest

 doctest.testmod()






