Spaces:
Runtime error
Runtime error
Update app.py
Browse files23 unmodified lines2425262728293031323334353637383940414243444546474849505152531 unmodified line5556575859606162636465666768697071727374757677787912 unmodified lines92939495969798991001011021031041051061 unmodified line1081091101111121131141152 unmodified lines1181191201211221231248 unmodified lines1331341351361371381395 unmodified lines14514614714814915015123 unmodified linesprompt_values = df.values.flatten()HF_TOKEN = os.getenv("HF_TOKEN")# --- Model Initialization ---# MODIFICATION : On ne détecte plus le device ici, on charge sur CPU par défaut.# La détection se fera à l'intérieur des fonctions GPU.print("Preparing model configurations...")dtype = torch.bfloat16base_model = "black-forest-labs/FLUX.1-dev"# 1. Load Image Generation Models (sur le CPU !)print("Loading image generation model components to CPU...")# MODIFICATION : Suppression du `.to(device)` icitaef1 = AutoencoderTiny.from_pretrained("madebyollin/taef1", torch_dtype=dtype)good_vae = AutoencoderKL.from_pretrained(base_model, subfolder="vae", torch_dtype=dtype, token=HF_TOKEN)pipe = DiffusionPipeline.from_pretrained(base_model, torch_dtype=dtype, vae=taef1, token=HF_TOKEN)print("Image models loaded.")print(f"Loading on-board LoRA: {KRYPTO_LORA['repo']}")pipe.load_lora_weights(KRYPTO_LORA['repo'], low_cpu_mem_usage=True, adapter_name=KRYPTO_LORA['adapter_name'])print("LoRA loaded successfully.")# 2. Load LLM for Prompt Enhancement (sur le CPU !)print(f"Loading prompt enhancement LLM: {LLM_MODEL_ID} to CPU...")# MODIFICATION : Suppression de `device_map=device` pour charger sur CPUllm_processor = AutoProcessor.from_pretrained(LLM_MODEL_ID, token=HF_TOKEN)llm_model = AutoModelForImageTextToText.from_pretrained(LLM_MODEL_ID, torch_dtype=dtype, token=HF_TOKEN)print("LLM loaded successfully.")1 unmodified linepipe.flux_pipe_call_that_returns_an_iterable_of_images = flux_pipe_call_that_returns_an_iterable_of_images.__get__(pipe)# Cette fonction sera maintenant décorée par @spaces.GPU car elle a besoin du LLM sur GPU@spaces.GPU(duration=30)@torch.inference_mode()def enhance_prompt(user_prompt: str) -> str:device = "cuda" if torch.cuda.is_available() else "cpu"print(f"Enhancing prompt on device: {device}")# MODIFICATION : On déplace le LLM sur le GPU à l'intérieur de la fonctionllm_model.to(device)messages = [{"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": user_prompt}]inputs = llm_processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=True, return_tensors="pt").to(device)outputs = llm_model.generate(**inputs, max_new_tokens=150)enhanced_prompt = llm_processor.batch_decode(outputs, skip_special_tokens=True)[0]final_prompt = enhanced_prompt.split("assistant\n")[-1].strip()# MODIFICATION : On remet le LLM sur le CPU pour libérer la mémoire GPUllm_model.to("cpu")return final_prompt12 unmodified linesdef generate_image(prompt_mash, steps, seed, cfg_scale, width, height, progress):device = "cuda" if torch.cuda.is_available() else "cpu"# MODIFICATION : On déplace le pipeline sur le GPU icipipe.to(device)generator = torch.Generator(device=device).manual_seed(seed)image_generator = pipe.flux_pipe_call_that_returns_an_iterable_of_images(prompt=prompt_mash, num_inference_steps=steps, guidance_scale=cfg_scale,width=width, height=height, generator=generator, joint_attention_kwargs={"scale": 1.0},output_type="pil", good_vae=good_vae.to(device) # On déplace aussi le bon VAE)final_image = Nonefor i, image in enumerate(image_generator):1 unmodified lineprogress_bar = f'<div class="progress-container"><div class="progress-bar" style="--current: {i + 1}; --total: {steps};"></div></div>'yield image, gr.update(value=progress_bar, visible=True)# MODIFICATION : On remet le pipeline sur le CPUpipe.to("cpu")yield final_image, gr.update(visible=False)def update_history(new_image, history):2 unmodified lineshistory.insert(0, new_image)return history# Cette fonction reste la fonction principale qui demande l'allocation GPU@spaces.GPU(duration=120)def run_generation(prompt, lora_scale, cfg_scale, steps, randomize_seed, seed, aspect_ratio, base_resolution, progress=gr.Progress(track_tqdm=True)):if not prompt: raise gr.Error("Prompt cannot be empty.")8 unmodified linesprint("Final prompt for diffusion model:", prompt_mash)pipe.set_adapters([KRYPTO_LORA['adapter_name']], adapter_weights=[lora_scale])print(f"Adapter '{KRYPTO_LORA['adapter_name']}' activated with weight {lora_scale}.")if randomize_seed: seed = random.randint(0, MAX_SEED)5 unmodified linesrun_generation.zerogpu = True# --- UI (inchangée) ---css = ''' #title{text-align: center} #title h1{font-size: 3em; display:inline-flex; align-items:center} #title img{width: 80px; margin-right: 0.25em} .progress-container {width: 100%;height: 30px;background-color: #f0f0f0;border-radius: 15px;overflow: hidden;margin-bottom: 20px} .progress-bar {height: 100%;background-color: #4f46e5;width: calc(var(--current) / var(--total) * 100%);transition: width 0.1s ease-in-out} #random_prompt_btn{max-width: 2.5em; min-width: 2.5em !important; height: 100% !important;} '''with gr.Blocks(css=css, theme=gr.themes.Soft()) as app:gr.HTML("""<div id='title'><h1><img src="https://huggingface.co/Econogoat/KRYPTO_LORA/resolve/main/krypt0.png" alt="LoRA"> Krypt0 Image Generator</h1><br><span>Generate images with the Krypt0 artistic style</span></div>""")23 unmodified lines2425262728293031323334353637383940414243444546474849501 unmodified line5253545556575859606162636465666768697071727374757677787980818212 unmodified lines95969798991001011021031041051061071081091101111121 unmodified line1141151161171181191201211222 unmodified lines1251261271281291308 unmodified lines1391401411421431445 unmodified lines15015115215315415515623 unmodified linesprompt_values = df.values.flatten()HF_TOKEN = os.getenv("HF_TOKEN")# --- Model Initialization (Strictly CPU and float32 for ZeroGPU compatibility) ---print("Preparing model configurations...")base_model = "black-forest-labs/FLUX.1-dev"# 1. Load Image Generation Models (on CPU, default float32)print("Loading image generation model components to CPU...")# CORRECTION : Suppression de torch_dtype=dtype pour éviter l'initialisation CUDA au démarragetaef1 = AutoencoderTiny.from_pretrained("madebyollin/taef1")good_vae = AutoencoderKL.from_pretrained(base_model, subfolder="vae", token=HF_TOKEN)pipe = DiffusionPipeline.from_pretrained(base_model, vae=taef1, token=HF_TOKEN)print("Image models loaded.")print(f"Loading on-board LoRA: {KRYPTO_LORA['repo']}")pipe.load_lora_weights(KRYPTO_LORA['repo'], low_cpu_mem_usage=True, adapter_name=KRYPTO_LORA['adapter_name'])print("LoRA loaded successfully.")# 2. Load LLM for Prompt Enhancement (on CPU, default float32)print(f"Loading prompt enhancement LLM: {LLM_MODEL_ID} to CPU...")# CORRECTION : Suppression de torch_dtype=dtypellm_processor = AutoProcessor.from_pretrained(LLM_MODEL_ID, token=HF_TOKEN)llm_model = AutoModelForImageTextToText.from_pretrained(LLM_MODEL_ID, token=HF_TOKEN)print("LLM loaded successfully.")1 unmodified linepipe.flux_pipe_call_that_returns_an_iterable_of_images = flux_pipe_call_that_returns_an_iterable_of_images.__get__(pipe)@spaces.GPU(duration=30)@torch.inference_mode()def enhance_prompt(user_prompt: str) -> str:device = "cuda" if torch.cuda.is_available() else "cpu"dtype = torch.bfloat16 # Utilisation de bfloat16 seulement ici, sur le GPUprint(f"Enhancing prompt on device: {device}")# Déplacer et convertir le LLM sur le GPUllm_model.to(device, dtype=dtype)messages = [{"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": user_prompt}]inputs = llm_processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=True, return_tensors="pt").to(device)# S'assurer que les inputs sont aussi dans le bon dtypeif 'pixel_values' in inputs:inputs['pixel_values'] = inputs['pixel_values'].to(dtype)outputs = llm_model.generate(**inputs, max_new_tokens=150)enhanced_prompt = llm_processor.batch_decode(outputs, skip_special_tokens=True)[0]final_prompt = enhanced_prompt.split("assistant\n")[-1].strip()# Remettre le LLM sur le CPU (il revient en float32)llm_model.to("cpu")return final_prompt12 unmodified linesdef generate_image(prompt_mash, steps, seed, cfg_scale, width, height, progress):device = "cuda" if torch.cuda.is_available() else "cpu"dtype = torch.bfloat16 # Utilisation de bfloat16 seulement ici, sur le GPU# Déplacer et convertir le pipeline sur le GPUpipe.to(device, dtype=dtype)good_vae.to(device, dtype=dtype)generator = torch.Generator(device=device).manual_seed(seed)image_generator = pipe.flux_pipe_call_that_returns_an_iterable_of_images(prompt=prompt_mash, num_inference_steps=steps, guidance_scale=cfg_scale,width=width, height=height, generator=generator, joint_attention_kwargs={"scale": 1.0},output_type="pil", good_vae=good_vae)final_image = Nonefor i, image in enumerate(image_generator):1 unmodified lineprogress_bar = f'<div class="progress-container"><div class="progress-bar" style="--current: {i + 1}; --total: {steps};"></div></div>'yield image, gr.update(value=progress_bar, visible=True)# Remettre le pipeline sur le CPUpipe.to("cpu")good_vae.to("cpu")yield final_image, gr.update(visible=False)def update_history(new_image, history):2 unmodified lineshistory.insert(0, new_image)return history@spaces.GPU(duration=120)def run_generation(prompt, lora_scale, cfg_scale, steps, randomize_seed, seed, aspect_ratio, base_resolution, progress=gr.Progress(track_tqdm=True)):if not prompt: raise gr.Error("Prompt cannot be empty.")8 unmodified linesprint("Final prompt for diffusion model:", prompt_mash)pipe.set_adapters([KRYPTO_LORA['adapter_name']], adapter_weights=[lora_scale])if randomize_seed: seed = random.randint(0, MAX_SEED)5 unmodified linesrun_generation.zerogpu = True# --- UI ---css = ''' #title{text-align: center} #title h1{font-size: 3em; display:inline-flex; align-items:center} #title img{width: 80px; margin-right: 0.25em} .progress-container {width: 100%;height: 30px;background-color: #f0f0f0;border-radius: 15px;overflow: hidden;margin-bottom: 20px} .progress-bar {height: 100%;background-color: #4f46e5;width: calc(var(--current) / var(--total) * 100%);transition: width 0.1s ease-in-out} #random_prompt_btn{max-width: 2.5em; min-width: 2.5em !important; height: 100% !important;} '''with gr.Blocks(css=css, theme=gr.themes.Soft()) as app:gr.HTML("""<div id='title'><h1><img src="https://huggingface.co/Econogoat/KRYPTO_LORA/resolve/main/krypt0.png" alt="LoRA"> Krypt0 Image Generator</h1><br><span>Generate images with the Krypt0 artistic style</span></div>""")
app.py+28-23