





'''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  _A :

		def __init__(   self					:   List[Any]  ,      __magic_name__					:   Dict  ,      __magic_name__					:   Optional[Any]=13  ,      __magic_name__					:   Optional[Any]=32  ,      __magic_name__					:   Tuple=3  ,      __magic_name__					:   Union[str, Any]=4  ,      __magic_name__					:   Dict=[10, 20, 30, 40]  ,      __magic_name__					:   str=[2, 2, 3, 2]  ,      __magic_name__					:   Tuple=True  ,      __magic_name__					:   Any=True  ,      __magic_name__					:   Tuple=37  ,      __magic_name__					:   int="gelu"  ,      __magic_name__					:   Union[str, Any]=10  ,      __magic_name__					:   Optional[int]=0.02  ,      __magic_name__					:   int=["stage2", "stage3", "stage4"]  ,      __magic_name__					:   Optional[Any]=3  ,      __magic_name__					:   Dict=None  ,      )					->    Tuple:


					"""simple docstring"""

					__snake_case					:      str							      =     parent
					__snake_case					:      List[Any]							      =     batch_size
					__snake_case					:      Any							      =     image_size
					__snake_case					:      int							      =     num_channels
					__snake_case					:      List[Any]							      =     num_stages
					__snake_case					:      Union[str, Any]							      =     hidden_sizes
					__snake_case					:      Dict							      =     depths
					__snake_case					:      Optional[int]							      =     is_training
					__snake_case					:      Any							      =     use_labels
					__snake_case					:      Union[str, Any]							      =     intermediate_size
					__snake_case					:      str							      =     hidden_act
					__snake_case					:      Dict							      =     type_sequence_label_size
					__snake_case					:      Any							      =     initializer_range
					__snake_case					:      str							      =     out_features
					__snake_case					:      str							      =     num_labels
					__snake_case					:      Dict							      =     scope
					__snake_case					:      Optional[int]							      =     num_stages

		def 	lowercase__     (   self					:   Any			)					->    Optional[Any]:


					"""simple docstring"""

					__snake_case					:      List[str]							      =     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

					__snake_case					:      Optional[int]							      =     None
					if self.use_labels:
								__snake_case					:      str							      =     ids_tensor([self.batch_size]  ,      self.type_sequence_label_size			)

					__snake_case					:      Optional[int]							      =     self.get_config()

					return config, pixel_values, labels

		def 	lowercase__     (   self					:   Optional[int]			)					->    Dict:


					"""simple docstring"""

					return ConvNextConfig(
					    num_channels=self.num_channels  ,      num_stages=self.num_stages  ,      hidden_sizes=self.hidden_sizes  ,      depths=self.depths  ,      is_training=self.is_training  ,      intermediate_size=self.intermediate_size  ,      hidden_act=self.hidden_act  ,      out_features=self.out_features  ,      )

		def 	lowercase__     (   self					:   int			)					->    int:


					"""simple docstring"""

					return UperNetConfig(
					    backbone_config=self.get_backbone_config()  ,      hidden_size=5_12  ,      pool_scales=[1, 2, 3, 6]  ,      use_auxiliary_head=__magic_name__  ,      auxiliary_loss_weight=0.4  ,      auxiliary_in_channels=40  ,      auxiliary_channels=2_56  ,      auxiliary_num_convs=1  ,      auxiliary_concat_input=__magic_name__  ,      loss_ignore_index=2_55  ,      num_labels=self.num_labels  ,      )

		def 	lowercase__     (   self					:   Optional[Any]  ,      __magic_name__					:   Tuple  ,      __magic_name__					:   Any  ,      __magic_name__					:   List[str]			)					->    Optional[int]:


					"""simple docstring"""

					__snake_case					:      Optional[Any]							      =     UperNetForSemanticSegmentation(config=__magic_name__			)
					model.to(__magic_name__			)
					model.eval()
					__snake_case					:      int							      =     model(__magic_name__			)
					self.parent.assertEqual(
					    result.logits.shape  ,      (self.batch_size, self.num_labels, self.image_size, self.image_size)			)

		def 	lowercase__     (   self					:   List[str]			)					->    Any:


					"""simple docstring"""

					__snake_case					:      Tuple							      =     self.prepare_config_and_inputs()
					(
					    (
					    __snake_case
					)      ,     (
					    __snake_case
					)      ,     (
					    __snake_case
					)      ,     
					)					:      List[str]							      =     config_and_inputs
					__snake_case					:      int							      =     {"""pixel_values""": pixel_values}
					return config, inputs_dict





@require_torch
class  _A (					__lowercase						,					__lowercase						,					unittest.TestCase		):
		lowercase__:   int				     =   (UperNetForSemanticSegmentation,) if is_torch_available() else ()
		lowercase__:   Dict				     =   {'''image-segmentation''': UperNetForSemanticSegmentation} if is_torch_available() else {}
		lowercase__:   int				     =   False
		lowercase__:   str				     =   False
		lowercase__:   Optional[Any]				     =   False
		lowercase__:   List[str]				     =   False
		lowercase__:   str				     =   False
		lowercase__:   str				     =   False

		def 	lowercase__     (   self					:   Optional[int]			)					->    Optional[int]:


					"""simple docstring"""

					__snake_case					:      Optional[Any]							      =     UperNetModelTester(self			)
					__snake_case					:      Union[str, Any]							      =     ConfigTester(self  ,      config_class=__magic_name__  ,      has_text_modality=__magic_name__  ,      hidden_size=37			)

		def 	lowercase__     (   self					:   Optional[Any]			)					->    Optional[int]:


					"""simple docstring"""

					self.create_and_test_config_common_properties()
					self.config_tester.create_and_test_config_to_json_string()
					self.config_tester.create_and_test_config_to_json_file()
					self.config_tester.create_and_test_config_from_and_save_pretrained()
					self.config_tester.create_and_test_config_with_num_labels()
					self.config_tester.check_config_can_be_init_without_params()
					self.config_tester.check_config_arguments_init()

		def 	lowercase__     (   self					:   Union[str, Any]			)					->    Optional[Any]:


					"""simple docstring"""

					return

		def 	lowercase__     (   self					:   Tuple			)					->    Dict:


					"""simple docstring"""

					__snake_case      ,     __snake_case					:      Optional[Any]							      =     self.model_tester.prepare_config_and_inputs_for_common()

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

								__snake_case					:      str							      =     ["""pixel_values"""]
								self.assertListEqual(arg_names[:1]  ,      __magic_name__			)

		def 	lowercase__     (   self					:   List[Any]			)					->    Optional[Any]:


					"""simple docstring"""

					__snake_case					:      Optional[Any]							      =     self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_semantic_segmentation(*__magic_name__			)

		@unittest.skip(reason="""UperNet does not use inputs_embeds"""			)
		def 	lowercase__     (   self					:   List[str]			)					->    Optional[int]:


					"""simple docstring"""

					pass

		@unittest.skip(reason="""UperNet does not support input and output embeddings"""			)
		def 	lowercase__     (   self					:   Union[str, Any]			)					->    List[str]:


					"""simple docstring"""

					pass

		@unittest.skip(reason="""UperNet does not have a base model"""			)
		def 	lowercase__     (   self					:   Tuple			)					->    Optional[Any]:


					"""simple docstring"""

					pass

		@unittest.skip(reason="""UperNet does not have a base model"""			)
		def 	lowercase__     (   self					:   int			)					->    int:


					"""simple docstring"""

					pass

		@require_torch_multi_gpu
		@unittest.skip(reason="""UperNet has some layers using `add_module` which doesn't work well with `nn.DataParallel`"""			)
		def 	lowercase__     (   self					:   Optional[Any]			)					->    List[str]:


					"""simple docstring"""

					pass

		@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""			)
		def 	lowercase__     (   self					:   List[str]			)					->    List[Any]:


					"""simple docstring"""

					pass

		def 	lowercase__     (   self					:   List[Any]			)					->    List[Any]:


					"""simple docstring"""

					def check_hidden_states_output(__magic_name__					:   Dict  ,      __magic_name__					:   int  ,      __magic_name__					:   Any			):
								__snake_case					:      Dict							      =     model_class(__magic_name__			)
								model.to(__magic_name__			)
								model.eval()

								with torch.no_grad():
											__snake_case					:      Union[str, Any]							      =     model(**self._prepare_for_class(__magic_name__  ,      __magic_name__			)			)

								__snake_case					:      int							      =     outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

								__snake_case					:      Optional[Any]							      =     self.model_tester.num_stages
								self.assertEqual(len(__magic_name__			)  ,      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]  ,      )

					__snake_case      ,     __snake_case					:      str							      =     self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
								__snake_case					:      List[str]							      =     True
								check_hidden_states_output(__magic_name__  ,      __magic_name__  ,      __magic_name__			)

								# check that output_hidden_states also work using config
								del inputs_dict["output_hidden_states"]
								__snake_case					:      Tuple							      =     True

								check_hidden_states_output(__magic_name__  ,      __magic_name__  ,      __magic_name__			)

		def 	lowercase__     (   self					:   Optional[Any]			)					->    Optional[Any]:


					"""simple docstring"""

					__snake_case      ,     __snake_case					:      Dict							      =     self.model_tester.prepare_config_and_inputs_for_common()

					__snake_case					:      Any							      =     _config_zero_init(__magic_name__			)
					__snake_case					:      Union[str, Any]							      =     _config_zero_init(configs_no_init.backbone_config			)
					for model_class in self.all_model_classes:
								__snake_case					:      Optional[int]							      =     model_class(config=__magic_name__			)
								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 	lowercase__     (   self					:   List[str]			)					->    Optional[Any]:


					"""simple docstring"""

					pass

		@slow
		def 	lowercase__     (   self					:   List[str]			)					->    int:


					"""simple docstring"""

					for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
								__snake_case					:      List[str]							      =     UperNetForSemanticSegmentation.from_pretrained(__magic_name__			)
								self.assertIsNotNone(__magic_name__			)







def 					_a						(       ) ->				Any:



			"""simple docstring"""


			__snake_case					:      Dict							      =     hf_hub_download(
			    repo_id="""hf-internal-testing/fixtures_ade20k"""    ,	repo_type="""dataset"""    ,	filename="""ADE_val_00000001.jpg""" )
			__snake_case					:      List[str]							      =     Image.open(_lowerCamelCase ).convert("""RGB""" )
			return image




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

		def 	lowercase__     (   self					:   List[str]			)					->    Optional[int]:


					"""simple docstring"""

					__snake_case					:      Union[str, Any]							      =     AutoImageProcessor.from_pretrained("""openmmlab/upernet-swin-tiny"""			)
					__snake_case					:      int							      =     UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-swin-tiny"""			).to(__magic_name__			)

					__snake_case					:      Tuple							      =     prepare_img()
					__snake_case					:      int							      =     processor(images=__magic_name__  ,      return_tensors="""pt"""			).to(__magic_name__			)

					with torch.no_grad():
								__snake_case					:      Union[str, Any]							      =     model(**__magic_name__			)

					__snake_case					:      str							      =     torch.Size((1, model.config.num_labels, 5_12, 5_12)			)
					self.assertEqual(outputs.logits.shape  ,      __magic_name__			)

					__snake_case					:      List[str]							      =     torch.tensor(
					    [[-7.5958, -7.5958, -7.4302], [-7.5958, -7.5958, -7.4302], [-7.4797, -7.4797, -7.3068]]			).to(__magic_name__			)
					self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]  ,      __magic_name__  ,      atol=1E-4			)			)

		def 	lowercase__     (   self					:   Optional[int]			)					->    str:


					"""simple docstring"""

					__snake_case					:      str							      =     AutoImageProcessor.from_pretrained("""openmmlab/upernet-convnext-tiny"""			)
					__snake_case					:      Any							      =     UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-convnext-tiny"""			).to(__magic_name__			)

					__snake_case					:      Union[str, Any]							      =     prepare_img()
					__snake_case					:      Optional[int]							      =     processor(images=__magic_name__  ,      return_tensors="""pt"""			).to(__magic_name__			)

					with torch.no_grad():
								__snake_case					:      int							      =     model(**__magic_name__			)

					__snake_case					:      Optional[Any]							      =     torch.Size((1, model.config.num_labels, 5_12, 5_12)			)
					self.assertEqual(outputs.logits.shape  ,      __magic_name__			)

					__snake_case					:      str							      =     torch.tensor(
					    [[-8.8110, -8.8110, -8.6521], [-8.8110, -8.8110, -8.6521], [-8.7746, -8.7746, -8.6130]]			).to(__magic_name__			)
					self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]  ,      __magic_name__  ,      atol=1E-4			)			)









'''simple docstring'''






import doctest
import logging
import os
import unittest
from pathlib import Path
from typing import List, Union

import transformers
from transformers.testing_utils import require_tf, require_torch, slow


__UpperCamelCase					    =	logging.getLogger()




@unittest.skip('''Temporarily disable the doc tests.'''		)
@require_torch
@require_tf
@slow
class  _A (					unittest.TestCase		):

		def 	lowercase__     (   self					:   Optional[int]  ,      __magic_name__					:   Path  ,      __magic_name__					:   Union[str, None] = None  ,      __magic_name__					:   Union[List[str], None] = None  ,      __magic_name__					:   Union[str, List[str], None] = None  ,      __magic_name__					:   bool = True  ,      )					->    Optional[int]:


					"""simple docstring"""

					__snake_case					:      Union[str, Any]							      =     [file for file in os.listdir(__magic_name__			) if os.path.isfile(os.path.join(__magic_name__  ,      __magic_name__			)			)]

					if identifier is not None:
								__snake_case					:      List[Any]							      =     [file for file in files if identifier in file]

					if n_identifier is not None:
								if isinstance(__magic_name__  ,      __magic_name__			):
											for n_ in n_identifier:
														__snake_case					:      Optional[int]							      =     [file for file in files if n_ not in file]
								else:
											__snake_case					:      Tuple							      =     [file for file in files if n_identifier not in file]

					__snake_case					:      Dict							      =     ignore_files or []
					ignore_files.append("""__init__.py"""			)
					__snake_case					:      List[str]							      =     [file for file in files if file not in ignore_files]

					for file in files:
								# Open all files
								print("""Testing"""  ,      __magic_name__			)

								if only_modules:
											__snake_case					:      List[Any]							      =     file.split("""."""			)[0]
											try:
														__snake_case					:      List[Any]							      =     getattr(__magic_name__  ,      __magic_name__			)
														__snake_case					:      Union[str, Any]							      =     doctest.DocTestSuite(__magic_name__			)
														__snake_case					:      Dict							      =     unittest.TextTestRunner().run(__magic_name__			)
														self.assertIs(len(result.failures			)  ,      0			)
											except AttributeError:
														logger.info(f'''{module_identifier} is not a module.'''			)
								else:
											__snake_case					:      Tuple							      =     doctest.testfile(str("""..""" / directory / file			)  ,      optionflags=doctest.ELLIPSIS			)
											self.assertIs(result.failed  ,      0			)

		def 	lowercase__     (   self					:   Union[str, Any]			)					->    Any:


					"""simple docstring"""

					__snake_case					:      List[Any]							      =     Path("""src/transformers"""			)
					__snake_case					:      List[Any]							      =     """modeling"""
					__snake_case					:      Union[str, Any]							      =     [
					    """modeling_ctrl.py""",
					    """modeling_tf_ctrl.py""",
					]
					self.analyze_directory(__magic_name__  ,      identifier=__magic_name__  ,      ignore_files=__magic_name__			)

		def 	lowercase__     (   self					:   Union[str, Any]			)					->    int:


					"""simple docstring"""

					__snake_case					:      Union[str, Any]							      =     Path("""src/transformers"""			)
					__snake_case					:      Any							      =     """tokenization"""
					self.analyze_directory(__magic_name__  ,      identifier=__magic_name__			)

		def 	lowercase__     (   self					:   Union[str, Any]			)					->    int:


					"""simple docstring"""

					__snake_case					:      List[Any]							      =     Path("""src/transformers"""			)
					__snake_case					:      List[str]							      =     """configuration"""
					self.analyze_directory(__magic_name__  ,      identifier=__magic_name__			)

		def 	lowercase__     (   self					:   Dict			)					->    Dict:


					"""simple docstring"""

					__snake_case					:      Tuple							      =     Path("""src/transformers"""			)
					__snake_case					:      int							      =     ["""configuration""", """modeling""", """tokenization"""]
					self.analyze_directory(__magic_name__  ,      n_identifier=__magic_name__			)

		def 	lowercase__     (   self					:   Optional[int]			)					->    Union[str, Any]:


					"""simple docstring"""

					__snake_case					:      int							      =     Path("""docs/source"""			)
					__snake_case					:      Optional[int]							      =     ["""favicon.ico"""]
					self.analyze_directory(__magic_name__  ,      ignore_files=__magic_name__  ,      only_modules=__magic_name__			)


