Skip to content

Opt-in growable KV cache for generic decode graphs - #17296

Merged
danielhanchen merged 66 commits into
mainfrom
growable-kv-cache
Nov 10, 2026
Merged

danielhanchen merged 66 commits into
mainfrom
growable-kv-cache

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds a growable KV cache to the generic FastModel decode path (the CUDA graph path from #16587). On by default where that path runs; UNSLOTH_GROWABLE_KV=0 keeps transformers' full-length StaticCache. Models whose mask or ALiBi is sized by the cache's full limit (get_max_cache_shape() / get_max_length(), e.g. BLOOM) keep StaticCache.

A transformers StaticCache allocates prompt + max_new_tokens slots for every full-attention layer at prefill, and attention reads every slot each step however early the reply stops. Under decode graphs the kept cache also stays at the largest size a previous call asked for, so a short call after a long one pays for the long one.

  • unsloth/models/_kv_cache.py (new): GrowableLayer is a transformers StaticLayer whose full-attention layers allocate a power-of-two bucket (at least UNSLOTH_GROWABLE_KV_MIN, default 256, never above the limit generate sized for) and double when a step would pass it. Writes are transformers' own update (index_copy_ at device positions), buffers are mark_static_address, and the mask reads the bucket length, so within a bucket every tensor keeps its shape and address. Sliding and chunked layers stay transformers' own.
  • Growth happens outside the graph: generate's prepare_inputs_for_generation re-syncs the host counter from generate's own lengths and reserves the next bucket eagerly, before the step's mask is built. No growth can happen inside a capture (frozen during recording and while a CUDA stream is capturing), and a step that would fill its bucket with no graph yet runs eagerly.
  • Hybrid models (Decode CUDA graphs for Qwen3.5 / Qwen3.6 hybrid linear-attention caches #17324): linear-attention layers keep their own states; the graph key and cache signature carry both their shapes and the growable buckets.
  • Memory: layers hold their growth group by weak reference (no cycle), so a released cache frees its KV at once; a layer built directly joins its group.
  • Decode graphs: the graph key uses the bucket and the cache signature carries a growth epoch, so a growth re-captures once per bucket instead of being refused as "cache moved"; the previous bucket's graph is dropped.
  • Kept cache: reused across calls when its capacity is at most max(2x the new call's need, that call's own minimum bucket), so repeated short calls do not re-capture; its limit is raised to the new call's (5.x _prepare_static_cache hook, 4.57 _get_cache wrapper).

Results

Kaggle T4, fp16, decode graphs on, greedy, max_new_tokens 512 / 3800 with replies that stop at the chat EOS, tokens equal to StaticCache on every row, 0 recompiles, 0 refusals:

torch / transformers Model, bsz Tokens of budget StaticCache ms/token Growable ms/token KV MiB static / growable
2.14.1 / 5.17.0 Qwen3-0.6B, 4 (after a 3800 call) 512 of 512 51.8 21.2 1673 / 448
2.14.1 / 5.17.0 Qwen3-0.6B, 4 1139 of 3800 52.1 32.4 1673 / 896
2.14.1 / 5.17.0 Llama-3.2-1B, 4 189 of 3800 44.4 16.1 481 / 32
2.14.1 / 5.17.0 gemma-3-1b, 4 180 of 3800 18.3 15.8 208 / 96
2.10.0 / 4.57.6 Llama-3.2-1B, 4 181 of 3800 44.2 16.1 481 / 32
2.10.0 / 4.57.6 gemma-3-1b, 4 180 of 3800 27.6 22.8 208 / 96

Colab L4 (bf16): Qwen3-0.6B bsz 1, 845 of 3800 tokens: 16.1 vs 9.0 ms/token, KV 418 vs 112 MiB; 4-bit, 737 tokens: 13.8 vs 6.9. A call that runs to its full budget ends in the same final bucket as the limit, so it costs the same as StaticCache (Qwen3-0.6B bsz 4, 3800 of 3800: 56.1 vs 56.1).

Default-on check (Kaggle T4, torch 2.14.1, transformers 5.17.0, graphs on, 2 repeats; tokens equal on every row): never slower beyond noise, e.g. Qwen3-0.6B bsz 4 early stop 33.8 -> 21.2 ms/token (KV 906 -> 448 MiB), Llama-3.2-1B bsz 4 36.4 -> 22.2 (KV 262 -> 32 MiB), Qwen3-0.6B bsz 1 full 2048 budget 17.1 -> 16.5. A short call after a long one adds 0 captures. Cost: about 20 to 190 MiB more reserved (one graph pool per bucket) and one capture plus one compiled mask builder per bucket. Split over 2 x T4 and on L4 with flex decode, growable vs static is at parity. AMD gfx1151 (ROCm): the growable and generic decode graph suites pass (90 / 90).

Tests

tests/test_growable_kv_cache.py (12 tests, CPU host stand-in): tokens equal to StaticCache for llama, a left-padded batch of 2 and gemma3 with sliding + full layers; captures per bucket with no refusals; a short call after a long one replays the kept graph; early EOS allocates one bucket; rows equal across bucket growths; the compiled update is fullgraph with one graph per bucket; no growth inside a capture; a stale host counter (updates that skip it, as a compiled update or a replay would) and a prepare hook already owned by another wrapper still grow correctly. They pass on transformers 4.57.6 and 5.22.1, and on GPU with torch 2.14.1 / transformers 5.17.0 and torch 2.10.0 / transformers 4.57.6. With the flag off the existing decode-graph suites give the same results before and after.

Not covered: the Llama-path KV buffers (_decode_graphs.py) and the per-model copies are unchanged; the attention still reads up to 2x the written length inside a bucket.

Each one-token decode step of unsloth_base_fast_generate replays a CUDA graph of the
model's eager forward when decode graphs are enabled (RL rollouts, Studio,
UNSLOTH_DECODE_CUDA_GRAPHS=1) on NVIDIA CUDA. Static attention layers only (sliding
layers until their window fills); recurrent, offloaded and dynamic caches stay eager.
A capture that syncs the host or a first replay that differs from the eager step
refuses the key. UNSLOTH_DECODE_GENERIC_GRAPHS=0 turns it off.
…cord capture errors; VALIDATE_ALL debug mode
…/ strides of static buffers, ambient autocast cache
…r-key decisions, prefill never graphed, setup failures run eagerly, validation leaves the eager step's cache rows

[skip ci]
…ps the model's own forward (mixed-precision autocast) or GRPO wraps it; device hooks stay eager
…erence calls

Plain generate() on FastModel models now enters generate_scope(), as the llama path and Studio do,
and decides one plan per call (plan()): eager when graphs are not wanted, the batch is over the
limit, the call is too short to win back a capture (unless a kept graph of its batch replays from
the first step), or free memory is low. An out-of-memory graphed call is redone once eagerly
without the graph wrapper, from the call's starting RNG and a fresh cache; calls with a streamer,
caller cache, stopping criteria or logits processors re-raise as before.

After an inference-mode call the graph and its StaticCache stay for the next call of the same
batch (transformers 5.x: handed back from _prepare_static_cache; 4.x: model._cache). A returned
or caller-owned cache, another batch, a cache over twice the call's length, a training forward,
for_training() and release_for_training() drop them.

call_plan() exposes the call's plan to per-call policies (the LoRA fold threshold), and
weights_changed() bumps an epoch both graph fingerprints carry, for in-place weight rewrites.
A flex BlockMask argument replays when its builder publishes _unsloth_graph_closure; any other
BlockMask stays refused.
… (Muse-Glimmer, Muse-Spark, Kimi-K2.5)

Their forward zeroes image / video (/ audio) placeholder ids with a boolean index assignment, a host
sync that no capture can hold, so every decode step stayed eager. A one-token text decode step now
gets the inputs_embeds the forward would compute (same masked ids, same embedding module) before the
graph; the first replay still validates bitwise against the eager step.
…s, kept sliding caches

Sliding windows: only a step that would fill a window part way stays eager; the graph key carries
each sliding window's filling / full state, and a full window's rows are restored between the
validation replay and the eager step (a roll is not idempotent).

_GraphDecodeSteps enters unsloth_zoo.decode_graph_state.graph_generate() for the graphed call and
graph_decode_step() for each one-token step (no-op without the module), so zoo picks the same
graph-safe kernels for the eager warm-up, the capture and every eager step.

A kept cache is matched by the length it was built for: sliding layers are capped at their window,
so the layers' own lengths under-state an all-sliding cache and it was never reused.
…device hook

A bitsandbytes model placed on a card other than cuda:0 gets accelerate's AlignDevicesHook with
force_hooks (vision.py _attach_bnb_multidevice_hooks): an instance forward plus _hf_hook, which
wanted() refused, so a model on cuda:1 never decoded through graphs. A root hook that only aligns
tensors to the model's own device (AlignDevicesHook, no offload, no weights map, execution device =
model.device) is a no-op there and runs in the eager step too, so it stays eligible; other hooks,
offload and devices elsewhere stay eager. A decode step whose inputs sit on another card than the
weights is refused (the hook would copy across cards inside the graph).
…e step's device; named refusals

The inputs_embeds computed before the graph for Muse-Glimmer style decoders are now looked up under
no_grad, detached and moved to the decode step's device, so a trainable or host-side (offloaded or
hooked) embedding can no longer make the argument check refuse every step.

A refused argument now says why and which one: 'tensor argument requires grad (<name>)' or
'tensor argument on <device> (<name>)', so a GPU log explains itself.
…he graph

offload_embedding keeps the input embedding in host RAM, so every decode step was refused as not on one CUDA device. When that embedding (hooked by Unsloth, not shared with the output head) holds the only off-device parameters, its rows are looked up eagerly before the graph and passed as inputs_embeds, and its parameters are exempt from the device check while staying in the fingerprint by identity. Any other off-device parameter is still refused.
… cards

A model split over several cards (Unsloth's balanced placement, Muse-Glimmer on two T4s) records one graph per card; the cross-card copies run eagerly between replays, so cards without peer access work. UNSLOTH_DECODE_MULTIDEVICE_GRAPHS=0 turns it off. An input embedding offloaded to the host does not count as another device.
…xception handler

The handler's traceback keeps the failed call's frames, so its StaticCache and graph buffers stayed allocated through the eager redo. [skip ci]
… block's card

With tied embeddings Unsloth's split puts the embedding / lm_head (model.device) on the last card while the root hook moves inputs to the first, so 16-bit gemma-3-1b / Qwen3-0.6B splits stayed eager. [skip ci]
…ing a call whose key moves every step

transformers rolls a full static sliding window with an index built by torch.tensor(..., device=...), a
host-to-device copy a CUDA graph capture refuses, so every step past the window (512 tokens on Gemma 3 / 4)
decoded eagerly. The warm-up and recording now run that branch op for op on an index made outside the
capture (only when the installed update matches it).

A call whose graph key changes every step captured every step and never replayed (an eager warm-up plus a
recording per token, graphs piling up until the card ran out of memory). After four captures in a row
without a replay the rest of the call decodes eagerly and its graphs are freed. An out-of-memory capture
frees the call's graphs and stops capturing for that call only.

[skip ci]
…er-passed type ids

TRL's GRPO passes the processor's mm_token_type_ids / token_type_ids to generate(). They reached every decode
step at full length, one column longer per step, so every step had a new graph key and nothing replayed
(Gemma 4 E2B GRPO on T4: 1018 captures, 0 replays). Gemma 3 / 4 read them only to build the attention masks,
which they skip when the step's masks come prebuilt; with prebuilt masks the graphed step now gets the last
q_len columns, as transformers slices them.

[skip ci]
…t buckets by the call's own need

BLOOM (transformers 5.x) sizes its padded mask and ALiBi by get_max_length(), the full limit; the layer -> group
-> layer cycle kept a released cache's KV alive until a gc pass; a kept bucket was compared against transformers'
longest-ever limit instead of the new call's need.
# Conflicts:
#	unsloth/models/_generic_decode_graphs.py
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 10, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 10, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 10, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 10, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 10, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 91cc4764d0

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Base automatically changed from dec-generic-graphs to main November 10, 2026 08:45
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 10, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 42629b09ea

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

super().__init__(max_cache_len = max_cache_len)
self.capacity = None
self.cumulative_length_int = 0
self.group = group if group is not None else _Group()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Register directly constructed layers in their growth group

When the exported GrowableLayer is instantiated directly with the default group=None, its new group has no members. Consequently, _plan() calls _grow_group() without ever growing this layer: get_mask_sizes() initially returns (None, 0), and after lazy initialization, an update crossing the first bucket writes beyond the allocated buffers. make_growable() registers layers externally, but direct construction requires undocumented manipulation of group.members (as the compiled-update test currently does). Register the layer during construction and remove the duplicate registration from the factory.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in a7639ac: GrowableLayer registers itself in its group in init (the factory no longer appends it), so a directly built layer grows past its first bucket. Added test_a_directly_built_layer_grows_past_its_first_bucket; it fails on the previous head.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: a7639acc05

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit a877612 into main Nov 10, 2026
@danielhanchen
danielhanchen deleted the growable-kv-cache branch November 10, 2026 14:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant