

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       ,							_a       ,							_a=1_3       ,							_a=3_2       ,							_a=3       ,							_a=4       ,							_a=[1_0, 2_0, 3_0, 4_0]       ,							_a=[2, 2, 3, 2]       ,							_a=True       ,							_a=True       ,							_a=3_7       ,							_a="gelu"       ,							_a=1_0       ,							_a=0.02       ,							_a=["stage2", "stage3", "stage4"]       ,							_a=[2, 3, 4]       ,							_a=None       ,							)    ->    Tuple:
												_a	:    Any         =		parent
												_a	:    List[str]         =		batch_size
												_a	:    Optional[int]         =		image_size
												_a	:    Dict         =		num_channels
												_a	:    str         =		num_stages
												_a	:    int         =		hidden_sizes
												_a	:    int         =		depths
												_a	:    int         =		is_training
												_a	:    str         =		use_labels
												_a	:    Tuple         =		intermediate_size
												_a	:    int         =		hidden_act
												_a	:    List[Any]         =		num_labels
												_a	:    List[str]         =		initializer_range
												_a	:    Tuple         =		out_features
												_a	:    Dict         =		out_indices
												_a	:    Any         =		scope


							def 				__lowercase				(			self       )    ->    List[Any]:
												_a	:    Tuple         =		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

												_a	:    Optional[Any]         =		None
												if self.use_labels:
																	_a	:    int         =		ids_tensor([self.batch_size]       ,							self.num_labels       )

												_a	:    Any         =		self.get_config()

												return config, pixel_values, labels


							def 				__lowercase				(			self       )    ->    Dict:
												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=_a       ,							initializer_range=self.initializer_range       ,							out_features=self.out_features       ,							out_indices=self.out_indices       ,							num_labels=self.num_labels       ,							)


							def 				__lowercase				(			self       ,							_a       ,							_a       ,							_a       )    ->    int:
												_a	:    int         =		ConvNextVaModel(config=_a       )
												model.to(_a       )
												model.eval()
												_a	:    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 // 3_2, self.image_size // 3_2)       ,							)


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


							def 				__lowercase				(			self       ,							_a       ,							_a       ,							_a       )    ->    Tuple:
												_a	:    Dict         =		ConvNextVaBackbone(config=_a       )
												model.to(_a       )
												model.eval()
												_a	:    str         =		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
												_a	:    Dict         =		None
												_a	:    int         =		ConvNextVaBackbone(config=_a       )
												model.to(_a       )
												model.eval()
												_a	:    int         =		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 				__lowercase				(			self       )    ->    Dict:
												_a	:    List[Any]         =		self.prepare_config_and_inputs()
												_a      ,					_a      ,					_a	:    List[Any]         =		config_and_inputs
												_a	:    Tuple         =		{'''pixel_values''': pixel_values}
												return config, inputs_dict




							def 				__lowercase				(			self       )    ->    List[str]:
												_a	:    Union[str, Any]         =		self.prepare_config_and_inputs()
												_a      ,					_a      ,					_a	:    Union[str, Any]         =		config_and_inputs
												_a	:    List[str]         =		{'''pixel_values''': pixel_values, '''labels''': labels}
												return config, inputs_dict



@require_torch
class 				UpperCAmelCase_		(			__lowercase				,       __lowercase				,       unittest.TestCase   ):
							"""simple docstring"""







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

							UpperCAmelCase__       :						Tuple	    =    False
							UpperCAmelCase__       :						Optional[int]	    =    False
							UpperCAmelCase__       :						int	    =    False
							UpperCAmelCase__       :						int	    =    False
							UpperCAmelCase__       :						Optional[int]	    =    False


							def 				__lowercase				(			self       )    ->    Tuple:
												_a	:    Any         =		ConvNextVaModelTester(self       )
												_a	:    str         =		ConfigTester(self       ,							config_class=_a       ,							has_text_modality=_a       ,							hidden_size=3_7       )


							def 				__lowercase				(			self       )    ->    str:
												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 				__lowercase				(			self       )    ->    Optional[int]:
												return


							@unittest.skip(reason='''ConvNextV2 does not use inputs_embeds'''       )
							def 				__lowercase				(			self       )    ->    int:
												pass


							@unittest.skip(reason='''ConvNextV2 does not support input and output embeddings'''       )
							def 				__lowercase				(			self       )    ->    List[Any]:
												pass


							@unittest.skip(reason='''ConvNextV2 does not use feedforward chunking'''       )
							def 				__lowercase				(			self       )    ->    Optional[int]:
												pass


							def 				__lowercase				(			self       )    ->    Optional[Any]:
												if not self.model_tester.is_training:
																	return

												for model_class in self.all_model_classes:
																	_a      ,					_a	:    Optional[Any]         =		self.model_tester.prepare_config_and_inputs_with_labels()
																	_a	:    str         =		True

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

																	_a	:    Tuple         =		model_class(_a       )
																	model.to(_a       )
																	model.train()
																	_a	:    str         =		self._prepare_for_class(_a       ,							_a       ,							return_labels=_a       )
																	_a	:    Tuple         =		model(**_a       ).loss
																	loss.backward()


							def 				__lowercase				(			self       )    ->    Optional[int]:
												if not self.model_tester.is_training:
																	return

												for model_class in self.all_model_classes:
																	_a      ,					_a	:    Optional[int]         =		self.model_tester.prepare_config_and_inputs_with_labels()
																	_a	:    Optional[int]         =		False
																	_a	:    Union[str, Any]         =		True

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

																	_a	:    Any         =		model_class(_a       )
																	model.to(_a       )
																	model.gradient_checkpointing_enable()
																	model.train()
																	_a	:    Any         =		self._prepare_for_class(_a       ,							_a       ,							return_labels=_a       )
																	_a	:    str         =		model(**_a       ).loss
																	loss.backward()


							def 				__lowercase				(			self       )    ->    Tuple:
												_a      ,					_a	:    List[Any]         =		self.model_tester.prepare_config_and_inputs_for_common()

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

																	_a	:    Dict         =		['''pixel_values''']
																	self.assertListEqual(arg_names[:1]       ,							_a       )


							def 				__lowercase				(			self       )    ->    Any:
												_a	:    str         =		self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*_a       )


							def 				__lowercase				(			self       )    ->    Any:
												def check_hidden_states_output(_a       ,							_a       ,							_a       ):
																	_a	:    List[Any]         =		model_class(_a       )
																	model.to(_a       )
																	model.eval()

																	with torch.no_grad():
																						_a	:    Dict         =		model(**self._prepare_for_class(_a       ,							_a       )       )

																	_a	:    str         =		outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

																	_a	:    Dict         =		self.model_tester.num_stages
																	self.assertEqual(len(_a       )       ,							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	:    str         =		self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes:
																	_a	:    int         =		True
																	check_hidden_states_output(_a       ,							_a       ,							_a       )

																	# check that output_hidden_states also work using config
																	del inputs_dict["output_hidden_states"]
																	_a	:    Optional[int]         =		True

																	check_hidden_states_output(_a       ,							_a       ,							_a       )


							def 				__lowercase				(			self       )    ->    Dict:
												_a	:    Optional[int]         =		self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_image_classification(*_a       )




							@slow
							def 				__lowercase				(			self       )    ->    List[str]:
												for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	_a	:    Optional[Any]         =		ConvNextVaModel.from_pretrained(_a       )
																	self.assertIsNotNone(_a       )



def    __UpperCAmelCase (	)			->     Any:

					"""simple docstring"""

					_a	:    Optional[int]         =		Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''	)
					return image







@require_torch
@require_vision
class 				UpperCAmelCase_		(			unittest.TestCase   ):
							"""simple docstring"""







							@cached_property
							def 				__lowercase				(			self       )    ->    List[Any]:
												return AutoImageProcessor.from_pretrained('''facebook/convnextv2-tiny-1k-224'''       ) if is_vision_available() else None




							@slow
							def 				__lowercase				(			self       )    ->    Optional[int]:
												_a	:    Any         =		ConvNextVaForImageClassification.from_pretrained('''facebook/convnextv2-tiny-1k-224'''       ).to(_a       )

												_a	:    Optional[int]         =		self.default_image_processor
												_a	:    Optional[Any]         =		prepare_img()
												_a	:    Any         =		preprocessor(images=_a       ,							return_tensors='''pt'''       ).to(_a       )

												# forward pass
												with torch.no_grad():
																	_a	:    Optional[int]         =		model(**_a       )

												# verify the logits
												_a	:    int         =		torch.Size((1, 1_0_0_0)       )
												self.assertEqual(outputs.logits.shape       ,							_a       )

												_a	:    Optional[Any]         =		torch.tensor([0.9996, 0.1966, -0.4386]       ).to(_a       )
												self.assertTrue(torch.allclose(outputs.logits[0, :3]       ,							_a       ,							atol=1e-4       )       )






from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices


a__				=		logging.get_logger(__name__)

a__				=		{
    '''google/bit-50''': '''https://huggingface.co/google/bit-50/resolve/main/config.json''',
}

class 				UpperCAmelCase_		(			__lowercase				,       __lowercase   ):
							"""simple docstring"""







							UpperCAmelCase__       :						Any	    =    "bit"
							UpperCAmelCase__       :						Optional[int]	    =    ["preactivation", "bottleneck"]
							UpperCAmelCase__       :						Optional[Any]	    =    ["SAME", "VALID"]


							def __init__(			self       ,							_a=3       ,							_a=6_4       ,							_a=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8]       ,							_a=[3, 4, 6, 3]       ,							_a="preactivation"       ,							_a="relu"       ,							_a=None       ,							_a=3_2       ,							_a=0.0       ,							_a=False       ,							_a=3_2       ,							_a=1       ,							_a=None       ,							_a=None       ,							**_a       ,							)    ->    Union[str, Any]:
												super().__init__(**_a       )
												if layer_type not in self.layer_types:
																	raise ValueError(F"""layer_type={layer_type} is not one of {','.join(self.layer_types       )}"""       )
												if global_padding is not None:
																	if global_padding.upper() in self.supported_padding:
																						_a	:    Any         =		global_padding.upper()
																	else:
																						raise ValueError(F"""Padding strategy {global_padding} not supported"""       )
												_a	:    Optional[int]         =		num_channels
												_a	:    List[Any]         =		embedding_size
												_a	:    Any         =		hidden_sizes
												_a	:    int         =		depths
												_a	:    Dict         =		layer_type
												_a	:    int         =		hidden_act
												_a	:    Optional[Any]         =		global_padding
												_a	:    Optional[Any]         =		num_groups
												_a	:    Union[str, Any]         =		drop_path_rate
												_a	:    Tuple         =		embedding_dynamic_padding
												_a	:    Union[str, Any]         =		output_stride
												_a	:    Any         =		width_factor

												_a	:    Any         =		['''stem'''] + [F"""stage{idx}""" for idx in range(1       ,							len(_a       ) + 1       )]
												_a      ,					_a	:    List[str]         =		get_aligned_output_features_output_indices(
												    out_features=_a       ,							out_indices=_a       ,							stage_names=self.stage_names       )



