Skip to content

Studio: /v1/chat/completions puts the whole answer in reasoning_content for templates with a {% generation %} tag - #16121

Merged
danielhanchen merged 6 commits into
unslothai:mainfrom
LeoBorcherding:night-shift-tester/think-probe-generation-tag
Nov 2, 2026
Merged

danielhanchen merged 6 commits into
unslothai:mainfrom
LeoBorcherding:night-shift-tester/think-probe-generation-tag

Conversation

@LeoBorcherding

@LeoBorcherding LeoBorcherding commented Oct 30, 2026 •

Copy link
Copy Markdown
Collaborator

Chat templates containing {% generation %} could fail Studio's reasoning-prefill probe, leaving API responses with empty content and the entire answer in reasoning_content.

The probe now uses Transformers' template compiler and supplies tools=None and documents=None when those contexts are absent. This preserves generation-block variable scope and the renderer's JSON filters and globals. A template that genuinely opens <think> still separates reasoning from the answer; an unrenderable probe no longer hides every answer.

Validation at bf691e50e:

  • 182 related reasoning, capability and continuation tests pass. The 55 reasoning-stream cases give 8 fixed / 47 unchanged against merge base 98f96f0ad, and 12 fixed / 43 unchanged against the submitted head 797992b78, with no head failures or skips.
  • 60 compiler checks pass on each of Transformers 4.52.4, 5.17.0 and 5.22.1. These include published LFM3-Omni and SmolLM3 templates, message histories, reasoning flags, default tools/documents context and scoped generation-block assignments.
  • JSON and SSE endpoint tests cover both torch and MLX adapters with generation controlled. No LFM3 or SmolLM3 weights were downloaded for this verification.

Found while testing LFM3 for #16054. Related: #16096, #16101.

Staging CI note

The final-head staging run completed with 54 successful jobs, three failed Core Zoo matrix cells and four skipped jobs. All three failed cells hit the same two test_quantized_decode_keeps_each_rows_padding_mask cases: the pinned Zoo CPU MLX shim does not implement BatchQuantizedKVCache. Both test IDs reproduce the identical failure in CPU controls against merge base 98f96f0ad and head bf691e50e, using Zoo fe1bfc2bbb75.

CI remains red on this pre-existing test-shim failure. It needs to be fixed, or explicitly waived by a maintainer for merge. Failing job and full traceback.

The selected broad Studio regression reports functional NO_REGRESSION at the final head (59 unchanged, two DOM-only and three visual differences, with the differing steps rerun on both arms). Linux, macOS and Windows Studio staging reports also give functional NO_REGRESSION; those reports retain fixture and crawl-coverage limitations.

Before and after: reasoning versus answer

Compared merge base 98f96f0ad with bf691e50e in two isolated Studio installs. Each install ran its own probe and response extractor against the published LFM3-Omni template and the same fixed generated text, Four. The resulting transcript was saved and opened in that install's chat UI: before, reasoning_content="Four", content="", one reasoning drawer; after, reasoning_content="", content="Four", no reasoning drawer.

This is a deterministic classification and saved-transcript replay, not a live model-generation screenshot. The current Studio frontend calls /v1/chat/completions, so its answer/reasoning display is affected too.

Before: Four in the reasoning drawer. After: Four as answer text.

The safetensors think-prefill probe compiled chat templates without the
{% generation %} tag, so LFM3-Omni and SmolLM3 templates failed to compile
and the probe failed open, reporting an open <think>. /v1/chat/completions
then routed the whole answer into reasoning_content with empty content.
@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

Codex review on the fork mirror (LeoBorcherding#663) found no major issues at fe73809f94, this PR's head: result.

@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

CI clean on the fork mirror (LeoBorcherding#663) at fe73809f94. The two red checks also fail without this PR: test_twins…early_download at the base, and rest-2's test_decision_dataset_prefetch.py encoding case on main (run).

@Lyxot Lyxot self-assigned this Nov 2, 2026
Lyxot added 2 commits November 2, 2026 16:36
…not render

A template the probe could not render was read as leaving <think> open, so the whole answer went to reasoning_content with empty content. Templates transformers renders can still reach this, for example an unguarded tools | tojson, since transformers passes tools=None and the probe leaves tools undefined. Read an unrenderable template as not open: a wrong answer then leaks the thought beside the answer instead of hiding the answer, matching the other chat template probes.
@Lyxot

Lyxot commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator

Pushed one review fix and merged latest main (the branch was 228 commits behind).

What changed: a template the think probe can't render now counts as not leaving <think> open, instead of open.

  • Before, any render failure still put the whole answer in reasoning_content. That can still happen with the {% generation %} fix alone: an unguarded {{ tools | tojson }} renders in transformers, which passes tools=None, but raises in the probe.
  • A wrong "not open" leaks the thought into content beside the answer, which is better than a blank reply. The other chat template probes already fail this way.
  • The {% generation %} registration stays: it's what makes templates that really open <think>, like LFM3-1.7B, route correctly.

Checked against transformers' renderer on every cached template with think markers (154 template and flag combinations): 20 blank answers on the old base, 0 wrong now. The route also gives the right split for real LFM3, d1, SmolLM3 and Qwen3 templates, on MLX and torch, streaming and not, with generation stubbed.

@Lyxot Lyxot added the MLX label Nov 2, 2026
@Lyxot

Lyxot commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 2, 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-02T09:02:24.244916Z 797992b 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

Copy link
Copy Markdown

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

Reviewed commit: 797992b78c

ℹ️ 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 self-assigned this Nov 2, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 2, 2026
@shimmyshimmer

Copy link
Copy Markdown
Member

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

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 eca3422576 (this PR's bf691e50e)

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

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

Reviewed commit: eca3422576

No triage reaction was recorded on the mirror

Verdict

The round converged at mirror eca3422576 (this PR's bf691e50e).

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

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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants