



"""simple docstring"""
import collections
import inspect
import unittest
from typing import Dict, List, Tuple

from transformers import MaskFormerSwinConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device
from transformers.utils import is_torch_available

from ...test_backbone_common import BackboneTesterMixin
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 torch import nn

						from transformers import MaskFormerSwinBackbone
						from transformers.models.maskformer import MaskFormerSwinModel
class 				lowerCamelCase  :






					'''simple docstring'''





					def __init__(       self:							Dict						,     snake_case:							Optional[Any]						,     snake_case:							Tuple=13						,     snake_case:							Any=32						,     snake_case:							Union[str, Any]=2						,     snake_case:							Tuple=3						,     snake_case:							Union[str, Any]=16						,     snake_case:							Union[str, Any]=[1, 2, 1]						,     snake_case:							Optional[Any]=[2, 2, 4]						,     snake_case:							str=2						,     snake_case:							List[str]=2.0						,     snake_case:							Optional[int]=True						,     snake_case:							Union[str, Any]=0.0						,     snake_case:							Optional[int]=0.0						,     snake_case:							Optional[Any]=0.1						,     snake_case:							List[str]="gelu"						,     snake_case:							Any=False						,     snake_case:							Optional[Any]=True						,     snake_case:							Optional[int]=0.0_2						,     snake_case:							Any=1E-5						,     snake_case:							Optional[int]=True						,     snake_case:							int=None						,     snake_case:							Any=True						,     snake_case:							str=10						,     snake_case:							Optional[Any]=8						,     snake_case:							Union[str, Any]=["stage1", "stage2", "stage3"]						,     snake_case:							Tuple=[1, 2, 3]						,     )   ->	Dict:
											snake_case_ :Dict						=			parent
											snake_case_ :List[Any]						=			batch_size
											snake_case_ :Dict						=			image_size
											snake_case_ :Dict						=			patch_size
											snake_case_ :Tuple						=			num_channels
											snake_case_ :List[Any]						=			embed_dim
											snake_case_ :List[str]						=			depths
											snake_case_ :str						=			num_heads
											snake_case_ :Tuple						=			window_size
											snake_case_ :Tuple						=			mlp_ratio
											snake_case_ :int						=			qkv_bias
											snake_case_ :Tuple						=			hidden_dropout_prob
											snake_case_ :Optional[Any]						=			attention_probs_dropout_prob
											snake_case_ :Dict						=			drop_path_rate
											snake_case_ :Any						=			hidden_act
											snake_case_ :Any						=			use_absolute_embeddings
											snake_case_ :int						=			patch_norm
											snake_case_ :List[Any]						=			layer_norm_eps
											snake_case_ :Tuple						=			initializer_range
											snake_case_ :str						=			is_training
											snake_case_ :int						=			scope
											snake_case_ :Tuple						=			use_labels
											snake_case_ :Tuple						=			type_sequence_label_size
											snake_case_ :str						=			encoder_stride
											snake_case_ :List[Any]						=			out_features
											snake_case_ :str						=			out_indices






					def    lowerCAmelCase_				(       self:							Tuple						)   ->	Dict:
											snake_case_ :Optional[int]						=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

											snake_case_ :str						=			None
											if self.use_labels:
																	snake_case_ :Optional[int]						=			ids_tensor([self.batch_size]						,     self.type_sequence_label_size						)

											snake_case_ :Union[str, Any]						=			self.get_config()

											return config, pixel_values, labels






					def    lowerCAmelCase_				(       self:							int						)   ->	Optional[Any]:
											return MaskFormerSwinConfig(
											    image_size=self.image_size						,     patch_size=self.patch_size						,     num_channels=self.num_channels						,     embed_dim=self.embed_dim						,     depths=self.depths						,     num_heads=self.num_heads						,     window_size=self.window_size						,     mlp_ratio=self.mlp_ratio						,     qkv_bias=self.qkv_bias						,     hidden_dropout_prob=self.hidden_dropout_prob						,     attention_probs_dropout_prob=self.attention_probs_dropout_prob						,     drop_path_rate=self.drop_path_rate						,     hidden_act=self.hidden_act						,     use_absolute_embeddings=self.use_absolute_embeddings						,     path_norm=self.patch_norm						,     layer_norm_eps=self.layer_norm_eps						,     initializer_range=self.initializer_range						,     encoder_stride=self.encoder_stride						,     out_features=self.out_features						,     out_indices=self.out_indices						,     )






					def    lowerCAmelCase_				(       self:							List[Any]						,     snake_case:							str						,     snake_case:							int						,     snake_case:							List[str]						)   ->	Any:
											snake_case_ :Dict						=			MaskFormerSwinModel(config=snake_case						)
											model.to(snake_case						)
											model.eval()
											snake_case_ :Tuple						=			model(snake_case						)

											snake_case_ :Dict						=			((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths						) - 1))
											snake_case_ :Any						=			int(config.embed_dim * 2 ** (len(config.depths						) - 1)						)

											self.parent.assertEqual(result.last_hidden_state.shape						,     (self.batch_size, expected_seq_len, expected_dim)						)






					def    lowerCAmelCase_				(       self:							Optional[Any]						,     snake_case:							int						,     snake_case:							List[str]						,     snake_case:							Tuple						)   ->	Union[str, Any]:
											snake_case_ :Any						=			MaskFormerSwinBackbone(config=snake_case						)
											model.to(snake_case						)
											model.eval()
											snake_case_ :Optional[Any]						=			model(snake_case						)

											# verify feature maps
											self.parent.assertEqual(len(result.feature_maps						)						,     len(config.out_features						)						)
											self.parent.assertListEqual(list(result.feature_maps[0].shape						)						,     [13, 16, 16, 16]						)

											# verify channels
											self.parent.assertEqual(len(model.channels						)						,     len(config.out_features						)						)
											self.parent.assertListEqual(model.channels						,     [16, 32, 64]						)

											# verify ValueError
											with self.parent.assertRaises(snake_case						):
																	snake_case_ :Optional[Any]						=			["""stem"""]
																	snake_case_ :str						=			MaskFormerSwinBackbone(config=snake_case						)






					def    lowerCAmelCase_				(       self:							List[str]						)   ->	Optional[Any]:
											snake_case_ :Optional[int]						=			self.prepare_config_and_inputs()
											snake_case_,       snake_case_,       snake_case_ :str						=			config_and_inputs
											snake_case_ :Tuple						=			{"""pixel_values""": pixel_values}
											return config, inputs_dict

@require_torch
class 				lowerCamelCase  (			_lowerCAmelCase    ,						_lowerCAmelCase    ,						unittest.TestCase				):






					'''simple docstring'''





					_A		:			Union[str, Any]						=     (
					    (
					        MaskFormerSwinModel,
					        MaskFormerSwinBackbone,
					    )
					    if is_torch_available()
					    else ()
					)
					_A		:			str						=     {"""feature-extraction""": MaskFormerSwinModel} if is_torch_available() else {}
					_A		:			List[str]						=     False
					_A		:			Any						=     False
					_A		:			Dict						=     False
					_A		:			List[Any]						=     False
					_A		:			Optional[int]						=     False






					def    lowerCAmelCase_				(       self:							Dict						)   ->	Any:
											snake_case_ :str						=			MaskFormerSwinModelTester(self						)
											snake_case_ :Optional[Any]						=			ConfigTester(self						,     config_class=snake_case						,     embed_dim=37						)






					@require_torch_multi_gpu
					@unittest.skip(
					    reason=(
					        """`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn't work well with"""
					        """ `nn.DataParallel`"""
					    )						)
					def    lowerCAmelCase_				(       self:							List[str]						)   ->	Optional[int]:
											pass






					def    lowerCAmelCase_				(       self:							Union[str, Any]						)   ->	Dict:
											self.create_and_test_config_common_properties()
											self.config_tester.create_and_test_config_to_json_string()
											self.config_tester.create_and_test_config_to_json_file()
											self.config_tester.create_and_test_config_from_and_save_pretrained()
											self.config_tester.create_and_test_config_with_num_labels()
											self.config_tester.check_config_can_be_init_without_params()
											self.config_tester.check_config_arguments_init()






					def    lowerCAmelCase_				(       self:							Any						)   ->	Tuple:
											return






					def    lowerCAmelCase_				(       self:							Any						)   ->	Any:
											snake_case_ :List[Any]						=			self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*snake_case						)






					def    lowerCAmelCase_				(       self:							Union[str, Any]						)   ->	int:
											snake_case_ :Any						=			self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_backbone(*snake_case						)






					@unittest.skip("""Swin does not use inputs_embeds"""						)
					def    lowerCAmelCase_				(       self:							str						)   ->	List[str]:
											pass






					@unittest.skip("""Swin does not support feedforward chunking"""						)
					def    lowerCAmelCase_				(       self:							int						)   ->	Optional[int]:
											pass






					def    lowerCAmelCase_				(       self:							List[str]						)   ->	List[Any]:
											snake_case_,       snake_case_ :List[Any]						=			self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																	snake_case_ :str						=			model_class(snake_case						)
																	self.assertIsInstance(model.get_input_embeddings()						,     (nn.Module)						)
																	snake_case_ :Dict						=			model.get_output_embeddings()
																	self.assertTrue(x is None or isinstance(snake_case						,     nn.Linear						)						)






					def    lowerCAmelCase_				(       self:							Tuple						)   ->	Dict:
											snake_case_,       snake_case_ :int						=			self.model_tester.prepare_config_and_inputs_for_common()

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

																	snake_case_ :str						=			["""pixel_values"""]
																	self.assertListEqual(arg_names[:1]						,     snake_case						)






					@unittest.skip(reason="""MaskFormerSwin is only used as backbone and doesn't support output_attentions"""						)
					def    lowerCAmelCase_				(       self:							List[Any]						)   ->	List[Any]:
											pass






					@unittest.skip(reason="""MaskFormerSwin is only used as an internal backbone"""						)
					def    lowerCAmelCase_				(       self:							Dict						)   ->	List[Any]:
											pass






					def    lowerCAmelCase_				(       self:							Union[str, Any]						,     snake_case:							Union[str, Any]						,     snake_case:							int						,     snake_case:							Any						,     snake_case:							List[str]						)   ->	str:
											snake_case_ :List[str]						=			model_class(snake_case						)
											model.to(snake_case						)
											model.eval()

											with torch.no_grad():
																	snake_case_ :List[Any]						=			model(**self._prepare_for_class(snake_case						,     snake_case						)						)

											snake_case_ :Any						=			outputs.hidden_states

											snake_case_ :Optional[int]						=			getattr(
											    self.model_tester						,     """expected_num_hidden_layers"""						,     len(self.model_tester.depths						) + 1						)
											self.assertEqual(len(snake_case						)						,     snake_case						)

											# Swin has a different seq_length
											snake_case_ :str						=			(
											    config.patch_size
											    if isinstance(config.patch_size						,     collections.abc.Iterable						)
											    else (config.patch_size, config.patch_size)
											)

											snake_case_ :int						=			(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

											self.assertListEqual(
											    list(hidden_states[0].shape[-2:]						)						,     [num_patches, self.model_tester.embed_dim]						,     )






					def    lowerCAmelCase_				(       self:							List[Any]						)   ->	Optional[int]:
											snake_case_,       snake_case_ :Any						=			self.model_tester.prepare_config_and_inputs_for_common()

											snake_case_ :List[Any]						=			(
											    self.model_tester.image_size
											    if isinstance(self.model_tester.image_size						,     collections.abc.Iterable						)
											    else (self.model_tester.image_size, self.model_tester.image_size)
											)

											for model_class in self.all_model_classes:
																	snake_case_ :Tuple						=			True
																	self.check_hidden_states_output(snake_case						,     snake_case						,     snake_case						,     snake_case						)

																	# check that output_hidden_states also work using config
																	del inputs_dict["output_hidden_states"]
																	snake_case_ :List[Any]						=			True

																	self.check_hidden_states_output(snake_case						,     snake_case						,     snake_case						,     snake_case						)






					def    lowerCAmelCase_				(       self:							Optional[Any]						)   ->	Tuple:
											snake_case_,       snake_case_ :int						=			self.model_tester.prepare_config_and_inputs_for_common()
											snake_case_ :List[Any]						=			3

											snake_case_ :List[Any]						=			(
											    self.model_tester.image_size
											    if isinstance(self.model_tester.image_size						,     collections.abc.Iterable						)
											    else (self.model_tester.image_size, self.model_tester.image_size)
											)
											snake_case_ :Any						=			(
											    config.patch_size
											    if isinstance(config.patch_size						,     collections.abc.Iterable						)
											    else (config.patch_size, config.patch_size)
											)

											snake_case_ :Tuple						=			image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
											snake_case_ :List[str]						=			image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

											for model_class in self.all_model_classes:
																	snake_case_ :str						=			True
																	self.check_hidden_states_output(snake_case						,     snake_case						,     snake_case						,     (padded_height, padded_width)						)

																	# check that output_hidden_states also work using config
																	del inputs_dict["output_hidden_states"]
																	snake_case_ :Any						=			True
																	self.check_hidden_states_output(snake_case						,     snake_case						,     snake_case						,     (padded_height, padded_width)						)






					@unittest.skip(reason="""MaskFormerSwin doesn't have pretrained checkpoints"""						)
					def    lowerCAmelCase_				(       self:							Union[str, Any]						)   ->	List[str]:
											pass






					@unittest.skip(reason="""This will be fixed once MaskFormerSwin is replaced by native Swin"""						)
					def    lowerCAmelCase_				(       self:							List[str]						)   ->	str:
											pass






					@unittest.skip(reason="""This will be fixed once MaskFormerSwin is replaced by native Swin"""						)
					def    lowerCAmelCase_				(       self:							str						)   ->	List[Any]:
											pass






					def    lowerCAmelCase_				(       self:							Union[str, Any]						)   ->	Optional[Any]:
											snake_case_,       snake_case_ :Dict						=			self.model_tester.prepare_config_and_inputs_for_common()

											def set_nan_tensor_to_zero(snake_case:							str						):
																	snake_case_ :Optional[int]						=			0
																	return t

											def check_equivalence(snake_case:							List[Any]						,     snake_case:							Union[str, Any]						,     snake_case:							int						,     snake_case:							Tuple={}						):
																	with torch.no_grad():
																							snake_case_ :List[Any]						=			model(**snake_case						,     return_dict=snake_case						,     **snake_case						)
																							snake_case_ :Any						=			model(**snake_case						,     return_dict=snake_case						,     **snake_case						).to_tuple()

																							def recursive_check(snake_case:							List[Any]						,     snake_case:							int						):
																													if isinstance(snake_case						,     (List, Tuple)						):
																																			for tuple_iterable_value, dict_iterable_value in zip(snake_case						,     snake_case						):
																																									recursive_check(snake_case						,     snake_case						)
																													elif isinstance(snake_case						,     snake_case						):
																																			for tuple_iterable_value, dict_iterable_value in zip(
																																			    tuple_object.values()						,     dict_object.values()						):
																																									recursive_check(snake_case						,     snake_case						)
																													elif tuple_object is None:
																																			return
																													else:
																																			self.assertTrue(
																																			    torch.allclose(
																																			        set_nan_tensor_to_zero(snake_case						)						,     set_nan_tensor_to_zero(snake_case						)						,     atol=1E-5						)						,     msg=(
																																			        """Tuple and dict output are not equal. Difference:"""
																																			        f""" {torch.max(torch.abs(tuple_object - dict_object						)						)}. Tuple has `nan`:"""
																																			        f""" {torch.isnan(snake_case						).any()} and `inf`: {torch.isinf(snake_case						)}. Dict has"""
																																			        f""" `nan`: {torch.isnan(snake_case						).any()} and `inf`: {torch.isinf(snake_case						)}."""
																																			    )						,     )

																							recursive_check(snake_case						,     snake_case						)

											for model_class in self.all_model_classes:
																	snake_case_ :int						=			model_class(snake_case						)
																	model.to(snake_case						)
																	model.eval()

																	snake_case_ :Any						=			self._prepare_for_class(snake_case						,     snake_case						)
																	snake_case_ :List[Any]						=			self._prepare_for_class(snake_case						,     snake_case						)
																	check_equivalence(snake_case						,     snake_case						,     snake_case						)

																	snake_case_ :Tuple						=			self._prepare_for_class(snake_case						,     snake_case						,     return_labels=snake_case						)
																	snake_case_ :Dict						=			self._prepare_for_class(snake_case						,     snake_case						,     return_labels=snake_case						)
																	check_equivalence(snake_case						,     snake_case						,     snake_case						)

																	snake_case_ :Tuple						=			self._prepare_for_class(snake_case						,     snake_case						)
																	snake_case_ :Any						=			self._prepare_for_class(snake_case						,     snake_case						)
																	check_equivalence(snake_case						,     snake_case						,     snake_case						,     {"""output_hidden_states""": True}						)

																	snake_case_ :Dict						=			self._prepare_for_class(snake_case						,     snake_case						,     return_labels=snake_case						)
																	snake_case_ :List[str]						=			self._prepare_for_class(snake_case						,     snake_case						,     return_labels=snake_case						)
																	check_equivalence(snake_case						,     snake_case						,     snake_case						,     {"""output_hidden_states""": True}						)

@require_torch
class 				lowerCamelCase  (			unittest.TestCase    ,						_lowerCAmelCase				):






					'''simple docstring'''





					_A		:			int						=     (MaskFormerSwinBackbone,) if is_torch_available() else ()
					_A		:			Tuple						=     MaskFormerSwinConfig






					def    lowerCAmelCase_				(       self:							List[str]						)   ->	Optional[int]:
											snake_case_ :Optional[Any]						=			MaskFormerSwinModelTester(self						)






					def    lowerCAmelCase_				(       self:							int						)   ->	Optional[int]:
											snake_case_,       snake_case_ :Any						=			self.model_tester.prepare_config_and_inputs_for_common()
											snake_case_ :Tuple						=			inputs_dict["""pixel_values"""].shape[0]

											for backbone_class in self.all_model_classes:
																	snake_case_ :List[str]						=			backbone_class(snake_case						)
																	backbone.to(snake_case						)
																	backbone.eval()

																	snake_case_ :List[Any]						=			backbone(**snake_case						)

																	# Test default outputs and verify feature maps
																	self.assertIsInstance(outputs.feature_maps						,     snake_case						)
																	self.assertTrue(len(outputs.feature_maps						) == len(backbone.channels						)						)
																	for feature_map, n_channels in zip(outputs.feature_maps						,     backbone.channels						):
																							self.assertTrue(feature_map.shape[:2]						,     (batch_size, n_channels)						)
																	self.assertIsNone(outputs.hidden_states						)
																	self.assertIsNone(outputs.attentions						)

																	# Test output_hidden_states=True
																	snake_case_ :Union[str, Any]						=			backbone(**snake_case						,     output_hidden_states=snake_case						)
																	self.assertIsNotNone(outputs.hidden_states						)
																	self.assertTrue(len(outputs.hidden_states						)						,     len(backbone.stage_names						)						)
																	# We skip the stem layer
																	for hidden_states, n_channels in zip(outputs.hidden_states[1:]						,     backbone.channels						):
																							for hidden_state in hidden_states:
																													# Hidden states are in the format (batch_size, (height * width), n_channels)
																													snake_case_,       snake_case_,       snake_case_ :List[Any]						=			hidden_state.shape
																													self.assertTrue((h_batch_size, h_n_channels)						,     (batch_size, n_channels)						)

            # Test output_attentions=True
																	if self.has_attentions:
																							snake_case_ :List[Any]						=			backbone(**snake_case						,     output_attentions=snake_case						)
																							self.assertIsNotNone(outputs.attentions						)




'''simple docstring'''



import unittest

from transformers import is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device


if is_torch_available():
      import torch

      from transformers import AutoModelForImageClassification

if is_vision_available():
      from transformers import AutoImageProcessor





@require_torch
@require_vision
class    UpperCAmelCase_  (unittest.TestCase  ):





    """simple docstring"""






    @slow
    def       lowercase_				(							self	)				->     List[str]:
         __lowerCamelCase   :	Any								=		AutoImageProcessor.from_pretrained('microsoft/dit-base-finetuned-rvlcdip'	)
         __lowerCamelCase   :	Tuple								=		AutoModelForImageClassification.from_pretrained('microsoft/dit-base-finetuned-rvlcdip'	)
         model.to(SCREAMING_SNAKE_CASE_	)

         from datasets import load_dataset

         __lowerCamelCase   :	str								=		load_dataset('nielsr/rvlcdip-demo'	)

         __lowerCamelCase   :	List[Any]								=		dataset['train'][0]['image'].convert('RGB'	)

         __lowerCamelCase   :	str								=		image_processor(SCREAMING_SNAKE_CASE_			,     return_tensors='pt'	).to(SCREAMING_SNAKE_CASE_	)

         # forward pass
         with torch.no_grad():
              __lowerCamelCase   :	str								=		model(**SCREAMING_SNAKE_CASE_	)
              __lowerCamelCase   :	int								=		outputs.logits

         __lowerCamelCase   :	List[Any]								=		torch.Size((1, 16)	)
         self.assertEqual(logits.shape			,     SCREAMING_SNAKE_CASE_	)

         __lowerCamelCase   :	Optional[Any]								=		torch.tensor(
             [-0.4_1_5_8, -0.4_0_9_2, -0.4_3_4_7]			,     device=SCREAMING_SNAKE_CASE_			,     dtype=torch.float			,     )
         self.assertTrue(torch.allclose(logits[0, :3]			,     SCREAMING_SNAKE_CASE_			,     atol=1E-4	)	)






