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        UpperCamelCase						:





						def __init__(self			,     __UpperCamelCase			,     __UpperCamelCase=13			,     __UpperCamelCase=32			,     __UpperCamelCase=3			,     __UpperCamelCase=4			,     __UpperCamelCase=[10, 20, 30, 40]			,     __UpperCamelCase=[2, 2, 3, 2]			,     __UpperCamelCase=True			,     __UpperCamelCase=True			,     __UpperCamelCase=37			,     __UpperCamelCase="gelu"			,     __UpperCamelCase=10			,     __UpperCamelCase=0.02			,     __UpperCamelCase=["stage2", "stage3", "stage4"]			,     __UpperCamelCase=3			,     __UpperCamelCase=None			,     )				->				List[Any]:
												UpperCamelCase_		:							List[str]  =		parent
												UpperCamelCase_		:							int  =		batch_size
												UpperCamelCase_		:							str  =		image_size
												UpperCamelCase_		:							str  =		num_channels
												UpperCamelCase_		:							Optional[int]  =		num_stages
												UpperCamelCase_		:							Tuple  =		hidden_sizes
												UpperCamelCase_		:							Dict  =		depths
												UpperCamelCase_		:							Optional[Any]  =		is_training
												UpperCamelCase_		:							Tuple  =		use_labels
												UpperCamelCase_		:							Any  =		intermediate_size
												UpperCamelCase_		:							Union[str, Any]  =		hidden_act
												UpperCamelCase_		:							int  =		type_sequence_label_size
												UpperCamelCase_		:							Any  =		initializer_range
												UpperCamelCase_		:							Tuple  =		out_features
												UpperCamelCase_		:							int  =		num_labels
												UpperCamelCase_		:							Any  =		scope
												UpperCamelCase_		:							List[Any]  =		num_stages





						def        A_							(self						)				->				List[str]:
												UpperCamelCase_		:							Any  =		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

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

												UpperCamelCase_		:							Union[str, Any]  =		self.get_config()

												return config, pixel_values, labels





						def        A_							(self						)				->				int:
												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        A_							(self						)				->				Union[str, Any]:
												return UperNetConfig(
												    backbone_config=self.get_backbone_config()			,     hidden_size=512			,     pool_scales=[1, 2, 3, 6]			,     use_auxiliary_head=__UpperCamelCase			,     auxiliary_loss_weight=0.4			,     auxiliary_in_channels=40			,     auxiliary_channels=256			,     auxiliary_num_convs=1			,     auxiliary_concat_input=__UpperCamelCase			,     loss_ignore_index=255			,     num_labels=self.num_labels			,     )





						def        A_							(self			,     __UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase						)				->				Tuple:
												UpperCamelCase_		:							Dict  =		UperNetForSemanticSegmentation(config=__UpperCamelCase						)
												model.to(__UpperCamelCase						)
												model.eval()
												UpperCamelCase_		:							Union[str, Any]  =		model(__UpperCamelCase						)
												self.parent.assertEqual(
												    result.logits.shape			,     (self.batch_size, self.num_labels, self.image_size, self.image_size)						)





						def        A_							(self						)				->				Union[str, Any]:
												UpperCamelCase_		:							int  =		self.prepare_config_and_inputs()
												(
												    (
												    UpperCamelCase_
												),(
												    UpperCamelCase_
												),(
												    UpperCamelCase_
												),
												)		:							Optional[Any]  =		config_and_inputs
												UpperCamelCase_		:							Optional[int]  =		{"""pixel_values""": pixel_values}
												return config, inputs_dict


@require_torch
class        UpperCamelCase						(				__a	,	__a	,	unittest.TestCase				):
						a__		:Optional[Any]      =			(UperNetForSemanticSegmentation,) if is_torch_available() else ()
						a__		:Optional[Any]      =			{'''image-segmentation''': UperNetForSemanticSegmentation} if is_torch_available() else {}
						a__		:str      =			False
						a__		:Optional[int]      =			False
						a__		:List[str]      =			False
						a__		:Optional[int]      =			False
						a__		:List[str]      =			False
						a__		:List[str]      =			False





						def        A_							(self						)				->				int:
												UpperCamelCase_		:							Tuple  =		UperNetModelTester(self						)
												UpperCamelCase_		:							Any  =		ConfigTester(self			,     config_class=__UpperCamelCase			,     has_text_modality=__UpperCamelCase			,     hidden_size=37						)





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





						def        A_							(self						)				->				Optional[Any]:
												UpperCamelCase_,UpperCamelCase_		:							Optional[int]  =		self.model_tester.prepare_config_and_inputs_for_common()

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

																		UpperCamelCase_		:							Dict  =		["""pixel_values"""]
																		self.assertListEqual(arg_names[:1]			,     __UpperCamelCase						)





						def        A_							(self						)				->				str:
												UpperCamelCase_		:							str  =		self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_semantic_segmentation(*__UpperCamelCase						)





						@unittest.skip(reason="""UperNet does not use inputs_embeds"""						)
						def        A_							(self						)				->				Dict:
												pass





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





						@unittest.skip(reason="""UperNet does not have a base model"""						)
						def        A_							(self						)				->				List[str]:
												pass





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





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





						@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""						)
						def        A_							(self						)				->				int:
												pass





						def        A_							(self						)				->				int:
												def check_hidden_states_output(__UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase						):
																		UpperCamelCase_		:							Union[str, Any]  =		model_class(__UpperCamelCase						)
																		model.to(__UpperCamelCase						)
																		model.eval()

																		with torch.no_grad():
																								UpperCamelCase_		:							List[str]  =		model(**self._prepare_for_class(__UpperCamelCase			,     __UpperCamelCase						)						)

																		UpperCamelCase_		:							List[Any]  =		outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

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

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

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

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

																		check_hidden_states_output(__UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase						)





						def        A_							(self						)				->				List[Any]:
												UpperCamelCase_,UpperCamelCase_		:							Any  =		self.model_tester.prepare_config_and_inputs_for_common()

												UpperCamelCase_		:							Optional[Any]  =		_config_zero_init(__UpperCamelCase						)
												UpperCamelCase_		:							Union[str, Any]  =		_config_zero_init(configs_no_init.backbone_config						)
												for model_class in self.all_model_classes:
																		UpperCamelCase_		:							int  =		model_class(config=__UpperCamelCase						)
																		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        A_							(self						)				->				Tuple:
												pass





						@slow
						def        A_							(self						)				->				int:
												for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																		UpperCamelCase_		:							Optional[int]  =		UperNetForSemanticSegmentation.from_pretrained(__UpperCamelCase						)
																		self.assertIsNotNone(__UpperCamelCase						)






def     lowerCAmelCase_			(   ):
						UpperCamelCase_		:							Optional[int]  =		hf_hub_download(
						    repo_id="""hf-internal-testing/fixtures_ade20k"""		, repo_type="""dataset"""		, filename="""ADE_val_00000001.jpg"""			)
						UpperCamelCase_		:							Any  =		Image.open(_SCREAMING_SNAKE_CASE			).convert("""RGB"""			)
						return image







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





						def        A_							(self						)				->				Tuple:
												UpperCamelCase_		:							str  =		AutoImageProcessor.from_pretrained("""openmmlab/upernet-swin-tiny"""						)
												UpperCamelCase_		:							Optional[Any]  =		UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-swin-tiny"""						).to(__UpperCamelCase						)

												UpperCamelCase_		:							List[str]  =		prepare_img()
												UpperCamelCase_		:							int  =		processor(images=__UpperCamelCase			,     return_tensors="""pt"""						).to(__UpperCamelCase						)

												with torch.no_grad():
																		UpperCamelCase_		:							Dict  =		model(**__UpperCamelCase						)

												UpperCamelCase_		:							Dict  =		torch.Size((1, model.config.num_labels, 512, 512)						)
												self.assertEqual(outputs.logits.shape			,     __UpperCamelCase						)

												UpperCamelCase_		:							Optional[int]  =		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(__UpperCamelCase						)
												self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]			,     __UpperCamelCase			,     atol=1E-4						)						)





						def        A_							(self						)				->				Any:
												UpperCamelCase_		:							Union[str, Any]  =		AutoImageProcessor.from_pretrained("""openmmlab/upernet-convnext-tiny"""						)
												UpperCamelCase_		:							int  =		UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-convnext-tiny"""						).to(__UpperCamelCase						)

												UpperCamelCase_		:							Tuple  =		prepare_img()
												UpperCamelCase_		:							int  =		processor(images=__UpperCamelCase			,     return_tensors="""pt"""						).to(__UpperCamelCase						)

												with torch.no_grad():
																		UpperCamelCase_		:							int  =		model(**__UpperCamelCase						)

												UpperCamelCase_		:							List[Any]  =		torch.Size((1, model.config.num_labels, 512, 512)						)
												self.assertEqual(outputs.logits.shape			,     __UpperCamelCase						)

												UpperCamelCase_		:							int  =		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(__UpperCamelCase						)
												self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]			,     __UpperCamelCase			,     atol=1E-4						)						)







from collections import OrderedDict
from typing import TYPE_CHECKING, Any, List, Mapping, Optional

from packaging import version


if TYPE_CHECKING:
	from ... import PreTrainedTokenizer, TensorType

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import is_torch_available, logging


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

SCREAMING_SNAKE_CASE		:     str         =	{
    "bigscience/bloom": "https://huggingface.co/bigscience/bloom/resolve/main/config.json",
    "bigscience/bloom-560m": "https://huggingface.co/bigscience/bloom-560m/blob/main/config.json",
    "bigscience/bloom-1b1": "https://huggingface.co/bigscience/bloom-1b1/blob/main/config.json",
    "bigscience/bloom-1b7": "https://huggingface.co/bigscience/bloom-1b7/blob/main/config.json",
    "bigscience/bloom-3b": "https://huggingface.co/bigscience/bloom-3b/blob/main/config.json",
    "bigscience/bloom-7b1": "https://huggingface.co/bigscience/bloom-7b1/blob/main/config.json",
}

class        UpperCamelCase						(				__a				):
						a__		:Any      =			'''bloom'''
						a__		:Optional[int]      =			['''past_key_values''']
						a__		:Tuple      =			{
						    '''num_hidden_layers''': '''n_layer''',
						    '''num_attention_heads''': '''n_head''',
						}





						def __init__(self			,     __UpperCamelCase=250_880			,     __UpperCamelCase=64			,     __UpperCamelCase=2			,     __UpperCamelCase=8			,     __UpperCamelCase=1E-5			,     __UpperCamelCase=0.02			,     __UpperCamelCase=True			,     __UpperCamelCase=1			,     __UpperCamelCase=2			,     __UpperCamelCase=False			,     __UpperCamelCase=0.0			,     __UpperCamelCase=0.0			,     __UpperCamelCase=1			,     __UpperCamelCase=False			,     **__UpperCamelCase			,     )				->				List[Any]:
												UpperCamelCase_		:							Dict  =		vocab_size
												# Backward compatibility with n_embed kwarg
												UpperCamelCase_		:							Optional[Any]  =		kwargs.pop("""n_embed"""			,     __UpperCamelCase						)
												UpperCamelCase_		:							List[Any]  =		hidden_size if n_embed is None else n_embed
												UpperCamelCase_		:							List[Any]  =		n_layer
												UpperCamelCase_		:							Optional[Any]  =		n_head
												UpperCamelCase_		:							List[str]  =		layer_norm_epsilon
												UpperCamelCase_		:							int  =		initializer_range
												UpperCamelCase_		:							List[str]  =		use_cache
												UpperCamelCase_		:							List[Any]  =		pretraining_tp
												UpperCamelCase_		:							Optional[int]  =		apply_residual_connection_post_layernorm
												UpperCamelCase_		:							Any  =		hidden_dropout
												UpperCamelCase_		:							Optional[Any]  =		attention_dropout

												UpperCamelCase_		:							List[str]  =		bos_token_id
												UpperCamelCase_		:							Optional[Any]  =		eos_token_id
												UpperCamelCase_		:							str  =		slow_but_exact

												super().__init__(bos_token_id=__UpperCamelCase			,     eos_token_id=__UpperCamelCase			,     **__UpperCamelCase						)


class        UpperCamelCase						(				__a				):
						a__		:Dict      =			version.parse('''1.12'''				)





						def __init__(self			,     __UpperCamelCase			,     __UpperCamelCase = "default"			,     __UpperCamelCase = None			,     __UpperCamelCase = False			,     )				->				List[str]:
												super().__init__(__UpperCamelCase			,     task=__UpperCamelCase			,     patching_specs=__UpperCamelCase			,     use_past=__UpperCamelCase						)
												if not getattr(self._config			,     """pad_token_id"""			,     __UpperCamelCase						):
																		# TODO: how to do that better?
																		UpperCamelCase_		:							Optional[Any]  =		0





						@property
						def        A_							(self						)				->				Mapping[str, Mapping[int, str]]:
												UpperCamelCase_		:							str  =		OrderedDict({"""input_ids""": {0: """batch""", 1: """sequence"""}}						)
												if self.use_past:
																		# BLOOM stores values on dynamic axis 2. For more details see: https://github.com/huggingface/transformers/pull/18344
																		self.fill_with_past_key_values_(__UpperCamelCase			,     direction="""inputs"""			,     inverted_values_shape=__UpperCamelCase						)
																		UpperCamelCase_		:							int  =		{0: """batch""", 1: """past_sequence + sequence"""}
												else:
																		UpperCamelCase_		:							Dict  =		{0: """batch""", 1: """sequence"""}

												return common_inputs





						@property
						def        A_							(self						)				->				int:
												return self._config.n_layer





						@property
						def        A_							(self						)				->				int:
												return self._config.n_head





						@property
						def        A_							(self						)				->				float:
												return 1E-3





						def        A_							(self			,     __UpperCamelCase			,     __UpperCamelCase = -1			,     __UpperCamelCase = -1			,     __UpperCamelCase = False			,     __UpperCamelCase = None			,     )				->				Mapping[str, Any]:
												UpperCamelCase_		:							Union[str, Any]  =		super(__UpperCamelCase			,     self						).generate_dummy_inputs(
												    __UpperCamelCase			,     batch_size=__UpperCamelCase			,     seq_length=__UpperCamelCase			,     is_pair=__UpperCamelCase			,     framework=__UpperCamelCase						)

												# We need to order the input in the way they appears in the forward()
												UpperCamelCase_		:							List[Any]  =		OrderedDict({"""input_ids""": common_inputs["""input_ids"""]}						)

												# Need to add the past_keys
												if self.use_past:
																		if not is_torch_available():
																								raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed."""						)
																		else:
																								import torch

																								UpperCamelCase_,UpperCamelCase_		:							List[str]  =		common_inputs["""input_ids"""].shape
																								# Not using the same length for past_key_values
																								UpperCamelCase_		:							List[str]  =		seqlen + 2
																								UpperCamelCase_		:							Tuple  =		self._config.hidden_size // self.num_attention_heads
																								UpperCamelCase_		:							List[Any]  =		(
																								    batch * self.num_attention_heads,
																								    head_dim,
																								    past_key_values_length,
																								)
																								UpperCamelCase_		:							str  =		(
																								    batch * self.num_attention_heads,
																								    past_key_values_length,
																								    head_dim,
																								)
																								UpperCamelCase_		:							Any  =		[
																								    (torch.zeros(__UpperCamelCase						), torch.zeros(__UpperCamelCase						)) for _ in range(self.num_layers						)
																								]

												UpperCamelCase_		:							int  =		common_inputs["""attention_mask"""]
												if self.use_past:
																		UpperCamelCase_		:							List[str]  =		ordered_inputs["""attention_mask"""].dtype
																		UpperCamelCase_		:							Any  =		torch.cat(
																		    [ordered_inputs["""attention_mask"""], torch.ones(__UpperCamelCase			,     __UpperCamelCase			,     dtype=__UpperCamelCase						)]			,     dim=1						)

												return ordered_inputs





						@property
						def        A_							(self						)				->				int:
												return 13






