"""simple docstring"""




import argparse
import json
import os

import fairseq
import torch
from fairseq.data import Dictionary

from transformers import (
    WavaVecaConfig,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaForCTC,
    WavaVecaForPreTraining,
    WavaVecaProcessor,
    logging,
)
from transformers.models.wavaveca.modeling_wavaveca import WavaVecaForSequenceClassification


logging.set_verbosity_info()
__lowerCamelCase							 =     logging.get_logger(__name__)

__lowerCamelCase							 =     {
    "post_extract_proj": "feature_projection.projection",
    "encoder.pos_conv.0": "encoder.pos_conv_embed.conv",
    "self_attn.k_proj": "encoder.layers.*.attention.k_proj",
    "self_attn.v_proj": "encoder.layers.*.attention.v_proj",
    "self_attn.q_proj": "encoder.layers.*.attention.q_proj",
    "self_attn.out_proj": "encoder.layers.*.attention.out_proj",
    "self_attn_layer_norm": "encoder.layers.*.layer_norm",
    "fc1": "encoder.layers.*.feed_forward.intermediate_dense",
    "fc2": "encoder.layers.*.feed_forward.output_dense",
    "final_layer_norm": "encoder.layers.*.final_layer_norm",
    "encoder.layer_norm": "encoder.layer_norm",
    "adapter_layer": "encoder.layers.*.adapter_layer",
    "w2v_model.layer_norm": "feature_projection.layer_norm",
    "quantizer.weight_proj": "quantizer.weight_proj",
    "quantizer.vars": "quantizer.codevectors",
    "project_q": "project_q",
    "final_proj": "project_hid",
    "w2v_encoder.proj": "lm_head",
    "mask_emb": "masked_spec_embed",
    "pooling_layer.linear": "projector",
    "pooling_layer.projection": "classifier",
}
__lowerCamelCase							 =     [
    "lm_head",
    "quantizer.weight_proj",
    "quantizer.codevectors",
    "project_q",
    "project_hid",
    "projector",
    "classifier",
]






def      UpperCAmelCase    (		UpperCamelCase__ ):






							"""simple docstring"""





							A__		   =							{}
							with open(UpperCamelCase__				,			'r' ) as file:
														for line_number, line in enumerate(UpperCamelCase__ ):
																					A__		   =							line.strip()
																					if line:
																												A__		   =							line.split()
																												A__		   =							line_number
																												A__		   =							words[0]
																												A__		   =							value
							return result






def      UpperCAmelCase    (		UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__ ):






							"""simple docstring"""





							for attribute in key.split('.' ):
														A__		   =							getattr(UpperCamelCase__				,			UpperCamelCase__ )

							A__		   =							None
							for param_key in PARAM_MAPPING.keys():
														if full_name.endswith(UpperCamelCase__ ):
																					A__		   =							PARAM_MAPPING[full_name.split('.' )[-1]]
																					A__		   =							'param'

							if weight_type is not None and weight_type != "param":
														A__		   =							getattr(UpperCamelCase__				,			UpperCamelCase__ ).shape
							elif weight_type is not None and weight_type == "param":
														A__		   =							hf_pointer
														for attribute in hf_param_name.split('.' ):
																					A__		   =							getattr(UpperCamelCase__				,			UpperCamelCase__ )
														A__		   =							shape_pointer.shape

														# let's reduce dimension
														A__		   =							value[0]
							else:
														A__		   =							hf_pointer.shape

							if hf_shape != value.shape:
														raise ValueError(
														    F'''Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be'''
														    F''' {value.shape} for {full_name}''' )

							if weight_type == "weight":
														A__		   =							value
							elif weight_type == "weight_g":
														A__		   =							value
							elif weight_type == "weight_v":
														A__		   =							value
							elif weight_type == "bias":
														A__		   =							value
							elif weight_type == "param":
														for attribute in hf_param_name.split('.' ):
																					A__		   =							getattr(UpperCamelCase__				,			UpperCamelCase__ )
														A__		   =							value
							else:
														A__		   =							value

							logger.info(F'''{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.''' )






def      UpperCAmelCase    (		UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__ ):






							"""simple docstring"""





							A__		   =							None
							for param_key in PARAM_MAPPING.keys():
														if full_name.endswith(UpperCamelCase__ ):
																					A__		   =							PARAM_MAPPING[full_name.split('.' )[-1]]
																					A__		   =							'param'

							if weight_type is not None and weight_type != "param":
														A__		   =							'.'.join([key, weight_type] )
							elif weight_type is not None and weight_type == "param":
														A__		   =							'.'.join([key, hf_param_name] )
							else:
														A__		   =							key

							A__		   =							value if 'lm_head' in full_key else value[0]


__lowerCamelCase							 =     {
    "W_a": "linear_1.weight",
    "W_b": "linear_2.weight",
    "b_a": "linear_1.bias",
    "b_b": "linear_2.bias",
    "ln_W": "norm.weight",
    "ln_b": "norm.bias",
}






def      UpperCAmelCase    (		UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__=None				,			UpperCamelCase__=None ):






							"""simple docstring"""





							A__		   =							False
							for key, mapped_key in MAPPING.items():
														A__		   =							'wav2vec2.' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key
														if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]:
																					A__		   =							True
																					if "*" in mapped_key:
																												A__		   =							name.split(UpperCamelCase__ )[0].split('.' )[-2]
																												A__		   =							mapped_key.replace('*'				,			UpperCamelCase__ )
																					if "weight_g" in name:
																												A__		   =							'weight_g'
																					elif "weight_v" in name:
																												A__		   =							'weight_v'
																					elif "bias" in name:
																												A__		   =							'bias'
																					elif "weight" in name:
																												# TODO: don't match quantizer.weight_proj
																												A__		   =							'weight'
																					else:
																												A__		   =							None
																					if hf_dict is not None:
																												rename_dict(UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__ )
																					else:
																												set_recursively(UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__ )
																					return is_used
							return is_used






def      UpperCAmelCase    (		UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__ ):






							"""simple docstring"""





							A__		   =							[]
							A__		   =							fairseq_model.state_dict()

							A__		   =							hf_model.wavaveca.feature_extractor

							for name, value in fairseq_dict.items():
														A__		   =							False
														if "conv_layers" in name:
																					load_conv_layer(
																					    UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			hf_model.config.feat_extract_norm == 'group'				,			)
																					A__		   =							True
														else:
																					A__		   =							load_wavaveca_layer(UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__ )
														if not is_used:
																					unused_weights.append(UpperCamelCase__ )

							logger.warning(F'''Unused weights: {unused_weights}''' )






def      UpperCAmelCase    (		UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__ ):






							"""simple docstring"""





							A__		   =							full_name.split('conv_layers.' )[-1]
							A__		   =							name.split('.' )
							A__		   =							int(items[0] )
							A__		   =							int(items[1] )

							if type_id == 0:
														if "bias" in name:
																					if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape:
																												raise ValueError(
																												    F'''{full_name} has size {value.shape}, but'''
																												    F''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' )
																					A__		   =							value
																					logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' )
														elif "weight" in name:
																					if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape:
																												raise ValueError(
																												    F'''{full_name} has size {value.shape}, but'''
																												    F''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' )
																					A__		   =							value
																					logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' )
							elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
														if "bias" in name:
																					if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape:
																												raise ValueError(
																												    F'''{full_name} has size {value.shape}, but'''
																												    F''' {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.''' )
																					A__		   =							value
																					logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' )
														elif "weight" in name:
																					if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape:
																												raise ValueError(
																												    F'''{full_name} has size {value.shape}, but'''
																												    F''' {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.''' )
																					A__		   =							value
																					logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' )
							else:
														unused_weights.append(UpperCamelCase__ )






@torch.no_grad()
def      UpperCAmelCase    (		UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__=None				,			UpperCamelCase__=None				,			UpperCamelCase__=True				,			UpperCamelCase__=False ):






							"""simple docstring"""





							if config_path is not None:
														A__		   =							WavaVecaConfig.from_pretrained(UpperCamelCase__ )
							else:
														A__		   =							WavaVecaConfig()

							if is_seq_class:
														A__		   =							read_txt_into_dict(UpperCamelCase__ )
														A__		   =							idalabel
														A__		   =							WavaVecaForSequenceClassification(UpperCamelCase__ )
														A__		   =							WavaVecaFeatureExtractor(
														    feature_size=1				,			sampling_rate=16_000				,			padding_value=0				,			do_normalize=UpperCamelCase__				,			return_attention_mask=UpperCamelCase__				,			)
														feature_extractor.save_pretrained(UpperCamelCase__ )

							elif is_finetuned:
														if dict_path:
																					A__		   =							Dictionary.load(UpperCamelCase__ )

																					# important change bos & pad token id since CTC symbol is <pad> and
																					# not <s> as in fairseq
																					A__		   =							target_dict.pad_index
																					A__		   =							target_dict.bos_index
																					A__		   =							target_dict.eos_index
																					A__		   =							len(target_dict.symbols )
																					A__		   =							os.path.join(UpperCamelCase__				,			'vocab.json' )
																					if not os.path.isdir(UpperCamelCase__ ):
																												logger.error('--pytorch_dump_folder_path ({}) should be a directory'.format(UpperCamelCase__ ) )
																												return
																					os.makedirs(UpperCamelCase__				,			exist_ok=UpperCamelCase__ )
																					A__		   =							target_dict.indices

																					# fairseq has the <pad> and <s> switched
																					A__		   =							0
																					A__		   =							1
																					with open(UpperCamelCase__				,			'w'				,			encoding='utf-8' ) as vocab_handle:
																												json.dump(UpperCamelCase__				,			UpperCamelCase__ )
																					A__		   =							WavaVecaCTCTokenizer(
																					    UpperCamelCase__				,			unk_token=target_dict.unk_word				,			pad_token=target_dict.pad_word				,			bos_token=target_dict.bos_word				,			eos_token=target_dict.eos_word				,			word_delimiter_token='|'				,			do_lower_case=UpperCamelCase__				,			)
																					A__		   =							True if config.feat_extract_norm == 'layer' else False
																					A__		   =							WavaVecaFeatureExtractor(
																					    feature_size=1				,			sampling_rate=16_000				,			padding_value=0				,			do_normalize=UpperCamelCase__				,			return_attention_mask=UpperCamelCase__				,			)
																					A__		   =							WavaVecaProcessor(feature_extractor=UpperCamelCase__				,			tokenizer=UpperCamelCase__ )
																					processor.save_pretrained(UpperCamelCase__ )

														A__		   =							WavaVecaForCTC(UpperCamelCase__ )
							else:
														A__		   =							WavaVecaForPreTraining(UpperCamelCase__ )

							if is_finetuned or is_seq_class:
														A__   ,     A__   ,     A__		   =							fairseq.checkpoint_utils.load_model_ensemble_and_task(
														    [checkpoint_path]				,			arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} )
							else:
														A__		   =							argparse.Namespace(task='audio_pretraining' )
														A__		   =							fairseq.tasks.setup_task(UpperCamelCase__ )

														A__   ,     A__   ,     A__		   =							fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path]				,			task=UpperCamelCase__ )

							A__		   =							model[0].eval()

							recursively_load_weights(UpperCamelCase__				,			UpperCamelCase__				,			not is_finetuned )

							hf_wavavec.save_pretrained(UpperCamelCase__ )


if __name__ == "__main__":
				__lowerCamelCase							 =     argparse.ArgumentParser()
				parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
				parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint")
				parser.add_argument("--dict_path", default=None, type=str, help="Path to dict of fine-tuned model")
				parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert")
				parser.add_argument(
				    "--not_finetuned", action="store_true", help="Whether the model to convert is a fine-tuned model or not"
				)
				parser.add_argument(
				    "--is_seq_class",
				    action="store_true",
				    help="Whether the model to convert is a fine-tuned sequence classification model or not",
				)
				__lowerCamelCase							 =     parser.parse_args()

				__lowerCamelCase							 =     not args.not_finetuned and not args.is_seq_class
				convert_wavaveca_checkpoint(
				    args.checkpoint_path,
				    args.pytorch_dump_folder_path,
				    args.config_path,
				    args.dict_path,
				    is_finetuned,
				    args.is_seq_class,
				)






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





						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.0_2						,__UpperCAmelCase=["stage2", "stage3", "stage4"]						,__UpperCAmelCase=3						,__UpperCAmelCase=None						,)    -> Optional[int]:
													A__		   =							parent
													A__		   =							batch_size
													A__		   =							image_size
													A__		   =							num_channels
													A__		   =							num_stages
													A__		   =							hidden_sizes
													A__		   =							depths
													A__		   =							is_training
													A__		   =							use_labels
													A__		   =							intermediate_size
													A__		   =							hidden_act
													A__		   =							type_sequence_label_size
													A__		   =							initializer_range
													A__		   =							out_features
													A__		   =							num_labels
													A__		   =							scope
													A__		   =							num_stages





						def  snake_case__		(				self   )    -> List[Any]:
													A__		   =							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

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

													A__		   =							self.get_config()

													return config, pixel_values, labels





						def  snake_case__		(				self   )    -> str:
													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   )    -> Tuple:
													return UperNetConfig(
													    backbone_config=self.get_backbone_config()						,hidden_size=5_12						,pool_scales=[1, 2, 3, 6]						,use_auxiliary_head=__UpperCAmelCase						,auxiliary_loss_weight=0.4						,auxiliary_in_channels=40						,auxiliary_channels=2_56						,auxiliary_num_convs=1						,auxiliary_concat_input=__UpperCAmelCase						,loss_ignore_index=2_55						,num_labels=self.num_labels						,)





						def  snake_case__		(				self						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase   )    -> Dict:
													A__		   =							UperNetForSemanticSegmentation(config=__UpperCAmelCase   )
													model.to(__UpperCAmelCase   )
													model.eval()
													A__		   =							model(__UpperCAmelCase   )
													self.parent.assertEqual(
													    result.logits.shape						,(self.batch_size, self.num_labels, self.image_size, self.image_size)   )





						def  snake_case__		(				self   )    -> str:
													A__		   =							self.prepare_config_and_inputs()
													(
													    (
													    A__
													)   ,     (
													    A__
													)   ,     (
													    A__
													)   ,     
													)		   =							config_and_inputs
													A__		   =							{'pixel_values': pixel_values}
													return config, inputs_dict






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





						def  snake_case__		(				self   )    -> Union[str, Any]:
													A__		   =							UperNetModelTester(self   )
													A__		   =							ConfigTester(self						,config_class=__UpperCAmelCase						,has_text_modality=__UpperCAmelCase						,hidden_size=37   )





						def  snake_case__		(				self   )    -> List[Any]:
													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   )    -> int:
													return





						def  snake_case__		(				self   )    -> List[Any]:
													A__   ,     A__		   =							self.model_tester.prepare_config_and_inputs_for_common()

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

																				A__		   =							['pixel_values']
																				self.assertListEqual(arg_names[:1]						,__UpperCAmelCase   )





						def  snake_case__		(				self   )    -> Tuple:
													A__		   =							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  snake_case__		(				self   )    -> Optional[int]:
													pass





						@unittest.skip(reason='UperNet does not support input and output embeddings'   )
						def  snake_case__		(				self   )    -> Tuple:
													pass





						@unittest.skip(reason='UperNet does not have a base model'   )
						def  snake_case__		(				self   )    -> List[Any]:
													pass





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





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





						def  snake_case__		(				self   )    -> Optional[int]:
													def check_hidden_states_output(__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase   ):
																				A__		   =							model_class(__UpperCAmelCase   )
																				model.to(__UpperCAmelCase   )
																				model.eval()

																				with torch.no_grad():
																											A__		   =							model(**self._prepare_for_class(__UpperCAmelCase						,__UpperCAmelCase   )   )

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

																				A__		   =							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]						,)

													A__   ,     A__		   =							self.model_tester.prepare_config_and_inputs_for_common()

													for model_class in self.all_model_classes:
																				A__		   =							True
																				check_hidden_states_output(__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase   )

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

																				check_hidden_states_output(__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase   )





						def  snake_case__		(				self   )    -> Optional[Any]:
													A__   ,     A__		   =							self.model_tester.prepare_config_and_inputs_for_common()

													A__		   =							_config_zero_init(__UpperCAmelCase   )
													A__		   =							_config_zero_init(configs_no_init.backbone_config   )
													for model_class in self.all_model_classes:
																				A__		   =							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  snake_case__		(				self   )    -> str:
													pass





						@slow
						def  snake_case__		(				self   )    -> List[str]:
													for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																				A__		   =							UperNetForSemanticSegmentation.from_pretrained(__UpperCAmelCase   )
																				self.assertIsNotNone(__UpperCAmelCase   )






def      UpperCAmelCase    (		):






							"""simple docstring"""





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


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





						def  snake_case__		(				self   )    -> Dict:
													A__		   =							AutoImageProcessor.from_pretrained('openmmlab/upernet-swin-tiny'   )
													A__		   =							UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-swin-tiny'   ).to(__UpperCAmelCase   )

													A__		   =							prepare_img()
													A__		   =							processor(images=__UpperCAmelCase						,return_tensors='pt'   ).to(__UpperCAmelCase   )

													with torch.no_grad():
																				A__		   =							model(**__UpperCAmelCase   )

													A__		   =							torch.Size((1, model.config.num_labels, 5_12, 5_12)   )
													self.assertEqual(outputs.logits.shape						,__UpperCAmelCase   )

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





						def  snake_case__		(				self   )    -> str:
													A__		   =							AutoImageProcessor.from_pretrained('openmmlab/upernet-convnext-tiny'   )
													A__		   =							UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-convnext-tiny'   ).to(__UpperCAmelCase   )

													A__		   =							prepare_img()
													A__		   =							processor(images=__UpperCAmelCase						,return_tensors='pt'   ).to(__UpperCAmelCase   )

													with torch.no_grad():
																				A__		   =							model(**__UpperCAmelCase   )

													A__		   =							torch.Size((1, model.config.num_labels, 5_12, 5_12)   )
													self.assertEqual(outputs.logits.shape						,__UpperCAmelCase   )

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





