Repository navigation
Grow lastrec KV buffers until cache length - #161
sathariels wants to merge 5 commits into
Conversation
mseeger
left a comment
There was a problem hiding this comment.
Good first step, but see my comments.
Once this is done and tests work, we can extend this to others.
|
On it, should have it done by the end of the day. |
|
Thanks for the review! I've pushed an update addressing your comments: Replaced grow_buffers with grow_buffers_init_length: Optional[int] = None (None = no growth, same behavior as before). Simplified growth: if the buffer is too small, it doubles (capped at cache_length). Removed the needed logic. _expand_slots now uses torch.cat with torch.zeros_like for the new slots. Updated the docstring to say the option is passed at construction. Tests pass locally. Happy to extend this to the other caches once you're happy with this one. |
|
OK. I am on holiday the next two weeks, and will only have time to review this after that. I'd suggest you now work out how to extend this to all KV cache types. I don't expect this to be difficult, because they all do more or less the same during the "growth" phase ( We'd then also need the tests to extend over all KV cache types. There is some functionality helping with this, check the other tests. |
|
Here is also some perspective. The issue is a small part of trying to make the library better for inference applications. Essentially, if KV caches are created on demand for inference tasks, and the prompt is short, you don't want to reserve lots of memory up front. But there are several other inefficiencies right now. For example, we don't use graph compilation, which would also require some smart caching of graphs. If you are interested in this, feel free to do some digging in this direction. It would need using some kind of inference benchmark, maybe something that vLLM uses. |
|
Thanks, that helps. This pull request stays the buffer-growth change: a cache created for a short prompt starts small and doubles until cache_length, instead of reserving the full buffer up front. While you are away I will extend grow_buffers_init_length to the other KV cache types and cover them in the tests, since they behave the same while current_length is still below cache_length. Graph compilation and an inference benchmark (along the lines of what vLLM uses) sound useful. I will look into that as a follow-up once the growth work is in, and I will not fold it into this pull request. |
|
Is this still active? |
|
Yes sorry, just waiting for you to get back :) |
|
Yes, this is still active and ready for review. While you were away I extended grow_buffers_init_length to the other default-buffer caches (dense, smart-lastrec, h2o, h2o-vlen, and h2o-orig) and added tests that a growing cache matches a full-size one. That is in 744efc9. Quantized buffers still do not grow. Happy to look at graph compilation and an inference benchmark as a follow-up after this lands. |
mangeshraut712
left a comment
There was a problem hiding this comment.
Read through the buffer-growth path (_allocate_buffers → _grow_to_fit → _expand_slots) and the three call sites in set_slots, _prefill and prefill_from_keys_values. Calling _grow_to_fit after _allocate_buffers in both prefill paths covers prompts longer than the initial length. One robustness nit:
| """ | ||
| n = self.k.shape[2] | ||
| extra = num_slots - n | ||
| k_extra = torch.zeros_like(self.k[:, :, :extra, :]) |
There was a problem hiding this comment.
torch.zeros_like(self.k[:, :, :extra, :]) only yields extra slots while extra <= n. That holds today because _grow_to_fit at most doubles. But _expand_slots(num_slots) reads as a general "extend to num_slots", and a future caller that jumps straight to cache_length (e.g. growing in one step for a long prefill) would silently get 2n slots instead, and the next scatter_/slice write would go out of range. Building the shape explicitly avoids that: self.k.new_zeros(self.k.shape[:2] + (extra,) + self.k.shape[3:]) (same for v), or torch.nn.functional.pad(self.k, (0, 0, 0, extra)).
There was a problem hiding this comment.
OK, and your new code does that? Good, I appreciate this kind of foresight
|
I'll review shortly, have been a bit busy. There were many changes, could you rebase your branch and fix conflicts? |
744efc9 to
7f36ebc
Compare
|
Yes. _expand_slots now allocates the extra region with new_zeros at length num_slots - n, so a jump straight to cache_length gets that many slots. I rebased onto main. The only conflict was the KVCacheWithBuffers docstring; both the switch_buffers section and the growth note are kept. Ready for review. |
|
Thanks, I do value your contribution. Sorry if I am a little slow, just have a stack of other things right now. |
|
Of course all good, take your time and let me know if any changes are neccesary |
|
|
||
| Optional growth of default buffers: | ||
|
|
||
| Pass `grow_buffers_init_length` to :meth:`from_config` (any subclass that |
There was a problem hiding this comment.
This comment (at this point) is misleading: There is no from_config method in this class, only in subclasses.
The grow_buffers_init_length is really a property of buffers. My suggestion:
- Move this comment to the buffer class(es) for which this feature is supported
- Add comments to the
from_configmethods of KV cache classes, to remind folks there
| buffers: KVCacheBuffers, | ||
| block_idx: int, | ||
| init_grace_tokens: Optional[int] = None, | ||
| grow_buffers_init_length: Optional[int] = None, |
There was a problem hiding this comment.
This should be a property of buffers, so no need to pass it here.
| **base_kwargs, | ||
| ): | ||
| super().__init__(config, buffers, block_idx, **base_kwargs) | ||
| if ( |
There was a problem hiding this comment.
It should be the other way around: If the cache really needs to know grow_buffers_init_length, it should
obtain it as buffers.grow_buffers_init_length
| cache_length=cache_length, | ||
| device=device, | ||
| dtype=dtype, | ||
| grow_buffers_init_length=grow_buffers_init_length, |
There was a problem hiding this comment.
Not needed. Property of buffers
| buffers, | ||
| block_idx, | ||
| init_grace_tokens=init_grace_tokens, | ||
| grow_buffers_init_length=grow_buffers_init_length, |
There was a problem hiding this comment.
Not needed. Property of buffers
| extra_shape = self.k.shape[:2] + (extra,) + self.k.shape[3:] | ||
| k_extra = self.k.new_zeros(extra_shape) | ||
| v_extra = self.v.new_zeros(extra_shape) | ||
| self.k = torch.cat((self.k, k_extra), dim=2) |
There was a problem hiding this comment.
A shorter alternative could be:
self.k = F.pad(self.k, (0, extra, 0, 0))
self.v = F.pad(self.v, (0, extra, 0, 0))
with import torch.nn.functional as F on top.
| """ | ||
| if self.grow_buffers_init_length is None or not self.buffers_are_allocated: | ||
| return | ||
| while self.k.shape[2] < limit and self.k.shape[2] < self.cache_length: |
There was a problem hiding this comment.
< min(limit, self.cache_length)
| return | ||
| while self.k.shape[2] < limit and self.k.shape[2] < self.cache_length: | ||
| new_length = min(self.cache_length, self.k.shape[2] * 2) | ||
| if new_length == self.k.shape[2]: |
There was a problem hiding this comment.
This condition can never be True.
| ) | ||
| result = cache_type.from_config(**from_config_kwargs) | ||
| else: | ||
| grow_buffers_init_length = cache_kwargs.pop( |
There was a problem hiding this comment.
Shorter: if "grow_buffers_init_length" in cache_kwargs, throw exception
Summary
grow_buffersforlastrec-default. Buffers start at 16 slots and double untilcache_length. Default remains a full allocation.get_keys_valuesagainst a full-size cache, a long prefill, the flag left off, and a batch-size change.Part of #137. The general case is a later change.
AI usage
I used AI to write this pull request, and to write 50% of the tests for this code.
Test plan
pytest test/kvcache/test_basics.pypytest test/kvcache/test_generic.py test/kvcache/test_replay.py -k "lastrec-default and not smart"@mseeger
By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.