'''simple docstring'''

import torch

from diffusers import DDPMScheduler

from .test_schedulers import SchedulerCommonTest


class 				_lowercase	(      lowerCAmelCase   ):
      '''simple docstring'''


      UpperCAmelCase_      :      List[str]      							=   (DDPMScheduler,)




      def 		lowerCAmelCase__					(				self					,**lowerCamelCase_							)			->			Any:



         '''simple docstring'''



         UpperCAmelCase__							:				List[str]   				=  {
             '''num_train_timesteps''': 1000,
             '''beta_start''': 0.0001,
             '''beta_end''': 0.02,
             '''beta_schedule''': '''linear''',
             '''variance_type''': '''fixed_small''',
             '''clip_sample''': True,
         }

         config.update(**lowerCamelCase_							)
         return config




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



         '''simple docstring'''



         for timesteps in [1, 5, 100, 1000]:
            self.check_over_configs(num_train_timesteps=lowerCamelCase_							)




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



         '''simple docstring'''



         for beta_start, beta_end in zip([0.0001, 0.001, 0.01, 0.1]					,[0.002, 0.02, 0.2, 2]							):
            self.check_over_configs(beta_start=lowerCamelCase_					,beta_end=lowerCamelCase_							)




      def 		lowerCAmelCase__					(				self							)			->			List[str]:



         '''simple docstring'''



         for schedule in ["linear", "squaredcos_cap_v2"]:
            self.check_over_configs(beta_schedule=lowerCamelCase_							)




      def 		lowerCAmelCase__					(				self							)			->			str:



         '''simple docstring'''



         for variance in ["fixed_small", "fixed_large", "other"]:
            self.check_over_configs(variance_type=lowerCamelCase_							)




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



         '''simple docstring'''



         for clip_sample in [True, False]:
            self.check_over_configs(clip_sample=lowerCamelCase_							)




      def 		lowerCAmelCase__					(				self							)			->			str:



         '''simple docstring'''



         self.check_over_configs(thresholding=lowerCamelCase_							)
         for threshold in [0.5, 1.0, 2.0]:
            for prediction_type in ["epsilon", "sample", "v_prediction"]:
               self.check_over_configs(
                   thresholding=lowerCamelCase_					,prediction_type=lowerCamelCase_					,sample_max_value=lowerCamelCase_					,)




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



         '''simple docstring'''



         for prediction_type in ["epsilon", "sample", "v_prediction"]:
            self.check_over_configs(prediction_type=lowerCamelCase_							)




      def 		lowerCAmelCase__					(				self							)			->			int:



         '''simple docstring'''



         for t in [0, 500, 999]:
            self.check_over_forward(time_step=lowerCamelCase_							)




      def 		lowerCAmelCase__					(				self							)			->			str:



         '''simple docstring'''



         UpperCAmelCase__							:				List[Any]   				=  self.scheduler_classes[0]
         UpperCAmelCase__							:				Any   				=  self.get_scheduler_config()
         UpperCAmelCase__							:				Dict   				=  scheduler_class(**lowerCamelCase_							)

         assert torch.sum(torch.abs(scheduler._get_variance(0							) - 0.0							)							) < 1e-5
         assert torch.sum(torch.abs(scheduler._get_variance(487							) - 0.0_0979							)							) < 1e-5
         assert torch.sum(torch.abs(scheduler._get_variance(999							) - 0.02							)							) < 1e-5




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



         '''simple docstring'''



         UpperCAmelCase__							:				Optional[int]   				=  self.scheduler_classes[0]
         UpperCAmelCase__							:				Union[str, Any]   				=  self.get_scheduler_config()
         UpperCAmelCase__							:				Optional[int]   				=  scheduler_class(**lowerCamelCase_							)

         UpperCAmelCase__							:				Union[str, Any]   				=  len(lowerCamelCase_							)

         UpperCAmelCase__							:				Any   				=  self.dummy_model()
         UpperCAmelCase__							:				Tuple   				=  self.dummy_sample_deter
         UpperCAmelCase__							:				Any   				=  torch.manual_seed(0							)

         for t in reversed(range(lowerCamelCase_							)							):
            # 1. predict noise residual
            UpperCAmelCase__							:				Tuple   				=  model(lowerCamelCase_					,lowerCamelCase_							)

            # 2. predict previous mean of sample x_t-1
            UpperCAmelCase__							:				Optional[int]   				=  scheduler.step(lowerCamelCase_					,lowerCamelCase_					,lowerCamelCase_					,generator=lowerCamelCase_							).prev_sample

            # if t > 0:
            #     noise = self.dummy_sample_deter
            #     variance = scheduler.get_variance(t) ** (0.5) * noise
            #
            # sample = pred_prev_sample + variance
            UpperCAmelCase__							:				int   				=  pred_prev_sample

         UpperCAmelCase__							:				Dict   				=  torch.sum(torch.abs(lowerCamelCase_							)							)
         UpperCAmelCase__							:				Union[str, Any]   				=  torch.mean(torch.abs(lowerCamelCase_							)							)

         assert abs(result_sum.item() - 258.9606							) < 1e-2
         assert abs(result_mean.item() - 0.3372							) < 1e-3




      def 		lowerCAmelCase__					(				self							)			->			Dict:



         '''simple docstring'''



         UpperCAmelCase__							:				str   				=  self.scheduler_classes[0]
         UpperCAmelCase__							:				List[str]   				=  self.get_scheduler_config(prediction_type='''v_prediction'''							)
         UpperCAmelCase__							:				str   				=  scheduler_class(**lowerCamelCase_							)

         UpperCAmelCase__							:				Optional[int]   				=  len(lowerCamelCase_							)

         UpperCAmelCase__							:				List[str]   				=  self.dummy_model()
         UpperCAmelCase__							:				List[Any]   				=  self.dummy_sample_deter
         UpperCAmelCase__							:				int   				=  torch.manual_seed(0							)

         for t in reversed(range(lowerCamelCase_							)							):
            # 1. predict noise residual
            UpperCAmelCase__							:				Any   				=  model(lowerCamelCase_					,lowerCamelCase_							)

            # 2. predict previous mean of sample x_t-1
            UpperCAmelCase__							:				Tuple   				=  scheduler.step(lowerCamelCase_					,lowerCamelCase_					,lowerCamelCase_					,generator=lowerCamelCase_							).prev_sample

            # if t > 0:
            #     noise = self.dummy_sample_deter
            #     variance = scheduler.get_variance(t) ** (0.5) * noise
            #
            # sample = pred_prev_sample + variance
            UpperCAmelCase__							:				List[str]   				=  pred_prev_sample

         UpperCAmelCase__							:				Dict   				=  torch.sum(torch.abs(lowerCamelCase_							)							)
         UpperCAmelCase__							:				Union[str, Any]   				=  torch.mean(torch.abs(lowerCamelCase_							)							)

         assert abs(result_sum.item() - 202.0296							) < 1e-2
         assert abs(result_mean.item() - 0.2631							) < 1e-3




      def 		lowerCAmelCase__					(				self							)			->			int:



         '''simple docstring'''



         UpperCAmelCase__							:				Dict   				=  self.scheduler_classes[0]
         UpperCAmelCase__							:				Tuple   				=  self.get_scheduler_config()
         UpperCAmelCase__							:				Any   				=  scheduler_class(**lowerCamelCase_							)

         UpperCAmelCase__							:				Optional[Any]   				=  [100, 87, 50, 1, 0]

         scheduler.set_timesteps(timesteps=lowerCamelCase_							)

         UpperCAmelCase__							:				List[str]   				=  scheduler.timesteps

         for i, timestep in enumerate(lowerCamelCase_							):
            if i == len(lowerCamelCase_							) - 1:
               UpperCAmelCase__							:				List[str]   				=  -1
            else:
               UpperCAmelCase__							:				Any   				=  timesteps[i + 1]

            UpperCAmelCase__							:				Tuple   				=  scheduler.previous_timestep(lowerCamelCase_							)
            UpperCAmelCase__							:				Optional[Any]   				=  prev_t.item()

            self.assertEqual(lowerCamelCase_					,lowerCamelCase_							)




      def 		lowerCAmelCase__					(				self							)			->			str:



         '''simple docstring'''



         UpperCAmelCase__							:				Any   				=  self.scheduler_classes[0]
         UpperCAmelCase__							:				int   				=  self.get_scheduler_config()
         UpperCAmelCase__							:				int   				=  scheduler_class(**lowerCamelCase_							)

         UpperCAmelCase__							:				List[str]   				=  [100, 87, 50, 51, 0]

         with self.assertRaises(lowerCamelCase_					,msg='''`custom_timesteps` must be in descending order.'''							):
            scheduler.set_timesteps(timesteps=lowerCamelCase_							)




      def 		lowerCAmelCase__					(				self							)			->			str:



         '''simple docstring'''



         UpperCAmelCase__							:				str   				=  self.scheduler_classes[0]
         UpperCAmelCase__							:				Dict   				=  self.get_scheduler_config()
         UpperCAmelCase__							:				Optional[Any]   				=  scheduler_class(**lowerCamelCase_							)

         UpperCAmelCase__							:				List[str]   				=  [100, 87, 50, 1, 0]
         UpperCAmelCase__							:				str   				=  len(lowerCamelCase_							)

         with self.assertRaises(lowerCamelCase_					,msg='''Can only pass one of `num_inference_steps` or `custom_timesteps`.'''							):
            scheduler.set_timesteps(num_inference_steps=lowerCamelCase_					,timesteps=lowerCamelCase_							)




      def 		lowerCAmelCase__					(				self							)			->			List[str]:



         '''simple docstring'''



         UpperCAmelCase__							:				Any   				=  self.scheduler_classes[0]
         UpperCAmelCase__							:				Any   				=  self.get_scheduler_config()
         UpperCAmelCase__							:				int   				=  scheduler_class(**lowerCamelCase_							)

         UpperCAmelCase__							:				Union[str, Any]   				=  [scheduler.config.num_train_timesteps]

         with self.assertRaises(
             lowerCamelCase_					,msg='''`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}'''					,):
            scheduler.set_timesteps(timesteps=lowerCamelCase_							)





'''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							)




