import csv
import json
import logging
import os
import re
import subprocess
import tempfile
import unittest
import zipfile
from pathlib import Path
from typing import Optional
from unittest import mock

import torch

# We use TF to parse the logs
from accelerate import Accelerator
from accelerate.test_utils.testing import (
    MockingTestCase,
    TempDirTestCase,
    require_comet_ml,
    require_tensorboard,
    require_wandb,
    skip,
)
from accelerate.tracking import CometMLTracker, GeneralTracker
from accelerate.utils import ProjectConfiguration, is_comet_ml_available, is_tensorboard_available


if is_comet_ml_available():
				from comet_ml import OfflineExperiment

if is_tensorboard_available():
				import struct

				import tensorboard.compat.proto.event_pba as event_pba

lowerCAmelCase__	:  Dict						=  logging.getLogger(__name__)





@require_tensorboard
class 					__snake_case    (     unittest.TestCase      ):




					def      __a     (  self						)	->    Optional[Any]:



									'''simple docstring'''







									snake_case__   :      Union[str, Any]   				= 'test_project_with_config'
									with tempfile.TemporaryDirectory() as dirpath:
													snake_case__   :      Union[str, Any]   				= Accelerator(log_with='tensorboard'       ,			project_dir=__lowerCAmelCase						)
													snake_case__   :      Dict   				= {'num_iterations': 12, 'learning_rate': 1E-2, 'some_boolean': False, 'some_string': 'some_value'}
													accelerator.init_trackers(__lowerCAmelCase       ,			__lowerCAmelCase						)
													accelerator.end_training()
													for child in Path(F"""{dirpath}/{project_name}"""						).glob('*/**'						):
																	snake_case__   :      List[str]   				= list(filter(lambda __UpperCamelCase						: x.is_file()       ,			child.iterdir()						)						)[0]
													self.assertNotEqual(str(__lowerCAmelCase						)       ,			''						)




					def      __a     (  self						)	->    Union[str, Any]:



									'''simple docstring'''







									snake_case__   :      Optional[int]   				= 'test_project_with_log'
									with tempfile.TemporaryDirectory() as dirpath:
													snake_case__   :      Optional[Any]   				= Accelerator(log_with='tensorboard'       ,			project_dir=__lowerCAmelCase						)
													accelerator.init_trackers(__lowerCAmelCase						)
													snake_case__   :      Optional[Any]   				= {'total_loss': 0.1, 'iteration': 1, 'my_text': 'some_value'}
													accelerator.log(__lowerCAmelCase       ,			step=0						)
													accelerator.end_training()
													# Logged values are stored in the outermost-tfevents file and can be read in as a TFRecord
													# Names are randomly generated each time
													snake_case__   :      Optional[int]   				= list(filter(lambda __UpperCamelCase						: x.is_file()       ,			Path(F"""{dirpath}/{project_name}"""						).iterdir()						)						)[0]
													self.assertNotEqual(str(__lowerCAmelCase						)       ,			''						)




					def      __a     (  self						)	->    Any:



									'''simple docstring'''







									snake_case__   :      List[str]   				= 'test_project_with_log'
									with tempfile.TemporaryDirectory() as dirpath:
													snake_case__   :      Union[str, Any]   				= Accelerator(log_with='tensorboard'       ,			project_dir=__lowerCAmelCase						)
													accelerator.init_trackers(__lowerCAmelCase						)
													snake_case__   :      Union[str, Any]   				= {'tensor': torch.tensor(1						)}
													accelerator.log(__lowerCAmelCase       ,			step=0						)
													accelerator.end_training()
													# Logged values are stored in the outermost-tfevents file and can be read in as a TFRecord
													# Names are randomly generated each time
													snake_case__   :      Tuple   				= list(filter(lambda __UpperCamelCase						: x.is_file()       ,			Path(F"""{dirpath}/{project_name}"""						).iterdir()						)						)[0]
													# Reading implementation based on https://github.com/pytorch/pytorch/issues/45327#issuecomment-703757685
													with open(__lowerCAmelCase       ,			'rb'						) as f:
																	snake_case__   :      Optional[Any]   				= f.read()
													snake_case__   :      Tuple   				= False
													while data:
																	snake_case__   :      List[str]   				= struct.unpack('Q'       ,			data[:8]						)

																	snake_case__   :      str   				= data[12 : 12 + int(header[0]						)]  # 8+4
																	snake_case__   :      Tuple   				= data[12 + int(header[0]						) + 4 :]
																	snake_case__   :      Optional[int]   				= event_pba.Event()

																	event.ParseFromString(__lowerCAmelCase						)
																	if event.HasField('summary'						):
																					for value in event.summary.value:
																									if value.simple_value == 1.0 and value.tag == "tensor":
																													snake_case__   :      Union[str, Any]   				= True
													self.assertTrue(__lowerCAmelCase       ,			'Converted tensor was not found in the log file!'						)




					def      __a     (  self						)	->    List[str]:



									'''simple docstring'''







									with self.assertRaisesRegex(__lowerCAmelCase       ,			'Logging with `tensorboard` requires a `logging_dir`'						):
													snake_case__   :      Optional[int]   				= Accelerator(log_with='tensorboard'						)
									with tempfile.TemporaryDirectory() as dirpath:
													snake_case__   :      str   				= Accelerator(log_with='tensorboard'       ,			project_dir=__lowerCAmelCase						)




					def      __a     (  self						)	->    str:



									'''simple docstring'''







									snake_case__   :      str   				= ProjectConfiguration(total_limit=30						)
									with tempfile.TemporaryDirectory() as dirpath:
													snake_case__   :      List[Any]   				= Accelerator(log_with='tensorboard'       ,			project_dir=__lowerCAmelCase       ,			project_config=__lowerCAmelCase						)





@require_wandb
@mock.patch.dict(os.environ       ,{"""WANDB_MODE""": """offline"""}      )
class 					__snake_case    (     _lowercase       ,_lowercase      ):




					def      __a     (  self						)	->    List[str]:



									'''simple docstring'''







									super().setUp()
									# wandb let's us override where logs are stored to via the WANDB_DIR env var
									self.add_mocks(mock.patch.dict(os.environ       ,			{'WANDB_DIR': self.tmpdir}						)						)




					@staticmethod
					def      __a     (  __UpperCamelCase       ,			__UpperCamelCase       ,			__UpperCamelCase = True						)	->    Optional[Any]:



									'''simple docstring'''







									snake_case__   :      Dict   				= rF"""{section} ([\S\s]*?)\n\n"""
									if record:
													snake_case__   :      Optional[int]   				= rF"""Record: {pattern}"""
									snake_case__   :      List[Any]   				= re.findall(__lowerCAmelCase       ,			__lowerCAmelCase						)[0]
									# A config
									if section == "config" or section == "history":
													snake_case__   :      Any   				= re.findall(r'\"([a-zA-Z0-9_.,]+)'       ,			__lowerCAmelCase						)
													return {key: val for key, val in zip(cleaned_record[0::2]       ,			cleaned_record[1::2]						)}
									# Everything else
									else:
													return dict(re.findall(r'(\w+): \"([^\s]+)\"'       ,			__lowerCAmelCase						)						)




					@skip
					def      __a     (  self						)	->    List[str]:



									'''simple docstring'''







									snake_case__   :      Any   				= 'test_project_with_config'
									snake_case__   :      int   				= Accelerator(log_with='wandb'						)
									snake_case__   :      str   				= {'num_iterations': 12, 'learning_rate': 1E-2, 'some_boolean': False, 'some_string': 'some_value'}
									snake_case__   :      List[str]   				= {'wandb': {'tags': ['my_tag']}}
									accelerator.init_trackers(__lowerCAmelCase       ,			__lowerCAmelCase       ,			__lowerCAmelCase						)
									snake_case__   :      int   				= {'total_loss': 0.1, 'iteration': 1, 'my_text': 'some_value'}
									accelerator.log(__lowerCAmelCase       ,			step=0						)
									accelerator.end_training()
									# The latest offline log is stored at wandb/latest-run/*.wandb
									for child in Path(F"""{self.tmpdir}/wandb/latest-run"""						).glob('*'						):
													if child.is_file() and child.suffix == ".wandb":
																	snake_case__   :      Union[str, Any]   				= subprocess.check_output(
																	    ['wandb', 'sync', '--view', '--verbose', str(__lowerCAmelCase						)]       ,			env=os.environ.copy()						).decode('utf8'       ,			'ignore'						)
																	break

        # Check HPS through careful parsing and cleaning
									snake_case__   :      Optional[Any]   				= self.parse_log(__lowerCAmelCase       ,			'config'						)
									self.assertEqual(logged_items['num_iterations']       ,			'12'						)
									self.assertEqual(logged_items['learning_rate']       ,			'0.01'						)
									self.assertEqual(logged_items['some_boolean']       ,			'false'						)
									self.assertEqual(logged_items['some_string']       ,			'some_value'						)
									self.assertEqual(logged_items['some_string']       ,			'some_value'						)

									# Run tags
									snake_case__   :      str   				= self.parse_log(__lowerCAmelCase       ,			'run'       ,			__lowerCAmelCase						)
									self.assertEqual(logged_items['tags']       ,			'my_tag'						)

									# Actual logging
									snake_case__   :      List[Any]   				= self.parse_log(__lowerCAmelCase       ,			'history'						)
									self.assertEqual(logged_items['total_loss']       ,			'0.1'						)
									self.assertEqual(logged_items['iteration']       ,			'1'						)
									self.assertEqual(logged_items['my_text']       ,			'some_value'						)
									self.assertEqual(logged_items['_step']       ,			'0'						)




def 					UpperCamelCase__		(							self     ,					A__     ,					A__       )  ->   Optional[int]:
				snake_case__   :      Optional[Any]   				= run_name
				snake_case__   :      List[Any]   				= OfflineExperiment(project_name=_lowercase     ,					offline_directory=_lowercase       )
				logger.info(F"""Initialized offline CometML project {self.run_name}"""       )
				logger.info('Make sure to log any initial configurations with `self.store_init_configuration` before training!'       )





@require_comet_ml
@mock.patch.object(_lowercase       ,"""__init__"""       ,_lowercase      )
class 					__snake_case    (     unittest.TestCase      ):




					@staticmethod
					def      __a     (  __UpperCamelCase       ,			__UpperCamelCase       ,			__UpperCamelCase = False						)	->    List[Any]:



									'''simple docstring'''







									for log in log_list:
													snake_case__   :      Any   				= json.loads(__lowerCAmelCase						)['payload']
													if is_param and "param" in j.keys():
																	if j["param"]["paramName"] == key:
																					return j["param"]["paramValue"]
													if "log_other" in j.keys():
																	if j["log_other"]["key"] == key:
																					return j["log_other"]["val"]
													if "metric" in j.keys():
																	if j["metric"]["metricName"] == key:
																					return j["metric"]["metricValue"]




					def      __a     (  self						)	->    List[Any]:



									'''simple docstring'''







									with tempfile.TemporaryDirectory() as d:
													snake_case__   :      Tuple   				= CometMLTracker('test_project_with_config'       ,			__lowerCAmelCase						)
													snake_case__   :      Optional[Any]   				= Accelerator(log_with=__lowerCAmelCase						)
													snake_case__   :      Tuple   				= {'num_iterations': 12, 'learning_rate': 1E-2, 'some_boolean': False, 'some_string': 'some_value'}
													accelerator.init_trackers(__lowerCAmelCase       ,			__lowerCAmelCase						)
													accelerator.end_training()
													snake_case__   :      str   				= os.listdir(__lowerCAmelCase						)[0]  # Comet is nice, it's just a zip file here
													# We parse the raw logs
													snake_case__   :      Union[str, Any]   				= os.path.join(__lowerCAmelCase       ,			__lowerCAmelCase						)
													snake_case__   :      int   				= zipfile.ZipFile(__lowerCAmelCase       ,			'r'						)
													snake_case__   :      Union[str, Any]   				= archive.open('messages.json'						).read().decode('utf-8'						)
									snake_case__   :      List[Any]   				= log.split('\n'						)[:-1]
									self.assertEqual(self.get_value_from_key(__lowerCAmelCase       ,			'num_iterations'       ,			__lowerCAmelCase						)       ,			12						)
									self.assertEqual(self.get_value_from_key(__lowerCAmelCase       ,			'learning_rate'       ,			__lowerCAmelCase						)       ,			0.0_1						)
									self.assertEqual(self.get_value_from_key(__lowerCAmelCase       ,			'some_boolean'       ,			__lowerCAmelCase						)       ,			__lowerCAmelCase						)
									self.assertEqual(self.get_value_from_key(__lowerCAmelCase       ,			'some_string'       ,			__lowerCAmelCase						)       ,			'some_value'						)




					def      __a     (  self						)	->    Any:



									'''simple docstring'''







									with tempfile.TemporaryDirectory() as d:
													snake_case__   :      Optional[Any]   				= CometMLTracker('test_project_with_config'       ,			__lowerCAmelCase						)
													snake_case__   :      Optional[Any]   				= Accelerator(log_with=__lowerCAmelCase						)
													accelerator.init_trackers(__lowerCAmelCase						)
													snake_case__   :      Optional[Any]   				= {'total_loss': 0.1, 'iteration': 1, 'my_text': 'some_value'}
													accelerator.log(__lowerCAmelCase       ,			step=0						)
													accelerator.end_training()
													snake_case__   :      int   				= os.listdir(__lowerCAmelCase						)[0]  # Comet is nice, it's just a zip file here
													# We parse the raw logs
													snake_case__   :      Optional[int]   				= os.path.join(__lowerCAmelCase       ,			__lowerCAmelCase						)
													snake_case__   :      Optional[int]   				= zipfile.ZipFile(__lowerCAmelCase       ,			'r'						)
													snake_case__   :      int   				= archive.open('messages.json'						).read().decode('utf-8'						)
									snake_case__   :      List[Any]   				= log.split('\n'						)[:-1]
									self.assertEqual(self.get_value_from_key(__lowerCAmelCase       ,			'curr_step'       ,			__lowerCAmelCase						)       ,			0						)
									self.assertEqual(self.get_value_from_key(__lowerCAmelCase       ,			'total_loss'						)       ,			0.1						)
									self.assertEqual(self.get_value_from_key(__lowerCAmelCase       ,			'iteration'						)       ,			1						)
									self.assertEqual(self.get_value_from_key(__lowerCAmelCase       ,			'my_text'						)       ,			'some_value'						)





class 					__snake_case    (     _lowercase      ):
					__lowerCamelCase			   =  [
					    """total_loss""",
					    """iteration""",
					    """my_text""",
					    """learning_rate""",
					    """num_iterations""",
					    """some_boolean""",
					    """some_string""",
					]

					__lowerCamelCase			   =  """my_custom_tracker"""
					__lowerCamelCase			   =  False




					def __init__(  self       ,			__UpperCamelCase						)	->    str:



									'''simple docstring'''







									snake_case__   :      int   				= open(F"""{dir}/log.csv"""       ,			'w+'						)
									snake_case__   :      Union[str, Any]   				= csv.DictWriter(self.f       ,			fieldnames=self._col_names						)
									self.writer.writeheader()




					@property
					def      __a     (  self						)	->    Tuple:



									'''simple docstring'''







									return self.writer




					def      __a     (  self       ,			__UpperCamelCase						)	->    List[str]:



									'''simple docstring'''







									logger.info('Call init'						)
									self.writer.writerow(__lowerCAmelCase						)




					def      __a     (  self       ,			__UpperCamelCase       ,			__UpperCamelCase						)	->    Union[str, Any]:



									'''simple docstring'''







									logger.info('Call log'						)
									self.writer.writerow(__lowerCAmelCase						)




					def      __a     (  self						)	->    Tuple:



									'''simple docstring'''







									self.f.close()





class 					__snake_case    (     unittest.TestCase      ):




					def      __a     (  self						)	->    Dict:



									'''simple docstring'''







									with tempfile.TemporaryDirectory() as d:
													snake_case__   :      List[str]   				= MyCustomTracker(__lowerCAmelCase						)
													snake_case__   :      List[str]   				= Accelerator(log_with=__lowerCAmelCase						)
													snake_case__   :      List[str]   				= {'num_iterations': 12, 'learning_rate': 1E-2, 'some_boolean': False, 'some_string': 'some_value'}
													accelerator.init_trackers('Some name'       ,			__lowerCAmelCase						)
													accelerator.end_training()
													with open(F"""{d}/log.csv"""       ,			'r'						) as f:
																	snake_case__   :      Optional[Any]   				= csv.DictReader(__lowerCAmelCase						)
																	snake_case__   :      Union[str, Any]   				= next(__lowerCAmelCase						)
																	snake_case__   :      str   				= {
																	    'total_loss': '',
																	    'iteration': '',
																	    'my_text': '',
																	    'learning_rate': '0.01',
																	    'num_iterations': '12',
																	    'some_boolean': 'False',
																	    'some_string': 'some_value',
																	}
																	self.assertDictEqual(__lowerCAmelCase       ,			__lowerCAmelCase						)




					def      __a     (  self						)	->    Any:



									'''simple docstring'''







									with tempfile.TemporaryDirectory() as d:
													snake_case__   :      List[str]   				= MyCustomTracker(__lowerCAmelCase						)
													snake_case__   :      Any   				= Accelerator(log_with=__lowerCAmelCase						)
													accelerator.init_trackers('Some name'						)
													snake_case__   :      str   				= {'total_loss': 0.1, 'iteration': 1, 'my_text': 'some_value'}
													accelerator.log(__lowerCAmelCase       ,			step=0						)
													accelerator.end_training()
													with open(F"""{d}/log.csv"""       ,			'r'						) as f:
																	snake_case__   :      List[Any]   				= csv.DictReader(__lowerCAmelCase						)
																	snake_case__   :      int   				= next(__lowerCAmelCase						)
																	snake_case__   :      Optional[Any]   				= {
																	    'total_loss': '0.1',
																	    'iteration': '1',
																	    'my_text': 'some_value',
																	    'learning_rate': '',
																	    'num_iterations': '',
																	    'some_boolean': '',
																	    'some_string': '',
																	}
																	self.assertDictEqual(__lowerCAmelCase       ,			__lowerCAmelCase						)









import gc
import random
import unittest

import numpy as np
import torch
from transformers import XLMRobertaTokenizerFast

from diffusers import DDIMScheduler, KandinskyPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel
from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP
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 	_UpperCAmelCase						( _lowercase			,							unittest.TestCase       ):
					__A        = KandinskyPipeline
					__A        = [
					    "prompt",
					    "image_embeds",
					    "negative_image_embeds",
					]
					__A        = ["prompt", "negative_prompt", "image_embeds", "negative_image_embeds"]
					__A        = [
					    "generator",
					    "height",
					    "width",
					    "latents",
					    "guidance_scale",
					    "negative_prompt",
					    "num_inference_steps",
					    "return_dict",
					    "guidance_scale",
					    "num_images_per_prompt",
					    "output_type",
					    "return_dict",
					]
					__A        = False




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




					@property
					def 						snake_case_		(    self							)    ->	Optional[Any]:
							return 32




					@property
					def 						snake_case_		(    self							)    ->	List[Any]:
							return self.time_input_dim




					@property
					def 						snake_case_		(    self							)    ->	Union[str, Any]:
							return self.time_input_dim * 4




					@property
					def 						snake_case_		(    self							)    ->	Dict:
							return 100




					@property
					def 						snake_case_		(    self							)    ->	List[str]:
							UpperCamelCase__								=						XLMRobertaTokenizerFast.from_pretrained("""YiYiXu/tiny-random-mclip-base"""							)
							return tokenizer




					@property
					def 						snake_case_		(    self							)    ->	Union[str, Any]:
							torch.manual_seed(0							)
							UpperCamelCase__								=						MCLIPConfig(
							    numDims=self.cross_attention_dim     ,   transformerDimensions=self.text_embedder_hidden_size     ,   hidden_size=self.text_embedder_hidden_size     ,   intermediate_size=37     ,   num_attention_heads=4     ,   num_hidden_layers=5     ,   vocab_size=1_005     ,   )

							UpperCamelCase__								=						MultilingualCLIP(__lowerCAmelCase							)
							UpperCamelCase__								=						text_encoder.eval()

							return text_encoder




					@property
					def 						snake_case_		(    self							)    ->	Optional[Any]:
							torch.manual_seed(0							)

							UpperCamelCase__								=						{
							    """in_channels""": 4,
							    # Out channels is double in channels because predicts mean and variance
							    """out_channels""": 8,
							    """addition_embed_type""": """text_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""": """text_image_proj""",
							    """cross_attention_dim""": self.cross_attention_dim,
							    """attention_head_dim""": 4,
							    """resnet_time_scale_shift""": """scale_shift""",
							    """class_embed_type""": None,
							}

							UpperCamelCase__								=						UNetaDConditionModel(**__lowerCAmelCase							)
							return model




					@property
					def 						snake_case_		(    self							)    ->	Union[str, Any]:
							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 						snake_case_		(    self							)    ->	Optional[int]:
							torch.manual_seed(0							)
							UpperCamelCase__								=						VQModel(**self.dummy_movq_kwargs							)
							return model




					def 						snake_case_		(    self							)    ->	Dict:
							UpperCamelCase__								=						self.dummy_text_encoder
							UpperCamelCase__								=						self.dummy_tokenizer
							UpperCamelCase__								=						self.dummy_unet
							UpperCamelCase__								=						self.dummy_movq

							UpperCamelCase__								=						DDIMScheduler(
							    num_train_timesteps=1_000     ,   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     ,   )

							UpperCamelCase__								=						{
							    """text_encoder""": text_encoder,
							    """tokenizer""": tokenizer,
							    """unet""": unet,
							    """scheduler""": scheduler,
							    """movq""": movq,
							}
							return components




					def 						snake_case_		(    self     ,   __lowerCAmelCase     ,   __lowerCAmelCase=0							)    ->	str:
							UpperCamelCase__								=						floats_tensor((1, self.cross_attention_dim)     ,   rng=random.Random(__lowerCAmelCase							)							).to(__lowerCAmelCase							)
							UpperCamelCase__								=						floats_tensor((1, self.cross_attention_dim)     ,   rng=random.Random(seed + 1							)							).to(__lowerCAmelCase							)
							if str(__lowerCAmelCase							).startswith("""mps"""							):
									UpperCamelCase__								=						torch.manual_seed(__lowerCAmelCase							)
							else:
									UpperCamelCase__								=						torch.Generator(device=__lowerCAmelCase							).manual_seed(__lowerCAmelCase							)
							UpperCamelCase__								=						{
							    """prompt""": """horse""",
							    """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 						snake_case_		(    self							)    ->	Tuple:
							UpperCamelCase__								=						"""cpu"""

							UpperCamelCase__								=						self.get_dummy_components()

							UpperCamelCase__								=						self.pipeline_class(**__lowerCAmelCase							)
							UpperCamelCase__								=						pipe.to(__lowerCAmelCase							)

							pipe.set_progress_bar_config(disable=__lowerCAmelCase							)

							UpperCamelCase__								=						pipe(**self.get_dummy_inputs(__lowerCAmelCase							)							)
							UpperCamelCase__								=						output.images

							UpperCamelCase__								=						pipe(
							    **self.get_dummy_inputs(__lowerCAmelCase							)     ,   return_dict=__lowerCAmelCase     ,   )[0]

							UpperCamelCase__								=						image[0, -3:, -3:, -1]
							UpperCamelCase__								=						image_from_tuple[0, -3:, -3:, -1]

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

							UpperCamelCase__								=						np.array(
							    [0.3_2_8_6_6_3, 1.0, 0.2_3_2_1_6_8_7_3, 1.0, 0.9_2_7_1_7_5_6_4, 0.4_6_3_9_0_4_6, 0.9_6_8_9_4_7_7_7, 0.3_1_7_1_3_3_7_8, 0.6_2_9_3_9_5_3]							)

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




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




					def 						snake_case_		(    self							)    ->	Any:
							UpperCamelCase__								=						load_numpy(
							    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
							    """/kandinsky/kandinsky_text2img_cat_fp16.npy"""							)

							UpperCamelCase__								=						KandinskyPriorPipeline.from_pretrained(
							    """kandinsky-community/kandinsky-2-1-prior"""     ,   torch_dtype=torch.floataa							)
							pipe_prior.to(__lowerCAmelCase							)

							UpperCamelCase__								=						KandinskyPipeline.from_pretrained("""kandinsky-community/kandinsky-2-1"""     ,   torch_dtype=torch.floataa							)
							UpperCamelCase__								=						pipeline.to(__lowerCAmelCase							)
							pipeline.set_progress_bar_config(disable=__lowerCAmelCase							)

							UpperCamelCase__								=						"""red cat, 4k photo"""

							UpperCamelCase__								=						torch.Generator(device="""cuda"""							).manual_seed(0							)
							UpperCamelCase__	,      UpperCamelCase__								=						pipe_prior(
							    __lowerCAmelCase     ,   generator=__lowerCAmelCase     ,   num_inference_steps=5     ,   negative_prompt=""""""     ,   ).to_tuple()

							UpperCamelCase__								=						torch.Generator(device="""cuda"""							).manual_seed(0							)
							UpperCamelCase__								=						pipeline(
							    __lowerCAmelCase     ,   image_embeds=__lowerCAmelCase     ,   negative_image_embeds=__lowerCAmelCase     ,   generator=__lowerCAmelCase     ,   num_inference_steps=100     ,   output_type="""np"""     ,   )

							UpperCamelCase__								=						output.images[0]

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

							assert_mean_pixel_difference(__lowerCAmelCase     ,   __lowerCAmelCase							)





