Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

fix(unsloth): honour training.gradient_checkpointing on the Unsloth path (#1981)

Abhishek Jha8f5d4a6ce0ff
diff --git a/changelog.d/0.76.0/1981.fixed.md b/changelog.d/0.76.0/1981.fixed.md
new file mode 100644
index 00000000..022dd6cc
--- /dev/null
+++ b/changelog.d/0.76.0/1981.fixed.md
@@ -0,0 +1 @@
+- **The Unsloth backend now honours `training.gradient_checkpointing` instead of silently ignoring it.** It was hardcoded to Unsloth's checkpointing kernel, so `training.gradient_checkpointing: false` changed nothing on the Unsloth path. The flag now resolves through the same rule as the HF path: `false` (the schema default) disables checkpointing entirely, `true` (or a tier) enables Unsloth's optimized kernel, and layer streaming keeps it off since it already checkpoints every layer. Set `training.gradient_checkpointing: true` to keep the optimized Unsloth checkpointing (#1981 by @SpinachDigital).
diff --git a/docs/backends-and-ops.md b/docs/backends-and-ops.md
index 911129a1..2d571f11 100644
--- a/docs/backends-and-ops.md
+++ b/docs/backends-and-ops.md
@@ -205,6 +205,19 @@ Works with the tasks that have an unsloth setup: SFT (text; SFT vision and audio
> **Tip:** Soup auto-detects unsloth. When it is installed, `soup train` prints a hint if you haven't enabled it yet and your config would load with it.
+### Gradient checkpointing on Unsloth
+
+On `backend: unsloth`, `training.gradient_checkpointing` is honoured instead of silently ignored ([#797](https://github.com/MakazhanAlpamys/Soup/issues/797)):
+
+- `false` (the schema default) disables checkpointing and may increase activation memory.
+- `true` (or a tier: `selective`, `medium`, `full`, `auto`) enables Unsloth's optimized checkpointing; throughput and maximum context depend on the workload.
+- Layer streaming (`training.stream_layers: true`) already checkpoints every layer, so the Unsloth kernel stays off there whatever the flag says.
+
+```yaml
+training:
+ gradient_checkpointing: true # keep Unsloth's optimized checkpointing
+```
+
## Cloud GPU Training
diff --git a/src/soup_cli/trainer/bco.py b/src/soup_cli/trainer/bco.py
index 2b6198cf..96535e26 100644
--- a/src/soup_cli/trainer/bco.py
+++ b/src/soup_cli/trainer/bco.py
@@ -362,7 +362,13 @@ class BCOTrainerWrapper:
def _setup_unsloth(self, cfg: SoupConfig, tcfg: "TrainingConfig") -> None:
"""Load model via unsloth FastLanguageModel."""
+ from soup_cli.utils import unsloth
from soup_cli.utils.unsloth import load_model_and_tokenizer
+ # #797: resolve training.gradient_checkpointing for the Unsloth path
+ # (streaming layers already checkpoint every layer, so it stays off).
+ use_gradient_checkpointing = unsloth.resolve_unsloth_gradient_checkpointing(
+ tcfg.gradient_checkpointing, stream_layers=getattr(tcfg, "stream_layers", False)
+ )
console.print(f"[dim]Loading model via [bold]unsloth[/]: {cfg.base}[/]")
self.model, self.tokenizer = load_model_and_tokenizer(
@@ -374,6 +380,7 @@ class BCOTrainerWrapper:
lora_dropout=tcfg.lora.dropout,
target_modules=tcfg.lora.target_modules,
use_rslora=tcfg.lora.use_rslora,
+ use_gradient_checkpointing=use_gradient_checkpointing,
)
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
diff --git a/src/soup_cli/trainer/dpo.py b/src/soup_cli/trainer/dpo.py
index 3d37448b..0d476738 100644
--- a/src/soup_cli/trainer/dpo.py
+++ b/src/soup_cli/trainer/dpo.py
@@ -406,7 +406,13 @@ class DPOTrainerWrapper(StreamingSetupMixin):
def _setup_unsloth(self, cfg, tcfg):
"""Load model via unsloth FastLanguageModel (2-5x faster)."""
+ from soup_cli.utils import unsloth
from soup_cli.utils.unsloth import load_model_and_tokenizer
+ # #797: resolve training.gradient_checkpointing for the Unsloth path
+ # (streaming layers already checkpoint every layer, so it stays off).
+ use_gradient_checkpointing = unsloth.resolve_unsloth_gradient_checkpointing(
+ tcfg.gradient_checkpointing, stream_layers=getattr(tcfg, "stream_layers", False)
+ )
console.print(f"[dim]Loading model via [bold]unsloth[/]: {cfg.base}[/]")
self.model, self.tokenizer = load_model_and_tokenizer(
@@ -418,6 +424,7 @@ class DPOTrainerWrapper(StreamingSetupMixin):
lora_dropout=tcfg.lora.dropout,
target_modules=tcfg.lora.target_modules,
use_rslora=tcfg.lora.use_rslora,
+ use_gradient_checkpointing=use_gradient_checkpointing,
)
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
diff --git a/src/soup_cli/trainer/embedding.py b/src/soup_cli/trainer/embedding.py
index c3e0dda6..4fef6b39 100644
--- a/src/soup_cli/trainer/embedding.py
+++ b/src/soup_cli/trainer/embedding.py
@@ -367,7 +367,13 @@ class EmbeddingTrainerWrapper:
def _setup_unsloth(self, cfg: SoupConfig, tcfg: TrainingConfig) -> None:
"""Load model via unsloth FastLanguageModel (2-5x faster)."""
+ from soup_cli.utils import unsloth
from soup_cli.utils.unsloth import load_model_and_tokenizer
+ # #797: resolve training.gradient_checkpointing for the Unsloth path
+ # (streaming layers already checkpoint every layer, so it stays off).
+ use_gradient_checkpointing = unsloth.resolve_unsloth_gradient_checkpointing(
+ tcfg.gradient_checkpointing, stream_layers=getattr(tcfg, "stream_layers", False)
+ )
console.print(f"[dim]Loading model via [bold]unsloth[/]: {cfg.base}[/]")
self.model, self.tokenizer = load_model_and_tokenizer(
@@ -379,6 +385,7 @@ class EmbeddingTrainerWrapper:
lora_dropout=tcfg.lora.dropout,
target_modules=tcfg.lora.target_modules,
use_rslora=tcfg.lora.use_rslora,
+ use_gradient_checkpointing=use_gradient_checkpointing,
)
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
diff --git a/src/soup_cli/trainer/grpo.py b/src/soup_cli/trainer/grpo.py
index f9c25be5..9889d13b 100644
--- a/src/soup_cli/trainer/grpo.py
+++ b/src/soup_cli/trainer/grpo.py
@@ -746,7 +746,13 @@ class GRPOTrainerWrapper:
def _setup_unsloth(self, cfg, tcfg):
"""Load model via unsloth FastLanguageModel (2-5x faster)."""
+ from soup_cli.utils import unsloth
from soup_cli.utils.unsloth import load_model_and_tokenizer
+ # #797: resolve training.gradient_checkpointing for the Unsloth path
+ # (streaming layers already checkpoint every layer, so it stays off).
+ use_gradient_checkpointing = unsloth.resolve_unsloth_gradient_checkpointing(
+ tcfg.gradient_checkpointing, stream_layers=getattr(tcfg, "stream_layers", False)
+ )
console.print(f"[dim]Loading model via [bold]unsloth[/]: {cfg.base}[/]")
self.model, self.tokenizer = load_model_and_tokenizer(
@@ -758,6 +764,7 @@ class GRPOTrainerWrapper:
lora_dropout=tcfg.lora.dropout,
target_modules=tcfg.lora.target_modules,
use_rslora=tcfg.lora.use_rslora,
+ use_gradient_checkpointing=use_gradient_checkpointing,
)
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
diff --git a/src/soup_cli/trainer/ipo.py b/src/soup_cli/trainer/ipo.py
index 52aa8f3e..37f99c8d 100644
--- a/src/soup_cli/trainer/ipo.py
+++ b/src/soup_cli/trainer/ipo.py
@@ -312,7 +312,13 @@ class IPOTrainerWrapper:
def _setup_unsloth(self, cfg: SoupConfig, tcfg) -> None:
"""Load model via unsloth FastLanguageModel (2-5x faster)."""
+ from soup_cli.utils import unsloth
from soup_cli.utils.unsloth import load_model_and_tokenizer
+ # #797: resolve training.gradient_checkpointing for the Unsloth path
+ # (streaming layers already checkpoint every layer, so it stays off).
+ use_gradient_checkpointing = unsloth.resolve_unsloth_gradient_checkpointing(
+ tcfg.gradient_checkpointing, stream_layers=getattr(tcfg, "stream_layers", False)
+ )
console.print(f"[dim]Loading model via [bold]unsloth[/]: {cfg.base}[/]")
self.model, self.tokenizer = load_model_and_tokenizer(
@@ -324,6 +330,7 @@ class IPOTrainerWrapper:
lora_dropout=tcfg.lora.dropout,
target_modules=tcfg.lora.target_modules,
use_rslora=tcfg.lora.use_rslora,
+ use_gradient_checkpointing=use_gradient_checkpointing,
)
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
diff --git a/src/soup_cli/trainer/kto.py b/src/soup_cli/trainer/kto.py
index 0be0919f..c129f465 100644
--- a/src/soup_cli/trainer/kto.py
+++ b/src/soup_cli/trainer/kto.py
@@ -343,7 +343,13 @@ class KTOTrainerWrapper(StreamingSetupMixin):
def _setup_unsloth(self, cfg: SoupConfig, tcfg) -> None:
"""Load model via unsloth FastLanguageModel (2-5x faster)."""
+ from soup_cli.utils import unsloth
from soup_cli.utils.unsloth import load_model_and_tokenizer
+ # #797: resolve training.gradient_checkpointing for the Unsloth path
+ # (streaming layers already checkpoint every layer, so it stays off).
+ use_gradient_checkpointing = unsloth.resolve_unsloth_gradient_checkpointing(
+ tcfg.gradient_checkpointing, stream_layers=getattr(tcfg, "stream_layers", False)
+ )
console.print(f"[dim]Loading model via [bold]unsloth[/]: {cfg.base}[/]")
self.model, self.tokenizer = load_model_and_tokenizer(
@@ -355,6 +361,7 @@ class KTOTrainerWrapper(StreamingSetupMixin):
lora_dropout=tcfg.lora.dropout,
target_modules=tcfg.lora.target_modules,
use_rslora=tcfg.lora.use_rslora,
+ use_gradient_checkpointing=use_gradient_checkpointing,
)
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
diff --git a/src/soup_cli/trainer/orpo.py b/src/soup_cli/trainer/orpo.py
index 9604580c..d006a308 100644
--- a/src/soup_cli/trainer/orpo.py
+++ b/src/soup_cli/trainer/orpo.py
@@ -361,7 +361,13 @@ class ORPOTrainerWrapper(StreamingSetupMixin):
def _setup_unsloth(self, cfg: SoupConfig, tcfg) -> None:
"""Load model via unsloth FastLanguageModel (2-5x faster)."""
+ from soup_cli.utils import unsloth
from soup_cli.utils.unsloth import load_model_and_tokenizer
+ # #797: resolve training.gradient_checkpointing for the Unsloth path
+ # (streaming layers already checkpoint every layer, so it stays off).
+ use_gradient_checkpointing = unsloth.resolve_unsloth_gradient_checkpointing(
+ tcfg.gradient_checkpointing, stream_layers=getattr(tcfg, "stream_layers", False)
+ )
console.print(f"[dim]Loading model via [bold]unsloth[/]: {cfg.base}[/]")
self.model, self.tokenizer = load_model_and_tokenizer(
@@ -373,6 +379,7 @@ class ORPOTrainerWrapper(StreamingSetupMixin):
lora_dropout=tcfg.lora.dropout,
target_modules=tcfg.lora.target_modules,
use_rslora=tcfg.lora.use_rslora,
+ use_gradient_checkpointing=use_gradient_checkpointing,
)
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
diff --git a/src/soup_cli/trainer/ppo.py b/src/soup_cli/trainer/ppo.py
index a6a42c24..406f6b09 100644
--- a/src/soup_cli/trainer/ppo.py
+++ b/src/soup_cli/trainer/ppo.py
@@ -783,7 +783,13 @@ class PPOTrainerWrapper:
def _setup_unsloth(self, cfg, tcfg):
"""Load model via unsloth FastLanguageModel (2-5x faster)."""
+ from soup_cli.utils import unsloth
from soup_cli.utils.unsloth import load_model_and_tokenizer
+ # #797: resolve training.gradient_checkpointing for the Unsloth path
+ # (streaming layers already checkpoint every layer, so it stays off).
+ use_gradient_checkpointing = unsloth.resolve_unsloth_gradient_checkpointing(
+ tcfg.gradient_checkpointing, stream_layers=getattr(tcfg, "stream_layers", False)
+ )
console.print(f"[dim]Loading model via [bold]unsloth[/]: {cfg.base}[/]")
self.model, self.tokenizer = load_model_and_tokenizer(
@@ -795,6 +801,7 @@ class PPOTrainerWrapper:
lora_dropout=tcfg.lora.dropout,
target_modules=tcfg.lora.target_modules,
use_rslora=tcfg.lora.use_rslora,
+ use_gradient_checkpointing=use_gradient_checkpointing,
)
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
diff --git a/src/soup_cli/trainer/pretrain.py b/src/soup_cli/trainer/pretrain.py
index 4d42db4b..20c3d786 100644
--- a/src/soup_cli/trainer/pretrain.py
+++ b/src/soup_cli/trainer/pretrain.py
@@ -465,7 +465,13 @@ class PretrainTrainerWrapper:
def _setup_unsloth(self, cfg: SoupConfig, tcfg) -> None:
"""Load model via unsloth FastLanguageModel (2-5x faster)."""
+ from soup_cli.utils import unsloth
from soup_cli.utils.unsloth import load_model_and_tokenizer
+ # #797: resolve training.gradient_checkpointing for the Unsloth path
+ # (streaming layers already checkpoint every layer, so it stays off).
+ use_gradient_checkpointing = unsloth.resolve_unsloth_gradient_checkpointing(
+ tcfg.gradient_checkpointing, stream_layers=getattr(tcfg, "stream_layers", False)
+ )
console.print(f"[dim]Loading model via [bold]unsloth[/]: {cfg.base}[/]")
self.model, self.tokenizer = load_model_and_tokenizer(
@@ -477,6 +483,7 @@ class PretrainTrainerWrapper:
lora_dropout=tcfg.lora.dropout,
target_modules=tcfg.lora.target_modules,
use_rslora=tcfg.lora.use_rslora,
+ use_gradient_checkpointing=use_gradient_checkpointing,
)
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
diff --git a/src/soup_cli/trainer/sft.py b/src/soup_cli/trainer/sft.py
index dd9a0af9..49017388 100644
--- a/src/soup_cli/trainer/sft.py
+++ b/src/soup_cli/trainer/sft.py
@@ -1933,7 +1933,13 @@ class SFTTrainerWrapper(StreamingSetupMixin):
def _setup_unsloth(self, cfg, tcfg):
"""Load model via unsloth FastLanguageModel (2-5x faster)."""
+ from soup_cli.utils import unsloth
from soup_cli.utils.unsloth import load_model_and_tokenizer
+ # #797: resolve training.gradient_checkpointing for the Unsloth path
+ # (streaming layers already checkpoint every layer, so it stays off).
+ use_gradient_checkpointing = unsloth.resolve_unsloth_gradient_checkpointing(
+ tcfg.gradient_checkpointing, stream_layers=getattr(tcfg, "stream_layers", False)
+ )
console.print(f"[dim]Loading model via [bold]unsloth[/]: {cfg.base}[/]")
self.model, self.tokenizer = load_model_and_tokenizer(
@@ -1945,6 +1951,7 @@ class SFTTrainerWrapper(StreamingSetupMixin):
lora_dropout=tcfg.lora.dropout,
target_modules=tcfg.lora.target_modules,
use_rslora=tcfg.lora.use_rslora,
+ use_gradient_checkpointing=use_gradient_checkpointing,
)
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
diff --git a/src/soup_cli/trainer/simpo.py b/src/soup_cli/trainer/simpo.py
index 93d0c51d..4ae29b77 100644
--- a/src/soup_cli/trainer/simpo.py
+++ b/src/soup_cli/trainer/simpo.py
@@ -356,7 +356,13 @@ class SimPOTrainerWrapper(StreamingSetupMixin):
def _setup_unsloth(self, cfg: SoupConfig, tcfg) -> None:
"""Load model via unsloth FastLanguageModel (2-5x faster)."""
+ from soup_cli.utils import unsloth
from soup_cli.utils.unsloth import load_model_and_tokenizer
+ # #797: resolve training.gradient_checkpointing for the Unsloth path
+ # (streaming layers already checkpoint every layer, so it stays off).
+ use_gradient_checkpointing = unsloth.resolve_unsloth_gradient_checkpointing(
+ tcfg.gradient_checkpointing, stream_layers=getattr(tcfg, "stream_layers", False)
+ )
console.print(f"[dim]Loading model via [bold]unsloth[/]: {cfg.base}[/]")
self.model, self.tokenizer = load_model_and_tokenizer(
@@ -368,6 +374,7 @@ class SimPOTrainerWrapper(StreamingSetupMixin):
lora_dropout=tcfg.lora.dropout,
target_modules=tcfg.lora.target_modules,
use_rslora=tcfg.lora.use_rslora,
+ use_gradient_checkpointing=use_gradient_checkpointing,
)
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
diff --git a/src/soup_cli/utils/unsloth.py b/src/soup_cli/utils/unsloth.py
index 4a0bb62a..3e5619b4 100644
--- a/src/soup_cli/utils/unsloth.py
+++ b/src/soup_cli/utils/unsloth.py
@@ -23,6 +23,28 @@ def get_unsloth_version() -> str | None:
return None
+def resolve_unsloth_gradient_checkpointing(
+ gradient_checkpointing: bool | str | None, *, stream_layers: bool = False
+) -> bool | str:
+ """Map ``training.gradient_checkpointing`` to Unsloth's ``use_gradient_checkpointing`` value.
+
+ Unsloth's ``get_peft_model`` takes either ``"unsloth"`` (its own optimized
+ checkpointing kernel) or ``False`` to disable checkpointing
+ entirely. This follows the same rule as the HF path
+ (``should_enable_hf_gradient_checkpointing``): checkpointing is off when the
+ config disables it or when layer streaming already checkpoints every layer.
+
+ The resolver is imported lazily — ``layer_stream`` pulls in ``rich`` at module
+ top, and ``unsloth`` helpers must stay import-light (repo rule: heavy deps
+ lazy-imported, never at module top).
+ """
+ from soup_cli.utils.layer_stream import should_enable_hf_gradient_checkpointing
+
+ if should_enable_hf_gradient_checkpointing(gradient_checkpointing, stream_layers=stream_layers):
+ return "unsloth"
+ return False
+
+
def load_model_and_tokenizer(
model_name: str,
max_seq_length: int,
@@ -32,6 +54,7 @@ def load_model_and_tokenizer(
lora_dropout: float = 0.05,
target_modules: str | list[str] | None = "auto",
use_rslora: bool = False,
+ use_gradient_checkpointing: bool | str = "unsloth",
):
"""Load model + tokenizer via unsloth FastLanguageModel with LoRA already applied.
@@ -42,6 +65,11 @@ def load_model_and_tokenizer(
directly and scales the adapter by ``alpha / sqrt(r)`` instead of
``alpha / r``. It is forwarded on every call so the config's value, not
Unsloth's default, decides (#1853: the flag loaded and was never passed).
+
+ ``use_gradient_checkpointing`` is ``training.gradient_checkpointing`` as
+ resolved by ``resolve_unsloth_gradient_checkpointing``: ``"unsloth"`` enables
+ Unsloth's checkpointing kernel, ``False`` disables checkpointing entirely
+ (#797: the flag was hardcoded to ``"unsloth"``, so disabling it was ignored).
"""
if quantization == "8bit":
# #1811: the config refuses this pairing; name it here too rather than
@@ -88,7 +116,7 @@ def load_model_and_tokenizer(
lora_dropout=lora_dropout,
target_modules=target_modules,
bias="none",
- use_gradient_checkpointing="unsloth", # 2x longer context for free
+ use_gradient_checkpointing=use_gradient_checkpointing, # #797: honoured, not hardcoded
use_rslora=use_rslora,
)
diff --git a/tests/test_unsloth.py b/tests/test_unsloth.py
index cf79ab77..9debb4d4 100644
--- a/tests/test_unsloth.py
+++ b/tests/test_unsloth.py
@@ -219,6 +219,7 @@ class TestSFTUnslothIntegration:
lora_dropout=0.05,
target_modules="auto",
use_rslora=False,
+ use_gradient_checkpointing=False, # #797: config false → resolved
)
assert wrapper.model is mock_model
assert wrapper.tokenizer is mock_tokenizer
diff --git a/tests/test_unsloth_gradient_checkpointing.py b/tests/test_unsloth_gradient_checkpointing.py
new file mode 100644
index 00000000..c974b9d0
--- /dev/null
+++ b/tests/test_unsloth_gradient_checkpointing.py
@@ -0,0 +1,204 @@
+"""Tests for issue #797 item 4 — unsloth path must honour training.gradient_checkpointing.
+
+Before the fix, ``load_model_and_tokenizer`` hardcoded
+``use_gradient_checkpointing="unsloth"`` in ``get_peft_model``, so setting
+``training.gradient_checkpointing: false`` was silently ignored on the unsloth
+path. The fix resolves the flag via ``resolve_unsloth_gradient_checkpointing``
+(built on the codebase's established ``should_enable_hf_gradient_checkpointing``
+rule) and threads it through every trainer's ``_setup_unsloth``.
+"""
+
+import importlib
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from soup_cli.config.schema import SoupConfig
+from soup_cli.utils.unsloth import (
+ load_model_and_tokenizer,
+ resolve_unsloth_gradient_checkpointing,
+)
+
+# ─── Resolver unit tests ─────────────────────────────────────────────────────
+
+
+class TestResolveUnslothGradientCheckpointing:
+ def test_false_disables(self):
+ """gradient_checkpointing: false → no checkpointing on the unsloth path."""
+ assert resolve_unsloth_gradient_checkpointing(False) is False
+
+ def test_none_disables(self):
+ assert resolve_unsloth_gradient_checkpointing(None) is False
+
+ def test_true_enables_unsloth_kernel(self):
+ assert resolve_unsloth_gradient_checkpointing(True) == "unsloth"
+
+ def test_full_tier_enables_unsloth_kernel(self):
+ """Tier strings ('selective'/'medium'/'full'/'auto') mean on → 'unsloth'."""
+ for tier in ("selective", "medium", "full", "auto"):
+ assert resolve_unsloth_gradient_checkpointing(tier) == "unsloth"
+
+ def test_stream_layers_forces_off(self):
+ """Layer streaming already checkpoints every layer — streaming wins."""
+ assert resolve_unsloth_gradient_checkpointing(True, stream_layers=True) is False
+
+ def test_false_with_stream_layers_stays_off(self):
+ assert resolve_unsloth_gradient_checkpointing(False, stream_layers=True) is False
+
+
+# ─── Loader passthrough tests (unsloth mocked) ───────────────────────────────
+
+_MODEL_KWARGS = dict(model_name="test-model", max_seq_length=2048, quantization="4bit")
+
+
+def _mocked_unsloth_call(**load_kwargs):
+ """Call load_model_and_tokenizer with unsloth mocked; return get_peft_model kwargs."""
+ mock_flm = MagicMock()
+ mock_flm.from_pretrained.return_value = (MagicMock(), MagicMock())
+ mock_flm.get_peft_model.return_value = MagicMock()
+ with patch.dict("sys.modules", {"unsloth": MagicMock(FastLanguageModel=mock_flm)}):
+ load_model_and_tokenizer(**_MODEL_KWARGS, **load_kwargs)
+ return mock_flm.get_peft_model.call_args[1]
+
+
+class TestLoadModelAndTokenizerCheckpointing:
+ def test_explicit_false_forwarded(self):
+ """The #797 regression: False must reach get_peft_model, not the hardcoded default."""
+ kwargs = _mocked_unsloth_call(use_gradient_checkpointing=False)
+ assert kwargs["use_gradient_checkpointing"] is False
+
+ def test_explicit_unsloth_forwarded(self):
+ kwargs = _mocked_unsloth_call(use_gradient_checkpointing="unsloth")
+ assert kwargs["use_gradient_checkpointing"] == "unsloth"
+
+ def test_default_preserves_prior_behavior(self):
+ """Default keeps today's behaviour ('unsloth') for existing call sites."""
+ assert _mocked_unsloth_call()["use_gradient_checkpointing"] == "unsloth"
+
+
+# ─── Trainer wiring tests (runtime, unsloth loader mocked) ───────────────────
+
+TRAINER_MODULES = [
+ "soup_cli.trainer.bco",
+ "soup_cli.trainer.dpo",
+ "soup_cli.trainer.embedding",
+ "soup_cli.trainer.grpo",
+ "soup_cli.trainer.ipo",
+ "soup_cli.trainer.kto",
+ "soup_cli.trainer.orpo",
+ "soup_cli.trainer.ppo",
+ "soup_cli.trainer.pretrain",
+ "soup_cli.trainer.sft",
+ "soup_cli.trainer.simpo",
+]
+
+
+def _trainer_cls(module_name):
+ """First class defined in the module that owns ``_setup_unsloth``."""
+ module = importlib.import_module(module_name)
+ return next(
+ obj
+ for name, obj in vars(module).items()
+ if isinstance(obj, type) and "_setup_unsloth" in obj.__dict__
+ )
+
+
+def _mock_configs(gradient_checkpointing):
+ cfg = MagicMock()
+ cfg.base = "test-model"
+ cfg.data.max_length = 2048
+ tcfg = MagicMock()
+ tcfg.quantization = "4bit"
+ tcfg.lora.r = 64
+ tcfg.lora.alpha = 16
+ tcfg.lora.dropout = 0.05
+ tcfg.lora.target_modules = "auto"
+ tcfg.lora.use_rslora = False
+ tcfg.gradient_checkpointing = gradient_checkpointing
+ tcfg.stream_layers = False
+ return cfg, tcfg
+
+
+def _run_setup_unsloth(module_name, gradient_checkpointing):
+ """Invoke the real _setup_unsloth with the loader mocked; return loader kwargs."""
+ trainer = _trainer_cls(module_name).__new__(_trainer_cls(module_name))
+ cfg, tcfg = _mock_configs(gradient_checkpointing)
+ with patch("soup_cli.utils.unsloth.load_model_and_tokenizer") as mock_loader:
+ mock_loader.return_value = (MagicMock(), MagicMock())
+ trainer._setup_unsloth(cfg, tcfg)
+ return mock_loader.call_args[1]
+
+
+class TestTrainerSetupUnslothWiring:
+ """Every _setup_unsloth must resolve the flag and hand it to the loader."""
+
+ @pytest.mark.parametrize("module_name", TRAINER_MODULES)
+ def test_setup_unsloth_forwards_false(self, module_name):
+ """The #797 case end-to-end: config false → loader receives False."""
+ kwargs = _run_setup_unsloth(module_name, gradient_checkpointing=False)
+ assert kwargs["use_gradient_checkpointing"] is False
+
+ @pytest.mark.parametrize("module_name", TRAINER_MODULES)
+ def test_setup_unsloth_forwards_unsloth(self, module_name):
+ """Config true → loader receives 'unsloth'."""
+ kwargs = _run_setup_unsloth(module_name, gradient_checkpointing=True)
+ assert kwargs["use_gradient_checkpointing"] == "unsloth"
+
+
+# ─── Real-config regression test (schema-derived default) ────────────────────
+
+
+def _real_configs(**training_overrides):
+ """Build a real SoupConfig; gradient_checkpointing comes from the schema default."""
+ data = {"train": "dummy.jsonl"}
+ if training_overrides:
+ cfg = SoupConfig(base="test-model", data=data, training=training_overrides)
+ else:
+ cfg = SoupConfig(base="test-model", data=data)
+ return cfg, cfg.training
+
+
+def _run_real_setup_unsloth(module_name, cfg, tcfg):
+ """Invoke the real _setup_unsloth with a real config and the loader mocked."""
+ trainer = _trainer_cls(module_name).__new__(_trainer_cls(module_name))
+ with patch("soup_cli.utils.unsloth.load_model_and_tokenizer") as mock_loader:
+ mock_loader.return_value = (MagicMock(), MagicMock())
+ trainer._setup_unsloth(cfg, tcfg)
+ return mock_loader.call_args[1]
+
+
+class TestRealConfigUnslothWiring:
+ """Schema-derived config through the real trainer setup, Unsloth loader mocked."""
+
+ @pytest.mark.parametrize("module_name", TRAINER_MODULES)
+ def test_schema_default_false_reaches_loader(self, module_name):
+ """Unset training.gradient_checkpointing (schema default False) → loader gets False."""
+ cfg, tcfg = _real_configs()
+ assert tcfg.gradient_checkpointing is False # schema default, not a mock
+ kwargs = _run_real_setup_unsloth(module_name, cfg, tcfg)
+ assert kwargs["use_gradient_checkpointing"] is False
+
+ @pytest.mark.parametrize("module_name", TRAINER_MODULES)
+ def test_explicit_true_reaches_loader(self, module_name):
+ """Explicit training.gradient_checkpointing: true → loader gets 'unsloth'."""
+ cfg, _ = _real_configs(gradient_checkpointing=True)
+ kwargs = _run_real_setup_unsloth(module_name, cfg, cfg.training)
+ assert kwargs["use_gradient_checkpointing"] == "unsloth"
+
+ def test_negative_control_old_hardcoded_behavior_fails(self):
+ """Sensitivity check: with the old hardcoded 'unsloth', the assertion must fail."""
+ cfg, tcfg = _real_configs()
+ trainer = _trainer_cls("soup_cli.trainer.sft").__new__(_trainer_cls("soup_cli.trainer.sft"))
+ with (
+ patch("soup_cli.utils.unsloth.load_model_and_tokenizer") as mock_loader,
+ patch(
+ "soup_cli.utils.unsloth.resolve_unsloth_gradient_checkpointing",
+ return_value="unsloth",
+ ),
+ ):
+ mock_loader.return_value = (MagicMock(), MagicMock())
+ trainer._setup_unsloth(cfg, tcfg)
+ # Old behaviour: loader receives 'unsloth' even though the config says False
+ assert mock_loader.call_args[1]["use_gradient_checkpointing"] == "unsloth"
+ with pytest.raises(AssertionError):
+ assert mock_loader.call_args[1]["use_gradient_checkpointing"] is False