



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

						'''simple docstring'''




						def __init__(   self				,							_A				,							_A=13				,							_A=32				,							_A=3				,							_A=4				,							_A=[10, 20, 30, 40]				,							_A=[2, 2, 3, 2]				,							_A=True				,							_A=True				,							_A=37				,							_A="gelu"				,							_A=10				,							_A=0.0_2				,							_A=["stage2", "stage3", "stage4"]				,							_A=[2, 3, 4]				,							_A=None				,							):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= parent
													__SCREAMING_SNAKE_CASE									= batch_size
													__SCREAMING_SNAKE_CASE									= image_size
													__SCREAMING_SNAKE_CASE									= num_channels
													__SCREAMING_SNAKE_CASE									= num_stages
													__SCREAMING_SNAKE_CASE									= hidden_sizes
													__SCREAMING_SNAKE_CASE									= depths
													__SCREAMING_SNAKE_CASE									= is_training
													__SCREAMING_SNAKE_CASE									= use_labels
													__SCREAMING_SNAKE_CASE									= intermediate_size
													__SCREAMING_SNAKE_CASE									= hidden_act
													__SCREAMING_SNAKE_CASE									= num_labels
													__SCREAMING_SNAKE_CASE									= initializer_range
													__SCREAMING_SNAKE_CASE									= out_features
													__SCREAMING_SNAKE_CASE									= out_indices
													__SCREAMING_SNAKE_CASE									= scope






						def 	_A     (   self		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

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

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






						def 	_A     (   self		):







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






						def 	_A     (   self				,							_A				,							_A				,							_A		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= ConvNextModel(config=__UpperCAmelCase		)
													model.to(__UpperCAmelCase		)
													model.eval()
													__SCREAMING_SNAKE_CASE									= 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 	_A     (   self				,							_A				,							_A				,							_A		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= ConvNextForImageClassification(__UpperCAmelCase		)
													model.to(__UpperCAmelCase		)
													model.eval()
													__SCREAMING_SNAKE_CASE									= model(__UpperCAmelCase				,							labels=__UpperCAmelCase		)
													self.parent.assertEqual(result.logits.shape				,							(self.batch_size, self.num_labels)		)






						def 	_A     (   self				,							_A				,							_A				,							_A		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= ConvNextBackbone(config=__UpperCAmelCase		)
													model.to(__UpperCAmelCase		)
													model.eval()
													__SCREAMING_SNAKE_CASE									= 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									= None
													__SCREAMING_SNAKE_CASE									= ConvNextBackbone(config=__UpperCAmelCase		)
													model.to(__UpperCAmelCase		)
													model.eval()
													__SCREAMING_SNAKE_CASE									= 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 	_A     (   self		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= self.prepare_config_and_inputs()
													__SCREAMING_SNAKE_CASE									= config_and_inputs
													__SCREAMING_SNAKE_CASE									= {"""pixel_values""": pixel_values}
													return config, inputs_dict







@require_torch
class        UpperCAmelCase_  (       __SCREAMING_SNAKE_CASE   ,   __SCREAMING_SNAKE_CASE   ,   unittest.TestCase	):

						'''simple docstring'''




						UpperCamelCase__      :			str      =  (
						    (
						        ConvNextModel,
						        ConvNextForImageClassification,
						        ConvNextBackbone,
						    )
						    if is_torch_available()
						    else ()
						)
						UpperCamelCase__      :			int      =  (
						    {"feature-extraction": ConvNextModel, "image-classification": ConvNextForImageClassification}
						    if is_torch_available()
						    else {}
						)

						UpperCamelCase__      :			Union[str, Any]      =  True
						UpperCamelCase__      :			List[Any]      =  False
						UpperCamelCase__      :			Any      =  False
						UpperCamelCase__      :			Optional[Any]      =  False
						UpperCamelCase__      :			str      =  False






						def 	_A     (   self		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= ConvNextModelTester(self		)
													__SCREAMING_SNAKE_CASE									= ConfigTester(self				,							config_class=__UpperCAmelCase				,							has_text_modality=__UpperCAmelCase				,							hidden_size=37		)






						def 	_A     (   self		):







													'''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 	_A     (   self		):







													'''simple docstring'''

													return






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







													'''simple docstring'''

													pass






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







													'''simple docstring'''

													pass






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







													'''simple docstring'''

													pass






						def 	_A     (   self		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= self.model_tester.prepare_config_and_inputs_for_common()

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

																				__SCREAMING_SNAKE_CASE									= ["""pixel_values"""]
																				self.assertListEqual(arg_names[:1]				,							__UpperCAmelCase		)






						def 	_A     (   self		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_model(*__UpperCAmelCase		)






						def 	_A     (   self		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_backbone(*__UpperCAmelCase		)






						def 	_A     (   self		):







													'''simple docstring'''

													def check_hidden_states_output(_A				,							_A				,							_A		):
																				__SCREAMING_SNAKE_CASE									= model_class(__UpperCAmelCase		)
																				model.to(__UpperCAmelCase		)
																				model.eval()

																				with torch.no_grad():
																											__SCREAMING_SNAKE_CASE									= model(**self._prepare_for_class(__UpperCAmelCase				,							__UpperCAmelCase		)		)

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

																				__SCREAMING_SNAKE_CASE									= 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									= self.model_tester.prepare_config_and_inputs_for_common()

													for model_class in self.all_model_classes:
																				__SCREAMING_SNAKE_CASE									= 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									= True

																				check_hidden_states_output(__UpperCAmelCase				,							__UpperCAmelCase				,							__UpperCAmelCase		)






						def 	_A     (   self		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase		)






						@slow
						def 	_A     (   self		):







													'''simple docstring'''

													for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																				__SCREAMING_SNAKE_CASE									= ConvNextModel.from_pretrained(__UpperCAmelCase		)
																				self.assertIsNotNone(__UpperCAmelCase		)







def      __lowercase       (			)    ->			Tuple:
							__SCREAMING_SNAKE_CASE									= Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'       )
							return image

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

						'''simple docstring'''




						@cached_property
						def 	_A     (   self		):







													'''simple docstring'''

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






						@slow
						def 	_A     (   self		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= ConvNextForImageClassification.from_pretrained('facebook/convnext-tiny-224'		).to(__UpperCAmelCase		)

													__SCREAMING_SNAKE_CASE									= self.default_image_processor
													__SCREAMING_SNAKE_CASE									= prepare_img()
													__SCREAMING_SNAKE_CASE									= image_processor(images=__UpperCAmelCase				,							return_tensors='pt'		).to(__UpperCAmelCase		)

													# forward pass
													with torch.no_grad():
																				__SCREAMING_SNAKE_CASE									= model(**__UpperCAmelCase		)

													# verify the logits
													__SCREAMING_SNAKE_CASE									= torch.Size((1, 1_000)		)
													self.assertEqual(outputs.logits.shape				,							__UpperCAmelCase		)

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

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







@require_torch
class        UpperCAmelCase_  (       unittest.TestCase   ,   __SCREAMING_SNAKE_CASE	):

						'''simple docstring'''




						UpperCamelCase__      :			int      =  (ConvNextBackbone,) if is_torch_available() else ()
						UpperCamelCase__      :			Optional[Any]      =  ConvNextConfig

						UpperCamelCase__      :			str      =  False






						def 	_A     (   self		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= ConvNextModelTester(self		)











from collections import deque

from .hash_table import HashTable

class        UpperCAmelCase_  (       UpperCamelCase_	):

						'''simple docstring'''




						def __init__(   self				,							*_A				,							**_A		):







													'''simple docstring'''

													super().__init__(*_A				,							**_A		)






						def 	_A     (   self				,							_A				,							_A		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= deque([]		) if self.values[key] is None else self.values[key]
													self.values[key].appendleft(_A		)
													__SCREAMING_SNAKE_CASE									= self.values[key]






						def 	_A     (   self		):







													'''simple docstring'''

													return (
													    sum(self.charge_factor - len(_A		) for slot in self.values		)
													    / self.size_table
													    * self.charge_factor
													)






						def 	_A     (   self				,							_A				,							_A=None		):







													'''simple docstring'''

													if not (
													    len(self.values[key]		) == self.charge_factor and self.values.count(_A		) == 0
													):
																				return key
													return super()._collision_resolution(_A				,							_A		)






