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(dpo): load a vision-language wrapper through AutoModelForImageTextToText when modality is vision (#1393) (#1707)

Srinivasan R1e281dff4182
diff --git a/changelog.d/0.75.1/1707.fixed.md b/changelog.d/0.75.1/1707.fixed.md
new file mode 100644
index 00000000..a7a958ea
--- /dev/null
+++ b/changelog.d/0.75.1/1707.fixed.md
@@ -0,0 +1 @@
+- **DPO loads a vision-language wrapper checkpoint when `modality: vision` is set (#1393 by @Srinivasan8888 in #1707).** `task: dpo` always built `AutoModelForCausalLM`, so a base published as a vision-language wrapper (MiniMax-M3, `model_type: minimax_m3_vl`) could not load at all, while SFT trained its language tower through its vision path. With `modality: vision`, DPO now loads `AutoModelForImageTextToText` with the model's processor, which trl's `DPOTrainer` takes as its processing class for text-only preference rows, and the LoRA targets resolve to the language tower as before; `soup recipes verify` builds the same class, and `task: preference` with `preference_loss: dpo` follows it. `backend: unsloth` does not read `modality` for DPO and is refused at config load for that combination. The text path is unchanged.
diff --git a/docs/training.md b/docs/training.md
index c1259c04..597a33f3 100644
--- a/docs/training.md
+++ b/docs/training.md
@@ -1263,6 +1263,13 @@ training:
quantization: 4bit
```
+A base published as a vision-language wrapper (MiniMax-M3, `model_type: minimax_m3_vl`) is not
+registered under `AutoModelForCausalLM`, so a plain DPO config cannot load it. Set `modality: vision`
+and DPO loads it the way SFT's vision path does, through `AutoModelForImageTextToText` with the
+model's processor, and trains the language tower; the LoRA targets resolve to that tower as before.
+Preference rows carry no images, and `soup recipes verify` builds the same class the trainer loads.
+`backend: unsloth` does not read `modality` for DPO and is refused at config load for it (#1393).
+
## Preference Variety — BCO + Unified Dispatcher + KL Variants
diff --git a/src/soup_cli/config/schema.py b/src/soup_cli/config/schema.py
index 009a9b98..0699bd1f 100644
--- a/src/soup_cli/config/schema.py
+++ b/src/soup_cli/config/schema.py
@@ -6727,6 +6727,26 @@ class SoupConfig(BaseModel):
)
return self
+ @model_validator(mode="after")
+ def _validate_dpo_vision_backend(self) -> "SoupConfig":
+ """#1393 — DPO reads ``modality`` only on the transformers backend: its
+ unsloth setup loads ``FastLanguageModel`` and never looks at it, so a
+ vision-language checkpoint there would load as a plain causal LM or not
+ at all. Refuse at config load with the backend that does read it. (MLX
+ refuses ``task: dpo`` itself.)"""
+ loss = self.training.preference_loss
+ weights = self.training.preference_loss_weights
+ if loss is None and weights:
+ loss = max(weights, key=weights.get) # a blend runs its largest weight's wrapper
+ runs_dpo = self.task == "dpo" or (self.task == "preference" and loss == "dpo")
+ if runs_dpo and self.modality == "vision" and self.backend == "unsloth":
+ raise ValueError(
+ f"task={self.task!r} with modality='vision' requires backend='transformers': "
+ "the unsloth DPO setup loads FastLanguageModel and does not read modality, so "
+ "a vision-language checkpoint cannot be trained there; got backend='unsloth'"
+ )
+ return self
+
@model_validator(mode="after")
def _validate_online_dpo_compat(self) -> "SoupConfig":
"""v0.71.31 — Online DPO gate.
diff --git a/src/soup_cli/trainer/dpo.py b/src/soup_cli/trainer/dpo.py
index 616736b3..cb37f8dd 100644
--- a/src/soup_cli/trainer/dpo.py
+++ b/src/soup_cli/trainer/dpo.py
@@ -289,12 +289,36 @@ class DPOTrainerWrapper(StreamingSetupMixin):
from peft import TaskType, get_peft_model, prepare_model_for_kbit_training
from transformers import AutoModelForCausalLM, AutoTokenizer
- console.print(f"[dim]Loading tokenizer: {cfg.base}[/]")
- self.tokenizer = AutoTokenizer.from_pretrained(
- cfg.base, trust_remote_code=self._trust_remote_code
- )
- if self.tokenizer.pad_token is None:
- self.tokenizer.pad_token = self.tokenizer.eos_token
+ if cfg.modality == "vision":
+ # #1393 — a checkpoint published as a vision-language wrapper
+ # (MiniMax-M3, ``model_type: minimax_m3_vl``) is not registered under
+ # AutoModelForCausalLM, so DPO could not load it at all while SFT's
+ # vision path trained its language tower. Load it the way SFT does:
+ # the processor stands in for the tokenizer (trl's DPOTrainer takes a
+ # ProcessorMixin as processing_class and tokenizes text-only
+ # preference rows through it), and the LoRA targets stay on the
+ # language tower through the usual resolver.
+ from transformers import AutoModelForImageTextToText, AutoProcessor
+
+ from soup_cli.trainer.sft import _ensure_vision_processor_pad_token
+
+ console.print(f"[dim]Loading vision processor: {cfg.base}[/]")
+ self.processor = AutoProcessor.from_pretrained(
+ cfg.base, trust_remote_code=self._trust_remote_code
+ )
+ _ensure_vision_processor_pad_token(self.processor)
+ self.tokenizer = self.processor
+ loader = AutoModelForImageTextToText
+ text_tokenizer = self.processor.tokenizer
+ else:
+ console.print(f"[dim]Loading tokenizer: {cfg.base}[/]")
+ self.tokenizer = AutoTokenizer.from_pretrained(
+ cfg.base, trust_remote_code=self._trust_remote_code
+ )
+ if self.tokenizer.pad_token is None:
+ self.tokenizer.pad_token = self.tokenizer.eos_token
+ loader = AutoModelForCausalLM
+ text_tokenizer = self.tokenizer
# Quantization (v0.38.0 Quant Menu — see soup_cli.utils.quant_menu)
from soup_cli.utils.quant_menu import build_quantization_config_for_loader
@@ -313,11 +337,11 @@ class DPOTrainerWrapper(StreamingSetupMixin):
if quant_config_obj is not None:
model_kwargs["quantization_config"] = quant_config_obj
- self.model = AutoModelForCausalLM.from_pretrained(cfg.base, **model_kwargs)
+ self.model = loader.from_pretrained(cfg.base, **model_kwargs)
from soup_cli.utils.data_pipeline import apply_vocab_expansion
apply_vocab_expansion(
- self.tokenizer,
+ text_tokenizer,
self.model,
cfg.data,
)
diff --git a/src/soup_cli/utils/attach_preflight.py b/src/soup_cli/utils/attach_preflight.py
index 865b2d6d..1f7971f5 100644
--- a/src/soup_cli/utils/attach_preflight.py
+++ b/src/soup_cli/utils/attach_preflight.py
@@ -427,9 +427,12 @@ _TASK_AUTO_CLASS = {
# trainer/asr.py loads the Whisper seq2seq class by name, not an auto-class.
"asr": ("WhisperForConditionalGeneration",),
}
-#: Only SFT reads ``modality`` (#1117 review): every other trainer loads its one
-#: class whatever the config says, so a vision DPO config is a causal LM there.
-_MODALITY_TASKS = frozenset({"sft"})
+#: The trainers that read ``modality``, and which values they read: SFT (#1117
+#: review) for vision and audio, and since #1393 DPO for vision only (its audio
+#: config still loads a causal LM, so answering by modality there would report a
+#: green verdict for a config the trainer cannot load). Every other trainer loads
+#: its one class whatever the config says.
+_MODALITY_TASKS = {"sft": frozenset({"vision", "audio"}), "dpo": frozenset({"vision"})}
#: ONE class per path, with no fallback, because no trainer has one. My first
#: version fell back from ``AutoModelForCausalLM`` to ``AutoModel``, so a config
#: the causal-LM class refuses -- MiniMax-M3 with no ``modality``, which cannot load
@@ -442,17 +445,27 @@ _DEFAULT_AUTO_CLASS = ("AutoModelForCausalLM",)
def loader_for(cfg: Any) -> tuple[str, ...]:
"""The auto-classes to try, in the order the config's trainer would.
- A task with its own class wins. After that only SFT lets ``modality`` choose
- (``trainer/sft.py`` is the one trainer that reads it); every other task loads
- a causal LM, so answering by modality there reported a vision DPO config as
- attaching while DPO's own ``AutoModelForCausalLM`` refused it (#1117 review).
+ A task with its own class wins. After that only the trainers that read
+ ``modality`` let it choose: SFT, and DPO since #1393 (``task: preference``
+ with ``preference_loss: dpo`` runs the DPO wrapper, so it answers the same
+ way). Every other task loads a causal LM, so answering by modality there
+ reported a vision config as attaching while the trainer's own
+ ``AutoModelForCausalLM`` refused it (#1117 review).
"""
task = getattr(cfg, "task", "")
if task in _TASK_AUTO_CLASS:
return _TASK_AUTO_CLASS[task]
- if task not in _MODALITY_TASKS:
- return _DEFAULT_AUTO_CLASS
- return _MODALITY_AUTO_CLASS.get(getattr(cfg, "modality", "text"), _DEFAULT_AUTO_CLASS)
+ if task == "preference":
+ training = getattr(cfg, "training", None)
+ loss = getattr(training, "preference_loss", None)
+ weights = getattr(training, "preference_loss_weights", None)
+ if loss is None and weights:
+ loss = max(weights, key=weights.get) # a blend runs its largest weight's wrapper
+ task = loss if loss in _MODALITY_TASKS else task
+ modality = getattr(cfg, "modality", "text")
+ if modality in _MODALITY_TASKS.get(task, ()):
+ return _MODALITY_AUTO_CLASS[modality]
+ return _DEFAULT_AUTO_CLASS
def load_hf_config(base: str) -> Any:
diff --git a/tests/test_issue1116_attach_preflight.py b/tests/test_issue1116_attach_preflight.py
index ef819865..2ac07ed1 100644
--- a/tests/test_issue1116_attach_preflight.py
+++ b/tests/test_issue1116_attach_preflight.py
@@ -859,9 +859,11 @@ class TestReviewFollowUps:
class TestOnlySftReadsModality:
"""#1117 review, round 3: ``loader_for`` chose the class from ``modality`` for
- every task, but only ``trainer/sft.py`` reads it. A vision DPO config was
+ every task, but only ``trainer/sft.py`` read it. A vision DPO config was
reported ATTACHES (8 modules, 4 of them in the vision tower) while DPO's own
- ``AutoModelForCausalLM`` refuses the base outright."""
+ ``AutoModelForCausalLM`` refused the base outright. Since #1393 DPO reads
+ ``modality`` too and is pinned in ``test_issue1393_dpo_vision_loader.py``; the
+ trainers here are the ones that still load one class whatever it says."""
@staticmethod
def _cfg(task, modality="text", **training):
@@ -879,7 +881,7 @@ class TestOnlySftReadsModality:
}
return load_config_from_string(yaml.safe_dump(raw))
- @pytest.mark.parametrize("task", ["dpo", "grpo"])
+ @pytest.mark.parametrize("task", ["grpo"])
def test_a_vision_config_on_a_text_trainer_is_a_causal_lm(self, task):
from soup_cli.utils.attach_preflight import loader_for
diff --git a/tests/test_issue1393_dpo_vision_loader.py b/tests/test_issue1393_dpo_vision_loader.py
new file mode 100644
index 00000000..06bdf8bd
--- /dev/null
+++ b/tests/test_issue1393_dpo_vision_loader.py
@@ -0,0 +1,297 @@
+"""#1393 — DPO loads a vision-language wrapper checkpoint when ``modality: vision``.
+
+``DPOTrainerWrapper`` always built ``AutoModelForCausalLM``, whatever ``modality``
+said, so a checkpoint published as a vision-language wrapper (MiniMax-M3,
+``model_type: minimax_m3_vl``) could not load at all, while SFT trained its language
+tower through ``AutoModelForImageTextToText``. DPO now picks the image-text class and
+the processor for ``modality: vision``, the attach preflight mirrors it (the class
+``soup recipes verify`` builds is the class the trainer loads), and the one backend
+whose DPO setup ignores ``modality`` is refused at config load. A tiny LLaVA stands in
+for MiniMax-M3: the same wrapper shape, built locally, no weights downloaded.
+"""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+torch = pytest.importorskip("torch")
+transformers = pytest.importorskip("transformers")
+pytest.importorskip("peft")
+
+from soup_cli.config.loader import load_config_from_string # noqa: E402
+from soup_cli.utils.attach_preflight import ( # noqa: E402
+ Verdict,
+ build_on_meta,
+ check_attach,
+ loader_for,
+)
+
+_LANGUAGE_TOWER = r".*language_model\..*\.self_attn\.(q_proj|v_proj)"
+
+
+def _llava_config():
+ from transformers import CLIPVisionConfig, LlamaConfig, LlavaConfig
+
+ return LlavaConfig(
+ text_config=LlamaConfig(
+ vocab_size=64, hidden_size=16, intermediate_size=32,
+ num_hidden_layers=2, num_attention_heads=2, num_key_value_heads=2,
+ pad_token_id=3, bos_token_id=1, eos_token_id=2,
+ ),
+ vision_config=CLIPVisionConfig(
+ hidden_size=16, intermediate_size=32, num_hidden_layers=2,
+ num_attention_heads=2, image_size=32, patch_size=16,
+ ),
+ image_token_index=63,
+ )
+
+
+def _tokenizer():
+ from tokenizers import Tokenizer, models, pre_tokenizers
+ from transformers import PreTrainedTokenizerFast
+
+ names = ["<unk>", "<s>", "</s>", "<pad>", "say", "hi", "hello", "world", "yes", "no"]
+ names += [f"w{i}" for i in range(len(names), 63)] + ["<image>"]
+ tok = Tokenizer(models.WordLevel(vocab={w: i for i, w in enumerate(names)}, unk_token="<unk>"))
+ tok.pre_tokenizer = pre_tokenizers.Whitespace()
+ # ``<image>`` is registered as a special token so the processor resolves its id
+ # (63) after a save/load round trip instead of falling back to the unknown id.
+ return PreTrainedTokenizerFast(
+ tokenizer_object=tok, unk_token="<unk>", bos_token="<s>", eos_token="</s>",
+ pad_token="<pad>", additional_special_tokens=["<image>"],
+ )
+
+
+def _save_tiny_llava(root):
+ """A LLaVA checkpoint on disk, the shape MiniMax-M3 is published in."""
+ from transformers import CLIPImageProcessor, LlavaForConditionalGeneration, LlavaProcessor
+
+ torch.manual_seed(7)
+ LlavaForConditionalGeneration(_llava_config()).save_pretrained(root)
+ LlavaProcessor(
+ image_processor=CLIPImageProcessor(
+ size={"height": 32, "width": 32}, crop_size={"height": 32, "width": 32}
+ ),
+ tokenizer=_tokenizer(),
+ patch_size=16,
+ ).save_pretrained(root)
+ return root.as_posix()
+
+
+def _save_tiny_llama(root):
+ from transformers import LlamaConfig, LlamaForCausalLM
+
+ torch.manual_seed(7)
+ LlamaForCausalLM(LlamaConfig(
+ vocab_size=64, hidden_size=16, intermediate_size=32, num_hidden_layers=2,
+ num_attention_heads=2, num_key_value_heads=2, pad_token_id=3, bos_token_id=1,
+ eos_token_id=2,
+ )).save_pretrained(root)
+ _tokenizer().save_pretrained(root)
+ return root.as_posix()
+
+
+def _yaml(base="org/m", task="dpo", modality=None, backend="transformers", targets=_LANGUAGE_TOWER,
+ output=None, **extra):
+ lines = [f"base: {base}", f"task: {task}", f"backend: {backend}"]
+ if modality is not None:
+ lines.append(f"modality: {modality}")
+ lines += ["data:", " train: x.jsonl", " format: dpo", " max_length: 64",
+ "training:", " quantization: none", " epochs: 1", " batch_size: 2"]
+ lines += [f" {k}: {v}" for k, v in extra.items()] # training.* knobs such as preference_loss
+ lines += [" lora:", " r: 4", " alpha: 8", " dropout: 0.0",
+ f" target_modules: {json.dumps(targets)}"]
+ if output is not None:
+ lines.append(f"output: {output}")
+ return "\n".join(lines) + "\n"
+
+
+def _cfg(**kw):
+ return load_config_from_string(_yaml(**kw))
+
+
+class TestTheLoaderMapFollowsTheTrainer:
+ """``loader_for`` must build the class ``trainer/dpo.py`` now loads."""
+
+ def test_vision_dpo_uses_the_image_text_class(self):
+ assert loader_for(_cfg(modality="vision")) == ("AutoModelForImageTextToText",)
+
+ def test_text_dpo_still_uses_a_causal_lm(self):
+ assert loader_for(_cfg()) == ("AutoModelForCausalLM",)
+ assert loader_for(_cfg(modality="text")) == ("AutoModelForCausalLM",)
+
+ def test_only_vision_changes_the_dpo_class(self):
+ """DPO reads ``vision`` only; its audio config still loads a causal LM, so the
+ preflight must say so too (review of #1707)."""
+ assert loader_for(_cfg(modality="audio")) == ("AutoModelForCausalLM",)
+
+ def test_a_blend_follows_its_highest_weighted_loss(self):
+ """``preference_loss_weights`` builds the wrapper of the largest weight."""
+ dpo_led = _cfg(task="preference", modality="vision",
+ preference_loss_weights="{dpo: 0.7, ipo: 0.3}")
+ ipo_led = _cfg(task="preference", modality="vision",
+ preference_loss_weights="{dpo: 0.3, ipo: 0.7}")
+ assert loader_for(dpo_led) == ("AutoModelForImageTextToText",)
+ assert loader_for(ipo_led) == ("AutoModelForCausalLM",)
+
+ def test_the_preference_alias_with_the_dpo_loss_follows_dpo(self):
+ """``task: preference`` with ``preference_loss: dpo`` runs the DPO wrapper, so
+ the preflight must answer for it the same way; the other losses keep their
+ own loaders and stay a causal LM."""
+ vision_dpo = _cfg(task="preference", modality="vision", preference_loss="dpo")
+ vision_simpo = _cfg(task="preference", modality="vision", preference_loss="simpo")
+ assert loader_for(vision_dpo) == ("AutoModelForImageTextToText",)
+ assert loader_for(vision_simpo) == ("AutoModelForCausalLM",)
+
+
+class TestTheRealAttach:
+ """The acceptance row of the issue, on the real resolution and the real
+ ``get_peft_model``: a DPO config with ``modality: vision`` attaches to the
+ language tower of a vision-language wrapper, and without the modality the
+ causal-LM class refuses the checkpoint, exactly what #1145 measured."""
+
+ @staticmethod
+ def _check(cfg):
+ return check_attach(
+ "vl-dpo", cfg, load_hf_config=lambda _base: _llava_config(), build_model=build_on_meta
+ )
+
+ def test_a_vision_dpo_config_attaches_to_the_language_tower(self):
+ check = self._check(_cfg(modality="vision"))
+ assert check.verdict is Verdict.ATTACHES, check.detail
+ assert check.adapted > 0
+ assert check.vision_modules == 0
+
+ def test_the_same_config_without_modality_still_cannot_load(self):
+ check = self._check(_cfg())
+ assert check.verdict is Verdict.CANNOT_ATTACH, check.detail
+
+ def test_a_dpo_audio_config_still_cannot_load(self):
+ check = self._check(_cfg(modality="audio"))
+ assert check.verdict is Verdict.CANNOT_ATTACH, check.detail
+
+
[email protected]("ignore::UserWarning")
+class TestTheWrapperLoadsTheRightClass:
+ """Through the real loaders on checkpoints saved to disk, nothing stubbed."""
+
+ @staticmethod
+ def _wrapper(tmp_path, monkeypatch, base, modality, targets=_LANGUAGE_TOWER):
+ from soup_cli.trainer.dpo import DPOTrainerWrapper
+
+ monkeypatch.setenv("WANDB_DISABLED", "true")
+ monkeypatch.chdir(tmp_path)
+ cfg = _cfg(base=base, modality=modality, targets=targets,
+ output=(tmp_path / "out").as_posix())
+ wrapper = DPOTrainerWrapper(cfg, device="cpu")
+ wrapper._setup_transformers(cfg, cfg.training)
+ return wrapper
+
+ def test_vision_loads_the_image_text_model_and_its_processor(self, tmp_path, monkeypatch):
+ from transformers import LlavaForConditionalGeneration, ProcessorMixin
+
+ base = _save_tiny_llava(tmp_path / "vl")
+ wrapper = self._wrapper(tmp_path, monkeypatch, base, "vision")
+ assert isinstance(wrapper.model.get_base_model(), LlavaForConditionalGeneration)
+ assert isinstance(wrapper.tokenizer, ProcessorMixin)
+ assert wrapper.tokenizer.pad_token is not None
+ adapted = [n for n, m in wrapper.model.named_modules() if hasattr(m, "lora_A")]
+ assert adapted and all("language_model" in n for n in adapted), adapted
+ assert not any("vision_tower" in n for n in adapted)
+
+ def test_vision_vocab_expansion_reaches_the_processors_tokenizer(self, tmp_path, monkeypatch):
+ """``data.add_new_tokens`` is applied by DPO (#1358), so on the vision path it
+ must go through the processor's nested tokenizer and resize the embeddings;
+ handing the processor itself to the expansion would skip both."""
+ from soup_cli.trainer.dpo import DPOTrainerWrapper
+
+ monkeypatch.setenv("WANDB_DISABLED", "true")
+ monkeypatch.chdir(tmp_path)
+ base = _save_tiny_llava(tmp_path / "vl")
+ text = _yaml(base=base, modality="vision", output=(tmp_path / "out").as_posix())
+ text = text.replace(" format: dpo\n", " format: dpo\n add_new_tokens: ['<zz>']\n")
+ cfg = load_config_from_string(text)
+ wrapper = DPOTrainerWrapper(cfg, device="cpu")
+ wrapper._setup_transformers(cfg, cfg.training)
+ tokenizer = wrapper.tokenizer.tokenizer
+ new_id = tokenizer.convert_tokens_to_ids("<zz>")
+ assert new_id not in (None, tokenizer.unk_token_id)
+ assert wrapper.model.get_input_embeddings().num_embeddings >= len(tokenizer)
+
+ def test_text_still_loads_a_causal_lm_with_a_tokenizer(self, tmp_path, monkeypatch):
+ from transformers import LlamaForCausalLM, PreTrainedTokenizerBase
+
+ base = _save_tiny_llama(tmp_path / "lm")
+ wrapper = self._wrapper(tmp_path, monkeypatch, base, None, targets=["q_proj", "v_proj"])
+ assert isinstance(wrapper.model.get_base_model(), LlamaForCausalLM)
+ assert isinstance(wrapper.tokenizer, PreTrainedTokenizerBase)
+
+
[email protected]("ignore::UserWarning")
+class TestARealDpoStepOnAVisionWrapper:
+ """The question the issue left open: what trl's ``DPOTrainer`` does with a
+ processor and preference rows that carry no images. Measured: it tokenizes the
+ text through the processor and trains. Nothing about trl is mocked."""
+
+ def test_setup_and_one_step(self, tmp_path, monkeypatch):
+ pytest.importorskip("trl")
+ pytest.importorskip("datasets")
+ from soup_cli.trainer.dpo import DPOTrainerWrapper
+
+ monkeypatch.setenv("WANDB_DISABLED", "true")
+ monkeypatch.delenv("WORLD_SIZE", raising=False)
+ monkeypatch.chdir(tmp_path)
+ base = _save_tiny_llava(tmp_path / "vl")
+ cfg = _cfg(base=base, modality="vision", output=(tmp_path / "out").as_posix())
+ # trl concatenates prompt + completion as strings, so the completions lead
+ # with a space to stay on the tiny word-level vocabulary.
+ rows = [
+ {"prompt": "say hi", "chosen": " hi", "rejected": " no"},
+ {"prompt": "say hello", "chosen": " hello world", "rejected": " no"},
+ {"prompt": "hello", "chosen": " hi", "rejected": " world"},
+ {"prompt": "hi", "chosen": " hello", "rejected": " no no"},
+ ]
+ wrapper = DPOTrainerWrapper(cfg, device="cpu")
+ wrapper.setup({"train": rows})
+ assert wrapper.trainer.processing_class is wrapper.tokenizer
+ result = wrapper.train()
+ assert result["total_steps"] >= 1, result
+ assert (tmp_path / "out" / "adapter_config.json").is_file()
+
+
+class TestABackendWhoseDpoIgnoresModalityIsRefused:
+ def test_unsloth_vision_dpo_is_refused_at_config_load(self):
+ with pytest.raises(ValueError) as excinfo:
+ _cfg(modality="vision", backend="unsloth")
+ message = " ".join(str(excinfo.value).split())
+ assert "modality='vision'" in message and "backend='transformers'" in message
+ assert "unsloth" in message
+
+ def test_the_preference_alias_with_the_dpo_loss_is_refused_the_same_way(self):
+ """``task: preference`` + ``preference_loss: dpo`` runs the same unsloth setup."""
+ with pytest.raises(ValueError) as excinfo:
+ _cfg(task="preference", modality="vision", backend="unsloth", preference_loss="dpo")
+ message = " ".join(str(excinfo.value).split())
+ assert "task='preference'" in message and "backend='transformers'" in message
+ alias = _cfg(task="preference", modality="vision", preference_loss="dpo")
+ assert alias.backend == "transformers"
+
+ def test_a_blend_led_by_dpo_is_refused_the_same_way(self):
+ with pytest.raises(ValueError) as excinfo:
+ _cfg(task="preference", modality="vision", backend="unsloth",
+ preference_loss_weights="{dpo: 0.7, ipo: 0.3}")
+ assert "backend='transformers'" in " ".join(str(excinfo.value).split())
+ led_by_ipo = _cfg(task="preference", modality="vision", backend="unsloth",
+ preference_loss_weights="{dpo: 0.3, ipo: 0.7}")
+ assert led_by_ipo.backend == "unsloth"
+
+ def test_unsloth_audio_dpo_is_not_refused(self):
+ """The refusal is about vision; widening it to every non-text modality would
+ survive every other test here."""
+ assert _cfg(modality="audio", backend="unsloth").backend == "unsloth"
+
+ def test_unsloth_text_dpo_and_transformers_vision_dpo_still_load(self):
+ assert _cfg(backend="unsloth").backend == "unsloth"
+ assert _cfg(modality="vision").modality == "vision"