


import torch

from diffusers import EulerAncestralDiscreteScheduler
from diffusers.utils import torch_device

from .test_schedulers import SchedulerCommonTest







class 					snake_case__(				UpperCAmelCase__				):







						'''simple docstring'''




						SCREAMING_SNAKE_CASE__   :	Any       =				(EulerAncestralDiscreteScheduler,)
						SCREAMING_SNAKE_CASE__   :	str       =				10




						def     lowercase_			(					self ,    **__lowercase				)       ->     Tuple:
										lowerCAmelCase_			:   Dict     					=					{
										    '''num_train_timesteps''': 1_1_0_0,
										    '''beta_start''': 0.00_01,
										    '''beta_end''': 0.02,
										    '''beta_schedule''': '''linear''',
										}

										config.update(**__lowercase				)
										return config




						def     lowercase_			(					self				)       ->     Any:
										for timesteps in [1_0, 5_0, 1_0_0, 1_0_0_0]:
														self.check_over_configs(num_train_timesteps=__lowercase				)




						def     lowercase_			(					self				)       ->     Any:
										for beta_start, beta_end in zip([0.0_00_01, 0.00_01, 0.0_01] ,    [0.00_02, 0.0_02, 0.02]				):
														self.check_over_configs(beta_start=__lowercase ,    beta_end=__lowercase				)




						def     lowercase_			(					self				)       ->     List[str]:
										for schedule in ["linear", "scaled_linear"]:
														self.check_over_configs(beta_schedule=__lowercase				)




						def     lowercase_			(					self				)       ->     Tuple:
										for prediction_type in ["epsilon", "v_prediction"]:
														self.check_over_configs(prediction_type=__lowercase				)




						def     lowercase_			(					self				)       ->     Tuple:
										lowerCAmelCase_			:   int     					=					self.scheduler_classes[0]
										lowerCAmelCase_			:   int     					=					self.get_scheduler_config()
										lowerCAmelCase_			:   List[Any]     					=					scheduler_class(**__lowercase				)

										scheduler.set_timesteps(self.num_inference_steps				)

										lowerCAmelCase_			:   str     					=					torch.manual_seed(0				)

										lowerCAmelCase_			:   Tuple     					=					self.dummy_model()
										lowerCAmelCase_			:   Dict     					=					self.dummy_sample_deter * scheduler.init_noise_sigma.cpu()
										lowerCAmelCase_			:   List[str]     					=					sample.to(__lowercase				)

										for i, t in enumerate(scheduler.timesteps				):
														lowerCAmelCase_			:   Tuple     					=					scheduler.scale_model_input(__lowercase ,    __lowercase				)

														lowerCAmelCase_			:   str     					=					model(__lowercase ,    __lowercase				)

														lowerCAmelCase_			:   List[Any]     					=					scheduler.step(__lowercase ,    __lowercase ,    __lowercase ,    generator=__lowercase				)
														lowerCAmelCase_			:   Any     					=					output.prev_sample

										lowerCAmelCase_			:   int     					=					torch.sum(torch.abs(__lowercase				)				)
										lowerCAmelCase_			:   Dict     					=					torch.mean(torch.abs(__lowercase				)				)

										assert abs(result_sum.item() - 1_52.31_92				) < 1e-2
										assert abs(result_mean.item() - 0.19_83				) < 1e-3




						def     lowercase_			(					self				)       ->     List[str]:
										lowerCAmelCase_			:   int     					=					self.scheduler_classes[0]
										lowerCAmelCase_			:   Tuple     					=					self.get_scheduler_config(prediction_type='''v_prediction'''				)
										lowerCAmelCase_			:   Dict     					=					scheduler_class(**__lowercase				)

										scheduler.set_timesteps(self.num_inference_steps				)

										lowerCAmelCase_			:   List[str]     					=					torch.manual_seed(0				)

										lowerCAmelCase_			:   List[str]     					=					self.dummy_model()
										lowerCAmelCase_			:   List[Any]     					=					self.dummy_sample_deter * scheduler.init_noise_sigma
										lowerCAmelCase_			:   List[str]     					=					sample.to(__lowercase				)

										for i, t in enumerate(scheduler.timesteps				):
														lowerCAmelCase_			:   int     					=					scheduler.scale_model_input(__lowercase ,    __lowercase				)

														lowerCAmelCase_			:   List[Any]     					=					model(__lowercase ,    __lowercase				)

														lowerCAmelCase_			:   Any     					=					scheduler.step(__lowercase ,    __lowercase ,    __lowercase ,    generator=__lowercase				)
														lowerCAmelCase_			:   int     					=					output.prev_sample

										lowerCAmelCase_			:   int     					=					torch.sum(torch.abs(__lowercase				)				)
										lowerCAmelCase_			:   int     					=					torch.mean(torch.abs(__lowercase				)				)

										assert abs(result_sum.item() - 1_08.44_39				) < 1e-2
										assert abs(result_mean.item() - 0.14_12				) < 1e-3




						def     lowercase_			(					self				)       ->     str:
										lowerCAmelCase_			:   int     					=					self.scheduler_classes[0]
										lowerCAmelCase_			:   int     					=					self.get_scheduler_config()
										lowerCAmelCase_			:   Optional[int]     					=					scheduler_class(**__lowercase				)

										scheduler.set_timesteps(self.num_inference_steps ,    device=__lowercase				)
										lowerCAmelCase_			:   int     					=					torch.manual_seed(0				)

										lowerCAmelCase_			:   Union[str, Any]     					=					self.dummy_model()
										lowerCAmelCase_			:   Optional[Any]     					=					self.dummy_sample_deter * scheduler.init_noise_sigma.cpu()
										lowerCAmelCase_			:   Optional[int]     					=					sample.to(__lowercase				)

										for t in scheduler.timesteps:
														lowerCAmelCase_			:   str     					=					scheduler.scale_model_input(__lowercase ,    __lowercase				)

														lowerCAmelCase_			:   Dict     					=					model(__lowercase ,    __lowercase				)

														lowerCAmelCase_			:   List[str]     					=					scheduler.step(__lowercase ,    __lowercase ,    __lowercase ,    generator=__lowercase				)
														lowerCAmelCase_			:   int     					=					output.prev_sample

										lowerCAmelCase_			:   Any     					=					torch.sum(torch.abs(__lowercase				)				)
										lowerCAmelCase_			:   Optional[Any]     					=					torch.mean(torch.abs(__lowercase				)				)

										assert abs(result_sum.item() - 1_52.31_92				) < 1e-2
										assert abs(result_mean.item() - 0.19_83				) < 1e-3



import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DiffusionPipeline,
    EulerDiscreteScheduler,
    StableDiffusionXLPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()







class 					snake_case__(				UpperCAmelCase__,    UpperCAmelCase__,    unittest.TestCase				):







						'''simple docstring'''




						SCREAMING_SNAKE_CASE__   :	str       =				StableDiffusionXLPipeline
						SCREAMING_SNAKE_CASE__   :	Dict       =				TEXT_TO_IMAGE_PARAMS
						SCREAMING_SNAKE_CASE__   :	Optional[int]       =				TEXT_TO_IMAGE_BATCH_PARAMS
						SCREAMING_SNAKE_CASE__   :	Optional[Any]       =				TEXT_TO_IMAGE_IMAGE_PARAMS
						SCREAMING_SNAKE_CASE__   :	int       =				TEXT_TO_IMAGE_IMAGE_PARAMS




						def     lowercase_			(					self				)       ->     int:
										torch.manual_seed(0				)
										lowerCAmelCase_			:   Tuple     					=					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''') ,    attention_head_dim=(2, 4) ,    use_linear_projection=__lowercase ,    addition_embed_type='''text_time''' ,    addition_time_embed_dim=8 ,    transformer_layers_per_block=(1, 2) ,    projection_class_embeddings_input_dim=8_0 ,    cross_attention_dim=6_4 ,    )
										lowerCAmelCase_			:   Any     					=					EulerDiscreteScheduler(
										    beta_start=0.0_00_85 ,    beta_end=0.0_12 ,    steps_offset=1 ,    beta_schedule='''scaled_linear''' ,    timestep_spacing='''leading''' ,    )
										torch.manual_seed(0				)
										lowerCAmelCase_			:   Any     					=					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 ,    sample_size=1_2_8 ,    )
										torch.manual_seed(0				)
										lowerCAmelCase_			:   Dict     					=					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 ,    hidden_act='''gelu''' ,    projection_dim=3_2 ,    )
										lowerCAmelCase_			:   str     					=					CLIPTextModel(__lowercase				)
										lowerCAmelCase_			:   List[str]     					=					CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ,    local_files_only=__lowercase				)

										lowerCAmelCase_			:   Tuple     					=					CLIPTextModelWithProjection(__lowercase				)
										lowerCAmelCase_			:   Optional[Any]     					=					CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ,    local_files_only=__lowercase				)

										lowerCAmelCase_			:   int     					=					{
										    '''unet''': unet,
										    '''scheduler''': scheduler,
										    '''vae''': vae,
										    '''text_encoder''': text_encoder,
										    '''tokenizer''': tokenizer,
										    '''text_encoder_2''': text_encoder_a,
										    '''tokenizer_2''': tokenizer_a,
										    # "safety_checker": None,
										    # "feature_extractor": None,
										}
										return components




						def     lowercase_			(					self ,    __lowercase ,    __lowercase=0				)       ->     Dict:
										if str(__lowercase				).startswith('''mps'''				):
														lowerCAmelCase_			:   Dict     					=					torch.manual_seed(__lowercase				)
										else:
														lowerCAmelCase_			:   Dict     					=					torch.Generator(device=__lowercase				).manual_seed(__lowercase				)
										lowerCAmelCase_			:   Dict     					=					{
										    '''prompt''': '''A painting of a squirrel eating a burger''',
										    '''generator''': generator,
										    '''num_inference_steps''': 2,
										    '''guidance_scale''': 5.0,
										    '''output_type''': '''numpy''',
										}
										return inputs




						def     lowercase_			(					self				)       ->     Optional[Any]:
										lowerCAmelCase_			:   Union[str, Any]     					=					'''cpu'''  # ensure determinism for the device-dependent torch.Generator
										lowerCAmelCase_			:   Any     					=					self.get_dummy_components()
										lowerCAmelCase_			:   Optional[int]     					=					StableDiffusionXLPipeline(**__lowercase				)
										lowerCAmelCase_			:   Optional[int]     					=					sd_pipe.to(__lowercase				)
										sd_pipe.set_progress_bar_config(disable=__lowercase				)

										lowerCAmelCase_			:   Dict     					=					self.get_dummy_inputs(__lowercase				)
										lowerCAmelCase_			:   str     					=					sd_pipe(**__lowercase				).images
										lowerCAmelCase_			:   Any     					=					image[0, -3:, -3:, -1]

										assert image.shape == (1, 6_4, 6_4, 3)
										lowerCAmelCase_			:   str     					=					np.array([0.58_73, 0.61_28, 0.47_97, 0.51_22, 0.56_74, 0.46_39, 0.52_27, 0.51_49, 0.47_47]				)

										assert np.abs(image_slice.flatten() - expected_slice				).max() < 1e-2




						def     lowercase_			(					self				)       ->     List[Any]:
										lowerCAmelCase_			:   Any     					=					self.get_dummy_components()
										lowerCAmelCase_			:   List[Any]     					=					StableDiffusionXLPipeline(**__lowercase				)
										lowerCAmelCase_			:   List[Any]     					=					sd_pipe.to(__lowercase				)
										lowerCAmelCase_			:   int     					=					sd_pipe.to(__lowercase				)
										sd_pipe.set_progress_bar_config(disable=__lowercase				)

										# forward without prompt embeds
										lowerCAmelCase_			:   Optional[Any]     					=					self.get_dummy_inputs(__lowercase				)
										lowerCAmelCase_			:   List[str]     					=					3 * ['''this is a negative prompt''']
										lowerCAmelCase_			:   Union[str, Any]     					=					negative_prompt
										lowerCAmelCase_			:   Union[str, Any]     					=					3 * [inputs['''prompt''']]

										lowerCAmelCase_			:   str     					=					sd_pipe(**__lowercase				)
										lowerCAmelCase_			:   Any     					=					output.images[0, -3:, -3:, -1]

										# forward with prompt embeds
										lowerCAmelCase_			:   Tuple     					=					self.get_dummy_inputs(__lowercase				)
										lowerCAmelCase_			:   Dict     					=					3 * ['''this is a negative prompt''']
										lowerCAmelCase_			:   Dict     					=					3 * [inputs.pop('''prompt'''				)]

										(
										    (
										    lowerCAmelCase_
										)					,	(
										    lowerCAmelCase_
										)					,	(
										    lowerCAmelCase_
										)					,	(
										    lowerCAmelCase_
										)					,	
										)			:   str     					=					sd_pipe.encode_prompt(__lowercase ,    negative_prompt=__lowercase				)

										lowerCAmelCase_			:   List[Any]     					=					sd_pipe(
										    **__lowercase ,    prompt_embeds=__lowercase ,    negative_prompt_embeds=__lowercase ,    pooled_prompt_embeds=__lowercase ,    negative_pooled_prompt_embeds=__lowercase ,    )
										lowerCAmelCase_			:   int     					=					output.images[0, -3:, -3:, -1]

										# make sure that it's equal
										assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()				).max() < 1e-4




						def     lowercase_			(					self				)       ->     List[str]:
										super().test_attention_slicing_forward_pass(expected_max_diff=3e-3				)




						def     lowercase_			(					self				)       ->     Tuple:
										super().test_inference_batch_single_identical(expected_max_diff=3e-3				)







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







						'''simple docstring'''




						def     lowercase_			(					self				)       ->     int:
										super().tearDown()
										gc.collect()
										torch.cuda.empty_cache()




						def     lowercase_			(					self ,    __lowercase ,    __lowercase="cpu" ,    __lowercase=torch.floataa ,    __lowercase=0				)       ->     Dict:
										lowerCAmelCase_			:   Any     					=					torch.Generator(device=__lowercase				).manual_seed(__lowercase				)
										lowerCAmelCase_			:   str     					=					np.random.RandomState(__lowercase				).standard_normal((1, 4, 6_4, 6_4)				)
										lowerCAmelCase_			:   List[str]     					=					torch.from_numpy(__lowercase				).to(device=__lowercase ,    dtype=__lowercase				)
										lowerCAmelCase_			:   Optional[Any]     					=					{
										    '''prompt''': '''a photograph of an astronaut riding a horse''',
										    '''latents''': latents,
										    '''generator''': generator,
										    '''num_inference_steps''': 3,
										    '''guidance_scale''': 7.5,
										    '''output_type''': '''numpy''',
										}
										return inputs




						def     lowercase_			(					self				)       ->     List[str]:
										lowerCAmelCase_			:   Optional[int]     					=					DiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-base'''				)
										pipe.to(__lowercase				)
										pipe.set_progress_bar_config(disable=__lowercase				)

										lowerCAmelCase_			:   Any     					=					self.get_inputs(__lowercase				)
										lowerCAmelCase_			:   List[str]     					=					pipe(**__lowercase				).images
										lowerCAmelCase_			:   Dict     					=					image[0, -3:, -3:, -1].flatten()

										assert image.shape == (1, 5_1_2, 5_1_2, 3)
										lowerCAmelCase_			:   Optional[int]     					=					np.array([0.4_94_93, 0.4_78_96, 0.4_07_98, 0.5_42_14, 0.5_32_12, 0.4_82_02, 0.4_76_56, 0.4_63_29, 0.4_85_06]				)
										assert np.abs(image_slice - expected_slice				).max() < 7e-3