"""simple docstring"""







import unittest

import numpy as np
import torch
from torch import nn
from transformers import (
    CLIPImageProcessor,
    CLIPTextConfig,
    CLIPTextModelWithProjection,
    CLIPTokenizer,
    CLIPVisionConfig,
    CLIPVisionModelWithProjection,
)

from diffusers import KandinskyVaaPriorPipeline, PriorTransformer, UnCLIPScheduler
from diffusers.utils import torch_device
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps

from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()

class 		UpperCamelCase      (   _lowercase				,     unittest.TestCase						):
				UpperCAmelCase    :				Optional[int]   =		KandinskyVaaPriorPipeline
				UpperCAmelCase    :				Any   =		["""prompt"""]
				UpperCAmelCase    :				Tuple   =		["""prompt""", """negative_prompt"""]
				UpperCAmelCase    :				Tuple   =		[
				    """num_images_per_prompt""",
				    """generator""",
				    """num_inference_steps""",
				    """latents""",
				    """negative_prompt""",
				    """guidance_scale""",
				    """output_type""",
				    """return_dict""",
				]
				UpperCAmelCase    :				int   =		False



				@property
				def  _lowercase					(self    :				int)   ->     int:
					return 32



				@property
				def  _lowercase					(self    :				str)   ->     Any:
					return 32



				@property
				def  _lowercase					(self    :				Union[str, Any])   ->     List[str]:
					return self.time_input_dim



				@property
				def  _lowercase					(self    :				str)   ->     Dict:
					return self.time_input_dim * 4



				@property
				def  _lowercase					(self    :				Tuple)   ->     Dict:
					return 1_00



				@property
				def  _lowercase					(self    :				List[str])   ->     str:
					__snake_case      :							Optional[int]						=			CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip')
					return tokenizer



				@property
				def  _lowercase					(self    :				List[str])   ->     Dict:
					torch.manual_seed(0)
					__snake_case      :							List[str]						=			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=10_00     ,  )
					return CLIPTextModelWithProjection(__UpperCamelCase)



				@property
				def  _lowercase					(self    :				Union[str, Any])   ->     Any:
					torch.manual_seed(0)

					__snake_case      :							List[Any]						=			{
					    'num_attention_heads': 2,
					    'attention_head_dim': 12,
					    'embedding_dim': self.text_embedder_hidden_size,
					    'num_layers': 1,
					}

					__snake_case      :							Any						=			PriorTransformer(**__UpperCamelCase)
					# 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
					__snake_case      :							Optional[int]						=			nn.Parameter(torch.ones(model.clip_std.shape))
					return model



				@property
				def  _lowercase					(self    :				List[Any])   ->     Union[str, Any]:
					torch.manual_seed(0)
					__snake_case      :							str						=			CLIPVisionConfig(
					    hidden_size=self.text_embedder_hidden_size     ,  image_size=2_24     ,  projection_dim=self.text_embedder_hidden_size     ,  intermediate_size=37     ,  num_attention_heads=4     ,  num_channels=3     ,  num_hidden_layers=5     ,  patch_size=14     ,  )

					__snake_case      :							Tuple						=			CLIPVisionModelWithProjection(__UpperCamelCase)
					return model



				@property
				def  _lowercase					(self    :				int)   ->     Any:
					__snake_case      :							Any						=			CLIPImageProcessor(
					    crop_size=2_24     ,  do_center_crop=__UpperCamelCase     ,  do_normalize=__UpperCamelCase     ,  do_resize=__UpperCamelCase     ,  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=2_24     ,  )

					return image_processor



				def  _lowercase					(self    :				Optional[int])   ->     List[Any]:
					__snake_case      :							str						=			self.dummy_prior
					__snake_case      :							int						=			self.dummy_image_encoder
					__snake_case      :							Any						=			self.dummy_text_encoder
					__snake_case      :							Optional[int]						=			self.dummy_tokenizer
					__snake_case      :							str						=			self.dummy_image_processor

					__snake_case      :							int						=			UnCLIPScheduler(
					    variance_type='fixed_small_log'     ,  prediction_type='sample'     ,  num_train_timesteps=10_00     ,  clip_sample=__UpperCamelCase     ,  clip_sample_range=10.0     ,  )

					__snake_case      :							Union[str, Any]						=			{
					    'prior': prior,
					    'image_encoder': image_encoder,
					    'text_encoder': text_encoder,
					    'tokenizer': tokenizer,
					    'scheduler': scheduler,
					    'image_processor': image_processor,
					}

					return components



				def  _lowercase					(self    :				Tuple     ,  _A    :				Tuple     ,  _A    :				Optional[int]=0)   ->     Tuple:
					if str(__UpperCamelCase).startswith('mps'):
						__snake_case      :							List[Any]						=			torch.manual_seed(__UpperCamelCase)
					else:
						__snake_case      :							Tuple						=			torch.Generator(device=__UpperCamelCase).manual_seed(__UpperCamelCase)
					__snake_case      :							str						=			{
					    'prompt': 'horse',
					    'generator': generator,
					    'guidance_scale': 4.0,
					    'num_inference_steps': 2,
					    'output_type': 'np',
					}
					return inputs



				def  _lowercase					(self    :				List[Any])   ->     Tuple:
					__snake_case      :							Tuple						=			'cpu'

					__snake_case      :							List[Any]						=			self.get_dummy_components()

					__snake_case      :							Tuple						=			self.pipeline_class(**__UpperCamelCase)
					__snake_case      :							str						=			pipe.to(__UpperCamelCase)

					pipe.set_progress_bar_config(disable=__UpperCamelCase)

					__snake_case      :							List[str]						=			pipe(**self.get_dummy_inputs(__UpperCamelCase))
					__snake_case      :							Tuple						=			output.image_embeds

					__snake_case      :							Optional[Any]						=			pipe(
					    **self.get_dummy_inputs(__UpperCamelCase)     ,  return_dict=__UpperCamelCase     ,  )[0]

					__snake_case      :							Dict						=			image[0, -10:]
					__snake_case      :							Dict						=			image_from_tuple[0, -10:]

					assert image.shape == (1, 32)

					__snake_case      :							str						=			np.array(
					    [-0.0_532, 1.7_120, 0.3_656, -1.0_852, -0.8_946, -1.1_756, 0.4_348, 0.2_482, 0.5_146, -0.1_156])

					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  _lowercase					(self    :				int)   ->     Optional[int]:
					__snake_case      :							Any						=			torch_device == 'cpu'
					__snake_case      :							Optional[Any]						=			True
					__snake_case      :							Optional[int]						=			False

					self._test_inference_batch_single_identical(
					    test_max_difference=__UpperCamelCase     ,  relax_max_difference=__UpperCamelCase     ,  test_mean_pixel_difference=__UpperCamelCase     ,  )






				@skip_mps
				def  _lowercase					(self    :				Any)   ->     Optional[int]:
					__snake_case      :							List[Any]						=			torch_device == 'cpu'
					__snake_case      :							Dict						=			False

					self._test_attention_slicing_forward_pass(
					    test_max_difference=__UpperCamelCase     ,  test_mean_pixel_difference=__UpperCamelCase     ,  )






"""simple docstring"""







import gc
import tempfile
import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionPipeline
from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device


_a					:					int=			False

class 		UpperCamelCase      (   unittest.TestCase						):
				pass







@nightly
@require_torch_gpu
class 		UpperCamelCase      (   unittest.TestCase						):



				def  _lowercase					(self    :				Optional[Any])   ->     Tuple:
					# clean up the VRAM after each test
					super().tearDown()
					gc.collect()
					torch.cuda.empty_cache()



				def  _lowercase					(self    :				int)   ->     Tuple:
					__snake_case      :							str						=			VersatileDiffusionPipeline.from_pretrained('shi-labs/versatile-diffusion'     ,  torch_dtype=torch.floataa)
					pipe.to(_A)
					pipe.set_progress_bar_config(disable=_A)

					__snake_case      :							int						=			load_image(
					    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg')

					__snake_case      :							List[Any]						=			torch.manual_seed(0)
					__snake_case      :							Optional[int]						=			pipe.dual_guided(
					    prompt='first prompt'     ,  image=_A     ,  text_to_image_strength=0.75     ,  generator=_A     ,  guidance_scale=7.5     ,  num_inference_steps=2     ,  output_type='numpy'     ,  ).images

					with tempfile.TemporaryDirectory() as tmpdirname:
						pipe.save_pretrained(_A)
						__snake_case      :							Optional[Any]						=			VersatileDiffusionPipeline.from_pretrained(_A     ,  torch_dtype=torch.floataa)
					pipe.to(_A)
					pipe.set_progress_bar_config(disable=_A)

					__snake_case      :							Tuple						=			generator.manual_seed(0)
					__snake_case      :							int						=			pipe.dual_guided(
					    prompt='first prompt'     ,  image=_A     ,  text_to_image_strength=0.75     ,  generator=_A     ,  guidance_scale=7.5     ,  num_inference_steps=2     ,  output_type='numpy'     ,  ).images

					assert np.abs(image - new_image).sum() < 1E-5, "Models don't have the same forward pass"






				def  _lowercase					(self    :				Optional[Any])   ->     Optional[int]:
					__snake_case      :							Optional[Any]						=			VersatileDiffusionPipeline.from_pretrained('shi-labs/versatile-diffusion'     ,  torch_dtype=torch.floataa)
					pipe.to(_A)
					pipe.set_progress_bar_config(disable=_A)

					__snake_case      :							Tuple						=			'cyberpunk 2077'
					__snake_case      :							int						=			load_image(
					    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg')
					__snake_case      :							str						=			torch.manual_seed(0)
					__snake_case      :							Union[str, Any]						=			pipe.dual_guided(
					    prompt=_A     ,  image=_A     ,  text_to_image_strength=0.75     ,  generator=_A     ,  guidance_scale=7.5     ,  num_inference_steps=50     ,  output_type='numpy'     ,  ).images

					__snake_case      :							Optional[Any]						=			image[0, 2_53:2_56, 2_53:2_56, -1]

					assert image.shape == (1, 5_12, 5_12, 3)
					__snake_case      :							Tuple						=			np.array([0.1_448, 0.1_619, 0.1_741, 0.1_086, 0.1_147, 0.1_128, 0.1_199, 0.1_165, 0.1_001])

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

					__snake_case      :							List[str]						=			'A painting of a squirrel eating a burger '
					__snake_case      :							str						=			torch.manual_seed(0)
					__snake_case      :							str						=			pipe.text_to_image(
					    prompt=_A     ,  generator=_A     ,  guidance_scale=7.5     ,  num_inference_steps=50     ,  output_type='numpy').images

					__snake_case      :							str						=			image[0, 2_53:2_56, 2_53:2_56, -1]

					assert image.shape == (1, 5_12, 5_12, 3)
					__snake_case      :							Any						=			np.array([0.3_367, 0.3_169, 0.2_656, 0.3_870, 0.4_790, 0.3_796, 0.4_009, 0.4_878, 0.4_778])

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

					__snake_case      :							List[str]						=			pipe.image_variation(_A     ,  generator=_A     ,  output_type='numpy').images

					__snake_case      :							Dict						=			image[0, 2_53:2_56, 2_53:2_56, -1]

					assert image.shape == (1, 5_12, 5_12, 3)
					__snake_case      :							List[Any]						=			np.array([0.3_076, 0.3_123, 0.3_284, 0.3_782, 0.3_770, 0.3_894, 0.4_297, 0.4_331, 0.4_456])

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





