
import json
import os
import re
import shutil
import tempfile
import unittest
from typing import Tuple

from transformers import AddedToken, BatchEncoding, PerceiverTokenizer
from transformers.utils import cached_property, is_tf_available, is_torch_available

from ...test_tokenization_common import TokenizerTesterMixin


if is_torch_available():
		A		: Tuple								=     '''pt'''
elif is_tf_available():
		A		: Union[str, Any]								=     '''tf'''
else:
		A		: List[Any]								=     '''jax'''



class    a_ (			_a					,			unittest.TestCase    ):
			a	:			List[str]					   =							PerceiverTokenizer
			a	:			Any					   =							False






			def    UpperCamelCase_				(      self  ):
									super().setUp()
									_lowercase					       =					PerceiverTokenizer()
									tokenizer.save_pretrained(self.tmpdirname  )






			@cached_property
			def    UpperCamelCase_				(      self  ):
									return PerceiverTokenizer.from_pretrained("""deepmind/language-perceiver"""  )






			def    UpperCamelCase_				(      self				,			**__UpperCamelCase  ):
									return self.tokenizer_class.from_pretrained(self.tmpdirname				,			**__UpperCamelCase  )






			def    UpperCamelCase_				(      self				,			__UpperCamelCase				,			__UpperCamelCase=False				,			__UpperCamelCase=20				,			__UpperCamelCase=5  ):
									# XXX The default common tokenizer tests assume that every ID is decodable on its own.
									# This assumption is invalid for Perceiver because single bytes might not be
									# valid utf-8 (byte 128 for instance).
									# Here we're overriding the smallest possible method to provide
									# a clean sequence without making the same assumption.

									_lowercase					       =					[]
									for i in range(len(__UpperCamelCase  )  ):
															try:
																					_lowercase					       =					tokenizer.decode([i]				,			clean_up_tokenization_spaces=__UpperCamelCase  )
															except UnicodeDecodeError:
																					pass
															toks.append((i, tok)  )

									_lowercase					       =					list(filter(lambda __UpperCamelCase  : re.match(r"""^[ a-zA-Z]+$"""				,			t[1]  )				,			__UpperCamelCase  )  )
									_lowercase					       =					list(filter(lambda __UpperCamelCase  : [t[0]] == tokenizer.encode(t[1]				,			add_special_tokens=__UpperCamelCase  )				,			__UpperCamelCase  )  )
									if max_length is not None and len(__UpperCamelCase  ) > max_length:
															_lowercase					       =					toks[:max_length]
									if min_length is not None and len(__UpperCamelCase  ) < min_length and len(__UpperCamelCase  ) > 0:
															while len(__UpperCamelCase  ) < min_length:
																					_lowercase					       =					toks + toks
        # toks_str = [t[1] for t in toks]
									_lowercase					       =					[t[0] for t in toks]

									# Ensure consistency
									_lowercase					       =					tokenizer.decode(__UpperCamelCase				,			clean_up_tokenization_spaces=__UpperCamelCase  )
									if " " not in output_txt and len(__UpperCamelCase  ) > 1:
															_lowercase					       =					(
															    tokenizer.decode([toks_ids[0]]				,			clean_up_tokenization_spaces=__UpperCamelCase  )
															    + """ """
															    + tokenizer.decode(toks_ids[1:]				,			clean_up_tokenization_spaces=__UpperCamelCase  )
															)
									if with_prefix_space:
															_lowercase					       =					""" """ + output_txt
									_lowercase					       =					tokenizer.encode(__UpperCamelCase				,			add_special_tokens=__UpperCamelCase  )
									return output_txt, output_ids






			def    UpperCamelCase_				(      self  ):
									_lowercase					       =					self.perceiver_tokenizer
									_lowercase					       =					"""Unicode €."""
									_lowercase					       =					tokenizer(__UpperCamelCase  )
									_lowercase					       =					[4, 91, 116, 111, 105, 117, 106, 107, 38, 232, 136, 178, 52, 5]
									self.assertEqual(encoded["""input_ids"""]				,			__UpperCamelCase  )

									# decoding
									_lowercase					       =					tokenizer.decode(__UpperCamelCase  )
									self.assertEqual(__UpperCamelCase				,			"""[CLS]Unicode €.[SEP]"""  )

									_lowercase					       =					tokenizer("""e è é ê ë"""  )
									_lowercase					       =					[4, 107, 38, 201, 174, 38, 201, 175, 38, 201, 176, 38, 201, 177, 5]
									self.assertEqual(encoded["""input_ids"""]				,			__UpperCamelCase  )
									# decoding
									_lowercase					       =					tokenizer.decode(__UpperCamelCase  )
									self.assertEqual(__UpperCamelCase				,			"""[CLS]e è é ê ë[SEP]"""  )

									# encode/decode, but with `encode` instead of `__call__`
									self.assertEqual(tokenizer.decode(tokenizer.encode("""e è é ê ë"""  )  )				,			"""[CLS]e è é ê ë[SEP]"""  )






			def    UpperCamelCase_				(      self  ):
									_lowercase					       =					self.perceiver_tokenizer
									_lowercase					       =					["""A long paragraph for summarization.""", """Another paragraph for summarization."""]
									# fmt: off
									_lowercase					       =					[4, 71, 38, 114, 117, 116, 109, 38, 118, 103, 120, 103, 109, 120, 103, 118, 110, 38, 108, 117, 120, 38, 121, 123, 115, 115, 103, 120, 111, 128, 103, 122, 111, 117, 116, 52, 5, 0]
									# fmt: on
									_lowercase					       =					tokenizer(__UpperCamelCase				,			padding=__UpperCamelCase				,			return_tensors=__UpperCamelCase  )
									self.assertIsInstance(__UpperCamelCase				,			__UpperCamelCase  )

									if FRAMEWORK != "jax":
															_lowercase					       =					list(batch.input_ids.numpy()[0]  )
									else:
															_lowercase					       =					list(batch.input_ids.tolist()[0]  )

									self.assertListEqual(__UpperCamelCase				,			__UpperCamelCase  )

									self.assertEqual((2, 38)				,			batch.input_ids.shape  )
									self.assertEqual((2, 38)				,			batch.attention_mask.shape  )






			def    UpperCamelCase_				(      self  ):
									_lowercase					       =					self.perceiver_tokenizer
									_lowercase					       =					["""A long paragraph for summarization.""", """Another paragraph for summarization."""]
									_lowercase					       =					tokenizer(__UpperCamelCase				,			padding=__UpperCamelCase				,			return_tensors=__UpperCamelCase  )
									# check if input_ids are returned and no decoder_input_ids
									self.assertIn("""input_ids"""				,			__UpperCamelCase  )
									self.assertIn("""attention_mask"""				,			__UpperCamelCase  )
									self.assertNotIn("""decoder_input_ids"""				,			__UpperCamelCase  )
									self.assertNotIn("""decoder_attention_mask"""				,			__UpperCamelCase  )






			def    UpperCamelCase_				(      self  ):
									_lowercase					       =					self.perceiver_tokenizer
									_lowercase					       =					[
									    """Summary of the text.""",
									    """Another summary.""",
									]
									_lowercase					       =					tokenizer(
									    text_target=__UpperCamelCase				,			max_length=32				,			padding="""max_length"""				,			truncation=__UpperCamelCase				,			return_tensors=__UpperCamelCase  )
									self.assertEqual(32				,			targets["""input_ids"""].shape[1]  )






			def    UpperCamelCase_				(      self  ):
									# safety check on max_len default value so we are sure the test works
									_lowercase					       =					self.get_tokenizers()
									for tokenizer in tokenizers:
															with self.subTest(f"""{tokenizer.__class__.__name__}"""  ):
																					self.assertNotEqual(tokenizer.model_max_length				,			42  )

        # Now let's start the test
									_lowercase					       =					self.get_tokenizers()
									for tokenizer in tokenizers:
															with self.subTest(f"""{tokenizer.__class__.__name__}"""  ):
																					# Isolate this from the other tests because we save additional tokens/etc
																					_lowercase					       =					tempfile.mkdtemp()

																					_lowercase					       =					""" He is very happy, UNwant\u00E9d,running"""
																					_lowercase					       =					tokenizer.encode(__UpperCamelCase				,			add_special_tokens=__UpperCamelCase  )
																					tokenizer.save_pretrained(__UpperCamelCase  )

																					_lowercase					       =					tokenizer.__class__.from_pretrained(__UpperCamelCase  )
																					_lowercase					       =					after_tokenizer.encode(__UpperCamelCase				,			add_special_tokens=__UpperCamelCase  )
																					self.assertListEqual(__UpperCamelCase				,			__UpperCamelCase  )

																					shutil.rmtree(__UpperCamelCase  )

									_lowercase					       =					self.get_tokenizers(model_max_length=42  )
									for tokenizer in tokenizers:
															with self.subTest(f"""{tokenizer.__class__.__name__}"""  ):
																					# Isolate this from the other tests because we save additional tokens/etc
																					_lowercase					       =					tempfile.mkdtemp()

																					_lowercase					       =					""" He is very happy, UNwant\u00E9d,running"""
																					tokenizer.add_tokens(["""bim""", """bambam"""]  )
																					_lowercase					       =					tokenizer.additional_special_tokens
																					additional_special_tokens.append("""new_additional_special_token"""  )
																					tokenizer.add_special_tokens({"""additional_special_tokens""": additional_special_tokens}  )
																					_lowercase					       =					tokenizer.encode(__UpperCamelCase				,			add_special_tokens=__UpperCamelCase  )
																					tokenizer.save_pretrained(__UpperCamelCase  )

																					_lowercase					       =					tokenizer.__class__.from_pretrained(__UpperCamelCase  )
																					_lowercase					       =					after_tokenizer.encode(__UpperCamelCase				,			add_special_tokens=__UpperCamelCase  )
																					self.assertListEqual(__UpperCamelCase				,			__UpperCamelCase  )
																					self.assertIn("""new_additional_special_token"""				,			after_tokenizer.additional_special_tokens  )
																					self.assertEqual(after_tokenizer.model_max_length				,			42  )

																					_lowercase					       =					tokenizer.__class__.from_pretrained(__UpperCamelCase				,			model_max_length=43  )
																					self.assertEqual(tokenizer.model_max_length				,			43  )

																					shutil.rmtree(__UpperCamelCase  )






			def    UpperCamelCase_				(      self  ):
									_lowercase					       =					[]
									if self.test_slow_tokenizer:
															tokenizer_list.append((self.tokenizer_class, self.get_tokenizer())  )

									if self.test_rust_tokenizer:
															tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer())  )

									for tokenizer_class, tokenizer_utils in tokenizer_list:
															with tempfile.TemporaryDirectory() as tmp_dir:
																					tokenizer_utils.save_pretrained(__UpperCamelCase  )

																					with open(os.path.join(__UpperCamelCase				,			"""special_tokens_map.json"""  )				,			encoding="""utf-8"""  ) as json_file:
																											_lowercase					       =					json.load(__UpperCamelCase  )

																					with open(os.path.join(__UpperCamelCase				,			"""tokenizer_config.json"""  )				,			encoding="""utf-8"""  ) as json_file:
																											_lowercase					       =					json.load(__UpperCamelCase  )

																					_lowercase					       =					[f"""<extra_id_{i}>""" for i in range(125  )]

																					_lowercase					       =					added_tokens_extra_ids + [
																					    """an_additional_special_token"""
																					]
																					_lowercase					       =					added_tokens_extra_ids + [
																					    """an_additional_special_token"""
																					]

																					with open(os.path.join(__UpperCamelCase				,			"""special_tokens_map.json"""  )				,			"""w"""				,			encoding="""utf-8"""  ) as outfile:
																											json.dump(__UpperCamelCase				,			__UpperCamelCase  )
																					with open(os.path.join(__UpperCamelCase				,			"""tokenizer_config.json"""  )				,			"""w"""				,			encoding="""utf-8"""  ) as outfile:
																											json.dump(__UpperCamelCase				,			__UpperCamelCase  )

																					# the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes
																					# into account the new value of additional_special_tokens given in the "tokenizer_config.json" and
																					# "special_tokens_map.json" files
																					_lowercase					       =					tokenizer_class.from_pretrained(
																					    __UpperCamelCase				,			)
																					self.assertIn(
																					    """an_additional_special_token"""				,			tokenizer_without_change_in_init.additional_special_tokens  )
																					self.assertEqual(
																					    ["""an_additional_special_token"""]				,			tokenizer_without_change_in_init.convert_ids_to_tokens(
																					        tokenizer_without_change_in_init.convert_tokens_to_ids(["""an_additional_special_token"""]  )  )				,			)

																					# Now we test that we can change the value of additional_special_tokens in the from_pretrained
																					_lowercase					       =					added_tokens_extra_ids + [AddedToken("""a_new_additional_special_token"""				,			lstrip=__UpperCamelCase  )]
																					_lowercase					       =					tokenizer_class.from_pretrained(
																					    __UpperCamelCase				,			additional_special_tokens=__UpperCamelCase				,			)

																					self.assertIn("""a_new_additional_special_token"""				,			tokenizer.additional_special_tokens  )
																					self.assertEqual(
																					    ["""a_new_additional_special_token"""]				,			tokenizer.convert_ids_to_tokens(
																					        tokenizer.convert_tokens_to_ids(["""a_new_additional_special_token"""]  )  )				,			)






			def    UpperCamelCase_				(      self  ):
									_lowercase					       =					self.perceiver_tokenizer
									self.assertEqual(tokenizer.decode([178]  )				,			"""�"""  )






			def    UpperCamelCase_				(      self  ):
									pass






			def    UpperCamelCase_				(      self  ):
									pass






			def    UpperCamelCase_				(      self  ):
									pass






			def    UpperCamelCase_				(      self  ):
									pass






			def    UpperCamelCase_				(      self  ):
									# The default common tokenizer tests uses invalid tokens for Perceiver that can only accept one-character
									# strings and special added tokens as tokens
									_lowercase					       =					self.get_tokenizers(fast=__UpperCamelCase				,			do_lower_case=__UpperCamelCase  )
									for tokenizer in tokenizers:
															with self.subTest(f"""{tokenizer.__class__.__name__}"""  ):
																					_lowercase					       =					["""[CLS]""", """t""", """h""", """i""", """s""", """ """, """i""", """s""", """ """, """a""", """ """, """t""", """e""", """s""", """t""", """[SEP]"""]
																					_lowercase					       =					tokenizer.convert_tokens_to_string(__UpperCamelCase  )

																					self.assertIsInstance(__UpperCamelCase				,			__UpperCamelCase  )

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				,			__UpperCamelCase				,			__UpperCamelCase=13				,			__UpperCamelCase=32				,			__UpperCamelCase=3				,			__UpperCamelCase=4				,			__UpperCamelCase=[10, 20, 30, 40]				,			__UpperCamelCase=[2, 2, 3, 2]				,			__UpperCamelCase=True				,			__UpperCamelCase=True				,			__UpperCamelCase=37				,			__UpperCamelCase="gelu"				,			__UpperCamelCase=10				,			__UpperCamelCase=0.02				,			__UpperCamelCase=["stage2", "stage3", "stage4"]				,			__UpperCamelCase=3				,			__UpperCamelCase=None				,			):
									_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    UpperCamelCase_				(      self  ):
									_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    UpperCamelCase_				(      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    UpperCamelCase_				(      self  ):
									return UperNetConfig(
									    backbone_config=self.get_backbone_config()				,			hidden_size=512				,			pool_scales=[1, 2, 3, 6]				,			use_auxiliary_head=__UpperCamelCase				,			auxiliary_loss_weight=0.4				,			auxiliary_in_channels=40				,			auxiliary_channels=256				,			auxiliary_num_convs=1				,			auxiliary_concat_input=__UpperCamelCase				,			loss_ignore_index=255				,			num_labels=self.num_labels				,			)






			def    UpperCamelCase_				(      self				,			__UpperCamelCase				,			__UpperCamelCase				,			__UpperCamelCase  ):
									_lowercase					       =					UperNetForSemanticSegmentation(config=__UpperCamelCase  )
									model.to(__UpperCamelCase  )
									model.eval()
									_lowercase					       =					model(__UpperCamelCase  )
									self.parent.assertEqual(
									    result.logits.shape				,			(self.batch_size, self.num_labels, self.image_size, self.image_size)  )






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







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






			def    UpperCamelCase_				(      self  ):
									_lowercase					       =					UperNetModelTester(self  )
									_lowercase					       =					ConfigTester(self				,			config_class=__UpperCamelCase				,			has_text_modality=__UpperCamelCase				,			hidden_size=37  )






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






			def    UpperCamelCase_				(      self  ):
									_lowercase       ,						_lowercase					       =					self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
															_lowercase					       =					model_class(__UpperCamelCase  )
															_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]				,			__UpperCamelCase  )






			def    UpperCamelCase_				(      self  ):
									_lowercase					       =					self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_semantic_segmentation(*__UpperCamelCase  )






			@unittest.skip(reason="""UperNet does not use inputs_embeds"""  )
			def    UpperCamelCase_				(      self  ):
									pass






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






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






			@unittest.skip(reason="""UperNet does not have a base model"""  )
			def    UpperCamelCase_				(      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    UpperCamelCase_				(      self  ):
									pass






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






			def    UpperCamelCase_				(      self  ):
									def check_hidden_states_output(__UpperCamelCase				,			__UpperCamelCase				,			__UpperCamelCase  ):
															_lowercase					       =					model_class(__UpperCamelCase  )
															model.to(__UpperCamelCase  )
															model.eval()

															with torch.no_grad():
																					_lowercase					       =					model(**self._prepare_for_class(__UpperCamelCase				,			__UpperCamelCase  )  )

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

															_lowercase					       =					self.model_tester.num_stages
															self.assertEqual(len(__UpperCamelCase  )				,			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(__UpperCamelCase				,			__UpperCamelCase				,			__UpperCamelCase  )

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

															check_hidden_states_output(__UpperCamelCase				,			__UpperCamelCase				,			__UpperCamelCase  )






			def    UpperCamelCase_				(      self  ):
									_lowercase       ,						_lowercase					       =					self.model_tester.prepare_config_and_inputs_for_common()

									_lowercase					       =					_config_zero_init(__UpperCamelCase  )
									_lowercase					       =					_config_zero_init(configs_no_init.backbone_config  )
									for model_class in self.all_model_classes:
															_lowercase					       =					model_class(config=__UpperCamelCase  )
															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  ):
									pass






			@slow
			def    UpperCamelCase_				(      self  ):
									for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															_lowercase					       =					UperNetForSemanticSegmentation.from_pretrained(__UpperCamelCase  )
															self.assertIsNotNone(__UpperCamelCase  )







def 	UpperCamelCase__  (     )  ->     str:
						_lowercase					       =					hf_hub_download(
						    repo_id="""hf-internal-testing/fixtures_ade20k"""		,   repo_type="""dataset"""		,   filename="""ADE_val_00000001.jpg"""       )
						_lowercase					       =					Image.open(SCREAMING_SNAKE_CASE_       ).convert("""RGB"""       )
						return image



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






			def    UpperCamelCase_				(      self  ):
									_lowercase					       =					AutoImageProcessor.from_pretrained("""openmmlab/upernet-swin-tiny"""  )
									_lowercase					       =					UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-swin-tiny"""  ).to(__UpperCamelCase  )

									_lowercase					       =					prepare_img()
									_lowercase					       =					processor(images=__UpperCamelCase				,			return_tensors="""pt"""  ).to(__UpperCamelCase  )

									with torch.no_grad():
															_lowercase					       =					model(**__UpperCamelCase  )

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

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






			def    UpperCamelCase_				(      self  ):
									_lowercase					       =					AutoImageProcessor.from_pretrained("""openmmlab/upernet-convnext-tiny"""  )
									_lowercase					       =					UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-convnext-tiny"""  ).to(__UpperCamelCase  )

									_lowercase					       =					prepare_img()
									_lowercase					       =					processor(images=__UpperCamelCase				,			return_tensors="""pt"""  ).to(__UpperCamelCase  )

									with torch.no_grad():
															_lowercase					       =					model(**__UpperCamelCase  )

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

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