



"""simple docstring"""






import itertools
import os
import random
import tempfile
import unittest

import numpy as np
from datasets import load_dataset

from transformers import is_speech_available
from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_speech_available():
		from transformers import WhisperFeatureExtractor

if is_torch_available():
		import torch

_lowercase				:				Union[str, Any]   		=		random.Random()






def   snake_case__     (	__lowerCamelCase       :					List[str]							,	__lowerCamelCase       :					str=1.0							,	__lowerCamelCase       :					List[str]=None							,	__lowerCamelCase       :					List[str]=None			):
			"""simple docstring"""
			if rng is None:
						lowerCamelCase__	:	Optional[Any]				=global_rng

			lowerCamelCase__	:	List[Any]				=[]
			for batch_idx in range(shape[0]			):
						values.append([]			)
						for _ in range(shape[1]			):
									values[-1].append(rng.random() * scale			)

			return values

@require_torch
@require_torchaudio
class  __SCREAMING_SNAKE_CASE			(   unittest.TestCase     ):


					'''simple docstring'''





					def __init__( self							:						str,						lowerCamelCase							:						List[str],						lowerCamelCase							:						str=7,						lowerCamelCase							:						Optional[int]=400,						lowerCamelCase							:						Any=2000,						lowerCamelCase							:						int=10,						lowerCamelCase							:						Optional[Any]=160,						lowerCamelCase							:						Dict=8,						lowerCamelCase							:						Dict=0.0,						lowerCamelCase							:						Any=4000,						lowerCamelCase							:						Dict=False,						lowerCamelCase							:						List[str]=True,						)->      Optional[int]:
								lowerCamelCase__	:	List[Any]				=parent
								lowerCamelCase__	:	Union[str, Any]				=batch_size
								lowerCamelCase__	:	List[str]				=min_seq_length
								lowerCamelCase__	:	List[str]				=max_seq_length
								lowerCamelCase__	:	Union[str, Any]				=(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
								lowerCamelCase__	:	Tuple				=padding_value
								lowerCamelCase__	:	List[Any]				=sampling_rate
								lowerCamelCase__	:	str				=return_attention_mask
								lowerCamelCase__	:	Optional[Any]				=do_normalize
								lowerCamelCase__	:	Optional[int]				=feature_size
								lowerCamelCase__	:	str				=chunk_length
								lowerCamelCase__	:	Optional[Any]				=hop_length



					def 	snake_case ( self							:						Tuple  )->      Any:
								return {
								    "feature_size": self.feature_size,
								    "hop_length": self.hop_length,
								    "chunk_length": self.chunk_length,
								    "padding_value": self.padding_value,
								    "sampling_rate": self.sampling_rate,
								    "return_attention_mask": self.return_attention_mask,
								    "do_normalize": self.do_normalize,
								}




					def 	snake_case ( self							:						Any,						lowerCamelCase							:						Optional[int]=False,						lowerCamelCase							:						int=False  )->      Optional[Any]:
								def _flatten(lowerCamelCase							:						Any  ):
											return list(itertools.chain(*lowerCamelCase  )  )

								if equal_length:
											lowerCamelCase__	:	List[Any]				=[floats_list((self.max_seq_length, self.feature_size)  ) for _ in range(self.batch_size  )]
								else:
											# make sure that inputs increase in size
											lowerCamelCase__	:	Optional[Any]				=[
											    floats_list((x, self.feature_size)  )
											    for x in range(self.min_seq_length,						self.max_seq_length,						self.seq_length_diff  )
											]
								if numpify:
											lowerCamelCase__	:	List[Any]				=[np.asarray(lowerCamelCase  ) for x in speech_inputs]
								return speech_inputs





@require_torch
@require_torchaudio
class  __SCREAMING_SNAKE_CASE			(   lowerCAmelCase_	,     unittest.TestCase     ):


					'''simple docstring'''





					_a         =							WhisperFeatureExtractor if is_speech_available() else None



					def 	snake_case ( self							:						List[Any]  )->      Dict:
								lowerCamelCase__	:	Optional[int]				=WhisperFeatureExtractionTester(self  )



					def 	snake_case ( self							:						str  )->      List[str]:
								lowerCamelCase__	:	List[str]				=self.feature_extraction_class(**self.feat_extract_dict  )

								with tempfile.TemporaryDirectory() as tmpdirname:
											lowerCamelCase__	:	List[Any]				=feat_extract_first.save_pretrained(lowerCamelCase  )[0]
											check_json_file_has_correct_format(lowerCamelCase  )
											lowerCamelCase__	:	Optional[Any]				=self.feature_extraction_class.from_pretrained(lowerCamelCase  )

								lowerCamelCase__	:	List[str]				=feat_extract_first.to_dict()
								lowerCamelCase__	:	Union[str, Any]				=feat_extract_second.to_dict()
								lowerCamelCase__	:	Any				=feat_extract_first.mel_filters
								lowerCamelCase__	:	int				=feat_extract_second.mel_filters
								self.assertTrue(np.allclose(lowerCamelCase,						lowerCamelCase  )  )
								self.assertEqual(lowerCamelCase,						lowerCamelCase  )



					def 	snake_case ( self							:						Union[str, Any]  )->      List[Any]:
								lowerCamelCase__	:	str				=self.feature_extraction_class(**self.feat_extract_dict  )

								with tempfile.TemporaryDirectory() as tmpdirname:
											lowerCamelCase__	:	Any				=os.path.join(lowerCamelCase,						'''feat_extract.json'''  )
											feat_extract_first.to_json_file(lowerCamelCase  )
											lowerCamelCase__	:	Any				=self.feature_extraction_class.from_json_file(lowerCamelCase  )

								lowerCamelCase__	:	Optional[Any]				=feat_extract_first.to_dict()
								lowerCamelCase__	:	Union[str, Any]				=feat_extract_second.to_dict()
								lowerCamelCase__	:	str				=feat_extract_first.mel_filters
								lowerCamelCase__	:	List[Any]				=feat_extract_second.mel_filters
								self.assertTrue(np.allclose(lowerCamelCase,						lowerCamelCase  )  )
								self.assertEqual(lowerCamelCase,						lowerCamelCase  )



					def 	snake_case ( self							:						str  )->      List[str]:
								# Tests that all call wrap to encode_plus and batch_encode_plus
								lowerCamelCase__	:	Union[str, Any]				=self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()  )
								# create three inputs of length 800, 1000, and 1200
								lowerCamelCase__	:	List[Any]				=[floats_list((1, x)  )[0] for x in range(800,						1400,						200  )]
								lowerCamelCase__	:	Dict				=[np.asarray(lowerCamelCase  ) for speech_input in speech_inputs]

								# Test feature size
								lowerCamelCase__	:	List[Any]				=feature_extractor(lowerCamelCase,						padding='''max_length''',						return_tensors='''np'''  ).input_features
								self.assertTrue(input_features.ndim == 3  )
								self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames  )
								self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size  )

								# Test not batched input
								lowerCamelCase__	:	Optional[Any]				=feature_extractor(speech_inputs[0],						return_tensors='''np'''  ).input_features
								lowerCamelCase__	:	List[Any]				=feature_extractor(np_speech_inputs[0],						return_tensors='''np'''  ).input_features
								self.assertTrue(np.allclose(lowerCamelCase,						lowerCamelCase,						atol=1E-3  )  )

								# Test batched
								lowerCamelCase__	:	Dict				=feature_extractor(lowerCamelCase,						return_tensors='''np'''  ).input_features
								lowerCamelCase__	:	List[Any]				=feature_extractor(lowerCamelCase,						return_tensors='''np'''  ).input_features
								for enc_seq_a, enc_seq_a in zip(lowerCamelCase,						lowerCamelCase  ):
											self.assertTrue(np.allclose(lowerCamelCase,						lowerCamelCase,						atol=1E-3  )  )

								# Test 2-D numpy arrays are batched.
								lowerCamelCase__	:	Union[str, Any]				=[floats_list((1, x)  )[0] for x in (800, 800, 800)]
								lowerCamelCase__	:	int				=np.asarray(lowerCamelCase  )
								lowerCamelCase__	:	Any				=feature_extractor(lowerCamelCase,						return_tensors='''np'''  ).input_features
								lowerCamelCase__	:	Optional[Any]				=feature_extractor(lowerCamelCase,						return_tensors='''np'''  ).input_features
								for enc_seq_a, enc_seq_a in zip(lowerCamelCase,						lowerCamelCase  ):
											self.assertTrue(np.allclose(lowerCamelCase,						lowerCamelCase,						atol=1E-3  )  )

								# Test truncation required
								lowerCamelCase__	:	int				=[floats_list((1, x)  )[0] for x in range(200,						(feature_extractor.n_samples + 500),						200  )]
								lowerCamelCase__	:	Any				=[np.asarray(lowerCamelCase  ) for speech_input in speech_inputs]

								lowerCamelCase__	:	List[Any]				=[x[: feature_extractor.n_samples] for x in speech_inputs]
								lowerCamelCase__	:	Optional[int]				=[np.asarray(lowerCamelCase  ) for speech_input in speech_inputs_truncated]

								lowerCamelCase__	:	List[Any]				=feature_extractor(lowerCamelCase,						return_tensors='''np'''  ).input_features
								lowerCamelCase__	:	int				=feature_extractor(lowerCamelCase,						return_tensors='''np'''  ).input_features
								for enc_seq_a, enc_seq_a in zip(lowerCamelCase,						lowerCamelCase  ):
											self.assertTrue(np.allclose(lowerCamelCase,						lowerCamelCase,						atol=1E-3  )  )



					def 	snake_case ( self							:						List[Any]  )->      Tuple:
								import torch

								lowerCamelCase__	:	List[str]				=self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()  )
								lowerCamelCase__	:	Union[str, Any]				=np.random.rand(100,						32  ).astype(np.floataa  )
								lowerCamelCase__	:	Optional[Any]				=np_speech_inputs.tolist()

								for inputs in [py_speech_inputs, np_speech_inputs]:
											lowerCamelCase__	:	int				=feature_extractor.pad([{'''input_features''': inputs}],						return_tensors='''np'''  )
											self.assertTrue(np_processed.input_features.dtype == np.floataa  )
											lowerCamelCase__	:	Optional[int]				=feature_extractor.pad([{'''input_features''': inputs}],						return_tensors='''pt'''  )
											self.assertTrue(pt_processed.input_features.dtype == torch.floataa  )



					def 	snake_case ( self							:						Any,						lowerCamelCase							:						Union[str, Any]  )->      Optional[int]:
								lowerCamelCase__	:	Tuple				=load_dataset('''hf-internal-testing/librispeech_asr_dummy''',						'''clean''',						split='''validation'''  )
								# automatic decoding with librispeech
								lowerCamelCase__	:	str				=ds.sort('''id'''  ).select(range(lowerCamelCase  )  )[:num_samples]['''audio''']

								return [x["array"] for x in speech_samples]



					def 	snake_case ( self							:						Tuple  )->      Dict:
								# fmt: off
								lowerCamelCase__	:	str				=torch.tensor(
								    [
								        0.1_193, -0.0_946, -0.1_098, -0.0_196, 0.0_225, -0.0_690, -0.1_736, 0.0_951,
								        0.0_971, -0.0_817, -0.0_702, 0.0_162, 0.0_260, 0.0_017, -0.0_192, -0.1_678,
								        0.0_709, -0.1_867, -0.0_655, -0.0_274, -0.0_234, -0.1_884, -0.0_516, -0.0_554,
								        -0.0_274, -0.1_425, -0.1_423, 0.0_837, 0.0_377, -0.0_854
								    ]  )
								# fmt: on

								lowerCamelCase__	:	Union[str, Any]				=self._load_datasamples(1  )
								lowerCamelCase__	:	Optional[int]				=WhisperFeatureExtractor()
								lowerCamelCase__	:	Any				=feature_extractor(lowerCamelCase,						return_tensors='''pt'''  ).input_features
								self.assertEqual(input_features.shape,						(1, 80, 3000)  )
								self.assertTrue(torch.allclose(input_features[0, 0, :30],						lowerCamelCase,						atol=1E-4  )  )




					def 	snake_case ( self							:						Optional[Any]  )->      str:
								lowerCamelCase__	:	Optional[Any]				=self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()  )
								lowerCamelCase__	:	Optional[int]				=self._load_datasamples(1  )[0]
								lowerCamelCase__	:	Any				=((audio - audio.min()) / (audio.max() - audio.min())) * 6_5535  # Rescale to [0, 65535] to show issue
								lowerCamelCase__	:	Union[str, Any]				=feat_extract.zero_mean_unit_var_norm([audio],						attention_mask=lowerCamelCase  )[0]

								self.assertTrue(np.all(np.mean(lowerCamelCase  ) < 1E-3  )  )
								self.assertTrue(np.all(np.abs(np.var(lowerCamelCase  ) - 1  ) < 1E-3  )  )









"""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  __SCREAMING_SNAKE_CASE			:


					'''simple docstring'''





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



					def 	snake_case ( self							:						str  )->      Optional[int]:
								lowerCamelCase__	:	str				=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

								lowerCamelCase__	:	Tuple				=None
								if self.use_labels:
											lowerCamelCase__	:	Union[str, Any]				=ids_tensor([self.batch_size],						self.type_sequence_label_size  )

								lowerCamelCase__	:	int				=self.get_config()

								return config, pixel_values, labels



					def 	snake_case ( self							:						Union[str, Any]  )->      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 	snake_case ( self							:						Union[str, Any]  )->      Any:
								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 	snake_case ( self							:						int,						lowerCamelCase							:						str,						lowerCamelCase							:						List[str],						lowerCamelCase							:						List[Any]  )->      Tuple:
								lowerCamelCase__	:	List[str]				=UperNetForSemanticSegmentation(config=lowerCamelCase  )
								model.to(lowerCamelCase  )
								model.eval()
								lowerCamelCase__	:	int				=model(lowerCamelCase  )
								self.parent.assertEqual(
								    result.logits.shape,						(self.batch_size, self.num_labels, self.image_size, self.image_size)  )




					def 	snake_case ( self							:						Any  )->      Tuple:
								lowerCamelCase__	:	Dict				=self.prepare_config_and_inputs()
								(
								    (
								    lowerCamelCase__
								)			,     (
								    lowerCamelCase__
								)			,     (
								    lowerCamelCase__
								)			,     
								)	:	Any				=config_and_inputs
								lowerCamelCase__	:	Optional[int]				={'''pixel_values''': pixel_values}
								return config, inputs_dict





@require_torch
class  __SCREAMING_SNAKE_CASE			(   lowerCAmelCase_	,     lowerCAmelCase_	,     unittest.TestCase     ):


					'''simple docstring'''





					_a         =							(UperNetForSemanticSegmentation,) if is_torch_available() else ()
					_a         =							{'image-segmentation': UperNetForSemanticSegmentation} if is_torch_available() else {}
					_a         =							False
					_a         =							False
					_a         =							False
					_a         =							False
					_a         =							False
					_a         =							False



					def 	snake_case ( self							:						Optional[int]  )->      Optional[int]:
								lowerCamelCase__	:	Optional[Any]				=UperNetModelTester(self  )
								lowerCamelCase__	:	Union[str, Any]				=ConfigTester(self,						config_class=lowerCamelCase,						has_text_modality=lowerCamelCase,						hidden_size=37  )



					def 	snake_case ( self							:						Optional[int]  )->      Optional[int]:
								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 	snake_case ( self							:						List[str]  )->      Dict:
								return



					def 	snake_case ( self							:						Optional[int]  )->      List[str]:
								lowerCamelCase__			,     lowerCamelCase__	:	str				=self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
											lowerCamelCase__	:	Union[str, Any]				=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__	:	List[Any]				=['''pixel_values''']
											self.assertListEqual(arg_names[:1],						lowerCamelCase  )



					def 	snake_case ( self							:						Any  )->      Union[str, Any]:
								lowerCamelCase__	:	Dict				=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 	snake_case ( self							:						Optional[Any]  )->      List[Any]:
								pass



					@unittest.skip(reason='''UperNet does not support input and output embeddings'''  )
					def 	snake_case ( self							:						Any  )->      List[str]:
								pass



					@unittest.skip(reason='''UperNet does not have a base model'''  )
					def 	snake_case ( self							:						int  )->      Any:
								pass



					@unittest.skip(reason='''UperNet does not have a base model'''  )
					def 	snake_case ( self							:						Dict  )->      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 	snake_case ( self							:						List[Any]  )->      List[str]:
								pass



					@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''  )
					def 	snake_case ( self							:						Tuple  )->      str:
								pass



					def 	snake_case ( self							:						Optional[int]  )->      List[str]:
								def check_hidden_states_output(lowerCamelCase							:						Dict,						lowerCamelCase							:						int,						lowerCamelCase							:						List[str]  ):
											lowerCamelCase__	:	Union[str, Any]				=model_class(lowerCamelCase  )
											model.to(lowerCamelCase  )
											model.eval()

											with torch.no_grad():
														lowerCamelCase__	:	Optional[Any]				=model(**self._prepare_for_class(lowerCamelCase,						lowerCamelCase  )  )

											lowerCamelCase__	:	Optional[Any]				=outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

											lowerCamelCase__	:	List[str]				=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__	:	Dict				=self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
											lowerCamelCase__	:	Optional[int]				=True
											check_hidden_states_output(lowerCamelCase,						lowerCamelCase,						lowerCamelCase  )

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

											check_hidden_states_output(lowerCamelCase,						lowerCamelCase,						lowerCamelCase  )



					def 	snake_case ( self							:						Any  )->      List[Any]:
								lowerCamelCase__			,     lowerCamelCase__	:	Optional[int]				=self.model_tester.prepare_config_and_inputs_for_common()

								lowerCamelCase__	:	str				=_config_zero_init(lowerCamelCase  )
								lowerCamelCase__	:	Union[str, Any]				=_config_zero_init(configs_no_init.backbone_config  )
								for model_class in self.all_model_classes:
											lowerCamelCase__	:	Optional[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 	snake_case ( self							:						Any  )->      str:
								pass




					@slow
					def 	snake_case ( self							:						int  )->      Union[str, Any]:
								for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											lowerCamelCase__	:	str				=UperNetForSemanticSegmentation.from_pretrained(lowerCamelCase  )
											self.assertIsNotNone(lowerCamelCase  )






def   snake_case__     (	):
			"""simple docstring"""
			lowerCamelCase__	:	Optional[int]				=hf_hub_download(
			    repo_id='''hf-internal-testing/fixtures_ade20k'''							,	repo_type='''dataset'''							,	filename='''ADE_val_00000001.jpg'''			)
			lowerCamelCase__	:	List[str]				=Image.open(__lowerCamelCase			).convert('''RGB'''			)
			return image

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


					'''simple docstring'''





					def 	snake_case ( self							:						str  )->      Union[str, Any]:
								lowerCamelCase__	:	List[Any]				=AutoImageProcessor.from_pretrained('''openmmlab/upernet-swin-tiny'''  )
								lowerCamelCase__	:	List[Any]				=UperNetForSemanticSegmentation.from_pretrained('''openmmlab/upernet-swin-tiny'''  ).to(lowerCamelCase  )

								lowerCamelCase__	:	List[Any]				=prepare_img()
								lowerCamelCase__	:	List[Any]				=processor(images=lowerCamelCase,						return_tensors='''pt'''  ).to(lowerCamelCase  )

								with torch.no_grad():
											lowerCamelCase__	:	List[Any]				=model(**lowerCamelCase  )

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

								lowerCamelCase__	:	Dict				=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 	snake_case ( self							:						Optional[int]  )->      Optional[Any]:
								lowerCamelCase__	:	str				=AutoImageProcessor.from_pretrained('''openmmlab/upernet-convnext-tiny'''  )
								lowerCamelCase__	:	Tuple				=UperNetForSemanticSegmentation.from_pretrained('''openmmlab/upernet-convnext-tiny'''  ).to(lowerCamelCase  )

								lowerCamelCase__	:	Dict				=prepare_img()
								lowerCamelCase__	:	Any				=processor(images=lowerCamelCase,						return_tensors='''pt'''  ).to(lowerCamelCase  )

								with torch.no_grad():
											lowerCamelCase__	:	Any				=model(**lowerCamelCase  )

								lowerCamelCase__	:	Dict				=torch.Size((1, model.config.num_labels, 512, 512)  )
								self.assertEqual(outputs.logits.shape,						lowerCamelCase  )

								lowerCamelCase__	:	List[str]				=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  )  )




