code: 
  
  
  
  
  
  
  import random
  import unittest
  
  import numpy as np
  import torch
  from PIL import Image
  from torch import nn
  from transformers import (
      CLIPImageProcessor,
      CLIPTextConfig,
      CLIPTextModelWithProjection,
      CLIPTokenizer,
      CLIPVisionConfig,
      CLIPVisionModelWithProjection,
  )
  
  from diffusers import KandinskyVaaPriorEmbaEmbPipeline, PriorTransformer, UnCLIPScheduler
  from diffusers.utils import floats_tensor, torch_device
  from diffusers.utils.testing_utils import enable_full_determinism, skip_mps
  
  from ..test_pipelines_common import PipelineTesterMixin
  
  
  enable_full_determinism()
  
  class 					snake_case_							(       UpperCamelCase__      ,			unittest.TestCase      ):
     __lowerCAmelCase      =						KandinskyVaaPriorEmbaEmbPipeline
     __lowerCAmelCase      =						["""prompt""", """image"""]
     __lowerCAmelCase      =						["""prompt""", """image"""]
     __lowerCAmelCase      =						[
         """num_images_per_prompt""",
         """strength""",
         """generator""",
         """num_inference_steps""",
         """latents""",
         """negative_prompt""",
         """guidance_scale""",
         """output_type""",
         """return_dict""",
     ]
     __lowerCAmelCase      =						False
  
     @property
     def 			SCREAMING_SNAKE_CASE__				(    self:	str	)  ->		Union[str, Any]:
  
  
         """simple docstring"""
  
  
  
         return 32
  
     @property
     def 			SCREAMING_SNAKE_CASE__				(    self:	Tuple	)  ->		int:
  
  
         """simple docstring"""
  
  
  
         return 32
  
     @property
     def 			SCREAMING_SNAKE_CASE__				(    self:	int	)  ->		List[Any]:
  
  
         """simple docstring"""
  
  
  
         return self.time_input_dim
  
     @property
     def 			SCREAMING_SNAKE_CASE__				(    self:	Dict	)  ->		Any:
  
  
         """simple docstring"""
  
  
  
         return self.time_input_dim * 4
  
     @property
     def 			SCREAMING_SNAKE_CASE__				(    self:	Union[str, Any]	)  ->		str:
  
  
         """simple docstring"""
  
  
  
         return 100
  
     @property
     def 			SCREAMING_SNAKE_CASE__				(    self:	List[str]	)  ->		List[str]:
  
  
         """simple docstring"""
  
  
  
         _lowercase     =	CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'	)
         return tokenizer
  
     @property
     def 			SCREAMING_SNAKE_CASE__				(    self:	Optional[Any]	)  ->		Tuple:
  
  
         """simple docstring"""
  
  
  
         torch.manual_seed(0	)
         _lowercase     =	CLIPTextConfig(
             bos_token_id=0   ,       eos_token_id=2   ,       hidden_size=self.text_embedder_hidden_size   ,       projection_dim=self.text_embedder_hidden_size   ,       intermediate_size=37   ,       layer_norm_eps=1E-05   ,       num_attention_heads=4   ,       num_hidden_layers=5   ,       pad_token_id=1   ,       vocab_size=1_000   ,       )
         return CLIPTextModelWithProjection(lowerCAmelCase__	)
  
     @property
     def 			SCREAMING_SNAKE_CASE__				(    self:	Any	)  ->		str:
  
  
         """simple docstring"""
  
  
  
         torch.manual_seed(0	)
  
         _lowercase     =	{
             "num_attention_heads": 2,
             "attention_head_dim": 12,
             "embedding_dim": self.text_embedder_hidden_size,
             "num_layers": 1,
         }
  
         _lowercase     =	PriorTransformer(**lowerCAmelCase__	)
         # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0
         _lowercase     =	nn.Parameter(torch.ones(model.clip_std.shape	)	)
         return model
  
     @property
     def 			SCREAMING_SNAKE_CASE__				(    self:	List[Any]	)  ->		str:
  
  
         """simple docstring"""
  
  
  
         torch.manual_seed(0	)
         _lowercase     =	CLIPVisionConfig(
             hidden_size=self.text_embedder_hidden_size   ,       image_size=224   ,       projection_dim=self.text_embedder_hidden_size   ,       intermediate_size=37   ,       num_attention_heads=4   ,       num_channels=3   ,       num_hidden_layers=5   ,       patch_size=14   ,       )
  
         _lowercase     =	CLIPVisionModelWithProjection(lowerCAmelCase__	)
         return model
  
     @property
     def 			SCREAMING_SNAKE_CASE__				(    self:	Tuple	)  ->		Optional[int]:
  
  
         """simple docstring"""
  
  
  
         _lowercase     =	CLIPImageProcessor(
             crop_size=224   ,       do_center_crop=lowerCAmelCase__   ,       do_normalize=lowerCAmelCase__   ,       do_resize=lowerCAmelCase__   ,       image_mean=[0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73]   ,       image_std=[0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11]   ,       resample=3   ,       size=224   ,       )
  
         return image_processor
  
     def 			SCREAMING_SNAKE_CASE__				(    self:	Union[str, Any]	)  ->		Dict:
  
  
         """simple docstring"""
  
  
  
         _lowercase     =	self.dummy_prior
         _lowercase     =	self.dummy_image_encoder
         _lowercase     =	self.dummy_text_encoder
         _lowercase     =	self.dummy_tokenizer
         _lowercase     =	self.dummy_image_processor
  
         _lowercase     =	UnCLIPScheduler(
             variance_type='fixed_small_log'   ,       prediction_type='sample'   ,       num_train_timesteps=1_000   ,       clip_sample=lowerCAmelCase__   ,       clip_sample_range=10.0   ,       )
  
         _lowercase     =	{
             "prior": prior,
             "image_encoder": image_encoder,
             "text_encoder": text_encoder,
             "tokenizer": tokenizer,
             "scheduler": scheduler,
             "image_processor": image_processor,
         }
  
         return components
  
     def 			SCREAMING_SNAKE_CASE__				(    self:	Dict   ,       snake_case__:	Any   ,       snake_case__:	List[str]=0	)  ->		Tuple:
  
  
         """simple docstring"""
  
  
  
         if str(lowerCAmelCase__	).startswith('mps'	):
             _lowercase     =	torch.manual_seed(lowerCAmelCase__	)
         else:
             _lowercase     =	torch.Generator(device=lowerCAmelCase__	).manual_seed(lowerCAmelCase__	)
  
         _lowercase     =	floats_tensor((1, 3, 64, 64)   ,       rng=random.Random(lowerCAmelCase__	)	).to(lowerCAmelCase__	)
         _lowercase     =	image.cpu().permute(0   ,       2   ,       3   ,       1	)[0]
         _lowercase     =	Image.fromarray(np.uinta(lowerCAmelCase__	)	).convert('RGB'	).resize((256, 256)	)
  
         _lowercase     =	{
             "prompt": "horse",
             "image": init_image,
             "strength": 0.5,
             "generator": generator,
             "guidance_scale": 4.0,
             "num_inference_steps": 2,
             "output_type": "np",
         }
         return inputs
  
     def 			SCREAMING_SNAKE_CASE__				(    self:	Union[str, Any]	)  ->		List[Any]:
  
  
         """simple docstring"""
  
  
  
         _lowercase     =	"cpu"
  
         _lowercase     =	self.get_dummy_components()
  
         _lowercase     =	self.pipeline_class(**lowerCAmelCase__	)
         _lowercase     =	pipe.to(lowerCAmelCase__	)
  
         pipe.set_progress_bar_config(disable=lowerCAmelCase__	)
  
         _lowercase     =	pipe(**self.get_dummy_inputs(lowerCAmelCase__	)	)
         _lowercase     =	output.image_embeds
  
         _lowercase     =	pipe(
             **self.get_dummy_inputs(lowerCAmelCase__	)   ,       return_dict=lowerCAmelCase__   ,       )[0]
  
         _lowercase     =	image[0, -10:]
         _lowercase     =	image_from_tuple[0, -10:]
  
         assert image.shape == (1, 32)
  
         _lowercase     =	np.array(
             [
                 0.1_07_12_84,
                 1.3_33_02_71,
                 0.61_26_02_23,
                 -0.6_69_10_65,
                 -0.3_84_68_52,
                 -1.0_30_36_61,
                 0.22_71_61_11,
                 0.03_34_89_01,
                 0.30_04_06_75,
                 -0.24_80_50_29,
             ]	)
  
         assert np.abs(image_slice.flatten() - expected_slice	).max() < 1E-2
         assert np.abs(image_from_tuple_slice.flatten() - expected_slice	).max() < 1E-2
  
     @skip_mps
     def 			SCREAMING_SNAKE_CASE__				(    self:	int	)  ->		Optional[int]:
  
  
         """simple docstring"""
  
  
  
         _lowercase     =	torch_device == "cpu"
         _lowercase     =	True
         _lowercase     =	False
  
         self._test_inference_batch_single_identical(
             test_max_difference=lowerCAmelCase__   ,       relax_max_difference=lowerCAmelCase__   ,       test_mean_pixel_difference=lowerCAmelCase__   ,       )
  
     @skip_mps
     def 			SCREAMING_SNAKE_CASE__				(    self:	Optional[int]	)  ->		Union[str, Any]:
  
  
         """simple docstring"""
  
  
  
         _lowercase     =	torch_device == "cpu"
         _lowercase     =	False
  
         self._test_attention_slicing_forward_pass(
             test_max_difference=lowerCAmelCase__   ,       test_mean_pixel_difference=lowerCAmelCase__   ,       )
  
style_context: 
  
  
  
  
  
  
  from typing import Dict, List, Optional, Union
  
  import numpy as np
  
  from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
  from ...image_transforms import center_crop, normalize, rescale, resize, to_channel_dimension_format
  from ...image_utils import (
      IMAGENET_STANDARD_MEAN,
      IMAGENET_STANDARD_STD,
      ChannelDimension,
      ImageInput,
      PILImageResampling,
      make_list_of_images,
      to_numpy_array,
      valid_images,
  )
  from ...utils import TensorType, is_vision_available, logging
  
  
  if is_vision_available():
     import PIL
  
  
  lowerCamelCase										=  logging.get_logger(__name__)
  
  class 					snake_case_							(       lowercase_      ):
  
  
  
  
  
  
  
     """simple docstring"""
  
  
  
     __lowerCAmelCase      =						["""pixel_values"""]
  
     def __init__(    self:	int   ,       snake_case__:	bool = True   ,       snake_case__:	Dict[str, int] = None   ,       snake_case__:	PILImageResampling = PIL.Image.NEAREST   ,       snake_case__:	bool = False   ,       snake_case__:	Dict[str, int] = None   ,       snake_case__:	Union[int, float] = 1 / 255   ,       snake_case__:	bool = False   ,       snake_case__:	bool = True   ,       snake_case__:	bool = True   ,       snake_case__:	Optional[Union[float, List[float]]] = None   ,       snake_case__:	Optional[Union[float, List[float]]] = None   ,       snake_case__:	bool = True   ,       **snake_case__:	Optional[Any]   ,       )  ->		None:
  
  
         """simple docstring"""
  
  
  
         super().__init__(**snake_case__	)
         _lowercase     =	size if size is not None else {'height': 346, 'width': 346}
         _lowercase     =	get_size_dict(snake_case__	)
         _lowercase     =	crop_size if crop_size is not None else {'height': 289, 'width': 289}
         _lowercase     =	get_size_dict(snake_case__   ,       param_name='crop_size'	)
  
         _lowercase     =	do_resize
         _lowercase     =	size
         _lowercase     =	resample
         _lowercase     =	do_center_crop
         _lowercase     =	crop_size
         _lowercase     =	do_rescale
         _lowercase     =	rescale_factor
         _lowercase     =	rescale_offset
         _lowercase     =	do_normalize
         _lowercase     =	image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
         _lowercase     =	image_std if image_std is not None else IMAGENET_STANDARD_STD
         _lowercase     =	include_top
  
     def 			SCREAMING_SNAKE_CASE__				(    self:	str   ,       snake_case__:	np.ndarray   ,       snake_case__:	Dict[str, int]   ,       snake_case__:	PILImageResampling = PIL.Image.NEAREST   ,       snake_case__:	Optional[Union[str, ChannelDimension]] = None   ,       **snake_case__:	Optional[int]   ,       )  ->		np.ndarray:
  
  
         """simple docstring"""
  
  
  
         _lowercase     =	get_size_dict(snake_case__	)
         if "height" not in size or "width" not in size:
             raise ValueError(f'''The size dictionary must have keys \'height\' and \'width\'. Got {size.keys()}'''	)
         return resize(
             snake_case__   ,       size=(size['height'], size['width'])   ,       resample=snake_case__   ,       data_format=snake_case__   ,       **snake_case__	)
  
     def 			SCREAMING_SNAKE_CASE__				(    self:	Optional[Any]   ,       snake_case__:	np.ndarray   ,       snake_case__:	Dict[str, int]   ,       snake_case__:	Optional[Union[str, ChannelDimension]] = None   ,       **snake_case__:	str   ,       )  ->		np.ndarray:
  
  
         """simple docstring"""
  
  
  
         _lowercase     =	get_size_dict(snake_case__	)
         if "height" not in size or "width" not in size:
             raise ValueError(f'''The size dictionary must have keys \'height\' and \'width\'. Got {size.keys()}'''	)
         return center_crop(snake_case__   ,       size=(size['height'], size['width'])   ,       data_format=snake_case__   ,       **snake_case__	)
  
     def 			SCREAMING_SNAKE_CASE__				(    self:	Optional[Any]   ,       snake_case__:	np.ndarray   ,       snake_case__:	Union[int, float]   ,       snake_case__:	bool = True   ,       snake_case__:	Optional[Union[str, ChannelDimension]] = None   ,       **snake_case__:	List[str]   ,       )  ->		Optional[int]:
  
  
         """simple docstring"""
  
  
  
         if offset:
             _lowercase     =	(image - 1_27.5) * scale
             if data_format is not None:
                 _lowercase     =	to_channel_dimension_format(snake_case__   ,       snake_case__	)
             _lowercase     =	rescaled_image.astype(np.floataa	)
         else:
             _lowercase     =	rescale(snake_case__   ,       scale=snake_case__   ,       data_format=snake_case__   ,       **snake_case__	)
         return rescaled_image
  
     def 			SCREAMING_SNAKE_CASE__				(    self:	Dict   ,       snake_case__:	np.ndarray   ,       snake_case__:	Union[float, List[float]]   ,       snake_case__:	Union[float, List[float]]   ,       snake_case__:	Optional[Union[str, ChannelDimension]] = None   ,       **snake_case__:	Any   ,       )  ->		np.ndarray:
  
  
         """simple docstring"""
  
  
  
         return normalize(snake_case__   ,       mean=snake_case__   ,       std=snake_case__   ,       data_format=snake_case__   ,       **snake_case__	)
  
     def 			SCREAMING_SNAKE_CASE__				(    self:	Optional[int]   ,       snake_case__:	ImageInput   ,       snake_case__:	bool = None   ,       snake_case__:	Dict[str, int] = None   ,       snake_case__:	Union[str, Any]=None   ,       snake_case__:	bool = None   ,       snake_case__:	Dict[str, int] = None   ,       snake_case__:	bool = None   ,       snake_case__:	float = None   ,       snake_case__:	bool = None   ,       snake_case__:	bool = None   ,       snake_case__:	Optional[Union[float, List[float]]] = None   ,       snake_case__:	Optional[Union[float, List[float]]] = None   ,       snake_case__:	bool = None   ,       snake_case__:	Optional[Union[str, TensorType]] = None   ,       snake_case__:	ChannelDimension = ChannelDimension.FIRST   ,       **snake_case__:	int   ,       )  ->		PIL.Image.Image:
  
  
         """simple docstring"""
  
  
  
         _lowercase     =	do_resize if do_resize is not None else self.do_resize
         _lowercase     =	resample if resample is not None else self.resample
         _lowercase     =	do_center_crop if do_center_crop is not None else self.do_center_crop
         _lowercase     =	do_rescale if do_rescale is not None else self.do_rescale
         _lowercase     =	rescale_factor if rescale_factor is not None else self.rescale_factor
         _lowercase     =	rescale_offset if rescale_offset is not None else self.rescale_offset
         _lowercase     =	do_normalize if do_normalize is not None else self.do_normalize
         _lowercase     =	image_mean if image_mean is not None else self.image_mean
         _lowercase     =	image_std if image_std is not None else self.image_std
         _lowercase     =	include_top if include_top is not None else self.include_top
  
         _lowercase     =	size if size is not None else self.size
         _lowercase     =	get_size_dict(snake_case__	)
         _lowercase     =	crop_size if crop_size is not None else self.crop_size
         _lowercase     =	get_size_dict(snake_case__   ,       param_name='crop_size'	)
  
         _lowercase     =	make_list_of_images(snake_case__	)
  
         if not valid_images(snake_case__	):
             raise ValueError(
                 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '
                 'torch.Tensor, tf.Tensor or jax.ndarray.'	)
  
         if do_resize and size is None or resample is None:
             raise ValueError('Size and resample must be specified if do_resize is True.'	)
  
         if do_center_crop and crop_size is None:
             raise ValueError('Crop size must be specified if do_center_crop is True.'	)
  
         if do_rescale and rescale_factor is None:
             raise ValueError('Rescale factor must be specified if do_rescale is True.'	)
  
         if do_normalize and (image_mean is None or image_std is None):
             raise ValueError('Image mean and std must be specified if do_normalize is True.'	)
  
         # All transformations expect numpy arrays.
         _lowercase     =	[to_numpy_array(snake_case__	) for image in images]
  
         if do_resize:
             _lowercase     =	[self.resize(image=snake_case__   ,       size=snake_case__   ,       resample=snake_case__	) for image in images]
  
         if do_center_crop:
             _lowercase     =	[self.center_crop(image=snake_case__   ,       size=snake_case__	) for image in images]
  
         if do_rescale:
             _lowercase     =	[self.rescale(image=snake_case__   ,       scale=snake_case__   ,       offset=snake_case__	) for image in images]
  
         if do_normalize:
             _lowercase     =	[self.normalize(image=snake_case__   ,       mean=snake_case__   ,       std=snake_case__	) for image in images]
  
         if include_top:
             _lowercase     =	[self.normalize(image=snake_case__   ,       mean=[0, 0, 0]   ,       std=snake_case__	) for image in images]
  
         _lowercase     =	[to_channel_dimension_format(snake_case__   ,       snake_case__	) for image in images]
  
         _lowercase     =	{'pixel_values': images}
         return BatchFeature(data=snake_case__   ,       tensor_type=snake_case__	)
  