


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





				"""simple docstring"""







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



				def 	lowerCAmelCase__		(    self  ):
								SCREAMING_SNAKE_CASE__  				=					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

								SCREAMING_SNAKE_CASE__  				=					None
								if self.use_labels:
												SCREAMING_SNAKE_CASE__  				=					ids_tensor([self.batch_size]							,		self.type_sequence_label_size  )

								SCREAMING_SNAKE_CASE__  				=					self.get_config()

								return config, pixel_values, labels



				def 	lowerCAmelCase__		(    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 	lowerCAmelCase__		(    self							,		UpperCAmelCase__							,		UpperCAmelCase__							,		UpperCAmelCase__  ):
								SCREAMING_SNAKE_CASE__  				=					TFConvNextModel(config=__A  )
								SCREAMING_SNAKE_CASE__  				=					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 	lowerCAmelCase__		(    self							,		UpperCAmelCase__							,		UpperCAmelCase__							,		UpperCAmelCase__  ):
								SCREAMING_SNAKE_CASE__  				=					self.type_sequence_label_size
								SCREAMING_SNAKE_CASE__  				=					TFConvNextForImageClassification(__A  )
								SCREAMING_SNAKE_CASE__  				=					model(__A							,		labels=__A							,		training=__A  )
								self.parent.assertEqual(result.logits.shape							,		(self.batch_size, self.type_sequence_label_size)  )






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


@require_tf
class       lowerCamelCase_		(      lowerCamelCase__							,	lowerCamelCase__							,	unittest.TestCase ):





				"""simple docstring"""







				_lowerCAmelCase   :   List[str]   				=       (TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
				_lowerCAmelCase   :   Union[str, Any]   				=       (
				    {"feature-extraction": TFConvNextModel, "image-classification": TFConvNextForImageClassification}
				    if is_tf_available()
				    else {}
				)

				_lowerCAmelCase   :   List[str]   				=       False
				_lowerCAmelCase   :   Optional[Any]   				=       False
				_lowerCAmelCase   :   Union[str, Any]   				=       False
				_lowerCAmelCase   :   List[str]   				=       False
				_lowerCAmelCase   :   Any   				=       False



				def 	lowerCAmelCase__		(    self  ):
								SCREAMING_SNAKE_CASE__  				=					TFConvNextModelTester(self  )
								SCREAMING_SNAKE_CASE__  				=					ConfigTester(
								    self							,		config_class=__A							,		has_text_modality=__A							,		hidden_size=37							,		)



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



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



				def 	lowerCAmelCase__		(    self  ):
								SCREAMING_SNAKE_CASE__  				=					self.model_tester.prepare_config_and_inputs_for_common()

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

												SCREAMING_SNAKE_CASE__  				=					['''pixel_values''']
												self.assertListEqual(arg_names[:1]							,		__A  )



				def 	lowerCAmelCase__		(    self  ):
								SCREAMING_SNAKE_CASE__  				=					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 	lowerCAmelCase__		(    self  ):
								super().test_dataset_conversion()



				def 	lowerCAmelCase__		(    self  ):
								def check_hidden_states_output(UpperCAmelCase__							,		UpperCAmelCase__							,		UpperCAmelCase__  ):
												SCREAMING_SNAKE_CASE__  				=					model_class(__A  )

												SCREAMING_SNAKE_CASE__  				=					model(**self._prepare_for_class(__A							,		__A  )  )
												SCREAMING_SNAKE_CASE__  				=					outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

												SCREAMING_SNAKE_CASE__  				=					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]							,		)

								SCREAMING_SNAKE_CASE__  				=					self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
												SCREAMING_SNAKE_CASE__  				=					True
												check_hidden_states_output(__A							,		__A							,		__A  )

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

												check_hidden_states_output(__A							,		__A							,		__A  )



				def 	lowerCAmelCase__		(    self  ):
								SCREAMING_SNAKE_CASE__  				=					self.model_tester.prepare_config_and_inputs_for_common()

								def check_equivalence(UpperCAmelCase__							,		UpperCAmelCase__							,		UpperCAmelCase__							,		UpperCAmelCase__={}  ):
												SCREAMING_SNAKE_CASE__  				=					model(__A							,		return_dict=__A							,		**__A  )
												SCREAMING_SNAKE_CASE__  				=					model(__A							,		return_dict=__A							,		**__A  ).to_tuple()

												def recursive_check(UpperCAmelCase__							,		UpperCAmelCase__  ):
																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:
												SCREAMING_SNAKE_CASE__  				=					model_class(__A  )

												SCREAMING_SNAKE_CASE__  				=					self._prepare_for_class(__A							,		__A  )
												SCREAMING_SNAKE_CASE__  				=					self._prepare_for_class(__A							,		__A  )
												check_equivalence(__A							,		__A							,		__A  )

												SCREAMING_SNAKE_CASE__  				=					self._prepare_for_class(__A							,		__A							,		return_labels=__A  )
												SCREAMING_SNAKE_CASE__  				=					self._prepare_for_class(__A							,		__A							,		return_labels=__A  )
												check_equivalence(__A							,		__A							,		__A  )

												SCREAMING_SNAKE_CASE__  				=					self._prepare_for_class(__A							,		__A  )
												SCREAMING_SNAKE_CASE__  				=					self._prepare_for_class(__A							,		__A  )
												check_equivalence(__A							,		__A							,		__A							,		{"output_hidden_states": True}  )

												SCREAMING_SNAKE_CASE__  				=					self._prepare_for_class(__A							,		__A							,		return_labels=__A  )
												SCREAMING_SNAKE_CASE__  				=					self._prepare_for_class(__A							,		__A							,		return_labels=__A  )
												check_equivalence(__A							,		__A							,		__A							,		{"output_hidden_states": True}  )



				def 	lowerCAmelCase__		(    self  ):
								SCREAMING_SNAKE_CASE__  				=					self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*__A  )






				@slow
				def 	lowerCAmelCase__		(    self  ):
								SCREAMING_SNAKE_CASE__  				=					TFConvNextModel.from_pretrained("facebook/convnext-tiny-224"  )
								self.assertIsNotNone(__A  )


def __lowercase  (   ):
				SCREAMING_SNAKE_CASE__  				=					Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"	)
				return image


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





				"""simple docstring"""







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






				@slow
				def 	lowerCAmelCase__		(    self  ):
								SCREAMING_SNAKE_CASE__  				=					TFConvNextForImageClassification.from_pretrained("facebook/convnext-tiny-224"  )

								SCREAMING_SNAKE_CASE__  				=					self.default_image_processor
								SCREAMING_SNAKE_CASE__  				=					prepare_img()
								SCREAMING_SNAKE_CASE__  				=					image_processor(images=__A							,		return_tensors="tf"  )

								# forward pass
								SCREAMING_SNAKE_CASE__  				=					model(**__A  )

								# verify the logits
								SCREAMING_SNAKE_CASE__  				=					tf.TensorShape((1, 1000)  )
								self.assertEqual(outputs.logits.shape							,		__A  )

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

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



def      a__	(						UpperCAmelCase				:     list     )    ->		list:
  UpperCAmelCase			:				Tuple										=					len(UpperCAmelCase     )

  # Set the gap value to be decreased by a factor of 1.3
  # after each iteration
  UpperCAmelCase			:				Optional[Any]										=					1.3

  # Continue sorting until the gap is 1
  while gap > 1:
    # Decrease the gap value
    UpperCAmelCase			:				int										=					int(gap / shrink     )

    # Sort the elements using insertion sort
    for i in range(UpperCAmelCase							,					len(UpperCAmelCase     )     ):
      UpperCAmelCase			:				Union[str, Any]										=					collection[i]
      UpperCAmelCase			:				List[Any]										=					i
      while j >= gap and collection[j - gap] > temp:
        UpperCAmelCase			:				int										=					collection[j - gap]
        j -= gap
      UpperCAmelCase			:				List[Any]										=					temp

  return collection


if __name__ == "__main__":
     import doctest

     doctest.testmod()





