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
Force non-reentrant gradient checkpointing for DeepSeek-V4.1 (#12318)
Daniel Hanadbf205f17e9
diff --git a/tests/test_deepseek_v41_non_reentrant_gc.py b/tests/test_deepseek_v41_non_reentrant_gc.pynew file mode 100644index 00000000000..38eb8ed5da5--- /dev/null+++ b/tests/test_deepseek_v41_non_reentrant_gc.py@@ -0,0 +1,155 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team.+"""DeepSeek-V4.1 must use non-reentrant gradient checkpointing (cross-layer KV grads)."""++import json+import os+import subprocess+import sys++import pytest++torch = pytest.importorskip("torch")++pytestmark = pytest.mark.skipif(+ not torch.cuda.is_available(), reason = "importing unsloth needs a GPU"+)++_CHILD = r"""+import json, sys+import unsloth # noqa: F401+import torch+import torch.utils.checkpoint as torch_checkpoint+from transformers import LlamaConfig, LlamaForCausalLM+from unsloth.models.vision import FastBaseModel++results, models = [], []+for model_type in sys.argv[1:]:+ config = LlamaConfig(+ vocab_size = 128, hidden_size = 64, intermediate_size = 128, num_hidden_layers = 2,+ num_attention_heads = 4, num_key_value_heads = 2, max_position_embeddings = 64,+ )+ model = LlamaForCausalLM(config).cuda()+ # Stand-in for DeepseekV41ForCausalLM: post_patch_model keys the GC mode on config.model_type.+ model.config.model_type = model_type+ model = FastBaseModel.post_patch_model(+ model, use_gradient_checkpointing = "unsloth", trust_remote_code = True,+ )+ # What UnslothSFTConfig / TRL pass at train time.+ model.gradient_checkpointing_enable(gradient_checkpointing_kwargs = {"use_reentrant": True})+ funcs = [+ m._gradient_checkpointing_func for m in model.modules()+ if getattr(m, "_gradient_checkpointing_func", None) is not None+ ]+ out = {+ "n_funcs": len(funcs),+ "use_reentrant": sorted({str(getattr(f, "keywords", {}).get("use_reentrant")) for f in funcs}),+ "global_checkpoint_patched": hasattr(torch_checkpoint.checkpoint, "_unsloth_original"),+ "wrapper_in_use": any(hasattr(getattr(f, "func", f), "_unsloth_original") for f in funcs),+ }+ # A checkpointed backward must run and reach the first layer (post_patch_model froze every weight).+ model.train()+ q_proj = model.model.layers[0].self_attn.q_proj.weight+ q_proj.requires_grad_(True)+ ids = torch.randint(0, 128, (2, 16), device = "cuda")+ model(input_ids = ids, labels = ids).loss.backward()+ out["layer0_grad"] = q_proj.grad is not None and bool(q_proj.grad.abs().sum() > 0)+ results.append(out)+ models.append(model)+# Re-enabling the first model (what the trainer does) after later loads.+models[0].gradient_checkpointing_enable(gradient_checkpointing_kwargs = {"use_reentrant": True})+results[0]["reenable_wrapper_in_use"] = all(+ hasattr(getattr(m._gradient_checkpointing_func, "func", None), "_unsloth_original")+ for m in models[0].modules() if getattr(m, "_gradient_checkpointing_func", None) is not None+)+print("@@@" + json.dumps(results))+"""+++# Two post_patch_model calls then a positional enable: the newest (offloading) wrapper must bind.+_CHILD_REPATCH = r"""+import json+import unsloth # noqa: F401+import torch+from transformers import LlamaConfig, LlamaForCausalLM+from unsloth.models.vision import FastBaseModel++config = LlamaConfig(+ vocab_size = 128, hidden_size = 64, intermediate_size = 128, num_hidden_layers = 2,+ num_attention_heads = 4, num_key_value_heads = 2, max_position_embeddings = 64,+)+model = LlamaForCausalLM(config).cuda()+model.config.model_type = "deepseek_v41"+for mode in (False, "unsloth"):+ model = FastBaseModel.post_patch_model(model, use_gradient_checkpointing = mode, trust_remote_code = True)+model.gradient_checkpointing_enable({"use_reentrant": True})+funcs = [+ m._gradient_checkpointing_func for m in model.modules()+ if getattr(m, "_gradient_checkpointing_func", None) is not None+]+def offload(f):+ f = getattr(f, "func", f)+ cells = dict(zip(f.__code__.co_freevars, (c.cell_contents for c in f.__closure__ or ())))+ return cells.get("_offload")+out = {+ "n_funcs": len(funcs),+ "use_reentrant": sorted({str(getattr(f, "keywords", {}).get("use_reentrant")) for f in funcs}),+ "offload": sorted({str(offload(f)) for f in funcs}),+}+print("@@@" + json.dumps([out]))+"""+++def _run(+ tmp_path,+ *model_types,+ child = _CHILD,+):+ env = dict(os.environ)+ repo_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+ env["PYTHONPATH"] = os.pathsep.join(+ [repo_root] + ([env["PYTHONPATH"]] if env.get("PYTHONPATH") else [])+ )+ env.setdefault("UNSLOTH_COMPILE_LOCATION", str(tmp_path / "unsloth_compiled_cache"))+ result = subprocess.run(+ [sys.executable, "-c", child, *model_types],+ cwd = str(tmp_path),+ env = env,+ capture_output = True,+ text = True,+ timeout = 900,+ )+ assert result.returncode == 0, result.stdout[-4000:] + result.stderr[-4000:]+ line = next(l for l in result.stdout.splitlines() if l.startswith("@@@"))+ return json.loads(line[3:])+++def test_deepseek_v41_forces_non_reentrant(tmp_path):+ (out,) = _run(tmp_path, "deepseek_v41")+ assert out["n_funcs"] > 0, out+ assert out["use_reentrant"] == ["False"], out+ assert out["global_checkpoint_patched"], out+ assert out["layer0_grad"], out+++def test_other_models_keep_reentrant(tmp_path):+ (out,) = _run(tmp_path, "llama")+ assert out["use_reentrant"] == ["True"], out+ assert out["layer0_grad"], out+++def test_later_model_gets_reentrant_back(tmp_path):+ # Same process: the deepseek_v41 wrapper must not leak into the next model's checkpointing.+ v41, llama = _run(tmp_path, "deepseek_v41", "llama")+ assert v41["wrapper_in_use"], v41+ assert v41["reenable_wrapper_in_use"], v41+ assert not llama["global_checkpoint_patched"], llama+ assert not llama["wrapper_in_use"], llama+ assert llama["layer0_grad"], llama+++def test_repatch_keeps_newest_wrapper_and_positional_call(tmp_path):+ (out,) = _run(tmp_path, child = _CHILD_REPATCH)+ assert out["n_funcs"] > 0, out+ assert out["use_reentrant"] == ["False"], out+ assert out["offload"] == ["True"], outdiff --git a/unsloth/models/vision.py b/unsloth/models/vision.pyindex 3ef77c66f13..0d180e69958 100644--- a/unsloth/models/vision.py+++ b/unsloth/models/vision.py@@ -2433,6 +2433,9 @@ def _offload_activation_unpack(packed):return x if device is None else x.to(device, non_blocking = True)+_NON_REENTRANT_GC_MODEL_TYPES = ("deepseek_v41",)++class FastBaseModel:@staticmethod@_offline_aware_load@@ -4138,6 +4141,11 @@ class FastBaseModel:# VLMs can hit DDP "marked ready twice" with re-entrant checkpointing (#3713), so under DDP skip the offloaded/re-entrant checkpoint patch and default native checkpoint to non-reentrant, offloading via saved-tensor hooks instead.use_reentrant = not is_distributed()+ # DeepSeek-V4.1 layers consume tensors from earlier layers; reentrant GC's no_grad pass drops those grads.+ _gc_model_type = (getattr(getattr(model, "config", None), "model_type", "") or "").lower()+ _force_non_reentrant = _gc_model_type.startswith(_NON_REENTRANT_GC_MODEL_TYPES)+ if _force_non_reentrant:+ use_reentrant = Falseif not use_reentrant:unpatch_unsloth_gradient_checkpointing()unpatch_unsloth_smart_gradient_checkpointing()@@ -4160,6 +4168,16 @@ class FastBaseModel:_nonre_checkpoint._unsloth_original = _orig_checkpointtorch_checkpoint.checkpoint = _nonre_checkpointhf_modeling_utils.checkpoint = _nonre_checkpoint+ else:+ # Drop the wrapper an earlier deepseek_v41 load in this process installed.+ for _mod, _name in (+ (torch_checkpoint, "checkpoint"),+ (torch_checkpoint, "_old_checkpoint"),+ (hf_modeling_utils, "checkpoint"),+ ):+ _orig = getattr(getattr(_mod, _name, None), "_unsloth_original", None)+ if _orig is not None:+ setattr(_mod, _name, _orig)from .loader_utils import enable_composite_gradient_checkpointingfrom .remote_moe_shims import prepare_remote_moe_for_training@@ -4202,6 +4220,32 @@ class FastBaseModel:model.gradient_checkpointing_enable = _gc_enable_reentrant+ if _force_non_reentrant:+ # Wrap the unpatched method so a second post_patch_model (get_peft_model) replaces the wrapper instead of nesting it.+ _original_gc_enable_nr = getattr(+ model.gradient_checkpointing_enable,+ "_unsloth_gc_original",+ model.gradient_checkpointing_enable,+ )++ def _gc_enable_non_reentrant(+ gradient_checkpointing_kwargs = None,+ *args,+ **kwargs,+ ):+ gc_kwargs = dict(gradient_checkpointing_kwargs or {})+ gc_kwargs["use_reentrant"] = False+ # Bind this model's wrapper (and its offloading) even if a later load restored the global.+ _prev_checkpoint = hf_modeling_utils.checkpoint+ hf_modeling_utils.checkpoint = _nonre_checkpoint+ try:+ return _original_gc_enable_nr(gc_kwargs, *args, **kwargs)+ finally:+ hf_modeling_utils.checkpoint = _prev_checkpoint++ _gc_enable_non_reentrant._unsloth_gc_original = _original_gc_enable_nr+ model.gradient_checkpointing_enable = _gc_enable_non_reentrant+from transformers.trainer import Trainerif (