Add support for H2O cache eviction with LLaMA #35381
Open
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.
What does this PR do?
We implement the Heavy-Hitter Oracle (H2O) cache eviction strategy in Huggingface transformers, which selectively retains a balance of KV pairs that are recent or contribute most to the cumulative attention scores while evicting less important ones to maintain a fixed cache size. Our implementation identifies and preserves these “heavy hitter” tokens during inference, maintaining generation quality while dramatically reducing memory requirements.
Key features:
Fixes #30758
Before submitting
Pull Request section?
to it if that's the case.
Yes, discussed in issue Implement kv cache sparsity like H2O with attention score #30758
documentation guidelines, and
here are tips on formatting docstrings.
Added informative docstrings to public methods following guidelines
Added test to validate that H2OCache works correctly with LLaMA model generation by ensuring it can produce non-empty text responses while using cache, specifically testing with TinyLlama-1.1B-Chat in 8-bit quantization on CUDA devices.
Who can review?
@gante as this relates to generation functionality since this touches core caching infrastructure.
Outline of code
Files modified:
src/transformers/cache_utils.py
: Added a new classH2OCache
src/transformers/models/llama/modeling_llama.py
: Added post processing function to track attention weights to identify heavy hittersbenchmark/h20
: Added benchmarking scripts to compare H2OCache performance with DynamicCachetests/h2O
: Added tests to run LLM with H20CacheExecuting code
To test an LLM with the H20 cache mechanism, run the following:
Results
We demonstrate that H2O achieves over 80% reduction in KV cache size while incurring less than a 5% reduction in throughput. This represents a significant improvement over QuantizedCache, which introduces substantially higher overhead for similar memory savings.