kkytai commited on
Commit ·
65a4b73
1
Parent(s): 1c02b3f
fix: Add memory cleanup to prevent CUDA OOM errors
Browse files- Add _cleanup_memory() method with gc.collect() and torch.cuda.empty_cache()
- Call cleanup before/after batch processing
- Call cleanup after each image generation
- Force cleanup on errors
- Clean up when GPU memory usage exceeds 85%
188 unmodified lines189190191192193194104 unmodified lines29930030130230330425 unmodified lines330331332333334335336337338339340111 unmodified lines45245345445545645719 unmodified lines47747847948048148214 unmodified lines4974984995005015029 unmodified lines512513514515516517188 unmodified linesprint("[FLUX-Dev] Diffusers pipeline ready")def _register_character(self, data: Dict) -> Dict:"""Register a character face and cache its embedding."""if not self._pulid_loaded:104 unmodified linesprint(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}")results = []for idx, prompt in enumerate(prompts):print(f"[FLUX-Dev] Generating image {idx + 1}/{len(prompts)}")25 unmodified lines"character_name": char_data["name"],})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})# Return single result for single input, array for batchif single_input:111 unmodified linesx = rearrange(x[0], "c h w -> h w c")img = Image.fromarray((127.5 * (x + 1.0)).cpu().byte().numpy())return imgdef _generate_normal(self, data: Dict) -> Union[Dict, List[Dict]]:19 unmodified linesprint(f"[FLUX-Dev] Generating {len(prompts)} image(s)")print(f"[FLUX-Dev] Settings: steps={num_steps}, guidance={guidance}, size={width}x{height}")all_images = []if self._pulid_loaded:14 unmodified linesid_weight=0.0,)all_images.append(image)else:# Use diffusers pipeline with batchingfor i in range(0, len(prompts), max_batch_size):9 unmodified linesguidance_scale=guidance,)all_images.extend(result.images)# Encode to base64encoded_results = []188 unmodified lines189190191192193194195196197198199200201202203204205206207208209210211212213214215104 unmodified lines32032132232332432532632732825 unmodified lines354355356357358359360361362363364365366367368369370371372111 unmodified lines48448548648748848949049149249349419 unmodified lines51451551651751851952052152214 unmodified lines5375385395405415425435449 unmodified lines554555556557558559560561188 unmodified linesprint("[FLUX-Dev] Diffusers pipeline ready")def _cleanup_memory(self, force: bool = False):"""Clean up GPU memory to prevent OOM errors.Args:force: If True, always clean up. If False, only clean when memory usage is high."""try:allocated = torch.cuda.memory_allocated()total = torch.cuda.get_device_properties(0).total_memoryusage_ratio = allocated / totalif force or usage_ratio > 0.85:gc.collect()torch.cuda.empty_cache()new_allocated = torch.cuda.memory_allocated() / 1e9reserved = torch.cuda.memory_reserved() / 1e9freed = (allocated / 1e9) - new_allocatedprint(f"[FLUX-Dev] Memory cleanup: freed={freed:.2f}GB, allocated={new_allocated:.2f}GB, reserved={reserved:.2f}GB")except Exception as e:print(f"[FLUX-Dev] Memory cleanup warning: {e}")def _register_character(self, data: Dict) -> Dict:"""Register a character face and cache its embedding."""if not self._pulid_loaded:104 unmodified linesprint(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}")# Clean up memory before batch processingself._cleanup_memory(force=True)results = []for idx, prompt in enumerate(prompts):print(f"[FLUX-Dev] Generating image {idx + 1}/{len(prompts)}")25 unmodified lines"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 batchif single_input:111 unmodified linesx = rearrange(x[0], "c h w -> h w c")img = Image.fromarray((127.5 * (x + 1.0)).cpu().byte().numpy())# Clean up intermediate tensorsdel x, inpif inp_neg is not None:del inp_negreturn imgdef _generate_normal(self, data: Dict) -> Union[Dict, List[Dict]]:19 unmodified linesprint(f"[FLUX-Dev] Generating {len(prompts)} image(s)")print(f"[FLUX-Dev] Settings: steps={num_steps}, guidance={guidance}, size={width}x{height}")# Clean up memory before generationself._cleanup_memory(force=True)all_images = []if self._pulid_loaded:14 unmodified linesid_weight=0.0,)all_images.append(image)# Clean up after each generationself._cleanup_memory()else:# Use diffusers pipeline with batchingfor i in range(0, len(prompts), max_batch_size):9 unmodified linesguidance_scale=guidance,)all_images.extend(result.images)# Clean up after each batchself._cleanup_memory()# Encode to base64encoded_results = []
handler.py+44