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 lines189190191192193194195196197198199200201202203204205206207208209210211212213214215104 unmodified lines32032132232332432532632732825 unmodified lines354355356357358359360361362363364365366367368369370371372111 unmodified lines48448548648748848949049149249349419 unmodified lines51451551651751851952052152214 unmodified lines5375385395405415425435449 unmodified lines554555556557558559560561188 unmodified lines
print("[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_memory
usage_ratio = allocated / total
if force or usage_ratio > 0.85:
gc.collect()
torch.cuda.empty_cache()
new_allocated = torch.cuda.memory_allocated() / 1e9
reserved = torch.cuda.memory_reserved() / 1e9
freed = (allocated / 1e9) - new_allocated
print(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 lines 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}")
# Clean up memory before batch processing
self._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 OOM
self._cleanup_memory()
except Exception as e:
print(f"[FLUX-Dev] Generation error for prompt {idx + 1}: {e}")
import traceback
traceback.print_exc()
results.append({"error": str(e), "success": False})
# Force cleanup on error
self._cleanup_memory(force=True)
# Final cleanup after batch
self._cleanup_memory(force=True)
# Return single result for single input, array for batch
if single_input:111 unmodified lines x = rearrange(x[0], "c h w -> h w c")
img = Image.fromarray((127.5 * (x + 1.0)).cpu().byte().numpy())
# Clean up intermediate tensors
del x, inp
if inp_neg is not None:
del inp_neg
return img
def _generate_normal(self, data: Dict) -> Union[Dict, List[Dict]]:19 unmodified lines print(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 generation
self._cleanup_memory(force=True)
all_images = []
if self._pulid_loaded:14 unmodified lines id_weight=0.0,
)
all_images.append(image)
# Clean up after each generation
self._cleanup_memory()
else:
# Use diffusers pipeline with batching
for i in range(0, len(prompts), max_batch_size):9 unmodified lines guidance_scale=guidance,
)
all_images.extend(result.images)
# Clean up after each batch
self._cleanup_memory()
# Encode to base64
encoded_results = []handler.py+44