




import argparse

import intel_extension_for_pytorch as ipex
import torch

from diffusers import DPMSolverMultistepScheduler, StableDiffusionPipeline


snake_case_ : str    		=       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_ : Tuple    		=       parser.parse_args()


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

snake_case_ : Union[str, Any]    		=       "path-to-your-trained-model"
snake_case_ : Tuple    		=       StableDiffusionPipeline.from_pretrained(model_id)
if args.dpm:
    snake_case_ : Any    		=       DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
snake_case_ : Dict    		=       pipe.to(device)

# to channels last
snake_case_ : List[Any]    		=       pipe.unet.to(memory_format=torch.channels_last)
snake_case_ : List[Any]    		=       pipe.vae.to(memory_format=torch.channels_last)
snake_case_ : Tuple    		=       pipe.text_encoder.to(memory_format=torch.channels_last)
if pipe.requires_safety_checker:
    snake_case_ : Union[str, Any]    		=       pipe.safety_checker.to(memory_format=torch.channels_last)

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

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

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

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












from typing import List, Optional, TypeVar

from .arrow_dataset import Dataset, _concatenate_map_style_datasets, _interleave_map_style_datasets
from .dataset_dict import DatasetDict, IterableDatasetDict
from .info import DatasetInfo
from .iterable_dataset import IterableDataset, _concatenate_iterable_datasets, _interleave_iterable_datasets
from .splits import NamedSplit
from .utils import logging
from .utils.py_utils import Literal


snake_case_ : Any    		=       logging.get_logger(__name__)


snake_case_ : Optional[int]    		=       TypeVar("DatasetType", Dataset, IterableDataset)


def    A						(__A   :    List[DatasetType]   ,				__A   :    Optional[List[float]] = None   ,				__A   :    Optional[int] = None   ,				__A   :    Optional[DatasetInfo] = None   ,				__A   :    Optional[NamedSplit] = None   ,				__A   :    Literal["first_exhausted", "all_exhausted"] = "first_exhausted"   ,				)   ->      DatasetType:







     """simple docstring"""


     from .arrow_dataset import Dataset
     from .iterable_dataset import IterableDataset

     if not datasets:
          raise ValueError('''Unable to interleave an empty list of datasets.'''       )
     for i, dataset in enumerate(__A       ):
          if not isinstance(__A   ,				(Dataset, IterableDataset)       ):
               if isinstance(__A   ,				(DatasetDict, IterableDatasetDict)       ):
                    if not dataset:
                         raise ValueError(
                             F"""Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} """
                             '''is an empty dataset dictionary.'''       )
                    raise ValueError(
                        F"""Dataset at position {i} has at least one split: {list(__A       )}\n"""
                        F"""Please pick one to interleave with the other datasets, for example: dataset['{next(iter(__A       )       )}']"""       )
               raise ValueError(
                   F"""Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(__A       ).__name__}."""       )
          if i == 0:
               UpperCAmelCase_     ,       UpperCAmelCase_          =							(
                   (Dataset, IterableDataset) if isinstance(__A   ,				__A       ) else (IterableDataset, Dataset)
               )
          elif not isinstance(__A   ,				__A       ):
               raise ValueError(
                   F"""Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects."""       )
     if stopping_strategy not in ["first_exhausted", "all_exhausted"]:
          raise ValueError(F"""{stopping_strategy} is not supported. Please enter a valid stopping_strategy."""       )
     if dataset_type is Dataset:
          return _interleave_map_style_datasets(
              __A   ,				__A   ,				__A   ,				info=__A   ,				split=__A   ,				stopping_strategy=__A       )
     else:
          return _interleave_iterable_datasets(
              __A   ,				__A   ,				__A   ,				info=__A   ,				split=__A   ,				stopping_strategy=__A       )


def    A						(__A   :    List[DatasetType]   ,				__A   :    Optional[DatasetInfo] = None   ,				__A   :    Optional[NamedSplit] = None   ,				__A   :    int = 0   ,				)   ->      DatasetType:







     """simple docstring"""


     if not dsets:
          raise ValueError('''Unable to concatenate an empty list of datasets.'''       )
     for i, dataset in enumerate(__A       ):
          if not isinstance(__A   ,				(Dataset, IterableDataset)       ):
               if isinstance(__A   ,				(DatasetDict, IterableDatasetDict)       ):
                    if not dataset:
                         raise ValueError(
                             F"""Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} """
                             '''is an empty dataset dictionary.'''       )
                    raise ValueError(
                        F"""Dataset at position {i} has at least one split: {list(__A       )}\n"""
                        F"""Please pick one to interleave with the other datasets, for example: dataset['{next(iter(__A       )       )}']"""       )
               raise ValueError(
                   F"""Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(__A       ).__name__}."""       )
          if i == 0:
               UpperCAmelCase_     ,       UpperCAmelCase_          =							(
                   (Dataset, IterableDataset) if isinstance(__A   ,				__A       ) else (IterableDataset, Dataset)
               )
          elif not isinstance(__A   ,				__A       ):
               raise ValueError(
                   F"""Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects."""       )
     if dataset_type is Dataset:
          return _concatenate_map_style_datasets(__A   ,				info=__A   ,				split=__A   ,				axis=__A       )
     else:
          return _concatenate_iterable_datasets(__A   ,				info=__A   ,				split=__A   ,				axis=__A       )






