"""simple docstring"""





import inspect
import unittest

from huggingface_hub import hf_hub_download

from transformers import ConvNextConfig, UperNetConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
			import torch

			from transformers import UperNetForSemanticSegmentation
			from transformers.models.upernet.modeling_upernet import UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
			from PIL import Image

			from transformers import AutoImageProcessor




class  _snake_case		:







				"""simple docstring"""






				def __init__(      self							:							List[str]      ,    _A							:							Optional[Any]      ,    _A							:							List[Any]=1_3      ,    _A							:							int=3_2      ,    _A							:							int=3      ,    _A							:							Tuple=4      ,    _A							:							str=[1_0, 2_0, 3_0, 4_0]      ,    _A							:							Optional[int]=[2, 2, 3, 2]      ,    _A							:							int=True      ,    _A							:							int=True      ,    _A							:							Tuple=3_7      ,    _A							:							List[str]="gelu"      ,    _A							:							Optional[int]=1_0      ,    _A							:							Union[str, Any]=0.02      ,    _A							:							Dict=["stage2", "stage3", "stage4"]      ,    _A							:							str=3      ,    _A							:							Dict=None      ,    ):



											"""simple docstring"""







											_SCREAMING_SNAKE_CASE		:						Tuple			  =    parent
											_SCREAMING_SNAKE_CASE		:						int			  =    batch_size
											_SCREAMING_SNAKE_CASE		:						int			  =    image_size
											_SCREAMING_SNAKE_CASE		:						str			  =    num_channels
											_SCREAMING_SNAKE_CASE		:						Union[str, Any]			  =    num_stages
											_SCREAMING_SNAKE_CASE		:						Any			  =    hidden_sizes
											_SCREAMING_SNAKE_CASE		:						Union[str, Any]			  =    depths
											_SCREAMING_SNAKE_CASE		:						int			  =    is_training
											_SCREAMING_SNAKE_CASE		:						int			  =    use_labels
											_SCREAMING_SNAKE_CASE		:						Any			  =    intermediate_size
											_SCREAMING_SNAKE_CASE		:						List[Any]			  =    hidden_act
											_SCREAMING_SNAKE_CASE		:						int			  =    type_sequence_label_size
											_SCREAMING_SNAKE_CASE		:						Dict			  =    initializer_range
											_SCREAMING_SNAKE_CASE		:						str			  =    out_features
											_SCREAMING_SNAKE_CASE		:						Any			  =    num_labels
											_SCREAMING_SNAKE_CASE		:						Union[str, Any]			  =    scope
											_SCREAMING_SNAKE_CASE		:						str			  =    num_stages





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



											"""simple docstring"""







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

											_SCREAMING_SNAKE_CASE		:						List[str]			  =    None
											if self.use_labels:
																		_SCREAMING_SNAKE_CASE		:						List[Any]			  =    ids_tensor([self.batch_size]      ,    self.type_sequence_label_size)

											_SCREAMING_SNAKE_CASE		:						List[Any]			  =    self.get_config()

											return config, pixel_values, labels





				def 		_lowerCAmelCase		(      self							:							List[str]):



											"""simple docstring"""







											return ConvNextConfig(
											    num_channels=self.num_channels      ,    num_stages=self.num_stages      ,    hidden_sizes=self.hidden_sizes      ,    depths=self.depths      ,    is_training=self.is_training      ,    intermediate_size=self.intermediate_size      ,    hidden_act=self.hidden_act      ,    out_features=self.out_features      ,    )





				def 		_lowerCAmelCase		(      self							:							Optional[Any]):



											"""simple docstring"""







											return UperNetConfig(
											    backbone_config=self.get_backbone_config()      ,    hidden_size=5_1_2      ,    pool_scales=[1, 2, 3, 6]      ,    use_auxiliary_head=_A      ,    auxiliary_loss_weight=0.4      ,    auxiliary_in_channels=4_0      ,    auxiliary_channels=2_5_6      ,    auxiliary_num_convs=1      ,    auxiliary_concat_input=_A      ,    loss_ignore_index=2_5_5      ,    num_labels=self.num_labels      ,    )





				def 		_lowerCAmelCase		(      self							:							Optional[int]      ,    _A							:							Optional[Any]      ,    _A							:							Optional[int]      ,    _A							:							Dict):



											"""simple docstring"""







											_SCREAMING_SNAKE_CASE		:						Any			  =    UperNetForSemanticSegmentation(config=_A)
											model.to(_A)
											model.eval()
											_SCREAMING_SNAKE_CASE		:						Dict			  =    model(_A)
											self.parent.assertEqual(
											    result.logits.shape      ,    (self.batch_size, self.num_labels, self.image_size, self.image_size))





				def 		_lowerCAmelCase		(      self							:							Tuple):



											"""simple docstring"""







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




@require_torch
class  _snake_case		(    __snake_case   ,       __snake_case   ,       unittest.TestCase ):







				"""simple docstring"""






				a			=						(UperNetForSemanticSegmentation,) if is_torch_available() else ()
				a			=						{"image-segmentation": UperNetForSemanticSegmentation} if is_torch_available() else {}
				a			=						False
				a			=						False
				a			=						False
				a			=						False
				a			=						False
				a			=						False





				def 		_lowerCAmelCase		(      self							:							Tuple):



											"""simple docstring"""







											_SCREAMING_SNAKE_CASE		:						Dict			  =    UperNetModelTester(self)
											_SCREAMING_SNAKE_CASE		:						List[str]			  =    ConfigTester(self      ,    config_class=_A      ,    has_text_modality=_A      ,    hidden_size=3_7)





				def 		_lowerCAmelCase		(      self							:							List[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							:							List[Any]):



											"""simple docstring"""







											return





				def 		_lowerCAmelCase		(      self							:							List[Any]):



											"""simple docstring"""







											_SCREAMING_SNAKE_CASE  ,				_SCREAMING_SNAKE_CASE		:						Union[str, Any]			  =    self.model_tester.prepare_config_and_inputs_for_common()

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

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





				def 		_lowerCAmelCase		(      self							:							str):



											"""simple docstring"""







											_SCREAMING_SNAKE_CASE		:						Tuple			  =    self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_semantic_segmentation(*_A)





				@unittest.skip(reason="""UperNet does not use inputs_embeds""")
				def 		_lowerCAmelCase		(      self							:							Optional[int]):



											"""simple docstring"""







											pass





				@unittest.skip(reason="""UperNet does not support input and output embeddings""")
				def 		_lowerCAmelCase		(      self							:							List[Any]):



											"""simple docstring"""







											pass





				@unittest.skip(reason="""UperNet does not have a base model""")
				def 		_lowerCAmelCase		(      self							:							str):



											"""simple docstring"""







											pass





				@unittest.skip(reason="""UperNet does not have a base model""")
				def 		_lowerCAmelCase		(      self							:							Union[str, Any]):



											"""simple docstring"""







											pass





				@require_torch_multi_gpu
				@unittest.skip(reason="""UperNet has some layers using `add_module` which doesn't work well with `nn.DataParallel`""")
				def 		_lowerCAmelCase		(      self							:							List[str]):



											"""simple docstring"""







											pass





				@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""")
				def 		_lowerCAmelCase		(      self							:							List[Any]):



											"""simple docstring"""







											pass





				def 		_lowerCAmelCase		(      self							:							Optional[int]):



											"""simple docstring"""







											def check_hidden_states_output(_A							:							List[Any]      ,    _A							:							Any      ,    _A							:							str):
																		_SCREAMING_SNAKE_CASE		:						int			  =    model_class(_A)
																		model.to(_A)
																		model.eval()

																		with torch.no_grad():
																									_SCREAMING_SNAKE_CASE		:						Optional[int]			  =    model(**self._prepare_for_class(_A      ,    _A))

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

																		_SCREAMING_SNAKE_CASE		:						Tuple			  =    self.model_tester.num_stages
																		self.assertEqual(len(_A)      ,    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]      ,    )

											_SCREAMING_SNAKE_CASE  ,				_SCREAMING_SNAKE_CASE		:						List[Any]			  =    self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																		_SCREAMING_SNAKE_CASE		:						Union[str, Any]			  =    True
																		check_hidden_states_output(_A      ,    _A      ,    _A)

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

																		check_hidden_states_output(_A      ,    _A      ,    _A)





				def 		_lowerCAmelCase		(      self							:							Any):



											"""simple docstring"""







											_SCREAMING_SNAKE_CASE  ,				_SCREAMING_SNAKE_CASE		:						Optional[Any]			  =    self.model_tester.prepare_config_and_inputs_for_common()

											_SCREAMING_SNAKE_CASE		:						Dict			  =    _config_zero_init(_A)
											_SCREAMING_SNAKE_CASE		:						Optional[int]			  =    _config_zero_init(configs_no_init.backbone_config)
											for model_class in self.all_model_classes:
																		_SCREAMING_SNAKE_CASE		:						Optional[int]			  =    model_class(config=_A)
																		for name, param in model.named_parameters():
																									if param.requires_grad:
																																self.assertIn(
																																    ((param.data.mean() * 1e9).round() / 1e9).item()      ,    [0.0, 1.0]      ,    msg=f"""Parameter {name} of model {model_class} seems not properly initialized"""      ,    )





				@unittest.skip(reason="""UperNet does not have tied weights""")
				def 		_lowerCAmelCase		(      self							:							str):



											"""simple docstring"""







											pass





				@slow
				def 		_lowerCAmelCase		(      self							:							Union[str, Any]):



											"""simple docstring"""







											for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																		_SCREAMING_SNAKE_CASE		:						Any			  =    UperNetForSemanticSegmentation.from_pretrained(_A)
																		self.assertIsNotNone(_A)



def      lowerCamelCase_()->    Dict:
							_SCREAMING_SNAKE_CASE		:						str			  =    hf_hub_download(
							    repo_id="""hf-internal-testing/fixtures_ade20k"""     ,	repo_type="""dataset"""     ,	filename="""ADE_val_00000001.jpg"""  )
							_SCREAMING_SNAKE_CASE		:						List[Any]			  =    Image.open(__SCREAMING_SNAKE_CASE  ).convert("""RGB"""  )
							return image




@require_torch
@require_vision
@slow
class  _snake_case		(    unittest.TestCase ):







				"""simple docstring"""






				def 		_lowerCAmelCase		(      self							:							Optional[Any]):



											"""simple docstring"""







											_SCREAMING_SNAKE_CASE		:						Tuple			  =    AutoImageProcessor.from_pretrained("""openmmlab/upernet-swin-tiny""")
											_SCREAMING_SNAKE_CASE		:						Optional[int]			  =    UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-swin-tiny""").to(_A)

											_SCREAMING_SNAKE_CASE		:						Dict			  =    prepare_img()
											_SCREAMING_SNAKE_CASE		:						List[Any]			  =    processor(images=_A      ,    return_tensors="""pt""").to(_A)

											with torch.no_grad():
																		_SCREAMING_SNAKE_CASE		:						Optional[Any]			  =    model(**_A)

											_SCREAMING_SNAKE_CASE		:						str			  =    torch.Size((1, model.config.num_labels, 5_1_2, 5_1_2))
											self.assertEqual(outputs.logits.shape      ,    _A)

											_SCREAMING_SNAKE_CASE		:						str			  =    torch.tensor(
											    [[-7.5_958, -7.5_958, -7.4_302], [-7.5_958, -7.5_958, -7.4_302], [-7.4_797, -7.4_797, -7.3_068]]).to(_A)
											self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]      ,    _A      ,    atol=1e-4))





				def 		_lowerCAmelCase		(      self							:							Any):



											"""simple docstring"""







											_SCREAMING_SNAKE_CASE		:						str			  =    AutoImageProcessor.from_pretrained("""openmmlab/upernet-convnext-tiny""")
											_SCREAMING_SNAKE_CASE		:						int			  =    UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-convnext-tiny""").to(_A)

											_SCREAMING_SNAKE_CASE		:						Union[str, Any]			  =    prepare_img()
											_SCREAMING_SNAKE_CASE		:						Dict			  =    processor(images=_A      ,    return_tensors="""pt""").to(_A)

											with torch.no_grad():
																		_SCREAMING_SNAKE_CASE		:						List[Any]			  =    model(**_A)

											_SCREAMING_SNAKE_CASE		:						Optional[int]			  =    torch.Size((1, model.config.num_labels, 5_1_2, 5_1_2))
											self.assertEqual(outputs.logits.shape      ,    _A)

											_SCREAMING_SNAKE_CASE		:						Union[str, Any]			  =    torch.tensor(
											    [[-8.8_110, -8.8_110, -8.6_521], [-8.8_110, -8.8_110, -8.6_521], [-8.7_746, -8.7_746, -8.6_130]]).to(_A)
											self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]      ,    _A      ,    atol=1e-4))



"""simple docstring"""





import functools
import operator

from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowerCAmelCase_     =	logging.get_logger(__name__)

lowerCAmelCase_     =	{
    '''asapp/sew-tiny-100k''': '''https://huggingface.co/asapp/sew-tiny-100k/resolve/main/config.json''',
    # See all SEW models at https://huggingface.co/models?filter=sew
}




class  _snake_case		(    __snake_case ):







				"""simple docstring"""






				a			=						"sew"





				def __init__(      self							:							List[Any]      ,    _A							:							Tuple=3_2      ,    _A							:							str=7_6_8      ,    _A							:							Dict=1_2      ,    _A							:							Tuple=1_2      ,    _A							:							Optional[Any]=3_0_7_2      ,    _A							:							List[str]=2      ,    _A							:							Dict="gelu"      ,    _A							:							Union[str, Any]=0.1      ,    _A							:							Optional[int]=0.1      ,    _A							:							Optional[int]=0.1      ,    _A							:							Optional[int]=0.0      ,    _A							:							str=0.1      ,    _A							:							Tuple=0.1      ,    _A							:							Optional[int]=0.02      ,    _A							:							Dict=1e-5      ,    _A							:							str="group"      ,    _A							:							Tuple="gelu"      ,    _A							:							Union[str, Any]=(6_4, 1_2_8, 1_2_8, 1_2_8, 1_2_8, 2_5_6, 2_5_6, 2_5_6, 2_5_6, 5_1_2, 5_1_2, 5_1_2, 5_1_2)      ,    _A							:							Optional[Any]=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1)      ,    _A							:							Any=(1_0, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1)      ,    _A							:							Tuple=False      ,    _A							:							Tuple=1_2_8      ,    _A							:							int=1_6      ,    _A							:							Union[str, Any]=True      ,    _A							:							Optional[Any]=0.05      ,    _A							:							List[Any]=1_0      ,    _A							:							Union[str, Any]=2      ,    _A							:							Tuple=0.0      ,    _A							:							Union[str, Any]=1_0      ,    _A							:							Optional[int]=0      ,    _A							:							Union[str, Any]="mean"      ,    _A							:							Optional[int]=False      ,    _A							:							List[Any]=False      ,    _A							:							int=2_5_6      ,    _A							:							str=0      ,    _A							:							Optional[int]=1      ,    _A							:							List[Any]=2      ,    **_A							:							Dict      ,    ):



											"""simple docstring"""







											super().__init__(**_A      ,    pad_token_id=_A      ,    bos_token_id=_A      ,    eos_token_id=_A)
											_SCREAMING_SNAKE_CASE		:						str			  =    hidden_size
											_SCREAMING_SNAKE_CASE		:						Optional[int]			  =    feat_extract_norm
											_SCREAMING_SNAKE_CASE		:						Optional[int]			  =    feat_extract_activation
											_SCREAMING_SNAKE_CASE		:						Dict			  =    list(_A)
											_SCREAMING_SNAKE_CASE		:						int			  =    list(_A)
											_SCREAMING_SNAKE_CASE		:						int			  =    list(_A)
											_SCREAMING_SNAKE_CASE		:						str			  =    conv_bias
											_SCREAMING_SNAKE_CASE		:						Tuple			  =    num_conv_pos_embeddings
											_SCREAMING_SNAKE_CASE		:						List[str]			  =    num_conv_pos_embedding_groups
											_SCREAMING_SNAKE_CASE		:						Tuple			  =    len(self.conv_dim)
											_SCREAMING_SNAKE_CASE		:						Tuple			  =    num_hidden_layers
											_SCREAMING_SNAKE_CASE		:						List[str]			  =    intermediate_size
											_SCREAMING_SNAKE_CASE		:						str			  =    squeeze_factor
											_SCREAMING_SNAKE_CASE		:						Dict			  =    hidden_act
											_SCREAMING_SNAKE_CASE		:						str			  =    num_attention_heads
											_SCREAMING_SNAKE_CASE		:						Dict			  =    hidden_dropout
											_SCREAMING_SNAKE_CASE		:						Tuple			  =    attention_dropout
											_SCREAMING_SNAKE_CASE		:						int			  =    activation_dropout
											_SCREAMING_SNAKE_CASE		:						Any			  =    feat_proj_dropout
											_SCREAMING_SNAKE_CASE		:						str			  =    final_dropout
											_SCREAMING_SNAKE_CASE		:						Union[str, Any]			  =    layerdrop
											_SCREAMING_SNAKE_CASE		:						Any			  =    layer_norm_eps
											_SCREAMING_SNAKE_CASE		:						int			  =    initializer_range
											_SCREAMING_SNAKE_CASE		:						List[Any]			  =    vocab_size

											if (
											    (len(self.conv_stride) != self.num_feat_extract_layers)
											    or (len(self.conv_kernel) != self.num_feat_extract_layers)
											    or (len(self.conv_dim) != self.num_feat_extract_layers)
											):
																		raise ValueError(
																		    """Configuration for convolutional layers is incorrect."""
																		    """It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,"""
																		    f"""but is `len(config.conv_dim) = {len(self.conv_dim)}`, `len(config.conv_stride)"""
																		    f"""= {len(self.conv_stride)}`, `len(config.conv_kernel) = {len(self.conv_kernel)}`.""")

											# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
											_SCREAMING_SNAKE_CASE		:						List[Any]			  =    apply_spec_augment
											_SCREAMING_SNAKE_CASE		:						List[Any]			  =    mask_time_prob
											_SCREAMING_SNAKE_CASE		:						List[str]			  =    mask_time_length
											_SCREAMING_SNAKE_CASE		:						List[Any]			  =    mask_time_min_masks
											_SCREAMING_SNAKE_CASE		:						List[Any]			  =    mask_feature_prob
											_SCREAMING_SNAKE_CASE		:						int			  =    mask_feature_length
											_SCREAMING_SNAKE_CASE		:						List[Any]			  =    mask_feature_min_masks

											# ctc loss
											_SCREAMING_SNAKE_CASE		:						int			  =    ctc_loss_reduction
											_SCREAMING_SNAKE_CASE		:						Optional[int]			  =    ctc_zero_infinity

											# sequence classification
											_SCREAMING_SNAKE_CASE		:						Dict			  =    use_weighted_layer_sum
											_SCREAMING_SNAKE_CASE		:						List[str]			  =    classifier_proj_size





				@property
				def 		_lowerCAmelCase		(      self							:							Any):



											"""simple docstring"""







											return functools.reduce(operator.mul      ,    self.conv_stride      ,    1)


