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

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

							UpperCamelCase_:							Tuple	=						None
							if self.use_labels:
											UpperCamelCase_:							Any	=						ids_tensor([self.batch_size]						,	self.num_labels      )

							UpperCamelCase_:							int	=						self.get_config()

							return config, pixel_values, labels

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

			def       lowerCAmelCase__	(       self :       List[str]						,	snake_case_ :       Optional[Any]						,	snake_case_ :       Any						,	snake_case_ :       List[str]      ):
							UpperCamelCase_:							Dict	=						ConvNextVaModel(config=lowercase_      )
							model.to(lowercase_      )
							model.eval()
							UpperCamelCase_:							Dict	=						model(lowercase_      )
							# 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 :       Union[str, Any]						,	snake_case_ :       Any						,	snake_case_ :       str						,	snake_case_ :       Optional[Any]      ):
							UpperCamelCase_:							Tuple	=						ConvNextVaForImageClassification(lowercase_      )
							model.to(lowercase_      )
							model.eval()
							UpperCamelCase_:							int	=						model(lowercase_						,	labels=lowercase_      )
							self.parent.assertEqual(result.logits.shape						,	(self.batch_size, self.num_labels)      )

			def       lowerCAmelCase__	(       self :       Optional[Any]						,	snake_case_ :       Any						,	snake_case_ :       List[Any]						,	snake_case_ :       str      ):
							UpperCamelCase_:							Tuple	=						ConvNextVaBackbone(config=lowercase_      )
							model.to(lowercase_      )
							model.eval()
							UpperCamelCase_:							Any	=						model(lowercase_      )

							# 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
							UpperCamelCase_:							Dict	=						None
							UpperCamelCase_:							str	=						ConvNextVaBackbone(config=lowercase_      )
							model.to(lowercase_      )
							model.eval()
							UpperCamelCase_:							List[str]	=						model(lowercase_      )

							# 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[Any]      ):
							UpperCamelCase_:							Optional[int]	=						self.prepare_config_and_inputs()
							UpperCamelCase_:							str	=						config_and_inputs
							UpperCamelCase_:							int	=						{"pixel_values": pixel_values}
							return config, inputs_dict




			def       lowerCAmelCase__	(       self :       List[str]      ):
							UpperCamelCase_:							Union[str, Any]	=						self.prepare_config_and_inputs()
							UpperCamelCase_:							Dict	=						config_and_inputs
							UpperCamelCase_:							Union[str, Any]	=						{"pixel_values": pixel_values, "labels": labels}
							return config, inputs_dict




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






			'''simple docstring'''

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

			__UpperCamelCase      :						List[Any]					      = False
			__UpperCamelCase      :						Dict					      = False
			__UpperCamelCase      :						Any					      = False
			__UpperCamelCase      :						Optional[int]					      = False
			__UpperCamelCase      :						Optional[int]					      = False

			def       lowerCAmelCase__	(       self :       int      ):
							UpperCamelCase_:							List[Any]	=						ConvNextVaModelTester(self      )
							UpperCamelCase_:							str	=						ConfigTester(self						,	config_class=lowercase_						,	has_text_modality=lowercase_						,	hidden_size=37      )

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

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

			@unittest.skip(reason="""ConvNextV2 does not support input and output embeddings"""      )
			def       lowerCAmelCase__	(       self :       List[str]      ):
							pass

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

			def       lowerCAmelCase__	(       self :       List[str]      ):
							if not self.model_tester.is_training:
											return

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

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

											UpperCamelCase_:							List[Any]	=						model_class(lowercase_      )
											model.to(lowercase_      )
											model.train()
											UpperCamelCase_:							int	=						self._prepare_for_class(lowercase_						,	lowercase_						,	return_labels=lowercase_      )
											UpperCamelCase_:							Union[str, Any]	=						model(**lowercase_      ).loss
											loss.backward()

			def       lowerCAmelCase__	(       self :       Any      ):
							if not self.model_tester.is_training:
											return

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

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

											UpperCamelCase_:							Any	=						model_class(lowercase_      )
											model.to(lowercase_      )
											model.gradient_checkpointing_enable()
											model.train()
											UpperCamelCase_:							Any	=						self._prepare_for_class(lowercase_						,	lowercase_						,	return_labels=lowercase_      )
											UpperCamelCase_:							Optional[int]	=						model(**lowercase_      ).loss
											loss.backward()

			def       lowerCAmelCase__	(       self :       Optional[int]      ):
							UpperCamelCase_:							Dict	=						self.model_tester.prepare_config_and_inputs_for_common()

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

											UpperCamelCase_:							str	=						["pixel_values"]
											self.assertListEqual(arg_names[:1]						,	lowercase_      )

			def       lowerCAmelCase__	(       self :       Tuple      ):
							UpperCamelCase_:							Tuple	=						self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*lowercase_      )

			def       lowerCAmelCase__	(       self :       Optional[Any]      ):
							def check_hidden_states_output(snake_case_ :       List[str]						,	snake_case_ :       Any						,	snake_case_ :       Optional[int]      ):
											UpperCamelCase_:							int	=						model_class(lowercase_      )
											model.to(lowercase_      )
											model.eval()

											with torch.no_grad():
															UpperCamelCase_:							int	=						model(**self._prepare_for_class(lowercase_						,	lowercase_      )      )

											UpperCamelCase_:							int	=						outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

											UpperCamelCase_:							Dict	=						self.model_tester.num_stages
											self.assertEqual(len(lowercase_      )						,	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]						,	)

							UpperCamelCase_:							Any	=						self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
											UpperCamelCase_:							Tuple	=						True
											check_hidden_states_output(lowercase_						,	lowercase_						,	lowercase_      )

											# check that output_hidden_states also work using config
											del inputs_dict["output_hidden_states"]
											UpperCamelCase_:							Union[str, Any]	=						True

											check_hidden_states_output(lowercase_						,	lowercase_						,	lowercase_      )

			def       lowerCAmelCase__	(       self :       Optional[Any]      ):
							UpperCamelCase_:							Union[str, Any]	=						self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*lowercase_      )




			@slow
			def       lowerCAmelCase__	(       self :       List[Any]      ):
							for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											UpperCamelCase_:							Any	=						ConvNextVaModel.from_pretrained(lowercase_      )
											self.assertIsNotNone(lowercase_      )







def        A__					(						)  ->	Dict:
				UpperCamelCase_:							List[Any]	=						Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""						)
				return image






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






			'''simple docstring'''

			@cached_property
			def       lowerCAmelCase__	(       self :       Optional[int]      ):
							return AutoImageProcessor.from_pretrained("""facebook/convnextv2-tiny-1k-224"""      ) if is_vision_available() else None




			@slow
			def       lowerCAmelCase__	(       self :       int      ):
							UpperCamelCase_:							List[str]	=						ConvNextVaForImageClassification.from_pretrained("""facebook/convnextv2-tiny-1k-224"""      ).to(lowercase_      )

							UpperCamelCase_:							List[Any]	=						self.default_image_processor
							UpperCamelCase_:							str	=						prepare_img()
							UpperCamelCase_:							Any	=						preprocessor(images=lowercase_						,	return_tensors="""pt"""      ).to(lowercase_      )

							# forward pass
							with torch.no_grad():
											UpperCamelCase_:							List[str]	=						model(**lowercase_      )

							# verify the logits
							UpperCamelCase_:							str	=						torch.Size((1, 1000)      )
							self.assertEqual(outputs.logits.shape						,	lowercase_      )

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








import random







def        A__					(						lowerCamelCase     ,    lowerCamelCase     ,    lowerCamelCase = False						)  ->	dict:
				UpperCamelCase_:							dict	=						{i: [] for i in range(lowerCamelCase						)}

				# if probability is greater or equal than 1, then generate a complete graph
				if probability >= 1:
								return complete_graph(lowerCamelCase						)
				# if probability is lower or equal than 0, then return a graph without edges
				if probability <= 0:
								return graph

				# for each couple of nodes, add an edge from u to v
				# if the number randomly generated is greater than probability probability
				for i in range(lowerCamelCase						):
								for j in range(i + 1     ,    lowerCamelCase						):
												if random.random() < probability:
																graph[i].append(lowerCamelCase						)
																if not directed:
																				# if the graph is undirected, add an edge in from j to i, either
																				graph[j].append(lowerCamelCase						)
				return graph







def        A__					(						lowerCamelCase						)  ->	dict:
				return {
				    i: [j for j in range(lowerCamelCase						) if i != j] for i in range(lowerCamelCase						)
				}


if __name__ == "__main__":
							import doctest

							doctest.testmod()






