
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			:			str					, SCREAMING_SNAKE_CASE__			:			Optional[int]					, SCREAMING_SNAKE_CASE__			:			Tuple=13					, SCREAMING_SNAKE_CASE__			:			List[str]=32					, SCREAMING_SNAKE_CASE__			:			List[Any]=3					, SCREAMING_SNAKE_CASE__			:			Union[str, Any]=4					, SCREAMING_SNAKE_CASE__			:			Union[str, Any]=[10, 20, 30, 40]					, SCREAMING_SNAKE_CASE__			:			Tuple=[2, 2, 3, 2]					, SCREAMING_SNAKE_CASE__			:			int=True					, SCREAMING_SNAKE_CASE__			:			Optional[Any]=True					, SCREAMING_SNAKE_CASE__			:			Optional[int]=37					, SCREAMING_SNAKE_CASE__			:			Union[str, Any]="gelu"					, SCREAMING_SNAKE_CASE__			:			Dict=10					, SCREAMING_SNAKE_CASE__			:			Optional[Any]=0.02					, SCREAMING_SNAKE_CASE__			:			List[Any]=["stage2", "stage3", "stage4"]					, SCREAMING_SNAKE_CASE__			:			int=3					, SCREAMING_SNAKE_CASE__			:			Union[str, Any]=None					, ):






      """simple docstring"""



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

 def      __lowerCAmelCase  (						self			:			Optional[int]   ):






      """simple docstring"""



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

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

      UpperCamelCase						    =					self.get_config()

      return config, pixel_values, labels

 def      __lowerCAmelCase  (						self			:			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      __lowerCAmelCase  (						self			:			int   ):






      """simple docstring"""



      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      __lowerCAmelCase  (						self			:			Union[str, Any]					, SCREAMING_SNAKE_CASE__			:			Tuple					, SCREAMING_SNAKE_CASE__			:			Any					, SCREAMING_SNAKE_CASE__			:			Tuple   ):






      """simple docstring"""



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






 def      __lowerCAmelCase  (						self			:			Optional[int]   ):






      """simple docstring"""



      UpperCamelCase						    =					self.prepare_config_and_inputs()
      (
          (
          UpperCamelCase   
      )    ,		(
          UpperCamelCase   
      )    ,		(
          UpperCamelCase   
      )    ,		   
      )						    =					config_and_inputs
      UpperCamelCase						    =					{'pixel_values': pixel_values}
      return config, inputs_dict




@require_torch
class       _lowerCAmelCase  (		a_			,	a_			,	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_				:					Union[str, Any]       						=False
 SCREAMING_SNAKE_CASE_				:					Optional[Any]       						=False
 SCREAMING_SNAKE_CASE_				:					Optional[Any]       						=False
 SCREAMING_SNAKE_CASE_				:					Any       						=False
 SCREAMING_SNAKE_CASE_				:					str       						=False

 def      __lowerCAmelCase  (						self			:			int   ):






      """simple docstring"""



      UpperCamelCase						    =					UperNetModelTester(self   )
      UpperCamelCase						    =					ConfigTester(self					, config_class=_SCREAMING_SNAKE_CASE					, has_text_modality=_SCREAMING_SNAKE_CASE					, hidden_size=37   )

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






      """simple docstring"""



      return

 def      __lowerCAmelCase  (						self			:			Dict   ):






      """simple docstring"""



      UpperCamelCase    ,		UpperCamelCase						    =					self.model_tester.prepare_config_and_inputs_for_common()

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

           UpperCamelCase						    =					['pixel_values']
           self.assertListEqual(arg_names[:1]					, _SCREAMING_SNAKE_CASE   )

 def      __lowerCAmelCase  (						self			:			Optional[Any]   ):






      """simple docstring"""



      UpperCamelCase						    =					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      __lowerCAmelCase  (						self			:			List[Any]   ):






      """simple docstring"""



      pass

 @unittest.skip(reason='UperNet does not support input and output embeddings'   )
 def      __lowerCAmelCase  (						self			:			Optional[int]   ):






      """simple docstring"""



      pass

 @unittest.skip(reason='UperNet does not have a base model'   )
 def      __lowerCAmelCase  (						self			:			List[str]   ):






      """simple docstring"""



      pass

 @unittest.skip(reason='UperNet does not have a base model'   )
 def      __lowerCAmelCase  (						self			:			Optional[int]   ):






      """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			:			Optional[int]   ):






      """simple docstring"""



      pass

 @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'   )
 def      __lowerCAmelCase  (						self			:			Tuple   ):






      """simple docstring"""



      pass

 def      __lowerCAmelCase  (						self			:			List[str]   ):






      """simple docstring"""



      def check_hidden_states_output(SCREAMING_SNAKE_CASE__			:			int					, SCREAMING_SNAKE_CASE__			:			List[str]					, SCREAMING_SNAKE_CASE__			:			str   ):
           UpperCamelCase						    =					model_class(_SCREAMING_SNAKE_CASE   )
           model.to(_SCREAMING_SNAKE_CASE   )
           model.eval()

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

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

           UpperCamelCase						    =					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						    =					self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
           UpperCamelCase						    =					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						    =					True

           check_hidden_states_output(_SCREAMING_SNAKE_CASE					, _SCREAMING_SNAKE_CASE					, _SCREAMING_SNAKE_CASE   )

 def      __lowerCAmelCase  (						self			:			Dict   ):






      """simple docstring"""



      UpperCamelCase    ,		UpperCamelCase						    =					self.model_tester.prepare_config_and_inputs_for_common()

      UpperCamelCase						    =					_config_zero_init(_SCREAMING_SNAKE_CASE   )
      UpperCamelCase						    =					_config_zero_init(configs_no_init.backbone_config   )
      for model_class in self.all_model_classes:
           UpperCamelCase						    =					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      __lowerCAmelCase  (						self			:			Any   ):






      """simple docstring"""



      pass






 @slow
 def      __lowerCAmelCase  (						self			:			Dict   ):






      """simple docstring"""



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




def  __lowerCamelCase					( )       ->      Tuple:
     UpperCamelCase						    =					hf_hub_download(
         repo_id='hf-internal-testing/fixtures_ade20k'						,     repo_type='dataset'						,     filename='ADE_val_00000001.jpg'			)
     UpperCamelCase						    =					Image.open(_lowercase			).convert('RGB'			)
     return image







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

 """simple docstring"""

 def      __lowerCAmelCase  (						self			:			Tuple   ):






      """simple docstring"""



      UpperCamelCase						    =					AutoImageProcessor.from_pretrained('openmmlab/upernet-swin-tiny'   )
      UpperCamelCase						    =					UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-swin-tiny'   ).to(_SCREAMING_SNAKE_CASE   )

      UpperCamelCase						    =					prepare_img()
      UpperCamelCase						    =					processor(images=_SCREAMING_SNAKE_CASE					, return_tensors='pt'   ).to(_SCREAMING_SNAKE_CASE   )

      with torch.no_grad():
           UpperCamelCase						    =					model(**_SCREAMING_SNAKE_CASE   )

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

      UpperCamelCase						    =					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      __lowerCAmelCase  (						self			:			Optional[int]   ):






      """simple docstring"""



      UpperCamelCase						    =					AutoImageProcessor.from_pretrained('openmmlab/upernet-convnext-tiny'   )
      UpperCamelCase						    =					UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-convnext-tiny'   ).to(_SCREAMING_SNAKE_CASE   )

      UpperCamelCase						    =					prepare_img()
      UpperCamelCase						    =					processor(images=_SCREAMING_SNAKE_CASE					, return_tensors='pt'   ).to(_SCREAMING_SNAKE_CASE   )

      with torch.no_grad():
           UpperCamelCase						    =					model(**_SCREAMING_SNAKE_CASE   )

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

      UpperCamelCase						    =					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'''



import operator


def       snake_case   (	snake_case      : list					,		snake_case      : bool = False					,		snake_case      : list | None = None			) ->  list:


    """simple docstring"""


    lowerCAmelCase 						=							operator.lt if reverse else operator.gt
    lowerCAmelCase 						=							solution or []

    if not arr:
        return solution

    lowerCAmelCase 						=							[arr.pop(0			)]
    for i, item in enumerate(snake_case			):
        if _operator(snake_case					,		sublist[-1]			):
            sublist.append(snake_case			)
            arr.pop(snake_case			)

    #  merging sublist into solution list
    if not solution:
        solution.extend(snake_case			)
    else:
        while sublist:
            lowerCAmelCase 						=							sublist.pop(0			)
            for i, xx in enumerate(snake_case			):
                if not _operator(snake_case					,		snake_case			):
                    solution.insert(snake_case					,		snake_case			)
                    break
            else:
                solution.append(snake_case			)

    strand_sort(snake_case					,		snake_case					,		snake_case			)
    return solution


if __name__ == "__main__":
     assert strand_sort([4, 3, 5, 1, 2]) == [1, 2, 3, 4, 5]
     assert strand_sort([4, 3, 5, 1, 2], reverse=True) == [5, 4, 3, 2, 1]





