






import gc
import random
import unittest

import numpy as np
import torch
from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel

from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline
from diffusers.pipelines.shap_e import ShapERenderer
from diffusers.utils import floats_tensor, load_image, load_numpy, slow
from diffusers.utils.testing_utils import require_torch_gpu, torch_device

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference




class 				__A     (			a      ,     unittest.TestCase ):





				"""simple docstring"""







				UpperCamelCase__ :      str			 =ShapEImgaImgPipeline
				UpperCamelCase__ :      Optional[int]			 =["""image"""]
				UpperCamelCase__ :      Dict			 =["""image"""]
				UpperCamelCase__ :      Optional[int]			 =[
				    """num_images_per_prompt""",
				    """num_inference_steps""",
				    """generator""",
				    """latents""",
				    """guidance_scale""",
				    """frame_size""",
				    """output_type""",
				    """return_dict""",
				]
				UpperCamelCase__ :      int			 =False


				@property
				def       __lowercase							( self    ):




									"""simple docstring"""

									return 32


				@property
				def       __lowercase							( self    ):




									"""simple docstring"""

									return 32


				@property
				def       __lowercase							( self    ):




									"""simple docstring"""

									return self.time_input_dim * 4


				@property
				def       __lowercase							( self    ):




									"""simple docstring"""

									return 8


				@property
				def       __lowercase							( self    ):




									"""simple docstring"""

									torch.manual_seed(0    )
									__UpperCamelCase      :					Optional[int]       		=CLIPVisionConfig(
									    hidden_size=self.text_embedder_hidden_size							,  image_size=64							,  projection_dim=self.text_embedder_hidden_size							,  intermediate_size=37							,  num_attention_heads=4							,  num_channels=3							,  num_hidden_layers=5							,  patch_size=1							,  )

									__UpperCamelCase      :					List[Any]       		=CLIPVisionModel(lowerCamelCase__    )
									return model


				@property
				def       __lowercase							( self    ):




									"""simple docstring"""

									__UpperCamelCase      :					List[Any]       		=CLIPImageProcessor(
									    crop_size=224							,  do_center_crop=lowerCamelCase__							,  do_normalize=lowerCamelCase__							,  do_resize=lowerCamelCase__							,  image_mean=[0.48_145_466, 0.4_578_275, 0.40_821_073]							,  image_std=[0.26_862_954, 0.26_130_258, 0.27_577_711]							,  resample=3							,  size=224							,  )

									return image_processor


				@property
				def       __lowercase							( self    ):




									"""simple docstring"""

									torch.manual_seed(0    )

									__UpperCamelCase      :					Tuple       		={
									    'num_attention_heads': 2,
									    'attention_head_dim': 16,
									    'embedding_dim': self.time_input_dim,
									    'num_embeddings': 32,
									    'embedding_proj_dim': self.text_embedder_hidden_size,
									    'time_embed_dim': self.time_embed_dim,
									    'num_layers': 1,
									    'clip_embed_dim': self.time_input_dim * 2,
									    'additional_embeddings': 0,
									    'time_embed_act_fn': 'gelu',
									    'norm_in_type': 'layer',
									    'embedding_proj_norm_type': 'layer',
									    'encoder_hid_proj_type': None,
									    'added_emb_type': None,
									}

									__UpperCamelCase      :					Tuple       		=PriorTransformer(**lowerCamelCase__    )
									return model


				@property
				def       __lowercase							( self    ):




									"""simple docstring"""

									torch.manual_seed(0    )

									__UpperCamelCase      :					Dict       		={
									    'param_shapes': (
									        (self.renderer_dim, 93),
									        (self.renderer_dim, 8),
									        (self.renderer_dim, 8),
									        (self.renderer_dim, 8),
									    ),
									    'd_latent': self.time_input_dim,
									    'd_hidden': self.renderer_dim,
									    'n_output': 12,
									    'background': (
									        0.1,
									        0.1,
									        0.1,
									    ),
									}
									__UpperCamelCase      :					List[Any]       		=ShapERenderer(**lowerCamelCase__    )
									return model


				def       __lowercase							( self    ):




									"""simple docstring"""

									__UpperCamelCase      :					Any       		=self.dummy_prior
									__UpperCamelCase      :					Optional[int]       		=self.dummy_image_encoder
									__UpperCamelCase      :					Dict       		=self.dummy_image_processor
									__UpperCamelCase      :					List[str]       		=self.dummy_renderer

									__UpperCamelCase      :					Union[str, Any]       		=HeunDiscreteScheduler(
									    beta_schedule='exp'							,  num_train_timesteps=1024							,  prediction_type='sample'							,  use_karras_sigmas=lowerCamelCase__							,  clip_sample=lowerCamelCase__							,  clip_sample_range=1.0							,  )
									__UpperCamelCase      :					List[Any]       		={
									    'prior': prior,
									    'image_encoder': image_encoder,
									    'image_processor': image_processor,
									    'renderer': renderer,
									    'scheduler': scheduler,
									}

									return components


				def       __lowercase							( self							,  lowerCamelCase__							,  lowerCamelCase__=0    ):




									"""simple docstring"""

									__UpperCamelCase      :					Optional[Any]       		=floats_tensor((1, 3, 64, 64)							,  rng=random.Random(lowerCamelCase__    )    ).to(lowerCamelCase__    )

									if str(lowerCamelCase__    ).startswith('mps'    ):
														__UpperCamelCase      :					Optional[Any]       		=torch.manual_seed(lowerCamelCase__    )
									else:
														__UpperCamelCase      :					Union[str, Any]       		=torch.Generator(device=lowerCamelCase__    ).manual_seed(lowerCamelCase__    )
									__UpperCamelCase      :					Optional[int]       		={
									    'image': input_image,
									    'generator': generator,
									    'num_inference_steps': 1,
									    'frame_size': 32,
									    'output_type': 'np',
									}
									return inputs


				def       __lowercase							( self    ):




									"""simple docstring"""

									__UpperCamelCase      :					Union[str, Any]       		='cpu'

									__UpperCamelCase      :					Any       		=self.get_dummy_components()

									__UpperCamelCase      :					Union[str, Any]       		=self.pipeline_class(**lowerCamelCase__    )
									__UpperCamelCase      :					List[str]       		=pipe.to(lowerCamelCase__    )

									pipe.set_progress_bar_config(disable=lowerCamelCase__    )

									__UpperCamelCase      :					Tuple       		=pipe(**self.get_dummy_inputs(lowerCamelCase__    )    )
									__UpperCamelCase      :					Any       		=output.images[0]
									__UpperCamelCase      :					Union[str, Any]       		=image[0, -3:, -3:, -1]

									assert image.shape == (20, 32, 32, 3)

									__UpperCamelCase      :					Optional[int]       		=np.array(
									    [
									        0.00_039_216,
									        0.00_039_216,
									        0.00_039_216,
									        0.00_039_216,
									        0.00_039_216,
									        0.00_039_216,
									        0.00_039_216,
									        0.00_039_216,
									        0.00_039_216,
									    ]    )

									assert np.abs(image_slice.flatten() - expected_slice    ).max() < 1E-2


				def       __lowercase							( self    ):




									"""simple docstring"""

									self._test_inference_batch_consistent(batch_sizes=[1, 2]    )


				def       __lowercase							( self    ):




									"""simple docstring"""

									__UpperCamelCase      :					Tuple       		=torch_device == 'cpu'
									__UpperCamelCase      :					Tuple       		=True
									self._test_inference_batch_single_identical(
									    batch_size=2							,  test_max_difference=lowerCamelCase__							,  relax_max_difference=lowerCamelCase__							,  )







				def       __lowercase							( self    ):




									"""simple docstring"""

									__UpperCamelCase      :					Dict       		=self.get_dummy_components()
									__UpperCamelCase      :					Dict       		=self.pipeline_class(**lowerCamelCase__    )
									__UpperCamelCase      :					Dict       		=pipe.to(lowerCamelCase__    )
									pipe.set_progress_bar_config(disable=lowerCamelCase__    )

									__UpperCamelCase      :					Any       		=1
									__UpperCamelCase      :					Optional[Any]       		=2

									__UpperCamelCase      :					List[str]       		=self.get_dummy_inputs(lowerCamelCase__    )

									for key in inputs.keys():
														if key in self.batch_params:
																			__UpperCamelCase      :					Any       		=batch_size * [inputs[key]]

									__UpperCamelCase      :					Union[str, Any]       		=pipe(**lowerCamelCase__							,  num_images_per_prompt=lowerCamelCase__    )[0]

									assert images.shape[0] == batch_size * num_images_per_prompt




@slow
@require_torch_gpu
class 				__A     (			unittest.TestCase ):





				"""simple docstring"""







				def       __lowercase							( self    ):




									"""simple docstring"""

									super().tearDown()
									gc.collect()
									torch.cuda.empty_cache()







				def       __lowercase							( self    ):




									"""simple docstring"""

									__UpperCamelCase      :					Optional[Any]       		=load_image(
									    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/corgi.png'    )
									__UpperCamelCase      :					Optional[Any]       		=load_numpy(
									    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
									    '/shap_e/test_shap_e_img2img_out.npy'    )
									__UpperCamelCase      :					List[str]       		=ShapEImgaImgPipeline.from_pretrained('openai/shap-e-img2img'    )
									__UpperCamelCase      :					Any       		=pipe.to(lowerCamelCase__    )
									pipe.set_progress_bar_config(disable=lowerCamelCase__    )

									__UpperCamelCase      :					Optional[Any]       		=torch.Generator(device=lowerCamelCase__    ).manual_seed(0    )

									__UpperCamelCase      :					Union[str, Any]       		=pipe(
									    lowerCamelCase__							,  generator=lowerCamelCase__							,  guidance_scale=3.0							,  num_inference_steps=64							,  frame_size=64							,  output_type='np'							,  ).images[0]

									assert images.shape == (20, 64, 64, 3)

									assert_mean_pixel_difference(lowerCamelCase__							,  lowerCamelCase__    )



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[int]			,							UpperCamelCase__			: Tuple			,							UpperCamelCase__			: Tuple=13			,							UpperCamelCase__			: Optional[Any]=32			,							UpperCamelCase__			: Dict=2			,							UpperCamelCase__			: Dict=3			,							UpperCamelCase__			: Union[str, Any]=16			,							UpperCamelCase__			: Any=[1, 2, 1]			,							UpperCamelCase__			: int=[2, 2, 4]			,							UpperCamelCase__			: int=2			,							UpperCamelCase__			: Optional[int]=2.0			,							UpperCamelCase__			: Optional[int]=True			,							UpperCamelCase__			: Any=0.0			,							UpperCamelCase__			: str=0.0			,							UpperCamelCase__			: Optional[Any]=0.1			,							UpperCamelCase__			: Tuple="gelu"			,							UpperCamelCase__			: Optional[Any]=False			,							UpperCamelCase__			: Any=True			,							UpperCamelCase__			: List[str]=0.02			,							UpperCamelCase__			: Union[str, Any]=1E-5			,							UpperCamelCase__			: str=True			,							UpperCamelCase__			: List[str]=None			,							UpperCamelCase__			: Union[str, Any]=True			,							UpperCamelCase__			: Tuple=10			,							UpperCamelCase__			: Dict=8			,							UpperCamelCase__			: Tuple=["stage1", "stage2", "stage3"]			,							UpperCamelCase__			: Tuple=[1, 2, 3]			,							)			->	Dict:







    """simple docstring"""






    __magic_name__				     =       parent
    __magic_name__				     =       batch_size
    __magic_name__				     =       image_size
    __magic_name__				     =       patch_size
    __magic_name__				     =       num_channels
    __magic_name__				     =       embed_dim
    __magic_name__				     =       depths
    __magic_name__				     =       num_heads
    __magic_name__				     =       window_size
    __magic_name__				     =       mlp_ratio
    __magic_name__				     =       qkv_bias
    __magic_name__				     =       hidden_dropout_prob
    __magic_name__				     =       attention_probs_dropout_prob
    __magic_name__				     =       drop_path_rate
    __magic_name__				     =       hidden_act
    __magic_name__				     =       use_absolute_embeddings
    __magic_name__				     =       patch_norm
    __magic_name__				     =       layer_norm_eps
    __magic_name__				     =       initializer_range
    __magic_name__				     =       is_training
    __magic_name__				     =       scope
    __magic_name__				     =       use_labels
    __magic_name__				     =       type_sequence_label_size
    __magic_name__				     =       encoder_stride
    __magic_name__				     =       out_features
    __magic_name__				     =       out_indices
  def 							_lowercase							( self			: str    )			->	Optional[int]:







    """simple docstring"""






    __magic_name__				     =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

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

    __magic_name__				     =       self.get_config()

    return config, pixel_values, labels
  def 							_lowercase							( self			: Tuple    )			->	str:







    """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 							_lowercase							( self			: Optional[int]			,							UpperCamelCase__			: Tuple			,							UpperCamelCase__			: Optional[int]			,							UpperCamelCase__			: Optional[int]    )			->	List[str]:







    """simple docstring"""






    __magic_name__				     =       MaskFormerSwinModel(config=UpperCamelCase__    )
    model.to(UpperCamelCase__    )
    model.eval()
    __magic_name__				     =       model(UpperCamelCase__    )

    __magic_name__				     =       ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths    ) - 1))
    __magic_name__				     =       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 							_lowercase							( self			: List[str]			,							UpperCamelCase__			: Tuple			,							UpperCamelCase__			: Optional[Any]			,							UpperCamelCase__			: List[str]    )			->	Tuple:







    """simple docstring"""






    __magic_name__				     =       MaskFormerSwinBackbone(config=UpperCamelCase__    )
    model.to(UpperCamelCase__    )
    model.eval()
    __magic_name__				     =       model(UpperCamelCase__    )

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





  def 							_lowercase							( self			: Any    )			->	Any:







    """simple docstring"""






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







@require_torch
class        UpperCAmelCase_			( _A  ,       _A  ,       unittest.TestCase     ):


  '''simple docstring'''







  a__           =		(
      (
          MaskFormerSwinModel,
          MaskFormerSwinBackbone,
      )
      if is_torch_available()
      else ()
  )
  a__           =		{"""feature-extraction""": MaskFormerSwinModel} if is_torch_available() else {}
  a__           =		False
  a__           =		False
  a__           =		False
  a__           =		False
  a__           =		False
  def 							_lowercase							( self			: Any    )			->	List[str]:







    """simple docstring"""






    __magic_name__				     =       MaskFormerSwinModelTester(self    )
    __magic_name__				     =       ConfigTester(self			,							config_class=UpperCamelCase__			,							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 							_lowercase							( self			: List[str]    )			->	Optional[int]:







    """simple docstring"""






    pass
  def 							_lowercase							( self			: str    )			->	Dict:







    """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 							_lowercase							( self			: Optional[int]    )			->	List[str]:







    """simple docstring"""






    return
  def 							_lowercase							( self			: str    )			->	str:







    """simple docstring"""






    __magic_name__				     =       self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*UpperCamelCase__    )
  def 							_lowercase							( self			: int    )			->	Optional[Any]:







    """simple docstring"""






    __magic_name__				     =       self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_backbone(*UpperCamelCase__    )
  @unittest.skip("""Swin does not use inputs_embeds"""    )
  def 							_lowercase							( self			: Any    )			->	int:







    """simple docstring"""






    pass
  @unittest.skip("""Swin does not support feedforward chunking"""    )
  def 							_lowercase							( self			: str    )			->	List[Any]:







    """simple docstring"""






    pass
  def 							_lowercase							( self			: Union[str, Any]    )			->	Dict:







    """simple docstring"""






    __magic_name__     ,    __magic_name__				     =       self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
      __magic_name__				     =       model_class(UpperCamelCase__    )
      self.assertIsInstance(model.get_input_embeddings()			,							(nn.Module)    )
      __magic_name__				     =       model.get_output_embeddings()
      self.assertTrue(x is None or isinstance(UpperCamelCase__			,							nn.Linear    )    )
  def 							_lowercase							( self			: Tuple    )			->	Dict:







    """simple docstring"""






    __magic_name__     ,    __magic_name__				     =       self.model_tester.prepare_config_and_inputs_for_common()

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

      __magic_name__				     =       ["""pixel_values"""]
      self.assertListEqual(arg_names[:1]			,							UpperCamelCase__    )
  @unittest.skip(reason="""MaskFormerSwin is only used as backbone and doesn't support output_attentions"""    )
  def 							_lowercase							( self			: Tuple    )			->	int:







    """simple docstring"""






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







    """simple docstring"""






    pass
  def 							_lowercase							( self			: Union[str, Any]			,							UpperCamelCase__			: List[Any]			,							UpperCamelCase__			: Any			,							UpperCamelCase__			: Optional[Any]			,							UpperCamelCase__			: Union[str, Any]    )			->	Any:







    """simple docstring"""






    __magic_name__				     =       model_class(UpperCamelCase__    )
    model.to(UpperCamelCase__    )
    model.eval()

    with torch.no_grad():
      __magic_name__				     =       model(**self._prepare_for_class(UpperCamelCase__			,							UpperCamelCase__    )    )

    __magic_name__				     =       outputs.hidden_states

    __magic_name__				     =       getattr(
        self.model_tester			,							"""expected_num_hidden_layers"""			,							len(self.model_tester.depths    ) + 1    )
    self.assertEqual(len(UpperCamelCase__    )			,							UpperCamelCase__    )

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

    __magic_name__				     =       (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 							_lowercase							( self			: Dict    )			->	Dict:







    """simple docstring"""






    __magic_name__     ,    __magic_name__				     =       self.model_tester.prepare_config_and_inputs_for_common()

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

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

      self.check_hidden_states_output(UpperCamelCase__			,							UpperCamelCase__			,							UpperCamelCase__			,							UpperCamelCase__    )
  def 							_lowercase							( self			: Optional[Any]    )			->	Union[str, Any]:







    """simple docstring"""






    __magic_name__     ,    __magic_name__				     =       self.model_tester.prepare_config_and_inputs_for_common()
    __magic_name__				     =       3

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

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

    for model_class in self.all_model_classes:
      __magic_name__				     =       True
      self.check_hidden_states_output(UpperCamelCase__			,							UpperCamelCase__			,							UpperCamelCase__			,							(padded_height, padded_width)    )

      # check that output_hidden_states also work using config
      del inputs_dict["output_hidden_states"]
      __magic_name__				     =       True
      self.check_hidden_states_output(UpperCamelCase__			,							UpperCamelCase__			,							UpperCamelCase__			,							(padded_height, padded_width)    )
  @unittest.skip(reason="""MaskFormerSwin doesn't have pretrained checkpoints"""    )
  def 							_lowercase							( self			: Optional[int]    )			->	int:







    """simple docstring"""






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







    """simple docstring"""






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







    """simple docstring"""






    pass





  def 							_lowercase							( self			: Dict    )			->	Any:







    """simple docstring"""






    __magic_name__     ,    __magic_name__				     =       self.model_tester.prepare_config_and_inputs_for_common()

    def set_nan_tensor_to_zero(UpperCamelCase__			: Union[str, Any]    ):
      __magic_name__				     =       0
      return t

    def check_equivalence(UpperCamelCase__			: str			,							UpperCamelCase__			: Dict			,							UpperCamelCase__			: Optional[Any]			,							UpperCamelCase__			: int={}    ):
      with torch.no_grad():
        __magic_name__				     =       model(**UpperCamelCase__			,							return_dict=UpperCamelCase__			,							**UpperCamelCase__    )
        __magic_name__				     =       model(**UpperCamelCase__			,							return_dict=UpperCamelCase__			,							**UpperCamelCase__    ).to_tuple()

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

        recursive_check(UpperCamelCase__			,							UpperCamelCase__    )

    for model_class in self.all_model_classes:
      __magic_name__				     =       model_class(UpperCamelCase__    )
      model.to(UpperCamelCase__    )
      model.eval()

      __magic_name__				     =       self._prepare_for_class(UpperCamelCase__			,							UpperCamelCase__    )
      __magic_name__				     =       self._prepare_for_class(UpperCamelCase__			,							UpperCamelCase__    )
      check_equivalence(UpperCamelCase__			,							UpperCamelCase__			,							UpperCamelCase__    )

      __magic_name__				     =       self._prepare_for_class(UpperCamelCase__			,							UpperCamelCase__			,							return_labels=UpperCamelCase__    )
      __magic_name__				     =       self._prepare_for_class(UpperCamelCase__			,							UpperCamelCase__			,							return_labels=UpperCamelCase__    )
      check_equivalence(UpperCamelCase__			,							UpperCamelCase__			,							UpperCamelCase__    )

      __magic_name__				     =       self._prepare_for_class(UpperCamelCase__			,							UpperCamelCase__    )
      __magic_name__				     =       self._prepare_for_class(UpperCamelCase__			,							UpperCamelCase__    )
      check_equivalence(UpperCamelCase__			,							UpperCamelCase__			,							UpperCamelCase__			,							{"""output_hidden_states""": True}    )

      __magic_name__				     =       self._prepare_for_class(UpperCamelCase__			,							UpperCamelCase__			,							return_labels=UpperCamelCase__    )
      __magic_name__				     =       self._prepare_for_class(UpperCamelCase__			,							UpperCamelCase__			,							return_labels=UpperCamelCase__    )
      check_equivalence(UpperCamelCase__			,							UpperCamelCase__			,							UpperCamelCase__			,							{"""output_hidden_states""": True}    )







@require_torch
class        UpperCAmelCase_			( unittest.TestCase  ,       _A     ):


  '''simple docstring'''







  a__           =		(MaskFormerSwinBackbone,) if is_torch_available() else ()
  a__           =		MaskFormerSwinConfig
  def 							_lowercase							( self			: Union[str, Any]    )			->	List[Any]:







    """simple docstring"""






    __magic_name__				     =       MaskFormerSwinModelTester(self    )





  def 							_lowercase							( self			: List[str]    )			->	Optional[Any]:







    """simple docstring"""






    __magic_name__     ,    __magic_name__				     =       self.model_tester.prepare_config_and_inputs_for_common()
    __magic_name__				     =       inputs_dict["""pixel_values"""].shape[0]

    for backbone_class in self.all_model_classes:
      __magic_name__				     =       backbone_class(UpperCamelCase__    )
      backbone.to(UpperCamelCase__    )
      backbone.eval()

      __magic_name__				     =       backbone(**UpperCamelCase__    )

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

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

