

import inspect
import unittest

from transformers import RegNetConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from transformers.utils import cached_property, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


if is_flax_available():
     import jax
     import jax.numpy as jnp

     from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel

if is_vision_available():
     from PIL import Image

     from transformers import AutoImageProcessor


class  A						(							unittest.TestCase ):







    """simple docstring"""





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





        '''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(lowercase_		)


    def 						snake_case__     (      self :       Any		)->    List[Any]:





        '''simple docstring'''







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

        A__          =   self.get_config()

        return config, pixel_values


    def 						snake_case__     (      self :       Any		)->    Dict:





        '''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,image_size=self.image_size,)


    def 						snake_case__     (      self :       List[Any],lowercase_ :       Optional[Any],lowercase_ :       List[str]		)->    List[str]:





        '''simple docstring'''







        A__          =   FlaxRegNetModel(config=lowercase_		)
        A__          =   model(lowercase_		)

        # Output shape (b, c, h, w)
        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 :       Any,lowercase_ :       int,lowercase_ :       List[str]		)->    Optional[Any]:





        '''simple docstring'''







        A__          =   self.num_labels
        A__          =   FlaxRegNetForImageClassification(config=lowercase_		)
        A__          =   model(lowercase_		)
        self.parent.assertEqual(result.logits.shape,(self.batch_size, self.num_labels)		)


    def 						snake_case__     (      self :       Tuple		)->    str:





        '''simple docstring'''







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




@require_flax
class  A						(							_UpperCAmelCase    ,							unittest.TestCase ):







    """simple docstring"""





    lowerCamelCase			=							(FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else ()

    lowerCamelCase			=							False
    lowerCamelCase			=							False
    lowerCamelCase			=							False


    def 						snake_case__     (      self :       Tuple		)->    None:





        '''simple docstring'''







        A__          =   FlaxRegNetModelTester(self		)
        A__          =   ConfigTester(self,config_class=lowercase_,has_text_modality=lowercase_		)


    def 						snake_case__     (      self :       Union[str, Any]		)->    List[Any]:





        '''simple docstring'''







        self.create_and_test_config_common_properties()
        self.config_tester.create_and_test_config_to_json_string()
        self.config_tester.create_and_test_config_to_json_file()
        self.config_tester.create_and_test_config_from_and_save_pretrained()
        self.config_tester.create_and_test_config_with_num_labels()
        self.config_tester.check_config_can_be_init_without_params()
        self.config_tester.check_config_arguments_init()


    def 						snake_case__     (      self :       List[str]		)->    int:





        '''simple docstring'''







        return


    def 						snake_case__     (      self :       str		)->    Union[str, Any]:





        '''simple docstring'''







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


    def 						snake_case__     (      self :       str		)->    Tuple:





        '''simple docstring'''







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


    @unittest.skip(reason='RegNet does not use inputs_embeds'		)
    def 						snake_case__     (      self :       int		)->    Optional[Any]:





        '''simple docstring'''







        pass


    @unittest.skip(reason='RegNet does not support input and output embeddings'		)
    def 						snake_case__     (      self :       Optional[Any]		)->    str:





        '''simple docstring'''







        pass


    def 						snake_case__     (      self :       int		)->    Dict:





        '''simple docstring'''







        A__      ,						A__          =   self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
            A__          =   model_class(lowercase_		)
            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],lowercase_		)


    def 						snake_case__     (      self :       Optional[Any]		)->    Optional[Any]:





        '''simple docstring'''







        def check_hidden_states_output(lowercase_ :       List[str],lowercase_ :       List[Any],lowercase_ :       Optional[int]		):
            A__          =   model_class(lowercase_		)

            A__          =   model(**self._prepare_for_class(lowercase_,lowercase_		)		)

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

            A__          =   self.model_tester.num_stages
            self.assertEqual(len(lowercase_		),expected_num_stages + 1		)

        A__      ,						A__          =   self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
            A__          =   True
            check_hidden_states_output(lowercase_,lowercase_,lowercase_		)

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

            check_hidden_states_output(lowercase_,lowercase_,lowercase_		)


    def 						snake_case__     (      self :       Tuple		)->    Tuple:





        '''simple docstring'''







        A__      ,						A__          =   self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
            with self.subTest(model_class.__name__		):
                A__          =   self._prepare_for_class(lowercase_,lowercase_		)
                A__          =   model_class(lowercase_		)

                @jax.jit
                def model_jitted(lowercase_ :       int,**lowercase_ :       Dict		):
                    return model(pixel_values=lowercase_,**lowercase_		)

                with self.subTest('JIT Enabled'		):
                    A__          =   model_jitted(**lowercase_		).to_tuple()

                with self.subTest('JIT Disabled'		):
                    with jax.disable_jit():
                        A__          =   model_jitted(**lowercase_		).to_tuple()

                self.assertEqual(len(lowercase_		),len(lowercase_		)		)
                for jitted_output, output in zip(lowercase_,lowercase_		):
                    self.assertEqual(jitted_output.shape,output.shape		)




def 						_snake_case(    )							->      Dict:





    '''simple docstring'''






    A__          =   Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'      )
    return image


@require_flax
class  A						(							unittest.TestCase ):







    """simple docstring"""





    @cached_property
    def 						snake_case__     (      self :       Dict		)->    Optional[int]:





        '''simple docstring'''







        return AutoImageProcessor.from_pretrained('facebook/regnet-y-040'		) if is_vision_available() else None


    @slow
    def 						snake_case__     (      self :       Union[str, Any]		)->    str:





        '''simple docstring'''







        A__          =   FlaxRegNetForImageClassification.from_pretrained('facebook/regnet-y-040'		)

        A__          =   self.default_image_processor
        A__          =   prepare_img()
        A__          =   image_processor(images=lowercase_,return_tensors='np'		)

        A__          =   model(**lowercase_		)

        # verify the logits
        A__          =   (1, 1_0_0_0)
        self.assertEqual(outputs.logits.shape,lowercase_		)

        A__          =   jnp.array([-0.4_180, -1.5_051, -3.4_836]		)

        self.assertTrue(jnp.allclose(outputs.logits[0, :3],lowercase_,atol=1E-4		)		)




'''simple docstring'''



from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices


UpperCAmelCase :       Optional[int]			   =     logging.get_logger(__name__)

UpperCAmelCase :       str			   =     {
    'facebook/convnextv2-tiny-1k-224': 'https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json',
}







class 						lowerCAmelCase__   (      a ,					a					):



 """simple docstring"""



 lowerCAmelCase__  					=      "convnextv2"
 def __init__(		self					:       Any					,							__SCREAMING_SNAKE_CASE					:       int=3					,							__SCREAMING_SNAKE_CASE					:       Dict=4					,							__SCREAMING_SNAKE_CASE					:       List[Any]=4					,							__SCREAMING_SNAKE_CASE					:       Optional[int]=None					,							__SCREAMING_SNAKE_CASE					:       Dict=None					,							__SCREAMING_SNAKE_CASE					:       Optional[int]="gelu"					,							__SCREAMING_SNAKE_CASE					:       Union[str, Any]=0.02					,							__SCREAMING_SNAKE_CASE					:       Dict=1E-12					,							__SCREAMING_SNAKE_CASE					:       List[str]=0.0					,							__SCREAMING_SNAKE_CASE					:       Optional[Any]=224					,							__SCREAMING_SNAKE_CASE					:       Tuple=None					,							__SCREAMING_SNAKE_CASE					:       List[str]=None					,							**__SCREAMING_SNAKE_CASE					:       Union[str, Any]					,							)  -> Union[str, Any]:


      """simple docstring"""




      super().__init__(**__SCREAMING_SNAKE_CASE			)

      __SCREAMING_SNAKE_CASE     =      num_channels
      __SCREAMING_SNAKE_CASE     =      patch_size
      __SCREAMING_SNAKE_CASE     =      num_stages
      __SCREAMING_SNAKE_CASE     =      [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes
      __SCREAMING_SNAKE_CASE     =      [3, 3, 9, 3] if depths is None else depths
      __SCREAMING_SNAKE_CASE     =      hidden_act
      __SCREAMING_SNAKE_CASE     =      initializer_range
      __SCREAMING_SNAKE_CASE     =      layer_norm_eps
      __SCREAMING_SNAKE_CASE     =      drop_path_rate
      __SCREAMING_SNAKE_CASE     =      image_size
      __SCREAMING_SNAKE_CASE     =      ["""stem"""] + [f'stage{idx}' for idx in range(1					,							len(self.depths			) + 1			)]
      __SCREAMING_SNAKE_CASE   ,			__SCREAMING_SNAKE_CASE     =      get_aligned_output_features_output_indices(
          out_features=__SCREAMING_SNAKE_CASE					,							out_indices=__SCREAMING_SNAKE_CASE					,							stage_names=self.stage_names			)






