





'''simple docstring'''







import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    StableDiffusionSAGPipeline,
    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 					__a      (lowerCamelCase       ,		lowerCamelCase       ,		unittest.TestCase     ):
							__a					:   Optional[Any]									=       StableDiffusionSAGPipeline
							__a					:   Optional[Any]									=       TEXT_TO_IMAGE_PARAMS
							__a					:   int									=       TEXT_TO_IMAGE_BATCH_PARAMS
							__a					:   str									=       TEXT_TO_IMAGE_IMAGE_PARAMS
							__a					:   Union[str, Any]									=       TEXT_TO_IMAGE_IMAGE_PARAMS
							__a					:   Dict									=       False

							def     UpperCAmelCase__	(							self							:     str   )					->       Tuple:







													"""simple docstring"""
													torch.manual_seed(0   )
													UpperCAmelCase_			:      Tuple     						=  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       ,     )
													UpperCAmelCase_			:      Tuple     						=  DDIMScheduler(
													    beta_start=0.0_0_0_8_5       ,     beta_end=0.0_1_2       ,     beta_schedule='''scaled_linear'''       ,     clip_sample=__magic_name__       ,     set_alpha_to_one=__magic_name__       ,     )
													torch.manual_seed(0   )
													UpperCAmelCase_			:      Optional[Any]     						=  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   )
													UpperCAmelCase_			:      Any     						=  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=10_00       ,     )
													UpperCAmelCase_			:      Tuple     						=  CLIPTextModel(__magic_name__   )
													UpperCAmelCase_			:      int     						=  CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''   )

													UpperCAmelCase_			:      Tuple     						=  {
													    '''unet''': unet,
													    '''scheduler''': scheduler,
													    '''vae''': vae,
													    '''text_encoder''': text_encoder,
													    '''tokenizer''': tokenizer,
													    '''safety_checker''': None,
													    '''feature_extractor''': None,
													}
													return components

							def     UpperCAmelCase__	(							self							:     Tuple       ,     __magic_name__							:     Union[str, Any]       ,     __magic_name__							:     str=0   )					->       Tuple:







													"""simple docstring"""
													if str(__magic_name__   ).startswith('''mps'''   ):
																			UpperCAmelCase_			:      List[Any]     						=  torch.manual_seed(__magic_name__   )
													else:
																			UpperCAmelCase_			:      int     						=  torch.Generator(device=__magic_name__   ).manual_seed(__magic_name__   )
													UpperCAmelCase_			:      Union[str, Any]     						=  {
													    '''prompt''': '''.''',
													    '''generator''': generator,
													    '''num_inference_steps''': 2,
													    '''guidance_scale''': 1.0,
													    '''sag_scale''': 1.0,
													    '''output_type''': '''numpy''',
													}
													return inputs



							def     UpperCAmelCase__	(							self							:     List[Any]   )					->       str:







													"""simple docstring"""
													super().test_inference_batch_single_identical(expected_max_diff=3E-3   )





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

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







													"""simple docstring"""
													# clean up the VRAM after each test
													super().tearDown()
													gc.collect()
													torch.cuda.empty_cache()

							def     UpperCAmelCase__	(							self							:     int   )					->       Optional[Any]:







													"""simple docstring"""
													UpperCAmelCase_			:      List[Any]     						=  StableDiffusionSAGPipeline.from_pretrained('''CompVis/stable-diffusion-v1-4'''   )
													UpperCAmelCase_			:      Optional[int]     						=  sag_pipe.to(__magic_name__   )
													sag_pipe.set_progress_bar_config(disable=__magic_name__   )

													UpperCAmelCase_			:      Any     						=  '''.'''
													UpperCAmelCase_			:      int     						=  torch.manual_seed(0   )
													UpperCAmelCase_			:      Optional[Any]     						=  sag_pipe(
													    [prompt]       ,     generator=__magic_name__       ,     guidance_scale=7.5       ,     sag_scale=1.0       ,     num_inference_steps=20       ,     output_type='''np'''   )

													UpperCAmelCase_			:      Any     						=  output.images

													UpperCAmelCase_			:      Any     						=  image[0, -3:, -3:, -1]

													assert image.shape == (1, 5_12, 5_12, 3)
													UpperCAmelCase_			:      Union[str, Any]     						=  np.array([0.1_5_6_8, 0.1_7_3_8, 0.1_6_9_5, 0.1_6_9_3, 0.1_5_0_7, 0.1_7_0_5, 0.1_5_4_7, 0.1_7_5_1, 0.1_9_4_9]   )

													assert np.abs(image_slice.flatten() - expected_slice   ).max() < 5E-2

							def     UpperCAmelCase__	(							self							:     List[Any]   )					->       Optional[Any]:







													"""simple docstring"""
													UpperCAmelCase_			:      Optional[Any]     						=  StableDiffusionSAGPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base'''   )
													UpperCAmelCase_			:      Any     						=  sag_pipe.to(__magic_name__   )
													sag_pipe.set_progress_bar_config(disable=__magic_name__   )

													UpperCAmelCase_			:      Any     						=  '''.'''
													UpperCAmelCase_			:      int     						=  torch.manual_seed(0   )
													UpperCAmelCase_			:      str     						=  sag_pipe(
													    [prompt]       ,     generator=__magic_name__       ,     guidance_scale=7.5       ,     sag_scale=1.0       ,     num_inference_steps=20       ,     output_type='''np'''   )

													UpperCAmelCase_			:      List[Any]     						=  output.images

													UpperCAmelCase_			:      Union[str, Any]     						=  image[0, -3:, -3:, -1]

													assert image.shape == (1, 5_12, 5_12, 3)
													UpperCAmelCase_			:      Tuple     						=  np.array([0.3_4_5_9, 0.2_8_7_6, 0.2_5_3_7, 0.3_0_0_2, 0.2_6_7_1, 0.2_1_6_0, 0.3_0_2_6, 0.2_2_6_2, 0.2_3_7_1]   )

													assert np.abs(image_slice.flatten() - expected_slice   ).max() < 5E-2



							def     UpperCAmelCase__	(							self							:     List[Any]   )					->       Optional[Any]:







													"""simple docstring"""
													UpperCAmelCase_			:      Optional[Any]     						=  StableDiffusionSAGPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base'''   )
													UpperCAmelCase_			:      Tuple     						=  sag_pipe.to(__magic_name__   )
													sag_pipe.set_progress_bar_config(disable=__magic_name__   )

													UpperCAmelCase_			:      Optional[Any]     						=  '''.'''
													UpperCAmelCase_			:      str     						=  torch.manual_seed(0   )
													UpperCAmelCase_			:      List[Any]     						=  sag_pipe(
													    [prompt]       ,     width=7_68       ,     height=5_12       ,     generator=__magic_name__       ,     guidance_scale=7.5       ,     sag_scale=1.0       ,     num_inference_steps=20       ,     output_type='''np'''       ,     )

													UpperCAmelCase_			:      Optional[int]     						=  output.images

													assert image.shape == (1, 5_12, 7_68, 3)












'''simple docstring'''







from typing import Any, Callable, Dict, List, Optional, Union

import torch
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    LMSDiscreteScheduler,
    PNDMScheduler,
    StableDiffusionPipeline,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker


snake_case_     :       Union[str, Any]						=  "CompVis/stable-diffusion-v1-1"
snake_case_     :       Dict						=  "CompVis/stable-diffusion-v1-2"
snake_case_     :       Any						=  "CompVis/stable-diffusion-v1-3"
snake_case_     :       str						=  "CompVis/stable-diffusion-v1-4"


class 					__a      (lowerCamelCase     ):

							def __init__(							self							:     Any       ,     __magic_name__							:     AutoencoderKL       ,     __magic_name__							:     CLIPTextModel       ,     __magic_name__							:     CLIPTokenizer       ,     __magic_name__							:     UNetaDConditionModel       ,     __magic_name__							:     Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]       ,     __magic_name__							:     StableDiffusionSafetyChecker       ,     __magic_name__							:     CLIPImageProcessor       ,     __magic_name__							:     bool = True       ,     )					->       str:







													"""simple docstring"""
													super()._init_()

													UpperCAmelCase_			:      Any     						=  StableDiffusionPipeline.from_pretrained(__magic_name__   )
													UpperCAmelCase_			:      Dict     						=  StableDiffusionPipeline.from_pretrained(__magic_name__   )
													UpperCAmelCase_			:      List[Any]     						=  StableDiffusionPipeline.from_pretrained(__magic_name__   )
													UpperCAmelCase_			:      Tuple     						=  StableDiffusionPipeline(
													    vae=__magic_name__       ,     text_encoder=__magic_name__       ,     tokenizer=__magic_name__       ,     unet=__magic_name__       ,     scheduler=__magic_name__       ,     safety_checker=__magic_name__       ,     feature_extractor=__magic_name__       ,     requires_safety_checker=__magic_name__       ,     )

													self.register_modules(pipelinea=self.pipea       ,     pipelinea=self.pipea       ,     pipelinea=self.pipea       ,     pipelinea=self.pipea   )

							@property
							def     UpperCAmelCase__	(							self							:     Tuple   )					->       Dict[str, Any]:







													"""simple docstring"""
													return {k: getattr(self       ,     __magic_name__   ) for k in self.config.keys() if not k.startswith('''_'''   )}

							def     UpperCAmelCase__	(							self							:     Dict       ,     __magic_name__							:     Optional[Union[str, int]] = "auto"   )					->       int:







													"""simple docstring"""
													if slice_size == "auto":
																			# half the attention head size is usually a good trade-off between
																			# speed and memory
																			UpperCAmelCase_			:      List[str]     						=  self.unet.config.attention_head_dim // 2
													self.unet.set_attention_slice(__magic_name__   )

							def     UpperCAmelCase__	(							self							:     Tuple   )					->       List[str]:







													"""simple docstring"""
													self.enable_attention_slicing(__magic_name__   )

							@torch.no_grad()
							def     UpperCAmelCase__	(							self							:     List[Any]       ,     __magic_name__							:     Union[str, List[str]]       ,     __magic_name__							:     int = 5_12       ,     __magic_name__							:     int = 5_12       ,     __magic_name__							:     int = 50       ,     __magic_name__							:     float = 7.5       ,     __magic_name__							:     Optional[Union[str, List[str]]] = None       ,     __magic_name__							:     Optional[int] = 1       ,     __magic_name__							:     float = 0.0       ,     __magic_name__							:     Optional[torch.Generator] = None       ,     __magic_name__							:     Optional[torch.FloatTensor] = None       ,     __magic_name__							:     Optional[str] = "pil"       ,     __magic_name__							:     bool = True       ,     __magic_name__							:     Optional[Callable[[int, int, torch.FloatTensor], None]] = None       ,     __magic_name__							:     int = 1       ,     **__magic_name__							:     Tuple       ,     )					->       Optional[int]:







													"""simple docstring"""
													return self.pipea(
													    prompt=__magic_name__       ,     height=__magic_name__       ,     width=__magic_name__       ,     num_inference_steps=__magic_name__       ,     guidance_scale=__magic_name__       ,     negative_prompt=__magic_name__       ,     num_images_per_prompt=__magic_name__       ,     eta=__magic_name__       ,     generator=__magic_name__       ,     latents=__magic_name__       ,     output_type=__magic_name__       ,     return_dict=__magic_name__       ,     callback=__magic_name__       ,     callback_steps=__magic_name__       ,     **__magic_name__       ,     )

							@torch.no_grad()
							def     UpperCAmelCase__	(							self							:     Optional[int]       ,     __magic_name__							:     Union[str, List[str]]       ,     __magic_name__							:     int = 5_12       ,     __magic_name__							:     int = 5_12       ,     __magic_name__							:     int = 50       ,     __magic_name__							:     float = 7.5       ,     __magic_name__							:     Optional[Union[str, List[str]]] = None       ,     __magic_name__							:     Optional[int] = 1       ,     __magic_name__							:     float = 0.0       ,     __magic_name__							:     Optional[torch.Generator] = None       ,     __magic_name__							:     Optional[torch.FloatTensor] = None       ,     __magic_name__							:     Optional[str] = "pil"       ,     __magic_name__							:     bool = True       ,     __magic_name__							:     Optional[Callable[[int, int, torch.FloatTensor], None]] = None       ,     __magic_name__							:     int = 1       ,     **__magic_name__							:     Any       ,     )					->       Any:







													"""simple docstring"""
													return self.pipea(
													    prompt=__magic_name__       ,     height=__magic_name__       ,     width=__magic_name__       ,     num_inference_steps=__magic_name__       ,     guidance_scale=__magic_name__       ,     negative_prompt=__magic_name__       ,     num_images_per_prompt=__magic_name__       ,     eta=__magic_name__       ,     generator=__magic_name__       ,     latents=__magic_name__       ,     output_type=__magic_name__       ,     return_dict=__magic_name__       ,     callback=__magic_name__       ,     callback_steps=__magic_name__       ,     **__magic_name__       ,     )

							@torch.no_grad()
							def     UpperCAmelCase__	(							self							:     List[Any]       ,     __magic_name__							:     Union[str, List[str]]       ,     __magic_name__							:     int = 5_12       ,     __magic_name__							:     int = 5_12       ,     __magic_name__							:     int = 50       ,     __magic_name__							:     float = 7.5       ,     __magic_name__							:     Optional[Union[str, List[str]]] = None       ,     __magic_name__							:     Optional[int] = 1       ,     __magic_name__							:     float = 0.0       ,     __magic_name__							:     Optional[torch.Generator] = None       ,     __magic_name__							:     Optional[torch.FloatTensor] = None       ,     __magic_name__							:     Optional[str] = "pil"       ,     __magic_name__							:     bool = True       ,     __magic_name__							:     Optional[Callable[[int, int, torch.FloatTensor], None]] = None       ,     __magic_name__							:     int = 1       ,     **__magic_name__							:     Dict       ,     )					->       List[str]:







													"""simple docstring"""
													return self.pipea(
													    prompt=__magic_name__       ,     height=__magic_name__       ,     width=__magic_name__       ,     num_inference_steps=__magic_name__       ,     guidance_scale=__magic_name__       ,     negative_prompt=__magic_name__       ,     num_images_per_prompt=__magic_name__       ,     eta=__magic_name__       ,     generator=__magic_name__       ,     latents=__magic_name__       ,     output_type=__magic_name__       ,     return_dict=__magic_name__       ,     callback=__magic_name__       ,     callback_steps=__magic_name__       ,     **__magic_name__       ,     )

							@torch.no_grad()
							def     UpperCAmelCase__	(							self							:     int       ,     __magic_name__							:     Union[str, List[str]]       ,     __magic_name__							:     int = 5_12       ,     __magic_name__							:     int = 5_12       ,     __magic_name__							:     int = 50       ,     __magic_name__							:     float = 7.5       ,     __magic_name__							:     Optional[Union[str, List[str]]] = None       ,     __magic_name__							:     Optional[int] = 1       ,     __magic_name__							:     float = 0.0       ,     __magic_name__							:     Optional[torch.Generator] = None       ,     __magic_name__							:     Optional[torch.FloatTensor] = None       ,     __magic_name__							:     Optional[str] = "pil"       ,     __magic_name__							:     bool = True       ,     __magic_name__							:     Optional[Callable[[int, int, torch.FloatTensor], None]] = None       ,     __magic_name__							:     int = 1       ,     **__magic_name__							:     Optional[int]       ,     )					->       str:







													"""simple docstring"""
													return self.pipea(
													    prompt=__magic_name__       ,     height=__magic_name__       ,     width=__magic_name__       ,     num_inference_steps=__magic_name__       ,     guidance_scale=__magic_name__       ,     negative_prompt=__magic_name__       ,     num_images_per_prompt=__magic_name__       ,     eta=__magic_name__       ,     generator=__magic_name__       ,     latents=__magic_name__       ,     output_type=__magic_name__       ,     return_dict=__magic_name__       ,     callback=__magic_name__       ,     callback_steps=__magic_name__       ,     **__magic_name__       ,     )



							@torch.no_grad()
							def     UpperCAmelCase__	(							self							:     Optional[Any]       ,     __magic_name__							:     Union[str, List[str]]       ,     __magic_name__							:     int = 5_12       ,     __magic_name__							:     int = 5_12       ,     __magic_name__							:     int = 50       ,     __magic_name__							:     float = 7.5       ,     __magic_name__							:     Optional[Union[str, List[str]]] = None       ,     __magic_name__							:     Optional[int] = 1       ,     __magic_name__							:     float = 0.0       ,     __magic_name__							:     Optional[torch.Generator] = None       ,     __magic_name__							:     Optional[torch.FloatTensor] = None       ,     __magic_name__							:     Optional[str] = "pil"       ,     __magic_name__							:     bool = True       ,     __magic_name__							:     Optional[Callable[[int, int, torch.FloatTensor], None]] = None       ,     __magic_name__							:     int = 1       ,     **__magic_name__							:     Optional[int]       ,     )					->       List[Any]:







													"""simple docstring"""
													UpperCAmelCase_			:      int     						=  '''cuda''' if torch.cuda.is_available() else '''cpu'''
													self.to(__magic_name__   )

													# Checks if the height and width are divisible by 8 or not
													if height % 8 != 0 or width % 8 != 0:
																			raise ValueError(F"""`height` and `width` must be divisible by 8 but are {height} and {width}."""   )

													# Get first result from Stable Diffusion Checkpoint v1.1
													UpperCAmelCase_			:      Optional[int]     						=  self.textaimg_sda_a(
													    prompt=__magic_name__       ,     height=__magic_name__       ,     width=__magic_name__       ,     num_inference_steps=__magic_name__       ,     guidance_scale=__magic_name__       ,     negative_prompt=__magic_name__       ,     num_images_per_prompt=__magic_name__       ,     eta=__magic_name__       ,     generator=__magic_name__       ,     latents=__magic_name__       ,     output_type=__magic_name__       ,     return_dict=__magic_name__       ,     callback=__magic_name__       ,     callback_steps=__magic_name__       ,     **__magic_name__       ,     )

													# Get first result from Stable Diffusion Checkpoint v1.2
													UpperCAmelCase_			:      int     						=  self.textaimg_sda_a(
													    prompt=__magic_name__       ,     height=__magic_name__       ,     width=__magic_name__       ,     num_inference_steps=__magic_name__       ,     guidance_scale=__magic_name__       ,     negative_prompt=__magic_name__       ,     num_images_per_prompt=__magic_name__       ,     eta=__magic_name__       ,     generator=__magic_name__       ,     latents=__magic_name__       ,     output_type=__magic_name__       ,     return_dict=__magic_name__       ,     callback=__magic_name__       ,     callback_steps=__magic_name__       ,     **__magic_name__       ,     )

													# Get first result from Stable Diffusion Checkpoint v1.3
													UpperCAmelCase_			:      str     						=  self.textaimg_sda_a(
													    prompt=__magic_name__       ,     height=__magic_name__       ,     width=__magic_name__       ,     num_inference_steps=__magic_name__       ,     guidance_scale=__magic_name__       ,     negative_prompt=__magic_name__       ,     num_images_per_prompt=__magic_name__       ,     eta=__magic_name__       ,     generator=__magic_name__       ,     latents=__magic_name__       ,     output_type=__magic_name__       ,     return_dict=__magic_name__       ,     callback=__magic_name__       ,     callback_steps=__magic_name__       ,     **__magic_name__       ,     )

													# Get first result from Stable Diffusion Checkpoint v1.4
													UpperCAmelCase_			:      str     						=  self.textaimg_sda_a(
													    prompt=__magic_name__       ,     height=__magic_name__       ,     width=__magic_name__       ,     num_inference_steps=__magic_name__       ,     guidance_scale=__magic_name__       ,     negative_prompt=__magic_name__       ,     num_images_per_prompt=__magic_name__       ,     eta=__magic_name__       ,     generator=__magic_name__       ,     latents=__magic_name__       ,     output_type=__magic_name__       ,     return_dict=__magic_name__       ,     callback=__magic_name__       ,     callback_steps=__magic_name__       ,     **__magic_name__       ,     )

													# Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result
													return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]]   )





