





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  A__    (							__UpperCAmelCase	):




   """simple docstring"""



   __A   :				torch.FloatTensor





class  A__    (							__UpperCAmelCase ,  __UpperCAmelCase	):




   """simple docstring"""



   @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.1_82_15					,  lowercase = "group"					,  )			->						List[Any]:







          '''simple docstring'''

          super().__init__()

          # pass init params to Encoder
          a__						:	Dict =				Encoder(
              in_channels=__A					,  out_channels=__A					,  down_block_types=__A					,  block_out_channels=__A					,  layers_per_block=__A					,  act_fn=__A					,  norm_num_groups=__A					,  double_z=__A					,  )

          a__						:	Union[str, Any] =				vq_embed_dim if vq_embed_dim is not None else latent_channels

          a__						:	Any =				nn.Convad(__A					,  __A					,  1)
          a__						:	Dict =				VectorQuantizer(__A					,  __A					,  beta=0.25					,  remap=__A					,  sane_index_shape=__A)
          a__						:	Optional[int] =				nn.Convad(__A					,  __A					,  1)

          # pass init params to Decoder
          a__						:	Optional[Any] =				Decoder(
              in_channels=__A					,  out_channels=__A					,  up_block_types=__A					,  block_out_channels=__A					,  layers_per_block=__A					,  act_fn=__A					,  norm_num_groups=__A					,  norm_type=__A					,  )

   @apply_forward_hook
   def 							__lowercase		(					self					,  lowercase					,  lowercase = True)			->						List[Any]:







          '''simple docstring'''

          a__						:	Dict =				self.encoder(__A)
          a__						:	Union[str, Any] =				self.quant_conv(__A)

          if not return_dict:
                 return (h,)

          return VQEncoderOutput(latents=__A)

   @apply_forward_hook
   def 							__lowercase		(					self					,  lowercase					,  lowercase = False					,  lowercase = True)			->						Any:







          '''simple docstring'''

          if not force_not_quantize:
                 a__						:	Any =				self.quantize(__A)
          else:
                 a__						:	Dict =				h
          a__						:	Tuple =				self.post_quant_conv(__A)
          a__						:	Any =				self.decoder(__A					,  quant if self.config.norm_type == 'spatial' else None)

          if not return_dict:
                 return (dec,)

          return DecoderOutput(sample=__A)

   def 							__lowercase		(					self					,  lowercase					,  lowercase = True)			->						Optional[Any]:







          '''simple docstring'''

          a__						:	int =				sample
          a__						:	Optional[Any] =				self.encode(__A).latents
          a__						:	List[str] =				self.decode(__A).sample

          if not return_dict:
                 return (dec,)

          return DecoderOutput(sample=__A)






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) * 9_99
_snake_case             =     torch.randn(2, 77, 7_68)
_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             =     6_66
_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''')



