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.

Gradient checkpointing: checkpoint_skip_layers = "auto" and UNSLOTH_GC_KEEP_LAYERS (#14404)

Daniel Hanaf2804159fe5
diff --git a/tests/test_block_swap_install.py b/tests/test_block_swap_install.py
index c92df79d64f..c2c7564274d 100644
--- a/tests/test_block_swap_install.py
+++ b/tests/test_block_swap_install.py
@@ -540,8 +540,8 @@ def test_host_load_runs_for_layers_or_streamed_embeddings_only():
def _load_skip():
src = open(UTILS, encoding = "utf-8").read()
mod = ast.parse(src)
- names = ("_skip_aware_flag", "skip_checkpointing")
- ns = {"find_decoder_layers": lambda m: m.layers}
+ names = ("_skip_aware_flag", "skip_checkpointing", "_gc_keep_layers_env")
+ ns = {"find_decoder_layers": lambda m: m.layers, "os": os}
for n in mod.body:
if isinstance(n, ast.FunctionDef) and n.name in names:
exec(ast.get_source_segment(src, n), ns)
diff --git a/tests/test_gc_skip_auto.py b/tests/test_gc_skip_auto.py
new file mode 100644
index 00000000000..4f042a1b900
--- /dev/null
+++ b/tests/test_gc_skip_auto.py
@@ -0,0 +1,605 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""checkpoint_skip_layers = "auto" / UNSLOTH_GC_KEEP_LAYERS, extracted from _utils.py with ast."""
+
+import ast, logging, os
+import pytest
+import torch
+
+transformers = pytest.importorskip("transformers")
+from transformers import Qwen3Config, Qwen3ForCausalLM
+
+HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+UTILS = os.path.join(HERE, "unsloth", "models", "_utils.py")
+NAMES = (
+ "_skip_aware_flag",
+ "skip_checkpointing",
+ "_gc_keep_layers_env",
+ "_AutoCheckpointSkip",
+ "usable_cuda_bytes",
+ "_size_auto_checkpoint_skip_for_trainer",
+)
+
+
+def _load():
+ src = open(UTILS, encoding = "utf-8").read()
+ ns = {
+ "torch": torch,
+ "os": os,
+ "math": __import__("math"),
+ "_PAIRED_FORWARD_TRAINERS": ("DPOTrainer", "ORPOTrainer", "CPOTrainer"),
+ "logger": logging.getLogger("test_gc_skip_auto"),
+ "find_decoder_layers": lambda m: list(_base(m).model.layers),
+ }
+ found = set()
+ for n in ast.parse(src).body:
+ if isinstance(n, (ast.FunctionDef, ast.ClassDef)) and n.name in NAMES:
+ exec(ast.get_source_segment(src, n), ns)
+ found.add(n.name)
+ return ns, found
+
+
+def _base(model):
+ return getattr(model, "base", model)
+
+
+def _model(layers = 6, device = "cpu"):
+ torch.manual_seed(0)
+ config = Qwen3Config(
+ vocab_size = 128,
+ hidden_size = 64,
+ intermediate_size = 256,
+ num_hidden_layers = layers,
+ num_attention_heads = 4,
+ num_key_value_heads = 2,
+ head_dim = 16,
+ )
+ model = Qwen3ForCausalLM(config).float().to(device).train()
+ model.gradient_checkpointing_enable(gradient_checkpointing_kwargs = {"use_reentrant": True})
+ model.max_seq_length = 64
+ return model
+
+
+def _checkpointed(model):
+ return [bool(layer.gradient_checkpointing) for layer in model.model.layers]
+
+
+def test_zero_and_unset_env_change_nothing(monkeypatch):
+ ns, found = _load()
+ monkeypatch.delenv("UNSLOTH_GC_KEEP_LAYERS", raising = False)
+ model = _model()
+ hooks = dict(model._forward_pre_hooks)
+ assert ns["skip_checkpointing"](model, 0) == []
+ assert _checkpointed(model) == [True] * 6
+ assert dict(model._forward_pre_hooks) == hooks
+ assert not hasattr(model, "_unsloth_auto_skip")
+
+
+ "value, expected", [("3", 3), ("max", "max"), ("auto", "auto"), ("0", 0), ("x", 0)]
+)
+def test_env_parsing(monkeypatch, value, expected):
+ ns, found = _load()
+ assert "_gc_keep_layers_env" in found, "UNSLOTH_GC_KEEP_LAYERS is not implemented"
+ monkeypatch.setenv("UNSLOTH_GC_KEEP_LAYERS", value)
+ assert ns["_gc_keep_layers_env"]() == expected
+
+
+def test_env_count_applies_when_argument_is_zero(monkeypatch):
+ ns, found = _load()
+ monkeypatch.setenv("UNSLOTH_GC_KEEP_LAYERS", "2")
+ model = _model()
+ assert ns["skip_checkpointing"](model, 0) == [2, 5]
+ assert _checkpointed(model) == [True, True, False, True, True, False]
+
+
+def _step(model, ids):
+ model.zero_grad(set_to_none = True)
+ loss = model(input_ids = ids, labels = ids).loss
+ loss.backward()
+ return loss.detach(), {
+ n: p.grad.detach().clone() for n, p in model.named_parameters() if p.grad is not None
+ }
+
+
[email protected](not torch.cuda.is_available(), reason = "the auto planner sizes CUDA memory")
+def test_auto_plans_after_first_step_and_keeps_gradients():
+ ns, found = _load()
+ assert "_AutoCheckpointSkip" in found, 'checkpoint_skip_layers = "auto" is not implemented'
+ ids = torch.randint(0, 128, (2, 64), generator = torch.Generator().manual_seed(1)).cuda()
+
+ reference = _model(device = "cuda")
+ ref = [_step(reference, ids) for _ in range(3)]
+
+ model = _model(device = "cuda")
+ hooks = dict(model._forward_pre_hooks)
+ assert ns["skip_checkpointing"](model, "auto") == []
+ planner = model._unsloth_auto_skip
+ first = _step(model, ids)
+ assert _checkpointed(model) == [True] * 6
+ assert planner.layer_bytes and planner.layer_bytes > 0
+ second = _step(model, ids)
+ third = _step(model, ids)
+ assert planner.kept == [0, 1, 2, 3, 4, 5]
+ assert _checkpointed(model) == [False] * 6
+ assert not hasattr(model, "_unsloth_auto_skip")
+ assert dict(model._forward_pre_hooks) == hooks and not model.model.layers[-1]._forward_hooks
+ for (loss, grads), (ref_loss, ref_grads) in zip((first, second, third), ref):
+ assert torch.equal(loss, ref_loss)
+ assert grads.keys() == ref_grads.keys()
+ for name in grads:
+ torch.testing.assert_close(grads[name], ref_grads[name], rtol = 0, atol = 0, msg = name)
+
+
[email protected](not torch.cuda.is_available(), reason = "the auto planner sizes CUDA memory")
+def test_auto_keeps_everything_checkpointed_without_headroom(monkeypatch):
+ ns, found = _load()
+ ids = torch.randint(0, 128, (2, 64), generator = torch.Generator().manual_seed(1)).cuda()
+ model = _model(device = "cuda")
+ ns["skip_checkpointing"](model, "auto")
+ planner = model._unsloth_auto_skip
+ total = torch.cuda.get_device_properties(0).total_memory
+ monkeypatch.setattr(torch.cuda, "mem_get_info", lambda device = None: (1 << 20, total))
+ monkeypatch.setattr(torch.cuda, "memory_reserved", lambda device = None: 0)
+ _step(model, ids)
+ _step(model, ids)
+ assert planner.kept == []
+ assert _checkpointed(model) == [True] * 6
+
+
[email protected](not torch.cuda.is_available(), reason = "the auto planner sizes CUDA memory")
+def test_auto_backs_off_without_reentrant_checkpointing():
+ ns, found = _load()
+ ids = torch.randint(0, 128, (2, 64), generator = torch.Generator().manual_seed(1)).cuda()
+ model = _model(device = "cuda")
+ model.gradient_checkpointing_enable(gradient_checkpointing_kwargs = {"use_reentrant": False})
+ ns["skip_checkpointing"](model, "auto")
+ _step(model, ids)
+ _step(model, ids)
+ assert not hasattr(model, "_unsloth_auto_skip")
+ assert _checkpointed(model) == [True] * 6
+
+
+def test_auto_without_cuda_says_so_once(monkeypatch, capsys):
+ ns, found = _load()
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: False)
+ model = _model()
+ assert ns["skip_checkpointing"](model, "auto") == []
+ assert ns["skip_checkpointing"](model, "auto") == []
+ out = capsys.readouterr().out
+ assert out.count("needs a CUDA GPU") == 1, out
+ assert _checkpointed(model) == [True] * 6
+ assert not hasattr(model, "_unsloth_auto_skip")
+
+
[email protected](not torch.cuda.is_available(), reason = "the auto planner sizes CUDA memory")
+def test_auto_ignores_allocation_spike_before_first_step():
+ ns, found = _load()
+ ids = torch.randint(0, 128, (2, 64), generator = torch.Generator().manual_seed(1)).cuda()
+ model = _model(device = "cuda")
+ ns["skip_checkpointing"](model, "auto")
+ planner = model._unsloth_auto_skip
+ # 3 GiB usable; a 2 GiB loading spike before training must not be read as activations.
+ ns["usable_cuda_bytes"] = lambda device: 3 << 30
+ spike = torch.empty(2 << 30, dtype = torch.uint8, device = "cuda")
+ del spike
+ _step(model, ids)
+ _step(model, ids)
+ assert planner.kept == [0, 1, 2, 3, 4, 5]
+ assert _checkpointed(model) == [False] * 6
+
+
+def _big_model():
+ torch.manual_seed(0)
+ config = Qwen3Config(
+ vocab_size = 32000,
+ hidden_size = 1024,
+ intermediate_size = 4096,
+ num_hidden_layers = 6,
+ num_attention_heads = 8,
+ num_key_value_heads = 4,
+ head_dim = 128,
+ )
+ model = Qwen3ForCausalLM(config).float().cuda().train()
+ model.gradient_checkpointing_enable(gradient_checkpointing_kwargs = {"use_reentrant": True})
+ model.max_seq_length = 64
+ return model
+
+
[email protected](not torch.cuda.is_available(), reason = "the auto planner sizes CUDA memory")
[email protected]("optimizer_stepped", [True, False])
+def test_auto_reserves_optimizer_state_only_when_not_allocated(optimizer_stepped):
+ ns, found = _load()
+ ids = torch.randint(0, 32000, (2, 64), generator = torch.Generator().manual_seed(1)).cuda()
+ model = _big_model()
+ numel = sum(p.numel() for p in model.parameters())
+ assert numel * 8 > (1 << 30) # AdamW state well above the planner's slack
+ ns["skip_checkpointing"](model, "auto")
+ planner = model._unsloth_auto_skip
+ optimizer = torch.optim.AdamW(model.parameters(), lr = 1e-5)
+ # Usable after step 1: grads + foreach AdamW workspace + 1.6 GiB.
+ ns["usable_cuda_bytes"] = lambda device: numel * 8 + int(1.6 * (1 << 30))
+ model(input_ids = ids, labels = ids).loss.backward()
+ if optimizer_stepped:
+ optimizer.step()
+ optimizer.zero_grad(set_to_none = True)
+ model(input_ids = ids, labels = ids).loss.backward()
+ if optimizer_stepped:
+ # Full finetuning: the state is in memory_allocated already and must not be reserved again.
+ assert planner.kept == [0, 1, 2, 3, 4, 5]
+ else:
+ # Gradient accumulation: the state does not exist yet, so it is reserved and nothing fits.
+ assert planner.kept == []
+ del optimizer, model
+ torch.cuda.empty_cache()
+
+
+def test_auto_with_model_off_cuda_on_a_cuda_host_installs_nothing(monkeypatch, capsys):
+ from torch.optim import optimizer as torch_optimizer
+
+ ns, found = _load()
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
+ global_hooks = dict(getattr(torch_optimizer, "_global_optimizer_pre_hooks", {}))
+ model = _model()
+ hooks = dict(model._forward_pre_hooks)
+ assert ns["skip_checkpointing"](model, "auto") == []
+ assert ns["skip_checkpointing"](model, "auto") == []
+ out = capsys.readouterr().out
+ assert out.count("needs a CUDA GPU") == 1, out
+ assert not hasattr(model, "_unsloth_auto_skip")
+ assert dict(model._forward_pre_hooks) == hooks
+ assert not model.model.layers[-1]._forward_hooks
+ assert dict(getattr(torch_optimizer, "_global_optimizer_pre_hooks", {})) == global_hooks
+
+
[email protected](not torch.cuda.is_available(), reason = "the auto planner sizes CUDA memory")
+def test_auto_reserves_state_for_params_the_optimizer_has_not_seen():
+ ns, found = _load()
+ ids = torch.randint(0, 32000, (2, 64), generator = torch.Generator().manual_seed(1)).cuda()
+ model = _big_model()
+ numel = sum(p.numel() for p in model.parameters())
+ # A trainable param the first batch never reaches (an unrouted MoE expert, an unused tower).
+ model.unused = torch.nn.Parameter(torch.zeros(1 << 27, device = "cuda"))
+ assert model.unused.numel() * 8 >= (1 << 30)
+ ns["skip_checkpointing"](model, "auto")
+ planner = model._unsloth_auto_skip
+ optimizer = torch.optim.AdamW(model.parameters(), lr = 1e-5)
+ ns["usable_cuda_bytes"] = lambda device: numel * 4 + int(1.6 * (1 << 30))
+ model(input_ids = ids, labels = ids).loss.backward()
+ assert model.unused.grad is None
+ optimizer.step()
+ optimizer.zero_grad(set_to_none = True)
+ assert model.unused not in optimizer.state
+ model(input_ids = ids, labels = ids).loss.backward()
+ # main: one step happened, so nothing is reserved for `unused` and every layer is kept.
+ assert planner.kept == []
+ del optimizer, model
+ torch.cuda.empty_cache()
+
+
[email protected](not torch.cuda.is_available(), reason = "the auto planner sizes CUDA memory")
+def test_auto_does_not_scale_persistent_grads_by_sequence_length():
+ ns, found = _load()
+ model = _big_model()
+ numel = sum(p.numel() for p in model.parameters())
+ model.max_seq_length = 1024
+ short = torch.randint(0, 32000, (1, 64), generator = torch.Generator().manual_seed(1)).cuda()
+ ns["skip_checkpointing"](model, "auto")
+ planner = model._unsloth_auto_skip
+ optimizer = torch.optim.AdamW(model.parameters(), lr = 1e-5)
+ # Room for 16x the short batch's activations, but not for 16x the fp32 grads it allocated.
+ usable = numel * 4 * 6
+ ns["usable_cuda_bytes"] = lambda device: usable
+ model(input_ids = short, labels = short).loss.backward()
+ optimizer.step()
+ optimizer.zero_grad(set_to_none = True)
+ model(input_ids = short, labels = short).loss.backward()
+ assert planner.layer_rows == 64
+ # main: (activations + grads) x 16 leaves no headroom, so nothing is kept.
+ assert planner.kept == [0, 1, 2, 3, 4, 5]
+ del optimizer, model
+ torch.cuda.empty_cache()
+
+
+class _FakeLayer(torch.nn.Module):
+ """A decoder layer whose recompute leaves `cost` fake CUDA bytes behind."""
+
+ def __init__(self, cost, memory):
+ super().__init__()
+ self.weight = torch.nn.Parameter(torch.zeros(1), requires_grad = False)
+ self.gradient_checkpointing = True
+ self.cost, self.memory = cost, memory
+
+ def forward(self, hidden):
+ if torch.is_grad_enabled():
+ self.memory["allocated"] += self.cost
+ return hidden
+
+
+class _FakeModel(torch.nn.Module):
+ def __init__(
+ self,
+ costs,
+ memory,
+ attn = "sdpa",
+ ):
+ super().__init__()
+ self.model = torch.nn.Module()
+ self.model.layers = torch.nn.ModuleList(_FakeLayer(c, memory) for c in costs)
+ self.config = type("Config", (), {"_attn_implementation": attn})()
+ self.max_seq_length = 16
+
+ def forward(self, hidden):
+ return hidden
+
+
+def _fake_cuda(monkeypatch, ns, usable):
+ """CPU stand-ins for the CUDA calls the planner makes; memory_allocated is a counter."""
+ memory = {"allocated": 0}
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
+ monkeypatch.setattr(torch.Tensor, "is_cuda", property(lambda self: True))
+ monkeypatch.setattr(torch.cuda, "reset_peak_memory_stats", lambda device = None: None)
+ monkeypatch.setattr(torch.cuda, "memory_allocated", lambda device = None: memory["allocated"])
+ monkeypatch.setattr(torch.cuda, "max_memory_allocated", lambda device = None: memory["allocated"])
+ ns["usable_cuda_bytes"] = lambda device: usable
+ return memory
+
+
+def _fake_step(model, rows):
+ """One reentrant-checkpointed step: no_grad forward of every layer, recompute in reverse."""
+ hidden = torch.zeros(1, rows, 4)
+ model(hidden)
+ with torch.no_grad():
+ for layer in model.model.layers:
+ layer(hidden)
+ for layer in reversed(model.model.layers):
+ layer(hidden)
+
+
+def test_auto_sizes_by_the_most_expensive_layer_type(monkeypatch):
+ ns, found = _load()
+ gib = 1 << 30
+ costs = [gib, gib // 8] * 4
+ memory = _fake_cuda(monkeypatch, ns, usable = 10 * gib)
+ model = _FakeModel(costs, memory)
+ ns["skip_checkpointing"](model, "auto")
+ planner = model._unsloth_auto_skip
+ _fake_step(model, rows = 16)
+ model(torch.zeros(1, 16, 4))
+ assert planner.layer_bytes == gib
+ # (10 GiB - 4.5 GiB step) * 0.75 - 1 GiB = 3.125 GiB: 3 one-GiB layers, not 25 eighth-GiB ones.
+ assert len(planner.kept) == 3
+ monkeypatch.undo()
+
+
[email protected]("attn, exponent", [("sdpa", 1), ("flash_attention_2", 1), ("eager", 2)])
+def test_auto_scales_eager_attention_quadratically(monkeypatch, attn, exponent):
+ ns, found = _load()
+ gib = 1 << 30
+ memory = _fake_cuda(monkeypatch, ns, usable = 12 * gib)
+ model = _FakeModel([gib // 16] * 8, memory, attn = attn)
+ model.max_seq_length = 64 # 4x the probed 16 rows
+ ns["skip_checkpointing"](model, "auto")
+ planner = model._unsloth_auto_skip
+ _fake_step(model, rows = 16)
+ model(torch.zeros(1, 16, 4))
+ scale = 4**exponent
+ step = 8 * (gib // 16)
+ budget = (12 * gib - step * scale) * 0.75 - gib
+ assert len(planner.kept) == min(8, int(budget // (gib // 16 * scale)))
+ # Linear: 8 of 8 fit. Quadratic: a 4x longer batch costs 16x, so only 2 do.
+ assert len(planner.kept) == (8 if exponent == 1 else 2)
+ monkeypatch.undo()
+
+
+def test_auto_planner_does_not_keep_an_unplanned_model_alive(monkeypatch):
+ import gc, weakref
+ from torch.optim import optimizer as torch_optimizer
+
+ ns, found = _load()
+ global_hooks = dict(getattr(torch_optimizer, "_global_optimizer_pre_hooks", {}))
+ memory = _fake_cuda(monkeypatch, ns, usable = 1 << 30)
+ model = _FakeModel([1] * 4, memory)
+ ns["skip_checkpointing"](model, "auto")
+ assert model._unsloth_auto_skip is not None
+ alive = weakref.ref(model)
+ del model
+ gc.collect()
+ assert alive() is None, "the global optimizer hook kept the model alive"
+ assert dict(getattr(torch_optimizer, "_global_optimizer_pre_hooks", {})) == global_hooks
+ monkeypatch.undo()
+
+
[email protected]("path", ["llama.py", "vision.py"])
+def test_full_finetuning_early_return_applies_checkpoint_skip(path):
+ src = open(os.path.join(HERE, "unsloth", "models", path), encoding = "utf-8").read()
+ mod = ast.parse(src)
+ fn = next(
+ f
+ for cls in mod.body
+ if isinstance(cls, ast.ClassDef)
+ for f in cls.body
+ if isinstance(f, ast.FunctionDef) and f.name == "get_peft_model"
+ )
+ branches = [
+ node
+ for node in ast.walk(fn)
+ if isinstance(node, ast.If)
+ and "UNSLOTH_ENABLE_FULL_FINETUNING" in ast.get_source_segment(src, node.test)
+ and isinstance(node.body[-1], ast.Return)
+ ]
+ assert branches, f"full finetuning early return not found in {path}"
+ for branch in branches:
+ calls = [
+ c
+ for stmt in branch.body
+ for c in ast.walk(stmt)
+ if isinstance(c, ast.Call) and getattr(c.func, "id", None) == "skip_checkpointing"
+ ]
+ assert calls and any(
+ getattr(a, "id", None) == "checkpoint_skip_layers" for c in calls for a in c.args
+ ), f"{path}: full finetuning returns before checkpoint_skip_layers is applied"
+
+
+def test_auto_sizes_for_the_trainer_batch_not_the_first_one(monkeypatch):
+ ns, found = _load()
+ gib = 1 << 30
+ memory = _fake_cuda(monkeypatch, ns, usable = 4 * gib)
+ model = _FakeModel([gib // 16] * 8, memory)
+ ns["skip_checkpointing"](model, "auto")
+ planner = model._unsloth_auto_skip
+ trainer = type("SFTTrainer", (), {})()
+ trainer.model = model
+ trainer.args = type("Args", (), {"per_device_train_batch_size": 4, "max_length": None})()
+ ns["_size_auto_checkpoint_skip_for_trainer"](trainer)
+ _fake_step(model, rows = 16) # first batch: 1 row at max_seq_length
+ model(torch.zeros(1, 16, 4))
+ # Sized for 4 rows: (4 GiB - 2 GiB) * 0.75 - 1 GiB = 0.5 GiB, two 0.25 GiB layers (not all 8).
+ assert planner.target_batch == 4
+ assert len(planner.kept) == 2
+ monkeypatch.undo()
+
+
+def test_auto_ignores_gradients_on_another_gpu(monkeypatch):
+ ns, found = _load()
+ gib = 1 << 30
+ memory = _fake_cuda(monkeypatch, ns, usable = 5 * gib)
+ model = _FakeModel([gib // 16] * 8, memory)
+ model.max_seq_length = 64 # 4x the probed rows
+ # A trainable vision tower on another card ("meta" stands in for cuda:1).
+ model.tower = torch.nn.Parameter(torch.empty(gib // 8, device = "meta"))
+ ns["skip_checkpointing"](model, "auto")
+ planner = model._unsloth_auto_skip
+ _fake_step(model, rows = 16)
+ model.tower.grad = torch.empty(gib // 8, device = "meta") # 0.5 GiB, not on the planned card
+ model(torch.zeros(1, 16, 4))
+ # 0.5 GiB step x 4 = 2 GiB activations, tower AdamW state on its own card: (5 - 2) * 0.75 - 1 =
+ # 1.25 GiB, five 0.25 GiB layers.
+ assert len(planner.kept) == 5
+ monkeypatch.undo()
+
+
+def test_auto_still_plans_when_the_probe_layer_moves_to_host(monkeypatch):
+ ns, found = _load()
+ gib = 1 << 30
+ memory = _fake_cuda(monkeypatch, ns, usable = 10 * gib)
+ monkeypatch.setattr(torch.Tensor, "is_cuda", property(lambda self: self.device.type != "meta"))
+ model = _FakeModel([gib // 16] * 8, memory)
+ ns["skip_checkpointing"](model, "auto")
+ planner = model._unsloth_auto_skip
+ # offload_layers = "auto" re-plans for the trainer and swaps the last layer (the probe) to host.
+ model.model.layers[-1].to("meta")
+ _fake_step(model, rows = 16)
+ model(torch.zeros(1, 16, 4))
+ assert planner.kept is not None and len(planner.kept) > 0
+ monkeypatch.undo()
+
+
+def test_auto_never_scales_below_the_measured_length(monkeypatch):
+ ns, found = _load()
+ gib = 1 << 30
+ memory = _fake_cuda(monkeypatch, ns, usable = 4 * gib)
+ model = _FakeModel([gib // 16] * 8, memory) # max_seq_length 16
+ ns["skip_checkpointing"](model, "auto")
+ planner = model._unsloth_auto_skip
+ planner.target_batch = 4
+ _fake_step(model, rows = 64) # a collator expanded the batch past max_seq_length
+ model(torch.zeros(1, 64, 4))
+ # 4 rows x 64 measured tokens: scale 4, not 4 x 16 / 64 = 1.
+ # (4 GiB - 2 GiB) * 0.75 - 1 GiB = 0.5 GiB, two 0.25 GiB layers (before: all 8).
+ assert len(planner.kept) == 2
+ monkeypatch.undo()
+
+
+def _trainable_head(model, numel):
+ # Expanded: numel elements of bookkeeping without allocating them.
+ model.head = torch.nn.Parameter(torch.zeros(1).expand(numel))
+ return model.head
+
+
[email protected]("accumulating", [True, False])
+def test_auto_counts_resident_accumulated_grads_once(monkeypatch, accumulating):
+ ns, found = _load()
+ gib = 1 << 30
+ numel = gib // 8 # fp32 grad 0.5 GiB, AdamW state + foreach workspace 1.5 GiB
+ # Resident grads are allocated, so the card has that much less usable memory.
+ memory = _fake_cuda(monkeypatch, ns, usable = 4 * gib - (gib // 2 if accumulating else 0))
+ model = _FakeModel([gib // 16] * 8, memory)
+ head = _trainable_head(model, numel)
+ ns["skip_checkpointing"](model, "auto")
+ planner = model._unsloth_auto_skip
+ _fake_step(model, rows = 16)
+ head.grad = torch.zeros(1).expand(numel)
+ memory["allocated"] += gib // 2
+ if not accumulating:
+ planner._optimizer_pre_hook(torch.optim.SGD([head], lr = 0.1), (), {})
+ head.grad = None
+ memory["allocated"] -= gib // 2
+ model(torch.zeros(1, 16, 4))
+ # Both: (4 GiB - 0.5 GiB activations - 0.5 GiB grads - 1.5 GiB) * 0.75 - 1 GiB = 0.125 GiB.
+ assert len(planner.kept) == 2
+ monkeypatch.undo()
+
+
+def test_auto_reserves_the_foreach_optimizer_workspace(monkeypatch):
+ ns, found = _load()
+ gib = 1 << 30
+ numel = gib // 8
+ memory = _fake_cuda(monkeypatch, ns, usable = 3 * gib)
+ model = _FakeModel([gib // 16] * 8, memory)
+ head = _trainable_head(model, numel)
+ ns["skip_checkpointing"](model, "auto")
+ planner = model._unsloth_auto_skip
+ _fake_step(model, rows = 16)
+ head.grad = torch.zeros(1).expand(numel)
+ memory["allocated"] += gib // 2
+ optimizer = torch.optim.AdamW([head])
+ planner._optimizer_pre_hook(optimizer, (), {})
+ optimizer.state[head] = {"step": torch.tensor(1.0)} # state allocated by the first step
+ head.grad = None
+ memory["allocated"] -= gib // 2
+ model(torch.zeros(1, 16, 4))
+ # 0.5 GiB foreach workspace still reserved: (3 - 1 - 0.5) * 0.75 - 1 = 0.125 GiB, two layers.
+ assert len(planner.kept) == 2
+ monkeypatch.undo()
+
+
+def test_explicit_value_removes_an_earlier_auto_planner(monkeypatch):
+ ns, found = _load()
+ gib = 1 << 30
+ memory = _fake_cuda(monkeypatch, ns, usable = 10 * gib)
+ model = _FakeModel([gib // 16] * 8, memory)
+ ns["skip_checkpointing"](model, "auto")
+ planner = model._unsloth_auto_skip
+ monkeypatch.delenv("UNSLOTH_GC_KEEP_LAYERS", raising = False)
+ ns["skip_checkpointing"](model, 0)
+ assert not hasattr(model, "_unsloth_auto_skip") and planner.handles == []
+ _fake_step(model, rows = 16)
+ model(torch.zeros(1, 16, 4))
+ assert planner.kept is None
+ monkeypatch.undo()
+
+
+def test_auto_reserves_pending_state_only_on_the_planned_card(monkeypatch):
+ ns, found = _load()
+ gib = 1 << 30
+ memory = _fake_cuda(monkeypatch, ns, usable = 3 * gib)
+ model = _FakeModel([gib // 16] * 8, memory)
+ # A large trainable tower on another card ("meta" stands in for cuda:1): its AdamW state lives there.
+ model.tower = torch.nn.Parameter(torch.empty(gib, device = "meta"))
+ ns["skip_checkpointing"](model, "auto")
+ planner = model._unsloth_auto_skip
+ _fake_step(model, rows = 16)
+ model(torch.zeros(1, 16, 4))
+ # (3 - 0.5) * 0.75 - 1 = 0.875 GiB: all 8 layers (before: 8 GiB tower state, nothing kept).
+ assert len(planner.kept) == 8
+ monkeypatch.undo()
+
+
+def test_counts_apply_only_to_checkpointable_layers():
+ ns, found = _load()
+ model = _FakeModel([1] * 6, {"allocated": 0})
+ for i in (1, 3, 5):
+ model.model.layers[i] = torch.nn.Linear(4, 4)
+ assert ns["skip_checkpointing"](model, 3) == [0, 2, 4]
diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.py
index 764d23980d2..196678644c7 100644
--- a/unsloth/models/_utils.py
+++ b/unsloth/models/_utils.py
@@ -5611,6 +5611,7 @@ def patch_gradient_accumulation_fix(Trainer):
from .llama import _decline_fused_lora_for_fsdp
_decline_fused_lora_for_fsdp(getattr(self, "model", None), reason)
_replan_auto_offload_safely(self)
+ _size_auto_checkpoint_skip_for_trainer(self)
_block_swap_for_trainer_backend(self)
_enable_ddp_batched_grad_copy(self)
from ._ddp_defaults import install_unsloth_ddp_comm_defaults
@@ -8422,16 +8423,328 @@ def _skip_aware_flag(cls):
cls._unsloth_skip_aware = True
+def _gc_keep_layers_env():
+ value = os.environ.get("UNSLOTH_GC_KEEP_LAYERS", "").strip().lower()
+ if value in ("", "0"):
+ return 0
+ if value in ("auto", "max"):
+ return value
+ try:
+ return max(0, int(value))
+ except ValueError:
+ logger.warning(
+ f"Unsloth: UNSLOTH_GC_KEEP_LAYERS = {value!r} is not K, max or auto; ignored."
+ )
+ return 0
+
+
+class _AutoCheckpointSkip:
+ """checkpoint_skip_layers = "auto": once, after step 1, un-checkpoint as many layers as fit.
+ Per-layer cost = the largest allocation any eligible layer's reentrant recompute leaves in the
+ first backward (hybrid stacks mix attention and Mamba blocks); AdamW state is reserved for every
+ trainable param the optimizer has no state for yet. Sized for the trainer batch at the longest of
+ max_length, max_seq_length and the measured length: inputs a collator expands past that (images,
+ audio) need max_seq_length set to their bound. Single process only: under torchrun each rank
+ would pick its own K."""
+
+ MARGIN = 1 << 30
+ FRACTION = 0.75
+ _warned_no_cuda = False
+
+ def __init__(self, model, layers, probe):
+ self.model = model
+ self.layers = layers
+ self.probe = probe
+ self.handles = []
+ self.started = None
+ self.no_grad_forward = False
+ self.before = None
+ self.measured = set()
+ self.layer_bytes = None
+ self.layer_rows = 1
+ self.layer_batch = 1
+ self.target_batch = None
+ self.target_seq = None
+ self.kept = None
+ self.step_peak = None
+ self.stepped = False
+ self.optimizers = []
+ self.fresh_grads = None
+ self.grad_bytes = None
+
+ @classmethod
+ def _no_cuda(cls):
+ if not cls._warned_no_cuda:
+ cls._warned_no_cuda = True
+ print(
+ 'Unsloth: checkpoint_skip_layers = "auto" needs a CUDA GPU; every layer stays checkpointed.'
+ )
+ return None
+
+ @classmethod
+ def install(cls, model):
+ if not torch.cuda.is_available():
+ return cls._no_cuda()
+ try:
+ from .loader_utils import is_distributed
+ distributed = is_distributed()
+ except Exception:
+ distributed = False
+ if distributed:
+ print(
+ 'Unsloth: checkpoint_skip_layers = "auto" is single process only; every layer stays checkpointed.'
+ )
+ return None
+ previous = getattr(model, "_unsloth_auto_skip", None)
+ if previous is not None:
+ previous.remove()
+ layers = find_decoder_layers(model) if find_decoder_layers is not None else []
+ swapper = getattr(model, "_unsloth_block_swap", None)
+ swapped = set(getattr(swapper, "indices", None) or ())
+ eligible = [
+ i
+ for i, layer in enumerate(layers)
+ if i not in swapped and hasattr(layer, "gradient_checkpointing")
+ ]
+ if not eligible:
+ return None
+ devices = {p.device for layer in layers for p in layer.parameters() if p.is_cuda}
+ if not devices:
+ # Model on CPU / XPU on a CUDA host: the hooks would never run (and keep the model alive).
+ return cls._no_cuda()
+ if len(devices) > 1:
+ print(
+ 'Unsloth: checkpoint_skip_layers = "auto" sizes one GPU; the layers span several, so every layer stays checkpointed.'
+ )
+ return None
+ import functools, weakref
+
+ self = cls(model, layers, layers[eligible[-1]])
+ self.device = next(iter(devices))
+ self.handles.append(model.register_forward_pre_hook(self._model_pre_hook))
+ for i in eligible:
+ layer = layers[i]
+ self.handles.append(
+ layer.register_forward_pre_hook(functools.partial(self._probe_pre_hook, i))
+ )
+ self.handles.append(layer.register_forward_hook(functools.partial(self._probe_hook, i)))
+ try:
+ from torch.optim.optimizer import register_optimizer_step_pre_hook
+ except ImportError:
+ register_optimizer_step_pre_hook = None
+ if register_optimizer_step_pre_hook is not None:
+ # The global registry must not keep the planner (and so the model) alive if plan() never runs.
+ planner_ref = weakref.ref(self)
+
+ def _optimizer_pre_hook(optimizer, args, kwargs):
+ planner = planner_ref()
+ if planner is not None:
+ planner._optimizer_pre_hook(optimizer, args, kwargs)
+
+ handle = register_optimizer_step_pre_hook(_optimizer_pre_hook)
+ self.handles.append(handle)
+ weakref.finalize(self, handle.remove)
+ model._unsloth_auto_skip = self
+ return self
+
+ def remove(self):
+ for handle in self.handles:
+ handle.remove()
+ self.handles = []
+ if getattr(self.model, "_unsloth_auto_skip", None) is self:
+ del self.model._unsloth_auto_skip
+
+ def _plan_device(self):
+ # Not one layer's: offload_layers = "auto" may re-plan after install and move any layer to host.
+ for layer in self.layers:
+ for p in layer.parameters():
+ if p.is_cuda:
+ return p.device
+ return None
+
+ def _model_pre_hook(self, module, args):
+ if not module.training or not torch.is_grad_enabled():
+ return
+ device = self._plan_device()
+ if device is None:
+ return
+ if self.started is None:
+ # Step-local peak: a model-loading spike must not count as activations.
+ torch.cuda.reset_peak_memory_stats(device)
+ self.started = torch.cuda.memory_allocated(device)
+ # Grads the first backward allocates persist: they are not sequence-dependent.
+ self.fresh_grads = [
+ p for p in self.model.parameters() if p.requires_grad and p.grad is None
+ ]
+ return
+ if self.layer_bytes is not None:
+ self.plan(device)
+
+ def _probe_pre_hook(self, index, module, args):
+ if self.started is None or index in self.measured or not module.training:
+ return
+ if not torch.is_grad_enabled():
+ # The reentrant checkpoint's own forward: the next grad-mode call is its recompute.
+ self.no_grad_forward = True
+ return
+ if not self.no_grad_forward:
+ print(
+ 'Unsloth: checkpoint_skip_layers = "auto" needs reentrant gradient checkpointing; unchanged.'
+ )
+ self.remove()
+ return
+ hidden = args[0] if args and torch.is_tensor(args[0]) else None
+ if hidden is not None and hidden.is_cuda:
+ self.layer_rows = hidden.shape[-2] if hidden.dim() >= 3 else hidden.shape[0]
+ self.layer_batch = math.prod(hidden.shape[:-2]) if hidden.dim() >= 3 else 1
+ self.before = (index, torch.cuda.memory_allocated(hidden.device), hidden.device)
+
+ def _probe_hook(self, index, module, args, output):
+ if self.before is None or self.before[0] != index or index in self.measured:
+ return
+ device = self.before[2]
+ cost = max(0, torch.cuda.memory_allocated(device) - self.before[1])
+ self.measured.add(index)
+ # Conservative: the most expensive layer type sizes every kept layer.
+ self.layer_bytes = max(self.layer_bytes or 0, cost)
+ self.before = None
+
+ def _seq_exponent(self):
+ """Activation growth with sequence length: 1 for SDPA / flash / flex, 2 for anything that
+ materialises the attention matrix (eager) or cannot be identified."""
+ config = getattr(self.model, "config", None)
+ text_config = config
+ get_text_config = getattr(config, "get_text_config", None)
+ if callable(get_text_config):
+ try:
+ text_config = get_text_config()
+ except Exception:
+ text_config = config
+ impl = getattr(text_config, "_attn_implementation", None) or getattr(
+ config, "_attn_implementation", None
+ )
+ if isinstance(impl, str) and any(k in impl for k in ("sdpa", "flash", "flex")):
+ return 1
+ return 2
+
+ def _optimizer_pre_hook(self, optimizer, args, kwargs):
+ if self.started is None or self.stepped:
+ return
+ trainable = {id(p) for p in self.model.parameters() if p.requires_grad}
+ if not any(id(p) in trainable for group in optimizer.param_groups for p in group["params"]):
+ return
+ if not any(o() is optimizer for o in self.optimizers):
+ import weakref
+ self.optimizers.append(weakref.ref(optimizer))
+ # Forward + backward peak, before the optimizer allocates its state and temporaries.
+ device = self._plan_device()
+ if self.grad_bytes is None:
+ self.grad_bytes = self._fresh_grad_bytes(device)
+ if device is not None:
+ self.step_peak = torch.cuda.max_memory_allocated(device)
+ self.stepped = True
+
+ def _fresh_grad_bytes(self, device):
+ # Only grads on the planned card are in its step peak (a vision tower may sit on another GPU).
+ return sum(
+ p.grad.numel() * p.grad.element_size()
+ for p in (self.fresh_grads or ())
+ if p.grad is not None and p.grad.is_cuda and p.grad.device == device
+ )
+
+ def _has_optimizer_state(self, param):
+ for ref in self.optimizers:
+ optimizer = ref()
+ if optimizer is not None and optimizer.state.get(param):
+ return True
+ return False
+
+ def plan(self, device):
+ self.remove()
+ allocated_start = self.started
+ peak = (
+ self.step_peak
+ if self.step_peak is not None
+ else torch.cuda.max_memory_allocated(device)
+ )
+ # A short or small first batch (dynamic padding, packing, token-budget batches) under-measures:
+ # size for the trainer's batch x max length tokens, else the measured batch at max_seq_length.
+ rows = max(1, self.layer_rows)
+ # Never below the measured length (multimodal collators can expand past max_seq_length).
+ max_seq = max(rows, self.target_seq or getattr(self.model, "max_seq_length", None) or rows)
+ batch = max(self.target_batch or 0, self.layer_batch)
+ tokens = max(1.0, batch * max_seq / (self.layer_batch * rows))
+ # Eager attention keeps a seq x seq matrix per layer: one more length factor (over-estimates the rest).
+ scale = tokens * max(1.0, max_seq / rows) ** (self._seq_exponent() - 1)
+ # Persistent grads from the first backward are in the peak too; only the rest grows with length.
+ step_bytes = max(0, peak - allocated_start)
+ grad_bytes = (
+ self.grad_bytes if self.grad_bytes is not None else self._fresh_grad_bytes(device)
+ )
+ grad_bytes = min(step_bytes, grad_bytes)
+ # Grads still resident (gradient accumulation) are already outside usable_cuda_bytes.
+ resident = self._fresh_grad_bytes(device) if self.fresh_grads else 0
+ activation_peak = (step_bytes - grad_bytes) * scale + max(0, grad_bytes - resident)
+ self.fresh_grads = None
+ # State an optimizer step already allocated is excluded by usable_cuda_bytes; reserve the rest
+ # (sparse MoE experts, unused towers and gradient accumulation have none yet).
+ trainable = [p for p in self.model.parameters() if p.requires_grad]
+ optimizer = sum(
+ p.numel() * 8
+ for p in trainable
+ if p.device == device and not self._has_optimizer_state(p)
+ )
+ # foreach AdamW allocates about one fp32 copy of the params (sqrt of exp_avg_sq) every step,
+ # on each param's own card.
+ optimizer += sum(p.numel() * 4 for p in trainable if p.device == device)
+ self.optimizers = []
+ headroom = usable_cuda_bytes(device) - activation_peak - optimizer
+ budget = headroom * self.FRACTION - self.MARGIN
+ per_layer = self.layer_bytes * scale
+ count = int(budget // per_layer) if per_layer > 0 and budget > 0 else 0
+ self.kept = skip_checkpointing(self.model, count) if count > 0 else []
+ if self.kept:
+ # Smart offloading learnt the checkpointed-call count in the first step; recount it.
+ try:
+ import unsloth_zoo.gradient_checkpointing as zoo_gc
+ if zoo_gc.CURRENT_GC_INDEX == 0:
+ zoo_gc.FIRST_PASS = True
+ zoo_gc.LAST_GC_INDEX = 0
+ except Exception:
+ pass
+ print(
+ f'Unsloth: checkpoint_skip_layers = "auto" keeps {len(self.kept)} of {len(self.layers)} '
+ f"decoder layers un-checkpointed ({per_layer / 2**30:.2f} GB each, "
+ f"{max(0, headroom) / 2**30:.1f} GB headroom)."
+ )
+ return self.kept
+
+
def skip_checkpointing(model, layers = 0):
"""get_peft_model(checkpoint_skip_layers = K | "max"): K decoder layers (evenly spaced; "max" =
all) keep their activations instead of recomputing them in backward. Faster, at the cost of
- each layer's activations on the card. Block-swapped layers keep checkpointing."""
+ each layer's activations on the card. Block-swapped layers keep checkpointing. "auto" (or
+ UNSLOTH_GC_KEEP_LAYERS when 0): _AutoCheckpointSkip."""
+ if not layers:
+ layers = _gc_keep_layers_env()
+ if layers != "auto":
+ # An explicit value replaces an earlier "auto" planner on the same model.
+ planner = getattr(model, "_unsloth_auto_skip", None)
+ if planner is not None:
+ planner.remove()
if not layers:
return []
+ if layers == "auto":
+ _AutoCheckpointSkip.install(model)
+ return []
layer_list = find_decoder_layers(model)
swapper = getattr(model, "_unsloth_block_swap", None)
swapped = set(getattr(swapper, "indices", None) or ())
- eligible = [i for i in range(len(layer_list)) if i not in swapped]
+ eligible = [
+ i
+ for i, layer in enumerate(layer_list)
+ if i not in swapped and hasattr(layer, "gradient_checkpointing")
+ ]
if layers == "max":
chosen = eligible
else:
@@ -8964,6 +9277,22 @@ def _trainer_offload_replan_skip(trainer):
return None
+def _size_auto_checkpoint_skip_for_trainer(trainer):
+ """checkpoint_skip_layers = "auto" sizes for the trainer's full batch, not only the first one."""
+ model = getattr(trainer, "model", None)
+ planner = getattr(model, "_unsloth_auto_skip", None)
+ if not isinstance(planner, _AutoCheckpointSkip):
+ return
+ args = getattr(trainer, "args", None)
+ batch_size = getattr(args, "per_device_train_batch_size", None)
+ if isinstance(batch_size, int) and batch_size > 0:
+ pairs = any(c.__name__.endswith(_PAIRED_FORWARD_TRAINERS) for c in type(trainer).__mro__)
+ planner.target_batch = batch_size * (2 if pairs else 1)
+ seq_len = getattr(args, "max_length", None) or getattr(args, "max_seq_length", None)
+ if isinstance(seq_len, int) and seq_len > 0:
+ planner.target_seq = max(seq_len, getattr(model, "max_seq_length", None) or 0)
+
+
def replan_auto_offload_for_trainer(trainer):
"""Swap more layers when the trainer's real batch does not fit the attach-time "auto" plan; never fewer."""
model = getattr(trainer, "model", None)
diff --git a/unsloth/models/llama.py b/unsloth/models/llama.py
index d3dcbd456ea..46a606b778e 100644
--- a/unsloth/models/llama.py
+++ b/unsloth/models/llama.py
@@ -4392,6 +4392,8 @@ class FastLlamaModel:
# Full finetuning still compiles, so a stray pre-train forward can poison the cache; install the
# detector here too (idempotent).
_unsloth_install_pretrain_detector(model)
+ # checkpoint_skip_layers / UNSLOTH_GC_KEEP_LAYERS apply to full finetuning too.
+ skip_checkpointing(model, checkpoint_skip_layers)
return model
transformers_set_seed(random_state)
diff --git a/unsloth/models/vision.py b/unsloth/models/vision.py
index 5d473ed80f2..2771170fcf7 100644
--- a/unsloth/models/vision.py
+++ b/unsloth/models/vision.py
@@ -4629,6 +4629,8 @@ class FastBaseModel:
print("Unsloth: Full finetuning is enabled, so .get_peft_model has no effect")
# Full finetuning still compiles, so a stray pre-train forward can poison the cache; install the detector here too (idempotent).
_unsloth_install_pretrain_detector(model)
+ # checkpoint_skip_layers / UNSLOTH_GC_KEEP_LAYERS apply to full finetuning too.
+ skip_checkpointing(model, checkpoint_skip_layers)
return model
transformers_set_seed(random_state)