Skip to content

Studio: batch MLX tool-protocol, response_format and video replies; several clips and Gemma 4 video on MLX - #15920

Merged
danielhanchen merged 12 commits into
unslothai:mainfrom
Lyxot:mlx-batch-agent-rows
Oct 29, 2026
Merged

danielhanchen merged 12 commits into
unslothai:mainfrom
Lyxot:mlx-batch-agent-rows

Conversation

@Lyxot

@Lyxot Lyxot commented Oct 29, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Coding agents (Claude Code, Codex, OpenCode over /v1/messages and /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 carrying tools, tool_protocol_active or response_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):

  • several clips per request;
  • Gemma 4 reading video;
  • the several replies of one video request decoding as one batch.

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

  • Tool-protocol replies (text loads). A batch row decoded its text differently from _generate_text: no NativeToolTokenDecoder, 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_row now builds the same decoder, stop-id rule (shared helper _native_reply_text) and _MlxStreamedText the single path uses; the session feeds it id by id and flushes a row's held text when it ends or is withdrawn.
  • response_format replies (text loads). No grammar constraint was built for batch rows, and a processor exception inside mlx-lm's BatchGenerator.next() failed every request in the batch. _plan_text_row now builds the constraint exactly as _generate_text does. 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.
  • Vision loads. unsloth-zoo's vision batch reported text only, while _generate_vlm decodes these replies from ids. With GenerationEvent.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, _MlxStreamedText over 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's history_only, which a drafted batch reads per row.
  • Drafted vision loads. _generate_vlm decodes tool turns without the draft, while a drafted batch drafted every row. With GenerationRequest.drafts, a tool row is admitted with drafts=False (same condition _generate_vlm uses), 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

  • Route: returns every clip on the latest user turn, with the same count, scheme and size checks as GGUF (_request_video_rejection).
  • Plumbing: the orchestrator, worker and MLX backend carry a list (videos, videos_base64).
  • Decoding: the backend writes, counts and samples every clip. mlx-vlm decodes all clips of a request before the processor runs, so the 2 GiB frame-decode budget is split across them. One sampling rate covers all clips, because mlx-vlm releases before 0.7.3 take a scalar fps.
  • Timestamps: mlx-vlm's processors already write them from each clip's frame metadata. Qwen3-VL and Qwen3.5 write <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 writes mm:ss per frame. No llama.cpp-style labels are injected, since labels between frames would split Qwen's temporal patches.

Gemma 4 video

  • Root cause: mlx-vlm's Gemma4Processor.apply_chat_template rebuilds 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 reported has_video_input = False.
  • Fix: a turn with video now renders through the tokenizer, in both the probe and generation. This happens only when the processor's own render of a video probe drops the marker and its chat template equals the tokenizer's.
  • Measured:
    • Gemma 4 E2B: the two renders differ only by the dropped <|video|>.
    • Qwen3.5 and Qwen2.5-VL: renders are identical, so nothing changes for them.

Batched video replies

  • Path: the fixed n-reply command batches video replies through unsloth-zoo stream_batch (needs GenerationRequest.videos from MLX batch: report each event's sampled token ids, let a speculative row opt out of drafting, and batch video rows unsloth-zoo#2237).
  • Shared files and budget: rows with the same clips share one temp file per clip, so unsloth-zoo groups them, and they divide the decode budget. With n>1 replies, a long high-resolution clip may therefore sample fewer frames per reply.
  • Fallback: clips that cannot fit the shared budget at the minimum frame count give each reply its own files, and each reply decodes alone with the whole budget, as before.
  • Cleanup: clip files live for the batch and are removed on completion, cancel or error.
  • Open resident batch: it refuses clips up front, because a clip row's fit is only known after its frames are decoded, and any text or image row beside it would refuse it.
  • Kept one at a time: drafted loads, loads that do not read video, an mlx-vlm without the video decoder, and an older unsloth-zoo.

Risks and tradeoffs

  • At batch width above 1, greedy output can differ from the single path for any row, plain ones included, because batched prefill, left padding and quantized matmuls at more than one row change the numerics. That predates this change; parity here is token-for-token at width 1 and, at any width, the same decode given the same sampled ids.
  • Side effects: rows on a template with native reasoning channels now decode exactly as the single path does even without tools; on a drafted vision load the fixed multi-reply command (which runs through the same session there) decodes plain rows from ids too. It still refuses tool and constrained rows.

Validation

studio/backend/tests/test_mlx_inference_backend.py
studio/backend/tests/test_mlx_resident_batch.py
studio/backend/tests/test_mlx_speculative.py
  pass, against both the current unsloth-zoo release and the companion unsloth-zoo branch
  • Differential tests replay the same token stream through generate_chat_response / _generate_vlm and 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.
  • On Apple Silicon: a tool call and a json_schema reply 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's ResponseFormatError.

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:

Model Width One at a time Batched Speedup
Qwen3-4B-4bit 2 5.47 s 3.33 s 1.64x
Qwen3-4B-4bit 3 7.38 s 3.28 s 2.25x
Qwen3-4B-4bit 4 9.18 s 3.92 s 2.34x
Qwen3.5-4B-4bit (vision, drafting off) 4 8.34 s 5.43 s 1.53x
Qwen3.5-4B-4bit (vision, MTP drafting on) 4 8.30 s 5.61 s 1.48x

Video, on Apple Silicon:

  • Two clips in one request (Qwen3.5-0.8B): both clips get per-clip <t.t seconds> stamps and are described correctly.
  • Onset sweep, 14 single 20 s clips: 14/14 within 1 s on Qwen3.5-0.8B; on Gemma 4 E2B also 14/14, mean error 0.5 s.
  • n=2 batched video request (Qwen3.5-0.8B and Gemma 4 E2B):
    • runs as one 2-row unsloth-zoo chunk, with prompt tokens equal to the single path;
    • the open batch refuses the clip, and no clip file is left;
    • Gemma 4 batched replies equal the single reply.
  • Tests: the video and batching tests were mutation-checked (24/24 caught).

Lyxot added 4 commits October 29, 2026 14:59
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.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 29, 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 ⚠️ Failed 2026-10-29T07:31:06.414755Z
We couldn’t complete this review. Comment @codex review to try again.
ca88fc1 PR opened
ℹ️ 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.

Lyxot added 3 commits October 29, 2026 15:45
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.
@Lyxot Lyxot changed the title Studio: batch MLX tool-protocol and response_format replies, on text, vision and drafted loads Studio: batch MLX tool-protocol, response_format and video replies; several clips and Gemma 4 video on MLX Oct 29, 2026
@danielhanchen danielhanchen self-assigned this Oct 29, 2026
…enizer; answer a failed reply when withdrawing its siblings fails

[skip ci]
@shimmyshimmer

Copy link
Copy Markdown
Member

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 d948b7324 (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] on studio/backend/core/inference/mlx_inference.py (on the mirror)

@@ -4452,22 +4628,36 @@ def step(self, waiting = None):
         now, stopped = None, {}
         # Only a speculative step spans many tokens, reported as they are decoded; only its unsloth-zoo has the call.
         # The batch cannot change mid-step, so a row that stopped itself ends the step and leaves after it.
-        for event in (
-            self.stream.iter_step(lambda: bool(stopped) or (waiting is not None and waiting()))
+        failing = {}
+        events = (
+            self.stream.iter_step(
+                lambda: bool(stopped or failing) or (waiting is not None and waiting())
+            )
             if self._speculative is not None
             else self.stream.step()
-        ):
+        )
+        # As in _TextBatchSession.step: reported before the step's tokens, which it never yields.
+        yield from self._fail([row for row in self._rows.values() if row.failure is not None])
+        for event in events:
             row = self._by_row.get(event.index)
             if row is None:
                 continue
+            if row.failure is not None:
+                # Only a drafted step decodes as it is read, so a row can fail mid-step and leave after it.
+                failing[row.handle] = row
+                continue
             if now is None:
                 now = time.perf_counter()
             if row.ready_at is None:
                 row.ready_at = now
-            if event.delta and not row.cancelled:
-                yield from (
-                    (row.handle, snapshot) for snapshot in row.plan.stream.feed(text = event.delta)
-                )
+            streamed = row.plan.streamed
+            text = (
+                event.delta
+                if streamed is None
+                else "".join(streamed.feed_token(int(token)) for token in event.token_ids)

P2 Badge Preserve the fallback when no independent detokenizer is available

When _mlx_stream_detokenizer cannot copy, rebuild, or reset either available detokenizer, _plan_vlm_row still creates a non-null _MlxStreamedText containing a null detokenizer. Calling feed_token() directly here then raises AttributeError on the first non-suppressed token because it unconditionally calls self._detokenizer.add_token(). The single-reply path explicitly supports this situation through feed()'s runtime-text fallback, but admitting the same tool or native-reasoning reply to the resident batch now fails the entire batch, including healthy neighboring requests. Preserve that fallback or decline batch admission when an independent detokenizer is unavailable.

Useful? React with 👍 / 👎.

Accepted on the mirror

Reply from danielhanchen:

Fixed in 5e69e0f: a batch row decoded from ids now refuses admission when no independent detokenizer exists, so it decodes alone on the single path.

Round 2: reviewed mirror d948b7324 (no equivalent commit found on this PR)

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

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: d948b73243

No triage reaction was recorded on the mirror

Round 3: reviewed mirror 18bd2a252 (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] on studio/backend/core/inference/mlx_inference.py (on the mirror)

@@ -3849,6 +3926,14 @@ def feed(
             return [self._prefix + self.sampled[: self._cut]]
         return []
 
+    def flush(self, text):
+        """Text a decoder held until the reply ended; under stop sequences ``settle`` delivers it."""
+        if not self._sequences:
+            return self.feed(text = text)
+        self.sampled += text
+        self._cut, self.stopped = _mlx_stop_cut(self.sampled, self._sequences)
+        return []

P2 Badge Release text preceding a stop found during the final flush

For a resident VLM tool reply without reasoning-channel markers, the row has a streaming detokenizer but no normalizer or snapshot decoder. If finish() releases buffered text containing a requested stop sequence, this method sets self.stopped and returns no snapshot; settle() then also returns nothing because its append-only branch requires not self.stopped. Consequently, valid text before the stop is silently lost. For example, an already-emitted already followed by a buffered tail of remaining HALT with stop HALT never delivers remaining . Emit the newly available prefix through _cut even when the flush discovers a stop, matching the single-reply path.

Useful? React with 👍 / 👎.

Accepted on the mirror

Reply from danielhanchen:

Fixed in 4a47806: without a normalizer or snapshot decoder the final flush goes through feed, which releases the text up to the stop.

Round 4: reviewed mirror 640e539496 (this PR's 4a47806ef)

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

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

Reviewed commit: 640e539496

No triage reaction was recorded on the mirror

Verdict

The round converged at mirror 640e539496 (this PR's 4a47806ef).

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 cb07e19 into unslothai:main Oct 29, 2026
52 of 55 checks passed
diablomike20 pushed a commit to diablomike20/unsloth-zoo that referenced this pull request Oct 29, 2026
…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]>
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.

3 participants