



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






		def SCREAMING_SNAKE_CASE_			(						self      :     List[str]      )				->					Any:
								'''simple docstring'''







								UpperCAmelCase         =     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  __magic_name__   :






		def __init__(						self      :     Union[str, Any]				,		UpperCamelCase__      :     Any				,		UpperCamelCase__      :     Union[str, Any]=13				,		UpperCamelCase__      :     Optional[Any]=64				,		UpperCamelCase__      :     Dict=3				,		UpperCamelCase__      :     Any=4				,		UpperCamelCase__      :     str=[2, 2, 2, 2]				,		UpperCamelCase__      :     Optional[Any]=[8, 4, 2, 1]				,		UpperCamelCase__      :     Any=[16, 32, 64, 1_28]				,		UpperCamelCase__      :     Tuple=[1, 4, 8, 16]				,		UpperCamelCase__      :     Dict=[1, 2, 4, 8]				,		UpperCamelCase__      :     Optional[Any]=True				,		UpperCamelCase__      :     Optional[Any]=True				,		UpperCamelCase__      :     str="gelu"				,		UpperCamelCase__      :     Any=0.1				,		UpperCamelCase__      :     Any=0.1				,		UpperCamelCase__      :     Tuple=0.02				,		UpperCamelCase__      :     Optional[int]=3				,		UpperCamelCase__      :     Dict=None				,		)				->					Dict:
								'''simple docstring'''







								UpperCAmelCase         =     parent
								UpperCAmelCase         =     batch_size
								UpperCAmelCase         =     image_size
								UpperCAmelCase         =     num_channels
								UpperCAmelCase         =     num_encoder_blocks
								UpperCAmelCase         =     sr_ratios
								UpperCAmelCase         =     depths
								UpperCAmelCase         =     hidden_sizes
								UpperCAmelCase         =     downsampling_rates
								UpperCAmelCase         =     num_attention_heads
								UpperCAmelCase         =     is_training
								UpperCAmelCase         =     use_labels
								UpperCAmelCase         =     hidden_act
								UpperCAmelCase         =     hidden_dropout_prob
								UpperCAmelCase         =     attention_probs_dropout_prob
								UpperCAmelCase         =     initializer_range
								UpperCAmelCase         =     num_labels
								UpperCAmelCase         =     scope






		def SCREAMING_SNAKE_CASE_			(						self      :     Optional[Any]      )				->					Union[str, Any]:
								'''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.image_size, self.image_size]				,		self.num_labels      )

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






		def SCREAMING_SNAKE_CASE_			(						self      :     Tuple      )				->					int:
								'''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 SCREAMING_SNAKE_CASE_			(						self      :     int				,		UpperCamelCase__      :     List[str]				,		UpperCamelCase__      :     Optional[Any]				,		UpperCamelCase__      :     Tuple      )				->					List[str]:
								'''simple docstring'''







								UpperCAmelCase         =     SegformerModel(config=UpperCamelCase__      )
								model.to(UpperCamelCase__      )
								model.eval()
								UpperCAmelCase         =     model(UpperCamelCase__      )
								UpperCAmelCase         =     UpperCAmelCase         =     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      :     List[str]				,		UpperCamelCase__      :     Any				,		UpperCamelCase__      :     Union[str, Any]				,		UpperCamelCase__      :     Tuple      )				->					str:
								'''simple docstring'''







								UpperCAmelCase         =     self.num_labels
								UpperCAmelCase         =     SegformerForSemanticSegmentation(UpperCamelCase__      )
								model.to(UpperCamelCase__      )
								model.eval()
								UpperCAmelCase         =     model(UpperCamelCase__      )
								self.parent.assertEqual(
								    result.logits.shape				,		(self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4)      )
								UpperCAmelCase         =     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 SCREAMING_SNAKE_CASE_			(						self      :     Any				,		UpperCamelCase__      :     Union[str, Any]				,		UpperCamelCase__      :     Tuple				,		UpperCamelCase__      :     Optional[int]      )				->					str:
								'''simple docstring'''







								UpperCAmelCase         =     1
								UpperCAmelCase         =     SegformerForSemanticSegmentation(config=UpperCamelCase__      )
								model.to(UpperCamelCase__      )
								model.eval()
								UpperCAmelCase         =     torch.randint(0				,		1				,		(self.batch_size, self.image_size, self.image_size)      ).to(UpperCamelCase__      )
								UpperCAmelCase         =     model(UpperCamelCase__				,		labels=UpperCamelCase__      )
								self.parent.assertGreater(result.loss				,		0.0      )







		def SCREAMING_SNAKE_CASE_			(						self      :     Tuple      )				->					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  __magic_name__   (							lowercase_,  lowercase_,  unittest.TestCase						):
		lowercase      :       str          =(
		    (
		        SegformerModel,
		        SegformerForSemanticSegmentation,
		        SegformerForImageClassification,
		    )
		    if is_torch_available()
		    else ()
		)
		lowercase      :       Dict          =(
		    {
		        '''feature-extraction''': SegformerModel,
		        '''image-classification''': SegformerForImageClassification,
		        '''image-segmentation''': SegformerForSemanticSegmentation,
		    }
		    if is_torch_available()
		    else {}
		)

		lowercase      :       int          =True
		lowercase      :       Dict          =False
		lowercase      :       List[str]          =False
		lowercase      :       List[Any]          =False






		def SCREAMING_SNAKE_CASE_			(						self      :     int      )				->					int:
								'''simple docstring'''







								UpperCAmelCase         =     SegformerModelTester(self      )
								UpperCAmelCase         =     SegformerConfigTester(self				,		config_class=UpperCamelCase__      )






		def SCREAMING_SNAKE_CASE_			(						self      :     List[str]      )				->					Dict:
								'''simple docstring'''







								self.config_tester.run_common_tests()






		def SCREAMING_SNAKE_CASE_			(						self      :     int      )				->					Tuple:
								'''simple docstring'''







								UpperCAmelCase         =     self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*UpperCamelCase__      )






		def SCREAMING_SNAKE_CASE_			(						self      :     Optional[int]      )				->					Tuple:
								'''simple docstring'''







								UpperCAmelCase         =     self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_binary_image_segmentation(*UpperCamelCase__      )






		def SCREAMING_SNAKE_CASE_			(						self      :     Dict      )				->					List[str]:
								'''simple docstring'''







								UpperCAmelCase         =     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 SCREAMING_SNAKE_CASE_			(						self      :     str      )				->					str:
								'''simple docstring'''







								pass






		@unittest.skip("SegFormer does not have get_input_embeddings method and get_output_embeddings methods"      )
		def SCREAMING_SNAKE_CASE_			(						self      :     Any      )				->					Tuple:
								'''simple docstring'''







								pass






		def SCREAMING_SNAKE_CASE_			(						self      :     Tuple      )				->					Tuple:
								'''simple docstring'''







								UpperCAmelCase       ,		UpperCAmelCase         =     self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
														UpperCAmelCase         =     model_class(UpperCamelCase__      )
														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]				,		UpperCamelCase__      )






		def SCREAMING_SNAKE_CASE_			(						self      :     Dict      )				->					List[Any]:
								'''simple docstring'''







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

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

														UpperCAmelCase         =     sum(self.model_tester.depths      )
														self.assertEqual(len(UpperCamelCase__      )				,		UpperCamelCase__      )

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

														self.assertEqual(len(UpperCamelCase__      )				,		UpperCamelCase__      )

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

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

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

														UpperCAmelCase         =     outputs.attentions

														self.assertEqual(len(UpperCamelCase__      )				,		UpperCamelCase__      )
														# verify the first attentions (first block, first layer)
														UpperCAmelCase         =     (self.model_tester.image_size // 4) ** 2
														UpperCAmelCase         =     (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      :     Dict      )				->					List[Any]:
								'''simple docstring'''







								def check_hidden_states_output(UpperCamelCase__      :     Dict				,		UpperCamelCase__      :     Tuple				,		UpperCamelCase__      :     int      ):
														UpperCAmelCase         =     model_class(UpperCamelCase__      )
														model.to(UpperCamelCase__      )
														model.eval()

														with torch.no_grad():
																				UpperCAmelCase         =     model(**self._prepare_for_class(UpperCamelCase__				,		UpperCamelCase__      )      )

														UpperCAmelCase         =     outputs.hidden_states

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

								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(UpperCamelCase__				,		UpperCamelCase__				,		UpperCamelCase__      )

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

														check_hidden_states_output(UpperCamelCase__				,		UpperCamelCase__				,		UpperCamelCase__      )






		def SCREAMING_SNAKE_CASE_			(						self      :     Tuple      )				->					Optional[Any]:
								'''simple docstring'''







								if not self.model_tester.is_training:
														return

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

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

														UpperCAmelCase         =     model_class(UpperCamelCase__      )
														model.to(UpperCamelCase__      )
														model.train()
														UpperCAmelCase         =     self._prepare_for_class(UpperCamelCase__				,		UpperCamelCase__				,		return_labels=UpperCamelCase__      )
														UpperCAmelCase         =     model(**UpperCamelCase__      ).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      :     Optional[Any]      )				->					List[str]:
								'''simple docstring'''







								pass







		@slow
		def SCREAMING_SNAKE_CASE_			(						self      :     Union[str, Any]      )				->					Union[str, Any]:
								'''simple docstring'''







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


def    lowerCamelCase_() ->       List[str]:
						UpperCAmelCase         =     Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"    )
						return image





@require_torch
class  __magic_name__   (							unittest.TestCase						):






		@slow
		def SCREAMING_SNAKE_CASE_			(						self      :     Optional[Any]      )				->					List[Any]:
								'''simple docstring'''







								UpperCAmelCase         =     SegformerImageProcessor(
								    image_scale=(5_12, 5_12)				,		keep_ratio=UpperCamelCase__				,		align=UpperCamelCase__				,		do_random_crop=UpperCamelCase__      )
								UpperCAmelCase         =     SegformerForSemanticSegmentation.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512"      ).to(
								    UpperCamelCase__      )

								UpperCAmelCase         =     prepare_img()
								UpperCAmelCase         =     image_processor(images=UpperCamelCase__				,		return_tensors="pt"      )
								UpperCAmelCase         =     encoded_inputs.pixel_values.to(UpperCamelCase__      )

								with torch.no_grad():
														UpperCAmelCase         =     model(UpperCamelCase__      )

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

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






		@slow
		def SCREAMING_SNAKE_CASE_			(						self      :     str      )				->					Optional[Any]:
								'''simple docstring'''







								UpperCAmelCase         =     SegformerImageProcessor(
								    image_scale=(5_12, 5_12)				,		keep_ratio=UpperCamelCase__				,		align=UpperCamelCase__				,		do_random_crop=UpperCamelCase__      )
								UpperCAmelCase         =     SegformerForSemanticSegmentation.from_pretrained(
								    "nvidia/segformer-b1-finetuned-cityscapes-1024-1024"      ).to(UpperCamelCase__      )

								UpperCAmelCase         =     prepare_img()
								UpperCAmelCase         =     image_processor(images=UpperCamelCase__				,		return_tensors="pt"      )
								UpperCAmelCase         =     encoded_inputs.pixel_values.to(UpperCamelCase__      )

								with torch.no_grad():
														UpperCAmelCase         =     model(UpperCamelCase__      )

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

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







		@slow
		def SCREAMING_SNAKE_CASE_			(						self      :     Optional[int]      )				->					Optional[Any]:
								'''simple docstring'''







								UpperCAmelCase         =     SegformerImageProcessor(
								    image_scale=(5_12, 5_12)				,		keep_ratio=UpperCamelCase__				,		align=UpperCamelCase__				,		do_random_crop=UpperCamelCase__      )
								UpperCAmelCase         =     SegformerForSemanticSegmentation.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512"      ).to(
								    UpperCamelCase__      )

								UpperCAmelCase         =     prepare_img()
								UpperCAmelCase         =     image_processor(images=UpperCamelCase__				,		return_tensors="pt"      )
								UpperCAmelCase         =     encoded_inputs.pixel_values.to(UpperCamelCase__      )

								with torch.no_grad():
														UpperCAmelCase         =     model(UpperCamelCase__      )

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

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

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








from __future__ import annotations

def    lowerCamelCase_(lowerCamelCase_    ) ->       int:
						UpperCAmelCase         =     len(lowerCamelCase_    ) // 2

						# choose the middle 3 elements
						UpperCAmelCase         =     lst[m - 1 : m + 2]

						# if middle element is peak
						if three[1] > three[0] and three[1] > three[2]:
												return three[1]

						# if increasing, recurse on right
						elif three[0] < three[2]:
												if len(lst[:m]    ) == 2:
																		m -= 1
												return peak(lst[m:]    )

						# decreasing
						else:
												if len(lst[:m]    ) == 2:
																		m += 1
												return peak(lst[:m]    )


if __name__ == "__main__":
		import doctest

		doctest.testmod()



