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(lora): apply lora.use_rslora on backend mlx and unsloth (#1899)

ndablizovf215941b23a5
diff --git a/changelog.d/0.76.0/1899.fixed.md b/changelog.d/0.76.0/1899.fixed.md
new file mode 100644
index 00000000..0c8aa2d9
--- /dev/null
+++ b/changelog.d/0.76.0/1899.fixed.md
@@ -0,0 +1 @@
+- `training.lora.use_rslora` is now applied on `backend: mlx` and `backend: unsloth`: MLX receives the rank-stabilised scale `alpha / sqrt(r)` in both `adapter_config.json` and at training time, and the Unsloth loader forwards `use_rslora` to `get_peft_model` from every trainer. Before, the flag loaded on both backends and was never read, so an rsLoRA run trained plain-LoRA scaling (`alpha / r`, an 8x smaller update at the default `r: 64, alpha: 16`) with nothing said. Existing configs with `use_rslora: true` on mlx or Unsloth now train at the rank-stabilised scale, so their results change; drop the flag to keep the old `alpha / r` behaviour (#1853 by @ndablizov in #1899)
diff --git a/docs/peft-and-efficiency.md b/docs/peft-and-efficiency.md
index 8f19fd15..931a91d6 100644
--- a/docs/peft-and-efficiency.md
+++ b/docs/peft-and-efficiency.md
@@ -458,6 +458,11 @@ training:
Works with all training tasks and backends. Recommended for LoRA rank ≥ 32.
+The scale is `alpha / sqrt(r)` instead of plain LoRA's `alpha / r` (2.0 instead of 0.25
+for the config above) on every backend: PEFT's `LoraConfig(use_rslora=True)` on
+`transformers`, the `scale` Soup hands mlx-lm (in `adapter_config.json` and at training
+time) on `mlx`, and `get_peft_model(..., use_rslora=True)` on `unsloth`.
+
## VeRA & OLoRA (Smaller-Footprint PEFT)
diff --git a/src/soup_cli/trainer/bco.py b/src/soup_cli/trainer/bco.py
index 3aa967c5..9262fdda 100644
--- a/src/soup_cli/trainer/bco.py
+++ b/src/soup_cli/trainer/bco.py
@@ -368,6 +368,7 @@ class BCOTrainerWrapper:
lora_alpha=tcfg.lora.alpha,
lora_dropout=tcfg.lora.dropout,
target_modules=tcfg.lora.target_modules,
+ use_rslora=tcfg.lora.use_rslora,
)
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 7fa6a188..ac367875 100644
--- a/src/soup_cli/trainer/dpo.py
+++ b/src/soup_cli/trainer/dpo.py
@@ -411,6 +411,7 @@ class DPOTrainerWrapper(StreamingSetupMixin):
lora_alpha=tcfg.lora.alpha,
lora_dropout=tcfg.lora.dropout,
target_modules=tcfg.lora.target_modules,
+ use_rslora=tcfg.lora.use_rslora,
)
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 88a6e5ba..792b686c 100644
--- a/src/soup_cli/trainer/embedding.py
+++ b/src/soup_cli/trainer/embedding.py
@@ -373,6 +373,7 @@ class EmbeddingTrainerWrapper:
lora_alpha=tcfg.lora.alpha,
lora_dropout=tcfg.lora.dropout,
target_modules=tcfg.lora.target_modules,
+ use_rslora=tcfg.lora.use_rslora,
)
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 f4b281e8..85198508 100644
--- a/src/soup_cli/trainer/grpo.py
+++ b/src/soup_cli/trainer/grpo.py
@@ -752,6 +752,7 @@ class GRPOTrainerWrapper:
lora_alpha=tcfg.lora.alpha,
lora_dropout=tcfg.lora.dropout,
target_modules=tcfg.lora.target_modules,
+ use_rslora=tcfg.lora.use_rslora,
)
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 a5b83e7d..6038455b 100644
--- a/src/soup_cli/trainer/ipo.py
+++ b/src/soup_cli/trainer/ipo.py
@@ -318,6 +318,7 @@ class IPOTrainerWrapper:
lora_alpha=tcfg.lora.alpha,
lora_dropout=tcfg.lora.dropout,
target_modules=tcfg.lora.target_modules,
+ use_rslora=tcfg.lora.use_rslora,
)
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 9b7b1b1e..3768106c 100644
--- a/src/soup_cli/trainer/kto.py
+++ b/src/soup_cli/trainer/kto.py
@@ -349,6 +349,7 @@ class KTOTrainerWrapper(StreamingSetupMixin):
lora_alpha=tcfg.lora.alpha,
lora_dropout=tcfg.lora.dropout,
target_modules=tcfg.lora.target_modules,
+ use_rslora=tcfg.lora.use_rslora,
)
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
diff --git a/src/soup_cli/trainer/mlx_sft.py b/src/soup_cli/trainer/mlx_sft.py
index 4d890cde..90186fec 100644
--- a/src/soup_cli/trainer/mlx_sft.py
+++ b/src/soup_cli/trainer/mlx_sft.py
@@ -220,6 +220,24 @@ def _clipping_optimizer(inner: object, max_norm: float) -> object:
return _GradientClippingOptimizer(inner, max_norm)
+def mlx_lora_scale(lora_cfg: object) -> float:
+ """The LoRA ``scale`` mlx-lm multiplies the adapter update by.
+
+ ``alpha / sqrt(r)`` when ``lora.use_rslora`` is set (rank-stabilised LoRA,
+ the value PEFT computes for the transformers backend), ``alpha / r``
+ otherwise. One function for both the ``adapter_config.json`` writer and
+ ``_apply_lora``, so the file and the trained modules cannot disagree
+ (#1853). Before this the flag loaded on ``backend: mlx`` and was never
+ read: with the default ``r: 64, alpha: 16`` an rsLoRA run trained at 0.25
+ instead of 2.0, an 8x smaller update than the config asked for.
+ """
+ rank = max(1.0, float(getattr(lora_cfg, "r", 0)))
+ alpha = float(getattr(lora_cfg, "alpha", 0.0))
+ if getattr(lora_cfg, "use_rslora", False):
+ return alpha / math.sqrt(rank)
+ return alpha / rank
+
+
def build_mlx_adapter_config(lora_cfg: object, *, adapter_path: str, **extra: object) -> dict:
"""The ``lora_parameters`` block, keyed off the RESOLVED module list.
@@ -228,13 +246,12 @@ def build_mlx_adapter_config(lora_cfg: object, *, adapter_path: str, **extra: ob
disagreement between those two values is the whole of #392.
"""
rank = int(getattr(lora_cfg, "r", 0))
- alpha = float(getattr(lora_cfg, "alpha", 0.0))
config: dict = {
"fine_tune_type": "lora",
"adapter_path": adapter_path,
"lora_parameters": {
"rank": rank,
- "scale": alpha / max(1.0, float(rank)),
+ "scale": mlx_lora_scale(lora_cfg),
"dropout": float(getattr(lora_cfg, "dropout", 0.0) or 0.0),
"keys": resolve_mlx_target_keys(lora_cfg),
},
@@ -417,7 +434,7 @@ class MLXSFTTrainerWrapper:
num_layers,
{
"rank": int(lora_cfg.r),
- "scale": float(lora_cfg.alpha) / max(1.0, float(lora_cfg.r)),
+ "scale": mlx_lora_scale(lora_cfg),
"dropout": float(getattr(lora_cfg, "dropout", 0.0) or 0.0),
"keys": keys,
},
diff --git a/src/soup_cli/trainer/orpo.py b/src/soup_cli/trainer/orpo.py
index 1ac42f59..52d9d035 100644
--- a/src/soup_cli/trainer/orpo.py
+++ b/src/soup_cli/trainer/orpo.py
@@ -367,6 +367,7 @@ class ORPOTrainerWrapper(StreamingSetupMixin):
lora_alpha=tcfg.lora.alpha,
lora_dropout=tcfg.lora.dropout,
target_modules=tcfg.lora.target_modules,
+ use_rslora=tcfg.lora.use_rslora,
)
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 9a2af7b0..3c8f3281 100644
--- a/src/soup_cli/trainer/ppo.py
+++ b/src/soup_cli/trainer/ppo.py
@@ -787,6 +787,7 @@ class PPOTrainerWrapper:
lora_alpha=tcfg.lora.alpha,
lora_dropout=tcfg.lora.dropout,
target_modules=tcfg.lora.target_modules,
+ use_rslora=tcfg.lora.use_rslora,
)
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 00fc089c..0b09cccd 100644
--- a/src/soup_cli/trainer/pretrain.py
+++ b/src/soup_cli/trainer/pretrain.py
@@ -470,6 +470,7 @@ class PretrainTrainerWrapper:
lora_alpha=tcfg.lora.alpha,
lora_dropout=tcfg.lora.dropout,
target_modules=tcfg.lora.target_modules,
+ use_rslora=tcfg.lora.use_rslora,
)
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 8b827958..6c2fa108 100644
--- a/src/soup_cli/trainer/sft.py
+++ b/src/soup_cli/trainer/sft.py
@@ -1932,6 +1932,7 @@ class SFTTrainerWrapper(StreamingSetupMixin):
lora_alpha=tcfg.lora.alpha,
lora_dropout=tcfg.lora.dropout,
target_modules=tcfg.lora.target_modules,
+ use_rslora=tcfg.lora.use_rslora,
)
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 bc11e03d..e49756dd 100644
--- a/src/soup_cli/trainer/simpo.py
+++ b/src/soup_cli/trainer/simpo.py
@@ -362,6 +362,7 @@ class SimPOTrainerWrapper(StreamingSetupMixin):
lora_alpha=tcfg.lora.alpha,
lora_dropout=tcfg.lora.dropout,
target_modules=tcfg.lora.target_modules,
+ use_rslora=tcfg.lora.use_rslora,
)
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 01184de8..6d622ff5 100644
--- a/src/soup_cli/utils/unsloth.py
+++ b/src/soup_cli/utils/unsloth.py
@@ -31,11 +31,17 @@ def load_model_and_tokenizer(
lora_alpha: int = 16,
lora_dropout: float = 0.05,
target_modules: str | list[str] | None = "auto",
+ use_rslora: bool = False,
):
"""Load model + tokenizer via unsloth FastLanguageModel with LoRA already applied.
Returns (model, tokenizer) — model already has LoRA adapters attached.
Unsloth handles quantization, LoRA patching, and kernel optimization internally.
+
+ ``use_rslora`` is ``lora.use_rslora``: Unsloth's ``get_peft_model`` takes it
+ 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).
"""
from unsloth import FastLanguageModel
@@ -75,6 +81,7 @@ def load_model_and_tokenizer(
target_modules=target_modules,
bias="none",
use_gradient_checkpointing="unsloth", # 2x longer context for free
+ use_rslora=use_rslora,
)
return model, tokenizer
diff --git a/tests/test_rslora_mlx_unsloth.py b/tests/test_rslora_mlx_unsloth.py
new file mode 100644
index 00000000..c37a41fa
--- /dev/null
+++ b/tests/test_rslora_mlx_unsloth.py
@@ -0,0 +1,268 @@
+"""#1853 — ``lora.use_rslora`` is applied on ``backend: mlx`` and ``backend: unsloth``.
+
+The flag was read in exactly one place, ``utils/peft_wiring.py`` (the PEFT
+``LoraConfig`` of the transformers backend). The MLX trainer computed the LoRA
+scale as ``alpha / r`` in two places (the ``adapter_config.json`` writer and
+``_apply_lora``), and the Unsloth loader called ``get_peft_model`` without the
+keyword, so with the default ``r: 64, alpha: 16`` an rsLoRA run on either
+backend trained at scale 0.25 instead of ``alpha / sqrt(r) = 2.0`` and nothing
+said so.
+
+Now one helper gives the MLX scale to both call sites, and the Unsloth loader
+forwards ``use_rslora`` from every trainer that uses it. MLX and Unsloth are not
+needed: both are replaced by recording stand-ins.
+"""
+
+from __future__ import annotations
+
+import math
+import re
+import sys
+import types
+from pathlib import Path
+from unittest.mock import MagicMock, patch
+
+import pytest
+import yaml
+
+from soup_cli.config.loader import load_config_from_string
+from soup_cli.trainer.mlx_sft import (
+ MLXSFTTrainerWrapper,
+ build_mlx_adapter_config,
+ mlx_lora_scale,
+)
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+TRAINER_DIR = REPO_ROOT / "src" / "soup_cli" / "trainer"
+
+
+def _lora(r: int = 64, alpha: float = 16.0, use_rslora: bool = False):
+ class _L:
+ dropout = 0.0
+ target_modules = ["q_proj", "v_proj"]
+
+ _L.r = r
+ _L.alpha = alpha
+ _L.use_rslora = use_rslora
+ return _L()
+
+
+# ---------------------------------------------------------------------------
+# MLX: the scale
+# ---------------------------------------------------------------------------
+
+
+class TestMlxScale:
+ def test_rslora_scales_by_the_square_root_of_the_rank(self):
+ assert mlx_lora_scale(_lora(64, 16.0, use_rslora=True)) == pytest.approx(2.0)
+ assert mlx_lora_scale(_lora(16, 32.0, use_rslora=True)) == pytest.approx(8.0)
+
+ def test_plain_lora_keeps_alpha_over_rank(self):
+ assert mlx_lora_scale(_lora(64, 16.0, use_rslora=False)) == pytest.approx(0.25)
+ assert mlx_lora_scale(_lora(16, 32.0, use_rslora=False)) == pytest.approx(2.0)
+
+ def test_the_two_formulas_agree_only_at_rank_one(self):
+ # alpha / sqrt(r) == alpha / r iff r == 1, so a fix that confused the two
+ # would fail every other case above.
+ assert mlx_lora_scale(_lora(1, 8.0, True)) == mlx_lora_scale(_lora(1, 8.0, False))
+
+ def test_a_config_without_the_flag_is_plain_lora(self):
+ class _Old: # a lora block from before the flag existed
+ r = 64
+ alpha = 16.0
+
+ assert mlx_lora_scale(_Old()) == pytest.approx(0.25)
+
+ def test_the_matching_peft_scaling(self):
+ # The value PEFT computes for the transformers backend (lora_alpha / sqrt(r)),
+ # so a run that moves between backends keeps its update size.
+ assert mlx_lora_scale(_lora(64, 16.0, True)) == pytest.approx(16.0 / math.sqrt(64))
+
+
+class TestMlxAdapterConfig:
+ def test_rslora_reaches_the_adapter_config(self):
+ params = build_mlx_adapter_config(_lora(64, 16.0, True), adapter_path="out")
+ assert params["lora_parameters"]["scale"] == pytest.approx(2.0)
+ assert params["lora_parameters"]["rank"] == 64
+
+ def test_plain_lora_is_unchanged(self):
+ params = build_mlx_adapter_config(_lora(64, 16.0, False), adapter_path="out")
+ assert params["lora_parameters"]["scale"] == pytest.approx(0.25)
+
+
+class TestMlxApplyLora:
+ """``_apply_lora`` hands ``linear_to_lora_layers`` the same scale as the writer."""
+
+ @staticmethod
+ def _wrapper_and_recorder(monkeypatch, use_rslora: bool):
+ seen: list[dict] = []
+
+ def linear_to_lora_layers(model, num_layers, params):
+ seen.append({"num_layers": num_layers, **params})
+
+ utils = types.ModuleType("mlx_lm.tuner.utils")
+ utils.linear_to_lora_layers = linear_to_lora_layers
+ tuner = types.ModuleType("mlx_lm.tuner")
+ tuner.utils = utils
+ mlx_lm = types.ModuleType("mlx_lm")
+ mlx_lm.tuner = tuner
+ monkeypatch.setitem(sys.modules, "mlx_lm", mlx_lm)
+ monkeypatch.setitem(sys.modules, "mlx_lm.tuner", tuner)
+ monkeypatch.setitem(sys.modules, "mlx_lm.tuner.utils", utils)
+
+ flag = str(use_rslora).lower()
+ cfg = load_config_from_string(
+ "base: mlx-community/SmolLM2-135M-Instruct\ntask: sft\nbackend: mlx\n"
+ "data:\n train: d.jsonl\n"
+ f"training:\n lora:\n r: 64\n alpha: 16\n use_rslora: {flag}\n"
+ )
+ return MLXSFTTrainerWrapper(cfg), seen
+
+ class _Model:
+ layers = [object(), object()]
+ frozen = False
+
+ def freeze(self):
+ self.frozen = True
+
+ def test_rslora_scale_reaches_linear_to_lora_layers(self, monkeypatch):
+ wrapper, seen = self._wrapper_and_recorder(monkeypatch, use_rslora=True)
+ model = self._Model()
+ wrapper._apply_lora(model)
+ assert model.frozen is True
+ assert len(seen) == 1
+ assert seen[0]["scale"] == pytest.approx(2.0)
+ assert seen[0]["rank"] == 64
+ assert seen[0]["num_layers"] == 2
+
+ def test_plain_lora_scale_is_unchanged(self, monkeypatch):
+ wrapper, seen = self._wrapper_and_recorder(monkeypatch, use_rslora=False)
+ wrapper._apply_lora(self._Model())
+ assert seen[0]["scale"] == pytest.approx(0.25)
+
+ def test_writer_and_trainer_agree(self, monkeypatch):
+ # The disagreement between the file and the trained modules was the whole
+ # of #392 for the keys; the scale now goes through the same helper.
+ wrapper, seen = self._wrapper_and_recorder(monkeypatch, use_rslora=True)
+ wrapper._apply_lora(self._Model())
+ written = build_mlx_adapter_config(wrapper.config.training.lora, adapter_path="out")
+ assert written["lora_parameters"]["scale"] == seen[0]["scale"]
+
+
+# ---------------------------------------------------------------------------
+# Unsloth: the loader
+# ---------------------------------------------------------------------------
+
+
+def _fake_unsloth():
+ seen: list[dict] = []
+ fast = types.SimpleNamespace(
+ from_pretrained=lambda **kw: (object(), object()),
+ get_peft_model=lambda model, **kw: seen.append(kw) or model,
+ )
+ return types.SimpleNamespace(FastLanguageModel=fast), seen
+
+
+class TestUnslothLoader:
+ def _load(self, monkeypatch, **kwargs):
+ module, seen = _fake_unsloth()
+ monkeypatch.setitem(sys.modules, "unsloth", module)
+ from soup_cli.utils.unsloth import load_model_and_tokenizer
+
+ load_model_and_tokenizer("m", 512, lora_r=64, lora_alpha=16, **kwargs)
+ assert len(seen) == 1
+ return seen[0]
+
+ def test_use_rslora_true_reaches_get_peft_model(self, monkeypatch):
+ assert self._load(monkeypatch, use_rslora=True)["use_rslora"] is True
+
+ def test_use_rslora_false_reaches_get_peft_model(self, monkeypatch):
+ assert self._load(monkeypatch, use_rslora=False)["use_rslora"] is False
+
+ def test_the_default_is_plain_lora(self, monkeypatch):
+ # Callers that predate the parameter (the issue's reproduction) keep
+ # their behaviour.
+ assert self._load(monkeypatch)["use_rslora"] is False
+
+ def test_the_other_lora_kwargs_still_arrive(self, monkeypatch):
+ got = self._load(monkeypatch, use_rslora=True, lora_dropout=0.1)
+ assert got["r"] == 64 and got["lora_alpha"] == 16 and got["lora_dropout"] == 0.1
+
+
+# ---------------------------------------------------------------------------
+# Unsloth: every trainer forwards the flag from the config
+# ---------------------------------------------------------------------------
+
+# The minimum each task needs to load (the same table as the task-gate tests).
+_DATA = {"dpo": {"format": "dpo"}, "kto": {"format": "kto"}, "pretrain": {"format": "plaintext"}}
+
+# (task, module, wrapper class): every trainer whose ``_setup_unsloth`` calls the
+# shared loader. Listed literally so a trainer that stops forwarding the flag
+# fails here rather than disappearing from a computed list.
+WRAPPERS = [
+ ("sft", "soup_cli.trainer.sft", "SFTTrainerWrapper"),
+ ("dpo", "soup_cli.trainer.dpo", "DPOTrainerWrapper"),
+ ("grpo", "soup_cli.trainer.grpo", "GRPOTrainerWrapper"),
+ ("ppo", "soup_cli.trainer.ppo", "PPOTrainerWrapper"),
+ ("kto", "soup_cli.trainer.kto", "KTOTrainerWrapper"),
+ ("orpo", "soup_cli.trainer.orpo", "ORPOTrainerWrapper"),
+ ("simpo", "soup_cli.trainer.simpo", "SimPOTrainerWrapper"),
+ ("ipo", "soup_cli.trainer.ipo", "IPOTrainerWrapper"),
+ ("bco", "soup_cli.trainer.bco", "BCOTrainerWrapper"),
+ ("pretrain", "soup_cli.trainer.pretrain", "PretrainTrainerWrapper"),
+ ("embedding", "soup_cli.trainer.embedding", "EmbeddingTrainerWrapper"),
+]
+
+
+def _unsloth_config(task: str, use_rslora: bool):
+ raw = {
+ "base": "org/m",
+ "task": task,
+ "backend": "unsloth",
+ "data": {"train": "./x.jsonl", "max_length": 2048, **_DATA.get(task, {})},
+ "training": {"lora": {"r": 64, "alpha": 16, "use_rslora": use_rslora}},
+ }
+ return load_config_from_string(yaml.safe_dump(raw))
+
+
[email protected]("task,module,cls", WRAPPERS, ids=[w[0] for w in WRAPPERS])
[email protected]("use_rslora", [True, False], ids=["rslora", "plain"])
+def test_every_unsloth_trainer_forwards_the_flag_from_the_config(task, module, cls, use_rslora):
+ import importlib
+
+ wrapper_cls = getattr(importlib.import_module(module), cls)
+ cfg = _unsloth_config(task, use_rslora)
+ wrapper = wrapper_cls(cfg, device="cuda")
+
+ mock_model = MagicMock()
+ mock_model.get_nb_trainable_parameters.return_value = (1000, 100000)
+ mock_tokenizer = MagicMock()
+ mock_tokenizer.pad_token = "pad"
+ with patch(
+ "soup_cli.utils.unsloth.load_model_and_tokenizer",
+ return_value=(mock_model, mock_tokenizer),
+ ) as mock_load:
+ wrapper._setup_unsloth(cfg, cfg.training)
+ mock_load.assert_called_once()
+ kwargs = mock_load.call_args.kwargs
+ assert kwargs["use_rslora"] is use_rslora
+ assert kwargs["lora_r"] == 64 and kwargs["lora_alpha"] == 16
+
+
+def test_every_loader_call_under_trainer_passes_the_flag():
+ """Source guard: a trainer added later cannot call the loader without it."""
+ pattern = re.compile(r"load_model_and_tokenizer\((.*?)\)", re.DOTALL)
+ offenders = []
+ checked = 0
+ for path in sorted(TRAINER_DIR.glob("*.py")):
+ text = path.read_text(encoding="utf-8")
+ if "from soup_cli.utils.unsloth import load_model_and_tokenizer" not in text:
+ continue
+ for call in pattern.finditer(text):
+ if "model_name=" not in call.group(1):
+ continue # the import line or a reference, not a call with kwargs
+ checked += 1
+ if "use_rslora=" not in call.group(1):
+ offenders.append(path.name)
+ assert checked >= len(WRAPPERS), checked
+ assert offenders == [], offenders
diff --git a/tests/test_unsloth.py b/tests/test_unsloth.py
index 435d3aac..cf79ab77 100644
--- a/tests/test_unsloth.py
+++ b/tests/test_unsloth.py
@@ -218,6 +218,7 @@ class TestSFTUnslothIntegration:
lora_alpha=16,
lora_dropout=0.05,
target_modules="auto",
+ use_rslora=False,
)
assert wrapper.model is mock_model
assert wrapper.tokenizer is mock_tokenizer