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.

Keep the load-time gradient checkpointing mode in for_training (#12629)

Daniel Han2557cbad6b74
diff --git a/tests/test_for_training_gc_off.py b/tests/test_for_training_gc_off.py
new file mode 100644
index 00000000000..93858bf13eb
--- /dev/null
+++ b/tests/test_for_training_gc_off.py
@@ -0,0 +1,214 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""for_training() on a model loaded with use_gradient_checkpointing=False used to crash on the next forward."""
+
+import pytest
+import torch
+
+
+def _tiny_qwen3():
+ from transformers import Qwen3Config, Qwen3ForCausalLM
+
+ config = Qwen3Config(
+ vocab_size = 64,
+ hidden_size = 32,
+ intermediate_size = 64,
+ num_hidden_layers = 2,
+ num_attention_heads = 4,
+ num_key_value_heads = 2,
+ head_dim = 8,
+ )
+ torch.manual_seed(0)
+ return Qwen3ForCausalLM(config)
+
+
+def _decoder_layers(model):
+ return [m for m in model.modules() if type(m).__name__.endswith("DecoderLayer")]
+
+
+def _fast_classes():
+ from unsloth.models.llama import FastLlamaModel
+ from unsloth.models.vision import FastBaseModel
+ return [FastLlamaModel, FastBaseModel]
+
+
[email protected]("which", [0, 1])
+def test_default_keeps_checkpointing_off_when_it_was_off_at_load(which):
+ fast = _fast_classes()[which]
+ model = _tiny_qwen3()
+ model._unsloth_gradient_checkpointing = False
+ fast.for_training(model)
+ assert all(not layer.gradient_checkpointing for layer in _decoder_layers(model))
+ ids = torch.randint(0, 64, (1, 8))
+ model(input_ids = ids, labels = ids).loss.backward()
+
+
[email protected]("which", [0, 1])
[email protected]("arg", [True, "unsloth"])
+def test_explicit_enable_arms_a_model_loaded_without_checkpointing(which, arg):
+ fast = _fast_classes()[which]
+ model = _tiny_qwen3()
+ model._unsloth_gradient_checkpointing = False
+ fast.for_training(model, use_gradient_checkpointing = arg)
+ layers = _decoder_layers(model)
+ assert layers and all(layer.gradient_checkpointing == arg for layer in layers)
+ assert all(callable(layer._gradient_checkpointing_func) for layer in layers)
+ ids = torch.randint(0, 64, (1, 8))
+ model(input_ids = ids, labels = ids).loss.backward()
+ assert all(p.grad is not None for p in model.model.layers.parameters())
+
+
[email protected]("which", [0, 1])
+def test_for_training_default_restores_the_recorded_mode(which):
+ fast = _fast_classes()[which]
+ model = _tiny_qwen3()
+ model.gradient_checkpointing_enable()
+ model._unsloth_gradient_checkpointing = "unsloth"
+ fast.for_training(model)
+ layers = _decoder_layers(model)
+ assert layers and all(layer.gradient_checkpointing == "unsloth" for layer in layers)
+ fast.for_training(model, use_gradient_checkpointing = False)
+ assert all(not layer.gradient_checkpointing for layer in layers)
+
+
+def test_unrecorded_model_keeps_the_old_default_of_on():
+ from unsloth.models._utils import resolve_training_gradient_checkpointing
+ assert resolve_training_gradient_checkpointing(torch.nn.Linear(2, 2), None) is True
+ assert resolve_training_gradient_checkpointing(torch.nn.Linear(2, 2), False) is False
+
+
[email protected]("which", [0, 1])
[email protected]("armed", [True, False])
+def test_unrecorded_model_keeps_its_load_time_choice(which, armed):
+ fast = _fast_classes()[which]
+ model = _tiny_qwen3()
+ if armed:
+ model.gradient_checkpointing_enable()
+ fast.for_training(model)
+ assert all(bool(layer.gradient_checkpointing) == armed for layer in _decoder_layers(model))
+
+
+class _Block(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.linear = torch.nn.Linear(8, 8)
+
+ def forward(self, hidden):
+ return torch.tanh(self.linear(hidden))
+
+
+class _RemoteBackbone(torch.nn.Module):
+ """Older / remote-code protocol: the backbone, not the block, calls the checkpoint function."""
+
+ def __init__(self):
+ super().__init__()
+ self.gradient_checkpointing = False
+ self.layers = torch.nn.ModuleList([_Block(), _Block()])
+
+ def forward(self, hidden):
+ for layer in self.layers:
+ if self.gradient_checkpointing and self.training:
+ hidden = self._gradient_checkpointing_func(layer.__call__, hidden)
+ else:
+ hidden = layer(hidden)
+ return hidden
+
+
+class _RemoteModel(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.model = _RemoteBackbone()
+ self.enabled_by = []
+
+ def gradient_checkpointing_enable(self):
+ from torch.utils.checkpoint import checkpoint
+ import functools
+
+ self.enabled_by.append("model")
+ for module in self.modules():
+ if hasattr(module, "gradient_checkpointing"):
+ module._gradient_checkpointing_func = functools.partial(
+ checkpoint, use_reentrant = False
+ )
+ module.gradient_checkpointing = True
+
+ def forward(self, hidden):
+ return self.model(hidden)
+
+
[email protected]("which", [0, 1])
[email protected]("arg", [True, None, False])
+def test_backbone_that_calls_the_checkpoint_function_itself(which, arg):
+ fast = _fast_classes()[which]
+ model = _RemoteModel()
+ fast.for_training(model, use_gradient_checkpointing = arg)
+ assert model.model.gradient_checkpointing == bool(arg)
+ assert model.enabled_by == (["model"] if arg else [])
+ model(torch.randn(2, 8, requires_grad = True)).sum().backward()
+
+
[email protected]("which", [0, 1])
+def test_explicit_enable_goes_through_the_outer_override(which):
+ fast = _fast_classes()[which]
+ model = _tiny_qwen3()
+ model._unsloth_gradient_checkpointing = False
+ calls = []
+ original = model.gradient_checkpointing_enable
+
+ def override(**kwargs):
+ calls.append(kwargs)
+ return original(gradient_checkpointing_kwargs = {"use_reentrant": True})
+
+ model.gradient_checkpointing_enable = override
+ fast.for_training(model, use_gradient_checkpointing = True)
+ assert calls == [{}]
+ assert all(
+ layer._gradient_checkpointing_func.keywords == {"use_reentrant": True}
+ for layer in _decoder_layers(model)
+ )
+
+
+class _SlowDiffusion(torch.nn.Module):
+ _unsloth_slow_diffusion = True
+
+ def __init__(self, recorded):
+ super().__init__()
+ self._unsloth_gradient_checkpointing = recorded
+ self.enabled = 0
+
+ def gradient_checkpointing_enable(self):
+ self.enabled += 1
+
+
[email protected]("recorded", [True, False])
+def test_fastmodel_default_keeps_the_diffusion_adapter_choice(recorded):
+ from unsloth.models.loader import FastModel
+
+ model = _SlowDiffusion(recorded)
+ FastModel.for_training(model)
+ assert model.enabled == int(recorded)
+ FastModel.for_training(model, use_gradient_checkpointing = True)
+ assert model.enabled == int(recorded) + 1
+
+
[email protected]("which", [0, 1])
+def test_late_enable_turns_the_cache_off_and_inference_restores_it(which):
+ fast = _fast_classes()[which]
+ model = _tiny_qwen3()
+ model._unsloth_gradient_checkpointing = False
+ assert model.config.use_cache
+ fast.for_training(model, use_gradient_checkpointing = True)
+ assert model.config.use_cache is False
+ fast.for_inference(model)
+ assert model.config.use_cache is True
+
+
+def test_unreadable_forward_counts_as_checkpointing():
+ from unsloth.models._utils import _forward_reads_checkpoint_function
+
+ class _NoSource(torch.nn.Module):
+ gradient_checkpointing = False
+
+ _NoSource.forward = eval("lambda self, x: x")
+ assert _forward_reads_checkpoint_function(_NoSource) is True
diff --git a/tests/test_for_training_generation_flag.py b/tests/test_for_training_generation_flag.py
index 490c0e205ea..2271196c453 100644
--- a/tests/test_for_training_generation_flag.py
+++ b/tests/test_for_training_generation_flag.py
@@ -3,6 +3,7 @@
import ast
import builtins
+import inspect
import os
from pathlib import Path
@@ -52,8 +53,26 @@ def _for_training(module, class_name):
if isinstance(node, ast.FunctionDef) and node.name == "for_training"
)
method.decorator_list = []
- compiled = ast.Module(body = _helpers_used_by(method, tree) + [method], type_ignores = [])
- namespace = _Namespace(os = os)
+ utils = ast.parse((path.parent / "_utils.py").read_text(encoding = "utf-8"))
+ shared = [
+ node
+ for node in utils.body
+ if isinstance(node, ast.FunctionDef)
+ and node.name
+ in (
+ "resolve_training_gradient_checkpointing",
+ "_gradient_checkpointing_layer_class",
+ "_forward_reads_checkpoint_function",
+ "_calls_checkpoint_function",
+ "_is_unarmed",
+ "arm_gradient_checkpointing",
+ "set_module_gradient_checkpointing",
+ )
+ ]
+ for node in shared:
+ node.decorator_list = []
+ compiled = ast.Module(body = shared + _helpers_used_by(method, tree) + [method], type_ignores = [])
+ namespace = _Namespace(os = os, inspect = inspect)
exec(compile(ast.fix_missing_locations(compiled), str(path), "exec"), namespace)
return namespace["for_training"]
diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.py
index 26963b9e20f..87921d74bdd 100644
--- a/unsloth/models/_utils.py
+++ b/unsloth/models/_utils.py
@@ -6805,3 +6805,80 @@ try:
patch_flex_attention_kernel_options()
except Exception:
pass
+
+
[email protected]_cache(maxsize = 1)
+def _gradient_checkpointing_layer_class():
+ try:
+ from transformers.modeling_layers import GradientCheckpointingLayer
+ except ImportError:
+ return None
+ return GradientCheckpointingLayer
+
+
[email protected]_cache(maxsize = None)
+def _forward_reads_checkpoint_function(cls):
+ try:
+ return "_gradient_checkpointing_func" in inspect.getsource(cls.forward)
+ except Exception:
+ return True # cannot read it: assume it does, as _forward_calls_checkpointing does
+
+
+def _calls_checkpoint_function(module):
+ """Calls `self._gradient_checkpointing_func` when its flag is on (also older / remote-code backbones)."""
+ layer_class = _gradient_checkpointing_layer_class()
+ if layer_class is not None and isinstance(module, layer_class):
+ return True
+ return hasattr(module, "gradient_checkpointing") and _forward_reads_checkpoint_function(
+ type(module)
+ )
+
+
+def _is_unarmed(module):
+ return (
+ _calls_checkpoint_function(module)
+ and getattr(module, "_gradient_checkpointing_func", None) is None
+ )
+
+
+def resolve_training_gradient_checkpointing(model, use_gradient_checkpointing):
+ """`None` keeps the mode chosen at load / get_peft_model instead of forcing it on."""
+ if use_gradient_checkpointing is not None:
+ return use_gradient_checkpointing
+ if hasattr(model, "_unsloth_gradient_checkpointing"):
+ return model._unsloth_gradient_checkpointing
+ # Nothing recorded (no adapter, full finetuning): loading's choice is whether it armed the layers.
+ checkpointing = [m for m in model.modules() if _calls_checkpoint_function(m)]
+ if checkpointing:
+ return any(not _is_unarmed(m) for m in checkpointing)
+ return True
+
+
+def arm_gradient_checkpointing(model):
+ """Install the checkpoint function a load with checkpointing off never gave the layers."""
+ if not any(_is_unarmed(m) for m in model.modules()):
+ return False
+ # Outer model, not get_base_model(): Gemma 3N / 4 and DeepSeek-V4.1 install their override there.
+ try:
+ model.gradient_checkpointing_enable()
+ except Exception as e:
+ logger.warning(
+ f"Unsloth: could not turn on gradient checkpointing ({e}); training without it."
+ )
+ return False
+ # As the load path does: a layer handed a cache skips checkpointing (_checkpointed_layer_forward).
+ try:
+ from unsloth_zoo.training_utils import disable_use_cache
+ except ImportError:
+ return True
+ disable_use_cache(model)
+ return True
+
+
+def set_module_gradient_checkpointing(module, value):
+ """Never turn on a module without its checkpoint function: its next training forward would raise."""
+ if value and _is_unarmed(module):
+ module.gradient_checkpointing = False
+ return False
+ module.gradient_checkpointing = value
+ return True
diff --git a/unsloth/models/diffusion.py b/unsloth/models/diffusion.py
index 55f3975a037..259e0e02c8b 100644
--- a/unsloth/models/diffusion.py
+++ b/unsloth/models/diffusion.py
@@ -374,6 +374,7 @@ class FastDiffusionModel:
model = peft_get_peft_model(model, lora_config)
model._unsloth_slow_diffusion = True
+ model._unsloth_gradient_checkpointing = use_gradient_checkpointing
try:
model.print_trainable_parameters()
except Exception:
diff --git a/unsloth/models/llama.py b/unsloth/models/llama.py
index 87ed091d1fa..ee135948bdb 100644
--- a/unsloth/models/llama.py
+++ b/unsloth/models/llama.py
@@ -30,6 +30,9 @@ from ._utils import (
is_bfloat16_supported,
get_quant_type,
resolve_model_class,
+ arm_gradient_checkpointing,
+ resolve_training_gradient_checkpointing,
+ set_module_gradient_checkpointing,
)
from .loader_utils import (
DEFAULT_DEVICE_MAP,
@@ -4348,11 +4351,16 @@ class FastLlamaModel:
return model
@staticmethod
- def for_training(model, use_gradient_checkpointing = True):
+ def for_training(model, use_gradient_checkpointing = None):
if not hasattr(model, "parameters"):
raise TypeError(
"Unsloth: I think you're passing a tokenizer, not the model to for_training!"
)
+ use_gradient_checkpointing = resolve_training_gradient_checkpointing(
+ model, use_gradient_checkpointing
+ )
+ if use_gradient_checkpointing:
+ arm_gradient_checkpointing(model)
for param in model.parameters():
if hasattr(param, "_fast_lora"):
@@ -4360,7 +4368,7 @@ class FastLlamaModel:
def _for_training(m):
if hasattr(m, "gradient_checkpointing"):
- m.gradient_checkpointing = use_gradient_checkpointing
+ set_module_gradient_checkpointing(m, use_gradient_checkpointing)
if hasattr(m, "training"):
m.training = True
if hasattr(m, "_saved_temp_tokenizer"):
@@ -4382,7 +4390,7 @@ class FastLlamaModel:
# Since transformers 4.53, this must be turned on explicitly.
for module in model.modules():
if hasattr(module, "gradient_checkpointing"):
- module.gradient_checkpointing = use_gradient_checkpointing
+ set_module_gradient_checkpointing(module, use_gradient_checkpointing)
if hasattr(model, "get_input_embeddings"):
embeddings = model.get_input_embeddings()
diff --git a/unsloth/models/loader.py b/unsloth/models/loader.py
index 221347b67ec..1c8c56d7985 100644
--- a/unsloth/models/loader.py
+++ b/unsloth/models/loader.py
@@ -1664,8 +1664,10 @@ class FastModel(FastBaseModel):
return FastBaseModel.for_inference(model)
@staticmethod
- def for_training(model, use_gradient_checkpointing = True):
+ def for_training(model, use_gradient_checkpointing = None):
if getattr(model, "_unsloth_slow_diffusion", False):
+ if use_gradient_checkpointing is None:
+ use_gradient_checkpointing = getattr(model, "_unsloth_gradient_checkpointing", True)
return FastDiffusionModel.for_training(model, use_gradient_checkpointing)
return FastBaseModel.for_training(model, use_gradient_checkpointing)
diff --git a/unsloth/models/vision.py b/unsloth/models/vision.py
index 3200fa793f7..510c752c636 100644
--- a/unsloth/models/vision.py
+++ b/unsloth/models/vision.py
@@ -118,6 +118,9 @@ from ._utils import (
_select_moe_detection_targets,
set_task_config_attr,
_unsloth_freeze_norm_running_stats,
+ arm_gradient_checkpointing,
+ resolve_training_gradient_checkpointing,
+ set_module_gradient_checkpointing,
)
from ._utils import *
from ._remote_code_buffers import restore_remote_code_non_persistent_buffers
@@ -4352,11 +4355,16 @@ class FastBaseModel:
return model
@staticmethod
- def for_training(model, use_gradient_checkpointing = True):
+ def for_training(model, use_gradient_checkpointing = None):
if not hasattr(model, "parameters"):
raise TypeError(
"Unsloth: I think you're passing a tokenizer, not the model to for_training!"
)
+ use_gradient_checkpointing = resolve_training_gradient_checkpointing(
+ model, use_gradient_checkpointing
+ )
+ if use_gradient_checkpointing:
+ arm_gradient_checkpointing(model)
for param in model.parameters():
if hasattr(param, "_fast_lora"):
@@ -4364,7 +4372,7 @@ class FastBaseModel:
def _for_training(m):
if hasattr(m, "gradient_checkpointing"):
- m.gradient_checkpointing = use_gradient_checkpointing
+ set_module_gradient_checkpointing(m, use_gradient_checkpointing)
if hasattr(m, "training"):
m.training = True
if hasattr(m, "_saved_temp_tokenizer"):
@@ -4386,7 +4394,7 @@ class FastBaseModel:
# Since transformers 4.53, this must be turned on explicitly.
for module in model.modules():
if hasattr(module, "gradient_checkpointing"):
- module.gradient_checkpointing = use_gradient_checkpointing
+ set_module_gradient_checkpointing(module, use_gradient_checkpointing)
for _getter in ("get_input_embeddings", "get_output_embeddings"):
embeddings = _embeddings_or_none(model, _getter)