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
Block compile: checkpoint recompute reuses the forward graph (shared_kv_states, output collector) (#16596)
Daniel Han161ed4731814
diff --git a/tests/test_block_compile.py b/tests/test_block_compile.pyindex adc6206dd7e..2276824ca07 100644--- a/tests/test_block_compile.py+++ b/tests/test_block_compile.py@@ -1842,6 +1842,89 @@ def test_graphs_off_compile_gets_the_same_region_limit(monkeypatch):assert kwargs["recompile_limit"] == M._region_recompile_limit(2) == 48+def test_shared_kv_writer_recompute_reuses_the_forward_graph(monkeypatch):+ """Gemma-4 E2B: recompute saw `shared_kv_states` filled and compiled a second graph (CheckpointError)."""+ from collections import UserDict+ from torch._dynamo.testing import CompileCounter+ from torch.utils.checkpoint import checkpoint++ M = _load()+ counter = CompileCounter()+ real_compile = torch.compile+ monkeypatch.setattr(+ torch,+ "compile",+ lambda fn, **kwargs: real_compile(fn, backend = counter, fullgraph = False, dynamic = None),+ )+ torch._dynamo.reset()++ class Attn(torch.nn.Module):+ def __init__(self, store, shared):+ super().__init__()+ self.store_full_length_kv, self.is_kv_shared_layer = store, shared+ self.q = torch.nn.Linear(8, 8)+ self.k = torch.nn.Linear(8, 8)++ def forward(self, x, shared_kv_states):+ if self.is_kv_shared_layer:+ k = shared_kv_states["sliding"]+ else:+ k = self.k(x)+ if self.store_full_length_kv:+ shared_kv_states["sliding"] = k+ return self.q(x) * k++ class KvDecoderLayer(torch.nn.Module):+ def __init__(self, store, shared):+ super().__init__()+ self.self_attn = Attn(store, shared)++ def forward(+ self,+ hidden_states,+ shared_kv_states = None,+ **kwargs,+ ):+ return hidden_states + self.self_attn(hidden_states, shared_kv_states)++ torch.manual_seed(0)+ layers = [+ KvDecoderLayer(False, False),+ KvDecoderLayer(True, False),+ KvDecoderLayer(False, True),+ ]+ stock = [KvDecoderLayer(False, False), KvDecoderLayer(True, False), KvDecoderLayer(False, True)]+ for a, b in zip(stock, layers):+ b.load_state_dict(a.state_dict())+ M._wrap(KvDecoderLayer, {})+ for layer in layers + stock:+ layer.train()+ for layer in stock:+ layer.__dict__["_unsloth_block_mode"] = M._OFF++ def step(stack, x):+ shared = UserDict()+ h = x+ for layer in stack:+ h = checkpoint(layer, h, shared_kv_states = shared, use_reentrant = False)+ return h, shared++ x = torch.randn(2, 5, 8)+ ref, ref_shared = step(stock, x)+ ref.sum().backward()+ out, shared = step(layers, x)+ forward_frames = counter.frame_count+ out.sum().backward()+ recompute_frames = counter.frame_count - forward_frames+ torch._dynamo.reset()+ assert recompute_frames == 0+ assert list(shared.keys()) == ["sliding"]+ torch.testing.assert_close(out, ref)+ for a, b in zip(stock, layers):+ for pa, pb in zip(a.parameters(), b.parameters()):+ torch.testing.assert_close(pa.grad, pb.grad)++def test_parametrized_class_is_reused_per_module(monkeypatch):"""PEFT's ParamWrapper registers a parametrization per forward: each module keeps oneParametrized<Class> (a stable type id for Dynamo), and two modules never share one."""diff --git a/unsloth/models/_block_compile.py b/unsloth/models/_block_compile.pyindex e3df9074d52..b7047a13098 100644--- a/unsloth/models/_block_compile.py+++ b/unsloth/models/_block_compile.py@@ -1425,6 +1425,22 @@ def _has_cache(args, kwargs):return any(isinstance(arg, Cache) for arg in args)+def _shared_kv_scratch(layer, kwargs):+ """KV-storing layers get an empty `shared_kv_states` (copied back): dynamo guards on it being empty and a recompute sees it filled."""+ shared = kwargs.get("shared_kv_states")+ if shared is None or not hasattr(shared, "update"):+ return kwargs, None+ attn = getattr(layer, "self_attn", None)+ # Readers keep the real dict.+ if attn is None or getattr(attn, "is_kv_shared_layer", False):+ return kwargs, None+ try:+ scratch = type(shared)()+ except Exception:+ return kwargs, None+ return {**kwargs, "shared_kv_states": scratch}, (shared, scratch)++def _layer_kind(layer):attn = (getattr(layer, "self_attn", None)@@ -1476,6 +1492,10 @@ def _wrap(from unsloth_zoo.temporary_patches.misc import output_capture_scratch as capture_scratchexcept Exception:capture_scratch = contextlib.nullcontext+ try:+ scratch_takes_owner = "owner" in inspect.signature(capture_scratch).parameters+ except (TypeError, ValueError):+ scratch_takes_owner = False# First call per grad mode compiles with errors raised: on failure retry with flex outside,# then the stock forward. The mode is per layer (a checkpoint recompute must not switch graph);# a failure is also the starting mode for later layers of the same kind.@@ -1514,6 +1534,13 @@ def _wrap(graph_shapes = set()def run(self, hidden_states, args, kwargs, mode):+ kwargs, shared = _shared_kv_scratch(self, kwargs)+ out = _run(self, hidden_states, args, kwargs, mode)+ if shared is not None:+ shared[0].update(shared[1])+ return out++ def _run(self, hidden_states, args, kwargs, mode):previous = inline_flag[0]inline_flag[0] = True_IN_BLOCK[0] = mode@@ -1532,7 +1559,8 @@ def _wrap(if varlen is not None:kwargs = {**kwargs, packed_module.BLOCK_VARLEN_KWARG: varlen}# Capture hooks (router_logits) append to empty scratch lists: no guard on the layer index.- with capture_scratch(), _no_ddp_graph_split():+ scratch = capture_scratch(owner = self) if scratch_takes_owner else capture_scratch()+ with scratch, _no_ddp_graph_split():use_graphs = graphsif auto and _CUDAGRAPH_STATE["auto"]["phase"] != "off":verdict = _auto_observe(self, hidden_states, args, kwargs)