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


 '''simple docstring'''






 def __init__(      self   :	List[str]      ,       SCREAMING_SNAKE_CASE__   :	Tuple      ,       SCREAMING_SNAKE_CASE__   :	List[str]=13      ,       SCREAMING_SNAKE_CASE__   :	int=32      ,       SCREAMING_SNAKE_CASE__   :	Dict=3      ,       SCREAMING_SNAKE_CASE__   :	List[Any]=4      ,       SCREAMING_SNAKE_CASE__   :	Optional[Any]=[10, 20, 30, 40]      ,       SCREAMING_SNAKE_CASE__   :	List[Any]=[2, 2, 3, 2]      ,       SCREAMING_SNAKE_CASE__   :	str=True      ,       SCREAMING_SNAKE_CASE__   :	List[Any]=True      ,       SCREAMING_SNAKE_CASE__   :	List[str]=37      ,       SCREAMING_SNAKE_CASE__   :	Optional[Any]="gelu"      ,       SCREAMING_SNAKE_CASE__   :	int=10      ,       SCREAMING_SNAKE_CASE__   :	Optional[int]=0.0_2      ,       SCREAMING_SNAKE_CASE__   :	Union[str, Any]=["stage2", "stage3", "stage4"]      ,       SCREAMING_SNAKE_CASE__   :	Union[str, Any]=3      ,       SCREAMING_SNAKE_CASE__   :	List[str]=None      ,       )  ->    str:
  __lowerCAmelCase											=						parent
  __lowerCAmelCase											=						batch_size
  __lowerCAmelCase											=						image_size
  __lowerCAmelCase											=						num_channels
  __lowerCAmelCase											=						num_stages
  __lowerCAmelCase											=						hidden_sizes
  __lowerCAmelCase											=						depths
  __lowerCAmelCase											=						is_training
  __lowerCAmelCase											=						use_labels
  __lowerCAmelCase											=						intermediate_size
  __lowerCAmelCase											=						hidden_act
  __lowerCAmelCase											=						type_sequence_label_size
  __lowerCAmelCase											=						initializer_range
  __lowerCAmelCase											=						out_features
  __lowerCAmelCase											=						num_labels
  __lowerCAmelCase											=						scope
  __lowerCAmelCase											=						num_stages
 def a					(      self   :	Tuple							)  ->    str:
  __lowerCAmelCase											=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

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

  __lowerCAmelCase											=						self.get_config()

  return config, pixel_values, labels
 def a					(      self   :	Optional[int]							)  ->    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 a					(      self   :	str							)  ->    List[Any]:
  return UperNetConfig(
      backbone_config=self.get_backbone_config()      ,       hidden_size=5_12      ,       pool_scales=[1, 2, 3, 6]      ,       use_auxiliary_head=SCREAMING_SNAKE_CASE__      ,       auxiliary_loss_weight=0.4      ,       auxiliary_in_channels=40      ,       auxiliary_channels=2_56      ,       auxiliary_num_convs=1      ,       auxiliary_concat_input=SCREAMING_SNAKE_CASE__      ,       loss_ignore_index=2_55      ,       num_labels=self.num_labels      ,       )
 def a					(      self   :	Dict      ,       SCREAMING_SNAKE_CASE__   :	List[Any]      ,       SCREAMING_SNAKE_CASE__   :	Tuple      ,       SCREAMING_SNAKE_CASE__   :	str							)  ->    List[str]:
  __lowerCAmelCase											=						UperNetForSemanticSegmentation(config=SCREAMING_SNAKE_CASE__							)
  model.to(SCREAMING_SNAKE_CASE__							)
  model.eval()
  __lowerCAmelCase											=						model(SCREAMING_SNAKE_CASE__							)
  self.parent.assertEqual(
      result.logits.shape      ,       (self.batch_size, self.num_labels, self.image_size, self.image_size)							)





 def a					(      self   :	Union[str, Any]							)  ->    Tuple:
  __lowerCAmelCase											=						self.prepare_config_and_inputs()
  (
      (
      __lowerCAmelCase
  )							,       (
      __lowerCAmelCase
  )							,       (
      __lowerCAmelCase
  )							,       
  )											=						config_and_inputs
  __lowerCAmelCase											=						{"""pixel_values""": pixel_values}
  return config, inputs_dict







@require_torch
class 				_lowercase     (				UpperCAmelCase__  ,							UpperCAmelCase__  ,							unittest.TestCase			):


 '''simple docstring'''






 _SCREAMING_SNAKE_CASE     :       Any      	=					(UperNetForSemanticSegmentation,) if is_torch_available() else ()
 _SCREAMING_SNAKE_CASE     :       Any      	=					{"""image-segmentation""": UperNetForSemanticSegmentation} if is_torch_available() else {}
 _SCREAMING_SNAKE_CASE     :       Dict      	=					False
 _SCREAMING_SNAKE_CASE     :       Any      	=					False
 _SCREAMING_SNAKE_CASE     :       Dict      	=					False
 _SCREAMING_SNAKE_CASE     :       Optional[Any]      	=					False
 _SCREAMING_SNAKE_CASE     :       int      	=					False
 _SCREAMING_SNAKE_CASE     :       List[str]      	=					False
 def a					(      self   :	int							)  ->    Optional[int]:
  __lowerCAmelCase											=						UperNetModelTester(self							)
  __lowerCAmelCase											=						ConfigTester(self      ,       config_class=SCREAMING_SNAKE_CASE__      ,       has_text_modality=SCREAMING_SNAKE_CASE__      ,       hidden_size=37							)
 def a					(      self   :	Dict							)  ->    Dict:
  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 a					(      self   :	List[Any]							)  ->    Optional[Any]:
  return
 def a					(      self   :	Any							)  ->    int:
  __lowerCAmelCase							,       __lowerCAmelCase											=						self.model_tester.prepare_config_and_inputs_for_common()

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

   __lowerCAmelCase											=						["""pixel_values"""]
   self.assertListEqual(arg_names[:1]      ,       SCREAMING_SNAKE_CASE__							)
 def a					(      self   :	Tuple							)  ->    Union[str, Any]:
  __lowerCAmelCase											=						self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_for_semantic_segmentation(*SCREAMING_SNAKE_CASE__							)
 @unittest.skip(reason="""UperNet does not use inputs_embeds"""							)
 def a					(      self   :	List[str]							)  ->    Optional[int]:
  pass
 @unittest.skip(reason="""UperNet does not support input and output embeddings"""							)
 def a					(      self   :	List[str]							)  ->    Union[str, Any]:
  pass
 @unittest.skip(reason="""UperNet does not have a base model"""							)
 def a					(      self   :	Union[str, Any]							)  ->    List[str]:
  pass
 @unittest.skip(reason="""UperNet does not have a base model"""							)
 def a					(      self   :	List[Any]							)  ->    List[Any]:
  pass
 @require_torch_multi_gpu
 @unittest.skip(reason="""UperNet has some layers using `add_module` which doesn't work well with `nn.DataParallel`"""							)
 def a					(      self   :	str							)  ->    List[str]:
  pass
 @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""							)
 def a					(      self   :	List[Any]							)  ->    Any:
  pass
 def a					(      self   :	Any							)  ->    int:
  def check_hidden_states_output(SCREAMING_SNAKE_CASE__   :	Optional[Any]      ,       SCREAMING_SNAKE_CASE__   :	Tuple      ,       SCREAMING_SNAKE_CASE__   :	Optional[int]							):
   __lowerCAmelCase											=						model_class(SCREAMING_SNAKE_CASE__							)
   model.to(SCREAMING_SNAKE_CASE__							)
   model.eval()

   with torch.no_grad():
    __lowerCAmelCase											=						model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__      ,       SCREAMING_SNAKE_CASE__							)							)

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

   __lowerCAmelCase											=						self.model_tester.num_stages
   self.assertEqual(len(SCREAMING_SNAKE_CASE__							)      ,       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											=						self.model_tester.prepare_config_and_inputs_for_common()

  for model_class in self.all_model_classes:
   __lowerCAmelCase											=						True
   check_hidden_states_output(SCREAMING_SNAKE_CASE__      ,       SCREAMING_SNAKE_CASE__      ,       SCREAMING_SNAKE_CASE__							)

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

   check_hidden_states_output(SCREAMING_SNAKE_CASE__      ,       SCREAMING_SNAKE_CASE__      ,       SCREAMING_SNAKE_CASE__							)
 def a					(      self   :	Any							)  ->    List[Any]:
  __lowerCAmelCase							,       __lowerCAmelCase											=						self.model_tester.prepare_config_and_inputs_for_common()

  __lowerCAmelCase											=						_config_zero_init(SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase											=						_config_zero_init(configs_no_init.backbone_config							)
  for model_class in self.all_model_classes:
   __lowerCAmelCase											=						model_class(config=SCREAMING_SNAKE_CASE__							)
   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 a					(      self   :	List[str]							)  ->    List[Any]:
  pass





 @slow
 def a					(      self   :	Optional[Any]							)  ->    Optional[Any]:
  for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
   __lowerCAmelCase											=						UperNetForSemanticSegmentation.from_pretrained(SCREAMING_SNAKE_CASE__							)
   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)







def      UpperCamelCase_						(					)					->     Any:






 '''simple docstring'''

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







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


 '''simple docstring'''






 def a					(      self   :	Dict							)  ->    Dict:
  __lowerCAmelCase											=						AutoImageProcessor.from_pretrained("""openmmlab/upernet-swin-tiny"""							)
  __lowerCAmelCase											=						UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-swin-tiny"""							).to(SCREAMING_SNAKE_CASE__							)

  __lowerCAmelCase											=						prepare_img()
  __lowerCAmelCase											=						processor(images=SCREAMING_SNAKE_CASE__      ,       return_tensors="""pt"""							).to(SCREAMING_SNAKE_CASE__							)

  with torch.no_grad():
   __lowerCAmelCase											=						model(**SCREAMING_SNAKE_CASE__							)

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

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





 def a					(      self   :	Tuple							)  ->    List[str]:
  __lowerCAmelCase											=						AutoImageProcessor.from_pretrained("""openmmlab/upernet-convnext-tiny"""							)
  __lowerCAmelCase											=						UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-convnext-tiny"""							).to(SCREAMING_SNAKE_CASE__							)

  __lowerCAmelCase											=						prepare_img()
  __lowerCAmelCase											=						processor(images=SCREAMING_SNAKE_CASE__      ,       return_tensors="""pt"""							).to(SCREAMING_SNAKE_CASE__							)

  with torch.no_grad():
   __lowerCAmelCase											=						model(**SCREAMING_SNAKE_CASE__							)

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

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







'''simple docstring'''

from unittest import TestCase

from datasets import Sequence, Value
from datasets.arrow_dataset import Dataset







class 				_lowercase     (				UpperCAmelCase__			):


 '''simple docstring'''






 def a					(      self   :	int							)  ->    Optional[Any]:
  return [
      {"col_1": 3, "col_2": "a"},
      {"col_1": 2, "col_2": "b"},
      {"col_1": 1, "col_2": "c"},
      {"col_1": 0, "col_2": "d"},
  ]
 def a					(      self   :	List[Any]							)  ->    Any:
  __lowerCAmelCase											=						{"""col_1""": [3, 2, 1, 0], """col_2""": ["""a""", """b""", """c""", """d"""]}
  return Dataset.from_dict(SCREAMING_SNAKE_CASE__							)
 def a					(      self   :	List[Any]							)  ->    Tuple:
  __lowerCAmelCase											=						self._create_example_records()
  __lowerCAmelCase											=						Dataset.from_list(SCREAMING_SNAKE_CASE__							)
  self.assertListEqual(dset.column_names      ,       ["""col_1""", """col_2"""]							)
  for i, r in enumerate(SCREAMING_SNAKE_CASE__							):
   self.assertDictEqual(SCREAMING_SNAKE_CASE__      ,       example_records[i]							)
 def a					(      self   :	Tuple							)  ->    List[str]:
  __lowerCAmelCase											=						self._create_example_records()
  __lowerCAmelCase											=						Dataset.from_list(SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase											=						Dataset.from_dict({k: [r[k] for r in example_records] for k in example_records[0]}							)
  self.assertEqual(dset.info      ,       dset_from_dict.info							)
 def a					(      self   :	List[str]							)  ->    List[str]:  # checks what happens with missing columns
  __lowerCAmelCase											=						[{"""col_1""": 1}, {"""col_2""": """x"""}]
  __lowerCAmelCase											=						Dataset.from_list(SCREAMING_SNAKE_CASE__							)
  self.assertDictEqual(dset[0]      ,       {"""col_1""": 1}							)
  self.assertDictEqual(dset[1]      ,       {"""col_1""": None}							)  # NB: first record is used for columns
 def a					(      self   :	Dict							)  ->    Optional[int]:  # checks if the type can be inferred from the second record
  __lowerCAmelCase											=						[{"""col_1""": []}, {"""col_1""": [1, 2]}]
  __lowerCAmelCase											=						Dataset.from_list(SCREAMING_SNAKE_CASE__							)
  self.assertEqual(dset.info.features["""col_1"""]      ,       Sequence(Value("""int64"""							)							)							)





 def a					(      self   :	Optional[Any]							)  ->    Tuple:
  __lowerCAmelCase											=						Dataset.from_list([]							)
  self.assertEqual(len(SCREAMING_SNAKE_CASE__							)      ,       0							)
  self.assertListEqual(dset.column_names      ,       []							)






