Spaces:
Runtime error
Runtime error
Update custom_pipeline.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151import torchimport numpy as npfrom diffusers import FluxPipeline, FlowMatchEulerDiscreteSchedulerfrom typing import Any, Dict, List, Optional, Unionfrom PIL import Image# Constants for shift calculationBASE_SEQ_LEN = 256MAX_SEQ_LEN = 4096BASE_SHIFT = 0.5MAX_SHIFT = 1.2# Helper functionsdef calculate_timestep_shift(image_seq_len: int) -> float:"""Calculates the timestep shift (mu) based on the image sequence length."""m = (MAX_SHIFT - BASE_SHIFT) / (MAX_SEQ_LEN - BASE_SEQ_LEN)b = BASE_SHIFT - m * BASE_SEQ_LENmu = image_seq_len * m + breturn mudef prepare_timesteps(scheduler: FlowMatchEulerDiscreteScheduler,num_inference_steps: Optional[int] = None,device: Optional[Union[str, torch.device]] = None,timesteps: Optional[List[int]] = None,sigmas: Optional[List[float]] = None,mu: Optional[float] = None,) -> (torch.Tensor, int):"""Prepares the timesteps for the diffusion process."""if timesteps is not None and sigmas is not None:raise ValueError("Only one of `timesteps` or `sigmas` can be passed.")if timesteps is not None:scheduler.set_timesteps(timesteps=timesteps, device=device)elif sigmas is not None:scheduler.set_timesteps(sigmas=sigmas, device=device)else:scheduler.set_timesteps(num_inference_steps, device=device, mu=mu)timesteps = scheduler.timestepsnum_inference_steps = len(timesteps)return timesteps, num_inference_steps# FLUX pipeline functionclass HighSpeedFluxPipeline(FluxPipeline):"""Extends the FluxPipeline to yield intermediate images during the denoising processwith progressively increasing resolution for faster generation."""@torch.inference_mode()def generate_images(self,prompt: Union[str, List[str]] = None,prompt_2: Optional[Union[str, List[str]]] = None,height: Optional[int] = None,width: Optional[int] = None,num_inference_steps: int = 4,timesteps: List[int] = None,num_images_per_prompt: Optional[int] = 1,generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,latents: Optional[torch.FloatTensor] = None,prompt_embeds: Optional[torch.FloatTensor] = None,pooled_prompt_embeds: Optional[torch.FloatTensor] = None,output_type: Optional[str] = "pil",return_dict: bool = True,max_sequence_length: int = 128,):"""Generates images and yields intermediate results during the denoising process."""height = height or self.default_sample_size * self.vae_scale_factorwidth = width or self.default_sample_size * self.vae_scale_factor# 1. Check inputsself.check_inputs(prompt,prompt_2,height,width,prompt_embeds=prompt_embeds,pooled_prompt_embeds=pooled_prompt_embeds,max_sequence_length=max_sequence_length,)# 2. Define call parametersbatch_size = 1 if isinstance(prompt, str) else len(prompt)device = self._execution_deviceprompt_embeds, pooled_prompt_embeds, text_ids = self.encode_prompt(prompt=prompt,prompt_2=prompt_2,prompt_embeds=prompt_embeds,pooled_prompt_embeds=pooled_prompt_embeds,device=device,num_images_per_prompt=num_images_per_prompt,max_sequence_length=max_sequence_length,)# 4. Prepare latent variablesnum_channels_latents = self.transformer.config.in_channels // 4latents, latent_image_ids = self.prepare_latents(batch_size * num_images_per_prompt,num_channels_latents,height,width,prompt_embeds.dtype,device,generator,latents,)# 5. Prepare timestepssigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps)image_seq_len = latents.shape[1]mu = calculate_timestep_shift(image_seq_len)timesteps, num_inference_steps = prepare_timesteps(self.scheduler,num_inference_steps,device,timesteps,sigmas,mu=mu,)self._num_timesteps = len(timesteps)# 6. Denoising loopfor i, t in enumerate(timesteps):timestep = t.expand(latents.shape[0]).to(latents.dtype)noise_pred = self.transformer(hidden_states=latents,timestep=timestep / 1000,pooled_projections=pooled_prompt_embeds,encoder_hidden_states=prompt_embeds,txt_ids=text_ids,img_ids=latent_image_ids,return_dict=False,)[0]latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]torch.cuda.empty_cache()# Final imagereturn self._decode_latents_to_image(latents, height, width, output_type)self.maybe_free_model_hooks()torch.cuda.empty_cache()def _decode_latents_to_image(self, latents, height, width, output_type, vae=None):"""Decodes the given latents into an image."""vae = vae or self.vaelatents = self._unpack_latents(latents, height, width, self.vae_scale_factor)latents = (latents / vae.config.scaling_factor) + vae.config.shift_factorimage = vae.decode(latents, return_dict=False)[0]return self.image_processor.postprocess(image, output_type=output_type)[0]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165import gradio as grimport numpy as npimport randomimport spacesimport torchimport timefrom diffusers import DiffusionPipelinefrom custom_pipeline import FLUXPipelineWithIntermediateOutputs# ConstantsMAX_SEED = np.iinfo(np.int32).maxMAX_IMAGE_SIZE = 2048DEFAULT_WIDTH = 1024DEFAULT_HEIGHT = 1024DEFAULT_INFERENCE_STEPS = 1# Device and model setupdtype = torch.float16pipe = FLUXPipelineWithIntermediateOutputs.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=dtype).to("cuda")torch.cuda.empty_cache()# Inference function@spaces.GPU(duration=25)def generate_image(prompt, seed=42, width=DEFAULT_WIDTH, height=DEFAULT_HEIGHT, randomize_seed=False, num_inference_steps=2, progress=gr.Progress(track_tqdm=True)):if randomize_seed:seed = random.randint(0, MAX_SEED)generator = torch.Generator().manual_seed(int(float(seed)))start_time = time.time()# Only generate the last image in the sequencefor img in pipe.generate_images(prompt=prompt,guidance_scale=0, # as Flux schnell is guidance freenum_inference_steps=num_inference_steps,width=width,height=height,generator=generator):latency = f"Latency: {(time.time()-start_time):.2f} seconds"yield img, seed, latency# Example promptsexamples = ["a tiny astronaut hatching from an egg on the moon","a cute white cat holding a sign that says hello world","an anime illustration of a wiener schnitzel","Create mage of Modern house in minecraft style","Imagine steve jobs as Star Wars movie character","Lion","Photo of a young woman with long, wavy brown hair tied in a bun and glasses. She has a fair complexion and is wearing subtle makeup, emphasizing her eyes and lips. She is dressed in a black top. The background appears to be an urban setting with a building facade, and the sunlight casts a warm glow on her face.",]# --- Gradio UI ---with gr.Blocks() as demo:with gr.Column(elem_id="app-container"):gr.Markdown("# 🎨 Realtime FLUX Image Generator")gr.Markdown("Generate stunning images in real-time with Modified Flux.Schnell pipeline.")gr.Markdown("<span style='color: red;'>Note: Sometimes it stucks or stops generating images (I don't know why). In that situation just refresh the site.</span>")with gr.Row():with gr.Column(scale=3):result = gr.Image(label="Generated Image", show_label=False, interactive=False)with gr.Column(scale=1):prompt = gr.Text(label="Prompt",placeholder="Describe the image you want to generate...",lines=3,show_label=False,container=False,)generateBtn = gr.Button("🖼️ Generate Image")enhanceBtn = gr.Button("🚀 Enhance Image")with gr.Column("Advanced Options"):with gr.Row():realtime = gr.Checkbox(label="Realtime Toggler", info="If TRUE then uses more GPU but create image in realtime.", value=False)latency = gr.Text(label="Latency")with gr.Row():seed = gr.Number(label="Seed", value=42)randomize_seed = gr.Checkbox(label="Randomize Seed", value=False)with gr.Row():width = gr.Slider(label="Width", minimum=256, maximum=MAX_IMAGE_SIZE, step=32, value=DEFAULT_WIDTH)height = gr.Slider(label="Height", minimum=256, maximum=MAX_IMAGE_SIZE, step=32, value=DEFAULT_HEIGHT)num_inference_steps = gr.Slider(label="Inference Steps", minimum=1, maximum=4, step=1, value=DEFAULT_INFERENCE_STEPS)with gr.Row():gr.Markdown("### 🌟 Inspiration Gallery")with gr.Row():gr.Examples(examples=examples,fn=generate_image,inputs=[prompt],outputs=[result, seed, latency],cache_examples="lazy")def enhance_image(*args):gr.Info("Enhancing Image") # currently just runs optimized pipeline for 2 steps. Further implementations later.return next(generate_image(*args))enhanceBtn.click(fn=enhance_image,inputs=[prompt, seed, width, height],outputs=[result, seed, latency],show_progress="hidden",api_name=False,queue=False,concurrency_limit=None)generateBtn.click(fn=generate_image,inputs=[prompt, seed, width, height, randomize_seed, num_inference_steps],outputs=[result, seed, latency],show_progress="full",api_name="RealtimeFlux",queue=False,concurrency_limit=None)def update_ui(realtime_enabled):return {prompt: gr.update(interactive=True),generateBtn: gr.update(visible=not realtime_enabled)}realtime.change(fn=update_ui,inputs=[realtime],outputs=[prompt, generateBtn],queue=False,concurrency_limit=None)def realtime_generation(*args):if args[0]: # If realtime is enabledreturn next(generate_image(*args[1:]))prompt.submit(fn=generate_image,inputs=[prompt, seed, width, height, randomize_seed, num_inference_steps],outputs=[result, seed, latency],show_progress="full",api_name=False,queue=False,concurrency_limit=None)for component in [prompt, width, height, num_inference_steps]:component.input(fn=realtime_generation,inputs=[realtime, prompt, seed, width, height, randomize_seed, num_inference_steps],outputs=[result, seed, latency],show_progress="hidden",api_name=False,trigger_mode="always_last",queue=False,concurrency_limit=None)# Launch the appdemo.launch()
custom_pipeline.py+160-146