



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        snake_case__    (A__ ,     unittest.TestCase		):







						"""simple docstring"""




						__lowerCAmelCase					:Optional[int]      =					KandinskyVaaPriorPipeline
						__lowerCAmelCase					:List[Any]      =					["prompt"]
						__lowerCAmelCase					:int      =					["prompt", "negative_prompt"]
						__lowerCAmelCase					:Tuple      =					[
						    "num_images_per_prompt",
						    "generator",
						    "num_inference_steps",
						    "latents",
						    "negative_prompt",
						    "guidance_scale",
						    "output_type",
						    "return_dict",
						]
						__lowerCAmelCase					:List[str]      =					False

						@property
						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				Union[str, Any]:
									"""simple docstring"""




									return 3_2

						@property
						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				Any:
									"""simple docstring"""




									return 3_2

						@property
						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				str:
									"""simple docstring"""




									return self.time_input_dim

						@property
						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				List[Any]:
									"""simple docstring"""




									return self.time_input_dim * 4

						@property
						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				str:
									"""simple docstring"""




									return 1_0_0

						@property
						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				Optional[Any]:
									"""simple docstring"""




									a__       :						Union[str, Any]							=  CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""  )
									return tokenizer

						@property
						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				Dict:
									"""simple docstring"""




									torch.manual_seed(0  )
									a__       :						Any							=  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=3_7 ,       layer_norm_eps=1E-05 ,       num_attention_heads=4 ,       num_hidden_layers=5 ,       pad_token_id=1 ,       vocab_size=1_0_0_0 ,       )
									return CLIPTextModelWithProjection(__lowercase  )

						@property
						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				Dict:
									"""simple docstring"""




									torch.manual_seed(0  )

									a__       :						Dict							=  {
									    """num_attention_heads""": 2,
									    """attention_head_dim""": 1_2,
									    """embedding_dim""": self.text_embedder_hidden_size,
									    """num_layers""": 1,
									}

									a__       :						List[str]							=  PriorTransformer(**__lowercase  )
									# 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
									a__       :						List[str]							=  nn.Parameter(torch.ones(model.clip_std.shape  )  )
									return model

						@property
						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				Optional[int]:
									"""simple docstring"""




									torch.manual_seed(0  )
									a__       :						Optional[int]							=  CLIPVisionConfig(
									    hidden_size=self.text_embedder_hidden_size ,       image_size=2_2_4 ,       projection_dim=self.text_embedder_hidden_size ,       intermediate_size=3_7 ,       num_attention_heads=4 ,       num_channels=3 ,       num_hidden_layers=5 ,       patch_size=1_4 ,       )

									a__       :						Optional[int]							=  CLIPVisionModelWithProjection(__lowercase  )
									return model

						@property
						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				List[str]:
									"""simple docstring"""




									a__       :						List[str]							=  CLIPImageProcessor(
									    crop_size=2_2_4 ,       do_center_crop=__lowercase ,       do_normalize=__lowercase ,       do_resize=__lowercase ,       image_mean=[0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3] ,       image_std=[0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1] ,       resample=3 ,       size=2_2_4 ,       )

									return image_processor

						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				List[str]:
									"""simple docstring"""




									a__       :						Dict							=  self.dummy_prior
									a__       :						Any							=  self.dummy_image_encoder
									a__       :						Any							=  self.dummy_text_encoder
									a__       :						Dict							=  self.dummy_tokenizer
									a__       :						int							=  self.dummy_image_processor

									a__       :						Tuple							=  UnCLIPScheduler(
									    variance_type="""fixed_small_log""" ,       prediction_type="""sample""" ,       num_train_timesteps=1_0_0_0 ,       clip_sample=__lowercase ,       clip_sample_range=1_0.0 ,       )

									a__       :						Any							=  {
									    """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 ,       __lowercase ,       __lowercase=0  ) ->				Any:
									"""simple docstring"""




									if str(__lowercase  ).startswith("""mps"""  ):
												a__       :						str							=  torch.manual_seed(__lowercase  )
									else:
												a__       :						int							=  torch.Generator(device=__lowercase  ).manual_seed(__lowercase  )
									a__       :						List[Any]							=  {
									    """prompt""": """horse""",
									    """generator""": generator,
									    """guidance_scale""": 4.0,
									    """num_inference_steps""": 2,
									    """output_type""": """np""",
									}
									return inputs

						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				Union[str, Any]:
									"""simple docstring"""




									a__       :						str							=  """cpu"""

									a__       :						Union[str, Any]							=  self.get_dummy_components()

									a__       :						Optional[Any]							=  self.pipeline_class(**__lowercase  )
									a__       :						Dict							=  pipe.to(__lowercase  )

									pipe.set_progress_bar_config(disable=__lowercase  )

									a__       :						Optional[int]							=  pipe(**self.get_dummy_inputs(__lowercase  )  )
									a__       :						Tuple							=  output.image_embeds

									a__       :						Dict							=  pipe(
									    **self.get_dummy_inputs(__lowercase  ) ,       return_dict=__lowercase ,       )[0]

									a__       :						Optional[int]							=  image[0, -1_0:]
									a__       :						Union[str, Any]							=  image_from_tuple[0, -1_0:]

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

									a__       :						Union[str, Any]							=  np.array(
									    [-0.0_5_3_2, 1.7_1_2_0, 0.3_6_5_6, -1.0_8_5_2, -0.8_9_4_6, -1.1_7_5_6, 0.4_3_4_8, 0.2_4_8_2, 0.5_1_4_6, -0.1_1_5_6]  )

									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  ) ->				Dict:
									"""simple docstring"""




									a__       :						Tuple							=  torch_device == """cpu"""
									a__       :						Optional[Any]							=  True
									a__       :						str							=  False

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

						@skip_mps
						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				Dict:
									"""simple docstring"""




									a__       :						List[Any]							=  torch_device == """cpu"""
									a__       :						Union[str, Any]							=  False

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





import asyncio
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from distutils.util import strtobool
from functools import partial
from pathlib import Path
from typing import List, Union
from unittest import mock

import torch

from ..state import AcceleratorState, PartialState
from ..utils import (
    gather,
    is_bnb_available,
    is_comet_ml_available,
    is_datasets_available,
    is_deepspeed_available,
    is_mps_available,
    is_safetensors_available,
    is_tensorboard_available,
    is_torch_version,
    is_tpu_available,
    is_transformers_available,
    is_wandb_available,
    is_xpu_available,
)

def      lowerCAmelCase_					(  _lowercase    :       Union[str, Any]						,       _lowercase    :       Dict=False)							->	Any:







			"""simple docstring"""
			try:
						a__       :						str							=  os.environ[key]
			except KeyError:
						# KEY isn't set, default to `default`.
						a__       :						Optional[int]							=  default
			else:
						# KEY is set, convert it to True or False.
						try:
									a__       :						Optional[int]							=  strtobool(_lowercase)
						except ValueError:
									# More values are supported, but let's keep the message simple.
									raise ValueError(F'''If set, {key} must be yes or no.''')
			return _value


_lowercase		:				Dict      		=parse_flag_from_env("RUN_SLOW", default=False)

def      lowerCAmelCase_					(  _lowercase    :       Any)							->	str:







			"""simple docstring"""
			return unittest.skip("""Test was skipped""")(_lowercase)

def      lowerCAmelCase_					(  _lowercase    :       str)							->	List[str]:







			"""simple docstring"""
			return unittest.skipUnless(_run_slow_tests						,       """test is slow""")(_lowercase)

def      lowerCAmelCase_					(  _lowercase    :       List[Any])							->	Union[str, Any]:







			"""simple docstring"""
			return unittest.skipUnless(not torch.cuda.is_available()						,       """test requires only a CPU""")(_lowercase)

def      lowerCAmelCase_					(  _lowercase    :       List[Any])							->	List[Any]:







			"""simple docstring"""
			return unittest.skipUnless(torch.cuda.is_available()						,       """test requires a GPU""")(_lowercase)

def      lowerCAmelCase_					(  _lowercase    :       Optional[int])							->	Dict:







			"""simple docstring"""
			return unittest.skipUnless(is_xpu_available()						,       """test requires a XPU""")(_lowercase)

def      lowerCAmelCase_					(  _lowercase    :       Tuple)							->	List[str]:







			"""simple docstring"""
			return unittest.skipUnless(is_mps_available()						,       """test requires a `mps` backend support in `torch`""")(_lowercase)

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







			"""simple docstring"""
			return unittest.skipUnless(
			    is_transformers_available() and is_datasets_available()						,       """test requires the Hugging Face suite""")(_lowercase)

def      lowerCAmelCase_					(  _lowercase    :       Tuple)							->	Any:







			"""simple docstring"""
			return unittest.skipUnless(is_bnb_available()						,       """test requires the bitsandbytes library""")(_lowercase)

def      lowerCAmelCase_					(  _lowercase    :       Union[str, Any])							->	List[str]:







			"""simple docstring"""
			return unittest.skipUnless(is_tpu_available()						,       """test requires TPU""")(_lowercase)

def      lowerCAmelCase_					(  _lowercase    :       str)							->	int:







			"""simple docstring"""
			return unittest.skipUnless(torch.cuda.device_count() == 1						,       """test requires a GPU""")(_lowercase)

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







			"""simple docstring"""
			return unittest.skipUnless(torch.xpu.device_count() == 1						,       """test requires a XPU""")(_lowercase)

def      lowerCAmelCase_					(  _lowercase    :       Union[str, Any])							->	Union[str, Any]:







			"""simple docstring"""
			return unittest.skipUnless(torch.cuda.device_count() > 1						,       """test requires multiple GPUs""")(_lowercase)

def      lowerCAmelCase_					(  _lowercase    :       int)							->	Tuple:







			"""simple docstring"""
			return unittest.skipUnless(torch.xpu.device_count() > 1						,       """test requires multiple XPUs""")(_lowercase)

def      lowerCAmelCase_					(  _lowercase    :       int)							->	Optional[Any]:







			"""simple docstring"""
			return unittest.skipUnless(is_safetensors_available()						,       """test requires safetensors""")(_lowercase)

def      lowerCAmelCase_					(  _lowercase    :       Optional[int])							->	List[str]:







			"""simple docstring"""
			return unittest.skipUnless(is_deepspeed_available()						,       """test requires DeepSpeed""")(_lowercase)

def      lowerCAmelCase_					(  _lowercase    :       Union[str, Any])							->	Optional[Any]:







			"""simple docstring"""
			return unittest.skipUnless(is_torch_version(""">="""						,       """1.12.0""")						,       """test requires torch version >= 1.12.0""")(_lowercase)

def      lowerCAmelCase_					(  _lowercase    :       Any=None						,       _lowercase    :       List[str]=None)							->	Dict:







			"""simple docstring"""
			if test_case is None:
						return partial(_lowercase						,       version=_lowercase)
			return unittest.skipUnless(is_torch_version(""">="""						,       _lowercase)						,       F'''test requires torch version >= {version}''')(_lowercase)

def      lowerCAmelCase_					(  _lowercase    :       Any)							->	int:







			"""simple docstring"""
			return unittest.skipUnless(is_tensorboard_available()						,       """test requires Tensorboard""")(_lowercase)

def      lowerCAmelCase_					(  _lowercase    :       str)							->	Union[str, Any]:







			"""simple docstring"""
			return unittest.skipUnless(is_wandb_available()						,       """test requires wandb""")(_lowercase)

def      lowerCAmelCase_					(  _lowercase    :       Optional[int])							->	Union[str, Any]:







			"""simple docstring"""
			return unittest.skipUnless(is_comet_ml_available()						,       """test requires comet_ml""")(_lowercase)


_lowercase		:				List[str]      		=(
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)

def      lowerCAmelCase_					(  _lowercase    :       Optional[int])							->	Union[str, Any]:







			"""simple docstring"""
			return unittest.skipUnless(
			    _atleast_one_tracker_available						,       """test requires at least one tracker to be available and for `comet_ml` to not be installed"""						,       )(_lowercase)

class        snake_case__    (unittest.TestCase		):







						"""simple docstring"""




						__lowerCAmelCase					:Optional[Any]      =					True

						@classmethod
						def 							SCREAMING_SNAKE_CASE__(       cls  ) ->				Optional[int]:
									"""simple docstring"""




									a__       :						Tuple							=  tempfile.mkdtemp()

						@classmethod
						def 							SCREAMING_SNAKE_CASE__(       cls  ) ->				Dict:
									"""simple docstring"""




									if os.path.exists(cls.tmpdir  ):
												shutil.rmtree(cls.tmpdir  )

						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				List[Any]:
									"""simple docstring"""




									if self.clear_on_setup:
												for path in Path(self.tmpdir  ).glob("""**/*"""  ):
															if path.is_file():
																		path.unlink()
															elif path.is_dir():
																		shutil.rmtree(__lowercase  )




class        snake_case__    (unittest.TestCase		):







						"""simple docstring"""




						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				Union[str, Any]:
									"""simple docstring"""




									super().tearDown()
									# Reset the state of the AcceleratorState singleton.
									AcceleratorState._reset_state()
									PartialState._reset_state()




class        snake_case__    (unittest.TestCase		):







						"""simple docstring"""




						def 							SCREAMING_SNAKE_CASE__(       self ,       __lowercase  ) ->				Union[str, Any]:
									"""simple docstring"""




									a__       :						Tuple							=  mocks if isinstance(__lowercase ,       (tuple, list)  ) else [mocks]
									for m in self.mocks:
												m.start()
												self.addCleanup(m.stop  )




def      lowerCAmelCase_					(  _lowercase    :       Optional[int])							->	List[Any]:







			"""simple docstring"""
			a__       :						Tuple							=  AcceleratorState()
			a__       :						List[str]							=  tensor[None].clone().to(state.device)
			a__       :						Any							=  gather(_lowercase).cpu()
			a__       :						Optional[Any]							=  tensor[0].cpu()
			for i in range(tensors.shape[0]):
						if not torch.equal(tensors[i]						,       _lowercase):
									return False
			return True

class        snake_case__    :







						"""simple docstring"""




						def __init__(       self ,       __lowercase ,       __lowercase ,       __lowercase  ) ->				Any:
									"""simple docstring"""




									a__       :						Any							=  returncode
									a__       :						List[Any]							=  stdout
									a__       :						Any							=  stderr




async def      lowerCAmelCase_					(  _lowercase    :       str						,       _lowercase    :       str)							->	List[Any]:







			"""simple docstring"""
			while True:
						a__       :						str							=  await stream.readline()
						if line:
									callback(_lowercase)
						else:
									break

async def      lowerCAmelCase_					(  _lowercase    :       Any						,       _lowercase    :       Union[str, Any]=None						,       _lowercase    :       List[str]=None						,       _lowercase    :       Tuple=None						,       _lowercase    :       Optional[Any]=False						,       _lowercase    :       Dict=False)							->	_RunOutput:







			"""simple docstring"""
			if echo:
						print("""\nRunning: """						,       """ """.join(_lowercase))

			a__       :						int							=  await asyncio.create_subprocess_exec(
			    cmd[0]						,       *cmd[1:]						,       stdin=_lowercase						,       stdout=asyncio.subprocess.PIPE						,       stderr=asyncio.subprocess.PIPE						,       env=_lowercase						,       )

			# note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
			# https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
			#
			# If it starts hanging, will need to switch to the following code. The problem is that no data
			# will be seen until it's done and if it hangs for example there will be no debug info.
			# out, err = await p.communicate()
			# return _RunOutput(p.returncode, out, err)

			a__       :						int							=  []
			a__       :						Optional[int]							=  []

			def tee(_lowercase    :       List[str]						,       _lowercase    :       Optional[int]						,       _lowercase    :       Any						,       _lowercase    :       Optional[Any]=""):
						a__       :						int							=  line.decode("""utf-8""").rstrip()
						sink.append(_lowercase)
						if not quiet:
									print(_lowercase						,       _lowercase						,       file=_lowercase)

    # XXX: the timeout doesn't seem to make any difference here
			await asyncio.wait(
			    [
			        asyncio.create_task(_read_stream(p.stdout						,       lambda _lowercase: tee(_lowercase						,       _lowercase						,       sys.stdout						,       label="""stdout:"""))),
			        asyncio.create_task(_read_stream(p.stderr						,       lambda _lowercase: tee(_lowercase						,       _lowercase						,       sys.stderr						,       label="""stderr:"""))),
			    ]						,       timeout=_lowercase						,       )
			return _RunOutput(await p.wait()						,       _lowercase						,       _lowercase)

def      lowerCAmelCase_					(  _lowercase    :       Optional[int]						,       _lowercase    :       Optional[int]=None						,       _lowercase    :       Tuple=None						,       _lowercase    :       Any=180						,       _lowercase    :       List[Any]=False						,       _lowercase    :       Dict=True)							->	_RunOutput:







			"""simple docstring"""
			a__       :						Any							=  asyncio.get_event_loop()
			a__       :						List[Any]							=  loop.run_until_complete(
			    _stream_subprocess(_lowercase						,       env=_lowercase						,       stdin=_lowercase						,       timeout=_lowercase						,       quiet=_lowercase						,       echo=_lowercase))

			a__       :						Optional[int]							=  """ """.join(_lowercase)
			if result.returncode > 0:
						a__       :						List[Any]							=  """\n""".join(result.stderr)
						raise RuntimeError(
						    F'''\'{cmd_str}\' failed with returncode {result.returncode}\n\n'''
						    F'''The combined stderr from workers follows:\n{stderr}''')

			return result

class        snake_case__    (A__		):







						"""simple docstring"""




						pass




def      lowerCAmelCase_					(  _lowercase    :       List[str]						,       _lowercase    :       Optional[int]=False)							->	Dict:







			"""simple docstring"""
			try:
						a__       :						List[Any]							=  subprocess.check_output(_lowercase						,       stderr=subprocess.STDOUT)
						if return_stdout:
									if hasattr(_lowercase						,       """decode"""):
												a__       :						Tuple							=  output.decode("""utf-8""")
									return output
			except subprocess.CalledProcessError as e:
						raise SubprocessCallException(
						    F'''Command `{' '.join(_lowercase)}` failed with the following error:\n\n{e.output.decode()}''') from e




