



'''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 __A    (						A     ,     unittest.TestCase		):



 '''simple docstring'''







 __lowerCamelCase					: int    = LDMTextToImagePipeline
 __lowerCamelCase					: List[Any]    = TEXT_TO_IMAGE_PARAMS - {
     'negative_prompt',
     'negative_prompt_embeds',
     'cross_attention_kwargs',
     'prompt_embeds',
 }
 __lowerCamelCase					: Optional[Any]    = PipelineTesterMixin.required_optional_params - {
     'num_images_per_prompt',
     'callback',
     'callback_steps',
 }
 __lowerCamelCase					: Optional[int]    = TEXT_TO_IMAGE_BATCH_PARAMS
 __lowerCamelCase					: Dict    = False



 def       a__						(self )					->  List[str]:


      """simple docstring"""



      torch.manual_seed(0 )
      _a											=						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				,     )
      _a											=						DDIMScheduler(
          beta_start=0.00085				,     beta_end=0.012				,     beta_schedule='''scaled_linear'''				,     clip_sample=A				,     set_alpha_to_one=A				,     )
      torch.manual_seed(0 )
      _a											=						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 )
      _a											=						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=1_000				,     )
      _a											=						CLIPTextModel(A )
      _a											=						CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' )

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



 def       a__						(self				,     A				,     A=0 )					->  Tuple:


      """simple docstring"""



      if str(A ).startswith('''mps''' ):
           _a											=						torch.manual_seed(A )
      else:
           _a											=						torch.Generator(device=A ).manual_seed(A )
      _a											=						{
          '''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       a__						(self )					->  Union[str, Any]:


      """simple docstring"""



      _a											=						'''cpu'''  # ensure determinism for the device-dependent torch.Generator

      _a											=						self.get_dummy_components()
      _a											=						LDMTextToImagePipeline(**A )
      pipe.to(A )
      pipe.set_progress_bar_config(disable=A )

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

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



 '''simple docstring'''







 def       a__						(self )					->  Optional[int]:


      """simple docstring"""



      super().tearDown()
      gc.collect()
      torch.cuda.empty_cache()



 def       a__						(self				,     A				,     A=torch.floataa				,     A=0 )					->  Tuple:


      """simple docstring"""



      _a											=						torch.manual_seed(A )
      _a											=						np.random.RandomState(A ).standard_normal((1, 4, 32, 32) )
      _a											=						torch.from_numpy(A ).to(device=A				,     dtype=A )
      _a											=						{
          '''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       a__						(self )					->  Optional[Any]:


      """simple docstring"""



      _a											=						LDMTextToImagePipeline.from_pretrained('''CompVis/ldm-text2im-large-256''' ).to(A )
      pipe.set_progress_bar_config(disable=A )

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

      assert image.shape == (1, 256, 256, 3)
      _a											=						np.array([0.51825, 0.52850, 0.52543, 0.54258, 0.52304, 0.52569, 0.54363, 0.55276, 0.56878] )
      _a											=						np.abs(expected_slice - image_slice ).max()
      assert max_diff < 1E-3






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



 '''simple docstring'''







 def       a__						(self )					->  Tuple:


      """simple docstring"""



      super().tearDown()
      gc.collect()
      torch.cuda.empty_cache()



 def       a__						(self				,     A				,     A=torch.floataa				,     A=0 )					->  Optional[Any]:


      """simple docstring"""



      _a											=						torch.manual_seed(A )
      _a											=						np.random.RandomState(A ).standard_normal((1, 4, 32, 32) )
      _a											=						torch.from_numpy(A ).to(device=A				,     dtype=A )
      _a											=						{
          '''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       a__						(self )					->  Union[str, Any]:


      """simple docstring"""



      _a											=						LDMTextToImagePipeline.from_pretrained('''CompVis/ldm-text2im-large-256''' ).to(A )
      pipe.set_progress_bar_config(disable=A )

      _a											=						self.get_inputs(A )
      _a											=						pipe(**A ).images[0]

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








'''simple docstring'''





from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowercase_	 =						logging.get_logger(__name__)

lowercase_	 =						{
    "google/pegasus-large": "https://huggingface.co/google/pegasus-large/resolve/main/config.json",
    # See all PEGASUS models at https://huggingface.co/models?filter=pegasus
}






class __A    (						A		):



 '''simple docstring'''







 __lowerCamelCase					: Union[str, Any]    = 'pegasus'
 __lowerCamelCase					: Tuple    = ['past_key_values']
 __lowerCamelCase					: List[Any]    = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'}



 def __init__(self				,     A=50_265				,     A=1_024				,     A=12				,     A=4_096				,     A=16				,     A=12				,     A=4_096				,     A=16				,     A=0.0				,     A=0.0				,     A=True				,     A=True				,     A="gelu"				,     A=1_024				,     A=0.1				,     A=0.0				,     A=0.0				,     A=0.02				,     A=0				,     A=False				,     A=0				,     A=1				,     A=1				,     **A				,     )					->  str:


      """simple docstring"""



      _a											=						vocab_size
      _a											=						max_position_embeddings
      _a											=						d_model
      _a											=						encoder_ffn_dim
      _a											=						encoder_layers
      _a											=						encoder_attention_heads
      _a											=						decoder_ffn_dim
      _a											=						decoder_layers
      _a											=						decoder_attention_heads
      _a											=						dropout
      _a											=						attention_dropout
      _a											=						activation_dropout
      _a											=						activation_function
      _a											=						init_std
      _a											=						encoder_layerdrop
      _a											=						decoder_layerdrop
      _a											=						use_cache
      _a											=						encoder_layers
      _a											=						scale_embedding  # scale factor will be sqrt(d_model) if True
      super().__init__(
          pad_token_id=A				,     eos_token_id=A				,     is_encoder_decoder=A				,     decoder_start_token_id=A				,     forced_eos_token_id=A				,     **A				,     )



 @property
 def       a__						(self )					->  int:


      """simple docstring"""



      return self.encoder_attention_heads



 @property
 def       a__						(self )					->  int:


      """simple docstring"""



      return self.d_model



