
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  __magic_name__						(  UpperCamelCase__):
				'''simple docstring'''







				def     _A							(							self:   List[Any]		):
											SCREAMING_SNAKE_CASE_   	=    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  __magic_name__						:
				'''simple docstring'''







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


				def     _A							(							self:   str		):
											SCREAMING_SNAKE_CASE_   	=    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

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

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


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





				def     _A							(							self:   List[Any]		):
											SCREAMING_SNAKE_CASE_   	=    self.prepare_config_and_inputs()
											SCREAMING_SNAKE_CASE_	,	SCREAMING_SNAKE_CASE_	,	SCREAMING_SNAKE_CASE_   	=    config_and_inputs
											SCREAMING_SNAKE_CASE_   	=    {'''pixel_values''': pixel_values}
											return config, inputs_dict






@require_torch
class  __magic_name__						(  UpperCamelCase__    ,  UpperCamelCase__    ,  unittest.TestCase):
				'''simple docstring'''







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

				SCREAMING_SNAKE_CASE__					:							Optional[int]	      =					True
				SCREAMING_SNAKE_CASE__					:							str	      =					False
				SCREAMING_SNAKE_CASE__					:							Optional[Any]	      =					False
				SCREAMING_SNAKE_CASE__					:							Optional[int]	      =					False


				def     _A							(							self:   int		):
											SCREAMING_SNAKE_CASE_   	=    SegformerModelTester(self		)
											SCREAMING_SNAKE_CASE_   	=    SegformerConfigTester(self		,					config_class=__A		)


				def     _A							(							self:   Any		):
											self.config_tester.run_common_tests()


				def     _A							(							self:   List[Any]		):
											SCREAMING_SNAKE_CASE_   	=    self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*__A		)


				def     _A							(							self:   Optional[Any]		):
											SCREAMING_SNAKE_CASE_   	=    self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_binary_image_segmentation(*__A		)


				def     _A							(							self:   Union[str, Any]		):
											SCREAMING_SNAKE_CASE_   	=    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     _A							(							self:   List[str]		):
											pass


				@unittest.skip('''SegFormer does not have get_input_embeddings method and get_output_embeddings methods'''		)
				def     _A							(							self:   Union[str, Any]		):
											pass


				def     _A							(							self:   Union[str, Any]		):
											SCREAMING_SNAKE_CASE_	,	SCREAMING_SNAKE_CASE_   	=    self.model_tester.prepare_config_and_inputs_for_common()

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

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


				def     _A							(							self:   int		):
											SCREAMING_SNAKE_CASE_	,	SCREAMING_SNAKE_CASE_   	=    self.model_tester.prepare_config_and_inputs_for_common()
											SCREAMING_SNAKE_CASE_   	=    True

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

																		SCREAMING_SNAKE_CASE_   	=    sum(self.model_tester.depths		)
																		self.assertEqual(len(__A		)		,					__A		)

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

																		self.assertEqual(len(__A		)		,					__A		)

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

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

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

																		SCREAMING_SNAKE_CASE_   	=    outputs.attentions

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



											def check_hidden_states_output(_lowerCamelCase:   Optional[Any]		,					_lowerCamelCase:   str		,					_lowerCamelCase:   List[str]		):
																		SCREAMING_SNAKE_CASE_   	=    model_class(__A		)
																		model.to(__A		)
																		model.eval()

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

																		SCREAMING_SNAKE_CASE_   	=    outputs.hidden_states

																		SCREAMING_SNAKE_CASE_   	=    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,
																		    ]		,					)

											SCREAMING_SNAKE_CASE_	,	SCREAMING_SNAKE_CASE_   	=    self.model_tester.prepare_config_and_inputs_for_common()

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

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

																		check_hidden_states_output(__A		,					__A		,					__A		)


				def     _A							(							self:   str		):



											if not self.model_tester.is_training:
																		return

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

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

																		SCREAMING_SNAKE_CASE_   	=    model_class(__A		)
																		model.to(__A		)
																		model.train()
																		SCREAMING_SNAKE_CASE_   	=    self._prepare_for_class(__A		,					__A		,					return_labels=__A		)
																		SCREAMING_SNAKE_CASE_   	=    model(**__A		).loss
																		loss.backward()


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





				@slow
				def     _A							(							self:   List[str]		):



											for model_name in SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																		SCREAMING_SNAKE_CASE_   	=    SegformerModel.from_pretrained(__A		)
																		self.assertIsNotNone(__A		)






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






@require_torch
class  __magic_name__						(  unittest.TestCase):
				'''simple docstring'''







				@slow
				def     _A							(							self:   Optional[int]		):
											SCREAMING_SNAKE_CASE_   	=    SegformerImageProcessor(
											    image_scale=(5_12, 5_12)		,					keep_ratio=__A		,					align=__A		,					do_random_crop=__A		)
											SCREAMING_SNAKE_CASE_   	=    SegformerForSemanticSegmentation.from_pretrained('''nvidia/segformer-b0-finetuned-ade-512-512'''		).to(
											    __A		)

											SCREAMING_SNAKE_CASE_   	=    prepare_img()
											SCREAMING_SNAKE_CASE_   	=    image_processor(images=__A		,					return_tensors='''pt'''		)
											SCREAMING_SNAKE_CASE_   	=    encoded_inputs.pixel_values.to(__A		)

											with torch.no_grad():
																		SCREAMING_SNAKE_CASE_   	=    model(__A		)

											SCREAMING_SNAKE_CASE_   	=    torch.Size((1, model.config.num_labels, 1_28, 1_28)		)
											self.assertEqual(outputs.logits.shape		,					__A		)

											SCREAMING_SNAKE_CASE_   	=    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     _A							(							self:   Dict		):
											SCREAMING_SNAKE_CASE_   	=    SegformerImageProcessor(
											    image_scale=(5_12, 5_12)		,					keep_ratio=__A		,					align=__A		,					do_random_crop=__A		)
											SCREAMING_SNAKE_CASE_   	=    SegformerForSemanticSegmentation.from_pretrained(
											    '''nvidia/segformer-b1-finetuned-cityscapes-1024-1024'''		).to(__A		)

											SCREAMING_SNAKE_CASE_   	=    prepare_img()
											SCREAMING_SNAKE_CASE_   	=    image_processor(images=__A		,					return_tensors='''pt'''		)
											SCREAMING_SNAKE_CASE_   	=    encoded_inputs.pixel_values.to(__A		)

											with torch.no_grad():
																		SCREAMING_SNAKE_CASE_   	=    model(__A		)

											SCREAMING_SNAKE_CASE_   	=    torch.Size((1, model.config.num_labels, 1_28, 1_28)		)
											self.assertEqual(outputs.logits.shape		,					__A		)

											SCREAMING_SNAKE_CASE_   	=    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     _A							(							self:   Optional[int]		):
											SCREAMING_SNAKE_CASE_   	=    SegformerImageProcessor(
											    image_scale=(5_12, 5_12)		,					keep_ratio=__A		,					align=__A		,					do_random_crop=__A		)
											SCREAMING_SNAKE_CASE_   	=    SegformerForSemanticSegmentation.from_pretrained('''nvidia/segformer-b0-finetuned-ade-512-512'''		).to(
											    __A		)

											SCREAMING_SNAKE_CASE_   	=    prepare_img()
											SCREAMING_SNAKE_CASE_   	=    image_processor(images=__A		,					return_tensors='''pt'''		)
											SCREAMING_SNAKE_CASE_   	=    encoded_inputs.pixel_values.to(__A		)

											with torch.no_grad():
																		SCREAMING_SNAKE_CASE_   	=    model(__A		)

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

											SCREAMING_SNAKE_CASE_   	=    image_processor.post_process_semantic_segmentation(outputs=__A		,					target_sizes=[(5_00, 3_00)]		)
											SCREAMING_SNAKE_CASE_   	=    torch.Size((5_00, 3_00)		)
											self.assertEqual(segmentation[0].shape		,					__A		)

											SCREAMING_SNAKE_CASE_   	=    image_processor.post_process_semantic_segmentation(outputs=__A		)
											SCREAMING_SNAKE_CASE_   	=    torch.Size((1_28, 1_28)		)
											self.assertEqual(segmentation[0].shape		,					__A		)








from typing import Any

def 			a   (_lowerCAmelCase     ):
							if not input_list:
														return []
							SCREAMING_SNAKE_CASE_   	=    [input_list.count(_lowerCAmelCase     ) for value in input_list]
							SCREAMING_SNAKE_CASE_   	=    max(_lowerCAmelCase     )  # Gets the maximum count in the input list.
							# Gets values of modes
							return sorted({input_list[i] for i, value in enumerate(_lowerCAmelCase     ) if value == y}     )


if __name__ == "__main__":
			import doctest

			doctest.testmod()


