






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


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


			def      UpperCAmelCase__						(				self					:  Union[str, Any] ):
										lowerCamelCase_	:							Dict									=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

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

										lowerCamelCase_	:							int									=self.get_config()
										return config, pixel_values, labels


			def      UpperCAmelCase__						(				self					:  Union[str, 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=snake_case__       ,	initializer_range=self.initializer_range       ,	out_features=self.out_features       ,	out_indices=self.out_indices       ,	num_labels=self.num_labels       ,	)


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


			def      UpperCAmelCase__						(				self					:  List[Any]       ,	snake_case__					:  Optional[Any]       ,	snake_case__					:  Dict       ,	snake_case__					:  Union[str, Any] ):
										lowerCamelCase_	:							Any									=ConvNextBackbone(config=snake_case__ )
										model.to(snake_case__ )
										model.eval()
										lowerCamelCase_	:							Optional[int]									=model(snake_case__ )

										# 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
										lowerCamelCase_	:							List[Any]									=None
										lowerCamelCase_	:							Any									=ConvNextBackbone(config=snake_case__ )
										model.to(snake_case__ )
										model.eval()
										lowerCamelCase_	:							Union[str, Any]									=model(snake_case__ )

										# 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      UpperCAmelCase__						(				self					:  Optional[Any] ):
										lowerCamelCase_	:							Dict									=self.prepare_config_and_inputs()
										lowerCamelCase_							,						lowerCamelCase_							,						lowerCamelCase_	:							Any									=config_and_inputs
										lowerCamelCase_	:							Union[str, Any]									={"pixel_values": pixel_values}
										return config, inputs_dict







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

			_UpperCAmelCase		:Any             =			True
			_UpperCAmelCase		:Any             =			False
			_UpperCAmelCase		:Tuple             =			False
			_UpperCAmelCase		:Optional[Any]             =			False
			_UpperCAmelCase		:List[str]             =			False


			def      UpperCAmelCase__						(				self					:  List[Any] ):
										lowerCamelCase_	:							Dict									=ConvNextModelTester(self )
										lowerCamelCase_	:							Union[str, Any]									=ConfigTester(self       ,	config_class=snake_case__       ,	has_text_modality=snake_case__       ,	hidden_size=37 )


			def      UpperCAmelCase__						(				self					:  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      UpperCAmelCase__						(				self					:  Optional[Any] ):
										return


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


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


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


			def      UpperCAmelCase__						(				self					:  Tuple ):
										lowerCamelCase_							,						lowerCamelCase_	:							Optional[int]									=self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
																	lowerCamelCase_	:							int									=model_class(snake_case__ )
																	lowerCamelCase_	:							Union[str, Any]									=inspect.signature(model.forward )
																	# signature.parameters is an OrderedDict => so arg_names order is deterministic
																	lowerCamelCase_	:							Any									=[*signature.parameters.keys()]

																	lowerCamelCase_	:							Union[str, Any]									=["pixel_values"]
																	self.assertListEqual(arg_names[:1]       ,	snake_case__ )


			def      UpperCAmelCase__						(				self					:  Any ):
										lowerCamelCase_	:							Dict									=self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*snake_case__ )


			def      UpperCAmelCase__						(				self					:  Dict ):
										lowerCamelCase_	:							str									=self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_backbone(*snake_case__ )


			def      UpperCAmelCase__						(				self					:  List[str] ):
										def check_hidden_states_output(snake_case__					:  Optional[int]       ,	snake_case__					:  Dict       ,	snake_case__					:  Tuple ):
																	lowerCamelCase_	:							Dict									=model_class(snake_case__ )
																	model.to(snake_case__ )
																	model.eval()

																	with torch.no_grad():
																								lowerCamelCase_	:							Union[str, Any]									=model(**self._prepare_for_class(snake_case__       ,	snake_case__ ) )

																	lowerCamelCase_	:							Dict									=outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

																	lowerCamelCase_	:							Optional[Any]									=self.model_tester.num_stages
																	self.assertEqual(len(snake_case__ )       ,	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]       ,	)

										lowerCamelCase_							,						lowerCamelCase_	:							Union[str, Any]									=self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
																	lowerCamelCase_	:							Union[str, Any]									=True
																	check_hidden_states_output(snake_case__       ,	snake_case__       ,	snake_case__ )

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

																	check_hidden_states_output(snake_case__       ,	snake_case__       ,	snake_case__ )


			def      UpperCAmelCase__						(				self					:  List[str] ):
										lowerCamelCase_	:							Tuple									=self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*snake_case__ )


			@slow
			def      UpperCAmelCase__						(				self					:  int ):
										for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	lowerCamelCase_	:							List[Any]									=ConvNextModel.from_pretrained(snake_case__ )
																	self.assertIsNotNone(snake_case__ )


def 			_snake_case    (					)    ->     List[str]:
							lowerCamelCase_	:							Optional[int]									=Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"  )
							return image







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


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


			@slow
			def      UpperCAmelCase__						(				self					:  Dict ):
										lowerCamelCase_	:							Union[str, Any]									=ConvNextForImageClassification.from_pretrained("facebook/convnext-tiny-224" ).to(snake_case__ )

										lowerCamelCase_	:							Union[str, Any]									=self.default_image_processor
										lowerCamelCase_	:							List[str]									=prepare_img()
										lowerCamelCase_	:							Dict									=image_processor(images=snake_case__       ,	return_tensors="pt" ).to(snake_case__ )

										# forward pass
										with torch.no_grad():
																	lowerCamelCase_	:							Tuple									=model(**snake_case__ )

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

										lowerCamelCase_	:							Any									=torch.tensor([-0.0_260, -0.4_739, 0.1_911] ).to(snake_case__ )

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







@require_torch
class        lowercase__      (							unittest.TestCase,       snake_case__       ):
			_UpperCAmelCase		:Optional[Any]             =			(ConvNextBackbone,) if is_torch_available() else ()
			_UpperCAmelCase		:int             =			ConvNextConfig

			_UpperCAmelCase		:Union[str, Any]             =			False


			def      UpperCAmelCase__						(				self					:  Union[str, Any] ):
										lowerCamelCase_	:							Dict									=ConvNextModelTester(self )











"""simple docstring"""



import copy
import json
import os
import tempfile

from transformers import is_torch_available

from .test_configuration_utils import config_common_kwargs







class        lowercase__      (							snake_case__       ):


			def __init__(				self					:  Tuple       ,	snake_case__					:  Optional[int]       ,	snake_case__					:  int=None       ,	snake_case__					:  Union[str, Any]=True       ,	snake_case__					:  Optional[int]=None       ,	**snake_case__					:  Optional[int] ):
										lowerCamelCase_	:							Dict									=parent
										lowerCamelCase_	:							List[str]									=config_class
										lowerCamelCase_	:							Union[str, Any]									=has_text_modality
										lowerCamelCase_	:							Optional[int]									=kwargs
										lowerCamelCase_	:							List[str]									=common_properties


			def      UpperCAmelCase__						(				self					:  Optional[Any] ):
										lowerCamelCase_	:							List[str]									=self.config_class(**self.inputs_dict )
										lowerCamelCase_	:							Any									=(
										    ["hidden_size", "num_attention_heads", "num_hidden_layers"]
										    if self.common_properties is None
										    else self.common_properties
										)

										# Add common fields for text models
										if self.has_text_modality:
																	common_properties.extend(["vocab_size"] )

										# Test that config has the common properties as getters
										for prop in common_properties:
																	self.parent.assertTrue(hasattr(snake_case__       ,	snake_case__ )       ,	msg=F"""`{prop}` does not exist""" )

										# Test that config has the common properties as setter
										for idx, name in enumerate(snake_case__ ):
																	try:
																								setattr(snake_case__       ,	snake_case__       ,	snake_case__ )
																								self.parent.assertEqual(
																								    getattr(snake_case__       ,	snake_case__ )       ,	snake_case__       ,	msg=F"""`{name} value {idx} expected, but was {getattr(snake_case__       ,	snake_case__ )}""" )
																	except NotImplementedError:
																								# Some models might not be able to implement setters for common_properties
																								# In that case, a NotImplementedError is raised
																								pass

        # Test if config class can be called with Config(prop_name=..)
										for idx, name in enumerate(snake_case__ ):
																	try:
																								lowerCamelCase_	:							Dict									=self.config_class(**{name: idx} )
																								self.parent.assertEqual(
																								    getattr(snake_case__       ,	snake_case__ )       ,	snake_case__       ,	msg=F"""`{name} value {idx} expected, but was {getattr(snake_case__       ,	snake_case__ )}""" )
																	except NotImplementedError:
																								# Some models might not be able to implement setters for common_properties
																								# In that case, a NotImplementedError is raised
																								pass


			def      UpperCAmelCase__						(				self					:  Any ):
										lowerCamelCase_	:							Tuple									=self.config_class(**self.inputs_dict )
										lowerCamelCase_	:							Any									=json.loads(config.to_json_string() )
										for key, value in self.inputs_dict.items():
																	self.parent.assertEqual(obj[key]       ,	snake_case__ )


			def      UpperCAmelCase__						(				self					:  int ):
										lowerCamelCase_	:							Tuple									=self.config_class(**self.inputs_dict )

										with tempfile.TemporaryDirectory() as tmpdirname:
																	lowerCamelCase_	:							List[Any]									=os.path.join(snake_case__       ,	"config.json" )
																	config_first.to_json_file(snake_case__ )
																	lowerCamelCase_	:							Optional[int]									=self.config_class.from_json_file(snake_case__ )

										self.parent.assertEqual(config_second.to_dict()       ,	config_first.to_dict() )


			def      UpperCAmelCase__						(				self					:  Dict ):
										lowerCamelCase_	:							Dict									=self.config_class(**self.inputs_dict )

										with tempfile.TemporaryDirectory() as tmpdirname:
																	config_first.save_pretrained(snake_case__ )
																	lowerCamelCase_	:							Optional[int]									=self.config_class.from_pretrained(snake_case__ )

										self.parent.assertEqual(config_second.to_dict()       ,	config_first.to_dict() )


			def      UpperCAmelCase__						(				self					:  str ):
										lowerCamelCase_	:							Dict									=self.config_class(**self.inputs_dict )

										lowerCamelCase_	:							Dict									="test"
										with tempfile.TemporaryDirectory() as tmpdirname:
																	lowerCamelCase_	:							str									=os.path.join(snake_case__       ,	snake_case__ )
																	config_first.save_pretrained(snake_case__ )
																	lowerCamelCase_	:							Optional[Any]									=self.config_class.from_pretrained(snake_case__       ,	subfolder=snake_case__ )

										self.parent.assertEqual(config_second.to_dict()       ,	config_first.to_dict() )


			def      UpperCAmelCase__						(				self					:  Optional[Any] ):
										lowerCamelCase_	:							Optional[Any]									=self.config_class(**self.inputs_dict       ,	num_labels=5 )
										self.parent.assertEqual(len(config.idalabel )       ,	5 )
										self.parent.assertEqual(len(config.labelaid )       ,	5 )

										lowerCamelCase_	:							List[Any]									=3
										self.parent.assertEqual(len(config.idalabel )       ,	3 )
										self.parent.assertEqual(len(config.labelaid )       ,	3 )


			def      UpperCAmelCase__						(				self					:  List[Any] ):
										if self.config_class.is_composition:
																	return
										lowerCamelCase_	:							Tuple									=self.config_class()
										self.parent.assertIsNotNone(snake_case__ )


			def      UpperCAmelCase__						(				self					:  List[Any] ):
										lowerCamelCase_	:							List[str]									=copy.deepcopy(snake_case__ )
										lowerCamelCase_	:							Optional[int]									=self.config_class(**snake_case__ )
										lowerCamelCase_	:							Union[str, Any]									=[]
										for key, value in config_common_kwargs.items():
																	if key == "torch_dtype":
																								if not is_torch_available():
																															continue
																								else:
																															import torch

																															if config.torch_dtype != torch.floataa:
																																						wrong_values.append(("torch_dtype", config.torch_dtype, torch.floataa) )
																	elif getattr(snake_case__       ,	snake_case__ ) != value:
																								wrong_values.append((key, getattr(snake_case__       ,	snake_case__ ), value) )

										if len(snake_case__ ) > 0:
																	lowerCamelCase_	:							Any									="\n".join([F"""- {v[0]}: got {v[1]} instead of {v[2]}""" for v in wrong_values] )
																	raise ValueError(F"""The following keys were not properly set in the config:\n{errors}""" )


			def      UpperCAmelCase__						(				self					:  int ):
										self.create_and_test_config_common_properties()
										self.create_and_test_config_to_json_string()
										self.create_and_test_config_to_json_file()
										self.create_and_test_config_from_and_save_pretrained()
										self.create_and_test_config_from_and_save_pretrained_subfolder()
										self.create_and_test_config_with_num_labels()
										self.check_config_can_be_init_without_params()
										self.check_config_arguments_init()



