





import inspect
import unittest

from transformers import ConvNextConfig
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_backbone_common import BackboneTesterMixin
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 ConvNextBackbone, ConvNextForImageClassification, ConvNextModel
					from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
					from PIL import Image

					from transformers import AutoImageProcessor
class      UpperCamelCase_						:




					def __init__(						self			,  lowerCAmelCase_			,  lowerCAmelCase_=13			,  lowerCAmelCase_=32			,  lowerCAmelCase_=3			,  lowerCAmelCase_=4			,  lowerCAmelCase_=[10, 20, 30, 40]			,  lowerCAmelCase_=[2, 2, 3, 2]			,  lowerCAmelCase_=True			,  lowerCAmelCase_=True			,  lowerCAmelCase_=37			,  lowerCAmelCase_="gelu"			,  lowerCAmelCase_=10			,  lowerCAmelCase_=0.02			,  lowerCAmelCase_=["stage2", "stage3", "stage4"]			,  lowerCAmelCase_=[2, 3, 4]			,  lowerCAmelCase_=None			,  )						->							int:
										_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					)						->							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					)						->							List[Any]:
										return ConvNextConfig(
										    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			,  lowerCAmelCase_			,  lowerCAmelCase_			,  lowerCAmelCase_					)						->							List[str]:
										_snake_case													=			ConvNextModel(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			,  lowerCAmelCase_			,  lowerCAmelCase_			,  lowerCAmelCase_					)						->							Optional[Any]:
										_snake_case													=			ConvNextForImageClassification(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			,  lowerCAmelCase_			,  lowerCAmelCase_			,  lowerCAmelCase_					)						->							Optional[int]:
										_snake_case													=			ConvNextBackbone(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													=			ConvNextBackbone(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					)						->							Dict:
										_snake_case													=			self.prepare_config_and_inputs()
										_snake_case							,       _snake_case							,       _snake_case													=			config_and_inputs
										_snake_case													=			{'pixel_values': pixel_values}
										return config, inputs_dict





@require_torch
class      UpperCamelCase_						(					_lowerCamelCase							,					_lowerCamelCase							,					unittest.TestCase   ):
					lowerCAmelCase_							=		(
					    (
					        ConvNextModel,
					        ConvNextForImageClassification,
					        ConvNextBackbone,
					    )
					    if is_torch_available()
					    else ()
					)
					lowerCAmelCase_							=		(
					    {'''feature-extraction''': ConvNextModel, '''image-classification''': ConvNextForImageClassification}
					    if is_torch_available()
					    else {}
					)

					lowerCAmelCase_							=		True
					lowerCAmelCase_							=		False
					lowerCAmelCase_							=		False
					lowerCAmelCase_							=		False
					lowerCAmelCase_							=		False




					def 		lowerCAmelCase     (						self					)						->							Dict:
										_snake_case													=			ConvNextModelTester(self					)
										_snake_case													=			ConfigTester(self			,  config_class=lowerCAmelCase_			,  has_text_modality=lowerCAmelCase_			,  hidden_size=37					)




					def 		lowerCAmelCase     (						self					)						->							Union[str, 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 		lowerCAmelCase     (						self					)						->							Tuple:
										return




					@unittest.skip(reason='ConvNext does not use inputs_embeds'					)
					def 		lowerCAmelCase     (						self					)						->							List[str]:
										pass




					@unittest.skip(reason='ConvNext does not support input and output embeddings'					)
					def 		lowerCAmelCase     (						self					)						->							Any:
										pass




					@unittest.skip(reason='ConvNext does not use feedforward chunking'					)
					def 		lowerCAmelCase     (						self					)						->							int:
										pass




					def 		lowerCAmelCase     (						self					)						->							List[str]:
										_snake_case							,       _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:
										_snake_case													=			self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*lowerCAmelCase_					)




					def 		lowerCAmelCase     (						self					)						->							Dict:
										_snake_case													=			self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_backbone(*lowerCAmelCase_					)




					def 		lowerCAmelCase     (						self					)						->							Optional[Any]:
										def check_hidden_states_output(lowerCAmelCase_			,  lowerCAmelCase_			,  lowerCAmelCase_					):
															_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					)

															# ConvNext'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							,       _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					)						->							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					)						->							str:
										for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															_snake_case													=			ConvNextModel.from_pretrained(lowerCAmelCase_					)
															self.assertIsNotNone(lowerCAmelCase_					)





def   lowerCamelCase__       (       )     ->	List[str]:



					'''simple docstring'''




					_snake_case													=			Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'  )
					return image
@require_torch
@require_vision
class      UpperCamelCase_						(					unittest.TestCase   ):




					@cached_property
					def 		lowerCAmelCase     (						self					)						->							Optional[Any]:
										return AutoImageProcessor.from_pretrained('facebook/convnext-tiny-224'					) if is_vision_available() else None






					@slow
					def 		lowerCAmelCase     (						self					)						->							Any:
										_snake_case													=			ConvNextForImageClassification.from_pretrained('facebook/convnext-tiny-224'					).to(lowerCAmelCase_					)

										_snake_case													=			self.default_image_processor
										_snake_case													=			prepare_img()
										_snake_case													=			image_processor(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, 1000)					)
										self.assertEqual(outputs.logits.shape			,  lowerCAmelCase_					)

										_snake_case													=			torch.tensor([-0.02_60, -0.47_39, 0.19_11]					).to(lowerCAmelCase_					)

										self.assertTrue(torch.allclose(outputs.logits[0, :3]			,  lowerCAmelCase_			,  atol=1E-4					)					)





@require_torch
class      UpperCamelCase_						(					unittest.TestCase							,					_lowerCamelCase   ):
					lowerCAmelCase_							=		(ConvNextBackbone,) if is_torch_available() else ()
					lowerCAmelCase_							=		ConvNextConfig

					lowerCAmelCase_							=		False




					def 		lowerCAmelCase     (						self					)						->							Dict:
										_snake_case													=			ConvNextModelTester(self					)








import random





def   lowerCamelCase__       (       UpperCamelCase__     :    int    ,      UpperCamelCase__     :    float    ,      UpperCamelCase__     :    bool = False  )     ->	dict:



					'''simple docstring'''




					_snake_case													=			{i: [] for i in range(UpperCamelCase__  )}

					# if probability is greater or equal than 1, then generate a complete graph
					if probability >= 1:
										return complete_graph(UpperCamelCase__  )
					# 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(UpperCamelCase__  ):
										for j in range(i + 1    ,      UpperCamelCase__  ):
															if random.random() < probability:
																				graph[i].append(UpperCamelCase__  )
																				if not directed:
																									# if the graph is undirected, add an edge in from j to i, either
																									graph[j].append(UpperCamelCase__  )
					return graph





def   lowerCamelCase__       (       UpperCamelCase__     :    int  )     ->	dict:



					'''simple docstring'''




					return {
					    i: [j for j in range(UpperCamelCase__  ) if i != j] for i in range(UpperCamelCase__  )
					}


if __name__ == "__main__":
					import doctest

					doctest.testmod()



