






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   __SCREAMING_SNAKE_CASE:
							def __init__(     self:      Optional[int]       ,	UpperCamelCase:      str       ,	UpperCamelCase:      List[Any]=13       ,	UpperCamelCase:      Optional[int]=32       ,	UpperCamelCase:      Any=3       ,	UpperCamelCase:      Dict=4       ,	UpperCamelCase:      Dict=[10, 20, 30, 40]       ,	UpperCamelCase:      List[Any]=[2, 2, 3, 2]       ,	UpperCamelCase:      int=True       ,	UpperCamelCase:      Tuple=True       ,	UpperCamelCase:      int=37       ,	UpperCamelCase:      int="gelu"       ,	UpperCamelCase:      Dict=10       ,	UpperCamelCase:      Any=0.02       ,	UpperCamelCase:      Tuple=["stage2", "stage3", "stage4"]       ,	UpperCamelCase:      Optional[int]=[2, 3, 4]       ,	UpperCamelCase:      int=None       ,	)		->		Tuple:
													snake_case__									=     parent
													snake_case__									=     batch_size
													snake_case__									=     image_size
													snake_case__									=     num_channels
													snake_case__									=     num_stages
													snake_case__									=     hidden_sizes
													snake_case__									=     depths
													snake_case__									=     is_training
													snake_case__									=     use_labels
													snake_case__									=     intermediate_size
													snake_case__									=     hidden_act
													snake_case__									=     num_labels
													snake_case__									=     initializer_range
													snake_case__									=     out_features
													snake_case__									=     out_indices
													snake_case__									=     scope
							def lowerCAmelCase_ (     self:      Optional[Any]						)		->		Union[str, Any]:
													snake_case__									=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

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

													snake_case__									=     self.get_config()

													return config, pixel_values, labels
							def lowerCAmelCase_ (     self:      int						)		->		str:
													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=__lowerCamelCase       ,	initializer_range=self.initializer_range       ,	out_features=self.out_features       ,	out_indices=self.out_indices       ,	num_labels=self.num_labels       ,	)
							def lowerCAmelCase_ (     self:      Optional[Any]       ,	UpperCamelCase:      Optional[Any]       ,	UpperCamelCase:      int       ,	UpperCamelCase:      Any						)		->		int:
													snake_case__									=     ConvNextVaModel(config=__lowerCamelCase						)
													model.to(__lowerCamelCase						)
													model.eval()
													snake_case__									=     model(__lowerCamelCase						)
													# 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 lowerCAmelCase_ (     self:      Tuple       ,	UpperCamelCase:      List[str]       ,	UpperCamelCase:      Dict       ,	UpperCamelCase:      Any						)		->		Dict:
													snake_case__									=     ConvNextVaForImageClassification(__lowerCamelCase						)
													model.to(__lowerCamelCase						)
													model.eval()
													snake_case__									=     model(__lowerCamelCase       ,	labels=__lowerCamelCase						)
													self.parent.assertEqual(result.logits.shape       ,	(self.batch_size, self.num_labels)						)
							def lowerCAmelCase_ (     self:      Union[str, Any]       ,	UpperCamelCase:      Tuple       ,	UpperCamelCase:      Dict       ,	UpperCamelCase:      Optional[Any]						)		->		Tuple:
													snake_case__									=     ConvNextVaBackbone(config=__lowerCamelCase						)
													model.to(__lowerCamelCase						)
													model.eval()
													snake_case__									=     model(__lowerCamelCase						)

													# 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
													snake_case__									=     None
													snake_case__									=     ConvNextVaBackbone(config=__lowerCamelCase						)
													model.to(__lowerCamelCase						)
													model.eval()
													snake_case__									=     model(__lowerCamelCase						)

													# 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 lowerCAmelCase_ (     self:      List[str]						)		->		Dict:
													snake_case__									=     self.prepare_config_and_inputs()
													snake_case__									=     config_and_inputs
													snake_case__									=     {'''pixel_values''': pixel_values}
													return config, inputs_dict


							def lowerCAmelCase_ (     self:      int						)		->		Dict:
													snake_case__									=     self.prepare_config_and_inputs()
													snake_case__									=     config_and_inputs
													snake_case__									=     {'''pixel_values''': pixel_values, '''labels''': labels}
													return config, inputs_dict


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

							_UpperCAmelCase     =       False
							_UpperCAmelCase     =       False
							_UpperCAmelCase     =       False
							_UpperCAmelCase     =       False
							_UpperCAmelCase     =       False
							def lowerCAmelCase_ (     self:      List[Any]						)		->		Optional[int]:
													snake_case__									=     ConvNextVaModelTester(self						)
													snake_case__									=     ConfigTester(self       ,	config_class=__lowerCamelCase       ,	has_text_modality=__lowerCamelCase       ,	hidden_size=37						)
							def lowerCAmelCase_ (     self:      Any						)		->		Optional[int]:
													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 lowerCAmelCase_ (     self:      List[str]						)		->		Tuple:
													return
							@unittest.skip(reason='ConvNextV2 does not use inputs_embeds'						)
							def lowerCAmelCase_ (     self:      Any						)		->		Optional[Any]:
													pass
							@unittest.skip(reason='ConvNextV2 does not support input and output embeddings'						)
							def lowerCAmelCase_ (     self:      str						)		->		Any:
													pass
							@unittest.skip(reason='ConvNextV2 does not use feedforward chunking'						)
							def lowerCAmelCase_ (     self:      Any						)		->		Tuple:
													pass
							def lowerCAmelCase_ (     self:      Dict						)		->		Tuple:






													if not self.model_tester.is_training:
																			return

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

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

																			snake_case__									=     model_class(__lowerCamelCase						)
																			model.to(__lowerCamelCase						)
																			model.train()
																			snake_case__									=     self._prepare_for_class(__lowerCamelCase       ,	__lowerCamelCase       ,	return_labels=__lowerCamelCase						)
																			snake_case__									=     model(**__lowerCamelCase						).loss
																			loss.backward()
							def lowerCAmelCase_ (     self:      List[Any]						)		->		str:






													if not self.model_tester.is_training:
																			return

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

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

																			snake_case__									=     model_class(__lowerCamelCase						)
																			model.to(__lowerCamelCase						)
																			model.gradient_checkpointing_enable()
																			model.train()
																			snake_case__									=     self._prepare_for_class(__lowerCamelCase       ,	__lowerCamelCase       ,	return_labels=__lowerCamelCase						)
																			snake_case__									=     model(**__lowerCamelCase						).loss
																			loss.backward()
							def lowerCAmelCase_ (     self:      Dict						)		->		Optional[int]:
													snake_case__									=     self.model_tester.prepare_config_and_inputs_for_common()

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

																			snake_case__									=     ['''pixel_values''']
																			self.assertListEqual(arg_names[:1]       ,	__lowerCamelCase						)
							def lowerCAmelCase_ (     self:      str						)		->		List[str]:
													snake_case__									=     self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_model(*__lowerCamelCase						)
							def lowerCAmelCase_ (     self:      Dict						)		->		Tuple:






													def check_hidden_states_output(UpperCamelCase:      Tuple       ,	UpperCamelCase:      int       ,	UpperCamelCase:      List[Any]						):
																			snake_case__									=     model_class(__lowerCamelCase						)
																			model.to(__lowerCamelCase						)
																			model.eval()

																			with torch.no_grad():
																									snake_case__									=     model(**self._prepare_for_class(__lowerCamelCase       ,	__lowerCamelCase						)						)

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

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

													snake_case__									=     self.model_tester.prepare_config_and_inputs_for_common()

													for model_class in self.all_model_classes:
																			snake_case__									=     True
																			check_hidden_states_output(__lowerCamelCase       ,	__lowerCamelCase       ,	__lowerCamelCase						)

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

																			check_hidden_states_output(__lowerCamelCase       ,	__lowerCamelCase       ,	__lowerCamelCase						)
							def lowerCAmelCase_ (     self:      Any						)		->		Union[str, Any]:
													snake_case__									=     self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase						)


							@slow
							def lowerCAmelCase_ (     self:      int						)		->		Any:






													for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																			snake_case__									=     ConvNextVaModel.from_pretrained(__lowerCamelCase						)
																			self.assertIsNotNone(__lowerCamelCase						)


def      a_ (      )			->			Dict:







						"""simple docstring"""
						snake_case__									=     Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'  )
						return image


@require_torch
@require_vision
class   __SCREAMING_SNAKE_CASE(	unittest.TestCase	):
							@cached_property
							def lowerCAmelCase_ (     self:      Dict						)		->		str:
													return AutoImageProcessor.from_pretrained('facebook/convnextv2-tiny-1k-224'						) if is_vision_available() else None


							@slow
							def lowerCAmelCase_ (     self:      Optional[Any]						)		->		str:
													snake_case__									=     ConvNextVaForImageClassification.from_pretrained('facebook/convnextv2-tiny-1k-224'						).to(__lowerCamelCase						)

													snake_case__									=     self.default_image_processor
													snake_case__									=     prepare_img()
													snake_case__									=     preprocessor(images=__lowerCamelCase       ,	return_tensors='pt'						).to(__lowerCamelCase						)

													# forward pass
													with torch.no_grad():
																			snake_case__									=     model(**__lowerCamelCase						)

													# verify the logits
													snake_case__									=     torch.Size((1, 10_00)						)
													self.assertEqual(outputs.logits.shape       ,	__lowerCamelCase						)

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












import doctest
import logging
import os
import unittest
from pathlib import Path
from typing import List, Union

import transformers
from transformers.testing_utils import require_tf, require_torch, slow


__UpperCamelCase					:		Optional[Any]	  =						logging.getLogger()


@unittest.skip("Temporarily disable the doc tests."	)
@require_torch
@require_tf
@slow
class   __SCREAMING_SNAKE_CASE(	unittest.TestCase	):
							def lowerCAmelCase_ (     self:      Dict       ,	UpperCamelCase:      Path       ,	UpperCamelCase:      Union[str, None] = None       ,	UpperCamelCase:      Union[List[str], None] = None       ,	UpperCamelCase:      Union[str, List[str], None] = None       ,	UpperCamelCase:      bool = True       ,	)		->		int:
											snake_case__									=     [file for file in os.listdir(UpperCamelCase						) if os.path.isfile(os.path.join(UpperCamelCase       ,	UpperCamelCase						)						)]

											if identifier is not None:
															snake_case__									=     [file for file in files if identifier in file]

											if n_identifier is not None:
															if isinstance(UpperCamelCase       ,	UpperCamelCase						):
																			for n_ in n_identifier:
																							snake_case__									=     [file for file in files if n_ not in file]
															else:
																			snake_case__									=     [file for file in files if n_identifier not in file]

											snake_case__									=     ignore_files or []
											ignore_files.append('__init__.py'						)
											snake_case__									=     [file for file in files if file not in ignore_files]

											for file in files:
															# Open all files
															print('Testing'       ,	UpperCamelCase						)

															if only_modules:
																			snake_case__									=     file.split('.'						)[0]
																			try:
																							snake_case__									=     getattr(UpperCamelCase       ,	UpperCamelCase						)
																							snake_case__									=     doctest.DocTestSuite(UpperCamelCase						)
																							snake_case__									=     unittest.TextTestRunner().run(UpperCamelCase						)
																							self.assertIs(len(result.failures						)       ,	0						)
																			except AttributeError:
																							logger.info(F'''{module_identifier} is not a module.'''						)
															else:
																			snake_case__									=     doctest.testfile(str('..' / directory / file						)       ,	optionflags=doctest.ELLIPSIS						)
																			self.assertIs(result.failed       ,	0						)
							def lowerCAmelCase_ (     self:      Tuple						)		->		int:
											snake_case__									=     Path('src/transformers'						)
											snake_case__									=     'modeling'
											snake_case__									=     [
											    'modeling_ctrl.py',
											    'modeling_tf_ctrl.py',
											]
											self.analyze_directory(UpperCamelCase       ,	identifier=UpperCamelCase       ,	ignore_files=UpperCamelCase						)
							def lowerCAmelCase_ (     self:      Optional[int]						)		->		str:
											snake_case__									=     Path('src/transformers'						)
											snake_case__									=     'tokenization'
											self.analyze_directory(UpperCamelCase       ,	identifier=UpperCamelCase						)
							def lowerCAmelCase_ (     self:      Optional[Any]						)		->		int:
											snake_case__									=     Path('src/transformers'						)
											snake_case__									=     'configuration'
											self.analyze_directory(UpperCamelCase       ,	identifier=UpperCamelCase						)
							def lowerCAmelCase_ (     self:      Dict						)		->		List[Any]:
											snake_case__									=     Path('src/transformers'						)
											snake_case__									=     ['configuration', 'modeling', 'tokenization']
											self.analyze_directory(UpperCamelCase       ,	n_identifier=UpperCamelCase						)


							def lowerCAmelCase_ (     self:      Tuple						)		->		Union[str, Any]:
											snake_case__									=     Path('docs/source'						)
											snake_case__									=     ['favicon.ico']
											self.analyze_directory(UpperCamelCase       ,	ignore_files=UpperCamelCase       ,	only_modules=UpperCamelCase						)




