





'''simple docstring'''






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



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



	def   _lowerCamelCase    (   self	):
			lowerCAmelCase     :    Dict						=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

			lowerCAmelCase     :    Optional[Any]						=   None
			if self.use_labels:
					lowerCAmelCase     :    Optional[Any]						=   ids_tensor([self.batch_size]		,      self.type_sequence_label_size	)

			lowerCAmelCase     :    Optional[Any]						=   self.get_config()

			return config, pixel_values, labels



	def   _lowerCamelCase    (   self	):
			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   _lowerCamelCase    (   self	):
			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   _lowerCamelCase    (   self		,      a_		,      a_		,      a_	):
			lowerCAmelCase     :    str						=   UperNetForSemanticSegmentation(config=_lowerCAmelCase	)
			model.to(_lowerCAmelCase	)
			model.eval()
			lowerCAmelCase     :    Dict						=   model(_lowerCAmelCase	)
			self.parent.assertEqual(
			    result.logits.shape		,      (self.batch_size, self.num_labels, self.image_size, self.image_size)	)





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






@require_torch
class 		lowerCamelCase  (      _lowerCAmelCase      ,   _lowerCAmelCase      ,   unittest.TestCase       ):
	snake_case_      =   (UperNetForSemanticSegmentation,) if is_torch_available() else ()
	snake_case_      =   {'image-segmentation': UperNetForSemanticSegmentation} if is_torch_available() else {}
	snake_case_      =   False
	snake_case_      =   False
	snake_case_      =   False
	snake_case_      =   False
	snake_case_      =   False
	snake_case_      =   False



	def   _lowerCamelCase    (   self	):
			lowerCAmelCase     :    List[Any]						=   UperNetModelTester(self	)
			lowerCAmelCase     :    Any						=   ConfigTester(self		,      config_class=_lowerCAmelCase		,      has_text_modality=_lowerCAmelCase		,      hidden_size=37	)



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



	def   _lowerCamelCase    (   self	):
			lowerCAmelCase	,		lowerCAmelCase     :    int						=   self.model_tester.prepare_config_and_inputs_for_common()

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

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



	def   _lowerCamelCase    (   self	):
			lowerCAmelCase     :    str						=   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   _lowerCamelCase    (   self	):
			pass



	@unittest.skip(reason="UperNet does not support input and output embeddings"	)
	def   _lowerCamelCase    (   self	):
			pass



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



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



	@require_torch_multi_gpu
	@unittest.skip(reason="UperNet has some layers using `add_module` which doesn't work well with `nn.DataParallel`"	)
	def   _lowerCamelCase    (   self	):
			pass



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



	def   _lowerCamelCase    (   self	):







			def check_hidden_states_output(a_		,      a_		,      a_	):
					lowerCAmelCase     :    List[Any]						=   model_class(_lowerCAmelCase	)
					model.to(_lowerCAmelCase	)
					model.eval()

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

					lowerCAmelCase     :    str						=   outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

					lowerCAmelCase     :    List[Any]						=   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]		,      )

			lowerCAmelCase	,		lowerCAmelCase     :    Optional[Any]						=   self.model_tester.prepare_config_and_inputs_for_common()

			for model_class in self.all_model_classes:
					lowerCAmelCase     :    Optional[Any]						=   True
					check_hidden_states_output(_lowerCAmelCase		,      _lowerCAmelCase		,      _lowerCAmelCase	)

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

					check_hidden_states_output(_lowerCAmelCase		,      _lowerCAmelCase		,      _lowerCAmelCase	)



	def   _lowerCamelCase    (   self	):
			lowerCAmelCase	,		lowerCAmelCase     :    str						=   self.model_tester.prepare_config_and_inputs_for_common()

			lowerCAmelCase     :    Optional[int]						=   _config_zero_init(_lowerCAmelCase	)
			lowerCAmelCase     :    str						=   _config_zero_init(configs_no_init.backbone_config	)
			for model_class in self.all_model_classes:
					lowerCAmelCase     :    int						=   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   _lowerCamelCase    (   self	):
			pass





	@slow
	def   _lowerCamelCase    (   self	):







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






def      __A						(							):
		lowerCAmelCase     :    Union[str, Any]						=   hf_hub_download(
		    repo_id="hf-internal-testing/fixtures_ade20k"      ,repo_type="dataset"      ,filename="ADE_val_00000001.jpg"	)
		lowerCAmelCase     :    Any						=   Image.open(a_	).convert("RGB"	)
		return image

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



	def   _lowerCamelCase    (   self	):
			lowerCAmelCase     :    List[Any]						=   AutoImageProcessor.from_pretrained("openmmlab/upernet-swin-tiny"	)
			lowerCAmelCase     :    Union[str, Any]						=   UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-swin-tiny"	).to(_lowerCAmelCase	)

			lowerCAmelCase     :    int						=   prepare_img()
			lowerCAmelCase     :    Any						=   processor(images=_lowerCAmelCase		,      return_tensors="pt"	).to(_lowerCAmelCase	)

			with torch.no_grad():
					lowerCAmelCase     :    Optional[int]						=   model(**_lowerCAmelCase	)

			lowerCAmelCase     :    Optional[int]						=   torch.Size((1, model.config.num_labels, 512, 512)	)
			self.assertEqual(outputs.logits.shape		,      _lowerCAmelCase	)

			lowerCAmelCase     :    Union[str, Any]						=   torch.tensor(
			    [[-7.5958, -7.5958, -7.4302], [-7.5958, -7.5958, -7.4302], [-7.4797, -7.4797, -7.3068]]	).to(_lowerCAmelCase	)
			self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]		,      _lowerCAmelCase		,      atol=1e-4	)	)





	def   _lowerCamelCase    (   self	):
			lowerCAmelCase     :    Any						=   AutoImageProcessor.from_pretrained("openmmlab/upernet-convnext-tiny"	)
			lowerCAmelCase     :    Union[str, Any]						=   UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-convnext-tiny"	).to(_lowerCAmelCase	)

			lowerCAmelCase     :    Any						=   prepare_img()
			lowerCAmelCase     :    Any						=   processor(images=_lowerCAmelCase		,      return_tensors="pt"	).to(_lowerCAmelCase	)

			with torch.no_grad():
					lowerCAmelCase     :    Dict						=   model(**_lowerCAmelCase	)

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

			lowerCAmelCase     :    List[Any]						=   torch.tensor(
			    [[-8.8110, -8.8110, -8.6521], [-8.8110, -8.8110, -8.6521], [-8.7746, -8.7746, -8.6130]]	).to(_lowerCAmelCase	)
			self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]		,      _lowerCAmelCase		,      atol=1e-4	)	)










'''simple docstring'''






from __future__ import annotations






def      __A						(							a_						:  float      ,a_						:  float      ,a_						:  float      ,):
		if (stress, tangential_force, area).count(0	) != 1:
				raise ValueError("You cannot supply more or less than 2 values"	)
		elif stress < 0:
				raise ValueError("Stress cannot be negative"	)
		elif tangential_force < 0:
				raise ValueError("Tangential Force cannot be negative"	)
		elif area < 0:
				raise ValueError("Area cannot be negative"	)
		elif stress == 0:
				return (
				    "stress",
				    tangential_force / area,
				)
		elif tangential_force == 0:
				return (
				    "tangential_force",
				    stress * area,
				)
		else:
				return (
				    "area",
				    tangential_force / stress,
				)


if __name__ == "__main__":
					import doctest

					doctest.testmod()



