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(dpo): subclass TrainerCallback lazily and refuse dpo_ref_regen_epochs until it is wired (#1229) (#1294)
Nurkhan Esenbekbb709b672346
diff --git a/changelog.d/0.75.1/1294.fixed.md b/changelog.d/0.75.1/1294.fixed.mdnew file mode 100644index 00000000..c996ab0e--- /dev/null+++ b/changelog.d/0.75.1/1294.fixed.md@@ -0,0 +1 @@+- **Fix DPO / IPO / preference beta schedule callback crashes and refuse un-wired reference regeneration (#1229 by @kok-o in #1294).** DPO, IPO, and `preference` runs configured with `dpo_beta_schedule` crashed at step 0 with `AttributeError: 'BetaScheduleCallback' object has no attribute 'on_epoch_begin'` because custom callbacks were plain Python classes rather than Hugging Face `TrainerCallback` subclasses. Converted callbacks to lazily subclass `TrainerCallback` without introducing import-time dependencies on heavy ML packages, verified beta annealing behavior under IPO and preference training, and enforced a load-time refusal for `dpo_ref_regen_epochs` as the feature is not wired yet.diff --git a/docs/training.md b/docs/training.mdindex 5e0cf740..5ffd15eb 100644--- a/docs/training.md+++ b/docs/training.md@@ -1219,7 +1219,7 @@ unified surface is additive.### KL-controlled DPO variants-Anneal β over training, periodically refresh the reference model:+Anneal β over training with `dpo_beta_schedule`:```yamltask: dpo # or task: preference + preference_loss: dpo, or task: ipo@@ -1227,12 +1227,9 @@ training:dpo_beta: 0.1dpo_beta_schedule: linear # linear | cosine | exponentialdpo_beta_end: 0.01- dpo_ref_regen_epochs: 2 # copy student → ref model every 2 epochs```-Both controls are gated to DPO-family tasks (`dpo`, `ipo`, or-`preference` with `preference_loss in {dpo, ipo}`); transformers-backend only.+Gated to DPO-family tasks (`dpo`, `ipo`, or `preference` with `preference_loss in {dpo, ipo}`); transformers backend only. `dpo_ref_regen_epochs` is refused at config load: it never regenerated the reference. With LoRA there is no separate reference model to copy into, and the DPO-family trainers cannot run with `lora.r: 0`. The wiring is tracked in [#1345](https://github.com/MakazhanAlpamys/Soup/issues/1345).### Multi-objective preference loss (schema-only in v0.40.0)diff --git a/src/soup_cli/config/schema.py b/src/soup_cli/config/schema.pyindex df43c888..04ed5096 100644--- a/src/soup_cli/config/schema.py+++ b/src/soup_cli/config/schema.py@@ -1398,7 +1398,7 @@ class TrainingConfig(BaseModel):le=1000,description=("Replace the frozen ref model with the current student every N "- "epochs. None = never regen (default). DPO-family tasks only."+ "epochs. Refused at load (#1345) - not wired yet."),)# Multi-objective preference loss (v0.40.0 Part D).@@ -6930,6 +6930,13 @@ class SoupConfig(BaseModel):f"preference_loss in {{dpo, ipo}}; got task={self.task!r}, "f"preference_loss={tcfg.preference_loss!r}.")+ # dpo_ref_regen_epochs refusal (#1345).+ if regen is not None:+ raise ValueError(+ "dpo_ref_regen_epochs is not wired yet (#1345): with LoRA TRL builds "+ "no separate reference model, and full fine-tuning is not supported on "+ f"task={self.task!r}. Remove dpo_ref_regen_epochs."+ )return self@model_validator(mode="after")diff --git a/src/soup_cli/utils/dpo_variants.py b/src/soup_cli/utils/dpo_variants.pyindex 3a37366a..d98b5f6a 100644--- a/src/soup_cli/utils/dpo_variants.py+++ b/src/soup_cli/utils/dpo_variants.py@@ -7,12 +7,12 @@ Two opt-in controls for DPO-family preference training:Three shapes: linear, cosine (1/2 (1 + cos(pi t)) ramp), exponential(geometric decay between ``beta_start`` and ``beta_end``).-2. **Reference-model regeneration** — every ``every_n_epochs``, replace- the frozen ref-model weights with a deep-copy of the current student.- Useful for self-improving loops where the policy quickly outpaces- the original reference.+2. **Reference-model regeneration** — refused at config load: with LoRA+ there is no separate reference model to copy into, and the DPO-family+ trainers cannot run with ``lora.r: 0``. The wiring is tracked in+ [#1345](https://github.com/MakazhanAlpamys/Soup/issues/1345).-Both helpers are duck-typed callbacks (no ``transformers`` import at+Both helpers are lazily-subclassed TrainerCallbacks (no ``transformers`` import atmodule scope) so they cost nothing on a torch-less interpreter and stayunit-testable on CI without GPUs."""@@ -20,11 +20,28 @@ unit-testable on CI without GPUs.from __future__ import annotationsimport math-from typing import Optional+from typing import TYPE_CHECKING, Optional++if TYPE_CHECKING:+ from transformers import TrainerCallback++ class BetaScheduleCallback(TrainerCallback):+ pass++ class RefModelRegenCallback(TrainerCallback):+ pass# Allowed schedule shapes, kept as a frozenset for runtime immutability.SUPPORTED_SCHEDULES: frozenset[str] = frozenset({"linear", "cosine", "exponential"})+__all__ = [+ "BetaScheduleCallback",+ "RefModelRegenCallback",+ "SUPPORTED_SCHEDULES",+ "build_dpo_variant_callbacks",+ "compute_beta_at_step",+]+def _validate_finite_positive(name: str, value: float) -> None:if isinstance(value, bool) or not isinstance(value, (int, float)):@@ -85,12 +102,12 @@ def compute_beta_at_step(return float(math.exp(log_start + (log_end - log_start) * progress))-class BetaScheduleCallback:- """Duck-typed ``TrainerCallback``: updates ``trainer.beta`` per step.+class _BetaScheduleCallback_body: # type: ignore[misc] # noqa: N801+ """HF ``TrainerCallback``: updates ``trainer.beta`` per step.- The HF ``TrainerCallback`` signature is matched without importing- ``transformers`` at module scope so this object is constructible in- a torch-less environment for unit testing.+ Subclasses the lazily-resolved ``TrainerCallback`` so it inherits the no-op+ default for every Trainer event; only ``on_train_begin`` and+ ``on_step_begin`` are overridden.Use ``attach(trainer)`` once, then add the callback to the trainer.Without ``attach``, ``on_step_begin`` is a no-op (defence-in-depth).@@ -154,8 +171,8 @@ class BetaScheduleCallback:return-class RefModelRegenCallback:- """Duck-typed callback: deep-copy student weights into ref_model on epoch.+class _RefModelRegenCallback_body: # type: ignore[misc] # noqa: N801+ """HF ``TrainerCallback``: deep-copy student weights into ref_model on epoch.On every Nth epoch (1-indexed; epoch 0 is skipped to avoid copyinguntrained weights), copies the current ``trainer.model`` state_dict@@ -237,8 +254,9 @@ def build_dpo_variant_callbacks("""callbacks: list = []if schedule is not None and beta_end is not None:+ beta_cls = globals().get("BetaScheduleCallback") or __getattr__("BetaScheduleCallback")callbacks.append(- BetaScheduleCallback(+ beta_cls(beta_start=beta_start,beta_end=beta_end,total_steps=total_steps,@@ -246,5 +264,42 @@ def build_dpo_variant_callbacks())if ref_regen_epochs is not None:- callbacks.append(RefModelRegenCallback(every_n_epochs=ref_regen_epochs))+ regen_cls = globals().get("RefModelRegenCallback") or __getattr__("RefModelRegenCallback")+ callbacks.append(regen_cls(every_n_epochs=ref_regen_epochs))return callbacks+++def _try_import_callback_base():+ """Return HF ``TrainerCallback`` (or ``object`` when transformers is absent).++ Imported inside the function so the module has no top-level transformers+ dependency; the class below still inherits every no-op event stub the HF+ dispatch loop requires. Mirrors ``monitoring/curriculum_callback.py``.+ """+ try:+ from transformers import TrainerCallback # noqa: PLC0415++ return TrainerCallback+ except Exception: # noqa: BLE001 — transformers optional in slim test envs.+ return object+++_LAZY_CALLBACKS = {+ "BetaScheduleCallback": _BetaScheduleCallback_body,+ "RefModelRegenCallback": _RefModelRegenCallback_body,+}+_BODY_SKIP = frozenset(("__dict__", "__weakref__"))+++def __getattr__(name: str): # PEP 562+ body = _LAZY_CALLBACKS.get(name)+ if body is not None:+ base = _try_import_callback_base()+ ns = {k: v for k, v in vars(body).items() if k not in _BODY_SKIP}+ cls = type(name, (base,), ns)+ cls.__module__ = __name__+ cls.__qualname__ = name+ globals()[name] = cls+ return cls+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+diff --git a/src/soup_cli/utils/trainer_plugins.py b/src/soup_cli/utils/trainer_plugins.pyindex d98fcaf4..dd2792f9 100644--- a/src/soup_cli/utils/trainer_plugins.py+++ b/src/soup_cli/utils/trainer_plugins.py@@ -140,7 +140,11 @@ def _instantiate_cce_plugin() -> Any:log that CCE is intended."""- class _CCEAdvisoryCallback:+ from soup_cli.utils.lisa import _try_import_callback_base++ base = _try_import_callback_base()++ class _CCEAdvisoryCallback(base):plugin_name = "cce_plugin"def on_train_begin(self, args=None, state=None, control=None, **kwargs): # noqa: ARG002diff --git a/tests/test_cli_startup_is_light.py b/tests/test_cli_startup_is_light.pyindex 82997c33..058a1112 100644--- a/tests/test_cli_startup_is_light.py+++ b/tests/test_cli_startup_is_light.py@@ -205,6 +205,7 @@ def test_light_command_invocation_stays_light(argv: list[str]):"soup_cli.utils.rl_checkpoint","soup_cli.utils.relora","soup_cli.utils.lisa",+ "soup_cli.utils.dpo_variants","soup_cli.monitoring.hf_push","soup_cli.monitoring.curriculum_callback","soup_cli.monitoring.grpo_stability_callback",diff --git a/tests/test_dpo_variants.py b/tests/test_dpo_variants.pyindex 2ad13406..6da9b61a 100644--- a/tests/test_dpo_variants.py+++ b/tests/test_dpo_variants.py@@ -11,7 +11,10 @@ constant-ref-model path is unchanged when both flags are unset.from __future__ import annotations+import ast+import importlibimport math+from pathlib import Pathfrom unittest.mock import MagicMockimport pytest@@ -31,6 +34,16 @@ class TestDPOVariantsConfig:training={"dpo_beta": 0.1, **training},)+ @pytest.mark.parametrize("lora_r", [0, 16])+ def test_ref_regen_epochs_refused_at_load(self, lora_r):+ with pytest.raises(ValidationError, match="dpo_ref_regen_epochs is not wired yet"):+ SoupConfig(+ base="some-model",+ task="dpo",+ data={"train": "./data.jsonl", "format": "dpo"},+ training={"dpo_ref_regen_epochs": 2, "lora": {"r": lora_r}},+ )+@pytest.mark.parametrize("sched", ["linear", "cosine", "exponential"])def test_beta_schedule_accepted(self, sched):cfg = self._base(dpo_beta_schedule=sched, dpo_beta_end=0.01)@@ -54,10 +67,6 @@ class TestDPOVariantsConfig:with pytest.raises(ValidationError, match="dpo_beta_schedule"):self._base(dpo_beta_end=0.01)- def test_ref_regen_epochs_positive(self):- cfg = self._base(dpo_ref_regen_epochs=2)- assert cfg.training.dpo_ref_regen_epochs == 2-def test_ref_regen_epochs_zero_rejected(self):with pytest.raises(ValidationError, match="dpo_ref_regen_epochs"):self._base(dpo_ref_regen_epochs=0)@@ -142,15 +151,42 @@ class TestDPOVariantsConfig:# ─── β schedule math ────────────────────────────────────────────────────────+ ("task", "extra"),+ [+ ("dpo", {}),+ ("ipo", {}),+ ("preference", {"preference_loss": "dpo"}),+ ("preference", {"preference_loss": "ipo"}),+ ],+)+def test_ref_regen_epochs_refused_on_every_dpo_family_task(task, extra):+ with pytest.raises(ValidationError, match="dpo_ref_regen_epochs is not wired yet"):+ SoupConfig(+ base="some-model",+ task=task,+ data={"train": "./data.jsonl", "format": "dpo"},+ training={"dpo_ref_regen_epochs": 2, **extra},+ )++class TestBetaSchedule:def test_linear_endpoints(self):from soup_cli.utils.dpo_variants import compute_beta_at_stepassert compute_beta_at_step(- beta_start=0.1, beta_end=0.01, step=0, total_steps=100, schedule="linear",+ beta_start=0.1,+ beta_end=0.01,+ step=0,+ total_steps=100,+ schedule="linear",) == pytest.approx(0.1)assert compute_beta_at_step(- beta_start=0.1, beta_end=0.01, step=100, total_steps=100, schedule="linear",+ beta_start=0.1,+ beta_end=0.01,+ step=100,+ total_steps=100,+ schedule="linear",) == pytest.approx(0.01)def test_linear_midpoint(self):@@ -158,7 +194,11 @@ class TestBetaSchedule:# Schema requires beta_end > 0; mid of (0.1, 0.02) = 0.06.mid = compute_beta_at_step(- beta_start=0.1, beta_end=0.02, step=50, total_steps=100, schedule="linear",+ beta_start=0.1,+ beta_end=0.02,+ step=50,+ total_steps=100,+ schedule="linear",)assert mid == pytest.approx(0.06)@@ -166,10 +206,18 @@ class TestBetaSchedule:from soup_cli.utils.dpo_variants import compute_beta_at_stepassert compute_beta_at_step(- beta_start=0.1, beta_end=0.01, step=0, total_steps=100, schedule="cosine",+ beta_start=0.1,+ beta_end=0.01,+ step=0,+ total_steps=100,+ schedule="cosine",) == pytest.approx(0.1)assert compute_beta_at_step(- beta_start=0.1, beta_end=0.01, step=100, total_steps=100, schedule="cosine",+ beta_start=0.1,+ beta_end=0.01,+ step=100,+ total_steps=100,+ schedule="cosine",) == pytest.approx(0.01)def test_cosine_midpoint(self):@@ -177,7 +225,11 @@ class TestBetaSchedule:# Cosine: at midpoint we expect (start+end)/2.mid = compute_beta_at_step(- beta_start=0.2, beta_end=0.02, step=50, total_steps=100, schedule="cosine",+ beta_start=0.2,+ beta_end=0.02,+ step=50,+ total_steps=100,+ schedule="cosine",)assert mid == pytest.approx(0.11, abs=1e-6)@@ -185,11 +237,17 @@ class TestBetaSchedule:from soup_cli.utils.dpo_variants import compute_beta_at_stepassert compute_beta_at_step(- beta_start=0.1, beta_end=0.01, step=0, total_steps=100,+ beta_start=0.1,+ beta_end=0.01,+ step=0,+ total_steps=100,schedule="exponential",) == pytest.approx(0.1)end = compute_beta_at_step(- beta_start=0.1, beta_end=0.01, step=100, total_steps=100,+ beta_start=0.1,+ beta_end=0.01,+ step=100,+ total_steps=100,schedule="exponential",)assert end == pytest.approx(0.01, rel=1e-4)@@ -199,14 +257,22 @@ class TestBetaSchedule:from soup_cli.utils.dpo_variants import compute_beta_at_stepassert compute_beta_at_step(- beta_start=0.1, beta_end=0.01, step=200, total_steps=100, schedule="linear",+ beta_start=0.1,+ beta_end=0.01,+ step=200,+ total_steps=100,+ schedule="linear",) == pytest.approx(0.01)def test_negative_step_clamps_to_start(self):from soup_cli.utils.dpo_variants import compute_beta_at_stepassert compute_beta_at_step(- beta_start=0.1, beta_end=0.01, step=-5, total_steps=100, schedule="linear",+ beta_start=0.1,+ beta_end=0.01,+ step=-5,+ total_steps=100,+ schedule="linear",) == pytest.approx(0.1)def test_invalid_schedule_raises(self):@@ -214,7 +280,10 @@ class TestBetaSchedule:with pytest.raises(ValueError, match="schedule"):compute_beta_at_step(- beta_start=0.1, beta_end=0.01, step=0, total_steps=100,+ beta_start=0.1,+ beta_end=0.01,+ step=0,+ total_steps=100,schedule="garbage",)@@ -222,7 +291,11 @@ class TestBetaSchedule:from soup_cli.utils.dpo_variants import compute_beta_at_stepassert compute_beta_at_step(- beta_start=0.1, beta_end=0.01, step=0, total_steps=0, schedule="linear",+ beta_start=0.1,+ beta_end=0.01,+ step=0,+ total_steps=0,+ schedule="linear",) == pytest.approx(0.01)def test_negative_total_steps_rejected(self):@@ -230,7 +303,10 @@ class TestBetaSchedule:with pytest.raises(ValueError, match="total_steps"):compute_beta_at_step(- beta_start=0.1, beta_end=0.01, step=0, total_steps=-1,+ beta_start=0.1,+ beta_end=0.01,+ step=0,+ total_steps=-1,schedule="linear",)@@ -240,7 +316,10 @@ class TestBetaSchedule:for bad in (float("nan"), float("inf"), -1.0):with pytest.raises(ValueError, match="finite|> 0"):compute_beta_at_step(- beta_start=bad, beta_end=0.01, step=0, total_steps=100,+ beta_start=bad,+ beta_end=0.01,+ step=0,+ total_steps=100,schedule="linear",)@@ -249,7 +328,10 @@ class TestBetaSchedule:with pytest.raises(ValueError, match="step"):compute_beta_at_step(- beta_start=0.1, beta_end=0.01, step=True, total_steps=100,+ beta_start=0.1,+ beta_end=0.01,+ step=True,+ total_steps=100,schedule="linear",)@@ -262,7 +344,10 @@ class TestBetaScheduleCallback:from soup_cli.utils.dpo_variants import BetaScheduleCallbackcb = BetaScheduleCallback(- beta_start=0.1, beta_end=0.01, total_steps=100, schedule="linear",+ beta_start=0.1,+ beta_end=0.01,+ total_steps=100,+ schedule="linear",)trainer = MagicMock()trainer.beta = 0.1@@ -278,7 +363,10 @@ class TestBetaScheduleCallback:from soup_cli.utils.dpo_variants import BetaScheduleCallbackcb = BetaScheduleCallback(- beta_start=0.1, beta_end=0.01, total_steps=100, schedule="linear",+ beta_start=0.1,+ beta_end=0.01,+ total_steps=100,+ schedule="linear",)state = MagicMock(global_step=50)# Should not raise.@@ -351,8 +439,11 @@ class TestBuildDPOVariantCallbacks:from soup_cli.utils.dpo_variants import build_dpo_variant_callbackscbs = build_dpo_variant_callbacks(- beta_start=0.1, beta_end=None, schedule=None,- total_steps=0, ref_regen_epochs=None,+ beta_start=0.1,+ beta_end=None,+ schedule=None,+ total_steps=0,+ ref_regen_epochs=None,)assert cbs == []@@ -363,8 +454,11 @@ class TestBuildDPOVariantCallbacks:)cbs = build_dpo_variant_callbacks(- beta_start=0.1, beta_end=0.01, schedule="linear",- total_steps=0, ref_regen_epochs=None,+ beta_start=0.1,+ beta_end=0.01,+ schedule="linear",+ total_steps=0,+ ref_regen_epochs=None,)assert len(cbs) == 1assert isinstance(cbs[0], BetaScheduleCallback)@@ -376,8 +470,11 @@ class TestBuildDPOVariantCallbacks:)cbs = build_dpo_variant_callbacks(- beta_start=0.1, beta_end=None, schedule=None,- total_steps=0, ref_regen_epochs=2,+ beta_start=0.1,+ beta_end=None,+ schedule=None,+ total_steps=0,+ ref_regen_epochs=2,)assert len(cbs) == 1assert isinstance(cbs[0], RefModelRegenCallback)@@ -390,8 +487,11 @@ class TestBuildDPOVariantCallbacks:)cbs = build_dpo_variant_callbacks(- beta_start=0.1, beta_end=0.01, schedule="linear",- total_steps=0, ref_regen_epochs=2,+ beta_start=0.1,+ beta_end=0.01,+ schedule="linear",+ total_steps=0,+ ref_regen_epochs=2,)assert len(cbs) == 2kinds = {type(cb) for cb in cbs}@@ -403,7 +503,10 @@ class TestBetaScheduleLazyTotalSteps:from soup_cli.utils.dpo_variants import BetaScheduleCallbackcb = BetaScheduleCallback(- beta_start=0.1, beta_end=0.01, total_steps=0, schedule="linear",+ beta_start=0.1,+ beta_end=0.01,+ total_steps=0,+ schedule="linear",)# Initially 0 — sentinel.assert cb.total_steps == 0@@ -416,7 +519,10 @@ class TestBetaScheduleLazyTotalSteps:from soup_cli.utils.dpo_variants import BetaScheduleCallbackcb = BetaScheduleCallback(- beta_start=0.1, beta_end=0.01, total_steps=0, schedule="linear",+ beta_start=0.1,+ beta_end=0.01,+ total_steps=0,+ schedule="linear",)trainer = MagicMock()trainer.beta = 0.1@@ -432,8 +538,216 @@ class TestBetaScheduleLazyTotalSteps:# Cosine at progress=0 should equal beta_start exactly (cos(0)=1).result = compute_beta_at_step(- beta_start=0.1, beta_end=0.01, step=1, total_steps=10**9,+ beta_start=0.1,+ beta_end=0.01,+ step=1,+ total_steps=10**9,schedule="cosine",)# Very near beta_start since progress ~ 1e-9.assert math.isclose(result, 0.1, rel_tol=1e-6)+++# ─── Issue #1229: TrainerCallback Subclassing & Dispatch ────────────────────+++class TestCallbacksSubclassTrainerCallback:+ """Pins issue #1229: callbacks must be real TrainerCallback subclasses."""++ def test_beta_schedule_is_trainer_callback_subclass(self):+ from transformers import TrainerCallback++ from soup_cli.utils.dpo_variants import BetaScheduleCallback++ cb = BetaScheduleCallback(0.1, 0.05, 10, "linear")+ assert isinstance(cb, TrainerCallback)++ def test_ref_model_regen_is_trainer_callback_subclass(self):+ from transformers import TrainerCallback++ from soup_cli.utils.dpo_variants import RefModelRegenCallback++ cb = RefModelRegenCallback(1)+ assert isinstance(cb, TrainerCallback)++ def test_inherits_noop_unimplemented_events(self):+ from soup_cli.utils.dpo_variants import BetaScheduleCallback, RefModelRegenCallback++ beta_cb = BetaScheduleCallback(0.1, 0.05, 10, "linear")+ assert callable(beta_cb.on_epoch_begin)+ # Calling inherited no-op stub must not raise AttributeError+ beta_cb.on_epoch_begin(None, None, None)++ regen_cb = RefModelRegenCallback(1)+ assert callable(regen_cb.on_train_begin)+ regen_cb.on_train_begin(None, None, None)++ def test_callback_handler_dispatch_no_attribute_error(self):+ from transformers.trainer_callback import CallbackHandler, TrainerControl, TrainerState++ from soup_cli.utils.dpo_variants import BetaScheduleCallback, RefModelRegenCallback++ for callback, event in (+ (BetaScheduleCallback(0.1, 0.05, 10, "linear"), "on_epoch_begin"),+ (RefModelRegenCallback(1), "on_train_begin"),+ ):+ handler = CallbackHandler([], None, None, None, None)+ handler.add_callback(callback)+ # HF CallbackHandler.call_event dispatches with getattr(cb, event)+ getattr(handler, event)(None, TrainerState(), TrainerControl())+++class TestRealTrainerBetaSchedule:+ """Real DPO / IPO / Preference train() runs on tiny CPU model."""++ @pytest.mark.parametrize("sched", ["linear", "cosine", "exponential"])+ def test_dpo_train_beta_schedule_acts(self, tmp_path, sched):+ from soup_cli.config.loader import load_config_from_string+ from soup_cli.trainer.dpo import DPOTrainerWrapper+ from soup_cli.utils.dpo_variants import compute_beta_at_step++ rows = [+ {"prompt": f"Q{i}?", "chosen": f"A{i} good.", "rejected": f"A{i} bad."}+ for i in range(4)+ ]+ out_dir = (tmp_path / f"out_dpo_{sched}").as_posix()+ cfg = load_config_from_string(f"""+base: sshleifer/tiny-gpt2+task: dpo+data:+ train: x.jsonl+ max_length: 64+training:+ epochs: 2+ batch_size: 2+ quantization: none+ lr: 1e-4+ dpo_beta: 0.1+ dpo_beta_schedule: {sched}+ dpo_beta_end: 0.05+output: {out_dir}+""")+ wrapper = DPOTrainerWrapper(cfg, device="cpu")+ wrapper.setup({"train": list(rows)})+ res = wrapper.train()+ assert res.get("total_steps", 0) >= 2+ expected_beta = compute_beta_at_step(+ beta_start=0.1,+ beta_end=0.05,+ step=1,+ total_steps=wrapper.trainer.state.max_steps,+ schedule=sched,+ )+ assert wrapper.trainer.beta == pytest.approx(expected_beta, abs=1e-5)+++def _run_schedule(tmp_path, task, training):+ from soup_cli.config.loader import load_config_from_string++ rows = [+ {"prompt": f"Q{i}?", "chosen": f"A{i} good.", "rejected": f"A{i} bad."} for i in range(4)+ ]+ cfg = load_config_from_string(+ "base: sshleifer/tiny-gpt2\n"+ f"task: {task}\n"+ "data:\n train: x.jsonl\n max_length: 64\n"+ "training:\n epochs: 2\n batch_size: 2\n quantization: none\n lr: 1e-4\n"+ f"{training}"+ f"output: {(tmp_path / 'out').as_posix()}\n"+ )+ if task == "ipo":+ from soup_cli.trainer.ipo import IPOTrainerWrapper as Wrapper+ else:+ from soup_cli.trainer.preference import PreferenceTrainerWrapper as Wrapper+ wrapper = Wrapper(cfg, device="cpu")+ wrapper.setup({"train": list(rows)})+ return wrapper, wrapper.train()+++def test_ipo_schedule_anneals_from_ipo_tau(tmp_path):+ from soup_cli.utils.dpo_variants import compute_beta_at_step++ wrapper, result = _run_schedule(+ tmp_path, "ipo", " ipo_tau: 0.2\n dpo_beta_schedule: linear\n dpo_beta_end: 0.05\n"+ )+ assert result.get("total_steps", 0) >= 2+ expected = compute_beta_at_step(+ beta_start=0.2,+ beta_end=0.05,+ step=1,+ total_steps=wrapper.trainer.state.max_steps,+ schedule="linear",+ )+ assert wrapper.trainer.beta == pytest.approx(expected, abs=1e-6)++[email protected]("loss", ["dpo", "ipo"])+def test_preference_dispatcher_schedule_acts(tmp_path, loss):+ from soup_cli.utils.dpo_variants import compute_beta_at_step++ start, start_key = (0.1, "dpo_beta") if loss == "dpo" else (0.2, "ipo_tau")+ wrapper, result = _run_schedule(+ tmp_path,+ "preference",+ f" preference_loss: {loss}\n {start_key}: {start}\n"+ " dpo_beta_schedule: cosine\n dpo_beta_end: 0.05\n",+ )+ assert result.get("total_steps", 0) >= 2+ expected = compute_beta_at_step(+ beta_start=start,+ beta_end=0.05,+ step=1,+ total_steps=wrapper.trainer.state.max_steps,+ schedule="cosine",+ )+ assert wrapper.trainer.beta == pytest.approx(expected, abs=1e-6)+++def _lazy_body_names(tree):+ names = set()+ for node in ast.walk(tree):+ if not (isinstance(node, ast.Assign) and isinstance(node.value, ast.Dict)):+ continue+ if any(isinstance(t, ast.Name) and t.id == "_LAZY_CALLBACKS" for t in node.targets):+ names |= {v.id for v in node.value.values if isinstance(v, ast.Name)}+ return names+++def test_no_bare_callback_classes():+ from transformers import TrainerCallback++ import soup_cli++ root = Path(soup_cli.__file__).parent+ events = {name for name in dir(TrainerCallback) if name.startswith("on_")}+ bare = []+ for path in sorted(root.rglob("*.py")):+ tree = ast.parse(path.read_text(encoding="utf-8"), str(path))+ lazy = _lazy_body_names(tree)+ for node in ast.walk(tree):+ if not isinstance(node, ast.ClassDef) or node.name in lazy:+ continue+ methods = {n.name for n in node.body if isinstance(n, ast.FunctionDef)}+ if not methods & events:+ continue+ bases = [b.id for b in node.bases if isinstance(b, ast.Name)]+ if not node.bases or bases == ["object"]:+ bare.append(f"{path.relative_to(root).as_posix()}::{node.name}")+ assert not bare, f"callback classes without a TrainerCallback base: {bare}"+++def test_every_lazy_callback_builds_a_trainer_callback():+ from transformers import TrainerCallback++ import soup_cli++ root = Path(soup_cli.__file__).parent+ for path in sorted(root.rglob("*.py")):+ tree = ast.parse(path.read_text(encoding="utf-8"), str(path))+ if not _lazy_body_names(tree):+ continue+ dotted = ".".join(path.relative_to(root.parent).with_suffix("").parts)+ module = importlib.import_module(dotted)+ for name in module._LAZY_CALLBACKS:+ cls = getattr(module, name)+ assert issubclass(cls, TrainerCallback), f"{dotted}.{name}"