



import inspect
import unittest

from transformers import ConvNextConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
							import torch

							from transformers import ConvNextBackbone, ConvNextForImageClassification, ConvNextModel
							from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
							from PIL import Image

							from transformers import AutoImageProcessor
class 			_snake_case     :




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




				def 							A__ (  self   :  Union[str, Any]  ):
							lowercase__   					=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

							lowercase__   					=			None
							if self.use_labels:
										lowercase__   					=			ids_tensor([self.batch_size],   self.num_labels  )

							lowercase__   					=			self.get_config()
							return config, pixel_values, labels




				def 							A__ (  self   :  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=__lowercase,   initializer_range=self.initializer_range,   out_features=self.out_features,   out_indices=self.out_indices,   num_labels=self.num_labels,   )




				def 							A__ (  self   :  List[str],   __lowercase   :  Union[str, Any],   __lowercase   :  Any,   __lowercase   :  List[Any]  ):
							lowercase__   					=			ConvNextModel(config=__lowercase  )
							model.to(__lowercase  )
							model.eval()
							lowercase__   					=			model(__lowercase  )
							# 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 							A__ (  self   :  List[Any],   __lowercase   :  Tuple,   __lowercase   :  str,   __lowercase   :  str  ):
							lowercase__   					=			ConvNextForImageClassification(__lowercase  )
							model.to(__lowercase  )
							model.eval()
							lowercase__   					=			model(__lowercase,   labels=__lowercase  )
							self.parent.assertEqual(result.logits.shape,   (self.batch_size, self.num_labels)  )




				def 							A__ (  self   :  int,   __lowercase   :  Any,   __lowercase   :  List[str],   __lowercase   :  List[str]  ):
							lowercase__   					=			ConvNextBackbone(config=__lowercase  )
							model.to(__lowercase  )
							model.eval()
							lowercase__   					=			model(__lowercase  )

							# verify hidden states
							self.parent.assertEqual(len(result.feature_maps  ),   len(config.out_features  )  )
							self.parent.assertListEqual(list(result.feature_maps[0].shape  ),   [self.batch_size, self.hidden_sizes[1], 4, 4]  )

							# verify channels
							self.parent.assertEqual(len(model.channels  ),   len(config.out_features  )  )
							self.parent.assertListEqual(model.channels,   config.hidden_sizes[1:]  )

							# verify backbone works with out_features=None
							lowercase__   					=			None
							lowercase__   					=			ConvNextBackbone(config=__lowercase  )
							model.to(__lowercase  )
							model.eval()
							lowercase__   					=			model(__lowercase  )

							# verify feature maps
							self.parent.assertEqual(len(result.feature_maps  ),   1  )
							self.parent.assertListEqual(list(result.feature_maps[0].shape  ),   [self.batch_size, self.hidden_sizes[-1], 1, 1]  )

							# verify channels
							self.parent.assertEqual(len(model.channels  ),   1  )
							self.parent.assertListEqual(model.channels,   [config.hidden_sizes[-1]]  )




				def 							A__ (  self   :  List[Any]  ):
							lowercase__   					=			self.prepare_config_and_inputs()
							lowercase__					,    lowercase__					,    lowercase__   					=			config_and_inputs
							lowercase__   					=			{"pixel_values": pixel_values}
							return config, inputs_dict
@require_torch
class 			_snake_case     (   lowercase__      ,		lowercase__      ,		unittest.TestCase):
				UpperCamelCase__			:   List[Any]       						=(
				    (
				        ConvNextModel,
				        ConvNextForImageClassification,
				        ConvNextBackbone,
				    )
				    if is_torch_available()
				    else ()
				)
				UpperCamelCase__			:   Dict       						=(
				    {"""feature-extraction""": ConvNextModel, """image-classification""": ConvNextForImageClassification}
				    if is_torch_available()
				    else {}
				)

				UpperCamelCase__			:   str       						=True
				UpperCamelCase__			:   Dict       						=False
				UpperCamelCase__			:   Optional[Any]       						=False
				UpperCamelCase__			:   str       						=False
				UpperCamelCase__			:   str       						=False




				def 							A__ (  self   :  str  ):
							lowercase__   					=			ConvNextModelTester(self  )
							lowercase__   					=			ConfigTester(self,   config_class=__lowercase,   has_text_modality=__lowercase,   hidden_size=37  )




				def 							A__ (  self   :  Tuple  ):
							self.create_and_test_config_common_properties()
							self.config_tester.create_and_test_config_to_json_string()
							self.config_tester.create_and_test_config_to_json_file()
							self.config_tester.create_and_test_config_from_and_save_pretrained()
							self.config_tester.create_and_test_config_with_num_labels()
							self.config_tester.check_config_can_be_init_without_params()
							self.config_tester.check_config_arguments_init()




				def 							A__ (  self   :  Optional[Any]  ):
							return




				@unittest.skip(reason="ConvNext does not use inputs_embeds"  )
				def 							A__ (  self   :  str  ):
							pass




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




				@unittest.skip(reason="ConvNext does not use feedforward chunking"  )
				def 							A__ (  self   :  int  ):
							pass




				def 							A__ (  self   :  str  ):
							lowercase__					,    lowercase__   					=			self.model_tester.prepare_config_and_inputs_for_common()

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

										lowercase__   					=			["pixel_values"]
										self.assertListEqual(arg_names[:1],   __lowercase  )




				def 							A__ (  self   :  Dict  ):
							lowercase__   					=			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*__lowercase  )




				def 							A__ (  self   :  Union[str, Any]  ):
							lowercase__   					=			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_backbone(*__lowercase  )




				def 							A__ (  self   :  Tuple  ):
							def check_hidden_states_output(__lowercase   :  Optional[int],   __lowercase   :  List[str],   __lowercase   :  Any  ):
										lowercase__   					=			model_class(__lowercase  )
										model.to(__lowercase  )
										model.eval()

										with torch.no_grad():
													lowercase__   					=			model(**self._prepare_for_class(__lowercase,   __lowercase  )  )

										lowercase__   					=			outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

										lowercase__   					=			self.model_tester.num_stages
										self.assertEqual(len(__lowercase  ),   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__   					=			self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
										lowercase__   					=			True
										check_hidden_states_output(__lowercase,   __lowercase,   __lowercase  )

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

										check_hidden_states_output(__lowercase,   __lowercase,   __lowercase  )




				def 							A__ (  self   :  Optional[int]  ):
							lowercase__   					=			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*__lowercase  )




				@slow
				def 							A__ (  self   :  List[str]  ):
							for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										lowercase__   					=			ConvNextModel.from_pretrained(__lowercase  )
										self.assertIsNotNone(__lowercase  )



def __lowerCAmelCase	(       ):
			lowercase__   					=			Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"					)
			return image
@require_torch
@require_vision
class 			_snake_case     (   unittest.TestCase):




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




				@slow
				def 							A__ (  self   :  int  ):
							lowercase__   					=			ConvNextForImageClassification.from_pretrained("facebook/convnext-tiny-224"  ).to(__lowercase  )

							lowercase__   					=			self.default_image_processor
							lowercase__   					=			prepare_img()
							lowercase__   					=			image_processor(images=__lowercase,   return_tensors="pt"  ).to(__lowercase  )

							# forward pass
							with torch.no_grad():
										lowercase__   					=			model(**__lowercase  )

							# verify the logits
							lowercase__   					=			torch.Size((1, 1000)  )
							self.assertEqual(outputs.logits.shape,   __lowercase  )

							lowercase__   					=			torch.tensor([-0.0260, -0.4739, 0.1911]  ).to(__lowercase  )

							self.assertTrue(torch.allclose(outputs.logits[0, :3],   __lowercase,   atol=1e-4  )  )
@require_torch
class 			_snake_case     (   unittest.TestCase      ,		lowercase__):
				UpperCamelCase__			:   int       						=(ConvNextBackbone,) if is_torch_available() else ()
				UpperCamelCase__			:   Dict       						=ConvNextConfig

				UpperCamelCase__			:   str       						=False




				def 							A__ (  self   :  int  ):
							lowercase__   					=			ConvNextModelTester(self  )









from __future__ import annotations



def __lowerCAmelCase	(       SCREAMING_SNAKE_CASE_					):
			return len(set(SCREAMING_SNAKE_CASE_					)					) == len(SCREAMING_SNAKE_CASE_					)


if __name__ == "__main__":
							import doctest

							doctest.testmod()




