





"""simple docstring"""



from __future__ import annotations

import copy
import inspect
import json
import math
import os
import tempfile
import unittest
from importlib import import_module

import numpy as np

from transformers import ViTMAEConfig
from transformers.file_utils import cached_property, is_tf_available, is_vision_available
from transformers.testing_utils import require_tf, require_vision, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
       import tensorflow as tf

       from transformers import TFViTMAEForPreTraining, TFViTMAEModel


if is_vision_available():
       from PIL import Image

       from transformers import ViTImageProcessor






class 						__snake_case   :





 """simple docstring"""


 def __init__(       self   ,		__lowerCamelCase   ,		__lowerCamelCase=13   ,		__lowerCamelCase=30   ,		__lowerCamelCase=2   ,		__lowerCamelCase=3   ,		__lowerCamelCase=True   ,		__lowerCamelCase=True   ,		__lowerCamelCase=32   ,		__lowerCamelCase=2   ,		__lowerCamelCase=4   ,		__lowerCamelCase=37   ,		__lowerCamelCase="gelu"   ,		__lowerCamelCase=0.1   ,		__lowerCamelCase=0.1   ,		__lowerCamelCase=10   ,		__lowerCamelCase=0.0_2   ,		__lowerCamelCase=3   ,		__lowerCamelCase=0.6   ,		__lowerCamelCase=None   ,		):



     '''simple docstring'''




     __A       :		Union[str, Any]							=	parent
     __A       :		Optional[Any]							=	batch_size
     __A       :		Optional[int]							=	image_size
     __A       :		Union[str, Any]							=	patch_size
     __A       :		List[Any]							=	num_channels
     __A       :		Any							=	is_training
     __A       :		Tuple							=	use_labels
     __A       :		List[Any]							=	hidden_size
     __A       :		Union[str, Any]							=	num_hidden_layers
     __A       :		Optional[int]							=	num_attention_heads
     __A       :		Tuple							=	intermediate_size
     __A       :		Optional[int]							=	hidden_act
     __A       :		Tuple							=	hidden_dropout_prob
     __A       :		List[str]							=	attention_probs_dropout_prob
     __A       :		str							=	type_sequence_label_size
     __A       :		Optional[int]							=	initializer_range
     __A       :		Tuple							=	mask_ratio
     __A       :		Optional[int]							=	scope

     # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above
     # (we add 1 for the [CLS] token)
     __A       :		Any							=	(image_size // patch_size) ** 2
     __A       :		Union[str, Any]							=	int(math.ceil((1 - mask_ratio) * (num_patches + 1)    )    )

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




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

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

     __A       :		Any							=	self.get_config()

     return config, pixel_values, labels

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     return ViTMAEConfig(
         image_size=self.image_size   ,		patch_size=self.patch_size   ,		num_channels=self.num_channels   ,		hidden_size=self.hidden_size   ,		num_hidden_layers=self.num_hidden_layers   ,		num_attention_heads=self.num_attention_heads   ,		intermediate_size=self.intermediate_size   ,		decoder_hidden_size=self.hidden_size   ,		decoder_num_hidden_layers=self.num_hidden_layers   ,		decoder_num_attention_heads=self.num_attention_heads   ,		decoder_intermediate_size=self.intermediate_size   ,		hidden_act=self.hidden_act   ,		hidden_dropout_prob=self.hidden_dropout_prob   ,		attention_probs_dropout_prob=self.attention_probs_dropout_prob   ,		is_decoder=__lowerCamelCase   ,		initializer_range=self.initializer_range   ,		mask_ratio=self.mask_ratio   ,		)

 def    UpperCamelCase__(       self   ,		__lowerCamelCase   ,		__lowerCamelCase   ,		__lowerCamelCase    ):



     '''simple docstring'''




     __A       :		str							=	TFViTMAEModel(config=__lowerCamelCase    )
     __A       :		List[str]							=	model(__lowerCamelCase   ,		training=__lowerCamelCase    )
     self.parent.assertEqual(result.last_hidden_state.shape   ,		(self.batch_size, self.seq_length, self.hidden_size)    )

 def    UpperCamelCase__(       self   ,		__lowerCamelCase   ,		__lowerCamelCase   ,		__lowerCamelCase    ):



     '''simple docstring'''




     __A       :		List[Any]							=	TFViTMAEForPreTraining(__lowerCamelCase    )
     __A       :		Tuple							=	model(__lowerCamelCase   ,		training=__lowerCamelCase    )
     # expected sequence length = num_patches
     __A       :		List[str]							=	(self.image_size // self.patch_size) ** 2
     __A       :		str							=	self.patch_size**2 * self.num_channels
     self.parent.assertEqual(result.logits.shape   ,		(self.batch_size, num_patches, expected_num_channels)    )

     # test greyscale images
     __A       :		Tuple							=	1
     __A       :		Tuple							=	TFViTMAEForPreTraining(__lowerCamelCase    )

     __A       :		Any							=	floats_tensor([self.batch_size, 1, self.image_size, self.image_size]    )
     __A       :		Union[str, Any]							=	model(__lowerCamelCase   ,		training=__lowerCamelCase    )
     __A       :		Any							=	self.patch_size**2
     self.parent.assertEqual(result.logits.shape   ,		(self.batch_size, num_patches, expected_num_channels)    )







 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




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






@require_tf
class 						__snake_case   (						SCREAMING_SNAKE_CASE__				,				SCREAMING_SNAKE_CASE__				,				unittest.TestCase	):





 """simple docstring"""


 _lowerCamelCase								=	(TFViTMAEModel, TFViTMAEForPreTraining) if is_tf_available() else ()
 _lowerCamelCase								=	{"""feature-extraction""": TFViTMAEModel} if is_tf_available() else {}

 _lowerCamelCase								=	False
 _lowerCamelCase								=	False
 _lowerCamelCase								=	False
 _lowerCamelCase								=	False

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     __A       :		Union[str, Any]							=	TFViTMAEModelTester(self    )
     __A       :		Any							=	ConfigTester(self   ,		config_class=__lowerCamelCase   ,		has_text_modality=__lowerCamelCase   ,		hidden_size=37    )

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     self.config_tester.run_common_tests()

 @unittest.skip(reason='''ViTMAE does not use inputs_embeds'''    )
 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     pass

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




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

     for model_class in self.all_model_classes:
         __A       :		List[Any]							=	model_class(__lowerCamelCase    )
         self.assertIsInstance(model.get_input_embeddings()   ,		(tf.keras.layers.Layer)    )
         __A       :		List[Any]							=	model.get_output_embeddings()
         self.assertTrue(x is None or isinstance(__lowerCamelCase   ,		tf.keras.layers.Layer    )    )

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




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

     for model_class in self.all_model_classes:
         __A       :		Tuple							=	model_class(__lowerCamelCase    )
         __A       :		List[str]							=	inspect.signature(model.call    )
         # signature.parameters is an OrderedDict => so arg_names order is deterministic
         __A       :		Optional[int]							=	[*signature.parameters.keys()]

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

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     __A       :		Any							=	self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*__lowerCamelCase    )

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     __A       :		Union[str, Any]							=	self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_pretraining(*__lowerCamelCase    )

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     np.random.seed(2    )

     __A					,			__A       :		Dict							=	self.model_tester.prepare_config_and_inputs_for_common()

     __A       :		int							=	int((config.image_size // config.patch_size) ** 2    )
     __A       :		Optional[int]							=	np.random.uniform(size=(self.model_tester.batch_size, num_patches)    )

     for model_class in self.all_model_classes:
         __A       :		Optional[Any]							=	model_class(__lowerCamelCase    )
         __A       :		Any							=	self._prepare_for_class(__lowerCamelCase   ,		__lowerCamelCase    )

         __A       :		Tuple							=	model(__lowerCamelCase   ,		noise=__lowerCamelCase    )

         __A       :		str							=	copy.deepcopy(self._prepare_for_class(__lowerCamelCase   ,		__lowerCamelCase    )    )
         __A       :		int							=	model(**__lowerCamelCase   ,		noise=__lowerCamelCase    )
         __A       :		Optional[int]							=	outputs_dict[0].numpy()
         __A       :		List[str]							=	outputs_keywords[0].numpy()

         self.assertLess(np.sum(np.abs(output_dict - output_keywords    )    )   ,		1e-6    )

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     np.random.seed(2    )

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

     __A       :		int							=	int((config.image_size // config.patch_size) ** 2    )
     __A       :		Tuple							=	np.random.uniform(size=(self.model_tester.batch_size, num_patches)    )

     def prepare_numpy_arrays(__lowerCamelCase    ):
         __A       :		Optional[Any]							=	{}
         for k, v in inputs_dict.items():
             if tf.is_tensor(__lowerCamelCase    ):
                 __A       :		str							=	v.numpy()
             else:
                 __A       :		str							=	np.array(__lowerCamelCase    )

         return inputs_np_dict

     for model_class in self.all_model_classes:
         __A       :		Any							=	model_class(__lowerCamelCase    )

         __A       :		List[Any]							=	self._prepare_for_class(__lowerCamelCase   ,		__lowerCamelCase    )
         __A       :		List[Any]							=	prepare_numpy_arrays(__lowerCamelCase    )

         __A       :		Dict							=	model(__lowerCamelCase   ,		noise=__lowerCamelCase    )
         __A       :		Union[str, Any]							=	model(**__lowerCamelCase   ,		noise=__lowerCamelCase    )
         self.assert_outputs_same(__lowerCamelCase   ,		__lowerCamelCase    )

 def    UpperCamelCase__(       self   ,		__lowerCamelCase   ,		__lowerCamelCase   ,		__lowerCamelCase    ):



     '''simple docstring'''




     np.random.seed(2    )

     __A       :		Union[str, Any]							=	int((tf_model.config.image_size // tf_model.config.patch_size) ** 2    )
     __A       :		Optional[int]							=	np.random.uniform(size=(self.model_tester.batch_size, num_patches)    )
     __A       :		Union[str, Any]							=	tf.constant(__lowerCamelCase    )

     # Add `noise` argument.
     # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument
     __A       :		Optional[int]							=	tf_noise

     super().check_pt_tf_models(__lowerCamelCase   ,		__lowerCamelCase   ,		__lowerCamelCase    )

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     np.random.seed(2    )

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

     __A       :		str							=	{
         module_member
         for model_class in self.all_model_classes
         for module in (import_module(model_class.__module__    ),)
         for module_member_name in dir(__lowerCamelCase    )
         if module_member_name.endswith('''MainLayer'''    )
         # This condition is required, since `modeling_tf_clip.py` has 3 classes whose names end with `MainLayer`.
         and module_member_name[: -len('''MainLayer'''    )] == model_class.__name__[: -len('''Model'''    )]
         for module_member in (getattr(__lowerCamelCase   ,		__lowerCamelCase    ),)
         if isinstance(__lowerCamelCase   ,		__lowerCamelCase    )
         and tf.keras.layers.Layer in module_member.__bases__
         and getattr(__lowerCamelCase   ,		'''_keras_serializable'''   ,		__lowerCamelCase    )
     }

     __A       :		Optional[int]							=	int((config.image_size // config.patch_size) ** 2    )
     __A       :		str							=	np.random.uniform(size=(self.model_tester.batch_size, num_patches)    )
     __A       :		Optional[int]							=	tf.convert_to_tensor(__lowerCamelCase    )
     inputs_dict.update({'''noise''': noise}    )

     for main_layer_class in tf_main_layer_classes:
         __A       :		Optional[int]							=	main_layer_class(__lowerCamelCase    )

         __A       :		List[str]							=	{
             name: tf.keras.Input(tensor.shape[1:]   ,		dtype=tensor.dtype    ) for name, tensor in inputs_dict.items()
         }

         __A       :		Dict							=	tf.keras.Model(__lowerCamelCase   ,		outputs=main_layer(__lowerCamelCase    )    )
         __A       :		List[Any]							=	model(__lowerCamelCase    )

         with tempfile.TemporaryDirectory() as tmpdirname:
             __A       :		Any							=	os.path.join(__lowerCamelCase   ,		'''keras_model.h5'''    )
             model.save(__lowerCamelCase    )
             __A       :		List[str]							=	tf.keras.models.load_model(
                 __lowerCamelCase   ,		custom_objects={main_layer_class.__name__: main_layer_class}    )
             assert isinstance(__lowerCamelCase   ,		tf.keras.Model    )
             __A       :		int							=	model(__lowerCamelCase    )
             self.assert_outputs_same(__lowerCamelCase   ,		__lowerCamelCase    )

 @slow
 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     np.random.seed(2    )

     __A					,			__A       :		List[str]							=	self.model_tester.prepare_config_and_inputs_for_common()

     __A       :		Any							=	int((config.image_size // config.patch_size) ** 2    )
     __A       :		Union[str, Any]							=	np.random.uniform(size=(self.model_tester.batch_size, num_patches)    )

     for model_class in self.all_model_classes:
         __A       :		Union[str, Any]							=	model_class(__lowerCamelCase    )
         __A       :		List[str]							=	self._prepare_for_class(__lowerCamelCase   ,		__lowerCamelCase    )
         __A       :		int							=	model(__lowerCamelCase   ,		noise=__lowerCamelCase    )

         if model_class.__name__ == "TFViTMAEModel":
             __A       :		Dict							=	outputs.last_hidden_state.numpy()
             __A       :		Union[str, Any]							=	0
         else:
             __A       :		List[Any]							=	outputs.logits.numpy()
             __A       :		Optional[Any]							=	0

         with tempfile.TemporaryDirectory() as tmpdirname:
             model.save_pretrained(__lowerCamelCase   ,		saved_model=__lowerCamelCase    )
             __A       :		List[str]							=	model_class.from_pretrained(__lowerCamelCase    )
             __A       :		Any							=	model(__lowerCamelCase   ,		noise=__lowerCamelCase    )

             if model_class.__name__ == "TFViTMAEModel":
                 __A       :		List[str]							=	after_outputs['''last_hidden_state'''].numpy()
                 __A       :		int							=	0
             else:
                 __A       :		List[str]							=	after_outputs['''logits'''].numpy()
                 __A       :		Dict							=	0

             __A       :		List[str]							=	np.amax(np.abs(out_a - out_a    )    )
             self.assertLessEqual(__lowerCamelCase   ,		1e-5    )

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     np.random.seed(2    )

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

     __A       :		Optional[Any]							=	int((config.image_size // config.patch_size) ** 2    )
     __A       :		Tuple							=	np.random.uniform(size=(self.model_tester.batch_size, num_patches)    )

     for model_class in self.all_model_classes:
         __A       :		List[Any]							=	model_class(__lowerCamelCase    )
         __A       :		Optional[Any]							=	self._prepare_for_class(__lowerCamelCase   ,		__lowerCamelCase    )

         __A       :		Optional[Any]							=	model(__lowerCamelCase   ,		noise=__lowerCamelCase    )
         __A       :		Any							=	model.get_config()
         # make sure that returned config is jsonifiable, which is required by keras
         json.dumps(__lowerCamelCase    )
         __A       :		Dict							=	model_class.from_config(model.get_config()    )
         # make sure it also accepts a normal config
         __A       :		Union[str, Any]							=	model_class.from_config(model.config    )
         __A       :		int							=	new_model(__lowerCamelCase    )  # Build model
         new_model.set_weights(model.get_weights()    )
         __A       :		Optional[int]							=	new_model(__lowerCamelCase   ,		noise=__lowerCamelCase    )

         self.assert_outputs_same(__lowerCamelCase   ,		__lowerCamelCase    )

 @unittest.skip(
     reason='''ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load
    to get deterministic results.'''    )
 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     pass

 @unittest.skip(reason='''ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load'''    )
 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     pass







 @slow
 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     __A       :		str							=	TFViTMAEModel.from_pretrained('''google/vit-base-patch16-224'''    )
     self.assertIsNotNone(__lowerCamelCase    )







def 						__lowercase	(  )  ->Dict:



    '''simple docstring'''







    __A       :		Tuple							=	Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''		)
    return image






@require_tf
@require_vision
class 						__snake_case   (						unittest.TestCase	):





 """simple docstring"""


 @cached_property
 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     return ViTImageProcessor.from_pretrained('''facebook/vit-mae-base'''    ) if is_vision_available() else None







 @slow
 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     np.random.seed(2    )

     __A       :		List[str]							=	TFViTMAEForPreTraining.from_pretrained('''facebook/vit-mae-base'''    )

     __A       :		Union[str, Any]							=	self.default_image_processor
     __A       :		Any							=	prepare_img()
     __A       :		Optional[int]							=	image_processor(images=__lowerCamelCase   ,		return_tensors='''tf'''    )

     # prepare a noise vector that will be also used for testing the TF model
     # (this way we can ensure that the PT and TF models operate on the same inputs)
     __A       :		Optional[Any]							=	ViTMAEConfig()
     __A       :		Union[str, Any]							=	int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2    )
     __A       :		List[str]							=	np.random.uniform(size=(1, num_patches)    )

     # forward pass
     __A       :		Optional[Any]							=	model(**__lowerCamelCase   ,		noise=__lowerCamelCase    )

     # verify the logits
     __A       :		Union[str, Any]							=	tf.convert_to_tensor([1, 196, 768]    )
     self.assertEqual(outputs.logits.shape   ,		__lowerCamelCase    )

     __A       :		List[Any]							=	tf.convert_to_tensor(
         [[-0.0_5_4_8, -1.7_0_2_3, -0.9_3_2_5], [0.3_7_2_1, -0.5_6_7_0, -0.2_2_3_3], [0.8_2_3_5, -1.3_8_7_8, -0.3_5_2_4]]    )

     tf.debugging.assert_near(outputs.logits[0, :3, :3]   ,		__lowerCamelCase   ,		atol=1e-4    )











"""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 						__snake_case   (						SCREAMING_SNAKE_CASE__				,				unittest.TestCase	):





 """simple docstring"""


 _lowerCamelCase								=	KandinskyVaaPipeline
 _lowerCamelCase								=	[
     """image_embeds""",
     """negative_image_embeds""",
 ]
 _lowerCamelCase								=	["""image_embeds""", """negative_image_embeds"""]
 _lowerCamelCase								=	[
     """generator""",
     """height""",
     """width""",
     """latents""",
     """guidance_scale""",
     """num_inference_steps""",
     """return_dict""",
     """guidance_scale""",
     """num_images_per_prompt""",
     """output_type""",
     """return_dict""",
 ]
 _lowerCamelCase								=	False

 @property
 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     return 32

 @property
 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     return 32

 @property
 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     return self.time_input_dim

 @property
 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     return self.time_input_dim * 4

 @property
 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     return 100

 @property
 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     torch.manual_seed(0    )

     __A       :		Optional[Any]							=	{
         '''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,
     }

     __A       :		Optional[Any]							=	UNetaDConditionModel(**__lowerCamelCase    )
     return model

 @property
 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




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



     '''simple docstring'''




     torch.manual_seed(0    )
     __A       :		Tuple							=	VQModel(**self.dummy_movq_kwargs    )
     return model

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     __A       :		List[Any]							=	self.dummy_unet
     __A       :		Optional[int]							=	self.dummy_movq

     __A       :		List[Any]							=	DDIMScheduler(
         num_train_timesteps=1000   ,		beta_schedule='''linear'''   ,		beta_start=0.0_0_0_8_5   ,		beta_end=0.0_1_2   ,		clip_sample=__lowerCamelCase   ,		set_alpha_to_one=__lowerCamelCase   ,		steps_offset=1   ,		prediction_type='''epsilon'''   ,		thresholding=__lowerCamelCase   ,		)

     __A       :		Optional[int]							=	{
         '''unet''': unet,
         '''scheduler''': scheduler,
         '''movq''': movq,
     }
     return components

 def    UpperCamelCase__(       self   ,		__lowerCamelCase   ,		__lowerCamelCase=0    ):



     '''simple docstring'''




     __A       :		Optional[int]							=	floats_tensor((1, self.text_embedder_hidden_size)   ,		rng=random.Random(__lowerCamelCase    )    ).to(__lowerCamelCase    )
     __A       :		List[Any]							=	floats_tensor((1, self.text_embedder_hidden_size)   ,		rng=random.Random(seed + 1    )    ).to(
         __lowerCamelCase    )
     if str(__lowerCamelCase    ).startswith('''mps'''    ):
         __A       :		Optional[Any]							=	torch.manual_seed(__lowerCamelCase    )
     else:
         __A       :		Dict							=	torch.Generator(device=__lowerCamelCase    ).manual_seed(__lowerCamelCase    )
     __A       :		Dict							=	{
         '''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    ):



     '''simple docstring'''




     __A       :		str							=	'''cpu'''

     __A       :		str							=	self.get_dummy_components()

     __A       :		Dict							=	self.pipeline_class(**__lowerCamelCase    )
     __A       :		Tuple							=	pipe.to(__lowerCamelCase    )

     pipe.set_progress_bar_config(disable=__lowerCamelCase    )

     __A       :		List[str]							=	pipe(**self.get_dummy_inputs(__lowerCamelCase    )    )
     __A       :		Tuple							=	output.images

     __A       :		Tuple							=	pipe(
         **self.get_dummy_inputs(__lowerCamelCase    )   ,		return_dict=__lowerCamelCase   ,		)[0]

     __A       :		Dict							=	image[0, -3:, -3:, -1]
     __A       :		Any							=	image_from_tuple[0, -3:, -3:, -1]

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

     __A       :		Optional[int]							=	np.array(
         [0.6_2_3_7_9_7_6, 1.0, 0.3_6_4_4_1_3_3_2, 1.0, 0.7_0_6_3_9_6_3_4, 0.2_9_8_7_7_1_8_6, 0.8_5_6_5_2_1_2_5, 0.5_2_1_6_8_4_3, 0.5_4_4_5_4_0_4_6]    )

     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 						__snake_case   (						unittest.TestCase	):





 """simple docstring"""


 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




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







 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     __A       :		Any							=	load_numpy(
         '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
         '''/kandinskyv22/kandinskyv22_text2img_cat_fp16.npy'''    )

     __A       :		Optional[Any]							=	KandinskyVaaPriorPipeline.from_pretrained(
         '''kandinsky-community/kandinsky-2-2-prior'''   ,		torch_dtype=torch.floataa    )
     pipe_prior.to(__lowerCamelCase    )

     __A       :		int							=	KandinskyVaaPipeline.from_pretrained(
         '''kandinsky-community/kandinsky-2-2-decoder'''   ,		torch_dtype=torch.floataa    )
     __A       :		Union[str, Any]							=	pipeline.to(__lowerCamelCase    )
     pipeline.set_progress_bar_config(disable=__lowerCamelCase    )

     __A       :		List[Any]							=	'''red cat, 4k photo'''

     __A       :		Union[str, Any]							=	torch.Generator(device='''cuda'''    ).manual_seed(0    )
     __A					,			__A       :		List[str]							=	pipe_prior(
         __lowerCamelCase   ,		generator=__lowerCamelCase   ,		num_inference_steps=5   ,		negative_prompt=''''''   ,		).to_tuple()

     __A       :		Any							=	torch.Generator(device='''cuda'''    ).manual_seed(0    )
     __A       :		Optional[int]							=	pipeline(
         image_embeds=__lowerCamelCase   ,		negative_image_embeds=__lowerCamelCase   ,		generator=__lowerCamelCase   ,		num_inference_steps=100   ,		output_type='''np'''   ,		)

     __A       :		Union[str, Any]							=	output.images[0]

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

     assert_mean_pixel_difference(__lowerCamelCase   ,		__lowerCamelCase    )




