





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






						def __init__(      self      :      Dict		,   _A      :      Union[str, Any]		,   _A      :      Dict=13		,   _A      :      List[Any]=32		,   _A      :      List[Any]=3		,   _A      :      Tuple=4		,   _A      :      int=[10, 20, 30, 40]		,   _A      :      List[Any]=[2, 2, 3, 2]		,   _A      :      Tuple=True		,   _A      :      List[Any]=True		,   _A      :      Union[str, Any]=37		,   _A      :      List[str]="gelu"		,   _A      :      Union[str, Any]=10		,   _A      :      str=0.0_2		,   _A      :      Any=["stage2", "stage3", "stage4"]		,   _A      :      Tuple=[2, 3, 4]		,   _A      :      Tuple=None		,   )							->    Optional[Any]:







							"""simple docstring"""


							snake_case_		:			Tuple											=	parent
							snake_case_		:			Union[str, Any]											=	batch_size
							snake_case_		:			int											=	image_size
							snake_case_		:			int											=	num_channels
							snake_case_		:			Dict											=	num_stages
							snake_case_		:			Dict											=	hidden_sizes
							snake_case_		:			Any											=	depths
							snake_case_		:			Dict											=	is_training
							snake_case_		:			List[str]											=	use_labels
							snake_case_		:			Union[str, Any]											=	intermediate_size
							snake_case_		:			Union[str, Any]											=	hidden_act
							snake_case_		:			Union[str, Any]											=	num_labels
							snake_case_		:			Any											=	initializer_range
							snake_case_		:			Any											=	out_features
							snake_case_		:			List[Any]											=	out_indices
							snake_case_		:			List[Any]											=	scope






						def UpperCAmelCase_				(      self      :      int	)							->    Optional[Any]:







							"""simple docstring"""


							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_		:			Any											=	self.get_config()
							return config, pixel_values, labels






						def UpperCAmelCase_				(      self      :      Any	)							->    List[str]:







							"""simple docstring"""


							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		,   out_features=self.out_features		,   out_indices=self.out_indices		,   num_labels=self.num_labels		,   )






						def UpperCAmelCase_				(      self      :      Dict		,   _A      :      Optional[Any]		,   _A      :      Optional[int]		,   _A      :      Optional[int]	)							->    List[Any]:







							"""simple docstring"""


							snake_case_		:			Optional[Any]											=	ConvNextModel(config=_A	)
							model.to(_A	)
							model.eval()
							snake_case_		:			Union[str, Any]											=	model(_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 UpperCAmelCase_				(      self      :      Dict		,   _A      :      Optional[int]		,   _A      :      List[str]		,   _A      :      Dict	)							->    Any:







							"""simple docstring"""


							snake_case_		:			List[Any]											=	ConvNextForImageClassification(_A	)
							model.to(_A	)
							model.eval()
							snake_case_		:			Dict											=	model(_A		,   labels=_A	)
							self.parent.assertEqual(result.logits.shape		,   (self.batch_size, self.num_labels)	)






						def UpperCAmelCase_				(      self      :      Dict		,   _A      :      Tuple		,   _A      :      Optional[Any]		,   _A      :      int	)							->    Tuple:







							"""simple docstring"""


							snake_case_		:			List[str]											=	ConvNextBackbone(config=_A	)
							model.to(_A	)
							model.eval()
							snake_case_		:			List[Any]											=	model(_A	)

							# 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_		:			List[Any]											=	None
							snake_case_		:			Optional[Any]											=	ConvNextBackbone(config=_A	)
							model.to(_A	)
							model.eval()
							snake_case_		:			Dict											=	model(_A	)

							# 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      :      int	)							->    Optional[int]:







							"""simple docstring"""


							snake_case_		:			List[Any]											=	self.prepare_config_and_inputs()
							snake_case_						,snake_case_						,snake_case_		:			Tuple											=	config_and_inputs
							snake_case_		:			Tuple											=	{'pixel_values': pixel_values}
							return config, inputs_dict
@require_torch
class SCREAMING_SNAKE_CASE_						(					snake_case_       ,				snake_case_       ,				unittest.TestCase					):
						__magic_name__:			Tuple       =       (
						    (
						        ConvNextModel,
						        ConvNextForImageClassification,
						        ConvNextBackbone,
						    )
						    if is_torch_available()
						    else ()
						)
						__magic_name__:			Union[str, Any]       =       (
						    {"feature-extraction": ConvNextModel, "image-classification": ConvNextForImageClassification}
						    if is_torch_available()
						    else {}
						)

						__magic_name__:			Any       =       True
						__magic_name__:			List[str]       =       False
						__magic_name__:			List[Any]       =       False
						__magic_name__:			Tuple       =       False
						__magic_name__:			Optional[int]       =       False






						def UpperCAmelCase_				(      self      :      int	)							->    Any:







							"""simple docstring"""


							snake_case_		:			Any											=	ConvNextModelTester(self	)
							snake_case_		:			str											=	ConfigTester(self		,   config_class=_A		,   has_text_modality=_A		,   hidden_size=37	)






						def UpperCAmelCase_				(      self      :      str	)							->    int:







							"""simple docstring"""


							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      :      Any	)							->    Optional[int]:







							"""simple docstring"""


							return






						@unittest.skip(reason='ConvNext does not use inputs_embeds'	)
						def UpperCAmelCase_				(      self      :      Optional[Any]	)							->    Union[str, Any]:







							"""simple docstring"""


							pass






						@unittest.skip(reason='ConvNext does not support input and output embeddings'	)
						def UpperCAmelCase_				(      self      :      Union[str, Any]	)							->    Optional[int]:







							"""simple docstring"""


							pass






						@unittest.skip(reason='ConvNext does not use feedforward chunking'	)
						def UpperCAmelCase_				(      self      :      Optional[Any]	)							->    Dict:







							"""simple docstring"""


							pass






						def UpperCAmelCase_				(      self      :      str	)							->    Optional[int]:







							"""simple docstring"""


							snake_case_						,snake_case_		:			Any											=	self.model_tester.prepare_config_and_inputs_for_common()

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

								snake_case_		:			Union[str, Any]											=	['pixel_values']
								self.assertListEqual(arg_names[:1]		,   _A	)






						def UpperCAmelCase_				(      self      :      Any	)							->    Optional[Any]:







							"""simple docstring"""


							snake_case_		:			Tuple											=	self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*_A	)






						def UpperCAmelCase_				(      self      :      Optional[int]	)							->    Optional[int]:







							"""simple docstring"""


							snake_case_		:			Optional[int]											=	self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_backbone(*_A	)






						def UpperCAmelCase_				(      self      :      str	)							->    List[Any]:







							"""simple docstring"""


							def check_hidden_states_output(_A      :      str		,   _A      :      Optional[Any]		,   _A      :      Dict	):
								snake_case_		:			Union[str, Any]											=	model_class(_A	)
								model.to(_A	)
								model.eval()

								with torch.no_grad():
									snake_case_		:			List[str]											=	model(**self._prepare_for_class(_A		,   _A	)	)

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

								snake_case_		:			Any											=	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]		,   )

							snake_case_						,snake_case_		:			Dict											=	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(_A		,   _A		,   _A	)

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

								check_hidden_states_output(_A		,   _A		,   _A	)






						def UpperCAmelCase_				(      self      :      Dict	)							->    List[str]:







							"""simple docstring"""


							snake_case_		:			Any											=	self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*_A	)






						@slow
						def UpperCAmelCase_				(      self      :      Optional[Any]	)							->    List[str]:







							"""simple docstring"""


							for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
								snake_case_		:			Tuple											=	ConvNextModel.from_pretrained(_A	)
								self.assertIsNotNone(_A	)


def 							SCREAMING_SNAKE_CASE__						(    ):
	snake_case_		:			Optional[Any]											=	Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'   )
	return image
@require_torch
@require_vision
class SCREAMING_SNAKE_CASE_						(					unittest.TestCase					):






						@cached_property
						def UpperCAmelCase_				(      self      :      List[str]	)							->    Tuple:







							"""simple docstring"""


							return AutoImageProcessor.from_pretrained('facebook/convnext-tiny-224'	) if is_vision_available() else None






						@slow
						def UpperCAmelCase_				(      self      :      Union[str, Any]	)							->    Any:







							"""simple docstring"""


							snake_case_		:			int											=	ConvNextForImageClassification.from_pretrained('facebook/convnext-tiny-224'	).to(_A	)

							snake_case_		:			Optional[Any]											=	self.default_image_processor
							snake_case_		:			List[str]											=	prepare_img()
							snake_case_		:			List[str]											=	image_processor(images=_A		,   return_tensors='pt'	).to(_A	)

							# forward pass
							with torch.no_grad():
								snake_case_		:			Any											=	model(**_A	)

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

							snake_case_		:			Union[str, Any]											=	torch.tensor([-0.0_2_6_0, -0.4_7_3_9, 0.1_9_1_1]	).to(_A	)

							self.assertTrue(torch.allclose(outputs.logits[0, :3]		,   _A		,   atol=1E-4	)	)
@require_torch
class SCREAMING_SNAKE_CASE_						(					unittest.TestCase       ,				snake_case_					):
						__magic_name__:			Union[str, Any]       =       (ConvNextBackbone,) if is_torch_available() else ()
						__magic_name__:			str       =       ConvNextConfig

						__magic_name__:			Tuple       =       False






						def UpperCAmelCase_				(      self      :      Union[str, Any]	)							->    Any:







							"""simple docstring"""


							snake_case_		:			Dict											=	ConvNextModelTester(self	)








import numpy as np


def 							SCREAMING_SNAKE_CASE__						(    __a   ):
	return (2 / (1 + np.exp(-2 * vector   ))) - 1


if __name__ == "__main__":
						import doctest

						doctest.testmod()

