Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
fix(relora): refuse a restart that would move a frozen reference (#1835) (#1891)
Yang Bai68efa2302985
diff --git a/changelog.d/0.76.0/1891.fixed.md b/changelog.d/0.76.0/1891.fixed.mdnew file mode 100644index 00000000..6bea0122--- /dev/null+++ b/changelog.d/0.76.0/1891.fixed.md@@ -0,0 +1 @@+- **`training.relora_steps` is refused where the loss has a frozen reference.** trl reads the reference of `dpo`, `ipo`, `kto`, `bco` and `grpo` with `grpo_beta` above 0 from the policy's own base weights, and every ReLoRA restart merges the trained adapter into those weights, so from the first restart on the reference was the policy as of that step, without an error. Those tasks, and a `preference` run whose loss or blend names `dpo`, `ipo` or `bco`, now stop when the config is loaded, with the reason. `sft`, `orpo`, `simpo`, `grpo` with `grpo_beta: 0` and a `simpo` / `orpo` preference run keep ReLoRA (#1835 by @ybai08 in #1891).diff --git a/docs/peft-and-efficiency.md b/docs/peft-and-efficiency.mdindex b2bacef1..1f051da8 100644--- a/docs/peft-and-efficiency.md+++ b/docs/peft-and-efficiency.md@@ -377,11 +377,24 @@ deprecated in favour of the YAML registry.**Multi-trainer scope** — ReLoRA and the surgical patches are wired into everytransformer-backend trainer: `sft`, `dpo`, `grpo`, `kto`, `orpo`, `simpo`, `ipo`,`ppo`, `reward_model`, `pretrain`, `embedding`, `bco`, plus the unified-`task: preference` dispatcher. Schema cross-validator rejects MLX backend,+`task: preference` dispatcher, though ReLoRA is refused for the tasks with a frozen+reference (below). Schema cross-validator rejects MLX backend,quantization other than `none`, `stream_layers`, `lora.use_vera`, `lora.use_dora`,and `use_fsdp2_compile` (the callback is HF Trainer-specific and restart requiresa writable float base).+**ReLoRA is refused where the loss has a frozen reference**: `task: dpo`, `ipo`,+`kto` and `bco`, `task: grpo` with `grpo_beta` above 0, and `task: preference`+whose loss or blend names `dpo`, `ipo` or `bco`. trl reads that reference from the+policy's own base weights (a `ref` adapter over them, or the model with its adapter+disabled), and every restart merges the trained adapter into those weights. From+the first restart on, the reference would be the policy as of that step instead of+the model the run started from. Measured on a fixed batch with the tiny test+model: the `dpo` reference does not move until the first restart and moves by 0.83+at it. `sft`, `orpo`, `simpo`, `reward_model`, `pretrain`, `embedding`, `grpo` with+`grpo_beta: 0` and a `simpo` / `orpo` preference run are not affected. `ppo` reads its+reference the same way as `kto` and `bco` but has not been measured.+## DoRA (Weight-Decomposed LoRA)diff --git a/docs/training.md b/docs/training.mdindex 4dc901ff..019f2196 100644--- a/docs/training.md+++ b/docs/training.md@@ -1044,7 +1044,10 @@ adapter off the model is then no longer the one the policy started from. A`dpo` / `ipo` term under a `simpo` / `orpo` primary is refused with either ofthem, before the model is loaded. With such an init, give `dpo` or `ipo` thelargest weight: trl's copy of the adapter carries the residual's other half,-so its reference is still the starting model.+so its reference is still the starting model. `relora_steps` has no such way+out: trl's `ref` adapter sits on the same base weights, so a blend that names+`dpo` or `ipo` refuses it whatever the largest weight is+([ReLoRA](peft-and-efficiency.md#lora-quality--pissa-relora-per-pattern-rank-surgical-patches)).**Which tokens.** The terms are computed on the primary trainer's batch, andthe two trainer families do not render a row the same way: the CPO / ORPOdiff --git a/src/soup_cli/config/schema.py b/src/soup_cli/config/schema.pyindex 5c34eaa4..5eb25c17 100644--- a/src/soup_cli/config/schema.py+++ b/src/soup_cli/config/schema.py@@ -7617,8 +7617,46 @@ class SoupConfig(BaseModel):"relora_steps is incompatible with training.use_fsdp2_compile=True: ""compiled FSDP2 wraps parameters and prevents in-place base merges.")+ reference = self._task_with_a_frozen_reference()+ if reference is not None:+ setting, terms = reference+ # #1835 -- measured: trl's reference on a fixed batch is unchanged+ # until the first restart and moves by 0.83 (dpo) at it.+ way_out = "Remove training.relora_steps."+ if terms:+ way_out = (+ f"Remove training.relora_steps, or remove {terms} from "+ "training.preference_loss_weights."+ )+ raise ValueError(+ f"training.relora_steps cannot be used here ({setting}): the loss "+ "compares the policy with a frozen reference, which trl builds on "+ "the policy's own base weights (a `ref` adapter, or the model with "+ "its adapter disabled). Every ReLoRA restart merges the trained "+ "adapter into those weights, so from the first restart on the "+ f"reference would be the policy as of that step. {way_out}"+ )return self+ def _task_with_a_frozen_reference(self) -> Optional[tuple[str, str]]:+ """``(the setting as a message names it, the blend's terms to drop or+ "")`` when this config's loss has a frozen reference on the policy's+ base weights; else ``None`` (#1835)."""+ tcfg = self.training+ if self.task in ("dpo", "ipo", "kto", "bco"):+ return f"task={self.task!r}", ""+ if self.task == "grpo" and tcfg.grpo_beta > 0:+ # With `grpo_beta: 0` trl adds no `ref` adapter and reads none.+ return f"task='grpo', grpo_beta={tcfg.grpo_beta}", ""+ if self.task == "preference":+ if tcfg.preference_loss_weights:+ terms = ", ".join(sorted(set(tcfg.preference_loss_weights) & {"dpo", "ipo", "bco"}))+ if terms:+ return f"task='preference', preference_loss_weights with {terms}", terms+ elif tcfg.preference_loss in ("dpo", "ipo", "bco"):+ return f"task='preference', preference_loss={tcfg.preference_loss!r}", ""+ return None+@model_validator(mode="after")def _validate_quant_menu_supported_tasks(self) -> "SoupConfig":"""v0.40.5 (#66) — Quant Menu (gptq/awq/hqq:Nbit/aqlm/eetq/mxfp4/fp8)diff --git a/tests/test_issue1425_dpo_ipo_blend.py b/tests/test_issue1425_dpo_ipo_blend.pyindex 218fa096..d37dd0cc 100644--- a/tests/test_issue1425_dpo_ipo_blend.py+++ b/tests/test_issue1425_dpo_ipo_blend.py@@ -838,7 +838,8 @@ class TestAnAdapterOffReferenceMustBeTheStartingModel:[(_LORA[:-1] + ", init_strategy: pissa}", FIELDS, "init_strategy='pissa'"),(_LORA[:-1] + ", use_olora: true}", FIELDS, "training.lora.use_olora=True"),- (_LORA, FIELDS + " relora_steps: 1\n", "training.relora_steps=1"),+ # relora_steps with a dpo / ipo term no longer gets this far: the+ # config refuses it when it is loaded (#1835).],)def test_a_real_setup_refuses_before_the_model_is_loaded(diff --git a/tests/test_relora.py b/tests/test_relora.pyindex 41e7ec6b..cb51804d 100644--- a/tests/test_relora.py+++ b/tests/test_relora.py@@ -1056,17 +1056,12 @@ class TestReLoRATaskGate:@pytest.mark.parametrize("task",[- "dpo",- "grpo",- "kto","orpo","simpo",- "ipo","ppo","reward_model","pretrain","embedding",- "bco",],)def test_other_tasks_accepted(self, task):@@ -1078,6 +1073,17 @@ class TestReLoRATaskGate:assert cfg.training.relora_steps == 100assert cfg.task == task+ @pytest.mark.parametrize("task", ["dpo", "grpo", "kto", "ipo", "bco"])+ def test_tasks_with_a_frozen_reference_rejected(self, task):+ """#1835: a restart merges the adapter into the weights the frozen+ reference is read from (``tests/test_relora_reference.py``)."""+ import yaml++ from soup_cli.config.loader import load_config_from_string++ with pytest.raises(ValueError, match="frozen reference"):+ load_config_from_string(yaml.safe_dump(self._base_cfg(task)))+def test_mlx_backend_rejected(self):import yamldiff --git a/tests/test_relora_reference.py b/tests/test_relora_reference.pynew file mode 100644index 00000000..4900ebeb--- /dev/null+++ b/tests/test_relora_reference.py@@ -0,0 +1,177 @@+"""#1835: a ReLoRA restart moves the frozen reference of a loss that has one.++trl builds the reference of DPO, IPO, KTO, BCO and GRPO on the policy's own+base weights: a frozen ``ref`` adapter, or the model with its adapter+disabled. A ReLoRA restart merges the trained adapter into those weights, so+from the first restart on the "frozen" reference is the policy as of that+step, and nothing says so. ``relora_steps`` is refused for those tasks.+"""++from __future__ import annotations++import pytest+from pydantic import ValidationError++from soup_cli.config.schema import SoupConfig++TRAIN = "tests/fixtures/sample_train.jsonl"+++def _cfg(task, data=None, **training):+ return SoupConfig(+ base="test/model",+ task=task,+ data={"train": TRAIN, **(data or {})},+ training={"batch_size": 2, "quantization": "none", **training},+ )+++def _refusal(task, data=None, **training):+ with pytest.raises(ValidationError) as excinfo:+ _cfg(task, data, relora_steps=100, **training)+ return excinfo.value.errors()[0]["msg"]+++_DPO_DATA = {"format": "dpo"}++#: (task, data, training, how the message names it)+WITH_A_REFERENCE = [+ ("dpo", _DPO_DATA, {}, "task='dpo'"),+ ("ipo", _DPO_DATA, {}, "task='ipo'"),+ ("bco", _DPO_DATA, {}, "task='bco'"),+ ("kto", {"format": "kto"}, {}, "task='kto'"),+ ("grpo", None, {}, "task='grpo', grpo_beta="),+ (+ "preference",+ _DPO_DATA,+ {"preference_loss": "dpo"},+ "task='preference', preference_loss='dpo'",+ ),+ (+ "preference",+ _DPO_DATA,+ {"preference_loss": "ipo"},+ "task='preference', preference_loss='ipo'",+ ),+ (+ "preference",+ _DPO_DATA,+ {"preference_loss": "bco"},+ "task='preference', preference_loss='bco'",+ ),+ (+ "preference",+ _DPO_DATA,+ {"preference_loss_weights": {"dpo": 0.7, "simpo": 0.3}},+ "task='preference', preference_loss_weights with dpo",+ ),+ (+ "preference",+ _DPO_DATA,+ {"preference_loss_weights": {"simpo": 0.5, "ipo": 0.3, "dpo": 0.2}},+ "task='preference', preference_loss_weights with dpo, ipo",+ ),+ (+ "preference",+ _DPO_DATA,+ # Loads, and is refused only when it runs (bco beside a paired loss).+ {"preference_loss_weights": {"bco": 0.6, "simpo": 0.4}},+ "task='preference', preference_loss_weights with bco",+ ),+]++WITHOUT_ONE = [+ ("sft", None, {}),+ ("orpo", _DPO_DATA, {}),+ ("simpo", _DPO_DATA, {}),+ ("grpo", None, {"grpo_beta": 0}),+ ("preference", _DPO_DATA, {"preference_loss": "simpo"}),+ ("preference", _DPO_DATA, {"preference_loss": "orpo"}),+ ("preference", _DPO_DATA, {"preference_loss_weights": {"simpo": 0.7, "orpo": 0.3}}),+]+++class TestTheRefusal:+ @pytest.mark.parametrize(("task", "data", "training", "named"), WITH_A_REFERENCE)+ def test_a_task_with_a_reference_refuses_relora_with_the_reason(+ self, task, data, training, named+ ):+ message = _refusal(task, data, **training)++ assert f"training.relora_steps cannot be used here ({named}" in message+ assert "frozen reference" in message and "merges the trained adapter" in message+ if "preference_loss_weights" in training:+ # A blend has a second way out: drop the terms that need a reference.+ terms = named.rsplit(" with ", 1)[1]+ assert message.rstrip().endswith(+ f"Remove training.relora_steps, or remove {terms} from "+ "training.preference_loss_weights."+ )+ else:+ assert message.rstrip().endswith("Remove training.relora_steps.")++ @pytest.mark.parametrize(("task", "data", "training", "named"), WITH_A_REFERENCE)+ def test_the_same_config_loads_without_relora(self, task, data, training, named):+ """The premise of each row above: it is ``relora_steps`` that is refused."""+ assert _cfg(task, data, **training).training.relora_steps is None++ @pytest.mark.parametrize(("task", "data", "training"), WITHOUT_ONE)+ def test_a_task_without_a_reference_keeps_relora(self, task, data, training):+ assert _cfg(task, data, relora_steps=100, **training).training.relora_steps == 100+++class TestThePremise:+ """What the refusal prevents, on a real run. The config is built without+ ``relora_steps`` and given it afterwards, past the validator."""++ @pytest.mark.parametrize("task", ["dpo", "ipo"])+ def test_a_restart_moves_trls_frozen_reference(self, tmp_path, monkeypatch, task):+ """trl's own ``compute_ref_log_probs`` on one fixed batch: unchanged+ until the restart at step 2, and another model's numbers from then on.+ If this fails, trl or PEFT keeps the reference apart from the base the+ restart merges into, and the refusal can go."""+ torch = pytest.importorskip("torch")+ from transformers import TrainerCallback++ from soup_cli.config.loader import load_config_from_string+ from soup_cli.trainer.dpo import DPOTrainerWrapper+ from soup_cli.trainer.ipo import IPOTrainerWrapper+ from tests.test_issue1425_dpo_ipo_blend import ROWS, _tiny_model_dir++ monkeypatch.chdir(tmp_path)+ base = _tiny_model_dir(tmp_path)+ cfg = load_config_from_string(+ f"base: {base.as_posix()}\ntask: {task}\n"+ "data: {train: ./unused.jsonl, format: dpo, max_length: 64}\n"+ "training:\n epochs: 3\n batch_size: 2\n lr: 0.05\n quantization: none\n"+ " lora: {r: 4, alpha: 8, dropout: 0.0}\noutput: ./out\n"+ )+ cfg = cfg.model_copy(+ update={"training": cfg.training.model_copy(update={"relora_steps": 2})}+ )+ wrapper = (DPOTrainerWrapper if task == "dpo" else IPOTrainerWrapper)(cfg, device="cpu")+ wrapper.setup({"train": ROWS})+ trainer = wrapper.trainer+ batch = trainer._prepare_inputs(next(iter(trainer.get_train_dataloader())))+ seen = {}++ def read(step):+ training = trainer.model.training+ with torch.no_grad():+ seen[step] = torch.cat(list(trainer.compute_ref_log_probs(batch))).clone()+ trainer.model.train(training)++ class _Probe(TrainerCallback):+ def on_train_begin(self, args, state, control, **kwargs):+ read(0)++ def on_step_end(self, args, state, control, **kwargs):+ read(state.global_step)++ trainer.add_callback(_Probe())++ wrapper.train()++ assert sorted(seen) == [0, 1, 2, 3]+ assert torch.equal(seen[1], seen[0])+ assert float((seen[2] - seen[0]).abs().max()) > 0.1diff --git a/tests/test_v0406_part_a.py b/tests/test_v0406_part_a.pyindex 77e1bec1..85f16d35 100644--- a/tests/test_v0406_part_a.py+++ b/tests/test_v0406_part_a.py@@ -258,12 +258,9 @@ def test_attach_relora_callback_rejects_zero_via_policy() -> None:class TestPreferenceTaskGate:"""Review-fix: cover the dispatcher task ('preference') with `relora_steps`."""- def test_preference_task_accepts_relora(self) -> None:- import yaml-- from soup_cli.config.loader import load_config_from_string-- cfg = load_config_from_string(yaml.safe_dump({+ @staticmethod+ def _cfg(preference_loss: str) -> dict:+ return {"base": "meta-llama/Llama-3.1-8B","task": "preference","backend": "transformers",@@ -271,16 +268,34 @@ class TestPreferenceTaskGate:"training": {"relora_steps": 100,"quantization": "none",- "preference_loss": "dpo",+ "preference_loss": preference_loss,},- }))+ }++ def test_preference_task_accepts_relora(self) -> None:+ """With a loss that has no frozen reference; ``dpo`` was the example+ here until #1835."""+ import yaml++ from soup_cli.config.loader import load_config_from_string++ cfg = load_config_from_string(yaml.safe_dump(self._cfg("simpo")))assert cfg.training.relora_steps == 100assert cfg.task == "preference"+ def test_preference_task_with_a_reference_loss_rejects_relora(self) -> None:+ import yaml++ from soup_cli.config.loader import load_config_from_string++ with pytest.raises(ValueError, match="frozen reference"):+ load_config_from_string(yaml.safe_dump(self._cfg("dpo")))+class TestReLoRASchemaGateWidened:"""v0.40.6 lifts the `task != 'sft'` rejection. Every transformer-backend- task now accepts `relora_steps`; MLX backend still rejected.+ task without a frozen reference accepts `relora_steps` (#1835 took out+ dpo / ipo / kto / bco / grpo); MLX backend still rejected."""def _base_cfg(@@ -298,17 +313,12 @@ class TestReLoRASchemaGateWidened:"task",["sft",- "dpo",- "grpo",- "kto","orpo","simpo",- "ipo","ppo","reward_model","pretrain","embedding",- "bco",],)def test_all_transformer_tasks_accepted(self, task: str) -> None:@@ -320,6 +330,15 @@ class TestReLoRASchemaGateWidened:assert cfg.training.relora_steps == 100assert cfg.task == task+ @pytest.mark.parametrize("task", ["dpo", "grpo", "kto", "ipo", "bco"])+ def test_tasks_with_a_frozen_reference_rejected(self, task: str) -> None:+ import yaml++ from soup_cli.config.loader import load_config_from_string++ with pytest.raises(ValueError, match="frozen reference"):+ load_config_from_string(yaml.safe_dump(self._base_cfg(task)))+def test_mlx_backend_still_rejected(self) -> None:import yaml