






'''simple docstring'''





import tempfile
import unittest

import numpy as np
import torch

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





class 		SCREAMING_SNAKE_CASE__   (     unittest.TestCase    ):



		def _lowerCAmelCase     (    self:    Any				,   a:    bool = False)  ->Optional[Any]:






								'''simple docstring'''


								a_				     =   10

								if only_cross_attention:
														a_				     =   12
								else:
														# when only cross attention is not set, the cross attention dim must be the same as the query dim
														a_				     =   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 _lowerCAmelCase     (    self:    Dict				,   a:    Optional[Any]				,   a:    Optional[Any])  ->List[Any]:






								'''simple docstring'''


								a_				     =   2

								a_				     =   torch.rand(a				,   a				,   3				,   2)
								a_				     =   torch.rand(a				,   4				,   a)
								a_				     =   None

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




		def _lowerCAmelCase     (    self:    Dict)  ->int:






								'''simple docstring'''


								torch.manual_seed(0)

								a_				     =   self.get_constructor_arguments(only_cross_attention=a)
								a_				     =   Attention(**a)

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

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

								a_				     =   attn(**a)

								# only self attention

								torch.manual_seed(0)

								a_				     =   self.get_constructor_arguments(only_cross_attention=a)
								a_				     =   Attention(**a)

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

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

								a_				     =   attn(**a)

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





class 		SCREAMING_SNAKE_CASE__   (     unittest.TestCase    ):



		def _lowerCAmelCase     (    self:    Optional[Any])  ->int:






								'''simple docstring'''


								a_				     =   DiffusionPipeline.from_pretrained("hf-internal-testing/tiny-stable-diffusion-pipe"				,   safety_checker=a)

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

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

								a_				     =   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(a)

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

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

								self.assertTrue(np.allclose(a				,   a				,   atol=1e-5))
								self.assertTrue(np.allclose(a				,   a				,   atol=1e-5))











'''simple docstring'''





from typing import List, Optional, Tuple, Union

from . import logging
from .import_utils import is_torch_available, is_torch_version


if is_torch_available():
							import torch

a_      = logging.get_logger(__name__)  # pylint: disable=invalid-name

try:
							from torch._dynamo import allow_in_graph as maybe_allow_in_graph
except (ImportError, ModuleNotFoundError):



							def 			__UpperCAmelCase				(cls				)		->				Optional[Any]:

													'''simple docstring'''


													return cls



def 			__UpperCAmelCase				(lowercase__	,lowercase__ = None	,lowercase__ = None	,lowercase__ = None	,lowercase__ = None	,)		->				Union[str, Any]:

						'''simple docstring'''


						a_				     =   device
						a_				     =   shape[0]

						a_				     =   layout or torch.strided
						a_				     =   device or torch.device("cpu"				)

						if generator is not None:
												a_				     =   generator.device.type if not isinstance(lowercase__	,lowercase__				) else generator[0].device.type
												if gen_device_type != device.type and gen_device_type == "cpu":
																		a_				     =   "cpu"
																		if device != "mps":
																								logger.info(
																								    F"""The passed generator was created on 'cpu' even though a tensor on {device} was expected."""
																								    F""" Tensors will be created on 'cpu' and then moved to {device}. Note that one can probably"""
																								    F""" slighly speed up this function by passing a generator that was created on the {device} device."""				)
												elif gen_device_type != device.type and gen_device_type == "cuda":
																		raise ValueError(F"""Cannot generate a {device} tensor from a generator of type {gen_device_type}."""				)

						if isinstance(lowercase__	,lowercase__				):
												a_				     =   (1,) + shape[1:]
												a_				     =   [
												    torch.randn(lowercase__	,generator=generator[i]	,device=lowercase__	,dtype=lowercase__	,layout=lowercase__				)
												    for i in range(lowercase__				)
												]
												a_				     =   torch.cat(lowercase__	,dim=0				).to(lowercase__				)
						else:
												a_				     =   torch.randn(lowercase__	,generator=lowercase__	,device=lowercase__	,dtype=lowercase__	,layout=lowercase__				).to(lowercase__				)

						return latents



def 			__UpperCAmelCase				(lowercase__				)		->				Tuple:

						'''simple docstring'''


						if is_torch_version("<"	,"2.0.0"				) or not hasattr(lowercase__	,"_dynamo"				):
												return False
						return isinstance(lowercase__	,torch._dynamo.eval_frame.OptimizedModule				)



