Skip to content

Studio: stop a short chat video attachment from taking minutes to prefill - #10973

Merged
danielhanchen merged 9 commits into
unslothai:mainfrom
oobabooga:worktree-studio-video-frame-budget
Sep 15, 2026
Merged

danielhanchen merged 9 commits into
unslothai:mainfrom
oobabooga:worktree-studio-video-frame-budget

Conversation

@oobabooga

Copy link
Copy Markdown
Member

Attaching a short video to a GGUF chat model can leave Studio in "Generating" for several minutes. This was reported on Reddit with Gemma 4 31B Q4_K_M on a 24 GB GPU. With this change, a 5-second clip on that setup answers in about 20 seconds instead of about 4 minutes.

Cause and fix

llama-server samples video at 4 fps by default and encodes every sampled frame at the clip's original resolution. On Gemma 4, a 720p frame costs about 400 prompt tokens and a 1080p frame about 900. When the projector is on the CPU, a 5-second 720p clip becomes 20 frames and 8,183 prompt tokens, taking 231 seconds to reach the first token.

Long clips also consume substantial memory before llama-server checks the context limit. A 90-second 1080p clip raised Qwen3.5-4B's resident server memory from 1.3 GB to 19.0 GB before being refused, then to 28.0 GB on a second attempt.

This PR reduces both dimensions of that cost:

  • Studio adds --video-fps 1 to every launch of a llama-server build that has the flag. That covers projectors from Studio, from --mmproj-auto in the advanced arguments, and from LLAMA_ARG_MMPROJ; llama-server ignores it when no projector loads. Gemma 4 documents video at up to one frame per second. Advanced --video-fps arguments still win, and LLAMA_ARG_VIDEO_FPS suppresses Studio's default.
  • Before attaching a GGUF chat video, Studio scales frames larger than a 640x360 pixel area. Portrait and landscape clips receive the same pixel budget, phone rotation is applied correctly, and timing is preserved so llama-server still controls frame sampling.
  • Unsupported binaries and missing, failed, or timed-out ffmpeg operations keep the previous behavior by forwarding the original clip.

The conversion uses ffmpeg and ffprobe on PATH, runs after the existing 64 MB check, and runs in a worker thread.

Results

Gemma 4 31B Q4_K_M on an RTX 3090 24 GB, with 24,320 context and the projector on the CPU:

Clip Before: first token Before: prompt tokens After: first token After: prompt tokens
5 s, 1280x720 231 s 8,183 22 s 573
12 s, 1280x720 536 s 19,598 36 s 1,334
5 s, 1080x1920 portrait 664 s 18,483 19 s 573

Both versions identified the changing captions correctly in all three clips.

For Qwen3.5-4B with a GPU projector and 262,144 context, a 90-second 1080p clip changed from a context refusal at 369,808 tokens to a correct answer in 6 seconds with 12,194 prompt tokens. Resident server memory after two attempts was 28.0 GB before and 2.9 GB after.

Resizing took 0.2 seconds for the 5-second clip and 1.3 seconds for the 90-second clip.

Verification

  • Added 15 tests covering launch capability detection, advanced and environment overrides, projectors supplied through --mmproj-auto or LLAMA_ARG_MMPROJ, real ffmpeg resizing and rotation, failure fallbacks, and route ordering.
  • 4,404 tests passed and 32 skipped across the affected inference and video suites, and 3,643 passed and 35 skipped across the llama and GGUF suites.
  • A text-only GGUF launched with --video-fps 1 and answered a chat request normally.
  • ruff check and scripts/run_ruff_format.py pass on the changed files.

Tradeoffs and scope

  • This changes only the GGUF chat route. MLX video handling and tool passthrough are unchanged.
  • The 640x360 area budget can lose fine detail, especially small text, and currently has no setting.
  • The policy follows Gemma 4's low-detail video guidance but does not reproduce its processor exactly: Google's config samples 32 frames across the clip at 70 tokens each, while this samples by duration at about 100.
  • Qwen3-VL's reference processor uses 2 fps and one pixel budget shared across all frames, so short Qwen clips get noticeably less detail here than in Transformers; around 60 seconds the two are similar. --video-fps 2 in the advanced arguments restores the frame rate. This PR does not add the frame-spacing UI requested in [Feature] Allow controlling spacing of images when processing video in chats (currently 0.5s) #9962.
  • Projector placement, repeated clip attachment on follow-up turns, prompt-processing progress, and llama-server's remaining decoded-frame memory are unchanged.
  • Tested on Linux with ffmpeg 6.1.1. Windows and macOS were not run.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3c27a0c608

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread studio/backend/routes/inference.py Outdated
video_b64, video_rejection = _video_b64_rejection(payload.video_base64)
if video_rejection is not None:
raise _reject(*video_rejection)
video_b64 = await asyncio.to_thread(shrink_video_for_llama, video_b64)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Limit video conversions before spawning ffmpeg

When multiple clients submit oversized videos concurrently, every request reaches this to_thread call before _openai_llama_admission_reserve and before the disconnect watcher is created. Each worker may therefore run an ffmpeg process for up to 300 seconds, and cancelling or disconnecting the request does not stop the underlying thread, allowing a small burst of uploads to saturate CPU and the shared executor and delay unrelated inference work. Put conversion behind a bounded admission/semaphore and make the subprocess cancellable.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing this. It does not produce wrong output, a crash, or data loss. The conversion runs in the same place and the same way as the existing audio transcode (asyncio.to_thread(_prepare_audio_for_llama, ...) before admission, also not cancellable). The input is capped at 64 MB, the ffmpeg run has a timeout, and after 09eb117 the encoder also stops once its output reaches the 64 MB cap, which bounds the run for long clips. A 2-minute 1080p clip converts in about 1.5 s.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 15, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 09eb117264

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: 8961c6bca2

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

The scale filter changed the frame size but not the frame rate, so a 30 fps
source was re-encoded at 30 fps while this same change tells llama-server to
sample it at 1. Twenty-nine frames in thirty were encoded, counted against
max_bytes, and then dropped by mtmd.

Those wasted bytes are not free, because they are what the cap guard measures.
A legal 53 MB 12-minute 1080p30 upload transcodes to more than 64 MB, so the
guard fires and the ORIGINAL full-size clip is forwarded -- after a 25 second
ffmpeg pass. The slowest clips, which is the case this whole change exists for,
paid the conversion and got none of it:

    as merged      wall 24.7s   out 53.0MB   shrink applied: no
    fps=4 first    wall 10.7s   out 16.9MB   shrink applied: yes

Cap at MAX_FRAME_RATE = 4, llama-server's own --video-fps default, rather than
at the 1 Studio asks for. Then no configuration samples a frame the container
no longer has: Studio asks for 1, a build too old for --video-fps samples at 4,
and the documented Qwen override of 2 is still whole.

The cap only ever reduces. ffmpeg's fps filter DUPLICATES frames when asked for
more than the source has, so a 1 fps timelapse would come back four times
heavier; the rate now comes back from the probe alongside the area and the
filter is only prepended when the source is genuinely faster.

Measured on Qwen3-VL-2B-Instruct-Q4_K_M with llama.cpp b10976, 5s 720p clip:
prompt tokens are unchanged at every sampling rate (10172 / 2472 / 2796 / 696
for original-4fps / shrunk-4fps / original-1fps / shrunk-1fps) while the
attachment drops from 966,757 to 211,690 bytes. The model reads the burned-in
per-second captions back correctly either way.

Also in this change, all from the same review pass:

* Reject through _reject when the conversion raises, like the audio path
  directly above it. The helper absorbs its own ffmpeg failures, so anything
  reaching the route is unmodelled -- previously a raw 500 with a non-OpenAI
  body, and a leaked api_monitor entry with it.
* Fall back instead of raising AttributeError when ffprobe answers `-of json`
  with something that is not an object.
* Drop the decoded copy once it is on disk. It was held to the end only so the
  log line could read len(raw), keeping 64 MiB alive beside the output and both
  base64 strings.
* Correct the -q:v comment: -fs bounds the result at the upload cap, it does
  not keep it near the source size. Near-static 1080p still grows ~3.4x.

Tests: frames beyond the sampled rate are not re-encoded, a clip slower than
the cap keeps every frame, a long clip is really shrunk rather than forwarded,
and a non-object probe falls back. The route-ordering test matched source text,
so it stayed green when the conversion's result was discarded and the original
injected -- a change that silently disables the feature. It is now paired with
an AST check that the awaited call is bound and that the bound name is the one
_inject_video_part receives; verified to fail on exactly that edit.

23 pass, 0 skipped, with real ffmpeg 6.1.1. ruff 0.6.9 check and
scripts/run_ruff_format.py are clean.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 15, 2026
@danielhanchen

Copy link
Copy Markdown
Member

Thank you for the PR! The goal of this PR is to stop a short video attachment on a GGUF chat model from spending minutes in prefill. As a summary, it pins --video-fps 1 on every llama-server launch whose build advertises the flag, and downscales attached clips to a 640x360 pixel-area budget with ffmpeg before they are forwarded, falling back to the original clip whenever anything is missing or fails.

I reproduced the problem and the fix independently on Qwen3-VL-2B-Instruct Q4_K_M with llama.cpp b10976, using a 5s 720p clip, ffmpeg 6.1.1. Four conditions, to separate the two interventions:

Condition Prompt tokens TTFT
A original clip, --video-fps 4 (before) 10,172 43.6s
B shrunk clip, --video-fps 4 2,472 (24.3%) 0.76s
C original clip, --video-fps 1 2,796 (27.5%) 0.87s
D shrunk clip, --video-fps 1 (this PR) 696 (6.8%) 0.39s

A 93.2% token reduction, against the 93.0% you measured. The two changes compose almost exactly multiplicatively (0.243 x 0.275 = 0.067), so neither one is redundant. TTFT here is not comparable to your 3090 numbers, this is a B200.

I also ran the affected suites on main and on the PR head: 214 failures on each, and the two failure sets are byte identical, so there are no new failures. Those are pre-existing video-generation suites unrelated to this change.

Committed in 0064f45

The re-encode kept the source frame rate. The chain scaled the frames but never touched the rate, so a 30 fps source was re-encoded at 30 fps while this same PR tells llama-server to sample it at 1. Those extra frames are not free, because they are what the cap guard measures. A legal 53 MB, 12 minute, 1080p30 upload transcodes past 64 MB, trips >= max_bytes, and the original full-size clip is forwarded anyway, after a full ffmpeg pass:

as merged      wall 24.7s   out 53.0MB   shrink applied: no
fps=4 first    wall 10.7s   out 16.9MB   shrink applied: yes

So the longest clips, which are the ones this PR exists for, paid the conversion and got none of it. I capped at MAX_FRAME_RATE = 4, llama-server's own --video-fps default rather than the 1 Studio asks for, so no configuration samples a frame the container no longer has: Studio asks for 1, a build too old for the flag samples at 4, and the Qwen override of 2 you document is still whole.

The cap only ever reduces. ffmpeg's fps filter duplicates frames when asked for more than the source has, so a 1 fps timelapse would have come back four times heavier; the rate now comes back from the probe beside the area, and the filter is only prepended when the source is genuinely faster. Verified: prompt tokens are unchanged at every sampling rate while the attachment drops from 966,757 to 211,690 bytes.

Also in that commit, smaller and from the same pass:

  • Reject through _reject when the conversion raises, matching the audio path directly above. Previously a raw 500 with a non-OpenAI body, and a leaked api_monitor entry with it.
  • Fall back rather than raising AttributeError when ffprobe answers -of json with a non-object.
  • Drop the decoded copy once it is on disk, it was held to the end only so the log line could read len(raw).
  • Corrected the -q:v comment: -fs bounds the result at the upload cap, it does not keep it near the source size. Near-static 1080p still grows about 3.4x.

One test was worth replacing. test_the_gguf_route_shrinks_the_clip_after_the_size_check_and_before_injection matches source text. I deleted just the assignment, so the conversion runs and its result is discarded and the original is injected, which silently disables the whole feature, and all 16 tests still passed. It is now paired with an AST check that the awaited call is bound and that the bound name is the one _inject_video_part receives, confirmed to fail on exactly that edit.

One regression that needs your call

Forcing 1 fps makes sub-second clips arrive with no frames at all. Measured against a real server, same model, prompt tokens:

Clip --video-fps 1 --video-fps 4
0.2s 21 252
0.3s 21 252
0.5s 252 474
1.0s 252 696

21 tokens is the bare text prompt, the video contributed nothing. At the previous default of 4 those clips worked. The cause is ffmpeg's fps filter emitting no frame when the clip is shorter than one sampling interval, inside llama-server's own -vf fps=1.000000 invocation, so info.n_frames rounding is a symptom rather than the cause and Studio cannot reach the filter options.

I did not fix this, because every option is a design decision that is yours: the flag is chosen at launch and cannot vary per request, and the helper currently only runs for clips above the pixel budget, so a small short clip skips it entirely. Padding short clips in the helper, running the helper unconditionally, or choosing a different default all change the feature's shape. Repro script and logs available if useful.

Raised, not changed

  • Clip duration is still unbounded. At 1 fps the frame count equals the duration in seconds, and a 52.7 MB one-hour 640x360 clip fits the 64 MB upload cap, which is roughly 3,600 frames. _MAX_AUDIO_SECONDS exists on the audio path for exactly this shape. ffprobe is already being run, so duration is one field away.
  • Conversion concurrency. I measured event-loop gaps rising from 51ms to 407ms with 16 concurrent conversions, and ffmpeg taking about 4.8x parallelism per conversion. On a 4-core laptop that is the whole machine. I understand your reasoning for declining to gate this, I am only adding the measurement.

Checked and clear, so nobody re-chases them

  • -fs truncation. I swept max_bytes across and around the natural transcoded size looking for an accepted-but-truncated clip. The boundary is exact: 966,757 falls back, 966,758 returns a complete 150/150 frame clip. The guard is sound.
  • Crafted playlist local file read. Several automated reviewers flagged this. It is not reachable: ffmpeg's concat demuxer refuses absolute paths as Unsafe file name without -safe 0, and the extensionless temp file defeats m3u8 detection. Six payload shapes, all forwarded unchanged.
  • Rotation, timing, degraded environments. Real display-matrix rotation comes out upright; frame timing is preserved within one frame interval on CFR, VFR, 60s and low-bitrate fixtures. 39 edge cases pass, including missing ffmpeg and ffprobe, which is the stock state on macOS and Windows and correctly forwards the clip untouched, plus non-ASCII and space-bearing temp paths, 8K, ultrawide, 1px-narrow, and malformed payloads. Also runs on Python 3.10 with no third-party packages.
  • Upgrade safety. The capability cache is in-memory and keyed on binary path, mtime and size, never persisted, so there is no stale dict across a Studio upgrade. No migration, schema, or settings key is touched. The flag emission sits under no if at all, so it is uniform across GPU vendors and platforms.

Cross-platform CI on Linux, macOS 15 and Windows is running now and I will follow up with the result, since that is the gap your description calls out.

@danielhanchen

Copy link
Copy Markdown
Member

@codex security review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 15, 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-09-15T17:23:27.797622Z a6db5f7 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.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 15, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Pinning --video-fps 1 introduced a regression at the short end. ffmpeg's fps
filter places its first output frame half an interval in, so at 1 fps a clip
under about half a second decodes to NOTHING and the model answers about a
video it never saw. Measured against llama-server's own `-vf fps=1` call:

    0.1s -> 0 frames   0.3s -> 0 frames   0.4s -> 0 frames
    0.49s -> 1 frame   0.6s -> 1 frame    1.0s -> 1 frame

and end to end on Qwen3-VL-2B-Instruct-Q4_K_M, a 0.2s and a 0.3s clip both
cost 21 prompt tokens, the bare text prompt, against 252 for the same clips at
the 4 fps default. Those clips worked before this PR, so this is a regression
guard rather than a new feature.

Hold the last frame out to MIN_SAMPLED_SECONDS with tpad, so every real frame
keeps the timestamp it was shot at and only the tail is invented. The floor is
a whole second rather than 0.5 to leave room for a rate typed into the
advanced arguments.

Two details that cost a round each:

* The pad has to run BEFORE the rate cap. `fps=4` has the same blind spot it
  exists to cover, so on a 0.1s clip the cap emitted nothing, tpad had no
  frame to clone, and the result was an undecodable 733 bytes. Padding first
  gives both filters something to work on.
* Scaling is now skipped for a clip already inside the pixel budget. A short
  clip can be small as well, and the scale factor is greater than one there,
  so the old unconditional chain would have UPSCALED it.

The probe returns the duration alongside the area and rate, and a clip that is
both big enough and long enough is still forwarded untouched with no re-encode.

Tests: a 0.1s, 0.3s and 0.4s clip each reach the sampler with at least one
frame and come back at the floor, and a within-budget two-second clip is still
returned by identity. 27 pass, 0 skipped, real ffmpeg 6.1.1. ruff 0.6.9 check
and scripts/run_ruff_format.py clean. The earlier long-clip, rotation, VFR,
byte-cap and degraded-environment suites all still pass unchanged.
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 15, 2026
@danielhanchen

Copy link
Copy Markdown
Member

Fixed the sub-second regression in b425b70 rather than leaving it for you, since it is a real behaviour change against the pre-PR default.

The floor is MIN_SAMPLED_SECONDS = 1.0, applied with tpad=stop_mode=clone, so every real frame keeps the timestamp it was shot at and only the tail is invented. A clip that is both inside the pixel budget and long enough is still forwarded untouched with no re-encode.

Two details worth recording, both of which cost a round:

  • The pad has to run BEFORE the rate cap. fps=4 has the same blind spot the pad exists to cover, so on a 0.1s clip the cap emitted nothing, tpad had no frame left to clone, and the result was an undecodable 733 bytes. Padding first gives both filters something to work on.
  • Scaling is now skipped when the clip is already inside the pixel budget. A short clip can be small too, and the scale factor is above one there, so the previously unconditional chain would have upscaled it.

Verified against llama-server's own -vf fps=1 call, frames actually delivered:

clip before after
0.05s 0 1
0.1s 0 1
0.3s 0 1
0.4s 0 1
0.49s 1 1
1.0s 1 1
2.0s 2 2

Clips at or above the old threshold are untouched. The long-clip, rotation, VFR, byte-cap and degraded-environment suites all still pass, and the four-condition prompt-token measurement is unchanged.

Still open and still yours, unchanged from my earlier comment: the unbounded clip duration, and conversion concurrency.

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 15, 2026
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 15, 2026
Codex is right that pinning the transcode at 4 fps silently caps a user who
asked llama-server for more. The transcode runs BEFORE the server samples, so
the server can only duplicate what was dropped here.

Measured on a 5s 720p clip with --video-fps 8, counting frames the server
actually receives:

    transcode capped at 4   40 frames, 20 exact duplicates -> 20 distinct
    transcode honours 8     40 frames,  0 exact duplicates -> 40 distinct

Prompt tokens are 4692 either way, which is why this does not show up in the
token measurements: the user pays for 40 frames in both cases and, capped,
half of them carry no new information.

requested_video_fps() reads what the user actually asked for: the environment
first, since Studio suppresses its own flag entirely when LLAMA_ARG_VIDEO_FPS
is set, otherwise the LAST --video-fps in the extras, matching how llama.cpp
resolves a repeated flag. The route passes it to the encoder.

The ceiling only ever rises. Below llama-server's own 4 fps default it stays
at MAX_FRAME_RATE, so the two rates Studio produces on its own (1 when the
build takes the flag, 4 when it does not) keep the shape every earlier
measurement was taken against: the sub-second floor, the long-clip guard and
the 93% token reduction are all unchanged.

Also re-anchored the route-ordering test on the bare function name. It matched
the full argument list, so reflowing that call broke it with a ValueError from
str.index rather than an ordering failure -- twice now. The AST test added
alongside it already covers the semantics.

Tests: the rate is read from extras and environment including last-wins,
`--video-fps=N`, garbage and zero; the ceiling rises only above the default;
and an 8 fps override really keeps 8 fps of frames through real ffmpeg. 30
pass. ruff 0.6.9 and run_ruff_format.py clean. The edge, integrity and
sub-second suites all still pass.
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 15, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…lings

Two follow-ups to the override fix, both confirmed against llama-server
b10976 rather than from the argument list alone.

argv beats the environment. llama.cpp reads the env var while registering the
option and argv overrides it afterwards, so an inherited LLAMA_ARG_VIDEO_FPS=1
alongside an advanced `--video-fps 8` samples at 8, not 1. Measured on a 5s
720p clip, prompt tokens:

    env=1, no argv      2796
    env=8, no argv     19392
    env=1 AND argv=8   19392   <- argv wins

Reading the environment first therefore capped the transcode at 4 for exactly
the case the previous commit set out to fix. Resolve argv first, fall back to
the environment only when argv says nothing.

llama.cpp also accepts the underscore spelling. `--video_fps 8` starts the
server while `--totally-bogus-flag 8` is rejected with "invalid argument", so
this is a real alias rather than a tolerated typo, and Studio's pass-through
validator permits it. An exact match on the hyphen missed it silently. Match
through `_flag_name`, which already normalises long-option underscores the way
llama.cpp does and peels `--key=value`, so `--video_fps=8` resolves too. Last
occurrence still wins across both spellings.

Tests cover the combined env-plus-argv case, both spellings with and without
`=`, last-wins across a mixed pair, and the environment still answering when
argv is silent. Verified to fail against the previous implementation. 30 pass.
@unslothai unslothai deleted a comment from oobabooga Sep 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 15, 2026
@unslothai unslothai deleted a comment from oobabooga Sep 15, 2026
@unslothai unslothai deleted a comment from oobabooga Sep 15, 2026
@unslothai unslothai deleted a comment from oobabooga Sep 15, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

The sub-second floor read `format.duration`, which a raw elementary stream
does not carry, so `duration` stayed None, `_filter_chain` omitted the pad and
a 0.3s `.h264` still reached the model with no frames at all. Reproduced end
to end: probe returned duration None, the shrink was skipped, and ffmpeg's
`fps=1` emitted 0 frames.

Fall back to packet timing when the container is silent. Two shapes, because
the obvious one is not enough on its own: a stream with presentation times
gives max(pts_time + duration_time), and Annex B, which carries no timestamps
at all, gives the sum of the per-packet durations. The h264 fixture resolves
to 0.299997s that way and comes back with a frame.

Bounded by `-read_intervals` to twice the floor. The only question being asked
is whether the clip is SHORTER than the floor, so a clip still producing
packets past that window is long enough by definition and walking the rest of
it would buy nothing.

The fallback is consulted only when `format.duration` is absent, so an
ordinary mp4 never pays for it; a test pins that by failing if the packet
probe is called for a two-second clip.

Also stopped the test helper reading `format.duration` to size a frame. It
needs only the dimensions, and on the raw fixture it raised KeyError before
the assertion it was there to make could run.

Verified to fail with the fallback removed. 32 pass, and the edge, integrity
and sub-second suites are unchanged.
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Sep 15, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: ef028387c5

ℹ️ 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 added a commit to Datta0/unsloth-staging-3 that referenced this pull request Sep 15, 2026
@danielhanchen

Copy link
Copy Markdown
Member

Final verification on a6db5f762.

Cross-platform

The description called out Windows and macOS as untested. They are now covered, with ffmpeg actually installed on the runner so the real-media tests execute rather than skip:

runner result
ubuntu-latest 32 passed
macos-15 (Apple Silicon) 32 passed
windows-latest 32 passed

Zero skips on all three. An earlier pass of this looked green while silently skipping all twelve real-media tests on every OS, so the skip count is the number worth reading here, not the pass count.

Comment pass

a6db5f762 trims the comments to the facts the code does not state: 64 net lines, with llama_video_input.py going from 83 comment and docstring lines to 34. The measured numbers that used to sit in the constants (the 53 MB clip, the 0.4s/0.49s frame boundary, the b10976 token counts) are recorded in this PR rather than in the source.

The change is comments and docstrings only. Verified by stripping docstrings and comparing ast.dump across all four files: identical. 32 tests still pass.

On the red pre-commit check

pre-commit.ci is failing, and it is not this PR. The ruff-format-with-kwargs hook run over all 2599 Python files reports the same three modified files at origin/main and at this head:

studio/backend/tests/test_diffusers_prewarm.py
studio/backend/utils/torch_warmup.py
tests/python/test_amd_extras_contract.py

None of them is touched here, and the last four commits on main carry the same red. The drift is pure line wrapping. This PR's four files are byte-stable under the pinned ruff 0.6.9.

One trap worth recording: scripts/run_ruff_format.py prints Adjusted kwarg spacing in <file> unconditionally, whether or not it changed anything. The pre-commit log therefore names about fifty files including studio/backend/routes/inference.py, which makes it look like this PR is implicated. It is not. Only the three files above actually differ afterwards, so that log line cannot be used to attribute a failure.

Fixing those three belongs in its own change, not bundled here.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 15, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: a6db5f7628

ℹ️ 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 4f56de1 into unslothai:main Sep 15, 2026
46 of 48 checks passed
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…fill (unslothai#10973)

* Studio: stop a short video clip from taking minutes to prefill

* Bound the shrunk video clip at the upload cap

* Drop restating comments

* Cap the re-encode at the frame rate llama-server samples

The scale filter changed the frame size but not the frame rate, so a 30 fps
source was re-encoded at 30 fps while this same change tells llama-server to
sample it at 1. Twenty-nine frames in thirty were encoded, counted against
max_bytes, and then dropped by mtmd.

Those wasted bytes are not free, because they are what the cap guard measures.
A legal 53 MB 12-minute 1080p30 upload transcodes to more than 64 MB, so the
guard fires and the ORIGINAL full-size clip is forwarded -- after a 25 second
ffmpeg pass. The slowest clips, which is the case this whole change exists for,
paid the conversion and got none of it:

    as merged      wall 24.7s   out 53.0MB   shrink applied: no
    fps=4 first    wall 10.7s   out 16.9MB   shrink applied: yes

Cap at MAX_FRAME_RATE = 4, llama-server's own --video-fps default, rather than
at the 1 Studio asks for. Then no configuration samples a frame the container
no longer has: Studio asks for 1, a build too old for --video-fps samples at 4,
and the documented Qwen override of 2 is still whole.

The cap only ever reduces. ffmpeg's fps filter DUPLICATES frames when asked for
more than the source has, so a 1 fps timelapse would come back four times
heavier; the rate now comes back from the probe alongside the area and the
filter is only prepended when the source is genuinely faster.

Measured on Qwen3-VL-2B-Instruct-Q4_K_M with llama.cpp b10976, 5s 720p clip:
prompt tokens are unchanged at every sampling rate (10172 / 2472 / 2796 / 696
for original-4fps / shrunk-4fps / original-1fps / shrunk-1fps) while the
attachment drops from 966,757 to 211,690 bytes. The model reads the burned-in
per-second captions back correctly either way.

Also in this change, all from the same review pass:

* Reject through _reject when the conversion raises, like the audio path
  directly above it. The helper absorbs its own ffmpeg failures, so anything
  reaching the route is unmodelled -- previously a raw 500 with a non-OpenAI
  body, and a leaked api_monitor entry with it.
* Fall back instead of raising AttributeError when ffprobe answers `-of json`
  with something that is not an object.
* Drop the decoded copy once it is on disk. It was held to the end only so the
  log line could read len(raw), keeping 64 MiB alive beside the output and both
  base64 strings.
* Correct the -q:v comment: -fs bounds the result at the upload cap, it does
  not keep it near the source size. Near-static 1080p still grows ~3.4x.

Tests: frames beyond the sampled rate are not re-encoded, a clip slower than
the cap keeps every frame, a long clip is really shrunk rather than forwarded,
and a non-object probe falls back. The route-ordering test matched source text,
so it stayed green when the conversion's result was discarded and the original
injected -- a change that silently disables the feature. It is now paired with
an AST check that the awaited call is bound and that the bound name is the one
_inject_video_part receives; verified to fail on exactly that edit.

23 pass, 0 skipped, with real ffmpeg 6.1.1. ruff 0.6.9 check and
scripts/run_ruff_format.py are clean.

* Keep a sub-second clip from reaching the model with no frames

Pinning --video-fps 1 introduced a regression at the short end. ffmpeg's fps
filter places its first output frame half an interval in, so at 1 fps a clip
under about half a second decodes to NOTHING and the model answers about a
video it never saw. Measured against llama-server's own `-vf fps=1` call:

    0.1s -> 0 frames   0.3s -> 0 frames   0.4s -> 0 frames
    0.49s -> 1 frame   0.6s -> 1 frame    1.0s -> 1 frame

and end to end on Qwen3-VL-2B-Instruct-Q4_K_M, a 0.2s and a 0.3s clip both
cost 21 prompt tokens, the bare text prompt, against 252 for the same clips at
the 4 fps default. Those clips worked before this PR, so this is a regression
guard rather than a new feature.

Hold the last frame out to MIN_SAMPLED_SECONDS with tpad, so every real frame
keeps the timestamp it was shot at and only the tail is invented. The floor is
a whole second rather than 0.5 to leave room for a rate typed into the
advanced arguments.

Two details that cost a round each:

* The pad has to run BEFORE the rate cap. `fps=4` has the same blind spot it
  exists to cover, so on a 0.1s clip the cap emitted nothing, tpad had no
  frame to clone, and the result was an undecodable 733 bytes. Padding first
  gives both filters something to work on.
* Scaling is now skipped for a clip already inside the pixel budget. A short
  clip can be small as well, and the scale factor is greater than one there,
  so the old unconditional chain would have UPSCALED it.

The probe returns the duration alongside the area and rate, and a clip that is
both big enough and long enough is still forwarded untouched with no re-encode.

Tests: a 0.1s, 0.3s and 0.4s clip each reach the sampler with at least one
frame and come back at the floor, and a within-budget two-second clip is still
returned by identity. 27 pass, 0 skipped, real ffmpeg 6.1.1. ruff 0.6.9 check
and scripts/run_ruff_format.py clean. The earlier long-clip, rotation, VFR,
byte-cap and degraded-environment suites all still pass unchanged.

* Let an explicit frame-rate override reach the encoder

Codex is right that pinning the transcode at 4 fps silently caps a user who
asked llama-server for more. The transcode runs BEFORE the server samples, so
the server can only duplicate what was dropped here.

Measured on a 5s 720p clip with --video-fps 8, counting frames the server
actually receives:

    transcode capped at 4   40 frames, 20 exact duplicates -> 20 distinct
    transcode honours 8     40 frames,  0 exact duplicates -> 40 distinct

Prompt tokens are 4692 either way, which is why this does not show up in the
token measurements: the user pays for 40 frames in both cases and, capped,
half of them carry no new information.

requested_video_fps() reads what the user actually asked for: the environment
first, since Studio suppresses its own flag entirely when LLAMA_ARG_VIDEO_FPS
is set, otherwise the LAST --video-fps in the extras, matching how llama.cpp
resolves a repeated flag. The route passes it to the encoder.

The ceiling only ever rises. Below llama-server's own 4 fps default it stays
at MAX_FRAME_RATE, so the two rates Studio produces on its own (1 when the
build takes the flag, 4 when it does not) keep the shape every earlier
measurement was taken against: the sub-second floor, the long-clip guard and
the 93% token reduction are all unchanged.

Also re-anchored the route-ordering test on the bare function name. It matched
the full argument list, so reflowing that call broke it with a ValueError from
str.index rather than an ordering failure -- twice now. The AST test added
alongside it already covers the semantics.

Tests: the rate is read from extras and environment including last-wins,
`--video-fps=N`, garbage and zero; the ceiling rises only above the default;
and an 8 fps override really keeps 8 fps of frames through real ffmpeg. 30
pass. ruff 0.6.9 and run_ruff_format.py clean. The edge, integrity and
sub-second suites all still pass.

* Resolve the requested frame rate from argv first, and match both spellings

Two follow-ups to the override fix, both confirmed against llama-server
b10976 rather than from the argument list alone.

argv beats the environment. llama.cpp reads the env var while registering the
option and argv overrides it afterwards, so an inherited LLAMA_ARG_VIDEO_FPS=1
alongside an advanced `--video-fps 8` samples at 8, not 1. Measured on a 5s
720p clip, prompt tokens:

    env=1, no argv      2796
    env=8, no argv     19392
    env=1 AND argv=8   19392   <- argv wins

Reading the environment first therefore capped the transcode at 4 for exactly
the case the previous commit set out to fix. Resolve argv first, fall back to
the environment only when argv says nothing.

llama.cpp also accepts the underscore spelling. `--video_fps 8` starts the
server while `--totally-bogus-flag 8` is rejected with "invalid argument", so
this is a real alias rather than a tolerated typo, and Studio's pass-through
validator permits it. An exact match on the hyphen missed it silently. Match
through `_flag_name`, which already normalises long-option underscores the way
llama.cpp does and peels `--key=value`, so `--video_fps=8` resolves too. Last
occurrence still wins across both spellings.

Tests cover the combined env-plus-argv case, both spellings with and without
`=`, last-wins across a mixed pair, and the environment still answering when
argv is silent. Verified to fail against the previous implementation. 30 pass.

* Pad a short clip whose container reports no duration

The sub-second floor read `format.duration`, which a raw elementary stream
does not carry, so `duration` stayed None, `_filter_chain` omitted the pad and
a 0.3s `.h264` still reached the model with no frames at all. Reproduced end
to end: probe returned duration None, the shrink was skipped, and ffmpeg's
`fps=1` emitted 0 frames.

Fall back to packet timing when the container is silent. Two shapes, because
the obvious one is not enough on its own: a stream with presentation times
gives max(pts_time + duration_time), and Annex B, which carries no timestamps
at all, gives the sum of the per-packet durations. The h264 fixture resolves
to 0.299997s that way and comes back with a frame.

Bounded by `-read_intervals` to twice the floor. The only question being asked
is whether the clip is SHORTER than the floor, so a clip still producing
packets past that window is long enough by definition and walking the rest of
it would buy nothing.

The fallback is consulted only when `format.duration` is absent, so an
ordinary mp4 never pays for it; a test pins that by failing if the packet
probe is called for a two-second clip.

Also stopped the test helper reading `format.duration` to size a frame. It
needs only the dimensions, and on the raw fixture it raised KeyError before
the assertion it was there to make could run.

Verified to fail with the fallback removed. 32 pass, and the edge, integrity
and sub-second suites are unchanged.

* Trim the comments to the facts the code does not state

---------

Co-authored-by: danielhanchen <[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.

2 participants