




'''simple docstring'''

import inspect
import unittest

from transformers import SegformerConfig, is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
						import torch

						from transformers import (
						    MODEL_MAPPING,
						    SegformerForImageClassification,
						    SegformerForSemanticSegmentation,
						    SegformerModel,
						)
						from transformers.models.segformer.modeling_segformer import SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
						from PIL import Image

						from transformers import SegformerImageProcessor



class 		SCREAMING_SNAKE_CASE__  (			_UpperCamelCase	):





			def 							A (      self						:    Optional[Any]							):



						"""simple docstring"""




						__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 		SCREAMING_SNAKE_CASE__  :





			def __init__(      self						:    List[Any]      ,		a_						:    Any      ,		a_						:    Tuple=13      ,		a_						:    Optional[Any]=64      ,		a_						:    str=3      ,		a_						:    Any=4      ,		a_						:    List[str]=[2, 2, 2, 2]      ,		a_						:    Optional[int]=[8, 4, 2, 1]      ,		a_						:    List[str]=[16, 32, 64, 128]      ,		a_						:    Union[str, Any]=[1, 4, 8, 16]      ,		a_						:    Dict=[1, 2, 4, 8]      ,		a_						:    Tuple=True      ,		a_						:    Optional[int]=True      ,		a_						:    int="gelu"      ,		a_						:    Optional[Any]=0.1      ,		a_						:    Optional[int]=0.1      ,		a_						:    int=0.02      ,		a_						:    Optional[int]=3      ,		a_						:    Any=None      ,		):



						"""simple docstring"""




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





			def 							A (      self						:    int							):



						"""simple docstring"""




						__snake_case			=		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

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

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





			def 							A (      self						:    Union[str, Any]							):



						"""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 							A (      self						:    List[Any]      ,		a_						:    int      ,		a_						:    List[str]      ,		a_						:    Dict							):



						"""simple docstring"""




						__snake_case			=		SegformerModel(config=a_							)
						model.to(a_							)
						model.eval()
						__snake_case			=		model(a_							)
						__snake_case			=		__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						:    int      ,		a_						:    List[Any]      ,		a_						:    Dict      ,		a_						:    Optional[Any]							):



						"""simple docstring"""




						__snake_case			=		self.num_labels
						__snake_case			=		SegformerForSemanticSegmentation(a_							)
						model.to(a_							)
						model.eval()
						__snake_case			=		model(a_							)
						self.parent.assertEqual(
						    result.logits.shape      ,		(self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4)							)
						__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]      ,		a_						:    str      ,		a_						:    Dict      ,		a_						:    str							):



						"""simple docstring"""




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






			def 							A (      self						:    Optional[Any]							):



						"""simple docstring"""




						__snake_case			=		self.prepare_config_and_inputs()
						__snake_case		,     __snake_case		,     __snake_case			=		config_and_inputs
						__snake_case			=		{"pixel_values": pixel_values}
						return config, inputs_dict







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

			__SCREAMING_SNAKE_CASE    =			True
			__SCREAMING_SNAKE_CASE    =			False
			__SCREAMING_SNAKE_CASE    =			False
			__SCREAMING_SNAKE_CASE    =			False





			def 							A (      self						:    Any							):



						"""simple docstring"""




						__snake_case			=		SegformerModelTester(self							)
						__snake_case			=		SegformerConfigTester(self      ,		config_class=a_							)





			def 							A (      self						:    Any							):



						"""simple docstring"""




						self.config_tester.run_common_tests()





			def 							A (      self						:    List[Any]							):



						"""simple docstring"""




						__snake_case			=		self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*a_							)





			def 							A (      self						:    str							):



						"""simple docstring"""




						__snake_case			=		self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_binary_image_segmentation(*a_							)





			def 							A (      self						:    Optional[Any]							):



						"""simple docstring"""




						__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						:    Tuple							):



						"""simple docstring"""




						pass





			@unittest.skip("SegFormer does not have get_input_embeddings method and get_output_embeddings methods"							)
			def 							A (      self						:    Optional[Any]							):



						"""simple docstring"""




						pass





			def 							A (      self						:    Optional[Any]							):



						"""simple docstring"""




						__snake_case		,     __snake_case			=		self.model_tester.prepare_config_and_inputs_for_common()

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

									__snake_case			=		["pixel_values"]
									self.assertListEqual(arg_names[:1]      ,		a_							)





			def 							A (      self						:    Tuple							):



						"""simple docstring"""




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

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

									__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"]
									__snake_case			=		True
									__snake_case			=		model_class(a_							)
									model.to(a_							)
									model.eval()
									with torch.no_grad():
												__snake_case			=		model(**self._prepare_for_class(a_      ,		a_							)							)
									__snake_case			=		outputs.attentions

									self.assertEqual(len(a_							)      ,		a_							)

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

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

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

									__snake_case			=		outputs.attentions

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



						"""simple docstring"""




						def check_hidden_states_output(a_						:    List[Any]      ,		a_						:    List[Any]      ,		a_						:    Tuple							):
									__snake_case			=		model_class(a_							)
									model.to(a_							)
									model.eval()

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

									__snake_case			=		outputs.hidden_states

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

						__snake_case		,     __snake_case			=		self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
									__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"]
									__snake_case			=		True

									check_hidden_states_output(a_      ,		a_      ,		a_							)





			def 							A (      self						:    Tuple							):



						"""simple docstring"""




						if not self.model_tester.is_training:
									return

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

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

									__snake_case			=		model_class(a_							)
									model.to(a_							)
									model.train()
									__snake_case			=		self._prepare_for_class(a_      ,		a_      ,		return_labels=a_							)
									__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						:    int							):



						"""simple docstring"""




						pass






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



						"""simple docstring"""




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







def __UpperCAmelCase	(   )      ->      List[Any]:
			__snake_case			=		Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"						)
			return image






@require_torch
class 		SCREAMING_SNAKE_CASE__  (			unittest.TestCase	):





			@slow
			def 							A (      self						:    Dict							):



						"""simple docstring"""




						__snake_case			=		SegformerImageProcessor(
						    image_scale=(512, 512)      ,		keep_ratio=a_      ,		align=a_      ,		do_random_crop=a_							)
						__snake_case			=		SegformerForSemanticSegmentation.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512"							).to(
						    a_							)

						__snake_case			=		prepare_img()
						__snake_case			=		image_processor(images=a_      ,		return_tensors="pt"							)
						__snake_case			=		encoded_inputs.pixel_values.to(a_							)

						with torch.no_grad():
									__snake_case			=		model(a_							)

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

						__snake_case			=		torch.tensor(
						    [
						        [[-4.6310, -5.5232, -6.2356], [-5.1921, -6.1444, -6.5996], [-5.4424, -6.2790, -6.7574]],
						        [[-12.1391, -13.3122, -13.9554], [-12.8732, -13.9352, -14.3563], [-12.9438, -13.8226, -14.2513]],
						        [[-12.5134, -13.4686, -14.4915], [-12.8669, -14.4343, -14.7758], [-13.2523, -14.5819, -15.0694]],
						    ]							).to(a_							)
						self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]      ,		a_      ,		atol=1e-4							)							)





			@slow
			def 							A (      self						:    Tuple							):



						"""simple docstring"""




						__snake_case			=		SegformerImageProcessor(
						    image_scale=(512, 512)      ,		keep_ratio=a_      ,		align=a_      ,		do_random_crop=a_							)
						__snake_case			=		SegformerForSemanticSegmentation.from_pretrained(
						    "nvidia/segformer-b1-finetuned-cityscapes-1024-1024"							).to(a_							)

						__snake_case			=		prepare_img()
						__snake_case			=		image_processor(images=a_      ,		return_tensors="pt"							)
						__snake_case			=		encoded_inputs.pixel_values.to(a_							)

						with torch.no_grad():
									__snake_case			=		model(a_							)

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

						__snake_case			=		torch.tensor(
						    [
						        [[-13.5748, -13.9111, -12.6500], [-14.3500, -15.3683, -14.2328], [-14.7532, -16.0424, -15.6087]],
						        [[-17.1651, -15.8725, -12.9653], [-17.2580, -17.3718, -14.8223], [-16.6058, -16.8783, -16.7452]],
						        [[-3.6456, -3.0209, -1.4203], [-3.0797, -3.1959, -2.0000], [-1.8757, -1.9217, -1.6997]],
						    ]							).to(a_							)
						self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]      ,		a_      ,		atol=1e-1							)							)






			@slow
			def 							A (      self						:    Tuple							):



						"""simple docstring"""




						__snake_case			=		SegformerImageProcessor(
						    image_scale=(512, 512)      ,		keep_ratio=a_      ,		align=a_      ,		do_random_crop=a_							)
						__snake_case			=		SegformerForSemanticSegmentation.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512"							).to(
						    a_							)

						__snake_case			=		prepare_img()
						__snake_case			=		image_processor(images=a_      ,		return_tensors="pt"							)
						__snake_case			=		encoded_inputs.pixel_values.to(a_							)

						with torch.no_grad():
									__snake_case			=		model(a_							)

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

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

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









'''simple docstring'''





from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
    is_vision_available,
)


UpperCAmelCase__  			=				{
    '''configuration_owlvit''': [
        '''OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''',
        '''OwlViTConfig''',
        '''OwlViTOnnxConfig''',
        '''OwlViTTextConfig''',
        '''OwlViTVisionConfig''',
    ],
    '''processing_owlvit''': ['''OwlViTProcessor'''],
}


try:
					if not is_vision_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					UpperCAmelCase__  			=				['''OwlViTFeatureExtractor''']
					UpperCAmelCase__  			=				['''OwlViTImageProcessor''']

try:
					if not is_torch_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					UpperCAmelCase__  			=				[
					    '''OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST''',
					    '''OwlViTModel''',
					    '''OwlViTPreTrainedModel''',
					    '''OwlViTTextModel''',
					    '''OwlViTVisionModel''',
					    '''OwlViTForObjectDetection''',
					]

if TYPE_CHECKING:
					from .configuration_owlvit import (
					    OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP,
					    OwlViTConfig,
					    OwlViTOnnxConfig,
					    OwlViTTextConfig,
					    OwlViTVisionConfig,
					)
					from .processing_owlvit import OwlViTProcessor

					try:
										if not is_vision_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .feature_extraction_owlvit import OwlViTFeatureExtractor
										from .image_processing_owlvit import OwlViTImageProcessor

					try:
										if not is_torch_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .modeling_owlvit import (
										    OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST,
										    OwlViTForObjectDetection,
										    OwlViTModel,
										    OwlViTPreTrainedModel,
										    OwlViTTextModel,
										    OwlViTVisionModel,
										)

else:
					import sys

					UpperCAmelCase__  			=				_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)



