Skip to content

Studio: train audio VLMs on the images in a mixed audio + image dataset - #16124

Merged
danielhanchen merged 16 commits into
unslothai:mainfrom
LeoBorcherding:night-shift-tester/audio-vlm-mixed-image-audio-train
Nov 2, 2026
Merged

danielhanchen merged 16 commits into
unslothai:mainfrom
LeoBorcherding:night-shift-tester/audio-vlm-mixed-image-audio-train

Conversation

@LeoBorcherding

@LeoBorcherding LeoBorcherding commented Oct 30, 2026 •

Copy link
Copy Markdown
Collaborator

Training an audio VLM (Gemma 3n, Gemma 4, LFM3-Omni) in Unsloth Studio on a dataset with both audio and image columns trained on audio + text only. There was no warning, and the images never reached the model.

Why. pre_detect routes these runs to the audio VLM path and sets is_vlm False (trainer.py:615, :1313). That routing is fine, since the path loads with FastModel and the processor takes images and audio together. But _format_audio_vlm_dataset built an audio + text user turn, and audio_vlm_collate_fn called processor(text=, audio=) with no images.

Fix.

  • The formatter finds the image column (mapped image role, else detection) and adds one image slot per image. A list-of-images column stays a list.
  • The collator passes each row's images as RGB.
  • The eval split uses the same image column as the train split.
  • Audio-only datasets go through the exact same processor call as before.

Tests. tests/test_trainer_audio_vlm_image_and_audio.py, 7 tests, CPU only: 3 fail on main, all pass here. Existing audio VLM masking and eval-split tests pass.

Real processor check (Gemma 3n E2B processor on CPU, no weights):

dataset pixel_values image tokens / row audio tokens / row
main, one image per row missing 0 188
this PR, one image per row (2, 3, 768, 768) 256 188
this PR, rows with 1 and 2 images (3, 3, 768, 768) 256 / 512 188

GPU train (A100 40GB, unsloth/gemma-3n-E2B-it, Unsloth Studio trainer, 80 steps; each colour maps to an arbitrary code, so it can only be learned from the image; scored on 8 held-out images):

commit batch held-out answers
main base a00356eecf no pixel_values 1/8
this PR 11fe262f1a pixel_values (4, 3, 768, 768) 8/8
11fe262f1a, two images per row pixel_values (8, 3, 768, 768) 5 steps ran
11fe262f1a, rows with and without an image images [[img], [], [], []] 5 steps ran

Not run: LFM3-Omni's processor.

Found while testing LFM3 for #16054; related to #16101.

pre_detect routes an audio_vlm model (Gemma 3n, Gemma 4, LFM3-Omni) with an
audio dataset to the audio VLM path and sets is_vlm False, but that path only
formatted and collated audio + text, so an image column was silently dropped.
The formatter now resolves an image column (mapped role or detection), adds the
image slot to the user turn, and the collator passes one image per example to
the processor. Audio-only datasets are unchanged.
A Sequence(Image()) column (e.g. "images") was cast to a scalar Image(),
which datasets cannot do. It now stays a list: one image slot per image in the
user turn, and the collator passes every image of the row.
pre-commit-ci Bot and others added 6 commits October 30, 2026 13:42
The multimodal detector also picks a column by name (file_name), which in an
audio dataset may hold audio paths; casting that to Image() broke decoding.
An Image or List(Image) column counts even when row 0 has no image; the
detector misses those (and any column like 'images' it doesn't name-match).
A partly filled image column passed [None] to the processor, which rejects
it. None rows and entries now get no image slot and no image, and a batch
with no images at all omits the kwarg.
A typed image column with decode=False skipped the cast and reached the
processor as {path, bytes} dicts. Cast any non-decoding Image feature, or
a list of them, to a decoding one.
_holds_images also matches a messages column with image parts, which the
resolver then picked and tried to cast to Image. Accept a list column only
when every entry is an image.
… column

An untyped image-path column whose first row is empty was rejected on the
row-0 sample alone. Probe the first non-empty value in the first 100 rows.
… arrays

`in (None, "", [])` compared a pixel ndarray elementwise and raised the
ambiguous truth value error, aborting column resolution.
@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

Codex review on the fork mirror (LeoBorcherding#664) found no major issues at 523f023e91, this PR's head: result. Since the last update, seven findings from its reviews were fixed, each with a test that fails before and passes after: an audio-path file_name column taken as images, an Image column with an empty first row, rows with no image, an Image(decode=False) column, a messages column taken as the image column, an untyped path column with an empty first row, and NumPy pixel arrays in column detection. GPU (A100, Gemma 3n E2B, 80 steps, held-out images): 1/8 on main, 8/8 here.

@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

CI clean on the fork mirror (LeoBorcherding#664) at 523f023e91. Nothing red comes from this diff: Source lint, workflow-trigger lint and Repo tests rest-2 all fail on one AV009 line in test_sd_cpp_probe_error_mode.py that main baselined 6 minutes after this branch's base (#16108), and a-f's test_twins…early_download fails on main too (run). Core zoo was cancelled by the fork's time limit mid-pytest, not failed.

@shimmyshimmer

Copy link
Copy Markdown
Member

Review record for #16124, carried over from the mirror it was reviewed on: danielhanchen/unsloth-staging-review#697.

Findings are quoted as posted and attributed to the account that posted them. The reactions shown are the triage recorded on the mirror; none were re-applied here. Commits are named as the mirror's, with this PR's equivalent where one was found.

Round 1: reviewed mirror 109e29f314 (this PR's 64e92fc05)

chatgpt-codex-connector[bot] (on the mirror)

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: 109e29f314

No triage reaction was recorded on the mirror

Verdict

The round converged at mirror 109e29f314 (this PR's 64e92fc05).

This is the review as it stood at that commit. Anything pushed to this PR afterwards was not part of it.

@danielhanchen
danielhanchen merged commit 50f09c8 into unslothai:main Nov 2, 2026
danielhanchen added a commit that referenced this pull request Nov 3, 2026
…tom-code generate (#16242)

Replaces #16101, which GitHub closed when #16096 merged and its base
branch was deleted. Same branch, now merged with main; the diff is only
this PR's changes.

## What breaks

`LiquidAI/LFM3-Omni-2B` (safetensors, custom code) loads as vision-only.
The backend logs `is_vision=True ... audio_type=None,
audio_type_known=True`, the chat chip says "Vision", and attaching a WAV
through "Add photos & files" is refused ("cannot accept audio"), so the
prompt goes out text-only and the model says it has no clip. The GGUF of
the same model takes audio fine, because llama.cpp reads the vocab.

## Why

Audio-input detection fingerprints `added_tokens_decoder` in
`tokenizer_config.json` (`<|audio|>` / `<audio_soft_token>` ->
`audio_vlm`). LFM3-Omni was saved by transformers 5, whose
`tokenizer_config.json` has no `added_tokens_decoder` at all:
`<|audio|>` only lives in `tokenizer.json` and in
`processor_config.json` (`"audio_token": "<|audio|>"`). So detection
read the tokenizer config, found nothing, and answered a definitive "not
audio".

## Fix

- `processor_config.json` joins the files audio detection reads (local
dir, HF cache and Hub), and `classify_audio_tokens` counts a config's
`audio_token`. Only the markers the tokenizer patterns already accept
route to `audio_vlm`, so Qwen2-Audio's `<|AUDIO|>` stays where it was.
- `generate_audio_input_response` needed no change: it goes through
`processor.apply_chat_template`, and transformers' base implementation
calls the processor with `text=`, `audio=` by keyword, so LFM3's
text-first signature is not a problem on this path (the positional issue
#16096 fixed was on the image path only).

## Evidence

Colab L4 (NVIDIA L4, 22.5 GB), Linux, transformers 5.22.0 latest sidecar
(installed through Studio's own upgrade prompt). Same VM, same WAV (2.9
s, macOS `say`: "Hello. The secret word for today is pineapple."), same
prompt "What is the secret word in this audio clip?", driven headless
with Playwright through the real "Add photos & files" picker.

| | before `0782561c9a` | after `a19ca071ed` |
|---|---|---|
| `/api/models/config` | `audio_type=None`, `has_audio_input=False`,
`model_type=vision` | `audio_type=audio_vlm`, `has_audio_input=True` |
| chip | Vision | Vision · Audio Input |
| attach WAV | refused: "LFM3-Omni-2B cannot accept audio" | attached |
| reply | "you haven't provided the audio clip" | "The secret word for
today is pineapple." |

![before/after
reply](https://raw.githubusercontent.com/LeoBorcherding/unsloth/d2f4a7b4cd6d193512de4b14506bf103154ca062/lfm3-omni-audio-2026-10/before-after-reply.png)

| before: attach refused | after: attached |
|---|---|
|
![](https://raw.githubusercontent.com/LeoBorcherding/unsloth/d2f4a7b4cd6d193512de4b14506bf103154ca062/lfm3-omni-audio-2026-10/before-04-attach-refused.png)
|
![](https://raw.githubusercontent.com/LeoBorcherding/unsloth/d2f4a7b4cd6d193512de4b14506bf103154ca062/lfm3-omni-audio-2026-10/after-04-attached.png)
|

<details><summary>GIFs of the full flow</summary>

Before:
![](https://raw.githubusercontent.com/LeoBorcherding/unsloth/d2f4a7b4cd6d193512de4b14506bf103154ca062/lfm3-omni-audio-2026-10/before.gif)

After:
![](https://raw.githubusercontent.com/LeoBorcherding/unsloth/d2f4a7b4cd6d193512de4b14506bf103154ca062/lfm3-omni-audio-2026-10/after.gif)
</details>

Image chat still works after the change (`/v1/chat/completions` with a
red-circle PNG: "Red circle on white background").

## Tests

Three new tests in `studio/backend/tests/test_audio_token_detection.py`
(classifier, local checkpoint shaped like the published repo, Hub
fetch). Red on `0782561c9a`, green here. Every test file touching
`tokenizer_config` / `detect_audio_type` / `audio_tokens` (84 files, Mac
M5, Unsloth Studio venv): no new failures. The other failures there are
the same on base (mostly MLX trainer tests that can't run on this Mac);
`test_memory_estimate::test_a_weightless_probe_never_runs_the_evaluations_its_model_asks_for`
failed once in the loaded full run and passes alone.

## Not covered

- Windows (the reporter's OS) and Unsloth Desktop: the change is in
backend detection, which is platform-independent, but no Windows run.
- Spoken-reply (`audio_out`) is untouched; this is audio in, text out.
- Seen in passing: with `/v1/chat/completions` non-streaming, LFM3's
image answer lands in `reasoning_content` with empty `content`. Separate
from this PR.


## Also in this PR (added after review and GPU testing)

- **Stop and stop sequences for custom-code `generate`:** LFM3's
`generate` rejects `stopping_criteria`, so Stop or a matched stop string
ran to `max_new_tokens` while holding the generation lock. Cancellation
now goes through the streamer on the text, vision and audio-input paths.
Stop strings use the existing text and vision stop-sequence streamers;
audio-input stop strings remain unsupported. T4, LFM3-Omni-2B, WAV
question cancelled after 8 chunks: the next request waited 80.3 s
before, 0.3 s after.
- **Export:** an `audio_vlm` checkpoint with a vision tower loads as a
VLM for export, so the processor, audio tokenizer and mmproj ship. Gemma
3n/4 exports are byte-identical before and after (G4).
- **LoRA defaults:** LFM3's MLP is `w1/w2/w3`, which the default
`up_proj/down_proj` targets miss, so every LFM3 repo defaults to
`all-linear`.
- **LFM3-Audio-2B:** its `audio_token` has no image processor beside it,
so it isn't advertised as an audio VLM, and a text-path load whose model
has no `generate` is refused by name instead of crashing on the first
message (#16128 builds the real chat path).
- **Routing:** a custom-code config whose `transformers_version` is only
on nested sub-configs (LFM3-Audio-2B) routes by that.

Hardware: Colab A100 / G4 / T4 / L4 (NVIDIA, Linux); RX 9060 XT gfx1200
on Linux (chat, LoRA, export); RX 6500 XT gfx1034 on Windows 11
(LFM3-1.7B chat and LoRA); RX 5700 XT gfx1010 loads but LFM3's own
Triton conv doesn't compile there (separate fix).

## Related

All from the LFM3 report #16054: #16096 (merged: LFM3 load, chat,
training and export), the Audio-2B chat PR stacked on this one, #16121
(API `reasoning_content`), #16124 (audio + image training), #16098
(video and ffmpeg), unslothai/unsloth-zoo#2278 (LoRA merge on renamed
weights).

<!-- lfm3-audio-ui:start -->

### Audio-input UI evidence

Before `4f4305ea10c4a9940a2a00f7c4b454a47d6e38fc`, after
`1dfec8c3537e3ddda2042eacf6c8f333a157c7da`. The scene runs each side's
actual metadata classifier on the same published configuration, supplies
that measured capability through an intercepted inference-status
response, and opens the real Compare chat attachment menu. Upload audio
is absent before and visible after. This proves metadata-derived
presentation; no model load or generation runs in this scene.

![Before and after audio-input attachment
menu](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/16242/pr16242_audio_upload_detail-f213e4162adc.png)

<!-- lfm3-audio-ui:end -->

---------

Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
@Lyxot

Lyxot commented Nov 3, 2026 •

Copy link
Copy Markdown
Collaborator

Checked whether this also covers MLX (Apple Silicon) training. Short answer: MLX doesn't go through this code, and it doesn't have the silent image drop either. It refuses any dataset with audio.

Call path. On an MLX device, UnslothTrainer isn't used for SFT. The training thread calls worker.run_mlx_training_process → _run_mlx_training, which loads through unsloth-zoo's FastMLXModel / MLXTrainer and formats data with format_and_template_dataset. _format_audio_vlm_dataset, _resolve_audio_vlm_image_column and audio_vlm_collate_fn are never reached.

Mixed audio + image dataset on current main (synthetic 8 rows with image, audio and text columns, run through the real path with google/gemma-4-E2B-it):

step result
check_dataset_format (what the UI uses to set the flags) is_image=True, is_audio=True
POST /api/train/start validation on MLX 400 Audio dataset training is not yet supported on Apple Silicon.
MLX worker with is_dataset_audio=True same error event, before the model loads
MLX worker with is_dataset_image=True, is_dataset_audio=False (an API caller leaving the flag off) trains. The batch reaching the VLM CCE loss has pixel_values (2, 3, 768, 768) and mm_token_type_ids, and no audio feature tensor (input_features etc.).

So in Unsloth Studio a mixed dataset on Mac fails up front with a clear error. It never trains on audio without the images. The only quiet drop is the reverse one (audio ignored) in the last row, and you only get it by sending is_dataset_audio=false by hand through the API.

If MLX should support this, the work is in Unsloth Studio, not unsloth-zoo. unsloth-zoo's MLX trainer already does audio-input VLM SFT behind a per-family gate, and Gemma 4 qualifies. The pieces are: lift the is_dataset_audio refusal in _validate_training_platform (routes/training.py) and in run_mlx_training_process (worker.py) for audio VLMs, then have _run_mlx_training build audio + image user turns the way _format_audio_vlm_dataset now does on the GPU path. That's a separate feature, not a gap in this PR.

I didn't hit any correctness issue in the GPU change while tracing this.

danielhanchen added a commit to NilayYadav/unsloth that referenced this pull request Nov 4, 2026
…eamed and audio datasets, with exact resume (unslothai#16622)

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 unslothai#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, unslothai#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 unslothai#16124's
tests, export) and the frontend:

```text
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](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/16622/pr16622_q-d14398072c19.png)

---------

Co-authored-by: Daniel Han <[email protected]>
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.

4 participants