





'''simple docstring'''






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


   def __init__(			self     , _UpperCAmelCase     , _UpperCAmelCase=13     , _UpperCAmelCase=32     , _UpperCAmelCase=3     , _UpperCAmelCase=4     , _UpperCAmelCase=[10, 20, 30, 40]     , _UpperCAmelCase=[2, 2, 3, 2]     , _UpperCAmelCase=True     , _UpperCAmelCase=True     , _UpperCAmelCase=37     , _UpperCAmelCase="gelu"     , _UpperCAmelCase=10     , _UpperCAmelCase=0.02     , _UpperCAmelCase=3     , _UpperCAmelCase=None     , ):
       A							:							Dict				=    parent
       A							:							Any				=    batch_size
       A							:							Optional[int]				=    image_size
       A							:							Tuple				=    num_channels
       A							:							Union[str, Any]				=    num_stages
       A							:							Tuple				=    hidden_sizes
       A							:							str				=    depths
       A							:							str				=    is_training
       A							:							Dict				=    use_labels
       A							:							Dict				=    intermediate_size
       A							:							Any				=    hidden_act
       A							:							Optional[int]				=    type_sequence_label_size
       A							:							List[str]				=    initializer_range
       A							:							str				=    scope


   def        snake_case					(			self       ):
       A							:							int				=    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

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

       A							:							str				=    self.get_config()

       return config, pixel_values, labels


   def        snake_case					(			self       ):
       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=_UpperCAmelCase     , initializer_range=self.initializer_range     , )


   def        snake_case					(			self     , _UpperCAmelCase     , _UpperCAmelCase     , _UpperCAmelCase       ):
       A							:							int				=    TFConvNextModel(config=_UpperCAmelCase       )
       A							:							List[Any]				=    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        snake_case					(			self     , _UpperCAmelCase     , _UpperCAmelCase     , _UpperCAmelCase       ):
       A							:							Tuple				=    self.type_sequence_label_size
       A							:							int				=    TFConvNextForImageClassification(_UpperCAmelCase       )
       A							:							Any				=    model(_UpperCAmelCase     , labels=_UpperCAmelCase     , training=_UpperCAmelCase       )
       self.parent.assertEqual(result.logits.shape     , (self.batch_size, self.type_sequence_label_size)       )


   def        snake_case					(			self       ):
       A							:							Dict				=    self.prepare_config_and_inputs()
       A,						A,						A							:							Tuple				=    config_and_inputs
       A							:							Any				=    {'''pixel_values''': pixel_values}
       return config, inputs_dict







@require_tf
class 	_lowercase    (				a		,       a		,       unittest.TestCase					):
   _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        snake_case					(			self       ):
       A							:							Dict				=    TFConvNextModelTester(self       )
       A							:							Dict				=    ConfigTester(
           self     , config_class=_UpperCAmelCase     , has_text_modality=_UpperCAmelCase     , hidden_size=37     , )


   @unittest.skip(reason='''ConvNext does not use inputs_embeds'''       )
   def        snake_case					(			self       ):
       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       ):
       super().test_keras_fit()


   @unittest.skip(reason='''ConvNext does not support input and output embeddings'''       )
   def        snake_case					(			self       ):
       pass


   def        snake_case					(			self       ):
       A,						A							:							Union[str, Any]				=    self.model_tester.prepare_config_and_inputs_for_common()

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

           A							:							Dict				=    ['''pixel_values''']
           self.assertListEqual(arg_names[:1]     , _UpperCAmelCase       )


   def        snake_case					(			self       ):
       A							:							Optional[Any]				=    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*_UpperCAmelCase       )


   @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        snake_case					(			self       ):
       super().test_dataset_conversion()


   def        snake_case					(			self       ):
       def check_hidden_states_output(_UpperCAmelCase     , _UpperCAmelCase     , _UpperCAmelCase       ):
           A							:							str				=    model_class(_UpperCAmelCase       )

           A							:							str				=    model(**self._prepare_for_class(_UpperCAmelCase     , _UpperCAmelCase       )       )
           A							:							str				=    outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

           A							:							Union[str, Any]				=    self.model_tester.num_stages
           self.assertEqual(len(_UpperCAmelCase       )     , 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,						A							:							List[str]				=    self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
           A							:							Dict				=    True
           check_hidden_states_output(_UpperCAmelCase     , _UpperCAmelCase     , _UpperCAmelCase       )

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

           check_hidden_states_output(_UpperCAmelCase     , _UpperCAmelCase     , _UpperCAmelCase       )


   def        snake_case					(			self       ):
       A,						A							:							Any				=    self.model_tester.prepare_config_and_inputs_for_common()

       def check_equivalence(_UpperCAmelCase     , _UpperCAmelCase     , _UpperCAmelCase     , _UpperCAmelCase={}       ):
           A							:							Union[str, Any]				=    model(_UpperCAmelCase     , return_dict=_UpperCAmelCase     , **_UpperCAmelCase       )
           A							:							str				=    model(_UpperCAmelCase     , return_dict=_UpperCAmelCase     , **_UpperCAmelCase       ).to_tuple()

           def recursive_check(_UpperCAmelCase     , _UpperCAmelCase       ):
               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							:							Optional[Any]				=    model_class(_UpperCAmelCase       )

           A							:							int				=    self._prepare_for_class(_UpperCAmelCase     , _UpperCAmelCase       )
           A							:							Union[str, Any]				=    self._prepare_for_class(_UpperCAmelCase     , _UpperCAmelCase       )
           check_equivalence(_UpperCAmelCase     , _UpperCAmelCase     , _UpperCAmelCase       )

           A							:							Optional[Any]				=    self._prepare_for_class(_UpperCAmelCase     , _UpperCAmelCase     , return_labels=_UpperCAmelCase       )
           A							:							int				=    self._prepare_for_class(_UpperCAmelCase     , _UpperCAmelCase     , return_labels=_UpperCAmelCase       )
           check_equivalence(_UpperCAmelCase     , _UpperCAmelCase     , _UpperCAmelCase       )

           A							:							str				=    self._prepare_for_class(_UpperCAmelCase     , _UpperCAmelCase       )
           A							:							str				=    self._prepare_for_class(_UpperCAmelCase     , _UpperCAmelCase       )
           check_equivalence(_UpperCAmelCase     , _UpperCAmelCase     , _UpperCAmelCase     , {'''output_hidden_states''': True}       )

           A							:							Dict				=    self._prepare_for_class(_UpperCAmelCase     , _UpperCAmelCase     , return_labels=_UpperCAmelCase       )
           A							:							Dict				=    self._prepare_for_class(_UpperCAmelCase     , _UpperCAmelCase     , return_labels=_UpperCAmelCase       )
           check_equivalence(_UpperCAmelCase     , _UpperCAmelCase     , _UpperCAmelCase     , {'''output_hidden_states''': True}       )


   def        snake_case					(			self       ):
       A							:							List[Any]				=    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase       )


   @slow
   def        snake_case					(			self       ):
       A							:							int				=    TFConvNextModel.from_pretrained('''facebook/convnext-tiny-224'''       )
       self.assertIsNotNone(_UpperCAmelCase       )







def 				_lowerCamelCase(	)		->	Tuple:
    A							:							Optional[Any]				=    Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''		)
    return image





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


   @cached_property
   def        snake_case					(			self       ):
       return ConvNextImageProcessor.from_pretrained('''facebook/convnext-tiny-224'''       ) if is_vision_available() else None


   @slow
   def        snake_case					(			self       ):
       A							:							List[str]				=    TFConvNextForImageClassification.from_pretrained('''facebook/convnext-tiny-224'''       )

       A							:							List[str]				=    self.default_image_processor
       A							:							Dict				=    prepare_img()
       A							:							List[Any]				=    image_processor(images=_UpperCAmelCase     , return_tensors='''tf'''       )

       # forward pass
       A							:							List[Any]				=    model(**_UpperCAmelCase       )

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

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

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







'''simple docstring'''






from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


snake_case_     			=						logging.get_logger(__name__)

snake_case_     			=						{
    """apple/mobilevit-small""": """https://huggingface.co/apple/mobilevit-small/resolve/main/config.json""",
    """apple/mobilevit-x-small""": """https://huggingface.co/apple/mobilevit-x-small/resolve/main/config.json""",
    """apple/mobilevit-xx-small""": """https://huggingface.co/apple/mobilevit-xx-small/resolve/main/config.json""",
    """apple/deeplabv3-mobilevit-small""": (
        """https://huggingface.co/apple/deeplabv3-mobilevit-small/resolve/main/config.json"""
    ),
    """apple/deeplabv3-mobilevit-x-small""": (
        """https://huggingface.co/apple/deeplabv3-mobilevit-x-small/resolve/main/config.json"""
    ),
    """apple/deeplabv3-mobilevit-xx-small""": (
        """https://huggingface.co/apple/deeplabv3-mobilevit-xx-small/resolve/main/config.json"""
    ),
    # See all MobileViT models at https://huggingface.co/models?filter=mobilevit
}


class 	_lowercase    (				a					):
   _UpperCamelCase									= """mobilevit"""


   def __init__(			self     , _UpperCAmelCase=3     , _UpperCAmelCase=256     , _UpperCAmelCase=2     , _UpperCAmelCase=[144, 192, 240]     , _UpperCAmelCase=[16, 32, 64, 96, 128, 160, 640]     , _UpperCAmelCase=4     , _UpperCAmelCase=2.0     , _UpperCAmelCase=4.0     , _UpperCAmelCase="silu"     , _UpperCAmelCase=3     , _UpperCAmelCase=32     , _UpperCAmelCase=0.1     , _UpperCAmelCase=0.0     , _UpperCAmelCase=0.1     , _UpperCAmelCase=0.02     , _UpperCAmelCase=1E-5     , _UpperCAmelCase=True     , _UpperCAmelCase=256     , _UpperCAmelCase=[6, 12, 18]     , _UpperCAmelCase=0.1     , _UpperCAmelCase=255     , **_UpperCAmelCase     , ):
       super().__init__(**_UpperCAmelCase       )

       A							:							Union[str, Any]				=    num_channels
       A							:							Union[str, Any]				=    image_size
       A							:							List[str]				=    patch_size
       A							:							Any				=    hidden_sizes
       A							:							Dict				=    neck_hidden_sizes
       A							:							int				=    num_attention_heads
       A							:							List[str]				=    mlp_ratio
       A							:							List[Any]				=    expand_ratio
       A							:							Dict				=    hidden_act
       A							:							List[Any]				=    conv_kernel_size
       A							:							List[str]				=    output_stride
       A							:							Dict				=    hidden_dropout_prob
       A							:							List[str]				=    attention_probs_dropout_prob
       A							:							Optional[Any]				=    classifier_dropout_prob
       A							:							Any				=    initializer_range
       A							:							Union[str, Any]				=    layer_norm_eps
       A							:							Union[str, Any]				=    qkv_bias

       # decode head attributes for semantic segmentation
       A							:							int				=    aspp_out_channels
       A							:							Any				=    atrous_rates
       A							:							Tuple				=    aspp_dropout_prob
       A							:							List[Any]				=    semantic_loss_ignore_index







class 	_lowercase    (				a					):
   _UpperCamelCase									= version.parse("""1.11"""					)


   @property
   def        snake_case					(			self       ):
       return OrderedDict([('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''})]       )


   @property
   def        snake_case					(			self       ):
       if self.task == "image-classification":
           return OrderedDict([('''logits''', {0: '''batch'''})]       )
       else:
           return OrderedDict([('''last_hidden_state''', {0: '''batch'''}), ('''pooler_output''', {0: '''batch'''})]       )


   @property
   def        snake_case					(			self       ):
       return 1E-4
