



"""simple docstring"""







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



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



			def 				__lowercase					(			self							:				str		)							->					Optional[int]:
									snake_case   :			str						    = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

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

									snake_case   :			str						    = self.get_config()
									return config, pixel_values, labels



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



			def 				__lowercase					(			self							:				Optional[int]   ,	_lowercase							:				List[Any]   ,	_lowercase							:				Tuple   ,	_lowercase							:				Union[str, Any]		)							->					Union[str, Any]:
									snake_case   :			Any						    = ConvNextBackbone(config=_lowercase		)
									model.to(_lowercase		)
									model.eval()
									snake_case   :			List[str]						    = 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
									snake_case   :			Tuple						    = None
									snake_case   :			List[str]						    = ConvNextBackbone(config=_lowercase		)
									model.to(_lowercase		)
									model.eval()
									snake_case   :			Dict						    = 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 				__lowercase					(			self							:				Optional[Any]		)							->					int:
									snake_case   :			Union[str, Any]						    = self.prepare_config_and_inputs()
									snake_case    ,			snake_case    ,			snake_case   :			Any						    = config_and_inputs
									snake_case   :			Optional[Any]						    = {"pixel_values": pixel_values}
									return config, inputs_dict



@require_torch
class       _a  ( SCREAMING_SNAKE_CASE__     ,	SCREAMING_SNAKE_CASE__     ,	unittest.TestCase):
			__magic_name__     					=     (
			    (
			        ConvNextModel,
			        ConvNextForImageClassification,
			        ConvNextBackbone,
			    )
			    if is_torch_available()
			    else ()
			)
			__magic_name__     					=     (
			    {"""feature-extraction""": ConvNextModel, """image-classification""": ConvNextForImageClassification}
			    if is_torch_available()
			    else {}
			)

			__magic_name__     					=     True
			__magic_name__     					=     False
			__magic_name__     					=     False
			__magic_name__     					=     False
			__magic_name__     					=     False



			def 				__lowercase					(			self							:				Dict		)							->					int:
									snake_case   :			int						    = ConvNextModelTester(self		)
									snake_case   :			str						    = ConfigTester(self   ,	config_class=_lowercase   ,	has_text_modality=_lowercase   ,	hidden_size=37		)



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



			@unittest.skip(reason="ConvNext does not use inputs_embeds"		)
			def 				__lowercase					(			self							:				List[Any]		)							->					List[str]:
									pass



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



			@unittest.skip(reason="ConvNext does not use feedforward chunking"		)
			def 				__lowercase					(			self							:				Tuple		)							->					Optional[int]:
									pass



			def 				__lowercase					(			self							:				Dict		)							->					Any:
									snake_case    ,			snake_case   :			int						    = self.model_tester.prepare_config_and_inputs_for_common()

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

															snake_case   :			Optional[Any]						    = ["pixel_values"]
															self.assertListEqual(arg_names[:1]   ,	_lowercase		)



			def 				__lowercase					(			self							:				str		)							->					Any:
									snake_case   :			List[Any]						    = self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*_lowercase		)



			def 				__lowercase					(			self							:				Union[str, Any]		)							->					int:
									snake_case   :			Optional[Any]						    = self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_backbone(*_lowercase		)



			def 				__lowercase					(			self							:				Dict		)							->					Tuple:
									def check_hidden_states_output(_lowercase							:				List[str]   ,	_lowercase							:				List[str]   ,	_lowercase							:				str		):
															snake_case   :			Any						    = model_class(_lowercase		)
															model.to(_lowercase		)
															model.eval()

															with torch.no_grad():
																					snake_case   :			Optional[int]						    = model(**self._prepare_for_class(_lowercase   ,	_lowercase		)		)

															snake_case   :			List[str]						    = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

															snake_case   :			Optional[Any]						    = 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]   ,	)

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

									for model_class in self.all_model_classes:
															snake_case   :			Tuple						    = True
															check_hidden_states_output(_lowercase   ,	_lowercase   ,	_lowercase		)

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

															check_hidden_states_output(_lowercase   ,	_lowercase   ,	_lowercase		)



			def 				__lowercase					(			self							:				Any		)							->					str:
									snake_case   :			int						    = self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*_lowercase		)



			@slow
			def 				__lowercase					(			self							:				int		)							->					int:
									for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															snake_case   :			Dict						    = ConvNextModel.from_pretrained(_lowercase		)
															self.assertIsNotNone(_lowercase		)



def  __SCREAMING_SNAKE_CASE		(			):
						"""simple docstring"""






						snake_case   :			List[str]						    = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
						return image

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



			@cached_property
			def 				__lowercase					(			self							:				int		)							->					List[Any]:
									return AutoImageProcessor.from_pretrained("facebook/convnext-tiny-224"		) if is_vision_available() else None



			@slow
			def 				__lowercase					(			self							:				str		)							->					Union[str, Any]:
									snake_case   :			int						    = ConvNextForImageClassification.from_pretrained("facebook/convnext-tiny-224"		).to(_lowercase		)

									snake_case   :			Union[str, Any]						    = self.default_image_processor
									snake_case   :			int						    = prepare_img()
									snake_case   :			Any						    = image_processor(images=_lowercase   ,	return_tensors="pt"		).to(_lowercase		)

									# forward pass
									with torch.no_grad():
															snake_case   :			Tuple						    = model(**_lowercase		)

									# verify the logits
									snake_case   :			List[str]						    = torch.Size((1, 1000)		)
									self.assertEqual(outputs.logits.shape   ,	_lowercase		)

									snake_case   :			Tuple						    = 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       _a  ( unittest.TestCase     ,	SCREAMING_SNAKE_CASE__):
			__magic_name__     					=     (ConvNextBackbone,) if is_torch_available() else ()
			__magic_name__     					=     ConvNextConfig

			__magic_name__     					=     False



			def 				__lowercase					(			self							:				List[str]		)							->					str:
									snake_case   :			Optional[int]						    = ConvNextModelTester(self		)








"""simple docstring"""







from ..utils import DummyObject, requires_backends

class       _a  ( metaclass=SCREAMING_SNAKE_CASE__):
			__magic_name__     					=     ["""keras_nlp"""]



			def __init__(			self							:				int   ,	*_lowercase							:				Optional[int]   ,	**_lowercase							:				Dict		)							->					List[Any]:
									requires_backends(self   ,	["keras_nlp"]		)



