





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







		def __init__(		self			,     __lowercase			,     __lowercase=1_3			,     __lowercase=3_2			,     __lowercase=3			,     __lowercase=4			,     __lowercase=[1_0, 2_0, 3_0, 4_0]			,     __lowercase=[2, 2, 3, 2]			,     __lowercase=True			,     __lowercase=True			,     __lowercase=3_7			,     __lowercase="gelu"			,     __lowercase=1_0			,     __lowercase=0.0_2			,     __lowercase=["stage2", "stage3", "stage4"]			,     __lowercase=3			,     __lowercase=None			,     )				->   Dict:
				lowerCamelCase   : Union[str, Any]								=parent
				lowerCamelCase   : Any								=batch_size
				lowerCamelCase   : str								=image_size
				lowerCamelCase   : Dict								=num_channels
				lowerCamelCase   : Tuple								=num_stages
				lowerCamelCase   : Dict								=hidden_sizes
				lowerCamelCase   : Dict								=depths
				lowerCamelCase   : Tuple								=is_training
				lowerCamelCase   : Dict								=use_labels
				lowerCamelCase   : Optional[Any]								=intermediate_size
				lowerCamelCase   : int								=hidden_act
				lowerCamelCase   : str								=type_sequence_label_size
				lowerCamelCase   : Tuple								=initializer_range
				lowerCamelCase   : int								=out_features
				lowerCamelCase   : Optional[int]								=num_labels
				lowerCamelCase   : Any								=scope
				lowerCamelCase   : Tuple								=num_stages







		def 			__lowercase   (		self   )				->   Dict:
				lowerCamelCase   : List[Any]								=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

				lowerCamelCase   : Dict								=None
				if self.use_labels:
						lowerCamelCase   : Dict								=ids_tensor([self.batch_size]			,     self.type_sequence_label_size   )

				lowerCamelCase   : int								=self.get_config()

				return config, pixel_values, labels







		def 			__lowercase   (		self   )				->   Union[str, Any]:
				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 			__lowercase   (		self   )				->   Tuple:
				return UperNetConfig(
				    backbone_config=self.get_backbone_config()			,     hidden_size=5_1_2			,     pool_scales=[1, 2, 3, 6]			,     use_auxiliary_head=__lowercase			,     auxiliary_loss_weight=0.4			,     auxiliary_in_channels=4_0			,     auxiliary_channels=2_5_6			,     auxiliary_num_convs=1			,     auxiliary_concat_input=__lowercase			,     loss_ignore_index=2_5_5			,     num_labels=self.num_labels			,     )







		def 			__lowercase   (		self			,     __lowercase			,     __lowercase			,     __lowercase   )				->   Optional[int]:
				lowerCamelCase   : str								=UperNetForSemanticSegmentation(config=__lowercase   )
				model.to(__lowercase   )
				model.eval()
				lowerCamelCase   : int								=model(__lowercase   )
				self.parent.assertEqual(
				    result.logits.shape			,     (self.batch_size, self.num_labels, self.image_size, self.image_size)   )







		def 			__lowercase   (		self   )				->   str:
				lowerCamelCase   : str								=self.prepare_config_and_inputs()
				(
				    lowerCamelCase   
				)   : Tuple								=config_and_inputs
				lowerCamelCase   : List[str]								={'''pixel_values''': pixel_values}
				return config, inputs_dict

@require_torch
class        snake_case_		(			_A						,					_A						,					unittest.TestCase):
		lowerCamelCase    :Optional[int]						=     (UperNetForSemanticSegmentation,) if is_torch_available() else ()
		lowerCamelCase    :Dict						=     {"image-segmentation": UperNetForSemanticSegmentation} if is_torch_available() else {}
		lowerCamelCase    :Dict						=     False
		lowerCamelCase    :str						=     False
		lowerCamelCase    :Tuple						=     False
		lowerCamelCase    :str						=     False
		lowerCamelCase    :Dict						=     False
		lowerCamelCase    :List[Any]						=     False







		def 			__lowercase   (		self   )				->   Any:
				lowerCamelCase   : Any								=UperNetModelTester(self   )
				lowerCamelCase   : Optional[Any]								=ConfigTester(self			,     config_class=__lowercase			,     has_text_modality=__lowercase			,     hidden_size=3_7   )







		def 			__lowercase   (		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 			__lowercase   (		self   )				->   str:
				return







		def 			__lowercase   (		self   )				->   Any:
				lowerCamelCase   : List[str]								=self.model_tester.prepare_config_and_inputs_for_common()

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

						lowerCamelCase   : Any								=['''pixel_values''']
						self.assertListEqual(arg_names[:1]			,     __lowercase   )







		def 			__lowercase   (		self   )				->   Dict:
				lowerCamelCase   : Any								=self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_semantic_segmentation(*__lowercase   )







		@unittest.skip(reason='''UperNet does not use inputs_embeds'''   )
		def 			__lowercase   (		self   )				->   int:
				pass







		@unittest.skip(reason='''UperNet does not support input and output embeddings'''   )
		def 			__lowercase   (		self   )				->   Tuple:
				pass







		@unittest.skip(reason='''UperNet does not have a base model'''   )
		def 			__lowercase   (		self   )				->   Tuple:
				pass







		@unittest.skip(reason='''UperNet does not have a base model'''   )
		def 			__lowercase   (		self   )				->   Optional[Any]:
				pass







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







		@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''   )
		def 			__lowercase   (		self   )				->   Optional[int]:
				pass







		def 			__lowercase   (		self   )				->   Any:
				def check_hidden_states_output(__lowercase			,     __lowercase			,     __lowercase   ):
						lowerCamelCase   : Optional[Any]								=model_class(__lowercase   )
						model.to(__lowercase   )
						model.eval()

						with torch.no_grad():
								lowerCamelCase   : Optional[Any]								=model(**self._prepare_for_class(__lowercase			,     __lowercase   )   )

						lowerCamelCase   : Union[str, Any]								=outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

						lowerCamelCase   : Union[str, Any]								=self.model_tester.num_stages
						self.assertEqual(len(__lowercase   )			,     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]			,     )

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

				for model_class in self.all_model_classes:
						lowerCamelCase   : List[str]								=True
						check_hidden_states_output(__lowercase			,     __lowercase			,     __lowercase   )

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

						check_hidden_states_output(__lowercase			,     __lowercase			,     __lowercase   )







		def 			__lowercase   (		self   )				->   List[Any]:
				lowerCamelCase   : Union[str, Any]								=self.model_tester.prepare_config_and_inputs_for_common()

				lowerCamelCase   : Any								=_config_zero_init(__lowercase   )
				lowerCamelCase   : List[Any]								=_config_zero_init(configs_no_init.backbone_config   )
				for model_class in self.all_model_classes:
						lowerCamelCase   : Union[str, Any]								=model_class(config=__lowercase   )
						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 			__lowercase   (		self   )				->   Union[str, Any]:
				pass







		@slow
		def 			__lowercase   (		self   )				->   Dict:
				for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
						lowerCamelCase   : Tuple								=UperNetForSemanticSegmentation.from_pretrained(__lowercase   )
						self.assertIsNotNone(__lowercase   )


def 					A__	(       )   ->     Optional[Any]:
		lowerCamelCase   : Optional[Any]								=hf_hub_download(
		    repo_id='''hf-internal-testing/fixtures_ade20k'''							,       repo_type='''dataset'''							,       filename='''ADE_val_00000001.jpg'''		)
		lowerCamelCase   : Union[str, Any]								=Image.open(SCREAMING_SNAKE_CASE_		).convert('''RGB'''		)
		return image



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







		def 			__lowercase   (		self   )				->   Union[str, Any]:
				lowerCamelCase   : int								=AutoImageProcessor.from_pretrained('''openmmlab/upernet-swin-tiny'''   )
				lowerCamelCase   : List[str]								=UperNetForSemanticSegmentation.from_pretrained('''openmmlab/upernet-swin-tiny'''   ).to(__lowercase   )

				lowerCamelCase   : Union[str, Any]								=prepare_img()
				lowerCamelCase   : List[Any]								=processor(images=__lowercase			,     return_tensors='''pt'''   ).to(__lowercase   )

				with torch.no_grad():
						lowerCamelCase   : List[Any]								=model(**__lowercase   )

				lowerCamelCase   : Union[str, Any]								=torch.Size((1, model.config.num_labels, 5_1_2, 5_1_2)   )
				self.assertEqual(outputs.logits.shape			,     __lowercase   )

				lowerCamelCase   : int								=torch.tensor(
				    [[-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.4_7_9_7, -7.4_7_9_7, -7.3_0_6_8]]   ).to(__lowercase   )
				self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]			,     __lowercase			,     atol=1e-4   )   )







		def 			__lowercase   (		self   )				->   str:
				lowerCamelCase   : Tuple								=AutoImageProcessor.from_pretrained('''openmmlab/upernet-convnext-tiny'''   )
				lowerCamelCase   : Tuple								=UperNetForSemanticSegmentation.from_pretrained('''openmmlab/upernet-convnext-tiny'''   ).to(__lowercase   )

				lowerCamelCase   : str								=prepare_img()
				lowerCamelCase   : List[Any]								=processor(images=__lowercase			,     return_tensors='''pt'''   ).to(__lowercase   )

				with torch.no_grad():
						lowerCamelCase   : List[Any]								=model(**__lowercase   )

				lowerCamelCase   : List[Any]								=torch.Size((1, model.config.num_labels, 5_1_2, 5_1_2)   )
				self.assertEqual(outputs.logits.shape			,     __lowercase   )

				lowerCamelCase   : Dict								=torch.tensor(
				    [[-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.7_7_4_6, -8.7_7_4_6, -8.6_1_3_0]]   ).to(__lowercase   )
				self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]			,     __lowercase			,     atol=1e-4   )   )








import numpy as np
from sklearn.datasets import fetch_california_housing
from sklearn.metrics import mean_absolute_error, mean_squared_error
from sklearn.model_selection import train_test_split
from xgboost import XGBRegressor


def 					A__	(       SCREAMING_SNAKE_CASE_		)   ->     tuple:
		return (data["data"], data["target"])


def 					A__	(       SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_		)   ->     np.ndarray:
		lowerCamelCase   : Dict								=XGBRegressor(verbosity=0							,       random_state=4_2		)
		xgb.fit(SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_		)
		# Predict target for test data
		lowerCamelCase   : List[str]								=xgb.predict(SCREAMING_SNAKE_CASE_		)
		lowerCamelCase   : List[Any]								=predictions.reshape(len(SCREAMING_SNAKE_CASE_		)							,       1		)
		return predictions


def 					A__	(       )   ->     None:
		lowerCamelCase   : Union[str, Any]								=fetch_california_housing()
		lowerCamelCase		,   lowerCamelCase   : Optional[Any]								=data_handling(SCREAMING_SNAKE_CASE_		)
		lowerCamelCase		,   lowerCamelCase		,   lowerCamelCase		,   lowerCamelCase   : str								=train_test_split(
		    SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_							,       test_size=0.2_5							,       random_state=1		)
		lowerCamelCase   : str								=xgboost(SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_		)
		# Error printing
		print(F"Mean Absolute Error : {mean_absolute_error(SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_		)}"		)
		print(F"Mean Square Error  : {mean_squared_error(SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_		)}"		)


if __name__ == "__main__":
				import doctest

				doctest.testmod(verbose=True)
				main()

