

import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    load_numpy,
    nightly,
    require_torch_gpu,
    slow,
    torch_device,
)

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()






class 	A_		(	SCREAMING_SNAKE_CASE      ,							unittest.TestCase    ):
							_UpperCAmelCase   :  Optional[Any]										=				LDMTextToImagePipeline
							_UpperCAmelCase   :  Any										=				TEXT_TO_IMAGE_PARAMS - {
							    '''negative_prompt''',
							    '''negative_prompt_embeds''',
							    '''cross_attention_kwargs''',
							    '''prompt_embeds''',
							}
							_UpperCAmelCase   :  Optional[Any]										=				PipelineTesterMixin.required_optional_params - {
							    '''num_images_per_prompt''',
							    '''callback''',
							    '''callback_steps''',
							}
							_UpperCAmelCase   :  Union[str, Any]										=				TEXT_TO_IMAGE_BATCH_PARAMS
							_UpperCAmelCase   :  Union[str, Any]										=				False
							def    lowerCAmelCase					(		self		:      Dict):
								torch.manual_seed(0)
								__lowerCamelCase    :    Any 	=			UNetaDConditionModel(
								    block_out_channels=(3_2, 6_4)       ,layers_per_block=2       ,sample_size=3_2       ,in_channels=4       ,out_channels=4       ,down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')       ,up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')       ,cross_attention_dim=3_2       ,)
								__lowerCamelCase    :    str 	=			DDIMScheduler(
								    beta_start=0.00085       ,beta_end=0.012       ,beta_schedule='scaled_linear'       ,clip_sample=SCREAMING_SNAKE_CASE__       ,set_alpha_to_one=SCREAMING_SNAKE_CASE__       ,)
								torch.manual_seed(0)
								__lowerCamelCase    :    str 	=			AutoencoderKL(
								    block_out_channels=(3_2, 6_4)       ,in_channels=3       ,out_channels=3       ,down_block_types=('DownEncoderBlock2D', 'DownEncoderBlock2D')       ,up_block_types=('UpDecoderBlock2D', 'UpDecoderBlock2D')       ,latent_channels=4       ,)
								torch.manual_seed(0)
								__lowerCamelCase    :    Union[str, Any] 	=			CLIPTextConfig(
								    bos_token_id=0       ,eos_token_id=2       ,hidden_size=3_2       ,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       ,)
								__lowerCamelCase    :    Union[str, Any] 	=			CLIPTextModel(SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    List[Any] 	=			CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip')

								__lowerCamelCase    :    int 	=			{
								    'unet': unet,
								    'scheduler': scheduler,
								    'vqvae': vae,
								    'bert': text_encoder,
								    'tokenizer': tokenizer,
								}
								return components
							def    lowerCAmelCase					(		self		:      Dict       ,SCREAMING_SNAKE_CASE__		:      Union[str, Any]       ,SCREAMING_SNAKE_CASE__		:      int=0):
								if str(SCREAMING_SNAKE_CASE__).startswith('mps'):
									__lowerCamelCase    :    Optional[int] 	=			torch.manual_seed(SCREAMING_SNAKE_CASE__)
								else:
									__lowerCamelCase    :    Tuple 	=			torch.Generator(device=SCREAMING_SNAKE_CASE__).manual_seed(SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    Optional[Any] 	=			{
								    'prompt': 'A painting of a squirrel eating a burger',
								    'generator': generator,
								    'num_inference_steps': 2,
								    'guidance_scale': 6.0,
								    'output_type': 'numpy',
								}
								return inputs


							def    lowerCAmelCase					(		self		:      Optional[int]):
								__lowerCamelCase    :    Union[str, Any] 	=			'cpu'  # ensure determinism for the device-dependent torch.Generator

								__lowerCamelCase    :    List[Any] 	=			self.get_dummy_components()
								__lowerCamelCase    :    int 	=			LDMTextToImagePipeline(**SCREAMING_SNAKE_CASE__)
								pipe.to(SCREAMING_SNAKE_CASE__)
								pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__)

								__lowerCamelCase    :    Optional[int] 	=			self.get_dummy_inputs(SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    List[str] 	=			pipe(**SCREAMING_SNAKE_CASE__).images
								__lowerCamelCase    :    Tuple 	=			image[0, -3:, -3:, -1]

								assert image.shape == (1, 1_6, 1_6, 3)
								__lowerCamelCase    :    Any 	=			np.array([0.6101, 0.6156, 0.5622, 0.4895, 0.6661, 0.3804, 0.5748, 0.6136, 0.5014])

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






@slow
@require_torch_gpu
class 	A_		(	unittest.TestCase    ):
							def    lowerCAmelCase					(		self		:      str):
								super().tearDown()
								gc.collect()
								torch.cuda.empty_cache()
							def    lowerCAmelCase					(		self		:      Union[str, Any]       ,SCREAMING_SNAKE_CASE__		:      Optional[Any]       ,SCREAMING_SNAKE_CASE__		:      List[Any]=torch.floataa       ,SCREAMING_SNAKE_CASE__		:      Any=0):
								__lowerCamelCase    :    Optional[Any] 	=			torch.manual_seed(SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    List[str] 	=			np.random.RandomState(SCREAMING_SNAKE_CASE__).standard_normal((1, 4, 3_2, 3_2))
								__lowerCamelCase    :    Dict 	=			torch.from_numpy(SCREAMING_SNAKE_CASE__).to(device=SCREAMING_SNAKE_CASE__       ,dtype=SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    Union[str, Any] 	=			{
								    'prompt': 'A painting of a squirrel eating a burger',
								    'latents': latents,
								    'generator': generator,
								    'num_inference_steps': 3,
								    'guidance_scale': 6.0,
								    'output_type': 'numpy',
								}
								return inputs


							def    lowerCAmelCase					(		self		:      str):
								__lowerCamelCase    :    int 	=			LDMTextToImagePipeline.from_pretrained('CompVis/ldm-text2im-large-256').to(SCREAMING_SNAKE_CASE__)
								pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__)

								__lowerCamelCase    :    int 	=			self.get_inputs(SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    str 	=			pipe(**SCREAMING_SNAKE_CASE__).images
								__lowerCamelCase    :    Optional[Any] 	=			image[0, -3:, -3:, -1].flatten()

								assert image.shape == (1, 2_5_6, 2_5_6, 3)
								__lowerCamelCase    :    List[str] 	=			np.array([0.51825, 0.52850, 0.52543, 0.54258, 0.52304, 0.52569, 0.54363, 0.55276, 0.56878])
								__lowerCamelCase    :    Optional[Any] 	=			np.abs(expected_slice - image_slice).max()
								assert max_diff < 1E-3






@nightly
@require_torch_gpu
class 	A_		(	unittest.TestCase    ):
							def    lowerCAmelCase					(		self		:      Optional[int]):
								super().tearDown()
								gc.collect()
								torch.cuda.empty_cache()
							def    lowerCAmelCase					(		self		:      List[Any]       ,SCREAMING_SNAKE_CASE__		:      Optional[int]       ,SCREAMING_SNAKE_CASE__		:      Union[str, Any]=torch.floataa       ,SCREAMING_SNAKE_CASE__		:      int=0):
								__lowerCamelCase    :    List[Any] 	=			torch.manual_seed(SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    Optional[int] 	=			np.random.RandomState(SCREAMING_SNAKE_CASE__).standard_normal((1, 4, 3_2, 3_2))
								__lowerCamelCase    :    Union[str, Any] 	=			torch.from_numpy(SCREAMING_SNAKE_CASE__).to(device=SCREAMING_SNAKE_CASE__       ,dtype=SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    Optional[Any] 	=			{
								    'prompt': 'A painting of a squirrel eating a burger',
								    'latents': latents,
								    'generator': generator,
								    'num_inference_steps': 5_0,
								    'guidance_scale': 6.0,
								    'output_type': 'numpy',
								}
								return inputs


							def    lowerCAmelCase					(		self		:      Any):
								__lowerCamelCase    :    Dict 	=			LDMTextToImagePipeline.from_pretrained('CompVis/ldm-text2im-large-256').to(SCREAMING_SNAKE_CASE__)
								pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__)

								__lowerCamelCase    :    Any 	=			self.get_inputs(SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    List[str] 	=			pipe(**SCREAMING_SNAKE_CASE__).images[0]

								__lowerCamelCase    :    Optional[int] 	=			load_numpy(
								    'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy')
								__lowerCamelCase    :    List[Any] 	=			np.abs(expected_image - image).max()
								assert max_diff < 1E-3







from __future__ import annotations

from collections.abc import Callable
from typing import Generic, TypeVar

a		=TypeVar("""T""")
a		=TypeVar("""U""")






class 	A_		(	Generic[T, U]    ):
							def __init__(		self		:      Tuple       ,SCREAMING_SNAKE_CASE__		:      T | None       ,SCREAMING_SNAKE_CASE__		:      U | None):
								__lowerCamelCase    :    Optional[Any] 	=			key
								__lowerCamelCase    :    Tuple 	=			val
								__lowerCamelCase    :    DoubleLinkedListNode[T, U] | None 	=			None
								__lowerCamelCase    :    DoubleLinkedListNode[T, U] | None 	=			None


							def __repr__(		self		:      Optional[int]):
								return (
								    F"Node: key: {self.key}, val: {self.val}, "
								    F"has next: {bool(self.next)}, has prev: {bool(self.prev)}"
								)






class 	A_		(	Generic[T, U]    ):
							def __init__(		self		:      List[Any]):
								__lowerCamelCase    :    DoubleLinkedListNode[T, U] 	=			DoubleLinkedListNode(SCREAMING_SNAKE_CASE__       ,SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    DoubleLinkedListNode[T, U] 	=			DoubleLinkedListNode(SCREAMING_SNAKE_CASE__       ,SCREAMING_SNAKE_CASE__)
								__lowerCamelCase	,			__lowerCamelCase    :    List[Any] 	=			self.rear, self.head
							def __repr__(		self		:      Optional[int]):
								__lowerCamelCase    :    int 	=			['DoubleLinkedList']
								__lowerCamelCase    :    Tuple 	=			self.head
								while node.next is not None:
									rep.append(str(SCREAMING_SNAKE_CASE__))
									__lowerCamelCase    :    Union[str, Any] 	=			node.next
								rep.append(str(self.rear))
								return ",\n    ".join(SCREAMING_SNAKE_CASE__)
							def    lowerCAmelCase					(		self		:      Optional[Any]       ,SCREAMING_SNAKE_CASE__		:      DoubleLinkedListNode[T, U]):
								__lowerCamelCase    :    str 	=			self.rear.prev

								# All nodes other than self.head are guaranteed to have non-None previous
								assert previous is not None

								__lowerCamelCase    :    Any 	=			node
								__lowerCamelCase    :    str 	=			previous
								__lowerCamelCase    :    str 	=			node
								__lowerCamelCase    :    List[str] 	=			self.rear


							def    lowerCAmelCase					(		self		:      int       ,SCREAMING_SNAKE_CASE__		:      DoubleLinkedListNode[T, U]):

								if node.prev is None or node.next is None:
									return None

								__lowerCamelCase    :    Union[str, Any] 	=			node.next
								__lowerCamelCase    :    Dict 	=			node.prev
								__lowerCamelCase    :    Optional[int] 	=			None
								__lowerCamelCase    :    List[str] 	=			None
								return node






class 	A_		(	Generic[T, U]    ):
							_UpperCAmelCase   :  dict[Callable[[T], U], LRUCache[T, U]]										=				{}
							def __init__(		self		:      str       ,SCREAMING_SNAKE_CASE__		:      int):
								__lowerCamelCase    :    DoubleLinkedList[T, U] 	=			DoubleLinkedList()
								__lowerCamelCase    :    List[Any] 	=			capacity
								__lowerCamelCase    :    Optional[int] 	=			0
								__lowerCamelCase    :    int 	=			0
								__lowerCamelCase    :    Optional[Any] 	=			0
								__lowerCamelCase    :    dict[T, DoubleLinkedListNode[T, U]] 	=			{}
							def __repr__(		self		:      Optional[Any]):
								return (
								    F"CacheInfo(hits={self.hits}, misses={self.miss}, "
								    F"capacity={self.capacity}, current size={self.num_keys})"
								)
							def __contains__(		self		:      List[str]       ,SCREAMING_SNAKE_CASE__		:      T):
								return key in self.cache
							def    lowerCAmelCase					(		self		:      Union[str, Any]       ,SCREAMING_SNAKE_CASE__		:      T):
								# Note: pythonic interface would throw KeyError rather than return None

								if key in self.cache:
									self.hits += 1
									__lowerCamelCase    :    DoubleLinkedListNode[T, U] 	=			self.cache[key]
									__lowerCamelCase    :    List[str] 	=			self.list.remove(self.cache[key])
									assert node == value_node

									# node is guaranteed not None because it is in self.cache
									assert node is not None
									self.list.add(SCREAMING_SNAKE_CASE__)
									return node.val
								self.miss += 1
								return None
							def    lowerCAmelCase					(		self		:      Dict       ,SCREAMING_SNAKE_CASE__		:      T       ,SCREAMING_SNAKE_CASE__		:      U):

								if key not in self.cache:
									if self.num_keys >= self.capacity:
										# delete first node (oldest) when over capacity
										__lowerCamelCase    :    Optional[Any] 	=			self.list.head.next

										# guaranteed to have a non-None first node when num_keys > 0
										# explain to type checker via assertions
										assert first_node is not None
										assert first_node.key is not None
										assert (
										    self.list.remove(SCREAMING_SNAKE_CASE__) is not None
										)  # node guaranteed to be in list assert node.key is not None

										del self.cache[first_node.key]
										self.num_keys -= 1
									__lowerCamelCase    :    List[Any] 	=			DoubleLinkedListNode(SCREAMING_SNAKE_CASE__       ,SCREAMING_SNAKE_CASE__)
									self.list.add(self.cache[key])
									self.num_keys += 1

								else:
									# bump node to the end of the list, update value
									__lowerCamelCase    :    List[str] 	=			self.list.remove(self.cache[key])
									assert node is not None  # node guaranteed to be in list
									__lowerCamelCase    :    List[Any] 	=			value
									self.list.add(SCREAMING_SNAKE_CASE__)


							@classmethod
							def    lowerCAmelCase					(		cls		:      Optional[int]       ,SCREAMING_SNAKE_CASE__		:      int = 1_2_8):

								def cache_decorator_inner(SCREAMING_SNAKE_CASE__		:      Callable[[T], U]) -> Callable[..., U]:
									def cache_decorator_wrapper(*SCREAMING_SNAKE_CASE__		:      T) -> U:
										if func not in cls.decorator_function_to_instance_map:
											__lowerCamelCase    :    str 	=			LRUCache(SCREAMING_SNAKE_CASE__)

										__lowerCamelCase    :    Dict 	=			cls.decorator_function_to_instance_map[func].get(args[0])
										if result is None:
											__lowerCamelCase    :    str 	=			func(*SCREAMING_SNAKE_CASE__)
											cls.decorator_function_to_instance_map[func].put(args[0]       ,SCREAMING_SNAKE_CASE__)
										return result

									def cache_info() -> LRUCache[T, U]:
										return cls.decorator_function_to_instance_map[func]

									setattr(SCREAMING_SNAKE_CASE__       ,'cache_info'       ,SCREAMING_SNAKE_CASE__)  # noqa: B010

									return cache_decorator_wrapper

								return cache_decorator_inner


if __name__ == "__main__":
					import doctest

					doctest.testmod()




