





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






				"""simple docstring"""







				__a            =LDMTextToImagePipeline
				__a            =TEXT_TO_IMAGE_PARAMS - {
				    'negative_prompt',
				    'negative_prompt_embeds',
				    'cross_attention_kwargs',
				    'prompt_embeds',
				}
				__a            =PipelineTesterMixin.required_optional_params - {
				    'num_images_per_prompt',
				    'callback',
				    'callback_steps',
				}
				__a            =TEXT_TO_IMAGE_BATCH_PARAMS
				__a            =False




				def   UpperCamelCase__   (  self     :					List[str]					):
								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-0_5					,				num_attention_heads=4					,				num_hidden_layers=5					,				pad_token_id=1					,				vocab_size=10_00					,				)
								_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   UpperCamelCase__   (  self     :					Tuple					,				__a     :					Any					,				__a     :					Tuple=0					):
								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   UpperCamelCase__   (  self     :					int					):
								_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 				__SCREAMING_SNAKE_CASE  (unittest.TestCase      ):






				"""simple docstring"""







				def   UpperCamelCase__   (  self     :					Union[str, Any]					):
								super().tearDown()
								gc.collect()
								torch.cuda.empty_cache()




				def   UpperCamelCase__   (  self     :					Union[str, Any]					,				__a     :					str					,				__a     :					Union[str, Any]=torch.floataa					,				__a     :					str=0					):
								_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   UpperCamelCase__   (  self     :					Union[str, Any]					):
								_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, 2_56, 2_56, 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 				__SCREAMING_SNAKE_CASE  (unittest.TestCase      ):






				"""simple docstring"""







				def   UpperCamelCase__   (  self     :					List[str]					):
								super().tearDown()
								gc.collect()
								torch.cuda.empty_cache()




				def   UpperCamelCase__   (  self     :					Any					,				__a     :					Optional[int]					,				__a     :					int=torch.floataa					,				__a     :					List[str]=0					):
								_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   UpperCamelCase__   (  self     :					Optional[Any]					):
								_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







from ..utils import (
    OptionalDependencyNotAvailable,
    is_flax_available,
    is_scipy_available,
    is_torch_available,
    is_torchsde_available,
)


try:
     if not is_torch_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     from ..utils.dummy_pt_objects import *  # noqa F403
else:
     from .scheduling_consistency_models import CMStochasticIterativeScheduler
     from .scheduling_ddim import DDIMScheduler
     from .scheduling_ddim_inverse import DDIMInverseScheduler
     from .scheduling_ddim_parallel import DDIMParallelScheduler
     from .scheduling_ddpm import DDPMScheduler
     from .scheduling_ddpm_parallel import DDPMParallelScheduler
     from .scheduling_deis_multistep import DEISMultistepScheduler
     from .scheduling_dpmsolver_multistep import DPMSolverMultistepScheduler
     from .scheduling_dpmsolver_multistep_inverse import DPMSolverMultistepInverseScheduler
     from .scheduling_dpmsolver_singlestep import DPMSolverSinglestepScheduler
     from .scheduling_euler_ancestral_discrete import EulerAncestralDiscreteScheduler
     from .scheduling_euler_discrete import EulerDiscreteScheduler
     from .scheduling_heun_discrete import HeunDiscreteScheduler
     from .scheduling_ipndm import IPNDMScheduler
     from .scheduling_k_dpm_2_ancestral_discrete import KDPMaAncestralDiscreteScheduler
     from .scheduling_k_dpm_2_discrete import KDPMaDiscreteScheduler
     from .scheduling_karras_ve import KarrasVeScheduler
     from .scheduling_pndm import PNDMScheduler
     from .scheduling_repaint import RePaintScheduler
     from .scheduling_sde_ve import ScoreSdeVeScheduler
     from .scheduling_sde_vp import ScoreSdeVpScheduler
     from .scheduling_unclip import UnCLIPScheduler
     from .scheduling_unipc_multistep import UniPCMultistepScheduler
     from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin
     from .scheduling_vq_diffusion import VQDiffusionScheduler

try:
     if not is_flax_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     from ..utils.dummy_flax_objects import *  # noqa F403
else:
     from .scheduling_ddim_flax import FlaxDDIMScheduler
     from .scheduling_ddpm_flax import FlaxDDPMScheduler
     from .scheduling_dpmsolver_multistep_flax import FlaxDPMSolverMultistepScheduler
     from .scheduling_karras_ve_flax import FlaxKarrasVeScheduler
     from .scheduling_lms_discrete_flax import FlaxLMSDiscreteScheduler
     from .scheduling_pndm_flax import FlaxPNDMScheduler
     from .scheduling_sde_ve_flax import FlaxScoreSdeVeScheduler
     from .scheduling_utils_flax import (
         FlaxKarrasDiffusionSchedulers,
         FlaxSchedulerMixin,
         FlaxSchedulerOutput,
         broadcast_to_shape_from_left,
     )


try:
     if not (is_torch_available() and is_scipy_available()):
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     from ..utils.dummy_torch_and_scipy_objects import *  # noqa F403
else:
     from .scheduling_lms_discrete import LMSDiscreteScheduler

try:
     if not (is_torch_available() and is_torchsde_available()):
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     from ..utils.dummy_torch_and_torchsde_objects import *  # noqa F403
else:
     from .scheduling_dpmsolver_sde import DPMSolverSDEScheduler

