Repository navigation
Studio: timestamp every other sampled video frame for GGUF chat - #14254
Conversation
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. |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d73c587240
ℹ️ 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".
| if server_caps.get("supports_video_fps") | ||
| else _LLAMA_SERVER_DEFAULT_VIDEO_FPS | ||
| ) | ||
| flags += ["--video-timestamp-interval", str(max(1, int(2000 / fps)))] |
There was a problem hiding this comment.
Avoid truncating fractional two-frame intervals
For frame rates where 2000 / fps is non-integral, truncation makes the timestamp threshold advance slightly faster than the frames, so labels eventually land on odd frames and split the Qwen-VL pairs this change is intended to preserve. For example, --video-fps 29.97 emits the documented millisecond interval as 66; under the threshold logic modeled by the new test, the first mismatch occurs around frame 91 (about three seconds), while the test stops at 120 frames only for rates whose drift takes longer. Preserve sufficient precision if llama-server accepts it, or avoid claiming/enforcing two-frame spacing for rates that cannot be represented by an integral millisecond interval. The upstream help defines this option as an interval in milliseconds between text timestamps.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
llama-server parses this flag as an int (common/arg.cpp), so more precision is not possible. The default 1 fps and the usual typed rates (0.5, 2, 4) give exact intervals. A drift only happens for a non-integral rate typed by hand (for 29.97 fps after about 45 labels), and then it only costs some prompt tokens on Qwen-VL; the timestamps themselves stay correct.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
…everal clips and Gemma 4 video on MLX (unslothai#15920) ## 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 unslothai#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 unslothai/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 ```text 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). --------- Co-authored-by: Daniel Han <[email protected]>
Fixes #9962
When a video is attached to a GGUF chat model, llama-server samples it at the rate Studio sets (1 fps) but only writes a text timestamp into the prompt every 5 seconds. The model has to guess the time of the frames in between, and in practice it snaps every event to the nearest 5 second mark. That is the wrong timestamps reported in #9962 when captioning a clip.
Change
Studio now passes
--video-timestamp-intervalalongside--video-fps, set to two sampled frames (2000 ms at the default 1 fps). The interval follows the frame rate the user actually asked for, so--video-fps 2in the advanced llama-server arguments (orLLAMA_ARG_VIDEO_FPS) gives frames 0.5 s apart with a timestamp every second. That is the existing way to control frame spacing, and it now produces matching timestamps instead of a fixed 5 s grid.--video-timestamp-intervaltyped in the advanced arguments, orLLAMA_ARG_VIDEO_TIMESTAMP_INTERVALin the environment, still wins and Studio adds nothing.--helpare not sent it (same capability probe as--video-fps).Why two frames rather than every frame: llama.cpp writes each timestamp after its frame, and Qwen-VL models merge consecutive frame pairs into one temporal patch. A timestamp between every frame splits every pair, which raised Qwen3-VL prompt tokens by 1.7x. At two frames the pairs stay whole (prompt is slightly smaller than today), and Gemma 4 placed events most accurately at this spacing too.
Results
Synthetic 20 s, 640x360 clips: a gray screen that turns red for 2 s starting at a known second (14 clips, starts at 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 16, 17, 18 s). Prompt: "At what time, in seconds from the start of the video, does the screen first turn red?" Temperature 0,
--video-fps 1, llama.cpp prebuilt b11719, Q4_K_M with F16 projector.Before the change, Gemma 4 E2B answered "5" for every clip starting at 2 through 8 s, and the Qwen models answered 5 or 10 for most clips. With no timestamps at all, Gemma answered numbers like 1000 and 1600, so the labels are what the model reads time from.
For reference, typing
--video-fps 2 --video-timestamp-interval 500in the advanced arguments brought Gemma 4 E4B to a mean error of 0.21 s (14/14 within 1 s) at 4659 prompt tokens, so users who need finer timing can still trade prompt length for it.Verification
tests/test_llama_video_frame_budget.py: 8 new tests (default interval, interval follows a typed or inherited frame rate, typed or inherited interval left alone, builds without the flag, labels land on every other frame, capability probe). 40 passed; 5 of the new tests fail with thellama_cpp.pychange reverted.test_server_tuning_flags,test_llama_cpp_placement,test_load_mode_fit_matrix,test_metal_explicit_context_guard,test_model_memory_settings,test_llama_flag_catalog,test_video_chat_completions_behaviour): 2852 passed, 32 skipped.--video-fps 1 --video-timestamp-interval 1000loads and answers normally.