|
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# This source code is licensed under the BSD-style license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | +""" |
| 8 | +Tests for lazy KV cache (DYNAMIC_UNBOUND) support. |
| 9 | +
|
| 10 | +Tests the update_cache custom op's ability to handle caches that start at |
| 11 | +seq_len=0 and grow on demand, which is the foundation for pay-as-you-go |
| 12 | +KV cache memory allocation. |
| 13 | +""" |
| 14 | + |
| 15 | +# pyre-unsafe |
| 16 | + |
| 17 | +import unittest |
| 18 | + |
| 19 | +import torch |
| 20 | + |
| 21 | +from executorch.extension.llm.custom_ops import custom_ops # noqa |
| 22 | + |
| 23 | + |
| 24 | +class LazyKVCacheUpdateTest(unittest.TestCase): |
| 25 | + """Test update_cache op with zero-sized initial caches (lazy KV cache).""" |
| 26 | + |
| 27 | + def setUp(self): |
| 28 | + torch.manual_seed(42) |
| 29 | + self.batch_size = 1 |
| 30 | + self.num_heads = 4 |
| 31 | + self.head_dim = 8 |
| 32 | + self.max_seq_len = 64 |
| 33 | + |
| 34 | + def test_update_cache_grows_from_zero(self): |
| 35 | + """Verify update_cache works when cache seq dim starts at full size |
| 36 | + and tokens are appended sequentially.""" |
| 37 | + cache = torch.zeros( |
| 38 | + (self.batch_size, self.max_seq_len, self.num_heads, self.head_dim), |
| 39 | + dtype=torch.float32, |
| 40 | + ) |
| 41 | + |
| 42 | + for pos in range(10): |
| 43 | + value = torch.randn( |
| 44 | + (self.batch_size, 1, self.num_heads, self.head_dim), |
| 45 | + dtype=torch.float32, |
| 46 | + ) |
| 47 | + torch.ops.llama.update_cache(value, cache, pos) |
| 48 | + self.assertTrue( |
| 49 | + torch.allclose(cache[:, pos : pos + 1, :, :], value), |
| 50 | + f"Cache mismatch at position {pos}", |
| 51 | + ) |
| 52 | + |
| 53 | + def test_custom_kv_cache_lazy_init(self): |
| 54 | + """Verify CustomKVCache with lazy=True creates zero-sized buffers.""" |
| 55 | + from executorch.examples.models.llama.source_transformation.custom_kv_cache import ( |
| 56 | + CustomKVCache, |
| 57 | + ) |
| 58 | + |
| 59 | + cache = CustomKVCache( |
| 60 | + max_batch_size=1, |
| 61 | + max_context_length=131072, # 128K ceiling |
| 62 | + n_heads=4, |
| 63 | + head_dim=8, |
| 64 | + dtype=torch.float32, |
| 65 | + lazy=True, |
| 66 | + ) |
| 67 | + self.assertEqual(cache.k_cache.shape[1], 0, "Lazy k_cache seq dim should be 0") |
| 68 | + self.assertEqual(cache.v_cache.shape[1], 0, "Lazy v_cache seq dim should be 0") |
| 69 | + self.assertEqual(cache.max_context_length, 131072) |
| 70 | + |
| 71 | + def test_custom_kv_cache_non_lazy_init(self): |
| 72 | + """Verify CustomKVCache without lazy=True creates full-sized buffers.""" |
| 73 | + from executorch.examples.models.llama.source_transformation.custom_kv_cache import ( |
| 74 | + CustomKVCache, |
| 75 | + ) |
| 76 | + |
| 77 | + cache = CustomKVCache( |
| 78 | + max_batch_size=1, |
| 79 | + max_context_length=64, |
| 80 | + n_heads=4, |
| 81 | + head_dim=8, |
| 82 | + dtype=torch.float32, |
| 83 | + lazy=False, |
| 84 | + ) |
| 85 | + self.assertEqual(cache.k_cache.shape[1], 64) |
| 86 | + self.assertEqual(cache.v_cache.shape[1], 64) |
| 87 | + |
| 88 | + def test_replace_kv_cache_with_lazy(self): |
| 89 | + """Verify replace_kv_cache_with_custom_kv_cache passes lazy flag.""" |
| 90 | + from executorch.examples.models.llama.source_transformation.custom_kv_cache import ( |
| 91 | + CustomKVCache, |
| 92 | + replace_kv_cache_with_custom_kv_cache, |
| 93 | + ) |
| 94 | + from executorch.examples.models.llama.attention import KVCache |
| 95 | + |
| 96 | + class FakeModel(torch.nn.Module): |
| 97 | + def __init__(self): |
| 98 | + super().__init__() |
| 99 | + # KVCache stores as [B, H, S, D] |
| 100 | + self.kv = KVCache( |
| 101 | + max_batch_size=1, |
| 102 | + max_context_length=128, |
| 103 | + n_heads=4, |
| 104 | + head_dim=8, |
| 105 | + enable_dynamic_shape=False, |
| 106 | + dtype=torch.float32, |
| 107 | + ) |
| 108 | + |
| 109 | + def forward(self, x): |
| 110 | + return x |
| 111 | + |
| 112 | + model = FakeModel() |
| 113 | + replace_kv_cache_with_custom_kv_cache(model, lazy=True) |
| 114 | + self.assertIsInstance(model.kv, CustomKVCache) |
| 115 | + # CustomKVCache stores as [B, S, H, D], lazy means seq_dim=0 |
| 116 | + self.assertEqual(model.kv.k_cache.shape[1], 0) |
| 117 | + |
| 118 | + |
| 119 | +class LazyKVCacheMetaKernelTest(unittest.TestCase): |
| 120 | + """Test that meta kernels work without upper-bound cache size checks.""" |
| 121 | + |
| 122 | + def test_meta_kernel_allows_start_pos_beyond_cache(self): |
| 123 | + """Meta kernel should not reject start_pos >= cache.size(1).""" |
| 124 | + value = torch.randn(1, 1, 4, 8) |
| 125 | + # Cache with seq_len=0 (lazy) |
| 126 | + cache = torch.zeros(1, 0, 4, 8) |
| 127 | + # This should not raise — the runtime op handles resize |
| 128 | + result = torch.ops.llama.update_cache(value, cache, 0) |
| 129 | + self.assertIsNotNone(result) |
| 130 | + |
| 131 | + def test_meta_kernel_allows_large_start_pos(self): |
| 132 | + """Meta kernel should allow start_pos beyond current cache size for lazy caches.""" |
| 133 | + value = torch.randn(1, 1, 4, 8) |
| 134 | + cache = torch.zeros(1, 0, 4, 8) |
| 135 | + # Lazy cache (size(1)==0) skips bounds checks — runtime op handles resize |
| 136 | + result = torch.ops.llama.update_cache(value, cache, 100) |
| 137 | + self.assertIsNotNone(result) |
| 138 | + |
| 139 | + |
| 140 | +if __name__ == "__main__": |
| 141 | + unittest.main() |
0 commit comments