Skip to content

Studio: MLX training from a saved adapter, Continued Pretraining, streamed and audio datasets, with exact resume - #16622

Merged
danielhanchen merged 15 commits into
unslothai:mainfrom
Lyxot:studio-mlx-training-wiring
Nov 4, 2026
Merged

danielhanchen merged 15 commits into
unslothai:mainfrom
Lyxot:studio-mlx-training-wiring

Conversation

@Lyxot

@Lyxot Lyxot commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator

Unsloth Studio refused several training options on Apple Silicon that unsloth-zoo's MLX trainer already supports: continuing from a saved adapter, Continued Pretraining, streaming a Hugging Face dataset, and audio datasets. This wires them up on the MLX path and fixes the resume and detection gaps they exposed. Text-diffusion models are out of scope.

What changes

MLX training options (each its own commit)

  • Continue from a saved adapter. The MLX loader reads a PEFT (adapter_model.safetensors) or MLX (adapters.safetensors) adapter folder. The worker now keeps the reloaded LoRA trainable instead of stacking a second adapter on top, and keeps the adapter's own target modules. Embedding and decision runs still need a base model.
  • Continued Pretraining. The same rules as CUDA:
    • It trains on raw text, so an image dataset loads as text.
    • embed_tokens and lm_head train as full modules.
    • embedding_learning_rate defaults to lr/10 and is dropped when no embedding module trains.
  • Streaming. The MLX loader passes streaming=True. Slicing is lazy and the dataset is read in source order, as on CUDA's trainer. Evaluation needs a separate split, capped so each pass ends. The MLX refusals in the route and in the UI are removed.
  • Audio datasets.
    • Supported models: audio-input vision-language models that zoo has verified (Gemma 3n, Gemma 4, Qwen3-Omni, Phi-4-multimodal, MiniCPM-o, Nemotron omni).
    • Rows: the same transcription rows as the CUDA audio-VLM path, with each clip decoded and cast to the processor's sampling rate.
    • Mixed audio + image datasets train on both, matching Studio: train audio VLMs on the images in a mixed audio + image dataset #16124 on CUDA. Each row's images get an image slot ahead of its audio, and the eval split uses the train split's image column.
    • Refusals: text-to-speech and speech-recognition checkpoints still have no MLX trainer, so the worker refuses an audio dataset on them, and the UI only offers audio rows on a Mac for an audio-capable vision model.
  • A preparatory refactor, with no behavior change. Audio column resolution, Studio: train audio VLMs on the images in a mixed audio + image dataset #16124's image-column resolution and preparation, and the transcription turns move into the torch-free utils/datasets/audio_rows.py, so the CUDA and MLX trainers build identical rows.

Exact resume

  • A run that continued from a saved adapter could never resume. It failed every time with "The exact model snapshot for this run is no longer available", because the base pin was cleared for the local model source before the worker re-validated it. Keeping the pin would not fix it either: the base snapshot is the load target, so the bare base would load without the adapter.
    • How it resumes now: it loads the adapter folder as the original run did, and checks the base the worker attests after loading against the attested base (repo, snapshot, load mode). On a mismatch it stops before its first step.
    • A failed resume attempt no longer weakens the next resume. An attempt refused at that check records only its dataset, and one that dies before attesting records nothing. Either way, the next resume of the same output directory still checks the checkpoint's original base. Before this, the newest row for that output directory became the resume source.
    • Under the latest-Transformers runtime, which cannot load the 4-bit base such a run trained on, the resume is refused before loading, as an exact Hub-model resume already is.
  • A streaming run could never resume. It has no dataset snapshot, so its provenance was always incomplete.
    • The fix: a new streaming run pins the dataset's current Hub commit and loads that revision. That commit attests the dataset, but only if it is the one the parent pinned; a revision the worker reports on its own is not trusted. On resume, the route replays the stored commit, including from an attempt that died before attesting.
    • Fallback: if the commit cannot be resolved (offline, gated), the run streams the latest revision and warns that it cannot be resumed.

Gemma 4 audio detection

  • The bug: Gemma 4's tokenizer_config.json uses the transformers 5 layout, with the placeholder in a top-level audio_token and no added_tokens_decoder. So every Gemma 4 checkpoint was typed as not audio, and Unsloth Studio refused audio datasets and hid audio input for E2B, E4B and 12B on every backend.
  • Why the token alone is not enough: 26B and 31B carry the same token with audio_config: null, and the assistant drafters have no audio_config at all.
  • The rule now: a declared audio_token counts as audio_vlm only when config.json has an audio encoder. That config is read from the same cache snapshot, local folder or Hub revision as the tokenizer.
  • When the config can't be read, or a tokenizer-only download lacks it, the answer is left unknown rather than caching "not audio".
  • Consequences in the UI and export:
    • The training UI no longer hides layer offload for audio-input vision models (Gemma 3n and 4), which have a decoder stack to offload.
    • Export takes audio_vlm checkpoints through the vision load with their processor. That is the same FastModel load their training uses, and it also moves Gemma 3n onto it.

Validation

All on an M3 Max.

Targeted backend suites (resume, provenance, pins, cached start, MLX worker config, streaming, audio detection, audio VLM including #16124's tests, export) and the frontend:

1138 passed, 2 skipped
frontend: training-start-payload-offload 14/14, typecheck clean

Mutation checks covered every added or changed test: each deliberate breakage of the code a test guards was caught by that test.

Live MLX stop-and-resume through the Unsloth Studio HTTP API (Qwen2.5-0.5B-Instruct, yahma/alpaca-cleaned, 40 steps), compared with an uninterrupted run:

run stopped at resumed steps identical to the uninterrupted run
streaming step 6 7–40 (34/34)
continued from a saved adapter step 8 9–40 (32/32)

Mixed audio + image on MLX (Gemma 4 E2B, 8 rows of image, audio and text), the loss batch:

pixel_values image tokens audio tokens
before missing 0 50
after (2, 3, 768, 768) 512 50

Gemma 4 detection, checked offline against real cached repos and on the Hub:

  • audio_vlm: E2B, E4B, 12B (Google, mlx-community quantizations, base and -it).
  • Not audio: 26B-A4B, 31B, the assistant drafters, DiffusionGemma, and a text-only variant.
  • Gemma 3n is unchanged.
  • /api/models/config returns the same audio fields for Gemma 4 E2B, E4B and 12B as for Gemma 3n.

Not run: CUDA end to end (in particular, a stop-and-resume of a streamed dataset on the Hugging Face Trainer), a real Gemma 3n or Gemma 4 export (only with mocked loaders), and a full-length MLX run that shows vision LoRA learning from mixed audio + image rows.

UI: before / after

With the host reported as Apple Silicon (MLX), the training-method picker no longer disables Continued pretraining:

Training-method picker on an Apple Silicon host, before and after

Lyxot added 8 commits November 4, 2026 13:39
… out of the CUDA trainer

Column resolution (audio, text and speaker, and the image column of a mixed audio + image dataset), the image column's preparation and the transcription turns now live in the torch-free utils/datasets/audio_rows.py so a non-torch trainer can build the same audio rows. Behavior is unchanged.
…icon (MLX)

unsloth-zoo's MLX trainer already takes audio clips in vision-language chat rows for the families it has verified (Gemma 3n, Gemma 4, Qwen3-Omni, Phi-4-multimodal, MiniCPM-o, Nemotron omni). Unsloth Studio refused every audio dataset on Apple Silicon in the route, the MLX worker and the frontend. The MLX worker now loads the model multimodally, builds the same transcription rows the CUDA audio-VLM path builds (keeping each clip decoded with its sampling rate, cast to the processor's rate, since zoo checks it), and hands them to the VLM collator. Text-to-speech and speech-recognition checkpoints still have no MLX trainer, so the worker refuses an audio dataset on a model that does not load as a vision-language model, and the frontend allows audio rows on a Mac only for an audio-capable vision model.

A dataset with both audio and image columns trains on both, as on CUDA: each row's images get an image slot ahead of its audio and are resized like any MLX vision row, and an eval split uses the train split's image column.
A run that continues from a local adapter folder attests the base model its adapter loaded, so resuming it required that exact base pin. The pin was then cleared for the local model source before the worker re-validated it, and every such resume failed with "The exact model snapshot for this run is no longer available." Keeping the pin is no fix: the base snapshot is the load target, so the bare base would load without the adapter.

Resume now loads the adapter folder exactly as the run did and carries the attested base (repo, snapshot, load mode) as an expectation. The attestation the worker already makes right after loading must match it, or the run stops before its first step with a message naming the moved base or load mode. The route still refuses up front when the attested base snapshot is gone, and the dataset pin is unchanged.

A resume refused at that check records only its dataset, and one that dies before its worker attests records nothing, so the next resume of the same output directory still checks the base the checkpoint was trained on, not the one that attempt loaded. Under the latest-Transformers runtime, which cannot load the 4-bit base such a run trained on, the resume is refused before loading, as an exact Hub-model resume already is.
A streaming run has no dataset cache snapshot, so its resource provenance was always incomplete and Unsloth Studio refused to resume it ("The dataset revision used by this run was not attested"), even though both trainers already fast-forward a stream to the resumed step.

A new streaming run now pins the dataset's current Hub commit before training and passes it as the load revision, so the rows it reads are fixed. That commit attests the dataset in place of a snapshot, but only when it is the one this process pinned; a revision the worker reports on its own is not trusted. On resume, the route replays the stored commit instead of resolving the branch again, so the resumed run reads the same rows. When the commit cannot be resolved (offline, gated), the run still streams from the latest revision and warns that it cannot be resumed.

The route replays a stored commit even from a resume that died before attesting, so retrying it cannot fall back to the moving branch.
Gemma 4's tokenizer_config uses the transformers 5 layout: no added_tokens_decoder, and the audio placeholder named in a top-level audio_token. The tokenizer classifier only read added_tokens_decoder, so every Gemma 4 checkpoint was typed as not audio and Unsloth Studio refused audio datasets and hid audio input for E2B/E4B/12B on every backend.

A declared audio_token is not enough on its own: Gemma 4 26B and 31B carry the same token with audio_config null, and the assistant drafters with no audio_config at all. It now counts as audio_vlm only when the model's config.json has an audio encoder, read from the same cache snapshot, local directory or Hub revision as the tokenizer, and only when no added-token fingerprint already matched. A config.json that cannot be read, or that a cache snapshot lacks (a tokenizer-only download), leaves the answer unknown instead of caching "not audio"; a selected local folder or an adapter repo without one is read as having no audio encoder of its own (callers that type an adapter by its base are unaffected).

The training UI hid layer offload for every audio model, a rule meant for the Whisper and codec paths, which have no decoder stack to stream. Typing Gemma 4 as audio would have taken offload away from E2B/E4B/12B, so the rule now spares audio-input vision models (Gemma 3n and 4), whose decoder offloads like any other. Export likewise took only non-audio models through the vision load, which would have moved Gemma 4 onto the text loader. Every audio_vlm checkpoint, Gemma 3n included, now exports through the vision load with its processor, the same FastModel load its training uses.
@Lyxot
Lyxot requested a review from danielhanchen as a code owner November 4, 2026 05:41
@danielhanchen

Copy link
Copy Markdown
Member

dispatch and Repo tests (CPU, studio) fail here on one test that passes on main:

tests/studio/test_mlx_training_worker_behaviors.py::test_mlx_dora_decided_before_load_and_merged_into_peft_kwargs
AssertionError: get_peft_model must expand **peft_kwargs, or the merged DoRA kwargs never reach it:
FastMLXModel.get_peft_model(model, r=..., ..., use_gradient_checkpointing=use_grad_checkpoint, **mlx_dora_kwargs)

The test reads the MLX worker source and expects the FastMLXModel.get_peft_model(...) call to expand **peft_kwargs, the dict the DoRA decision is merged into before the model loads. In this branch the call expands **mlx_dora_kwargs instead. If mlx_dora_kwargs still carries everything peft_kwargs did, update the test to look for the new name. If it carries only the DoRA keys, anything else merged into peft_kwargs no longer reaches get_peft_model, and the call should go back to **peft_kwargs.

@danielhanchen

Copy link
Copy Markdown
Member

Two more jobs fail here on tests that pass on main. Both tests pull a function's source out of the training worker and run it in a namespace they build themselves, so a new free name in that function raises NameError there:

  • (Python 3.13, g-r): tests/test_mlx_epoch_report.py (test_mlx_step_callback_reports_zero_before_the_trainer_has_an_epoch, test_mlx_step_callback_counts_a_bounded_run_over_the_whole_dataset, test_mlx_training_never_streams) fails with NameError: name 'dataset_streaming' is not defined.
  • (Python 3.13, rest): tests/test_snac_code_interleave.py::test_host_copy_matches_scalar_loop[*] fails with NameError: name 'resolve_audio_columns' is not defined.

Either give those harnesses the new names (dataset_streaming, resolve_audio_columns), or keep the extracted functions free of them.

@danielhanchen danielhanchen self-assigned this Nov 4, 2026
# Conflicts:
#	studio/backend/core/training/worker.py
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 4, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-04T15:05:47.511299Z 3d8422e Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: da7c3a89ff

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

requires_exact_dataset,
False,
None,
{**overrides, "resume_expected_model": expected_model},

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Carry dataset attestation across failed adapter-resume attempts

For a continued-adapter run using a non-streaming Hugging Face dataset, a resume that crashes during model loading leaves a new history row with the original dataset_snapshot_path but a freshly initialized pending provenance marker. On the next retry, _provenance_awaiting_attestation() rejects that pending marker because the dataset pin is present, and exact_resume_resource_requirements() raises “The dataset revision used by this run was not attested” before the carried model expectation can be used. Since get_resumable_run_by_output_dir() selects only the newest attempt, every subsequent retry is blocked even though the original checkpoint and dataset snapshot remain intact. Carry the source dataset attestation alongside the model expectation, or prevent an unattested attempt from superseding the resumable source.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not specific to this PR: on main, a hub-model resume that dies before its worker attests leaves the same pending row (with the model and dataset pins), and the next retry is refused the same way (reproduced with the provenance test fixtures on main and on this branch). The adapter path now behaves like every other exact resume; making a failed attempt not supersede its source belongs in get_resumable_run_by_output_dir for all runs, as a separate change.

danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 4, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: da7c3a89ff

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

…ncoder config is unread, and scan escaped audio_token fields

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 3d8422eb8f

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants