Spaces:
Running
Running
App update
Browse filesFiles changed (27)
- app.py+109-9
- app_settings.py+23
- backend/__pycache__/__init__.cpython-311.pyc
- backend/__pycache__/image_saver.cpython-311.pyc
- backend/__pycache__/lcm_text_to_image.cpython-311.pyc
- backend/lcm_text_to_image.py+256-44
- backend/lcmdiffusion/pipelines/openvino/__pycache__/lcm_ov_pipeline.cpython-311.pyc
- backend/lcmdiffusion/pipelines/openvino/__pycache__/lcm_scheduler.cpython-311.pyc
- backend/lcmdiffusion/pipelines/openvino/lcm_ov_pipeline.py+86-29
- backend/lcmdiffusion/pipelines/openvino/lcm_scheduler.py+67-20
- backend/models/__pycache__/lcmdiffusion_setting.cpython-311.pyc
- backend/models/lcmdiffusion_setting.py+15-5
- constants.py+8-2
- context.py+13-8
- frontend/__pycache__/utils.cpython-311.pyc
- frontend/gui/__pycache__/app_window.cpython-311.pyc
- frontend/gui/__pycache__/image_generator_worker.cpython-311.pyc
- frontend/gui/__pycache__/ui.cpython-311.pyc
- frontend/gui/app_window.py+177-22
- frontend/utils.py+22-4
- frontend/webui/text_to_image_ui.py+41-49
- frontend/webui/ui.py+2-2
- models/__pycache__/interface_types.cpython-311.pyc
- models/__pycache__/settings.cpython-311.pyc
- models/settings.py+2-2
- paths.py+11-2
- utils.py+11
5 unmodified lines678910111215 unmodified lines28293031323332 unmodified lines666768697071727324 unmodified lines98991001011021031041051061071081091101111121131141151161171181191201211221231241255 unmodified linesfrom constants import APP_VERSION, LCM_DEFAULT_MODEL_OPENVINOfrom models.interface_types import InterfaceTypefrom constants import DEVICEfrom frontend.webui.ui import start_webuiparser = ArgumentParser(description=f"FAST SD CPU {constants.APP_VERSION}")parser.add_argument("-s",15 unmodified linesaction="store_true",help="Start Web UI",)group.add_argument("-v","--version",32 unmodified linesparser.add_argument("--guidance_scale",type=int,help="Guidance scale,default : 8.0",default=8.0,)parser.add_argument(24 unmodified linesaction="store_false",help="Use safety checker",)parser.add_argument("-i","--interactive",action="store_true",help="Interactive CLI mode",)args = parser.parse_args()if args.version:print(APP_VERSION)exit()parser.print_help()show_system_info()print(f"Using device : {constants.DEVICE}")app_settings = AppSettings()app_settings.load()start_webui(app_settings,args.share,)5 unmodified lines678910111215 unmodified lines28293031323334353637383932 unmodified lines727374757677787924 unmodified lines1041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242255 unmodified linesfrom constants import APP_VERSION, LCM_DEFAULT_MODEL_OPENVINOfrom models.interface_types import InterfaceTypefrom constants import DEVICEparser = ArgumentParser(description=f"FAST SD CPU {constants.APP_VERSION}")parser.add_argument("-s",15 unmodified linesaction="store_true",help="Start Web UI",)group.add_argument("-r","--realtime",action="store_true",help="Start realtime inference UI(experimental)",)group.add_argument("-v","--version",32 unmodified linesparser.add_argument("--guidance_scale",type=int,help="Guidance scale,default : 1.0",default=1.0,)parser.add_argument(24 unmodified linesaction="store_false",help="Use safety checker",)parser.add_argument("--use_lcm_lora",action="store_true",help="Use LCM-LoRA",)parser.add_argument("--base_model_id",type=str,help="LCM LoRA base model ID,Default Lykon/dreamshaper-8",default="Lykon/dreamshaper-8",)parser.add_argument("--lcm_lora_id",type=str,help="LCM LoRA model ID,Default latent-consistency/lcm-lora-sdv1-5",default="latent-consistency/lcm-lora-sdv1-5",)parser.add_argument("-i","--interactive",action="store_true",help="Interactive CLI mode",)parser.add_argument("--use_tiny_auto_encoder",action="store_true",help="Use tiny auto encoder for SD (TAESD)",)args = parser.parse_args()if args.version:print(APP_VERSION)exit()# parser.print_help()show_system_info()print(f"Using device : {constants.DEVICE}")app_settings = AppSettings()app_settings.load()print(f"Found {len(app_settings.stable_diffsuion_models)} stable diffusion models in config/stable-diffusion-models.txt")print(f"Found {len(app_settings.lcm_lora_models)} LCM-LoRA models in config/lcm-lora-models.txt")print(f"Found {len(app_settings.openvino_lcm_models)} OpenVINO LCM models in config/openvino-lcm-models.txt")if args.gui:from frontend.gui.ui import start_guiprint("Starting desktop GUI mode(Qt)")start_gui([],app_settings,)elif args.webui:from frontend.webui.ui import start_webuiprint("Starting web UI mode")start_webui(app_settings,args.share,)elif args.realtime:from frontend.webui.realtime_ui import start_realtime_text_to_imageprint("Starting realtime text to image(EXPERIMENTAL)")start_realtime_text_to_image(args.share)else:context = Context(InterfaceType.CLI)config = app_settings.settingsif args.use_openvino:config.lcm_diffusion_setting.lcm_model_id = LCM_DEFAULT_MODEL_OPENVINOelse:config.lcm_diffusion_setting.lcm_model_id = args.lcm_model_idconfig.lcm_diffusion_setting.prompt = args.promptconfig.lcm_diffusion_setting.image_height = args.image_heightconfig.lcm_diffusion_setting.image_width = args.image_widthconfig.lcm_diffusion_setting.guidance_scale = args.guidance_scaleconfig.lcm_diffusion_setting.number_of_images = args.number_of_imagesconfig.lcm_diffusion_setting.seed = args.seedconfig.lcm_diffusion_setting.use_openvino = args.use_openvinoconfig.lcm_diffusion_setting.use_tiny_auto_encoder = args.use_tiny_auto_encoderconfig.lcm_diffusion_setting.use_lcm_lora = args.use_lcm_loraconfig.lcm_diffusion_setting.lcm_lora.base_model_id = args.base_model_idconfig.lcm_diffusion_setting.lcm_lora.lcm_lora_id = args.lcm_lora_idif args.seed > -1:config.lcm_diffusion_setting.use_seed = Trueelse:config.lcm_diffusion_setting.use_seed = Falseconfig.lcm_diffusion_setting.use_offline_model = args.use_offline_modelconfig.lcm_diffusion_setting.use_safety_checker = args.use_safety_checkerif args.interactive:while True:user_input = input(">>")if user_input == "exit":breakconfig.lcm_diffusion_setting.prompt = user_inputcontext.generate_text_to_image(settings=config,device=DEVICE,)else:context.generate_text_to_image(settings=config,device=DEVICE,)from frontend.webui.hf_demo import start_demo_text_to_imageprint("Starting demo text to image")start_demo_text_to_image(True)
1 unmodified line2345678910111213141516171 unmodified linefrom os import path, makedirsfrom models.settings import Settingsfrom paths import FastStableDiffusionPathsclass AppSettings:def __init__(self):self.config_path = FastStableDiffusionPaths().get_app_settings_path()@propertydef settings(self):return self._configdef load(self):if not path.exists(self.config_path):base_dir = path.dirname(self.config_path)1 unmodified line23456789101112131415161718192021222324252627282930313233343536373839401 unmodified linefrom os import path, makedirsfrom models.settings import Settingsfrom paths import FastStableDiffusionPathsfrom utils import get_models_from_text_filefrom constants import OPENVINO_LCM_MODELS_FILE, LCM_LORA_MODELS_FILE, SD_MODELS_FILEclass AppSettings:def __init__(self):self.config_path = FastStableDiffusionPaths().get_app_settings_path()self._stable_diffsuion_models = get_models_from_text_file(FastStableDiffusionPaths().get_models_config_path(SD_MODELS_FILE))self._lcm_lora_models = get_models_from_text_file(FastStableDiffusionPaths().get_models_config_path(LCM_LORA_MODELS_FILE))self._openvino_lcm_models = get_models_from_text_file(FastStableDiffusionPaths().get_models_config_path(OPENVINO_LCM_MODELS_FILE))@propertydef settings(self):return self._config@propertydef stable_diffsuion_models(self):return self._stable_diffsuion_models@propertydef openvino_lcm_models(self):return self._openvino_lcm_models@propertydef lcm_lora_models(self):return self._lcm_lora_modelsdef load(self):if not path.exists(self.config_path):base_dir = path.dirname(self.config_path)
12345678910111213141516171819202 unmodified lines2324252627282930313233343536373839401 unmodified line42434445464748495051525354555657585960616263646566676869707172737475767778798081828384851 unmodified line8788899091929394959697983 unmodified lines102103104105106107108109110111112113114115from typing import Anyfrom diffusers import DiffusionPipelinefrom os import pathimport torchfrom backend.models.lcmdiffusion_setting import LCMDiffusionSettingimport numpy as npfrom constants import DEVICEif DEVICE == "cpu":from backend.lcmdiffusion.pipelines.openvino.lcm_ov_pipeline import (OVLatentConsistencyModelPipeline,)from backend.lcmdiffusion.pipelines.openvino.lcm_scheduler import (LCMScheduler,)class LCMTextToImage:def __init__(2 unmodified lines) -> None:self.pipeline = Noneself.use_openvino = Falseself.device = Noneself.previous_model_id = Nonedef _get_lcm_diffusion_pipeline_path(self) -> str:script_path = path.dirname(path.abspath(__file__))file_path = path.join(script_path,"lcmdiffusion","pipelines","latent_consistency_txt2img.py",)return file_pathdef init(self,1 unmodified lineuse_openvino: bool = False,device: str = "cpu",use_local_model: bool = False,) -> None:self.device = deviceself.use_openvino = use_openvinoif self.pipeline is None or self.previous_model_id != model_id:if self.use_openvino and DEVICE == "cpu":if self.pipeline:del self.pipelinescheduler = LCMScheduler.from_pretrained(model_id,subfolder="scheduler",)self.pipeline = OVLatentConsistencyModelPipeline.from_pretrained(model_id,scheduler=scheduler,compile=False,local_files_only=use_local_model,)else:if self.pipeline:del self.pipelineself.pipeline = DiffusionPipeline.from_pretrained(model_id,custom_pipeline=self._get_lcm_diffusion_pipeline_path(),custom_revision="main",local_files_only=use_local_model,)self.pipeline.to(torch_device=self.device,torch_dtype=torch.float32,)self.previous_model_id = model_iddef generate(self,lcm_diffusion_setting: LCMDiffusionSetting,reshape: bool = False,) -> Any:if lcm_diffusion_setting.use_seed:cur_seed = lcm_diffusion_setting.seedif self.use_openvino:1 unmodified lineelse:torch.manual_seed(cur_seed)if self.use_openvino and DEVICE == "cpu":print("Using OpenVINO")if reshape:print("Reshape and compile")self.pipeline.reshape(batch_size=1,height=lcm_diffusion_setting.image_height,width=lcm_diffusion_setting.image_width,num_images_per_prompt=lcm_diffusion_setting.number_of_images,3 unmodified linesif not lcm_diffusion_setting.use_safety_checker:self.pipeline.safety_checker = Noneresult_images = self.pipeline(prompt=lcm_diffusion_setting.prompt,num_inference_steps=lcm_diffusion_setting.inference_steps,guidance_scale=lcm_diffusion_setting.guidance_scale,width=lcm_diffusion_setting.image_width,height=lcm_diffusion_setting.image_height,output_type="pil",num_images_per_prompt=lcm_diffusion_setting.number_of_images,).imagesreturn result_images12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152532 unmodified lines56575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801 unmodified line1821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772781 unmodified line2802812822832842852862872882892902913 unmodified lines295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327from typing import Anyfrom diffusers import (DiffusionPipeline,AutoencoderTiny,LCMScheduler,UNet2DConditionModel,)from os import pathimport torchfrom backend.models.lcmdiffusion_setting import LCMDiffusionSettingimport numpy as npfrom constants import (DEVICE,LCM_DEFAULT_MODEL,TAESD_MODEL,TAESDXL_MODEL,TAESD_MODEL_OPENVINO,)from huggingface_hub import model_infofrom backend.models.lcmdiffusion_setting import LCMLorafrom backend.device import is_openvino_deviceif is_openvino_device():from huggingface_hub import snapshot_downloadfrom optimum.intel.openvino.modeling_diffusion import OVModelVaeDecoder, OVBaseModel# from optimum.intel.openvino.modeling_diffusion import OVStableDiffusionPipelinefrom backend.lcmdiffusion.pipelines.openvino.lcm_ov_pipeline import (OVStableDiffusionPipeline,)from backend.lcmdiffusion.pipelines.openvino.lcm_scheduler import (LCMScheduler as OpenVinoLCMscheduler,)class CustomOVModelVaeDecoder(OVModelVaeDecoder):def __init__(self,model,parent_model,ov_config=None,model_dir=None,):super(OVModelVaeDecoder, self).__init__(model,parent_model,ov_config,"vae_decoder",model_dir,)class LCMTextToImage:def __init__(2 unmodified lines) -> None:self.pipeline = Noneself.use_openvino = Falseself.device = ""self.previous_model_id = Noneself.previous_use_tae_sd = Falseself.previous_use_lcm_lora = Falseself.torch_data_type = (torch.float32 if is_openvino_device() or DEVICE == "mps" else torch.float16)print(f"Torch datatype : {self.torch_data_type}")def _get_lcm_pipeline(self,lcm_model_id: str,base_model_id: str,use_local_model: bool,):pipeline = Noneunet = UNet2DConditionModel.from_pretrained(lcm_model_id,torch_dtype=torch.float32,local_files_only=use_local_model# resume_download=True,)pipeline = DiffusionPipeline.from_pretrained(base_model_id,unet=unet,torch_dtype=torch.float32,local_files_only=use_local_model# resume_download=True,)pipeline.scheduler = LCMScheduler.from_config(pipeline.scheduler.config)return pipelinedef get_tiny_decoder_vae_model(self) -> str:pipeline_class = self.pipeline.__class__.__name__print(f"Pipeline class : {pipeline_class}")if (pipeline_class == "LatentConsistencyModelPipeline"or pipeline_class == "StableDiffusionPipeline"):return TAESD_MODELelif pipeline_class == "StableDiffusionXLPipeline":return TAESDXL_MODELelif pipeline_class == "OVStableDiffusionPipeline":return TAESD_MODEL_OPENVINOdef _get_lcm_model_pipeline(self,model_id: str,use_local_model,):pipeline = Noneif model_id == LCM_DEFAULT_MODEL:pipeline = DiffusionPipeline.from_pretrained(model_id,local_files_only=use_local_model,)elif model_id == "latent-consistency/lcm-sdxl":pipeline = self._get_lcm_pipeline(model_id,"stabilityai/stable-diffusion-xl-base-1.0",use_local_model,)elif model_id == "latent-consistency/lcm-ssd-1b":pipeline = self._get_lcm_pipeline(model_id,"segmind/SSD-1B",use_local_model,)return pipelinedef _get_lcm_lora_pipeline(self,base_model_id: str,lcm_lora_id: str,use_local_model: bool,):pipeline = DiffusionPipeline.from_pretrained(base_model_id,torch_dtype=self.torch_data_type,local_files_only=use_local_model,)pipeline.load_lora_weights(lcm_lora_id,local_files_only=use_local_model,)pipeline.scheduler = LCMScheduler.from_config(pipeline.scheduler.config)pipeline.fuse_lora()pipeline.unet.to(memory_format=torch.channels_last)return pipelinedef _pipeline_to_device(self):print(f"Pipeline device : {DEVICE}")print(f"Pipeline dtype : {self.torch_data_type}")self.pipeline.to(torch_device=DEVICE,torch_dtype=self.torch_data_type,)def _add_freeu(self):pipeline_class = self.pipeline.__class__.__name__if pipeline_class == "StableDiffusionPipeline":print("Add FreeU - SD")self.pipeline.enable_freeu(s1=0.9,s2=0.2,b1=1.2,b2=1.4,)elif pipeline_class == "StableDiffusionXLPipeline":print("Add FreeU - SDXL")self.pipeline.enable_freeu(s1=0.6,s2=0.4,b1=1.1,b2=1.2,)def init(self,1 unmodified lineuse_openvino: bool = False,device: str = "cpu",use_local_model: bool = False,use_tiny_auto_encoder: bool = False,use_lora: bool = False,lcm_lora: LCMLora = LCMLora(),) -> None:self.device = deviceself.use_openvino = use_openvinoif (self.pipeline is Noneor self.previous_model_id != model_idor self.previous_use_tae_sd != use_tiny_auto_encoderor self.previous_lcm_lora_base_id != lcm_lora.base_model_idor self.previous_lcm_lora_id != lcm_lora.lcm_lora_idor self.previous_use_lcm_lora != use_lora):if self.use_openvino and is_openvino_device():if self.pipeline:del self.pipelineself.pipeline = Noneself.pipeline = OVStableDiffusionPipeline.from_pretrained(model_id,local_files_only=use_local_model,ov_config={"CACHE_DIR": ""},device=DEVICE.upper(),)if use_tiny_auto_encoder:print("Using Tiny Auto Encoder (OpenVINO)")taesd_dir = snapshot_download(repo_id=self.get_tiny_decoder_vae_model(),local_files_only=use_local_model,)self.pipeline.vae_decoder = CustomOVModelVaeDecoder(model=OVBaseModel.load_model(f"{taesd_dir}/vae_decoder/openvino_model.xml"),parent_model=self.pipeline,model_dir=taesd_dir,)else:if self.pipeline:del self.pipelineself.pipeline = Noneif use_lora:print("Init LCM-LoRA pipeline")self.pipeline = self._get_lcm_lora_pipeline(lcm_lora.base_model_id,lcm_lora.lcm_lora_id,use_local_model,)else:print("Init LCM Model pipeline")self.pipeline = self._get_lcm_model_pipeline(model_id,use_local_model,)if use_tiny_auto_encoder:vae_model = self.get_tiny_decoder_vae_model()print(f"Using Tiny Auto Encoder {vae_model}")self.pipeline.vae = AutoencoderTiny.from_pretrained(vae_model,torch_dtype=torch.float32,local_files_only=use_local_model,)self._pipeline_to_device()self.previous_model_id = model_idself.previous_use_tae_sd = use_tiny_auto_encoderself.previous_lcm_lora_base_id = lcm_lora.base_model_idself.previous_lcm_lora_id = lcm_lora.lcm_lora_idself.previous_use_lcm_lora = use_loraprint(f"Model :{model_id}")print(f"Pipeline : {self.pipeline}")self.pipeline.scheduler = LCMScheduler.from_config(self.pipeline.scheduler.config,beta_start=0.001,beta_end=0.01,)if use_lora:self._add_freeu()def generate(self,lcm_diffusion_setting: LCMDiffusionSetting,reshape: bool = False,) -> Any:guidance_scale = lcm_diffusion_setting.guidance_scaleif lcm_diffusion_setting.use_seed:cur_seed = lcm_diffusion_setting.seedif self.use_openvino:1 unmodified lineelse:torch.manual_seed(cur_seed)if lcm_diffusion_setting.use_openvino and is_openvino_device():print("Using OpenVINO")if reshape:print("Reshape and compile")self.pipeline.reshape(batch_size=-1,height=lcm_diffusion_setting.image_height,width=lcm_diffusion_setting.image_width,num_images_per_prompt=lcm_diffusion_setting.number_of_images,3 unmodified linesif not lcm_diffusion_setting.use_safety_checker:self.pipeline.safety_checker = Noneif (not lcm_diffusion_setting.use_lcm_loraand not lcm_diffusion_setting.use_openvinoand lcm_diffusion_setting.guidance_scale != 1.0):print("Not using LCM-LoRA so setting guidance_scale 1.0")guidance_scale = 1.0if lcm_diffusion_setting.use_openvino:result_images = self.pipeline(prompt=lcm_diffusion_setting.prompt,negative_prompt=lcm_diffusion_setting.negative_prompt,num_inference_steps=lcm_diffusion_setting.inference_steps,guidance_scale=guidance_scale,width=lcm_diffusion_setting.image_width,height=lcm_diffusion_setting.image_height,num_images_per_prompt=lcm_diffusion_setting.number_of_images,).imageselse:result_images = self.pipeline(prompt=lcm_diffusion_setting.prompt,negative_prompt=lcm_diffusion_setting.negative_prompt,num_inference_steps=lcm_diffusion_setting.inference_steps,guidance_scale=guidance_scale,width=lcm_diffusion_setting.image_width,height=lcm_diffusion_setting.image_height,num_images_per_prompt=lcm_diffusion_setting.number_of_images,).imagesreturn result_images
10 unmodified lines111213141516174 unmodified lines222324252627282922 unmodified lines525354555657585918 unmodified lines787980818283848586878889909192939495969721 unmodified lines1191201211221231241256 unmodified lines13213313413513613713813 unmodified lines15215315415515615715815916016116216316416514 unmodified lines18018118218318418518618718818986 unmodified lines27627727827928028128213 unmodified lines2962972982993003013023033048 unmodified lines3133143153163173183198 unmodified lines3283293303313323333342 unmodified lines3373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673684 unmodified lines3733743753763773783792 unmodified lines38238338438538638738838939010 unmodified linesimport torchfrom diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutputfrom optimum.intel.openvino.modeling_diffusion import OVStableDiffusionPipeline, OVModelUnet, OVModelVaeDecoder, OVModelTextEncoder, OVModelVaeEncoder, VaeImageProcessorfrom optimum.utils import (DIFFUSION_MODEL_TEXT_ENCODER_2_SUBFOLDER,DIFFUSION_MODEL_TEXT_ENCODER_SUBFOLDER,4 unmodified linesfrom diffusers import logginglogger = logging.get_logger(__name__) # pylint: disable=invalid-nameclass LCMOVModelUnet(OVModelUnet):def __call__(self,22 unmodified linesoutputs = self.request(inputs, shared_memory=True)return list(outputs.values())class OVLatentConsistencyModelPipeline(OVStableDiffusionPipeline):def __init__(self,vae_decoder: openvino.runtime.Model,18 unmodified linesself.is_dynamic = dynamic_shapesself.ov_config = ov_config if ov_config is not None else {}self._model_save_dir = (Path(model_save_dir.name) if isinstance(model_save_dir, TemporaryDirectory) else model_save_dir)self.vae_decoder = OVModelVaeDecoder(vae_decoder, self)self.unet = LCMOVModelUnet(unet, self)self.text_encoder = OVModelTextEncoder(text_encoder, self) if text_encoder is not None else Noneself.text_encoder_2 = (OVModelTextEncoder(text_encoder_2, self, model_name=DIFFUSION_MODEL_TEXT_ENCODER_2_SUBFOLDER)if text_encoder_2 is not Noneelse None)self.vae_encoder = OVModelVaeEncoder(vae_encoder, self) if vae_encoder is not None else Noneif "block_out_channels" in self.vae_decoder.config:self.vae_scale_factor = 2 ** (len(self.vae_decoder.config["block_out_channels"]) - 1)else:self.vae_scale_factor = 821 unmodified lines}for name in sub_models.keys():self._internal_dict[name] = (("optimum", sub_models[name].__class__.__name__) if sub_models[name] is not None else (None, None))self._internal_dict.pop("vae", None)6 unmodified lineswidth: int = -1,num_images_per_prompt: int = -1,tokenizer_max_length: int = -1,):if batch_size == -1 or num_images_per_prompt == -1:batch_size = -1else:13 unmodified linesif in_channels.is_dynamic:logger.warning("Could not identify `in_channels` from the unet configuration, to statically reshape the unet please provide a configuration.")self.is_dynamic = Trueshapes[inputs] = [batch_size, in_channels, height, width]elif inputs.get_any_name() == "timestep_cond":shapes[inputs] = [batch_size, inputs.get_partial_shape()[1]]elif inputs.get_any_name() == "text_embeds":shapes[inputs] = [batch_size, self.text_encoder_2.config["projection_dim"]]elif inputs.get_any_name() == "time_ids":shapes[inputs] = [batch_size, inputs.get_partial_shape()[1]]else:14 unmodified linesembedding vectors with shape `(len(timesteps), embedding_dim)`"""assert len(w.shape) == 1w = w * 1000.half_dim = embedding_dim // 2emb = np.log(np.array(10000.)) / (half_dim - 1)emb = np.exp(np.arange(half_dim, dtype=dtype) * -emb)emb = w.astype(dtype)[:, None] * emb[None, :]emb = np.concatenate([np.sin(emb), np.cos(emb)], axis=1)86 unmodified lineslist of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"(nsfw) content, according to the `safety_checker`."""height = height or self.unet.config.get("sample_size", 64) * self.vae_scale_factorwidth = width or self.unet.config.get("sample_size", 64) * self.vae_scale_factor# check inputs. Raise error if not correct13 unmodified linesgenerator = np.random# Create torch.Generator instance with same state as np.random.RandomStatetorch_generator = torch.Generator().manual_seed(int(generator.get_state()[1][0]))#do_classifier_free_guidance = guidance_scale > 1.0# NOTE: when a LCM is distilled from an LDM via latent consistency distillation (Algorithm 1) with guided# distillation, the forward pass of the LCM learns to approximate sampling from the LDM using CFG with the8 unmodified lines)# set timestepsself.scheduler.set_timesteps(num_inference_steps, "cpu", original_inference_steps=original_inference_steps)timesteps = self.scheduler.timestepslatents = self.prepare_latents(8 unmodified lines# Get Guidance Scale Embeddingw = np.tile(guidance_scale - 1, batch_size * num_images_per_prompt)w_embedding = self.get_guidance_scale_embedding(w, embedding_dim=self.unet.config.get("time_cond_proj_dim", 256))# Adapted from diffusers to extend it for other runtimes than ORTtimestep_dtype = self.unet.input_dtype.get("timestep", np.float32)2 unmodified lines# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502# and should be between [0, 1]accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())extra_step_kwargs = {}if accepts_eta:extra_step_kwargs["eta"] = etaaccepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())if accepts_generator:extra_step_kwargs["generator"] = torch_generatornum_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.orderfor i, t in enumerate(self.progress_bar(timesteps)):# predict the noise residualtimestep = np.array([t], dtype=timestep_dtype)noise_pred = self.unet(sample=latents, timestep=timestep, timestep_cond = w_embedding, encoder_hidden_states=prompt_embeds)[0]# compute the previous noisy sample x_t -> x_t-1latents, denoised = self.scheduler.step(torch.from_numpy(noise_pred), t, torch.from_numpy(latents), **extra_step_kwargs, return_dict = False)latents, denoised = latents.numpy(), denoised.numpy()# call the callback, if providedif i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):if callback is not None and i % callback_steps == 0:callback(i, t, latents)4 unmodified linesdenoised /= self.vae_decoder.config.get("scaling_factor", 0.18215)# it seems likes there is a strange result for using half-precision vae decoder if batchsize>1image = np.concatenate([self.vae_decoder(latent_sample=denoised[i : i + 1])[0] for i in range(latents.shape[0])])image, has_nsfw_concept = self.run_safety_checker(image)2 unmodified lineselse:do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)if not return_dict:return (image, has_nsfw_concept)return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)10 unmodified lines11121314151617181920212223244 unmodified lines2930313233343536373822 unmodified lines616263646566676818 unmodified lines8788899091929394959697989910010110210310410510610710810911011111211311411511611711821 unmodified lines1401411421431441451461471486 unmodified lines15515615715815916016113 unmodified lines17517617717817918018118218318418518618718818919019114 unmodified lines20620720820921021121221321421586 unmodified lines30230330430530630730830931013 unmodified lines3243253263273283293303313323333348 unmodified lines3433443453463473483493503513523538 unmodified lines3623633643653663673683693702 unmodified lines3733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184 unmodified lines4234244254264274284294304314322 unmodified lines43543643743843944044144244344444544644710 unmodified linesimport torchfrom diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutputfrom optimum.intel.openvino.modeling_diffusion import (OVStableDiffusionPipeline,OVModelUnet,OVModelVaeDecoder,OVModelTextEncoder,OVModelVaeEncoder,VaeImageProcessor,)from optimum.utils import (DIFFUSION_MODEL_TEXT_ENCODER_2_SUBFOLDER,DIFFUSION_MODEL_TEXT_ENCODER_SUBFOLDER,4 unmodified linesfrom diffusers import logginglogger = logging.get_logger(__name__) # pylint: disable=invalid-nameclass LCMOVModelUnet(OVModelUnet):def __call__(self,22 unmodified linesoutputs = self.request(inputs, shared_memory=True)return list(outputs.values())class OVLatentConsistencyModelPipeline(OVStableDiffusionPipeline):def __init__(self,vae_decoder: openvino.runtime.Model,18 unmodified linesself.is_dynamic = dynamic_shapesself.ov_config = ov_config if ov_config is not None else {}self._model_save_dir = (Path(model_save_dir.name)if isinstance(model_save_dir, TemporaryDirectory)else model_save_dir)self.vae_decoder = OVModelVaeDecoder(vae_decoder, self)self.unet = LCMOVModelUnet(unet, self)self.text_encoder = (OVModelTextEncoder(text_encoder, self) if text_encoder is not None else None)self.text_encoder_2 = (OVModelTextEncoder(text_encoder_2,self,model_name=DIFFUSION_MODEL_TEXT_ENCODER_2_SUBFOLDER,)if text_encoder_2 is not Noneelse None)self.vae_encoder = (OVModelVaeEncoder(vae_encoder, self) if vae_encoder is not None else None)if "block_out_channels" in self.vae_decoder.config:self.vae_scale_factor = 2 ** (len(self.vae_decoder.config["block_out_channels"]) - 1)else:self.vae_scale_factor = 821 unmodified lines}for name in sub_models.keys():self._internal_dict[name] = (("optimum", sub_models[name].__class__.__name__)if sub_models[name] is not Noneelse (None, None))self._internal_dict.pop("vae", None)6 unmodified lineswidth: int = -1,num_images_per_prompt: int = -1,tokenizer_max_length: int = -1,):if batch_size == -1 or num_images_per_prompt == -1:batch_size = -1else:13 unmodified linesif in_channels.is_dynamic:logger.warning("Could not identify `in_channels` from the unet configuration, to statically reshape the unet please provide a configuration.")self.is_dynamic = Trueshapes[inputs] = [batch_size, in_channels, height, width]elif inputs.get_any_name() == "timestep_cond":shapes[inputs] = [batch_size, inputs.get_partial_shape()[1]]elif inputs.get_any_name() == "text_embeds":shapes[inputs] = [batch_size,self.text_encoder_2.config["projection_dim"],]elif inputs.get_any_name() == "time_ids":shapes[inputs] = [batch_size, inputs.get_partial_shape()[1]]else:14 unmodified linesembedding vectors with shape `(len(timesteps), embedding_dim)`"""assert len(w.shape) == 1w = w * 1000.0half_dim = embedding_dim // 2emb = np.log(np.array(10000.0)) / (half_dim - 1)emb = np.exp(np.arange(half_dim, dtype=dtype) * -emb)emb = w.astype(dtype)[:, None] * emb[None, :]emb = np.concatenate([np.sin(emb), np.cos(emb)], axis=1)86 unmodified lineslist of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"(nsfw) content, according to the `safety_checker`."""height = (height or self.unet.config.get("sample_size", 64) * self.vae_scale_factor)width = width or self.unet.config.get("sample_size", 64) * self.vae_scale_factor# check inputs. Raise error if not correct13 unmodified linesgenerator = np.random# Create torch.Generator instance with same state as np.random.RandomStatetorch_generator = torch.Generator().manual_seed(int(generator.get_state()[1][0]))# do_classifier_free_guidance = guidance_scale > 1.0# NOTE: when a LCM is distilled from an LDM via latent consistency distillation (Algorithm 1) with guided# distillation, the forward pass of the LCM learns to approximate sampling from the LDM using CFG with the8 unmodified lines)# set timestepsself.scheduler.set_timesteps(num_inference_steps,"cpu",original_inference_steps=original_inference_steps,)timesteps = self.scheduler.timestepslatents = self.prepare_latents(8 unmodified lines# Get Guidance Scale Embeddingw = np.tile(guidance_scale - 1, batch_size * num_images_per_prompt)w_embedding = self.get_guidance_scale_embedding(w, embedding_dim=self.unet.config.get("time_cond_proj_dim", 256))# Adapted from diffusers to extend it for other runtimes than ORTtimestep_dtype = self.unet.input_dtype.get("timestep", np.float32)2 unmodified lines# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502# and should be between [0, 1]accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())extra_step_kwargs = {}if accepts_eta:extra_step_kwargs["eta"] = etaaccepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())if accepts_generator:extra_step_kwargs["generator"] = torch_generatornum_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.orderfor i, t in enumerate(self.progress_bar(timesteps)):# predict the noise residualtimestep = np.array([t], dtype=timestep_dtype)noise_pred = self.unet(sample=latents,timestep=timestep,timestep_cond=w_embedding,encoder_hidden_states=prompt_embeds,)[0]# compute the previous noisy sample x_t -> x_t-1latents, denoised = self.scheduler.step(torch.from_numpy(noise_pred),t,torch.from_numpy(latents),**extra_step_kwargs,return_dict=False,)latents, denoised = latents.numpy(), denoised.numpy()# call the callback, if providedif i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):if callback is not None and i % callback_steps == 0:callback(i, t, latents)4 unmodified linesdenoised /= self.vae_decoder.config.get("scaling_factor", 0.18215)# it seems likes there is a strange result for using half-precision vae decoder if batchsize>1image = np.concatenate([self.vae_decoder(latent_sample=denoised[i : i + 1])[0]for i in range(latents.shape[0])])image, has_nsfw_concept = self.run_safety_checker(image)2 unmodified lineselse:do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)if not return_dict:return (image, has_nsfw_concept)return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
212 unmodified lines2132142152162172182192202212222232242252262272282296 unmodified lines23623723823924024124224324424524624724824919 unmodified lines26927027127227327427524 unmodified lines3003013023033043053065 unmodified lines31231331431531631731830 unmodified lines34935035135235335435519 unmodified lines37537637737837938038150 unmodified lines4324334344354364374383 unmodified lines4424434444454464474484494504514522 unmodified lines4554564574584594604615 unmodified lines46746846947047147247347413 unmodified lines4884894904914924934946 unmodified lines501502503504505506507508509510511512513514515212 unmodified linesif trained_betas is not None:self.betas = torch.tensor(trained_betas, dtype=torch.float32)elif beta_schedule == "linear":self.betas = torch.linspace(beta_start, beta_end, num_train_timesteps, dtype=torch.float32)elif beta_schedule == "scaled_linear":# this schedule is very specific to the latent diffusion model.self.betas = (torch.linspace(beta_start**0.5, beta_end**0.5, num_train_timesteps, dtype=torch.float32) ** 2)elif beta_schedule == "squaredcos_cap_v2":# Glide cosine scheduleself.betas = betas_for_alpha_bar(num_train_timesteps)else:raise NotImplementedError(f"{beta_schedule} does is not implemented for {self.__class__}")# Rescale for zero SNRif rescale_betas_zero_snr:6 unmodified lines# For the final step, there is no previous alphas_cumprod because we are already at 0# `set_alpha_to_one` decides whether we set this parameter simply to one or# whether we use the final alpha of the "non-previous" one.self.final_alpha_cumprod = torch.tensor(1.0) if set_alpha_to_one else self.alphas_cumprod[0]# standard deviation of the initial noise distributionself.init_noise_sigma = 1.0# setable valuesself.num_inference_steps = Noneself.timesteps = torch.from_numpy(np.arange(0, num_train_timesteps)[::-1].copy().astype(np.int64))self._step_index = None19 unmodified linesdef step_index(self):return self._step_indexdef scale_model_input(self, sample: torch.FloatTensor, timestep: Optional[int] = None) -> torch.FloatTensor:"""Ensures interchangeability with schedulers that need to scale the denoising model input depending on thecurrent timestep.24 unmodified linesbatch_size, channels, *remaining_dims = sample.shapeif dtype not in (torch.float32, torch.float64):sample = sample.float() # upcast for quantile calculation, and clamp not implemented for cpu half# Flatten sample for doing quantile calculation along each imagesample = sample.reshape(batch_size, channels * np.prod(remaining_dims))5 unmodified liness, min=1, max=self.config.sample_max_value) # When clamped to min=1, equivalent to standard clipping to [-1, 1]s = s.unsqueeze(1) # (batch_size, 1) because clamp will broadcast along dim=0sample = torch.clamp(sample, -s, s) / s # "we threshold xt0 to the range [-s, s] and then divide by s"sample = sample.reshape(batch_size, channels, *remaining_dims)sample = sample.to(dtype)30 unmodified linesself.num_inference_steps = num_inference_stepsoriginal_steps = (original_inference_steps if original_inference_steps is not None else self.original_inference_steps)if original_steps > self.config.num_train_timesteps:19 unmodified lines# LCM Inference Steps Scheduletimesteps = lcm_origin_timesteps[::-skipping_step][:num_inference_steps]self.timesteps = torch.from_numpy(timesteps.copy()).to(device=device, dtype=torch.long)self._step_index = None50 unmodified lines# 2. compute alphas, betasalpha_prod_t = self.alphas_cumprod[timestep]alpha_prod_t_prev = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprodbeta_prod_t = 1 - alpha_prod_tbeta_prod_t_prev = 1 - alpha_prod_t_prev3 unmodified lines# 4. Compute the predicted original sample x_0 based on the model parameterizationif self.config.prediction_type == "epsilon": # noise-predictionpredicted_original_sample = (sample - beta_prod_t.sqrt() * model_output) / alpha_prod_t.sqrt()elif self.config.prediction_type == "sample": # x-predictionpredicted_original_sample = model_outputelif self.config.prediction_type == "v_prediction": # v-predictionpredicted_original_sample = alpha_prod_t.sqrt() * sample - beta_prod_t.sqrt() * model_outputelse:raise ValueError(f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` or"2 unmodified lines# 5. Clip or threshold "predicted x_0"if self.config.thresholding:predicted_original_sample = self._threshold_sample(predicted_original_sample)elif self.config.clip_sample:predicted_original_sample = predicted_original_sample.clamp(-self.config.clip_sample_range, self.config.clip_sample_range5 unmodified lines# 7. Sample and inject noise z ~ N(0, I) for MultiStep Inference# Noise is not used for one-step sampling.if len(self.timesteps) > 1:noise = randn_tensor(model_output.shape, generator=generator, device=model_output.device)prev_sample = alpha_prod_t_prev.sqrt() * denoised + beta_prod_t_prev.sqrt() * noiseelse:prev_sample = denoised13 unmodified linestimesteps: torch.IntTensor,) -> torch.FloatTensor:# Make sure alphas_cumprod and timestep have same device and dtype as original_samplesalphas_cumprod = self.alphas_cumprod.to(device=original_samples.device, dtype=original_samples.dtype)timesteps = timesteps.to(original_samples.device)sqrt_alpha_prod = alphas_cumprod[timesteps] ** 0.56 unmodified lineswhile len(sqrt_one_minus_alpha_prod.shape) < len(original_samples.shape):sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.unsqueeze(-1)noisy_samples = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noisereturn noisy_samples# Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler.get_velocitydef get_velocity(self, sample: torch.FloatTensor, noise: torch.FloatTensor, timesteps: torch.IntTensor) -> torch.FloatTensor:# Make sure alphas_cumprod and timestep have same device and dtype as samplealphas_cumprod = self.alphas_cumprod.to(device=sample.device, dtype=sample.dtype)timesteps = timesteps.to(sample.device)sqrt_alpha_prod = alphas_cumprod[timesteps] ** 0.5212 unmodified lines2132142152162172182192202212222232242252262272282292302312322332342352362372382396 unmodified lines24624724824925025125225325425525625725825926026126226319 unmodified lines28328428528628728828929029124 unmodified lines3163173183193203213223233245 unmodified lines33033133233333433533633733830 unmodified lines36937037137237337437537637719 unmodified lines39739839940040140240340440550 unmodified lines4564574584594604614624634644654663 unmodified lines4704714724734744754764774784794804814824834842 unmodified lines4874884894904914924934944955 unmodified lines50150250350450550650750850951051151213 unmodified lines5265275285295305315325335346 unmodified lines541542543544545546547548549550551552553554555556557558559560561562212 unmodified linesif trained_betas is not None:self.betas = torch.tensor(trained_betas, dtype=torch.float32)elif beta_schedule == "linear":self.betas = torch.linspace(beta_start, beta_end, num_train_timesteps, dtype=torch.float32)elif beta_schedule == "scaled_linear":# this schedule is very specific to the latent diffusion model.self.betas = (torch.linspace(beta_start**0.5,beta_end**0.5,num_train_timesteps,dtype=torch.float32,)** 2)elif beta_schedule == "squaredcos_cap_v2":# Glide cosine scheduleself.betas = betas_for_alpha_bar(num_train_timesteps)else:raise NotImplementedError(f"{beta_schedule} does is not implemented for {self.__class__}")# Rescale for zero SNRif rescale_betas_zero_snr:6 unmodified lines# For the final step, there is no previous alphas_cumprod because we are already at 0# `set_alpha_to_one` decides whether we set this parameter simply to one or# whether we use the final alpha of the "non-previous" one.self.final_alpha_cumprod = (torch.tensor(1.0) if set_alpha_to_one else self.alphas_cumprod[0])# standard deviation of the initial noise distributionself.init_noise_sigma = 1.0# setable valuesself.num_inference_steps = Noneself.timesteps = torch.from_numpy(np.arange(0, num_train_timesteps)[::-1].copy().astype(np.int64))self._step_index = None19 unmodified linesdef step_index(self):return self._step_indexdef scale_model_input(self, sample: torch.FloatTensor, timestep: Optional[int] = None) -> torch.FloatTensor:"""Ensures interchangeability with schedulers that need to scale the denoising model input depending on thecurrent timestep.24 unmodified linesbatch_size, channels, *remaining_dims = sample.shapeif dtype not in (torch.float32, torch.float64):sample = (sample.float()) # upcast for quantile calculation, and clamp not implemented for cpu half# Flatten sample for doing quantile calculation along each imagesample = sample.reshape(batch_size, channels * np.prod(remaining_dims))5 unmodified liness, min=1, max=self.config.sample_max_value) # When clamped to min=1, equivalent to standard clipping to [-1, 1]s = s.unsqueeze(1) # (batch_size, 1) because clamp will broadcast along dim=0sample = (torch.clamp(sample, -s, s) / s) # "we threshold xt0 to the range [-s, s] and then divide by s"sample = sample.reshape(batch_size, channels, *remaining_dims)sample = sample.to(dtype)30 unmodified linesself.num_inference_steps = num_inference_stepsoriginal_steps = (original_inference_stepsif original_inference_steps is not Noneelse self.original_inference_steps)if original_steps > self.config.num_train_timesteps:19 unmodified lines# LCM Inference Steps Scheduletimesteps = lcm_origin_timesteps[::-skipping_step][:num_inference_steps]self.timesteps = torch.from_numpy(timesteps.copy()).to(device=device, dtype=torch.long)self._step_index = None50 unmodified lines# 2. compute alphas, betasalpha_prod_t = self.alphas_cumprod[timestep]alpha_prod_t_prev = (self.alphas_cumprod[prev_timestep]if prev_timestep >= 0else self.final_alpha_cumprod)beta_prod_t = 1 - alpha_prod_tbeta_prod_t_prev = 1 - alpha_prod_t_prev3 unmodified lines# 4. Compute the predicted original sample x_0 based on the model parameterizationif self.config.prediction_type == "epsilon": # noise-predictionpredicted_original_sample = (sample - beta_prod_t.sqrt() * model_output) / alpha_prod_t.sqrt()elif self.config.prediction_type == "sample": # x-predictionpredicted_original_sample = model_outputelif self.config.prediction_type == "v_prediction": # v-predictionpredicted_original_sample = (alpha_prod_t.sqrt() * sample - beta_prod_t.sqrt() * model_output)else:raise ValueError(f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` or"2 unmodified lines# 5. Clip or threshold "predicted x_0"if self.config.thresholding:predicted_original_sample = self._threshold_sample(predicted_original_sample)elif self.config.clip_sample:predicted_original_sample = predicted_original_sample.clamp(-self.config.clip_sample_range, self.config.clip_sample_range5 unmodified lines# 7. Sample and inject noise z ~ N(0, I) for MultiStep Inference# Noise is not used for one-step sampling.if len(self.timesteps) > 1:noise = randn_tensor(model_output.shape, generator=generator, device=model_output.device)prev_sample = (alpha_prod_t_prev.sqrt() * denoised + beta_prod_t_prev.sqrt() * noise)else:prev_sample = denoised13 unmodified linestimesteps: torch.IntTensor,) -> torch.FloatTensor:# Make sure alphas_cumprod and timestep have same device and dtype as original_samplesalphas_cumprod = self.alphas_cumprod.to(device=original_samples.device, dtype=original_samples.dtype)timesteps = timesteps.to(original_samples.device)sqrt_alpha_prod = alphas_cumprod[timesteps] ** 0.56 unmodified lineswhile len(sqrt_one_minus_alpha_prod.shape) < len(original_samples.shape):sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.unsqueeze(-1)noisy_samples = (sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise)return noisy_samples# Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler.get_velocitydef get_velocity(self,sample: torch.FloatTensor,noise: torch.FloatTensor,timesteps: torch.IntTensor,) -> torch.FloatTensor:# Make sure alphas_cumprod and timestep have same device and dtype as samplealphas_cumprod = self.alphas_cumprod.to(device=sample.device, dtype=sample.dtype)timesteps = timesteps.to(sample.device)sqrt_alpha_prod = alphas_cumprod[timesteps] ** 0.5
12345678910111213141516171819from typing import Optionalfrom pydantic import BaseModelfrom constants import LCM_DEFAULT_MODELclass LCMDiffusionSetting(BaseModel):lcm_model_id: str = LCM_DEFAULT_MODELprompt: str = ""image_height: Optional[int] = 512image_width: Optional[int] = 512inference_steps: Optional[int] = 4guidance_scale: Optional[float] = 8number_of_images: Optional[int] = 1seed: Optional[int] = -1use_openvino: bool = Falseuse_seed: bool = Falseuse_offline_model: bool = Falseuse_safety_checker: bool = True1234567891011121314151617181920212223242526272829from typing import Optionalfrom pydantic import BaseModelfrom constants import LCM_DEFAULT_MODEL, LCM_DEFAULT_MODEL_OPENVINOclass LCMLora(BaseModel):base_model_id: str = ""lcm_lora_id: str = ""class LCMDiffusionSetting(BaseModel):lcm_model_id: str = LCM_DEFAULT_MODELopenvino_lcm_model_id: str = LCM_DEFAULT_MODEL_OPENVINOuse_offline_model: bool = Falseuse_lcm_lora: bool = Falselcm_lora: Optional[LCMLora] = LCMLora()use_tiny_auto_encoder: bool = Falseuse_openvino: bool = Falseprompt: str = ""negative_prompt: str = ""image_height: Optional[int] = 512image_width: Optional[int] = 512inference_steps: Optional[int] = 4guidance_scale: Optional[float] = 1number_of_images: Optional[int] = 1seed: Optional[int] = -1use_seed: bool = Falseuse_safety_checker: bool = False
12345678910from os import environAPP_VERSION = "v1.0.0 beta 7"LCM_DEFAULT_MODEL = "SimianLuo/LCM_Dreamshaper_v7"LCM_DEFAULT_MODEL_OPENVINO = "rupeshs/LCM-dreamshaper-v7-openvino-int8"APP_NAME = "FastSD CPU"APP_SETTINGS_FILE = "settings.yaml"RESULTS_DIRECTORY = "results"CONFIG_DIRECTORY = "configs"DEVICE = environ.get("DEVICE", "cpu")12345678910111213141516from os import environAPP_VERSION = "v1.0.0 beta 16"LCM_DEFAULT_MODEL = "SimianLuo/LCM_Dreamshaper_v7"LCM_DEFAULT_MODEL_OPENVINO = "rupeshs/LCM-dreamshaper-v7-openvino"APP_NAME = "FastSD CPU"APP_SETTINGS_FILE = "settings.yaml"RESULTS_DIRECTORY = "results"CONFIG_DIRECTORY = "configs"DEVICE = environ.get("DEVICE", "cpu")SD_MODELS_FILE = "stable-diffusion-models.txt"LCM_LORA_MODELS_FILE = "lcm-lora-models.txt"OPENVINO_LCM_MODELS_FILE = "openvino-lcm-models.txt"TAESD_MODEL = "madebyollin/taesd"TAESDXL_MODEL = "madebyollin/taesdxl"TAESD_MODEL_OPENVINO = "deinferno/taesd-openvino"
1 unmodified line234567813 unmodified lines22232425262728293031323334353637383940414243441 unmodified linefrom app_settings import Settingsfrom models.interface_types import InterfaceTypefrom backend.lcm_text_to_image import LCMTextToImagefrom time import timefrom backend.image_saver import ImageSaverfrom pprint import pprint13 unmodified linesreshape: bool = False,device: str = "cpu",) -> Any:tick = time()pprint(settings.lcm_diffusion_setting.model_dump())self.lcm_text_to_image.init(settings.lcm_diffusion_setting.lcm_model_id,settings.lcm_diffusion_setting.use_openvino,device,settings.lcm_diffusion_setting.use_offline_model,)images = self.lcm_text_to_image.generate(settings.lcm_diffusion_setting,reshape,)elapsed = time() - tick# ImageSaver.save_images(# settings.results_path,# images=images,# lcm_diffusion_setting=settings.lcm_diffusion_setting,# )print(f"Elapsed time : {elapsed:.2f} seconds")return images1 unmodified line234567813 unmodified lines222324252627282930313233343536373839404142434445464748491 unmodified linefrom app_settings import Settingsfrom models.interface_types import InterfaceTypefrom backend.lcm_text_to_image import LCMTextToImagefrom time import perf_counterfrom backend.image_saver import ImageSaverfrom pprint import pprint13 unmodified linesreshape: bool = False,device: str = "cpu",) -> Any:tick = perf_counter()pprint(settings.lcm_diffusion_setting.model_dump())if not settings.lcm_diffusion_setting.lcm_lora:return Noneself.lcm_text_to_image.init(settings.lcm_diffusion_setting.lcm_model_id,settings.lcm_diffusion_setting.use_openvino,device,settings.lcm_diffusion_setting.use_offline_model,settings.lcm_diffusion_setting.use_tiny_auto_encoder,settings.lcm_diffusion_setting.use_lcm_lora,settings.lcm_diffusion_setting.lcm_lora,)images = self.lcm_text_to_image.generate(settings.lcm_diffusion_setting,reshape,)elapsed = perf_counter() - tickImageSaver.save_images(settings.results_path,images=images,lcm_diffusion_setting=settings.lcm_diffusion_setting,)print(f"Elapsed time : {elapsed:.2f} seconds")return images
15 unmodified lines1617181920212211 unmodified lines34353637383940414243444546474849505137 unmodified lines8990919293945 unmodified lines10010110210310410510610710810911011111211311411511611711811910 unmodified lines13013113213313413510 unmodified lines1461471481491501511521531541551569 unmodified lines1661671681691701711721731741751761 unmodified line1781791801811821832 unmodified lines1861871881891901919 unmodified lines20120220320420520620720820921021121221321413 unmodified lines2282292302312322332342357 unmodified lines24324424524624724824922 unmodified lines2722732742752762772782792802812824 unmodified lines28728828929029129229320 unmodified lines31431531631731831932032132232332432532632732832933033133229 unmodified lines36236336436536636736836937037137230 unmodified lines40340440540640740840918 unmodified lines42842943043143243343443515 unmodified linesQToolButton,QFileDialog,)from PyQt5.QtGui import QPixmap, QDesktopServicesfrom PyQt5.QtCore import QSize, QThreadPool, Qt, QUrl11 unmodified linesfrom context import Contextfrom models.interface_types import InterfaceTypefrom constants import DEVICEfrom frontend.utils import enable_openvino_controlsclass MainWindow(QMainWindow):def __init__(self, config: AppSettings):super().__init__()self.setWindowTitle(APP_NAME)self.setFixedSize(QSize(600, 620))self.init_ui()self.pipeline = Noneself.threadpool = QThreadPool()self.config = configself.device = "cpu"self.previous_width = 0self.previous_height = 037 unmodified linesself.num_images.setValue(self.config.settings.lcm_diffusion_setting.number_of_images)def init_ui(self):self.create_main_tab()5 unmodified linesself.img = QLabel("<<Image>>")self.img.setAlignment(Qt.AlignCenter)self.img.setFixedSize(QSize(512, 512))self.prompt = QTextEdit()self.prompt.setPlaceholderText("A fantasy landscape")self.prompt.setAcceptRichText(False)self.generate = QPushButton("Generate")self.generate.clicked.connect(self.text_to_image)self.prompt.setFixedHeight(35)self.browse_results = QPushButton("...")self.browse_results.setFixedWidth(30)self.browse_results.clicked.connect(self.on_open_results_folder)self.browse_results.setToolTip("Open output folder")hlayout = QHBoxLayout()hlayout.addWidget(self.prompt)hlayout.addWidget(self.generate)hlayout.addWidget(self.browse_results)10 unmodified linesvlayout = QVBoxLayout()vlayout.addLayout(hlayout_nav)vlayout.addLayout(hlayout)self.tab_widget = QTabWidget(self)10 unmodified linesself.use_seed = Falsedef create_settings_tab(self):model_hlayout = QHBoxLayout()self.lcm_model_label = QLabel("Latent Consistency Model:")self.lcm_model = QLineEdit(LCM_DEFAULT_MODEL)model_hlayout.addWidget(self.lcm_model_label)model_hlayout.addWidget(self.lcm_model)self.inference_steps_value = QLabel("Number of inference steps: 4")self.inference_steps = QSlider(orientation=Qt.Orientation.Horizontal)9 unmodified linesself.num_images.setValue(1)self.num_images.valueChanged.connect(self.update_num_images_label)self.guidance_value = QLabel("Guidance scale: 8")self.guidance = QSlider(orientation=Qt.Orientation.Horizontal)self.guidance.setMaximum(200)self.guidance.setMinimum(10)self.guidance.setValue(80)self.guidance.valueChanged.connect(self.update_guidance_label)self.width_value = QLabel("Width :")1 unmodified lineself.width.addItem("256")self.width.addItem("512")self.width.addItem("768")self.width.setCurrentText("512")self.width.currentIndexChanged.connect(self.on_width_changed)2 unmodified linesself.height.addItem("256")self.height.addItem("512")self.height.addItem("768")self.height.setCurrentText("512")self.height.currentIndexChanged.connect(self.on_height_changed)9 unmodified linesself.use_openvino_check = QCheckBox("Use OpenVINO")self.use_openvino_check.setChecked(False)self.use_local_model_folder = QCheckBox("Use locally cached model or downloaded model folder(offline)")self.use_openvino_check.setEnabled(enable_openvino_controls())self.use_local_model_folder.setChecked(False)self.use_local_model_folder.stateChanged.connect(self.use_offline_model_changed)self.use_openvino_check.stateChanged.connect(self.use_openvino_changed)hlayout = QHBoxLayout()hlayout.addWidget(self.seed_check)hlayout.addWidget(self.seed_value)13 unmodified linesvlayout = QVBoxLayout()vspacer = QSpacerItem(20, 20, QSizePolicy.Minimum, QSizePolicy.Expanding)vlayout.addItem(hspacer)vlayout.addLayout(model_hlayout)vlayout.addWidget(self.use_local_model_folder)vlayout.addItem(slider_hspacer)vlayout.addWidget(self.inference_steps_value)vlayout.addWidget(self.inference_steps)7 unmodified linesvlayout.addWidget(self.guidance)vlayout.addLayout(hlayout)vlayout.addWidget(self.safety_checker)vlayout.addWidget(self.use_openvino_check)vlayout.addWidget(self.results_path_label)hlayout_path = QHBoxLayout()hlayout_path.addWidget(self.results_path)22 unmodified linesvlayout.addWidget(self.label)self.tab_about.setLayout(vlayout)def on_show_next_image(self):if self.image_index != len(self.gen_images) - 1 and len(self.gen_images) > 0:self.previous_img_btn.setEnabled(True)self.image_index += 1self.img.setPixmap(self.gen_images[self.image_index])if self.image_index == len(self.gen_images) - 1:self.next_img_btn.setEnabled(False)4 unmodified linesif self.image_index != 0:self.next_img_btn.setEnabled(True)self.image_index -= 1self.img.setPixmap(self.gen_images[self.image_index])if self.image_index == 0:self.previous_img_btn.setEnabled(False)20 unmodified linesheight_txt = self.height.itemText(index)self.config.settings.lcm_diffusion_setting.image_height = int(height_txt)def use_openvino_changed(self, state):if state == 2:self.lcm_model.setEnabled(False)self.config.settings.lcm_diffusion_setting.use_openvino = Trueelse:self.config.settings.lcm_diffusion_setting.use_openvino = Falsedef use_offline_model_changed(self, state):if state == 2:self.config.settings.lcm_diffusion_setting.use_offline_model = Trueelse:self.config.settings.lcm_diffusion_setting.use_offline_model = Falsedef use_safety_checker_changed(self, state):if state == 2:self.config.settings.lcm_diffusion_setting.use_safety_checker = True29 unmodified linesdef generate_image(self):self.config.settings.lcm_diffusion_setting.seed = self.get_seed_value()self.config.settings.lcm_diffusion_setting.prompt = self.prompt.toPlainText()if self.config.settings.lcm_diffusion_setting.use_openvino:model_id = LCM_DEFAULT_MODEL_OPENVINOelse:model_id = self.lcm_model.text()self.config.settings.lcm_diffusion_setting.lcm_model_id = model_id30 unmodified linesself.next_img_btn.setEnabled(False)self.previous_img_btn.setEnabled(False)self.img.setPixmap(self.gen_images[0])self.previous_width = self.config.settings.lcm_diffusion_setting.image_widthself.previous_height = self.config.settings.lcm_diffusion_setting.image_height18 unmodified linesself.width.setCurrentText("512")self.height.setCurrentText("512")self.inference_steps.setValue(4)self.guidance.setValue(80)self.use_openvino_check.setChecked(False)self.seed_check.setChecked(False)self.safety_checker.setChecked(True)self.results_path.setText(FastStableDiffusionPaths().get_results_path())15 unmodified lines1617181920212211 unmodified lines343536373839404142434445464748495051525354555637 unmodified lines9495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291305 unmodified lines13613713813914014114214314414514614714814915015115215315415515615715815916016110 unmodified lines17217317417517617717817918010 unmodified lines1911921931941951961971981992002012022032042052062072082092102112122132142152169 unmodified lines2262272282292302312322332342352361 unmodified line2382392402412422432442 unmodified lines2472482492502512522539 unmodified lines26326426526626726826927027127227327427527627727827928028128228328428528628728828913 unmodified lines3033043053063073083093103113123133143153163173183193207 unmodified lines32832933033133233333422 unmodified lines3573583593603613623633643653663673683693703713723733743753763773783793803813823834 unmodified lines38838939039139239339420 unmodified lines41541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547629 unmodified lines50650750850951051151251351451551651751851952052152252352452530 unmodified lines55655755855956056156218 unmodified lines58158258358458558658758858959015 unmodified linesQToolButton,QFileDialog,)from PyQt5 import QtWidgets, QtCorefrom PyQt5.QtGui import QPixmap, QDesktopServicesfrom PyQt5.QtCore import QSize, QThreadPool, Qt, QUrl11 unmodified linesfrom context import Contextfrom models.interface_types import InterfaceTypefrom constants import DEVICEfrom frontend.utils import enable_openvino_controls, get_valid_model_idfrom backend.lcm_models import get_available_models# DPI scale fixQtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True)QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, True)class MainWindow(QMainWindow):def __init__(self, config: AppSettings):super().__init__()self.config = configself.setWindowTitle(APP_NAME)self.setFixedSize(QSize(600, 670))self.init_ui()self.pipeline = Noneself.threadpool = QThreadPool()self.device = "cpu"self.previous_width = 0self.previous_height = 037 unmodified linesself.num_images.setValue(self.config.settings.lcm_diffusion_setting.number_of_images)self.use_tae_sd.setChecked(self.config.settings.lcm_diffusion_setting.use_tiny_auto_encoder)self.use_lcm_lora.setChecked(self.config.settings.lcm_diffusion_setting.use_lcm_lora)self.base_model_id.setCurrentText(get_valid_model_id(self.config.stable_diffsuion_models,self.config.settings.lcm_diffusion_setting.lcm_lora.base_model_id,))self.lcm_lora_id.setCurrentText(get_valid_model_id(self.config.lcm_lora_models,self.config.settings.lcm_diffusion_setting.lcm_lora.lcm_lora_id,))self.openvino_lcm_model_id.setCurrentText(get_valid_model_id(self.config.openvino_lcm_models,self.config.settings.lcm_diffusion_setting.openvino_lcm_model_id,))self.neg_prompt.setEnabled(self.config.settings.lcm_diffusion_setting.use_lcm_loraor self.config.settings.lcm_diffusion_setting.use_openvino)self.openvino_lcm_model_id.setEnabled(self.config.settings.lcm_diffusion_setting.use_openvino)def init_ui(self):self.create_main_tab()5 unmodified linesself.img = QLabel("<<Image>>")self.img.setAlignment(Qt.AlignCenter)self.img.setFixedSize(QSize(512, 512))self.vspacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)self.prompt = QTextEdit()self.prompt.setPlaceholderText("A fantasy landscape")self.prompt.setAcceptRichText(False)self.neg_prompt = QTextEdit()self.neg_prompt.setPlaceholderText("")self.neg_prompt.setAcceptRichText(False)self.neg_prompt_label = QLabel("Negative prompt (Set guidance scale > 1.0):")self.generate = QPushButton("Generate")self.generate.clicked.connect(self.text_to_image)self.prompt.setFixedHeight(40)self.neg_prompt.setFixedHeight(35)self.browse_results = QPushButton("...")self.browse_results.setFixedWidth(30)self.browse_results.clicked.connect(self.on_open_results_folder)self.browse_results.setToolTip("Open output folder")hlayout = QHBoxLayout()hlayout.addWidget(self.neg_prompt)hlayout.addWidget(self.generate)hlayout.addWidget(self.browse_results)10 unmodified linesvlayout = QVBoxLayout()vlayout.addLayout(hlayout_nav)vlayout.addItem(self.vspacer)vlayout.addWidget(self.prompt)vlayout.addWidget(self.neg_prompt_label)vlayout.addLayout(hlayout)self.tab_widget = QTabWidget(self)10 unmodified linesself.use_seed = Falsedef create_settings_tab(self):self.lcm_model_label = QLabel("Latent Consistency Model:")# self.lcm_model = QLineEdit(LCM_DEFAULT_MODEL)lcm_models = get_available_models()self.lcm_model = QComboBox(self)for model in lcm_models:self.lcm_model.addItem(model)self.use_lcm_lora = QCheckBox("Use LCM LoRA")self.use_lcm_lora.setChecked(False)self.use_lcm_lora.stateChanged.connect(self.use_lcm_lora_changed)self.lora_base_model_id_label = QLabel("Lora base model ID :")self.base_model_id = QComboBox(self)self.base_model_id.addItems(self.config.stable_diffsuion_models)self.base_model_id.currentIndexChanged.connect(self.on_base_model_id_changed)self.lcm_lora_model_id_label = QLabel("LCM LoRA model ID :")self.lcm_lora_id = QComboBox(self)self.lcm_lora_id.addItems(self.config.lcm_lora_models)self.lcm_lora_id.currentIndexChanged.connect(self.on_lcm_lora_id_changed)self.inference_steps_value = QLabel("Number of inference steps: 4")self.inference_steps = QSlider(orientation=Qt.Orientation.Horizontal)9 unmodified linesself.num_images.setValue(1)self.num_images.valueChanged.connect(self.update_num_images_label)self.guidance_value = QLabel("Guidance scale: 1")self.guidance = QSlider(orientation=Qt.Orientation.Horizontal)self.guidance.setMaximum(20)self.guidance.setMinimum(10)self.guidance.setValue(10)self.guidance.valueChanged.connect(self.update_guidance_label)self.width_value = QLabel("Width :")1 unmodified lineself.width.addItem("256")self.width.addItem("512")self.width.addItem("768")self.width.addItem("1024")self.width.setCurrentText("512")self.width.currentIndexChanged.connect(self.on_width_changed)2 unmodified linesself.height.addItem("256")self.height.addItem("512")self.height.addItem("768")self.height.addItem("1024")self.height.setCurrentText("512")self.height.currentIndexChanged.connect(self.on_height_changed)9 unmodified linesself.use_openvino_check = QCheckBox("Use OpenVINO")self.use_openvino_check.setChecked(False)self.openvino_model_label = QLabel("OpenVINO LCM model:")self.use_local_model_folder = QCheckBox("Use locally cached model or downloaded model folder(offline)")self.openvino_lcm_model_id = QComboBox(self)self.openvino_lcm_model_id.addItems(self.config.openvino_lcm_models)self.openvino_lcm_model_id.currentIndexChanged.connect(self.on_openvino_lcm_model_id_changed)self.use_openvino_check.setEnabled(enable_openvino_controls())self.use_local_model_folder.setChecked(False)self.use_local_model_folder.stateChanged.connect(self.use_offline_model_changed)self.use_openvino_check.stateChanged.connect(self.use_openvino_changed)self.use_tae_sd = QCheckBox("Use Tiny Auto Encoder - TAESD (Fast, moderate quality)")self.use_tae_sd.setChecked(False)self.use_tae_sd.stateChanged.connect(self.use_tae_sd_changed)hlayout = QHBoxLayout()hlayout.addWidget(self.seed_check)hlayout.addWidget(self.seed_value)13 unmodified linesvlayout = QVBoxLayout()vspacer = QSpacerItem(20, 20, QSizePolicy.Minimum, QSizePolicy.Expanding)vlayout.addItem(hspacer)vlayout.addWidget(self.lcm_model_label)vlayout.addWidget(self.lcm_model)vlayout.addWidget(self.use_local_model_folder)vlayout.addWidget(self.use_lcm_lora)vlayout.addWidget(self.lora_base_model_id_label)vlayout.addWidget(self.base_model_id)vlayout.addWidget(self.lcm_lora_model_id_label)vlayout.addWidget(self.lcm_lora_id)vlayout.addWidget(self.use_openvino_check)vlayout.addWidget(self.openvino_model_label)vlayout.addWidget(self.openvino_lcm_model_id)vlayout.addWidget(self.use_tae_sd)vlayout.addItem(slider_hspacer)vlayout.addWidget(self.inference_steps_value)vlayout.addWidget(self.inference_steps)7 unmodified linesvlayout.addWidget(self.guidance)vlayout.addLayout(hlayout)vlayout.addWidget(self.safety_checker)vlayout.addWidget(self.results_path_label)hlayout_path = QHBoxLayout()hlayout_path.addWidget(self.results_path)22 unmodified linesvlayout.addWidget(self.label)self.tab_about.setLayout(vlayout)def show_image(self, pixmap):image_width = self.config.settings.lcm_diffusion_setting.image_widthimage_height = self.config.settings.lcm_diffusion_setting.image_heightif image_width > 512 or image_height > 512:new_width = 512 if image_width > 512 else image_widthnew_height = 512 if image_height > 512 else image_heightself.img.setPixmap(pixmap.scaled(new_width,new_height,Qt.KeepAspectRatio,))else:self.img.setPixmap(pixmap)def on_show_next_image(self):if self.image_index != len(self.gen_images) - 1 and len(self.gen_images) > 0:self.previous_img_btn.setEnabled(True)self.image_index += 1self.show_image(self.gen_images[self.image_index])if self.image_index == len(self.gen_images) - 1:self.next_img_btn.setEnabled(False)4 unmodified linesif self.image_index != 0:self.next_img_btn.setEnabled(True)self.image_index -= 1self.show_image(self.gen_images[self.image_index])if self.image_index == 0:self.previous_img_btn.setEnabled(False)20 unmodified linesheight_txt = self.height.itemText(index)self.config.settings.lcm_diffusion_setting.image_height = int(height_txt)def on_base_model_id_changed(self, index):model_id = self.base_model_id.itemText(index)self.config.settings.lcm_diffusion_setting.lcm_lora.base_model_id = model_iddef on_lcm_lora_id_changed(self, index):model_id = self.lcm_lora_id.itemText(index)self.config.settings.lcm_diffusion_setting.lcm_lora.lcm_lora_id = model_iddef on_openvino_lcm_model_id_changed(self, index):model_id = self.openvino_lcm_model_id.itemText(index)self.config.settings.lcm_diffusion_setting.openvino_lcm_model_id = model_iddef use_openvino_changed(self, state):if state == 2:self.lcm_model.setEnabled(False)self.use_lcm_lora.setEnabled(False)self.lcm_lora_id.setEnabled(False)self.base_model_id.setEnabled(False)self.neg_prompt.setEnabled(True)self.openvino_lcm_model_id.setEnabled(True)self.config.settings.lcm_diffusion_setting.use_openvino = Trueelse:self.lcm_model.setEnabled(True)self.use_lcm_lora.setEnabled(True)self.lcm_lora_id.setEnabled(True)self.base_model_id.setEnabled(True)self.neg_prompt.setEnabled(False)self.openvino_lcm_model_id.setEnabled(False)self.config.settings.lcm_diffusion_setting.use_openvino = Falsedef use_tae_sd_changed(self, state):if state == 2:self.config.settings.lcm_diffusion_setting.use_tiny_auto_encoder = Trueelse:self.config.settings.lcm_diffusion_setting.use_tiny_auto_encoder = Falsedef use_offline_model_changed(self, state):if state == 2:self.config.settings.lcm_diffusion_setting.use_offline_model = Trueelse:self.config.settings.lcm_diffusion_setting.use_offline_model = Falsedef use_lcm_lora_changed(self, state):if state == 2:self.lcm_model.setEnabled(False)self.lcm_lora_id.setEnabled(True)self.base_model_id.setEnabled(True)self.neg_prompt.setEnabled(True)self.config.settings.lcm_diffusion_setting.use_lcm_lora = Trueelse:self.lcm_model.setEnabled(True)self.lcm_lora_id.setEnabled(False)self.base_model_id.setEnabled(False)self.neg_prompt.setEnabled(False)self.config.settings.lcm_diffusion_setting.use_lcm_lora = Falsedef use_safety_checker_changed(self, state):if state == 2:self.config.settings.lcm_diffusion_setting.use_safety_checker = True29 unmodified linesdef generate_image(self):self.config.settings.lcm_diffusion_setting.seed = self.get_seed_value()self.config.settings.lcm_diffusion_setting.prompt = self.prompt.toPlainText()self.config.settings.lcm_diffusion_setting.negative_prompt = (self.neg_prompt.toPlainText())self.config.settings.lcm_diffusion_setting.lcm_lora.lcm_lora_id = (self.lcm_lora_id.currentText())self.config.settings.lcm_diffusion_setting.lcm_lora.base_model_id = (self.base_model_id.currentText())if self.config.settings.lcm_diffusion_setting.use_openvino:model_id = self.openvino_lcm_model_id.currentText()else:model_id = self.lcm_model.currentText()self.config.settings.lcm_diffusion_setting.lcm_model_id = model_id30 unmodified linesself.next_img_btn.setEnabled(False)self.previous_img_btn.setEnabled(False)self.show_image(self.gen_images[0])self.previous_width = self.config.settings.lcm_diffusion_setting.image_widthself.previous_height = self.config.settings.lcm_diffusion_setting.image_height18 unmodified linesself.width.setCurrentText("512")self.height.setCurrentText("512")self.inference_steps.setValue(4)self.guidance.setValue(10)self.use_openvino_check.setChecked(False)self.seed_check.setChecked(False)self.safety_checker.setChecked(False)self.results_path.setText(FastStableDiffusionPaths().get_results_path())self.use_tae_sd.setChecked(False)self.use_lcm_lora.setChecked(False)
123456 unmodified lines1213141516171819208 unmodified lines29303132from constants import DEVICEimport platformdef is_reshape_required(6 unmodified linesprev_num_of_images: int,cur_num_of_images: int,) -> bool:print(f"width - {prev_width} {cur_width}")print(f"height - {prev_height} {cur_height}")print(f"model - {prev_model} {cur_model}")reshape_required = Falseif (prev_width != cur_width8 unmodified linesdef enable_openvino_controls() -> bool:return DEVICE == "cpu" and platform.system().lower() != "darwin"12345676 unmodified lines1415161718198 unmodified lines2829303132333435363738394041424344454647484950from constants import DEVICEfrom typing import Listimport platformfrom backend.device import is_openvino_devicedef is_reshape_required(6 unmodified linesprev_num_of_images: int,cur_num_of_images: int,) -> bool:reshape_required = Falseif (prev_width != cur_width8 unmodified linesdef enable_openvino_controls() -> bool:return is_openvino_device() and platform.system().lower() != "darwin"def get_valid_model_id(models: List,model_id: str,) -> str:if len(models) == 0:print("Error: model configuration file is empty,please add some models.")return ""if model_id == "":return models[0]if model_id in models:return model_idelse:print(f"Error:{model_id} Model not found in configuration file,so using first model : {models[0]}")return models[0]
9 unmodified lines101112131415161718192021222324252627282 unmodified lines313233343536373839404142434445465 unmodified lines5253545556575859606162636465662 unmodified lines69707172737475767778798081828384858687888990919293949596979825 unmodified lines12412512612712812913013113213310 unmodified lines1441451461471481491501511 unmodified line1531541551561571581591601611621631641651661671681691701711721731741751761771781791801811829 unmodified linesfrom app_settings import AppSettingsfrom constants import DEVICEfrom frontend.utils import enable_openvino_controlsfrom scipy.ndimage import zoomimport numpy as npfrom PIL import Imagefrom super_image import CarnModel, ImageLoaderfrom torchvision import transformstransform_image = transforms.ToPILImage()def tensor2img(tensor):tensor = tensor.squeeze(0).cpu().clamp(0, 1)return transform_image(tensor)random_enabled = True2 unmodified linesprevious_height = 0previous_model_id = ""previous_num_of_images = 0upscaler = CarnModel.from_pretrained("eugenesiow/carn-bam", scale=2)def generate_text_to_image(prompt,inference_steps,guidance_scale,seed,use_openvino,use_safety_checker,) -> Any:global previous_height, previous_width, previous_model_id, previous_num_of_imagesmodel_id = LCM_DEFAULT_MODEL5 unmodified lineslcm_diffusion_settings = LCMDiffusionSetting(lcm_model_id=model_id,prompt=prompt,image_height=384,image_width=384,inference_steps=inference_steps,guidance_scale=guidance_scale,number_of_images=1,seed=seed,use_openvino=use_openvino,use_safety_checker=use_safety_checker,use_seed=use_seed,)settings = Settings(lcm_diffusion_setting=lcm_diffusion_settings,2 unmodified linesif use_openvino:reshape = is_reshape_required(previous_width,384,previous_height,384,previous_model_id,model_id,previous_num_of_images,1,)images = context.generate_text_to_image(settings,reshape,DEVICE,)previous_width = 384previous_height = 384previous_model_id = model_idprevious_num_of_images = 1out_images = []# for image in images:# out_images.append(image.resize((768, 768), resample=Image.LANCZOS))# # in_image = ImageLoader.load_image(image)# # up_image = upscaler(in_image)# # out_images.append(tensor2img(up_image))# # out_images(image)return images25 unmodified lineselem_id="generate_button",scale=0,)with gr.Accordion("Advanced options", open=False):guidance_scale = gr.Slider(1.0, 30.0, value=8, step=0.5, label="Guidance Scale")seed = gr.Number(10 unmodified linesopenvino_checkbox = gr.Checkbox(label="Use OpenVINO",value=True,interactive=False,)safety_checker_checkbox = gr.Checkbox(1 unmodified linevalue=True,interactive=True,)num_inference_steps = gr.Slider(1, 8, value=4, step=1, label="Inference Steps")# image_height = gr.Slider(# 256, 768, value=384, step=64, label="Image Height",interactive=Fa# )# image_width = gr.Slider(# 256, 768, value=384, step=64, label="Image Width"# )# num_images = gr.Slider(# 1,# 50,# value=1,# step=1,# label="Number of images to generate",# )input_params = [prompt,num_inference_steps,guidance_scale,seed,openvino_checkbox,safety_checker_checkbox,]with gr.Column():9 unmodified lines1011121314152 unmodified lines181920212223242526272829303132333435365 unmodified lines424344454647484950515253545556572 unmodified lines606162636465666768697071727374757677787980818225 unmodified lines10810911011111211311411511611711811912012112212312412512612712812913013113210 unmodified lines1431441451461471481491501 unmodified line1521531541551561571581591601611621631641651661671681691701711721731749 unmodified linesfrom app_settings import AppSettingsfrom constants import DEVICEfrom frontend.utils import enable_openvino_controlsrandom_enabled = True2 unmodified linesprevious_height = 0previous_model_id = ""previous_num_of_images = 0def generate_text_to_image(prompt,image_height,image_width,inference_steps,guidance_scale,num_images,seed,use_openvino,use_safety_checker,tiny_auto_encoder_checkbox,) -> Any:global previous_height, previous_width, previous_model_id, previous_num_of_imagesmodel_id = LCM_DEFAULT_MODEL5 unmodified lineslcm_diffusion_settings = LCMDiffusionSetting(lcm_model_id=model_id,prompt=prompt,image_height=image_height,image_width=image_width,inference_steps=inference_steps,guidance_scale=guidance_scale,number_of_images=num_images,seed=seed,use_openvino=use_openvino,use_safety_checker=use_safety_checker,use_seed=use_seed,use_tiny_auto_encoder=tiny_auto_encoder_checkbox,)settings = Settings(lcm_diffusion_setting=lcm_diffusion_settings,2 unmodified linesif use_openvino:reshape = is_reshape_required(previous_width,image_width,previous_height,image_height,previous_model_id,model_id,previous_num_of_images,num_images,)images = context.generate_text_to_image(settings,reshape,DEVICE,)previous_width = image_widthprevious_height = image_heightprevious_model_id = model_idprevious_num_of_images = num_imagesreturn images25 unmodified lineselem_id="generate_button",scale=0,)num_inference_steps = gr.Slider(1, 25, value=4, step=1, label="Inference Steps")image_height = gr.Slider(256, 768, value=512, step=256, label="Image Height")image_width = gr.Slider(256, 768, value=512, step=256, label="Image Width")num_images = gr.Slider(1,50,value=1,step=1,label="Number of images to generate",)with gr.Accordion("Advanced options", open=False):guidance_scale = gr.Slider(1.0, 2.0, value=1.0, step=0.5, label="Guidance Scale")seed = gr.Number(10 unmodified linesopenvino_checkbox = gr.Checkbox(label="Use OpenVINO",value=False,interactive=enable_openvino_controls(),)safety_checker_checkbox = gr.Checkbox(1 unmodified linevalue=True,interactive=True,)tiny_auto_encoder_checkbox = gr.Checkbox(label="Use tiny auto encoder for SD",value=False,interactive=True,)input_params = [prompt,image_height,image_width,num_inference_steps,guidance_scale,num_images,seed,openvino_checkbox,safety_checker_checkbox,tiny_auto_encoder_checkbox,]with gr.Column():
5 unmodified lines67891011126 unmodified lines192021222324255 unmodified linesdef _get_footer_message() -> str:version = f"<center><p> v{APP_VERSION} "footer_msg = version + (' © 2023 <a href="https://github.com/rupeshs">'" Rupesh Sreeraman</a></p></center>"6 unmodified linescss=FastStableDiffusionPaths.get_css_path(),title="FastSD CPU",) as fastsd_web_ui:gr.HTML("<center><H1>FastSD CPU demo (OpenVINO)</H1></center>")with gr.Tabs():with gr.TabItem("Text to Image"):get_text_to_image_ui(app_settings)5 unmodified lines67891011126 unmodified lines192021222324255 unmodified linesdef _get_footer_message() -> str:version = f"<center><p> {APP_VERSION} "footer_msg = version + (' © 2023 <a href="https://github.com/rupeshs">'" Rupesh Sreeraman</a></p></center>"6 unmodified linescss=FastStableDiffusionPaths.get_css_path(),title="FastSD CPU",) as fastsd_web_ui:gr.HTML("<center><H1>FastSD CPU</H1></center>")with gr.Tabs():with gr.TabItem("Text to Image"):get_text_to_image_ui(app_settings)
12345678from pydantic import BaseModelfrom backend.models.lcmdiffusion_setting import LCMDiffusionSettingfrom paths import FastStableDiffusionPathsclass Settings(BaseModel):results_path: str = FastStableDiffusionPaths().get_results_path()lcm_diffusion_setting: LCMDiffusionSetting = LCMDiffusionSetting()12345678from pydantic import BaseModelfrom backend.models.lcmdiffusion_setting import LCMDiffusionSetting, LCMLorafrom paths import FastStableDiffusionPathsclass Settings(BaseModel):results_path: str = FastStableDiffusionPaths().get_results_path()lcm_diffusion_setting: LCMDiffusionSetting = LCMDiffusionSetting(lcm_lora=LCMLora())
8 unmodified lines910111213141520 unmodified lines363738394041423 unmodified lines4647488 unmodified linesreturn os.path.join(first_path, second_path)def get_app_path():app_dir = os.path.dirname(__file__)work_dir = os.path.dirname(app_dir)return work_dir20 unmodified linesreturn results_path@staticmethoddef get_css_path():app_dir = os.path.dirname(__file__)css_path = os.path.join(app_dir,3 unmodified lines"style.css",)return css_path8 unmodified lines910111213141520 unmodified lines363738394041423 unmodified lines4647484950515253545556578 unmodified linesreturn os.path.join(first_path, second_path)def get_app_path() -> str:app_dir = os.path.dirname(__file__)work_dir = os.path.dirname(app_dir)return work_dir20 unmodified linesreturn results_path@staticmethoddef get_css_path() -> str:app_dir = os.path.dirname(__file__)css_path = os.path.join(app_dir,3 unmodified lines"style.css",)return css_path@staticmethoddef get_models_config_path(model_config_file: str) -> str:configs_path = get_configs_path()models_path = join_paths(configs_path,model_config_file,)return models_path
12343 unmodified lines8910import platformdef show_system_info():3 unmodified linesprint(f"Processor: {platform.processor()}")except Exception as ex:print(f"Error ocurred while getting system information {ex}")123453 unmodified lines9101112131415161718192021import platformfrom typing import Listdef show_system_info():3 unmodified linesprint(f"Processor: {platform.processor()}")except Exception as ex:print(f"Error ocurred while getting system information {ex}")def get_models_from_text_file(file_path: str) -> List:models = []with open(file_path, "r") as file:lines = file.readlines()for repo_id in lines:if repo_id.strip() != "":models.append(repo_id.strip())return models
app.py+109-9
app_settings.py+23
backend/__pycache__/__init__.cpython-311.pyc
backend/__pycache__/image_saver.cpython-311.pyc
backend/__pycache__/lcm_text_to_image.cpython-311.pyc
backend/lcm_text_to_image.py+256-44
backend/lcmdiffusion/pipelines/openvino/__pycache__/lcm_ov_pipeline.cpython-311.pyc
backend/lcmdiffusion/pipelines/openvino/__pycache__/lcm_scheduler.cpython-311.pyc
backend/lcmdiffusion/pipelines/openvino/lcm_ov_pipeline.py+86-29
backend/lcmdiffusion/pipelines/openvino/lcm_scheduler.py+67-20
backend/models/__pycache__/lcmdiffusion_setting.cpython-311.pyc
backend/models/lcmdiffusion_setting.py+15-5
constants.py+8-2
context.py+13-8
frontend/__pycache__/utils.cpython-311.pyc
frontend/gui/__pycache__/app_window.cpython-311.pyc
frontend/gui/__pycache__/image_generator_worker.cpython-311.pyc
frontend/gui/__pycache__/ui.cpython-311.pyc
frontend/gui/app_window.py+177-22
frontend/utils.py+22-4
frontend/webui/text_to_image_ui.py+41-49
frontend/webui/ui.py+2-2
models/__pycache__/interface_types.cpython-311.pyc
models/__pycache__/settings.cpython-311.pyc
models/settings.py+2-2
paths.py+11-2
utils.py+11