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




	'''simple docstring'''





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






	def     UpperCamelCase_  (	self :			Any			):
					__A             =			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

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

					__A             =			self.get_config()

					return config, pixel_values, labels






	def     UpperCamelCase_  (	self :			List[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     UpperCamelCase_  (	self :			Optional[int]							,A :			Optional[Any]							,A :			int							,A :			Tuple			):
					__A             =			MaskFormerSwinModel(config=_A			)
					model.to(_A			)
					model.eval()
					__A             =			model(_A			)

					__A             =			((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths			) - 1))
					__A             =			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     UpperCamelCase_  (	self :			Union[str, Any]							,A :			List[str]							,A :			int							,A :			Any			):
					__A             =			MaskFormerSwinBackbone(config=_A			)
					model.to(_A			)
					model.eval()
					__A             =			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			):
									__A             =			['stem']
									__A             =			MaskFormerSwinBackbone(config=_A			)







	def     UpperCamelCase_  (	self :			Tuple			):
					__A             =			self.prepare_config_and_inputs()
					__A             =			config_and_inputs
					__A             =			{'pixel_values': pixel_values}
					return config, inputs_dict





@require_torch
class 							UpperCAmelCase				(  snake_case_      ,      snake_case_      ,      unittest.TestCase  ):




	'''simple docstring'''





	snake_case_    =					(
	    (
	        MaskFormerSwinModel,
	        MaskFormerSwinBackbone,
	    )
	    if is_torch_available()
	    else ()
	)
	snake_case_    =					{"feature-extraction": MaskFormerSwinModel} if is_torch_available() else {}
	snake_case_    =					False
	snake_case_    =					False
	snake_case_    =					False
	snake_case_    =					False
	snake_case_    =					False






	def     UpperCamelCase_  (	self :			Union[str, Any]			):
					__A             =			MaskFormerSwinModelTester(self			)
					__A             =			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     UpperCamelCase_  (	self :			str			):
					pass






	def     UpperCamelCase_  (	self :			List[Any]			):
					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     UpperCamelCase_  (	self :			Dict			):
					return






	def     UpperCamelCase_  (	self :			Any			):
					__A             =			self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*_A			)






	def     UpperCamelCase_  (	self :			Optional[Any]			):
					__A             =			self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_backbone(*_A			)






	@unittest.skip("Swin does not use inputs_embeds"			)
	def     UpperCamelCase_  (	self :			str			):
					pass






	@unittest.skip("Swin does not support feedforward chunking"			)
	def     UpperCamelCase_  (	self :			Union[str, Any]			):
					pass






	def     UpperCamelCase_  (	self :			Tuple			):
					__A             =			self.model_tester.prepare_config_and_inputs_for_common()

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






	def     UpperCamelCase_  (	self :			Optional[Any]			):
					__A             =			self.model_tester.prepare_config_and_inputs_for_common()

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

									__A             =			['pixel_values']
									self.assertListEqual(arg_names[:1]							,_A			)






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






	@unittest.skip(reason="MaskFormerSwin is only used as an internal backbone"			)
	def     UpperCamelCase_  (	self :			List[str]			):
					pass






	def     UpperCamelCase_  (	self :			Tuple							,A :			Optional[Any]							,A :			int							,A :			Tuple							,A :			List[str]			):
					__A             =			model_class(_A			)
					model.to(_A			)
					model.eval()

					with torch.no_grad():
									__A             =			model(**self._prepare_for_class(_A							,_A			)			)

					__A             =			outputs.hidden_states

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

					__A             =			(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     UpperCamelCase_  (	self :			Optional[Any]			):
					__A             =			self.model_tester.prepare_config_and_inputs_for_common()

					__A             =			(
					    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:
									__A             =			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"]
									__A             =			True

									self.check_hidden_states_output(_A							,_A							,_A							,_A			)






	def     UpperCamelCase_  (	self :			str			):
					__A             =			self.model_tester.prepare_config_and_inputs_for_common()
					__A             =			3

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

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

					for model_class in self.all_model_classes:
									__A             =			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"]
									__A             =			True
									self.check_hidden_states_output(_A							,_A							,_A							,(padded_height, padded_width)			)






	@unittest.skip(reason="MaskFormerSwin doesn\'t have pretrained checkpoints"			)
	def     UpperCamelCase_  (	self :			Optional[Any]			):
					pass






	@unittest.skip(reason="This will be fixed once MaskFormerSwin is replaced by native Swin"			)
	def     UpperCamelCase_  (	self :			Optional[Any]			):
					pass






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







	def     UpperCamelCase_  (	self :			Union[str, Any]			):
					__A             =			self.model_tester.prepare_config_and_inputs_for_common()

					def set_nan_tensor_to_zero(A :			Tuple			):
									__A             =			0
									return t

					def check_equivalence(A :			Tuple							,A :			int							,A :			Tuple							,A :			List[str]={}			):
									with torch.no_grad():
													__A             =			model(**_A							,return_dict=_A							,**_A			)
													__A             =			model(**_A							,return_dict=_A							,**_A			).to_tuple()

													def recursive_check(A :			Optional[Any]							,A :			str			):
																	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:
									__A             =			model_class(_A			)
									model.to(_A			)
									model.eval()

									__A             =			self._prepare_for_class(_A							,_A			)
									__A             =			self._prepare_for_class(_A							,_A			)
									check_equivalence(_A							,_A							,_A			)

									__A             =			self._prepare_for_class(_A							,_A							,return_labels=_A			)
									__A             =			self._prepare_for_class(_A							,_A							,return_labels=_A			)
									check_equivalence(_A							,_A							,_A			)

									__A             =			self._prepare_for_class(_A							,_A			)
									__A             =			self._prepare_for_class(_A							,_A			)
									check_equivalence(_A							,_A							,_A							,{"output_hidden_states": True}			)

									__A             =			self._prepare_for_class(_A							,_A							,return_labels=_A			)
									__A             =			self._prepare_for_class(_A							,_A							,return_labels=_A			)
									check_equivalence(_A							,_A							,_A							,{"output_hidden_states": True}			)





@require_torch
class 							UpperCAmelCase				(  unittest.TestCase      ,      snake_case_  ):




	'''simple docstring'''





	snake_case_    =					(MaskFormerSwinBackbone,) if is_torch_available() else ()
	snake_case_    =					MaskFormerSwinConfig






	def     UpperCamelCase_  (	self :			int			):
					__A             =			MaskFormerSwinModelTester(self			)







	def     UpperCamelCase_  (	self :			Any			):
					__A             =			self.model_tester.prepare_config_and_inputs_for_common()
					__A             =			inputs_dict['pixel_values'].shape[0]

					for backbone_class in self.all_model_classes:
									__A             =			backbone_class(_A			)
									backbone.to(_A			)
									backbone.eval()

									__A             =			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
									__A             =			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)
																	__A             =			hidden_state.shape
																	self.assertTrue((h_batch_size, h_n_channels)							,(batch_size, n_channels)			)

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


# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from packaging import version

from .. import __version__
from .constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD
from .doc import (
    add_code_sample_docstrings,
    add_end_docstrings,
    add_start_docstrings,
    add_start_docstrings_to_model_forward,
    copy_func,
    replace_return_docstrings,
)
from .generic import (
    ContextManagers,
    ExplicitEnum,
    ModelOutput,
    PaddingStrategy,
    TensorType,
    add_model_info_to_auto_map,
    cached_property,
    can_return_loss,
    expand_dims,
    find_labels,
    flatten_dict,
    infer_framework,
    is_jax_tensor,
    is_numpy_array,
    is_tensor,
    is_tf_symbolic_tensor,
    is_tf_tensor,
    is_torch_device,
    is_torch_dtype,
    is_torch_tensor,
    reshape,
    squeeze,
    strtobool,
    tensor_size,
    to_numpy,
    to_py_obj,
    transpose,
    working_or_temp_dir,
)
from .hub import (
    CLOUDFRONT_DISTRIB_PREFIX,
    DISABLE_TELEMETRY,
    HF_MODULES_CACHE,
    HUGGINGFACE_CO_PREFIX,
    HUGGINGFACE_CO_RESOLVE_ENDPOINT,
    PYTORCH_PRETRAINED_BERT_CACHE,
    PYTORCH_TRANSFORMERS_CACHE,
    S3_BUCKET_PREFIX,
    TRANSFORMERS_CACHE,
    TRANSFORMERS_DYNAMIC_MODULE_NAME,
    EntryNotFoundError,
    PushToHubMixin,
    RepositoryNotFoundError,
    RevisionNotFoundError,
    cached_file,
    default_cache_path,
    define_sagemaker_information,
    download_url,
    extract_commit_hash,
    get_cached_models,
    get_file_from_repo,
    get_full_repo_name,
    has_file,
    http_user_agent,
    is_offline_mode,
    is_remote_url,
    move_cache,
    send_example_telemetry,
    try_to_load_from_cache,
)
from .import_utils import (
    ENV_VARS_TRUE_AND_AUTO_VALUES,
    ENV_VARS_TRUE_VALUES,
    TORCH_FX_REQUIRED_VERSION,
    USE_JAX,
    USE_TF,
    USE_TORCH,
    DummyObject,
    OptionalDependencyNotAvailable,
    _LazyModule,
    ccl_version,
    direct_transformers_import,
    get_torch_version,
    is_accelerate_available,
    is_apex_available,
    is_bitsandbytes_available,
    is_bsa_available,
    is_coloredlogs_available,
    is_cython_available,
    is_datasets_available,
    is_decord_available,
    is_detectrona_available,
    is_faiss_available,
    is_flax_available,
    is_ftfy_available,
    is_in_notebook,
    is_ipex_available,
    is_jieba_available,
    is_jumanpp_available,
    is_kenlm_available,
    is_keras_nlp_available,
    is_librosa_available,
    is_natten_available,
    is_ninja_available,
    is_onnx_available,
    is_openai_available,
    is_optimum_available,
    is_pandas_available,
    is_peft_available,
    is_phonemizer_available,
    is_protobuf_available,
    is_psutil_available,
    is_pyanvml_available,
    is_pyctcdecode_available,
    is_pytesseract_available,
    is_pytest_available,
    is_pytorch_quantization_available,
    is_rjieba_available,
    is_sacremoses_available,
    is_safetensors_available,
    is_sagemaker_dp_enabled,
    is_sagemaker_mp_enabled,
    is_scipy_available,
    is_sentencepiece_available,
    is_seqio_available,
    is_sklearn_available,
    is_soundfile_availble,
    is_spacy_available,
    is_speech_available,
    is_sudachi_available,
    is_tensorflow_probability_available,
    is_tensorflow_text_available,
    is_tfaonnx_available,
    is_tf_available,
    is_timm_available,
    is_tokenizers_available,
    is_torch_available,
    is_torch_bfaa_available,
    is_torch_bfaa_cpu_available,
    is_torch_bfaa_gpu_available,
    is_torch_compile_available,
    is_torch_cuda_available,
    is_torch_fx_available,
    is_torch_fx_proxy,
    is_torch_mps_available,
    is_torch_neuroncore_available,
    is_torch_tensorrt_fx_available,
    is_torch_tfaa_available,
    is_torch_tpu_available,
    is_torchaudio_available,
    is_torchdistx_available,
    is_torchdynamo_available,
    is_torchvision_available,
    is_training_run_on_sagemaker,
    is_vision_available,
    requires_backends,
    torch_only_method,
)


SCREAMING_SNAKE_CASE							:Tuple										=    'pytorch_model.bin'
SCREAMING_SNAKE_CASE							:str										=    'pytorch_model.bin.index.json'
SCREAMING_SNAKE_CASE							:int										=    'adapter_config.json'
SCREAMING_SNAKE_CASE							:List[str]										=    'adapter_model.bin'
SCREAMING_SNAKE_CASE							:Any										=    'adapter_model.safetensors'
SCREAMING_SNAKE_CASE							:int										=    'tf_model.h5'
SCREAMING_SNAKE_CASE							:Tuple										=    'tf_model.h5.index.json'
SCREAMING_SNAKE_CASE							:List[Any]										=    'model.ckpt'
SCREAMING_SNAKE_CASE							:Optional[int]										=    'flax_model.msgpack'
SCREAMING_SNAKE_CASE							:List[Any]										=    'flax_model.msgpack.index.json'
SCREAMING_SNAKE_CASE							:List[Any]										=    'model.safetensors'
SCREAMING_SNAKE_CASE							:Any										=    'model.safetensors.index.json'
SCREAMING_SNAKE_CASE							:int										=    'config.json'
SCREAMING_SNAKE_CASE							:List[str]										=    'preprocessor_config.json'
SCREAMING_SNAKE_CASE							:Optional[int]										=    FEATURE_EXTRACTOR_NAME
SCREAMING_SNAKE_CASE							:Optional[Any]										=    'generation_config.json'
SCREAMING_SNAKE_CASE							:Dict										=    'modelcard.json'

SCREAMING_SNAKE_CASE							:Optional[Any]										=    '▁'
SCREAMING_SNAKE_CASE							:Any										=    SENTENCEPIECE_UNDERLINE  # Kept for backward compatibility

SCREAMING_SNAKE_CASE							:Tuple										=    [
    [[0, 1, 0, 1], [1, 0, 0, 1]]
] * 2  # Needs to have 0s and 1s only since XLM uses it for langs too.
SCREAMING_SNAKE_CASE							:Union[str, Any]										=    [[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]]
SCREAMING_SNAKE_CASE							:Tuple										=    [[1, 1, 1, 1, 1], [1, 1, 1, 0, 0], [0, 0, 0, 1, 1]]


def 						UpperCAmelCase      (     a_						)		->     List[str]:







				"""simple docstring"""



				if version.parse(a_						) < version.parse(a_						):
								if "dev" in min_version:
												__A             =			(
												    "This example requires a source install from HuggingFace Transformers (see "
												    "`https://huggingface.co/docs/transformers/installation#install-from-source`),"
												)
								else:
												__A             =			F'''This example requires a minimum version of {min_version},'''
								error_message += F''' but the version found is {__version__}.\n'''
								raise ImportError(
								    error_message
								    + "Check out https://github.com/huggingface/transformers/tree/main/examples#important-note for the examples corresponding to other "
								    "versions of HuggingFace Transformers."						)
