Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

MLX: train decision models on Apple Silicon (#13016)

Long Yixing94a00e95a75d
diff --git a/scripts/risky_loaders_baseline.json b/scripts/risky_loaders_baseline.json
index f9dd93907ed..82cc9b9fc9a 100644
--- a/scripts/risky_loaders_baseline.json
+++ b/scripts/risky_loaders_baseline.json
@@ -442,6 +442,14 @@
"count": 1,
"reason": "Loads unsloth's own _mlx_raw_text.py from the installed package directory; the path is derived from __file__."
},
+ {
+ "file": "unsloth/__init__.py",
+ "rule": "dynamic-import",
+ "sink": "spec_from_file_location",
+ "digest": "5f461f0c8175f45a",
+ "count": 1,
+ "reason": "Loads unsloth/models/decision_mlx.py from a fixed path inside this package on Apple Silicon, where importing unsloth.models would import torch; never a downloaded or user-supplied file."
+ },
{
"file": "unsloth/_gpu_init.py",
"rule": "dynamic-import",
@@ -514,6 +522,14 @@
"count": 1,
"reason": "Imports the fixed literal peft.utils.transformers_weight_conversion held in a local."
},
+ {
+ "file": "unsloth/models/_decision_common.py",
+ "rule": "dynamic-import",
+ "sink": "spec_from_file_location",
+ "digest": "3738585f7559a2ad",
+ "count": 1,
+ "reason": "Imports the laya copy vendored in this repository at a fixed path (studio/backend/vendor/laya/__init__.py); never a downloaded or user-supplied file."
+ },
{
"file": "unsloth/models/_utils.py",
"rule": "dynamic-import",
@@ -555,20 +571,28 @@
"reason": "Reads back a .pt file this function just wrote with torch.save into the local offload folder; never a downloaded file."
},
{
- "file": "unsloth/models/decision.py",
+ "file": "unsloth/models/decision_gguf.py",
"rule": "dynamic-import",
"sink": "spec_from_file_location",
- "digest": "3738585f7559a2ad",
+ "digest": "6894b59960c95a35",
"count": 1,
- "reason": "Imports the laya copy vendored in this repository at a fixed path (studio/backend/vendor/laya/__init__.py); never a downloaded or user-supplied file."
+ "reason": "Loads Studio's standard-library gguf_export_contract.py from a constant path beside the unsloth package; nothing caller-supplied picks the file."
},
{
- "file": "unsloth/models/decision_gguf.py",
+ "file": "unsloth/models/decision_mlx.py",
"rule": "dynamic-import",
"sink": "spec_from_file_location",
- "digest": "6894b59960c95a35",
+ "digest": "d4eff4fdda8d4ae4",
"count": 1,
- "reason": "Loads Studio's standard-library gguf_export_contract.py from a constant path beside the unsloth package; nothing caller-supplied picks the file."
+ "reason": "Loads the sibling _decision_common.py by a fixed name beside this file, so the MLX path shares the torch-free helpers without importing unsloth.models; nothing caller-supplied picks the file."
+ },
+ {
+ "file": "unsloth/models/decision_mlx.py",
+ "rule": "dynamic-import",
+ "sink": "spec_from_file_location",
+ "digest": "e1987e041e60a061",
+ "count": 1,
+ "reason": "Loads the sibling decision_gguf.py by a fixed name beside this file for GGUF export on MLX, without importing unsloth.models; nothing caller-supplied picks the file."
},
{
"file": "unsloth/models/loader.py",
diff --git a/studio/backend/core/training/decision_trainer.py b/studio/backend/core/training/decision_trainer.py
index f192d107f58..0ed6e88d02b 100644
--- a/studio/backend/core/training/decision_trainer.py
+++ b/studio/backend/core/training/decision_trainer.py
@@ -207,6 +207,63 @@ def _load_rows(
return rows, eval_rows
+def _is_mlx() -> bool:
+ from utils.hardware import hardware
+ return hardware.DEVICE == hardware.DeviceType.MLX
+
+
+def _peak_memory_gb() -> float | None:
+ import torch
+
+ if torch.cuda.is_available():
+ return torch.cuda.max_memory_allocated() / 1e9
+ if _is_mlx():
+ import mlx.core as mx
+ return mx.get_peak_memory() / 1e9
+ return None
+
+
+def _mlx_tracking_callback(report_to: list):
+ from transformers import TrainerCallback
+
+ # transformers' reporting callbacks are added by its own Trainer, which MLX does not run.
+ class Tracking(TrainerCallback):
+ writer = None
+
+ def on_train_begin(self, args, state, control, **kwargs):
+ if "tensorboard" in report_to:
+ try:
+ from tensorboardX import SummaryWriter
+ except ImportError:
+ from torch.utils.tensorboard import SummaryWriter
+ self.writer = SummaryWriter(log_dir = os.environ["TENSORBOARD_LOGGING_DIR"])
+
+ def on_log(
+ self,
+ args,
+ state,
+ control,
+ logs = None,
+ **kwargs,
+ ):
+ scalars = {
+ f"eval/{name[5:]}" if name.startswith("eval_") else f"train/{name}": value
+ for name, value in (logs or {}).items()
+ if isinstance(value, (int, float))
+ }
+ for name, value in scalars.items() if self.writer else ():
+ self.writer.add_scalar(name, value, state.global_step)
+ if "wandb" in report_to:
+ import wandb
+ wandb.log(scalars, step = state.global_step)
+
+ def on_train_end(self, args, state, control, **kwargs):
+ if self.writer:
+ self.writer.close()
+
+ return Tracking()
+
+
def run_decision_training(event_queue: Any, stop_queue: Any, config: dict) -> None:
import torch
@@ -458,7 +515,8 @@ def _run(event_queue: Any, stop_queue: Any, config: dict, output_dir: str) -> No
report_to.append("wandb")
except Exception as exc:
warn(f"Weights & Biases logging is off: {exc}")
- arguments["report_to"] = report_to or "none"
+ # On MLX the run's own tracking callback reports instead, into the directory and W&B run opened above.
+ arguments["report_to"] = "none" if _is_mlx() or not report_to else report_to
base_metrics = None
if eval_items:
@@ -487,7 +545,8 @@ def _run(event_queue: Any, stop_queue: Any, config: dict, output_dir: str) -> No
training_start_time = time.time(),
should_stop = lambda: stop["requested"],
)
- ],
+ ]
+ + ([_mlx_tracking_callback(report_to)] if report_to and _is_mlx() else []),
)
_drop_hf_stdout_callbacks(trainer)
start = time.time()
@@ -507,7 +566,7 @@ def _run(event_queue: Any, stop_queue: Any, config: dict, output_dir: str) -> No
raise _Stopped("Training cancelled")
status("Saving model...")
- peak_gb = torch.cuda.max_memory_allocated() / 1e9 if torch.cuda.is_available() else None
+ peak_gb = _peak_memory_gb()
model.decision_config["training"] = {
"base": model_name,
"subfolder": subfolder,
diff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.py
index 317012ff9f3..8131d037d45 100644
--- a/studio/backend/core/training/worker.py
+++ b/studio/backend/core/training/worker.py
@@ -2631,10 +2631,6 @@ def _run_mlx_training(event_queue, stop_queue, config):
message = "Embedding model training is not supported for MLX training yet."
_send("error", error = message)
raise NotImplementedError(message)
- if config.get("is_decision"):
- message = "Decision model training is not supported for MLX training yet."
- _send("error", error = message)
- raise NotImplementedError(message)
if config.get("training_type") == "Continued Pretraining":
message = "Continued Pretraining is not supported for MLX training yet."
_send("error", error = message)
@@ -3431,7 +3427,19 @@ def run_mlx_training_process(
try:
try:
- _run_mlx_training(event_queue, stop_queue, config)
+ if config.get("is_decision"):
+ # Its own pipeline, as on the torch path, behind the same security gate.
+ security_error = _model_load_security_error(
+ config, model_load_target, _worker_hf_token(config)
+ )
+ if security_error:
+ event_queue.put({"type": "error", **security_error, "ts": time.time()})
+ else:
+ _download_decision_checkpoint(event_queue, config)
+ from core.training.decision_trainer import run_decision_training
+ run_decision_training(event_queue, stop_queue, config)
+ else:
+ _run_mlx_training(event_queue, stop_queue, config)
finally:
try:
stop_queue.put({"type": _MLX_WORKER_COMPLETE})
diff --git a/studio/backend/routes/training.py b/studio/backend/routes/training.py
index 4dca2b1cf35..323a853f31c 100644
--- a/studio/backend/routes/training.py
+++ b/studio/backend/routes/training.py
@@ -1202,11 +1202,6 @@ def _validate_training_platform(request: TrainingStartRequest) -> None:
status_code = 400,
detail = "Embedding model training is not supported for MLX training yet.",
)
- if request.is_decision:
- raise HTTPException(
- status_code = 400,
- detail = "Decision model training is not supported for MLX training yet.",
- )
if request.is_dataset_audio:
raise HTTPException(
status_code = 400,
@@ -1281,13 +1276,9 @@ def _validate_decision_request(request: TrainingStartRequest, via_api_key: bool
from core.systemone.catalog import clef_unsupported_reason
from utils.hardware import hardware
- # Runs before _validate_training_platform: name the MLX limit, not a missing GPU.
- if hardware.get_device() == hardware.DeviceType.MLX:
- raise HTTPException(
- status_code = 400,
- detail = "Decision model training is not supported for MLX training yet.",
- )
- if (reason := clef_unsupported_reason()) is not None:
+ # Apple Silicon trains Clef with MLX; elsewhere it needs the GPU the torch path runs on.
+ mlx = hardware.get_device() == hardware.DeviceType.MLX
+ if not mlx and (reason := clef_unsupported_reason()) is not None:
raise HTTPException(status_code = 400, detail = reason)
request.decision_layout = "llm" if llm else "clef"
if request.model_subfolder is not None:
diff --git a/studio/backend/tests/test_decision_training.py b/studio/backend/tests/test_decision_training.py
index 40adad31fc2..f94afd6c0a9 100644
--- a/studio/backend/tests/test_decision_training.py
+++ b/studio/backend/tests/test_decision_training.py
@@ -158,9 +158,11 @@ def _config(base, dataset, **overrides):
# The worker imports unsloth; CI installs unsloth_zoo only for the step that runs this file.
+# Apple Silicon trains with MLX, through unsloth_zoo's decision module.
+_WORKER = "unsloth_zoo.mlx.decision" if sys.platform == "darwin" else "unsloth_zoo"
needs_worker = pytest.mark.skipif(
- sys.platform == "darwin" or importlib.util.find_spec("unsloth_zoo") is None,
- reason = "trains in a worker that imports unsloth (Apple Silicon trains with MLX)",
+ importlib.util.find_spec("unsloth_zoo") is None or importlib.util.find_spec(_WORKER) is None,
+ reason = "trains in a worker that imports unsloth",
)
@@ -475,6 +477,26 @@ def _fake_output(
return folder
+def test_mlx_runs_report_to_tensorboard_and_wandb(monkeypatch, tmp_path):
+ from types import SimpleNamespace
+
+ from core.training.decision_trainer import _mlx_tracking_callback
+
+ # Built first: importing transformers looks for the real reporting packages.
+ callback, state, seen = _mlx_tracking_callback(["tensorboard", "wandb"]), SimpleNamespace(), []
+ state.global_step = 7
+ writer = SimpleNamespace(add_scalar = lambda *row: seen.append(row), close = lambda: None)
+ boards = SimpleNamespace(SummaryWriter = lambda log_dir: seen.append(log_dir) or writer)
+ monkeypatch.setitem(sys.modules, "tensorboardX", boards)
+ wandb = SimpleNamespace(log = lambda scalars, step: seen.append((scalars, step)))
+ monkeypatch.setitem(sys.modules, "wandb", wandb)
+ monkeypatch.setenv("TENSORBOARD_LOGGING_DIR", str(tmp_path))
+ callback.on_train_begin(None, state, None)
+ callback.on_log(None, state, None, logs = {"loss": 0.5, "eval_loss": 0.25, "note": "skipped"})
+ scalars = {"train/loss": 0.5, "eval/loss": 0.25}
+ assert seen == [str(tmp_path), ("train/loss", 0.5, 7), ("eval/loss", 0.25, 7), (scalars, 7)]
+
+
def test_settings_accept_only_complete_owner_fine_tunes(studio_home, client, tmp_path):
from utils.paths import outputs_root
diff --git a/studio/backend/tests/test_decision_training_route.py b/studio/backend/tests/test_decision_training_route.py
index e776a876d7e..b7bd8d323fe 100644
--- a/studio/backend/tests/test_decision_training_route.py
+++ b/studio/backend/tests/test_decision_training_route.py
@@ -549,6 +549,7 @@ def device(monkeypatch):
"cuda": hardware.DeviceType.CUDA,
"cpu": hardware.DeviceType.CPU,
"xpu": hardware.DeviceType.XPU,
+ "mlx": hardware.DeviceType.MLX,
}[kind]
monkeypatch.setattr(hardware, "get_device", lambda: value)
monkeypatch.setattr(hardware, "DEVICE", value)
@@ -643,3 +644,9 @@ def test_clef_training_is_refused_without_an_nvidia_or_amd_gpu(route, device, tm
laya = _request(model_name = str(_laya_folder(tmp_path / "laya")))
route._validate_decision_request(laya)
assert laya.decision_layout == "laya"
+ # Apple Silicon trains a Clef, and a language model given a decision head, with MLX.
+ device("mlx")
+ for folder in (tmp_path / "c", _llm_folder(tmp_path / "l")):
+ request = _request(model_name = str(folder))
+ route._validate_decision_request(request)
+ assert request.decision_layout == {"c": "clef", "l": "llm"}[folder.name]
diff --git a/studio/backend/tests/test_training_cached_start.py b/studio/backend/tests/test_training_cached_start.py
index 18c4c413617..a412bbd0a7c 100644
--- a/studio/backend/tests/test_training_cached_start.py
+++ b/studio/backend/tests/test_training_cached_start.py
@@ -1326,7 +1326,6 @@ def test_streaming_rejects_cached_dataset_hints(cache_overrides):
({"is_embedding": True}, "Embedding model training"),
({"is_dataset_audio": True}, "Audio dataset training"),
({"use_loftq": True}, "LoftQ"),
- ({"is_decision": True, "training_type": "Full Finetuning"}, "Decision model training"),
],
)
def test_mlx_start_rejects_unsupported_training_config(request_overrides, expected):
@@ -1355,6 +1354,7 @@ def test_mlx_start_accepts_dora():
with patch.object(hardware, "DEVICE", hardware.DeviceType.MLX):
route._validate_training_platform(_request(use_dora = True))
+ route._validate_training_platform(_request(is_decision = True))
with pytest.raises(HTTPException) as exc_info:
route._validate_training_platform(_request(use_loftq = True))
diff --git a/studio/backend/tests/test_training_preflight.py b/studio/backend/tests/test_training_preflight.py
index 7dfd9115fea..31704759843 100644
--- a/studio/backend/tests/test_training_preflight.py
+++ b/studio/backend/tests/test_training_preflight.py
@@ -1863,6 +1863,26 @@ def test_run_mlx_training_process_applies_side_effects_before_hardware_detection
assert "MLX training requires Apple Silicon" in event["error"]
+def test_run_mlx_training_process_gates_a_decision_model_before_its_download(monkeypatch):
+ _load_trainer_module(monkeypatch, "mlx")
+ from core.training import worker
+ from utils.hardware import hardware as hw
+
+ monkeypatch.setattr(worker, "_validate_training_worker_config", lambda *args: True)
+ monkeypatch.setattr(worker, "_activate_transformers_version_or_warn", lambda *args: None)
+ monkeypatch.setattr(hw, "detect_hardware", lambda: None)
+ monkeypatch.setattr(hw, "DEVICE", hw.DeviceType.MLX)
+ blocked = lambda config, target, token: {"error": f"blocked {target}"}
+ monkeypatch.setattr(worker, "_model_load_security_error", blocked)
+ monkeypatch.setattr(
+ worker, "_download_decision_checkpoint", lambda *args: pytest.fail("downloaded")
+ )
+ events = queue.Queue()
+ config = {"model_name": "org/clef", "is_decision": True}
+ worker.run_mlx_training_process(event_queue = events, stop_queue = queue.Queue(), config = config)
+ assert events.get_nowait()["error"] == "blocked org/clef"
+
+
def test_run_mlx_training_process_rejects_untrainable_format_before_side_effects(monkeypatch):
_load_trainer_module(monkeypatch, "mlx")
from core.training import worker
diff --git a/studio/frontend/src/features/training/lib/training-methods.ts b/studio/frontend/src/features/training/lib/training-methods.ts
index ea259dae7b1..6272246daaa 100644
--- a/studio/frontend/src/features/training/lib/training-methods.ts
+++ b/studio/frontend/src/features/training/lib/training-methods.ts
@@ -50,9 +50,7 @@ export function isTrainingModelTypeSupportedOnDevice(
): boolean {
return (
deviceType !== "mac" ||
- (modelType !== "audio" &&
- modelType !== "embeddings" &&
- modelType !== "decision")
+ (modelType !== "audio" && modelType !== "embeddings")
);
}
diff --git a/studio/frontend/tests/training-decision-model.test.ts b/studio/frontend/tests/training-decision-model.test.ts
index 07ab5f9c921..1d456f09807 100644
--- a/studio/frontend/tests/training-decision-model.test.ts
+++ b/studio/frontend/tests/training-decision-model.test.ts
@@ -495,7 +495,7 @@ test("an LLM run keeps its method and sends no decision fields", () => {
assert.equal(payload.max_seq_length, 32768);
});
-test("decision training is refused on Apple Silicon only", () => {
+test("decision training starts on Apple Silicon and on CUDA", () => {
const config = {
...useTrainingConfigStore.getState(),
...HF_DECISION_DATASET,
@@ -505,8 +505,8 @@ test("decision training is refused on Apple Silicon only", () => {
};
assert.deepEqual(validateTrainingConfig(config, "mac"), {
- ok: false,
- errorKey: "studio.params.notSupportedAppleSilicon",
+ ok: true,
+ errorKey: null,
});
assert.deepEqual(validateTrainingConfig(config, "cuda"), {
ok: true,
@@ -523,7 +523,7 @@ test("the model picker knows Laya is a decision model before its config loads",
const modelType = inferTrainingModelTypeFromFlags(flags);
assert.equal(modelType, "decision");
- assert.equal(isTrainingModelTypeSupportedOnDevice(modelType, "mac"), false);
+ assert.equal(isTrainingModelTypeSupportedOnDevice(modelType, "mac"), true);
assert.equal(isTrainingModelTypeSupportedOnDevice(modelType, "cuda"), true);
});
diff --git a/tests/test_decision_mlx_guards.py b/tests/test_decision_mlx_guards.py
new file mode 100644
index 00000000000..9b698defcb2
--- /dev/null
+++ b/tests/test_decision_mlx_guards.py
@@ -0,0 +1,46 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.
+
+import importlib.util
+import sys
+from pathlib import Path
+
+import pytest
+
+_MODELS = Path(__file__).resolve().parents[1] / "unsloth" / "models"
+
+
+def decision_mlx(monkeypatch):
+ # By path, as unsloth/__init__.py loads it on Apple Silicon; needs neither mlx nor torch to import.
+ for name in ("unsloth._decision_common", "_decision_mlx_under_test"):
+ monkeypatch.delitem(sys.modules, name, raising = False)
+ spec = importlib.util.spec_from_file_location(
+ "_decision_mlx_under_test", _MODELS / "decision_mlx.py"
+ )
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+def test_an_install_without_torch_is_told_to_install_it(decision_mlx, monkeypatch):
+ find_spec = importlib.util.find_spec
+ monkeypatch.setattr(
+ importlib.util,
+ "find_spec",
+ lambda name, *args: None if name == "torch" else find_spec(name, *args),
+ )
+ decision_mlx._decision_zoo.cache_clear()
+ with pytest.raises(ImportError, match = "decision models on MLX need PyTorch"):
+ decision_mlx._decision_zoo()
+
+
+def test_adapters_refuse_a_full_finetune_before_loading(decision_mlx, monkeypatch, tmp_path):
+ (tmp_path / "adapter_config.json").write_text("{}", encoding = "utf-8")
+
+ def never():
+ raise AssertionError("loaded before refusing")
+
+ monkeypatch.setattr(decision_mlx, "_decision_zoo", never)
+ with pytest.raises(ValueError, match = "save_pretrained_merged"):
+ decision_mlx._load_clef(tmp_path, None, False, True, None, False, {})
diff --git a/tests/test_decision_model.py b/tests/test_decision_model.py
index 9dc3762f5a7..76da6f2f21f 100644
--- a/tests/test_decision_model.py
+++ b/tests/test_decision_model.py
@@ -13,10 +13,16 @@ from real_accelerator import has_real_cuda
torch = pytest.importorskip("torch")
+import unsloth
+
+# The torch backend: on Apple Silicon unsloth serves decision models from decision_mlx instead.
+if unsloth._IS_MLX:
+ pytest.skip("the torch backend", allow_module_level = True)
+
from transformers import TrainerCallback, TrainingArguments
from unsloth import DecisionTrainer, FastDecisionModel
-from unsloth.models import decision
+from unsloth.models import _decision_common, decision
from unsloth.models.decision import (
DecisionDataCollator,
DecisionDataError,
@@ -171,7 +177,7 @@ def test_laya_is_the_copy_vendored_with_unsloth(monkeypatch, fresh_laya):
def test_missing_vendored_laya_is_a_clear_error(monkeypatch, tmp_path, fresh_laya):
- monkeypatch.setattr(decision, "_VENDORED_LAYA", tmp_path / "laya" / "__init__.py")
+ monkeypatch.setattr(_decision_common, "_VENDORED_LAYA", tmp_path / "laya" / "__init__.py")
with pytest.raises(ImportError, match = "Unsloth: decision models need laya"):
decision._laya()
diff --git a/tests/test_decision_model_mlx.py b/tests/test_decision_model_mlx.py
new file mode 100644
index 00000000000..c709f846962
--- /dev/null
+++ b/tests/test_decision_model_mlx.py
@@ -0,0 +1,435 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.
+
+import ast
+import json
+import os
+import platform
+import sys
+from pathlib import Path
+
+import pytest
+
+# Before any unsloth_zoo import: without torch off Apple Silicon it raises a plain ImportError.
+if sys.platform != "darwin" or platform.machine() != "arm64":
+ pytest.skip("the MLX backend", allow_module_level = True)
+pytest.importorskip("unsloth_zoo.mlx.decision")
+torch = pytest.importorskip("torch")
+
+import mlx.core as mx
+import mlx.nn as nn
+from mlx.utils import tree_flatten, tree_unflatten
+from transformers import TrainingArguments
+
+import unsloth
+from unsloth import DecisionTrainer, FastDecisionModel
+
+pytestmark = pytest.mark.skipif(not unsloth._IS_MLX, reason = "the MLX backend")
+
+WORDS = (
+ "the server is down again refund my card charge twice please help now noul choice score "
+ "question : ? , does this need a reply which team should handle it how upset customer outage "
+ "service billing charges and refunds level 0 1 2 calm annoyed angry false no statement not hold "
+ "true yes holds"
+).split()
+TEAMS = {"outage": "service down", "billing": "charges and refunds"}
+MOODS = ["calm", "annoyed", "angry"]
+QUESTIONS = {
+ "urgent": {"type": "noul", "instructions": "Does this need a reply now?"},
+ "team": {"type": "choice", "instructions": "Which team should handle it?", "criteria": TEAMS},
+ "mood": {"type": "score", "instructions": "How upset is the customer?", "criteria": MOODS},
+}
+ENCODER = {"vocab_size": 64, "hidden_size": 64, "intermediate_size": 96, "num_hidden_layers": 2}
+ENCODER.update(num_attention_heads = 4, pad_token_id = 0, cls_token_id = 2, sep_token_id = 1)
+ENCODER.update(global_attn_every_n_layers = 2, local_attention = 16)
+
+
+def _row(i):
+ state = "the server is down again help now" if i % 2 == 0 else "refund my card charge twice"
+ gold = {"urgent": "true", "team": "outage", "mood": 2}
+ gold = gold if i % 2 == 0 else {"urgent": "false", "team": "billing", "mood": 0}
+ return {"state": state, "questions": QUESTIONS, "gold": gold}
+
+
+ARGS = {"per_device_train_batch_size": 16, "max_steps": 80, "report_to": "none"}
+ARGS.update(save_strategy = "no", eval_strategy = "steps", eval_steps = 40)
+
+
+def checkpoint(tmp_path):
+ from safetensors.torch import save_file
+ from tokenizers import Tokenizer, models, normalizers, pre_tokenizers
+ from transformers import ModernBertConfig, PreTrainedTokenizerFast
+
+ base = tmp_path / "base"
+ specials = ["[PAD]", "[SEP]", "[CLS]", "[UNK]", "[MASK]"]
+ vocab = {token: i for i, token in enumerate(specials + sorted(set(WORDS)))}
+ tokenizer = Tokenizer(models.WordLevel(vocab, unk_token = "[UNK]"))
+ tokenizer.normalizer = normalizers.Lowercase()
+ tokenizer.pre_tokenizer = pre_tokenizers.Whitespace()
+ names = dict(zip(("pad_token", "sep_token", "cls_token", "unk_token", "mask_token"), specials))
+ tokenizer = PreTrainedTokenizerFast(tokenizer_object = tokenizer, **names)
+ tokenizer.save_pretrained(str(base / "tokenizer"))
+ (base / "encoder").mkdir()
+ encoder = json.dumps(ModernBertConfig(**ENCODER).to_dict())
+ (base / "encoder" / "config.json").write_text(encoder)
+ config = {"encoder": "tiny", "head_layers": 1, "act_costs": {"escalate": 0.5}, "max_len": 96}
+ config.update(head_max_len = 48, temperature = [1.2, 1.1, 1.3], training = {"updates": 1000})
+ torch.manual_seed(0)
+ model = unsloth._decision_mlx._laya().common.build_model(
+ config, encoder_dir = str(base / "encoder")
+ )
+ weights = {k: v.half().contiguous() for k, v in model.state_dict().items()}
+ save_file(weights, str(base / "model.safetensors"))
+ (base / "rl_agent_config.json").write_text(json.dumps(config))
+ return base
+
+
[email protected]("full", [False, True])
+def test_train_calibrate_save_and_serve(checkpoint, tmp_path, full):
+ model, tokenizer = FastDecisionModel.from_pretrained(str(checkpoint), full_finetuning = full)
+ model = FastDecisionModel.get_peft_model(model, r = 8, lora_alpha = 16)
+ rows = [_row(i) for i in range(120)]
+ items, report = FastDecisionModel.build_dataset(rows, tokenizer, model)
+ train, held = FastDecisionModel.split_holdout(items, 3407, fraction = 0.25)
+ assert report["skipped"] == 0 and len(train) + len(held) == 360
+ base = FastDecisionModel.evaluate(model, tokenizer, held)
+ args = TrainingArguments(
+ str(tmp_path / "run"), learning_rate = 1e-3 if full else 5e-3, warmup_steps = 8, **ARGS
+ )
+ trainer = DecisionTrainer(model, args, train, held, head_learning_rate = 5e-3)
+ trainer.train()
+ tuned = FastDecisionModel.evaluate(model, tokenizer, held)
+ assert tuned["accuracy"] >= base["accuracy"] + 0.25 and tuned["loss"] < base["loss"] / 2
+ assert [log["step"] for log in trainer.state.log_history if "eval_loss" in log] == [40, 80]
+ assert trainer.args is not args and args.eval_steps == 40
+ adapters = [v for k, v in tree_flatten(model.trainable_parameters()) if k.endswith("lora_b")]
+ assert full != bool(adapters) and all(abs(v).max().item() > 0 for v in adapters)
+ assert full == (
+ "encoder.layers.0.attn.Wo.weight" in dict(tree_flatten(model.trainable_parameters()))
+ )
+ manual = DecisionTrainer(model, TrainingArguments(str(tmp_path / "run")), train[:16], held)
+ assert manual.evaluate()["eval_loss"] > 0
+ assert manual.evaluate(held[:8])["eval_loss"] != manual.evaluate()["eval_loss"]
+ assert FastDecisionModel.calibrate(model, tokenizer, held)["fitted_types"] == [0, 1, 2]
+ calibrated = FastDecisionModel.evaluate(model, tokenizer, held)
+ assert model.decision_config["temperature"] != [1.2, 1.1, 1.3]
+ model.save_pretrained_merged(tmp_path / "out")
+ saved = json.loads((tmp_path / "out" / "rl_agent_config.json").read_text())
+ assert saved["fine_tuned"] is True and "training" not in saved
+ assert saved["temperature"] == model.decision_config["temperature"] and saved["max_len"] == 1024
+ unsloth._decision_mlx._laya().load(str(tmp_path / "out"), device = "cpu")
+ served, tokenizer = FastDecisionModel.from_pretrained(str(tmp_path / "out"))
+ loss = FastDecisionModel.evaluate(served, tokenizer, held)["loss"]
+ assert loss == pytest.approx(calibrated["loss"], abs = 2e-2)
+
+
+def test_unsupported_options_are_refused(checkpoint, tmp_path):
+ with pytest.raises(NotImplementedError, match = "load_in_4bit"):
+ FastDecisionModel.from_pretrained(str(checkpoint), load_in_4bit = True)
+ with pytest.raises(NotImplementedError, match = "bfloat16"):
+ FastDecisionModel.from_pretrained(str(checkpoint), dtype = torch.bfloat16)
+ model, _ = FastDecisionModel.from_pretrained(str(checkpoint), dtype = torch.float16)
+ for option in ({"use_dora": True}, {"bias": "all"}, {"loftq_config": {"loftq_bits": 4}}):
+ with pytest.raises(NotImplementedError, match = next(iter(option))):
+ FastDecisionModel.get_peft_model(model, **option)
+ with pytest.raises(NotImplementedError, match = "data_collator, optimizers"):
+ DecisionTrainer(model, data_collator = len, optimizers = (None, None), brier_weight = 0.5)
+ best = {"save_strategy": "best", "eval_strategy": "steps", "metric_for_best_model": "loss"}
+ for option in ({"auto_find_batch_size": True}, best):
+ with pytest.raises(NotImplementedError, match = next(iter(option))):
+ DecisionTrainer(model, TrainingArguments(str(tmp_path), **option))
+ ignored = {"data_seed": 1, "eval_on_start": True, "neftune_noise_alpha": 5.0}
+ with pytest.warns(UserWarning, match = "ignores data_seed, eval_on_start, neftune_noise_alpha"):
+ DecisionTrainer(model, TrainingArguments(str(tmp_path), **ignored))
+
+
+def test_the_torch_trainer_options_reach_the_mlx_trainer(checkpoint, tmp_path):
+ model, tokenizer = FastDecisionModel.from_pretrained(str(checkpoint))
+ items, _ = FastDecisionModel.build_dataset([_row(i) for i in range(4)], tokenizer, model)
+ schedule = {"eval_strategy": "steps", "eval_steps": 2, "save_steps": 2, "max_steps": 4}
+ schedule.update(logging_first_step = True, label_smoothing_factor = 0.3, report_to = "none")
+ args = TrainingArguments(str(tmp_path), **schedule)
+ count = lambda prediction: {"rows": len(prediction.label_ids)}
+ options = {"preprocess_logits_for_metrics": lambda logits, _: logits.argmax(dim = -1)}
+ trainer = DecisionTrainer(model, args, items, items, compute_metrics = count, **options)
+ assert trainer.objective == (0.3, 0.0, 0.0) and min(trainer.train_dataset[0]["target"]) == 0.0
+ trainer.train()
+ assert trainer.state.log_history[0]["step"] == 1 and (tmp_path / "checkpoint-2").is_dir()
+ resumed = DecisionTrainer(model, args, items, items)
+ resumed.train(resume_from_checkpoint = str(tmp_path / "checkpoint-2"))
+ logs = resumed.state.log_history, trainer.state.log_history
+ assert (
+ logs[0][:2] == logs[1][:2] and len(logs[0]) == len(logs[1]) and logs[0][2:] != logs[1][2:]
+ )
+ assert trainer.predict(items[:3]).predictions.shape == (3,)
+ assert trainer.evaluate()["eval_rows"] == 12
+
+
+def test_transformers_callbacks_read_the_training_arguments(checkpoint, tmp_path):
+ from transformers import EarlyStoppingCallback
+
+ model, tokenizer = FastDecisionModel.from_pretrained(str(checkpoint))
+ items, _ = FastDecisionModel.build_dataset([_row(0), _row(1)], tokenizer, model)
+ args = {**ARGS, "eval_steps": 1, "metric_for_best_model": "eval_loss"}
+ args = TrainingArguments(str(tmp_path), **args)
+ # An improvement of 10 never happens, so the second evaluation stops the run.
+ trainer = DecisionTrainer(model, args, items, items, callbacks = [EarlyStoppingCallback(1, 10.0)])
+ trainer.train()
+ assert trainer.state.global_step == 2 and trainer.args.eval_strategy == args.eval_strategy
+
+
+def test_decision_helpers_are_one_torch_free_module_for_both_backends():
+ import sys
+
+ common = sys.modules["unsloth._decision_common"]
+ assert unsloth._decision_mlx._metrics is common._metrics
+ root = Path(unsloth.__file__).parent / "models"
+ shared = ast.parse((root / "_decision_common.py").read_text(encoding = "utf-8")).body
+ # Loaded by path on MLX, where unsloth.models and its torch imports are never imported.
+ modules = [a.name for n in shared if isinstance(n, ast.Import) for a in n.names]
+ modules += [n.module for n in shared if isinstance(n, ast.ImportFrom)]
+ assert {name.split(".")[0] for name in modules}.isdisjoint({"torch", "transformers"})
+ torch_module = ast.parse((root / "decision.py").read_text(encoding = "utf-8")).body
+ for module in (
+ torch_module,
+ ast.parse((root / "decision_mlx.py").read_text(encoding = "utf-8")).body,
+ ):
+ assert {n.name for n in module if hasattr(n, "name")}.isdisjoint(common.__all__)
+ taken = [n for n in torch_module if getattr(n, "module", None) == "_decision_common"]
+ assert [a.name for n in taken for a in n.names] == ["*"]
+
+
+def clef_checkpoint(tmp_path, monkeypatch):
+ from types import SimpleNamespace
+
+ from mlx_lm.models import qwen3_5
+ from unsloth_zoo.mlx import decision as zoo
+
+ text = {"model_type": "qwen3_5_text", "hidden_size": 64, "intermediate_size": 128}
+ text.update(num_hidden_layers = 4, num_attention_heads = 2, num_key_value_heads = 1)
+ # The default recurrent state is the full model's, megabytes per token whatever the hidden size.
+ text.update(linear_num_value_heads = 4, linear_num_key_heads = 2)
+ text.update(linear_key_head_dim = 32, linear_value_head_dim = 16)
+ args = qwen3_5.ModelArgs(model_type = "qwen3_5", text_config = {**text, "vocab_size": 512})
+ kernel = lambda value: value.swapaxes(1, 2) if value.ndim == 3 else value
+ # The checkpoint names the decoder's tensors differently from the loaded model.
+ names = (
+ ("language_model.model.", "model.language_model."),
+ ("language_model.lm_head.", "lm_head."),
+ )
+
+ def renamed(name, saving):
+ for loaded, stored in names:
+ old, new = (loaded, stored) if saving else (stored, loaded)
+ if name.startswith(old):
+ return new + name[len(old) :]
+ return name
+
+ def build(weights = None, quantized = False):
+ model = qwen3_5.Model(args)
+ model.set_dtype(mx.bfloat16)
+ if weights:
+ stored = mx.load(weights).items()
+ model.update(tree_unflatten([(renamed(k, False), kernel(v)) for k, v in stored]))
+ if quantized:
+ # Stands in for the loader's 4-bit quantization, finely enough to compare with the saved model.
+ nn.quantize(model, group_size = 64, bits = 8)
+ return model
+
+ def load(
+ self,
+ source,
+ revision,
+ dtype,
+ token,
+ adapter = None,
+ load_in_4bit = False,
+ ):
+ encode = lambda text, add_special_tokens = False: [ord(c) % 512 for c in text]
+ tokenizer = SimpleNamespace(encode = encode, pad_token_id = 0)
+ model = build(f"{source}/model.safetensors", load_in_4bit)
+ vars(self).update(model = model, tokenizer = tokenizer)
+
+ folder, head = tmp_path / "clef", {"hidden_size": 64, "width": 32, "feedforward": 48}
+ head.update(routing_layers = 1, layers = 1, heads = 4)
+ folder.mkdir()
+ weights = {renamed(k, True): kernel(v) for k, v in tree_flatten(build().parameters())}
+ mx.save_safetensors(str(folder / "model.safetensors"), weights)
+ weights = dict(tree_flatten(zoo._JointHead(**head).parameters()))
+ mx.save_safetensors(str(folder / "joint_head.safetensors"), weights)
+ (folder / "joint_head_config.json").write_text(json.dumps(head))
+ (folder / "config.json").write_text("{}")
+ monkeypatch.setattr(zoo.ClefModel, "_load", load)
+ return folder
+
+
[email protected]("full, four_bit", [(False, False), (False, True), (True, True)])
+def test_clef_trains_calibrates_saves_and_reloads(
+ clef_checkpoint, tmp_path, monkeypatch, full, four_bit
+):
+ model, tokenizer = FastDecisionModel.from_pretrained(
+ str(clef_checkpoint), full_finetuning = full, max_seq_length = 2048, load_in_4bit = four_bit
+ )
+ # Full fine-tuning drops the 4-bit request, as the torch loader does.
+ quantized = any(name.endswith("scales") for name, _ in tree_flatten(model.parameters()))
+ assert quantized == (four_bit and not full)
+ model = FastDecisionModel.get_peft_model(model, r = 8, lora_alpha = 16)
+ rows = [{**_row(0), "state": "long " * 1000}, *(_row(i) for i in range(1, 40))]
+ rows.append({"state": "s", "questions": {"q": {"type": "noul"}}, "gold": {"q": True}})
+ items, report = FastDecisionModel.build_dataset(rows, tokenizer, model)
+ train, held = FastDecisionModel.split_holdout(items, 3407, fraction = 0.25)
+ assert (report["total"], report["skipped"], len(items)) == (121, 1, 40)
+ assert "instructions" in report["reason"] and sum(len(item["labels"]) for item in held) == 30
+ assert max(len(item["input_ids"]) for item in items) == 2048 == len(items[0]["input_ids"])
+ # Scored per question, typed as the shared metrics number them: choice, score, noul.
+ assert [
+ q["qtype"] for q in unsloth._decision_mlx._decision_logits(model, tokenizer, held[:1])[1]
+ ] == [
+ 2,
+ 0,
+ 1,
+ ]
+ args = {**ARGS, "max_steps": 12, "eval_strategy": "no", "per_device_train_batch_size": 4}
+ args.update(save_strategy = "steps", save_steps = 12)
+ args = TrainingArguments(str(tmp_path / "run"), learning_rate = 1e-3, **args)
+ options = {"kl_weight": 0.0 if full else 0.5, "permute_fields": True, "ordinal_weight": 0.3}
+ options["brier_weight"] = 0.5
+ trainer = DecisionTrainer(model, args, train, held, head_learning_rate = 1e-3, **options)
+ assert trainer.train_dataset[0]["source"]["max_length"] == 2048 and trainer._permute
+ assert trainer.objective == (0.0, 0.5, 0.3) and (trainer._reference is None) == full
+ before = {name: mx.array(value) for name, value in tree_flatten(model.trainable_parameters())}
+ trainer.train()
+ after = dict(tree_flatten(model.trainable_parameters()))
+ moved = {name.split(".")[0] for name in before if not mx.array_equal(before[name], after[name])}
+ assert moved == {"encoder", "head"}
+ assert (tmp_path / "run" / "checkpoint-12" / "adapter_model.safetensors").exists() != full
+ trained = [name for name, _ in tree_flatten(model.trainable_parameters())]
+ assert {name.split(".")[0] for name in trained} == {"encoder", "head"}
+ assert full != any(name.endswith("lora_b") for name in trained)
+ assert FastDecisionModel.calibrate(model, tokenizer, held)["fitted_types"] == [0, 1, 2]
+ calibrated = FastDecisionModel.evaluate(model, tokenizer, held, batch_size = 4)
+ # A backbone frozen after it trained is still saved as trained, and stays frozen.
+ FastDecisionModel.freeze_backbone(model)
+ with pytest.raises(ValueError, match = "saved over"):
+ model.save_pretrained_merged(clef_checkpoint)
+ assert not tree_flatten(model.encoder.trainable_parameters())
+ model.save_pretrained_merged(tmp_path / "out")
+ assert not tree_flatten(model.encoder.trainable_parameters())
+ saved = json.loads((tmp_path / "out" / "unsloth_decision_config.json").read_text())
+ assert saved["fine_tuned"] is True and saved["layout"] == "clef" and saved["max_len"] == 2048
+ assert "head_temperature" in model.decision_config and "head_temperature" not in saved
+ served, tokenizer = FastDecisionModel.from_pretrained(str(tmp_path / "out"))
+ assert served.decision_config["temperature"] == saved["temperature"] != [1.0] * 3
+ held = FastDecisionModel.build_dataset([rows[item["row"]] for item in held], tokenizer, served)
+ loss = FastDecisionModel.evaluate(served, tokenizer, held[0])["loss"]
+ assert loss == pytest.approx(calibrated["loss"], abs = 3e-2)
+ # save_pretrained keeps LoRA adapters as adapters over their base; a full fine-tune has none and saves merged.
+ model.save_pretrained(tmp_path / "lora")
+ assert (tmp_path / "lora" / "adapter_model.safetensors").exists() != full
+ assert (tmp_path / "lora" / "model.safetensors").exists() == full
+ again, tokenizer = FastDecisionModel.from_pretrained(
+ str(tmp_path / "lora"), load_in_4bit = four_bit
+ )
+ base = tmp_path / "lora" if full else clef_checkpoint
+ reloaded = FastDecisionModel.evaluate(again, tokenizer, held[0])["loss"]
+ assert again.decision_config["base_model"] == str(base) and reloaded == pytest.approx(
+ loss, abs = 3e-2
+ )
+ if not full:
+ # Loaded adapters are the ones that go on training, and they save as adapters again.
+ with pytest.raises(RuntimeError, match = "already added"):
+ FastDecisionModel.get_peft_model(again, r = 64)
+ tuned = dict(tree_flatten(again.trainable_parameters()))
+ assert sorted(tuned) == sorted(trained)
+ assert {v.shape[1] for k, v in tuned.items() if k.endswith("lora_a")} == {8}
+ again.save_pretrained(tmp_path / "again")
+ # Without a decision config, the adapters still name their base.
+ (tmp_path / "again" / "unsloth_decision_config.json").unlink()
+ bare = FastDecisionModel.from_pretrained(str(tmp_path / "again"))[0]
+ assert bare.decision_config["base_model"] == str(clef_checkpoint)
+ # Merged, they go into the base's weights, which the adapter folder does not hold.
+ again.save_pretrained_merged(tmp_path / "whole")
+ whole, tokenizer = FastDecisionModel.from_pretrained(str(tmp_path / "whole"))
+ merged = FastDecisionModel.evaluate(whole, tokenizer, held[0])["loss"]
+ assert merged == pytest.approx(loss, abs = 3e-2)
+ # The GGUF export converts a merged save, whatever the model trained through.
+ seen, gguf = [], unsloth._decision_mlx._decision_gguf()
+ monkeypatch.setattr(gguf, "_converter_dir", lambda *args: None)
+ # The exporter reads the checkpoint through the helpers both backends share.
+ assert gguf._layout(clef_checkpoint) == "clef" and gguf._layout(tmp_path) is None
+ assert gguf._laya_max_head_tokens(tmp_path, {"head_max_len": 64}) == 256
+ assert gguf.effective_temperatures({"temperature": [2.0, 1.0, 1.0]}, "laya")["choice"] == 2.0
+ export = lambda folder, method, **kwargs: seen.append(
+ (sorted(os.listdir(folder)), method, kwargs["output_dir"], Path(folder).name)
+ )
+ monkeypatch.setattr(gguf, "export_decision_gguf", export)
+ # A merge an ended process left behind is swept, and this one is named for its own process.
+ monkeypatch.setattr(gguf, "_pid_alive", lambda pid: False)
+ (tmp_path / "gguf" / ".unsloth-merged-1-left").mkdir(parents = True)
+ model.save_pretrained_gguf(tmp_path / "gguf", tokenizer)
+ assert seen[0][3].startswith(f".unsloth-merged-{os.getpid()}-")
+ assert "model.safetensors" in seen[0][0] and "adapter_config.json" not in seen[0][0]
+ assert (
+ seen[0][1:3] == ("q8_0", tmp_path / "gguf" / "gguf") and os.listdir(tmp_path / "gguf") == []
+ )
+
+
+def _predicted_shapes(answers):
+ assert isinstance(answers["urgent"]["answer"], bool) and answers["team"]["answer"] in TEAMS
+ assert answers["mood"]["answer"] in (0, 1, 2) and answers["team"]["type"] == "choice"
+ assert sum(answers["mood"]["probabilities"].values()) == pytest.approx(1.0, abs = 1e-3)
+ return max(answers["mood"]["probabilities"].values())
+
+
+def test_predict_answers_at_the_calibrated_temperatures(checkpoint, monkeypatch):
+ model, tokenizer = FastDecisionModel.from_pretrained(str(checkpoint))
+ rows = [{**_row(0), "state": "down " * 2000}, _row(1)]
+ assert FastDecisionModel.build_dataset(rows, tokenizer, model)[1]["truncated"] == 3
+ # An untrained head answers uniformly, so each question's last option is made the likeliest.
+ rising = lambda model, items, pad: [
+ torch.arange(len(i["markers"])).float().numpy() for i in items
+ ]
+ monkeypatch.setattr(unsloth._decision_mlx._decision_zoo(), "decision_logits", rising)
+ # One temperature per question type: choice, score, noul.
+ model.decision_config["temperature"] = [0.5, 1.0, 5.0]
+ answers = FastDecisionModel.predict(model, tokenizer, _row(0)["state"], QUESTIONS)
+ confidence = [answers["team"]["confidence"], _predicted_shapes(answers)]
+ confidence.append(answers["urgent"]["noul"])
+ assert confidence == pytest.approx([0.8808, 0.6652, 0.5498], abs = 2e-4)
+ assert list(answers) == list(QUESTIONS)
+ picked = [answers[name]["answer"] for name in QUESTIONS]
+ assert picked == [True, "billing", 2] and answers["team"]["choice"] == "billing"
+ with pytest.raises(unsloth._decision_mlx.DecisionDataError, match = "non-empty"):
+ FastDecisionModel.predict(model, tokenizer, "s", {})
+
+
[email protected]("four_bit", [False, True])
+def test_a_plain_language_model_trains_as_a_clef(clef_checkpoint, tmp_path, four_bit):
+ for name in ("joint_head.safetensors", "joint_head_config.json"):
+ (clef_checkpoint / name).unlink()
+ with pytest.raises(NotImplementedError, match = "head_init"):
+ FastDecisionModel.from_pretrained(str(clef_checkpoint), head_init = "org/clef")
+ # Without head files the folder is a plain language model, which gets a new joint head.
+ model, tokenizer = FastDecisionModel.from_pretrained(
+ str(clef_checkpoint), head_width = 32, load_in_4bit = four_bit, random_state = 1
+ )
+ config = model.decision_config
+ assert (config["base_model"], config["load_in_4bit"]) == (str(clef_checkpoint), four_bit)
+ assert model._unsloth_pipeline.head_config["width"] == 32
+ assert four_bit == any(name.endswith("scales") for name, _ in tree_flatten(model.parameters()))
+ model = FastDecisionModel.get_peft_model(model, r = 8, lora_alpha = 16)
+ names = lambda: {name for name, _ in tree_flatten(model.trainable_parameters())}
+ adapters = names()
+ FastDecisionModel.freeze_backbone(model)
+ assert {name.split(".")[0] for name in names()} == {"head"}
+ FastDecisionModel.unfreeze_backbone(model)
+ # Exactly the weights that trained before: the adapters, not the base weights under them.
+ assert names() == adapters and any(name.startswith("encoder") for name in adapters)
+ confidence = _predicted_shapes(FastDecisionModel.predict(model, tokenizer, "s", QUESTIONS))
+ model.save_pretrained_merged(tmp_path / "out")
+ served, tokenizer = FastDecisionModel.from_pretrained(str(tmp_path / "out"))
+ answers = FastDecisionModel.predict(served, tokenizer, "s", QUESTIONS)
+ assert _predicted_shapes(answers) == pytest.approx(confidence, abs = 3e-2)
+ assert served.decision_config["base_model"] == str(tmp_path / "out")
diff --git a/unsloth/__init__.py b/unsloth/__init__.py
index 999896cbe4a..28b61594eb8 100644
--- a/unsloth/__init__.py
+++ b/unsloth/__init__.py
@@ -391,22 +391,17 @@ if _IS_MLX:
"Unsloth: FastSentenceTransformer is not yet supported on MLX."
)
- class FastDecisionModel:
- @staticmethod
- def from_pretrained(*args, **kwargs):
- raise NotImplementedError(
- "Unsloth: FastDecisionModel training is not yet supported on MLX."
- )
-
- @staticmethod
- def get_peft_model(*args, **kwargs):
- raise NotImplementedError(
- "Unsloth: FastDecisionModel training is not yet supported on MLX."
- )
-
- class DecisionTrainer:
- def __init__(self, *args, **kwargs):
- raise NotImplementedError("Unsloth: DecisionTrainer is not yet supported on MLX.")
+ # Decision models (Laya, Clef): models/decision_mlx.py, by path because unsloth.models needs torch.
+ _decision_spec = importlib.util.spec_from_file_location(
+ "unsloth._decision_mlx",
+ os.path.join(os.path.dirname(__file__), "models", "decision_mlx.py"),
+ )
+ _decision_mlx = importlib.util.module_from_spec(_decision_spec)
+ sys.modules[_decision_spec.name] = _decision_mlx
+ _decision_spec.loader.exec_module(_decision_mlx)
+ FastDecisionModel = _decision_mlx.FastDecisionModel
+ DecisionTrainer = _decision_mlx.DecisionTrainer
+ del _decision_spec
def is_bfloat16_supported():
try:
diff --git a/unsloth/models/_decision_common.py b/unsloth/models/_decision_common.py
new file mode 100644
index 00000000000..a952fed5b85
--- /dev/null
+++ b/unsloth/models/_decision_common.py
@@ -0,0 +1,468 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.
+
+# Checkpoint lookup, gold labels and calibration shared by FastDecisionModel's torch and MLX paths.
+# Imports torch only inside functions: the MLX path loads this file by path, without unsloth.models.
+
+__all__ = [
+ "TRAIN_MAX_LEN",
+ "TRAIN_HEAD_MAX_LEN",
+ "HOLDOUT_MAX",
+ "MIN_CALIBRATION_ITEMS",
+ "QUESTION_TYPES",
+ "_FILES",
+ "_DIRS",
+ "_CLEF_HEAD_FILES",
+ "_ADAPTER_CONFIG",
+ "CLEF_MAX_LEN",
+ "CLEF_SERVE_MAX_LEN",
+ "_VENDORED_LAYA",
+ "HEAD_TEMPERATURE_RANGE",
+ "DecisionDataError",
+ "_laya",
+ "is_decision_checkpoint",
+ "is_clef_checkpoint",
+ "_is_clef_adapter",
+ "_is_clef_repo",
+ "_is_plain_lm",
+ "_checkpoint_folder",
+ "_lm_subfolder",
+ "_parsed",
+ "_internal",
+ "_option_keys",
+ "_label",
+ "_target",
+ "_target_for",
+ "_clef_question",
+ "_predicted",
+ "_metrics",
+ "_fit_temperature",
+ "_fit_temperatures",
+ "_served_temperatures",
+ "_calibrate_clef",
+ "_served_lengths",
+]
+
+import functools
+import importlib.util
+import json
+import math
+import sys
+from pathlib import Path
+from typing import Optional
+
+TRAIN_MAX_LEN, TRAIN_HEAD_MAX_LEN = 1024, 256
+HOLDOUT_MAX = 400
+MIN_CALIBRATION_ITEMS = 10
+QUESTION_TYPES = ("choice", "score", "noul")
+_FILES = ("rl_agent_config.json", "model.safetensors")
+_DIRS = ("encoder", "tokenizer")
+_CLEF_HEAD_FILES = ("joint_head.safetensors", "joint_head_config.json")
+_ADAPTER_CONFIG = "adapter_config.json"
+CLEF_MAX_LEN = 4096
+# predict() and serving read this many tokens whatever the training length: cutting a state drops evidence.
+CLEF_SERVE_MAX_LEN = 16384
+# laya 0.3.5 ships inside Unsloth for Studio's Decision API (studio/backend/vendor/README.md).
+_VENDORED_LAYA = (
+ Path(__file__).resolve().parents[2] / "studio" / "backend" / "vendor" / "laya" / "__init__.py"
+).resolve()
+
+
+class DecisionDataError(ValueError):
+ pass
+
+
[email protected]_cache(maxsize = None)
+def _laya():
+ # By path, so a pip installed "laya" is never used or replaced; Studio registers this copy.
+ for name in ("laya", "unsloth._laya"):
+ module = sys.modules.get(name)
+ if getattr(module, "__file__", None) and Path(module.__file__).resolve() == _VENDORED_LAYA:
+ return module
+ if not _VENDORED_LAYA.is_file():
+ raise ImportError(
+ f"Unsloth: decision models need laya, which ships with Unsloth at {_VENDORED_LAYA.parent}. "
+ "Please reinstall Unsloth."
+ )
+ spec = importlib.util.spec_from_file_location(
+ "unsloth._laya", _VENDORED_LAYA, submodule_search_locations = [str(_VENDORED_LAYA.parent)]
+ )
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = module
+ spec.loader.exec_module(module)
+ # laya's JSON reads and writes use a bare open(), which is the locale encoding on Windows.
+ module.agent.open = functools.partial(open, encoding = "utf-8")
+ return module
+
+
+def is_decision_checkpoint(folder) -> bool:
+ folder = Path(folder)
+ return is_clef_checkpoint(folder) or (
+ all((folder / name).is_file() for name in _FILES)
+ and all((folder / name).is_dir() for name in _DIRS)
+ )
+
+
+def is_clef_checkpoint(folder) -> bool:
+ # Cloudflare's Clef layout: a backbone (merged, or LoRA adapters over a base) plus a joint schema head.
+ folder = Path(folder)
+ return all((folder / name).is_file() for name in _CLEF_HEAD_FILES) and (
+ (folder / "config.json").is_file() or (folder / _ADAPTER_CONFIG).is_file()
+ )
+
+
+def _is_clef_adapter(folder) -> bool:
+ folder = Path(folder)
+ return not (folder / "config.json").is_file() and (folder / _ADAPTER_CONFIG).is_file()
+
+
+def _is_clef_repo(model_name, prefix, token, revision) -> Optional[bool]:
+ # Asked up front: Unsloth's download wrapper rejects a snapshot that lacks an exact file it was
+ # asked for, so a Laya pattern on a Clef repo (or the reverse) would fail as "incomplete".
+ from huggingface_hub import HfApi, constants
+
+ if constants.HF_HUB_OFFLINE:
+ return None
+ try:
+ files = HfApi(token = token).list_repo_files(model_name, revision = revision)
+ except Exception:
+ return None
+ return prefix + _CLEF_HEAD_FILES[1] in files
+
+
+def _is_plain_lm(model_name, subfolder, token, revision, local_files_only) -> bool:
+ # Unknown (offline, no access) answers False, so the checkpoint loader names what is missing.
+ markers = {_FILES[0], _CLEF_HEAD_FILES[1]}
+ if subfolder:
+ return False
+ root = Path(str(model_name)).expanduser()
+ if root.is_dir():
+ has = lambda name: (root / name).is_file()
+ return (has("config.json") or has(_ADAPTER_CONFIG)) and not any(map(has, markers))
+ from huggingface_hub import constants
+
+ if not (local_files_only or constants.HF_HUB_OFFLINE):
+ try:
+ from huggingface_hub import HfApi
+ files = HfApi(token = token).list_repo_files(str(model_name), revision = revision)
+ except Exception:
+ files = None
+ if files is not None:
+ names = {name.rsplit("/", 1)[-1] for name in files}
+ return bool({"config.json", _ADAPTER_CONFIG} & set(files)) and not (names & markers)
+ from huggingface_hub import try_to_load_from_cache
+
+ def cached(name) -> bool:
+ try:
+ return isinstance(try_to_load_from_cache(str(model_name), name, revision = revision), str)
+ except Exception:
+ return False
+
+ return (cached("config.json") or cached(_ADAPTER_CONFIG)) and not any(map(cached, markers))
+
+
+def _checkpoint_folder(model_name, subfolder, token, revision, local_files_only) -> Path:
+ root = Path(model_name).expanduser()
+ if not root.is_dir():
+ from huggingface_hub import snapshot_download as cached_snapshot
+
+ try:
+ from unsloth_zoo.hf_xet_fallback import (
+ snapshot_download_with_xet_fallback as snapshot_download,
+ )
+ except ImportError:
+ snapshot_download = cached_snapshot
+ prefix = f"{subfolder}/" if subfolder else ""
+ laya = [prefix + name for name in _FILES] + [f"{prefix}{name}/*" for name in _DIRS]
+ clef = None if local_files_only else _is_clef_repo(model_name, prefix, token, revision)
+ if clef is None:
+ # Offline: the cache already holds one layout or the other.
+ root = Path(
+ cached_snapshot(
+ model_name,
+ token = token,
+ revision = revision,
+ local_files_only = True,
+ allow_patterns = laya + [prefix + "*.json"],
+ )
+ )
+ clef = (root / prefix / _CLEF_HEAD_FILES[1]).is_file()
+ # Laya repos hold several checkpoints in subfolders, so only the asked one is fetched.
+ root = Path(
+ snapshot_download(
+ model_name,
+ token = token,
+ revision = revision,
+ local_files_only = local_files_only,
+ allow_patterns = [prefix + "*"] if clef else laya,
+ )
+ )
+ folder = root / subfolder if subfolder else root
+ if not is_decision_checkpoint(folder):
+ raise ValueError(
+ f"Unsloth: {folder} is not a decision model checkpoint "
+ "(rl_agent_config.json, model.safetensors, encoder/ and tokenizer/, "
+ "or a Clef backbone with joint_head.safetensors and joint_head_config.json). "
+ 'To turn a plain language model into a decision model, pass decision_head = "clef".'
+ )
+ return folder
+
+
+def _lm_subfolder(model_name, subfolder, token, revision, local_files_only) -> str:
+ if Path(model_name).expanduser().is_dir():
+ return str(Path(model_name).expanduser() / subfolder)
+ from huggingface_hub import snapshot_download
+
+ root = snapshot_download(
+ model_name,
+ allow_patterns = [f"{subfolder}/*"],
+ token = token,
+ revision = revision,
+ local_files_only = local_files_only,
+ )
+ return str(Path(root) / subfolder)
+
+
+def _parsed(value):
+ if isinstance(value, str) and value.strip()[:1] in ("{", "["):
+ try:
+ return json.loads(value)
+ except ValueError:
+ return value
+ return value
+
+
+def _internal(question) -> dict:
+ if not isinstance(question, dict) or question.get("type") not in QUESTION_TYPES:
+ raise DecisionDataError("is not a valid question")
+ kind, criteria = question["type"], question.get("criteria")
+ if kind == "choice" and not (
+ isinstance(criteria, (dict, list))
+ and criteria
+ and all(isinstance(option, str) for option in criteria)
+ ):
+ raise DecisionDataError("needs criteria naming its options")
+ if kind == "score" and not (isinstance(criteria, list) and criteria):
+ raise DecisionDataError("needs a list of criteria levels")
+ if kind == "noul" and criteria is not None and not isinstance(criteria, dict):
+ raise DecisionDataError('criteria may only have "true" and "false"')
+ laya_question = {"type": kind, "instructions": question.get("instructions") or ""}
+ if criteria is not None:
+ laya_question["criteria"] = criteria
+ return _laya().agent.Agent._to_internal(laya_question)
+
+
+def _option_keys(internal: dict) -> list:
+ if internal["t"] == "choice":
+ return [str(key) for key in internal["crit"]]
+ if internal["t"] == "noul":
+ return ["false", "true"]
+ return [str(i) for i in range(len(internal["crit"]))]
+
+
+def _label(kind: str, label):
+ if kind == "score" and isinstance(label, (int, float, str)) and not isinstance(label, bool):
+ try:
+ level = float(label)
+ except ValueError:
+ return None
+ return str(int(level)) if level.is_integer() else None
+ if label is None:
+ return None
+ return str(label).strip().lower() if kind == "noul" else str(label)
+
+
+def _target(internal: dict, gold) -> tuple:
+ return _target_for(internal["t"], _option_keys(internal), gold)
+
+
+def _target_for(kind: str, keys: list, gold) -> tuple:
+ if not isinstance(gold, dict):
+ gold = {"label": gold}
+ label = _label(kind, gold.get("label"))
+ probabilities = gold.get("probabilities")
+ if kind == "noul" and not isinstance(probabilities, dict):
+ noul = gold.get("noul")
+ probabilities = {"true": noul} if isinstance(noul, (int, float)) else None
+ if isinstance(probabilities, dict):
+ try:
+ values = {str(key): float(value) for key, value in probabilities.items()}
+ except (TypeError, ValueError):
+ values = {}
+ if not all(math.isfinite(value) for value in values.values()):
+ raise DecisionDataError("gold has probabilities that are not finite numbers")
+ if kind == "noul" and len(values.keys() & {"false", "true"}) == 1:
+ known = "true" if "true" in values else "false"
+ values[{"true": "false", "false": "true"}[known]] = 1.0 - values[known]
+ target = [max(0.0, values.get(key, 0.0)) for key in keys]
+ total = sum(target)
+ if 0 < total < math.inf:
+ target = [value / total for value in target]
+ return target, keys.index(label) if label in keys else target.index(max(target))
+ if label in keys:
+ return [1.0 if key == label else 0.0 for key in keys], keys.index(label)
+ raise DecisionDataError("gold has no usable label or probabilities")
+
+
+def _clef_question(question) -> dict:
+ if not isinstance(question, dict) or question.get("type") not in QUESTION_TYPES:
+ raise DecisionDataError("is not a valid question")
+ kind, criteria = question["type"], question.get("criteria")
+ if kind == "choice":
+ if isinstance(criteria, list) and criteria and all(isinstance(c, str) for c in criteria):
+ criteria = dict.fromkeys(criteria)
+ if not (isinstance(criteria, dict) and criteria):
+ raise DecisionDataError("needs criteria naming its options")
+ if len({str(key) for key in criteria}) != len(criteria):
+ raise DecisionDataError("has repeated options")
+ if kind == "score" and not (isinstance(criteria, list) and criteria):
+ raise DecisionDataError("needs a list of criteria levels")
+ if kind == "noul" and criteria is not None:
+ if not isinstance(criteria, dict) or set(criteria) - {"true", "false"}:
+ raise DecisionDataError('criteria may only have "true" and "false"')
+ clef_question = {"type": kind, "instructions": question.get("instructions")}
+ if criteria is not None:
+ clef_question["criteria"] = criteria
+ return clef_question
+
+
+def _predicted(question: dict, answer: dict, probabilities: dict) -> dict:
+ # The Decision API answer plus "answer": the option (choice), True / False (noul) or level number (score).
+ kind = question["type"]
+ best = max(probabilities, key = probabilities.__getitem__)
+ return {
+ **answer,
+ "answer": int(best) if kind == "score" else best == "true" if kind == "noul" else best,
+ "probabilities": answer.get("probabilities")
+ or {key: round(float(value), 4) for key, value in probabilities.items()},
+ }
+
+
+def _metrics(logits, items, temperatures) -> dict:
+ import numpy as np
+ import torch
+
+ conf, correct, loss, records = [], [], [], {}
+ for z, item, temperature in zip(logits, items, temperatures):
+ log_p = torch.log_softmax(z / temperature, -1)
+ conf.append(float(log_p.exp().max()))
+ correct.append(float(int(log_p.argmax()) == item["label"]))
+ loss.append(float(-(torch.tensor(item["target"]) * log_p).sum()))
+ row = item.get("row", ("item", len(correct)))
+ records[row] = records.get(row, True) and bool(correct[-1])
+ return {
+ "accuracy": float(np.mean(correct)),
+ "ece": _laya().common.ece_score(np.array(conf), np.array(correct)),
+ "loss": float(np.mean(loss)),
+ # Every question of a row right, the record-level precision Cloudflare rewards.
+ "record_accuracy": float(np.mean(list(records.values()))),
+ }
+
+
+def _fit_temperature(
+ logits,
+ items,
+ line_search = None,
+) -> float:
+ import torch
+
+ options = max(len(z) for z in logits)
+ z = torch.full((len(logits), options), -1e4)
+ target = torch.zeros((len(logits), options))
+ for i, (row, item) in enumerate(zip(logits, items)):
+ z[i, : len(row)] = row
+ target[i, : len(row)] = torch.tensor(item["target"])
+ log_t = torch.zeros(1, requires_grad = True)
+ # Clef's hard-label fit passes "strong_wolfe": plain LBFGS can overshoot on peaked targets.
+ optimizer = torch.optim.LBFGS([log_t], lr = 0.1, max_iter = 100, line_search_fn = line_search)
+
+ def closure():
+ optimizer.zero_grad()
+ loss = -(target * torch.log_softmax(z / log_t.exp(), -1)).sum(-1).mean()
+ loss.backward()
+ return loss
+
+ optimizer.step(closure)
+ return float(log_t.exp().item())
+
+
+def _fit_temperatures(logits, items, indices, fallback: list) -> tuple:
+ clamp = _laya().common.clamp_temperature
+ temperature, fitted = list(fallback), set()
+ for qtype in range(3):
+ chosen = [i for i in indices if items[i]["qtype"] == qtype]
+ if len(chosen) >= MIN_CALIBRATION_ITEMS:
+ temperature[qtype] = clamp(
+ _fit_temperature([logits[i] for i in chosen], [items[i] for i in chosen])
+ )
+ fitted.add(qtype)
+ return temperature, fitted
+
+
+def _served_temperatures(config: dict, logits, items) -> list:
+ common = _laya().common
+ per_type = [common.clamp_temperature(t) for t in config.get("temperature", [1.0] * 3)]
+ buckets = {
+ key: common.clamp_temperature(value)
+ for key, value in (config.get("temperature_by_options") or {}).items()
+ }
+ # A Clef temperature not yet folded into the head (_save_clef folds it on save).
+ head = config.get("head_temperature", 1.0)
+ return [
+ head * buckets.get(common.temp_bucket(item["qtype"], len(z)), per_type[item["qtype"]])
+ for z, item in zip(logits, items)
+ ]
+
+
+HEAD_TEMPERATURE_RANGE = (0.05, 20.0)
+
+
+def _calibrate_clef(config: dict, logits, items) -> dict:
+ # Calibrated against being right (the gold label), not the soft gold distribution: Clef's
+ # confidence is read as the chance the answer is correct, and soft gold targets left a tuned
+ # model underconfident (confidence 0.61 at accuracy 0.78 on typed-decisions).
+ common = _laya().common
+ hard = [
+ {**item, "target": [float(j == item["label"]) for j in range(len(z))]}
+ for z, item in zip(logits, items)
+ ]
+
+ def fit(indices) -> tuple:
+ chosen = list(indices)
+ head = _fit_temperature(
+ [logits[i] for i in chosen], [hard[i] for i in chosen], line_search = "strong_wolfe"
+ )
+ head = min(max(head, HEAD_TEMPERATURE_RANGE[0]), HEAD_TEMPERATURE_RANGE[1])
+ scaled = [z / head for z in logits]
+ relative, fitted = _fit_temperatures(scaled, hard, chosen, [1.0] * 3)
+ return head, relative, fitted
+
+ everything = range(len(items))
+ if len(items) < MIN_CALIBRATION_ITEMS:
+ return {
+ **_metrics(logits, items, _served_temperatures(config, logits, items)),
+ "fitted_types": [],
+ }
+ head, relative, fitted = fit(everything)
+ half = {row: i % 2 for i, row in enumerate(sorted({item["row"] for item in items}))}
+ per_item = [head * common.clamp_temperature(relative[item["qtype"]]) for item in items]
+ for side in (0, 1) if len(half) > 1 else ():
+ side_head, side_relative, _ = fit(i for i in everything if half[items[i]["row"]] != side)
+ for i in everything:
+ if half[items[i]["row"]] == side:
+ per_item[i] = side_head * common.clamp_temperature(side_relative[items[i]["qtype"]])
+ config["head_temperature"] = head
+ config["temperature"] = relative
+ config.pop("temperature_by_options", None)
+ return {**_metrics(logits, items, per_item), "fitted_types": sorted(fitted)}
+
+
+def _served_lengths(
+ config: dict,
+ positions: int,
+ max_seq_length = None,
+) -> tuple:
+ """(max_len, head_max_len) a Laya checkpoint serves with once loaded."""
+ wanted = max_seq_length or max(int(config.get("max_len", 512)), TRAIN_MAX_LEN)
+ max_len = min(int(positions), int(wanted))
+ return max_len, min(max_len // 2, max(int(config.get("head_max_len", 192)), TRAIN_HEAD_MAX_LEN))
diff --git a/unsloth/models/decision.py b/unsloth/models/decision.py
index df7248b254c..178fd838d31 100644
--- a/unsloth/models/decision.py
+++ b/unsloth/models/decision.py
@@ -8,13 +8,10 @@ __all__ = [
import contextlib
import copy
-import functools
-import importlib.util
import json
import math
import os
import random
-import sys
import tempfile
import types
from collections import Counter
@@ -32,18 +29,11 @@ from ._utils import (
)
from .loader_utils import is_distributed
from ._decision_fast import compiled_encoder, pad_length
+from ._decision_common import * # noqa: F401,F403
-TRAIN_MAX_LEN, TRAIN_HEAD_MAX_LEN = 1024, 256
-HOLDOUT_MAX = 400
-MIN_CALIBRATION_ITEMS = 10
HEAD_LEARNING_RATE = 1e-4
-QUESTION_TYPES = ("choice", "score", "noul")
# DecisionTrainer defaults for Clef; every key is also a DecisionTrainer argument.
CLEF_RECIPE = {}
-_FILES = ("rl_agent_config.json", "model.safetensors")
-_DIRS = ("encoder", "tokenizer")
-_CLEF_HEAD_FILES = ("joint_head.safetensors", "joint_head_config.json")
-_ADAPTER_CONFIG = "adapter_config.json"
_DECISION_CONFIG = "unsloth_decision_config.json"
# Copied byte for byte from the checkpoint a Clef fine-tune started from: Cloudflare's loader and
# license, and the tokenizer / processor files, which transformers would otherwise rewrite (a
@@ -57,153 +47,6 @@ _CLEF_EXTRA_FILES = (
"processor_config.json",
"generation_config.json",
)
-CLEF_MAX_LEN = 4096
-# predict() and serving read this many tokens whatever the training length: cutting a state drops evidence.
-CLEF_SERVE_MAX_LEN = 16384
-# laya 0.3.5 ships inside Unsloth for Studio's Decision API (studio/backend/vendor/README.md).
-_VENDORED_LAYA = (
- Path(__file__).resolve().parents[2] / "studio" / "backend" / "vendor" / "laya" / "__init__.py"
-).resolve()
-
-
-class DecisionDataError(ValueError):
- pass
-
-
[email protected]_cache(maxsize = None)
-def _laya():
- # By path, so a pip installed "laya" is never used or replaced; Studio registers this copy.
- for name in ("laya", "unsloth._laya"):
- module = sys.modules.get(name)
- if getattr(module, "__file__", None) and Path(module.__file__).resolve() == _VENDORED_LAYA:
- return module
- if not _VENDORED_LAYA.is_file():
- raise ImportError(
- f"Unsloth: decision models need laya, which ships with Unsloth at {_VENDORED_LAYA.parent}. "
- "Please reinstall Unsloth."
- )
- spec = importlib.util.spec_from_file_location(
- "unsloth._laya", _VENDORED_LAYA, submodule_search_locations = [str(_VENDORED_LAYA.parent)]
- )
- module = importlib.util.module_from_spec(spec)
- sys.modules[spec.name] = module
- spec.loader.exec_module(module)
- # laya's JSON reads and writes use a bare open(), which is the locale encoding on Windows.
- module.agent.open = functools.partial(open, encoding = "utf-8")
- return module
-
-
-def is_decision_checkpoint(folder) -> bool:
- folder = Path(folder)
- return is_clef_checkpoint(folder) or (
- all((folder / name).is_file() for name in _FILES)
- and all((folder / name).is_dir() for name in _DIRS)
- )
-
-
-def is_clef_checkpoint(folder) -> bool:
- # Cloudflare's Clef layout: a backbone (merged, or LoRA adapters over a base) plus a joint schema head.
- folder = Path(folder)
- return all((folder / name).is_file() for name in _CLEF_HEAD_FILES) and (
- (folder / "config.json").is_file() or (folder / _ADAPTER_CONFIG).is_file()
- )
-
-
-def _is_clef_adapter(folder) -> bool:
- folder = Path(folder)
- return not (folder / "config.json").is_file() and (folder / _ADAPTER_CONFIG).is_file()
-
-
-def _is_clef_repo(model_name, prefix, token, revision) -> Optional[bool]:
- # Asked up front: Unsloth's download wrapper rejects a snapshot that lacks an exact file it was
- # asked for, so a Laya pattern on a Clef repo (or the reverse) would fail as "incomplete".
- from huggingface_hub import HfApi, constants
-
- if constants.HF_HUB_OFFLINE:
- return None
- try:
- files = HfApi(token = token).list_repo_files(model_name, revision = revision)
- except Exception:
- return None
- return prefix + _CLEF_HEAD_FILES[1] in files
-
-
-def _is_plain_lm(model_name, subfolder, token, revision, local_files_only) -> bool:
- # Unknown (offline, no access) answers False, so the checkpoint loader names what is missing.
- markers = {_FILES[0], _CLEF_HEAD_FILES[1]}
- if subfolder:
- return False
- root = Path(str(model_name)).expanduser()
- if root.is_dir():
- has = lambda name: (root / name).is_file()
- return (has("config.json") or has(_ADAPTER_CONFIG)) and not any(map(has, markers))
- from huggingface_hub import constants
-
- if not (local_files_only or constants.HF_HUB_OFFLINE):
- try:
- from huggingface_hub import HfApi
- files = HfApi(token = token).list_repo_files(str(model_name), revision = revision)
- except Exception:
- files = None
- if files is not None:
- names = {name.rsplit("/", 1)[-1] for name in files}
- return bool({"config.json", _ADAPTER_CONFIG} & set(files)) and not (names & markers)
- from huggingface_hub import try_to_load_from_cache
-
- def cached(name) -> bool:
- try:
- return isinstance(try_to_load_from_cache(str(model_name), name, revision = revision), str)
- except Exception:
- return False
-
- return (cached("config.json") or cached(_ADAPTER_CONFIG)) and not any(map(cached, markers))
-
-
-def _checkpoint_folder(model_name, subfolder, token, revision, local_files_only) -> Path:
- root = Path(model_name).expanduser()
- if not root.is_dir():
- from huggingface_hub import snapshot_download as cached_snapshot
-
- try:
- from unsloth_zoo.hf_xet_fallback import (
- snapshot_download_with_xet_fallback as snapshot_download,
- )
- except ImportError:
- snapshot_download = cached_snapshot
- prefix = f"{subfolder}/" if subfolder else ""
- laya = [prefix + name for name in _FILES] + [f"{prefix}{name}/*" for name in _DIRS]
- clef = None if local_files_only else _is_clef_repo(model_name, prefix, token, revision)
- if clef is None:
- # Offline: the cache already holds one layout or the other.
- root = Path(
- cached_snapshot(
- model_name,
- token = token,
- revision = revision,
- local_files_only = True,
- allow_patterns = laya + [prefix + "*.json"],
- )
- )
- clef = (root / prefix / _CLEF_HEAD_FILES[1]).is_file()
- # Laya repos hold several checkpoints in subfolders, so only the asked one is fetched.
- root = Path(
- snapshot_download(
- model_name,
- token = token,
- revision = revision,
- local_files_only = local_files_only,
- allow_patterns = [prefix + "*"] if clef else laya,
- )
- )
- folder = root / subfolder if subfolder else root
- if not is_decision_checkpoint(folder):
- raise ValueError(
- f"Unsloth: {folder} is not a decision model checkpoint "
- "(rl_agent_config.json, model.safetensors, encoder/ and tokenizer/, "
- "or a Clef backbone with joint_head.safetensors and joint_head_config.json). "
- 'To turn a plain language model into a decision model, pass decision_head = "clef".'
- )
- return folder
def _encoder_config(folder):
@@ -317,87 +160,6 @@ def _lean_lora(encoder) -> None:
module.forward = types.MethodType(_lean_lora_forward, module)
-def _parsed(value):
- if isinstance(value, str) and value.strip()[:1] in ("{", "["):
- try:
- return json.loads(value)
- except ValueError:
- return value
- return value
-
-
-def _internal(question) -> dict:
- if not isinstance(question, dict) or question.get("type") not in QUESTION_TYPES:
- raise DecisionDataError("is not a valid question")
- kind, criteria = question["type"], question.get("criteria")
- if kind == "choice" and not (
- isinstance(criteria, (dict, list))
- and criteria
- and all(isinstance(option, str) for option in criteria)
- ):
- raise DecisionDataError("needs criteria naming its options")
- if kind == "score" and not (isinstance(criteria, list) and criteria):
- raise DecisionDataError("needs a list of criteria levels")
- if kind == "noul" and criteria is not None and not isinstance(criteria, dict):
- raise DecisionDataError('criteria may only have "true" and "false"')
- laya_question = {"type": kind, "instructions": question.get("instructions") or ""}
- if criteria is not None:
- laya_question["criteria"] = criteria
- return _laya().agent.Agent._to_internal(laya_question)
-
-
-def _option_keys(internal: dict) -> list:
- if internal["t"] == "choice":
- return [str(key) for key in internal["crit"]]
- if internal["t"] == "noul":
- return ["false", "true"]
- return [str(i) for i in range(len(internal["crit"]))]
-
-
-def _label(kind: str, label):
- if kind == "score" and isinstance(label, (int, float, str)) and not isinstance(label, bool):
- try:
- level = float(label)
- except ValueError:
- return None
- return str(int(level)) if level.is_integer() else None
- if label is None:
- return None
- return str(label).strip().lower() if kind == "noul" else str(label)
-
-
-def _target(internal: dict, gold) -> tuple:
- return _target_for(internal["t"], _option_keys(internal), gold)
-
-
-def _target_for(kind: str, keys: list, gold) -> tuple:
- if not isinstance(gold, dict):
- gold = {"label": gold}
- label = _label(kind, gold.get("label"))
- probabilities = gold.get("probabilities")
- if kind == "noul" and not isinstance(probabilities, dict):
- noul = gold.get("noul")
- probabilities = {"true": noul} if isinstance(noul, (int, float)) else None
- if isinstance(probabilities, dict):
- try:
- values = {str(key): float(value) for key, value in probabilities.items()}
- except (TypeError, ValueError):
- values = {}
- if not all(math.isfinite(value) for value in values.values()):
- raise DecisionDataError("gold has probabilities that are not finite numbers")
- if kind == "noul" and len(values.keys() & {"false", "true"}) == 1:
- known = "true" if "true" in values else "false"
- values[{"true": "false", "false": "true"}[known]] = 1.0 - values[known]
- target = [max(0.0, values.get(key, 0.0)) for key in keys]
- total = sum(target)
- if 0 < total < math.inf:
- target = [value / total for value in target]
- return target, keys.index(label) if label in keys else target.index(max(target))
- if label in keys:
- return [1.0 if key == label else 0.0 for key in keys], keys.index(label)
- raise DecisionDataError("gold has no usable label or probabilities")
-
-
def _soft_cross_entropy(logits, target, mask):
logits = logits.float().masked_fill(~mask, -1e4)
return -(target * torch.log_softmax(logits, -1)).sum(-1).mean()
@@ -580,28 +342,6 @@ class ClefDecisionModel(torch.nn.Module):
return padded, None
-def _clef_question(question) -> dict:
- if not isinstance(question, dict) or question.get("type") not in QUESTION_TYPES:
- raise DecisionDataError("is not a valid question")
- kind, criteria = question["type"], question.get("criteria")
- if kind == "choice":
- if isinstance(criteria, list) and criteria and all(isinstance(c, str) for c in criteria):
- criteria = dict.fromkeys(criteria)
- if not (isinstance(criteria, dict) and criteria):
- raise DecisionDataError("needs criteria naming its options")
- if len({str(key) for key in criteria}) != len(criteria):
- raise DecisionDataError("has repeated options")
- if kind == "score" and not (isinstance(criteria, list) and criteria):
- raise DecisionDataError("needs a list of criteria levels")
- if kind == "noul" and criteria is not None:
- if not isinstance(criteria, dict) or set(criteria) - {"true", "false"}:
- raise DecisionDataError('criteria may only have "true" and "false"')
- clef_question = {"type": kind, "instructions": question.get("instructions")}
- if criteria is not None:
- clef_question["criteria"] = criteria
- return clef_question
-
-
def _clef_items(rows, tokenizer, max_len, validate, report, skip) -> list:
from .clef import QUESTION_TYPES as CLEF_TYPES, encode_record, question_options
@@ -709,18 +449,6 @@ def _decision_logits(
return _logits(model, items, pad_token_id), items
-def _predicted(question: dict, answer: dict, probabilities: dict) -> dict:
- # The Decision API answer plus "answer": the option (choice), True / False (noul) or level number (score).
- kind = question["type"]
- best = max(probabilities, key = probabilities.__getitem__)
- return {
- **answer,
- "answer": int(best) if kind == "score" else best == "true" if kind == "noul" else best,
- "probabilities": answer.get("probabilities")
- or {key: round(float(value), 4) for key, value in probabilities.items()},
- }
-
-
@torch.no_grad()
def _clef_decide(
model,
@@ -1588,133 +1316,6 @@ def _logits(
return out
-def _metrics(logits, items, temperatures) -> dict:
- import numpy as np
-
- conf, correct, loss, records = [], [], [], {}
- for z, item, temperature in zip(logits, items, temperatures):
- log_p = torch.log_softmax(z / temperature, -1)
- conf.append(float(log_p.exp().max()))
- correct.append(float(int(log_p.argmax()) == item["label"]))
- loss.append(float(-(torch.tensor(item["target"]) * log_p).sum()))
- row = item.get("row", ("item", len(correct)))
- records[row] = records.get(row, True) and bool(correct[-1])
- return {
- "accuracy": float(np.mean(correct)),
- "ece": _laya().common.ece_score(np.array(conf), np.array(correct)),
- "loss": float(np.mean(loss)),
- # Every question of a row right, the record-level precision Cloudflare rewards.
- "record_accuracy": float(np.mean(list(records.values()))),
- }
-
-
-def _fit_temperature(
- logits,
- items,
- line_search = None,
-) -> float:
- options = max(len(z) for z in logits)
- z = torch.full((len(logits), options), -1e4)
- target = torch.zeros((len(logits), options))
- for i, (row, item) in enumerate(zip(logits, items)):
- z[i, : len(row)] = row
- target[i, : len(row)] = torch.tensor(item["target"])
- log_t = torch.zeros(1, requires_grad = True)
- # Clef's hard-label fit passes "strong_wolfe": plain LBFGS can overshoot on peaked targets.
- optimizer = torch.optim.LBFGS([log_t], lr = 0.1, max_iter = 100, line_search_fn = line_search)
-
- def closure():
- optimizer.zero_grad()
- loss = -(target * torch.log_softmax(z / log_t.exp(), -1)).sum(-1).mean()
- loss.backward()
- return loss
-
- optimizer.step(closure)
- return float(log_t.exp().item())
-
-
-def _fit_temperatures(logits, items, indices, fallback: list) -> tuple:
- clamp = _laya().common.clamp_temperature
- temperature, fitted = list(fallback), set()
- for qtype in range(3):
- chosen = [i for i in indices if items[i]["qtype"] == qtype]
- if len(chosen) >= MIN_CALIBRATION_ITEMS:
- temperature[qtype] = clamp(
- _fit_temperature([logits[i] for i in chosen], [items[i] for i in chosen])
- )
- fitted.add(qtype)
- return temperature, fitted
-
-
-def _served_temperatures(config: dict, logits, items) -> list:
- common = _laya().common
- per_type = [common.clamp_temperature(t) for t in config.get("temperature", [1.0] * 3)]
- buckets = {
- key: common.clamp_temperature(value)
- for key, value in (config.get("temperature_by_options") or {}).items()
- }
- # A Clef temperature not yet folded into the head (_save_clef folds it on save).
- head = config.get("head_temperature", 1.0)
- return [
- head * buckets.get(common.temp_bucket(item["qtype"], len(z)), per_type[item["qtype"]])
- for z, item in zip(logits, items)
- ]
-
-
-HEAD_TEMPERATURE_RANGE = (0.05, 20.0)
-
-
-def _calibrate_clef(config: dict, logits, items) -> dict:
- # Calibrated against being right (the gold label), not the soft gold distribution: Clef's
- # confidence is read as the chance the answer is correct, and soft gold targets left a tuned
- # model underconfident (confidence 0.61 at accuracy 0.78 on typed-decisions).
- common = _laya().common
- hard = [
- {**item, "target": [float(j == item["label"]) for j in range(len(z))]}
- for z, item in zip(logits, items)
- ]
-
- def fit(indices) -> tuple:
- chosen = list(indices)
- head = _fit_temperature(
- [logits[i] for i in chosen], [hard[i] for i in chosen], line_search = "strong_wolfe"
- )
- head = min(max(head, HEAD_TEMPERATURE_RANGE[0]), HEAD_TEMPERATURE_RANGE[1])
- scaled = [z / head for z in logits]
- relative, fitted = _fit_temperatures(scaled, hard, chosen, [1.0] * 3)
- return head, relative, fitted
-
- everything = range(len(items))
- if len(items) < MIN_CALIBRATION_ITEMS:
- return {
- **_metrics(logits, items, _served_temperatures(config, logits, items)),
- "fitted_types": [],
- }
- head, relative, fitted = fit(everything)
- half = {row: i % 2 for i, row in enumerate(sorted({item["row"] for item in items}))}
- per_item = [head * common.clamp_temperature(relative[item["qtype"]]) for item in items]
- for side in (0, 1) if len(half) > 1 else ():
- side_head, side_relative, _ = fit(i for i in everything if half[items[i]["row"]] != side)
- for i in everything:
- if half[items[i]["row"]] == side:
- per_item[i] = side_head * common.clamp_temperature(side_relative[items[i]["qtype"]])
- config["head_temperature"] = head
- config["temperature"] = relative
- config.pop("temperature_by_options", None)
- return {**_metrics(logits, items, per_item), "fitted_types": sorted(fitted)}
-
-
-def _served_lengths(
- config: dict,
- positions: int,
- max_seq_length = None,
-) -> tuple:
- """(max_len, head_max_len) a Laya checkpoint serves with once loaded."""
- wanted = max_seq_length or max(int(config.get("max_len", 512)), TRAIN_MAX_LEN)
- max_len = min(int(positions), int(wanted))
- return max_len, min(max_len // 2, max(int(config.get("head_max_len", 192)), TRAIN_HEAD_MAX_LEN))
-
-
def save_pretrained_merged(
self,
save_directory,
@@ -1789,21 +1390,6 @@ def push_to_hub_merged(
# Decision models in Laya's rl_agent_config.json layout: any encoder plus a typed decision head.
-def _lm_subfolder(model_name, subfolder, token, revision, local_files_only) -> str:
- if Path(model_name).expanduser().is_dir():
- return str(Path(model_name).expanduser() / subfolder)
- from huggingface_hub import snapshot_download
-
- root = snapshot_download(
- model_name,
- allow_patterns = [f"{subfolder}/*"],
- token = token,
- revision = revision,
- local_files_only = local_files_only,
- )
- return str(Path(root) / subfolder)
-
-
class FastDecisionModel:
@staticmethod
def from_pretrained(
diff --git a/unsloth/models/decision_gguf.py b/unsloth/models/decision_gguf.py
index 3270520f543..07e023e4586 100644
--- a/unsloth/models/decision_gguf.py
+++ b/unsloth/models/decision_gguf.py
@@ -86,10 +86,10 @@ def _read_json(path: Path) -> dict:
def _layout(folder: Path) -> Optional[str]:
- from .decision import is_clef_checkpoint, is_decision_checkpoint
- if is_clef_checkpoint(folder):
+ from . import _decision_common as common
+ if common.is_clef_checkpoint(folder):
return "clef"
- return "laya" if is_decision_checkpoint(folder) else None
+ return "laya" if common.is_decision_checkpoint(folder) else None
def _base_config(
@@ -197,9 +197,9 @@ def effective_temperatures(config: dict, layout: str) -> dict:
"""The temperature PyTorch serving divides each question type's logits by
(decision._served_temperatures), keyed as llama.cpp reads them after
"<arch>.decision.temperature.": "<type>" and "<type>.<option-count bucket>"."""
- from .decision import _laya
+ from . import _decision_common as common
- clamp = _laya().common.clamp_temperature
+ clamp = common._laya().common.clamp_temperature
# Clef only: a head temperature _fold_temperature could not fold into the weights.
head = (
_positive(config.get("head_temperature", 1.0), "head_temperature")
@@ -587,11 +587,11 @@ def _write_export(output: Path, layout: str, files: dict, source_fingerprint: st
def _laya_max_head_tokens(folder: Path, config: dict) -> int:
# The converter writes the raw head_max_len; PyTorch serves FastDecisionModel's normalised one.
- from .decision import TRAIN_MAX_LEN, _served_lengths
+ from . import _decision_common as common
encoder = folder / "encoder" / "config.json"
positions = _read_json(encoder).get("max_position_embeddings") if encoder.is_file() else None
- return _served_lengths(config, positions or TRAIN_MAX_LEN)[1]
+ return common._served_lengths(config, positions or common.TRAIN_MAX_LEN)[1]
def export_decision_gguf(
diff --git a/unsloth/models/decision_mlx.py b/unsloth/models/decision_mlx.py
new file mode 100644
index 00000000000..f1b380180db
--- /dev/null
+++ b/unsloth/models/decision_mlx.py
@@ -0,0 +1,1032 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.
+
+# FastDecisionModel and DecisionTrainer on Apple Silicon, over unsloth-zoo's MLX decision models.
+# Loaded by path as unsloth._decision_mlx, because importing unsloth.models needs torch.
+
+__all__ = [
+ "FastDecisionModel",
+ "DecisionTrainer",
+]
+
+import copy
+import dataclasses
+import functools
+import importlib.util
+import json
+import random
+import sys
+import tempfile
+import types
+import warnings
+from collections import Counter
+from pathlib import Path
+from typing import Callable, Optional
+
+_common_spec = importlib.util.spec_from_file_location(
+ "unsloth._decision_common", Path(__file__).with_name("_decision_common.py")
+)
+sys.modules[_common_spec.name] = importlib.util.module_from_spec(_common_spec)
+_common_spec.loader.exec_module(sys.modules[_common_spec.name])
+from unsloth._decision_common import (
+ CLEF_MAX_LEN,
+ CLEF_SERVE_MAX_LEN,
+ DecisionDataError,
+ HOLDOUT_MAX,
+ QUESTION_TYPES,
+ TRAIN_MAX_LEN,
+ _ADAPTER_CONFIG,
+ _calibrate_clef,
+ _checkpoint_folder,
+ _clef_question,
+ _fit_temperatures,
+ _internal,
+ _is_plain_lm,
+ _laya,
+ _lm_subfolder,
+ _metrics,
+ _option_keys,
+ _parsed,
+ _predicted,
+ _served_lengths,
+ _served_temperatures,
+ _target,
+ _target_for,
+ is_clef_checkpoint,
+)
+
+
+def _decision_clef_items(rows, options: Callable, encode: Callable, validate, report, skip) -> list:
+ # One item per row. `options(question)` names a question's options in the head's order and
+ # `encode(state, questions)` returns the backend's tokenized fields, raising when they do not fit.
+ items = []
+ for index, row in enumerate(rows):
+ row = row if isinstance(row, dict) else {}
+ state = _parsed(row.get("state"))
+ questions = _parsed(row.get("questions"))
+ gold = _parsed(row["gold"] if row.get("gold") is not None else row.get("answers"))
+ if state is None or not isinstance(questions, dict) or not isinstance(gold, dict):
+ report["total"] += 1
+ skip(index, "needs state, questions and gold")
+ continue
+ kept, targets, labels = {}, [], []
+ for name, question in questions.items():
+ report["total"] += 1
+ if name not in gold:
+ skip(index, "has no gold", name)
+ continue
+ try:
+ if validate is not None:
+ validate(name, question)
+ clef_question = _clef_question(question)
+ keys = options(clef_question)
+ target, label = _target_for(clef_question["type"], keys, _parsed(gold[name]))
+ except (TypeError, ValueError, KeyError) as exc:
+ skip(index, str(exc) or "is not a valid question", name)
+ continue
+ kept[str(name)], targets, labels = (
+ clef_question,
+ targets + [target],
+ labels + [label],
+ )
+ if not kept:
+ continue
+ try:
+ encoded = encode(state, kept)
+ except (TypeError, ValueError) as exc:
+ for name in kept:
+ skip(index, f"does not fit: {exc}", name)
+ continue
+ items.append(
+ {
+ **encoded,
+ "targets": targets,
+ "labels": labels,
+ "row": index,
+ "source": {"state": state, "questions": kept},
+ }
+ )
+ return items
+
+
+def _decision_dataset(
+ rows,
+ tokenizer,
+ config: dict,
+ validate: Optional[Callable[[str, dict], None]] = None,
+ clef: Optional[Callable] = None,
+) -> tuple:
+ # `clef` builds a Clef model's items: the backend's (rows, tokenizer, max_len, validate, report, skip).
+ max_len = int(config.get("max_len", 512))
+ head_max_len = int(config.get("head_max_len", 192))
+ items, report, skips = [], {"total": 0, "skipped": 0, "reason": None, "truncated": 0}, {}
+
+ def skip(
+ index,
+ reason,
+ name = None,
+ ):
+ report["skipped"] += 1
+ where = f"row {index + 1}" if name is None else f'row {index + 1}: "{name}"'
+ skips.setdefault(reason, [0, f"{where} {reason}"])[0] += 1
+
+ if clef is not None:
+ items = clef(rows, tokenizer, max_len, validate, report, skip)
+ rows = ()
+ else:
+ common = _laya().common
+ for index, row in enumerate(rows):
+ row = row if isinstance(row, dict) else {}
+ state = _parsed(row.get("state"))
+ questions = _parsed(row.get("questions"))
+ gold = _parsed(row["gold"] if row.get("gold") is not None else row.get("answers"))
+ if state is None or not isinstance(questions, dict) or not isinstance(gold, dict):
+ report["total"] += 1
+ skip(index, "needs state, questions and gold")
+ continue
+ for name, question in questions.items():
+ report["total"] += 1
+ if name not in gold:
+ skip(index, "has no gold", name)
+ continue
+ try:
+ if validate is not None:
+ validate(name, question)
+ internal = _internal(question)
+ target, label = _target(internal, _parsed(gold[name]))
+ ids, markers = common.build_sequence(
+ tokenizer, state, internal, max_len, head_max_len
+ )
+ except (TypeError, ValueError) as exc:
+ skip(index, str(exc), name)
+ continue
+ if len(markers) != len(target):
+ skip(index, f"options exceed the {max_len}-token context", name)
+ continue
+ items.append(
+ {
+ "input_ids": ids,
+ "markers": markers,
+ "qtype": common.QTYPES[internal["t"]],
+ "target": target,
+ "label": label,
+ "row": index,
+ }
+ )
+ if skips:
+ # The most common reason, shown with the first decision it applied to.
+ count, example = max(skips.values(), key = lambda skipped: skipped[0])
+ report["reason"] = example if count == 1 else f"{example} (and {count - 1:,} more like it)"
+ # Over max_seq_length the end of the state is cut, never questions or options.
+ report["truncated"] = sum(len(item["input_ids"]) >= max_len for item in items)
+ if report["truncated"]:
+ print(
+ f"Unsloth: {report['truncated']:,} of {len(items):,} training inputs are longer than "
+ f"max_seq_length = {max_len}, so the end of their state is cut. Raise "
+ "max_seq_length to train on all of it."
+ )
+ return items, report
+
+
+def _decision_holdout(
+ items: list,
+ seed: int = 3407,
+ fraction: float = 0.1,
+ max_items: int = HOLDOUT_MAX,
+):
+ # Counted in decisions: a Clef item holds every question of its row.
+ sizes = Counter()
+ for item in items:
+ sizes[item["row"]] += len(item.get("labels", (None,)))
+ target = min(max_items, int(sum(sizes.values()) * fraction))
+ rows = sorted(sizes)
+ random.Random(seed).shuffle(rows)
+ held, count = set(), 0
+ # Whole rows that still fit under the target; the last row always stays in training.
+ for row in rows[:-1]:
+ if count + sizes[row] <= target:
+ held.add(row)
+ count += sizes[row]
+ return (
+ [item for item in items if item["row"] not in held],
+ [item for item in items if item["row"] in held],
+ )
+
+
+def _decision_evaluation(config: dict, logits, items: list) -> dict:
+ return _metrics(logits, items, _served_temperatures(config, logits, items))
+
+
+def _decision_calibration(
+ config: dict,
+ logits,
+ items: list,
+ clef: bool = False,
+) -> dict:
+ common = _laya().common
+ fallback = [common.clamp_temperature(t) for t in config.get("temperature", [1.0] * 3)]
+ if clef:
+ return _calibrate_clef(config, logits, items)
+ everything = range(len(items))
+ temperature, fitted = _fit_temperatures(logits, items, everything, fallback)
+ # Reported numbers score each half of the rows with temperatures fitted on the other half.
+ half = {row: i % 2 for i, row in enumerate(sorted({item["row"] for item in items}))}
+ per_item = [1.0] * len(items)
+ for side in (0, 1):
+ other = [i for i in everything if half[items[i]["row"]] != side]
+ side_temperature, _ = _fit_temperatures(logits, items, other, fallback)
+ for i in everything:
+ if half[items[i]["row"]] == side:
+ per_item[i] = side_temperature[items[i]["qtype"]]
+ config["temperature"] = temperature
+ buckets = {
+ key: value
+ for key, value in (config.pop("temperature_by_options", None) or {}).items()
+ if common.QTYPES.get(key.split(":")[0]) not in fitted
+ }
+ if buckets:
+ config["temperature_by_options"] = buckets
+ return {**_metrics(logits, items, per_item), "fitted_types": sorted(fitted)}
+
+
+# PEFT options the MLX adapters have no counterpart for, with the value that leaves each one off.
+_DECISION_UNSUPPORTED_LORA = {
+ "bias": "none",
+ "layers_to_transform": None,
+ "layers_pattern": None,
+ "use_dora": False,
+ "modules_to_save": None,
+ "init_lora_weights": True,
+}
+
+# Training arguments that change what is trained and that the MLX trainer does not implement.
+_DECISION_UNSUPPORTED_ARGUMENTS = ("optim_args", "auto_find_batch_size")
+
+# The MLX trainer for language models takes these; this trainer has no counterpart for them.
+_DECISION_UNUSED = {"neftune_noise_alpha", "push_to_hub"}
+
+# Read by the MLX decision trainer without a field in the MLX config, or set by transformers itself.
+_DECISION_QUIET_ARGUMENTS = (
+ "do_eval",
+ "do_train",
+ "logging_dir",
+ "run_name",
+ "label_names",
+ "label_smoothing_factor",
+ "eval_delay",
+ "logging_first_step",
+ "dataloader_drop_last",
+)
+
+# What the torch DecisionTrainer takes beyond transformers' own arguments, and the MLX trainer too.
+_DECISION_TRAINER_OPTIONS = (
+ "brier_weight",
+ "ordinal_weight",
+ "kl_weight",
+ "permute_fields",
+ "compute_metrics",
+ "preprocess_logits_for_metrics",
+)
+
+# Defaults for training a Clef, as the torch DecisionTrainer's.
+CLEF_RECIPE = {}
+
+
[email protected]_cache(maxsize = None)
+def _decision_zoo():
+ # The vendored Laya and Clef code scores with torch, which unsloth-zoo leaves out on Apple Silicon.
+ if importlib.util.find_spec("torch") is None:
+ raise ImportError(
+ "Unsloth: decision models on MLX need PyTorch. Install it with `pip install torch`."
+ )
+ try:
+ from unsloth_zoo.mlx import decision
+ from unsloth_zoo.mlx.trainer import MLXDecisionTrainer
+ decision.load_language_model_as_clef
+ except (ImportError, AttributeError) as error:
+ raise ImportError(
+ "Unsloth: training decision models on MLX needs a newer unsloth-zoo. "
+ "Upgrade with `pip install -U unsloth-zoo`."
+ ) from error
+ return types.SimpleNamespace(MLXDecisionTrainer = MLXDecisionTrainer, **vars(decision))
+
+
+def _is_clef(model) -> bool:
+ return getattr(model, "is_clef", False)
+
+
+def _decision_annotate(model, **attributes):
+ # Plain attributes: an mlx module would otherwise hold them as part of its state.
+ for name, value in attributes.items():
+ object.__setattr__(model, name, value)
+ model.save_pretrained_merged = types.MethodType(_decision_save_merged, model)
+ model.push_to_hub_merged = types.MethodType(_decision_push_merged, model)
+ if _is_clef(model):
+ model.save_pretrained = types.MethodType(_clef_save, model)
+ model.push_to_hub = types.MethodType(_clef_push, model)
+ model.save_pretrained_gguf = types.MethodType(_decision_save_gguf, model)
+ model.push_to_hub_gguf = types.MethodType(_decision_gguf().push_to_hub_gguf, model)
+ return model
+
+
+def _clef_save(
+ self,
+ save_directory,
+ tokenizer = None,
+ **kwargs,
+) -> None:
+ # Adapters plus the head, as Unsloth's other models; a full finetune has none, so it saves merged.
+ if not getattr(self, "_unsloth_lora", False):
+ return self.save_pretrained_merged(save_directory, tokenizer)
+ config = {**self.decision_config, "fine_tuned": True}
+ _decision_zoo().save_clef_adapter(
+ self._unsloth_pipeline,
+ save_directory,
+ self._unsloth_source,
+ config["base_model"],
+ config.get("base_revision"),
+ config,
+ )
+
+
+def _clef_push(
+ self,
+ repo_id,
+ tokenizer = None,
+ token = None,
+ private = None,
+ **kwargs,
+) -> None:
+ from huggingface_hub import HfApi
+
+ api = HfApi(token = token)
+ repo_id = api.create_repo(repo_id, private = private, exist_ok = True).repo_id
+ with tempfile.TemporaryDirectory() as folder:
+ self.save_pretrained(folder, tokenizer)
+ api.upload_folder(folder_path = folder, repo_id = repo_id)
+ print(f"Unsloth: Saved the decision model to https://huggingface.co/{repo_id}")
+
+
[email protected]_cache(maxsize = None)
+def _decision_gguf():
+ # By path: the exporter runs llama.cpp's converter in a subprocess, and unsloth.models needs torch.
+ spec = importlib.util.spec_from_file_location(
+ "unsloth._decision_gguf", Path(__file__).with_name("decision_gguf.py")
+ )
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+def _decision_save_gguf(
+ self,
+ save_directory,
+ tokenizer = None,
+ quantization_method = "q8_0",
+ source_folder = None,
+ print_output = False,
+ **kwargs,
+) -> dict:
+ """GGUF for llama.cpp's decision server in <save_directory>/gguf, from a temporary merged save."""
+ gguf = _decision_gguf()
+ # Fail before the merge when llama.cpp cannot convert.
+ gguf._converter_dir(print_output)
+ output = Path(save_directory)
+ output.mkdir(parents = True, exist_ok = True)
+ gguf._remove_abandoned_temp(output)
+ prefix = gguf._temp_prefix(".unsloth-merged-")
+ with (
+ gguf._exit_on_sigterm(),
+ tempfile.TemporaryDirectory(prefix = prefix, dir = output) as merged,
+ ):
+ self.save_pretrained_merged(merged, tokenizer)
+ return gguf.export_decision_gguf(
+ merged,
+ quantization_method,
+ output_dir = output / gguf._contract().EXPORT_DIR,
+ source_folder = source_folder,
+ print_output = print_output,
+ )
+
+
+def _decision_pad_token_id(tokenizer) -> int:
+ return getattr(tokenizer, "tokenizer", tokenizer).pad_token_id
+
+
+def _clef_items(pipeline, rows, tokenizer, max_len, validate, report, skip) -> list:
+ zoo = _decision_zoo()
+ return _decision_clef_items(
+ rows,
+ functools.partial(zoo.clef_option_keys, pipeline),
+ lambda state, questions: zoo.clef_training_item(pipeline, state, questions, max_len),
+ validate,
+ report,
+ skip,
+ )
+
+
+def _decision_logits(model, tokenizer, items: list) -> tuple:
+ import torch
+
+ # Torch rows, so both backends score and calibrate with the same code.
+ if not _is_clef(model):
+ rows = _decision_zoo().decision_logits(model, items, _decision_pad_token_id(tokenizer))
+ return [torch.from_numpy(row) for row in rows], items
+ # One Laya-shaped item per question for the shared metrics.
+ logits, questions = [], []
+ for item, rows in zip(items, _decision_zoo().clef_logits(model, items)):
+ kinds = [question["type"] for question in item["source"]["questions"].values()]
+ for row, target, label, kind in zip(rows, item["targets"], item["labels"], kinds):
+ logits.append(torch.from_numpy(row))
+ questions.append(
+ {
+ "target": target,
+ "label": label,
+ "qtype": QUESTION_TYPES.index(kind),
+ "row": item["row"],
+ }
+ )
+ return logits, questions
+
+
+def _decision_save_merged(
+ self,
+ save_directory,
+ tokenizer = None,
+ save_method = "merged_16bit",
+ **kwargs,
+) -> None:
+ if save_method != "merged_16bit":
+ raise NotImplementedError(
+ f"Unsloth: decision models are saved merged in 16-bit, not as {save_method!r}."
+ )
+ # The tokenizer is the checkpoint's own, which the savers copy from the source.
+ config = {**self.decision_config, "fine_tuned": True}
+ # The Clef saver writes the weights that train, so a frozen backbone is saved as trained before it was frozen.
+ frozen = getattr(self, "_unsloth_frozen_backbone", ())
+ FastDecisionModel.unfreeze_backbone(self)
+ try:
+ if _is_clef(self):
+ _decision_zoo().save_clef_model(
+ self._unsloth_pipeline, save_directory, self._unsloth_source, config
+ )
+ else:
+ _decision_zoo().save_decision_model(self, save_directory, self._unsloth_source, config)
+ finally:
+ if frozen:
+ FastDecisionModel.freeze_backbone(self)
+
+
+def _decision_push_merged(
+ self,
+ repo_id,
+ tokenizer = None,
+ save_method = "merged_16bit",
+ token = None,
+ private = None,
+ **kwargs,
+) -> None:
+ from huggingface_hub import HfApi
+
+ api = HfApi(token = token)
+ repo_id = api.create_repo(repo_id, private = private, exist_ok = True).repo_id
+ with tempfile.TemporaryDirectory() as folder:
+ self.save_pretrained_merged(folder, tokenizer, save_method)
+ api.upload_folder(folder_path = folder, repo_id = repo_id)
+ print(f"Unsloth: Saved the decision model to https://huggingface.co/{repo_id}")
+
+
+_CLEF_ATTRIBUTES = (
+ "decision_config",
+ "is_clef",
+ "_unsloth_pipeline",
+ "_unsloth_source",
+ "_unsloth_full_finetuning",
+ "_saved_temp_tokenizer",
+)
+
+
+def _clef_network(pipeline, folder, config, full_finetuning, gradient_checkpointing):
+ zoo = _decision_zoo()
+ # A checkpoint saved as adapters comes with them, and they go on training.
+ adapters = hasattr(pipeline, "base_folder")
+ if full_finetuning or adapters:
+ network = zoo.clef_training_network(
+ pipeline,
+ full_finetuning = bool(full_finetuning),
+ gradient_checkpointing = gradient_checkpointing,
+ )
+ else:
+ # Until get_peft_model adds adapters, only the joint head trains.
+ pipeline.model.freeze()
+ pipeline.head.unfreeze()
+ network = zoo.ClefNetwork(pipeline, gradient_checkpointing)
+ network.train()
+ _decision_annotate(
+ network,
+ decision_config = config,
+ is_clef = True,
+ _unsloth_pipeline = pipeline,
+ _unsloth_source = getattr(pipeline, "base_folder", folder),
+ _unsloth_full_finetuning = bool(full_finetuning),
+ _saved_temp_tokenizer = pipeline.tokenizer,
+ _unsloth_lora = adapters,
+ )
+ return network, pipeline.tokenizer
+
+
+def _load_clef(
+ folder, max_seq_length, load_in_4bit, full_finetuning, token, gradient_checkpointing, name
+):
+ if full_finetuning and (folder / _ADAPTER_CONFIG).is_file():
+ # As on torch: the adapters would be saved without the base weights the run trained.
+ raise ValueError(
+ f"Unsloth: {folder} holds LoRA adapters. Save it with save_pretrained_merged and "
+ "full finetune the merged folder instead."
+ )
+ # A 4-bit decoder trains through LoRA adapters only.
+ pipeline = _decision_zoo().load_decision_model(
+ folder, token = token, load_in_4bit = bool(load_in_4bit) and not full_finetuning
+ )
+ max_len = int(max_seq_length or CLEF_MAX_LEN)
+ config = {"layout": "clef", "max_len": max_len, "temperature": [1.0] * 3}
+ saved = folder / "unsloth_decision_config.json"
+ if saved.is_file():
+ config.update(json.loads(saved.read_text(encoding = "utf-8")), max_len = max_len)
+ # The parent run's training record does not describe the next fine-tune, as for Laya.
+ config.pop("training", None)
+ if hasattr(pipeline, "base_folder"):
+ # Adapters stay over the base they were trained on.
+ adapter = json.loads((folder / _ADAPTER_CONFIG).read_text(encoding = "utf-8"))
+ config.setdefault("base_model", adapter["base_model_name_or_path"])
+ if adapter.get("revision"):
+ config.setdefault("base_revision", adapter["revision"])
+ else:
+ # A merged checkpoint is its own base, whatever model it once started from.
+ config.pop("base_revision", None)
+ config.update(name)
+ return _clef_network(pipeline, folder, config, full_finetuning, gradient_checkpointing)
+
+
+def _load_lm_as_clef(
+ model_name,
+ max_seq_length,
+ load_in_4bit,
+ full_finetuning,
+ token,
+ revision,
+ local_files_only,
+ gradient_checkpointing,
+ random_state,
+ decision_head = "clef",
+ head_width = None,
+ head_config = None,
+ **kwargs,
+):
+ # A plain language model plus a new joint schema head, as unsloth/models/decision_from_lm.py builds one.
+ if decision_head != "clef":
+ raise ValueError(f"Unsloth: decision_head must be one of ('clef',), not {decision_head!r}.")
+ if kwargs:
+ raise NotImplementedError(
+ f"Unsloth: decision models on MLX do not support {', '.join(sorted(kwargs))}."
+ )
+ folder = Path(str(model_name)).expanduser()
+ if not folder.is_dir():
+ from huggingface_hub import snapshot_download
+ folder = Path(
+ snapshot_download(
+ str(model_name),
+ token = token,
+ revision = revision,
+ local_files_only = local_files_only,
+ )
+ )
+ if not (folder / "config.json").is_file():
+ raise NotImplementedError(
+ f"Unsloth: {folder} holds LoRA adapters over a base model, which MLX does not load. "
+ "Merge them into the base model first."
+ )
+ load_in_4bit = bool(load_in_4bit) and not full_finetuning
+ pipeline = _decision_zoo().load_language_model_as_clef(
+ folder,
+ head_width = head_width,
+ head_config = head_config,
+ seed = random_state,
+ token = token,
+ load_in_4bit = load_in_4bit,
+ )
+ config = {
+ "layout": "clef",
+ "max_len": int(max_seq_length or CLEF_MAX_LEN),
+ "temperature": [1.0] * 3,
+ "base_model": str(model_name),
+ **({"base_revision": revision} if revision else {}),
+ "load_in_4bit": load_in_4bit,
+ }
+ return _clef_network(pipeline, folder, config, full_finetuning, gradient_checkpointing)
+
+
+class FastDecisionModel:
+ @staticmethod
+ def from_pretrained(
+ model_name: str,
+ subfolder: Optional[str] = None,
+ max_seq_length: Optional[int] = None,
+ dtype = None,
+ load_in_4bit: bool = False,
+ load_in_8bit: bool = False,
+ full_finetuning: bool = False,
+ token: Optional[str] = None,
+ revision: Optional[str] = None,
+ local_files_only: bool = False,
+ use_gradient_checkpointing = "unsloth",
+ random_state: int = 3407,
+ **kwargs,
+ ):
+ if load_in_8bit:
+ raise NotImplementedError("Unsloth: decision models do not support load_in_8bit.")
+ checkpointing = bool(use_gradient_checkpointing)
+ if kwargs.get("decision_head") is None and _is_plain_lm(
+ model_name, subfolder, token, revision, local_files_only
+ ):
+ kwargs["decision_head"] = "clef"
+ lm = kwargs.get("decision_head") is not None
+ if not lm:
+ folder = _checkpoint_folder(model_name, subfolder, token, revision, local_files_only)
+ if (lm or is_clef_checkpoint(folder)) and dtype is not None:
+ raise NotImplementedError(
+ f"Unsloth: Clef on MLX trains at its checkpoint's precision, not {dtype}."
+ )
+ if lm:
+ if subfolder:
+ model_name = _lm_subfolder(model_name, subfolder, token, revision, local_files_only)
+ return _load_lm_as_clef(
+ model_name,
+ max_seq_length,
+ load_in_4bit,
+ full_finetuning,
+ token,
+ revision,
+ local_files_only,
+ checkpointing,
+ random_state,
+ **kwargs,
+ )
+ if is_clef_checkpoint(folder):
+ name = {
+ "base_model": str(model_name),
+ **({"base_revision": revision} if revision else {}),
+ }
+ return _load_clef(
+ folder,
+ max_seq_length,
+ load_in_4bit,
+ full_finetuning,
+ token,
+ checkpointing,
+ name,
+ )
+ if load_in_4bit:
+ raise NotImplementedError(
+ "Unsloth: Laya decision models train in 16-bit, so load_in_4bit is not supported."
+ )
+ if not (full_finetuning or dtype is None or str(dtype).rsplit(".", 1)[-1] == "float16"):
+ raise NotImplementedError(
+ f"Unsloth: decision models on MLX keep the frozen encoder in float16, not {dtype}."
+ )
+ from transformers import AutoTokenizer
+
+ config = json.loads((folder / "rl_agent_config.json").read_text(encoding = "utf-8"))
+ # The base model's training record does not describe the fine-tune.
+ config.pop("training", None)
+ encoder = json.loads((folder / "encoder" / "config.json").read_text(encoding = "utf-8"))
+ config["max_len"], config["head_max_len"] = _served_lengths(
+ config, int(encoder.get("max_position_embeddings", TRAIN_MAX_LEN)), max_seq_length
+ )
+ tokenizer = AutoTokenizer.from_pretrained(str(folder / "tokenizer"))
+ model = _decision_zoo().load_trainable_decision_model(
+ folder, full_finetuning, gradient_checkpointing = checkpointing
+ )
+ _decision_annotate(
+ model,
+ decision_config = config,
+ _unsloth_source = folder,
+ _unsloth_full_finetuning = bool(full_finetuning),
+ _saved_temp_tokenizer = tokenizer,
+ )
+ return model, tokenizer
+
+ @staticmethod
+ def get_peft_model(
+ model,
+ r = 64,
+ target_modules = "all-linear",
+ lora_alpha = 64,
+ lora_dropout = 0.0,
+ bias = "none",
+ layers_to_transform = None,
+ layers_pattern = None,
+ use_gradient_checkpointing = "unsloth",
+ random_state = 3407,
+ max_seq_length = None,
+ use_rslora = False,
+ use_dora = False,
+ modules_to_save = None,
+ init_lora_weights = True,
+ loftq_config = {},
+ **kwargs,
+ ):
+ if getattr(model, "_unsloth_full_finetuning", False):
+ print("Unsloth: Full finetuning is enabled, so .get_peft_model has no effect")
+ return model
+ given = {**locals(), **kwargs}
+ unsupported = [
+ name for name, off in _DECISION_UNSUPPORTED_LORA.items() if given[name] != off
+ ]
+ unsupported += ["loftq_config"] if loftq_config else []
+ unsupported += sorted(kwargs)
+ if unsupported:
+ raise NotImplementedError(
+ f"Unsloth: decision models on MLX do not support {', '.join(unsupported)}."
+ )
+ if _is_clef(model):
+ if getattr(model, "_unsloth_lora", False):
+ raise RuntimeError("Unsloth: You already added LoRA adapters to your model!")
+ network = _decision_zoo().clef_training_network(
+ model._unsloth_pipeline,
+ r = r,
+ lora_alpha = lora_alpha,
+ lora_dropout = lora_dropout,
+ use_rslora = use_rslora,
+ target_modules = target_modules,
+ random_state = random_state,
+ gradient_checkpointing = bool(use_gradient_checkpointing),
+ )
+ attributes = {name: getattr(model, name) for name in _CLEF_ATTRIBUTES}
+ return _decision_annotate(network, **attributes, _unsloth_lora = True)
+ _decision_zoo().add_lora_adapters(
+ model,
+ r = r,
+ lora_alpha = lora_alpha,
+ lora_dropout = lora_dropout,
+ use_rslora = use_rslora,
+ target_modules = target_modules,
+ random_state = random_state,
+ )
+ model.gradient_checkpointing = bool(use_gradient_checkpointing)
+ return model
+
+ @staticmethod
+ def freeze_backbone(model):
+ # Head-only warm-up for a fresh decision head; undo with unfreeze_backbone.
+ from mlx.utils import tree_flatten
+
+ frozen = [name for name, _ in tree_flatten(model.encoder.trainable_parameters())]
+ model.encoder.freeze()
+ object.__setattr__(model, "_unsloth_frozen_backbone", frozen)
+ return model
+
+ @staticmethod
+ def unfreeze_backbone(model):
+ names = set(getattr(model, "_unsloth_frozen_backbone", ()))
+ for path, module in model.encoder.named_modules():
+ keys = [key for key in module if f"{path}.{key}".lstrip(".") in names]
+ if keys:
+ module.unfreeze(recurse = False, keys = keys)
+ object.__setattr__(model, "_unsloth_frozen_backbone", ())
+ return model
+
+ @staticmethod
+ def for_inference(model):
+ model.eval()
+ return model
+
+ @staticmethod
+ def for_training(model, use_gradient_checkpointing = True):
+ model.train()
+ if not _is_clef(model):
+ model.gradient_checkpointing = bool(use_gradient_checkpointing)
+ return model
+
+ @staticmethod
+ def build_dataset(
+ rows,
+ tokenizer,
+ model,
+ validate: Optional[Callable[[str, dict], None]] = None,
+ ) -> tuple:
+ clef = functools.partial(_clef_items, model._unsloth_pipeline) if _is_clef(model) else None
+ return _decision_dataset(rows, tokenizer, model.decision_config, validate, clef)
+
+ split_holdout = staticmethod(_decision_holdout)
+
+ @staticmethod
+ def predict(model, tokenizer, state, questions: dict) -> dict:
+ """Answers one Decision API request: {name: answer} at the calibrated temperatures.
+ Each answer is the Decision API's (choice / confidence, score / legend, or noul) plus
+ "answer" (the option, True / False for noul, the level number for score) and
+ "probabilities" over every option."""
+ import torch
+
+ from unsloth._vendor.clef.joint_schema_model import systemone_answer
+
+ if not isinstance(questions, dict) or not questions:
+ raise DecisionDataError("questions must be a non-empty dict of name to question")
+ state, config, zoo = _parsed(state), model.decision_config, _decision_zoo()
+ if _is_clef(model):
+ pipeline = model._unsloth_pipeline
+ questions = {str(name): _clef_question(q) for name, q in questions.items()}
+ # Read up to CLEF_SERVE_MAX_LEN tokens, like serving, even past the training cut.
+ max_length = max(int(config.get("max_len", CLEF_MAX_LEN)), CLEF_SERVE_MAX_LEN)
+ item = zoo.clef_training_item(pipeline, state, questions, max_length)
+ logits = zoo.clef_logits(model, [item])[0]
+ keys = [zoo.clef_option_keys(pipeline, q) for q in questions.values()]
+ kinds = [QUESTION_TYPES.index(q["type"]) for q in questions.values()]
+ else:
+ common, max_len = _laya().common, int(config.get("max_len", 512))
+ tokenizer = getattr(tokenizer, "tokenizer", tokenizer)
+ items, keys = [], []
+ for name, question in questions.items():
+ internal = _internal(question)
+ ids, markers = common.build_sequence(
+ tokenizer, state, internal, max_len, int(config.get("head_max_len", 192))
+ )
+ keys.append(_option_keys(internal))
+ if len(markers) != len(keys[-1]):
+ raise DecisionDataError(
+ f'"{name}" has more options than fit in {max_len} tokens'
+ )
+ items.append(
+ {
+ "input_ids": ids,
+ "markers": markers,
+ "qtype": common.QTYPES[internal["t"]],
+ "target": [0.0] * len(markers),
+ }
+ )
+ logits = zoo.decision_logits(model, items, tokenizer.pad_token_id)
+ kinds = [item["qtype"] for item in items]
+ logits = [torch.from_numpy(row) for row in logits]
+ scales = _served_temperatures(config, logits, [{"qtype": kind} for kind in kinds])
+ answers = {}
+ for (name, question), row, scale, options in zip(questions.items(), logits, scales, keys):
+ probabilities = dict(zip(options, torch.softmax(row / scale, -1).tolist()))
+ answers[name] = _predicted(
+ question, systemone_answer(question, probabilities), probabilities
+ )
+ return answers
+
+ # batch_size is the torch call shape; MLX scores Clef a record at a time and Laya in its own batches.
+ @staticmethod
+ def evaluate(
+ model,
+ tokenizer,
+ items: list,
+ batch_size = None,
+ ) -> dict:
+ logits, items = _decision_logits(model, tokenizer, items)
+ return _decision_evaluation(model.decision_config, logits, items)
+
+ @staticmethod
+ def calibrate(
+ model,
+ tokenizer,
+ items: list,
+ batch_size = None,
+ ) -> dict:
+ logits, items = _decision_logits(model, tokenizer, items)
+ return _decision_calibration(model.decision_config, logits, items, _is_clef(model))
+
+
+def _decision_arguments(args):
+ from unsloth import _MLX_ALLOWED_EXTRA_ARGUMENTS, _mlx_training_argument_values
+ from unsloth_zoo.mlx.trainer import MLXTrainingConfig
+
+ if args is None:
+ # The torch trainer's default: three epochs, no evaluation schedule.
+ from transformers import TrainingArguments
+ args = TrainingArguments(output_dir = "tmp_trainer")
+ given, checkpointing = args, None
+ if isinstance(args, MLXTrainingConfig):
+ args = copy.copy(args)
+ else:
+ # transformers.TrainingArguments, as the torch DecisionTrainer takes.
+ checkpointing = bool(getattr(args, "gradient_checkpointing", False)) or None
+ fields = {field.name for field in dataclasses.fields(MLXTrainingConfig)}
+ values = _mlx_training_argument_values(args)
+ args = MLXTrainingConfig(**{k: v for k, v in values.items() if k in fields})
+ if dataclasses.is_dataclass(given):
+ # Whatever else differs from the defaults has no MLX counterpart.
+ default, quiet = (
+ type(given)(output_dir = given.output_dir),
+ {*fields, *_DECISION_QUIET_ARGUMENTS, *_DECISION_UNSUPPORTED_ARGUMENTS},
+ )
+ ignored = [
+ field.name
+ for field in dataclasses.fields(given)
+ if field.name not in (quiet | _MLX_ALLOWED_EXTRA_ARGUMENTS) - _DECISION_UNUSED
+ and getattr(given, field.name) != getattr(default, field.name)
+ ]
+ if ignored:
+ warnings.warn(
+ f"Unsloth: DecisionTrainer on MLX ignores {', '.join(sorted(ignored))}."
+ )
+ # The MLX trainer and transformers callbacks read arguments the MLX config has no field for.
+ for name, value in vars(given).items():
+ if not (name.startswith("_") or hasattr(args, name)):
+ setattr(args, name, value)
+ unsupported = [name for name in _DECISION_UNSUPPORTED_ARGUMENTS if getattr(given, name, None)]
+ saving = getattr(given, "save_strategy", None)
+ if str(getattr(saving, "value", saving)).lower() == "best":
+ unsupported.append('save_strategy = "best"')
+ if unsupported:
+ raise NotImplementedError(
+ f"Unsloth: DecisionTrainer on MLX does not support {', '.join(unsupported)}."
+ )
+ return args, checkpointing
+
+
+class DecisionTrainer:
+ """The MLX decision trainer behind the torch DecisionTrainer's arguments.
+
+ Everything else, such as `train(resume_from_checkpoint = ...)`, `evaluate` and `predict`,
+ is the MLX trainer's own.
+ """
+
+ def __init__(
+ self,
+ model = None,
+ args = None,
+ train_dataset = None,
+ eval_dataset = None,
+ *,
+ head_learning_rate: Optional[float] = None,
+ tokenizer = None,
+ label_smoothing: Optional[float] = None,
+ callbacks = None,
+ processing_class = None,
+ **kwargs,
+ ):
+ unknown = sorted(set(kwargs) - set(_DECISION_TRAINER_OPTIONS))
+ if unknown:
+ raise NotImplementedError(
+ f"Unsloth: DecisionTrainer on MLX does not support {', '.join(unknown)}."
+ )
+ args, gradient_checkpointing = _decision_arguments(args)
+ clef = _is_clef(model)
+ recipe = CLEF_RECIPE if clef else {}
+ if label_smoothing is None:
+ label_smoothing = getattr(args, "label_smoothing_factor", 0.0) or recipe.get(
+ "label_smoothing", 0.0
+ )
+ options = {name: recipe[name] for name in _DECISION_TRAINER_OPTIONS if name in recipe}
+ options.update({name: value for name, value in kwargs.items() if value is not None})
+ preprocess = options.get("preprocess_logits_for_metrics")
+ if preprocess is not None:
+ import torch
+
+ # The hook is written for the torch trainer, which hands it tensors.
+ options["preprocess_logits_for_metrics"] = lambda logits, labels: preprocess(
+ torch.from_numpy(logits), torch.from_numpy(labels)
+ )
+ if gradient_checkpointing and not clef:
+ model.gradient_checkpointing = True
+ if clef and getattr(model, "_unsloth_lora", False):
+ # Lets a checkpoint be written as the adapters save_pretrained writes.
+ config = model.decision_config
+ origin = (
+ model._unsloth_source,
+ config["base_model"],
+ config.get("base_revision"),
+ config,
+ )
+ object.__setattr__(model, "_origin", origin)
+ if clef and options.get("permute_fields") and train_dataset is not None:
+ # A record is encoded again in its new order, to the length it was built for.
+ length = model.decision_config["max_len"]
+ train_dataset = [
+ {**item, "source": {**item["source"], "max_length": length}}
+ if "source" in item
+ else item
+ for item in train_dataset
+ ]
+ processing_class = tokenizer if processing_class is None else processing_class
+ if processing_class is None:
+ processing_class = model._saved_temp_tokenizer
+ self._trainer = _decision_zoo().MLXDecisionTrainer(
+ model,
+ args,
+ train_dataset,
+ eval_dataset,
+ pad_token_id = _decision_pad_token_id(processing_class),
+ head_learning_rate = head_learning_rate,
+ callbacks = callbacks,
+ processing_class = processing_class,
+ label_smoothing = float(label_smoothing or 0.0),
+ **options,
+ )
+
+ def __getattr__(self, name):
+ if name == "_trainer":
+ raise AttributeError(name)
+ return getattr(self._trainer, name)