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.

feat(mlx): add native DoRA for text SFT (#1920)

AmixDigitalebd1570b75dd
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 78c25ada..6cede7ac 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -398,12 +398,12 @@ jobs:
python -c "import importlib.util; names=('torch','trl','datasets','peft','accelerate','bitsandbytes'); present=[name for name in names if importlib.util.find_spec(name)]; assert not present, f'unexpected training dependencies: {present}'"
- name: Run one-step MLX SFT through the real CLI
run: pytest -o addopts= -m smoke -k mlx_sft_smoke -q tests/test_smoke_train.py
- - name: Run the MLX flight-recorder tests
+ - name: Run the MLX flight-recorder and DoRA lifecycle tests
# These importorskip on `mlx.core` / `mlx_lm`, which the 3x3 matrix does
# not install (`mlx` is not in [dev]), so this is the only job that can
# execute them. Without this step, replacing the whole MLX per-row loss
# with a constant 0.0 left the suite green (#1018 review).
- run: pytest -o addopts= -q tests/test_rewind_mlx.py
+ run: pytest -o addopts= -q tests/test_rewind_mlx.py tests/test_mlx_dora_native.py
torchao-contract:
needs: plan
# Not on a pull request, approval run included: it is not a required check.
diff --git a/changelog.d/0.76.0/1918.added.md b/changelog.d/0.76.0/1918.added.md
new file mode 100644
index 00000000..79be1f59
--- /dev/null
+++ b/changelog.d/0.76.0/1918.added.md
@@ -0,0 +1 @@
+- Native DoRA for MLX text SFT on dense unquantized and pre-quantized 4-bit linear targets, with reloadable adapter metadata, compatible-weight warm-start checks, explicit unsupported-target refusals and Apple Silicon lifecycle regression coverage (#1918 by @Amix29).
diff --git a/docs/backends-and-ops.md b/docs/backends-and-ops.md
index f0be800a..0015faef 100644
--- a/docs/backends-and-ops.md
+++ b/docs/backends-and-ops.md
@@ -119,6 +119,35 @@ training:
MLX backend supports SFT. `backend: mlx` with `task: dpo` or `task: grpo` is refused when the config is loaded, with an error naming the task — upstream `mlx-lm` ships no DPO/GRPO training helper, so those wrappers exist only as a backstop for callers that bypass config validation. Requires `mlx-lm >= 0.31.3`. Use `soup recipes search mlx` for ready-made Apple Silicon configs.
+#### DoRA on MLX
+
+For text SFT, set `training.lora.use_dora: true` to use MLX-LM's native
+weight-decomposed adapter instead of plain LoRA. Soup supports dense linear
+targets on unquantized or pre-quantized 4-bit bases, with the same scalar
+`lora.r`, `lora.alpha` and `target_modules` settings as MLX LoRA. The base remains
+frozen; the low-rank factors and magnitude parameters train. Switch/expert layers,
+embedding targets, unmatched target names and 8-bit target layers are refused
+before adapter conversion. `use_rslora`, `rank_pattern` and `alpha_pattern` are
+not supported with MLX DoRA. Unsloth DoRA remains refused.
+
+The output records `fine_tune_type: dora` and is loadable with
+`mlx_lm.load(base, adapter_path=output)`. `soup train --resume auto` warm-starts
+the DoRA weights, including magnitudes; it refuses missing, extra or differently
+shaped adapter tensors before loading any of them. This restores weights only,
+not optimizer state, dataset position or the iteration counter.
+
+To fuse the adapter, use the native MLX-LM command (this is not `soup merge`):
+
+```bash
+mlx_lm.fuse --model ./mlx-base --adapter-path ./output \
+ --save-path ./fused-model --dequantize
+```
+
+Native regression tests use a local, randomly initialized one-layer Llama and
+check training, frozen base weights, gradients, reload and dequantized fusion.
+They require no model downloads. They establish adapter lifecycle correctness;
+they do not establish pretrained-model quality or a speed advantage over LoRA.
+
#### Optimizers and schedules
`training.optimizer`, `training.scheduler`, `training.warmup_ratio` and
diff --git a/docs/peft-and-efficiency.md b/docs/peft-and-efficiency.md
index 1f051da8..7fc16ba3 100644
--- a/docs/peft-and-efficiency.md
+++ b/docs/peft-and-efficiency.md
@@ -409,9 +409,11 @@ training:
```
Works with all training tasks on the transformers backend (see the note on
-quantized bases below). On `backend: unsloth` and `backend: mlx`, `use_dora: true`
-is refused when the config is loaded: neither backend builds a DoRA adapter, so
-it would silently train plain LoRA.
+quantized bases below). The MLX backend also supports DoRA for text SFT on dense
+linear targets with unquantized or pre-quantized 4-bit bases; see
+[DoRA on MLX](backends-and-ops.md#dora-on-mlx) for restrictions and native adapter
+loading/fusion. On `backend: unsloth`, `use_dora: true` remains refused at config
+load because that path does not build a DoRA adapter.
> **Not on GPTQ / AWQ / AQLM / EETQ bases.** peft has no DoRA variant for those
> layers and raises when the adapter is attached, so `use_dora: true` with
diff --git a/src/soup_cli/config/schema.py b/src/soup_cli/config/schema.py
index 5eb25c17..9f7e00c8 100644
--- a/src/soup_cli/config/schema.py
+++ b/src/soup_cli/config/schema.py
@@ -5426,6 +5426,23 @@ class SoupConfig(BaseModel):
# mlx refuses Quant Menu formats in the quant-menu task validator below.
if self.backend == "mlx" and is_quant_menu_format(self.training.quantization):
return self
+ if self.backend == "mlx" and variant == "dora":
+ if lcfg.use_rslora or lcfg.rank_pattern or lcfg.alpha_pattern:
+ raise ValueError(
+ "MLX DoRA does not support lora.use_rslora, rank_pattern "
+ "or alpha_pattern; use scalar lora.r and lora.alpha."
+ )
+ if (
+ self.task == "sft"
+ and self.modality == "text"
+ and self.training.quantization in ("none", "4bit")
+ ):
+ return self
+ raise ValueError(
+ "MLX DoRA requires task='sft', modality='text' and "
+ "quantization='none' or '4bit'. Use backend='transformers' "
+ "for other supported DoRA training paths."
+ )
raise ValueError(
f"training.lora variant {variant!r} requires backend='transformers'; "
f"backend={self.backend!r} has its own adapter constructor and cannot "
diff --git a/src/soup_cli/trainer/mlx_sft.py b/src/soup_cli/trainer/mlx_sft.py
index 90186fec..80980c33 100644
--- a/src/soup_cli/trainer/mlx_sft.py
+++ b/src/soup_cli/trainer/mlx_sft.py
@@ -247,7 +247,7 @@ def build_mlx_adapter_config(lora_cfg: object, *, adapter_path: str, **extra: ob
"""
rank = int(getattr(lora_cfg, "r", 0))
config: dict = {
- "fine_tune_type": "lora",
+ "fine_tune_type": "dora" if getattr(lora_cfg, "use_dora", False) else "lora",
"adapter_path": adapter_path,
"lora_parameters": {
"rank": rank,
@@ -411,7 +411,6 @@ class MLXSFTTrainerWrapper:
without it every parameter is trainable and the saved "adapter" is
actually a full fine-tune (172 tensors instead of ~64 LoRA weights).
"""
- model.freeze()
from mlx_lm.tuner.utils import linear_to_lora_layers
cfg = self.config
@@ -428,6 +427,33 @@ class MLXSFTTrainerWrapper:
f"all architectures; defaulting to {target_keys}[/]"
)
keys = set(target_keys)
+ use_dora = bool(lora_cfg.use_dora)
+ if use_dora:
+ import mlx.nn as nn
+
+ # Upstream also converts embeddings and switch layers. This first
+ # DoRA path qualifies dense linear targets only. Check every target
+ # before freezing/converting so a typo or unsupported layer cannot
+ # silently train a subset or leave a partly converted model.
+ matches = [
+ (name, module)
+ for parent in [*model.layers, model]
+ for name, module in parent.named_modules()
+ if name in keys
+ ]
+ missing = keys - {name for name, _ in matches}
+ unsupported = [
+ name for name, module in matches
+ if not isinstance(module, (nn.Linear, nn.QuantizedLinear))
+ or (isinstance(module, nn.QuantizedLinear) and module.bits != 4)
+ ]
+ if missing or unsupported:
+ raise ValueError(
+ "MLX DoRA requires dense linear targets (unquantized or 4-bit); "
+ f"unmatched targets: {sorted(missing)}; "
+ f"unsupported targets: {sorted(set(unsupported))}."
+ )
+ model.freeze()
num_layers = len(getattr(model, "layers", []))
linear_to_lora_layers(
model,
@@ -438,6 +464,7 @@ class MLXSFTTrainerWrapper:
"dropout": float(getattr(lora_cfg, "dropout", 0.0) or 0.0),
"keys": keys,
},
+ **({"use_dora": True} if use_dora else {}),
)
def _load_checkpoint_weights(self, checkpoint_path: str) -> None:
@@ -474,6 +501,23 @@ class MLXSFTTrainerWrapper:
f"MLX checkpoint {checkpoint_path} declares no tensors; refusing "
"to warm-start from an empty or corrupt checkpoint file"
)
+ if self.config.training.lora.use_dora:
+ import mlx.core as mx
+ from mlx.utils import tree_flatten
+
+ # load_weights(strict=False) is needed for adapter-only files, but
+ # also silently ignores missing/unexpected tensors. Validate the
+ # complete DoRA adapter before any model state is changed.
+ weights = mx.load(checkpoint_path)
+ expected = dict(tree_flatten(self.model.trainable_parameters()))
+ if weights.keys() != expected.keys() or any(
+ weights[name].shape != expected[name].shape for name in weights.keys() & expected
+ ):
+ raise ValueError(
+ f"DoRA checkpoint {checkpoint_path} is incompatible with the "
+ "configured adapter targets/rank; all DoRA tensors, including "
+ "magnitudes, must match."
+ )
console.print(
f"[green]MLX: loading checkpoint weights from[/] {checkpoint_path} "
f"({tensor_count} tensors)"
@@ -901,7 +945,7 @@ class MLXSFTTrainerWrapper:
(output_dir / "adapter_config.json").write_text(
json.dumps(
{
- "fine_tune_type": "lora",
+ **build_mlx_adapter_config(lora_cfg, adapter_path=str(output_dir)),
"model": str(cfg.base),
"num_layers": len(getattr(self.model, "layers", [])),
"batch_size": batch_size,
@@ -911,11 +955,6 @@ class MLXSFTTrainerWrapper:
"steps_per_eval": steps_per_eval,
"steps_per_save": steps_per_save,
"max_seq_length": max_seq_length,
- "adapter_path": str(output_dir),
- # #392: the RESOLVED module list, never the raw `auto`.
- "lora_parameters": build_mlx_adapter_config(
- lora_cfg, adapter_path=str(output_dir)
- )["lora_parameters"],
# #683: the EFFECTIVE masking, not a hardcoded False.
# `mask_prompt` stays upstream's meaning (a single masked
# prefix); `response_token_mask` is Soup's per-token mask,
diff --git a/tests/test_advanced_peft.py b/tests/test_advanced_peft.py
index bfdacf62..251614dc 100644
--- a/tests/test_advanced_peft.py
+++ b/tests/test_advanced_peft.py
@@ -54,8 +54,8 @@ class TestDoRAConfig:
assert cfg.training.lora.r == 128
assert cfg.training.lora.alpha == 32
- @pytest.mark.parametrize("backend", ["unsloth", "mlx"])
- def test_use_dora_is_refused_off_the_transformers_backend(self, backend: str):
+ @pytest.mark.parametrize("backend", ["unsloth"])
+ def test_use_dora_is_refused_on_unsloth(self, backend: str):
from soup_cli.config.loader import load_config_from_string
with pytest.raises(
diff --git a/tests/test_mlx_dora.py b/tests/test_mlx_dora.py
new file mode 100644
index 00000000..3dacab60
--- /dev/null
+++ b/tests/test_mlx_dora.py
@@ -0,0 +1,74 @@
+"""The supported MLX DoRA contract, without requiring Apple hardware."""
+
+import pytest
+from pydantic import ValidationError
+
+from soup_cli.config.schema import LoraConfig, SoupConfig
+from soup_cli.trainer.mlx_sft import build_mlx_adapter_config
+
+
[email protected]("quantization", ["none", "4bit"])
+def test_mlx_text_sft_accepts_dora(quantization):
+ cfg = SoupConfig(
+ base="local-llama",
+ backend="mlx",
+ data={"train": "train.jsonl"},
+ training={"quantization": quantization, "lora": {"use_dora": True}},
+ )
+ assert cfg.training.lora.use_dora is True
+ assert cfg.training.quantization == quantization
+
+
[email protected]("use_dora", [False, True])
+def test_adapter_metadata_preserves_the_method_and_parameters(use_dora):
+ cfg = LoraConfig(
+ r=4, alpha=12, dropout=0.1, target_modules=["self_attn.v_proj"], use_dora=use_dora
+ )
+ written = build_mlx_adapter_config(cfg, adapter_path="adapters")
+ assert written["fine_tune_type"] == ("dora" if use_dora else "lora")
+ assert written["adapter_path"] == "adapters"
+ assert written["lora_parameters"] == {
+ "rank": 4, "scale": 3.0, "dropout": 0.1, "keys": ["self_attn.v_proj"]
+ }
+
+
+ "overrides, training",
+ [
+ ({"backend": "unsloth"}, {}),
+ ({"task": "dpo"}, {}),
+ ({"modality": "vision"}, {}),
+ ({"modality": "audio"}, {}),
+ ({}, {"quantization": "8bit"}),
+ ],
+)
+def test_unimplemented_dora_routes_remain_refused(overrides, training):
+ with pytest.raises(ValidationError, match="[Dd][Oo][Rr][Aa]|variant 'dora'"):
+ SoupConfig(
+ **{"base": "local-llama", "backend": "mlx", **overrides},
+ data={"train": "train.jsonl"},
+ training={"quantization": "none", **training, "lora": {"use_dora": True}},
+ )
+
+
[email protected]("task", ["grpo", "pretrain"])
+def test_non_sft_dora_is_refused_by_the_dora_task_gate(task: str) -> None:
+ # Pin the DoRA-specific refusal: the general MLX task validator must not
+ # hide a missing task gate here by rejecting the config for another reason.
+ with pytest.raises(ValidationError, match="MLX DoRA requires task='sft'"):
+ SoupConfig(
+ base="local-llama", backend="mlx", task=task,
+ data={"train": "train.jsonl"},
+ training={"quantization": "none", "lora": {"use_dora": True}},
+ )
+
+
[email protected]("option", [
+ {"use_rslora": True}, {"rank_pattern": {"q_proj": 2}}, {"alpha_pattern": {"q_proj": 4}}
+])
+def test_mlx_dora_refuses_unimplemented_scaling_options(option):
+ with pytest.raises(ValidationError, match="MLX DoRA does not support"):
+ SoupConfig(
+ base="local-llama", backend="mlx", data={"train": "train.jsonl"},
+ training={"lora": {"use_dora": True, **option}},
+ )
diff --git a/tests/test_mlx_dora_native.py b/tests/test_mlx_dora_native.py
new file mode 100644
index 00000000..4e566b2a
--- /dev/null
+++ b/tests/test_mlx_dora_native.py
@@ -0,0 +1,249 @@
+"""Native DoRA lifecycle on a tiny, local random Llama; no model downloads."""
+
+import json
+import math
+
+import pytest
+
+pytest.importorskip("mlx.core")
+pytest.importorskip("mlx_lm")
+
+import mlx.core as mx # noqa: E402
+import mlx.nn as nn # noqa: E402
+from mlx.utils import tree_flatten, tree_unflatten # noqa: E402
+from mlx_lm import load # noqa: E402
+from mlx_lm.models.llama import Model, ModelArgs # noqa: E402
+from mlx_lm.tuner.dora import DoRALinear # noqa: E402
+from tokenizers import Tokenizer, models, pre_tokenizers # noqa: E402
+from transformers import PreTrainedTokenizerFast # noqa: E402
+
+from soup_cli.config.schema import SoupConfig # noqa: E402
+from soup_cli.trainer.mlx_sft import MLXSFTTrainerWrapper # noqa: E402
+
+
+def _checkpoint(path, quantized=False):
+ path.mkdir()
+ mx.random.seed(7)
+ config = dict(
+ model_type="llama", hidden_size=64, num_hidden_layers=1, intermediate_size=128,
+ num_attention_heads=4, num_key_value_heads=4, rms_norm_eps=1e-5,
+ vocab_size=32, tie_word_embeddings=False,
+ )
+ model = Model(ModelArgs(**config))
+ if quantized:
+ nn.quantize(model, group_size=32, bits=4)
+ config["quantization"] = {"group_size": 32, "bits": 4}
+ mx.save_safetensors(str(path / "model.safetensors"), dict(tree_flatten(model.parameters())))
+ (path / "config.json").write_text(json.dumps(config))
+ vocab = {word: i for i, word in enumerate(
+ ["<unk>", "<eos>", "<pad>", "user", "assistant", "alpha", "beta", "gamma"]
+ )}
+ tokenizer = Tokenizer(models.WordLevel(vocab, unk_token="<unk>"))
+ tokenizer.pre_tokenizer = pre_tokenizers.WhitespaceSplit()
+ tokenizer = PreTrainedTokenizerFast(
+ tokenizer_object=tokenizer, unk_token="<unk>", eos_token="<eos>", pad_token="<pad>"
+ )
+ tokenizer.chat_template = (
+ "{% for message in messages %}{{ message['role'] }} {{ message['content'] }} "
+ "<eos> {% endfor %}{% if add_generation_prompt %}assistant {% endif %}"
+ )
+ tokenizer.save_pretrained(path)
+ return path
+
+
+def _config(base, output, *, dora=True, quantized=False, targets="auto"):
+ return SoupConfig(
+ base=str(base), backend="mlx", output=str(output),
+ data={"train": "unused.jsonl", "train_on_responses_only": False, "max_length": 64},
+ training={
+ "quantization": "4bit" if quantized else "none", "epochs": 1,
+ "batch_size": 1, "gradient_accumulation_steps": 1, "lr": 0.005,
+ "logging_steps": 1, "save_steps": 2, "scheduler": "constant",
+ "warmup_ratio": 0, "weight_decay": 0,
+ "lora": {"r": 4, "alpha": 8, "dropout": 0, "use_dora": dora,
+ "target_modules": targets},
+ },
+ )
+
+
+def _rows():
+ return {"train": [{"text": "alpha beta gamma alpha beta gamma"}] * 4}
+
+
[email protected]("quantized, checkpoint, accumulation", [
+ (False, False, 1), (True, False, 1), (False, True, 2), (True, True, 2),
+])
+def test_native_training_reload_warm_start_and_fusion(
+ tmp_path, quantized, checkpoint, accumulation, monkeypatch
+):
+ base = _checkpoint(tmp_path / "base", quantized)
+ cfg = _config(base, tmp_path / "adapters", quantized=quantized)
+ cfg.training.gradient_checkpointing = checkpoint
+ cfg.training.gradient_accumulation_steps = accumulation
+ wrapper = MLXSFTTrainerWrapper(cfg)
+ wrapper.setup(_rows())
+ original = dict(tree_flatten(wrapper.model.parameters()))
+ initial = {}
+ apply = wrapper._apply_lora
+
+ def capture_initial(model):
+ apply(model)
+ initial.update(tree_flatten(model.trainable_parameters()))
+ mx.eval(initial)
+
+ monkeypatch.setattr(wrapper, "_apply_lora", capture_initial)
+ result = wrapper.train()
+ assert result["total_steps"] == 4
+ assert math.isfinite(result["final_loss"])
+ assert isinstance(wrapper.model.layers[0].self_attn.q_proj, DoRALinear)
+ trainable = dict(tree_flatten(wrapper.model.trainable_parameters()))
+ assert len(trainable) == 6
+ assert {name.rsplit(".", 1)[-1] for name in trainable} == {"lora_a", "lora_b", "m"}
+ assert all(not mx.array_equal(value, initial[name]).item()
+ for name, value in trainable.items())
+ from mlx_lm.tuner.trainer import default_loss
+
+ (_, _), gradients = nn.value_and_grad(wrapper.model, default_loss)(
+ wrapper.model, mx.array([[5, 6, 7, 5]]), mx.array([[0, 4]])
+ )
+ assert all(mx.isfinite(value).all().item() for _, value in tree_flatten(gradients))
+ # Every frozen base tensor, including quantization scales/biases, is unchanged.
+ trained = dict(tree_flatten(wrapper.model.parameters()))
+ for name, value in original.items():
+ parent, leaf = name.rsplit(".", 1)
+ adapted_name = f"{parent}.linear.{leaf}"
+ actual = trained[adapted_name] if adapted_name in trained else trained[name]
+ assert mx.array_equal(actual, value).item(), name
+ for projection in ("q_proj", "v_proj"):
+ layer = getattr(wrapper.model.layers[0].self_attn, projection)
+ assert not mx.array_equal(layer.lora_b, mx.zeros_like(layer.lora_b)).item()
+ assert not mx.array_equal(
+ layer.m, mx.linalg.norm(layer._dequantized_weight().astype(mx.float32), axis=1)
+ ).item()
+
+ tokens = mx.array([[5, 6, 7, 5]])
+ wrapper.model.eval()
+ expected = wrapper.model(tokens)
+ metadata = json.loads((tmp_path / "adapters" / "adapter_config.json").read_text())
+ assert metadata["fine_tune_type"] == "dora"
+ assert metadata["lora_parameters"]["scale"] == 2
+ restored, _ = load(str(base), adapter_path=str(tmp_path / "adapters"))
+ restored.eval()
+ assert isinstance(restored.layers[0].self_attn.q_proj, DoRALinear)
+ assert mx.allclose(restored(tokens), expected, atol=1e-5, rtol=1e-5).item()
+
+ resumed = MLXSFTTrainerWrapper(cfg)
+ resumed.setup(_rows())
+ resumed._apply_lora(resumed.model)
+ resumed._load_checkpoint_weights(str(tmp_path / "adapters" / "adapters.safetensors"))
+ resumed.model.eval()
+ assert mx.allclose(resumed.model(tokens), expected, atol=1e-5, rtol=1e-5).item()
+
+ # This is the operation used by mlx_lm.fuse --dequantize. Avoid requantization
+ # error when asserting that the adapter's mathematical effect is preserved.
+ restored.update_modules(tree_unflatten([
+ (name, module.fuse(dequantize=True))
+ for name, module in restored.named_modules() if isinstance(module, DoRALinear)
+ ]))
+ assert mx.allclose(restored(tokens), expected, atol=2e-5, rtol=2e-5).item()
+
+
[email protected]("quantized", [False, True])
+def test_public_cli_trains_a_reloadable_dora_adapter(tmp_path, quantized, monkeypatch):
+ from typer.testing import CliRunner
+
+ from soup_cli.cli import app
+
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")
+ base = _checkpoint(tmp_path / "base", quantized)
+ cfg = _config(base, tmp_path / "out", quantized=quantized)
+ data = tmp_path / "data.jsonl"
+ data.write_text("\n".join(json.dumps({"messages": [
+ {"role": "user", "content": "alpha beta"},
+ {"role": "assistant", "content": "gamma alpha beta"},
+ ]}) for _ in range(4)) + "\n")
+ cfg.data.train = str(data)
+ cfg.data.format = "chatml"
+ cfg.data.val_split = 0
+ config = tmp_path / "soup.json"
+ # The loader uses YAML, whose JSON subset keeps the serialized schema exact.
+ config.write_text(cfg.model_dump_json())
+ outcome = CliRunner().invoke(app, ["train", "--config", str(config), "--yes"])
+ assert outcome.exit_code == 0, (outcome.output, repr(outcome.exception))
+ restored, _ = load(str(base), adapter_path=str(tmp_path / "out"))
+ assert isinstance(restored.layers[0].self_attn.q_proj, DoRALinear)
+ assert mx.isfinite(restored(mx.array([[5, 6, 7]]))).all().item()
+ resumed = CliRunner().invoke(
+ app, ["train", "--config", str(config), "--yes", "--resume", "auto"]
+ )
+ assert resumed.exit_code == 0, (resumed.output, repr(resumed.exception))
+ assert "loading checkpoint weights" in resumed.output
+ reloaded, _ = load(str(base), adapter_path=str(tmp_path / "out"))
+ assert isinstance(reloaded.layers[0].self_attn.q_proj, DoRALinear)
+ assert mx.isfinite(reloaded(mx.array([[5, 6, 7]]))).all().item()
+
+
[email protected]("change", ["lora", "rank", "targets", "missing", "extra"])
+def test_dora_refuses_incompatible_warm_start_before_loading(tmp_path, change):
+ base = _checkpoint(tmp_path / "base")
+ cfg = _config(base, tmp_path / "out")
+ target = MLXSFTTrainerWrapper(cfg)
+ target.setup(_rows())
+ target._apply_lora(target.model)
+ before = dict(tree_flatten(target.model.trainable_parameters()))
+ source_cfg = _config(base, tmp_path / "other", dora=change != "lora")
+ if change == "rank":
+ source_cfg.training.lora.r = 2
+ if change == "targets":
+ source_cfg.training.lora.target_modules = ["self_attn.k_proj"]
+ source = MLXSFTTrainerWrapper(source_cfg)
+ source.setup(_rows())
+ source._apply_lora(source.model)
+ weights = dict(tree_flatten(source.model.trainable_parameters()))
+ if change == "missing":
+ weights.pop(next(iter(weights)))
+ if change == "extra":
+ weights["unexpected.m"] = mx.ones((1,))
+ checkpoint = tmp_path / "incompatible.safetensors"
+ mx.save_safetensors(str(checkpoint), weights)
+ with pytest.raises(ValueError, match="[Dd][Oo][Rr][Aa].*incompatible"):
+ target._load_checkpoint_weights(str(checkpoint))
+ after = dict(tree_flatten(target.model.trainable_parameters()))
+ assert all(mx.array_equal(value, after[name]).item() for name, value in before.items())
+
+
[email protected]("invalid", ["missing", "switch", "embedding", "8bit"])
+def test_unsupported_targets_fail_before_any_conversion(tmp_path, invalid):
+ from mlx_lm.models.switch_layers import SwitchLinear
+
+ base = _checkpoint(tmp_path / "base")
+ targets = ["self_attn.q_proj", "self_attn.v_proj"]
+ if invalid == "missing":
+ targets.append("self_attn.typo")
+ wrapper = MLXSFTTrainerWrapper(_config(base, tmp_path / "out", targets=targets))
+ wrapper.setup(_rows())
+ attention = wrapper.model.layers[0].self_attn
+ if invalid == "switch":
+ attention.v_proj = SwitchLinear(64, 64, 2)
+ elif invalid == "embedding":
+ attention.v_proj = nn.Embedding(32, 64)
+ elif invalid == "8bit":
+ attention.v_proj = nn.QuantizedLinear.from_linear(attention.v_proj, group_size=32, bits=8)
+ before = dict(tree_flatten(wrapper.model.trainable_parameters()))
+ with pytest.raises(ValueError, match="MLX DoRA requires dense linear targets"):
+ wrapper._apply_lora(wrapper.model)
+ assert isinstance(attention.q_proj, nn.Linear)
+ assert set(dict(tree_flatten(wrapper.model.trainable_parameters()))) == set(before)
+
+
+def test_plain_lora_still_constructs_lora_layers(tmp_path):
+ from mlx_lm.tuner.lora import LoRALinear
+
+ base = _checkpoint(tmp_path / "base")
+ wrapper = MLXSFTTrainerWrapper(_config(base, tmp_path / "out", dora=False))
+ wrapper.setup(_rows())
+ wrapper._apply_lora(wrapper.model)
+ assert isinstance(wrapper.model.layers[0].self_attn.q_proj, LoRALinear)
+ assert not any(name.endswith(".m")
+ for name, _ in tree_flatten(wrapper.model.trainable_parameters()))