Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

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

Daniel Hana87761278c1b
diff --git a/tests/test_generic_decode_graphs_default.py b/tests/test_generic_decode_graphs_default.py
index 00693e6c815..e61d17a0291 100644
--- a/tests/test_generic_decode_graphs_default.py
+++ b/tests/test_generic_decode_graphs_default.py
@@ -219,6 +219,8 @@ def test_kept_graph_hook_is_inert_in_a_compiled_training_forward(host, llama):
def test_a_short_call_after_a_long_one_replays_the_kept_graph(host, llama, monkeypatch):
# transformers 5.x sizes every later cache to the longest call so far (_previous_max_cache_length), so a short
# call after a long one gets a cache as long as the kept one: it must reuse it, not re-capture every call.
+ # (StaticCache only: a growable bucket is judged against the call's own need, test_growable_kv_cache.)
+ monkeypatch.setenv("UNSLOTH_GROWABLE_KV", "0")
_gen(llama, new = 40)
s1 = _stats(llama)
assert s1["captures"] == 1 and GG.kept_cache(llama) is not None, s1
diff --git a/tests/test_growable_kv_cache.py b/tests/test_growable_kv_cache.py
new file mode 100644
index 00000000000..9fc9e14d89b
--- /dev/null
+++ b/tests/test_growable_kv_cache.py
@@ -0,0 +1,505 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""Growable KV cache (on by default, UNSLOTH_GROWABLE_KV=0 turns it off), checked on the host via test_generic_decode_graphs' stand-in graphs."""
+
+import contextlib
+import functools
+import os
+import sys
+import types
+import weakref
+
+import pytest
+import torch
+
+import unsloth # noqa: F401 (must precede transformers)
+
+import unsloth.models._decode_graphs as G
+import unsloth.models._generic_decode_graphs as GG
+import unsloth.models._kv_cache as KV
+from unsloth.models import vision
+
+from transformers import AutoModelForCausalLM, StaticCache
+from transformers import cache_utils
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from test_generic_decode_graphs import GEMMA3, LLAMA, _FakeGraph # noqa: E402
+from test_generic_decode_graphs_default import _DefaultHost # noqa: E402
+
+ENV = "UNSLOTH_DECODE_CUDA_GRAPHS"
+_MASK_TAKES_POSITIONS = (
+ "cache_position" in cache_utils.StaticLayer.get_mask_sizes.__code__.co_varnames[:2]
+)
+
+
+def host(monkeypatch):
+ backend = type("Host", (_DefaultHost,), {"graphs": []})
+ monkeypatch.setattr(GG, "_BACKEND", backend)
+ monkeypatch.setattr(G, "ENABLED", None)
+ monkeypatch.setattr(G, "_DEFAULT_OK", True)
+ monkeypatch.setattr(G, "_STUDIO_DEFAULT_OK", True)
+ for name in (ENV, "UNSLOTH_DECODE_GENERIC_GRAPHS", "UNSLOTH_DECODE_GENERIC_GRAPHS_KEEP"):
+ monkeypatch.delenv(name, raising = False)
+ monkeypatch.setenv("UNSLOTH_GROWABLE_KV_MIN", "16")
+ # As a real replay, which runs no Python: a growable layer must not grow while a step replays (the stand-in
+ # re-runs the step to fill the outputs). Every growth is logged with whether a capture or replay was running.
+ backend.growths = []
+ replaying = [False]
+ real_replay = _FakeGraph.replay
+
+ def replay(self):
+ replaying[0] = True
+ try:
+ with getattr(KV, "frozen", contextlib.nullcontext)():
+ return real_replay(self)
+ finally:
+ replaying[0] = False
+
+ monkeypatch.setattr(_FakeGraph, "replay", replay)
+ real_grow = KV._grow_group
+
+ def grow(group, size):
+ backend.growths.append((size, backend.recording, replaying[0]))
+ return real_grow(group, size)
+
+ monkeypatch.setattr(KV, "_grow_group", grow)
+ return backend
+
+
+def _load(name, **kwargs):
+ torch.manual_seed(0)
+ model = AutoModelForCausalLM.from_pretrained(name, dtype = torch.float32, **kwargs).eval()
+ model._old_generate = model.generate
+ model.generate = types.MethodType(vision.unsloth_base_fast_generate, model)
+ return model
+
+
+def llama():
+ return _load(LLAMA)
+
+
+def gemma3():
+ # A short window, so a short generation runs past it; one full-attention layer to grow.
+ return _load(GEMMA3, sliding_window = 8, layer_types = ["sliding_attention", "full_attention"])
+
+
+def _ids(
+ bsz = 1,
+ length = 6,
+ pad = 0,
+):
+ g = torch.Generator().manual_seed(1)
+ ids = torch.randint(3, 1000, (bsz, length), generator = g)
+ mask = torch.ones_like(ids)
+ if pad:
+ ids[0, :pad] = 0
+ mask[0, :pad] = 0
+ return ids, mask
+
+
+def _gen(
+ model,
+ new = 10,
+ bsz = 1,
+ pad = 0,
+ length = 6,
+ **kwargs,
+):
+ ids, mask = _ids(bsz, length = length, pad = pad)
+ kwargs.setdefault("min_new_tokens", new)
+ with torch.inference_mode():
+ return model.generate(
+ input_ids = ids,
+ attention_mask = mask,
+ max_new_tokens = new,
+ do_sample = False,
+ pad_token_id = 0,
+ **kwargs,
+ )
+
+
+def _both(model, monkeypatch, **kwargs):
+ """Tokens with a plain StaticCache, then with the growable one (same graph path)."""
+ monkeypatch.setenv("UNSLOTH_GROWABLE_KV", "0")
+ GG.release(model)
+ static = _gen(model, **kwargs)
+ GG.release(model)
+ model.__dict__.pop(GG._ATTR, None)
+ monkeypatch.setenv("UNSLOTH_GROWABLE_KV", "1")
+ grown = _gen(model, **kwargs)
+ return static, grown
+
+
+def _stats(model):
+ return GG.stats(model) or {"captures": 0, "replays": 0, "graphs": 0, "refusals": {}}
+
+
+def _full_layers(cache):
+ return [layer for layer in cache.layers if type(layer) is KV.GrowableLayer]
+
+
+def test_buckets():
+ os.environ.pop("UNSLOTH_GROWABLE_KV_MIN", None)
+ assert (
+ KV.bucket(1, 10_000) == 256
+ and KV.bucket(256, 10_000) == 256
+ and KV.bucket(257, 10_000) == 512
+ )
+ assert KV.bucket(3000, 2100) == 2100 # clamped to the limit generate sized for
+
+
+def test_layer_rows_match_a_static_cache_across_growth(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_GROWABLE_KV_MIN", "16")
+ config = AutoModelForCausalLM.from_pretrained(LLAMA).config
+ limit = 70
+ static = StaticCache(config = config, max_cache_len = limit)
+ grown = KV.make_growable(StaticCache(config = config, max_cache_len = limit))
+ assert len(_full_layers(grown)) == config.num_hidden_layers
+ g = torch.Generator().manual_seed(0)
+ heads, dim = config.num_key_value_heads, config.hidden_size // config.num_attention_heads
+ written, caps = 0, []
+ for q in [5] + [1] * 60:
+ k = torch.randn(2, heads, q, dim, generator = g)
+ v = torch.randn(2, heads, q, dim, generator = g)
+ kwargs = {"cache_position": torch.arange(written, written + q)}
+ size = grown.layers[0].get_mask_sizes(
+ kwargs["cache_position"] if _MASK_TAKES_POSITIONS else q
+ )[0]
+ assert size >= written + q
+ for idx in range(config.num_hidden_layers):
+ a = static.update(k, v, idx, kwargs)
+ b = grown.update(k, v, idx, kwargs)
+ assert b[0].shape[-2] == grown.layers[idx].capacity
+ assert torch.equal(a[0][:, :, : written + q], b[0][:, :, : written + q])
+ assert torch.equal(a[1][:, :, : written + q], b[1][:, :, : written + q])
+ written += q
+ caps.append(grown.layers[0].capacity)
+ assert sorted(set(caps)) == [16, 32, 64, 70], caps
+ assert all(layer.cumulative_length_int == written for layer in _full_layers(grown))
+ assert grown.layers[0].max_cache_len == limit and grown.layers[0].get_max_cache_shape() == limit
+
+
+def test_generate_matches_static_and_recaptures_once_per_bucket(host, llama, monkeypatch):
+ static, grown = _both(llama, monkeypatch, new = 40)
+ assert torch.equal(static, grown)
+ s = _stats(llama)
+ cache = GG.kept_cache(llama)
+ assert KV.is_growable(cache)
+ # prompt 6 + 39: buckets 16 -> 32 -> 45 (the limit), one capture per bucket.
+ assert KV.capacity(cache) == 45, KV.capacity(cache)
+ assert s["captures"] == 3 and s["graphs"] == 1 and not s["refusals"], s
+
+
+def test_early_stop_allocates_only_its_bucket(host, llama, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_GROWABLE_KV", "1")
+ first = _gen(llama, new = 8)
+ stop = int(first[0, 6 + 4])
+ GG.release(llama)
+ llama.__dict__.pop(GG._ATTR, None)
+ llama.__dict__.pop("_cache", None)
+ out = _gen(llama, new = 500, min_new_tokens = 0, eos_token_id = stop)
+ assert out.shape[1] <= 6 + 5, out.shape
+ cache = GG.kept_cache(llama)
+ assert KV.is_growable(cache)
+ assert KV.capacity(cache) == 16
+ assert all(layer.keys.shape[-2] == 16 for layer in _full_layers(cache))
+ assert _full_layers(cache)[0].max_cache_len >= 505
+
+
+def test_kept_cache_grows_for_a_longer_call(host, llama, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_GROWABLE_KV", "1")
+ _gen(llama, new = 10)
+ kept = GG.kept_cache(llama)
+ assert KV.capacity(kept) <= 16
+ before = GG.PLANS["reused kept cache"]
+ longer = _gen(llama, new = 30)
+ if hasattr(
+ llama, "_prepare_static_cache"
+ ): # 5.x plans the call's cache; 4.x reuses model._cache itself
+ assert GG.PLANS["reused kept cache"] == before + 1
+ assert GG.kept_cache(llama) is kept and KV.capacity(kept) == 35
+ monkeypatch.setenv("UNSLOTH_GROWABLE_KV", "0")
+ GG.release(llama)
+ llama.__dict__.pop(GG._ATTR, None)
+ assert torch.equal(longer, _gen(llama, new = 30))
+
+
+def test_sliding_layers_stay_transformers_own(host, gemma3, monkeypatch):
+ static, grown = _both(gemma3, monkeypatch, new = 30)
+ assert torch.equal(static, grown)
+ cache = GG.kept_cache(gemma3)
+ kinds = {type(layer).__name__ for layer in cache.layers}
+ assert "GrowableLayer" in kinds and kinds - {"GrowableLayer"}, kinds
+ assert all(
+ layer.keys.shape[-2] == 8 for layer in cache.layers if type(layer) is not KV.GrowableLayer
+ )
+
+
+def test_left_padding(host, llama, monkeypatch):
+ static, grown = _both(llama, monkeypatch, new = 30, bsz = 2, pad = 2)
+ assert torch.equal(static, grown)
+
+
+def test_a_directly_built_layer_grows_past_its_first_bucket(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_GROWABLE_KV_MIN", "16")
+ layer = KV.GrowableLayer(max_cache_len = 64)
+ k = torch.randn(1, 2, 12, 8)
+ layer.update(k, k, {"cache_position": torch.arange(12)})
+ k = torch.randn(1, 2, 8, 8)
+ layer.update(k, k, {"cache_position": torch.arange(12, 20)})
+ assert layer.capacity == 32 and layer.keys.shape[-2] == 32
+ assert torch.equal(layer.keys[:, :, 12:20], k)
+
+
+def test_compiled_update_is_one_graph_per_bucket(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_GROWABLE_KV_MIN", "16")
+ torch._logging.set_logs(graph_breaks = True, recompiles = True)
+ from torch._dynamo.testing import CompileCounter
+
+ torch._dynamo.reset()
+ layer = KV.GrowableLayer(max_cache_len = 64)
+ k = torch.randn(1, 2, 4, 8)
+ layer.update(
+ k, k, {"cache_position": torch.arange(4)}
+ ) # eager prefill: allocates the first bucket
+ counter = CompileCounter()
+
+ @torch.compile(backend = counter, fullgraph = True)
+ def step(layer, k, pos):
+ keys, _ = layer.update(k, k, {"cache_position": pos})
+ return keys.sum()
+
+ written = 4
+ for _ in range(6):
+ k1 = torch.randn(1, 2, 1, 8)
+ step(layer, k1, torch.tensor([written]))
+ layer.cumulative_length_int += (
+ 1 # the decode graph path advances the host counter outside the graph
+ )
+ written += 1
+ assert counter.frame_count == 1, counter.frame_count
+ layer.get_mask_sizes(
+ torch.arange(written, written + 10) if _MASK_TAKES_POSITIONS else 10
+ ) # eager growth
+ assert layer.capacity == 32
+ step(layer, torch.randn(1, 2, 1, 8), torch.tensor([written]))
+ assert counter.frame_count == 2, counter.frame_count
+ torch._dynamo.reset()
+
+
+def test_a_short_call_after_a_long_one_replays_the_kept_bucket(host, llama, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_GROWABLE_KV", "1")
+ _gen(llama, new = 40)
+ kept = GG.kept_cache(llama)
+ assert KV.is_growable(kept) and _stats(llama)["captures"] == 3
+ monkeypatch.setattr(
+ llama, "_previous_max_cache_length", GG._kept_len(llama.__dict__[GG._ATTR]), raising = False
+ )
+ s2 = _stats(llama)
+ # 6 + 20 - 1 = 25 slots needed: the 45-slot bucket is within 2x, so its graphs replay.
+ outs = [_gen(llama, new = 20) for _ in range(2)]
+ s3 = _stats(llama)
+ assert torch.equal(outs[0], outs[1])
+ assert GG.kept_cache(llama) is kept and KV.capacity(kept) == 45
+ assert s3["captures"] == s2["captures"], (s2, s3)
+ assert s3["replays"] - s2["replays"] == 2 * 19, (s2, s3)
+ # 15 slots needed: judged against this call, not transformers' longest-ever limit, so a smaller cache.
+ _gen(llama, new = 10)
+ assert GG.kept_cache(llama) is not kept and KV.capacity(GG.kept_cache(llama)) <= 30
+
+
+def _no_growth_in_graphs(host):
+ assert host.growths and not [g for g in host.growths if g[1] or g[2]], host.growths
+
+
+def test_no_growth_inside_a_capture(host, llama, monkeypatch):
+ # A 15-token prompt fills its 16-slot bucket on the first captured step: growing inside the capture is a bug.
+ static, grown = _both(llama, monkeypatch, new = 30, length = 15)
+ assert torch.equal(static, grown)
+ _no_growth_in_graphs(host)
+ # That first step runs eagerly instead (a graph captured there could never replay); the next one captures.
+ assert _stats(llama)["refusals"] == {"kv cache fills its bucket": 1}, _stats(llama)
+ assert KV.capacity(GG.kept_cache(llama)) == 44
+
+
+def test_kept_cache_grows_from_a_clamped_bucket(host, llama, monkeypatch):
+ # The first call's bucket is clamped to its limit (15); the longer call grows it to 16, a step that fills it.
+ monkeypatch.setenv("UNSLOTH_GROWABLE_KV", "1")
+ _gen(llama, new = 10)
+ kept = GG.kept_cache(llama)
+ longer = _gen(llama, new = 30)
+ assert GG.kept_cache(llama) is kept and KV.capacity(kept) == 35
+ _no_growth_in_graphs(host)
+ monkeypatch.setenv("UNSLOTH_GROWABLE_KV", "0")
+ GG.release(llama)
+ llama.__dict__.pop(GG._ATTR, None)
+ llama.__dict__.pop("_cache", None)
+ assert torch.equal(longer, _gen(llama, new = 30))
+
+
+def test_stale_host_counter_and_a_wrapped_prepare(host, llama, monkeypatch):
+ # A stale host counter and a foreign prepare_inputs wrapper: growth must follow generate's own lengths.
+ real_update = KV.GrowableLayer.update
+
+ def compiled_like(self, key_states, value_states, *args, **kwargs):
+ if key_states.shape[-2] != 1:
+ return real_update(self, key_states, value_states, *args, **kwargs)
+ return KV._StaticLayer.update(self, key_states, value_states, *args, **kwargs)
+
+ monkeypatch.setattr(KV.GrowableLayer, "update", compiled_like)
+ inner = llama.prepare_inputs_for_generation
+ wrapper = functools.wraps(inner)(lambda *a, **k: inner(*a, **k))
+ llama.prepare_inputs_for_generation = wrapper
+ static, grown = _both(llama, monkeypatch, new = 40)
+ assert torch.equal(static, grown)
+ cache = GG.kept_cache(llama)
+ assert KV.capacity(cache) == 45, KV.capacity(cache)
+ assert llama.__dict__.get("prepare_inputs_for_generation") is wrapper
+
+
+def _gen_embeds(model, new, length):
+ ids, mask = _ids(1, length = length)
+ with torch.inference_mode():
+ embeds = model.get_input_embeddings()(ids)
+ return model.generate(
+ inputs_embeds = embeds,
+ attention_mask = mask,
+ max_new_tokens = new,
+ min_new_tokens = new,
+ do_sample = False,
+ pad_token_id = 0,
+ )
+
+
+def test_inputs_embeds_prompt_that_fills_its_bucket(host, llama, monkeypatch):
+ # inputs_embeds-only prompt (16 = first bucket) must still count, or decode writes past the bucket.
+ monkeypatch.setenv("UNSLOTH_GROWABLE_KV", "0")
+ static = _gen_embeds(llama, 10, 16)
+ GG.release(llama)
+ llama.__dict__.pop(GG._ATTR, None)
+ monkeypatch.setenv("UNSLOTH_GROWABLE_KV", "1")
+ grown = _gen_embeds(llama, 10, 16)
+ assert torch.equal(static, grown)
+ assert KV.capacity(GG.kept_cache(llama)) == 25
+
+
+def test_kept_cache_with_short_sliding_layers_is_not_reused(host, monkeypatch):
+ # Sliding layers sized min(window 32, limit 15) = 15 must not be reused by a longer call.
+ model = _load(GEMMA3, sliding_window = 32, layer_types = ["sliding_attention", "full_attention"])
+ monkeypatch.setenv("UNSLOTH_GROWABLE_KV", "1")
+ _gen(model, new = 10)
+ short = GG.kept_cache(model)
+ assert short is not None
+ assert KV.short_layers(short, 45) and not KV.short_layers(short, 15)
+ grown = _gen(model, new = 40)
+ assert GG.kept_cache(model) is not short
+ monkeypatch.setenv("UNSLOTH_GROWABLE_KV", "0")
+ GG.release(model)
+ model.__dict__.pop(GG._ATTR, None)
+ assert torch.equal(grown, _gen(model, new = 40))
+
+
+def _growable_cache(model, limit = 64):
+ cache = StaticCache(config = model.config, max_cache_len = limit)
+ KV.make_growable(cache)
+ assert KV.is_growable(cache)
+ return cache
+
+
[email protected]("version", ["5.x", "4.x"])
+def test_reserve_counts_tokens_held_only_by_the_cache(llama, monkeypatch, version):
+ # The host counter must match the device write position across 4.x / 5.x step inputs.
+ monkeypatch.setenv("UNSLOTH_GROWABLE_KV_MIN", "16")
+
+ def step(
+ cache,
+ call,
+ ids_len,
+ q,
+ mask_len = None,
+ embeds = None,
+ ):
+ bound = (
+ {"next_sequence_length": q} if version == "5.x" else {"cache_position": torch.arange(q)}
+ )
+ if mask_len is not None:
+ bound["attention_mask"] = torch.ones(1, mask_len, dtype = torch.long)
+ if embeds is not None:
+ bound["inputs_embeds"] = torch.zeros(1, embeds, 4)
+ GG._reserve_step(cache, torch.zeros(1, ids_len, dtype = torch.long), bound, call)
+ return KV.written(cache), KV.capacity(cache)
+
+ cache, call = _growable_cache(llama), {}
+ assert step(cache, call, 0, 16, embeds = 16) == (0, 16)
+ assert step(cache, call, 1, 1) == (16, 32)
+ assert step(cache, call, 5, 1) == (20, 32)
+ for mask in (True, False):
+ cache = _growable_cache(llama)
+ KV.reserve(cache, 19, written = 19)
+ call = {}
+ assert step(cache, call, 3, 3, 22 if mask else None) == (19, 32)
+ assert step(cache, call, 4, 1, 23 if mask else None) == (22, 32)
+ assert step(cache, call, 14, 1, 33 if mask else None) == (32, 64)
+ cache = _growable_cache(llama)
+ KV.reserve(cache, 19, written = 19)
+ call = {}
+ assert step(cache, call, 22, 3, 22) == (19, 32) and call["prefix"] == 0
+
+
+def test_models_sizing_masks_by_the_max_cache_shape_keep_static_cache(monkeypatch):
+ # BLOOM-style (mask / ALiBi at get_max_cache_shape()) never get growable layers.
+ class Old(torch.nn.Module):
+ def _prepare_4d_causal_attention_mask_with_cache_position(self):
+ pass
+
+ assert not KV.supports(Old())
+ assert KV.supports(_load(LLAMA))
+ # transformers 5.x BLOOM sizes its padded mask / ALiBi by past_key_values.get_max_length() (the full limit).
+ from transformers import BloomConfig, BloomForCausalLM
+
+ bloom = BloomForCausalLM(BloomConfig(vocab_size = 64, hidden_size = 16, n_layer = 2, n_head = 2))
+ KV._SUPPORTS.pop(BloomForCausalLM, None)
+ assert not KV.supports(bloom)
+
+
+def test_released_cache_frees_its_kv_without_a_gc_pass(monkeypatch):
+ # The group must not own its layers: a layer -> group -> layer cycle kept a dropped cache's KV until gc ran.
+ import gc
+ import weakref
+
+ from transformers import StaticCache
+
+ monkeypatch.setenv("UNSLOTH_GROWABLE_KV_MIN", "4")
+ cache = KV.make_growable(StaticCache(config = _load(LLAMA).config, max_cache_len = 64))
+ k = torch.zeros(1, 4, 3, 4)
+ cache.update(k, k.clone(), 0)
+ KV.reserve(cache, 20)
+ alive = weakref.ref(next(KV._members(cache)).keys)
+ gc.disable()
+ try:
+ del cache
+ assert alive() is None
+ finally:
+ gc.enable()
+
+
+def test_repeated_short_calls_after_a_long_one_keep_their_minimum_bucket(host, llama, monkeypatch):
+ # The smallest bucket (64) is over 2x a short call's need (15): judging reuse by 2x alone dropped and re-captured
+ # an equal bucket on every short call after a long one.
+ monkeypatch.setenv("UNSLOTH_GROWABLE_KV", "1")
+ monkeypatch.setenv("UNSLOTH_GROWABLE_KV_MIN", "64")
+ _gen(llama, new = 80)
+ monkeypatch.setattr(
+ llama, "_previous_max_cache_length", GG._kept_len(llama.__dict__[GG._ATTR]), raising = False
+ )
+ _gen(llama, new = 10)
+ kept = GG.kept_cache(llama)
+ before = _stats(llama)["captures"]
+ for _ in range(2):
+ _gen(llama, new = 10)
+ assert GG.kept_cache(llama) is kept and KV.capacity(kept) <= 64
+ assert _stats(llama)["captures"] == before
diff --git a/unsloth/models/_generic_decode_graphs.py b/unsloth/models/_generic_decode_graphs.py
index 875c70349ef..53dee47ba73 100644
--- a/unsloth/models/_generic_decode_graphs.py
+++ b/unsloth/models/_generic_decode_graphs.py
@@ -23,6 +23,7 @@ import contextlib
import warnings
import copy
import functools
+import inspect
import threading
import os
import traceback
@@ -31,6 +32,7 @@ import weakref
import torch
from . import _decode_graphs as G
+from . import _kv_cache as KV
__all__ = [
"wanted",
@@ -403,7 +405,11 @@ def _static_layer_types():
from transformers import cache_utils
except Exception:
return (), ()
- full = tuple(t for t in (getattr(cache_utils, "StaticLayer", None),) if isinstance(t, type))
+ from ._kv_cache import GrowableLayer
+
+ full = tuple(
+ t for t in (getattr(cache_utils, "StaticLayer", None), GrowableLayer) if isinstance(t, type)
+ )
sliding = tuple(
t
for t in (
@@ -509,7 +515,11 @@ def plan(model, args, kwargs, input_ids):
previous = getattr(model, "_previous_max_cache_length", -1)
if type(previous) is int:
need = max(need, previous)
- kept = length is not None and need <= length <= _KEEP_MAX_RATIO * max(need, 1)
+ if KV.is_growable(state.kept):
+ length = KV.capacity(state.kept)
+ kept = length is not None and length <= _bucket_budget(max_len - 1, need)
+ else:
+ kept = length is not None and need <= length <= _KEEP_MAX_RATIO * max(need, 1)
if state is not None and state.kept is not None and not kept:
state.clear()
if bsz > MAX_BSZ:
@@ -883,20 +893,87 @@ def release(model):
state.invalidate()
-def _kept_compatible(state, batch_size, max_cache_len, offloading):
+def _bucket_budget(need, limit):
+ # 2x the call's need, but never below the smallest bucket a fresh cache would get: else repeated short calls
+ # after a long one would drop and re-capture an equal bucket every call.
+ return max(_KEEP_MAX_RATIO * max(need, 1), KV.bucket(max(need, 1), max(limit, need, 1)))
+
+
+def _kept_compatible(
+ state,
+ batch_size,
+ max_cache_len,
+ offloading,
+ need = None,
+):
kept = state.kept
if kept is None:
return False
- length = _kept_len(state)
- if length is None:
- return False
+ if KV.is_growable(kept):
+ length = KV.capacity(kept)
+ # A growable bucket is judged against this call's need, not transformers' longest-ever limit.
+ need = max_cache_len if need is None else need
+ fits = (
+ length is not None
+ and length <= _bucket_budget(int(need), int(max_cache_len))
+ and not KV.short_layers(kept, max_cache_len)
+ )
+ else:
+ length = _kept_len(state)
+ fits = length is not None and max_cache_len <= length <= _KEEP_MAX_RATIO * max(
+ int(max_cache_len), 1
+ )
return (
- state.kept_bsz == batch_size
+ fits
+ and state.kept_bsz == batch_size
and bool(getattr(kept, "offloading", False)) == bool(offloading)
- and max_cache_len <= length <= _KEEP_MAX_RATIO * max(int(max_cache_len), 1)
)
+def _reserve_step(
+ cache,
+ input_ids,
+ bound,
+ call = None,
+):
+ """Grows a growable cache to hold this generate step. `call` tracks tokens in the cache but not in input_ids
+ (inputs_embeds prompt, or a returned cache continued with only new tokens)."""
+ call = {} if call is None else call
+ total = (
+ input_ids.shape[-1] if isinstance(input_ids, torch.Tensor) and input_ids.dim() >= 2 else 0
+ )
+ embeds = bound.get("inputs_embeds")
+ q = bound.get("next_sequence_length")
+ if type(q) is not int:
+ position = bound.get("cache_position")
+ q = (
+ int(position.shape[0])
+ if isinstance(position, torch.Tensor) and position.dim() == 1
+ else None
+ )
+ written = KV.written(cache)
+ if q is None and written == 0:
+ q = total
+ if "prefix" not in call:
+ prefix = 0
+ if isinstance(embeds, torch.Tensor) and embeds.dim() >= 3 and total == 0:
+ total = q = prefix = embeds.shape[1]
+ elif written > 0 and q is not None and q == total:
+ # A cache passed back with only the new tokens: its prefix stays in the cache, not in input_ids.
+ prefix = written
+ total += prefix
+ call["prefix"] = prefix
+ elif total > 0:
+ total += call["prefix"]
+ mask = bound.get("attention_mask")
+ if isinstance(mask, torch.Tensor) and mask.dim() == 2 and total > 0:
+ total = max(total, mask.shape[-1])
+ if total <= 0 or q is None or q > total:
+ KV.reserve(cache, max(total, written + 1))
+ return
+ KV.reserve(cache, total, written = total - q)
+
+
class reuse_kept_cache:
"""One graphed generate() call: transformers builds this call's StaticCache, unless a compatible kept
one exists, which is reset and handed back (same tensors, so the kept graphs replay). 5.x builds a new
@@ -906,6 +983,25 @@ class reuse_kept_cache:
def __init__(self, model):
self.model = model
self.prepare = None
+ self.get_cache = None
+ self.prepare_inputs = None
+ self.prepare_inputs_saved = None
+ self.prepare_signature = None
+ self.reserve_call = {}
+
+ def _prepare_inputs(self, input_ids, *args, **kwargs):
+ # Grow eagerly before the (possibly compiled) mask is built; re-sync host counters from generate's lengths.
+ try:
+ bound = self.prepare_signature.bind_partial(input_ids, *args, **kwargs).arguments
+ except (TypeError, ValueError, AttributeError):
+ bound = dict(kwargs)
+ extra = bound.get("kwargs")
+ if isinstance(extra, dict):
+ bound = {**extra, **bound}
+ cache = bound.get("past_key_values")
+ if KV.is_growable(cache):
+ _reserve_step(cache, input_ids, bound, self.reserve_call)
+ return self.prepare_inputs(input_ids, *args, **kwargs)
def _prepare(self, *args, **kwargs):
model = self.model
@@ -926,16 +1022,27 @@ class reuse_kept_cache:
and prefill_chunk is None
and not getattr(model.config, "is_encoder_decoder", False)
and _kept_compatible(
- state, batch_size, effective, "offloaded" in str(cache_implementation)
+ state,
+ batch_size,
+ effective,
+ "offloaded" in str(cache_implementation),
+ need = max_cache_len,
)
):
cache = state.kept
cache.reset()
+ KV.raise_limit(cache, effective)
PLANS["reused kept cache"] += 1
else:
if state.kept is not None:
state.clear()
cache = self.prepare(*args, **kwargs)
+ if (
+ KV.enabled()
+ and not getattr(model.config, "is_encoder_decoder", False)
+ and KV.supports(model)
+ ):
+ KV.make_growable(cache)
model.__dict__["_unsloth_generic_call_cache"] = cache
if type(effective) is int:
model.__dict__["_unsloth_generic_call_len"] = (
@@ -943,11 +1050,59 @@ class reuse_kept_cache:
)
return cache
+ def _get_cache(self, cache_implementation, batch_size, max_cache_len, *args, **kwargs):
+ # transformers 4.x reuses model._cache unless too short, so a kept growable cache gets this call's limit first.
+ model = self.model
+ kept = model.__dict__.get("_cache")
+ if (
+ KV.is_growable(kept)
+ and type(max_cache_len) is int
+ and not KV.short_layers(kept, max_cache_len)
+ ):
+ # Sliding layers too short: keep the old limit so transformers builds a new cache.
+ KV.raise_limit(kept, max_cache_len)
+ cache = self.get_cache(cache_implementation, batch_size, max_cache_len, *args, **kwargs)
+ if (
+ cache is not kept
+ and not getattr(model.config, "is_encoder_decoder", False)
+ and KV.supports(model)
+ ):
+ KV.make_growable(cache)
+ return cache
+
def __enter__(self):
model = self.model
+ self.reserve_call = {}
+ self.get_cache = None
+ self.prepare_inputs = None
+ self.prepare_inputs_saved = None
+ prepare = getattr(model, "prepare_inputs_for_generation", None)
+ if KV.enabled() and prepare is not None:
+ self.prepare_inputs = prepare
+ self.prepare_inputs_saved = (
+ "prepare_inputs_for_generation" in model.__dict__,
+ model.__dict__.get("prepare_inputs_for_generation"),
+ )
+ try:
+ self.prepare_signature = inspect.signature(prepare)
+ except (TypeError, ValueError):
+ self.prepare_signature = None
+ hook = self._prepare_inputs
+ # wraps(): generate and Unsloth read the signature (inspect follows __wrapped__).
+ model.prepare_inputs_for_generation = functools.wraps(prepare)(
+ lambda *args, **kwargs: hook(*args, **kwargs)
+ )
if "_prepare_static_cache" in model.__dict__ or not hasattr(model, "_prepare_static_cache"):
# 4.x (or a wrapper owns the hook): the call's cache is model._cache, read in end().
self.prepare = None
+ if (
+ KV.enabled()
+ and "_prepare_static_cache" not in model.__dict__
+ and "_get_cache" not in model.__dict__
+ and hasattr(model, "_get_cache")
+ ):
+ self.get_cache = model._get_cache
+ model._get_cache = self._get_cache
return self
self.prepare = model._prepare_static_cache
model._prepare_static_cache = self._prepare
@@ -955,6 +1110,16 @@ class reuse_kept_cache:
def __exit__(self, *exc):
model = self.model
+ if self.prepare_inputs is not None:
+ had, previous = self.prepare_inputs_saved
+ if had:
+ model.__dict__["prepare_inputs_for_generation"] = previous
+ else:
+ model.__dict__.pop("prepare_inputs_for_generation", None)
+ self.prepare_inputs = self.prepare_inputs_saved = None
+ if self.get_cache is not None:
+ del model._get_cache
+ self.get_cache = None
if self.prepare is not None:
del model._prepare_static_cache
elif "_unsloth_generic_call_cache" not in model.__dict__:
@@ -1738,6 +1903,9 @@ def decode_step(
reason = _cache_reason(cache)
if reason is None:
reason = _window_reason(cache, 1)
+ if reason is None and KV.needs_growth(cache, 1):
+ # A growth inside this step would move tensors: run eager, the next step captures.
+ reason = "kv cache grows"
if reason is not None:
return _refusal(state, reason)
device = getattr(model, "device", None)
@@ -1789,7 +1957,12 @@ def decode_step(
layout = tuple(
(type(layer).__name__, tuple((tuple(t.shape), t.dtype) for t in _linear_states(layer)))
if type(layer) in _LINEAR_LAYERS
- else (type(layer).__name__, layer.max_cache_len, tuple(layer.keys.shape), layer.keys.dtype)
+ else (
+ type(layer).__name__,
+ layer.capacity if type(layer) is KV.GrowableLayer else layer.max_cache_len,
+ tuple(layer.keys.shape),
+ layer.keys.dtype,
+ )
for layer in cache.layers
)
# Ambient autocast incl. cache flag (Dynamo guards on it); cached casts outlive end() in generate().
@@ -1806,14 +1979,14 @@ def decode_step(
if refused is not None:
return _refusal(state, refused)
# Graphs address this cache's tensors: a new cache re-captures; one reordered in place stays eager.
- cache_sig = (id(cache),) + tuple(
+ cache_sig = (id(cache), KV.epoch(cache)) + tuple(
tuple(t.data_ptr() for t in _linear_states(layer))
if type(layer) in _LINEAR_LAYERS
else (layer.keys.data_ptr(), layer.values.data_ptr())
for layer in cache.layers
)
if cache_sig != state.cache_sig:
- moved = state.cache_sig is not None and state.cache_sig[0] == id(cache)
+ moved = state.cache_sig is not None and state.cache_sig[:2] == cache_sig[:2]
state.clear()
if moved or state.moved == id(cache):
state.moved = id(cache)
@@ -1833,6 +2006,9 @@ def decode_step(
if _window_fills(cache, 1):
# A filling-key graph already captured replays this step correctly; a new one would not.
return _refusal(state, "sliding window fills in this step")
+ if KV.fills_bucket(cache, 1):
+ # A graph first captured on the bucket-filling step could never replay (the next step grows).
+ return _refusal(state, "kv cache fills its bucket")
return _capture(state, key, forward, kwargs, leaves, cache)
for buffer, leaf in zip(entry.leaves, leaves):
buffer.copy_(_compact(leaf))
@@ -1939,14 +2115,20 @@ def _capture(state, key, forward, kwargs, leaves, cache):
after = _snapshot(cache, rows = False)
graph = False
try:
- if side:
- graph, static_outputs = _BACKEND.record(
- state.pool, lambda: forward(**static_kwargs), cache, side, state.mempools
- )
- else:
- graph, static_outputs = _BACKEND.record(
- state.pool, lambda: forward(**static_kwargs), cache
- )
+ # A growable cache never grows inside a capture (its host counter is past the step here).
+ with KV.frozen():
+ if side:
+ graph, static_outputs = _BACKEND.record(
+ state.pool,
+ lambda: forward(**static_kwargs),
+ cache,
+ side,
+ state.mempools,
+ )
+ else:
+ graph, static_outputs = _BACKEND.record(
+ state.pool, lambda: forward(**static_kwargs), cache
+ )
finally:
# Capturing ran the Python update again: put the host counters back.
_restore((after[0], []))
diff --git a/unsloth/models/_kv_cache.py b/unsloth/models/_kv_cache.py
new file mode 100644
index 00000000000..4d81578c5fc
--- /dev/null
+++ b/unsloth/models/_kv_cache.py
@@ -0,0 +1,311 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.
+
+"""A transformers StaticCache whose full-attention layers grow by power-of-two buckets.
+
+Within a bucket tensors keep shape and address (graph/compile friendly); growth is eager between buckets. The growth
+check reads only the host counter `cumulative_length_int`, never the device."""
+
+import inspect
+import os
+import sys
+import weakref
+
+import torch
+
+try:
+ from transformers.cache_utils import StaticLayer as _StaticLayer
+except Exception: # transformers without layered static caches
+ _StaticLayer = None
+
+__all__ = [
+ "GrowableLayer",
+ "enabled",
+ "make_growable",
+ "supports",
+ "is_growable",
+ "needs_growth",
+ "fills_bucket",
+ "reserve",
+ "frozen",
+ "written",
+ "epoch",
+ "capacity",
+ "bucket",
+]
+
+
+def enabled():
+ # On by default; UNSLOTH_GROWABLE_KV=0 keeps transformers' full-length StaticCache.
+ return _StaticLayer is not None and os.environ.get("UNSLOTH_GROWABLE_KV", "1") != "0"
+
+
+def _min_slots():
+ try:
+ return max(1, int(os.environ.get("UNSLOTH_GROWABLE_KV_MIN", "256")))
+ except ValueError:
+ return 256
+
+
+def bucket(needed, limit):
+ """Smallest power of two >= needed (and >= the minimum), clamped to `limit`."""
+ size = max(_min_slots(), 1 << max(int(needed) - 1, 0).bit_length())
+ return min(size, int(limit)) if limit else size
+
+
+class _Group:
+ """Shared by the growable layers of one cache: they grow together, and graphs key on the epoch. Members are
+ weak references: a strong layer -> group -> layer cycle kept a released cache's KV alive until a gc pass."""
+
+ __slots__ = ("members", "epoch", "__weakref__")
+
+ def __init__(self):
+ self.members = []
+ self.epoch = 0
+
+
+if _StaticLayer is not None:
+
+ class GrowableLayer(_StaticLayer):
+ """A transformers StaticLayer that allocates `capacity` slots (a bucket) instead of `max_cache_len`."""
+
+ def __init__(
+ self,
+ max_cache_len,
+ group = None,
+ ):
+ 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()
+ self.group.members.append(weakref.ref(self))
+
+ def _plan(self, q_len):
+ """Capacity for q_len more tokens; grows the group if short. Never during a capture: the host counter is
+ already past the step and the copy would be recorded, not run."""
+ needed = self.cumulative_length_int + int(q_len)
+ if (self.capacity is None or needed > self.capacity) and not _frozen():
+ _grow_group(self.group, bucket(needed, max(int(self.max_cache_len), needed)))
+ return self.capacity
+
+ def lazy_initialization(self, key_states, *rest):
+ if self.capacity is None:
+ self.capacity = bucket(key_states.shape[-2], self.max_cache_len)
+ limit = self.max_cache_len
+ self.max_cache_len = self.capacity
+ try:
+ super().lazy_initialization(key_states, *rest)
+ finally:
+ self.max_cache_len = limit
+
+ def update(self, key_states, value_states, *args, **kwargs):
+ if torch.compiler.is_compiling():
+ return super().update(key_states, value_states, *args, **kwargs)
+ q_len = key_states.shape[-2]
+ self._plan(q_len)
+ out = super().update(key_states, value_states, *args, **kwargs)
+ self.cumulative_length_int += q_len
+ return out
+
+ def get_mask_sizes(self, *args, **kwargs):
+ query = args[0] if args else kwargs.get("query_length", kwargs.get("cache_position"))
+ q_len = query.shape[0] if isinstance(query, torch.Tensor) else int(query)
+ if not torch.compiler.is_compiling():
+ return self._plan(q_len), 0
+ # Compiled mask code must not mutate the cache: generate reserves beforehand, so only read capacity.
+ if self.capacity is None:
+ return bucket(q_len, self.max_cache_len), 0
+ return self.capacity, 0
+
+ def get_max_cache_shape(self):
+ return self.max_cache_len
+
+ def reset(self):
+ super().reset()
+ self.cumulative_length_int = 0
+
+ def _grow(self, size):
+ if size <= (self.capacity or 0):
+ return
+ old = self.capacity
+ self.capacity = size
+ if not getattr(self, "is_initialized", False):
+ return
+ for name in ("keys", "values"):
+ tensor = getattr(self, name)
+ shape = list(tensor.shape)
+ shape[-2] = size
+ grown = tensor.new_zeros(shape)
+ grown[:, :, :old].copy_(tensor)
+ torch._dynamo.mark_static_address(grown)
+ setattr(self, name, grown)
+
+else: # pragma: no cover
+ GrowableLayer = None
+
+
+_FREEZE = [0]
+
+
+def _frozen():
+ if _FREEZE[0]:
+ return True
+ try:
+ return torch.cuda.is_available() and torch.cuda.is_current_stream_capturing()
+ except Exception:
+ return False
+
+
+class frozen:
+ """No growth while active (decode graph captures): steps use the capacity reserved before them."""
+
+ def __enter__(self):
+ _FREEZE[0] += 1
+ return self
+
+ def __exit__(self, *exc):
+ _FREEZE[0] -= 1
+ return False
+
+
+def _grow_group(group, size):
+ for ref in group.members:
+ layer = ref()
+ if layer is not None:
+ layer._grow(size)
+ group.epoch += 1
+
+
+_SUPPORTS = {}
+
+
+def _sizes_by_max_cache_shape(module):
+ # Models sizing the mask / ALiBi by the cache's full limit (get_max_cache_shape(), BLOOM's get_max_length())
+ # would disagree with the bucket.
+ if module is None:
+ return False
+ if hasattr(module, "_prepare_4d_causal_attention_mask_with_cache_position"):
+ return True
+ source = sys.modules.get(type(module).__module__)
+ try:
+ text = inspect.getsource(source) if source is not None else ""
+ return "get_max_cache_shape(" in text or "get_max_length(" in text
+ except (OSError, TypeError):
+ return True
+
+
+def supports(model):
+ """Whether this model's mask code reads the cache's allocated length (transformers' masking_utils), so its
+ full-attention layers may grow. Models that size masks or ALiBi by get_max_cache_shape() keep StaticCache."""
+ key = type(model)
+ if key not in _SUPPORTS:
+ base = getattr(model, getattr(model, "base_model_prefix", ""), None) or model
+ decoder = base.get_decoder() if hasattr(base, "get_decoder") else None
+ _SUPPORTS[key] = not any(
+ _sizes_by_max_cache_shape(m)
+ for m in {id(x): x for x in (model, base, decoder) if x is not None}.values()
+ )
+ return _SUPPORTS[key]
+
+
+def make_growable(cache):
+ """Swaps the uninitialised full-attention StaticLayers of a transformers StaticCache for growable ones, in place.
+ Returns the cache. Initialised layers (a cache that already holds tokens) are left as they are."""
+ if GrowableLayer is None or cache is None:
+ return cache
+ layers = getattr(cache, "layers", None)
+ if not layers:
+ return cache
+ group = None
+ for i, layer in enumerate(layers):
+ if type(layer) is not _StaticLayer or getattr(layer, "is_initialized", False):
+ continue
+ if group is None:
+ group = _Group()
+ grown = GrowableLayer(max_cache_len = layer.max_cache_len, group = group)
+ layers[i] = grown
+ return cache
+
+
+def _members(cache):
+ for layer in getattr(cache, "layers", None) or ():
+ if GrowableLayer is not None and type(layer) is GrowableLayer:
+ yield layer
+
+
+def is_growable(cache):
+ return any(True for _ in _members(cache))
+
+
+def fills_bucket(cache, q_len):
+ """Whether a step writing q_len tokens fills the last slots of this cache's bucket: a graph captured there
+ can never replay (the next step grows the cache and moves its tensors)."""
+ for layer in _members(cache):
+ if layer.capacity is not None and layer.cumulative_length_int + q_len == layer.capacity:
+ return True
+ return False
+
+
+def needs_growth(cache, q_len):
+ """Whether a step writing q_len tokens grows this cache (host counters only, no device read)."""
+ for layer in _members(cache):
+ if layer.capacity is None or layer.cumulative_length_int + q_len > layer.capacity:
+ return True
+ return False
+
+
+def reserve(
+ cache,
+ total,
+ written = None,
+):
+ """Grows a growable cache, eagerly, to hold `total` tokens. `written` re-syncs the host counters, which a
+ compiled update or a replay may leave stale."""
+ members = list(_members(cache))
+ if not members:
+ return
+ if written is not None and written >= 0:
+ for layer in members:
+ layer.cumulative_length_int = int(written)
+ layer = members[0]
+ if layer.capacity is None or int(total) > layer.capacity:
+ _grow_group(layer.group, bucket(total, max(int(layer.max_cache_len), int(total))))
+
+
+def written(cache):
+ """Tokens written to a growable cache (host counter), 0 when it has no growable layer."""
+ return max((layer.cumulative_length_int for layer in _members(cache)), default = 0)
+
+
+def epoch(cache):
+ for layer in _members(cache):
+ return layer.group.epoch
+ return None
+
+
+def capacity(cache):
+ """Allocated slots of the growable layers (None when the cache has none)."""
+ caps = [layer.capacity for layer in _members(cache) if layer.capacity is not None]
+ return max(caps) if caps else None
+
+
+def short_layers(cache, max_cache_len):
+ """Whether a sliding / chunked layer was cut at the creating call's limit (min(window, limit)), so a longer
+ call up to `max_cache_len` would roll it early."""
+ limit = max((int(layer.max_cache_len) for layer in _members(cache)), default = None)
+ if limit is None:
+ return False
+ for layer in getattr(cache, "layers", None) or ():
+ if GrowableLayer is not None and type(layer) is GrowableLayer:
+ continue
+ length = getattr(layer, "max_cache_len", None)
+ if type(length) is int and limit <= length < int(max_cache_len):
+ return True
+ return False
+
+
+def raise_limit(cache, max_cache_len):
+ """A kept growable cache reused by a longer call: its layers may grow up to the new limit."""
+ for layer in _members(cache):
+ if int(max_cache_len) > int(layer.max_cache_len):
+ layer.max_cache_len = int(max_cache_len)