





"""simple docstring"""





import argparse

import intel_extension_for_pytorch as ipex
import torch

from diffusers import DPMSolverMultistepScheduler, StableDiffusionPipeline


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


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

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

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

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

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

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

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













"""simple docstring"""





from dataclasses import dataclass
from typing import Optional, Tuple, Union

import torch
import torch.nn as nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, apply_forward_hook
from .modeling_utils import ModelMixin
from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer

@dataclass
class 		lowercase					(					_UpperCAmelCase					):
      _SCREAMING_SNAKE_CASE					=      42







class 		lowercase					(					_UpperCAmelCase     ,  _UpperCAmelCase					):





      @register_to_config
      def __init__(       self      ,						lowercase = 3      ,						lowercase = 3      ,						lowercase = ("DownEncoderBlock2D",)      ,						lowercase = ("UpDecoderBlock2D",)      ,						lowercase = (64,)      ,						lowercase = 1      ,						lowercase = "silu"      ,						lowercase = 3      ,						lowercase = 32      ,						lowercase = 256      ,						lowercase = 32      ,						lowercase = None      ,						lowercase = 0.18_215      ,						lowercase = "group"      ,						)		->     Union[str, Any]:
            super().__init__()

            # pass init params to Encoder
            lowerCAmelCase  						=       Encoder(
                in_channels=lowercase      ,						out_channels=lowercase      ,						down_block_types=lowercase      ,						block_out_channels=lowercase      ,						layers_per_block=lowercase      ,						act_fn=lowercase      ,						norm_num_groups=lowercase      ,						double_z=lowercase      ,						)

            lowerCAmelCase  						=       vq_embed_dim if vq_embed_dim is not None else latent_channels

            lowerCAmelCase  						=       nn.Convad(lowercase      ,						lowercase      ,						1 )
            lowerCAmelCase  						=       VectorQuantizer(lowercase      ,						lowercase      ,						beta=0.25      ,						remap=lowercase      ,						sane_index_shape=lowercase )
            lowerCAmelCase  						=       nn.Convad(lowercase      ,						lowercase      ,						1 )

            # pass init params to Decoder
            lowerCAmelCase  						=       Decoder(
                in_channels=lowercase      ,						out_channels=lowercase      ,						up_block_types=lowercase      ,						block_out_channels=lowercase      ,						layers_per_block=lowercase      ,						act_fn=lowercase      ,						norm_num_groups=lowercase      ,						norm_type=lowercase      ,						)





      @apply_forward_hook
      def     _snake_case			(       self      ,						lowercase      ,						lowercase = True )		->     VQEncoderOutput:
            lowerCAmelCase  						=       self.encoder(lowercase )
            lowerCAmelCase  						=       self.quant_conv(lowercase )

            if not return_dict:
                  return (h,)

            return VQEncoderOutput(latents=lowercase )





      @apply_forward_hook
      def     _snake_case			(       self      ,						lowercase      ,						lowercase = False      ,						lowercase = True )		->     Union[DecoderOutput, torch.FloatTensor]:
            # also go through quantization layer
            if not force_not_quantize:
                  lowerCAmelCase						,		lowerCAmelCase						,		lowerCAmelCase  						=       self.quantize(lowercase )
            else:
                  lowerCAmelCase  						=       h
            lowerCAmelCase  						=       self.post_quant_conv(lowercase )
            lowerCAmelCase  						=       self.decoder(lowercase      ,						quant if self.config.norm_type == """spatial""" else None )

            if not return_dict:
                  return (dec,)

            return DecoderOutput(sample=lowercase )





      def     _snake_case			(       self      ,						lowercase      ,						lowercase = True )		->     Union[DecoderOutput, torch.FloatTensor]:
            lowerCAmelCase  						=       sample
            lowerCAmelCase  						=       self.encode(lowercase ).latents
            lowerCAmelCase  						=       self.decode(lowercase ).sample

            if not return_dict:
                  return (dec,)

            return DecoderOutput(sample=lowercase )






