Skip to content

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

Merged
danielhanchen merged 6 commits into
unslothai:mainfrom
BardiaKoopah:fix/mlx-masking-warning
Aug 9, 2026
Merged

danielhanchen merged 6 commits into
unslothai:mainfrom
BardiaKoopah:fix/mlx-masking-warning

Conversation

@BardiaKoopah

Copy link
Copy Markdown
Contributor

Follow-up from testing the studio training paths on Apple Silicon. One commit, two files.

apply_completion_masking reports a double miss at level "warning" and returns applied=False, leaving the run training on full sequences. The MLX worker discarded both signals:

trainer, _masking_applied = apply_completion_masking(
    trainer,
    model_name,
    train_on_responses_only,
    notify = lambda level, message: _send("status", status_message = message),
)

The lambda drops level, so a warning becomes a status line that scrolls past. _masking_applied is discarded outright. A run that asked for response-only training and did not get it finishes looking like an ordinary success.

Why this is the odd one out

The CUDA path already does both halves — it routes by level, and drops train_on_responses_enabled so the run reports what it actually did:

self.trainer, masking_applied = apply_completion_masking(..., notify = _notify)
if not masking_applied:
    train_on_responses_enabled = False

And the MLX worker already emits real warning events elsewhere; the eval-split fallback a few hundred lines above uses exactly this channel:

_send("warning", message = "Evaluation is enabled, but the training dataset has only ...")

Masking was the one path still flattening them.

Verified end to end

M2 MacBook Air, mlx-community/SmolLM-135M-Instruct-4bit, a chatml dataset, train_on_completions on. A double miss was forced with an older unsloth_zoo whose dataset_utils has no get_chat_template_parts, so auto-detection fails and the model is absent from MODEL_TO_TEMPLATE_MAPPER:

before: WARNING_EVENTS []
        (both notices arrived only as transient status messages)

after : WARNING_EVENTS [
          "Auto-detection of instruction/response markers failed (...)",
          "'Train on completions' could not be applied for mlx-community/SmolLM-135M-Instruct-4bit:
           no auto-detected or mapped instruction/response markers. Training will run on full
           sequences (prompts included)."
        ]

The run still completes in both cases, which is the intended behaviour — a masking miss should be visible, not fatal.

Scope, honestly

This is a robustness and parity fix rather than a live bug. On a correctly pinned unsloth_zoo (>=2026.8.3) auto-detection succeeded for every mlx-community model I tried, so reaching a double miss needs a template the detector cannot parse and one absent from the 630-entry MODEL_TO_TEMPLATE_MAPPER. I am not claiming users are hitting this today; the point is that when it does happen the training objective changes silently.

I deliberately did not change what the run metadata records. Both backends store the requested train_on_completions, and changing one would introduce a new inconsistency rather than remove one.

Tests

The routing is a module-level helper so it can be tested without a training run. Both new tests fail without this change — the helper does not exist, so the module attribute lookup raises.

tests/test_mlx_training_worker_config.py   17 passed
tests/test_training_progress_callback.py   10 passed

ruff check clean.

For anyone re-running the suites: test_training_streaming.py (8 failures) and test_training_raw_support.py (1) fail identically on unmodified main — I baselined them before and after this change, same counts both ways.

apply_completion_masking reports a double miss at level "warning" and returns
applied=False, leaving the run training on full sequences. The MLX worker passed
`notify = lambda level, message: _send("status", ...)`, which drops the level, and
assigned the result to `_masking_applied`, which discards it. So a run that was
asked for response-only training and did not get it finished looking like an
ordinary success.

The CUDA path already does both halves: it routes by level and drops
train_on_responses_enabled so the run reports what it actually did. The MLX worker
also already emits real warning events elsewhere -- the eval-split fallback uses
exactly this channel -- so masking was the one path still flattening them.

Verified end to end on an M2 (SmolLM-135M-Instruct-4bit, chatml dataset,
train_on_completions on), forcing a double miss with an older unsloth_zoo whose
dataset_utils has no get_chat_template_parts:

  before: WARNING_EVENTS []           <- both notices arrived as transient statuses
  after : WARNING_EVENTS [auto-detection failed..., could not be applied...]

The run still completes in both cases, which is correct: a masking miss should be
visible, not fatal.

Note this is a robustness fix rather than a live bug. On a correctly pinned
unsloth_zoo (>=2026.8.3) auto-detection succeeds for the mlx-community models I
tried, so a double miss needs a template the detector cannot parse AND absent from
MODEL_TO_TEMPLATE_MAPPER.

The routing is a module-level helper so it can be tested without a training run.
Both new tests fail without this change (the helper does not exist).
tests/test_mlx_training_worker_config.py is 17 passed.
@BardiaKoopah

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 6d639ae19c

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

danielhanchen added 2 commits August 8, 2026 13:28
Resolves the conflict in the MLX completion-masking call. Keeps main's
dataset_template argument from unslothai#8103 alongside the level-preserving notifier,
so Alpaca-rendered datasets still get explicit markers.
apply_completion_masking also reports at level "warning" when auto-detection
raises and the template table then succeeds. Routing on level meant that run,
which got the masking it asked for, was left with a permanent warning in the UI.

Send from the caller instead, where masking_applied is already in hand, so only
a real miss is sticky. That also drops the duplicate log line, since the parent
pump already logs every warning event it receives.

Tests now pin the call site rather than the helper in isolation: a revert to the
old flattening lambda, or a dropped dataset_template, passed the previous tests.
Also stubs utils.hf_dataset_options so the module can be run on its own.
@danielhanchen

Copy link
Copy Markdown
Member

Good catch on this one, the flattening was real and the warning channel is the right home for it. I pushed two commits to the branch.

645e7cc merge main. The branch had gone stale and conflicted on the masking call itself. #8103 landed there after you opened this: it widened the guard to let Alpaca through and added dataset_template = "alpaca" if dataset_final_format == "alpaca" else None. Taking either side of that conflict alone loses something, so the resolution keeps both. That also clears the failing checks, which were all staleness rather than anything in your change (the three Repo tests (CPU) failures pass on main and on the merge, and scan-packages was a stale baseline file).

50f09e7 send the warning on the miss rather than on the level. apply_completion_masking emits at level warning in two places, not one:

    except Exception as e:
        notify(
            "warning",
            f"Auto-detection of instruction/response markers failed ({e}); "
            f"falling back to the template table",
        )

That one is recoverable, and the template table right below it can still return applied=True. Routing on level meant a run that got exactly the masking it asked for was left with a permanent entry in the warnings list saying detection failed. I reproduced it on unsloth/Phi-3.5-mini-instruct-bnb-4bit: one warning event, one status, applied: True.

Since masking_applied is already in hand at the call site, the event goes out from there:

        if not 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)."
                ),
            )

Only a real miss is sticky, _completion_masking_notifier is no longer needed, and the logger.warning goes away with it since the parent already logs every warning event at training.py:2809.

One correction on the comment that was there. The CUDA path does not actually report anything either. train_on_responses_enabled = False at trainer.py:3700 is a dead store: its only remaining read at 3752 sits in the else: of the gate that was already evaluated, and it reaches no config, DB row or event. So this was never mirroring CUDA, it was doing strictly more than CUDA does. Which is fine, just worth not claiming otherwise in a comment.

On the tests. Both of the originals passed against a call site reverted to the old flattening lambda, and against one with dataset_template dropped, because they only exercised the helper. They now parse _run_mlx_training and assert on the call itself, which is the same trick test_training_raw_support.py:201 uses on the sibling helper. I mutation checked all three: dropping dataset_template, turning the miss event back into a status, and routing warnings in notify each fail exactly one test.

Also added a utils.hf_dataset_options stub to _load_worker_module. Not yours, #8103 added that import to worker.py without it, which is invisible under a whole-directory run but breaks pytest tests/test_mlx_training_worker_config.py on its own.

Verified: 18927 passed on pytest tests/ under studio/backend, with the only failures in test_studio_api.py and test_hf_xet_fallback.py, identical on main here since they want a live server. ruff clean. Your 8 + 1 in test_training_streaming.py and test_training_raw_support.py check out too, they reproduce exactly by pinning hardware.DEVICE to MLX and are unrelated to this.

Two things I left alone. CUDA's _notify at trainer.py:3683 still only logs, so a miss there never reaches the UI, and _record_warning is sitting right there in the same class already used for the eval-split fallbacks. And warnings are in-memory only, so this is gone on reload since historical-training-view.tsx:95 hardcodes warnings: []. Both are worth doing, neither belongs in this PR.

pre-commit-ci Bot and others added 2 commits August 8, 2026 13:34
_run_mlx_training only runs on Apple Silicon, so the guarded masking block is
lifted out with ast and executed directly against the real apply_completion_masking
and the real template tables. That gives Linux CI actual behavioural coverage of
the branch this PR changes.

Covers the three skip conditions, both applied paths (auto-detected, and recovered
by the template table after detection raises), the double miss, and odd model names
in the interpolated message. Mutation checked: routing the miss back to a status
event, dropping dataset_template, routing warnings in notify, and ignoring
masking_applied each fail at least one test.
@danielhanchen

Copy link
Copy Markdown
Member

Ran this through a proper simulation pass before signing off. Summary first: the issue is real, the fix holds, and nothing else can be affected. One more commit, dd5e6e8, adding behavioural coverage.

Before and after

Before, _run_mlx_training passed a notify lambda that flattened every level to a status event and threw the return value away. A double miss (auto-detection cannot parse the template and the model is absent from MODEL_TO_TEMPLATE_MAPPER) left the run training on full sequences with nothing but a status line that the next update overwrote.

After, the miss goes out as _send("warning", ...), which the pump at training.py:2803 appends to TrainingProgress.warnings, which routes/training.py:1837 returns and the amber callout renders. A run that asked for response-only training and did not get it now says so.

Real issue, narrow blast radius. It needs both halves of the double miss, so it is a robustness fix rather than something users hit daily, which is what you said in the description.

Simulation

Rather than reimplement the call site, the harness lifts the guarded masking block out of _run_mlx_training with ast and executes it, so the production statements, the real apply_completion_masking and the real template tables are all under test. 72 checks across four files, then run against three trees:

tree result
main, pre-PR 12 failed: every "a miss must be recorded" check
this PR, first draft 12 failed: a double miss emitted 2 warnings, and a recovered run emitted 1
this PR now 25 passed

That is the issue reproduced and the fix demonstrated, in the same file, without a Mac.

Coverage: the three skip conditions, preset markers on the tokenizer, preset markers behind mlx-lm's TokenizerWrapper, auto-detect success, detection failure recovered by the table, detection failure into a miss, detector returning nothing, the alpaca dataset_template path, train_fn raising (must still fail the run, not fall back), event ordering, dedupe stability, and model names that are empty, None, 300 characters, spaced, unicode or brace-bearing, since the name is interpolated into an f-string.

Pipeline: events pushed through a real spawn queue into the real TrainingBackend._handle_event and the real _MLXTrainerAdapter._handle_event, asserting the warning lands, survives 200 later status events, dedupes across repeats, coexists with the eval-split warning, and stays JSON-serialisable for the status endpoint.

Nothing else can break

[Windows, Linux, WSL, macOS-Intel] x [NVIDIA, AMD, CPU], all 12, drive run_mlx_training_process with the device forced and stop at the existing _hw.DEVICE != DeviceType.MLX gate with the same error as before, never reaching the change. Backed by an AST diff against origin/main: of every top-level definition in worker.py, exactly one differs, _run_mlx_training. Module import surface identical, no new import inside the function, no OS or vendor conditional added, trainer.py byte-identical.

Old installs are fine. models/training.py, routes/training.py, training.py and studio_db.py are untouched, so no new field, no new event type, no migration. warnings already shipped and MLX already emitted type: warning for the eval-split fallback, so the change adds a string to a list that already existed rather than changing any contract. Old unsloth_zoo without get_chat_template_parts is covered explicitly: mapped model still masks, unmapped model still degrades to full sequences with one warning, neither raises.

Browsers do not come into it, there is no frontend diff. The string lands in the existing callout in progress-section.tsx:326 as an escaped React text child inside break-words, with key={warning}, which the pump's dedupe already guarantees is unique.

Python matrix in isolated uv venvs, 3.9 through 3.14, covering the whole declared >=3.9,<3.15 range: 3.10 to 3.14 all green. On 3.9 the behavioural tests skip, because utils/datasets/format_detection.py:47 uses dict | None without from __future__ import annotations, so the backend cannot import there at all. Pre-existing, unrelated to this, and outside the studio CI matrix, but worth knowing. Also confirmed ast.unparse produces byte-identical output for every expression the tests assert on across all six versions, so the AST assertions are not version-fragile.

The new commit

The tests were shape-only, so they could not catch a behavioural regression. dd5e6e8 adds the block-exec harness and the behavioural cases. Mutation checked, each of these now fails at least one test: routing the miss back to a status event, dropping dataset_template, routing warnings inside notify, and ignoring masking_applied.

Full suite under studio/backend: 18965 passed, with the only failures in test_studio_api.py and test_hf_xet_fallback.py, identical on main here since they want a live server. ruff clean, and I ran scripts/run_ruff_format.py with the pinned ruff==0.6.9 so pre-commit.ci has nothing left to push.

One thing the simulation surfaced that is worth a separate look: a marker mismatch, where train_on_responses_only applies markers that do not match the rendered template, produces all -100 labels and a flat zero loss. That is silent in a different way and is not something this PR covers.

@danielhanchen
danielhanchen merged commit 6fd4e9a into unslothai:main Aug 9, 2026
5 of 41 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants