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


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


   '''simple docstring'''




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


 def   lowercase__  (       self):


   '''simple docstring'''




   lowercase__	: Optional[Any]     		=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

   lowercase__	: Any     		=   None
   if self.use_labels:
     lowercase__	: int     		=   ids_tensor([self.batch_size]       ,	self.type_sequence_label_size)

   lowercase__	: List[str]     		=   self.get_config()

   return config, pixel_values, labels


 def   lowercase__  (       self):


   '''simple docstring'''




   return MaskFormerSwinConfig(
       image_size=self.image_size       ,	patch_size=self.patch_size       ,	num_channels=self.num_channels       ,	embed_dim=self.embed_dim       ,	depths=self.depths       ,	num_heads=self.num_heads       ,	window_size=self.window_size       ,	mlp_ratio=self.mlp_ratio       ,	qkv_bias=self.qkv_bias       ,	hidden_dropout_prob=self.hidden_dropout_prob       ,	attention_probs_dropout_prob=self.attention_probs_dropout_prob       ,	drop_path_rate=self.drop_path_rate       ,	hidden_act=self.hidden_act       ,	use_absolute_embeddings=self.use_absolute_embeddings       ,	path_norm=self.patch_norm       ,	layer_norm_eps=self.layer_norm_eps       ,	initializer_range=self.initializer_range       ,	encoder_stride=self.encoder_stride       ,	out_features=self.out_features       ,	out_indices=self.out_indices       ,	)


 def   lowercase__  (       self       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   lowercase__	: Any     		=   MaskFormerSwinModel(config=__snake_case)
   model.to(__snake_case)
   model.eval()
   lowercase__	: Any     		=   model(__snake_case)

   lowercase__	: List[str]     		=   ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths) - 1))
   lowercase__	: List[Any]     		=   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       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   lowercase__	: str     		=   MaskFormerSwinBackbone(config=__snake_case)
   model.to(__snake_case)
   model.eval()
   lowercase__	: Optional[int]     		=   model(__snake_case)

   # 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(__snake_case):
     lowercase__	: Optional[Any]     		=   ["""stem"""]
     lowercase__	: Any     		=   MaskFormerSwinBackbone(config=__snake_case)



 def   lowercase__  (       self):


   '''simple docstring'''




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



@require_torch
class    _snake_case (						_snake_case	,    _snake_case	,    unittest.TestCase				):
 __lowerCAmelCase	:  Any	   =      (
     (
         MaskFormerSwinModel,
         MaskFormerSwinBackbone,
     )
     if is_torch_available()
     else ()
 )
 __lowerCAmelCase	:  List[Any]	   =      {"""feature-extraction""": MaskFormerSwinModel} if is_torch_available() else {}
 __lowerCAmelCase	:  Optional[Any]	   =      False
 __lowerCAmelCase	:  Dict	   =      False
 __lowerCAmelCase	:  Optional[int]	   =      False
 __lowerCAmelCase	:  Union[str, Any]	   =      False
 __lowerCAmelCase	:  Union[str, Any]	   =      False


 def   lowercase__  (       self):


   '''simple docstring'''




   lowercase__	: str     		=   MaskFormerSwinModelTester(self)
   lowercase__	: Tuple     		=   ConfigTester(self       ,	config_class=__snake_case       ,	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):


   '''simple docstring'''




   pass


 def   lowercase__  (       self):


   '''simple docstring'''




   self.create_and_test_config_common_properties()
   self.config_tester.create_and_test_config_to_json_string()
   self.config_tester.create_and_test_config_to_json_file()
   self.config_tester.create_and_test_config_from_and_save_pretrained()
   self.config_tester.create_and_test_config_with_num_labels()
   self.config_tester.check_config_can_be_init_without_params()
   self.config_tester.check_config_arguments_init()


 def   lowercase__  (       self):


   '''simple docstring'''




   return


 def   lowercase__  (       self):


   '''simple docstring'''




   lowercase__	: Optional[Any]     		=   self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*__snake_case)


 def   lowercase__  (       self):


   '''simple docstring'''




   lowercase__	: Tuple     		=   self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_backbone(*__snake_case)


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


   '''simple docstring'''




   pass


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


   '''simple docstring'''




   pass


 def   lowercase__  (       self):


   '''simple docstring'''




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

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


 def   lowercase__  (       self):


   '''simple docstring'''




   lowercase__	: int     		=   self.model_tester.prepare_config_and_inputs_for_common()

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

     lowercase__	: str     		=   ["""pixel_values"""]
     self.assertListEqual(arg_names[:1]       ,	__snake_case)


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


   '''simple docstring'''




   pass


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


   '''simple docstring'''




   pass


 def   lowercase__  (       self       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   lowercase__	: List[str]     		=   model_class(__snake_case)
   model.to(__snake_case)
   model.eval()

   with torch.no_grad():
     lowercase__	: str     		=   model(**self._prepare_for_class(__snake_case       ,	__snake_case))

   lowercase__	: str     		=   outputs.hidden_states

   lowercase__	: Optional[int]     		=   getattr(
       self.model_tester       ,	"""expected_num_hidden_layers"""       ,	len(self.model_tester.depths) + 1)
   self.assertEqual(len(__snake_case)       ,	__snake_case)

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

   lowercase__	: Optional[int]     		=   (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):


   '''simple docstring'''




   lowercase__	: List[Any]     		=   self.model_tester.prepare_config_and_inputs_for_common()

   lowercase__	: str     		=   (
       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:
     lowercase__	: Union[str, Any]     		=   True
     self.check_hidden_states_output(__snake_case       ,	__snake_case       ,	__snake_case       ,	__snake_case)

     # check that output_hidden_states also work using config
     del inputs_dict["output_hidden_states"]
     lowercase__	: List[str]     		=   True

     self.check_hidden_states_output(__snake_case       ,	__snake_case       ,	__snake_case       ,	__snake_case)


 def   lowercase__  (       self):


   '''simple docstring'''




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

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

   lowercase__	: Tuple     		=   image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
   lowercase__	: Optional[int]     		=   image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

   for model_class in self.all_model_classes:
     lowercase__	: List[str]     		=   True
     self.check_hidden_states_output(__snake_case       ,	__snake_case       ,	__snake_case       ,	(padded_height, padded_width))

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


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


   '''simple docstring'''




   pass


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


   '''simple docstring'''




   pass


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


   '''simple docstring'''




   pass



 def   lowercase__  (       self):


   '''simple docstring'''




   lowercase__	: List[Any]     		=   self.model_tester.prepare_config_and_inputs_for_common()

   def set_nan_tensor_to_zero(SCREAMING_SNAKE_CASE_):
     lowercase__	: Optional[int]     		=   0
     return t

   def check_equivalence(SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_={}):
     with torch.no_grad():
       lowercase__	: Dict     		=   model(**__snake_case       ,	return_dict=__snake_case       ,	**__snake_case)
       lowercase__	: Optional[int]     		=   model(**__snake_case       ,	return_dict=__snake_case       ,	**__snake_case).to_tuple()

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

       recursive_check(__snake_case       ,	__snake_case)

   for model_class in self.all_model_classes:
     lowercase__	: Union[str, Any]     		=   model_class(__snake_case)
     model.to(__snake_case)
     model.eval()

     lowercase__	: str     		=   self._prepare_for_class(__snake_case       ,	__snake_case)
     lowercase__	: str     		=   self._prepare_for_class(__snake_case       ,	__snake_case)
     check_equivalence(__snake_case       ,	__snake_case       ,	__snake_case)

     lowercase__	: Any     		=   self._prepare_for_class(__snake_case       ,	__snake_case       ,	return_labels=__snake_case)
     lowercase__	: int     		=   self._prepare_for_class(__snake_case       ,	__snake_case       ,	return_labels=__snake_case)
     check_equivalence(__snake_case       ,	__snake_case       ,	__snake_case)

     lowercase__	: List[str]     		=   self._prepare_for_class(__snake_case       ,	__snake_case)
     lowercase__	: Optional[int]     		=   self._prepare_for_class(__snake_case       ,	__snake_case)
     check_equivalence(__snake_case       ,	__snake_case       ,	__snake_case       ,	{"""output_hidden_states""": True})

     lowercase__	: List[Any]     		=   self._prepare_for_class(__snake_case       ,	__snake_case       ,	return_labels=__snake_case)
     lowercase__	: Optional[Any]     		=   self._prepare_for_class(__snake_case       ,	__snake_case       ,	return_labels=__snake_case)
     check_equivalence(__snake_case       ,	__snake_case       ,	__snake_case       ,	{"""output_hidden_states""": True})



@require_torch
class    _snake_case (						unittest.TestCase	,    _snake_case				):
 __lowerCAmelCase	:  Any	   =      (MaskFormerSwinBackbone,) if is_torch_available() else ()
 __lowerCAmelCase	:  List[Any]	   =      MaskFormerSwinConfig


 def   lowercase__  (       self):


   '''simple docstring'''




   lowercase__	: Optional[int]     		=   MaskFormerSwinModelTester(self)



 def   lowercase__  (       self):


   '''simple docstring'''




   lowercase__	: Optional[int]     		=   self.model_tester.prepare_config_and_inputs_for_common()
   lowercase__	: Optional[int]     		=   inputs_dict["""pixel_values"""].shape[0]

   for backbone_class in self.all_model_classes:
     lowercase__	: List[Any]     		=   backbone_class(__snake_case)
     backbone.to(__snake_case)
     backbone.eval()

     lowercase__	: List[str]     		=   backbone(**__snake_case)

     # Test default outputs and verify feature maps
     self.assertIsInstance(outputs.feature_maps       ,	__snake_case)
     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
     lowercase__	: Optional[Any]     		=   backbone(**__snake_case       ,	output_hidden_states=__snake_case)
     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)
         lowercase__	: Dict     		=   hidden_state.shape
         self.assertTrue((h_batch_size, h_n_channels)       ,	(batch_size, n_channels))

            # Test output_attentions=True
     if self.has_attentions:
       lowercase__	: Optional[int]     		=   backbone(**__snake_case       ,	output_attentions=__snake_case)
       self.assertIsNotNone(outputs.attentions)










'''simple docstring'''


import gc
import random
import unittest

import numpy as np
import torch

from diffusers import DDIMScheduler, KandinskyVaaPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel
from diffusers.utils import floats_tensor, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference


enable_full_determinism()





class        lowercase__    (		_snake_case	,	unittest.TestCase   ):





							'''simple docstring'''


							A_				: Dict       =    KandinskyVaaPipeline
							A_				: List[str]       =    [
							    """image_embeds""",
							    """negative_image_embeds""",
							]
							A_				: Optional[int]       =    ["""image_embeds""", """negative_image_embeds"""]
							A_				: Optional[Any]       =    [
							    """generator""",
							    """height""",
							    """width""",
							    """latents""",
							    """guidance_scale""",
							    """num_inference_steps""",
							    """return_dict""",
							    """guidance_scale""",
							    """num_images_per_prompt""",
							    """output_type""",
							    """return_dict""",
							]
							A_				: Dict       =    False






							@property
							def UpperCAmelCase_      (       self    ):
											return 32






							@property
							def UpperCAmelCase_      (       self    ):
											return 32






							@property
							def UpperCAmelCase_      (       self    ):
											return self.time_input_dim






							@property
							def UpperCAmelCase_      (       self    ):
											return self.time_input_dim * 4






							@property
							def UpperCAmelCase_      (       self    ):
											return 100






							@property
							def UpperCAmelCase_      (       self    ):
											torch.manual_seed(0    )

											_SCREAMING_SNAKE_CASE					:			Tuple							= {
											    """in_channels""": 4,
											    # Out channels is double in channels because predicts mean and variance
											    """out_channels""": 8,
											    """addition_embed_type""": """image""",
											    """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""),
											    """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""),
											    """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""",
											    """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2),
											    """layers_per_block""": 1,
											    """encoder_hid_dim""": self.text_embedder_hidden_size,
											    """encoder_hid_dim_type""": """image_proj""",
											    """cross_attention_dim""": self.cross_attention_dim,
											    """attention_head_dim""": 4,
											    """resnet_time_scale_shift""": """scale_shift""",
											    """class_embed_type""": None,
											}

											_SCREAMING_SNAKE_CASE					:			Any							= UNetaDConditionModel(**__snake_case    )
											return model






							@property
							def UpperCAmelCase_      (       self    ):
											return {
											    "block_out_channels": [32, 64],
											    "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"],
											    "in_channels": 3,
											    "latent_channels": 4,
											    "layers_per_block": 1,
											    "norm_num_groups": 8,
											    "norm_type": "spatial",
											    "num_vq_embeddings": 12,
											    "out_channels": 3,
											    "up_block_types": [
											        "AttnUpDecoderBlock2D",
											        "UpDecoderBlock2D",
											    ],
											    "vq_embed_dim": 4,
											}






							@property
							def UpperCAmelCase_      (       self    ):
											torch.manual_seed(0    )
											_SCREAMING_SNAKE_CASE					:			Tuple							= VQModel(**self.dummy_movq_kwargs    )
											return model






							def UpperCAmelCase_      (       self    ):
											_SCREAMING_SNAKE_CASE					:			int							= self.dummy_unet
											_SCREAMING_SNAKE_CASE					:			List[str]							= self.dummy_movq

											_SCREAMING_SNAKE_CASE					:			Optional[Any]							= DDIMScheduler(
											    num_train_timesteps=1000       ,   beta_schedule="""linear"""       ,   beta_start=0.00085       ,   beta_end=0.012       ,   clip_sample=__snake_case       ,   set_alpha_to_one=__snake_case       ,   steps_offset=1       ,   prediction_type="""epsilon"""       ,   thresholding=__snake_case       ,   )

											_SCREAMING_SNAKE_CASE					:			Dict							= {
											    """unet""": unet,
											    """scheduler""": scheduler,
											    """movq""": movq,
											}
											return components






							def UpperCAmelCase_      (       self       ,   __snake_case       ,   __snake_case=0    ):
											_SCREAMING_SNAKE_CASE					:			int							= floats_tensor((1, self.text_embedder_hidden_size)       ,   rng=random.Random(__snake_case    )    ).to(__snake_case    )
											_SCREAMING_SNAKE_CASE					:			List[str]							= floats_tensor((1, self.text_embedder_hidden_size)       ,   rng=random.Random(seed + 1    )    ).to(
											    __snake_case    )
											if str(__snake_case    ).startswith("""mps"""    ):
															_SCREAMING_SNAKE_CASE					:			str							= torch.manual_seed(__snake_case    )
											else:
															_SCREAMING_SNAKE_CASE					:			Dict							= torch.Generator(device=__snake_case    ).manual_seed(__snake_case    )
											_SCREAMING_SNAKE_CASE					:			Tuple							= {
											    """image_embeds""": image_embeds,
											    """negative_image_embeds""": negative_image_embeds,
											    """generator""": generator,
											    """height""": 64,
											    """width""": 64,
											    """guidance_scale""": 4.0,
											    """num_inference_steps""": 2,
											    """output_type""": """np""",
											}
											return inputs






							def UpperCAmelCase_      (       self    ):
											_SCREAMING_SNAKE_CASE					:			Optional[Any]							= """cpu"""

											_SCREAMING_SNAKE_CASE					:			Dict							= self.get_dummy_components()

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

											pipe.set_progress_bar_config(disable=__snake_case    )

											_SCREAMING_SNAKE_CASE					:			Any							= pipe(**self.get_dummy_inputs(__snake_case    )    )
											_SCREAMING_SNAKE_CASE					:			Tuple							= output.images

											_SCREAMING_SNAKE_CASE					:			Dict							= pipe(
											    **self.get_dummy_inputs(__snake_case    )       ,   return_dict=__snake_case       ,   )[0]

											_SCREAMING_SNAKE_CASE					:			Tuple							= image[0, -3:, -3:, -1]
											_SCREAMING_SNAKE_CASE					:			List[Any]							= image_from_tuple[0, -3:, -3:, -1]

											assert image.shape == (1, 64, 64, 3)

											_SCREAMING_SNAKE_CASE					:			Dict							= np.array(
											    [0.6237976, 1.0, 0.36441332, 1.0, 0.70639634, 0.29877186, 0.85652125, 0.5216843, 0.54454046]    )

											assert (
											    np.abs(image_slice.flatten() - expected_slice    ).max() < 1e-2
											), f""" expected_slice {expected_slice}, but got {image_slice.flatten()}"""

											assert (
											    np.abs(image_from_tuple_slice.flatten() - expected_slice    ).max() < 1e-2
											), f""" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}"""





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





							'''simple docstring'''


							def UpperCAmelCase_      (       self    ):
											# clean up the VRAM after each test
											super().tearDown()
											gc.collect()
											torch.cuda.empty_cache()






							def UpperCAmelCase_      (       self    ):
											_SCREAMING_SNAKE_CASE					:			List[str]							= load_numpy(
											    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
											    """/kandinskyv22/kandinskyv22_text2img_cat_fp16.npy"""    )

											_SCREAMING_SNAKE_CASE					:			List[Any]							= KandinskyVaaPriorPipeline.from_pretrained(
											    """kandinsky-community/kandinsky-2-2-prior"""       ,   torch_dtype=torch.floataa    )
											pipe_prior.to(__snake_case    )

											_SCREAMING_SNAKE_CASE					:			Tuple							= KandinskyVaaPipeline.from_pretrained(
											    """kandinsky-community/kandinsky-2-2-decoder"""       ,   torch_dtype=torch.floataa    )
											_SCREAMING_SNAKE_CASE					:			Union[str, Any]							= pipeline.to(__snake_case    )
											pipeline.set_progress_bar_config(disable=__snake_case    )

											_SCREAMING_SNAKE_CASE					:			Dict							= """red cat, 4k photo"""

											_SCREAMING_SNAKE_CASE					:			List[str]							= torch.Generator(device="""cuda"""    ).manual_seed(0    )
											_SCREAMING_SNAKE_CASE						,			_SCREAMING_SNAKE_CASE					:			List[str]							= pipe_prior(
											    __snake_case       ,   generator=__snake_case       ,   num_inference_steps=5       ,   negative_prompt=""""""       ,   ).to_tuple()

											_SCREAMING_SNAKE_CASE					:			Dict							= torch.Generator(device="""cuda"""    ).manual_seed(0    )
											_SCREAMING_SNAKE_CASE					:			List[str]							= pipeline(
											    image_embeds=__snake_case       ,   negative_image_embeds=__snake_case       ,   generator=__snake_case       ,   num_inference_steps=100       ,   output_type="""np"""       ,   )

											_SCREAMING_SNAKE_CASE					:			List[Any]							= output.images[0]

											assert image.shape == (512, 512, 3)

											assert_mean_pixel_difference(__snake_case       ,   __snake_case    )




