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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Decode graphs: preserve eager cache growth and reject stale replay (#16191)
Daniel Han788967b9f1b9
diff --git a/tests/test_decode_graphs_eager_growth.py b/tests/test_decode_graphs_eager_growth.pynew file mode 100644index 00000000000..fbb0e909a5c--- /dev/null+++ b/tests/test_decode_graphs_eager_growth.py@@ -0,0 +1,62 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++import types++import torch++import unsloth # noqa: F401 (must precede transformers)+import unsloth.models._decode_graphs as G+++def _alloc(attn, seq_len, increment):+ kv = torch.arange(seq_len * 4, dtype = torch.float32).reshape(1, 1, seq_len, 4)+ G.alloc_decode_buffers(+ attn, kv, -kv, 1, 1, 1, 4, 4, torch.float32, torch.device("cpu"), increment+ )+++def _attn():+ return types.SimpleNamespace(config = types.SimpleNamespace(model_type = "llama"))+++def test_eager_growth_ignores_a_retained_graph_store(monkeypatch):+ increment = 512+ eager_only = _attn()+ monkeypatch.setattr(G, "ENABLED", False)+ _alloc(eager_only, 1023, increment)+ G.resize_decode_buffers(eager_only, increment, 1, 1, 1, 4)+ expected_rows = eager_only.paged_attention.shape[0]+ assert expected_rows == 1023 + 1 + 2 * increment++ attn = _attn()+ monkeypatch.setattr(G, "ENABLED", True)+ G.start_generation(32768)+ _alloc(attn, 31, increment)+ G.end_generation()+ assert "_unsloth_graph_buffers" in attn.__dict__++ monkeypatch.setattr(G, "ENABLED", False)+ _alloc(attn, 1023, increment)+ kv = attn.paged_attention[:1023].clone()+ epoch = G.BUFFER_EPOCH+ G.resize_decode_buffers(attn, increment, 1, 1, 1, 4)+ assert attn.paged_attention.shape[0] == expected_rows+ assert attn.attention.shape[-1] == eager_only.attention.shape[-1]+ assert torch.equal(attn.paged_attention[:1023], kv)+ assert G.BUFFER_EPOCH == epoch+++def test_graph_backed_growth_still_doubles(monkeypatch):+ attn = _attn()+ monkeypatch.setattr(G, "ENABLED", True)+ monkeypatch.setattr(G, "PREALLOC", False)+ G.start_generation(0)+ _alloc(attn, 31, 512)+ rows = attn.paged_attention.shape[0]+ epoch = G.BUFFER_EPOCH+ G.resize_decode_buffers(attn, 1, 1, 1, 1, 4)+ G.end_generation()+ assert attn.paged_attention.shape[0] >= 2 * rows+ assert attn.paged_attention.shape[0] % G.BUCKET == 0+ assert G.BUFFER_EPOCH == epoch + 1diff --git a/tests/test_decode_graphs_kv_growth_device.py b/tests/test_decode_graphs_kv_growth_device.pyindex 9a7f649a204..053a6b4238d 100644--- a/tests/test_decode_graphs_kv_growth_device.py+++ b/tests/test_decode_graphs_kv_growth_device.py@@ -8,7 +8,7 @@ import pytestimport unsloth # noqa: F401 (must precede transformers)from unsloth import FastLanguageModelimport torch-from real_accelerator import has_real_cuda # tests/_shared, on sys.path via tests/conftest.py+from real_accelerator import has_real_cudafrom transformers import StoppingCriteria, StoppingCriteriaListimport unsloth.models._decode_graphs as G@@ -98,7 +98,6 @@ def test_early_stop_does_not_hold_max_new_tokens(monkeypatch):ids_g, logits_g, rows, delta = _run(model, tok, enc, True, monkeypatch, 32768, stop = 20)assert torch.equal(ids_e, ids_g) and torch.equal(logits_e, logits_g)assert delta["replays"] > 0, delta- # prompt + one 512 increment, rounded to the 256-row bucket; not 32768 + promptassert rows is not None and rows <= 1024, rows@@ -110,7 +109,6 @@ def test_long_rollout_grows_and_stays_bitwise(monkeypatch):ids_e, logits_e, _, _ = _run(model, tok, enc, False, monkeypatch, new, min_new = new)ids_g, logits_g, _, delta = _run(model, tok, enc, True, monkeypatch, new, min_new = new)assert torch.equal(ids_e, ids_g) and torch.equal(logits_e, logits_g)- # 768 -> 1536 -> hint: a few re-captures, most steps replayedassert 2 <= delta["captures"] <= 4, deltaassert delta["replays"] >= new - 10, delta@@ -124,6 +122,95 @@ def test_prealloc_kill_switch(monkeypatch):assert rows >= 4096, rows+@cuda+def test_eager_growth_does_not_replay_a_retained_graph(monkeypatch):+ model, tok = _load()+ enc = tok(PROMPTS[:1], return_tensors = "pt").to("cuda")+ monkeypatch.setattr(G, "ENABLED", True)+ monkeypatch.setattr(G, "PREALLOC", True)+ try:+ model.generate(+ **enc,+ max_new_tokens = 4096,+ min_new_tokens = 8,+ do_sample = False,+ pad_token_id = tok.pad_token_id,+ stopping_criteria = StoppingCriteriaList([_StopAfter(8)]),+ return_dict_in_generate = False,+ )+ state = G._state(model)+ assert state.captures > 0 and state.replays > 0, G.stats(model)+ assert len(state.graphs) == 1, G.stats(model)+ prime_key = next(iter(state.graphs))+ attn = model.model.layers[0].self_attn+ prime_cache = attn.paged_attention+ prime_capacity = prime_cache.shape[0]+ assert prime_capacity >= 4096++ monkeypatch.setattr(G, "ENABLED", False)+ eager = model.generate(+ **enc,+ max_new_tokens = 600,+ min_new_tokens = 600,+ do_sample = False,+ pad_token_id = tok.pad_token_id,+ return_dict_in_generate = True,+ )+ past = eager.past_key_values+ seq_len = past.get_seq_length() if hasattr(past, "get_seq_length") else past[0][0].shape[-2]+ assert seq_len >= 600+ assert attn.paged_attention is not prime_cache+ assert attn.paged_attention.shape[0] > enc["input_ids"].shape[-1] + 513+ assert prime_capacity > attn.paged_attention.shape[0]+ assert prime_key in state.graphs+ ids = eager.sequences[:, -1:]+ positions = torch.full_like(ids, seq_len)+ autocast_enabled, autocast_dtype = prime_key[2]+ with (+ torch.no_grad(),+ torch.inference_mode(prime_key[3]),+ torch.autocast("cuda", enabled = autocast_enabled, dtype = autocast_dtype),+ ):+ assert (+ ids.shape[0],+ ids.device,+ G._autocast_state(),+ torch.is_inference_mode_enabled(),+ ) == prime_key[:4]+ # The next slot is outside the valid past and must be overwritten before attention.+ for layer in model.model.layers:+ layer.self_attn.paged_attention[seq_len].fill_(float("nan"))+ monkeypatch.setattr(G, "ENABLED", True)+ calls = []+ decode_step = G.decode_step++ def observed_decode_step(*args, **kwargs):+ calls.append(True)+ return decode_step(*args, **kwargs)++ monkeypatch.setattr(G, "decode_step", observed_decode_step)+ actual = model(+ input_ids = ids,+ past_key_values = past,+ position_ids = positions,+ use_cache = True,+ return_dict = True,+ ).logits.clone()+ monkeypatch.setattr(G, "ENABLED", False)+ expected = model(+ input_ids = ids,+ past_key_values = past,+ position_ids = positions,+ use_cache = True,+ return_dict = True,+ ).logits+ assert calls+ assert torch.isfinite(expected).all()+ assert torch.equal(actual, expected)+ finally:+ G.release(model)++@pytest.mark.skipif(not has_real_cuda() or torch.cuda.device_count() < 2, reason = "needs 2 CUDA GPUs")diff --git a/unsloth/models/_decode_graphs.py b/unsloth/models/_decode_graphs.pyindex 4a837fac823..d5d3e6f9506 100644--- a/unsloth/models/_decode_graphs.py+++ b/unsloth/models/_decode_graphs.py@@ -280,7 +280,9 @@ def resize_decode_buffers(attn, increment, bsz, n_heads, n_kv_heads, head_dim):"""The eager growth of the KV cache by `increment` rows (new rows zeroed with graphs on)."""global BUFFER_EPOCHrows = attn.paged_attention.shape[0]- if "_unsloth_graph_buffers" in attn.__dict__:+ store = attn.__dict__.get("_unsloth_graph_buffers") or {}+ graph_backed = any(bufs[0] is attn.paged_attention for bufs in store.values())+ if graph_backed:# Each growth re-captures: double, capped at the hint, so O(log n) re-captures.grown = max(rows + increment, 2 * rows)if MAX_LEN_HINT + 1 > rows:@@ -290,7 +292,7 @@ def resize_decode_buffers(attn, increment, bsz, n_heads, n_kv_heads, head_dim):attn.paged_attention_K = attn.paged_attention[:, 0]attn.paged_attention_V = attn.paged_attention[:, 1]attn.attention.resize_((bsz, n_heads, 1, attn.attention.shape[-1] + increment))- if "_unsloth_graph_buffers" in attn.__dict__:+ if graph_backed:attn.paged_attention[rows:].zero_()BUFFER_EPOCH += 1@@ -615,9 +617,10 @@ def decode_step(attn0 = layers[0].self_attnpaged = attn0.__dict__.get("paged_attention")bsz = input_ids.shape[0]+ store = attn0.__dict__.get("_unsloth_graph_buffers") or {}if (paged is None- or "_unsloth_graph_buffers" not in attn0.__dict__+ or not any(bufs[0] is paged for bufs in store.values())or paged.shape[2] != bszor input_ids.shape[1] != 1):