Skip to content

Grow lastrec KV buffers until cache length - #161

Open
sathariels wants to merge 5 commits into
awslabs:mainfrom
sathariels:grow-lastrec-buffers
Open

sathariels wants to merge 5 commits into
awslabs:mainfrom
sathariels:grow-lastrec-buffers

Conversation

@sathariels

@sathariels sathariels commented Oct 9, 2026 •

Copy link
Copy Markdown

Summary

  • Opt-in grow_buffers for lastrec-default. Buffers start at 16 slots and double until cache_length. Default remains a full allocation.
  • Scoped to the lastrec warm-up phase from Allocate KV cache buffers in pages #137. Quantized buffers, smart-lastrec, and gradient code are unchanged.
  • Tests check doubling, the cap, matching get_keys_values against 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.py
  • pytest test/kvcache/test_generic.py test/kvcache/test_replay.py -k "lastrec-default and not smart"
  • black and flake8

@mseeger

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

@mseeger mseeger left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good first step, but see my comments.
Once this is done and tests work, we can extend this to others.

Comment thread keys_values/kvcache/basics.py Resolved
Comment thread keys_values/kvcache/basics.py Resolved
Comment thread keys_values/kvcache/buffers.py Resolved
Comment thread keys_values/kvcache/buffers.py Resolved
Comment thread keys_values/kvcache/buffers.py Resolved
@sathariels

Copy link
Copy Markdown
Author

On it, should have it done by the end of the day.

@sathariels

sathariels commented Oct 13, 2026 •

Copy link
Copy Markdown
Author

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.
set_slots now just doubles when the write doesn't fit, with no special-casing of positions.

_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.

@mseeger

mseeger commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

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 (current_length < cache_length).

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.

@mseeger

mseeger commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

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.

@sathariels

Copy link
Copy Markdown
Author

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.

@mseeger

mseeger commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

Is this still active?

@sathariels

Copy link
Copy Markdown
Author

Yes sorry, just waiting for you to get back :)

@sathariels

Copy link
Copy Markdown
Author

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 mangeshraut712 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Comment thread keys_values/kvcache/buffers.py Outdated
"""
n = self.k.shape[2]
extra = num_slots - n
k_extra = torch.zeros_like(self.k[:, :, :extra, :])

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, and your new code does that? Good, I appreciate this kind of foresight

@mseeger

mseeger commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

I'll review shortly, have been a bit busy.

There were many changes, could you rebase your branch and fix conflicts?

@sathariels

Copy link
Copy Markdown
Author

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.

@mseeger

mseeger commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

Thanks, I do value your contribution. Sorry if I am a little slow, just have a stack of other things right now.

@sathariels

Copy link
Copy Markdown
Author

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_config methods 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,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 (

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not needed. Property of buffers

buffers,
block_idx,
init_grace_tokens=init_grace_tokens,
grow_buffers_init_length=grow_buffers_init_length,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

< 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]:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This condition can never be True.

)
result = cache_type.from_config(**from_config_kwargs)
else:
grow_buffers_init_length = cache_kwargs.pop(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shorter: if "grow_buffers_init_length" in cache_kwargs, throw exception

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants