



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


	"""simple docstring"""


	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.02						,a_=3						,a_=None						,)	->     List[str]:
								_UpperCAmelCase						:		int      =				parent
								_UpperCAmelCase						:		List[str]      =				batch_size
								_UpperCAmelCase						:		List[Any]      =				image_size
								_UpperCAmelCase						:		Optional[Any]      =				num_channels
								_UpperCAmelCase						:		Optional[int]      =				num_stages
								_UpperCAmelCase						:		List[str]      =				hidden_sizes
								_UpperCAmelCase						:		List[str]      =				depths
								_UpperCAmelCase						:		str      =				is_training
								_UpperCAmelCase						:		int      =				use_labels
								_UpperCAmelCase						:		Optional[int]      =				intermediate_size
								_UpperCAmelCase						:		Optional[int]      =				hidden_act
								_UpperCAmelCase						:		Optional[int]      =				type_sequence_label_size
								_UpperCAmelCase						:		Any      =				initializer_range
								_UpperCAmelCase						:		str      =				scope







	def _snake_case				(							self							)	->     List[str]:
								_UpperCAmelCase						:		Optional[int]      =				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

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

								_UpperCAmelCase						:		Optional[Any]      =				self.get_config()

								return config, pixel_values, labels







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







	def _snake_case				(							self							)	->     str:
								_UpperCAmelCase						:		Union[str, Any]      =				self.prepare_config_and_inputs()
								_UpperCAmelCase						:		int      =				config_and_inputs
								_UpperCAmelCase						:		List[str]      =				{"""pixel_values""": pixel_values}
								return config, inputs_dict







@require_tf
class 							lowercase (						_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 _snake_case				(							self							)	->     int:
								_UpperCAmelCase						:		Tuple      =				TFConvNextModelTester(self							)
								_UpperCAmelCase						:		Union[str, Any]      =				ConfigTester(
								    self						,config_class=a_						,has_text_modality=a_						,hidden_size=37						,)







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







	@unittest.skip(reason="""ConvNext does not support input and output embeddings"""							)
	def _snake_case				(							self							)	->     int:
								pass







	def _snake_case				(							self							)	->     Dict:
								_UpperCAmelCase						:		Optional[int]      =				self.model_tester.prepare_config_and_inputs_for_common()

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

															_UpperCAmelCase						:		Tuple      =				["""pixel_values"""]
															self.assertListEqual(arg_names[:1]						,a_							)







	def _snake_case				(							self							)	->     Tuple:
								_UpperCAmelCase						:		str      =				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 _snake_case				(							self							)	->     Optional[int]:
								super().test_dataset_conversion()







	def _snake_case				(							self							)	->     Tuple:
								def check_hidden_states_output(a_						,a_						,a_							):
															_UpperCAmelCase						:		Any      =				model_class(a_							)

															_UpperCAmelCase						:		List[str]      =				model(**self._prepare_for_class(a_						,a_							)							)
															_UpperCAmelCase						:		Any      =				outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

															_UpperCAmelCase						:		int      =				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]						,)

								_UpperCAmelCase						:		Tuple      =				self.model_tester.prepare_config_and_inputs_for_common()

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

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

															check_hidden_states_output(a_						,a_						,a_							)







	def _snake_case				(							self							)	->     str:
								_UpperCAmelCase						:		Tuple      =				self.model_tester.prepare_config_and_inputs_for_common()

								def check_equivalence(a_						,a_						,a_						,a_={}							):
															_UpperCAmelCase						:		Dict      =				model(a_						,return_dict=a_						,**a_							)
															_UpperCAmelCase						:		Any      =				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:
															_UpperCAmelCase						:		Dict      =				model_class(a_							)

															_UpperCAmelCase						:		Tuple      =				self._prepare_for_class(a_						,a_							)
															_UpperCAmelCase						:		List[Any]      =				self._prepare_for_class(a_						,a_							)
															check_equivalence(a_						,a_						,a_							)

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

															_UpperCAmelCase						:		Optional[int]      =				self._prepare_for_class(a_						,a_							)
															_UpperCAmelCase						:		Dict      =				self._prepare_for_class(a_						,a_							)
															check_equivalence(a_						,a_						,a_						,{"""output_hidden_states""": True}							)

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







	def _snake_case				(							self							)	->     Any:
								_UpperCAmelCase						:		str      =				self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*a_							)







	@slow
	def _snake_case				(							self							)	->     Tuple:
								_UpperCAmelCase						:		List[str]      =				TFConvNextModel.from_pretrained("""facebook/convnext-tiny-224"""							)
								self.assertIsNotNone(a_							)







def 					snake_case_      (  )->	Optional[int]:





							'''simple docstring'''


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



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


	"""simple docstring"""


	@cached_property
	def _snake_case				(							self							)	->     List[str]:
								return ConvNextImageProcessor.from_pretrained("""facebook/convnext-tiny-224"""							) if is_vision_available() else None







	@slow
	def _snake_case				(							self							)	->     Any:
								_UpperCAmelCase						:		Optional[Any]      =				TFConvNextForImageClassification.from_pretrained("""facebook/convnext-tiny-224"""							)

								_UpperCAmelCase						:		Optional[int]      =				self.default_image_processor
								_UpperCAmelCase						:		int      =				prepare_img()
								_UpperCAmelCase						:		str      =				image_processor(images=a_						,return_tensors="""tf"""							)

								# forward pass
								_UpperCAmelCase						:		str      =				model(**a_							)

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

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

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








'''simple docstring'''






from typing import TYPE_CHECKING

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


A_							:				Union[str, Any]						=			{
    """configuration_segformer""": ["""SEGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """SegformerConfig""", """SegformerOnnxConfig"""]
}

try:
   if not is_vision_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   A_							:				Tuple						=			["""SegformerFeatureExtractor"""]
   A_							:				Tuple						=			["""SegformerImageProcessor"""]

try:
   if not is_torch_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   A_							:				Dict						=			[
       """SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""",
       """SegformerDecodeHead""",
       """SegformerForImageClassification""",
       """SegformerForSemanticSegmentation""",
       """SegformerLayer""",
       """SegformerModel""",
       """SegformerPreTrainedModel""",
   ]

try:
   if not is_tf_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   A_							:				List[str]						=			[
       """TF_SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""",
       """TFSegformerDecodeHead""",
       """TFSegformerForImageClassification""",
       """TFSegformerForSemanticSegmentation""",
       """TFSegformerModel""",
       """TFSegformerPreTrainedModel""",
   ]


if TYPE_CHECKING:
   from .configuration_segformer import SEGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, SegformerConfig, SegformerOnnxConfig

   try:
      if not is_vision_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .feature_extraction_segformer import SegformerFeatureExtractor
      from .image_processing_segformer import SegformerImageProcessor

   try:
      if not is_torch_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_segformer import (
          SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
          SegformerDecodeHead,
          SegformerForImageClassification,
          SegformerForSemanticSegmentation,
          SegformerLayer,
          SegformerModel,
          SegformerPreTrainedModel,
      )
   try:
      if not is_tf_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_tf_segformer import (
          TF_SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
          TFSegformerDecodeHead,
          TFSegformerForImageClassification,
          TFSegformerForSemanticSegmentation,
          TFSegformerModel,
          TFSegformerPreTrainedModel,
      )

else:
   import sys

   A_							:				Optional[Any]						=			_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)



