# Changed from https://huggingface.co/spaces/playgroundai/playground-v2.5/blob/main/app.py import argparse import os import random import time from datetime import datetime import GPUtil import spaces import torch from peft.tuners import lora from utils import get_pipeline from vars import DEFAULT_HEIGHT, DEFAULT_WIDTH, EXAMPLES, MAX_SEED, PROMPT_TEMPLATES, SVDQ_LORA_PATHS from nunchaku.models.safety_checker import SafetyChecker # import gradio last to avoid conflicts with other imports import gradio as gr # noqa: isort: skip def get_args() -> argparse.Namespace: parser = argparse.ArgumentParser() parser.add_argument( "-m", "--model", type=str, default="schnell", choices=["schnell", "dev"], help="Which FLUX.1 model to use" ) parser.add_argument( "-p", "--precisions", type=str, default=["int4"], nargs="*", choices=["int4", "fp4", "bf16"], help="Which precisions to use", ) parser.add_argument("--use-qencoder", action="store_true", help="Whether to use 4-bit text encoder") parser.add_argument("--no-safety-checker", action="store_true", help="Disable safety checker") parser.add_argument("--count-use", action="store_true", help="Whether to count the number of uses") parser.add_argument("--gradio-root-path", type=str, default="") return parser.parse_args() args = get_args() pipeline_init_kwargs = {} pipelines = [] for i, precision in enumerate(args.precisions): pipeline = get_pipeline( model_name=args.model, precision=precision, use_qencoder=args.use_qencoder, device="cuda", lora_name="All", pipeline_init_kwargs={**pipeline_init_kwargs}, ) pipeline.cur_lora_name = "None" pipeline.cur_lora_weight = 0 pipelines.append(pipeline) if i == 0: pipeline_init_kwargs["vae"] = pipeline.vae pipeline_init_kwargs["text_encoder"] = pipeline.text_encoder pipeline_init_kwargs["text_encoder_2"] = pipeline.text_encoder_2 safety_checker = SafetyChecker("cuda", disabled=args.no_safety_checker) @spaces.GPU(enable_queue=True) def generate( prompt: str = None, height: int = 1024, width: int = 1024, num_inference_steps: int = 4, guidance_scale: float = 0, lora_name: str = "None", lora_weight: float = 1, seed: int = 0, ): print(f"Generating image with prompt: {prompt}") is_unsafe_prompt = False if not safety_checker(prompt): is_unsafe_prompt = True prompt = "A peaceful world." prompt = PROMPT_TEMPLATES[lora_name].format(prompt=prompt) images, latency_strs = [], [] for i, pipeline in enumerate(pipelines): precision = args.precisions[i] gr.Progress(track_tqdm=True) if pipeline.cur_lora_name != lora_name: if precision == "bf16": for m in pipeline.transformer.modules(): if isinstance(m, lora.LoraLayer): if pipeline.cur_lora_name != "None": if pipeline.cur_lora_name in m.scaling: m.scaling[pipeline.cur_lora_name] = 0 if lora_name != "None": if lora_name in m.scaling: m.scaling[lora_name] = lora_weight else: assert precision == "int4" if lora_name != "None": pipeline.transformer.update_lora_params(SVDQ_LORA_PATHS[lora_name]) pipeline.transformer.set_lora_strength(lora_weight) else: pipeline.transformer.set_lora_strength(0) elif lora_name != "None": if precision == "bf16": if pipeline.cur_lora_weight != lora_weight: for m in pipeline.transformer.modules(): if isinstance(m, lora.LoraLayer): if lora_name in m.scaling: m.scaling[lora_name] = lora_weight else: assert precision == "int4" pipeline.transformer.set_lora_strength(lora_weight) pipeline.cur_lora_name = lora_name pipeline.cur_lora_weight = lora_weight start_time = time.time() image = pipeline( prompt=prompt, height=height, width=width, num_inference_steps=num_inference_steps, guidance_scale=guidance_scale, generator=torch.Generator().manual_seed(seed), ).images[0] end_time = time.time() latency = end_time - start_time if latency < 1: latency = latency * 1000 latency_str = f"{latency:.2f}ms" else: latency_str = f"{latency:.2f}s" images.append(image) latency_strs.append(latency_str) if is_unsafe_prompt: for i in range(len(latency_strs)): latency_strs[i] += " (Unsafe prompt detected)" torch.cuda.empty_cache() if args.count_use: if os.path.exists(f"{args.model}-use_count.txt"): with open(f"{args.model}-use_count.txt", "r") as f: count = int(f.read()) else: count = 0 count += 1 current_time = datetime.now() print(f"{current_time}: {count}") with open(f"{args.model}-use_count.txt", "w") as f: f.write(str(count)) with open(f"{args.model}-use_record.txt", "a") as f: f.write(f"{current_time}: {count}\n") return *images, *latency_strs with open("./assets/description.html", "r") as f: DESCRIPTION = f.read() gpus = GPUtil.getGPUs() if len(gpus) > 0: gpu = gpus[0] memory = gpu.memoryTotal / 1024 device_info = f"Running on {gpu.name} with {memory:.0f} GiB memory." else: device_info = "Running on CPU 🥶 This demo does not work on CPU." notice = 'Notice: We will replace unsafe prompts with a default prompt: "A peaceful world."' with gr.Blocks( css_paths=[f"assets/frame{len(args.precisions)}.css", "assets/common.css"], title=f"SVDQuant FLUX.1-{args.model} Demo", ) as demo: def get_header_str(): if args.count_use: if os.path.exists(f"{args.model}-use_count.txt"): with open(f"{args.model}-use_count.txt", "r") as f: count = int(f.read()) else: count = 0 count_info = ( f"