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







   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       ,							)   ->int:
      a_						   =     parent
      a_						   =     batch_size
      a_						   =     image_size
      a_						   =     num_channels
      a_						   =     num_stages
      a_						   =     hidden_sizes
      a_						   =     depths
      a_						   =     is_training
      a_						   =     use_labels
      a_						   =     intermediate_size
      a_						   =     hidden_act
      a_						   =     type_sequence_label_size
      a_						   =     initializer_range
      a_						   =     scope







   def    UpperCAmelCase__	( self)   ->int:
      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.type_sequence_label_size)

      a_						   =     self.get_config()

      return config, pixel_values, labels







   def    UpperCAmelCase__	( self)   ->Dict:
      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    UpperCAmelCase__	( self       ,							__UpperCAmelCase       ,							__UpperCAmelCase       ,							__UpperCAmelCase)   ->Dict:
      a_						   =     TFConvNextModel(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       ,							__UpperCAmelCase       ,							__UpperCAmelCase       ,							__UpperCAmelCase)   ->Optional[int]:
      a_						   =     self.type_sequence_label_size
      a_						   =     TFConvNextForImageClassification(__UpperCAmelCase)
      a_						   =     model(__UpperCAmelCase       ,							labels=__UpperCAmelCase       ,							training=__UpperCAmelCase)
      self.parent.assertEqual(result.logits.shape       ,							(self.batch_size, self.type_sequence_label_size))







   def    UpperCAmelCase__	( self)   ->Any:
      a_						   =     self.prepare_config_and_inputs()
      a_   ,			a_   ,			a_						   =     config_and_inputs
      a_						   =     {"pixel_values": pixel_values}
      return config, inputs_dict






@require_tf
class 							snake_case       (     SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_							,       unittest.TestCase		):
   a_					:		int     					=     (TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
   a_					:		str     					=     (
       {"""feature-extraction""": TFConvNextModel, """image-classification""": TFConvNextForImageClassification}
       if is_tf_available()
       else {}
   )

   a_					:		List[Any]     					=     False
   a_					:		Dict     					=     False
   a_					:		str     					=     False
   a_					:		str     					=     False
   a_					:		Optional[int]     					=     False







   def    UpperCAmelCase__	( self)   ->Tuple:
      a_						   =     TFConvNextModelTester(self)
      a_						   =     ConfigTester(
          self       ,							config_class=__UpperCAmelCase       ,							has_text_modality=__UpperCAmelCase       ,							hidden_size=37       ,							)







   @unittest.skip(reason="ConvNext does not use inputs_embeds")
   def    UpperCAmelCase__	( self)   ->List[Any]:
      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:
      super().test_keras_fit()







   @unittest.skip(reason="ConvNext does not support input and output embeddings")
   def    UpperCAmelCase__	( self)   ->Optional[Any]:
      pass







   def    UpperCAmelCase__	( self)   ->Dict:
      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)   ->Dict:
      a_						   =     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    UpperCAmelCase__	( self)   ->List[Any]:
      super().test_dataset_conversion()







   def    UpperCAmelCase__	( self)   ->Optional[Any]:
      def check_hidden_states_output(__UpperCAmelCase       ,							__UpperCAmelCase       ,							__UpperCAmelCase):
         a_						   =     model_class(__UpperCAmelCase)

         a_						   =     model(**self._prepare_for_class(__UpperCAmelCase       ,							__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)

         # 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_						   =     self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
         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)   ->Union[str, Any]:
      a_   ,			a_						   =     self.model_tester.prepare_config_and_inputs_for_common()

      def check_equivalence(__UpperCAmelCase       ,							__UpperCAmelCase       ,							__UpperCAmelCase       ,							__UpperCAmelCase={}):
         a_						   =     model(__UpperCAmelCase       ,							return_dict=__UpperCAmelCase       ,							**__UpperCAmelCase)
         a_						   =     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_						   =     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)   ->int:
      a_						   =     self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase)







   @slow
   def    UpperCAmelCase__	( self)   ->Tuple:
      a_						   =     TFConvNextModel.from_pretrained("facebook/convnext-tiny-224")
      self.assertIsNotNone(__UpperCAmelCase)






def    UpperCamelCase						(					)						->List[Any]:

   """simple docstring"""



   a_						   =     Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"     )
   return image





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







   @cached_property
   def    UpperCAmelCase__	( self)   ->int:
      return ConvNextImageProcessor.from_pretrained("facebook/convnext-tiny-224") if is_vision_available() else None







   @slow
   def    UpperCAmelCase__	( self)   ->Dict:
      a_						   =     TFConvNextForImageClassification.from_pretrained("facebook/convnext-tiny-224")

      a_						   =     self.default_image_processor
      a_						   =     prepare_img()
      a_						   =     image_processor(images=__UpperCAmelCase       ,							return_tensors="tf")

      # forward pass
      a_						   =     model(**__UpperCAmelCase)

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

      a_						   =     tf.constant([-0.0_260, -0.4_739, 0.1_911])

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

"""simple docstring"""






from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_torch_available,
    is_vision_available,
)


UpperCamelCase_						   =   {
    'configuration_mobilevitv2': [
        'MOBILEVITV2_PRETRAINED_CONFIG_ARCHIVE_MAP',
        'MobileViTV2Config',
        'MobileViTV2OnnxConfig',
    ],
}


try:
      if not is_torch_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      UpperCamelCase_						   =   [
          'MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST',
          'MobileViTV2ForImageClassification',
          'MobileViTV2ForSemanticSegmentation',
          'MobileViTV2Model',
          'MobileViTV2PreTrainedModel',
      ]

if TYPE_CHECKING:
      from .configuration_mobilevitva import (
          MOBILEVITV2_PRETRAINED_CONFIG_ARCHIVE_MAP,
          MobileViTVaConfig,
          MobileViTVaOnnxConfig,
      )

      try:
            if not is_torch_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_mobilevitva import (
                MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST,
                MobileViTVaForImageClassification,
                MobileViTVaForSemanticSegmentation,
                MobileViTVaModel,
                MobileViTVaPreTrainedModel,
            )

else:
      import sys

      UpperCamelCase_						   =   _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)