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 	__snake_case	:





      '''simple docstring'''






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


          """simple docstring"""


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



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


          """simple docstring"""


          _lowerCamelCase     :		Any 						=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

          _lowerCamelCase     :		List[Any] 						=						self.get_config()

          return config, pixel_values, labels



      def 	_SCREAMING_SNAKE_CASE    (					self     :				str)				->List[str]:


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


          """simple docstring"""


          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 	_SCREAMING_SNAKE_CASE    (					self     :				Any    ,  _UpperCamelCase     :				int    ,  _UpperCamelCase     :				List[str]    ,  _UpperCamelCase     :				Optional[int])				->Tuple:


          """simple docstring"""


          _lowerCamelCase     :		List[Any] 						=						UperNetForSemanticSegmentation(config=_UpperCamelCase)
          model.to(_UpperCamelCase)
          model.eval()
          _lowerCamelCase     :		Tuple 						=						model(_UpperCamelCase)
          self.parent.assertEqual(
              result.logits.shape    ,  (self.batch_size, self.num_labels, self.image_size, self.image_size))




      def 	_SCREAMING_SNAKE_CASE    (					self     :				int)				->Tuple:


          """simple docstring"""


          _lowerCamelCase     :		Union[str, Any] 						=						self.prepare_config_and_inputs()
          (
              (
              _lowerCamelCase
          )						,							(
              _lowerCamelCase
          )						,							(
              _lowerCamelCase
          )						,							
          )     :		List[Any] 						=						config_and_inputs
          _lowerCamelCase     :		str 						=						{"""pixel_values""": pixel_values}
          return config, inputs_dict





@require_torch
class 	__snake_case	( __lowerCAmelCase ,  __lowerCAmelCase ,  unittest.TestCase		):





      '''simple docstring'''






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



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


          """simple docstring"""


          _lowerCamelCase     :		Union[str, Any] 						=						UperNetModelTester(self)
          _lowerCamelCase     :		Dict 						=						ConfigTester(self    ,  config_class=_UpperCamelCase    ,  has_text_modality=_UpperCamelCase    ,  hidden_size=37)



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


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


          """simple docstring"""


          return



      def 	_SCREAMING_SNAKE_CASE    (					self     :				Any)				->Dict:


          """simple docstring"""


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

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

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



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


          """simple docstring"""


          _lowerCamelCase     :		str 						=						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 	_SCREAMING_SNAKE_CASE    (					self     :				Dict)				->str:


          """simple docstring"""


          pass



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


          """simple docstring"""


          pass



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


          """simple docstring"""


          pass



      @unittest.skip(reason="""UperNet does not have a base model""")
      def 	_SCREAMING_SNAKE_CASE    (					self     :				List[str])				->Optional[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 	_SCREAMING_SNAKE_CASE    (					self     :				str)				->Tuple:


          """simple docstring"""


          pass



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


          """simple docstring"""


          pass



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


          """simple docstring"""


          def check_hidden_states_output(_UpperCamelCase     :				Optional[Any]    ,  _UpperCamelCase     :				Dict    ,  _UpperCamelCase     :				Optional[Any]):
              _lowerCamelCase     :		List[Any] 						=						model_class(_UpperCamelCase)
              model.to(_UpperCamelCase)
              model.eval()

              with torch.no_grad():
                  _lowerCamelCase     :		Tuple 						=						model(**self._prepare_for_class(_UpperCamelCase    ,  _UpperCamelCase))

              _lowerCamelCase     :		Any 						=						outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

              _lowerCamelCase     :		Dict 						=						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]    ,  )

          _lowerCamelCase						,							_lowerCamelCase     :		List[Any] 						=						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(_UpperCamelCase    ,  _UpperCamelCase    ,  _UpperCamelCase)

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

              check_hidden_states_output(_UpperCamelCase    ,  _UpperCamelCase    ,  _UpperCamelCase)



      def 	_SCREAMING_SNAKE_CASE    (					self     :				Dict)				->List[Any]:


          """simple docstring"""


          _lowerCamelCase						,							_lowerCamelCase     :		Union[str, Any] 						=						self.model_tester.prepare_config_and_inputs_for_common()

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


          """simple docstring"""


          pass




      @slow
      def 	_SCREAMING_SNAKE_CASE    (					self     :				Tuple)				->Tuple:


          """simple docstring"""


          for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              _lowerCamelCase     :		Optional[Any] 						=						UperNetForSemanticSegmentation.from_pretrained(_UpperCamelCase)
              self.assertIsNotNone(_UpperCamelCase)







def 						A__  (					):







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




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





      '''simple docstring'''






      def 	_SCREAMING_SNAKE_CASE    (					self     :				Tuple)				->Dict:


          """simple docstring"""


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

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

          with torch.no_grad():
              _lowerCamelCase     :		Any 						=						model(**_UpperCamelCase)

          _lowerCamelCase     :		List[Any] 						=						torch.Size((1, model.config.num_labels, 512, 512))
          self.assertEqual(outputs.logits.shape    ,  _UpperCamelCase)

          _lowerCamelCase     :		Optional[Any] 						=						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 	_SCREAMING_SNAKE_CASE    (					self     :				Union[str, Any])				->Optional[int]:


          """simple docstring"""


          _lowerCamelCase     :		Dict 						=						AutoImageProcessor.from_pretrained("""openmmlab/upernet-convnext-tiny""")
          _lowerCamelCase     :		Tuple 						=						UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-convnext-tiny""").to(_UpperCamelCase)

          _lowerCamelCase     :		Dict 						=						prepare_img()
          _lowerCamelCase     :		str 						=						processor(images=_UpperCamelCase    ,  return_tensors="""pt""").to(_UpperCamelCase)

          with torch.no_grad():
              _lowerCamelCase     :		str 						=						model(**_UpperCamelCase)

          _lowerCamelCase     :		List[str] 						=						torch.Size((1, model.config.num_labels, 512, 512))
          self.assertEqual(outputs.logits.shape    ,  _UpperCamelCase)

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





import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow


if is_torch_available():
    import torch

    from transformers import XLMRobertaModel




@require_sentencepiece
@require_tokenizers
@require_torch
class 	__snake_case	( unittest.TestCase		):





      '''simple docstring'''






      @slow
      def 	_SCREAMING_SNAKE_CASE    (					self     :				Tuple)				->int:


          """simple docstring"""


          _lowerCamelCase     :		Tuple 						=						XLMRobertaModel.from_pretrained("""xlm-roberta-base""")
          _lowerCamelCase     :		Optional[int] 						=						torch.tensor([[0, 581, 1_0269, 83, 9_9942, 136, 6_0742, 23, 70, 8_0583, 1_8276, 2]])
          # The dog is cute and lives in the garden house

          _lowerCamelCase     :		Optional[Any] 						=						torch.Size((1, 12, 768))  # batch_size, sequence_length, embedding_vector_dim
          _lowerCamelCase     :		str 						=						torch.tensor(
              [[-0.0_1_0_1, 0.1_2_1_8, -0.0_8_0_3, 0.0_8_0_1, 0.1_3_2_7, 0.0_7_7_6, -0.1_2_1_5, 0.2_3_8_3, 0.3_3_3_8, 0.3_1_0_6, 0.0_3_0_0, 0.0_2_5_2]])
          #  xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base')
          #  xlmr.eval()
          #  expected_output_values_last_dim = xlmr.extract_features(input_ids[0])[:, :, -1]
          with torch.no_grad():
              _lowerCamelCase     :		List[str] 						=						model(_UpperCamelCase)["""last_hidden_state"""].detach()
          self.assertEqual(output.shape    ,  _UpperCamelCase)
          # compare the actual values for a slice of last dim
          self.assertTrue(torch.allclose(output[:, :, -1]    ,  _UpperCamelCase    ,  atol=1E-3))




      @slow
      def 	_SCREAMING_SNAKE_CASE    (					self     :				List[Any])				->Optional[Any]:


          """simple docstring"""


          _lowerCamelCase     :		List[Any] 						=						XLMRobertaModel.from_pretrained("""xlm-roberta-large""")
          _lowerCamelCase     :		Optional[Any] 						=						torch.tensor([[0, 581, 1_0269, 83, 9_9942, 136, 6_0742, 23, 70, 8_0583, 1_8276, 2]])
          # The dog is cute and lives in the garden house

          _lowerCamelCase     :		str 						=						torch.Size((1, 12, 1024))  # batch_size, sequence_length, embedding_vector_dim
          _lowerCamelCase     :		Union[str, Any] 						=						torch.tensor(
              [[-0.0_6_9_9, -0.0_3_1_8, 0.0_7_0_5, -0.1_2_4_1, 0.0_9_9_9, -0.0_5_2_0, 0.1_0_0_4, -0.1_8_3_8, -0.4_7_0_4, 0.1_4_3_7, 0.0_8_2_1, 0.0_1_2_6]])
          #  xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.large')
          #  xlmr.eval()
          #  expected_output_values_last_dim = xlmr.extract_features(input_ids[0])[:, :, -1]
          with torch.no_grad():
              _lowerCamelCase     :		int 						=						model(_UpperCamelCase)["""last_hidden_state"""].detach()
          self.assertEqual(output.shape    ,  _UpperCamelCase)
          # compare the actual values for a slice of last dim
          self.assertTrue(torch.allclose(output[:, :, -1]    ,  _UpperCamelCase    ,  atol=1E-3))




