






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      :							Optional[int]       ,				_lowerCAmelCase      :							List[Any]       ,				_lowerCAmelCase      :							Any=13       ,				_lowerCAmelCase      :							List[Any]=32       ,				_lowerCAmelCase      :							Optional[Any]=3       ,				_lowerCAmelCase      :							int=4       ,				_lowerCAmelCase      :							List[str]=[10, 20, 30, 40]       ,				_lowerCAmelCase      :							Tuple=[2, 2, 3, 2]       ,				_lowerCAmelCase      :							Tuple=True       ,				_lowerCAmelCase      :							Optional[Any]=True       ,				_lowerCAmelCase      :							Optional[int]=37       ,				_lowerCAmelCase      :							Dict="gelu"       ,				_lowerCAmelCase      :							Any=10       ,				_lowerCAmelCase      :							Optional[Any]=0.02       ,				_lowerCAmelCase      :							Optional[int]=["stage2", "stage3", "stage4"]       ,				_lowerCAmelCase      :							List[str]=3       ,				_lowerCAmelCase      :							Optional[Any]=None       ,				)		-> List[str]:
		"""simple docstring"""







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







	def  _a   (  self      :							str			)		-> Optional[Any]:
		"""simple docstring"""







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

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

		__lowercase             =  self.get_config()

		return config, pixel_values, labels







	def  _a   (  self      :							Any			)		-> int:
		"""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  _a   (  self      :							Dict			)		-> str:
		"""simple docstring"""







		return UperNetConfig(
		    backbone_config=self.get_backbone_config()       ,				hidden_size=512       ,				pool_scales=[1, 2, 3, 6]       ,				use_auxiliary_head=_lowerCAmelCase       ,				auxiliary_loss_weight=0.4       ,				auxiliary_in_channels=40       ,				auxiliary_channels=256       ,				auxiliary_num_convs=1       ,				auxiliary_concat_input=_lowerCAmelCase       ,				loss_ignore_index=255       ,				num_labels=self.num_labels       ,				)







	def  _a   (  self      :							List[str]       ,				_lowerCAmelCase      :							Any       ,				_lowerCAmelCase      :							Tuple       ,				_lowerCAmelCase      :							List[Any]			)		-> List[Any]:
		"""simple docstring"""







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







	def  _a   (  self      :							int			)		-> Any:
		"""simple docstring"""







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


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







	def  _a   (  self      :							List[Any]			)		-> str:
		"""simple docstring"""







		__lowercase             =  UperNetModelTester(self			)
		__lowercase             =  ConfigTester(self       ,				config_class=_lowerCAmelCase       ,				has_text_modality=_lowerCAmelCase       ,				hidden_size=37			)







	def  _a   (  self      :							Union[str, Any]			)		-> Optional[Any]:
		"""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  _a   (  self      :							Any			)		-> Optional[Any]:
		"""simple docstring"""







		return







	def  _a   (  self      :							List[Any]			)		-> List[Any]:
		"""simple docstring"""







		__lowercase       ,						__lowercase             =  self.model_tester.prepare_config_and_inputs_for_common()

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

			__lowercase             =  ["""pixel_values"""]
			self.assertListEqual(arg_names[:1]       ,				_lowerCAmelCase			)







	def  _a   (  self      :							List[Any]			)		-> Optional[Any]:
		"""simple docstring"""







		__lowercase             =  self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_for_semantic_segmentation(*_lowerCAmelCase			)







	@unittest.skip(reason="""UperNet does not use inputs_embeds"""			)
	def  _a   (  self      :							Union[str, Any]			)		-> Union[str, Any]:
		"""simple docstring"""







		pass







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







		pass







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







		pass







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







		pass







	@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""			)
	def  _a   (  self      :							Union[str, Any]			)		-> List[str]:
		"""simple docstring"""







		pass







	def  _a   (  self      :							Dict			)		-> int:
		"""simple docstring"""







		def check_hidden_states_output(_lowerCAmelCase      :							List[Any]       ,				_lowerCAmelCase      :							List[str]       ,				_lowerCAmelCase      :							Dict			):
			__lowercase             =  model_class(_lowerCAmelCase			)
			model.to(_lowerCAmelCase			)
			model.eval()

			with torch.no_grad():
				__lowercase             =  model(**self._prepare_for_class(_lowerCAmelCase       ,				_lowerCAmelCase			)			)

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

			__lowercase             =  self.model_tester.num_stages
			self.assertEqual(len(_lowerCAmelCase			)       ,				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]       ,				)

		__lowercase       ,						__lowercase             =  self.model_tester.prepare_config_and_inputs_for_common()

		for model_class in self.all_model_classes:
			__lowercase             =  True
			check_hidden_states_output(_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase			)

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

			check_hidden_states_output(_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase			)







	def  _a   (  self      :							List[str]			)		-> List[Any]:
		"""simple docstring"""







		__lowercase       ,						__lowercase             =  self.model_tester.prepare_config_and_inputs_for_common()

		__lowercase             =  _config_zero_init(_lowerCAmelCase			)
		__lowercase             =  _config_zero_init(configs_no_init.backbone_config			)
		for model_class in self.all_model_classes:
			__lowercase             =  model_class(config=_lowerCAmelCase			)
			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			)		-> List[Any]:
		"""simple docstring"""







		pass







	@slow
	def  _a   (  self      :							Any			)		-> Tuple:
		"""simple docstring"""







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





def 				snake_case  (     ):




	'''simple docstring'''







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




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







	def  _a   (  self      :							Union[str, Any]			)		-> List[str]:
		"""simple docstring"""







		__lowercase             =  AutoImageProcessor.from_pretrained("""openmmlab/upernet-swin-tiny"""			)
		__lowercase             =  UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-swin-tiny"""			).to(_lowerCAmelCase			)

		__lowercase             =  prepare_img()
		__lowercase             =  processor(images=_lowerCAmelCase       ,				return_tensors="""pt"""			).to(_lowerCAmelCase			)

		with torch.no_grad():
			__lowercase             =  model(**_lowerCAmelCase			)

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

		__lowercase             =  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(_lowerCAmelCase			)
		self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]       ,				_lowerCAmelCase       ,				atol=1e-4			)			)







	def  _a   (  self      :							List[str]			)		-> int:
		"""simple docstring"""







		__lowercase             =  AutoImageProcessor.from_pretrained("""openmmlab/upernet-convnext-tiny"""			)
		__lowercase             =  UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-convnext-tiny"""			).to(_lowerCAmelCase			)

		__lowercase             =  prepare_img()
		__lowercase             =  processor(images=_lowerCAmelCase       ,				return_tensors="""pt"""			).to(_lowerCAmelCase			)

		with torch.no_grad():
			__lowercase             =  model(**_lowerCAmelCase			)

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

		__lowercase             =  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(_lowerCAmelCase			)
		self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]       ,				_lowerCAmelCase       ,				atol=1e-4			)			)









def 				snake_case  (     lowerCamelCase					):




	'''simple docstring'''







	if not isinstance(lowerCamelCase				,  lowerCamelCase					):
		raise ValueError("""check_bouncy() accepts only integer arguments"""					)
	__lowercase             =  str(lowerCamelCase					)
	__lowercase             =  """""".join(sorted(lowerCamelCase					)					)
	return sorted_str_n != str_n and sorted_str_n[::-1] != str_n





def 				snake_case  (     lowerCamelCase = 99					):




	'''simple docstring'''







	if not 0 < percent < 100:
		raise ValueError("""solution() only accepts values from 0 to 100"""					)
	__lowercase             =  0
	__lowercase             =  1

	while True:
		if check_bouncy(lowerCamelCase					):
			bouncy_num += 1
		if (bouncy_num / num) * 100 >= percent:
			return num
		num += 1


if __name__ == "__main__":
						from doctest import testmod

						testmod()
						print(F'''{solution(99)}''')

