


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






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






		def _snake_case		(						self				:     str):
				SCREAMING_SNAKE_CASE_				:str				     =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

				SCREAMING_SNAKE_CASE_				:List[Any]				     =						None
				if self.use_labels:
						SCREAMING_SNAKE_CASE_				:Any				     =						ids_tensor([self.batch_size]   ,  self.num_labels)

				SCREAMING_SNAKE_CASE_				:Tuple				     =						self.get_config()
				return config, pixel_values, labels






		def _snake_case		(						self				:     int):
				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   ,  out_features=self.out_features   ,  out_indices=self.out_indices   ,  num_labels=self.num_labels   ,  )






		def _snake_case		(						self				:     Union[str, Any]   ,  UpperCAmelCase				:     str   ,  UpperCAmelCase				:     List[str]   ,  UpperCAmelCase				:     List[Any]):
				SCREAMING_SNAKE_CASE_				:str				     =						ConvNextModel(config=UpperCAmelCase)
				model.to(UpperCAmelCase)
				model.eval()
				SCREAMING_SNAKE_CASE_				:Dict				     =						model(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 _snake_case		(						self				:     List[Any]   ,  UpperCAmelCase				:     int   ,  UpperCAmelCase				:     Any   ,  UpperCAmelCase				:     Union[str, Any]):
				SCREAMING_SNAKE_CASE_				:int				     =						ConvNextForImageClassification(UpperCAmelCase)
				model.to(UpperCAmelCase)
				model.eval()
				SCREAMING_SNAKE_CASE_				:Optional[int]				     =						model(UpperCAmelCase   ,  labels=UpperCAmelCase)
				self.parent.assertEqual(result.logits.shape   ,  (self.batch_size, self.num_labels))






		def _snake_case		(						self				:     Tuple   ,  UpperCAmelCase				:     Dict   ,  UpperCAmelCase				:     Tuple   ,  UpperCAmelCase				:     int):
				SCREAMING_SNAKE_CASE_				:int				     =						ConvNextBackbone(config=UpperCAmelCase)
				model.to(UpperCAmelCase)
				model.eval()
				SCREAMING_SNAKE_CASE_				:Tuple				     =						model(UpperCAmelCase)

				# 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
				SCREAMING_SNAKE_CASE_				:List[str]				     =						None
				SCREAMING_SNAKE_CASE_				:str				     =						ConvNextBackbone(config=UpperCAmelCase)
				model.to(UpperCAmelCase)
				model.eval()
				SCREAMING_SNAKE_CASE_				:Tuple				     =						model(UpperCAmelCase)

				# 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 _snake_case		(						self				:     str):
				SCREAMING_SNAKE_CASE_				:Tuple				     =						self.prepare_config_and_inputs()
				SCREAMING_SNAKE_CASE_     ,				SCREAMING_SNAKE_CASE_     ,				SCREAMING_SNAKE_CASE_				:int				     =						config_and_inputs
				SCREAMING_SNAKE_CASE_				:List[str]				     =						{"pixel_values": pixel_values}
				return config, inputs_dict




@require_torch
class 						_UpperCAmelCase      (     lowercase		,		lowercase		,		unittest.TestCase							):
		lowerCamelCase_	:			str       			=  (
		    (
		        ConvNextModel,
		        ConvNextForImageClassification,
		        ConvNextBackbone,
		    )
		    if is_torch_available()
		    else ()
		)
		lowerCamelCase_	:			Union[str, Any]       			=  (
		    {"""feature-extraction""": ConvNextModel, """image-classification""": ConvNextForImageClassification}
		    if is_torch_available()
		    else {}
		)

		lowerCamelCase_	:			int       			=  True
		lowerCamelCase_	:			str       			=  False
		lowerCamelCase_	:			Tuple       			=  False
		lowerCamelCase_	:			str       			=  False
		lowerCamelCase_	:			Dict       			=  False






		def _snake_case		(						self				:     Tuple):
				SCREAMING_SNAKE_CASE_				:Dict				     =						ConvNextModelTester(self)
				SCREAMING_SNAKE_CASE_				:List[str]				     =						ConfigTester(self   ,  config_class=UpperCAmelCase   ,  has_text_modality=UpperCAmelCase   ,  hidden_size=37)






		def _snake_case		(						self				:     List[Any]):
				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 _snake_case		(						self				:     List[str]):
				return






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






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






		@unittest.skip(reason="ConvNext does not use feedforward chunking")
		def _snake_case		(						self				:     List[Any]):
				pass






		def _snake_case		(						self				:     Union[str, Any]):
				SCREAMING_SNAKE_CASE_     ,				SCREAMING_SNAKE_CASE_				:str				     =						self.model_tester.prepare_config_and_inputs_for_common()

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

						SCREAMING_SNAKE_CASE_				:Optional[int]				     =						["pixel_values"]
						self.assertListEqual(arg_names[:1]   ,  UpperCAmelCase)






		def _snake_case		(						self				:     Any):
				SCREAMING_SNAKE_CASE_				:Optional[Any]				     =						self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*UpperCAmelCase)






		def _snake_case		(						self				:     List[str]):
				SCREAMING_SNAKE_CASE_				:List[str]				     =						self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_backbone(*UpperCAmelCase)






		def _snake_case		(						self				:     Union[str, Any]):
				def check_hidden_states_output(UpperCAmelCase				:     Tuple   ,  UpperCAmelCase				:     int   ,  UpperCAmelCase				:     Any):
						SCREAMING_SNAKE_CASE_				:Any				     =						model_class(UpperCAmelCase)
						model.to(UpperCAmelCase)
						model.eval()

						with torch.no_grad():
								SCREAMING_SNAKE_CASE_				:Any				     =						model(**self._prepare_for_class(UpperCAmelCase   ,  UpperCAmelCase))

						SCREAMING_SNAKE_CASE_				:List[Any]				     =						outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

						SCREAMING_SNAKE_CASE_				:Tuple				     =						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]   ,  )

				SCREAMING_SNAKE_CASE_     ,				SCREAMING_SNAKE_CASE_				:Optional[Any]				     =						self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
						SCREAMING_SNAKE_CASE_				:Tuple				     =						True
						check_hidden_states_output(UpperCAmelCase   ,  UpperCAmelCase   ,  UpperCAmelCase)

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

						check_hidden_states_output(UpperCAmelCase   ,  UpperCAmelCase   ,  UpperCAmelCase)






		def _snake_case		(						self				:     List[Any]):
				SCREAMING_SNAKE_CASE_				:Optional[int]				     =						self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase)







		@slow
		def _snake_case		(						self				:     Dict):
				for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
						SCREAMING_SNAKE_CASE_				:List[str]				     =						ConvNextModel.from_pretrained(UpperCAmelCase)
						self.assertIsNotNone(UpperCAmelCase)




def     lowercase	(    ):



		'''simple docstring'''




		SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
		return image



@require_torch
@require_vision
class 						_UpperCAmelCase      (     unittest.TestCase							):






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







		@slow
		def _snake_case		(						self				:     str):
				SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						ConvNextForImageClassification.from_pretrained("facebook/convnext-tiny-224").to(UpperCAmelCase)

				SCREAMING_SNAKE_CASE_				:Optional[int]				     =						self.default_image_processor
				SCREAMING_SNAKE_CASE_				:List[str]				     =						prepare_img()
				SCREAMING_SNAKE_CASE_				:Tuple				     =						image_processor(images=UpperCAmelCase   ,  return_tensors="pt").to(UpperCAmelCase)

				# forward pass
				with torch.no_grad():
						SCREAMING_SNAKE_CASE_				:Optional[int]				     =						model(**UpperCAmelCase)

				# verify the logits
				SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						torch.Size((1, 10_00))
				self.assertEqual(outputs.logits.shape   ,  UpperCAmelCase)

				SCREAMING_SNAKE_CASE_				:Any				     =						torch.tensor([-0.0260, -0.4739, 0.1911]).to(UpperCAmelCase)

				self.assertTrue(torch.allclose(outputs.logits[0, :3]   ,  UpperCAmelCase   ,  atol=1E-4))




@require_torch
class 						_UpperCAmelCase      (     unittest.TestCase		,		lowercase							):
		lowerCamelCase_	:			Tuple       			=  (ConvNextBackbone,) if is_torch_available() else ()
		lowerCamelCase_	:			List[str]       			=  ConvNextConfig

		lowerCamelCase_	:			str       			=  False






		def _snake_case		(						self				:     Tuple):
				SCREAMING_SNAKE_CASE_				:List[Any]				     =						ConvNextModelTester(self)










import unittest

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


if is_torch_available():
		import torch

		from transformers import AutoModelForImageClassification

if is_vision_available():
		from transformers import AutoImageProcessor



@require_torch
@require_vision
class 						_UpperCAmelCase      (     unittest.TestCase							):






		@slow
		def _snake_case		(						self				:     List[str]):
				SCREAMING_SNAKE_CASE_				:Tuple				     =						AutoImageProcessor.from_pretrained("microsoft/dit-base-finetuned-rvlcdip")
				SCREAMING_SNAKE_CASE_				:int				     =						AutoModelForImageClassification.from_pretrained("microsoft/dit-base-finetuned-rvlcdip")
				model.to(UpperCAmelCase)

				from datasets import load_dataset

				SCREAMING_SNAKE_CASE_				:Optional[Any]				     =						load_dataset("nielsr/rvlcdip-demo")

				SCREAMING_SNAKE_CASE_				:Dict				     =						dataset["train"][0]["image"].convert("RGB")

				SCREAMING_SNAKE_CASE_				:Optional[Any]				     =						image_processor(UpperCAmelCase   ,  return_tensors="pt").to(UpperCAmelCase)

				# forward pass
				with torch.no_grad():
						SCREAMING_SNAKE_CASE_				:Optional[int]				     =						model(**UpperCAmelCase)
						SCREAMING_SNAKE_CASE_				:List[str]				     =						outputs.logits

				SCREAMING_SNAKE_CASE_				:int				     =						torch.Size((1, 16))
				self.assertEqual(logits.shape   ,  UpperCAmelCase)

				SCREAMING_SNAKE_CASE_				:Optional[Any]				     =						torch.tensor(
				    [-0.4158, -0.4092, -0.4347]   ,  device=UpperCAmelCase   ,  dtype=torch.float   ,  )
				self.assertTrue(torch.allclose(logits[0, :3]   ,  UpperCAmelCase   ,  atol=1E-4))






