'''simple docstring'''




_A								=   [
    'Audio',
    'Array2D',
    'Array3D',
    'Array4D',
    'Array5D',
    'ClassLabel',
    'Features',
    'Sequence',
    'Value',
    'Image',
    'Translation',
    'TranslationVariableLanguages',
]
from .audio import Audio
from .features import ArrayaD, ArrayaD, ArrayaD, ArrayaD, ClassLabel, Features, Sequence, Value
from .image import Image
from .translation import Translation, TranslationVariableLanguages





'''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__  (       _snake_case			):






   """simple docstring"""
   def 		_lowerCamelCase (self				)    ->     Any:
        lowercase_					:       Optional[Any]     				=					self.config_class(**self.inputs_dict				)
        self.parent.assertTrue(hasattr(_a       ,				'hidden_sizes'				)				)
        self.parent.assertTrue(hasattr(_a       ,				'num_attention_heads'				)				)
        self.parent.assertTrue(hasattr(_a       ,				'num_encoder_blocks'				)				)



class       UpperCAmelCase__  :






   """simple docstring"""
   def __init__(self       ,				_a       ,				_a=13       ,				_a=64       ,				_a=3       ,				_a=4       ,				_a=[2, 2, 2, 2]       ,				_a=[8, 4, 2, 1]       ,				_a=[16, 32, 64, 128]       ,				_a=[1, 4, 8, 16]       ,				_a=[1, 2, 4, 8]       ,				_a=True       ,				_a=True       ,				_a="gelu"       ,				_a=0.1       ,				_a=0.1       ,				_a=0.02       ,				_a=3       ,				_a=None       ,				)    ->     List[Any]:
        lowercase_					:       Dict     				=					parent
        lowercase_					:       int     				=					batch_size
        lowercase_					:       Any     				=					image_size
        lowercase_					:       List[str]     				=					num_channels
        lowercase_					:       str     				=					num_encoder_blocks
        lowercase_					:       Tuple     				=					sr_ratios
        lowercase_					:       Tuple     				=					depths
        lowercase_					:       Dict     				=					hidden_sizes
        lowercase_					:       Optional[int]     				=					downsampling_rates
        lowercase_					:       List[str]     				=					num_attention_heads
        lowercase_					:       List[Any]     				=					is_training
        lowercase_					:       Dict     				=					use_labels
        lowercase_					:       Optional[Any]     				=					hidden_act
        lowercase_					:       Any     				=					hidden_dropout_prob
        lowercase_					:       int     				=					attention_probs_dropout_prob
        lowercase_					:       Any     				=					initializer_range
        lowercase_					:       List[str]     				=					num_labels
        lowercase_					:       str     				=					scope
   def 		_lowerCamelCase (self				)    ->     str:
        lowercase_					:       Union[str, Any]     				=					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

        lowercase_					:       str     				=					None
        if self.use_labels:
             lowercase_					:       Optional[Any]     				=					ids_tensor([self.batch_size, self.image_size, self.image_size]       ,				self.num_labels				)

        lowercase_					:       Tuple     				=					self.get_config()
        return config, pixel_values, labels
   def 		_lowerCamelCase (self				)    ->     List[Any]:
        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 		_lowerCamelCase (self       ,				_a       ,				_a       ,				_a				)    ->     Dict:
        lowercase_					:       Union[str, Any]     				=					SegformerModel(config=_a				)
        model.to(_a				)
        model.eval()
        lowercase_					:       int     				=					model(_a				)
        lowercase_					:       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 		_lowerCamelCase (self       ,				_a       ,				_a       ,				_a				)    ->     Tuple:
        lowercase_					:       Optional[Any]     				=					self.num_labels
        lowercase_					:       Union[str, Any]     				=					SegformerForSemanticSegmentation(_a				)
        model.to(_a				)
        model.eval()
        lowercase_					:       Tuple     				=					model(_a				)
        self.parent.assertEqual(
            result.logits.shape       ,				(self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4)				)
        lowercase_					:       str     				=					model(_a       ,				labels=_a				)
        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 		_lowerCamelCase (self       ,				_a       ,				_a       ,				_a				)    ->     int:
        lowercase_					:       Dict     				=					1
        lowercase_					:       Dict     				=					SegformerForSemanticSegmentation(config=_a				)
        model.to(_a				)
        model.eval()
        lowercase_					:       List[str]     				=					torch.randint(0       ,				1       ,				(self.batch_size, self.image_size, self.image_size)				).to(_a				)
        lowercase_					:       Any     				=					model(_a       ,				labels=_a				)
        self.parent.assertGreater(result.loss       ,				0.0				)





   def 		_lowerCamelCase (self				)    ->     str:
        lowercase_					:       Any     				=					self.prepare_config_and_inputs()
        lowercase_				,lowercase_				,lowercase_					:       Dict     				=					config_and_inputs
        lowercase_					:       int     				=					{'pixel_values': pixel_values}
        return config, inputs_dict



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






   """simple docstring"""
   A							:       int     =    (
       (
           SegformerModel,
           SegformerForSemanticSegmentation,
           SegformerForImageClassification,
       )
       if is_torch_available()
       else ()
   )
   A							:       Tuple     =    (
       {
           '''feature-extraction''': SegformerModel,
           '''image-classification''': SegformerForImageClassification,
           '''image-segmentation''': SegformerForSemanticSegmentation,
       }
       if is_torch_available()
       else {}
   )

   A							:       str     =    True
   A							:       int     =    False
   A							:       int     =    False
   A							:       Optional[Any]     =    False
   def 		_lowerCamelCase (self				)    ->     int:
        lowercase_					:       List[str]     				=					SegformerModelTester(self				)
        lowercase_					:       str     				=					SegformerConfigTester(self       ,				config_class=_a				)
   def 		_lowerCamelCase (self				)    ->     str:
        self.config_tester.run_common_tests()
   def 		_lowerCamelCase (self				)    ->     Dict:
        lowercase_					:       Dict     				=					self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*_a				)
   def 		_lowerCamelCase (self				)    ->     Dict:
        lowercase_					:       Any     				=					self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_binary_image_segmentation(*_a				)
   def 		_lowerCamelCase (self				)    ->     Union[str, Any]:
        lowercase_					:       int     				=					self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_segmentation(*_a				)
   @unittest.skip('SegFormer does not use inputs_embeds'				)
   def 		_lowerCamelCase (self				)    ->     Any:
        pass
   @unittest.skip('SegFormer does not have get_input_embeddings method and get_output_embeddings methods'				)
   def 		_lowerCamelCase (self				)    ->     Optional[int]:
        pass
   def 		_lowerCamelCase (self				)    ->     Dict:
        lowercase_				,lowercase_					:       Optional[int]     				=					self.model_tester.prepare_config_and_inputs_for_common()

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

             lowercase_					:       Dict     				=					['pixel_values']
             self.assertListEqual(arg_names[:1]       ,				_a				)
   def 		_lowerCamelCase (self				)    ->     Tuple:
        lowercase_				,lowercase_					:       Dict     				=					self.model_tester.prepare_config_and_inputs_for_common()
        lowercase_					:       Optional[Any]     				=					True

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

             lowercase_					:       Tuple     				=					sum(self.model_tester.depths				)
             self.assertEqual(len(_a				)       ,				_a				)

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

             self.assertEqual(len(_a				)       ,				_a				)

             # verify the first attentions (first block, first layer)
             lowercase_					:       Any     				=					(self.model_tester.image_size // 4) ** 2
             lowercase_					:       Dict     				=					(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)
             lowercase_					:       Optional[int]     				=					(self.model_tester.image_size // 32) ** 2
             lowercase_					:       Optional[int]     				=					(self.model_tester.image_size // (32 * 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]       ,				)
             lowercase_					:       Optional[Any]     				=					len(_a				)

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

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

             lowercase_					:       List[Any]     				=					outputs.attentions

             self.assertEqual(len(_a				)       ,				_a				)
             # verify the first attentions (first block, first layer)
             lowercase_					:       Any     				=					(self.model_tester.image_size // 4) ** 2
             lowercase_					:       List[str]     				=					(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 		_lowerCamelCase (self				)    ->     List[str]:
        def check_hidden_states_output(_a       ,				_a       ,				_a				):
             lowercase_					:       Dict     				=					model_class(_a				)
             model.to(_a				)
             model.eval()

             with torch.no_grad():
                  lowercase_					:       List[Any]     				=					model(**self._prepare_for_class(_a       ,				_a				)				)

             lowercase_					:       Any     				=					outputs.hidden_states

             lowercase_					:       str     				=					self.model_tester.num_encoder_blocks
             self.assertEqual(len(_a				)       ,				_a				)

             # 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,
                 ]       ,				)

        lowercase_				,lowercase_					:       Optional[Any]     				=					self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
             lowercase_					:       str     				=					True
             check_hidden_states_output(_a       ,				_a       ,				_a				)

             # check that output_hidden_states also work using config
             del inputs_dict["output_hidden_states"]
             lowercase_					:       Optional[Any]     				=					True

             check_hidden_states_output(_a       ,				_a       ,				_a				)
   def 		_lowerCamelCase (self				)    ->     Dict:
        if not self.model_tester.is_training:
             return

        lowercase_				,lowercase_					:       Optional[Any]     				=					self.model_tester.prepare_config_and_inputs_for_common()
        lowercase_					:       List[Any]     				=					True

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

             lowercase_					:       Optional[int]     				=					model_class(_a				)
             model.to(_a				)
             model.train()
             lowercase_					:       List[Any]     				=					self._prepare_for_class(_a       ,				_a       ,				return_labels=_a				)
             lowercase_					:       str     				=					model(**_a				).loss
             loss.backward()
   @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'				)
   def 		_lowerCamelCase (self				)    ->     str:
        pass





   @slow
   def 		_lowerCamelCase (self				)    ->     Any:
        for model_name in SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             lowercase_					:       List[Any]     				=					SegformerModel.from_pretrained(_a				)
             self.assertIsNotNone(_a				)



def _UpperCamelCase   (       ):
     lowercase_					:       int     				=					Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'							)
     return image






@require_torch
class       UpperCAmelCase__  (       unittest.TestCase			):






   """simple docstring"""
   @slow
   def 		_lowerCamelCase (self				)    ->     Union[str, Any]:
        # only resize + normalize
        lowercase_					:       Union[str, Any]     				=					SegformerImageProcessor(
            image_scale=(512, 512)       ,				keep_ratio=_a       ,				align=_a       ,				do_random_crop=_a				)
        lowercase_					:       List[str]     				=					SegformerForSemanticSegmentation.from_pretrained('nvidia/segformer-b0-finetuned-ade-512-512'				).to(
            _a				)

        lowercase_					:       int     				=					prepare_img()
        lowercase_					:       int     				=					image_processor(images=_a       ,				return_tensors='pt'				)
        lowercase_					:       int     				=					encoded_inputs.pixel_values.to(_a				)

        with torch.no_grad():
             lowercase_					:       List[Any]     				=					model(_a				)

        lowercase_					:       Union[str, Any]     				=					torch.Size((1, model.config.num_labels, 128, 128)				)
        self.assertEqual(outputs.logits.shape       ,				_a				)

        lowercase_					:       int     				=					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(_a				)
        self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]       ,				_a       ,				atol=1e-4				)				)
   @slow
   def 		_lowerCamelCase (self				)    ->     Dict:
        # only resize + normalize
        lowercase_					:       Optional[Any]     				=					SegformerImageProcessor(
            image_scale=(512, 512)       ,				keep_ratio=_a       ,				align=_a       ,				do_random_crop=_a				)
        lowercase_					:       Union[str, Any]     				=					SegformerForSemanticSegmentation.from_pretrained(
            'nvidia/segformer-b1-finetuned-cityscapes-1024-1024'				).to(_a				)

        lowercase_					:       Optional[Any]     				=					prepare_img()
        lowercase_					:       Tuple     				=					image_processor(images=_a       ,				return_tensors='pt'				)
        lowercase_					:       Any     				=					encoded_inputs.pixel_values.to(_a				)

        with torch.no_grad():
             lowercase_					:       Union[str, Any]     				=					model(_a				)

        lowercase_					:       str     				=					torch.Size((1, model.config.num_labels, 128, 128)				)
        self.assertEqual(outputs.logits.shape       ,				_a				)

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





   @slow
   def 		_lowerCamelCase (self				)    ->     Optional[Any]:
        # only resize + normalize
        lowercase_					:       List[Any]     				=					SegformerImageProcessor(
            image_scale=(512, 512)       ,				keep_ratio=_a       ,				align=_a       ,				do_random_crop=_a				)
        lowercase_					:       List[Any]     				=					SegformerForSemanticSegmentation.from_pretrained('nvidia/segformer-b0-finetuned-ade-512-512'				).to(
            _a				)

        lowercase_					:       List[str]     				=					prepare_img()
        lowercase_					:       List[str]     				=					image_processor(images=_a       ,				return_tensors='pt'				)
        lowercase_					:       Optional[Any]     				=					encoded_inputs.pixel_values.to(_a				)

        with torch.no_grad():
             lowercase_					:       Dict     				=					model(_a				)

        lowercase_					:       Optional[int]     				=					outputs.logits.detach().cpu()

        lowercase_					:       Tuple     				=					image_processor.post_process_semantic_segmentation(outputs=_a       ,				target_sizes=[(500, 300)]				)
        lowercase_					:       Any     				=					torch.Size((500, 300)				)
        self.assertEqual(segmentation[0].shape       ,				_a				)

        lowercase_					:       List[str]     				=					image_processor.post_process_semantic_segmentation(outputs=_a				)
        lowercase_					:       Optional[int]     				=					torch.Size((128, 128)				)
        self.assertEqual(segmentation[0].shape       ,				_a				)




