
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 		lowercase__    :
	def __init__(     self				:  Optional[int]			,  UpperCAmelCase_				:  Dict			,  UpperCAmelCase_				:  Any=13			,  UpperCAmelCase_				:  List[str]=32			,  UpperCAmelCase_				:  List[Any]=3			,  UpperCAmelCase_				:  List[str]=4			,  UpperCAmelCase_				:  str=[10, 20, 30, 40]			,  UpperCAmelCase_				:  Dict=[2, 2, 3, 2]			,  UpperCAmelCase_				:  Tuple=True			,  UpperCAmelCase_				:  Optional[Any]=True			,  UpperCAmelCase_				:  Optional[int]=37			,  UpperCAmelCase_				:  Tuple="gelu"			,  UpperCAmelCase_				:  Any=10			,  UpperCAmelCase_				:  Optional[Any]=0.02			,  UpperCAmelCase_				:  Any=["stage2", "stage3", "stage4"]			,  UpperCAmelCase_				:  List[Any]=3			,  UpperCAmelCase_				:  Dict=None			,  ):
						SCREAMING_SNAKE_CASE__						=					parent
						SCREAMING_SNAKE_CASE__						=					batch_size
						SCREAMING_SNAKE_CASE__						=					image_size
						SCREAMING_SNAKE_CASE__						=					num_channels
						SCREAMING_SNAKE_CASE__						=					num_stages
						SCREAMING_SNAKE_CASE__						=					hidden_sizes
						SCREAMING_SNAKE_CASE__						=					depths
						SCREAMING_SNAKE_CASE__						=					is_training
						SCREAMING_SNAKE_CASE__						=					use_labels
						SCREAMING_SNAKE_CASE__						=					intermediate_size
						SCREAMING_SNAKE_CASE__						=					hidden_act
						SCREAMING_SNAKE_CASE__						=					type_sequence_label_size
						SCREAMING_SNAKE_CASE__						=					initializer_range
						SCREAMING_SNAKE_CASE__						=					out_features
						SCREAMING_SNAKE_CASE__						=					num_labels
						SCREAMING_SNAKE_CASE__						=					scope
						SCREAMING_SNAKE_CASE__						=					num_stages
	def 	A_							(     self				:  Any				):
						SCREAMING_SNAKE_CASE__						=					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

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

						SCREAMING_SNAKE_CASE__						=					self.get_config()

						return config, pixel_values, labels
	def 	A_							(     self				:  List[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 	A_							(     self				:  Optional[int]				):
						return UperNetConfig(
						    backbone_config=self.get_backbone_config()			,  hidden_size=512			,  pool_scales=[1, 2, 3, 6]			,  use_auxiliary_head=a__			,  auxiliary_loss_weight=0.4			,  auxiliary_in_channels=40			,  auxiliary_channels=256			,  auxiliary_num_convs=1			,  auxiliary_concat_input=a__			,  loss_ignore_index=255			,  num_labels=self.num_labels			,  )
	def 	A_							(     self				:  Optional[Any]			,  UpperCAmelCase_				:  List[Any]			,  UpperCAmelCase_				:  List[Any]			,  UpperCAmelCase_				:  int				):
						SCREAMING_SNAKE_CASE__						=					UperNetForSemanticSegmentation(config=a__				)
						model.to(a__				)
						model.eval()
						SCREAMING_SNAKE_CASE__						=					model(a__				)
						self.parent.assertEqual(
						    result.logits.shape			,  (self.batch_size, self.num_labels, self.image_size, self.image_size)				)





	def 	A_							(     self				:  Optional[Any]				):
						SCREAMING_SNAKE_CASE__						=					self.prepare_config_and_inputs()
						(
						    SCREAMING_SNAKE_CASE__     
						)						=					config_and_inputs
						SCREAMING_SNAKE_CASE__						=					{"pixel_values": pixel_values}
						return config, inputs_dict





@require_torch
class 		lowercase__    (		UpperCamelCase_	,			UpperCamelCase_	,			unittest.TestCase    ):
	A__       :  int										=(UperNetForSemanticSegmentation,) if is_torch_available() else ()
	A__       :  Dict										={"""image-segmentation""": UperNetForSemanticSegmentation} if is_torch_available() else {}
	A__       :  Optional[int]										=False
	A__       :  List[str]										=False
	A__       :  List[str]										=False
	A__       :  List[Any]										=False
	A__       :  Optional[Any]										=False
	A__       :  Optional[Any]										=False
	def 	A_							(     self				:  List[str]				):
						SCREAMING_SNAKE_CASE__						=					UperNetModelTester(self				)
						SCREAMING_SNAKE_CASE__						=					ConfigTester(self			,  config_class=a__			,  has_text_modality=a__			,  hidden_size=37				)
	def 	A_							(     self				:  Dict				):
						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[int]				):
						SCREAMING_SNAKE_CASE__						=					self.model_tester.prepare_config_and_inputs_for_common()

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

											SCREAMING_SNAKE_CASE__						=					["pixel_values"]
											self.assertListEqual(arg_names[:1]			,  a__				)
	def 	A_							(     self				:  Union[str, Any]				):
						SCREAMING_SNAKE_CASE__						=					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 	A_							(     self				:  Any				):
						pass
	@unittest.skip(reason='UperNet does not support input and output embeddings'				)
	def 	A_							(     self				:  int				):
						pass
	@unittest.skip(reason='UperNet does not have a base model'				)
	def 	A_							(     self				:  Optional[Any]				):
						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				:  int				):
						pass
	@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'				)
	def 	A_							(     self				:  Tuple				):
						pass
	def 	A_							(     self				:  Tuple				):

						def check_hidden_states_output(UpperCAmelCase_				:  int			,  UpperCAmelCase_				:  str			,  UpperCAmelCase_				:  List[str]				):
											SCREAMING_SNAKE_CASE__						=					model_class(a__				)
											model.to(a__				)
											model.eval()

											with torch.no_grad():
																SCREAMING_SNAKE_CASE__						=					model(**self._prepare_for_class(a__			,  a__				)				)

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

											SCREAMING_SNAKE_CASE__						=					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__						=					self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
											SCREAMING_SNAKE_CASE__						=					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__						=					True

											check_hidden_states_output(a__			,  a__			,  a__				)
	def 	A_							(     self				:  List[Any]				):
						SCREAMING_SNAKE_CASE__						=					self.model_tester.prepare_config_and_inputs_for_common()

						SCREAMING_SNAKE_CASE__						=					_config_zero_init(a__				)
						SCREAMING_SNAKE_CASE__						=					_config_zero_init(configs_no_init.backbone_config				)
						for model_class in self.all_model_classes:
											SCREAMING_SNAKE_CASE__						=					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 	A_							(     self				:  Any				):
						pass





	@slow
	def 	A_							(     self				:  Any				):

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






def 				_lowercase				(	)						->						Optional[Any]:
					'''simple docstring'''


					SCREAMING_SNAKE_CASE__						=					hf_hub_download(
					    repo_id='hf-internal-testing/fixtures_ade20k'      ,      repo_type='dataset'      ,      filename='ADE_val_00000001.jpg'						)
					SCREAMING_SNAKE_CASE__						=					Image.open(lowerCamelCase_						).convert('RGB'						)
					return image




@require_torch
@require_vision
@slow
class 		lowercase__    (		unittest.TestCase    ):
	def 	A_							(     self				:  Dict				):
						SCREAMING_SNAKE_CASE__						=					AutoImageProcessor.from_pretrained('openmmlab/upernet-swin-tiny'				)
						SCREAMING_SNAKE_CASE__						=					UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-swin-tiny'				).to(a__				)

						SCREAMING_SNAKE_CASE__						=					prepare_img()
						SCREAMING_SNAKE_CASE__						=					processor(images=a__			,  return_tensors='pt'				).to(a__				)

						with torch.no_grad():
											SCREAMING_SNAKE_CASE__						=					model(**a__				)

						SCREAMING_SNAKE_CASE__						=					torch.Size((1, model.config.num_labels, 512, 512)				)
						self.assertEqual(outputs.logits.shape			,  a__				)

						SCREAMING_SNAKE_CASE__						=					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 	A_							(     self				:  Optional[int]				):
						SCREAMING_SNAKE_CASE__						=					AutoImageProcessor.from_pretrained('openmmlab/upernet-convnext-tiny'				)
						SCREAMING_SNAKE_CASE__						=					UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-convnext-tiny'				).to(a__				)

						SCREAMING_SNAKE_CASE__						=					prepare_img()
						SCREAMING_SNAKE_CASE__						=					processor(images=a__			,  return_tensors='pt'				).to(a__				)

						with torch.no_grad():
											SCREAMING_SNAKE_CASE__						=					model(**a__				)

						SCREAMING_SNAKE_CASE__						=					torch.Size((1, model.config.num_labels, 512, 512)				)
						self.assertEqual(outputs.logits.shape			,  a__				)

						SCREAMING_SNAKE_CASE__						=					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'''

def        UpperCAmelCase_ (  lowerCamelCase_      ,			lowerCamelCase_      ,			lowerCamelCase_      ,			lowerCamelCase_			):







 """simple docstring"""


 if height >= 1:
  move_tower(height - 1      ,			lowerCamelCase_      ,			lowerCamelCase_      ,			lowerCamelCase_			)
  move_disk(lowerCamelCase_      ,			lowerCamelCase_			)
  move_tower(height - 1      ,			lowerCamelCase_      ,			lowerCamelCase_      ,			lowerCamelCase_			)


def        UpperCAmelCase_ (  lowerCamelCase_      ,			lowerCamelCase_			):







 """simple docstring"""


 print("moving disk from"      ,			lowerCamelCase_      ,			"to"      ,			lowerCamelCase_			)


def        UpperCAmelCase_ (  ):







 """simple docstring"""


 lowerCAmelCase__     :   List[str]     		=	int(input("Height of hanoi: "			).strip()			)
 move_tower(lowerCamelCase_      ,			"A"      ,			"B"      ,			"C"			)


if __name__ == "__main__":
     main()





