feat: Add H200 batch processing support (batch_size=4, torch.compile)
Browse files8 unmodified lines9101112131415161718192021222324252617 unmodified lines444546474849129 unmodified lines17918018118218318418518618718818919019119219319419519619719819990 unmodified lines290291292293294295165 unmodified lines46146246346446546639 unmodified lines506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561119 unmodified lines6816826836846856868 unmodified lines2. Full PuLID integration for character consistency across images3. Face embedding caching for efficient batch processing4. Dual mode: normal generation and ID-consistent generationGPU Requirements:- A100 80GB: Recommended (full quality)- L40S 48GB: With offload modeAPI Modes:- generate: Normal image generation (no PuLID)- register: Register character face -> extract embedding -> cache- generate_with_ids: Generate with cached character embeddings- check_cache: Check which character IDs are cached- clear_cache: Clear character embedding cacheReferences:- PuLID: https://github.com/ToTheBeginning/PuLID- FLUX.1-dev: https://huggingface.co/black-forest-labs/FLUX.1-dev17 unmodified linesENABLE_OFFLOAD = os.environ.get("ENABLE_OFFLOAD", "auto").lower()NUM_INFERENCE_STEPS = int(os.environ.get("NUM_INFERENCE_STEPS", "28"))PULID_VERSION = os.environ.get("PULID_VERSION", "v0.9.1")def setup_pulid():129 unmodified linesprint(f"[FLUX-Dev] ENABLE_OFFLOAD: {ENABLE_OFFLOAD}")# Determine offload mode based on GPU memory# A100 80GB (reports ~85GB) needs offload - models consume ~77GB leaving no room for inference# Use < 90 threshold to safely catch A100-SXM4-80GB which reports 85.1 GB# IMPORTANT: aggressive_offload must also be enabled for A100 80GB to prevent# full model loading via model.to(device) which causes OOMif ENABLE_OFFLOAD == "auto":self.use_offload = self.gpu_memory_gb < 90 # Enable for A100 80GB (reports 85.1GB)self.use_aggressive_offload = self.gpu_memory_gb < 90 # Also enable for A100 80GBelif ENABLE_OFFLOAD == "true":self.use_offload = Trueself.use_aggressive_offload = self.gpu_memory_gb < 90 # Enable for A100 80GBelse:self.use_offload = Falseself.use_aggressive_offload = Falseprint(f"[FLUX-Dev] Offload: {self.use_offload}, Aggressive: {self.use_aggressive_offload}")# Setup PuLID if enabledif ENABLE_PULID:90 unmodified linesreserved = torch.cuda.memory_reserved() / 1e9print(f"[FLUX-Dev] Post-init memory: allocated={allocated:.2f}GB, reserved={reserved:.2f}GB")def _setup_diffusers_pipeline(self):"""Fallback: Setup diffusers FluxPipeline without PuLID."""print("[FLUX-Dev] Setting up diffusers pipeline (no PuLID)...")165 unmodified linesSupports both single prompt (string) and batch prompts (list of strings).Returns single result dict for single prompt, or list of result dicts for batch."""if not self._pulid_loaded:return {"error": "PuLID not loaded", "success": False}39 unmodified linesseed = params.get("seed", -1)true_cfg = params.get("true_cfg", 1.0)print(f"[FLUX-Dev] Batch PuLID generation: {len(prompts)} image(s) with character '{char_data['name']}'")print(f"[FLUX-Dev] Settings: id_weight={id_weight}, start_step={start_step}, steps={num_steps}")# Offload all models before batch processing to ensure clean GPU stateif self.use_offload:self._offload_all_models()results = []for idx, prompt in enumerate(prompts):print(f"[FLUX-Dev] Generating image {idx + 1}/{len(prompts)}")try:# Generate using PuLID generatorimage = self._generate_with_embedding(prompt=prompt,id_embedding=id_embedding,uncond_embedding=uncond_embedding,width=width,height=height,num_steps=num_steps,guidance=guidance,id_weight=id_weight,start_step=start_step,seed=seed if seed == -1 else seed + idx, # Increment seed for varietytrue_cfg=true_cfg,)# Encode to base64buffered = BytesIO()image.save(buffered, format="PNG")b64_image = base64.b64encode(buffered.getvalue()).decode("utf-8")results.append({"success": True,"image": f"data:image/png;base64,{b64_image}","characters_used": [char_ids[0]],"character_name": char_data["name"],})# Clean up memory after each generation to prevent OOMself._cleanup_memory()except Exception as e:print(f"[FLUX-Dev] Generation error for prompt {idx + 1}: {e}")import tracebacktraceback.print_exc()results.append({"error": str(e), "success": False})# Force cleanup on errorself._cleanup_memory(force=True)# Final cleanup after batchself._cleanup_memory(force=True)# Return single result for single input, array for batch119 unmodified linesreturn imgdef _generate_normal(self, data: Dict) -> Union[Dict, List[Dict]]:"""Normal image generation without character consistency."""inputs = data.get("inputs", data)8 unmodified lines910111213141516171819202122232425262728293031323334353637383917 unmodified lines5758596061626364129 unmodified lines19419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422590 unmodified lines316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414165 unmodified lines58058158258358458558658758839 unmodified lines628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738119 unmodified lines85885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010218 unmodified lines2. Full PuLID integration for character consistency across images3. Face embedding caching for efficient batch processing4. Dual mode: normal generation and ID-consistent generation5. Batch processing support for high-VRAM GPUs (H200)GPU Requirements:- H200 141GB: Recommended (batch processing, no offload, highest throughput)- A100 80GB: With offload mode (single inference)- L40S 48GB: With aggressive offload modeBatch Processing (H200 only):- Batch size 4 by default (configurable via BATCH_SIZE env var)- ~3x throughput improvement over single inference- Same character ID applied to all images in batchAPI Modes:- generate: Normal image generation (no PuLID)- register: Register character face -> extract embedding -> cache- generate_with_ids: Generate with cached character embeddings (supports batch)- check_cache: Check which character IDs are cached- clear_cache: Clear character embedding cacheEnvironment Variables:- BATCH_SIZE: Max batch size for ID-consistent generation (default: 4)- ENABLE_OFFLOAD: "auto" (default), "true", or "false"- NUM_INFERENCE_STEPS: Default inference steps (default: 28)- ENABLE_TORCH_COMPILE: Enable torch.compile for transformer (default: "auto")References:- PuLID: https://github.com/ToTheBeginning/PuLID- FLUX.1-dev: https://huggingface.co/black-forest-labs/FLUX.1-dev17 unmodified linesENABLE_OFFLOAD = os.environ.get("ENABLE_OFFLOAD", "auto").lower()NUM_INFERENCE_STEPS = int(os.environ.get("NUM_INFERENCE_STEPS", "28"))PULID_VERSION = os.environ.get("PULID_VERSION", "v0.9.1")BATCH_SIZE = int(os.environ.get("BATCH_SIZE", "4"))ENABLE_TORCH_COMPILE = os.environ.get("ENABLE_TORCH_COMPILE", "auto").lower()def setup_pulid():129 unmodified linesprint(f"[FLUX-Dev] ENABLE_OFFLOAD: {ENABLE_OFFLOAD}")# Determine offload mode based on GPU memory# H200 141GB: No offload needed, full batch processing support# A100 80GB (reports ~85GB): Needs offload - models consume ~77GB leaving no room for inference# L40S 48GB: Needs aggressive offload# Thresholds:# - >= 120GB (H200): No offload, batch processing enabled# - >= 60GB, < 120GB (A100): Offload enabled, single inference# - < 60GB (L40S): Aggressive offload enabledif ENABLE_OFFLOAD == "auto":self.use_offload = self.gpu_memory_gb < 120 # Disable for H200 (141GB)self.use_aggressive_offload = self.gpu_memory_gb < 60 # Enable for L40Selif ENABLE_OFFLOAD == "true":self.use_offload = Trueself.use_aggressive_offload = self.gpu_memory_gb < 60else:self.use_offload = Falseself.use_aggressive_offload = False# Determine max batch size based on GPU memory# H200 141GB: batch 4 (default), A100/L40S: batch 1 (offload mode)if self.use_offload:self.max_batch_size = 1 # Offload mode requires single inferenceelse:self.max_batch_size = BATCH_SIZE # Full GPU mode supports batchingprint(f"[FLUX-Dev] Offload: {self.use_offload}, Aggressive: {self.use_aggressive_offload}")print(f"[FLUX-Dev] Max batch size: {self.max_batch_size}")# Setup PuLID if enabledif ENABLE_PULID:90 unmodified linesreserved = torch.cuda.memory_reserved() / 1e9print(f"[FLUX-Dev] Post-init memory: allocated={allocated:.2f}GB, reserved={reserved:.2f}GB")# Apply torch.compile for H200 (no offload mode)# torch.compile is incompatible with CPU offload due to model movementself._compiled = Falseif not self.use_offload:should_compile = (ENABLE_TORCH_COMPILE == "true" or(ENABLE_TORCH_COMPILE == "auto" and self.gpu_memory_gb >= 120))if should_compile:self._apply_torch_compile()def _apply_torch_compile(self):"""Apply torch.compile optimization to the FLUX transformer.This provides ~1.3x speedup by using CUDA graphs for the denoising loop.Only applied when offload is disabled (H200 mode)."""print("[FLUX-Dev] Applying torch.compile to transformer...")compile_start = time.time()try:if hasattr(self._generator, 'model') and self._generator.model is not None:# Use reduce-overhead mode for best performance with CUDA graphsself._generator.model = torch.compile(self._generator.model,mode="reduce-overhead",fullgraph=False,)self._compiled = Trueprint(f"[FLUX-Dev] torch.compile applied in {time.time() - compile_start:.1f}s")# Run warmup to trigger compilationself._run_compile_warmup()else:print("[FLUX-Dev] No model found for torch.compile")except Exception as e:print(f"[FLUX-Dev] torch.compile failed: {e}")self._compiled = Falsedef _run_compile_warmup(self):"""Run warmup inference to trigger torch.compile and capture CUDA graphs."""print("[FLUX-Dev] Running warmup for torch.compile...")warmup_start = time.time()try:from flux.sampling import get_noise, get_schedule, prepare, denoisegen = self._generator# Create dummy inputs for warmup# Use smaller size for faster warmupwarmup_height, warmup_width = 768, 768x = get_noise(1,warmup_height,warmup_width,device=gen.device,dtype=torch.bfloat16,seed=42,)timesteps = get_schedule(4, # Minimal steps for warmupx.shape[-1] * x.shape[-2] // 4,shift=True,)# Prepare text embeddingsinp = prepare(t5=gen.t5, clip=gen.clip, img=x, prompt="warmup test")# Run denoising (this triggers compilation)with torch.inference_mode():_ = denoise(gen.model,**inp,timesteps=timesteps,guidance=4.0,id=None,id_weight=0.0,start_step=4,)# Clean updel x, inpgc.collect()torch.cuda.empty_cache()print(f"[FLUX-Dev] Warmup completed in {time.time() - warmup_start:.1f}s")except Exception as e:print(f"[FLUX-Dev] Warmup failed: {e}")# Don't disable compiled mode, it may still work for actual inferencedef _setup_diffusers_pipeline(self):"""Fallback: Setup diffusers FluxPipeline without PuLID."""print("[FLUX-Dev] Setting up diffusers pipeline (no PuLID)...")165 unmodified linesSupports both single prompt (string) and batch prompts (list of strings).Returns single result dict for single prompt, or list of result dicts for batch.On H200 (no offload), uses batch processing for higher throughput.On A100/L40S (with offload), uses sequential processing."""if not self._pulid_loaded:return {"error": "PuLID not loaded", "success": False}39 unmodified linesseed = params.get("seed", -1)true_cfg = params.get("true_cfg", 1.0)print(f"[FLUX-Dev] PuLID generation: {len(prompts)} image(s) with character '{char_data['name']}'")print(f"[FLUX-Dev] Settings: id_weight={id_weight}, start_step={start_step}, steps={num_steps}")print(f"[FLUX-Dev] Batch mode: {'enabled' if self.max_batch_size > 1 else 'disabled'} (max_batch_size={self.max_batch_size})")# Offload all models before processing to ensure clean GPU stateif self.use_offload:self._offload_all_models()results = []total_prompts = len(prompts)# Process in batchesfor batch_start in range(0, total_prompts, self.max_batch_size):batch_end = min(batch_start + self.max_batch_size, total_prompts)batch_prompts = prompts[batch_start:batch_end]batch_size = len(batch_prompts)# Prepare seeds for this batchbatch_seeds = []for idx in range(batch_size):global_idx = batch_start + idxif seed == -1:batch_seeds.append(-1)else:batch_seeds.append(seed + global_idx)print(f"[FLUX-Dev] Processing batch {batch_start // self.max_batch_size + 1}: {batch_size} image(s) [{batch_start + 1}-{batch_end}/{total_prompts}]")try:if self.max_batch_size > 1 and batch_size > 1:# Use batch processing (H200)batch_images = self._generate_with_embedding_batch(prompts=batch_prompts,id_embedding=id_embedding,uncond_embedding=uncond_embedding,width=width,height=height,num_steps=num_steps,guidance=guidance,id_weight=id_weight,start_step=start_step,seeds=batch_seeds,true_cfg=true_cfg,)# Encode all images in batchfor idx, image in enumerate(batch_images):buffered = BytesIO()image.save(buffered, format="PNG")b64_image = base64.b64encode(buffered.getvalue()).decode("utf-8")results.append({"success": True,"image": f"data:image/png;base64,{b64_image}","characters_used": [char_ids[0]],"character_name": char_data["name"],})else:# Use sequential processing (A100/L40S with offload)for idx, prompt in enumerate(batch_prompts):global_idx = batch_start + idxprint(f"[FLUX-Dev] Generating image {global_idx + 1}/{total_prompts}")image = self._generate_with_embedding(prompt=prompt,id_embedding=id_embedding,uncond_embedding=uncond_embedding,width=width,height=height,num_steps=num_steps,guidance=guidance,id_weight=id_weight,start_step=start_step,seed=batch_seeds[idx],true_cfg=true_cfg,)buffered = BytesIO()image.save(buffered, format="PNG")b64_image = base64.b64encode(buffered.getvalue()).decode("utf-8")results.append({"success": True,"image": f"data:image/png;base64,{b64_image}","characters_used": [char_ids[0]],"character_name": char_data["name"],})# Clean up memory after each generationself._cleanup_memory()# Clean up after batchself._cleanup_memory()except Exception as e:print(f"[FLUX-Dev] Batch generation error: {e}")import tracebacktraceback.print_exc()# Add error results for remaining items in batchfor _ in range(batch_size - (len(results) - batch_start)):results.append({"error": str(e), "success": False})# Force cleanup on errorself._cleanup_memory(force=True)# Final cleanupself._cleanup_memory(force=True)# Return single result for single input, array for batch119 unmodified linesreturn imgdef _generate_with_embedding_batch(self,prompts: List[str],id_embedding: torch.Tensor,uncond_embedding: Optional[torch.Tensor],width: int,height: int,num_steps: int,guidance: float,id_weight: float,start_step: int,seeds: List[int],true_cfg: float,) -> List[Image.Image]:"""Generate multiple images in a single batch using pre-computed ID embedding.This method processes multiple prompts simultaneously for higher throughput.All images share the same character ID embedding.Args:prompts: List of prompts to generateid_embedding: Character ID embedding (shared across batch)uncond_embedding: Unconditional embedding for true CFGwidth, height: Image dimensionsnum_steps: Number of inference stepsguidance: Guidance scaleid_weight: ID embedding weightstart_step: Step to start ID injectionseeds: List of seeds (one per prompt)true_cfg: True CFG scaleReturns:List of PIL Images"""from einops import rearrangefrom flux.sampling import denoise, get_noise, get_schedule, prepare, unpackfrom flux.util import SamplingOptionsgen = self._generatorbatch_size = len(prompts)print(f"[FLUX-Dev] Batch generation: {batch_size} images")# Prepare seedsprocessed_seeds = []for seed in seeds:if seed == -1:processed_seeds.append(torch.Generator(device="cpu").seed())else:processed_seeds.append(seed)use_true_cfg = abs(true_cfg - 1.0) > 1e-2# Prepare input noise for batch# get_noise expects num_samples as first argumentx = get_noise(batch_size,height,width,device=gen.device,dtype=torch.bfloat16,seed=processed_seeds[0], # Use first seed for noise generation)# For different seeds per image, we need to generate noise separately and stackif len(set(processed_seeds)) > 1:noise_list = []for seed in processed_seeds:noise = get_noise(1,height,width,device=gen.device,dtype=torch.bfloat16,seed=seed,)noise_list.append(noise)x = torch.cat(noise_list, dim=0)timesteps = get_schedule(num_steps,x.shape[-1] * x.shape[-2] // 4,shift=True,)# Prepare text embeddings for batch# T5 and CLIP should be on GPU for encodingif gen.offload:gen.t5, gen.clip = gen.t5.to(gen.device), gen.clip.to(gen.device)# prepare() handles batch prompts - pass list of promptsinp = prepare(t5=gen.t5, clip=gen.clip, img=x, prompt=prompts)inp_neg = Noneif use_true_cfg:# For negative prompt, use empty strings for all batch itemsinp_neg = prepare(t5=gen.t5, clip=gen.clip, img=x, prompt=[""] * batch_size)if gen.offload:gen.t5, gen.clip = gen.t5.cpu(), gen.clip.cpu()torch.cuda.empty_cache()# Load model if offloadedif gen.offload:if gen.aggressive_offload:gen.model.components_to_gpu()else:gen.model = gen.model.to(gen.device)# Denoise with ID injection# ID embedding is automatically broadcast across batch dimensionx = denoise(gen.model,**inp,timesteps=timesteps,guidance=guidance,id=id_embedding,id_weight=id_weight,start_step=start_step,uncond_id=uncond_embedding if use_true_cfg else None,true_cfg=true_cfg,timestep_to_start_cfg=1,neg_txt=inp_neg["txt"] if use_true_cfg else None,neg_txt_ids=inp_neg["txt_ids"] if use_true_cfg else None,neg_vec=inp_neg["vec"] if use_true_cfg else None,aggressive_offload=gen.aggressive_offload,)# Offload model, load autoencoderif gen.offload:gen.model.cpu()torch.cuda.empty_cache()gen.ae.decoder.to(x.device)# Decode latents (batch)x = unpack(x.float(), height, width)with torch.autocast(device_type=gen.device.type, dtype=torch.bfloat16):x = gen.ae.decode(x) # [B, C, H, W]if gen.offload:gen.ae.decoder.cpu()torch.cuda.empty_cache()# Convert to PIL imagesx = x.clamp(-1, 1)images = []for i in range(batch_size):img_tensor = rearrange(x[i], "c h w -> h w c")img = Image.fromarray((127.5 * (img_tensor + 1.0)).cpu().byte().numpy())images.append(img)# Clean up intermediate tensorsdel x, inpif inp_neg is not None:del inp_negreturn imagesdef _generate_normal(self, data: Dict) -> Union[Dict, List[Dict]]:"""Normal image generation without character consistency."""inputs = data.get("inputs", data)
handler.py+378-43