






'''simple docstring'''





import argparse

import intel_extension_for_pytorch as ipex
import torch

from diffusers import DPMSolverMultistepScheduler, StableDiffusionPipeline


__UpperCamelCase      :      Optional[int]     						=						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""")
__UpperCamelCase      :      Optional[Any]     						=						parser.parse_args()


__UpperCamelCase      :      Dict     						=						'''cpu'''
__UpperCamelCase      :      Optional[Any]     						=						'''a lovely <dicoo> in red dress and hat, in the snowly and brightly night, with many brighly buildings'''

__UpperCamelCase      :      Tuple     						=						'''path-to-your-trained-model'''
__UpperCamelCase      :      List[Any]     						=						StableDiffusionPipeline.from_pretrained(model_id)
if args.dpm:
						__UpperCamelCase      :      Optional[int]     						=						DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
__UpperCamelCase      :      List[Any]     						=						pipe.to(device)

# to channels last
__UpperCamelCase      :      Optional[Any]     						=						pipe.unet.to(memory_format=torch.channels_last)
__UpperCamelCase      :      List[str]     						=						pipe.vae.to(memory_format=torch.channels_last)
__UpperCamelCase      :      Optional[Any]     						=						pipe.text_encoder.to(memory_format=torch.channels_last)
if pipe.requires_safety_checker:
						__UpperCamelCase      :      Dict     						=						pipe.safety_checker.to(memory_format=torch.channels_last)

# optimize with ipex
__UpperCamelCase      :      Tuple     						=						torch.randn(2, 4, 64, 64)
__UpperCamelCase      :      Any     						=						torch.rand(1) * 999
__UpperCamelCase      :      List[str]     						=						torch.randn(2, 77, 768)
__UpperCamelCase      :      Optional[int]     						=						(sample, timestep, encoder_hidden_status)
try:
						__UpperCamelCase      :      List[Any]     						=						ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True, sample_input=input_example)
except Exception:
						__UpperCamelCase      :      Optional[Any]     						=						ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True)
__UpperCamelCase      :      Any     						=						ipex.optimize(pipe.vae.eval(), dtype=torch.bfloataa, inplace=True)
__UpperCamelCase      :      int     						=						ipex.optimize(pipe.text_encoder.eval(), dtype=torch.bfloataa, inplace=True)
if pipe.requires_safety_checker:
						__UpperCamelCase      :      Union[str, Any]     						=						ipex.optimize(pipe.safety_checker.eval(), dtype=torch.bfloataa, inplace=True)

# compute
__UpperCamelCase      :      List[str]     						=						666
__UpperCamelCase      :      Optional[int]     						=						torch.Generator(device).manual_seed(seed)
__UpperCamelCase      :      List[Any]     						=						{'''generator''': generator}
if args.steps is not None:
						__UpperCamelCase      :      Any     						=						args.steps

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

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









import gc
import unittest

from diffusers import FlaxDPMSolverMultistepScheduler, FlaxStableDiffusionPipeline
from diffusers.utils import is_flax_available, slow
from diffusers.utils.testing_utils import require_flax


if is_flax_available():
						import jax
						import jax.numpy as jnp
						from flax.jax_utils import replicate
						from flax.training.common_utils import shard


@slow
@require_flax
class        __UpperCamelCase    (     unittest.TestCase   ):







	def  _a   (  self      :							Union[str, Any]			)		-> Any:
		"""simple docstring"""







		super().tearDown()
		gc.collect()







	def  _a   (  self      :							List[str]			)		-> int:
		"""simple docstring"""







		__lowercase       ,						__lowercase             =  FlaxStableDiffusionPipeline.from_pretrained(
		    """stabilityai/stable-diffusion-2"""       ,				revision="""bf16"""       ,				dtype=jnp.bfloataa       ,				)

		__lowercase             =  """A painting of a squirrel eating a burger"""
		__lowercase             =  jax.device_count()
		__lowercase             =  num_samples * [prompt]
		__lowercase             =  sd_pipe.prepare_inputs(_lowerCAmelCase			)

		__lowercase             =  replicate(_lowerCAmelCase			)
		__lowercase             =  shard(_lowerCAmelCase			)

		__lowercase             =  jax.random.PRNGKey(0			)
		__lowercase             =  jax.random.split(_lowerCAmelCase       ,				jax.device_count()			)

		__lowercase             =  sd_pipe(_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase       ,				num_inference_steps=25       ,				jit=_lowerCAmelCase			)[0]
		assert images.shape == (jax.device_count(), 1, 768, 768, 3)

		__lowercase             =  images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:]			)
		__lowercase             =  images[0, 253:256, 253:256, -1]

		__lowercase             =  jnp.asarray(jax.device_get(image_slice.flatten()			)			)
		__lowercase             =  jnp.array([0.4_238, 0.4_414, 0.4_395, 0.4_453, 0.4_629, 0.4_590, 0.4_531, 0.45_508, 0.4_512]			)
		print(F'output_slice: {output_slice}'			)
		assert jnp.abs(output_slice - expected_slice			).max() < 1e-2







	def  _a   (  self      :							str			)		-> List[Any]:
		"""simple docstring"""







		__lowercase             =  """stabilityai/stable-diffusion-2"""
		__lowercase       ,						__lowercase             =  FlaxDPMSolverMultistepScheduler.from_pretrained(_lowerCAmelCase       ,				subfolder="""scheduler"""			)
		__lowercase       ,						__lowercase             =  FlaxStableDiffusionPipeline.from_pretrained(
		    _lowerCAmelCase       ,				scheduler=_lowerCAmelCase       ,				revision="""bf16"""       ,				dtype=jnp.bfloataa       ,				)
		__lowercase             =  scheduler_params

		__lowercase             =  """A painting of a squirrel eating a burger"""
		__lowercase             =  jax.device_count()
		__lowercase             =  num_samples * [prompt]
		__lowercase             =  sd_pipe.prepare_inputs(_lowerCAmelCase			)

		__lowercase             =  replicate(_lowerCAmelCase			)
		__lowercase             =  shard(_lowerCAmelCase			)

		__lowercase             =  jax.random.PRNGKey(0			)
		__lowercase             =  jax.random.split(_lowerCAmelCase       ,				jax.device_count()			)

		__lowercase             =  sd_pipe(_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase       ,				num_inference_steps=25       ,				jit=_lowerCAmelCase			)[0]
		assert images.shape == (jax.device_count(), 1, 768, 768, 3)

		__lowercase             =  images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:]			)
		__lowercase             =  images[0, 253:256, 253:256, -1]

		__lowercase             =  jnp.asarray(jax.device_get(image_slice.flatten()			)			)
		__lowercase             =  jnp.array([0.4_336, 0.42_969, 0.4_453, 0.4_199, 0.4_297, 0.4_531, 0.4_434, 0.4_434, 0.4_297]			)
		print(F'output_slice: {output_slice}'			)
		assert jnp.abs(output_slice - expected_slice			).max() < 1e-2

