


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 							A   :
					'''simple docstring'''






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




							"""simple docstring"""


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

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




							"""simple docstring"""


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

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

							lowercase__					      =		self.get_config()

							return config, pixel_values, labels

					def   lowerCamelCase__					(self   :						int		)						->       Optional[int]:




							"""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   lowerCamelCase__					(self   :						int				, _UpperCAmelCase   :						List[str]				, _UpperCAmelCase   :						List[str]				, _UpperCAmelCase   :						str		)						->       int:




							"""simple docstring"""


							lowercase__					      =		RegNetModel(config=_UpperCAmelCase		)
							model.to(_UpperCAmelCase		)
							model.eval()
							lowercase__					      =		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   lowerCamelCase__					(self   :						List[str]				, _UpperCAmelCase   :						Optional[int]				, _UpperCAmelCase   :						Any				, _UpperCAmelCase   :						List[Any]		)						->       Optional[int]:




							"""simple docstring"""


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


					def   lowerCamelCase__					(self   :						str		)						->       int:




							"""simple docstring"""


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






@require_torch
class 							A   (	_SCREAMING_SNAKE_CASE			,  _SCREAMING_SNAKE_CASE			,  unittest.TestCase							):
					'''simple docstring'''






					A__      =			(RegNetModel, RegNetForImageClassification) if is_torch_available() else ()
					A__      =			(
					    {'''feature-extraction''': RegNetModel, '''image-classification''': RegNetForImageClassification}
					    if is_torch_available()
					    else {}
					)

					A__      =			False
					A__      =			False
					A__      =			False
					A__      =			False

					def   lowerCamelCase__					(self   :						Optional[int]		)						->       Optional[int]:




							"""simple docstring"""


							lowercase__					      =		RegNetModelTester(self		)
							lowercase__					      =		ConfigTester(self				, config_class=_UpperCAmelCase				, has_text_modality=_UpperCAmelCase		)

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




							"""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   lowerCamelCase__					(self   :						str		)						->       List[str]:




							"""simple docstring"""


							return

					@unittest.skip(reason="""RegNet does not use inputs_embeds"""		)
					def   lowerCamelCase__					(self   :						str		)						->       Union[str, Any]:




							"""simple docstring"""


							pass

					@unittest.skip(reason="""RegNet does not support input and output embeddings"""		)
					def   lowerCamelCase__					(self   :						int		)						->       str:




							"""simple docstring"""


							pass

					def   lowerCamelCase__					(self   :						List[Any]		)						->       List[str]:




							"""simple docstring"""


							lowercase__      ,     lowercase__					      =		self.model_tester.prepare_config_and_inputs_for_common()

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

									lowercase__					      =		["""pixel_values"""]
									self.assertListEqual(arg_names[:1]				, _UpperCAmelCase		)

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




							"""simple docstring"""


							lowercase__					      =		self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*_UpperCAmelCase		)

					def   lowerCamelCase__					(self   :						Optional[int]		)						->       Dict:




							"""simple docstring"""


							lowercase__      ,     lowercase__					      =		self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
									lowercase__					      =		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   lowerCamelCase__					(self   :						List[Any]		)						->       Dict:




							"""simple docstring"""


							def check_hidden_states_output(_UpperCAmelCase   :						Dict				, _UpperCAmelCase   :						Tuple				, _UpperCAmelCase   :						List[str]		):
									lowercase__					      =		model_class(_UpperCAmelCase		)
									model.to(_UpperCAmelCase		)
									model.eval()

									with torch.no_grad():
											lowercase__					      =		model(**self._prepare_for_class(_UpperCAmelCase				, _UpperCAmelCase		)		)

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

									lowercase__					      =		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]				, )

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

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

											check_hidden_states_output(_UpperCAmelCase				, _UpperCAmelCase				, _UpperCAmelCase		)

					def   lowerCamelCase__					(self   :						Any		)						->       int:




							"""simple docstring"""


							lowercase__					      =		self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase		)


					@slow
					def   lowerCamelCase__					(self   :						Tuple		)						->       str:




							"""simple docstring"""


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






def 			UpperCamelCase (     )       ->  List[str]:
		"""simple docstring"""




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







@require_torch
@require_vision
class 							A   (	unittest.TestCase							):
					'''simple docstring'''






					@cached_property
					def   lowerCamelCase__					(self   :						Tuple		)						->       Optional[Any]:




							"""simple docstring"""


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


					@slow
					def   lowerCamelCase__					(self   :						List[str]		)						->       Any:




							"""simple docstring"""


							lowercase__					      =		RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]		).to(_UpperCAmelCase		)

							lowercase__					      =		self.default_image_processor
							lowercase__					      =		prepare_img()
							lowercase__					      =		image_processor(images=_UpperCAmelCase				, return_tensors="""pt"""		).to(_UpperCAmelCase		)

							# forward pass
							with torch.no_grad():
									lowercase__					      =		model(**_UpperCAmelCase		)

							# verify the logits
							lowercase__					      =		torch.Size((1, 1000)		)
							self.assertEqual(outputs.logits.shape				, _UpperCAmelCase		)

							lowercase__					      =		torch.tensor([-0.4_180, -1.5_051, -3.4_836]		).to(_UpperCAmelCase		)

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





import warnings
from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


A	:		List[str]    =       logging.get_logger(__name__)

A	:		List[Any]    =       {
    'nvidia/segformer-b0-finetuned-ade-512-512': (
        'https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json'
    ),
    # See all SegFormer models at https://huggingface.co/models?filter=segformer
}



class 							A   (	UpperCAmelCase__							):
					'''simple docstring'''






					A__      =			'''segformer'''

					def __init__(self   :						Dict				, _UpperCAmelCase   :						Optional[int]=3				, _UpperCAmelCase   :						Dict=4				, _UpperCAmelCase   :						Union[str, Any]=[2, 2, 2, 2]				, _UpperCAmelCase   :						List[str]=[8, 4, 2, 1]				, _UpperCAmelCase   :						str=[32, 64, 160, 256]				, _UpperCAmelCase   :						Optional[int]=[7, 3, 3, 3]				, _UpperCAmelCase   :						int=[4, 2, 2, 2]				, _UpperCAmelCase   :						str=[1, 2, 5, 8]				, _UpperCAmelCase   :						Optional[int]=[4, 4, 4, 4]				, _UpperCAmelCase   :						List[Any]="gelu"				, _UpperCAmelCase   :						Optional[Any]=0.0				, _UpperCAmelCase   :						Dict=0.0				, _UpperCAmelCase   :						Dict=0.1				, _UpperCAmelCase   :						List[str]=0.02				, _UpperCAmelCase   :						str=0.1				, _UpperCAmelCase   :						Optional[Any]=1E-6				, _UpperCAmelCase   :						Optional[Any]=256				, _UpperCAmelCase   :						Any=255				, **_UpperCAmelCase   :						str				, )						->       Tuple:




							"""simple docstring"""


							super().__init__(**_UpperCAmelCase		)

							if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False:
									warnings.warn(
									    """Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be"""
									    """ removed, as the behaviour will default to that of reshape_last_stage = True."""				, _UpperCAmelCase				, )

							lowercase__					      =		num_channels
							lowercase__					      =		num_encoder_blocks
							lowercase__					      =		depths
							lowercase__					      =		sr_ratios
							lowercase__					      =		hidden_sizes
							lowercase__					      =		patch_sizes
							lowercase__					      =		strides
							lowercase__					      =		mlp_ratios
							lowercase__					      =		num_attention_heads
							lowercase__					      =		hidden_act
							lowercase__					      =		hidden_dropout_prob
							lowercase__					      =		attention_probs_dropout_prob
							lowercase__					      =		classifier_dropout_prob
							lowercase__					      =		initializer_range
							lowercase__					      =		drop_path_rate
							lowercase__					      =		layer_norm_eps
							lowercase__					      =		decoder_hidden_size
							lowercase__					      =		kwargs.get("""reshape_last_stage"""				, _UpperCAmelCase		)
							lowercase__					      =		semantic_loss_ignore_index






class 							A   (	UpperCAmelCase__							):
					'''simple docstring'''






					A__      =			version.parse('''1.11'''							)

					@property
					def   lowerCamelCase__					(self   :						Optional[int]		)						->       Mapping[str, Mapping[int, str]]:




							"""simple docstring"""


							return OrderedDict(
							    [
							        ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}),
							    ]		)

					@property
					def   lowerCamelCase__					(self   :						Optional[int]		)						->       float:




							"""simple docstring"""


							return 1E-4


					@property
					def   lowerCamelCase__					(self   :						Optional[Any]		)						->       int:




							"""simple docstring"""


							return 12

