import tempfile
import unittest

import numpy as np
import torch

from diffusers import DiffusionPipeline
from diffusers.models.attention_processor import Attention, AttnAddedKVProcessor






class        __UpperCAmelCase						(     unittest.TestCase     ):

				def 		_a     (				self     ,			_lowerCamelCase = False				):
										lowerCamelCase__ =10

										if only_cross_attention:
																lowerCamelCase__ =12
										else:
																# when only cross attention is not set, the cross attention dim must be the same as the query dim
																lowerCamelCase__ =query_dim

										return {
										    "query_dim": query_dim,
										    "cross_attention_dim": cross_attention_dim,
										    "heads": 2,
										    "dim_head": 4,
										    "added_kv_proj_dim": 6,
										    "norm_num_groups": 1,
										    "only_cross_attention": only_cross_attention,
										    "processor": AttnAddedKVProcessor(),
										}

				def 		_a     (				self     ,			_lowerCamelCase     ,			_lowerCamelCase				):
										lowerCamelCase__ =2

										lowerCamelCase__ =torch.rand(_lowerCamelCase     ,			_lowerCamelCase     ,			3     ,			2				)
										lowerCamelCase__ =torch.rand(_lowerCamelCase     ,			4     ,			_lowerCamelCase				)
										lowerCamelCase__ =None

										return {
										    "hidden_states": hidden_states,
										    "encoder_hidden_states": encoder_hidden_states,
										    "attention_mask": attention_mask,
										}






				def 		_a     (				self				):
										# self and cross attention

										torch.manual_seed(0				)

										lowerCamelCase__ =self.get_constructor_arguments(only_cross_attention=_lowerCamelCase				)
										lowerCamelCase__ =Attention(**_lowerCamelCase				)

										self.assertTrue(attn.to_k is not None				)
										self.assertTrue(attn.to_v is not None				)

										lowerCamelCase__ =self.get_forward_arguments(
										    query_dim=constructor_args["query_dim"]     ,			added_kv_proj_dim=constructor_args["added_kv_proj_dim"]				)

										lowerCamelCase__ =attn(**_lowerCamelCase				)

										# only self attention

										torch.manual_seed(0				)

										lowerCamelCase__ =self.get_constructor_arguments(only_cross_attention=_lowerCamelCase				)
										lowerCamelCase__ =Attention(**_lowerCamelCase				)

										self.assertTrue(attn.to_k is None				)
										self.assertTrue(attn.to_v is None				)

										lowerCamelCase__ =self.get_forward_arguments(
										    query_dim=constructor_args["query_dim"]     ,			added_kv_proj_dim=constructor_args["added_kv_proj_dim"]				)

										lowerCamelCase__ =attn(**_lowerCamelCase				)

										self.assertTrue((only_cross_attn_out != self_and_cross_attn_out).all()				)






class        __UpperCAmelCase						(     unittest.TestCase     ):

				def 		_a     (				self				):
										lowerCamelCase__ =DiffusionPipeline.from_pretrained("hf-internal-testing/tiny-stable-diffusion-pipe"     ,			safety_checker=_lowerCamelCase				)

										lowerCamelCase__ =pipe(
										    "foo"     ,			num_inference_steps=2     ,			generator=torch.Generator("cpu"				).manual_seed(0				)     ,			output_type="np"     ,			).images

										# the initial conversion succeeds
										lowerCamelCase__ =DiffusionPipeline.from_pretrained(
										    "hf-internal-testing/tiny-stable-diffusion-pipe"     ,			device_map="sequential"     ,			safety_checker=_lowerCamelCase				)

										lowerCamelCase__ =pipe(
										    "foo"     ,			num_inference_steps=2     ,			generator=torch.Generator("cpu"				).manual_seed(0				)     ,			output_type="np"     ,			).images

										with tempfile.TemporaryDirectory() as tmpdir:
																# save the converted model
																pipe.save_pretrained(_lowerCamelCase				)

																# can also load the converted weights
																lowerCamelCase__ =DiffusionPipeline.from_pretrained(_lowerCamelCase     ,			device_map="sequential"     ,			safety_checker=_lowerCamelCase				)

										lowerCamelCase__ =pipe(
										    "foo"     ,			num_inference_steps=2     ,			generator=torch.Generator("cpu"				).manual_seed(0				)     ,			output_type="np"     ,			).images

										self.assertTrue(np.allclose(_lowerCamelCase     ,			_lowerCamelCase     ,			atol=1E-5				)				)
										self.assertTrue(np.allclose(_lowerCamelCase     ,			_lowerCamelCase     ,			atol=1E-5				)				)



"""simple docstring"""


import random
import unittest

import torch

from diffusers import IFSuperResolutionPipeline
from diffusers.utils import floats_tensor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import skip_mps, torch_device

from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin






@skip_mps
class        __UpperCAmelCase						(     __lowerCAmelCase				,				__lowerCAmelCase				,				unittest.TestCase     ):
				A__				:       Any  							=	IFSuperResolutionPipeline
				A__				:       Tuple  							=	TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''width''', '''height'''}
				A__				:       Optional[int]  							=	TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
				A__				:       List[Any]  							=	PipelineTesterMixin.required_optional_params - {'''latents'''}

				def 		_a     (				self				):
										return self._get_superresolution_dummy_components()

				def 		_a     (				self     ,			_lowerCamelCase     ,			_lowerCamelCase=0				):
										if str(_lowerCamelCase				).startswith("mps"				):
																lowerCamelCase__ =torch.manual_seed(_lowerCamelCase				)
										else:
																lowerCamelCase__ =torch.Generator(device=_lowerCamelCase				).manual_seed(_lowerCamelCase				)

										lowerCamelCase__ =floats_tensor((1, 3, 32, 32)     ,			rng=random.Random(_lowerCamelCase				)				).to(_lowerCamelCase				)

										lowerCamelCase__ ={
										    "prompt": "A painting of a squirrel eating a burger",
										    "image": image,
										    "generator": generator,
										    "num_inference_steps": 2,
										    "output_type": "numpy",
										}

										return inputs

				@unittest.skipIf(
				    torch_device != "cuda" or not is_xformers_available()     ,			reason="XFormers attention is only available with CUDA and `xformers` installed"     ,			)
				def 		_a     (				self				):
										self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3				)

				def 		_a     (				self				):
										self._test_save_load_optional_components()

				@unittest.skipIf(torch_device != "cuda"     ,			reason="float16 requires CUDA"				)
				def 		_a     (				self				):
										# Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder
										super().test_save_load_floataa(expected_max_diff=1E-1				)

				def 		_a     (				self				):
										self._test_attention_slicing_forward_pass(expected_max_diff=1E-2				)

				def 		_a     (				self				):
										self._test_save_load_local()






				def 		_a     (				self				):
										self._test_inference_batch_single_identical(
										    expected_max_diff=1E-2     ,			)


