



"""simple docstring"""







import inspect
import unittest

from transformers import SegformerConfig, is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
     import torch

     from transformers import (
         MODEL_MAPPING,
         SegformerForImageClassification,
         SegformerForSemanticSegmentation,
         SegformerModel,
     )
     from transformers.models.segformer.modeling_segformer import SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
     from PIL import Image

     from transformers import SegformerImageProcessor







class       UpperCamelCase__   (	lowercase_  ):




      """simple docstring"""




      def      SCREAMING_SNAKE_CASE__ (      self				:      Optional[Any]       ):
        lowerCAmelCase_   :				List[Any]								= self.config_class(**self.inputs_dict       )
        self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE_    ,			'hidden_sizes'       )       )
        self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE_    ,			'num_attention_heads'       )       )
        self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE_    ,			'num_encoder_blocks'       )       )







class       UpperCamelCase__   :




      """simple docstring"""




      def __init__(      self				:      List[str]    ,			SCREAMING_SNAKE_CASE_				:      Tuple    ,			SCREAMING_SNAKE_CASE_				:      Any=1_3    ,			SCREAMING_SNAKE_CASE_				:      Dict=6_4    ,			SCREAMING_SNAKE_CASE_				:      Union[str, Any]=3    ,			SCREAMING_SNAKE_CASE_				:      List[str]=4    ,			SCREAMING_SNAKE_CASE_				:      Tuple=[2, 2, 2, 2]    ,			SCREAMING_SNAKE_CASE_				:      Tuple=[8, 4, 2, 1]    ,			SCREAMING_SNAKE_CASE_				:      Optional[Any]=[1_6, 3_2, 6_4, 1_2_8]    ,			SCREAMING_SNAKE_CASE_				:      Tuple=[1, 4, 8, 1_6]    ,			SCREAMING_SNAKE_CASE_				:      List[str]=[1, 2, 4, 8]    ,			SCREAMING_SNAKE_CASE_				:      Union[str, Any]=True    ,			SCREAMING_SNAKE_CASE_				:      Tuple=True    ,			SCREAMING_SNAKE_CASE_				:      Optional[int]="gelu"    ,			SCREAMING_SNAKE_CASE_				:      List[Any]=0.1    ,			SCREAMING_SNAKE_CASE_				:      List[Any]=0.1    ,			SCREAMING_SNAKE_CASE_				:      str=0.02    ,			SCREAMING_SNAKE_CASE_				:      Union[str, Any]=3    ,			SCREAMING_SNAKE_CASE_				:      Union[str, Any]=None    ,			):
        lowerCAmelCase_   :				Optional[int]								= parent
        lowerCAmelCase_   :				Tuple								= batch_size
        lowerCAmelCase_   :				Dict								= image_size
        lowerCAmelCase_   :				Dict								= num_channels
        lowerCAmelCase_   :				List[str]								= num_encoder_blocks
        lowerCAmelCase_   :				Optional[int]								= sr_ratios
        lowerCAmelCase_   :				int								= depths
        lowerCAmelCase_   :				Optional[int]								= hidden_sizes
        lowerCAmelCase_   :				Dict								= downsampling_rates
        lowerCAmelCase_   :				Optional[Any]								= num_attention_heads
        lowerCAmelCase_   :				List[Any]								= is_training
        lowerCAmelCase_   :				Any								= use_labels
        lowerCAmelCase_   :				str								= hidden_act
        lowerCAmelCase_   :				List[str]								= hidden_dropout_prob
        lowerCAmelCase_   :				Optional[int]								= attention_probs_dropout_prob
        lowerCAmelCase_   :				Dict								= initializer_range
        lowerCAmelCase_   :				Optional[Any]								= num_labels
        lowerCAmelCase_   :				List[str]								= scope



      def      SCREAMING_SNAKE_CASE__ (      self				:      Union[str, Any]       ):
        lowerCAmelCase_   :				Optional[int]								= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

        lowerCAmelCase_   :				Tuple								= None
        if self.use_labels:
          lowerCAmelCase_   :				List[str]								= ids_tensor([self.batch_size, self.image_size, self.image_size]    ,			self.num_labels       )

        lowerCAmelCase_   :				Tuple								= self.get_config()
        return config, pixel_values, labels



      def      SCREAMING_SNAKE_CASE__ (      self				:      List[str]       ):
        return SegformerConfig(
            image_size=self.image_size    ,			num_channels=self.num_channels    ,			num_encoder_blocks=self.num_encoder_blocks    ,			depths=self.depths    ,			hidden_sizes=self.hidden_sizes    ,			num_attention_heads=self.num_attention_heads    ,			hidden_act=self.hidden_act    ,			hidden_dropout_prob=self.hidden_dropout_prob    ,			attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,			initializer_range=self.initializer_range    ,			)



      def      SCREAMING_SNAKE_CASE__ (      self				:      Optional[Any]    ,			SCREAMING_SNAKE_CASE_				:      Dict    ,			SCREAMING_SNAKE_CASE_				:      Dict    ,			SCREAMING_SNAKE_CASE_				:      Dict       ):
        lowerCAmelCase_   :				Optional[Any]								= SegformerModel(config=SCREAMING_SNAKE_CASE_       )
        model.to(SCREAMING_SNAKE_CASE_       )
        model.eval()
        lowerCAmelCase_   :				Tuple								= model(SCREAMING_SNAKE_CASE_       )
        lowerCAmelCase_   :				Any								= self.image_size // (self.downsampling_rates[-1] * 2)
        self.parent.assertEqual(
            result.last_hidden_state.shape    ,			(self.batch_size, self.hidden_sizes[-1], expected_height, expected_width)       )



      def      SCREAMING_SNAKE_CASE__ (      self				:      Optional[Any]    ,			SCREAMING_SNAKE_CASE_				:      Union[str, Any]    ,			SCREAMING_SNAKE_CASE_				:      List[Any]    ,			SCREAMING_SNAKE_CASE_				:      Dict       ):
        lowerCAmelCase_   :				Tuple								= self.num_labels
        lowerCAmelCase_   :				Any								= SegformerForSemanticSegmentation(SCREAMING_SNAKE_CASE_       )
        model.to(SCREAMING_SNAKE_CASE_       )
        model.eval()
        lowerCAmelCase_   :				int								= model(SCREAMING_SNAKE_CASE_       )
        self.parent.assertEqual(
            result.logits.shape    ,			(self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4)       )
        lowerCAmelCase_   :				int								= model(SCREAMING_SNAKE_CASE_    ,			labels=SCREAMING_SNAKE_CASE_       )
        self.parent.assertEqual(
            result.logits.shape    ,			(self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4)       )
        self.parent.assertGreater(result.loss    ,			0.0       )



      def      SCREAMING_SNAKE_CASE__ (      self				:      Union[str, Any]    ,			SCREAMING_SNAKE_CASE_				:      List[Any]    ,			SCREAMING_SNAKE_CASE_				:      Any    ,			SCREAMING_SNAKE_CASE_				:      Union[str, Any]       ):
        lowerCAmelCase_   :				int								= 1
        lowerCAmelCase_   :				Optional[Any]								= SegformerForSemanticSegmentation(config=SCREAMING_SNAKE_CASE_       )
        model.to(SCREAMING_SNAKE_CASE_       )
        model.eval()
        lowerCAmelCase_   :				Any								= torch.randint(0    ,			1    ,			(self.batch_size, self.image_size, self.image_size)       ).to(SCREAMING_SNAKE_CASE_       )
        lowerCAmelCase_   :				Any								= model(SCREAMING_SNAKE_CASE_    ,			labels=SCREAMING_SNAKE_CASE_       )
        self.parent.assertGreater(result.loss    ,			0.0       )





      def      SCREAMING_SNAKE_CASE__ (      self				:      Optional[Any]       ):
        lowerCAmelCase_   :				int								= self.prepare_config_and_inputs()
        lowerCAmelCase_						,lowerCAmelCase_						,lowerCAmelCase_   :				List[str]								= config_and_inputs
        lowerCAmelCase_   :				List[str]								= {'pixel_values': pixel_values}
        return config, inputs_dict







@require_torch
class       UpperCamelCase__   (	lowercase_,					lowercase_,					unittest.TestCase  ):




      """simple docstring"""




      _SCREAMING_SNAKE_CASE  				=     (
          (
              SegformerModel,
              SegformerForSemanticSegmentation,
              SegformerForImageClassification,
          )
          if is_torch_available()
          else ()
      )
      _SCREAMING_SNAKE_CASE  				=     (
          {
              """feature-extraction""": SegformerModel,
              """image-classification""": SegformerForImageClassification,
              """image-segmentation""": SegformerForSemanticSegmentation,
          }
          if is_torch_available()
          else {}
      )

      _SCREAMING_SNAKE_CASE  				=     True
      _SCREAMING_SNAKE_CASE  				=     False
      _SCREAMING_SNAKE_CASE  				=     False
      _SCREAMING_SNAKE_CASE  				=     False



      def      SCREAMING_SNAKE_CASE__ (      self				:      int       ):
        lowerCAmelCase_   :				Any								= SegformerModelTester(self       )
        lowerCAmelCase_   :				Any								= SegformerConfigTester(self    ,			config_class=SCREAMING_SNAKE_CASE_       )



      def      SCREAMING_SNAKE_CASE__ (      self				:      Tuple       ):
        self.config_tester.run_common_tests()



      def      SCREAMING_SNAKE_CASE__ (      self				:      Dict       ):
        lowerCAmelCase_   :				List[Any]								= self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_       )



      def      SCREAMING_SNAKE_CASE__ (      self				:      str       ):
        lowerCAmelCase_   :				Dict								= self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_binary_image_segmentation(*SCREAMING_SNAKE_CASE_       )



      def      SCREAMING_SNAKE_CASE__ (      self				:      Any       ):
        lowerCAmelCase_   :				Tuple								= self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_segmentation(*SCREAMING_SNAKE_CASE_       )



      @unittest.skip('SegFormer does not use inputs_embeds'       )
      def      SCREAMING_SNAKE_CASE__ (      self				:      Optional[int]       ):
        pass



      @unittest.skip('SegFormer does not have get_input_embeddings method and get_output_embeddings methods'       )
      def      SCREAMING_SNAKE_CASE__ (      self				:      List[str]       ):
        pass



      def      SCREAMING_SNAKE_CASE__ (      self				:      Optional[int]       ):
        lowerCAmelCase_						,lowerCAmelCase_   :				Optional[int]								= self.model_tester.prepare_config_and_inputs_for_common()

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

          lowerCAmelCase_   :				Tuple								= ['pixel_values']
          self.assertListEqual(arg_names[:1]    ,			SCREAMING_SNAKE_CASE_       )



      def      SCREAMING_SNAKE_CASE__ (      self				:      Tuple       ):
        lowerCAmelCase_						,lowerCAmelCase_   :				Tuple								= self.model_tester.prepare_config_and_inputs_for_common()
        lowerCAmelCase_   :				Optional[int]								= True

        for model_class in self.all_model_classes:
          lowerCAmelCase_   :				List[str]								= True
          lowerCAmelCase_   :				Union[str, Any]								= False
          lowerCAmelCase_   :				Union[str, Any]								= True
          lowerCAmelCase_   :				List[str]								= model_class(SCREAMING_SNAKE_CASE_       )
          model.to(SCREAMING_SNAKE_CASE_       )
          model.eval()
          with torch.no_grad():
            lowerCAmelCase_   :				str								= model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )       )
          lowerCAmelCase_   :				Optional[int]								= outputs.attentions

          lowerCAmelCase_   :				Union[str, Any]								= sum(self.model_tester.depths       )
          self.assertEqual(len(SCREAMING_SNAKE_CASE_       )    ,			SCREAMING_SNAKE_CASE_       )

          # check that output_attentions also work using config
          del inputs_dict["output_attentions"]
          lowerCAmelCase_   :				Dict								= True
          lowerCAmelCase_   :				Tuple								= model_class(SCREAMING_SNAKE_CASE_       )
          model.to(SCREAMING_SNAKE_CASE_       )
          model.eval()
          with torch.no_grad():
            lowerCAmelCase_   :				Optional[int]								= model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )       )
          lowerCAmelCase_   :				Union[str, Any]								= outputs.attentions

          self.assertEqual(len(SCREAMING_SNAKE_CASE_       )    ,			SCREAMING_SNAKE_CASE_       )

          # verify the first attentions (first block, first layer)
          lowerCAmelCase_   :				str								= (self.model_tester.image_size // 4) ** 2
          lowerCAmelCase_   :				Union[str, Any]								= (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
          self.assertListEqual(
              list(attentions[0].shape[-3:]       )    ,			[self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len]    ,			)

          # verify the last attentions (last block, last layer)
          lowerCAmelCase_   :				int								= (self.model_tester.image_size // 3_2) ** 2
          lowerCAmelCase_   :				int								= (self.model_tester.image_size // (3_2 * self.model_tester.sr_ratios[-1])) ** 2
          self.assertListEqual(
              list(attentions[-1].shape[-3:]       )    ,			[self.model_tester.num_attention_heads[-1], expected_seq_len, expected_reduced_seq_len]    ,			)
          lowerCAmelCase_   :				Any								= len(SCREAMING_SNAKE_CASE_       )

          # Check attention is always last and order is fine
          lowerCAmelCase_   :				Optional[int]								= True
          lowerCAmelCase_   :				int								= True
          lowerCAmelCase_   :				Any								= model_class(SCREAMING_SNAKE_CASE_       )
          model.to(SCREAMING_SNAKE_CASE_       )
          model.eval()
          with torch.no_grad():
            lowerCAmelCase_   :				Union[str, Any]								= model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )       )

          self.assertEqual(out_len + 1    ,			len(SCREAMING_SNAKE_CASE_       )       )

          lowerCAmelCase_   :				Tuple								= outputs.attentions

          self.assertEqual(len(SCREAMING_SNAKE_CASE_       )    ,			SCREAMING_SNAKE_CASE_       )
          # verify the first attentions (first block, first layer)
          lowerCAmelCase_   :				Optional[Any]								= (self.model_tester.image_size // 4) ** 2
          lowerCAmelCase_   :				Any								= (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
          self.assertListEqual(
              list(self_attentions[0].shape[-3:]       )    ,			[self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len]    ,			)



      def      SCREAMING_SNAKE_CASE__ (      self				:      List[Any]       ):
        def check_hidden_states_output(SCREAMING_SNAKE_CASE_				:      Optional[int]    ,			SCREAMING_SNAKE_CASE_				:      List[Any]    ,			SCREAMING_SNAKE_CASE_				:      str       ):
          lowerCAmelCase_   :				List[str]								= model_class(SCREAMING_SNAKE_CASE_       )
          model.to(SCREAMING_SNAKE_CASE_       )
          model.eval()

          with torch.no_grad():
            lowerCAmelCase_   :				int								= model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )       )

          lowerCAmelCase_   :				Dict								= outputs.hidden_states

          lowerCAmelCase_   :				Any								= self.model_tester.num_encoder_blocks
          self.assertEqual(len(SCREAMING_SNAKE_CASE_       )    ,			SCREAMING_SNAKE_CASE_       )

          # verify the first hidden states (first block)
          self.assertListEqual(
              list(hidden_states[0].shape[-3:]       )    ,			[
                  self.model_tester.hidden_sizes[0],
                  self.model_tester.image_size // 4,
                  self.model_tester.image_size // 4,
              ]    ,			)

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

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

          check_hidden_states_output(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )



      def      SCREAMING_SNAKE_CASE__ (      self				:      Any       ):
        if not self.model_tester.is_training:
          return

        lowerCAmelCase_						,lowerCAmelCase_   :				int								= self.model_tester.prepare_config_and_inputs_for_common()
        lowerCAmelCase_   :				Tuple								= True

        for model_class in self.all_model_classes:
          if model_class in get_values(SCREAMING_SNAKE_CASE_       ):
            continue

          lowerCAmelCase_   :				Optional[int]								= model_class(SCREAMING_SNAKE_CASE_       )
          model.to(SCREAMING_SNAKE_CASE_       )
          model.train()
          lowerCAmelCase_   :				Tuple								= self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			return_labels=SCREAMING_SNAKE_CASE_       )
          lowerCAmelCase_   :				Tuple								= model(**SCREAMING_SNAKE_CASE_       ).loss
          loss.backward()



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





      @slow
      def      SCREAMING_SNAKE_CASE__ (      self				:      List[str]       ):
        for model_name in SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          lowerCAmelCase_   :				Union[str, Any]								= SegformerModel.from_pretrained(SCREAMING_SNAKE_CASE_       )
          self.assertIsNotNone(SCREAMING_SNAKE_CASE_       )




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

  """simple docstring"""




  lowerCAmelCase_   :				str								= Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'						)
  return image







@require_torch
class       UpperCamelCase__   (	unittest.TestCase  ):




      """simple docstring"""




      @slow
      def      SCREAMING_SNAKE_CASE__ (      self				:      Tuple       ):
        # only resize + normalize
        lowerCAmelCase_   :				Optional[Any]								= SegformerImageProcessor(
            image_scale=(5_1_2, 5_1_2)    ,			keep_ratio=SCREAMING_SNAKE_CASE_    ,			align=SCREAMING_SNAKE_CASE_    ,			do_random_crop=SCREAMING_SNAKE_CASE_       )
        lowerCAmelCase_   :				Dict								= SegformerForSemanticSegmentation.from_pretrained('nvidia/segformer-b0-finetuned-ade-512-512'       ).to(
            SCREAMING_SNAKE_CASE_       )

        lowerCAmelCase_   :				Any								= prepare_img()
        lowerCAmelCase_   :				Optional[int]								= image_processor(images=SCREAMING_SNAKE_CASE_    ,			return_tensors='pt'       )
        lowerCAmelCase_   :				str								= encoded_inputs.pixel_values.to(SCREAMING_SNAKE_CASE_       )

        with torch.no_grad():
          lowerCAmelCase_   :				Dict								= model(SCREAMING_SNAKE_CASE_       )

        lowerCAmelCase_   :				Dict								= torch.Size((1, model.config.num_labels, 1_2_8, 1_2_8)       )
        self.assertEqual(outputs.logits.shape    ,			SCREAMING_SNAKE_CASE_       )

        lowerCAmelCase_   :				str								= torch.tensor(
            [
                [[-4.63_10, -5.52_32, -6.23_56], [-5.19_21, -6.14_44, -6.59_96], [-5.44_24, -6.27_90, -6.75_74]],
                [[-12.13_91, -13.31_22, -13.95_54], [-12.87_32, -13.93_52, -14.35_63], [-12.94_38, -13.82_26, -14.25_13]],
                [[-12.51_34, -13.46_86, -14.49_15], [-12.86_69, -14.43_43, -14.77_58], [-13.25_23, -14.58_19, -15.06_94]],
            ]       ).to(SCREAMING_SNAKE_CASE_       )
        self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]    ,			SCREAMING_SNAKE_CASE_    ,			atol=1E-4       )       )



      @slow
      def      SCREAMING_SNAKE_CASE__ (      self				:      Union[str, Any]       ):
        # only resize + normalize
        lowerCAmelCase_   :				Dict								= SegformerImageProcessor(
            image_scale=(5_1_2, 5_1_2)    ,			keep_ratio=SCREAMING_SNAKE_CASE_    ,			align=SCREAMING_SNAKE_CASE_    ,			do_random_crop=SCREAMING_SNAKE_CASE_       )
        lowerCAmelCase_   :				int								= SegformerForSemanticSegmentation.from_pretrained(
            'nvidia/segformer-b1-finetuned-cityscapes-1024-1024'       ).to(SCREAMING_SNAKE_CASE_       )

        lowerCAmelCase_   :				Tuple								= prepare_img()
        lowerCAmelCase_   :				Tuple								= image_processor(images=SCREAMING_SNAKE_CASE_    ,			return_tensors='pt'       )
        lowerCAmelCase_   :				Tuple								= encoded_inputs.pixel_values.to(SCREAMING_SNAKE_CASE_       )

        with torch.no_grad():
          lowerCAmelCase_   :				int								= model(SCREAMING_SNAKE_CASE_       )

        lowerCAmelCase_   :				Tuple								= torch.Size((1, model.config.num_labels, 1_2_8, 1_2_8)       )
        self.assertEqual(outputs.logits.shape    ,			SCREAMING_SNAKE_CASE_       )

        lowerCAmelCase_   :				Optional[Any]								= torch.tensor(
            [
                [[-13.57_48, -13.91_11, -12.65_00], [-14.35_00, -15.36_83, -14.23_28], [-14.75_32, -16.04_24, -15.60_87]],
                [[-17.16_51, -15.87_25, -12.96_53], [-17.25_80, -17.37_18, -14.82_23], [-16.60_58, -16.87_83, -16.74_52]],
                [[-3.64_56, -3.02_09, -1.42_03], [-3.07_97, -3.19_59, -2.00_00], [-1.87_57, -1.92_17, -1.69_97]],
            ]       ).to(SCREAMING_SNAKE_CASE_       )
        self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]    ,			SCREAMING_SNAKE_CASE_    ,			atol=1E-1       )       )





      @slow
      def      SCREAMING_SNAKE_CASE__ (      self				:      Any       ):
        # only resize + normalize
        lowerCAmelCase_   :				Tuple								= SegformerImageProcessor(
            image_scale=(5_1_2, 5_1_2)    ,			keep_ratio=SCREAMING_SNAKE_CASE_    ,			align=SCREAMING_SNAKE_CASE_    ,			do_random_crop=SCREAMING_SNAKE_CASE_       )
        lowerCAmelCase_   :				Any								= SegformerForSemanticSegmentation.from_pretrained('nvidia/segformer-b0-finetuned-ade-512-512'       ).to(
            SCREAMING_SNAKE_CASE_       )

        lowerCAmelCase_   :				Optional[Any]								= prepare_img()
        lowerCAmelCase_   :				Dict								= image_processor(images=SCREAMING_SNAKE_CASE_    ,			return_tensors='pt'       )
        lowerCAmelCase_   :				Union[str, Any]								= encoded_inputs.pixel_values.to(SCREAMING_SNAKE_CASE_       )

        with torch.no_grad():
          lowerCAmelCase_   :				Union[str, Any]								= model(SCREAMING_SNAKE_CASE_       )

        lowerCAmelCase_   :				Union[str, Any]								= outputs.logits.detach().cpu()

        lowerCAmelCase_   :				Optional[Any]								= image_processor.post_process_semantic_segmentation(outputs=SCREAMING_SNAKE_CASE_    ,			target_sizes=[(5_0_0, 3_0_0)]       )
        lowerCAmelCase_   :				int								= torch.Size((5_0_0, 3_0_0)       )
        self.assertEqual(segmentation[0].shape    ,			SCREAMING_SNAKE_CASE_       )

        lowerCAmelCase_   :				List[str]								= image_processor.post_process_semantic_segmentation(outputs=SCREAMING_SNAKE_CASE_       )
        lowerCAmelCase_   :				str								= torch.Size((1_2_8, 1_2_8)       )
        self.assertEqual(segmentation[0].shape    ,			SCREAMING_SNAKE_CASE_       )










"""simple docstring"""







import random

def 				UpperCamelCase_    (    lowerCAmelCase__      :				int    ,   lowerCAmelCase__      :				float    ,   lowerCAmelCase__      :				bool = False						)						->   dict:

  """simple docstring"""




  lowerCAmelCase_   :				dict								= {i: [] for i in range(lowerCAmelCase__						)}

  # if probability is greater or equal than 1, then generate a complete graph
  if probability >= 1:
    return complete_graph(lowerCAmelCase__						)
  # if probability is lower or equal than 0, then return a graph without edges
  if probability <= 0:
    return graph

  # for each couple of nodes, add an edge from u to v
  # if the number randomly generated is greater than probability probability
  for i in range(lowerCAmelCase__						):
    for j in range(i + 1    ,   lowerCAmelCase__						):
      if random.random() < probability:
        graph[i].append(lowerCAmelCase__						)
        if not directed:
          # if the graph is undirected, add an edge in from j to i, either
          graph[j].append(lowerCAmelCase__						)
  return graph

def 				UpperCamelCase_    (    lowerCAmelCase__      :				int						)						->   dict:

  """simple docstring"""




  return {
      i: [j for j in range(lowerCAmelCase__						) if i != j] for i in range(lowerCAmelCase__						)
  }


if __name__ == "__main__":
     import doctest

     doctest.testmod()





