
"""simple docstring"""




from __future__ import annotations

import inspect
import unittest

from transformers import MobileViTConfig
from transformers.file_utils import is_tf_available, is_vision_available
from transformers.testing_utils import require_tf, slow

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 numpy as np
			import tensorflow as tf

			from transformers import TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation, TFMobileViTModel
			from transformers.models.mobilevit.modeling_tf_mobilevit import TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
			from PIL import Image

			from transformers import MobileViTImageProcessor

class 		a__						(				lowercase_						):
			def       __magic_name__      (      self    ):
										lowercase   :    List[Any]			=							self.config_class(**self.inputs_dict    )
										self.parent.assertTrue(hasattr(_a     ,   "hidden_sizes"    )    )
										self.parent.assertTrue(hasattr(_a     ,   "neck_hidden_sizes"    )    )
										self.parent.assertTrue(hasattr(_a     ,   "num_attention_heads"    )    )


class 		a__						:
			def __init__(      self     ,   _a     ,   _a=13     ,   _a=32     ,   _a=2     ,   _a=3     ,   _a=640     ,   _a=4     ,   _a="silu"     ,   _a=3     ,   _a=32     ,   _a=0.1     ,   _a=0.1     ,   _a=0.1     ,   _a=0.0_2     ,   _a=True     ,   _a=True     ,   _a=10     ,   _a=None     ,   ):
										lowercase   :    Optional[Any]			=							parent
										lowercase   :    Any			=							batch_size
										lowercase   :    str			=							image_size
										lowercase   :    str			=							patch_size
										lowercase   :    Union[str, Any]			=							num_channels
										lowercase   :    Any			=							last_hidden_size
										lowercase   :    Optional[int]			=							num_attention_heads
										lowercase   :    List[Any]			=							hidden_act
										lowercase   :    Optional[Any]			=							conv_kernel_size
										lowercase   :    List[Any]			=							output_stride
										lowercase   :    Any			=							hidden_dropout_prob
										lowercase   :    List[str]			=							attention_probs_dropout_prob
										lowercase   :    Optional[int]			=							classifier_dropout_prob
										lowercase   :    int			=							use_labels
										lowercase   :    List[Any]			=							is_training
										lowercase   :    int			=							num_labels
										lowercase   :    Optional[int]			=							initializer_range
										lowercase   :    Tuple			=							scope
			def       __magic_name__      (      self    ):
										lowercase   :    List[str]			=							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

										lowercase   :    Dict			=							None
										lowercase   :    Dict			=							None
										if self.use_labels:
																	lowercase   :    Union[str, Any]			=							ids_tensor([self.batch_size]     ,   self.num_labels    )
																	lowercase   :    List[str]			=							ids_tensor([self.batch_size, self.image_size, self.image_size]     ,   self.num_labels    )

										lowercase   :    List[str]			=							self.get_config()

										return config, pixel_values, labels, pixel_labels
			def       __magic_name__      (      self    ):
										return MobileViTConfig(
										    image_size=self.image_size     ,   patch_size=self.patch_size     ,   num_channels=self.num_channels     ,   num_attention_heads=self.num_attention_heads     ,   hidden_act=self.hidden_act     ,   conv_kernel_size=self.conv_kernel_size     ,   output_stride=self.output_stride     ,   hidden_dropout_prob=self.hidden_dropout_prob     ,   attention_probs_dropout_prob=self.attention_probs_dropout_prob     ,   classifier_dropout_prob=self.classifier_dropout_prob     ,   initializer_range=self.initializer_range     ,   )
			def       __magic_name__      (      self     ,   _a     ,   _a     ,   _a     ,   _a    ):
										lowercase   :    Any			=							TFMobileViTModel(config=_a    )
										lowercase   :    Tuple			=							model(_a     ,   training=_a    )
										lowercase   :    Optional[int]			=							self.image_size // self.output_stride
										self.parent.assertEqual(
										    result.last_hidden_state.shape     ,   (self.batch_size, self.last_hidden_size, expected_height, expected_width)    )
			def       __magic_name__      (      self     ,   _a     ,   _a     ,   _a     ,   _a    ):
										lowercase   :    List[Any]			=							self.num_labels
										lowercase   :    List[Any]			=							TFMobileViTForImageClassification(_a    )
										lowercase   :    int			=							model(_a     ,   labels=_a     ,   training=_a    )
										self.parent.assertEqual(result.logits.shape     ,   (self.batch_size, self.num_labels)    )
			def       __magic_name__      (      self     ,   _a     ,   _a     ,   _a     ,   _a    ):
										lowercase   :    Optional[int]			=							self.num_labels
										lowercase   :    Optional[int]			=							TFMobileViTForSemanticSegmentation(_a    )
										lowercase   :    Dict			=							self.image_size // self.output_stride

										lowercase   :    List[str]			=							model(_a     ,   training=_a    )
										self.parent.assertEqual(
										    result.logits.shape     ,   (self.batch_size, self.num_labels, expected_height, expected_width)    )

										lowercase   :    List[str]			=							model(_a     ,   labels=_a     ,   training=_a    )
										self.parent.assertEqual(
										    result.logits.shape     ,   (self.batch_size, self.num_labels, expected_height, expected_width)    )

			def       __magic_name__      (      self    ):
										lowercase   :    Union[str, Any]			=							self.prepare_config_and_inputs()
										lowercase		,   lowercase		,   lowercase		,   lowercase   :    Any			=							config_and_inputs
										lowercase   :    Any			=							{"pixel_values": pixel_values}
										return config, inputs_dict


@require_tf
class 		a__						(				lowercase_,      lowercase_,      unittest.TestCase						):
			__lowerCAmelCase						=    (
			    (TFMobileViTModel, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation)
			    if is_tf_available()
			    else ()
			)
			__lowerCAmelCase						=    (
			    {"""feature-extraction""": TFMobileViTModel, """image-classification""": TFMobileViTForImageClassification}
			    if is_tf_available()
			    else {}
			)

			__lowerCAmelCase						=    False
			__lowerCAmelCase						=    False
			__lowerCAmelCase						=    False
			__lowerCAmelCase						=    False
			__lowerCAmelCase						=    False
			def       __magic_name__      (      self    ):
										lowercase   :    Optional[Any]			=							TFMobileViTModelTester(self    )
										lowercase   :    Optional[Any]			=							TFMobileViTConfigTester(self     ,   config_class=_a     ,   has_text_modality=_a    )
			def       __magic_name__      (      self    ):
										self.config_tester.run_common_tests()
			@unittest.skip(reason="MobileViT does not use inputs_embeds"    )
			def       __magic_name__      (      self    ):
										pass
			@unittest.skip(reason="MobileViT does not support input and output embeddings"    )
			def       __magic_name__      (      self    ):
										pass
			@unittest.skip(reason="MobileViT does not output attentions"    )
			def       __magic_name__      (      self    ):
										pass
			def       __magic_name__      (      self    ):
										lowercase		,   lowercase   :    Optional[int]			=							self.model_tester.prepare_config_and_inputs_for_common()

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

																	lowercase   :    int			=							["pixel_values"]
																	self.assertListEqual(arg_names[:1]     ,   _a    )
			def       __magic_name__      (      self    ):
										lowercase   :    Optional[int]			=							self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*_a    )
			def       __magic_name__      (      self    ):







										def check_hidden_states_output(_a     ,   _a     ,   _a    ):
																	lowercase   :    List[Any]			=							model_class(_a    )

																	lowercase   :    Optional[int]			=							model(**self._prepare_for_class(_a     ,   _a    )    )

																	lowercase   :    Dict			=							outputs.hidden_states

																	lowercase   :    Optional[Any]			=							5
																	self.assertEqual(len(_a    )     ,   _a    )

																	# MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
																	# with the width and height being successively divided by 2.
																	lowercase   :    Union[str, Any]			=							2
																	for i in range(len(_a    )    ):
																								self.assertListEqual(
																								    list(hidden_states[i].shape[-2:]    )     ,   [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor]     ,   )
																								divisor *= 2

																	self.assertEqual(self.model_tester.output_stride     ,   divisor // 2    )

										lowercase		,   lowercase   :    Union[str, Any]			=							self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
																	lowercase   :    Tuple			=							True
																	check_hidden_states_output(_a     ,   _a     ,   _a    )

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

																	check_hidden_states_output(_a     ,   _a     ,   _a    )
			def       __magic_name__      (      self    ):
										lowercase   :    str			=							self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*_a    )
			def       __magic_name__      (      self    ):
										lowercase   :    Optional[int]			=							self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_semantic_segmentation(*_a    )
			@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       __magic_name__      (      self    ):
										super().test_dataset_conversion()
			def       __magic_name__      (      self     ,   _a     ,   _a     ,   _a=2E-1     ,   _a=2E-1    ):
										self.assertTrue(np.allclose(_a     ,   _a     ,   atol=_a     ,   rtol=_a    )    )
			@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       __magic_name__      (      self    ):
										lowercase		,   lowercase   :    List[Any]			=							self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
																	# Since `TFMobileViTModel` cannot operate with the default `fit()` method.
																	if model_class.__name__ != "TFMobileViTModel":
																								lowercase   :    str			=							model_class(_a    )
																								if getattr(_a     ,   "hf_compute_loss"     ,   _a    ):
																															super().test_keras_fit()
			def       __magic_name__      (      self    ):
										lowercase		,   lowercase   :    List[str]			=							self.model_tester.prepare_config_and_inputs_for_common()
										for model_class in self.all_model_classes:
																	# set an ignore index to correctly test the masked loss used in
																	# `TFMobileViTForSemanticSegmentation`.
																	if model_class.__name__ != "TFMobileViTForSemanticSegmentation":
																								lowercase   :    List[str]			=							5

																	lowercase   :    Optional[Any]			=							model_class(_a    )
																	if getattr(_a     ,   "hf_compute_loss"     ,   _a    ):
																								# The number of elements in the loss should be the same as the number of elements in the label
																								lowercase   :    str			=							self._prepare_for_class(inputs_dict.copy()     ,   _a     ,   return_labels=_a    )
																								lowercase   :    str			=							prepared_for_class[
																								    sorted(prepared_for_class.keys() - inputs_dict.keys()     ,   reverse=_a    )[0]
																								]
																								lowercase   :    Union[str, Any]			=							added_label.shape.as_list()[:1]

																								# Test that model correctly compute the loss with kwargs
																								lowercase   :    Tuple			=							self._prepare_for_class(inputs_dict.copy()     ,   _a     ,   return_labels=_a    )
																								lowercase   :    Optional[int]			=							{"input_ids", "pixel_values", "input_features"}
																								lowercase   :    str			=							possible_input_names.intersection(set(_a    )    ).pop()
																								lowercase   :    str			=							prepared_for_class.pop(_a    )

																								lowercase   :    int			=							model(_a     ,   **_a    )[0]
																								self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]    )

																								# Test that model correctly compute the loss when we mask some positions
																								lowercase   :    Tuple			=							self._prepare_for_class(inputs_dict.copy()     ,   _a     ,   return_labels=_a    )
																								lowercase   :    Union[str, Any]			=							{"input_ids", "pixel_values", "input_features"}
																								lowercase   :    str			=							possible_input_names.intersection(set(_a    )    ).pop()
																								lowercase   :    Optional[int]			=							prepared_for_class.pop(_a    )
																								if "labels" in prepared_for_class:
																															lowercase   :    str			=							prepared_for_class["labels"].numpy()
																															if len(labels.shape    ) > 1 and labels.shape[1] != 1:
																																						# labels[0] = -100
																																						lowercase   :    Optional[int]			=							tf.convert_to_tensor(_a    )
																																						lowercase   :    int			=							model(_a     ,   **_a    )[0]
																																						self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]    )
																																						self.assertTrue(not np.any(np.isnan(loss.numpy()    )    )    )

                # Test that model correctly compute the loss with a dict
																								lowercase   :    int			=							self._prepare_for_class(inputs_dict.copy()     ,   _a     ,   return_labels=_a    )
																								lowercase   :    List[str]			=							model(_a    )[0]
																								self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]    )

																								# Test that model correctly compute the loss with a tuple
																								lowercase   :    str			=							self._prepare_for_class(inputs_dict.copy()     ,   _a     ,   return_labels=_a    )

																								# Get keys that were added with the _prepare_for_class function
																								lowercase   :    str			=							prepared_for_class.keys() - inputs_dict.keys()
																								lowercase   :    Any			=							inspect.signature(model.call    ).parameters
																								lowercase   :    Any			=							list(signature.keys()    )

																								# Create a dictionary holding the location of the tensors in the tuple
																								lowercase   :    Union[str, Any]			=							{0: input_name}
																								for label_key in label_keys:
																															lowercase   :    List[Any]			=							signature_names.index(_a    )
																															lowercase   :    Optional[int]			=							label_key
																								lowercase   :    Optional[int]			=							sorted(tuple_index_mapping.items()    )
																								# Initialize a list with their default values, update the values and convert to a tuple
																								lowercase   :    Union[str, Any]			=							[]

																								for name in signature_names:
																															if name != "kwargs":
																																						list_input.append(signature[name].default    )

																								for index, value in sorted_tuple_index_mapping:
																															lowercase   :    Optional[Any]			=							prepared_for_class[value]

																								lowercase   :    Optional[int]			=							tuple(_a    )

																								# Send to model
																								lowercase   :    str			=							model(tuple_input[:-1]    )[0]

																								self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]    )

			@slow
			def       __magic_name__      (      self    ):







										for model_name in TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	lowercase   :    Any			=							TFMobileViTModel.from_pretrained(_a    )
																	self.assertIsNotNone(_a    )


def   __magic_name__     (				)			->    Optional[Any]:
							lowercase   :    List[str]			=							Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"  )
							return image

@require_tf
class 		a__						(				unittest.TestCase						):
			@slow
			def       __magic_name__      (      self    ):
										lowercase   :    Union[str, Any]			=							TFMobileViTForImageClassification.from_pretrained("apple/mobilevit-xx-small"    )

										lowercase   :    Dict			=							MobileViTImageProcessor.from_pretrained("apple/mobilevit-xx-small"    )
										lowercase   :    Optional[int]			=							prepare_img()
										lowercase   :    Dict			=							image_processor(images=_a     ,   return_tensors="tf"    )

										# forward pass
										lowercase   :    List[str]			=							model(**_a     ,   training=_a    )

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

										lowercase   :    Dict			=							tf.constant([-1.9_3_6_4, -1.2_3_2_7, -0.4_6_5_3]    )

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

			@slow
			def       __magic_name__      (      self    ):
										lowercase   :    Tuple			=							TFMobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small"    )

										lowercase   :    Optional[int]			=							MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small"    )

										lowercase   :    int			=							prepare_img()
										lowercase   :    List[Any]			=							image_processor(images=_a     ,   return_tensors="tf"    )

										# forward pass
										lowercase   :    List[Any]			=							model(inputs.pixel_values     ,   training=_a    )
										lowercase   :    Dict			=							outputs.logits

										# verify the logits
										lowercase   :    List[Any]			=							tf.TensorShape((1, 21, 32, 32)    )
										self.assertEqual(logits.shape     ,   _a    )

										lowercase   :    str			=							tf.constant(
										    [
										        [[6.9_7_1_3, 6.9_7_8_6, 7.2_4_2_2], [7.2_8_9_3, 7.2_8_2_5, 7.4_4_4_6], [7.6_5_8_0, 7.8_7_9_7, 7.9_4_2_0]],
										        [[-1_0.6_8_6_9, -1_0.3_2_5_0, -1_0.3_4_7_1], [-1_0.4_2_2_8, -9.9_8_6_8, -9.7_1_3_2], [-1_1.0_4_0_5, -1_1.0_2_2_1, -1_0.7_3_1_8]],
										        [[-3.3_0_8_9, -2.8_5_3_9, -2.6_7_4_0], [-3.2_7_0_6, -2.5_6_2_1, -2.5_1_0_8], [-3.2_5_3_4, -2.6_6_1_5, -2.6_6_5_1]],
										    ]    )

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




"""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 		a__						:
   def __init__(      self     ,   _a     ,   _a=13     ,   _a=32     ,   _a=3     ,   _a=4     ,   _a=[10, 20, 30, 40]     ,   _a=[2, 2, 3, 2]     ,   _a=True     ,   _a=True     ,   _a=37     ,   _a="gelu"     ,   _a=10     ,   _a=0.0_2     ,   _a=3     ,   _a=None     ,   ):
          lowercase   :    Any			=							parent
          lowercase   :    Optional[int]			=							batch_size
          lowercase   :    Optional[Any]			=							image_size
          lowercase   :    Any			=							num_channels
          lowercase   :    str			=							num_stages
          lowercase   :    Union[str, Any]			=							hidden_sizes
          lowercase   :    Optional[Any]			=							depths
          lowercase   :    str			=							is_training
          lowercase   :    int			=							use_labels
          lowercase   :    str			=							intermediate_size
          lowercase   :    Dict			=							hidden_act
          lowercase   :    int			=							type_sequence_label_size
          lowercase   :    Optional[int]			=							initializer_range
          lowercase   :    Dict			=							scope
   def       __magic_name__      (      self    ):
          lowercase   :    Optional[Any]			=							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

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

          lowercase   :    str			=							self.get_config()

          return config, pixel_values, labels
   def       __magic_name__      (      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=_a     ,   initializer_range=self.initializer_range     ,   )
   def       __magic_name__      (      self     ,   _a     ,   _a     ,   _a    ):
          lowercase   :    Any			=							TFConvNextModel(config=_a    )
          lowercase   :    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 // 32, self.image_size // 32)     ,   )
   def       __magic_name__      (      self     ,   _a     ,   _a     ,   _a    ):
          lowercase   :    List[Any]			=							self.type_sequence_label_size
          lowercase   :    List[str]			=							TFConvNextForImageClassification(_a    )
          lowercase   :    int			=							model(_a     ,   labels=_a     ,   training=_a    )
          self.parent.assertEqual(result.logits.shape     ,   (self.batch_size, self.type_sequence_label_size)    )

   def       __magic_name__      (      self    ):
          lowercase   :    Union[str, Any]			=							self.prepare_config_and_inputs()
          lowercase		,   lowercase		,   lowercase   :    str			=							config_and_inputs
          lowercase   :    List[Any]			=							{"pixel_values": pixel_values}
          return config, inputs_dict


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

   __lowerCAmelCase						=    False
   __lowerCAmelCase						=    False
   __lowerCAmelCase						=    False
   __lowerCAmelCase						=    False
   __lowerCAmelCase						=    False
   def       __magic_name__      (      self    ):
          lowercase   :    Tuple			=							TFConvNextModelTester(self    )
          lowercase   :    int			=							ConfigTester(
              self     ,   config_class=_a     ,   has_text_modality=_a     ,   hidden_size=37     ,   )
   @unittest.skip(reason="ConvNext does not use inputs_embeds"    )
   def       __magic_name__      (      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       __magic_name__      (      self    ):
          super().test_keras_fit()
   @unittest.skip(reason="ConvNext does not support input and output embeddings"    )
   def       __magic_name__      (      self    ):
          pass
   def       __magic_name__      (      self    ):
          lowercase		,   lowercase   :    List[str]			=							self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
                 lowercase   :    Dict			=							model_class(_a    )
                 lowercase   :    str			=							inspect.signature(model.call    )
                 # signature.parameters is an OrderedDict => so arg_names order is deterministic
                 lowercase   :    Optional[int]			=							[*signature.parameters.keys()]

                 lowercase   :    Optional[Any]			=							["pixel_values"]
                 self.assertListEqual(arg_names[:1]     ,   _a    )
   def       __magic_name__      (      self    ):
          lowercase   :    Union[str, Any]			=							self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*_a    )
   @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       __magic_name__      (      self    ):
          super().test_dataset_conversion()
   def       __magic_name__      (      self    ):
          def check_hidden_states_output(_a     ,   _a     ,   _a    ):
                 lowercase   :    str			=							model_class(_a    )

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

                 lowercase   :    str			=							self.model_tester.num_stages
                 self.assertEqual(len(_a    )     ,   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]     ,   )

          lowercase		,   lowercase   :    Any			=							self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
                 lowercase   :    Union[str, Any]			=							True
                 check_hidden_states_output(_a     ,   _a     ,   _a    )

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

                 check_hidden_states_output(_a     ,   _a     ,   _a    )
   def       __magic_name__      (      self    ):
          lowercase		,   lowercase   :    List[str]			=							self.model_tester.prepare_config_and_inputs_for_common()

          def check_equivalence(_a     ,   _a     ,   _a     ,   _a={}    ):
                 lowercase   :    Union[str, Any]			=							model(_a     ,   return_dict=_a     ,   **_a    )
                 lowercase   :    Dict			=							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:
                 lowercase   :    str			=							model_class(_a    )

                 lowercase   :    int			=							self._prepare_for_class(_a     ,   _a    )
                 lowercase   :    Dict			=							self._prepare_for_class(_a     ,   _a    )
                 check_equivalence(_a     ,   _a     ,   _a    )

                 lowercase   :    Tuple			=							self._prepare_for_class(_a     ,   _a     ,   return_labels=_a    )
                 lowercase   :    Union[str, Any]			=							self._prepare_for_class(_a     ,   _a     ,   return_labels=_a    )
                 check_equivalence(_a     ,   _a     ,   _a    )

                 lowercase   :    Any			=							self._prepare_for_class(_a     ,   _a    )
                 lowercase   :    List[str]			=							self._prepare_for_class(_a     ,   _a    )
                 check_equivalence(_a     ,   _a     ,   _a     ,   {"output_hidden_states": True}    )

                 lowercase   :    Union[str, Any]			=							self._prepare_for_class(_a     ,   _a     ,   return_labels=_a    )
                 lowercase   :    Optional[Any]			=							self._prepare_for_class(_a     ,   _a     ,   return_labels=_a    )
                 check_equivalence(_a     ,   _a     ,   _a     ,   {"output_hidden_states": True}    )
   def       __magic_name__      (      self    ):
          lowercase   :    int			=							self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*_a    )

   @slow
   def       __magic_name__      (      self    ):
          lowercase   :    Tuple			=							TFConvNextModel.from_pretrained("facebook/convnext-tiny-224"    )
          self.assertIsNotNone(_a    )


def   __magic_name__     (				)			->    Any:
       lowercase   :    List[str]			=							Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"  )
       return image

@require_tf
@require_vision
class 		a__						(				unittest.TestCase						):
   @cached_property
   def       __magic_name__      (      self    ):
          return ConvNextImageProcessor.from_pretrained("facebook/convnext-tiny-224"    ) if is_vision_available() else None

   @slow
   def       __magic_name__      (      self    ):
          lowercase   :    Dict			=							TFConvNextForImageClassification.from_pretrained("facebook/convnext-tiny-224"    )

          lowercase   :    List[str]			=							self.default_image_processor
          lowercase   :    List[str]			=							prepare_img()
          lowercase   :    Union[str, Any]			=							image_processor(images=_a     ,   return_tensors="tf"    )

          # forward pass
          lowercase   :    str			=							model(**_a    )

          # verify the logits
          lowercase   :    List[str]			=							tf.TensorShape((1, 1_000)    )
          self.assertEqual(outputs.logits.shape     ,   _a    )

          lowercase   :    int			=							tf.constant([-0.0_2_6_0, -0.4_7_3_9, 0.1_9_1_1]    )

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


