


"""simple docstring"""







import inspect
import unittest

from transformers import ConvNextVaConfig
from transformers.models.auto import get_values
from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES
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_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 ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel
		from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import AutoImageProcessor




class 				UpperCamelCase_			:

	"""simple docstring"""





	def __init__(				self    :       Optional[Any]    ,    UpperCAmelCase__    :       Union[str, Any]    ,    UpperCAmelCase__    :       List[str]=1_3    ,    UpperCAmelCase__    :       int=3_2    ,    UpperCAmelCase__    :       Tuple=3    ,    UpperCAmelCase__    :       Optional[int]=4    ,    UpperCAmelCase__    :       Any=[1_0, 2_0, 3_0, 4_0]    ,    UpperCAmelCase__    :       Union[str, Any]=[2, 2, 3, 2]    ,    UpperCAmelCase__    :       Union[str, Any]=True    ,    UpperCAmelCase__    :       List[str]=True    ,    UpperCAmelCase__    :       Union[str, Any]=3_7    ,    UpperCAmelCase__    :       str="gelu"    ,    UpperCAmelCase__    :       List[str]=1_0    ,    UpperCAmelCase__    :       List[str]=0.02    ,    UpperCAmelCase__    :       Optional[int]=["stage2", "stage3", "stage4"]    ,    UpperCAmelCase__    :       Dict=[2, 3, 4]    ,    UpperCAmelCase__    :       Optional[Any]=None    ,    ) ->			int:
						__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 						UpperCAmelCase_   (				self    :       Dict     ) ->			Any:
						__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 						UpperCAmelCase_   (				self    :       Dict     ) ->			int:
						return ConvNextVaConfig(
						    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 						UpperCAmelCase_   (				self    :       Optional[int]    ,    UpperCAmelCase__    :       Optional[int]    ,    UpperCAmelCase__    :       Any    ,    UpperCAmelCase__    :       Optional[int]     ) ->			Optional[Any]:
						__SCREAMING_SNAKE_CASE		     =       ConvNextVaModel(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 // 3_2, self.image_size // 3_2)    ,    )




	def 						UpperCAmelCase_   (				self    :       Optional[int]    ,    UpperCAmelCase__    :       Optional[int]    ,    UpperCAmelCase__    :       List[Any]    ,    UpperCAmelCase__    :       str     ) ->			Optional[int]:
						__SCREAMING_SNAKE_CASE		     =       ConvNextVaForImageClassification(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 						UpperCAmelCase_   (				self    :       Dict    ,    UpperCAmelCase__    :       Optional[Any]    ,    UpperCAmelCase__    :       Tuple    ,    UpperCAmelCase__    :       Dict     ) ->			int:
						__SCREAMING_SNAKE_CASE		     =       ConvNextVaBackbone(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		     =       ConvNextVaBackbone(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 						UpperCAmelCase_   (				self    :       Any     ) ->			Dict:
						__SCREAMING_SNAKE_CASE		     =       self.prepare_config_and_inputs()
						__SCREAMING_SNAKE_CASE     ,						__SCREAMING_SNAKE_CASE     ,						__SCREAMING_SNAKE_CASE		     =       config_and_inputs
						__SCREAMING_SNAKE_CASE		     =       {"pixel_values": pixel_values}
						return config, inputs_dict




	def 						UpperCAmelCase_   (				self    :       Optional[int]     ) ->			Any:
						__SCREAMING_SNAKE_CASE		     =       self.prepare_config_and_inputs()
						__SCREAMING_SNAKE_CASE     ,						__SCREAMING_SNAKE_CASE     ,						__SCREAMING_SNAKE_CASE		     =       config_and_inputs
						__SCREAMING_SNAKE_CASE		     =       {"pixel_values": pixel_values, "labels": labels}
						return config, inputs_dict




@require_torch
class 				UpperCamelCase_			(				UpperCamelCase    ,						UpperCamelCase    ,						unittest.TestCase):

	"""simple docstring"""





	snake_case__       :						Optional[int]					      =    (
	    (
	        ConvNextVaModel,
	        ConvNextVaForImageClassification,
	        ConvNextVaBackbone,
	    )
	    if is_torch_available()
	    else ()
	)
	snake_case__       :						Optional[int]					      =    (
	    {"feature-extraction": ConvNextVaModel, "image-classification": ConvNextVaForImageClassification}
	    if is_torch_available()
	    else {}
	)

	snake_case__       :						Tuple					      =    False
	snake_case__       :						Dict					      =    False
	snake_case__       :						Optional[int]					      =    False
	snake_case__       :						str					      =    False
	snake_case__       :						Tuple					      =    False




	def 						UpperCAmelCase_   (				self    :       Any     ) ->			Optional[int]:
						__SCREAMING_SNAKE_CASE		     =       ConvNextVaModelTester(self     )
						__SCREAMING_SNAKE_CASE		     =       ConfigTester(self    ,    config_class=UpperCAmelCase__    ,    has_text_modality=UpperCAmelCase__    ,    hidden_size=3_7     )




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




	@unittest.skip(reason="ConvNextV2 does not use inputs_embeds"     )
	def 						UpperCAmelCase_   (				self    :       str     ) ->			Tuple:
						pass




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




	@unittest.skip(reason="ConvNextV2 does not use feedforward chunking"     )
	def 						UpperCAmelCase_   (				self    :       Optional[int]     ) ->			Union[str, Any]:
						pass




	def 						UpperCAmelCase_   (				self    :       Union[str, Any]     ) ->			Dict:
						if not self.model_tester.is_training:
											return

						for model_class in self.all_model_classes:
											__SCREAMING_SNAKE_CASE     ,						__SCREAMING_SNAKE_CASE		     =       self.model_tester.prepare_config_and_inputs_with_labels()
											__SCREAMING_SNAKE_CASE		     =       True

											if model_class.__name__ in [
											    *get_values(UpperCAmelCase__     ),
											    *get_values(UpperCAmelCase__     ),
											]:
																continue

											__SCREAMING_SNAKE_CASE		     =       model_class(UpperCAmelCase__     )
											model.to(UpperCAmelCase__     )
											model.train()
											__SCREAMING_SNAKE_CASE		     =       self._prepare_for_class(UpperCAmelCase__    ,    UpperCAmelCase__    ,    return_labels=UpperCAmelCase__     )
											__SCREAMING_SNAKE_CASE		     =       model(**UpperCAmelCase__     ).loss
											loss.backward()




	def 						UpperCAmelCase_   (				self    :       List[Any]     ) ->			Tuple:
						if not self.model_tester.is_training:
											return

						for model_class in self.all_model_classes:
											__SCREAMING_SNAKE_CASE     ,						__SCREAMING_SNAKE_CASE		     =       self.model_tester.prepare_config_and_inputs_with_labels()
											__SCREAMING_SNAKE_CASE		     =       False
											__SCREAMING_SNAKE_CASE		     =       True

											if (
											    model_class.__name__
											    in [*get_values(UpperCAmelCase__     ), *get_values(UpperCAmelCase__     )]
											    or not model_class.supports_gradient_checkpointing
											):
																continue

											__SCREAMING_SNAKE_CASE		     =       model_class(UpperCAmelCase__     )
											model.to(UpperCAmelCase__     )
											model.gradient_checkpointing_enable()
											model.train()
											__SCREAMING_SNAKE_CASE		     =       self._prepare_for_class(UpperCAmelCase__    ,    UpperCAmelCase__    ,    return_labels=UpperCAmelCase__     )
											__SCREAMING_SNAKE_CASE		     =       model(**UpperCAmelCase__     ).loss
											loss.backward()




	def 						UpperCAmelCase_   (				self    :       List[Any]     ) ->			List[Any]:
						__SCREAMING_SNAKE_CASE     ,						__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 						UpperCAmelCase_   (				self    :       str     ) ->			List[str]:
						__SCREAMING_SNAKE_CASE		     =       self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*UpperCAmelCase__     )




	def 						UpperCAmelCase_   (				self    :       Union[str, Any]     ) ->			List[str]:
						def check_hidden_states_output(UpperCAmelCase__    :       str    ,    UpperCAmelCase__    :       int    ,    UpperCAmelCase__    :       List[str]     ):
											__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     )

											# ConvNextV2'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     ,						__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 						UpperCAmelCase_   (				self    :       Optional[Any]     ) ->			List[Any]:
						__SCREAMING_SNAKE_CASE		     =       self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase__     )




	@slow
	def 						UpperCAmelCase_   (				self    :       Tuple     ) ->			Dict:
						for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											__SCREAMING_SNAKE_CASE		     =       ConvNextVaModel.from_pretrained(UpperCAmelCase__     )
											self.assertIsNotNone(UpperCAmelCase__     )




def      UpperCAmelCase__ ():




					'''simple docstring'''


					__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 						UpperCAmelCase_   (				self    :       Tuple     ) ->			str:
						return AutoImageProcessor.from_pretrained("facebook/convnextv2-tiny-1k-224"     ) if is_vision_available() else None




	@slow
	def 						UpperCAmelCase_   (				self    :       List[Any]     ) ->			int:
						__SCREAMING_SNAKE_CASE		     =       ConvNextVaForImageClassification.from_pretrained("facebook/convnextv2-tiny-1k-224"     ).to(UpperCAmelCase__     )

						__SCREAMING_SNAKE_CASE		     =       self.default_image_processor
						__SCREAMING_SNAKE_CASE		     =       prepare_img()
						__SCREAMING_SNAKE_CASE		     =       preprocessor(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_0_0_0)     )
						self.assertEqual(outputs.logits.shape    ,    UpperCAmelCase__     )

						__SCREAMING_SNAKE_CASE		     =       torch.tensor([0.9_996, 0.1_966, -0.4_386]     ).to(UpperCAmelCase__     )
						self.assertTrue(torch.allclose(outputs.logits[0, :3]    ,    UpperCAmelCase__    ,    atol=1E-4     )     )




"""simple docstring"""







import warnings

from ...utils import logging
from .image_processing_videomae import VideoMAEImageProcessor


a__       :							Dict        =  logging.get_logger(__name__)




class 				UpperCamelCase_			(				UpperCamelCase):

	"""simple docstring"""





	def __init__(				self    :       str    ,    *UpperCAmelCase__    :       List[Any]    ,    **UpperCAmelCase__    :       Tuple     ) ->			None:
						warnings.warn(
						    "The class VideoMAEFeatureExtractor is deprecated and will be removed in version 5 of Transformers."
						    " Please use VideoMAEImageProcessor instead."    ,    UpperCAmelCase__    ,    )
						super().__init__(*UpperCAmelCase__    ,    **UpperCAmelCase__     )
