Fix CLIP memory leak causing 600-800MB accumulation per batch#41215
Fix CLIP memory leak causing 600-800MB accumulation per batch#41215goodhee wants to merge 2 commits into
Conversation
- Explicitly delete intermediate vision_outputs and text_outputs to prevent memory accumulation - Resolves issue where repeated calls to get_image_features caused 600-800MB memory increase per batch - Fixes huggingface#41178 The issue was caused by holding references to full BaseModelOutputWithPooling objects when only pooler_output was needed. By extracting the required tensor and immediately deleting the full output object, we allow proper garbage collection.
- Add explicit deletion of intermediate outputs in get_image_features and get_text_features - Ensures consistency across all CLIP-based models - Resolves repository consistency check failures
|
[For maintainers] Suggested jobs to run (before merge) run-slow: aimv2, clip, metaclip_2 |
|
@ydshieh After reviewing my PR and running additional memory profiling, I need to revise my initial approach. Current PR ReviewMy current fix: # Extract pooled output and immediately delete the full output to free memory
pooled_output = text_outputs.pooler_output
del text_outputs # Explicitly delete to help with memory managementWhile this helps with immediate Python object cleanup, I found it's not addressing the root cause. Memory Profiling ResultsI created a test script to isolate the issue: Model Only (get_image_features):Line 71: image_features = model.get_image_features(**inputs) → 514.2 MiB leak per batchProcessor Only (preprocess):Line 99: inputs = processor(images=images, return_tensors="pt", padding=True) → 74.0 MiB leak per batchFull Pipeline:
Root CauseAfter this analysis, I realize this is actually a system-level memory fragmentation issue, not a transformers library bug. This matches known PyTorch/glibc behavior (refs: pytorch/pytorch#68114, pytorch/pytorch#114455). RecommendationI suggest we:
def trim_memory():
try:
import ctypes
libc = ctypes.CDLL("libc.so.6")
return libc.malloc_trim(0)
except:
return False
# Use after batch processing
features = model.get_image_features(**inputs)
del inputs, features
gc.collect()
trim_memory()I've attached my full analysis script and results for reference. Let me know if you'd like me to update the documentation instead to help users handle this properly at the application level. |
|
Thank you a lot @eun2ce for taking a deeper analysis. For the documentation, the discussions in this PR is already a good resource, we don't need to add a documentation within the codebase (which is a bit off-topic). But it would be nice if you can add @Adefey, maybe you could try what @eun2ce suggests? |
|
I’ve updated the PR description with the details from my last comment. Please let me know if anything else should be added or clarified. |
What does this PR do?
This PR fixes a critical memory leak in CLIP model's
get_image_featuresandget_text_featuresmethods that was causing significant memory accumulation during repeated inference calls.Problem
When using CLIP models for batch processing (e.g., in microservices), repeated calls to
get_image_featuresorget_text_featurescaused memory to increase by 600-800MB per batch, eventually leading to OOM crashes. This was particularly problematic in production environments processing multiple batches sequentially.Root Cause
The issue was caused by holding references to full
BaseModelOutputWithPoolingobjects when only thepooler_outputtensor was needed. These large intermediate objects contained all hidden states, attentions, and other tensors that were not being properly garbage collected.Solution
vision_outputsandtext_outputsobjects after extracting the requiredpooler_outputTesting
Fixes #41178
Before submitting
Who can review?
@amyeroberts @qubvel (vision models)
[UPDATE] Further Memory Analysis Results
After deeper profiling investigation, we discovered this is actually a system-level memory fragmentation issue, matching known PyTorch/glibc behavior (refs: pytorch/pytorch#68114, pytorch/pytorch#114455).
Detailed Memory Profiling
Recommended Application-Level Solution
Users experiencing significant memory issues should handle memory management at the application level: