'''simple docstring'''

from scipy.stats import pearsonr

import datasets


UpperCamelCase__     :	Union[str, Any]				=			'\nPearson correlation coefficient and p-value for testing non-correlation.\nThe Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.\nThe p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.\n'


UpperCamelCase__     :	str				=			'\nArgs:\n    predictions (`list` of `int`): Predicted class labels, as returned by a model.\n    references (`list` of `int`): Ground truth labels.\n    return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.\n\nReturns:\n    pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation.\n    p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities.\n\nExamples:\n\n    Example 1-A simple example using only predictions and references.\n        >>> pearsonr_metric = datasets.load_metric("pearsonr")\n        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])\n        >>> print(round(results[\'pearsonr\'], 2))\n        -0.74\n\n    Example 2-The same as Example 1, but that also returns the `p-value`.\n        >>> pearsonr_metric = datasets.load_metric("pearsonr")\n        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)\n        >>> print(sorted(list(results.keys())))\n        [\'p-value\', \'pearsonr\']\n        >>> print(round(results[\'pearsonr\'], 2))\n        -0.74\n        >>> print(round(results[\'p-value\'], 2))\n        0.15\n'


UpperCamelCase__     :	int				=			'\n@article{2020SciPy-NMeth,\nauthor  = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and\n      Haberland, Matt and Reddy, Tyler and Cournapeau, David and\n      Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and\n      Bright, Jonathan and {van der Walt}, St{\'e}fan J. and\n      Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and\n      Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and\n      Kern, Robert and Larson, Eric and Carey, C J and\n      Polat, Ilhan and Feng, Yu and Moore, Eric W. and\n      {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and\n      Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and\n      Harris, Charles R. and Archibald, Anne M. and\n      Ribeiro, Antonio H. and Pedregosa, Fabian and\n      {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},\ntitle   = {{{SciPy} 1.0: Fundamental Algorithms for Scientific\n      Computing in Python}},\njournal = {Nature Methods},\nyear    = {2020},\nvolume  = {17},\npages   = {261--272},\nadsurl  = {https://rdcu.be/b08Wh},\ndoi = {10.1038/s41592-019-0686-2},\n}\n'


@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION		,_KWARGS_DESCRIPTION   )
class 				_lowercase	(      datasets.Metric   ):
      '''simple docstring'''


      def 		lowerCAmelCase__					(				self							)			->			str:



         '''simple docstring'''



         return datasets.MetricInfo(
             description=_DESCRIPTION					,citation=_CITATION					,inputs_description=_KWARGS_DESCRIPTION					,features=datasets.Features(
                 {
                     '''predictions''': datasets.Value('''float'''							),
                     '''references''': datasets.Value('''float'''							),
                 }							)					,reference_urls=['''https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html''']					,)




      def 		lowerCAmelCase__					(				self					,lowerCamelCase_					,lowerCamelCase_					,lowerCamelCase_=False							)			->			Union[str, Any]:



         '''simple docstring'''



         if return_pvalue:
            UpperCAmelCase__							:				Optional[int]   				=  pearsonr(lowerCamelCase_					,lowerCamelCase_							)
            return {"pearsonr": results[0], "p-value": results[1]}
         else:
            return {"pearsonr": float(pearsonr(lowerCamelCase_					,lowerCamelCase_							)[0]							)}





'''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 				_lowercase	:
      '''simple docstring'''


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



         '''simple docstring'''



         UpperCAmelCase__							:				Optional[Any]   				=  parent
         UpperCAmelCase__							:				Optional[Any]   				=  batch_size
         UpperCAmelCase__							:				Tuple   				=  image_size
         UpperCAmelCase__							:				Tuple   				=  patch_size
         UpperCAmelCase__							:				int   				=  num_channels
         UpperCAmelCase__							:				str   				=  embed_dim
         UpperCAmelCase__							:				List[str]   				=  depths
         UpperCAmelCase__							:				List[Any]   				=  num_heads
         UpperCAmelCase__							:				Optional[Any]   				=  window_size
         UpperCAmelCase__							:				Tuple   				=  mlp_ratio
         UpperCAmelCase__							:				List[str]   				=  qkv_bias
         UpperCAmelCase__							:				List[str]   				=  hidden_dropout_prob
         UpperCAmelCase__							:				str   				=  attention_probs_dropout_prob
         UpperCAmelCase__							:				Any   				=  drop_path_rate
         UpperCAmelCase__							:				List[Any]   				=  hidden_act
         UpperCAmelCase__							:				Optional[int]   				=  use_absolute_embeddings
         UpperCAmelCase__							:				int   				=  patch_norm
         UpperCAmelCase__							:				Dict   				=  layer_norm_eps
         UpperCAmelCase__							:				Tuple   				=  initializer_range
         UpperCAmelCase__							:				Optional[int]   				=  is_training
         UpperCAmelCase__							:				List[Any]   				=  scope
         UpperCAmelCase__							:				Any   				=  use_labels
         UpperCAmelCase__							:				Any   				=  type_sequence_label_size
         UpperCAmelCase__							:				Any   				=  encoder_stride
         UpperCAmelCase__							:				Optional[int]   				=  out_features
         UpperCAmelCase__							:				Optional[Any]   				=  out_indices




      def 		lowerCAmelCase__					(				self							)			->			str:



         '''simple docstring'''



         UpperCAmelCase__							:				List[str]   				=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

         UpperCAmelCase__							:				Any   				=  None
         if self.use_labels:
            UpperCAmelCase__							:				List[str]   				=  ids_tensor([self.batch_size]					,self.type_sequence_label_size							)

         UpperCAmelCase__							:				Tuple   				=  self.get_config()

         return config, pixel_values, labels




      def 		lowerCAmelCase__					(				self							)			->			Optional[int]:



         '''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					,lowerCamelCase_					,lowerCamelCase_					,lowerCamelCase_							)			->			List[str]:



         '''simple docstring'''



         UpperCAmelCase__							:				Union[str, Any]   				=  MaskFormerSwinModel(config=lowerCamelCase_							)
         model.to(lowerCamelCase_							)
         model.eval()
         UpperCAmelCase__							:				Union[str, Any]   				=  model(lowerCamelCase_							)

         UpperCAmelCase__							:				Any   				=  ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths							) - 1))
         UpperCAmelCase__							:				Optional[int]   				=  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					,lowerCamelCase_					,lowerCamelCase_					,lowerCamelCase_							)			->			Union[str, Any]:



         '''simple docstring'''



         UpperCAmelCase__							:				Union[str, Any]   				=  MaskFormerSwinBackbone(config=lowerCamelCase_							)
         model.to(lowerCamelCase_							)
         model.eval()
         UpperCAmelCase__							:				Optional[Any]   				=  model(lowerCamelCase_							)

         # 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(lowerCamelCase_							):
            UpperCAmelCase__							:				List[Any]   				=  ['''stem''']
            UpperCAmelCase__							:				int   				=  MaskFormerSwinBackbone(config=lowerCamelCase_							)




      def 		lowerCAmelCase__					(				self							)			->			Tuple:



         '''simple docstring'''



         UpperCAmelCase__							:				List[Any]   				=  self.prepare_config_and_inputs()
         UpperCAmelCase__				,      UpperCAmelCase__				,      UpperCAmelCase__							:				List[Any]   				=  config_and_inputs
         UpperCAmelCase__							:				str   				=  {'''pixel_values''': pixel_values}
         return config, inputs_dict




@require_torch
class 				_lowercase	(      lowerCAmelCase		,lowerCAmelCase		,unittest.TestCase   ):
      '''simple docstring'''


      UpperCAmelCase_      :      str      							=   (
          (
              MaskFormerSwinModel,
              MaskFormerSwinBackbone,
          )
          if is_torch_available()
          else ()
      )
      UpperCAmelCase_      :      Union[str, Any]      							=   {'''feature-extraction''': MaskFormerSwinModel} if is_torch_available() else {}
      UpperCAmelCase_      :      Optional[Any]      							=   False
      UpperCAmelCase_      :      Any      							=   False
      UpperCAmelCase_      :      str      							=   False
      UpperCAmelCase_      :      Union[str, Any]      							=   False
      UpperCAmelCase_      :      List[str]      							=   False




      def 		lowerCAmelCase__					(				self							)			->			Any:



         '''simple docstring'''



         UpperCAmelCase__							:				Tuple   				=  MaskFormerSwinModelTester(self							)
         UpperCAmelCase__							:				List[str]   				=  ConfigTester(self					,config_class=lowerCamelCase_					,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							)			->			int:



         '''simple docstring'''



         pass




      def 		lowerCAmelCase__					(				self							)			->			str:



         '''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							)			->			List[Any]:



         '''simple docstring'''



         return




      def 		lowerCAmelCase__					(				self							)			->			Optional[int]:



         '''simple docstring'''



         UpperCAmelCase__							:				Optional[Any]   				=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*lowerCamelCase_							)




      def 		lowerCAmelCase__					(				self							)			->			Optional[Any]:



         '''simple docstring'''



         UpperCAmelCase__							:				Optional[Any]   				=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_backbone(*lowerCamelCase_							)




      @unittest.skip('''Swin does not use inputs_embeds'''							)
      def 		lowerCAmelCase__					(				self							)			->			int:



         '''simple docstring'''



         pass




      @unittest.skip('''Swin does not support feedforward chunking'''							)
      def 		lowerCAmelCase__					(				self							)			->			Any:



         '''simple docstring'''



         pass




      def 		lowerCAmelCase__					(				self							)			->			Any:



         '''simple docstring'''



         UpperCAmelCase__				,      UpperCAmelCase__							:				Optional[Any]   				=  self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
            UpperCAmelCase__							:				Optional[int]   				=  model_class(lowerCamelCase_							)
            self.assertIsInstance(model.get_input_embeddings()					,(nn.Module)							)
            UpperCAmelCase__							:				int   				=  model.get_output_embeddings()
            self.assertTrue(x is None or isinstance(lowerCamelCase_					,nn.Linear							)							)




      def 		lowerCAmelCase__					(				self							)			->			str:



         '''simple docstring'''



         UpperCAmelCase__				,      UpperCAmelCase__							:				Union[str, Any]   				=  self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
            UpperCAmelCase__							:				List[Any]   				=  model_class(lowerCamelCase_							)
            UpperCAmelCase__							:				Optional[Any]   				=  inspect.signature(model.forward							)
            # signature.parameters is an OrderedDict => so arg_names order is deterministic
            UpperCAmelCase__							:				Dict   				=  [*signature.parameters.keys()]

            UpperCAmelCase__							:				Optional[int]   				=  ['''pixel_values''']
            self.assertListEqual(arg_names[:1]					,lowerCamelCase_							)




      @unittest.skip(reason='''MaskFormerSwin is only used as backbone and doesn\'t support output_attentions'''							)
      def 		lowerCAmelCase__					(				self							)			->			Any:



         '''simple docstring'''



         pass




      @unittest.skip(reason='''MaskFormerSwin is only used as an internal backbone'''							)
      def 		lowerCAmelCase__					(				self							)			->			str:



         '''simple docstring'''



         pass




      def 		lowerCAmelCase__					(				self					,lowerCamelCase_					,lowerCamelCase_					,lowerCamelCase_					,lowerCamelCase_							)			->			Optional[int]:



         '''simple docstring'''



         UpperCAmelCase__							:				str   				=  model_class(lowerCamelCase_							)
         model.to(lowerCamelCase_							)
         model.eval()

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

         UpperCAmelCase__							:				Optional[int]   				=  outputs.hidden_states

         UpperCAmelCase__							:				Union[str, Any]   				=  getattr(
             self.model_tester					,'''expected_num_hidden_layers'''					,len(self.model_tester.depths							) + 1							)
         self.assertEqual(len(lowerCamelCase_							)					,lowerCamelCase_							)

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

         UpperCAmelCase__							:				Union[str, Any]   				=  (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							)			->			Dict:



         '''simple docstring'''



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

         UpperCAmelCase__							:				Optional[int]   				=  (
             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:
            UpperCAmelCase__							:				Tuple   				=  True
            self.check_hidden_states_output(lowerCamelCase_					,lowerCamelCase_					,lowerCamelCase_					,lowerCamelCase_							)

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

            self.check_hidden_states_output(lowerCamelCase_					,lowerCamelCase_					,lowerCamelCase_					,lowerCamelCase_							)




      def 		lowerCAmelCase__					(				self							)			->			str:



         '''simple docstring'''



         UpperCAmelCase__				,      UpperCAmelCase__							:				Optional[Any]   				=  self.model_tester.prepare_config_and_inputs_for_common()
         UpperCAmelCase__							:				List[Any]   				=  3

         UpperCAmelCase__							:				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)
         )
         UpperCAmelCase__							:				Optional[Any]   				=  (
             config.patch_size
             if isinstance(config.patch_size					,collections.abc.Iterable							)
             else (config.patch_size, config.patch_size)
         )

         UpperCAmelCase__							:				List[Any]   				=  image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
         UpperCAmelCase__							:				Optional[int]   				=  image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

         for model_class in self.all_model_classes:
            UpperCAmelCase__							:				Optional[int]   				=  True
            self.check_hidden_states_output(lowerCamelCase_					,lowerCamelCase_					,lowerCamelCase_					,(padded_height, padded_width)							)

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




      @unittest.skip(reason='''MaskFormerSwin doesn\'t have pretrained checkpoints'''							)
      def 		lowerCAmelCase__					(				self							)			->			Any:



         '''simple docstring'''



         pass




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



         '''simple docstring'''



         pass




      @unittest.skip(reason='''This will be fixed once MaskFormerSwin is replaced by native Swin'''							)
      def 		lowerCAmelCase__					(				self							)			->			Any:



         '''simple docstring'''



         pass




      def 		lowerCAmelCase__					(				self							)			->			int:



         '''simple docstring'''



         UpperCAmelCase__				,      UpperCAmelCase__							:				Optional[int]   				=  self.model_tester.prepare_config_and_inputs_for_common()

         def set_nan_tensor_to_zero(lowerCamelCase_							):
            UpperCAmelCase__							:				int   				=  0
            return t

         def check_equivalence(lowerCamelCase_					,lowerCamelCase_					,lowerCamelCase_					,lowerCamelCase_={}							):
            with torch.no_grad():
               UpperCAmelCase__							:				Any   				=  model(**lowerCamelCase_					,return_dict=lowerCamelCase_					,**lowerCamelCase_							)
               UpperCAmelCase__							:				Optional[int]   				=  model(**lowerCamelCase_					,return_dict=lowerCamelCase_					,**lowerCamelCase_							).to_tuple()

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

               recursive_check(lowerCamelCase_					,lowerCamelCase_							)

         for model_class in self.all_model_classes:
            UpperCAmelCase__							:				List[str]   				=  model_class(lowerCamelCase_							)
            model.to(lowerCamelCase_							)
            model.eval()

            UpperCAmelCase__							:				Optional[int]   				=  self._prepare_for_class(lowerCamelCase_					,lowerCamelCase_							)
            UpperCAmelCase__							:				Any   				=  self._prepare_for_class(lowerCamelCase_					,lowerCamelCase_							)
            check_equivalence(lowerCamelCase_					,lowerCamelCase_					,lowerCamelCase_							)

            UpperCAmelCase__							:				List[str]   				=  self._prepare_for_class(lowerCamelCase_					,lowerCamelCase_					,return_labels=lowerCamelCase_							)
            UpperCAmelCase__							:				Tuple   				=  self._prepare_for_class(lowerCamelCase_					,lowerCamelCase_					,return_labels=lowerCamelCase_							)
            check_equivalence(lowerCamelCase_					,lowerCamelCase_					,lowerCamelCase_							)

            UpperCAmelCase__							:				int   				=  self._prepare_for_class(lowerCamelCase_					,lowerCamelCase_							)
            UpperCAmelCase__							:				Optional[Any]   				=  self._prepare_for_class(lowerCamelCase_					,lowerCamelCase_							)
            check_equivalence(lowerCamelCase_					,lowerCamelCase_					,lowerCamelCase_					,{'''output_hidden_states''': True}							)

            UpperCAmelCase__							:				List[Any]   				=  self._prepare_for_class(lowerCamelCase_					,lowerCamelCase_					,return_labels=lowerCamelCase_							)
            UpperCAmelCase__							:				List[str]   				=  self._prepare_for_class(lowerCamelCase_					,lowerCamelCase_					,return_labels=lowerCamelCase_							)
            check_equivalence(lowerCamelCase_					,lowerCamelCase_					,lowerCamelCase_					,{'''output_hidden_states''': True}							)




@require_torch
class 				_lowercase	(      unittest.TestCase		,lowerCAmelCase   ):
      '''simple docstring'''


      UpperCAmelCase_      :      Dict      							=   (MaskFormerSwinBackbone,) if is_torch_available() else ()
      UpperCAmelCase_      :      Optional[int]      							=   MaskFormerSwinConfig




      def 		lowerCAmelCase__					(				self							)			->			Dict:



         '''simple docstring'''



         UpperCAmelCase__							:				Tuple   				=  MaskFormerSwinModelTester(self							)




      def 		lowerCAmelCase__					(				self							)			->			Tuple:



         '''simple docstring'''



         UpperCAmelCase__				,      UpperCAmelCase__							:				str   				=  self.model_tester.prepare_config_and_inputs_for_common()
         UpperCAmelCase__							:				List[str]   				=  inputs_dict['''pixel_values'''].shape[0]

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

            UpperCAmelCase__							:				List[Any]   				=  backbone(**lowerCamelCase_							)

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

            # Test output_attentions=True
            if self.has_attentions:
               UpperCAmelCase__							:				List[str]   				=  backbone(**lowerCamelCase_					,output_attentions=lowerCamelCase_							)
               self.assertIsNotNone(outputs.attentions							)




