





from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import ConvNextConfig
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 TFConvNextForImageClassification, TFConvNextModel


if is_vision_available():
 from PIL import Image

 from transformers import ConvNextImageProcessor


class 					__magic_name__  :





     """simple docstring"""



     def __init__(							self       :Optional[int]			,      snake_case       :int			,      snake_case       :Dict=13			,      snake_case       :int=32			,      snake_case       :Dict=3			,      snake_case       :Dict=4			,      snake_case       :str=[10, 20, 30, 40]			,      snake_case       :Any=[2, 2, 3, 2]			,      snake_case       :Union[str, Any]=True			,      snake_case       :List[str]=True			,      snake_case       :List[Any]=37			,      snake_case       :Union[str, Any]="gelu"			,      snake_case       :str=10			,      snake_case       :str=0.02			,      snake_case       :int=3			,      snake_case       :str=None			,      ):





        '''simple docstring'''




        A_					:				List[Any]          =			parent
        A_					:				Optional[int]          =			batch_size
        A_					:				Optional[Any]          =			image_size
        A_					:				Dict          =			num_channels
        A_					:				Union[str, Any]          =			num_stages
        A_					:				Union[str, Any]          =			hidden_sizes
        A_					:				Any          =			depths
        A_					:				Tuple          =			is_training
        A_					:				int          =			use_labels
        A_					:				Optional[Any]          =			intermediate_size
        A_					:				int          =			hidden_act
        A_					:				int          =			type_sequence_label_size
        A_					:				List[str]          =			initializer_range
        A_					:				List[Any]          =			scope



     def 						SCREAMING_SNAKE_CASE		(							self       :Any  ):





        '''simple docstring'''




        A_					:				Optional[Any]          =			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

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

        A_					:				Union[str, Any]          =			self.get_config()

        return config, pixel_values, labels



     def 						SCREAMING_SNAKE_CASE		(							self       :Tuple  ):





        '''simple docstring'''




        return ConvNextConfig(
            num_channels=self.num_channels			,      hidden_sizes=self.hidden_sizes			,      depths=self.depths			,      num_stages=self.num_stages			,      hidden_act=self.hidden_act			,      is_decoder=snake_case			,      initializer_range=self.initializer_range			,      )



     def 						SCREAMING_SNAKE_CASE		(							self       :str			,      snake_case       :Dict			,      snake_case       :Tuple			,      snake_case       :List[Any]  ):





        '''simple docstring'''




        A_					:				int          =			TFConvNextModel(config=snake_case  )
        A_					:				List[Any]          =			model(snake_case			,      training=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 						SCREAMING_SNAKE_CASE		(							self       :List[str]			,      snake_case       :str			,      snake_case       :Optional[int]			,      snake_case       :Dict  ):





        '''simple docstring'''




        A_					:				Optional[int]          =			self.type_sequence_label_size
        A_					:				List[str]          =			TFConvNextForImageClassification(snake_case  )
        A_					:				Optional[Any]          =			model(snake_case			,      labels=snake_case			,      training=snake_case  )
        self.parent.assertEqual(result.logits.shape			,      (self.batch_size, self.type_sequence_label_size)  )





     def 						SCREAMING_SNAKE_CASE		(							self       :List[str]  ):





        '''simple docstring'''




        A_					:				Any          =			self.prepare_config_and_inputs()
        A_					:				Tuple          =			config_and_inputs
        A_					:				Optional[int]          =			{"pixel_values": pixel_values}
        return config, inputs_dict




@require_tf
class 					__magic_name__  (							lowerCamelCase__    ,				lowerCamelCase__    ,				unittest.TestCase							):





     """simple docstring"""



     __UpperCamelCase					    =     (TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
     __UpperCamelCase					    =     (
         {'''feature-extraction''': TFConvNextModel, '''image-classification''': TFConvNextForImageClassification}
         if is_tf_available()
         else {}
     )

     __UpperCamelCase					    =     False
     __UpperCamelCase					    =     False
     __UpperCamelCase					    =     False
     __UpperCamelCase					    =     False
     __UpperCamelCase					    =     False



     def 						SCREAMING_SNAKE_CASE		(							self       :List[str]  ):





        '''simple docstring'''




        A_					:				Optional[int]          =			TFConvNextModelTester(self  )
        A_					:				List[Any]          =			ConfigTester(
            self			,      config_class=snake_case			,      has_text_modality=snake_case			,      hidden_size=37			,      )



     @unittest.skip(reason="ConvNext does not use inputs_embeds"  )
     def 						SCREAMING_SNAKE_CASE		(							self       :str  ):





        '''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 						SCREAMING_SNAKE_CASE		(							self       :Optional[Any]  ):





        '''simple docstring'''




        super().test_keras_fit()



     @unittest.skip(reason="ConvNext does not support input and output embeddings"  )
     def 						SCREAMING_SNAKE_CASE		(							self       :Union[str, Any]  ):





        '''simple docstring'''




        pass



     def 						SCREAMING_SNAKE_CASE		(							self       :Any  ):





        '''simple docstring'''




        A_					:				List[str]          =			self.model_tester.prepare_config_and_inputs_for_common()

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

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



     def 						SCREAMING_SNAKE_CASE		(							self       :int  ):





        '''simple docstring'''




        A_					:				Optional[int]          =			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*snake_case  )



     @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."			,      )
     def 						SCREAMING_SNAKE_CASE		(							self       :List[str]  ):





        '''simple docstring'''




        super().test_dataset_conversion()



     def 						SCREAMING_SNAKE_CASE		(							self       :Optional[Any]  ):





        '''simple docstring'''




        def check_hidden_states_output(snake_case       :List[Any]			,      snake_case       :Optional[int]			,      snake_case       :str  ):
           A_					:				List[str]          =			model_class(snake_case  )

           A_					:				Optional[Any]          =			model(**self._prepare_for_class(snake_case			,      snake_case  )  )
           A_					:				List[Any]          =			outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

           A_					:				Optional[Any]          =			self.model_tester.num_stages
           self.assertEqual(len(snake_case  )			,      expected_num_stages + 1  )

           # ConvNext'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 // 4, self.model_tester.image_size // 4]			,      )

        A_					:				Dict          =			self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
           A_					:				Optional[Any]          =			True
           check_hidden_states_output(snake_case			,      snake_case			,      snake_case  )

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

           check_hidden_states_output(snake_case			,      snake_case			,      snake_case  )



     def 						SCREAMING_SNAKE_CASE		(							self       :int  ):





        '''simple docstring'''




        A_					:				Any          =			self.model_tester.prepare_config_and_inputs_for_common()

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

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

              recursive_check(snake_case			,      snake_case  )

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

           A_					:				str          =			self._prepare_for_class(snake_case			,      snake_case  )
           A_					:				List[Any]          =			self._prepare_for_class(snake_case			,      snake_case  )
           check_equivalence(snake_case			,      snake_case			,      snake_case  )

           A_					:				Tuple          =			self._prepare_for_class(snake_case			,      snake_case			,      return_labels=snake_case  )
           A_					:				List[str]          =			self._prepare_for_class(snake_case			,      snake_case			,      return_labels=snake_case  )
           check_equivalence(snake_case			,      snake_case			,      snake_case  )

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

           A_					:				int          =			self._prepare_for_class(snake_case			,      snake_case			,      return_labels=snake_case  )
           A_					:				Union[str, Any]          =			self._prepare_for_class(snake_case			,      snake_case			,      return_labels=snake_case  )
           check_equivalence(snake_case			,      snake_case			,      snake_case			,      {"output_hidden_states": True}  )



     def 						SCREAMING_SNAKE_CASE		(							self       :Optional[Any]  ):





        '''simple docstring'''




        A_					:				int          =			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*snake_case  )





     @slow
     def 						SCREAMING_SNAKE_CASE		(							self       :List[Any]  ):





        '''simple docstring'''




        A_					:				Tuple          =			TFConvNextModel.from_pretrained("facebook/convnext-tiny-224"  )
        self.assertIsNotNone(snake_case  )




def      __snake_case						(					) ->						Optional[int]:
   A_					:				Union[str, Any]          =			Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"	)
   return image





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





     """simple docstring"""



     @cached_property
     def 						SCREAMING_SNAKE_CASE		(							self       :List[Any]  ):





        '''simple docstring'''




        return ConvNextImageProcessor.from_pretrained("facebook/convnext-tiny-224"  ) if is_vision_available() else None





     @slow
     def 						SCREAMING_SNAKE_CASE		(							self       :List[Any]  ):





        '''simple docstring'''




        A_					:				int          =			TFConvNextForImageClassification.from_pretrained("facebook/convnext-tiny-224"  )

        A_					:				int          =			self.default_image_processor
        A_					:				Dict          =			prepare_img()
        A_					:				int          =			image_processor(images=snake_case			,      return_tensors="tf"  )

        # forward pass
        A_					:				Optional[Any]          =			model(**snake_case  )

        # verify the logits
        A_					:				Optional[Any]          =			tf.TensorShape((1, 1_000)  )
        self.assertEqual(outputs.logits.shape			,      snake_case  )

        A_					:				str          =			tf.constant([-0.0260, -0.4739, 0.1911]  )

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








from __future__ import annotations

def      __snake_case						(					_lowerCAmelCase : int	) ->						list[int]:
   assert (
       isinstance(_lowerCAmelCase				,				_lowerCAmelCase	) and mask > 0
   ), f"mask needs to be positive integer, your input {mask}"
   A_					:				Optional[Any]          =			[]
   A_					:				Optional[int]          =			mask

   while submask:
      all_submasks.append(_lowerCAmelCase	)
      A_					:				List[str]          =			(submask - 1) & mask

   return all_submasks


if __name__ == "__main__":
 import doctest

 doctest.testmod()
