




"""simple docstring"""






import gc
import tempfile
import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionPipeline
from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device


lowercase__			=		False






class lowerCAmelCase__      (	unittest.TestCase		):






			'''simple docstring'''



			pass






@nightly
@require_torch_gpu
class lowerCAmelCase__      (	unittest.TestCase		):






			'''simple docstring'''



			def    A_       (    self    ):
							# clean up the VRAM after each test
							super().tearDown()
							gc.collect()
							torch.cuda.empty_cache()
			def    A_       (    self    ):
							_lowerCamelCase	:     Optional[int]       =       VersatileDiffusionPipeline.from_pretrained('shi-labs/versatile-diffusion'    , torch_dtype=torch.floataa    )
							pipe.to(lowercase    )
							pipe.set_progress_bar_config(disable=lowercase    )

							_lowerCamelCase	:     Union[str, Any]       =       load_image(
							    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg'    )

							_lowerCamelCase	:     List[str]       =       torch.manual_seed(0    )
							_lowerCamelCase	:     List[Any]       =       pipe.dual_guided(
							    prompt='first prompt'    , image=lowercase    , text_to_image_strength=0.75    , generator=lowercase    , guidance_scale=7.5    , num_inference_steps=2    , output_type='numpy'    , ).images

							with tempfile.TemporaryDirectory() as tmpdirname:
											pipe.save_pretrained(lowercase    )
											_lowerCamelCase	:     int       =       VersatileDiffusionPipeline.from_pretrained(lowercase    , torch_dtype=torch.floataa    )
							pipe.to(lowercase    )
							pipe.set_progress_bar_config(disable=lowercase    )

							_lowerCamelCase	:     Any       =       generator.manual_seed(0    )
							_lowerCamelCase	:     Tuple       =       pipe.dual_guided(
							    prompt='first prompt'    , image=lowercase    , text_to_image_strength=0.75    , generator=lowercase    , guidance_scale=7.5    , num_inference_steps=2    , output_type='numpy'    , ).images

							assert np.abs(image - new_image    ).sum() < 1E-5, "Models don't have the same forward pass"






			def    A_       (    self    ):
							_lowerCamelCase	:     Optional[int]       =       VersatileDiffusionPipeline.from_pretrained('shi-labs/versatile-diffusion'    , torch_dtype=torch.floataa    )
							pipe.to(lowercase    )
							pipe.set_progress_bar_config(disable=lowercase    )

							_lowerCamelCase	:     Optional[Any]       =       'cyberpunk 2077'
							_lowerCamelCase	:     Optional[Any]       =       load_image(
							    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg'    )
							_lowerCamelCase	:     List[Any]       =       torch.manual_seed(0    )
							_lowerCamelCase	:     Dict       =       pipe.dual_guided(
							    prompt=lowercase    , image=lowercase    , text_to_image_strength=0.75    , generator=lowercase    , guidance_scale=7.5    , num_inference_steps=50    , output_type='numpy'    , ).images

							_lowerCamelCase	:     Any       =       image[0, 253:256, 253:256, -1]

							assert image.shape == (1, 512, 512, 3)
							_lowerCamelCase	:     Dict       =       np.array([0.14_48, 0.16_19, 0.17_41, 0.10_86, 0.11_47, 0.11_28, 0.11_99, 0.11_65, 0.10_01]    )

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

							_lowerCamelCase	:     str       =       'A painting of a squirrel eating a burger '
							_lowerCamelCase	:     Optional[Any]       =       torch.manual_seed(0    )
							_lowerCamelCase	:     Union[str, Any]       =       pipe.text_to_image(
							    prompt=lowercase    , generator=lowercase    , guidance_scale=7.5    , num_inference_steps=50    , output_type='numpy'    ).images

							_lowerCamelCase	:     Union[str, Any]       =       image[0, 253:256, 253:256, -1]

							assert image.shape == (1, 512, 512, 3)
							_lowerCamelCase	:     Optional[int]       =       np.array([0.33_67, 0.31_69, 0.26_56, 0.38_70, 0.47_90, 0.37_96, 0.40_09, 0.48_78, 0.47_78]    )

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

							_lowerCamelCase	:     Optional[int]       =       pipe.image_variation(lowercase    , generator=lowercase    , output_type='numpy'    ).images

							_lowerCamelCase	:     str       =       image[0, 253:256, 253:256, -1]

							assert image.shape == (1, 512, 512, 3)
							_lowerCamelCase	:     Optional[int]       =       np.array([0.30_76, 0.31_23, 0.32_84, 0.37_82, 0.37_70, 0.38_94, 0.42_97, 0.43_31, 0.44_56]    )

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





"""simple docstring"""






import argparse

import intel_extension_for_pytorch as ipex
import torch

from diffusers import DPMSolverMultistepScheduler, StableDiffusionPipeline


lowercase__			=		argparse.ArgumentParser("""Stable Diffusion script with intel optimization""", add_help=False)
parser.add_argument("""--dpm""", action="""store_true""", help="""Enable DPMSolver or not""")
parser.add_argument("""--steps""", default=None, type=int, help="""Num inference steps""")
lowercase__			=		parser.parse_args()


lowercase__			=		"""cpu"""
lowercase__			=		"""a lovely <dicoo> in red dress and hat, in the snowly and brightly night, with many brighly buildings"""

lowercase__			=		"""path-to-your-trained-model"""
lowercase__			=		StableDiffusionPipeline.from_pretrained(model_id)
if args.dpm:
			lowercase__			=		DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
lowercase__			=		pipe.to(device)

# to channels last
lowercase__			=		pipe.unet.to(memory_format=torch.channels_last)
lowercase__			=		pipe.vae.to(memory_format=torch.channels_last)
lowercase__			=		pipe.text_encoder.to(memory_format=torch.channels_last)
if pipe.requires_safety_checker:
			lowercase__			=		pipe.safety_checker.to(memory_format=torch.channels_last)

# optimize with ipex
lowercase__			=		torch.randn(2, 4, 64, 64)
lowercase__			=		torch.rand(1) * 999
lowercase__			=		torch.randn(2, 77, 768)
lowercase__			=		(sample, timestep, encoder_hidden_status)
try:
			lowercase__			=		ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True, sample_input=input_example)
except Exception:
			lowercase__			=		ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True)
lowercase__			=		ipex.optimize(pipe.vae.eval(), dtype=torch.bfloataa, inplace=True)
lowercase__			=		ipex.optimize(pipe.text_encoder.eval(), dtype=torch.bfloataa, inplace=True)
if pipe.requires_safety_checker:
			lowercase__			=		ipex.optimize(pipe.safety_checker.eval(), dtype=torch.bfloataa, inplace=True)

# compute
lowercase__			=		666
lowercase__			=		torch.Generator(device).manual_seed(seed)
lowercase__			=		{"""generator""": generator}
if args.steps is not None:
			lowercase__			=		args.steps

with torch.cpu.amp.autocast(enabled=True, dtype=torch.bfloataa):
			lowercase__			=		pipe(prompt, **generate_kwargs).images[0]

# save image
image.save("""generated.png""")