fix: force gc + clear_cache after KV prefix cache eviction#1832
Open
adurham wants to merge 1 commit intoexo-explore:mainfrom
Open
fix: force gc + clear_cache after KV prefix cache eviction#1832adurham wants to merge 1 commit intoexo-explore:mainfrom
adurham wants to merge 1 commit intoexo-explore:mainfrom
Conversation
When `KVPrefixCache` evicts LRU entries under memory pressure, the Python list `pop()` removes references but the underlying MLX Metal buffers stay allocated until Python's garbage collector runs. This causes ~3-4 GB of leaked memory between long-context requests, reducing the effective context ceiling for back-to-back requests. Adding `gc.collect()` + `mx.clear_cache()` after eviction ensures Metal buffers are freed promptly. Measured: 3.78 GB leak reduced to 0.38 GB (draft model KV + minor Python heap overhead). The `gc.collect()` call adds a few milliseconds of latency but only runs once per eviction cycle (not per token), so the impact on generation throughput is negligible. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
KVPrefixCacheevicts LRU entries, the MLX Metal buffers stay allocated until Python's GC runsgc.collect()+mx.clear_cache()after eviction frees Metal buffers promptlyTest plan
gc.collect()adds ~2-3ms latency, runs once per eviction cycle (not per token)uv run pytest🤖 Generated with Claude Code