



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






		def __init__(    self   :  Optional[int]					,		UpperCamelCase__   :  Union[str, Any]					,		UpperCamelCase__   :  str=13					,		UpperCamelCase__   :  Optional[int]=32					,		UpperCamelCase__   :  Tuple=3					,		UpperCamelCase__   :  Optional[Any]=4					,		UpperCamelCase__   :  str=[10, 20, 30, 40]					,		UpperCamelCase__   :  str=[2, 2, 3, 2]					,		UpperCamelCase__   :  Union[str, Any]=True					,		UpperCamelCase__   :  List[Any]=True					,		UpperCamelCase__   :  Dict=37					,		UpperCamelCase__   :  str="gelu"					,		UpperCamelCase__   :  List[str]=10					,		UpperCamelCase__   :  int=0.02					,		UpperCamelCase__   :  List[str]=["stage2", "stage3", "stage4"]					,		UpperCamelCase__   :  List[Any]=3					,		UpperCamelCase__   :  Dict=None					,		)					->       Optional[Any]:
								'''simple docstring'''







								UpperCAmelCase								=  parent
								UpperCAmelCase								=  batch_size
								UpperCAmelCase								=  image_size
								UpperCAmelCase								=  num_channels
								UpperCAmelCase								=  num_stages
								UpperCAmelCase								=  hidden_sizes
								UpperCAmelCase								=  depths
								UpperCAmelCase								=  is_training
								UpperCAmelCase								=  use_labels
								UpperCAmelCase								=  intermediate_size
								UpperCAmelCase								=  hidden_act
								UpperCAmelCase								=  type_sequence_label_size
								UpperCAmelCase								=  initializer_range
								UpperCAmelCase								=  out_features
								UpperCAmelCase								=  num_labels
								UpperCAmelCase								=  scope
								UpperCAmelCase								=  num_stages






		def SCREAMING_SNAKE_CASE_      (    self   :  Tuple   )					->       List[str]:
								'''simple docstring'''







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

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

								UpperCAmelCase								=  self.get_config()

								return config, pixel_values, labels






		def SCREAMING_SNAKE_CASE_      (    self   :  int   )					->       Any:
								'''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 SCREAMING_SNAKE_CASE_      (    self   :  Optional[Any]   )					->       Optional[int]:
								'''simple docstring'''







								return UperNetConfig(
								    backbone_config=self.get_backbone_config()					,		hidden_size=5_12					,		pool_scales=[1, 2, 3, 6]					,		use_auxiliary_head=__a					,		auxiliary_loss_weight=0.4					,		auxiliary_in_channels=40					,		auxiliary_channels=2_56					,		auxiliary_num_convs=1					,		auxiliary_concat_input=__a					,		loss_ignore_index=2_55					,		num_labels=self.num_labels					,		)






		def SCREAMING_SNAKE_CASE_      (    self   :  Optional[int]					,		UpperCamelCase__   :  str					,		UpperCamelCase__   :  Tuple					,		UpperCamelCase__   :  Optional[int]   )					->       Optional[Any]:
								'''simple docstring'''







								UpperCAmelCase								=  UperNetForSemanticSegmentation(config=__a   )
								model.to(__a   )
								model.eval()
								UpperCAmelCase								=  model(__a   )
								self.parent.assertEqual(
								    result.logits.shape					,		(self.batch_size, self.num_labels, self.image_size, self.image_size)   )







		def SCREAMING_SNAKE_CASE_      (    self   :  str   )					->       Dict:
								'''simple docstring'''







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





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






		def SCREAMING_SNAKE_CASE_      (    self   :  Optional[Any]   )					->       Union[str, Any]:
								'''simple docstring'''







								UpperCAmelCase								=  UperNetModelTester(self   )
								UpperCAmelCase								=  ConfigTester(self					,		config_class=__a					,		has_text_modality=__a					,		hidden_size=37   )






		def SCREAMING_SNAKE_CASE_      (    self   :  List[Any]   )					->       Dict:
								'''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 SCREAMING_SNAKE_CASE_      (    self   :  Tuple   )					->       List[Any]:
								'''simple docstring'''







								return






		def SCREAMING_SNAKE_CASE_      (    self   :  Tuple   )					->       str:
								'''simple docstring'''







								UpperCAmelCase							,		UpperCAmelCase								=  self.model_tester.prepare_config_and_inputs_for_common()

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

														UpperCAmelCase								=  ["pixel_values"]
														self.assertListEqual(arg_names[:1]					,		__a   )






		def SCREAMING_SNAKE_CASE_      (    self   :  Any   )					->       Optional[int]:
								'''simple docstring'''







								UpperCAmelCase								=  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 SCREAMING_SNAKE_CASE_      (    self   :  int   )					->       Any:
								'''simple docstring'''







								pass






		@unittest.skip(reason="UperNet does not support input and output embeddings"   )
		def SCREAMING_SNAKE_CASE_      (    self   :  str   )					->       List[Any]:
								'''simple docstring'''







								pass






		@unittest.skip(reason="UperNet does not have a base model"   )
		def SCREAMING_SNAKE_CASE_      (    self   :  Union[str, Any]   )					->       Tuple:
								'''simple docstring'''







								pass






		@unittest.skip(reason="UperNet does not have a base model"   )
		def SCREAMING_SNAKE_CASE_      (    self   :  Union[str, Any]   )					->       int:
								'''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 SCREAMING_SNAKE_CASE_      (    self   :  Optional[Any]   )					->       Union[str, Any]:
								'''simple docstring'''







								pass






		@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."   )
		def SCREAMING_SNAKE_CASE_      (    self   :  int   )					->       Any:
								'''simple docstring'''







								pass






		def SCREAMING_SNAKE_CASE_      (    self   :  int   )					->       List[Any]:
								'''simple docstring'''







								def check_hidden_states_output(UpperCamelCase__   :  Optional[Any]					,		UpperCamelCase__   :  str					,		UpperCamelCase__   :  List[str]   ):
														UpperCAmelCase								=  model_class(__a   )
														model.to(__a   )
														model.eval()

														with torch.no_grad():
																				UpperCAmelCase								=  model(**self._prepare_for_class(__a					,		__a   )   )

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

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

								UpperCAmelCase							,		UpperCAmelCase								=  self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
														UpperCAmelCase								=  True
														check_hidden_states_output(__a					,		__a					,		__a   )

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

														check_hidden_states_output(__a					,		__a					,		__a   )






		def SCREAMING_SNAKE_CASE_      (    self   :  Optional[int]   )					->       Optional[Any]:
								'''simple docstring'''







								UpperCAmelCase							,		UpperCAmelCase								=  self.model_tester.prepare_config_and_inputs_for_common()

								UpperCAmelCase								=  _config_zero_init(__a   )
								UpperCAmelCase								=  _config_zero_init(configs_no_init.backbone_config   )
								for model_class in self.all_model_classes:
														UpperCAmelCase								=  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 SCREAMING_SNAKE_CASE_      (    self   :  Optional[int]   )					->       Optional[int]:
								'''simple docstring'''







								pass







		@slow
		def SCREAMING_SNAKE_CASE_      (    self   :  List[str]   )					->       Optional[Any]:
								'''simple docstring'''







								for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
														UpperCAmelCase								=  UperNetForSemanticSegmentation.from_pretrained(__a   )
														self.assertIsNotNone(__a   )

def  lowerCamelCase_()			->							int:
						UpperCAmelCase								=  hf_hub_download(
						    repo_id="hf-internal-testing/fixtures_ade20k"     , repo_type="dataset"     , filename="ADE_val_00000001.jpg"     )
						UpperCAmelCase								=  Image.open(__snake_case     ).convert("RGB"     )
						return image





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






		def SCREAMING_SNAKE_CASE_      (    self   :  List[Any]   )					->       Optional[int]:
								'''simple docstring'''







								UpperCAmelCase								=  AutoImageProcessor.from_pretrained("openmmlab/upernet-swin-tiny"   )
								UpperCAmelCase								=  UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-swin-tiny"   ).to(__a   )

								UpperCAmelCase								=  prepare_img()
								UpperCAmelCase								=  processor(images=__a					,		return_tensors="pt"   ).to(__a   )

								with torch.no_grad():
														UpperCAmelCase								=  model(**__a   )

								UpperCAmelCase								=  torch.Size((1, model.config.num_labels, 5_12, 5_12)   )
								self.assertEqual(outputs.logits.shape					,		__a   )

								UpperCAmelCase								=  torch.tensor(
								    [[-7.59_58, -7.59_58, -7.43_02], [-7.59_58, -7.59_58, -7.43_02], [-7.47_97, -7.47_97, -7.30_68]]   ).to(__a   )
								self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]					,		__a					,		atol=1e-4   )   )







		def SCREAMING_SNAKE_CASE_      (    self   :  List[Any]   )					->       List[Any]:
								'''simple docstring'''







								UpperCAmelCase								=  AutoImageProcessor.from_pretrained("openmmlab/upernet-convnext-tiny"   )
								UpperCAmelCase								=  UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-convnext-tiny"   ).to(__a   )

								UpperCAmelCase								=  prepare_img()
								UpperCAmelCase								=  processor(images=__a					,		return_tensors="pt"   ).to(__a   )

								with torch.no_grad():
														UpperCAmelCase								=  model(**__a   )

								UpperCAmelCase								=  torch.Size((1, model.config.num_labels, 5_12, 5_12)   )
								self.assertEqual(outputs.logits.shape					,		__a   )

								UpperCAmelCase								=  torch.tensor(
								    [[-8.81_10, -8.81_10, -8.65_21], [-8.81_10, -8.81_10, -8.65_21], [-8.77_46, -8.77_46, -8.61_30]]   ).to(__a   )
								self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]					,		__a					,		atol=1e-4   )   )





"""simple docstring"""





from collections.abc import Callable

import numpy as np



def  lowerCamelCase__						(     __snake_case,	__snake_case,	__snake_case,	__snake_case,	__snake_case      )				->						np.array:


					"""simple docstring"""





					_UpperCamelCase									=    int(np.ceil((x_end - xa) / step_size      )      )
					_UpperCamelCase									=    np.zeros((n + 1,)      )
					_UpperCamelCase									=    ya
					_UpperCamelCase									=    xa

					for k in range(__snake_case      ):
										_UpperCamelCase									=    y[k] + step_size * ode_func(__snake_case,	y[k]      )
										_UpperCamelCase									=    y[k] + (
										    (step_size / 2) * (ode_func(__snake_case,	y[k]      ) + ode_func(x + step_size,	__snake_case      ))
										)
										x += step_size

					return y


if __name__ == "__main__":
				import doctest

				doctest.testmod()






