Repository navigation
Studio: batch MLX tool-protocol, response_format and video replies; several clips and Gemma 4 video on MLX - #15920
Conversation
A reply carrying `tools` or `tool_protocol_active` was refused by every MLX batch, so coding agents (Claude Code, Codex, OpenCode over `/v1/messages` and `/v1/chat/completions`) were served one reply at a time even with Parallel Slots above 1, and a refused reply held everything queued behind it until the batch drained. The refusal stood because a batch row decoded its text differently from `_generate_text`: it never built the `NativeToolTokenDecoder`, so native tool controls were stripped as special tokens, a trailing stop id that closes a tool envelope was lost, and a template with native reasoning channels went through mlx-lm's plain detokenizer instead of `_MlxStreamedText`. `_plan_text_row` now builds the same decoder, stop-id rule and streamed text the single path uses (the stop-id rule is one shared helper, `_native_reply_text`), the session feeds `_MlxStreamedText` id by id, and a row's held text is flushed when it ends or is withdrawn, as the single path flushes on finish and on cancel. Unrestricted tool mode (`tool_protocol_active` with an empty catalog) reaches the planner too. Text loads now admit tool replies. Vision loads still refuse them: unsloth-zoo's vision batch reports text deltas, not token ids, so a vision row cannot be decoded with the native controls yet. As a side effect, rows on a template with native reasoning channels decode exactly as the single path does even without tools. Validated with a differential test that replays the same token stream through `generate_chat_response` and through two concurrent `_TextBatchSession` rows (native channels, plain native decode, unrestricted mode, stop on a closer and on an opener, length finish, stop sequences hit and held, withdraw), mutation-checked. On Apple Silicon a single tool row through the resident batch matches the single path token for token, and four concurrent agent-style tool requests on Qwen3-4B-4bit finished in 4.07 s against 9.73 s served one at a time, each reply parsing as one tool call. Greedy output at batch width above 1 can differ from the single path for any row, tool or plain, because batched prefill, left padding and quantized matmuls at more than one row change the numerics; that predates this change.
A reply with `response_format` (or a raw completion's `grammar`) was refused by every MLX batch, so structured-output clients were served one reply at a time and held the queue behind them. `_plan_text_row` now builds the grammar constraint exactly as `_generate_text` does: the same `_build_grammar_constraint` call (whether a kept `</think>` survives the decode included), a document-only constraint clears the think prefix and the native channels, the constraint is told which ids the native decoder drops, and a constrained plain reply decodes without space cleanup. A raw prompt's `grammar` uses `_raw_prompt_constraint`. A grammar can fail mid-decode: a schema that forces a reserved control token raises `ResponseFormatError`, and a bind or desync error can surface on any step. mlx-lm runs a row's logits processors inside `BatchGenerator.next()`, so such an error used to fail every request in the batch. A row's processor error is now kept on that row: the session removes the row from the generator and reports `(handle, exception)` ahead of the step's other events (processors run a step ahead, so the single path raises before yielding that step's token, and a sibling ending in the same step cannot answer the request as done). The resident worker answers that request with the error the single path would send, withdraws its other rows and keeps the rest decoding; the fixed multi-reply command raises it, as one reply would. Vision loads still refuse constrained replies: their batch reports text, not ids. Validated with a differential planning test (what the constraint builder, processors and decode receive alone and in two concurrent rows), session and worker tests for a failing row beside healthy ones, and mutation checks. On Apple Silicon (Qwen3-4B-4bit) a json_schema reply through the resident batch matches the single path at width 1, stays schema-valid beside a tool reply, and a schema whose only completion is the EOS text fails just its own row with the single path's `ResponseFormatError` while the tool reply beside it finishes.
…ormat replies Text loads already batch tool-protocol and response_format replies, but a vision load (Qwen3.5, Gemma and other models that load as vision models) refused them: unsloth-zoo's vision batch reported only its own text, while `_generate_vlm` decodes these replies from token ids (native tool controls kept, a stop id held until it is known to close a tool envelope, the grammar told what the decoder drops). With an unsloth-zoo whose `GenerationEvent` carries `token_ids`, a resident vision batch now plans such a row exactly as `_generate_vlm` does (`_plan_vlm_row(decodes_ids=True)`): the think prefix that keeps a `</think>` the decoder preserves, the grammar constraint with its stop ids, dropped ids and processor, a document-only constraint clearing the think prefix and the reasoning normalizer, and `_MlxStreamedText` fed the row's ids. A row's held text is flushed when it ends or is withdrawn by `_streamed_tail`, now shared with the text session. A row whose own processor fails leaves the batch and is reported in-band as on the text session; on a drafted load, whose step decodes lazily, a row failing mid-step leaves after the step. Only resident sessions decode by id, and only without a draft model (the single path turns the draft off for tool turns): the fixed multi-reply vision command, drafted loads and an older unsloth-zoo keep refusing these rows as before, and with ids unavailable a vision row is planned exactly as before. Resident vision rows on a template with reasoning markers also decode from ids now, as the single path does. `_failing_alone`'s wrapper now keeps the wrapped processor's `history_only`, which a drafted batch reads to decide whether a row may draft; without it a penalty row would have stopped drafting for the whole batch. Validated with a differential test replaying the same token stream through `_generate_vlm` and through two concurrent resident vision rows (the tool-row cases of the text batch, the constrained planning cases, a prompt opening `<think>`, row failure, drafted and not), mutation-checked. The vision single path re-yields unchanged text on every response, so parity there is the same final reply with every batched snapshot one the single path showed. On Apple Silicon (Qwen3.5-0.8B-4bit) a tool call and a json_schema reply through the resident batch match the single path at width 1, both stay valid beside each other, and a schema whose only completion is the EOS text fails just its own row with the single path's `ResponseFormatError`.
…afted loads A resident MLX vision batch admits tool-protocol and response_format replies, decoded from token ids as `_generate_vlm` decodes them, but refused them whenever a speculative draft was loaded: `_generate_vlm` decodes tool turns without the draft, while a drafted batch drafted every row. Qwen3.5 checkpoints with MTP heads turn drafting on automatically, so agents on those loads were served one reply at a time. With an unsloth-zoo whose `GenerationRequest` has `drafts`, a drafted vision load now admits these rows. `_plan_vlm_row` marks a row undrafted under the same condition `_generate_vlm` drops the draft (`tools` or `tool_protocol_active`), and the session admits it with `drafts=False`, so it takes the target's own tokens while plain rows beside it keep drafting. Grammar rows were already kept off the draft per row, as their processor is not history-only. With an older unsloth-zoo nothing changes. On a drafted load the fixed multi-reply vision command also runs through the vision batch session, so its plain rows now decode from ids there too, as the resident batch and the single path do; it still refuses tool and constrained rows. Validated with the gate test over both unsloth-zoo capabilities, mutation-checked, against the installed and the updated unsloth-zoo. On Apple Silicon (Qwen3.5-4B-4bit with MTP drafting on) a tool call and a json_schema reply through the resident batch match the single path at width 1, stay valid beside each other, a schema whose only completion is the EOS text fails just its own row, and in a batch with a plain reply the tool row drafts no tokens while the plain row keeps drafting.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
An MLX chat request with more than one video clip was refused ("Only one video is supported per request on this model"), while GGUF forwards every clip. The non-GGUF route now serves every clip on the latest user turn, in request order (the legacy `video_base64` field first, then `video_url` parts), after the same request-wide count, scheme and size checks the GGUF path applies.
- The clips travel as a list (`videos` / `videos_base64`) through the orchestrator and worker to the MLX backend, which renders one video marker per clip, writes each clip to its own temp file for counting and generation, and removes them all afterwards.
- mlx-vlm decodes every clip before the processor runs, so the 2 GiB decode budget is split across the clips. Releases before 0.7.3 apply one `fps` to every clip, so the backend passes the slowest per-clip rate.
- Frame timestamps still come from mlx-vlm's processor, which reads each clip's own frame metadata (Qwen3-VL / Qwen3.5 stamp every two-frame group, Gemma 4 every frame), so each clip's stamps start at its own beginning.
- Video rows remain excluded from batched decoding, as before.
Gemma 4 took no video on MLX: Unsloth Studio reported `has_video_input` false and refused the clip. mlx-vlm's `Gemma4Processor.apply_chat_template` rebuilds each message from media counts and only re-adds video items for clip paths passed as `video=` (which it would then attach to every message), so a bare `{"type": "video"}` part renders as nothing. The capability probe saw a render identical to the text one, and a generation render would have lost the marker too.
A turn with video now renders through the processor's tokenizer when the processor renders, its tokenizer holds the same chat template, and the processor's own render of a video turn drops the marker. Processors that keep the marker keep rendering, since some deliberately differ from their tokenizer (MiniCPM-V's non-thinking prefix); other turns are unchanged. For Gemma 4 E2B the processor and tokenizer renders are otherwise identical (text, images, multi-turn, thinking), and Qwen3.5 / Qwen2.5-VL keep rendering through their processors.
Validated on Gemma 4 E2B through the MLX backend: two clips in one request reach the model with per-frame `mm:ss` timestamps, and a red-onset timing check answers within 1 s on 14 of 14 clips.
The n replies of a video request now decode as one unsloth-zoo stream_batch group instead of one at a time. Rows with the same clips share one temp file per clip so they stack, and divide the 2 GiB frame-decode budget between them; when the clips cannot fit that shared budget, each row gets its own files and decodes alone with the whole budget, as before. The open resident batch still refuses clips up front, because whether a clip row fits it is known only after its frames are decoded. Speculative loads, loads that do not read video, an mlx-vlm without the video decoder, and an unsloth-zoo without GenerationRequest.videos keep serving video replies one at a time.
…enizer; answer a failed reply when withdrawing its siblings fails [skip ci]
|
Review record for #15920, carried over from the mirror it was reviewed on: danielhanchen/unsloth-staging-review#612. 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
|
…ow opt out of drafting, and batch video rows (unslothai#2237) ## Summary Two small additions to the MLX batched generation API that let Unsloth Studio batch agent-style replies (tool calls and `response_format`) on vision loads, including loads with a speculative (MTP) draft. A third lets batched vision rows carry video clips, so the several replies of one video request decode together. ### Report the token ids each batched event sampled `GenerationEvent` gains `token_ids`: the ids that event sampled, each reported once, including the stop id that ended the row (which `result.token_ids` leaves out). A caller that decodes replies itself from ids (native tool-call controls, a stop id kept only when it closes a tool envelope, a grammar told which ids the decoder drops) needs exactly these; text deltas lose them. The field defaults to `()` and comes last, so positional construction and existing consumers are unaffected. ### Let a speculative batch row opt out of drafting `GenerationRequest.drafts` (default `True`) is passed to `EngineRow.drafts`. A row with `drafts=False` never starts a drafter state and is offered no copy proposals, so it takes only the target's own tokens, as a reply decoded without speculation draws them. Other batch kinds ignore the field. A caller whose single-reply path decodes some replies without the draft (Unsloth Studio does this for tool-protocol turns) can now keep those rows in a drafted batch instead of refusing them. `_plain` pipelining was keyed on every row speculating, but its actual precondition is that every row's logits processors read only the token history (a processor that reads more needs each token before the next step). It now keys on that, so an undrafted plain row does not stop the batch pipelining. With `drafts=True` the two conditions are identical, so existing callers see no change. ### Batch vision rows that carry video clips Before this, a batched row had no way to carry a clip, so a caller serving several replies to one video request decoded them one at a time. - **New fields:** `GenerationRequest` gains `videos` (clip paths) and `fps` (the processor's own rate when `None`). Both are added after the existing fields. - **Inputs:** `_VLMBatchAdapter._prompt_inputs` hands every row's clips, in row order, to mlx-vlm `prepare_inputs(videos=, fps=)`. That keyword exists since mlx-vlm 0.5.0, the release that added `load_video`. - **Grouping:** `_group_key` adds `(clips, fps)` to the prompt-row key. A clip sets the row's frame count, and with it the vision-token count and pixel shapes, so only rows with the same clips and rate stack. Rows without clips key exactly as before. - **Refusals:** - beside `prompt_token_ids`, since only the processor can place media tokens; - beside audio, which decodes on its own; - on text models; - a bare string as `videos` (`TypeError`); - a non-positive `fps` (`ValueError`). - **Shared decode cost:** rows of one group decode their clips together in one `prepare_inputs` call, so the caller sizes the frame budget for the group. Unsloth Studio divides its budget by the rows that share the clips. - **Not exercised:** the resident and speculative `BatchStream` accept clip rows through the same path but never receive them. Unsloth Studio keeps video out of the open batch, because a clip row's fit is only known after its frames are decoded. ## Validation ```text tests/test_mlx_speculative.py, tests/test_mlx_generate.py pass tests/test_mlx_speculative_metal.py::test_speculative_batch_stream_rows_join_and_leave_as_if_decoded_alone pass (Apple Silicon) ``` - Unit test: a vision row reports every id it sampled, the stop id included and the last id of a `length` finish not duplicated. - Unit test: a row kept off the draft never drafts, and pipelines exactly when its processors allow. - Metal test: an undrafted row joining a drafted batch mid-stream decodes the same ids as a drafted row with the same prompt and drafts no tokens. - Unit tests for video rows: - clip paths are normalised, and clips and fps reach the processor in row order; - the group key separates rows by clips, rate and no clips; - every refusal case is covered. - The new tests were mutation-checked (each fails when the change it covers is reverted; 12/12 for the video rows). - End to end on Apple Silicon (through the Unsloth Studio change), a two-reply video request runs as one 2-row chunk with the single path's prompt token count: - Qwen3.5-0.8B and Gemma 4 E2B on the current branch; - a shrunken Qwen3-VL-2B checkpoint before this branch was rebased. - End to end with the companion Unsloth Studio change on Qwen3.5-4B-4bit with MTP drafting on: tool and `json_schema` replies through a resident batch match the single path at width 1; in a batch with a plain reply the tool row drafts 0 tokens while the plain row keeps drafting. Companion Unsloth Studio PR: unslothai/unsloth#15920 --------- Co-authored-by: Daniel Han <[email protected]>
Summary
Coding agents (Claude Code, Codex, OpenCode over
/v1/messagesand/v1/chat/completions) and structured-output clients were served one reply at a time on MLX, even with Parallel Slots above 1: every MLX batch refused a reply carryingtools,tool_protocol_activeorresponse_format, and a refused reply held everything queued behind it until the batch drained. On vision loads (Qwen3.5, Gemma and other models that load as vision models) the same replies were refused, and on drafted loads (Qwen3.5 checkpoints with MTP heads turn speculative decoding on automatically) as well.This lets those replies join the resident MLX batch, decoded exactly as the one-at-a-time path decodes them.
It also brings MLX video chat up to the GGUF path (see Video on MLX chat below):
Depends on unslothai/unsloth-zoo#2237 for vision rows (
GenerationEvent.token_ids,GenerationRequest.drafts); with an older unsloth-zoo, text loads batch these replies and vision loads keep refusing them as before.Root causes and changes
_generate_text: noNativeToolTokenDecoder, so native tool controls were stripped as special tokens, a trailing stop id that closes a tool envelope was lost, and native reasoning channels went through mlx-lm's plain detokenizer._plan_text_rownow builds the same decoder, stop-id rule (shared helper_native_reply_text) and_MlxStreamedTextthe single path uses; the session feeds it id by id and flushes a row's held text when it ends or is withdrawn.response_formatreplies (text loads). No grammar constraint was built for batch rows, and a processor exception inside mlx-lm'sBatchGenerator.next()failed every request in the batch._plan_text_rownow builds the constraint exactly as_generate_textdoes. A row's processor error is kept on that row: the session withdraws it and reports(handle, exception)in-band ahead of the step's other events, the resident worker answers that request with the error the single path would send, and the other rows keep decoding._generate_vlmdecodes these replies from ids. WithGenerationEvent.token_ids,_plan_vlm_row(decodes_ids=True)mirrors_generate_vlm(think prefix that keeps a</think>the decoder preserves, grammar constraint with its stop ids and dropped ids, document-only constraints,_MlxStreamedTextover the row's ids). Row failures are isolated as on the text session; on a drafted load, whose step decodes lazily, a row failing mid-step leaves after the step._failing_alone's wrapper now keeps the wrapped processor'shistory_only, which a drafted batch reads per row._generate_vlmdecodes tool turns without the draft, while a drafted batch drafted every row. WithGenerationRequest.drafts, a tool row is admitted withdrafts=False(same condition_generate_vlmuses), so it takes the target's own tokens while plain rows beside it keep drafting. Grammar rows were already kept off the draft per row.Still refused: replayed tool images,
n_probs, raw prompts on vision loads, and video in the resident batch (video replies batch only as the replies of one request, below).Video on MLX chat
Before this, MLX chat kept only the first clip of a request, while GGUF accepts several. Gemma 4 had no video at all, and the n replies of a video request decoded one at a time.
Several clips per request
_request_video_rejection).videos,videos_base64).fps.<t.t seconds>once per 2-frame temporal group, the spacing Studio: timestamp every other sampled video frame for GGUF chat #14254 chose for GGUF; Gemma 4 writesmm:ssper frame. No llama.cpp-style labels are injected, since labels between frames would split Qwen's temporal patches.Gemma 4 video
Gemma4Processor.apply_chat_templaterebuilds each message from media counts and only re-adds video items for real clip paths. A bare{"type": "video"}part therefore vanished, and the probe reportedhas_video_input = False.<|video|>.Batched video replies
stream_batch(needsGenerationRequest.videosfrom MLX batch: report each event's sampled token ids, let a speculative row opt out of drafting, and batch video rows unsloth-zoo#2237).Risks and tradeoffs
Validation
generate_chat_response/_generate_vlmand through two concurrent batch rows (native channels, unrestricted tool mode, stop on a closer and on an opener, length finish, stop sequences, withdraw, constrained planning, row failure beside healthy rows), mutation-checked.json_schemareply through the resident batch match the single path at width 1 (Qwen3-4B-4bit text; Qwen3.5-0.8B-4bit and Qwen3.5-4B-4bit vision, the latter with MTP drafting on); they stay valid beside each other; a schema whose only completion is the EOS text fails just its own row with the single path'sResponseFormatError.Throughput, four agent-style tool requests (shared warmed system + tool prefix, up to 400 tokens, temperature 0), served one at a time vs. in one resident batch, best of two alternating rounds, every reply parsing as one tool call:
Video, on Apple Silicon:
<t.t seconds>stamps and are described correctly.