






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





  """simple docstring"""



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





       '''simple docstring'''

       __a       =   parent
       __a       =   batch_size
       __a       =   image_size
       __a       =   num_channels
       __a       =   num_stages
       __a       =   hidden_sizes
       __a       =   depths
       __a       =   is_training
       __a       =   use_labels
       __a       =   intermediate_size
       __a       =   hidden_act
       __a       =   type_sequence_label_size
       __a       =   initializer_range
       __a       =   out_features
       __a       =   num_labels
       __a       =   scope
       __a       =   num_stages

  def __a						(					self     :							List[str]						):





       '''simple docstring'''

       __a       =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

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

       __a       =   self.get_config()

       return config, pixel_values, labels

  def __a						(					self     :							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 __a						(					self     :							List[str]						):





       '''simple docstring'''

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

  def __a						(					self     :							Optional[int]				,							SCREAMING_SNAKE_CASE__     :							List[Any]				,							SCREAMING_SNAKE_CASE__     :							str				,							SCREAMING_SNAKE_CASE__     :							List[Any]						):





       '''simple docstring'''

       __a       =   UperNetForSemanticSegmentation(config=__A						)
       model.to(__A						)
       model.eval()
       __a       =   model(__A						)
       self.parent.assertEqual(
           result.logits.shape				,							(self.batch_size, self.num_labels, self.image_size, self.image_size)						)


  def __a						(					self     :							List[str]						):





       '''simple docstring'''

       __a       =   self.prepare_config_and_inputs()
       (
           __a		
       )       =   config_and_inputs
       __a       =   {"pixel_values": pixel_values}
       return config, inputs_dict


@require_torch
class  lowerCAmelCase_						(       snake_case__		,    snake_case__		,    unittest.TestCase      ):





  """simple docstring"""



  a_       :int												=(UperNetForSemanticSegmentation,) if is_torch_available() else ()
  a_       :Any												={"""image-segmentation""": UperNetForSemanticSegmentation} if is_torch_available() else {}
  a_       :Optional[Any]												=False
  a_       :List[str]												=False
  a_       :List[Any]												=False
  a_       :int												=False
  a_       :Tuple												=False
  a_       :Optional[Any]												=False

  def __a						(					self     :							int						):





       '''simple docstring'''

       __a       =   UperNetModelTester(self						)
       __a       =   ConfigTester(self				,							config_class=__A				,							has_text_modality=__A				,							hidden_size=3_7						)

  def __a						(					self     :							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 __a						(					self     :							str						):





       '''simple docstring'''

       return

  def __a						(					self     :							int						):





       '''simple docstring'''

       __a       =   self.model_tester.prepare_config_and_inputs_for_common()

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

            __a       =   ["pixel_values"]
            self.assertListEqual(arg_names[:1]				,							__A						)

  def __a						(					self     :							Optional[int]						):





       '''simple docstring'''

       __a       =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_semantic_segmentation(*__A						)

  @unittest.skip(reason="""UperNet does not use inputs_embeds"""						)
  def __a						(					self     :							Dict						):





       '''simple docstring'''

       pass

  @unittest.skip(reason="""UperNet does not support input and output embeddings"""						)
  def __a						(					self     :							List[Any]						):





       '''simple docstring'''

       pass

  @unittest.skip(reason="""UperNet does not have a base model"""						)
  def __a						(					self     :							Dict						):





       '''simple docstring'''

       pass

  @unittest.skip(reason="""UperNet does not have a base model"""						)
  def __a						(					self     :							Union[str, 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 __a						(					self     :							Any						):





       '''simple docstring'''

       pass

  @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""						)
  def __a						(					self     :							Optional[Any]						):





       '''simple docstring'''

       pass

  def __a						(					self     :							int						):





       '''simple docstring'''

       def check_hidden_states_output(SCREAMING_SNAKE_CASE__     :							int				,							SCREAMING_SNAKE_CASE__     :							List[str]				,							SCREAMING_SNAKE_CASE__     :							Optional[int]						):
            __a       =   model_class(__A						)
            model.to(__A						)
            model.eval()

            with torch.no_grad():
                 __a       =   model(**self._prepare_for_class(__A				,							__A						)						)

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

            __a       =   self.model_tester.num_stages
            self.assertEqual(len(__A						)				,							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]				,							)

       __a       =   self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
            __a       =   True
            check_hidden_states_output(__A				,							__A				,							__A						)

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

            check_hidden_states_output(__A				,							__A				,							__A						)

  def __a						(					self     :							List[str]						):





       '''simple docstring'''

       __a       =   self.model_tester.prepare_config_and_inputs_for_common()

       __a       =   _config_zero_init(__A						)
       __a       =   _config_zero_init(configs_no_init.backbone_config						)
       for model_class in self.all_model_classes:
            __a       =   model_class(config=__A						)
            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     :							Optional[Any]						):





       '''simple docstring'''

       pass


  @slow
  def __a						(					self     :							Any						):





       '''simple docstring'''

       for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            __a       =   UperNetForSemanticSegmentation.from_pretrained(__A						)
            self.assertIsNotNone(__A						)




def        __lowercase						(      )				->					List[str]:
     """simple docstring"""




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



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





  """simple docstring"""



  def __a						(					self     :							List[Any]						):





       '''simple docstring'''

       __a       =   AutoImageProcessor.from_pretrained("""openmmlab/upernet-swin-tiny"""						)
       __a       =   UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-swin-tiny"""						).to(__A						)

       __a       =   prepare_img()
       __a       =   processor(images=__A				,							return_tensors="""pt"""						).to(__A						)

       with torch.no_grad():
            __a       =   model(**__A						)

       __a       =   torch.Size((1, model.config.num_labels, 5_1_2, 5_1_2)						)
       self.assertEqual(outputs.logits.shape				,							__A						)

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


  def __a						(					self     :							Dict						):





       '''simple docstring'''

       __a       =   AutoImageProcessor.from_pretrained("""openmmlab/upernet-convnext-tiny"""						)
       __a       =   UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-convnext-tiny"""						).to(__A						)

       __a       =   prepare_img()
       __a       =   processor(images=__A				,							return_tensors="""pt"""						).to(__A						)

       with torch.no_grad():
            __a       =   model(**__A						)

       __a       =   torch.Size((1, model.config.num_labels, 5_1_2, 5_1_2)						)
       self.assertEqual(outputs.logits.shape				,							__A						)

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










'''simple docstring'''







from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


SCREAMING_SNAKE_CASE_      =			{
    'configuration_bridgetower': [
        'BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP',
        'BridgeTowerConfig',
        'BridgeTowerTextConfig',
        'BridgeTowerVisionConfig',
    ],
    'processing_bridgetower': ['BridgeTowerProcessor'],
}

try:
 if not is_vision_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 SCREAMING_SNAKE_CASE_      =			['BridgeTowerImageProcessor']

try:
 if not is_torch_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 SCREAMING_SNAKE_CASE_      =			[
     'BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST',
     'BridgeTowerForContrastiveLearning',
     'BridgeTowerForImageAndTextRetrieval',
     'BridgeTowerForMaskedLM',
     'BridgeTowerModel',
     'BridgeTowerPreTrainedModel',
 ]


if TYPE_CHECKING:
 from .configuration_bridgetower import (
     BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP,
     BridgeTowerConfig,
     BridgeTowerTextConfig,
     BridgeTowerVisionConfig,
 )
 from .processing_bridgetower import BridgeTowerProcessor

 try:
  if not is_vision_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .image_processing_bridgetower import BridgeTowerImageProcessor

 try:
  if not is_torch_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_bridgetower import (
      BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST,
      BridgeTowerForContrastiveLearning,
      BridgeTowerForImageAndTextRetrieval,
      BridgeTowerForMaskedLM,
      BridgeTowerModel,
      BridgeTowerPreTrainedModel,
  )


else:
 import sys

 SCREAMING_SNAKE_CASE_      =			_LazyModule(__name__, globals()['__file__'], _import_structure)






