


import dataclasses
import json
import sys
import types
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError
from copy import copy
from enum import Enum
from inspect import isclass
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optional, Tuple, Union, get_type_hints

import yaml


A				:       Optional[Any]      =  NewType('DataClass', Any)
A				:       int      =  NewType('DataClassType', Any)





def 						_lowerCAmelCase							(     _lowerCAmelCase			)    ->						Optional[int]:


						'''simple docstring'''






						if isinstance(snake_case__   ,						snake_case__			):
												return v
						if v.lower() in ("yes", "true", "t", "y", "1"):
												return True
						elif v.lower() in ("no", "false", "f", "n", "0"):
												return False
						else:
												raise ArgumentTypeError(
												    F'''Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive).'''			)





def 						_lowerCAmelCase							(     _lowerCAmelCase			)    ->						Callable[[str], Any]:


						'''simple docstring'''






						__snake_case				=		{str(snake_case__			): choice for choice in choices}
						return lambda _lowerCAmelCase			: str_to_choice.get(snake_case__   ,						snake_case__			)





def 						_lowerCAmelCase							(     *,
    _lowerCAmelCase = None   ,						_lowerCAmelCase = None   ,						_lowerCAmelCase = dataclasses.MISSING   ,						_lowerCAmelCase = dataclasses.MISSING   ,						_lowerCAmelCase = None   ,						**_lowerCAmelCase   ,						)    ->						dataclasses.Field:


						'''simple docstring'''






						if metadata is None:
												# Important, don't use as default param in function signature because dict is mutable and shared across function calls
												__snake_case				=		{}
						if aliases is not None:
												__snake_case				=		aliases
						if help is not None:
												__snake_case				=		help

						return dataclasses.field(metadata=snake_case__   ,						default=snake_case__   ,						default_factory=snake_case__   ,						**snake_case__			)






class      UpperCamelCase(	UpperCAmelCase__ ):
					snake_case_		:					Optional[int]    					=						42


					def __init__(    self						:		List[str]  ,     SCREAMING_SNAKE_CASE						:		List[str]  ,     **SCREAMING_SNAKE_CASE						:		Optional[int]    )      ->						Any:




											'''simple docstring'''

											if "formatter_class" not in kwargs:
																	__snake_case				=		ArgumentDefaultsHelpFormatter
											super().__init__(**_a    )
											if dataclasses.is_dataclass(_a    ):
																	__snake_case				=		[dataclass_types]
											__snake_case				=		list(_a    )
											for dtype in self.dataclass_types:
																	self._add_dataclass_arguments(_a    )


					@staticmethod
					def 				SCREAMING_SNAKE_CASE_	(    SCREAMING_SNAKE_CASE						:		str  ,     SCREAMING_SNAKE_CASE						:		Optional[Any]    )      ->						Union[str, Any]:




											'''simple docstring'''

											__snake_case				=		f'''--{field.name}'''
											__snake_case				=		field.metadata.copy()
											# field.metadata is not used at all by Data Classes,
											# it is provided as a third-party extension mechanism.
											if isinstance(field.type  ,     _a    ):
																	raise RuntimeError(
																	    "Unresolved type detected, which should have been done with the help of "
																	    "`typing.get_type_hints` method by default"    )

											__snake_case				=		kwargs.pop("aliases"  ,     []    )
											if isinstance(_a  ,     _a    ):
																	__snake_case				=		[aliases]

											__snake_case				=		getattr(field.type  ,     "__origin__"  ,     field.type    )
											if origin_type is Union or (hasattr(_a  ,     "UnionType"    ) and isinstance(_a  ,     types.UnionType    )):
																	if str not in field.type.__args__ and (
																	    len(field.type.__args__    ) != 2 or type(_a    ) not in field.type.__args__
																	):
																							raise ValueError(
																							    "Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because"
																							    " the argument parser only supports one type per argument."
																							    f''' Problem encountered in field \'{field.name}\'.'''    )
																	if type(_a    ) not in field.type.__args__:
																							# filter `str` in Union
																							__snake_case				=		field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1]
																							__snake_case				=		getattr(field.type  ,     "__origin__"  ,     field.type    )
																	elif bool not in field.type.__args__:
																							# filter `NoneType` in Union (except for `Union[bool, NoneType]`)
																							__snake_case				=		(
																							    field.type.__args__[0] if isinstance(_a  ,     field.type.__args__[1]    ) else field.type.__args__[1]
																							)
																							__snake_case				=		getattr(field.type  ,     "__origin__"  ,     field.type    )

        # A variable to store kwargs for a boolean field, if needed
        # so that we can init a `no_*` complement argument (see below)
											__snake_case				=		{}
											if origin_type is Literal or (isinstance(field.type  ,     _a    ) and issubclass(field.type  ,     _a    )):
																	if origin_type is Literal:
																							__snake_case				=		field.type.__args__
																	else:
																							__snake_case				=		[x.value for x in field.type]

																	__snake_case				=		make_choice_type_function(kwargs["choices"]    )

																	if field.default is not dataclasses.MISSING:
																							__snake_case				=		field.default
																	else:
																							__snake_case				=		True
											elif field.type is bool or field.type == Optional[bool]:
																	# Copy the currect kwargs to use to instantiate a `no_*` complement argument below.
																	# We do not initialize it here because the `no_*` alternative must be instantiated after the real argument
																	__snake_case				=		copy(_a    )

																	# Hack because type=bool in argparse does not behave as we want.
																	__snake_case				=		string_to_bool
																	if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING):
																							# Default value is False if we have no default when of type bool.
																							__snake_case				=		False if field.default is dataclasses.MISSING else field.default
																							# This is the value that will get picked if we don't include --field_name in any way
																							__snake_case				=		default
																							# This tells argparse we accept 0 or 1 value after --field_name
																							__snake_case				=		"?"
																							# This is the value that will get picked if we do --field_name (without value)
																							__snake_case				=		True
											elif isclass(_a    ) and issubclass(_a  ,     _a    ):
																	__snake_case				=		field.type.__args__[0]
																	__snake_case				=		"+"
																	if field.default_factory is not dataclasses.MISSING:
																							__snake_case				=		field.default_factory()
																	elif field.default is dataclasses.MISSING:
																							__snake_case				=		True
											else:
																	__snake_case				=		field.type
																	if field.default is not dataclasses.MISSING:
																							__snake_case				=		field.default
																	elif field.default_factory is not dataclasses.MISSING:
																							__snake_case				=		field.default_factory()
																	else:
																							__snake_case				=		True
											parser.add_argument(_a  ,     *_a  ,     **_a    )

											# Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added.
											# Order is important for arguments with the same destination!
											# We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down
											# here and we do not need those changes/additional keys.
											if field.default is True and (field.type is bool or field.type == Optional[bool]):
																	__snake_case				=		False
																	parser.add_argument(f'''--no_{field.name}'''  ,     action="store_false"  ,     dest=field.name  ,     **_a    )


					def 				SCREAMING_SNAKE_CASE_	(    self						:		Union[str, Any]  ,     SCREAMING_SNAKE_CASE						:		Optional[int]    )      ->						Tuple:




											'''simple docstring'''

											if hasattr(_a  ,     "_argument_group_name"    ):
																	__snake_case				=		self.add_argument_group(dtype._argument_group_name    )
											else:
																	__snake_case				=		self

											try:
																	__snake_case				=		get_type_hints(_a    )
											except NameError:
																	raise RuntimeError(
																	    f'''Type resolution failed for {dtype}. Try declaring the class in global scope or '''
																	    "removing line of `from __future__ import annotations` which opts in Postponed "
																	    "Evaluation of Annotations (PEP 563)"    )
											except TypeError as ex:
																	# Remove this block when we drop Python 3.9 support
																	if sys.version_info[:2] < (3, 1_0) and "unsupported operand type(s) for |" in str(_a    ):
																							__snake_case				=		".".join(map(_a  ,     sys.version_info[:3]    )    )
																							raise RuntimeError(
																							    f'''Type resolution failed for {dtype} on Python {python_version}. Try removing '''
																							    "line of `from __future__ import annotations` which opts in union types as "
																							    "`X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To "
																							    "support Python versions that lower than 3.10, you need to use "
																							    "`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of "
																							    "`X | None`."    ) from ex
																	raise

											for field in dataclasses.fields(_a    ):
																	if not field.init:
																							continue
																	__snake_case				=		type_hints[field.name]
																	self._parse_dataclass_field(_a  ,     _a    )


					def 				SCREAMING_SNAKE_CASE_	(    self						:		List[Any]  ,     SCREAMING_SNAKE_CASE						:		int=None  ,     SCREAMING_SNAKE_CASE						:		Optional[int]=False  ,     SCREAMING_SNAKE_CASE						:		Tuple=True  ,     SCREAMING_SNAKE_CASE						:		Tuple=None  ,     SCREAMING_SNAKE_CASE						:		Dict=None  ,     )      ->						str:




											'''simple docstring'''

											if args_file_flag or args_filename or (look_for_args_file and len(sys.argv    )):
																	__snake_case				=		[]

																	if args_filename:
																							args_files.append(Path(_a    )    )
																	elif look_for_args_file and len(sys.argv    ):
																							args_files.append(Path(sys.argv[0]    ).with_suffix(".args"    )    )

																	# args files specified via command line flag should overwrite default args files so we add them last
																	if args_file_flag:
																							# Create special parser just to extract the args_file_flag values
																							__snake_case				=		ArgumentParser()
																							args_file_parser.add_argument(_a  ,     type=_a  ,     action="append"    )

																							# Use only remaining args for further parsing (remove the args_file_flag)
																							__snake_case		,       __snake_case				=		args_file_parser.parse_known_args(args=_a    )
																							__snake_case				=		vars(_a    ).get(args_file_flag.lstrip("-"    )  ,     _a    )

																							if cmd_args_file_paths:
																													args_files.extend([Path(_a    ) for p in cmd_args_file_paths]    )

																	__snake_case				=		[]
																	for args_file in args_files:
																							if args_file.exists():
																													file_args += args_file.read_text().split()

            # in case of duplicate arguments the last one has precedence
            # args specified via the command line should overwrite args from files, so we add them last
																	__snake_case				=		file_args + args if args is not None else file_args + sys.argv[1:]
											__snake_case		,       __snake_case				=		self.parse_known_args(args=_a    )
											__snake_case				=		[]
											for dtype in self.dataclass_types:
																	__snake_case				=		{f.name for f in dataclasses.fields(_a    ) if f.init}
																	__snake_case				=		{k: v for k, v in vars(_a    ).items() if k in keys}
																	for k in keys:
																							delattr(_a  ,     _a    )
																	__snake_case				=		dtype(**_a    )
																	outputs.append(_a    )
											if len(namespace.__dict__    ) > 0:
																	# additional namespace.
																	outputs.append(_a    )
											if return_remaining_strings:
																	return (*outputs, remaining_args)
											else:
																	if remaining_args:
																							raise ValueError(f'''Some specified arguments are not used by the HfArgumentParser: {remaining_args}'''    )

																	return (*outputs,)


					def 				SCREAMING_SNAKE_CASE_	(    self						:		int  ,     SCREAMING_SNAKE_CASE						:		Dict  ,     SCREAMING_SNAKE_CASE						:		Tuple = False    )      ->						Any:




											'''simple docstring'''

											__snake_case				=		set(args.keys()    )
											__snake_case				=		[]
											for dtype in self.dataclass_types:
																	__snake_case				=		{f.name for f in dataclasses.fields(_a    ) if f.init}
																	__snake_case				=		{k: v for k, v in args.items() if k in keys}
																	unused_keys.difference_update(inputs.keys()    )
																	__snake_case				=		dtype(**_a    )
																	outputs.append(_a    )
											if not allow_extra_keys and unused_keys:
																	raise ValueError(f'''Some keys are not used by the HfArgumentParser: {sorted(_a    )}'''    )
											return tuple(_a    )


					def 				SCREAMING_SNAKE_CASE_	(    self						:		Union[str, Any]  ,     SCREAMING_SNAKE_CASE						:		Tuple  ,     SCREAMING_SNAKE_CASE						:		str = False    )      ->						str:




											'''simple docstring'''

											with open(Path(_a    )  ,     encoding="utf-8"    ) as open_json_file:
																	__snake_case				=		json.loads(open_json_file.read()    )
											__snake_case				=		self.parse_dict(_a  ,     allow_extra_keys=_a    )
											return tuple(_a    )






					def 				SCREAMING_SNAKE_CASE_	(    self						:		Optional[Any]  ,     SCREAMING_SNAKE_CASE						:		Optional[int]  ,     SCREAMING_SNAKE_CASE						:		str = False    )      ->						Any:




											'''simple docstring'''

											__snake_case				=		self.parse_dict(yaml.safe_load(Path(_a    ).read_text()    )  ,     allow_extra_keys=_a    )
											return tuple(_a    )











"""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        __magic_name__				:






				'''simple docstring'''





				def __init__(			self						,					_a						,					_a=13						,					_a=32						,					_a=2						,					_a=3						,					_a=16						,					_a=[1, 2, 1]						,					_a=[2, 2, 4]						,					_a=2						,					_a=2.0						,					_a=True						,					_a=0.0						,					_a=0.0						,					_a=0.1						,					_a="gelu"						,					_a=False						,					_a=True						,					_a=0.02						,					_a=1e-5						,					_a=True						,					_a=None						,					_a=True						,					_a=10						,					_a=8						,					_a=["stage1", "stage2", "stage3"]						,					_a=[1, 2, 3]						,					):





							"""simple docstring"""
							lowerCamelCase      =   parent
							lowerCamelCase      =   batch_size
							lowerCamelCase      =   image_size
							lowerCamelCase      =   patch_size
							lowerCamelCase      =   num_channels
							lowerCamelCase      =   embed_dim
							lowerCamelCase      =   depths
							lowerCamelCase      =   num_heads
							lowerCamelCase      =   window_size
							lowerCamelCase      =   mlp_ratio
							lowerCamelCase      =   qkv_bias
							lowerCamelCase      =   hidden_dropout_prob
							lowerCamelCase      =   attention_probs_dropout_prob
							lowerCamelCase      =   drop_path_rate
							lowerCamelCase      =   hidden_act
							lowerCamelCase      =   use_absolute_embeddings
							lowerCamelCase      =   patch_norm
							lowerCamelCase      =   layer_norm_eps
							lowerCamelCase      =   initializer_range
							lowerCamelCase      =   is_training
							lowerCamelCase      =   scope
							lowerCamelCase      =   use_labels
							lowerCamelCase      =   type_sequence_label_size
							lowerCamelCase      =   encoder_stride
							lowerCamelCase      =   out_features
							lowerCamelCase      =   out_indices





				def   _lowerCAmelCase							(			self					):





							"""simple docstring"""
							lowerCamelCase      =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

							lowerCamelCase      =   None
							if self.use_labels:
										lowerCamelCase      =   ids_tensor([self.batch_size]						,					self.type_sequence_label_size					)

							lowerCamelCase      =   self.get_config()

							return config, pixel_values, labels





				def   _lowerCAmelCase							(			self					):





							"""simple docstring"""
							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						,					_a						,					_a						,					_a					):





							"""simple docstring"""
							lowerCamelCase      =   MaskFormerSwinModel(config=_a					)
							model.to(_a					)
							model.eval()
							lowerCamelCase      =   model(_a					)

							lowerCamelCase      =   ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths					) - 1))
							lowerCamelCase      =   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						,					_a						,					_a						,					_a					):





							"""simple docstring"""
							lowerCamelCase      =   MaskFormerSwinBackbone(config=_a					)
							model.to(_a					)
							model.eval()
							lowerCamelCase      =   model(_a					)

							# 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(_a					):
										lowerCamelCase      =   ["""stem"""]
										lowerCamelCase      =   MaskFormerSwinBackbone(config=_a					)





				def   _lowerCAmelCase							(			self					):





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






@require_torch
class        __magic_name__				(			UpperCAmelCase__		,   UpperCAmelCase__		,   unittest.TestCase							):






				'''simple docstring'''
				__UpperCamelCase         =		(
				    (
				        MaskFormerSwinModel,
				        MaskFormerSwinBackbone,
				    )
				    if is_torch_available()
				    else ()
				)
				__UpperCamelCase         =		{"feature-extraction": MaskFormerSwinModel} if is_torch_available() else {}
				__UpperCamelCase         =		False
				__UpperCamelCase         =		False
				__UpperCamelCase         =		False
				__UpperCamelCase         =		False
				__UpperCamelCase         =		False





				def   _lowerCAmelCase							(			self					):





							"""simple docstring"""
							lowerCamelCase      =   MaskFormerSwinModelTester(self					)
							lowerCamelCase      =   ConfigTester(self						,					config_class=_a						,					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					):





							"""simple docstring"""
							pass





				def   _lowerCAmelCase							(			self					):





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





							"""simple docstring"""
							return





				def   _lowerCAmelCase							(			self					):





							"""simple docstring"""
							lowerCamelCase      =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*_a					)





				def   _lowerCAmelCase							(			self					):





							"""simple docstring"""
							lowerCamelCase      =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_backbone(*_a					)





				@unittest.skip("""Swin does not use inputs_embeds"""					)
				def   _lowerCAmelCase							(			self					):





							"""simple docstring"""
							pass





				@unittest.skip("""Swin does not support feedforward chunking"""					)
				def   _lowerCAmelCase							(			self					):





							"""simple docstring"""
							pass





				def   _lowerCAmelCase							(			self					):





							"""simple docstring"""
							lowerCamelCase ,  lowerCamelCase      =   self.model_tester.prepare_config_and_inputs_for_common()

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





				def   _lowerCAmelCase							(			self					):





							"""simple docstring"""
							lowerCamelCase ,  lowerCamelCase      =   self.model_tester.prepare_config_and_inputs_for_common()

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

										lowerCamelCase      =   ["""pixel_values"""]
										self.assertListEqual(arg_names[:1]						,					_a					)





				@unittest.skip(reason="""MaskFormerSwin is only used as backbone and doesn't support output_attentions"""					)
				def   _lowerCAmelCase							(			self					):





							"""simple docstring"""
							pass





				@unittest.skip(reason="""MaskFormerSwin is only used as an internal backbone"""					)
				def   _lowerCAmelCase							(			self					):





							"""simple docstring"""
							pass





				def   _lowerCAmelCase							(			self						,					_a						,					_a						,					_a						,					_a					):





							"""simple docstring"""
							lowerCamelCase      =   model_class(_a					)
							model.to(_a					)
							model.eval()

							with torch.no_grad():
										lowerCamelCase      =   model(**self._prepare_for_class(_a						,					_a					)					)

							lowerCamelCase      =   outputs.hidden_states

							lowerCamelCase      =   getattr(
							    self.model_tester						,					"""expected_num_hidden_layers"""						,					len(self.model_tester.depths					) + 1					)
							self.assertEqual(len(_a					)						,					_a					)

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

							lowerCamelCase      =   (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					):





							"""simple docstring"""
							lowerCamelCase ,  lowerCamelCase      =   self.model_tester.prepare_config_and_inputs_for_common()

							lowerCamelCase      =   (
							    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:
										lowerCamelCase      =   True
										self.check_hidden_states_output(_a						,					_a						,					_a						,					_a					)

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

										self.check_hidden_states_output(_a						,					_a						,					_a						,					_a					)





				def   _lowerCAmelCase							(			self					):





							"""simple docstring"""
							lowerCamelCase ,  lowerCamelCase      =   self.model_tester.prepare_config_and_inputs_for_common()
							lowerCamelCase      =   3

							lowerCamelCase      =   (
							    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)
							)
							lowerCamelCase      =   (
							    config.patch_size
							    if isinstance(config.patch_size						,					collections.abc.Iterable					)
							    else (config.patch_size, config.patch_size)
							)

							lowerCamelCase      =   image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
							lowerCamelCase      =   image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

							for model_class in self.all_model_classes:
										lowerCamelCase      =   True
										self.check_hidden_states_output(_a						,					_a						,					_a						,					(padded_height, padded_width)					)

										# check that output_hidden_states also work using config
										del inputs_dict["output_hidden_states"]
										lowerCamelCase      =   True
										self.check_hidden_states_output(_a						,					_a						,					_a						,					(padded_height, padded_width)					)





				@unittest.skip(reason="""MaskFormerSwin doesn't have pretrained checkpoints"""					)
				def   _lowerCAmelCase							(			self					):





							"""simple docstring"""
							pass





				@unittest.skip(reason="""This will be fixed once MaskFormerSwin is replaced by native Swin"""					)
				def   _lowerCAmelCase							(			self					):





							"""simple docstring"""
							pass





				@unittest.skip(reason="""This will be fixed once MaskFormerSwin is replaced by native Swin"""					)
				def   _lowerCAmelCase							(			self					):





							"""simple docstring"""
							pass





				def   _lowerCAmelCase							(			self					):





							"""simple docstring"""
							lowerCamelCase ,  lowerCamelCase      =   self.model_tester.prepare_config_and_inputs_for_common()

							def set_nan_tensor_to_zero(_a					):
										lowerCamelCase      =   0
										return t

							def check_equivalence(_a						,					_a						,					_a						,					_a={}					):
										with torch.no_grad():
													lowerCamelCase      =   model(**_a						,					return_dict=_a						,					**_a					)
													lowerCamelCase      =   model(**_a						,					return_dict=_a						,					**_a					).to_tuple()

													def recursive_check(_a						,					_a					):
																if isinstance(_a						,					(List, Tuple)					):
																			for tuple_iterable_value, dict_iterable_value in zip(_a						,					_a					):
																						recursive_check(_a						,					_a					)
																elif isinstance(_a						,					_a					):
																			for tuple_iterable_value, dict_iterable_value in zip(
																			    tuple_object.values()						,					dict_object.values()					):
																						recursive_check(_a						,					_a					)
																elif tuple_object is None:
																			return
																else:
																			self.assertTrue(
																			    torch.allclose(
																			        set_nan_tensor_to_zero(_a					)						,					set_nan_tensor_to_zero(_a					)						,					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(_a					).any()} and `inf`: {torch.isinf(_a					)}. Dict has'
																			        f' `nan`: {torch.isnan(_a					).any()} and `inf`: {torch.isinf(_a					)}.'
																			    )						,					)

													recursive_check(_a						,					_a					)

							for model_class in self.all_model_classes:
										lowerCamelCase      =   model_class(_a					)
										model.to(_a					)
										model.eval()

										lowerCamelCase      =   self._prepare_for_class(_a						,					_a					)
										lowerCamelCase      =   self._prepare_for_class(_a						,					_a					)
										check_equivalence(_a						,					_a						,					_a					)

										lowerCamelCase      =   self._prepare_for_class(_a						,					_a						,					return_labels=_a					)
										lowerCamelCase      =   self._prepare_for_class(_a						,					_a						,					return_labels=_a					)
										check_equivalence(_a						,					_a						,					_a					)

										lowerCamelCase      =   self._prepare_for_class(_a						,					_a					)
										lowerCamelCase      =   self._prepare_for_class(_a						,					_a					)
										check_equivalence(_a						,					_a						,					_a						,					{"""output_hidden_states""": True}					)

										lowerCamelCase      =   self._prepare_for_class(_a						,					_a						,					return_labels=_a					)
										lowerCamelCase      =   self._prepare_for_class(_a						,					_a						,					return_labels=_a					)
										check_equivalence(_a						,					_a						,					_a						,					{"""output_hidden_states""": True}					)






@require_torch
class        __magic_name__				(			unittest.TestCase		,   UpperCAmelCase__							):






				'''simple docstring'''
				__UpperCamelCase         =		(MaskFormerSwinBackbone,) if is_torch_available() else ()
				__UpperCamelCase         =		MaskFormerSwinConfig





				def   _lowerCAmelCase							(			self					):





							"""simple docstring"""
							lowerCamelCase      =   MaskFormerSwinModelTester(self					)





				def   _lowerCAmelCase							(			self					):





							"""simple docstring"""
							lowerCamelCase ,  lowerCamelCase      =   self.model_tester.prepare_config_and_inputs_for_common()
							lowerCamelCase      =   inputs_dict["""pixel_values"""].shape[0]

							for backbone_class in self.all_model_classes:
										lowerCamelCase      =   backbone_class(_a					)
										backbone.to(_a					)
										backbone.eval()

										lowerCamelCase      =   backbone(**_a					)

										# Test default outputs and verify feature maps
										self.assertIsInstance(outputs.feature_maps						,					_a					)
										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
										lowerCamelCase      =   backbone(**_a						,					output_hidden_states=_a					)
										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)
																lowerCamelCase ,  lowerCamelCase ,  lowerCamelCase      =   hidden_state.shape
																self.assertTrue((h_batch_size, h_n_channels)						,					(batch_size, n_channels)					)

            # Test output_attentions=True
										if self.has_attentions:
													lowerCamelCase      =   backbone(**_a						,					output_attentions=_a					)
													self.assertIsNotNone(outputs.attentions					)



