



import argparse
import os

from transformers.utils import direct_transformers_import


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_task_guides.py
a_      :      List[Any]    =     '''src/transformers'''
a_      :      Any    =     '''docs/source/en/tasks'''






def     __a					(		__UpperCAmelCase							,  __UpperCAmelCase							,  __UpperCAmelCase       ):
 with open(SCREAMING_SNAKE_CASE_							,  '''r'''							,  encoding='''utf-8'''							,  newline='''\n'''       ) as f:
  a__												= f.readlines()
 # Find the start prompt.
 a__												= 0
 while not lines[start_index].startswith(SCREAMING_SNAKE_CASE_       ):
  start_index += 1
 start_index += 1

 a__												= start_index
 while not lines[end_index].startswith(SCREAMING_SNAKE_CASE_       ):
  end_index += 1
 end_index -= 1

 while len(lines[start_index]       ) <= 1:
  start_index += 1
 while len(lines[end_index]       ) <= 1:
  end_index -= 1
 end_index += 1
 return "".join(lines[start_index:end_index]       ), start_index, end_index, lines


# This is to make sure the transformers module imported is the one in the repo.
a_      :      Tuple    =     direct_transformers_import(TRANSFORMERS_PATH)

a_      :      Optional[Any]    =     {
    '''asr.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_CTC_MAPPING_NAMES,
    '''audio_classification.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES,
    '''language_modeling.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,
    '''image_classification.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES,
    '''masked_language_modeling.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_MASKED_LM_MAPPING_NAMES,
    '''multiple_choice.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES,
    '''object_detection.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES,
    '''question_answering.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES,
    '''semantic_segmentation.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES,
    '''sequence_classification.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES,
    '''summarization.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,
    '''token_classification.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES,
    '''translation.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,
    '''video_classification.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES,
    '''document_question_answering.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES,
    '''monocular_depth_estimation.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES,
}

# This list contains model types used in some task guides that are not in `CONFIG_MAPPING_NAMES` (therefore not in any
# `MODEL_MAPPING_NAMES` or any `MODEL_FOR_XXX_MAPPING_NAMES`).
a_      :      int    =     {
    '''summarization.md''': ('''nllb''',),
    '''translation.md''': ('''nllb''',),
}






def     __a					(		__UpperCAmelCase       ):
 a__												= TASK_GUIDE_TO_MODELS[task_guide]
 a__												= SPECIAL_TASK_GUIDE_TO_MODEL_TYPES.get(SCREAMING_SNAKE_CASE_							,  set()       )
 a__												= {
     code: name
     for code, name in transformers_module.MODEL_NAMES_MAPPING.items()
     if (code in model_maping_names or code in special_model_types)
 }
 return ", ".join([f"[{name}](../model_doc/{code})" for code, name in model_names.items()]       ) + "\n"






def     __a					(		__UpperCAmelCase							,  __UpperCAmelCase=False       ):
 a__							,			a__							,			a__							,			a__												= _find_text_in_file(
     filename=os.path.join(SCREAMING_SNAKE_CASE_							,  SCREAMING_SNAKE_CASE_       )							,  start_prompt='''<!--This tip is automatically generated by `make fix-copies`, do not fill manually!-->'''							,  end_prompt='''<!--End of the generated tip-->'''							,  )

 a__												= get_model_list_for_task(SCREAMING_SNAKE_CASE_       )

 if current_list != new_list:
  if overwrite:
   with open(os.path.join(SCREAMING_SNAKE_CASE_							,  SCREAMING_SNAKE_CASE_       )							,  '''w'''							,  encoding='''utf-8'''							,  newline='''\n'''       ) as f:
    f.writelines(lines[:start_index] + [new_list] + lines[end_index:]       )
  else:
   raise ValueError(
       f"The list of models that can be used in the {task_guide} guide needs an update. Run `make fix-copies`"
       ''' to fix this.'''       )


if __name__ == "__main__":
     a_      :      Optional[int]    =     argparse.ArgumentParser()
     parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.')
     a_      :      Dict    =     parser.parse_args()

     for task_guide in TASK_GUIDE_TO_MODELS.keys():
          check_model_list_for_task(task_guide, args.fix_and_overwrite)







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  )  )