


'''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__				:







				"""simple docstring"""



				def __init__(self       ,			__lowercase       ,			__lowercase=13       ,			__lowercase=32       ,			__lowercase=3       ,			__lowercase=4       ,			__lowercase=[10, 20, 30, 40]       ,			__lowercase=[2, 2, 3, 2]       ,			__lowercase=True       ,			__lowercase=True       ,			__lowercase=37       ,			__lowercase="gelu"       ,			__lowercase=10       ,			__lowercase=0.0_2       ,			__lowercase=["stage2", "stage3", "stage4"]       ,			__lowercase=[2, 3, 4]       ,			__lowercase=None       ,			):
										__lowerCAmelCase							       =				parent
										__lowerCAmelCase							       =				batch_size
										__lowerCAmelCase							       =				image_size
										__lowerCAmelCase							       =				num_channels
										__lowerCAmelCase							       =				num_stages
										__lowerCAmelCase							       =				hidden_sizes
										__lowerCAmelCase							       =				depths
										__lowerCAmelCase							       =				is_training
										__lowerCAmelCase							       =				use_labels
										__lowerCAmelCase							       =				intermediate_size
										__lowerCAmelCase							       =				hidden_act
										__lowerCAmelCase							       =				num_labels
										__lowerCAmelCase							       =				initializer_range
										__lowerCAmelCase							       =				out_features
										__lowerCAmelCase							       =				out_indices
										__lowerCAmelCase							       =				scope




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

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

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




				def 					_snake_case  (self		):
										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 					_snake_case  (self       ,			__lowercase       ,			__lowercase       ,			__lowercase		):
										__lowerCAmelCase							       =				ConvNextModel(config=__lowercase		)
										model.to(__lowercase		)
										model.eval()
										__lowerCAmelCase							       =				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 					_snake_case  (self       ,			__lowercase       ,			__lowercase       ,			__lowercase		):
										__lowerCAmelCase							       =				ConvNextForImageClassification(__lowercase		)
										model.to(__lowercase		)
										model.eval()
										__lowerCAmelCase							       =				model(__lowercase       ,			labels=__lowercase		)
										self.parent.assertEqual(result.logits.shape       ,			(self.batch_size, self.num_labels)		)




				def 					_snake_case  (self       ,			__lowercase       ,			__lowercase       ,			__lowercase		):
										__lowerCAmelCase							       =				ConvNextBackbone(config=__lowercase		)
										model.to(__lowercase		)
										model.eval()
										__lowerCAmelCase							       =				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
										__lowerCAmelCase							       =				None
										__lowerCAmelCase							       =				ConvNextBackbone(config=__lowercase		)
										model.to(__lowercase		)
										model.eval()
										__lowerCAmelCase							       =				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 					_snake_case  (self		):
										__lowerCAmelCase							       =				self.prepare_config_and_inputs()
										__lowerCAmelCase       ,					__lowerCAmelCase       ,					__lowerCAmelCase							       =				config_and_inputs
										__lowerCAmelCase							       =				{'''pixel_values''': pixel_values}
										return config, inputs_dict


@require_torch
class       a__				( __A							,						__A							,						unittest.TestCase      ):







				"""simple docstring"""



				__UpperCamelCase    :		Optional[int]	=	(
				    (
				        ConvNextModel,
				        ConvNextForImageClassification,
				        ConvNextBackbone,
				    )
				    if is_torch_available()
				    else ()
				)
				__UpperCamelCase    :		List[Any]	=	(
				    {'feature-extraction': ConvNextModel, 'image-classification': ConvNextForImageClassification}
				    if is_torch_available()
				    else {}
				)

				__UpperCamelCase    :		int	=	True
				__UpperCamelCase    :		Optional[int]	=	False
				__UpperCamelCase    :		Optional[int]	=	False
				__UpperCamelCase    :		Optional[Any]	=	False
				__UpperCamelCase    :		Tuple	=	False




				def 					_snake_case  (self		):
										__lowerCAmelCase							       =				ConvNextModelTester(self		)
										__lowerCAmelCase							       =				ConfigTester(self       ,			config_class=__lowercase       ,			has_text_modality=__lowercase       ,			hidden_size=37		)




				def 					_snake_case  (self		):
										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		):
										return




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




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




				@unittest.skip(reason='''ConvNext does not use feedforward chunking'''		)
				def 					_snake_case  (self		):
										pass




				def 					_snake_case  (self		):
										__lowerCAmelCase       ,					__lowerCAmelCase							       =				self.model_tester.prepare_config_and_inputs_for_common()

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

																__lowerCAmelCase							       =				['''pixel_values''']
																self.assertListEqual(arg_names[:1]       ,			__lowercase		)




				def 					_snake_case  (self		):
										__lowerCAmelCase							       =				self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*__lowercase		)




				def 					_snake_case  (self		):
										__lowerCAmelCase							       =				self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_backbone(*__lowercase		)




				def 					_snake_case  (self		):
										def check_hidden_states_output(__lowercase       ,			__lowercase       ,			__lowercase		):
																__lowerCAmelCase							       =				model_class(__lowercase		)
																model.to(__lowercase		)
																model.eval()

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

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

																__lowerCAmelCase							       =				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]       ,			)

										__lowerCAmelCase       ,					__lowerCAmelCase							       =				self.model_tester.prepare_config_and_inputs_for_common()

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

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

																check_hidden_states_output(__lowercase       ,			__lowercase       ,			__lowercase		)




				def 					_snake_case  (self		):
										__lowerCAmelCase							       =				self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*__lowercase		)




				@slow
				def 					_snake_case  (self		):
										for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																__lowerCAmelCase							       =				ConvNextModel.from_pretrained(__lowercase		)
																self.assertIsNotNone(__lowercase		)

def 							__magic_name__(						):
						__lowerCAmelCase							       =				Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''')
						return image


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







				"""simple docstring"""



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




				@slow
				def 					_snake_case  (self		):
										__lowerCAmelCase							       =				ConvNextForImageClassification.from_pretrained('''facebook/convnext-tiny-224'''		).to(__lowercase		)

										__lowerCAmelCase							       =				self.default_image_processor
										__lowerCAmelCase							       =				prepare_img()
										__lowerCAmelCase							       =				image_processor(images=__lowercase       ,			return_tensors='''pt'''		).to(__lowercase		)

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

										# verify the logits
										__lowerCAmelCase							       =				torch.Size((1, 10_00)		)
										self.assertEqual(outputs.logits.shape       ,			__lowercase		)

										__lowerCAmelCase							       =				torch.tensor([-0.0_2_6_0, -0.4_7_3_9, 0.1_9_1_1]		).to(__lowercase		)

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


@require_torch
class       a__				( unittest.TestCase							,						__A      ):







				"""simple docstring"""



				__UpperCamelCase    :		str	=	(ConvNextBackbone,) if is_torch_available() else ()
				__UpperCamelCase    :		Optional[int]	=	ConvNextConfig

				__UpperCamelCase    :		Tuple	=	False




				def 					_snake_case  (self		):
										__lowerCAmelCase							       =				ConvNextModelTester(self		)





'''simple docstring'''

import sys

from .dependency_versions_table import deps
from .utils.versions import require_version, require_version_core


# define which module versions we always want to check at run time
# (usually the ones defined in `install_requires` in setup.py)
#
# order specific notes:
# - tqdm must be checked before tokenizers

_UpperCAmelCase				: Tuple							    =				"""python tqdm regex requests packaging filelock numpy tokenizers""".split()
if sys.version_info < (3, 7):
	pkgs_to_check_at_runtime.append("""dataclasses""")
if sys.version_info < (3, 8):
	pkgs_to_check_at_runtime.append("""importlib_metadata""")

for pkg in pkgs_to_check_at_runtime:
	if pkg in deps:
		if pkg == "tokenizers":
			# must be loaded here, or else tqdm check may fail
			from .utils import is_tokenizers_available

			if not is_tokenizers_available():
				continue  # not required, check version only if installed

		require_version_core(deps[pkg])
	else:
		raise ValueError(f"""can't find {pkg} in {deps.keys()}, check dependency_versions_table.py""")

def 							__magic_name__(						lowerCamelCase,				lowerCamelCase=None):
						require_version(deps[pkg],				lowerCamelCase)

