Repository navigation
Studio: train audio VLMs on the images in a mixed audio + image dataset - #16124
Conversation
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.
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.
|
Codex review on the fork mirror (LeoBorcherding#664) found no major issues at |
|
CI clean on the fork mirror (LeoBorcherding#664) at |
|
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
|
…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: attach refused | after: attached | |---|---| |  |  | <details><summary>GIFs of the full flow</summary> Before:  After:  </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.  <!-- 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>
|
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, Mixed audio + image dataset on current
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 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 I didn't hit any correctness issue in the GPU change while tracing this. |
…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:  --------- Co-authored-by: Daniel Han <[email protected]>
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_detectroutes these runs to the audio VLM path and setsis_vlmFalse (trainer.py:615,:1313). That routing is fine, since the path loads withFastModeland the processor takes images and audio together. But_format_audio_vlm_datasetbuilt an audio + text user turn, andaudio_vlm_collate_fncalledprocessor(text=, audio=)with noimages.Fix.
imagerole, else detection) and adds one image slot per image. A list-of-images column stays a list.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):
pixel_valuesGPU 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):
a00356eecfpixel_values11fe262f1apixel_values(4, 3, 768, 768)11fe262f1a, two images per rowpixel_values(8, 3, 768, 768)11fe262f1a, rows with and without an image[[img], [], [], []]Not run: LFM3-Omni's processor.
Found while testing LFM3 for #16054; related to #16101.