


'''simple docstring'''


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     lowercase__  (						_snake_case     ,     unittest.TestCase					):





							'''simple docstring'''


							A_							:      Optional[Any]      	=  LDMTextToImagePipeline
							A_							:      List[str]      	=  TEXT_TO_IMAGE_PARAMS - {
							    """negative_prompt""",
							    """negative_prompt_embeds""",
							    """cross_attention_kwargs""",
							    """prompt_embeds""",
							}
							A_							:      List[str]      	=  PipelineTesterMixin.required_optional_params - {
							    """num_images_per_prompt""",
							    """callback""",
							    """callback_steps""",
							}
							A_							:      List[str]      	=  TEXT_TO_IMAGE_BATCH_PARAMS
							A_							:      List[Any]      	=  False






							def UpperCAmelCase_	(    self  ):
											torch.manual_seed(0  )
											_SCREAMING_SNAKE_CASE :       List[Any]     		=      UNetaDConditionModel(
											    block_out_channels=(32, 64)    ,					layers_per_block=2    ,					sample_size=32    ,					in_channels=4    ,					out_channels=4    ,					down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")    ,					up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""")    ,					cross_attention_dim=32    ,					)
											_SCREAMING_SNAKE_CASE :       str     		=      DDIMScheduler(
											    beta_start=0.00085    ,					beta_end=0.012    ,					beta_schedule="""scaled_linear"""    ,					clip_sample=__snake_case    ,					set_alpha_to_one=__snake_case    ,					)
											torch.manual_seed(0  )
											_SCREAMING_SNAKE_CASE :       Optional[Any]     		=      AutoencoderKL(
											    block_out_channels=(32, 64)    ,					in_channels=3    ,					out_channels=3    ,					down_block_types=("""DownEncoderBlock2D""", """DownEncoderBlock2D""")    ,					up_block_types=("""UpDecoderBlock2D""", """UpDecoderBlock2D""")    ,					latent_channels=4    ,					)
											torch.manual_seed(0  )
											_SCREAMING_SNAKE_CASE :       str     		=      CLIPTextConfig(
											    bos_token_id=0    ,					eos_token_id=2    ,					hidden_size=32    ,					intermediate_size=37    ,					layer_norm_eps=1e-05    ,					num_attention_heads=4    ,					num_hidden_layers=5    ,					pad_token_id=1    ,					vocab_size=1000    ,					)
											_SCREAMING_SNAKE_CASE :       Optional[int]     		=      CLIPTextModel(__snake_case  )
											_SCREAMING_SNAKE_CASE :       Optional[int]     		=      CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""  )

											_SCREAMING_SNAKE_CASE :       List[str]     		=      {
											    """unet""": unet,
											    """scheduler""": scheduler,
											    """vqvae""": vae,
											    """bert""": text_encoder,
											    """tokenizer""": tokenizer,
											}
											return components






							def UpperCAmelCase_	(    self    ,					__snake_case    ,					__snake_case=0  ):
											if str(__snake_case  ).startswith("""mps"""  ):
															_SCREAMING_SNAKE_CASE :       Tuple     		=      torch.manual_seed(__snake_case  )
											else:
															_SCREAMING_SNAKE_CASE :       Any     		=      torch.Generator(device=__snake_case  ).manual_seed(__snake_case  )
											_SCREAMING_SNAKE_CASE :       List[str]     		=      {
											    """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 UpperCAmelCase_	(    self  ):
											_SCREAMING_SNAKE_CASE :       int     		=      """cpu"""  # ensure determinism for the device-dependent torch.Generator

											_SCREAMING_SNAKE_CASE :       Tuple     		=      self.get_dummy_components()
											_SCREAMING_SNAKE_CASE :       str     		=      LDMTextToImagePipeline(**__snake_case  )
											pipe.to(__snake_case  )
											pipe.set_progress_bar_config(disable=__snake_case  )

											_SCREAMING_SNAKE_CASE :       Dict     		=      self.get_dummy_inputs(__snake_case  )
											_SCREAMING_SNAKE_CASE :       Any     		=      pipe(**__snake_case  ).images
											_SCREAMING_SNAKE_CASE :       List[str]     		=      image[0, -3:, -3:, -1]

											assert image.shape == (1, 16, 16, 3)
											_SCREAMING_SNAKE_CASE :       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     lowercase__  (						unittest.TestCase					):





							'''simple docstring'''


							def UpperCAmelCase_	(    self  ):
											super().tearDown()
											gc.collect()
											torch.cuda.empty_cache()






							def UpperCAmelCase_	(    self    ,					__snake_case    ,					__snake_case=torch.floataa    ,					__snake_case=0  ):
											_SCREAMING_SNAKE_CASE :       str     		=      torch.manual_seed(__snake_case  )
											_SCREAMING_SNAKE_CASE :       Any     		=      np.random.RandomState(__snake_case  ).standard_normal((1, 4, 32, 32)  )
											_SCREAMING_SNAKE_CASE :       Union[str, Any]     		=      torch.from_numpy(__snake_case  ).to(device=__snake_case    ,					dtype=__snake_case  )
											_SCREAMING_SNAKE_CASE :       Optional[int]     		=      {
											    """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 UpperCAmelCase_	(    self  ):
											_SCREAMING_SNAKE_CASE :       Any     		=      LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256"""  ).to(__snake_case  )
											pipe.set_progress_bar_config(disable=__snake_case  )

											_SCREAMING_SNAKE_CASE :       str     		=      self.get_inputs(__snake_case  )
											_SCREAMING_SNAKE_CASE :       Optional[Any]     		=      pipe(**__snake_case  ).images
											_SCREAMING_SNAKE_CASE :       Tuple     		=      image[0, -3:, -3:, -1].flatten()

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





@nightly
@require_torch_gpu
class     lowercase__  (						unittest.TestCase					):





							'''simple docstring'''


							def UpperCAmelCase_	(    self  ):
											super().tearDown()
											gc.collect()
											torch.cuda.empty_cache()






							def UpperCAmelCase_	(    self    ,					__snake_case    ,					__snake_case=torch.floataa    ,					__snake_case=0  ):
											_SCREAMING_SNAKE_CASE :       Optional[int]     		=      torch.manual_seed(__snake_case  )
											_SCREAMING_SNAKE_CASE :       Dict     		=      np.random.RandomState(__snake_case  ).standard_normal((1, 4, 32, 32)  )
											_SCREAMING_SNAKE_CASE :       List[str]     		=      torch.from_numpy(__snake_case  ).to(device=__snake_case    ,					dtype=__snake_case  )
											_SCREAMING_SNAKE_CASE :       Optional[int]     		=      {
											    """prompt""": """A painting of a squirrel eating a burger""",
											    """latents""": latents,
											    """generator""": generator,
											    """num_inference_steps""": 50,
											    """guidance_scale""": 6.0,
											    """output_type""": """numpy""",
											}
											return inputs






							def UpperCAmelCase_	(    self  ):
											_SCREAMING_SNAKE_CASE :       Union[str, Any]     		=      LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256"""  ).to(__snake_case  )
											pipe.set_progress_bar_config(disable=__snake_case  )

											_SCREAMING_SNAKE_CASE :       Tuple     		=      self.get_inputs(__snake_case  )
											_SCREAMING_SNAKE_CASE :       Union[str, Any]     		=      pipe(**__snake_case  ).images[0]

											_SCREAMING_SNAKE_CASE :       Union[str, Any]     		=      load_numpy(
											    """https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy"""  )
											_SCREAMING_SNAKE_CASE :       Any     		=      np.abs(expected_image - image  ).max()
											assert max_diff < 1e-3








'''simple docstring'''


UpperCAmelCase_		:   Union[str, Any]							   =		'\n# Transformers installation\n! pip install transformers datasets\n# To install from source instead of the last release, comment the command above and uncomment the following one.\n# ! pip install git+https://github.com/huggingface/transformers.git\n'

UpperCAmelCase_		:   Dict							   =		[{'type': 'code', 'content': INSTALL_CONTENT}]
UpperCAmelCase_		:   Any							   =		{
    '{processor_class}': 'FakeProcessorClass',
    '{model_class}': 'FakeModelClass',
    '{object_class}': 'FakeObjectClass',
}




