Skip to content

Studio: load LFM3 custom-code models (route by saving transformers version, fix generate, chat and export) - #16096

Merged
danielhanchen merged 16 commits into
mainfrom
studio-lfm3-custom-code-load
Oct 30, 2026
Merged

danielhanchen merged 16 commits into
mainfrom
studio-lfm3-custom-code-load

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 30, 2026 •

Copy link
Copy Markdown
Member

Fixes #16054. Also fixes the same load error reported on LFM3-1.7B in #15588.

Based on LeoBorcherding's draft (LeoBorcherding#650, commits kept with authorship), rebased onto current main, plus a routing fix on top.

What was broken

LFM3 is not in transformers yet, so it loads from LiquidAI's own code (trust_remote_code). That code needs transformers 5.19 or later (the checkpoint was saved with 5.19.0.dev0; the model card asks for 5.20.2+). Once the load worked, each later step hit a new incompatibility:

# Where What broke
1 studio/backend/utils/transformers_version.py The tier probe parses config.json with trust_remote_code=False, fails on every sidecar and falls to the 5.3.0 floor, where @strict raises Class 'Lfm3Config' must be a dataclass before applying @strict (the reported error).
2 unsloth/models/vision.py The generate wrapper forces cache_implementation / compile_config, which LFM3's own generate rejects (also on the FlashAttention early return).
3 studio/backend/core/inference/inference.py Studio chat always passes logits_processor and stopping_criteria; LFM3 rejects both, even as empty lists.
4 studio/backend/core/inference/inference.py Image prompts call the processor as (images, text); LFM3's is (text, audio, ..., images).
5 studio/backend/core/export/export.py Merged export saved use_cache: False (LFM3 rejects it) and shipped no processor, so no audio_tokenizer/ and no GGUF mmproj.

The fixes

  1. Custom-code configs (auto_map.AutoConfig, saved by transformers 5.x) are routed by their saving transformers_version: default if new enough, else the oldest sidecar that is, else latest when pinned, else 510. Versions compare at major.minor (a 5.5.4 save still fits the 5.5.0 default). Routing only ever raises a tier to meet the saving version; checkpoints saved with 5.3 or older keep the tier they got before. check_upgrade_for_model offers the latest transformers (PyPI, or main when PyPI is behind) when no installed tier is new enough, so LFM3 gets Studio's existing install prompt.
  2. Models whose generate lists cache_implementation in _generation_fields_unsupported get no cache fields forced on them.
  3. For those models Studio drops logits_processor / stopping_criteria. Tradeoff, LFM3 only: no presence penalty or prefill timing, and Stop ends the stream while generation finishes in the background.
  4. Processors whose first argument is text get keyword arguments; the check reads past unsloth_zoo's (*args, **kwargs) wrapper. Every other VLM keeps the positional call.
  5. Export restores use_cache after the load and wraps the adapter's tokenizer in the base model's processor when the VLM processor load falls back to a bare tokenizer.

_generation_fields_unsupported is defined only by LFM3's remote code (not by transformers 5.22.0), so fixes 2 and 3 are inert for every other model.

Proof

Reported error, transformers 5.3.0, real LiquidAI/LFM3-Omni-2B config: StrictDataclassDefinitionError: Class 'Lfm3Config' must be a dataclass before applying @strict.

Tier picked for the real LFM3-Omni config:

main this PR
no latest sidecar 530 (5.3.0) 510, and the upgrade prompt offers the latest transformers
latest sidecar at 5.22.0 530 (5.3.0) latest

Generate on a tiny random LFM3-Omni copy (Colab T4, transformers 5.22.0, merge base 858a97c vs 2b0d79f on the same machine, each arm importing its own tree):

step main this PR
generate ValueError: ... does not implement ['cache_implementation', 'compile_config'] OK
3 LoRA steps, loss 11.8466, 11.7277, 11.6237 11.8466, 11.7277, 11.6237
generate after LoRA same ValueError OK

Routing over 216 synthetic config combinations (saving version x auto_map x model_type x tokenizer x latest pinned): 160 unchanged, 56 moved, every move to a tier at least as new as the saving version, none lowered.

Real-weight end-to-end runs (Colab L4/T4, from the draft): Studio load, text chat ("What is 2+2?" gives "4"), image chat ("A red circle"), Studio LoRA training (loss 3.567 to 0.184 in 40 steps), merged 16-bit and GGUF q8_0 export with mmproj.

AMD gfx1151 (merge base vs head, both OSes): Linux ROCm generate probe CONFIRMED (base raises the cache_implementation error, head generates, identical LoRA losses); Studio backend suites NO_REGRESSION on Linux and Windows 11 (134/134).

Tests: TestCustomCodeRouting in studio/backend/tests/test_transformers_latest.py, an LFM3 case in tests/test_fa2_fast_generate_bypass.py, studio/backend/tests/test_custom_generate_kwargs.py, studio/backend/tests/test_export_vlm_processor_use_cache.py.

Other models

Routing of the 759 most downloaded, most liked and newest custom_code Hub configs, main vs this PR, with and without a latest sidecar (1518 cells): 1231 unchanged, 287 moved, every move to a tier at least as new as the saving version, none lowered, no errors. All moved configs carry auto_map.AutoConfig and were saved by transformers 5.6 or newer; checkpoints saved with 4.x or with no version are untouched.

For the moved models from known orgs, the remote code was imported (config plus model class, no weights) on transformers 5.5.0 (main's default), 5.10.2 and 5.22.0:

repo 5.5.0 5.10.2 5.22.0
LiquidAI/LFM3-1.7B model import fails model import fails OK
LiquidAI/LFM3-Omni-2B model import fails model import fails OK
google/tipsv2-so400m14 OK OK OK
ibm-granite/granite-speech-4.1-2b-nar OK OK OK
nvidia/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B (BF16, NVFP4) OK OK OK
microsoft/Mage-VL needs an extra pip package on every version same same
unsloth/Kimi-K3 OutputRecorder import fails on every version same same

No model that works on its old tier fails on its new one.

Studio regression switchboard, merge base 858a97c vs b1c1ea9: NO_REGRESSION (63 same, 5 DOM-only with 0 changed pixels). jobs sft, vision_sft, vision_sft gemma4, vision_grpo and inference_smoke NO_REGRESSION on Colab T4 / A100; regression_smoke SAME. The one FAIL_BOTH (export_reload/export_merged) fails on both sides because the harness ran with HF offline and could not reach unsloth/gemma-3-270m-it; merged export for other models is not exercised by this run. Staging CI on ubuntu-latest, macos-15 and windows-latest: 135 tests pass on each.

Tradeoff

Custom-code checkpoints saved with transformers newer than 5.5 now move to a newer sidecar (510 or latest) instead of the default. Checkpoints saved with 5.5 or older are unchanged or raised only to their saving version.

UI before and after

Chat model picker, LFM3-Omni-2B from a local folder (real config, remote code and tokenizer; no weights). BEFORE (merge base 858a97c): no install prompt, Studio goes straight to the custom-code consent and then loads on transformers 5.3.0, where the config fails as in the issue. AFTER (b1c1ea9): Studio stops at the install prompt for transformers 5.22.1. The dialog's right edge clips at this width on both sides; that layout is unchanged by this PR.

LFM3-Omni-2B before and after

LeoBorcherding and others added 11 commits October 30, 2026 03:18
The tier probe parses config.json with trust_remote_code=False, so a custom-code
config (LFM3) fails in every sidecar and lands on the 5.3.0 floor, where its
@strict config class cannot load. Route these by transformers_version instead,
and offer the latest transformers when no installed tier is new enough.
LFM3-Omni's remote generate lists cache_implementation in
_generation_fields_unsupported and raises when it is set, so FastModel's
generate wrapper failed on every call. Leave the cache fields unset for
such models.
LFM3-Omni's remote generate raises on logits_processor and stopping_criteria,
which every Studio chat request sets, so each prompt failed with an internal
error. Drop them for models that mark a custom generate.
LFM3-Omni's processor signature is (text, audio, ..., images), so the
positional (images, text) call handed it the image as text and failed.
…adapters

A text-only LoRA on a VLM saves a bare tokenizer, so the export load wrapped
no processor: merged exports had no processor_config.json or processor code
(AutoProcessor fails) and GGUF skipped the mmproj. Wrap the adapter's
tokenizer in the base model's processor. The load also leaves training's
use_cache=False on every config, which a merged config.json then persists;
restore it, since custom generate code can reject use_cache=False.
@danielhanchen danielhanchen self-assigned this Oct 30, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 30, 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-10-30T13:35:50.712783Z 2b0d79f 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.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 379649af34

ℹ️ 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".

@danielhanchen

Copy link
Copy Markdown
Member 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: b1c1ea99bc

ℹ️ 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".

danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 30, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 30, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 06d838064c

ℹ️ 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".

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: 2b0d79f35f

ℹ️ 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".

@danielhanchen
danielhanchen merged commit 87a4d57 into main Oct 30, 2026
36 of 66 checks passed
@danielhanchen
danielhanchen deleted the studio-lfm3-custom-code-load branch October 30, 2026 15:43
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>
danielhanchen added a commit that referenced this pull request Nov 3, 2026
Replaces #16128, which GitHub closed when #16096 merged and its base
branch was deleted. Built on merged #16242. This PR adds LFM3-Audio-2B
chat through the multimodal loader; its diff now contains only the child
layer.

LFM3-Audio-2B takes audio in and answers in text, but it has no image
processor, so Unsloth Studio loaded it on the text path. That builds the
bare `Lfm3AudioModel`, which has no `generate()`.

- A processor whose `audio_token` sits beside a `feature_extractor` is
now typed `audio_vlm`, as an image processor already does for LFM3-Omni,
so audio input is advertised.
- An `audio_vlm` checkpoint with no vision loads through
`AutoModelForMultimodalLM` (`Lfm3AudioForConditionalGeneration` via the
repo's `auto_map`). Audio turns use the existing audio-input path, text
turns the text path. A load that still can't generate is refused by
name, as before.
- Omni and Gemma 3n keep the VLM load. Plain text models are unchanged.

Tests: the focused loader, metadata and generation suites pass all 64
tests on Transformers 4.57.6 and 5.22.1 after integrating the parent
squash. Retained differentials reproduce the missing audio
classification and chat loader. Tiny random checkpoints also exercise
real GPU FastModel loading and text/synthetic-audio turns in 16-bit and
4-bit modes; they do not establish pretrained output quality.

Original real-model check reported by the author on Colab G4 (RTX PRO
6000), Linux, transformers 5.22.1, at `f03b06a0cd`: Audio-2B answered
"Four" to a text question and "The capital of France is Paris." to a
spoken WAV question. LFM3-Omni-2B still loads as a VLM and answers text,
image and WAV turns.

Not covered: the audio-input path doesn't split `<think>` reasoning yet,
so Audio-2B's spoken-question replies include it raw. Unsloth Studio
LoRA training on Audio-2B still loads without the multimodal class, and
merging its LoRA needs unslothai/unsloth-zoo's remote-code rename fix.

Part of #16054.

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

### Audio-input UI evidence

Before `25485284fe5de5f612432a2c3810fc2110f5d2f2` (merged parent
#16242), after `02f00f83945292dc46ae08e89837c05266cbe9bb` (child with
the parent squash integrated). This pair isolates the child layer
against its current merge base. 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/16243/pr16243_audio_upload_detail-1945e7c9a1bc.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>
raoofaltaher added a commit to raoofaltaher/lead-decision-models that referenced this pull request Nov 3, 2026
…rver

Unsloth Studio 2026.10.11 cannot load LFM3: its Clef runtime loads
without trust_remote_code and its environment pins transformers 5.5.0.
The fix (unslothai/unsloth#16096) is on main and not yet released.

integration/decision_server.py exposes the same decide tool as Studio's
MCP endpoint. It loads one local merged folder on the first call with
trust_remote_code=True in 4-bit, answers through
FastDecisionModel.predict, refuses what Studio refuses with Studio's
messages, and keeps Unsloth's console output off the protocol stream.
.mcp.json starts it over stdio for lead-decisions and reply-decisions;
serve.sh and the two Studio processes are gone. mcp 2.3.0 joins the
pinned freeze; torch, transformers and unsloth are unchanged.

RAOOF A.
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.

[Bug] LFM3-Omni Safetensors fails to load

2 participants