



"""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     UpperCAmelCase    (	__SCREAMING_SNAKE_CASE,unittest.TestCase  ):
   A__		:	str           =  LDMTextToImagePipeline
   A__		:	Union[str, Any]           =  TEXT_TO_IMAGE_PARAMS - {
       '''negative_prompt''',
       '''negative_prompt_embeds''',
       '''cross_attention_kwargs''',
       '''prompt_embeds''',
   }
   A__		:	Optional[Any]           =  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    :	List[Any]				):



     """simple docstring"""
     torch.manual_seed(0				)
     _snake_case   	=      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							,       )
     _snake_case   	=      DDIMScheduler(
         beta_start=0.0_0_0_8_5							,       beta_end=0.0_1_2							,       beta_schedule='''scaled_linear'''							,       clip_sample=__lowerCamelCase							,       set_alpha_to_one=__lowerCamelCase							,       )
     torch.manual_seed(0				)
     _snake_case   	=      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				)
     _snake_case   	=      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							,       )
     _snake_case   	=      CLIPTextModel(__lowerCamelCase				)
     _snake_case   	=      CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''				)

     _snake_case   	=      {
         '''unet''': unet,
         '''scheduler''': scheduler,
         '''vqvae''': vae,
         '''bert''': text_encoder,
         '''tokenizer''': tokenizer,
     }
     return components



   def    __UpperCAmelCase    (       self    :	Optional[Any]							,       __lowerCamelCase    :	Optional[Any]							,       __lowerCamelCase    :	Dict=0				):



     """simple docstring"""
     if str(__lowerCamelCase				).startswith('''mps'''				):
       _snake_case   	=      torch.manual_seed(__lowerCamelCase				)
     else:
       _snake_case   	=      torch.Generator(device=__lowerCamelCase				).manual_seed(__lowerCamelCase				)
     _snake_case   	=      {
         '''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    :	Optional[Any]				):



     """simple docstring"""
     _snake_case   	=      '''cpu'''  # ensure determinism for the device-dependent torch.Generator

     _snake_case   	=      self.get_dummy_components()
     _snake_case   	=      LDMTextToImagePipeline(**__lowerCamelCase				)
     pipe.to(__lowerCamelCase				)
     pipe.set_progress_bar_config(disable=__lowerCamelCase				)

     _snake_case   	=      self.get_dummy_inputs(__lowerCamelCase				)
     _snake_case   	=      pipe(**__lowerCamelCase				).images
     _snake_case   	=      image[0, -3:, -3:, -1]

     assert image.shape == (1, 1_6, 1_6, 3)
     _snake_case   	=      np.array([0.6_1_0_1, 0.6_1_5_6, 0.5_6_2_2, 0.4_8_9_5, 0.6_6_6_1, 0.3_8_0_4, 0.5_7_4_8, 0.6_1_3_6, 0.5_0_1_4]				)

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



@slow
@require_torch_gpu
class     UpperCAmelCase    (	unittest.TestCase  ):



   def    __UpperCAmelCase    (       self    :	str				):



     """simple docstring"""
     super().tearDown()
     gc.collect()
     torch.cuda.empty_cache()



   def    __UpperCAmelCase    (       self    :	List[Any]							,       __lowerCamelCase    :	Optional[Any]							,       __lowerCamelCase    :	Tuple=torch.floataa							,       __lowerCamelCase    :	Optional[int]=0				):



     """simple docstring"""
     _snake_case   	=      torch.manual_seed(__lowerCamelCase				)
     _snake_case   	=      np.random.RandomState(__lowerCamelCase				).standard_normal((1, 4, 3_2, 3_2)				)
     _snake_case   	=      torch.from_numpy(__lowerCamelCase				).to(device=__lowerCamelCase							,       dtype=__lowerCamelCase				)
     _snake_case   	=      {
         '''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    :	Any				):



     """simple docstring"""
     _snake_case   	=      LDMTextToImagePipeline.from_pretrained('''CompVis/ldm-text2im-large-256'''				).to(__lowerCamelCase				)
     pipe.set_progress_bar_config(disable=__lowerCamelCase				)

     _snake_case   	=      self.get_inputs(__lowerCamelCase				)
     _snake_case   	=      pipe(**__lowerCamelCase				).images
     _snake_case   	=      image[0, -3:, -3:, -1].flatten()

     assert image.shape == (1, 2_5_6, 2_5_6, 3)
     _snake_case   	=      np.array([0.5_1_8_2_5, 0.5_2_8_5_0, 0.5_2_5_4_3, 0.5_4_2_5_8, 0.5_2_3_0_4, 0.5_2_5_6_9, 0.5_4_3_6_3, 0.5_5_2_7_6, 0.5_6_8_7_8]				)
     _snake_case   	=      np.abs(expected_slice - image_slice				).max()
     assert max_diff < 1E-3



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



   def    __UpperCAmelCase    (       self    :	Optional[int]				):



     """simple docstring"""
     super().tearDown()
     gc.collect()
     torch.cuda.empty_cache()



   def    __UpperCAmelCase    (       self    :	Tuple							,       __lowerCamelCase    :	Any							,       __lowerCamelCase    :	int=torch.floataa							,       __lowerCamelCase    :	Tuple=0				):



     """simple docstring"""
     _snake_case   	=      torch.manual_seed(__lowerCamelCase				)
     _snake_case   	=      np.random.RandomState(__lowerCamelCase				).standard_normal((1, 4, 3_2, 3_2)				)
     _snake_case   	=      torch.from_numpy(__lowerCamelCase				).to(device=__lowerCamelCase							,       dtype=__lowerCamelCase				)
     _snake_case   	=      {
         '''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    __UpperCAmelCase    (       self    :	Dict				):



     """simple docstring"""
     _snake_case   	=      LDMTextToImagePipeline.from_pretrained('''CompVis/ldm-text2im-large-256'''				).to(__lowerCamelCase				)
     pipe.set_progress_bar_config(disable=__lowerCamelCase				)

     _snake_case   	=      self.get_inputs(__lowerCamelCase				)
     _snake_case   	=      pipe(**__lowerCamelCase				).images[0]

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










"""simple docstring"""






from ...configuration_utils import PretrainedConfig



class     UpperCAmelCase    (	__SCREAMING_SNAKE_CASE  ):
   A__		:	str           =  '''bert-generation'''



   def __init__(       self    :	Tuple							,       __lowerCamelCase    :	Optional[int]=5_0_3_5_8							,       __lowerCamelCase    :	List[str]=1_0_2_4							,       __lowerCamelCase    :	Optional[Any]=2_4							,       __lowerCamelCase    :	Any=1_6							,       __lowerCamelCase    :	Union[str, Any]=4_0_9_6							,       __lowerCamelCase    :	Optional[Any]="gelu"							,       __lowerCamelCase    :	str=0.1							,       __lowerCamelCase    :	List[str]=0.1							,       __lowerCamelCase    :	int=5_1_2							,       __lowerCamelCase    :	Dict=0.0_2							,       __lowerCamelCase    :	Tuple=1E-12							,       __lowerCamelCase    :	Any=0							,       __lowerCamelCase    :	Union[str, Any]=2							,       __lowerCamelCase    :	List[Any]=1							,       __lowerCamelCase    :	Optional[Any]="absolute"							,       __lowerCamelCase    :	str=True							,       **__lowerCamelCase    :	List[Any]							,       ):



     """simple docstring"""
     super().__init__(pad_token_id=__lowerCamelCase							,       bos_token_id=__lowerCamelCase							,       eos_token_id=__lowerCamelCase							,       **__lowerCamelCase				)

     _snake_case   	=      vocab_size
     _snake_case   	=      hidden_size
     _snake_case   	=      num_hidden_layers
     _snake_case   	=      num_attention_heads
     _snake_case   	=      hidden_act
     _snake_case   	=      intermediate_size
     _snake_case   	=      hidden_dropout_prob
     _snake_case   	=      attention_probs_dropout_prob
     _snake_case   	=      max_position_embeddings
     _snake_case   	=      initializer_range
     _snake_case   	=      layer_norm_eps
     _snake_case   	=      position_embedding_type
     _snake_case   	=      use_cache





