




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 						__lowercase		:




      """simple docstring"""





      def __init__(				self    ,				A    ,				A=3    ,				A=3_2    ,				A=3    ,				A=1_0    ,				A=[1_0, 2_0, 3_0, 4_0]    ,				A=[1, 1, 2, 1]    ,				A=True    ,				A=True    ,				A="relu"    ,				A=3    ,				A=None    ,				)		->    Optional[Any]:
         snake_case				:    str           =	parent
         snake_case				:    Union[str, Any]           =	batch_size
         snake_case				:    List[str]           =	image_size
         snake_case				:    int           =	num_channels
         snake_case				:    Any           =	embeddings_size
         snake_case				:    Dict           =	hidden_sizes
         snake_case				:    Any           =	depths
         snake_case				:    List[str]           =	is_training
         snake_case				:    Optional[int]           =	use_labels
         snake_case				:    Optional[Any]           =	hidden_act
         snake_case				:    List[str]           =	num_labels
         snake_case				:    Optional[Any]           =	scope
         snake_case				:    List[Any]           =	len(A     )

      def      UpperCAmelCase				(				self     )		->    Tuple:
         snake_case				:    Dict           =	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

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

         snake_case				:    Optional[int]           =	self.get_config()
         return config, pixel_values, labels

      def      UpperCAmelCase				(				self     )		->    Tuple:
         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    ,				A    ,				A    ,				A     )		->    List[Any]:
         snake_case				:    str           =	TFRegNetModel(config=A     )
         snake_case				:    int           =	model(A    ,				training=A     )
         # 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    ,				A    ,				A    ,				A     )		->    Optional[int]:
         snake_case				:    Dict           =	self.num_labels
         snake_case				:    List[Any]           =	TFRegNetForImageClassification(A     )
         snake_case				:    Tuple           =	model(A    ,				labels=A    ,				training=A     )
         self.parent.assertEqual(result.logits.shape    ,				(self.batch_size, self.num_labels)     )

      def      UpperCAmelCase				(				self     )		->    int:
         snake_case				:    Optional[Any]           =	self.prepare_config_and_inputs()
         snake_case     , snake_case     , snake_case				:    Any           =	config_and_inputs
         snake_case				:    List[str]           =	{"""pixel_values""": pixel_values}
         return config, inputs_dict




@require_tf
class 						__lowercase		(UpperCamelCase__					,		UpperCamelCase__					,		unittest.TestCase							):




      """simple docstring"""





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

      _snake_case												=						False
      _snake_case												=						False
      _snake_case												=						False
      _snake_case												=						False
      _snake_case												=						False

      def      UpperCAmelCase				(				self     )		->    Tuple:
         snake_case				:    Any           =	TFRegNetModelTester(self     )
         snake_case				:    int           =	ConfigTester(self    ,				config_class=A    ,				has_text_modality=A     )

      def      UpperCAmelCase				(				self     )		->    Tuple:
         return

      @unittest.skip(reason="""RegNet does not use inputs_embeds"""     )
      def      UpperCAmelCase				(				self     )		->    Dict:
         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     )		->    Tuple:
         super().test_keras_fit()

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

      def      UpperCAmelCase				(				self     )		->    Dict:
         snake_case     , snake_case				:    Optional[Any]           =	self.model_tester.prepare_config_and_inputs_for_common()

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

            snake_case				:    Dict           =	["""pixel_values"""]
            self.assertListEqual(arg_names[:1]    ,				A     )

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

      def      UpperCAmelCase				(				self     )		->    Any:
         def check_hidden_states_output(A    ,				A    ,				A     ):
            snake_case				:    List[str]           =	model_class(A     )
            snake_case				:    List[Any]           =	model(**self._prepare_for_class(A    ,				A     )    ,				training=A     )

            snake_case				:    Tuple           =	outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

            snake_case				:    Optional[int]           =	self.model_tester.num_stages
            self.assertEqual(len(A     )    ,				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				:    Tuple           =	self.model_tester.prepare_config_and_inputs_for_common()
         snake_case				:    str           =	["""basic""", """bottleneck"""]
         for model_class in self.all_model_classes:
            for layer_type in layers_type:
               snake_case				:    Optional[Any]           =	layer_type
               snake_case				:    List[str]           =	True
               check_hidden_states_output(A    ,				A    ,				A     )

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

               check_hidden_states_output(A    ,				A    ,				A     )

      def      UpperCAmelCase				(				self     )		->    Dict:
         snake_case     , snake_case				:    int           =	self.model_tester.prepare_config_and_inputs_for_common()

         def check_equivalence(A    ,				A    ,				A    ,				A={}     ):
            snake_case				:    int           =	model(A    ,				return_dict=A    ,				**A     )
            snake_case				:    Any           =	model(A    ,				return_dict=A    ,				**A     ).to_tuple()

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

               recursive_check(A    ,				A     )

         for model_class in self.all_model_classes:
            snake_case				:    List[str]           =	model_class(A     )

            snake_case				:    Optional[int]           =	self._prepare_for_class(A    ,				A     )
            snake_case				:    str           =	self._prepare_for_class(A    ,				A     )
            check_equivalence(A    ,				A    ,				A     )

            snake_case				:    Tuple           =	self._prepare_for_class(A    ,				A    ,				return_labels=A     )
            snake_case				:    int           =	self._prepare_for_class(A    ,				A    ,				return_labels=A     )
            check_equivalence(A    ,				A    ,				A     )

            snake_case				:    List[str]           =	self._prepare_for_class(A    ,				A     )
            snake_case				:    Tuple           =	self._prepare_for_class(A    ,				A     )
            check_equivalence(A    ,				A    ,				A    ,				{"""output_hidden_states""": True}     )

            snake_case				:    Any           =	self._prepare_for_class(A    ,				A    ,				return_labels=A     )
            snake_case				:    Any           =	self._prepare_for_class(A    ,				A    ,				return_labels=A     )
            check_equivalence(A    ,				A    ,				A    ,				{"""output_hidden_states""": True}     )

      def      UpperCAmelCase				(				self     )		->    Tuple:
         snake_case				:    Optional[Any]           =	self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*A     )

      @slow
      def      UpperCAmelCase				(				self     )		->    str:
         for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            snake_case				:    List[str]           =	TFRegNetModel.from_pretrained(A     )
            self.assertIsNotNone(A     )




def 						SCREAMING_SNAKE_CASE__ (   )  ->       Dict:
   snake_case				:    Optional[int]           =	Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""					)
   return image




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




      """simple docstring"""





      @cached_property
      def      UpperCAmelCase				(				self     )		->    Tuple:
         return (
             AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]     )
             if is_vision_available()
             else None
         )

      @slow
      def      UpperCAmelCase				(				self     )		->    int:
         snake_case				:    int           =	TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]     )

         snake_case				:    int           =	self.default_image_processor
         snake_case				:    Dict           =	prepare_img()
         snake_case				:    List[str]           =	image_processor(images=A    ,				return_tensors="""tf"""     )

         # forward pass
         snake_case				:    Dict           =	model(**A    ,				training=A     )

         # verify the logits
         snake_case				:    List[Any]           =	tf.TensorShape((1, 1_0_0_0)     )
         self.assertEqual(outputs.logits.shape    ,				A     )

         snake_case				:    Optional[int]           =	tf.constant([-0.41_80, -1.50_51, -3.48_36]     )

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











from math import pow




def 						SCREAMING_SNAKE_CASE__ (   lowercase						,lowercase						,lowercase						,lowercase						,lowercase						,)  ->       tuple[int, int]:
   if current_sum == needed_sum:
      # If the sum of the powers is equal to needed_sum, then we have a solution.
      solutions_count += 1
      return current_sum, solutions_count

   snake_case				:    Union[str, Any]           =	int(pow(lowercase						,lowercase					)					)
   if current_sum + i_to_n <= needed_sum:
      # If the sum of the powers is less than needed_sum, then continue adding powers.
      current_sum += i_to_n
      snake_case     , snake_case				:    List[Any]           =	backtrack(
          lowercase						,lowercase						,current_number + 1						,lowercase						,lowercase					)
      current_sum -= i_to_n
   if i_to_n < needed_sum:
      # If the power of i is less than needed_sum, then try with the next power.
      snake_case     , snake_case				:    str           =	backtrack(
          lowercase						,lowercase						,current_number + 1						,lowercase						,lowercase					)
   return current_sum, solutions_count




def 						SCREAMING_SNAKE_CASE__ (   lowercase						,lowercase					)  ->       int:
   if not (1 <= needed_sum <= 1000 and 2 <= power <= 10):
      raise ValueError(
          """Invalid input\n"""
          """needed_sum must be between 1 and 1000, power between 2 and 10."""					)

   return backtrack(lowercase						,lowercase						,1						,0						,0					)[1]  # Return the solutions_count


if __name__ == "__main__":
       import doctest

       doctest.testmod()





