-
Notifications
You must be signed in to change notification settings - Fork 1k
DYNAMIC_UNBOUND support for portable runtime: lazy KV cache allocation #18350
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
psiddh
wants to merge
2
commits into
main
Choose a base branch
from
dynamic_unbound_kv_cache
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| # Copyright (c) Meta Platforms, Inc. and affiliates. | ||
| # All rights reserved. | ||
| # | ||
| # This source code is licensed under the BSD-style license found in the | ||
| # LICENSE file in the root directory of this source tree. | ||
|
|
||
| from typing import List, Optional | ||
|
|
||
| from executorch.exir.pass_base import ExportPass | ||
|
|
||
|
|
||
| class MarkDynamicUnboundPass(ExportPass): | ||
| """ | ||
| Marks matching placeholder nodes with ``et_dynamic_unbound`` metadata. | ||
|
|
||
| After ``SpecPropPass`` creates ``TensorSpec`` for each placeholder, | ||
| ``update_placeholder_tensor_specs`` reads this flag and sets the spec's | ||
| ``shape_dynamism`` to ``DYNAMIC_UNBOUND``. The memory planner then skips | ||
| those tensors, and the runtime allocates their memory lazily via | ||
| ``DynamicAllocator``. | ||
|
|
||
| Typical usage: mark KV cache buffers so they start unallocated and grow | ||
| on demand, avoiding the full upfront memory cost of max_context_length. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| name_patterns: Optional[List[str]] = None, | ||
| ) -> None: | ||
| super().__init__() | ||
| self.name_patterns = name_patterns or ["k_cache", "v_cache"] | ||
|
|
||
| def placeholder(self, name: str, arg, meta): | ||
| if any(pattern in name for pattern in self.name_patterns): | ||
| meta["et_dynamic_unbound"] = True | ||
| return super().placeholder(name, arg, meta) |
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
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
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
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,141 @@ | ||
| # Copyright (c) Meta Platforms, Inc. and affiliates. | ||
| # All rights reserved. | ||
| # | ||
| # This source code is licensed under the BSD-style license found in the | ||
| # LICENSE file in the root directory of this source tree. | ||
|
|
||
| """ | ||
| Tests for lazy KV cache (DYNAMIC_UNBOUND) support. | ||
|
|
||
| Tests the update_cache custom op's ability to handle caches that start at | ||
| seq_len=0 and grow on demand, which is the foundation for pay-as-you-go | ||
| KV cache memory allocation. | ||
| """ | ||
|
|
||
| # pyre-unsafe | ||
|
|
||
| import unittest | ||
|
|
||
| import torch | ||
|
|
||
| from executorch.extension.llm.custom_ops import custom_ops # noqa | ||
|
|
||
|
|
||
| class LazyKVCacheUpdateTest(unittest.TestCase): | ||
| """Test update_cache op with zero-sized initial caches (lazy KV cache).""" | ||
|
|
||
| def setUp(self): | ||
| torch.manual_seed(42) | ||
| self.batch_size = 1 | ||
| self.num_heads = 4 | ||
| self.head_dim = 8 | ||
| self.max_seq_len = 64 | ||
|
|
||
| def test_update_cache_grows_from_zero(self): | ||
| """Verify update_cache works when cache seq dim starts at full size | ||
| and tokens are appended sequentially.""" | ||
| cache = torch.zeros( | ||
| (self.batch_size, self.max_seq_len, self.num_heads, self.head_dim), | ||
| dtype=torch.float32, | ||
| ) | ||
|
|
||
| for pos in range(10): | ||
| value = torch.randn( | ||
| (self.batch_size, 1, self.num_heads, self.head_dim), | ||
| dtype=torch.float32, | ||
| ) | ||
| torch.ops.llama.update_cache(value, cache, pos) | ||
| self.assertTrue( | ||
| torch.allclose(cache[:, pos : pos + 1, :, :], value), | ||
| f"Cache mismatch at position {pos}", | ||
| ) | ||
|
|
||
| def test_custom_kv_cache_lazy_init(self): | ||
| """Verify CustomKVCache with lazy=True creates zero-sized buffers.""" | ||
| from executorch.examples.models.llama.source_transformation.custom_kv_cache import ( | ||
| CustomKVCache, | ||
| ) | ||
|
|
||
| cache = CustomKVCache( | ||
| max_batch_size=1, | ||
| max_context_length=131072, # 128K ceiling | ||
| n_heads=4, | ||
| head_dim=8, | ||
| dtype=torch.float32, | ||
| lazy=True, | ||
| ) | ||
| self.assertEqual(cache.k_cache.shape[1], 0, "Lazy k_cache seq dim should be 0") | ||
| self.assertEqual(cache.v_cache.shape[1], 0, "Lazy v_cache seq dim should be 0") | ||
| self.assertEqual(cache.max_context_length, 131072) | ||
|
|
||
| def test_custom_kv_cache_non_lazy_init(self): | ||
| """Verify CustomKVCache without lazy=True creates full-sized buffers.""" | ||
| from executorch.examples.models.llama.source_transformation.custom_kv_cache import ( | ||
| CustomKVCache, | ||
| ) | ||
|
|
||
| cache = CustomKVCache( | ||
| max_batch_size=1, | ||
| max_context_length=64, | ||
| n_heads=4, | ||
| head_dim=8, | ||
| dtype=torch.float32, | ||
| lazy=False, | ||
| ) | ||
| self.assertEqual(cache.k_cache.shape[1], 64) | ||
| self.assertEqual(cache.v_cache.shape[1], 64) | ||
|
|
||
| def test_replace_kv_cache_with_lazy(self): | ||
| """Verify replace_kv_cache_with_custom_kv_cache passes lazy flag.""" | ||
| from executorch.examples.models.llama.attention import KVCache | ||
| from executorch.examples.models.llama.source_transformation.custom_kv_cache import ( | ||
| CustomKVCache, | ||
| replace_kv_cache_with_custom_kv_cache, | ||
| ) | ||
|
|
||
| class FakeModel(torch.nn.Module): | ||
| def __init__(self): | ||
| super().__init__() | ||
| # KVCache stores as [B, H, S, D] | ||
| self.kv = KVCache( | ||
| max_batch_size=1, | ||
| max_context_length=128, | ||
| n_heads=4, | ||
| head_dim=8, | ||
| enable_dynamic_shape=False, | ||
| dtype=torch.float32, | ||
| ) | ||
|
|
||
| def forward(self, x): | ||
| return x | ||
|
|
||
| model = FakeModel() | ||
| replace_kv_cache_with_custom_kv_cache(model, lazy=True) | ||
| self.assertIsInstance(model.kv, CustomKVCache) | ||
| # CustomKVCache stores as [B, S, H, D], lazy means seq_dim=0 | ||
| self.assertEqual(model.kv.k_cache.shape[1], 0) | ||
|
|
||
|
|
||
| class LazyKVCacheMetaKernelTest(unittest.TestCase): | ||
| """Test that meta kernels work without upper-bound cache size checks.""" | ||
|
|
||
| def test_meta_kernel_allows_start_pos_beyond_cache(self): | ||
| """Meta kernel should not reject start_pos >= cache.size(1).""" | ||
| value = torch.randn(1, 1, 4, 8) | ||
| # Cache with seq_len=0 (lazy) | ||
| cache = torch.zeros(1, 0, 4, 8) | ||
| # This should not raise — the runtime op handles resize | ||
| result = torch.ops.llama.update_cache(value, cache, 0) | ||
| self.assertIsNotNone(result) | ||
|
|
||
| def test_meta_kernel_allows_large_start_pos(self): | ||
| """Meta kernel should allow start_pos beyond current cache size for lazy caches.""" | ||
| value = torch.randn(1, 1, 4, 8) | ||
| cache = torch.zeros(1, 0, 4, 8) | ||
| # Lazy cache (size(1)==0) skips bounds checks — runtime op handles resize | ||
| result = torch.ops.llama.update_cache(value, cache, 100) | ||
| self.assertIsNotNone(result) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() |
Oops, something went wrong.
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
is this because we do actually touch the full memory during attention?
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Missed out on this comment...
Yes, the full max_context_length buffer is allocated on first inference, not at load time. This defers the KV cache allocation from Module.load() to the first generate() call.
Sharing some Test Results:
Concrete KV cache costs for Qwen3-0.6B (28 layers, 8 KV heads, 128 head_dim,fp16):
▎ | max_context_length | KV Cache | Without PR | With PR (at load) |
▎ |-------------------- |----------|---------------|-------------------|
▎ | 128 (default) | 14 MB | Pre-allocated | 0 MB |
▎ | 1024 | 115 MB | Pre-allocated | 0 MB |
▎ | 2048 (standard) | 229 MB | Pre-allocated | 0 MB |
▎ | 4096 | 459 MB | Pre-allocated | 0 MB |
▎ | 16384 | 1.8 GB | OOM at load | 0 MB |
Note : KV cache sizes above are for fp16. fp32 doubles these values
With this PR I increased max_context_length to 4096 on Samsung S23 (8GB RAM) and tested 10+ multi-turn conversations with stable RSS:
Key benefits:
(onTrimMemory) // Future enhacements
this feature / lazy allocation