



"""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    SCREAMING_SNAKE_CASE__						:

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





    '''simple docstring'''




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

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Dict:





    '''simple docstring'''




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

    UpperCAmelCase			:      Optional[int]			=			None
    if self.use_labels:
     UpperCAmelCase			:      List[Any]			=			ids_tensor([self.batch_size]   ,  self.type_sequence_label_size		)

    UpperCAmelCase			:      Optional[Any]			=			self.get_config()

    return config, pixel_values, labels

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   int:





    '''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		)						->   Tuple:





    '''simple docstring'''




    return UperNetConfig(
        backbone_config=self.get_backbone_config()   ,  hidden_size=512   ,  pool_scales=[1, 2, 3, 6]   ,  use_auxiliary_head=_SCREAMING_SNAKE_CASE   ,  auxiliary_loss_weight=0.4   ,  auxiliary_in_channels=40   ,  auxiliary_channels=256   ,  auxiliary_num_convs=1   ,  auxiliary_concat_input=_SCREAMING_SNAKE_CASE   ,  loss_ignore_index=255   ,  num_labels=self.num_labels   ,  )

   def 			SCREAMING_SNAKE_CASE  (     self   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		)						->   Tuple:





    '''simple docstring'''




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




   def 			SCREAMING_SNAKE_CASE  (     self		)						->   str:





    '''simple docstring'''




    UpperCAmelCase			:      List[Any]			=			self.prepare_config_and_inputs()
    (
        (
        UpperCAmelCase
    )			,	(
        UpperCAmelCase
    )			,	(
        UpperCAmelCase
    )			,	
    )			:      Optional[Any]			=			config_and_inputs
    UpperCAmelCase			:      Dict			=			{"""pixel_values""": pixel_values}
    return config, inputs_dict



@require_torch
class    SCREAMING_SNAKE_CASE__						(      UpperCAmelCase__   ,    UpperCAmelCase__   ,    unittest.TestCase				):
   __lowerCAmelCase						:     Optional[Any]		=		(UperNetForSemanticSegmentation,) if is_torch_available() else ()
   __lowerCAmelCase						:     Optional[Any]		=		{'image-segmentation': UperNetForSemanticSegmentation} if is_torch_available() else {}
   __lowerCAmelCase						:     List[str]		=		False
   __lowerCAmelCase						:     Tuple		=		False
   __lowerCAmelCase						:     Any		=		False
   __lowerCAmelCase						:     str		=		False
   __lowerCAmelCase						:     Union[str, Any]		=		False
   __lowerCAmelCase						:     int		=		False

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





    '''simple docstring'''




    UpperCAmelCase			:      List[Any]			=			UperNetModelTester(self		)
    UpperCAmelCase			:      Any			=			ConfigTester(self   ,  config_class=_SCREAMING_SNAKE_CASE   ,  has_text_modality=_SCREAMING_SNAKE_CASE   ,  hidden_size=37		)

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   str:





    '''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		)						->   Tuple:





    '''simple docstring'''




    return

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





    '''simple docstring'''




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

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

     UpperCAmelCase			:      Optional[Any]			=			["""pixel_values"""]
     self.assertListEqual(arg_names[:1]   ,  _SCREAMING_SNAKE_CASE		)

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Dict:





    '''simple docstring'''




    UpperCAmelCase			:      Any			=			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 			SCREAMING_SNAKE_CASE  (     self		)						->   int:





    '''simple docstring'''




    pass

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





    '''simple docstring'''




    pass

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





    '''simple docstring'''




    pass

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





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





    '''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		)						->   int:





    '''simple docstring'''




    pass

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





    '''simple docstring'''




    def check_hidden_states_output(_SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		):
     UpperCAmelCase			:      Optional[Any]			=			model_class(_SCREAMING_SNAKE_CASE		)
     model.to(_SCREAMING_SNAKE_CASE		)
     model.eval()

     with torch.no_grad():
      UpperCAmelCase			:      str			=			model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		)		)

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

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

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

    for model_class in self.all_model_classes:
     UpperCAmelCase			:      Optional[int]			=			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"]
     UpperCAmelCase			:      Union[str, Any]			=			True

     check_hidden_states_output(_SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		)

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





    '''simple docstring'''




    UpperCAmelCase			,	UpperCAmelCase			:      int			=			self.model_tester.prepare_config_and_inputs_for_common()

    UpperCAmelCase			:      Dict			=			_config_zero_init(_SCREAMING_SNAKE_CASE		)
    UpperCAmelCase			:      List[Any]			=			_config_zero_init(configs_no_init.backbone_config		)
    for model_class in self.all_model_classes:
     UpperCAmelCase			:      Dict			=			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 			SCREAMING_SNAKE_CASE  (     self		)						->   List[str]:





    '''simple docstring'''




    pass




   @slow
   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Optional[int]:





    '''simple docstring'''




    for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     UpperCAmelCase			:      Dict			=			UperNetForSemanticSegmentation.from_pretrained(_SCREAMING_SNAKE_CASE		)
     self.assertIsNotNone(_SCREAMING_SNAKE_CASE		)

def    _snake_case		(		):
 UpperCAmelCase			:      str			=			hf_hub_download(
     repo_id="""hf-internal-testing/fixtures_ade20k"""    ,	repo_type="""dataset"""    ,	filename="""ADE_val_00000001.jpg"""		)
 UpperCAmelCase			:      str			=			Image.open(UpperCamelCase		).convert("""RGB"""		)
 return image



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

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





    '''simple docstring'''




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

    UpperCAmelCase			:      Optional[int]			=			prepare_img()
    UpperCAmelCase			:      Optional[int]			=			processor(images=_SCREAMING_SNAKE_CASE   ,  return_tensors="""pt"""		).to(_SCREAMING_SNAKE_CASE		)

    with torch.no_grad():
     UpperCAmelCase			:      List[Any]			=			model(**_SCREAMING_SNAKE_CASE		)

    UpperCAmelCase			:      Union[str, Any]			=			torch.Size((1, model.config.num_labels, 512, 512)		)
    self.assertEqual(outputs.logits.shape   ,  _SCREAMING_SNAKE_CASE		)

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




   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Dict:





    '''simple docstring'''




    UpperCAmelCase			:      List[Any]			=			AutoImageProcessor.from_pretrained("""openmmlab/upernet-convnext-tiny"""		)
    UpperCAmelCase			:      List[Any]			=			UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-convnext-tiny"""		).to(_SCREAMING_SNAKE_CASE		)

    UpperCAmelCase			:      int			=			prepare_img()
    UpperCAmelCase			:      str			=			processor(images=_SCREAMING_SNAKE_CASE   ,  return_tensors="""pt"""		).to(_SCREAMING_SNAKE_CASE		)

    with torch.no_grad():
     UpperCAmelCase			:      Dict			=			model(**_SCREAMING_SNAKE_CASE		)

    UpperCAmelCase			:      Dict			=			torch.Size((1, model.config.num_labels, 512, 512)		)
    self.assertEqual(outputs.logits.shape   ,  _SCREAMING_SNAKE_CASE		)

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





"""simple docstring"""
from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_sentencepiece_available,
    is_torch_available,
)


A:     Union[str, Any]										=	{
    "configuration_speecht5": [
        "SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP",
        "SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP",
        "SpeechT5Config",
        "SpeechT5HifiGanConfig",
    ],
    "feature_extraction_speecht5": ["SpeechT5FeatureExtractor"],
    "processing_speecht5": ["SpeechT5Processor"],
}

try:
      if not is_sentencepiece_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      A:     List[str]										=	["SpeechT5Tokenizer"]

try:
      if not is_torch_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      A:     Dict										=	[
          "SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST",
          "SpeechT5ForSpeechToText",
          "SpeechT5ForSpeechToSpeech",
          "SpeechT5ForTextToSpeech",
          "SpeechT5Model",
          "SpeechT5PreTrainedModel",
          "SpeechT5HifiGan",
      ]

if TYPE_CHECKING:
      from .configuration_speechta import (
          SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP,
          SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP,
          SpeechTaConfig,
          SpeechTaHifiGanConfig,
      )
      from .feature_extraction_speechta import SpeechTaFeatureExtractor
      from .processing_speechta import SpeechTaProcessor

      try:
            if not is_sentencepiece_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .tokenization_speechta import SpeechTaTokenizer

      try:
            if not is_torch_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_speechta import (
                SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST,
                SpeechTaForSpeechToSpeech,
                SpeechTaForSpeechToText,
                SpeechTaForTextToSpeech,
                SpeechTaHifiGan,
                SpeechTaModel,
                SpeechTaPreTrainedModel,
            )

else:
      import sys

      A:     Dict										=	_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
