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





   """simple docstring"""





   def __init__( self     :		Optional[int]						,     lowerCAmelCase__     :		List[str]						,     lowerCAmelCase__     :		int=1_3						,     lowerCAmelCase__     :		Optional[Any]=3_2						,     lowerCAmelCase__     :		Optional[Any]=3						,     lowerCAmelCase__     :		str=4						,     lowerCAmelCase__     :		Union[str, Any]=[1_0, 2_0, 3_0, 4_0]						,     lowerCAmelCase__     :		Tuple=[2, 2, 3, 2]						,     lowerCAmelCase__     :		Union[str, Any]=True						,     lowerCAmelCase__     :		Any=True						,     lowerCAmelCase__     :		int=3_7						,     lowerCAmelCase__     :		Any="gelu"						,     lowerCAmelCase__     :		List[Any]=1_0						,     lowerCAmelCase__     :		List[str]=0.02						,     lowerCAmelCase__     :		Union[str, Any]=["stage2", "stage3", "stage4"]						,     lowerCAmelCase__     :		Tuple=3						,     lowerCAmelCase__     :		int=None						,     )       ->    Tuple:







      """simple docstring"""




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




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







      """simple docstring"""




      _UpperCAmelCase							:	Tuple							=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

      _UpperCAmelCase							:	List[str]							=   None
      if self.use_labels:
         _UpperCAmelCase							:	List[str]							=   ids_tensor([self.batch_size]						,     self.type_sequence_label_size			)

      _UpperCAmelCase							:	Dict							=   self.get_config()

      return config, pixel_values, labels




   def 			_lowerCAmelCase		( self     :		List[Any]			)       ->    Tuple:







      """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 			_lowerCAmelCase		( self     :		Any			)       ->    Optional[Any]:







      """simple docstring"""




      return UperNetConfig(
          backbone_config=self.get_backbone_config()						,     hidden_size=5_1_2						,     pool_scales=[1, 2, 3, 6]						,     use_auxiliary_head=_UpperCamelCase						,     auxiliary_loss_weight=0.4						,     auxiliary_in_channels=4_0						,     auxiliary_channels=2_5_6						,     auxiliary_num_convs=1						,     auxiliary_concat_input=_UpperCamelCase						,     loss_ignore_index=2_5_5						,     num_labels=self.num_labels						,     )




   def 			_lowerCAmelCase		( self     :		Dict						,     lowerCAmelCase__     :		int						,     lowerCAmelCase__     :		Tuple						,     lowerCAmelCase__     :		Optional[Any]			)       ->    Any:







      """simple docstring"""




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




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







      """simple docstring"""




      _UpperCAmelCase							:	Tuple							=   self.prepare_config_and_inputs()
      (
          _UpperCAmelCase  
      )							:	List[str]							=   config_and_inputs
      _UpperCAmelCase							:	Optional[Any]							=   {'pixel_values': pixel_values}
      return config, inputs_dict





@require_torch
class     A__							(       _snake_case					,		_snake_case					,		unittest.TestCase   ):





   """simple docstring"""





   UpperCamelCase_       :						str    				=     (UperNetForSemanticSegmentation,) if is_torch_available() else ()
   UpperCamelCase_       :						List[str]    				=     {'''image-segmentation''': UperNetForSemanticSegmentation} if is_torch_available() else {}
   UpperCamelCase_       :						Tuple    				=     False
   UpperCamelCase_       :						Optional[Any]    				=     False
   UpperCamelCase_       :						Optional[Any]    				=     False
   UpperCamelCase_       :						List[str]    				=     False
   UpperCamelCase_       :						Any    				=     False
   UpperCamelCase_       :						Dict    				=     False




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







      """simple docstring"""




      _UpperCAmelCase							:	Optional[int]							=   UperNetModelTester(self			)
      _UpperCAmelCase							:	int							=   ConfigTester(self						,     config_class=_UpperCamelCase						,     has_text_modality=_UpperCamelCase						,     hidden_size=3_7			)




   def 			_lowerCAmelCase		( self     :		Tuple			)       ->    Dict:







      """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 			_lowerCAmelCase		( self     :		Dict			)       ->    List[Any]:







      """simple docstring"""




      return




   def 			_lowerCAmelCase		( self     :		int			)       ->    Tuple:







      """simple docstring"""




      _UpperCAmelCase							:	Any							=   self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
         _UpperCAmelCase							:	List[Any]							=   model_class(_UpperCamelCase			)
         _UpperCAmelCase							:	Tuple							=   inspect.signature(model.forward			)
         # signature.parameters is an OrderedDict => so arg_names order is deterministic
         _UpperCAmelCase							:	str							=   [*signature.parameters.keys()]

         _UpperCAmelCase							:	List[str]							=   ['pixel_values']
         self.assertListEqual(arg_names[:1]						,     _UpperCamelCase			)




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







      """simple docstring"""




      _UpperCAmelCase							:	Any							=   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 			_lowerCAmelCase		( self     :		str			)       ->    int:







      """simple docstring"""




      pass




   @unittest.skip(reason="UperNet does not support input and output embeddings"			)
   def 			_lowerCAmelCase		( self     :		int			)       ->    Any:







      """simple docstring"""




      pass




   @unittest.skip(reason="UperNet does not have a base model"			)
   def 			_lowerCAmelCase		( self     :		Union[str, Any]			)       ->    List[Any]:







      """simple docstring"""




      pass




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







      """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 			_lowerCAmelCase		( self     :		int			)       ->    int:







      """simple docstring"""




      pass




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







      """simple docstring"""




      pass




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







      """simple docstring"""




      def check_hidden_states_output(lowerCAmelCase__     :		List[str]						,     lowerCAmelCase__     :		Optional[int]						,     lowerCAmelCase__     :		int			):
         _UpperCAmelCase							:	Tuple							=   model_class(_UpperCamelCase			)
         model.to(_UpperCamelCase			)
         model.eval()

         with torch.no_grad():
            _UpperCAmelCase							:	int							=   model(**self._prepare_for_class(_UpperCamelCase						,     _UpperCamelCase			)			)

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

         _UpperCAmelCase							:	Tuple							=   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]						,     )

      _UpperCAmelCase							:	int							=   self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
         _UpperCAmelCase							:	Tuple							=   True
         check_hidden_states_output(_UpperCamelCase						,     _UpperCamelCase						,     _UpperCamelCase			)

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

         check_hidden_states_output(_UpperCamelCase						,     _UpperCamelCase						,     _UpperCamelCase			)




   def 			_lowerCAmelCase		( self     :		List[str]			)       ->    Dict:







      """simple docstring"""




      _UpperCAmelCase							:	str							=   self.model_tester.prepare_config_and_inputs_for_common()

      _UpperCAmelCase							:	int							=   _config_zero_init(_UpperCamelCase			)
      _UpperCAmelCase							:	List[str]							=   _config_zero_init(configs_no_init.backbone_config			)
      for model_class in self.all_model_classes:
         _UpperCAmelCase							:	List[str]							=   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 			_lowerCAmelCase		( self     :		int			)       ->    Optional[int]:







      """simple docstring"""




      pass




   @slow
   def 			_lowerCAmelCase		( self     :		str			)       ->    List[Any]:







      """simple docstring"""




      for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         _UpperCAmelCase							:	Tuple							=   UperNetForSemanticSegmentation.from_pretrained(_UpperCamelCase			)
         self.assertIsNotNone(_UpperCamelCase			)






def    __UpperCAmelCase			(  ):
   _UpperCAmelCase							:	str							=   hf_hub_download(
       repo_id="hf-internal-testing/fixtures_ade20k",					repo_type="dataset",					filename="ADE_val_00000001.jpg"							)
   _UpperCAmelCase							:	Optional[Any]							=   Image.open(__snake_case							).convert("RGB"							)
   return image






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





   """simple docstring"""





   def 			_lowerCAmelCase		( self     :		int			)       ->    Tuple:







      """simple docstring"""




      _UpperCAmelCase							:	int							=   AutoImageProcessor.from_pretrained("openmmlab/upernet-swin-tiny"			)
      _UpperCAmelCase							:	Optional[int]							=   UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-swin-tiny"			).to(_UpperCamelCase			)

      _UpperCAmelCase							:	Union[str, Any]							=   prepare_img()
      _UpperCAmelCase							:	Optional[Any]							=   processor(images=_UpperCamelCase						,     return_tensors="pt"			).to(_UpperCamelCase			)

      with torch.no_grad():
         _UpperCAmelCase							:	Optional[int]							=   model(**_UpperCamelCase			)

      _UpperCAmelCase							:	Any							=   torch.Size((1, model.config.num_labels, 5_1_2, 5_1_2)			)
      self.assertEqual(outputs.logits.shape						,     _UpperCamelCase			)

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




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







      """simple docstring"""




      _UpperCAmelCase							:	Optional[int]							=   AutoImageProcessor.from_pretrained("openmmlab/upernet-convnext-tiny"			)
      _UpperCAmelCase							:	str							=   UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-convnext-tiny"			).to(_UpperCamelCase			)

      _UpperCAmelCase							:	Any							=   prepare_img()
      _UpperCAmelCase							:	List[str]							=   processor(images=_UpperCamelCase						,     return_tensors="pt"			).to(_UpperCamelCase			)

      with torch.no_grad():
         _UpperCAmelCase							:	Optional[Any]							=   model(**_UpperCamelCase			)

      _UpperCAmelCase							:	int							=   torch.Size((1, model.config.num_labels, 5_1_2, 5_1_2)			)
      self.assertEqual(outputs.logits.shape						,     _UpperCamelCase			)

      _UpperCAmelCase							:	Dict							=   torch.tensor(
          [[-8.8110, -8.8110, -8.6521], [-8.8110, -8.8110, -8.6521], [-8.7746, -8.7746, -8.6130]]			).to(_UpperCamelCase			)
      self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]						,     _UpperCamelCase						,     atol=1e-4			)			)







import random
import unittest

import torch

from diffusers import IFImgaImgSuperResolutionPipeline
from diffusers.utils import floats_tensor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import skip_mps, torch_device

from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin



@skip_mps
class   lowerCamelCase      (_snake_case ,  _snake_case ,  unittest.TestCase			):







		'''simple docstring'''



		_snake_case    :    Union[str, Any]       						=  IFImgaImgSuperResolutionPipeline
		_snake_case    :    Union[str, Any]       						=  TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''width''', '''height'''}
		_snake_case    :    List[Any]       						=  TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'''original_image'''}			)
		_snake_case    :    List[str]       						=  PipelineTesterMixin.required_optional_params - {'''latents'''}



		def 					__UpperCAmelCase			(							self   )	->							Optional[Any]:
							return self._get_superresolution_dummy_components()



		def 					__UpperCAmelCase			(							self				,		_UpperCamelCase				,		_UpperCamelCase=0   )	->							Any:
							if str(_UpperCamelCase   ).startswith('mps'   ):
												UpperCAmelCase_    :      List[Any]            =						torch.manual_seed(_UpperCamelCase   )
							else:
												UpperCAmelCase_    :      int            =						torch.Generator(device=_UpperCamelCase   ).manual_seed(_UpperCamelCase   )

							UpperCAmelCase_    :      List[Any]            =						floats_tensor((1, 3, 3_2, 3_2)				,		rng=random.Random(_UpperCamelCase   )   ).to(_UpperCamelCase   )
							UpperCAmelCase_    :      Dict            =						floats_tensor((1, 3, 1_6, 1_6)				,		rng=random.Random(_UpperCamelCase   )   ).to(_UpperCamelCase   )

							UpperCAmelCase_    :      Tuple            =						{
							    'prompt': 'A painting of a squirrel eating a burger',
							    'image': image,
							    'original_image': original_image,
							    'generator': generator,
							    'num_inference_steps': 2,
							    'output_type': 'numpy',
							}

							return inputs



		@unittest.skipIf(
		    torch_device != 'cuda' or not is_xformers_available()				,		reason='XFormers attention is only available with CUDA and `xformers` installed'				,		)
		def 					__UpperCAmelCase			(							self   )	->							Any:
							self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3   )



		def 					__UpperCAmelCase			(							self   )	->							Dict:
							self._test_save_load_optional_components()



		@unittest.skipIf(torch_device != 'cuda'				,		reason='float16 requires CUDA'   )
		def 					__UpperCAmelCase			(							self   )	->							str:
							# Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder
							super().test_save_load_floataa(expected_max_diff=1E-1   )



		def 					__UpperCAmelCase			(							self   )	->							List[Any]:
							self._test_attention_slicing_forward_pass(expected_max_diff=1E-2   )



		def 					__UpperCAmelCase			(							self   )	->							Union[str, Any]:
							self._test_save_load_local()



		def 					__UpperCAmelCase			(							self   )	->							Dict:
							self._test_inference_batch_single_identical(
							    expected_max_diff=1E-2				,		)






