






'''simple docstring'''

import gc
import unittest

import numpy as np
import torch

from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel
from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import (
    CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS,
    CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()






class     a_						(      lowerCamelCase     ,	unittest.TestCase    ):
  lowercase							=				DiTPipeline
  lowercase							=				CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS
  lowercase							=				PipelineTesterMixin.required_optional_params - {
      """latents""",
      """num_images_per_prompt""",
      """callback""",
      """callback_steps""",
  }
  lowercase							=				CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS
  lowercase							=				False

  def   A__						(				self				)  ->				str:



        """simple docstring"""






        torch.manual_seed(0				)
        UpperCamelCase      = TransformeraDModel(
            sample_size=16      ,		num_layers=2      ,		patch_size=4      ,		attention_head_dim=8      ,		num_attention_heads=2      ,		in_channels=4      ,		out_channels=8      ,		attention_bias=lowerCamelCase_      ,		activation_fn="""gelu-approximate"""      ,		num_embeds_ada_norm=1000      ,		norm_type="""ada_norm_zero"""      ,		norm_elementwise_affine=lowerCamelCase_      ,		)
        UpperCamelCase      = AutoencoderKL()
        UpperCamelCase      = DDIMScheduler()
        UpperCamelCase      = {"""transformer""": transformer.eval(), """vae""": vae.eval(), """scheduler""": scheduler}
        return components

  def   A__						(				self      ,		_SCREAMING_SNAKE_CASE      ,		_SCREAMING_SNAKE_CASE=0				)  ->				Dict:



        """simple docstring"""






        if str(lowerCamelCase_				).startswith("""mps"""				):
              UpperCamelCase      = torch.manual_seed(lowerCamelCase_				)
        else:
              UpperCamelCase      = torch.Generator(device=lowerCamelCase_				).manual_seed(lowerCamelCase_				)
        UpperCamelCase      = {
            """class_labels""": [1],
            """generator""": generator,
            """num_inference_steps""": 2,
            """output_type""": """numpy""",
        }
        return inputs

  def   A__						(				self				)  ->				str:



        """simple docstring"""






        UpperCamelCase      = """cpu"""

        UpperCamelCase      = self.get_dummy_components()
        UpperCamelCase      = self.pipeline_class(**lowerCamelCase_				)
        pipe.to(lowerCamelCase_				)
        pipe.set_progress_bar_config(disable=lowerCamelCase_				)

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

        self.assertEqual(image.shape      ,		(1, 16, 16, 3)				)
        UpperCamelCase      = np.array([0.2_9_4_6, 0.6_6_0_1, 0.4_3_2_9, 0.3_2_9_6, 0.4_1_4_4, 0.5_3_1_9, 0.7_2_7_3, 0.5_0_1_3, 0.4_4_5_7]				)
        UpperCamelCase      = np.abs(image_slice.flatten() - expected_slice				).max()
        self.assertLessEqual(lowerCamelCase_      ,		1e-3				)

  def   A__						(				self				)  ->				Optional[Any]:



        """simple docstring"""






        self._test_inference_batch_single_identical(relax_max_difference=lowerCamelCase_      ,		expected_max_diff=1e-3				)


  @unittest.skipIf(
      torch_device != """cuda""" or not is_xformers_available()      ,		reason="""XFormers attention is only available with CUDA and `xformers` installed"""      ,		)
  def   A__						(				self				)  ->				Optional[int]:



        """simple docstring"""






        self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3				)






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

  def   A__						(				self				)  ->				Dict:



        """simple docstring"""






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

  def   A__						(				self				)  ->				Dict:



        """simple docstring"""






        UpperCamelCase      = torch.manual_seed(0				)

        UpperCamelCase      = DiTPipeline.from_pretrained("""facebook/DiT-XL-2-256"""				)
        pipe.to("""cuda"""				)

        UpperCamelCase      = ["""vase""", """umbrella""", """white shark""", """white wolf"""]
        UpperCamelCase      = pipe.get_label_ids(lowerCamelCase_				)

        UpperCamelCase      = pipe(lowerCamelCase_      ,		generator=lowerCamelCase_      ,		num_inference_steps=40      ,		output_type="""np"""				).images

        for word, image in zip(lowerCamelCase_      ,		lowerCamelCase_				):
              UpperCamelCase      = load_numpy(
                  F"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy"				)
              assert np.abs((expected_image - image).max()				) < 1e-2


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



        """simple docstring"""






        UpperCamelCase      = DiTPipeline.from_pretrained("""facebook/DiT-XL-2-512"""				)
        UpperCamelCase      = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config				)
        pipe.to("""cuda"""				)

        UpperCamelCase      = ["""vase""", """umbrella"""]
        UpperCamelCase      = pipe.get_label_ids(lowerCamelCase_				)

        UpperCamelCase      = torch.manual_seed(0				)
        UpperCamelCase      = pipe(lowerCamelCase_      ,		generator=lowerCamelCase_      ,		num_inference_steps=25      ,		output_type="""np"""				).images

        for word, image in zip(lowerCamelCase_      ,		lowerCamelCase_				):
              UpperCamelCase      = load_numpy(
                  """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
                  F"/dit/{word}_512.npy"				)

              assert np.abs((expected_image - image).max()				) < 1e-1








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


SCREAMING_SNAKE_CASE__     =       'CompVis/stable-diffusion-v1-1'
SCREAMING_SNAKE_CASE__     =       'CompVis/stable-diffusion-v1-2'
SCREAMING_SNAKE_CASE__     =       'CompVis/stable-diffusion-v1-3'
SCREAMING_SNAKE_CASE__     =       'CompVis/stable-diffusion-v1-4'






class     a_						(      lowerCamelCase    ):

  def __init__(				self      ,		_SCREAMING_SNAKE_CASE      ,		_SCREAMING_SNAKE_CASE      ,		_SCREAMING_SNAKE_CASE      ,		_SCREAMING_SNAKE_CASE      ,		_SCREAMING_SNAKE_CASE      ,		_SCREAMING_SNAKE_CASE      ,		_SCREAMING_SNAKE_CASE      ,		_SCREAMING_SNAKE_CASE = True      ,		)  ->				int:



        """simple docstring"""






        super()._init_()

        UpperCamelCase      = StableDiffusionPipeline.from_pretrained(_SCREAMING_SNAKE_CASE				)
        UpperCamelCase      = StableDiffusionPipeline.from_pretrained(_SCREAMING_SNAKE_CASE				)
        UpperCamelCase      = StableDiffusionPipeline.from_pretrained(_SCREAMING_SNAKE_CASE				)
        UpperCamelCase      = StableDiffusionPipeline(
            vae=_SCREAMING_SNAKE_CASE      ,		text_encoder=_SCREAMING_SNAKE_CASE      ,		tokenizer=_SCREAMING_SNAKE_CASE      ,		unet=_SCREAMING_SNAKE_CASE      ,		scheduler=_SCREAMING_SNAKE_CASE      ,		safety_checker=_SCREAMING_SNAKE_CASE      ,		feature_extractor=_SCREAMING_SNAKE_CASE      ,		requires_safety_checker=_SCREAMING_SNAKE_CASE      ,		)

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

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



        """simple docstring"""






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

  def   A__						(				self      ,		_SCREAMING_SNAKE_CASE = "auto"				)  ->				Any:



        """simple docstring"""






        if slice_size == "auto":
              # half the attention head size is usually a good trade-off between
              # speed and memory
              UpperCamelCase      = self.unet.config.attention_head_dim // 2
        self.unet.set_attention_slice(_SCREAMING_SNAKE_CASE				)

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



        """simple docstring"""






        self.enable_attention_slicing(_SCREAMING_SNAKE_CASE				)

  @torch.no_grad()
  def   A__						(				self      ,		_SCREAMING_SNAKE_CASE      ,		_SCREAMING_SNAKE_CASE = 512      ,		_SCREAMING_SNAKE_CASE = 512      ,		_SCREAMING_SNAKE_CASE = 50      ,		_SCREAMING_SNAKE_CASE = 7.5      ,		_SCREAMING_SNAKE_CASE = None      ,		_SCREAMING_SNAKE_CASE = 1      ,		_SCREAMING_SNAKE_CASE = 0.0      ,		_SCREAMING_SNAKE_CASE = None      ,		_SCREAMING_SNAKE_CASE = None      ,		_SCREAMING_SNAKE_CASE = "pil"      ,		_SCREAMING_SNAKE_CASE = True      ,		_SCREAMING_SNAKE_CASE = None      ,		_SCREAMING_SNAKE_CASE = 1      ,		**_SCREAMING_SNAKE_CASE      ,		)  ->				List[Any]:



        """simple docstring"""






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

  @torch.no_grad()
  def   A__						(				self      ,		_SCREAMING_SNAKE_CASE      ,		_SCREAMING_SNAKE_CASE = 512      ,		_SCREAMING_SNAKE_CASE = 512      ,		_SCREAMING_SNAKE_CASE = 50      ,		_SCREAMING_SNAKE_CASE = 7.5      ,		_SCREAMING_SNAKE_CASE = None      ,		_SCREAMING_SNAKE_CASE = 1      ,		_SCREAMING_SNAKE_CASE = 0.0      ,		_SCREAMING_SNAKE_CASE = None      ,		_SCREAMING_SNAKE_CASE = None      ,		_SCREAMING_SNAKE_CASE = "pil"      ,		_SCREAMING_SNAKE_CASE = True      ,		_SCREAMING_SNAKE_CASE = None      ,		_SCREAMING_SNAKE_CASE = 1      ,		**_SCREAMING_SNAKE_CASE      ,		)  ->				str:



        """simple docstring"""






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

  @torch.no_grad()
  def   A__						(				self      ,		_SCREAMING_SNAKE_CASE      ,		_SCREAMING_SNAKE_CASE = 512      ,		_SCREAMING_SNAKE_CASE = 512      ,		_SCREAMING_SNAKE_CASE = 50      ,		_SCREAMING_SNAKE_CASE = 7.5      ,		_SCREAMING_SNAKE_CASE = None      ,		_SCREAMING_SNAKE_CASE = 1      ,		_SCREAMING_SNAKE_CASE = 0.0      ,		_SCREAMING_SNAKE_CASE = None      ,		_SCREAMING_SNAKE_CASE = None      ,		_SCREAMING_SNAKE_CASE = "pil"      ,		_SCREAMING_SNAKE_CASE = True      ,		_SCREAMING_SNAKE_CASE = None      ,		_SCREAMING_SNAKE_CASE = 1      ,		**_SCREAMING_SNAKE_CASE      ,		)  ->				Optional[Any]:



        """simple docstring"""






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

  @torch.no_grad()
  def   A__						(				self      ,		_SCREAMING_SNAKE_CASE      ,		_SCREAMING_SNAKE_CASE = 512      ,		_SCREAMING_SNAKE_CASE = 512      ,		_SCREAMING_SNAKE_CASE = 50      ,		_SCREAMING_SNAKE_CASE = 7.5      ,		_SCREAMING_SNAKE_CASE = None      ,		_SCREAMING_SNAKE_CASE = 1      ,		_SCREAMING_SNAKE_CASE = 0.0      ,		_SCREAMING_SNAKE_CASE = None      ,		_SCREAMING_SNAKE_CASE = None      ,		_SCREAMING_SNAKE_CASE = "pil"      ,		_SCREAMING_SNAKE_CASE = True      ,		_SCREAMING_SNAKE_CASE = None      ,		_SCREAMING_SNAKE_CASE = 1      ,		**_SCREAMING_SNAKE_CASE      ,		)  ->				Union[str, Any]:



        """simple docstring"""






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


  @torch.no_grad()
  def   A__						(				self      ,		_SCREAMING_SNAKE_CASE      ,		_SCREAMING_SNAKE_CASE = 512      ,		_SCREAMING_SNAKE_CASE = 512      ,		_SCREAMING_SNAKE_CASE = 50      ,		_SCREAMING_SNAKE_CASE = 7.5      ,		_SCREAMING_SNAKE_CASE = None      ,		_SCREAMING_SNAKE_CASE = 1      ,		_SCREAMING_SNAKE_CASE = 0.0      ,		_SCREAMING_SNAKE_CASE = None      ,		_SCREAMING_SNAKE_CASE = None      ,		_SCREAMING_SNAKE_CASE = "pil"      ,		_SCREAMING_SNAKE_CASE = True      ,		_SCREAMING_SNAKE_CASE = None      ,		_SCREAMING_SNAKE_CASE = 1      ,		**_SCREAMING_SNAKE_CASE      ,		)  ->				int:



        """simple docstring"""






        UpperCamelCase      = """cuda""" if torch.cuda.is_available() else """cpu"""
        self.to(_SCREAMING_SNAKE_CASE				)

        # 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      = self.textaimg_sda_a(
            prompt=_SCREAMING_SNAKE_CASE      ,		height=_SCREAMING_SNAKE_CASE      ,		width=_SCREAMING_SNAKE_CASE      ,		num_inference_steps=_SCREAMING_SNAKE_CASE      ,		guidance_scale=_SCREAMING_SNAKE_CASE      ,		negative_prompt=_SCREAMING_SNAKE_CASE      ,		num_images_per_prompt=_SCREAMING_SNAKE_CASE      ,		eta=_SCREAMING_SNAKE_CASE      ,		generator=_SCREAMING_SNAKE_CASE      ,		latents=_SCREAMING_SNAKE_CASE      ,		output_type=_SCREAMING_SNAKE_CASE      ,		return_dict=_SCREAMING_SNAKE_CASE      ,		callback=_SCREAMING_SNAKE_CASE      ,		callback_steps=_SCREAMING_SNAKE_CASE      ,		**_SCREAMING_SNAKE_CASE      ,		)

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

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

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

        # 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]]				)
