




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"""


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




     def     __A							(      self     :					Dict		)						->  List[str]:


         '''simple docstring'''





         torch.manual_seed(0		)
         SCREAMING_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							,)
         SCREAMING_SNAKE_CASE__        =DDIMScheduler(
             beta_start=0.0_0085							,beta_end=0.012							,beta_schedule="""scaled_linear"""							,clip_sample=_UpperCamelCase							,set_alpha_to_one=_UpperCamelCase							,)
         torch.manual_seed(0		)
         SCREAMING_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		)
         SCREAMING_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							,)
         SCREAMING_SNAKE_CASE__        =CLIPTextModel(_UpperCamelCase		)
         SCREAMING_SNAKE_CASE__        =CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""		)

         SCREAMING_SNAKE_CASE__        ={
             """unet""": unet,
             """scheduler""": scheduler,
             """vqvae""": vae,
             """bert""": text_encoder,
             """tokenizer""": tokenizer,
         }
         return components




     def     __A							(      self     :					str							,_UpperCamelCase     :					Tuple							,_UpperCamelCase     :					Optional[Any]=0		)						->  str:


         '''simple docstring'''





         if str(_UpperCamelCase		).startswith("""mps"""		):
             SCREAMING_SNAKE_CASE__        =torch.manual_seed(_UpperCamelCase		)
         else:
             SCREAMING_SNAKE_CASE__        =torch.Generator(device=_UpperCamelCase		).manual_seed(_UpperCamelCase		)
         SCREAMING_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     __A							(      self     :					Tuple		)						->  List[Any]:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__        ="""cpu"""  # ensure determinism for the device-dependent torch.Generator

         SCREAMING_SNAKE_CASE__        =self.get_dummy_components()
         SCREAMING_SNAKE_CASE__        =LDMTextToImagePipeline(**_UpperCamelCase		)
         pipe.to(_UpperCamelCase		)
         pipe.set_progress_bar_config(disable=_UpperCamelCase		)

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

         assert image.shape == (1, 1_6, 1_6, 3)
         SCREAMING_SNAKE_CASE__        =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[Any]		)						->  str:


         '''simple docstring'''





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




     def     __A							(      self     :					Any							,_UpperCamelCase     :					Any							,_UpperCamelCase     :					Any=torch.floataa							,_UpperCamelCase     :					Optional[Any]=0		)						->  List[Any]:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__        =torch.manual_seed(_UpperCamelCase		)
         SCREAMING_SNAKE_CASE__        =np.random.RandomState(_UpperCamelCase		).standard_normal((1, 4, 3_2, 3_2)		)
         SCREAMING_SNAKE_CASE__        =torch.from_numpy(_UpperCamelCase		).to(device=_UpperCamelCase							,dtype=_UpperCamelCase		)
         SCREAMING_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     __A							(      self     :					Tuple		)						->  Union[str, Any]:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__        =LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256"""		).to(_UpperCamelCase		)
         pipe.set_progress_bar_config(disable=_UpperCamelCase		)

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

         assert image.shape == (1, 2_5_6, 2_5_6, 3)
         SCREAMING_SNAKE_CASE__        =np.array([0.5_1825, 0.5_2850, 0.5_2543, 0.5_4258, 0.5_2304, 0.5_2569, 0.5_4363, 0.5_5276, 0.5_6878]		)
         SCREAMING_SNAKE_CASE__        =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     :					Any		)						->  Optional[int]:


         '''simple docstring'''





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




     def     __A							(      self     :					List[Any]							,_UpperCamelCase     :					Union[str, Any]							,_UpperCamelCase     :					Tuple=torch.floataa							,_UpperCamelCase     :					Union[str, Any]=0		)						->  int:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__        =torch.manual_seed(_UpperCamelCase		)
         SCREAMING_SNAKE_CASE__        =np.random.RandomState(_UpperCamelCase		).standard_normal((1, 4, 3_2, 3_2)		)
         SCREAMING_SNAKE_CASE__        =torch.from_numpy(_UpperCamelCase		).to(device=_UpperCamelCase							,dtype=_UpperCamelCase		)
         SCREAMING_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     __A							(      self     :					int		)						->  Optional[Any]:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__        =LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256"""		).to(_UpperCamelCase		)
         pipe.set_progress_bar_config(disable=_UpperCamelCase		)

         SCREAMING_SNAKE_CASE__        =self.get_inputs(_UpperCamelCase		)
         SCREAMING_SNAKE_CASE__        =pipe(**_UpperCamelCase		).images[0]

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










"""simple docstring"""
from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_tf_available,
    is_torch_available,
)


UpperCAmelCase				=						{
    """configuration_vision_encoder_decoder""": ["""VisionEncoderDecoderConfig""", """VisionEncoderDecoderOnnxConfig"""]
}

try:
 if not is_torch_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 UpperCAmelCase				=						["""VisionEncoderDecoderModel"""]

try:
 if not is_tf_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 UpperCAmelCase				=						["""TFVisionEncoderDecoderModel"""]

try:
 if not is_flax_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 UpperCAmelCase				=						["""FlaxVisionEncoderDecoderModel"""]

if TYPE_CHECKING:
 from .configuration_vision_encoder_decoder import VisionEncoderDecoderConfig, VisionEncoderDecoderOnnxConfig

 try:
  if not is_torch_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_vision_encoder_decoder import VisionEncoderDecoderModel

 try:
  if not is_tf_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_tf_vision_encoder_decoder import TFVisionEncoderDecoderModel

 try:
  if not is_flax_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_flax_vision_encoder_decoder import FlaxVisionEncoderDecoderModel

else:
 import sys

 UpperCAmelCase				=						_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)

