






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		:       Any						,_SCREAMING_SNAKE_CASE		:       Dict						,_SCREAMING_SNAKE_CASE		:       int=1_3						,_SCREAMING_SNAKE_CASE		:       str=3_2						,_SCREAMING_SNAKE_CASE		:       str=3						,_SCREAMING_SNAKE_CASE		:       Dict=4						,_SCREAMING_SNAKE_CASE		:       List[str]=[1_0, 2_0, 3_0, 4_0]						,_SCREAMING_SNAKE_CASE		:       List[str]=[2, 2, 3, 2]						,_SCREAMING_SNAKE_CASE		:       Dict=True						,_SCREAMING_SNAKE_CASE		:       Union[str, Any]=True						,_SCREAMING_SNAKE_CASE		:       List[str]=3_7						,_SCREAMING_SNAKE_CASE		:       str="gelu"						,_SCREAMING_SNAKE_CASE		:       List[str]=1_0						,_SCREAMING_SNAKE_CASE		:       int=0.02						,_SCREAMING_SNAKE_CASE		:       str=["stage2", "stage3", "stage4"]						,_SCREAMING_SNAKE_CASE		:       Any=[2, 3, 4]						,_SCREAMING_SNAKE_CASE		:       List[str]=None						,)    ->   int:


						'''simple docstring'''
						A	 =      parent
						A	 =      batch_size
						A	 =      image_size
						A	 =      num_channels
						A	 =      num_stages
						A	 =      hidden_sizes
						A	 =      depths
						A	 =      is_training
						A	 =      use_labels
						A	 =      intermediate_size
						A	 =      hidden_act
						A	 =      num_labels
						A	 =      initializer_range
						A	 =      out_features
						A	 =      out_indices
						A	 =      scope
		def       A(  self		:       List[str]		)    ->   Any:


						'''simple docstring'''
						A	 =      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

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

						A	 =      self.get_config()

						return config, pixel_values, labels
		def       A(  self		:       Any		)    ->   List[Any]:


						'''simple docstring'''
						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=_SCREAMING_SNAKE_CASE						,initializer_range=self.initializer_range						,out_features=self.out_features						,out_indices=self.out_indices						,num_labels=self.num_labels						,)
		def       A(  self		:       List[Any]						,_SCREAMING_SNAKE_CASE		:       Union[str, Any]						,_SCREAMING_SNAKE_CASE		:       List[Any]						,_SCREAMING_SNAKE_CASE		:       Any		)    ->   Optional[Any]:


						'''simple docstring'''
						A	 =      ConvNextVaModel(config=_SCREAMING_SNAKE_CASE		)
						model.to(_SCREAMING_SNAKE_CASE		)
						model.eval()
						A	 =      model(_SCREAMING_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 // 3_2, self.image_size // 3_2)						,)
		def       A(  self		:       str						,_SCREAMING_SNAKE_CASE		:       int						,_SCREAMING_SNAKE_CASE		:       List[Any]						,_SCREAMING_SNAKE_CASE		:       Optional[Any]		)    ->   List[Any]:


						'''simple docstring'''
						A	 =      ConvNextVaForImageClassification(_SCREAMING_SNAKE_CASE		)
						model.to(_SCREAMING_SNAKE_CASE		)
						model.eval()
						A	 =      model(_SCREAMING_SNAKE_CASE						,labels=_SCREAMING_SNAKE_CASE		)
						self.parent.assertEqual(result.logits.shape						,(self.batch_size, self.num_labels)		)
		def       A(  self		:       Union[str, Any]						,_SCREAMING_SNAKE_CASE		:       int						,_SCREAMING_SNAKE_CASE		:       List[str]						,_SCREAMING_SNAKE_CASE		:       Union[str, Any]		)    ->   Optional[Any]:


						'''simple docstring'''
						A	 =      ConvNextVaBackbone(config=_SCREAMING_SNAKE_CASE		)
						model.to(_SCREAMING_SNAKE_CASE		)
						model.eval()
						A	 =      model(_SCREAMING_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
						A	 =      None
						A	 =      ConvNextVaBackbone(config=_SCREAMING_SNAKE_CASE		)
						model.to(_SCREAMING_SNAKE_CASE		)
						model.eval()
						A	 =      model(_SCREAMING_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       A(  self		:       Optional[int]		)    ->   Optional[Any]:


						'''simple docstring'''
						A	 =      self.prepare_config_and_inputs()
						A ,		A ,		A	 =      config_and_inputs
						A	 =      {'pixel_values': pixel_values}
						return config, inputs_dict







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


						'''simple docstring'''
						A	 =      self.prepare_config_and_inputs()
						A ,		A ,		A	 =      config_and_inputs
						A	 =      {'pixel_values': pixel_values, 'labels': labels}
						return config, inputs_dict


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







		"""simple docstring"""



		snake_case    =   (
		    (
		        ConvNextVaModel,
		        ConvNextVaForImageClassification,
		        ConvNextVaBackbone,
		    )
		    if is_torch_available()
		    else ()
		)
		snake_case    =   (
		    {"feature-extraction": ConvNextVaModel, "image-classification": ConvNextVaForImageClassification}
		    if is_torch_available()
		    else {}
		)

		snake_case    =   False
		snake_case    =   False
		snake_case    =   False
		snake_case    =   False
		snake_case    =   False
		def       A(  self		:       Union[str, Any]		)    ->   Dict:


						'''simple docstring'''
						A	 =      ConvNextVaModelTester(self		)
						A	 =      ConfigTester(self						,config_class=_SCREAMING_SNAKE_CASE						,has_text_modality=_SCREAMING_SNAKE_CASE						,hidden_size=3_7		)
		def       A(  self		:       List[Any]		)    ->   str:


						'''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		:       Union[str, Any]		)    ->   Union[str, Any]:


						'''simple docstring'''
						return
		@unittest.skip(reason='ConvNextV2 does not use inputs_embeds'		)
		def       A(  self		:       Any		)    ->   List[str]:


						'''simple docstring'''
						pass
		@unittest.skip(reason='ConvNextV2 does not support input and output embeddings'		)
		def       A(  self		:       str		)    ->   Dict:


						'''simple docstring'''
						pass
		@unittest.skip(reason='ConvNextV2 does not use feedforward chunking'		)
		def       A(  self		:       Dict		)    ->   Any:


						'''simple docstring'''
						pass
		def       A(  self		:       List[str]		)    ->   int:


						'''simple docstring'''
						if not self.model_tester.is_training:
										return

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

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

										A	 =      model_class(_SCREAMING_SNAKE_CASE		)
										model.to(_SCREAMING_SNAKE_CASE		)
										model.train()
										A	 =      self._prepare_for_class(_SCREAMING_SNAKE_CASE						,_SCREAMING_SNAKE_CASE						,return_labels=_SCREAMING_SNAKE_CASE		)
										A	 =      model(**_SCREAMING_SNAKE_CASE		).loss
										loss.backward()
		def       A(  self		:       Union[str, Any]		)    ->   Optional[Any]:


						'''simple docstring'''
						if not self.model_tester.is_training:
										return

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

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

										A	 =      model_class(_SCREAMING_SNAKE_CASE		)
										model.to(_SCREAMING_SNAKE_CASE		)
										model.gradient_checkpointing_enable()
										model.train()
										A	 =      self._prepare_for_class(_SCREAMING_SNAKE_CASE						,_SCREAMING_SNAKE_CASE						,return_labels=_SCREAMING_SNAKE_CASE		)
										A	 =      model(**_SCREAMING_SNAKE_CASE		).loss
										loss.backward()
		def       A(  self		:       List[str]		)    ->   Union[str, Any]:


						'''simple docstring'''
						A ,		A	 =      self.model_tester.prepare_config_and_inputs_for_common()

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

										A	 =      ['pixel_values']
										self.assertListEqual(arg_names[:1]						,_SCREAMING_SNAKE_CASE		)
		def       A(  self		:       List[Any]		)    ->   Optional[int]:


						'''simple docstring'''
						A	 =      self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE		)
		def       A(  self		:       Dict		)    ->   Dict:


						'''simple docstring'''
						def check_hidden_states_output(_SCREAMING_SNAKE_CASE		:       int						,_SCREAMING_SNAKE_CASE		:       List[Any]						,_SCREAMING_SNAKE_CASE		:       Tuple		):
										A	 =      model_class(_SCREAMING_SNAKE_CASE		)
										model.to(_SCREAMING_SNAKE_CASE		)
										model.eval()

										with torch.no_grad():
														A	 =      model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE						,_SCREAMING_SNAKE_CASE		)		)

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

										A	 =      self.model_tester.num_stages
										self.assertEqual(len(_SCREAMING_SNAKE_CASE		)						,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]						,)

						A ,		A	 =      self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
										A	 =      True
										check_hidden_states_output(_SCREAMING_SNAKE_CASE						,_SCREAMING_SNAKE_CASE						,_SCREAMING_SNAKE_CASE		)

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

										check_hidden_states_output(_SCREAMING_SNAKE_CASE						,_SCREAMING_SNAKE_CASE						,_SCREAMING_SNAKE_CASE		)
		def       A(  self		:       Tuple		)    ->   List[Any]:


						'''simple docstring'''
						A	 =      self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE		)







		@slow
		def       A(  self		:       Union[str, Any]		)    ->   Optional[int]:


						'''simple docstring'''
						for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										A	 =      ConvNextVaModel.from_pretrained(_SCREAMING_SNAKE_CASE		)
										self.assertIsNotNone(_SCREAMING_SNAKE_CASE		)







def      snake_case		(							):
				A	 =      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		:       str		)    ->   Optional[Any]:


						'''simple docstring'''
						return AutoImageProcessor.from_pretrained('facebook/convnextv2-tiny-1k-224'		) if is_vision_available() else None







		@slow
		def       A(  self		:       Optional[Any]		)    ->   Tuple:


						'''simple docstring'''
						A	 =      ConvNextVaForImageClassification.from_pretrained('facebook/convnextv2-tiny-1k-224'		).to(_SCREAMING_SNAKE_CASE		)

						A	 =      self.default_image_processor
						A	 =      prepare_img()
						A	 =      preprocessor(images=_SCREAMING_SNAKE_CASE						,return_tensors='pt'		).to(_SCREAMING_SNAKE_CASE		)

						# forward pass
						with torch.no_grad():
										A	 =      model(**_SCREAMING_SNAKE_CASE		)

						# verify the logits
						A	 =      torch.Size((1, 1_0_0_0)		)
						self.assertEqual(outputs.logits.shape						,_SCREAMING_SNAKE_CASE		)

						A	 =      torch.tensor([0.9996, 0.1966, -0.4386]		).to(_SCREAMING_SNAKE_CASE		)
						self.assertTrue(torch.allclose(outputs.logits[0, :3]						,_SCREAMING_SNAKE_CASE						,atol=1E-4		)		)













import copy
import re
class      UpperCamelCase :







		"""simple docstring"""



		snake_case    =   "hp"
		snake_case    =   {}
		snake_case    =   None
		@classmethod
		def       A(  cls		:       Union[str, Any]						,_SCREAMING_SNAKE_CASE		:       int						,_SCREAMING_SNAKE_CASE		:       List[Any]		)    ->   int:


						'''simple docstring'''
						A	 =      prefix
						A	 =      defaults
						cls.build_naming_info()
		@staticmethod
		def       A(  _SCREAMING_SNAKE_CASE		:       List[str]						,_SCREAMING_SNAKE_CASE		:       List[Any]		)    ->   Optional[Any]:


						'''simple docstring'''
						if len(_SCREAMING_SNAKE_CASE		) == 0:
										return ""
						A	 =      None
						if any(char.isdigit() for char in word		):
										raise Exception(f'Parameters should not contain numbers: \'{word}\' contains a number'		)
						if word in info["short_word"]:
										return info["short_word"][word]
						for prefix_len in range(1						,len(_SCREAMING_SNAKE_CASE		) + 1		):
										A	 =      word[:prefix_len]
										if prefix in info["reverse_short_word"]:
														continue
										else:
														A	 =      prefix
														break

						if short_word is None:
										# Paranoid fallback
										def int_to_alphabetic(_SCREAMING_SNAKE_CASE		:       Optional[int]		):
														A	 =      ''
														while integer != 0:
																		A	 =      chr(ord('A'		) + integer % 1_0		) + s
																		integer //= 1_0
														return s

										A	 =      0
										while True:
														A	 =      word + '#' + int_to_alphabetic(_SCREAMING_SNAKE_CASE		)
														if sword in info["reverse_short_word"]:
																		continue
														else:
																		A	 =      sword
																		break

						A	 =      short_word
						A	 =      word
						return short_word
		@staticmethod
		def       A(  _SCREAMING_SNAKE_CASE		:       Optional[int]						,_SCREAMING_SNAKE_CASE		:       Optional[int]		)    ->   int:


						'''simple docstring'''
						A	 =      param_name.split('_'		)

						A	 =      [TrialShortNamer.shortname_for_word(_SCREAMING_SNAKE_CASE						,_SCREAMING_SNAKE_CASE		) for word in words]

						# We try to create a separatorless short name, but if there is a collision we have to fallback
						# to a separated short name
						A	 =      ['', '_']

						for separator in separators:
										A	 =      separator.join(_SCREAMING_SNAKE_CASE		)
										if shortname not in info["reverse_short_param"]:
														A	 =      shortname
														A	 =      param_name
														return shortname

						return param_name
		@staticmethod
		def       A(  _SCREAMING_SNAKE_CASE		:       Optional[Any]						,_SCREAMING_SNAKE_CASE		:       Optional[int]		)    ->   List[str]:


						'''simple docstring'''
						A	 =      TrialShortNamer.shortname_for_key(_SCREAMING_SNAKE_CASE						,_SCREAMING_SNAKE_CASE		)
						A	 =      short_name
						A	 =      param_name
		@classmethod
		def       A(  cls		:       Optional[int]		)    ->   str:


						'''simple docstring'''
						if cls.NAMING_INFO is not None:
										return

						A	 =      {
						    'short_word': {},
						    'reverse_short_word': {},
						    'short_param': {},
						    'reverse_short_param': {},
						}

						A	 =      list(cls.DEFAULTS.keys()		)

						for k in field_keys:
										cls.add_new_param_name(_SCREAMING_SNAKE_CASE						,_SCREAMING_SNAKE_CASE		)

						A	 =      info
		@classmethod
		def       A(  cls		:       List[str]						,_SCREAMING_SNAKE_CASE		:       str		)    ->   List[Any]:


						'''simple docstring'''
						cls.build_naming_info()
						assert cls.PREFIX is not None
						A	 =      [copy.copy(cls.PREFIX		)]

						for k, v in params.items():
										if k not in cls.DEFAULTS:
														raise Exception(f'You should provide a default value for the param name {k} with value {v}'		)
										if v == cls.DEFAULTS[k]:
														# The default value is not added to the name
														continue

										A	 =      cls.NAMING_INFO['short_param'][k]

										if isinstance(_SCREAMING_SNAKE_CASE						,_SCREAMING_SNAKE_CASE		):
														A	 =      1 if v else 0

										A	 =      '' if isinstance(_SCREAMING_SNAKE_CASE						,(int, float)		) else '-'
										A	 =      f'{key}{sep}{v}'
										name.append(_SCREAMING_SNAKE_CASE		)

						return "_".join(_SCREAMING_SNAKE_CASE		)







		@classmethod
		def       A(  cls		:       int						,_SCREAMING_SNAKE_CASE		:       Optional[int]		)    ->   str:


						'''simple docstring'''
						A	 =      repr[len(cls.PREFIX		) + 1 :]
						if repr == "":
										A	 =      []
						else:
										A	 =      repr.split('_'		)

						A	 =      {}

						for value in values:
										if "-" in value:
														A ,		A	 =      value.split('-'		)
										else:
														A	 =      re.sub('[0-9.]'						,''						,_SCREAMING_SNAKE_CASE		)
														A	 =      float(re.sub('[^0-9.]'						,''						,_SCREAMING_SNAKE_CASE		)		)

										A	 =      cls.NAMING_INFO['reverse_short_param'][p_k]

										A	 =      p_v

						for k in cls.DEFAULTS:
										if k not in parameters:
														A	 =      cls.DEFAULTS[k]

						return parameters





