






import inspect
import unittest

from transformers import RegNetConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

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 torch import nn

		from transformers import RegNetForImageClassification, RegNetModel
		from transformers.models.regnet.modeling_regnet import REGNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import AutoImageProcessor



class 				__UpperCAmelCase		:







			def __init__(     self:  Tuple				,     UpperCAmelCase_:  Optional[int]				,     UpperCAmelCase_:  Union[str, Any]=3				,     UpperCAmelCase_:  Optional[int]=32				,     UpperCAmelCase_:  Tuple=3				,     UpperCAmelCase_:  int=10				,     UpperCAmelCase_:  int=[10, 20, 30, 40]				,     UpperCAmelCase_:  Union[str, Any]=[1, 1, 2, 1]				,     UpperCAmelCase_:  Dict=True				,     UpperCAmelCase_:  Dict=True				,     UpperCAmelCase_:  Optional[Any]="relu"				,     UpperCAmelCase_:  int=3				,     UpperCAmelCase_:  List[str]=None				,     ):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  parent
									_SCREAMING_SNAKE_CASE     				=  batch_size
									_SCREAMING_SNAKE_CASE     				=  image_size
									_SCREAMING_SNAKE_CASE     				=  num_channels
									_SCREAMING_SNAKE_CASE     				=  embeddings_size
									_SCREAMING_SNAKE_CASE     				=  hidden_sizes
									_SCREAMING_SNAKE_CASE     				=  depths
									_SCREAMING_SNAKE_CASE     				=  is_training
									_SCREAMING_SNAKE_CASE     				=  use_labels
									_SCREAMING_SNAKE_CASE     				=  hidden_act
									_SCREAMING_SNAKE_CASE     				=  num_labels
									_SCREAMING_SNAKE_CASE     				=  scope
									_SCREAMING_SNAKE_CASE     				=  len(UpperCAmelCase_					)







			def 							UpperCamelCase				(     self:  Dict					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

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

									_SCREAMING_SNAKE_CASE     				=  self.get_config()

									return config, pixel_values, labels







			def 							UpperCamelCase				(     self:  List[str]					):







									'''simple docstring'''




									return RegNetConfig(
									    num_channels=self.num_channels				,     embeddings_size=self.embeddings_size				,     hidden_sizes=self.hidden_sizes				,     depths=self.depths				,     hidden_act=self.hidden_act				,     num_labels=self.num_labels				,     )







			def 							UpperCamelCase				(     self:  int				,     UpperCAmelCase_:  int				,     UpperCAmelCase_:  Optional[Any]				,     UpperCAmelCase_:  Any					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  RegNetModel(config=UpperCAmelCase_					)
									model.to(UpperCAmelCase_					)
									model.eval()
									_SCREAMING_SNAKE_CASE     				=  model(UpperCAmelCase_					)
									# 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:  int				,     UpperCAmelCase_:  List[Any]				,     UpperCAmelCase_:  Any				,     UpperCAmelCase_:  str					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  self.num_labels
									_SCREAMING_SNAKE_CASE     				=  RegNetForImageClassification(UpperCAmelCase_					)
									model.to(UpperCAmelCase_					)
									model.eval()
									_SCREAMING_SNAKE_CASE     				=  model(UpperCAmelCase_				,     labels=UpperCAmelCase_					)
									self.parent.assertEqual(result.logits.shape				,     (self.batch_size, self.num_labels)					)







			def 							UpperCamelCase				(     self:  Tuple					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  self.prepare_config_and_inputs()
									_SCREAMING_SNAKE_CASE				,					_SCREAMING_SNAKE_CASE				,					_SCREAMING_SNAKE_CASE     				=  config_and_inputs
									_SCREAMING_SNAKE_CASE     				=  {"""pixel_values""": pixel_values}
									return config, inputs_dict



@require_torch
class 				__UpperCAmelCase		(_UpperCAmelCase	,_UpperCAmelCase	,unittest.TestCase   ):
			__snake_case    :				Dict									=(RegNetModel, RegNetForImageClassification) if is_torch_available() else ()
			__snake_case    :				Tuple									=(
			    {"feature-extraction": RegNetModel, "image-classification": RegNetForImageClassification}
			    if is_torch_available()
			    else {}
			)

			__snake_case    :				Optional[int]									=False
			__snake_case    :				Optional[int]									=False
			__snake_case    :				int									=False
			__snake_case    :				Optional[Any]									=False







			def 							UpperCamelCase				(     self:  Any					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  RegNetModelTester(self					)
									_SCREAMING_SNAKE_CASE     				=  ConfigTester(self				,     config_class=UpperCAmelCase_				,     has_text_modality=UpperCAmelCase_					)







			def 							UpperCamelCase				(     self:  Union[str, Any]					):







									'''simple docstring'''




									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:  Optional[int]					):







									'''simple docstring'''




									return







			@unittest.skip(reason="""RegNet does not use inputs_embeds"""					)
			def 							UpperCamelCase				(     self:  Tuple					):







									'''simple docstring'''




									pass







			@unittest.skip(reason="""RegNet does not support input and output embeddings"""					)
			def 							UpperCamelCase				(     self:  Optional[Any]					):







									'''simple docstring'''




									pass







			def 							UpperCamelCase				(     self:  Any					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE				,					_SCREAMING_SNAKE_CASE     				=  self.model_tester.prepare_config_and_inputs_for_common()

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

															_SCREAMING_SNAKE_CASE     				=  ["""pixel_values"""]
															self.assertListEqual(arg_names[:1]				,     UpperCAmelCase_					)







			def 							UpperCamelCase				(     self:  List[str]					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*UpperCAmelCase_					)







			def 							UpperCamelCase				(     self:  Optional[int]					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE				,					_SCREAMING_SNAKE_CASE     				=  self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
															_SCREAMING_SNAKE_CASE     				=  model_class(config=UpperCAmelCase_					)
															for name, module in model.named_modules():
																					if isinstance(UpperCAmelCase_				,     (nn.BatchNormad, nn.GroupNorm)					):
																											self.assertTrue(
																											    torch.all(module.weight == 1					)				,     msg=F'Parameter {name} of model {model_class} seems not properly initialized'				,     )
																											self.assertTrue(
																											    torch.all(module.bias == 0					)				,     msg=F'Parameter {name} of model {model_class} seems not properly initialized'				,     )







			def 							UpperCamelCase				(     self:  Optional[int]					):







									'''simple docstring'''




									def check_hidden_states_output(UpperCAmelCase_:  Optional[int]				,     UpperCAmelCase_:  int				,     UpperCAmelCase_:  Union[str, Any]					):
															_SCREAMING_SNAKE_CASE     				=  model_class(UpperCAmelCase_					)
															model.to(UpperCAmelCase_					)
															model.eval()

															with torch.no_grad():
																					_SCREAMING_SNAKE_CASE     				=  model(**self._prepare_for_class(UpperCAmelCase_				,     UpperCAmelCase_					)					)

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

															_SCREAMING_SNAKE_CASE     				=  self.model_tester.num_stages
															self.assertEqual(len(UpperCAmelCase_					)				,     expected_num_stages + 1					)

															# RegNet'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 // 2, self.model_tester.image_size // 2]				,     )

									_SCREAMING_SNAKE_CASE				,					_SCREAMING_SNAKE_CASE     				=  self.model_tester.prepare_config_and_inputs_for_common()
									_SCREAMING_SNAKE_CASE     				=  ["""basic""", """bottleneck"""]
									for model_class in self.all_model_classes:
															for layer_type in layers_type:
																					_SCREAMING_SNAKE_CASE     				=  layer_type
																					_SCREAMING_SNAKE_CASE     				=  True
																					check_hidden_states_output(UpperCAmelCase_				,     UpperCAmelCase_				,     UpperCAmelCase_					)

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

																					check_hidden_states_output(UpperCAmelCase_				,     UpperCAmelCase_				,     UpperCAmelCase_					)







			def 							UpperCamelCase				(     self:  List[Any]					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_					)







			@slow
			def 							UpperCamelCase				(     self:  int					):







									'''simple docstring'''




									for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															_SCREAMING_SNAKE_CASE     				=  RegNetModel.from_pretrained(UpperCAmelCase_					)
															self.assertIsNotNone(UpperCAmelCase_					)

def 	__lowerCamelCase      (		)							->  Union[str, Any]:






						"""simple docstring"""





						_SCREAMING_SNAKE_CASE     				=  Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""		)
						return image




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







			@cached_property
			def 							UpperCamelCase				(     self:  Tuple					):







									'''simple docstring'''




									return (
									    AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]					)
									    if is_vision_available()
									    else None
									)







			@slow
			def 							UpperCamelCase				(     self:  int					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]					).to(UpperCAmelCase_					)

									_SCREAMING_SNAKE_CASE     				=  self.default_image_processor
									_SCREAMING_SNAKE_CASE     				=  prepare_img()
									_SCREAMING_SNAKE_CASE     				=  image_processor(images=UpperCAmelCase_				,     return_tensors="""pt"""					).to(UpperCAmelCase_					)

									# forward pass
									with torch.no_grad():
															_SCREAMING_SNAKE_CASE     				=  model(**UpperCAmelCase_					)

									# verify the logits
									_SCREAMING_SNAKE_CASE     				=  torch.Size((1, 1_000)					)
									self.assertEqual(outputs.logits.shape				,     UpperCAmelCase_					)

									_SCREAMING_SNAKE_CASE     				=  torch.tensor([-0.41_80, -1.50_51, -3.48_36]					).to(UpperCAmelCase_					)

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









UpperCamelCase			    =     {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []}

UpperCamelCase			    =     {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]}

def 	__lowerCamelCase      (		snake_case__	,snake_case__	,snake_case__		)							->  list[int]:






						"""simple docstring"""





						_SCREAMING_SNAKE_CASE     				=  True
						_SCREAMING_SNAKE_CASE     				=  []

						for neighbour in graph[vert]:
												if not visited[neighbour]:
																		order += topology_sort(snake_case__	,snake_case__	,snake_case__		)

						order.append(snake_case__		)

						return order

def 	__lowerCamelCase      (		snake_case__	,snake_case__	,snake_case__		)							->  list[int]:






						"""simple docstring"""





						_SCREAMING_SNAKE_CASE     				=  True
						_SCREAMING_SNAKE_CASE     				=  [vert]

						for neighbour in reversed_graph[vert]:
												if not visited[neighbour]:
																		component += find_components(snake_case__	,snake_case__	,snake_case__		)

						return component




def 	__lowerCamelCase      (		snake_case__		)							->  list[list[int]]:






						"""simple docstring"""





						_SCREAMING_SNAKE_CASE     				=  len(snake_case__		) * [False]
						_SCREAMING_SNAKE_CASE     				=  {vert: [] for vert in range(len(snake_case__		)		)}

						for vert, neighbours in graph.items():
												for neighbour in neighbours:
																		reversed_graph[neighbour].append(snake_case__		)

						_SCREAMING_SNAKE_CASE     				=  []
						for i, was_visited in enumerate(snake_case__		):
												if not was_visited:
																		order += topology_sort(snake_case__	,snake_case__	,snake_case__		)

						_SCREAMING_SNAKE_CASE     				=  []
						_SCREAMING_SNAKE_CASE     				=  len(snake_case__		) * [False]

						for i in range(len(snake_case__		)		):
												_SCREAMING_SNAKE_CASE     				=  order[len(snake_case__		) - i - 1]
												if not visited[vert]:
																		_SCREAMING_SNAKE_CASE     				=  find_components(snake_case__	,snake_case__	,snake_case__		)
																		components_list.append(snake_case__		)

						return components_list

