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.

Studio: surface an MLX completion-masking miss as a warning, not a status line (#8133)

BardiaKoopah6fd4e9a2af36
diff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.py
index 40453b5c022..4c4d2a134c8 100644
--- a/studio/backend/core/training/worker.py
+++ b/studio/backend/core/training/worker.py
@@ -2839,13 +2839,26 @@ def _run_mlx_training(event_queue, stop_queue, config):
# No catch: the helper handles detection failures and double misses, so an exception here
# is a real masking failure that must fail the run, not silently train full sequences.
from utils.datasets.completion_masking import apply_completion_masking
- trainer, _masking_applied = apply_completion_masking(
+
+ trainer, masking_applied = apply_completion_masking(
trainer,
model_name,
train_on_responses_only,
notify = lambda level, message: _send("status", status_message = message),
dataset_template = "alpaca" if dataset_final_format == "alpaca" else None,
)
+ if not masking_applied:
+ # A miss changes the training objective for the whole run, so it belongs in the
+ # sticky warning list the eval-split fallback already uses, not a status line
+ # that scrolls past. Recovered detection failures stay status: masking applied.
+ _send(
+ "warning",
+ message = (
+ f"'Train on completions' could not be applied for {model_name}: no "
+ f"instruction/response markers were found. Training will run on full "
+ f"sequences (prompts included)."
+ ),
+ )
# ── 8. Setup wandb / tensorboard ──
wandb_run = None
diff --git a/studio/backend/tests/test_mlx_training_worker_config.py b/studio/backend/tests/test_mlx_training_worker_config.py
index a121fd8c160..bd881ef6ff4 100644
--- a/studio/backend/tests/test_mlx_training_worker_config.py
+++ b/studio/backend/tests/test_mlx_training_worker_config.py
@@ -1,7 +1,10 @@
# SPDX-License-Identifier: AGPL-3.0-only
+import ast
import importlib.util
+import inspect
import sys
+import textwrap
import types
from pathlib import Path
@@ -15,6 +18,7 @@ def _load_worker_module():
"utils",
"utils.child_stdio",
"utils.hardware",
+ "utils.hf_dataset_options",
"utils.training_runs",
"utils.wheel_utils",
)
@@ -39,6 +43,10 @@ def _load_worker_module():
hardware.apply_gpu_ids = lambda *_args, **_kwargs: None
sys.modules["utils.hardware"] = hardware
+ hf_dataset_options = types.ModuleType("utils.hf_dataset_options")
+ hf_dataset_options.hf_dataset_split_instruction_names = lambda *_args, **_kwargs: ()
+ sys.modules["utils.hf_dataset_options"] = hf_dataset_options
+
training_runs = types.ModuleType("utils.training_runs")
training_runs.build_default_output_dir_name = lambda *_args, **_kwargs: "training-run"
sys.modules["utils.training_runs"] = training_runs
@@ -288,3 +296,158 @@ def test_activate_transformers_version_or_warn_silent_on_success(monkeypatch):
_worker._activate_transformers_version_or_warn("meta-llama/Llama-3-8B")
assert warnings_logged == [], "should not warn when activation succeeds"
+
+
+def _masking_block():
+ """The whole `if train_on_completions ...:` block from _run_mlx_training."""
+ tree = ast.parse(textwrap.dedent(inspect.getsource(_worker._run_mlx_training)))
+ blocks = [
+ n
+ for n in ast.walk(tree)
+ if isinstance(n, ast.If)
+ and isinstance(n.test, ast.BoolOp)
+ and "apply_completion_masking" in ast.unparse(n)
+ ]
+ assert len(blocks) == 1, "expected one guarded masking block"
+ return blocks[0]
+
+
+def _masking_call_and_guard():
+ """The apply_completion_masking call in _run_mlx_training, plus the `if not applied` guard."""
+ tree = ast.parse(textwrap.dedent(inspect.getsource(_worker._run_mlx_training)))
+ calls = [
+ n
+ for n in ast.walk(tree)
+ if isinstance(n, ast.Call) and getattr(n.func, "id", None) == "apply_completion_masking"
+ ]
+ assert len(calls) == 1, "expected exactly one masking call in the MLX path"
+ guards = [
+ n
+ for n in ast.walk(tree)
+ if isinstance(n, ast.If) and ast.unparse(n.test) == "not masking_applied"
+ ]
+ assert len(guards) == 1, "masking result must be checked exactly once"
+ return calls[0], guards[0]
+
+
+def test_alpaca_datasets_still_get_explicit_markers():
+ """Alpaca text carries no chat markers, so the template must be passed explicitly."""
+ call, _ = _masking_call_and_guard()
+ passed = {kw.arg: ast.unparse(kw.value) for kw in call.keywords}
+
+ assert passed["dataset_template"] == "'alpaca' if dataset_final_format == 'alpaca' else None"
+
+
+def _run_masking(
+ model_name = "org/unmapped",
+ detect = None,
+ **overrides,
+):
+ """Execute the real masking block from _run_mlx_training and return its events.
+
+ _run_mlx_training only runs on Apple Silicon, so the block is lifted out and executed
+ directly. That keeps the production statements under test rather than a copy of them.
+ """
+ block = compile(ast.Module(body = [_masking_block()], type_ignores = []), "<masking>", "exec")
+ events = []
+ trainer = types.SimpleNamespace(processing_class = types.SimpleNamespace(), tokenizer = None)
+ zoo = types.ModuleType("unsloth_zoo")
+ zoo.__path__ = []
+ datasets = types.ModuleType("unsloth_zoo.dataset_utils")
+ if detect is not None:
+ datasets.get_chat_template_parts = detect
+ previous = {n: sys.modules.get(n) for n in ("unsloth_zoo", "unsloth_zoo.dataset_utils")}
+ sys.modules["unsloth_zoo"] = zoo
+ sys.modules["unsloth_zoo.dataset_utils"] = datasets
+
+ namespace = dict(vars(_worker))
+ namespace.update(
+ {
+ "config": {"train_on_completions": overrides.pop("train_on_completions", True)},
+ "raw_text_mode": overrides.pop("raw_text_mode", False),
+ "dataset_final_format": overrides.pop("dataset_final_format", "chatml"),
+ "model_name": model_name,
+ "trainer": trainer,
+ "train_on_responses_only": lambda t, **_kw: t,
+ "_send": lambda event_type, **kw: events.append((event_type, kw)),
+ }
+ )
+ try:
+ exec(block, namespace)
+ finally:
+ for name, module in previous.items():
+ sys.modules.pop(name, None) if module is None else sys.modules.update({name: module})
+ return events, namespace.get("masking_applied")
+
+
+try: # the block imports this lazily; skip the behaviour tests where it cannot load
+ import utils.datasets.completion_masking # noqa: F401
+ _MASKING_IMPORTABLE = True
+except Exception: # pragma: no cover
+ _MASKING_IMPORTABLE = False
+
+needs_masking_helper = pytest.mark.skipif(
+ not _MASKING_IMPORTABLE, reason = "utils.datasets.completion_masking is not importable"
+)
+
+
+def _warnings(events):
+ return [kwargs["message"] for kind, kwargs in events if kind == "warning"]
+
+
+def _detect_fails(_processor):
+ raise RuntimeError("no chat template parts")
+
+
+ "overrides",
+ [
+ {"train_on_completions": False},
+ {"raw_text_mode": True},
+ {"dataset_final_format": "raw_text"},
+ ],
+ ids = ["not-requested", "raw-text-mode", "raw-text-format"],
+)
+@needs_masking_helper
+def test_masking_block_is_skipped(overrides):
+ events, applied = _run_masking(**overrides)
+
+ assert events == [] and applied is None
+
+
+@needs_masking_helper
+def test_masking_miss_reaches_the_warning_channel():
+ """A miss must be a sticky warning, not a status line the next update overwrites."""
+ events, applied = _run_masking(detect = _detect_fails)
+
+ assert applied is False
+ warnings = _warnings(events)
+ assert len(warnings) == 1
+ assert "org/unmapped" in warnings[0] and "full sequences" in warnings[0]
+ # The parent pump reads only `message` for warnings, so `status_message` would be lost.
+ assert [kind for kind, _ in events][-1] == "warning"
+
+
+ "model_name,detect",
+ [
+ ("org/unmapped", lambda _p: ("<|user|>", "<|assistant|>")),
+ ("unsloth/llama-3-8b-instruct", _detect_fails),
+ ],
+ ids = ["auto-detected", "recovered-by-template-table"],
+)
+@needs_masking_helper
+def test_applied_runs_leave_no_warning(model_name, detect):
+ """Detection can fail at level "warning" and the table still mask. That is not a miss."""
+ events, applied = _run_masking(model_name = model_name, detect = detect)
+
+ assert applied is True
+ assert _warnings(events) == []
+
+
[email protected]("model_name", ["", None, "org/model with spaces", "org/{brace}"])
+@needs_masking_helper
+def test_odd_model_names_do_not_break_the_warning(model_name):
+ events, applied = _run_masking(model_name = model_name, detect = _detect_fails)
+
+ assert applied is False and len(_warnings(events)) == 1