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







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







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







							def       UpperCAmelCase__					(						self  :  int ):
								"""simple docstring"""







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

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

								__lowerCAmelCase         =							self.get_config()

								return config, pixel_values, labels







							def       UpperCAmelCase__					(						self  :  Tuple ):
								"""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       UpperCAmelCase__					(						self  :  Optional[Any] ):
								"""simple docstring"""







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







							def       UpperCAmelCase__					(						self  :  Any      ,				snake_case__  :  Optional[Any]      ,				snake_case__  :  str      ,				snake_case__  :  str ):
								"""simple docstring"""







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







							def       UpperCAmelCase__					(						self  :  int ):
								"""simple docstring"""







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

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







							def       UpperCAmelCase__					(						self  :  Optional[Any] ):
								"""simple docstring"""







								__lowerCAmelCase         =							UperNetModelTester(self )
								__lowerCAmelCase         =							ConfigTester(self      ,				config_class=snake_case__      ,				has_text_modality=snake_case__      ,				hidden_size=37 )







							def       UpperCAmelCase__					(						self  :  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       UpperCAmelCase__					(						self  :  List[Any] ):
								"""simple docstring"""







								return







							def       UpperCAmelCase__					(						self  :  List[str] ):
								"""simple docstring"""







								__lowerCAmelCase   ,						__lowerCAmelCase         =							self.model_tester.prepare_config_and_inputs_for_common()

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

									__lowerCAmelCase         =							["pixel_values"]
									self.assertListEqual(arg_names[:1]      ,				snake_case__ )







							def       UpperCAmelCase__					(						self  :  List[str] ):
								"""simple docstring"""







								__lowerCAmelCase         =							self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_semantic_segmentation(*snake_case__ )







							@unittest.skip(reason="UperNet does not use inputs_embeds" )
							def       UpperCAmelCase__					(						self  :  int ):
								"""simple docstring"""







								pass







							@unittest.skip(reason="UperNet does not support input and output embeddings" )
							def       UpperCAmelCase__					(						self  :  Tuple ):
								"""simple docstring"""







								pass







							@unittest.skip(reason="UperNet does not have a base model" )
							def       UpperCAmelCase__					(						self  :  Dict ):
								"""simple docstring"""







								pass







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







								pass







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







								pass







							def       UpperCAmelCase__					(						self  :  List[Any] ):
								"""simple docstring"""







								def check_hidden_states_output(snake_case__  :  Any      ,				snake_case__  :  Union[str, Any]      ,				snake_case__  :  Union[str, Any] ):
									__lowerCAmelCase         =							model_class(snake_case__ )
									model.to(snake_case__ )
									model.eval()

									with torch.no_grad():
										__lowerCAmelCase         =							model(**self._prepare_for_class(snake_case__      ,				snake_case__ ) )

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

									__lowerCAmelCase         =							self.model_tester.num_stages
									self.assertEqual(len(snake_case__ )      ,				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         =							self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
									__lowerCAmelCase         =							True
									check_hidden_states_output(snake_case__      ,				snake_case__      ,				snake_case__ )

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

									check_hidden_states_output(snake_case__      ,				snake_case__      ,				snake_case__ )







							def       UpperCAmelCase__					(						self  :  Dict ):
								"""simple docstring"""







								__lowerCAmelCase   ,						__lowerCAmelCase         =							self.model_tester.prepare_config_and_inputs_for_common()

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







								pass







							@slow
							def       UpperCAmelCase__					(						self  :  List[str] ):
								"""simple docstring"""







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






def 		_UpperCAmelCase   (	):






	"""simple docstring"""


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







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







							def       UpperCAmelCase__					(						self  :  Any ):
								"""simple docstring"""







								__lowerCAmelCase         =							AutoImageProcessor.from_pretrained("openmmlab/upernet-swin-tiny" )
								__lowerCAmelCase         =							UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-swin-tiny" ).to(snake_case__ )

								__lowerCAmelCase         =							prepare_img()
								__lowerCAmelCase         =							processor(images=snake_case__      ,				return_tensors="pt" ).to(snake_case__ )

								with torch.no_grad():
									__lowerCAmelCase         =							model(**snake_case__ )

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

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







							def       UpperCAmelCase__					(						self  :  List[str] ):
								"""simple docstring"""







								__lowerCAmelCase         =							AutoImageProcessor.from_pretrained("openmmlab/upernet-convnext-tiny" )
								__lowerCAmelCase         =							UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-convnext-tiny" ).to(snake_case__ )

								__lowerCAmelCase         =							prepare_img()
								__lowerCAmelCase         =							processor(images=snake_case__      ,				return_tensors="pt" ).to(snake_case__ )

								with torch.no_grad():
									__lowerCAmelCase         =							model(**snake_case__ )

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

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








from __future__ import annotations

from collections.abc import Iterator
from typing import Any

class       a		:







							def __init__(						self  :  Optional[int]      ,				snake_case__  :  Any ):
								"""simple docstring"""







								__lowerCAmelCase         =							data
								__lowerCAmelCase         =							None

class       a		:







							def __init__(						self  :  Optional[Any] ):
								"""simple docstring"""







								__lowerCAmelCase         =							None
								__lowerCAmelCase         =							None







							def __iter__(						self  :  Dict ):
								"""simple docstring"""







								__lowerCAmelCase         =							self.head
								while self.head:
									yield node.data
									__lowerCAmelCase         =							node.next
									if node == self.head:
										break







							def __len__(						self  :  Dict ):
								"""simple docstring"""







								return sum(1 for _ in self )







							def __repr__(						self  :  str ):
								"""simple docstring"""







								return "->".join(str(snake_case__ ) for item in iter(self ) )







							def       UpperCAmelCase__					(						self  :  Optional[Any]      ,				snake_case__  :  Any ):
								"""simple docstring"""







								self.insert_nth(len(self )      ,				snake_case__ )







							def       UpperCAmelCase__					(						self  :  Union[str, Any]      ,				snake_case__  :  Any ):
								"""simple docstring"""







								self.insert_nth(0      ,				snake_case__ )







							def       UpperCAmelCase__					(						self  :  List[Any]      ,				snake_case__  :  int      ,				snake_case__  :  Any ):
								"""simple docstring"""







								if index < 0 or index > len(self ):
									raise IndexError("list index out of range." )
								__lowerCAmelCase         =							Node(snake_case__ )
								if self.head is None:
									__lowerCAmelCase         =							new_node  # first node points itself
									__lowerCAmelCase         =							__lowerCAmelCase         =							new_node
								elif index == 0:  # insert at head
									__lowerCAmelCase         =							self.head
									__lowerCAmelCase         =							__lowerCAmelCase         =							new_node
								else:
									__lowerCAmelCase         =							self.head
									for _ in range(index - 1 ):
										__lowerCAmelCase         =							temp.next
									__lowerCAmelCase         =							temp.next
									__lowerCAmelCase         =							new_node
									if index == len(self ) - 1:  # insert at tail
										__lowerCAmelCase         =							new_node







							def       UpperCAmelCase__					(						self  :  List[Any] ):
								"""simple docstring"""







								return self.delete_nth(0 )







							def       UpperCAmelCase__					(						self  :  Union[str, Any] ):
								"""simple docstring"""







								return self.delete_nth(len(self ) - 1 )







							def       UpperCAmelCase__					(						self  :  str      ,				snake_case__  :  int = 0 ):
								"""simple docstring"""







								if not 0 <= index < len(self ):
									raise IndexError("list index out of range." )
								__lowerCAmelCase         =							self.head
								if self.head == self.tail:  # just one node
									__lowerCAmelCase         =							__lowerCAmelCase         =							None
								elif index == 0:  # delete head node
									__lowerCAmelCase         =							self.tail.next.next
									__lowerCAmelCase         =							self.head.next
								else:
									__lowerCAmelCase         =							self.head
									for _ in range(index - 1 ):
										__lowerCAmelCase         =							temp.next
									__lowerCAmelCase         =							temp.next
									__lowerCAmelCase         =							temp.next.next
									if index == len(self ) - 1:  # delete at tail
										__lowerCAmelCase         =							temp
								return delete_node.data







							def       UpperCAmelCase__					(						self  :  str ):
								"""simple docstring"""







								return len(self ) == 0






def 		_UpperCAmelCase   (	):






	"""simple docstring"""


	__lowerCAmelCase         =							CircularLinkedList()
	assert len(UpperCamelCase  ) == 0
	assert circular_linked_list.is_empty() is True
	assert str(UpperCamelCase  ) == ""

	try:
		circular_linked_list.delete_front()
		raise AssertionError  # This should not happen
	except IndexError:
		assert True  # This should happen

	try:
		circular_linked_list.delete_tail()
		raise AssertionError  # This should not happen
	except IndexError:
		assert True  # This should happen

	try:
		circular_linked_list.delete_nth(-1  )
		raise AssertionError
	except IndexError:
		assert True

	try:
		circular_linked_list.delete_nth(0  )
		raise AssertionError
	except IndexError:
		assert True

	assert circular_linked_list.is_empty() is True
	for i in range(5  ):
		assert len(UpperCamelCase  ) == i
		circular_linked_list.insert_nth(UpperCamelCase			,							i + 1  )
	assert str(UpperCamelCase  ) == "->".join(str(UpperCamelCase  ) for i in range(1			,							6  )  )

	circular_linked_list.insert_tail(6  )
	assert str(UpperCamelCase  ) == "->".join(str(UpperCamelCase  ) for i in range(1			,							7  )  )
	circular_linked_list.insert_head(0  )
	assert str(UpperCamelCase  ) == "->".join(str(UpperCamelCase  ) for i in range(0			,							7  )  )

	assert circular_linked_list.delete_front() == 0
	assert circular_linked_list.delete_tail() == 6
	assert str(UpperCamelCase  ) == "->".join(str(UpperCamelCase  ) for i in range(1			,							6  )  )
	assert circular_linked_list.delete_nth(2  ) == 3

	circular_linked_list.insert_nth(2			,							3  )
	assert str(UpperCamelCase  ) == "->".join(str(UpperCamelCase  ) for i in range(1			,							6  )  )

	assert circular_linked_list.is_empty() is False


if __name__ == "__main__":
					import doctest

					doctest.testmod()






