






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        lowercase__      :


			def __init__(				self					:  int       ,	snake_case__					:  List[str]       ,	snake_case__					:  Union[str, Any]=13       ,	snake_case__					:  Optional[int]=32       ,	snake_case__					:  int=3       ,	snake_case__					:  List[str]=4       ,	snake_case__					:  Optional[int]=[10, 20, 30, 40]       ,	snake_case__					:  Tuple=[2, 2, 3, 2]       ,	snake_case__					:  Dict=True       ,	snake_case__					:  List[str]=True       ,	snake_case__					:  Optional[Any]=37       ,	snake_case__					:  Union[str, Any]="gelu"       ,	snake_case__					:  Any=10       ,	snake_case__					:  str=0.02       ,	snake_case__					:  str=["stage2", "stage3", "stage4"]       ,	snake_case__					:  List[str]=[2, 3, 4]       ,	snake_case__					:  List[Any]=None       ,	):
										lowerCamelCase_	:							Dict									=parent
										lowerCamelCase_	:							List[str]									=batch_size
										lowerCamelCase_	:							str									=image_size
										lowerCamelCase_	:							Tuple									=num_channels
										lowerCamelCase_	:							List[str]									=num_stages
										lowerCamelCase_	:							Optional[Any]									=hidden_sizes
										lowerCamelCase_	:							str									=depths
										lowerCamelCase_	:							int									=is_training
										lowerCamelCase_	:							Optional[int]									=use_labels
										lowerCamelCase_	:							Tuple									=intermediate_size
										lowerCamelCase_	:							List[str]									=hidden_act
										lowerCamelCase_	:							Union[str, Any]									=num_labels
										lowerCamelCase_	:							Union[str, Any]									=initializer_range
										lowerCamelCase_	:							Union[str, Any]									=out_features
										lowerCamelCase_	:							List[str]									=out_indices
										lowerCamelCase_	:							Union[str, Any]									=scope


			def      UpperCAmelCase__						(				self					:  str ):
										lowerCamelCase_	:							Union[str, Any]									=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

										lowerCamelCase_	:							Dict									=None
										if self.use_labels:
																	lowerCamelCase_	:							Union[str, Any]									=ids_tensor([self.batch_size]       ,	self.num_labels )

										lowerCamelCase_	:							Optional[Any]									=self.get_config()

										return config, pixel_values, labels


			def      UpperCAmelCase__						(				self					:  Tuple ):
										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      UpperCAmelCase__						(				self					:  Union[str, Any]       ,	snake_case__					:  int       ,	snake_case__					:  Optional[Any]       ,	snake_case__					:  int ):
										lowerCamelCase_	:							Any									=ConvNextVaModel(config=_a )
										model.to(_a )
										model.eval()
										lowerCamelCase_	:							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 // 32, self.image_size // 32)       ,	)


			def      UpperCAmelCase__						(				self					:  Any       ,	snake_case__					:  Any       ,	snake_case__					:  str       ,	snake_case__					:  Optional[Any] ):
										lowerCamelCase_	:							Tuple									=ConvNextVaForImageClassification(_a )
										model.to(_a )
										model.eval()
										lowerCamelCase_	:							Optional[Any]									=model(_a       ,	labels=_a )
										self.parent.assertEqual(result.logits.shape       ,	(self.batch_size, self.num_labels) )


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


			def      UpperCAmelCase__						(				self					:  Optional[int] ):
										lowerCamelCase_	:							Dict									=self.prepare_config_and_inputs()
										lowerCamelCase_	:							Tuple									=config_and_inputs
										lowerCamelCase_	:							Union[str, Any]									={'pixel_values': pixel_values, 'labels': labels}
										return config, inputs_dict







@require_torch
class        lowercase__      (							lowercase__,       lowercase__,       unittest.TestCase       ):
			_UpperCAmelCase		:Dict             =			(
			    (
			        ConvNextVaModel,
			        ConvNextVaForImageClassification,
			        ConvNextVaBackbone,
			    )
			    if is_torch_available()
			    else ()
			)
			_UpperCAmelCase		:Dict             =			(
			    {'''feature-extraction''': ConvNextVaModel, '''image-classification''': ConvNextVaForImageClassification}
			    if is_torch_available()
			    else {}
			)

			_UpperCAmelCase		:Optional[int]             =			False
			_UpperCAmelCase		:List[str]             =			False
			_UpperCAmelCase		:Tuple             =			False
			_UpperCAmelCase		:List[str]             =			False
			_UpperCAmelCase		:List[Any]             =			False


			def      UpperCAmelCase__						(				self					:  Tuple ):
										lowerCamelCase_	:							Any									=ConvNextVaModelTester(self )
										lowerCamelCase_	:							Dict									=ConfigTester(self       ,	config_class=_a       ,	has_text_modality=_a       ,	hidden_size=37 )


			def      UpperCAmelCase__						(				self					:  Any ):
										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] ):
										return


			@unittest.skip(reason="ConvNextV2 does not use inputs_embeds" )
			def      UpperCAmelCase__						(				self					:  int ):
										pass


			@unittest.skip(reason="ConvNextV2 does not support input and output embeddings" )
			def      UpperCAmelCase__						(				self					:  Dict ):
										pass


			@unittest.skip(reason="ConvNextV2 does not use feedforward chunking" )
			def      UpperCAmelCase__						(				self					:  Tuple ):
										pass


			def      UpperCAmelCase__						(				self					:  str ):






										if not self.model_tester.is_training:
																	return

										for model_class in self.all_model_classes:
																	lowerCamelCase_	:							Dict									=self.model_tester.prepare_config_and_inputs_with_labels()
																	lowerCamelCase_	:							List[str]									=True

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

																	lowerCamelCase_	:							Union[str, Any]									=model_class(_a )
																	model.to(_a )
																	model.train()
																	lowerCamelCase_	:							Any									=self._prepare_for_class(_a       ,	_a       ,	return_labels=_a )
																	lowerCamelCase_	:							Optional[int]									=model(**_a ).loss
																	loss.backward()


			def      UpperCAmelCase__						(				self					:  List[str] ):






										if not self.model_tester.is_training:
																	return

										for model_class in self.all_model_classes:
																	lowerCamelCase_	:							Optional[Any]									=self.model_tester.prepare_config_and_inputs_with_labels()
																	lowerCamelCase_	:							Tuple									=False
																	lowerCamelCase_	:							int									=True

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

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


			def      UpperCAmelCase__						(				self					:  Union[str, Any] ):
										lowerCamelCase_	:							Dict									=self.model_tester.prepare_config_and_inputs_for_common()

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

																	lowerCamelCase_	:							Optional[Any]									=['pixel_values']
																	self.assertListEqual(arg_names[:1]       ,	_a )


			def      UpperCAmelCase__						(				self					:  Tuple ):
										lowerCamelCase_	:							Optional[int]									=self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*_a )


			def      UpperCAmelCase__						(				self					:  Any ):






										def check_hidden_states_output(snake_case__					:  Any       ,	snake_case__					:  List[str]       ,	snake_case__					:  List[Any] ):
																	lowerCamelCase_	:							Any									=model_class(_a )
																	model.to(_a )
																	model.eval()

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

																	lowerCamelCase_	:							Any									=outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

																	lowerCamelCase_	:							Tuple									=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]       ,	)

										lowerCamelCase_	:							Optional[int]									=self.model_tester.prepare_config_and_inputs_for_common()

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

																	# check that output_hidden_states also work using config
																	del inputs_dict["output_hidden_states"]
																	lowerCamelCase_	:							Any									=True

																	check_hidden_states_output(_a       ,	_a       ,	_a )


			def      UpperCAmelCase__						(				self					:  str ):
										lowerCamelCase_	:							List[str]									=self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*_a )


			@slow
			def      UpperCAmelCase__						(				self					:  int ):






										for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	lowerCamelCase_	:							Optional[int]									=ConvNextVaModel.from_pretrained(_a )
																	self.assertIsNotNone(_a )


def 			_snake_case    (					)    ->     Any:
							lowerCamelCase_	:							Union[str, Any]									=Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"  )
							return image







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


			@cached_property
			def      UpperCAmelCase__						(				self					:  Dict ):
										return AutoImageProcessor.from_pretrained("facebook/convnextv2-tiny-1k-224" ) if is_vision_available() else None


			@slow
			def      UpperCAmelCase__						(				self					:  Optional[int] ):
										lowerCamelCase_	:							str									=ConvNextVaForImageClassification.from_pretrained("facebook/convnextv2-tiny-1k-224" ).to(_a )

										lowerCamelCase_	:							Any									=self.default_image_processor
										lowerCamelCase_	:							Dict									=prepare_img()
										lowerCamelCase_	:							Tuple									=preprocessor(images=_a       ,	return_tensors="pt" ).to(_a )

										# forward pass
										with torch.no_grad():
																	lowerCamelCase_	:							str									=model(**_a )

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

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











"""simple docstring"""



import pytest

from datasets.parallel import ParallelBackendConfig, parallel_backend
from datasets.utils.py_utils import map_nested

from .utils import require_dill_gt_0_3_2, require_joblibspark, require_not_windows

def 			_snake_case    (					lowerCamelCase__     :   Any  )    ->     Union[str, Any]:  # picklable for multiprocessing
							return i + 1

@require_dill_gt_0_3_2
@require_joblibspark
@require_not_windows
def 			_snake_case    (					)    ->     List[Any]:
							with parallel_backend("spark"  ):
														assert ParallelBackendConfig.backend_name == "spark"

							lowerCamelCase_	:							Optional[Any]									=[1, 2, 3]
							with pytest.raises(lowerCamelCase__  ):
														with parallel_backend("unsupported backend"  ):
																					map_nested(lowerCamelCase__    ,						lowerCamelCase__    ,						num_proc=2  )

							with pytest.raises(lowerCamelCase__  ):
														with parallel_backend("unsupported backend"  ):
																					map_nested(lowerCamelCase__    ,						lowerCamelCase__    ,						num_proc=-1  )

@require_dill_gt_0_3_2
@require_joblibspark
@require_not_windows
@pytest.mark.parametrize("num_proc"    ,						[2, -1]  )
def 			_snake_case    (					lowerCamelCase__     :   Tuple  )    ->     Optional[Any]:
							lowerCamelCase_	:							str									=[1, 2]
							lowerCamelCase_	:							List[str]									={"a": 1, "b": 2}
							lowerCamelCase_	:							List[str]									={"a": [1, 2], "b": [3, 4]}
							lowerCamelCase_	:							Optional[int]									={"a": {"1": 1}, "b": 2}
							lowerCamelCase_	:							int									={"a": 1, "b": 2, "c": 3, "d": 4}
							lowerCamelCase_	:							Optional[int]									=[2, 3]
							lowerCamelCase_	:							List[Any]									={"a": 2, "b": 3}
							lowerCamelCase_	:							int									={"a": [2, 3], "b": [4, 5]}
							lowerCamelCase_	:							str									={"a": {"1": 2}, "b": 3}
							lowerCamelCase_	:							Dict									={"a": 2, "b": 3, "c": 4, "d": 5}

							with parallel_backend("spark"  ):
														assert map_nested(lowerCamelCase__    ,						lowerCamelCase__    ,						num_proc=lowerCamelCase__  ) == expected_map_nested_sa
														assert map_nested(lowerCamelCase__    ,						lowerCamelCase__    ,						num_proc=lowerCamelCase__  ) == expected_map_nested_sa
														assert map_nested(lowerCamelCase__    ,						lowerCamelCase__    ,						num_proc=lowerCamelCase__  ) == expected_map_nested_sa
														assert map_nested(lowerCamelCase__    ,						lowerCamelCase__    ,						num_proc=lowerCamelCase__  ) == expected_map_nested_sa
														assert map_nested(lowerCamelCase__    ,						lowerCamelCase__    ,						num_proc=lowerCamelCase__  ) == expected_map_nested_sa



