





import argparse

import intel_extension_for_pytorch as ipex
import torch

from diffusers import DPMSolverMultistepScheduler, StableDiffusionPipeline


_snake_case           =			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""")
_snake_case           =			parser.parse_args()


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

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

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

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

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

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

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












import math
from typing import List, Optional, Tuple, Union

import numpy as np
import torch

from ..configuration_utils import ConfigMixin, register_to_config
from .scheduling_utils import SchedulerMixin, SchedulerOutput





class  lowerCAmelCase							(       lowercase_							,							lowercase_ ):
  __lowerCamelCase		=      1







  @register_to_config
  def __init__(      self  :Dict   ,							_lowercase  :int = 10_00   ,							_lowercase  :Optional[Union[np.ndarray, List[float]]] = None ):






     '''simple docstring'''





     self.set_timesteps(_lowercase )

     # standard deviation of the initial noise distribution
     lowercase__			       =  1.0

     # For now we only support F-PNDM, i.e. the runge-kutta method
     # For more information on the algorithm please take a look at the paper: https://arxiv.org/pdf/2202.09778.pdf
     # mainly at formula (9), (12), (13) and the Algorithm 2.
     lowercase__			       =  4

     # running values
     lowercase__			       =  []







  def   UpperCAmelCase					(      self  :str   ,							_lowercase  :int   ,							_lowercase  :Union[str, torch.device] = None ):






     '''simple docstring'''





     lowercase__			       =  num_inference_steps
     lowercase__			       =  torch.linspace(1   ,							0   ,							num_inference_steps + 1 )[:-1]
     lowercase__			       =  torch.cat([steps, torch.tensor([0.0] )] )

     if self.config.trained_betas is not None:
        lowercase__			       =  torch.tensor(self.config.trained_betas   ,							dtype=torch.floataa )
     else:
        lowercase__			       =  torch.sin(steps * math.pi / 2 ) ** 2

     lowercase__			       =  (1.0 - self.betas**2) ** 0.5

     lowercase__			       =  (torch.atana(self.betas   ,							self.alphas ) / math.pi * 2)[:-1]
     lowercase__			       =  timesteps.to(_lowercase )

     lowercase__			       =  []







  def   UpperCAmelCase					(      self  :Optional[int]   ,							_lowercase  :torch.FloatTensor   ,							_lowercase  :int   ,							_lowercase  :torch.FloatTensor   ,							_lowercase  :bool = True   ,							):






     '''simple docstring'''





     if self.num_inference_steps is None:
        raise ValueError(
            "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler" )

     lowercase__			       =  (self.timesteps == timestep).nonzero().item()
     lowercase__			       =  timestep_index + 1

     lowercase__			       =  sample * self.betas[timestep_index] + model_output * self.alphas[timestep_index]
     self.ets.append(_lowercase )

     if len(self.ets ) == 1:
        lowercase__			       =  self.ets[-1]
     elif len(self.ets ) == 2:
        lowercase__			       =  (3 * self.ets[-1] - self.ets[-2]) / 2
     elif len(self.ets ) == 3:
        lowercase__			       =  (23 * self.ets[-1] - 16 * self.ets[-2] + 5 * self.ets[-3]) / 12
     else:
        lowercase__			       =  (1 / 24) * (55 * self.ets[-1] - 59 * self.ets[-2] + 37 * self.ets[-3] - 9 * self.ets[-4])

     lowercase__			       =  self._get_prev_sample(_lowercase   ,							_lowercase   ,							_lowercase   ,							_lowercase )

     if not return_dict:
        return (prev_sample,)

     return SchedulerOutput(prev_sample=_lowercase )







  def   UpperCAmelCase					(      self  :Any   ,							_lowercase  :torch.FloatTensor   ,							*_lowercase  :int   ,							**_lowercase  :int ):






     '''simple docstring'''





     return sample







  def   UpperCAmelCase					(      self  :str   ,							_lowercase  :Tuple   ,							_lowercase  :int   ,							_lowercase  :Optional[Any]   ,							_lowercase  :List[str] ):






     '''simple docstring'''





     lowercase__			       =  self.alphas[timestep_index]
     lowercase__			       =  self.betas[timestep_index]

     lowercase__			       =  self.alphas[prev_timestep_index]
     lowercase__			       =  self.betas[prev_timestep_index]

     lowercase__			       =  (sample - sigma * ets) / max(_lowercase   ,							1e-8 )
     lowercase__			       =  next_alpha * pred + ets * next_sigma

     return prev_sample







  def __len__(      self  :Union[str, Any] ):






     '''simple docstring'''





     return self.config.num_train_timesteps






