



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 			__lowerCAmelCase  (						lowerCAmelCase__ ):




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    __lowerCamelCase    				=     self.config_class(**self.inputs_dict					)
    self.parent.assertTrue(hasattr(__UpperCAmelCase						,					'''hidden_sizes'''					)					)
    self.parent.assertTrue(hasattr(__UpperCAmelCase						,					'''num_attention_heads'''					)					)
    self.parent.assertTrue(hasattr(__UpperCAmelCase						,					'''num_encoder_blocks'''					)					)



class 			__lowerCAmelCase  :




 def __init__(    self						,					__UpperCAmelCase						,					__UpperCAmelCase=13						,					__UpperCAmelCase=64						,					__UpperCAmelCase=3						,					__UpperCAmelCase=4						,					__UpperCAmelCase=[2, 2, 2, 2]						,					__UpperCAmelCase=[8, 4, 2, 1]						,					__UpperCAmelCase=[16, 32, 64, 128]						,					__UpperCAmelCase=[1, 4, 8, 16]						,					__UpperCAmelCase=[1, 2, 4, 8]						,					__UpperCAmelCase=True						,					__UpperCAmelCase=True						,					__UpperCAmelCase="gelu"						,					__UpperCAmelCase=0.1						,					__UpperCAmelCase=0.1						,					__UpperCAmelCase=0.02						,					__UpperCAmelCase=3						,					__UpperCAmelCase=None						,					):



    '''simple docstring'''
    __lowerCamelCase    				=     parent
    __lowerCamelCase    				=     batch_size
    __lowerCamelCase    				=     image_size
    __lowerCamelCase    				=     num_channels
    __lowerCamelCase    				=     num_encoder_blocks
    __lowerCamelCase    				=     sr_ratios
    __lowerCamelCase    				=     depths
    __lowerCamelCase    				=     hidden_sizes
    __lowerCamelCase    				=     downsampling_rates
    __lowerCamelCase    				=     num_attention_heads
    __lowerCamelCase    				=     is_training
    __lowerCamelCase    				=     use_labels
    __lowerCamelCase    				=     hidden_act
    __lowerCamelCase    				=     hidden_dropout_prob
    __lowerCamelCase    				=     attention_probs_dropout_prob
    __lowerCamelCase    				=     initializer_range
    __lowerCamelCase    				=     num_labels
    __lowerCamelCase    				=     scope




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    __lowerCamelCase    				=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

    __lowerCamelCase    				=     None
    if self.use_labels:
       __lowerCamelCase    				=     ids_tensor([self.batch_size, self.image_size, self.image_size]						,					self.num_labels					)

    __lowerCamelCase    				=     self.get_config()
    return config, pixel_values, labels




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    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						,					__UpperCAmelCase						,					__UpperCAmelCase						,					__UpperCAmelCase					):



    '''simple docstring'''
    __lowerCamelCase    				=     SegformerModel(config=__UpperCAmelCase					)
    model.to(__UpperCAmelCase					)
    model.eval()
    __lowerCamelCase    				=     model(__UpperCAmelCase					)
    __lowerCamelCase    				=     __lowerCamelCase    				=     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						,					__UpperCAmelCase						,					__UpperCAmelCase						,					__UpperCAmelCase					):



    '''simple docstring'''
    __lowerCamelCase    				=     self.num_labels
    __lowerCamelCase    				=     SegformerForSemanticSegmentation(__UpperCAmelCase					)
    model.to(__UpperCAmelCase					)
    model.eval()
    __lowerCamelCase    				=     model(__UpperCAmelCase					)
    self.parent.assertEqual(
        result.logits.shape						,					(self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4)					)
    __lowerCamelCase    				=     model(__UpperCAmelCase						,					labels=__UpperCAmelCase					)
    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						,					__UpperCAmelCase						,					__UpperCAmelCase						,					__UpperCAmelCase					):



    '''simple docstring'''
    __lowerCamelCase    				=     1
    __lowerCamelCase    				=     SegformerForSemanticSegmentation(config=__UpperCAmelCase					)
    model.to(__UpperCAmelCase					)
    model.eval()
    __lowerCamelCase    				=     torch.randint(0						,					1						,					(self.batch_size, self.image_size, self.image_size)					).to(__UpperCAmelCase					)
    __lowerCamelCase    				=     model(__UpperCAmelCase						,					labels=__UpperCAmelCase					)
    self.parent.assertGreater(result.loss						,					0.0					)




 def 							lowerCamelCase   (    self					):



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



@require_torch
class 			__lowerCAmelCase  (						lowerCAmelCase__	,						lowerCAmelCase__	,						unittest.TestCase ):
 lowerCAmelCase__							       =	(
     (
         SegformerModel,
         SegformerForSemanticSegmentation,
         SegformerForImageClassification,
     )
     if is_torch_available()
     else ()
 )
 lowerCAmelCase__							       =	(
     {
         """feature-extraction""": SegformerModel,
         """image-classification""": SegformerForImageClassification,
         """image-segmentation""": SegformerForSemanticSegmentation,
     }
     if is_torch_available()
     else {}
 )

 lowerCAmelCase__							       =	True
 lowerCAmelCase__							       =	False
 lowerCAmelCase__							       =	False
 lowerCAmelCase__							       =	False




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    __lowerCamelCase    				=     SegformerModelTester(self					)
    __lowerCamelCase    				=     SegformerConfigTester(self						,					config_class=__UpperCAmelCase					)




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    self.config_tester.run_common_tests()




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    __lowerCamelCase    				=     self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*__UpperCAmelCase					)




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    __lowerCamelCase    				=     self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_binary_image_segmentation(*__UpperCAmelCase					)




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    __lowerCamelCase    				=     self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_image_segmentation(*__UpperCAmelCase					)




 @unittest.skip('''SegFormer does not use inputs_embeds'''					)
 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    pass




 @unittest.skip('''SegFormer does not have get_input_embeddings method and get_output_embeddings methods'''					)
 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    pass




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    __lowerCamelCase				,__lowerCamelCase    				=     self.model_tester.prepare_config_and_inputs_for_common()

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

       __lowerCamelCase    				=     ['''pixel_values''']
       self.assertListEqual(arg_names[:1]						,					__UpperCAmelCase					)




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    __lowerCamelCase				,__lowerCamelCase    				=     self.model_tester.prepare_config_and_inputs_for_common()
    __lowerCamelCase    				=     True

    for model_class in self.all_model_classes:
       __lowerCamelCase    				=     True
       __lowerCamelCase    				=     False
       __lowerCamelCase    				=     True
       __lowerCamelCase    				=     model_class(__UpperCAmelCase					)
       model.to(__UpperCAmelCase					)
       model.eval()
       with torch.no_grad():
          __lowerCamelCase    				=     model(**self._prepare_for_class(__UpperCAmelCase						,					__UpperCAmelCase					)					)
       __lowerCamelCase    				=     outputs.attentions

       __lowerCamelCase    				=     sum(self.model_tester.depths					)
       self.assertEqual(len(__UpperCAmelCase					)						,					__UpperCAmelCase					)

       # check that output_attentions also work using config
       del inputs_dict["output_attentions"]
       __lowerCamelCase    				=     True
       __lowerCamelCase    				=     model_class(__UpperCAmelCase					)
       model.to(__UpperCAmelCase					)
       model.eval()
       with torch.no_grad():
          __lowerCamelCase    				=     model(**self._prepare_for_class(__UpperCAmelCase						,					__UpperCAmelCase					)					)
       __lowerCamelCase    				=     outputs.attentions

       self.assertEqual(len(__UpperCAmelCase					)						,					__UpperCAmelCase					)

       # verify the first attentions (first block, first layer)
       __lowerCamelCase    				=     (self.model_tester.image_size // 4) ** 2
       __lowerCamelCase    				=     (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    				=     (self.model_tester.image_size // 32) ** 2
       __lowerCamelCase    				=     (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]						,					)
       __lowerCamelCase    				=     len(__UpperCAmelCase					)

       # Check attention is always last and order is fine
       __lowerCamelCase    				=     True
       __lowerCamelCase    				=     True
       __lowerCamelCase    				=     model_class(__UpperCAmelCase					)
       model.to(__UpperCAmelCase					)
       model.eval()
       with torch.no_grad():
          __lowerCamelCase    				=     model(**self._prepare_for_class(__UpperCAmelCase						,					__UpperCAmelCase					)					)

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

       __lowerCamelCase    				=     outputs.attentions

       self.assertEqual(len(__UpperCAmelCase					)						,					__UpperCAmelCase					)
       # verify the first attentions (first block, first layer)
       __lowerCamelCase    				=     (self.model_tester.image_size // 4) ** 2
       __lowerCamelCase    				=     (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					):



    '''simple docstring'''
    def check_hidden_states_output(__UpperCAmelCase						,					__UpperCAmelCase						,					__UpperCAmelCase					):
       __lowerCamelCase    				=     model_class(__UpperCAmelCase					)
       model.to(__UpperCAmelCase					)
       model.eval()

       with torch.no_grad():
          __lowerCamelCase    				=     model(**self._prepare_for_class(__UpperCAmelCase						,					__UpperCAmelCase					)					)

       __lowerCamelCase    				=     outputs.hidden_states

       __lowerCamelCase    				=     self.model_tester.num_encoder_blocks
       self.assertEqual(len(__UpperCAmelCase					)						,					__UpperCAmelCase					)

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

    for model_class in self.all_model_classes:
       __lowerCamelCase    				=     True
       check_hidden_states_output(__UpperCAmelCase						,					__UpperCAmelCase						,					__UpperCAmelCase					)

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

       check_hidden_states_output(__UpperCAmelCase						,					__UpperCAmelCase						,					__UpperCAmelCase					)




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    if not self.model_tester.is_training:
       return

    __lowerCamelCase				,__lowerCamelCase    				=     self.model_tester.prepare_config_and_inputs_for_common()
    __lowerCamelCase    				=     True

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

       __lowerCamelCase    				=     model_class(__UpperCAmelCase					)
       model.to(__UpperCAmelCase					)
       model.train()
       __lowerCamelCase    				=     self._prepare_for_class(__UpperCAmelCase						,					__UpperCAmelCase						,					return_labels=__UpperCAmelCase					)
       __lowerCamelCase    				=     model(**__UpperCAmelCase					).loss
       loss.backward()




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



    '''simple docstring'''
    pass




 @slow
 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    for model_name in SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       __lowerCamelCase    				=     SegformerModel.from_pretrained(__UpperCAmelCase					)
       self.assertIsNotNone(__UpperCAmelCase					)





def 		a__      (		):
   __lowerCamelCase    				=     Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''				)
   return image





@require_torch
class 			__lowerCAmelCase  (						unittest.TestCase ):




 @slow
 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    # only resize + normalize
    __lowerCamelCase    				=     SegformerImageProcessor(
        image_scale=(512, 512)						,					keep_ratio=__UpperCAmelCase						,					align=__UpperCAmelCase						,					do_random_crop=__UpperCAmelCase					)
    __lowerCamelCase    				=     SegformerForSemanticSegmentation.from_pretrained('''nvidia/segformer-b0-finetuned-ade-512-512'''					).to(
        __UpperCAmelCase					)

    __lowerCamelCase    				=     prepare_img()
    __lowerCamelCase    				=     image_processor(images=__UpperCAmelCase						,					return_tensors='''pt'''					)
    __lowerCamelCase    				=     encoded_inputs.pixel_values.to(__UpperCAmelCase					)

    with torch.no_grad():
       __lowerCamelCase    				=     model(__UpperCAmelCase					)

    __lowerCamelCase    				=     torch.Size((1, model.config.num_labels, 128, 128)					)
    self.assertEqual(outputs.logits.shape						,					__UpperCAmelCase					)

    __lowerCamelCase    				=     torch.tensor(
        [
            [[-4.6_310, -5.5_232, -6.2_356], [-5.1_921, -6.1_444, -6.5_996], [-5.4_424, -6.2_790, -6.7_574]],
            [[-12.1_391, -13.3_122, -13.9_554], [-12.8_732, -13.9_352, -14.3_563], [-12.9_438, -13.8_226, -14.2_513]],
            [[-12.5_134, -13.4_686, -14.4_915], [-12.8_669, -14.4_343, -14.7_758], [-13.2_523, -14.5_819, -15.0_694]],
        ]					).to(__UpperCAmelCase					)
    self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]						,					__UpperCAmelCase						,					atol=1E-4					)					)




 @slow
 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    # only resize + normalize
    __lowerCamelCase    				=     SegformerImageProcessor(
        image_scale=(512, 512)						,					keep_ratio=__UpperCAmelCase						,					align=__UpperCAmelCase						,					do_random_crop=__UpperCAmelCase					)
    __lowerCamelCase    				=     SegformerForSemanticSegmentation.from_pretrained(
        '''nvidia/segformer-b1-finetuned-cityscapes-1024-1024'''					).to(__UpperCAmelCase					)

    __lowerCamelCase    				=     prepare_img()
    __lowerCamelCase    				=     image_processor(images=__UpperCAmelCase						,					return_tensors='''pt'''					)
    __lowerCamelCase    				=     encoded_inputs.pixel_values.to(__UpperCAmelCase					)

    with torch.no_grad():
       __lowerCamelCase    				=     model(__UpperCAmelCase					)

    __lowerCamelCase    				=     torch.Size((1, model.config.num_labels, 128, 128)					)
    self.assertEqual(outputs.logits.shape						,					__UpperCAmelCase					)

    __lowerCamelCase    				=     torch.tensor(
        [
            [[-13.5_748, -13.9_111, -12.6_500], [-14.3_500, -15.3_683, -14.2_328], [-14.7_532, -16.0_424, -15.6_087]],
            [[-17.1_651, -15.8_725, -12.9_653], [-17.2_580, -17.3_718, -14.8_223], [-16.6_058, -16.8_783, -16.7_452]],
            [[-3.6_456, -3.0_209, -1.4_203], [-3.0_797, -3.1_959, -2.0_000], [-1.8_757, -1.9_217, -1.6_997]],
        ]					).to(__UpperCAmelCase					)
    self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]						,					__UpperCAmelCase						,					atol=1E-1					)					)




 @slow
 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    # only resize + normalize
    __lowerCamelCase    				=     SegformerImageProcessor(
        image_scale=(512, 512)						,					keep_ratio=__UpperCAmelCase						,					align=__UpperCAmelCase						,					do_random_crop=__UpperCAmelCase					)
    __lowerCamelCase    				=     SegformerForSemanticSegmentation.from_pretrained('''nvidia/segformer-b0-finetuned-ade-512-512'''					).to(
        __UpperCAmelCase					)

    __lowerCamelCase    				=     prepare_img()
    __lowerCamelCase    				=     image_processor(images=__UpperCAmelCase						,					return_tensors='''pt'''					)
    __lowerCamelCase    				=     encoded_inputs.pixel_values.to(__UpperCAmelCase					)

    with torch.no_grad():
       __lowerCamelCase    				=     model(__UpperCAmelCase					)

    __lowerCamelCase    				=     outputs.logits.detach().cpu()

    __lowerCamelCase    				=     image_processor.post_process_semantic_segmentation(outputs=__UpperCAmelCase						,					target_sizes=[(500, 300)]					)
    __lowerCamelCase    				=     torch.Size((500, 300)					)
    self.assertEqual(segmentation[0].shape						,					__UpperCAmelCase					)

    __lowerCamelCase    				=     image_processor.post_process_semantic_segmentation(outputs=__UpperCAmelCase					)
    __lowerCamelCase    				=     torch.Size((128, 128)					)
    self.assertEqual(segmentation[0].shape						,					__UpperCAmelCase					)











def 		a__      (		_UpperCamelCase      :			int				):
   __lowerCamelCase    				=     int(_UpperCamelCase				)
   if decimal in (0, 1):  # Exit cases for the recursion
      return str(_UpperCamelCase				)
   __lowerCamelCase				,__lowerCamelCase    				=     divmod(_UpperCamelCase			,2				)
   return binary_recursive(_UpperCamelCase				) + str(_UpperCamelCase				)





def 		a__      (		_UpperCamelCase      :			str				):
   __lowerCamelCase    				=     str(_UpperCamelCase				).strip()
   if not number:
      raise ValueError('''No input value was provided'''				)
   __lowerCamelCase    				=     '''-''' if number.startswith('''-'''				) else ''''''
   __lowerCamelCase    				=     number.lstrip('''-'''				)
   if not number.isnumeric():
      raise ValueError('''Input value is not an integer'''				)
   return F"""{negative}0b{binary_recursive(int(_UpperCamelCase				)				)}"""


if __name__ == "__main__":
  from doctest import testmod

  testmod()






