



'''simple docstring'''





import unittest

import numpy as np

from transformers.testing_utils import require_pytesseract, require_torch
from transformers.utils import is_pytesseract_available, is_torch_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
      import torch

if is_pytesseract_available():
      from PIL import Image

      from transformers import LayoutLMvaImageProcessor





class 				lowerCAmelCase_						(			unittest.TestCase		):





    def __init__(							self							:							Optional[Any],							_snake_case							:							Any,							_snake_case							:							int=7,							_snake_case							:							Tuple=3,							_snake_case							:							Dict=18,							_snake_case							:							int=30,							_snake_case							:							Dict=400,							_snake_case							:							List[Any]=True,							_snake_case							:							Optional[int]=None,							_snake_case							:							List[Any]=True,							):



       '''simple docstring'''







       snake_case       :				Optional[Any]		    =size if size is not None else {"""height""": 18, """width""": 18}
       snake_case       :				Optional[int]		    =parent
       snake_case       :				Dict		    =batch_size
       snake_case       :				Union[str, Any]		    =num_channels
       snake_case       :				Optional[int]		    =image_size
       snake_case       :				str		    =min_resolution
       snake_case       :				Optional[Any]		    =max_resolution
       snake_case       :				List[Any]		    =do_resize
       snake_case       :				str		    =size
       snake_case       :				List[Any]		    =apply_ocr






    def 	__snake_case  (							self							:							str      ):



       '''simple docstring'''







       return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr}





@require_torch
@require_pytesseract
class 				lowerCAmelCase_						(			a_    ,     unittest.TestCase		):
    __UpperCAmelCase				=			LayoutLMvaImageProcessor if is_pytesseract_available() else None





    def 	__snake_case  (							self							:							List[str]      ):



       '''simple docstring'''







       snake_case       :				Union[str, Any]		    =LayoutLMvaImageProcessingTester(self      )





    @property
    def 	__snake_case  (							self							:							str      ):



       '''simple docstring'''







       return self.image_processor_tester.prepare_image_processor_dict()





    def 	__snake_case  (							self							:							List[str]      ):



       '''simple docstring'''







       snake_case       :				Optional[Any]		    =self.image_processing_class(**self.image_processor_dict      )
       self.assertTrue(hasattr(_lowercase,							'''do_resize'''      )      )
       self.assertTrue(hasattr(_lowercase,							'''size'''      )      )
       self.assertTrue(hasattr(_lowercase,							'''apply_ocr'''      )      )





    def 	__snake_case  (							self							:							str      ):



       '''simple docstring'''







       snake_case       :				str		    =self.image_processing_class.from_dict(self.image_processor_dict      )
       self.assertEqual(image_processor.size,							{'''height''': 18, '''width''': 18}      )

       snake_case       :				List[str]		    =self.image_processing_class.from_dict(self.image_processor_dict,							size=42      )
       self.assertEqual(image_processor.size,							{'''height''': 42, '''width''': 42}      )





    def 	__snake_case  (							self							:							List[Any]      ):



       '''simple docstring'''







       pass





    def 	__snake_case  (							self							:							Any      ):



       '''simple docstring'''







       snake_case       :				Union[str, Any]		    =self.image_processing_class(**self.image_processor_dict      )
       # create random PIL images
       snake_case       :				Union[str, Any]		    =prepare_image_inputs(self.image_processor_tester,							equal_resolution=_lowercase      )
       for image in image_inputs:
          self.assertIsInstance(_lowercase,							Image.Image      )

       # Test not batched input
       snake_case       :				Dict		    =image_processing(image_inputs[0],							return_tensors='''pt'''      )
       self.assertEqual(
           encoding.pixel_values.shape,							(
               1,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.size['''height'''],
               self.image_processor_tester.size['''width'''],
           ),							)

       self.assertIsInstance(encoding.words,							_lowercase      )
       self.assertIsInstance(encoding.boxes,							_lowercase      )

       # Test batched
       snake_case       :				Union[str, Any]		    =image_processing(_lowercase,							return_tensors='''pt'''      ).pixel_values
       self.assertEqual(
           encoded_images.shape,							(
               self.image_processor_tester.batch_size,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.size['''height'''],
               self.image_processor_tester.size['''width'''],
           ),							)





    def 	__snake_case  (							self							:							str      ):



       '''simple docstring'''







       snake_case       :				List[str]		    =self.image_processing_class(**self.image_processor_dict      )
       # create random numpy tensors
       snake_case       :				Union[str, Any]		    =prepare_image_inputs(self.image_processor_tester,							equal_resolution=_lowercase,							numpify=_lowercase      )
       for image in image_inputs:
          self.assertIsInstance(_lowercase,							np.ndarray      )

       # Test not batched input
       snake_case       :				Dict		    =image_processing(image_inputs[0],							return_tensors='''pt'''      ).pixel_values
       self.assertEqual(
           encoded_images.shape,							(
               1,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.size['''height'''],
               self.image_processor_tester.size['''width'''],
           ),							)

       # Test batched
       snake_case       :				Any		    =image_processing(_lowercase,							return_tensors='''pt'''      ).pixel_values
       self.assertEqual(
           encoded_images.shape,							(
               self.image_processor_tester.batch_size,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.size['''height'''],
               self.image_processor_tester.size['''width'''],
           ),							)





    def 	__snake_case  (							self							:							Tuple      ):



       '''simple docstring'''







       snake_case       :				List[Any]		    =self.image_processing_class(**self.image_processor_dict      )
       # create random PyTorch tensors
       snake_case       :				Any		    =prepare_image_inputs(self.image_processor_tester,							equal_resolution=_lowercase,							torchify=_lowercase      )
       for image in image_inputs:
          self.assertIsInstance(_lowercase,							torch.Tensor      )

       # Test not batched input
       snake_case       :				int		    =image_processing(image_inputs[0],							return_tensors='''pt'''      ).pixel_values
       self.assertEqual(
           encoded_images.shape,							(
               1,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.size['''height'''],
               self.image_processor_tester.size['''width'''],
           ),							)

       # Test batched
       snake_case       :				Dict		    =image_processing(_lowercase,							return_tensors='''pt'''      ).pixel_values
       self.assertEqual(
           encoded_images.shape,							(
               self.image_processor_tester.batch_size,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.size['''height'''],
               self.image_processor_tester.size['''width'''],
           ),							)






    def 	__snake_case  (							self							:							Optional[Any]      ):



       '''simple docstring'''







       snake_case       :				Optional[Any]		    =LayoutLMvaImageProcessor()

       from datasets import load_dataset

       snake_case       :				Union[str, Any]		    =load_dataset('''hf-internal-testing/fixtures_docvqa''',							split='''test'''      )

       snake_case       :				Any		    =Image.open(ds[0]['''file''']      ).convert('''RGB'''      )

       snake_case       :				Optional[int]		    =image_processing(_lowercase,							return_tensors='''pt'''      )

       self.assertEqual(encoding.pixel_values.shape,							(1, 3, 224, 224)      )
       self.assertEqual(len(encoding.words      ),							len(encoding.boxes      )      )

       # fmt: off
       # the words and boxes were obtained with Tesseract 4.1.1
       snake_case       :				Any		    =[["""11:14""", """to""", """11:39""", """a.m""", """11:39""", """to""", """11:44""", """a.m.""", """11:44""", """a.m.""", """to""", """12:25""", """p.m.""", """12:25""", """to""", """12:58""", """p.m.""", """12:58""", """to""", """4:00""", """p.m.""", """2:00""", """to""", """5:00""", """p.m.""", """Coffee""", """Break""", """Coffee""", """will""", """be""", """served""", """for""", """men""", """and""", """women""", """in""", """the""", """lobby""", """adjacent""", """to""", """exhibit""", """area.""", """Please""", """move""", """into""", """exhibit""", """area.""", """(Exhibits""", """Open)""", """TRRF""", """GENERAL""", """SESSION""", """(PART""", """|)""", """Presiding:""", """Lee""", """A.""", """Waller""", """TRRF""", """Vice""", """President""", """“Introductory""", """Remarks”""", """Lee""", """A.""", """Waller,""", """TRRF""", """Vice""", """Presi-""", """dent""", """Individual""", """Interviews""", """with""", """TRRF""", """Public""", """Board""", """Members""", """and""", """Sci-""", """entific""", """Advisory""", """Council""", """Mem-""", """bers""", """Conducted""", """by""", """TRRF""", """Treasurer""", """Philip""", """G.""", """Kuehn""", """to""", """get""", """answers""", """which""", """the""", """public""", """refrigerated""", """warehousing""", """industry""", """is""", """looking""", """for.""", """Plus""", """questions""", """from""", """the""", """floor.""", """Dr.""", """Emil""", """M.""", """Mrak,""", """University""", """of""", """Cal-""", """ifornia,""", """Chairman,""", """TRRF""", """Board;""", """Sam""", """R.""", """Cecil,""", """University""", """of""", """Georgia""", """College""", """of""", """Agriculture;""", """Dr.""", """Stanley""", """Charm,""", """Tufts""", """University""", """School""", """of""", """Medicine;""", """Dr.""", """Robert""", """H.""", """Cotton,""", """ITT""", """Continental""", """Baking""", """Company;""", """Dr.""", """Owen""", """Fennema,""", """University""", """of""", """Wis-""", """consin;""", """Dr.""", """Robert""", """E.""", """Hardenburg,""", """USDA.""", """Questions""", """and""", """Answers""", """Exhibits""", """Open""", """Capt.""", """Jack""", """Stoney""", """Room""", """TRRF""", """Scientific""", """Advisory""", """Council""", """Meeting""", """Ballroom""", """Foyer"""]]  # noqa: E231
       snake_case       :				int		    =[[[141, 57, 214, 69], [228, 58, 252, 69], [141, 75, 216, 88], [230, 79, 280, 88], [142, 260, 218, 273], [230, 261, 255, 273], [143, 279, 218, 290], [231, 282, 290, 291], [143, 342, 218, 354], [231, 345, 289, 355], [202, 362, 227, 373], [143, 379, 220, 392], [231, 382, 291, 394], [144, 714, 220, 726], [231, 715, 256, 726], [144, 732, 220, 745], [232, 736, 291, 747], [144, 769, 218, 782], [231, 770, 256, 782], [141, 788, 202, 801], [215, 791, 274, 804], [143, 826, 204, 838], [215, 826, 240, 838], [142, 844, 202, 857], [215, 847, 274, 859], [334, 57, 427, 69], [440, 57, 522, 69], [369, 75, 461, 88], [469, 75, 516, 88], [528, 76, 562, 88], [570, 76, 667, 88], [675, 75, 711, 87], [721, 79, 778, 88], [789, 75, 840, 88], [369, 97, 470, 107], [484, 94, 507, 106], [518, 94, 562, 107], [576, 94, 655, 110], [668, 94, 792, 109], [804, 95, 829, 107], [369, 113, 465, 125], [477, 116, 547, 125], [562, 113, 658, 125], [671, 116, 748, 125], [761, 113, 811, 125], [369, 131, 465, 143], [477, 133, 548, 143], [563, 130, 698, 145], [710, 130, 802, 146], [336, 171, 412, 183], [423, 171, 572, 183], [582, 170, 716, 184], [728, 171, 817, 187], [829, 171, 844, 186], [338, 197, 482, 212], [507, 196, 557, 209], [569, 196, 595, 208], [610, 196, 702, 209], [505, 214, 583, 226], [595, 214, 656, 227], [670, 215, 807, 227], [335, 259, 543, 274], [556, 259, 708, 272], [372, 279, 422, 291], [435, 279, 460, 291], [474, 279, 574, 292], [587, 278, 664, 291], [676, 278, 738, 291], [751, 279, 834, 291], [372, 298, 434, 310], [335, 341, 483, 354], [497, 341, 655, 354], [667, 341, 728, 354], [740, 341, 825, 354], [335, 360, 430, 372], [442, 360, 534, 372], [545, 359, 687, 372], [697, 360, 754, 372], [765, 360, 823, 373], [334, 378, 428, 391], [440, 378, 577, 394], [590, 378, 705, 391], [720, 378, 801, 391], [334, 397, 400, 409], [370, 416, 529, 429], [544, 416, 576, 432], [587, 416, 665, 428], [677, 416, 814, 429], [372, 435, 452, 450], [465, 434, 495, 447], [511, 434, 600, 447], [611, 436, 637, 447], [649, 436, 694, 451], [705, 438, 824, 447], [369, 453, 452, 466], [464, 454, 509, 466], [522, 453, 611, 469], [625, 453, 792, 469], [370, 472, 556, 488], [570, 472, 684, 487], [697, 472, 718, 485], [732, 472, 835, 488], [369, 490, 411, 503], [425, 490, 484, 503], [496, 490, 635, 506], [645, 490, 707, 503], [718, 491, 761, 503], [771, 490, 840, 503], [336, 510, 374, 521], [388, 510, 447, 522], [460, 510, 489, 521], [503, 510, 580, 522], [592, 509, 736, 525], [745, 509, 770, 522], [781, 509, 840, 522], [338, 528, 434, 541], [448, 528, 596, 541], [609, 527, 687, 540], [700, 528, 792, 541], [336, 546, 397, 559], [407, 546, 431, 559], [443, 546, 525, 560], [537, 546, 680, 562], [688, 546, 714, 559], [722, 546, 837, 562], [336, 565, 449, 581], [461, 565, 485, 577], [497, 565, 665, 581], [681, 565, 718, 577], [732, 565, 837, 580], [337, 584, 438, 597], [452, 583, 521, 596], [535, 584, 677, 599], [690, 583, 787, 596], [801, 583, 825, 596], [338, 602, 478, 615], [492, 602, 530, 614], [543, 602, 638, 615], [650, 602, 676, 614], [688, 602, 788, 615], [802, 602, 843, 614], [337, 621, 502, 633], [516, 621, 615, 637], [629, 621, 774, 636], [789, 621, 827, 633], [337, 639, 418, 652], [432, 640, 571, 653], [587, 639, 731, 655], [743, 639, 769, 652], [780, 639, 841, 652], [338, 658, 440, 673], [455, 658, 491, 670], [508, 658, 602, 671], [616, 658, 638, 670], [654, 658, 835, 674], [337, 677, 429, 689], [337, 714, 482, 726], [495, 714, 548, 726], [561, 714, 683, 726], [338, 770, 461, 782], [474, 769, 554, 785], [489, 788, 562, 803], [576, 788, 643, 801], [656, 787, 751, 804], [764, 788, 844, 801], [334, 825, 421, 838], [430, 824, 574, 838], [584, 824, 723, 841], [335, 844, 450, 857], [464, 843, 583, 860], [628, 862, 755, 875], [769, 861, 848, 878]]]  # noqa: E231
       # fmt: on

       self.assertListEqual(encoding.words,							_lowercase      )
       self.assertListEqual(encoding.boxes,							_lowercase      )

       # with apply_OCR = False
       snake_case       :				Tuple		    =LayoutLMvaImageProcessor(apply_ocr=_lowercase      )

       snake_case       :				int		    =image_processing(_lowercase,							return_tensors='''pt'''      )

       self.assertEqual(encoding.pixel_values.shape,							(1, 3, 224, 224)      )








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        A__(a_							):
						"""simple docstring"""






						def 			UpperCamelCase__					(    self    )     -> List[str]:
									a_						:						Optional[Any] 							= self.config_class(**self.inputs_dict    )
									self.parent.assertTrue(hasattr(_lowercase  ,      """hidden_sizes"""    )    )
									self.parent.assertTrue(hasattr(_lowercase  ,      """num_attention_heads"""    )    )
									self.parent.assertTrue(hasattr(_lowercase  ,      """num_encoder_blocks"""    )    )







class        A__:
						"""simple docstring"""






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





						def 			UpperCamelCase__					(    self    )     -> List[str]:
									a_						:						Dict 							= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

									a_						:						int 							= None
									if self.use_labels:
												a_						:						List[Any] 							= ids_tensor([self.batch_size, self.image_size, self.image_size]  ,      self.num_labels    )

									a_						:						Dict 							= self.get_config()
									return config, pixel_values, labels





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





						def 			UpperCamelCase__					(    self    )     -> Optional[int]:
									a_						:						Union[str, Any] 							= self.prepare_config_and_inputs()
									a_							,					a_							,					a_						:						Optional[int] 							= config_and_inputs
									a_						:						int 							= {"""pixel_values""": pixel_values}
									return config, inputs_dict







@require_torch
class        A__(a_,  a_,  unittest.TestCase							):
						"""simple docstring"""






						_A    :				Dict       					=			(
						    (
						        SegformerModel,
						        SegformerForSemanticSegmentation,
						        SegformerForImageClassification,
						    )
						    if is_torch_available()
						    else ()
						)
						_A    :				List[Any]       					=			(
						    {
						        '''feature-extraction''': SegformerModel,
						        '''image-classification''': SegformerForImageClassification,
						        '''image-segmentation''': SegformerForSemanticSegmentation,
						    }
						    if is_torch_available()
						    else {}
						)

						_A    :				Optional[int]       					=			True
						_A    :				Optional[Any]       					=			False
						_A    :				int       					=			False
						_A    :				Optional[int]       					=			False





						def 			UpperCamelCase__					(    self    )     -> Dict:
									a_						:						str 							= SegformerModelTester(self    )
									a_						:						Optional[int] 							= SegformerConfigTester(self  ,      config_class=_lowercase    )





						def 			UpperCamelCase__					(    self    )     -> Union[str, Any]:
									self.config_tester.run_common_tests()





						def 			UpperCamelCase__					(    self    )     -> List[Any]:
									a_						:						str 							= self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*_lowercase    )





						def 			UpperCamelCase__					(    self    )     -> int:
									a_						:						int 							= self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_binary_image_segmentation(*_lowercase    )





						def 			UpperCamelCase__					(    self    )     -> Optional[int]:
									a_						:						int 							= self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_segmentation(*_lowercase    )





						@unittest.skip("""SegFormer does not use inputs_embeds"""    )
						def 			UpperCamelCase__					(    self    )     -> Optional[int]:
									pass





						@unittest.skip("""SegFormer does not have get_input_embeddings method and get_output_embeddings methods"""    )
						def 			UpperCamelCase__					(    self    )     -> List[Any]:
									pass





						def 			UpperCamelCase__					(    self    )     -> Dict:
									a_							,					a_						:						Any 							= self.model_tester.prepare_config_and_inputs_for_common()

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

												a_						:						List[str] 							= ["""pixel_values"""]
												self.assertListEqual(arg_names[:1]  ,      _lowercase    )





						def 			UpperCamelCase__					(    self    )     -> Optional[int]:
									a_							,					a_						:						Any 							= self.model_tester.prepare_config_and_inputs_for_common()
									a_						:						Optional[int] 							= True

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

												a_						:						Optional[int] 							= sum(self.model_tester.depths    )
												self.assertEqual(len(_lowercase    )  ,      _lowercase    )

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

												self.assertEqual(len(_lowercase    )  ,      _lowercase    )

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

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

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

												a_						:						Optional[int] 							= outputs.attentions

												self.assertEqual(len(_lowercase    )  ,      _lowercase    )
												# verify the first attentions (first block, first layer)
												a_						:						int 							= (self.model_tester.image_size // 4) ** 2
												a_						:						Union[str, 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 			UpperCamelCase__					(    self    )     -> Optional[int]:
									def check_hidden_states_output(_lowercase  ,      _lowercase  ,      _lowercase    ):
												a_						:						Tuple 							= model_class(_lowercase    )
												model.to(_lowercase    )
												model.eval()

												with torch.no_grad():
															a_						:						Tuple 							= model(**self._prepare_for_class(_lowercase  ,      _lowercase    )    )

												a_						:						Optional[Any] 							= outputs.hidden_states

												a_						:						Optional[Any] 							= self.model_tester.num_encoder_blocks
												self.assertEqual(len(_lowercase    )  ,      _lowercase    )

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

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

									for model_class in self.all_model_classes:
												a_						:						List[Any] 							= True
												check_hidden_states_output(_lowercase  ,      _lowercase  ,      _lowercase    )

												# check that output_hidden_states also work using config
												del inputs_dict["output_hidden_states"]
												a_						:						Dict 							= True

												check_hidden_states_output(_lowercase  ,      _lowercase  ,      _lowercase    )





						def 			UpperCamelCase__					(    self    )     -> Optional[Any]:
									if not self.model_tester.is_training:
												return

									a_							,					a_						:						Dict 							= self.model_tester.prepare_config_and_inputs_for_common()
									a_						:						List[Any] 							= True

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

												a_						:						Union[str, Any] 							= model_class(_lowercase    )
												model.to(_lowercase    )
												model.train()
												a_						:						List[str] 							= self._prepare_for_class(_lowercase  ,      _lowercase  ,      return_labels=_lowercase    )
												a_						:						List[Any] 							= model(**_lowercase    ).loss
												loss.backward()





						@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""    )
						def 			UpperCamelCase__					(    self    )     -> Union[str, Any]:
									pass





						@slow
						def 			UpperCamelCase__					(    self    )     -> Optional[Any]:
									for model_name in SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												a_						:						Union[str, Any] 							= SegformerModel.from_pretrained(_lowercase    )
												self.assertIsNotNone(_lowercase    )







def 					_UpperCAmelCase				(						):

			'''simple docstring'''



			a_						:						List[str] 							= Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""")
			return image



@require_torch
class        A__(unittest.TestCase							):
						"""simple docstring"""






						@slow
						def 			UpperCamelCase__					(    self    )     -> List[str]:
									# only resize + normalize
									a_						:						Tuple 							= SegformerImageProcessor(
									    image_scale=(512, 512)  ,      keep_ratio=_lowercase  ,      align=_lowercase  ,      do_random_crop=_lowercase    )
									a_						:						Dict 							= SegformerForSemanticSegmentation.from_pretrained("""nvidia/segformer-b0-finetuned-ade-512-512"""    ).to(
									    _lowercase    )

									a_						:						str 							= prepare_img()
									a_						:						str 							= image_processor(images=_lowercase  ,      return_tensors="""pt"""    )
									a_						:						List[str] 							= encoded_inputs.pixel_values.to(_lowercase    )

									with torch.no_grad():
												a_						:						Union[str, Any] 							= model(_lowercase    )

									a_						:						Tuple 							= torch.Size((1, model.config.num_labels, 128, 128)    )
									self.assertEqual(outputs.logits.shape  ,      _lowercase    )

									a_						:						Any 							= torch.tensor(
									    [
									        [[-4.6_3_1_0, -5.5_2_3_2, -6.2_3_5_6], [-5.1_9_2_1, -6.1_4_4_4, -6.5_9_9_6], [-5.4_4_2_4, -6.2_7_9_0, -6.7_5_7_4]],
									        [[-1_2.1_3_9_1, -1_3.3_1_2_2, -1_3.9_5_5_4], [-1_2.8_7_3_2, -1_3.9_3_5_2, -1_4.3_5_6_3], [-1_2.9_4_3_8, -1_3.8_2_2_6, -1_4.2_5_1_3]],
									        [[-1_2.5_1_3_4, -1_3.4_6_8_6, -1_4.4_9_1_5], [-1_2.8_6_6_9, -1_4.4_3_4_3, -1_4.7_7_5_8], [-1_3.2_5_2_3, -1_4.5_8_1_9, -1_5.0_6_9_4]],
									    ]    ).to(_lowercase    )
									self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]  ,      _lowercase  ,      atol=1e-4    )    )





						@slow
						def 			UpperCamelCase__					(    self    )     -> Optional[Any]:
									# only resize + normalize
									a_						:						Optional[Any] 							= SegformerImageProcessor(
									    image_scale=(512, 512)  ,      keep_ratio=_lowercase  ,      align=_lowercase  ,      do_random_crop=_lowercase    )
									a_						:						int 							= SegformerForSemanticSegmentation.from_pretrained(
									    """nvidia/segformer-b1-finetuned-cityscapes-1024-1024"""    ).to(_lowercase    )

									a_						:						Any 							= prepare_img()
									a_						:						List[Any] 							= image_processor(images=_lowercase  ,      return_tensors="""pt"""    )
									a_						:						Optional[int] 							= encoded_inputs.pixel_values.to(_lowercase    )

									with torch.no_grad():
												a_						:						List[str] 							= model(_lowercase    )

									a_						:						Tuple 							= torch.Size((1, model.config.num_labels, 128, 128)    )
									self.assertEqual(outputs.logits.shape  ,      _lowercase    )

									a_						:						Any 							= torch.tensor(
									    [
									        [[-1_3.5_7_4_8, -1_3.9_1_1_1, -1_2.6_5_0_0], [-1_4.3_5_0_0, -1_5.3_6_8_3, -1_4.2_3_2_8], [-1_4.7_5_3_2, -1_6.0_4_2_4, -1_5.6_0_8_7]],
									        [[-1_7.1_6_5_1, -1_5.8_7_2_5, -1_2.9_6_5_3], [-1_7.2_5_8_0, -1_7.3_7_1_8, -1_4.8_2_2_3], [-1_6.6_0_5_8, -1_6.8_7_8_3, -1_6.7_4_5_2]],
									        [[-3.6_4_5_6, -3.0_2_0_9, -1.4_2_0_3], [-3.0_7_9_7, -3.1_9_5_9, -2.0_0_0_0], [-1.8_7_5_7, -1.9_2_1_7, -1.6_9_9_7]],
									    ]    ).to(_lowercase    )
									self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]  ,      _lowercase  ,      atol=1e-1    )    )





						@slow
						def 			UpperCamelCase__					(    self    )     -> List[str]:
									# only resize + normalize
									a_						:						Tuple 							= SegformerImageProcessor(
									    image_scale=(512, 512)  ,      keep_ratio=_lowercase  ,      align=_lowercase  ,      do_random_crop=_lowercase    )
									a_						:						str 							= SegformerForSemanticSegmentation.from_pretrained("""nvidia/segformer-b0-finetuned-ade-512-512"""    ).to(
									    _lowercase    )

									a_						:						int 							= prepare_img()
									a_						:						Any 							= image_processor(images=_lowercase  ,      return_tensors="""pt"""    )
									a_						:						Optional[int] 							= encoded_inputs.pixel_values.to(_lowercase    )

									with torch.no_grad():
												a_						:						Any 							= model(_lowercase    )

									a_						:						str 							= outputs.logits.detach().cpu()

									a_						:						int 							= image_processor.post_process_semantic_segmentation(outputs=_lowercase  ,      target_sizes=[(500, 300)]    )
									a_						:						Any 							= torch.Size((500, 300)    )
									self.assertEqual(segmentation[0].shape  ,      _lowercase    )

									a_						:						Tuple 							= image_processor.post_process_semantic_segmentation(outputs=_lowercase    )
									a_						:						Optional[Any] 							= torch.Size((128, 128)    )
									self.assertEqual(segmentation[0].shape  ,      _lowercase    )


