Skip to content

fix(studio): restore parallel vision chat slots - #9842

Merged
danielhanchen merged 8 commits into
unslothai:mainfrom
Biotrioo:fix/issue-9840-vision-parallel-slots
Aug 27, 2026
Merged

danielhanchen merged 8 commits into
unslothai:mainfrom
Biotrioo:fix/issue-9840-vision-parallel-slots

Conversation

@Biotrioo

Copy link
Copy Markdown
Contributor

Summary

  • Restore concurrent local vision chat requests when the shared KV cache has room.
  • Keep the existing KV admission guard for genuinely large prompt/output commitments.

Root cause

  • Studio sends the current image as both a message-level image_url and the legacy top-level image_base64 field.
  • Admission charged the raw Base64/Data-URL bytes as dense prompt text and charged the duplicate legacy field again.
  • Normal images therefore saturated the estimated KV budget, so the FIFO queue admitted one vision request at a time and could delay following text requests.

Fix

  • Replace image payload bytes with a compact marker before dense message estimation.
  • Charge one bounded 4,096-token image allowance per message-level image, or once for a legacy-only image.
  • Add regressions for the Studio dual representation, bounded large-image accounting, and concurrent vision leases.

Testing

  • python -m compileall -q routes/inference.py tests/test_llama_admission_kv_budget_media_and_tools.py — passed.
  • Targeted admission smoke — passed (dual-image deduplication, bounded cost, queue parallelism, and unchanged audio/video/tool-loop behavior).
  • Focused pytest suite was not runnable in this checkout because the available runtime does not include pytest or fastapi.

Issue

Fixes #9840

@danielhanchen

Copy link
Copy Markdown
Member

Thanks for digging into this one. I reproduced the bug, confirmed your diagnosis is correct, and measured the constant against real projectors. Summary first: the direction is right and the core of the fix works, but the flat 4096 is 2 tokens under the real Qwen ceiling, and the passthrough route forwards an image it is not billed for. Details and evidence below.

The diagnosis holds

I ran the estimator directly on main and on this branch, with the body Studio's composer actually sends (a message-level image_url part and the legacy top-level image_base64), 4 slots:

shape max_tokens budget main reserved main admitted this PR reserved this PR admitted
200 KiB image 512 40000 40000 1 4642 4
200 KiB image 2048 40000 40000 1 6178 4
200 KiB image 8192 40000 40000 1 12322 3
2 MiB image 512 40000 40000 1 4642 4
2 MiB image 2048 131072 131072 1 6178 4
text only (control) 2048 40000 2063 4 2063 4

On main every vision request reserves the entire cache at every budget and every output cap, so the second one always queues. That is the min(budget, ...) clamp in _openai_llama_admission_tokens swallowing a base64 blob priced as prompt text. Your fix makes the cost independent of transport size, which is the correct property.

I also confirmed the layer. A bare llama-server on the build we ship (b10639), --parallel 4 --kv-unified -c 40000, Qwen3-VL-4B, running the sequences from the issue with each request launched only once the previous one was already generating:

sequence max slots processing overlap
V,V 2 1.04 s
V,T 2 1.15 s
V,T,V 3 2.10 s
T,T,V 3 1.41 s
V,V,V,V 4 1.70 s

llama.cpp overlaps vision requests fine. The serialisation was ours, and this is the right place to fix it.

For the record, this is a regression I introduced in #9392. The docstring there claimed Studio "sends every attachment as image_base64 ... never as messages content parts". It sends both (chat-adapter.ts builds the image_url part and sets image_base64 from the same string in the same body), so the image was charged twice, each time at base64 length.

1. The 4096 constant is 2 tokens under the real ceiling

I measured actual mtmd cost as prompt_tokens(with image) - prompt_tokens(same text, no image) against live llama-server:

image Qwen3-VL-4B Gemma 3 4B
1x1 11 258
224x224 51 258
448x448 198 258
896x896 786 258
1344x1344 1766 258
2048x2048 4098 258
4096x4096 4098 258
4096x256 1026 258
256x4096 1026 258

Two things worth keeping:

  • Byte size really is irrelevant, as your docstring says: the 2048x2048 PNG is 16 MB of base64 and the 4096x4096 is 65 MB, and both cost 4098. That is the premise of the fix and it is correct.
  • The Qwen ceiling is 4098, not 4096. The projector caps at 4096 embeddings and llama.cpp adds 2 wrapper tokens around them (the server log shows encoding batch with 1 entries and total 784 tokens for the 896x896 case, which I measure as 786). So a max-resolution Qwen image is under-reserved by exactly 2 tokens. Tiny, but the whole point of this accounting is to be an upper bound, so I would rather the constant not be provably below the real cost. Bumping it to 4224 or so, with a comment naming the 4096 embedding cap plus wrapper allowance, would close it.

Gemma 3 is a flat 258 at every resolution, so 4096 over-reserves it ~16x. At a 40k context that is harmless (still 4 concurrent). At an 8k context it is not: this PR still admits only 1 Gemma vision chat, where projector-aware accounting would admit 4. Worth a follow-up rather than a blocker.

I only tested these two projector families. Tiled or multi-crop projectors are not covered by either of us, and Studio never passes --image-max-tokens, so a user pointing Studio at a hand-run llama-server with a raised limit is outside the constant's guarantee. A comment saying so would be honest.

2. Blocking: passthrough forwards an image it is not billed for

The new docstring says the generation path injects the legacy image only when there is no message-level image. That is true of _openai_messages_for_gguf_chat, which has the has_message_image guard, but not of _openai_messages_for_passthrough, which splices payload.image_base64 unconditionally. Passthrough is its own admission call site, and it is the route a vision request takes when the client sends tools or a response_format.

Measured on this branch with real ChatCompletionRequest objects:

payload        builder         reserved  billed   fwd  verdict
dual           gguf chat           4671       1     1  ok
dual           passthrough         4671       1     2  MISMATCH (2 fwd vs 1 billed)
inline only    gguf chat           4671       1     1  ok
inline only    passthrough         4671       1     1  ok
legacy only    gguf chat           4645       1     1  ok
legacy only    passthrough         4645       1     1  ok

Before this PR that route was over-charged (whole cache) so it was accidentally safe. After, it under-charges by a full image. I would fix it by giving both builders one shared normalisation helper rather than patching the estimator, since a second copy of "which images does this request really carry" is exactly how #9392's docstring drifted from reality. _legacy_image_is_distinct already exists as the precise predicate.

3. The same bug survives on other shapes that reach the same estimator

The strip predicate is part.get("type") != "image_url", so anything else carrying base64 is still priced as prompt text. Measured on this branch:

shape reserved budget
200 KiB image_url (fixed) 4245 65536
200 KiB input_document (PDF file_data) 65536 65536
200 KiB Anthropic type: "image" block on /v1/messages 40000 40000
text control 548 65536

/v1/messages shares the same LlamaAdmissionQueue, but Anthropic images are type: "image" blocks with base64 in source.data. InputDocumentContentPart (models/inference.py:1624) accepts a data:application/pdf;base64,... URI on the same /v1/chat/completions body. Both still lease the entire cache by the identical mechanism the PR's own docstring argues against. Same for input_audio / input_video parts already inside messages.

Neither is a defect you introduced, and Studio's own frontend emits neither, so I am happy for them to be follow-ups. But the PR title says "restore parallel vision chat slots" and one of the two vision routes is untouched.

4. Audio and video

You call this out as deliberate, and I agree it is out of scope, but for the record it is not a small residue: a 200 KiB audio_base64 still reserves the full 40000-token budget on this branch, so an audio chat reproduces #9840 verbatim.

5. Smaller things, all in the lines this PR rewrote

  • model_dump() without exclude_none (inference.py:1656). Every other message dump in this file uses exclude_none = True, including _openai_messages_for_gguf_chat at :27829, which is the thing this estimate is meant to predict. ChatMessage has five optional fields, so the bare dump measures "reasoning_content": null, "tool_call_id": null, ... as prompt text. Measured for {"role": "user", "content": "hi"}: 34 tokens with model_dump(), 8 with exclude_none = True. That is ~26 phantom tokens per message, so ~2.6k of padding on a 100-turn thread against a budget that is often 4096-8192. Pre-existing, but you rewrote this exact line into the new helper, so it is the natural place to fix it.
  • No clamp relating the constant to the budget (inference.py:1641). 4096 is absolute, with no min(..., budget // capacity). That is what makes the Gemma small-cache case above bite, and it is why the two media tests now pin opposite policies: the new test at line 89 asserts two vision chats co-admit at budget = 12_000, while test_two_image_chats_are_not_both_admitted asserts they must not at budget = 2048, and the only thing choosing between them is the constant-to-budget ratio.
  • detail is copied through unvalidated (inference.py:1673). ImageUrl.detail is a Literal, so a typed body 422s first, but the helper explicitly supports raw dicts and has no guard there; a {"url": "x", "detail": {...200 KiB...}} part re-inflates the estimate the helper just deflated. Also, detail defaults to "auto" and is never None, so the is not None conditional never actually skips anything on a typed payload.
  • Dead branch (inference.py:1651). if not isinstance(message_dict, dict) cannot fire: the ternary above yields either a dict or model_dump(), which always returns one.

6. Test notes

Both media equality assertions are currently vacuous, because _openai_llama_admission_tokens clamps to max(1, min(budget, ...)):

  • test_legacy_image_costs_what_the_same_image_inline_costs runs at budget = 4096, so both sides clamp to 4096.
  • The new test_studio_image_echo_is_charged_once_and_is_bounded runs at budget = 65536, and I checked it against main: pre-fix, dual = 65536 and inline = 65536, so assert dual_cost == inline_cost passes unchanged on the buggy code. Only the 4096 <= dual_cost < 10_000 bound actually discriminates (it fails on main, as it should). Since the test's name promises "charged once", dual_cost < 2 * _OPENAI_LLAMA_ADMISSION_IMAGE_TOKENS would be the assertion that tests the name.

The fixtures are also b"\x89PNG" + b"x" * n, which never decode. Fine for the estimator, but it means nothing in the suite relates the constant to a real projector, which is how being 2 under went unnoticed.

What passes

  • All 132 tests in test_llama_admission.py, test_llama_admission_kv_budget.py, test_llama_admission_kv_budget_media_and_tools.py and test_anthropic_admission.py pass on this branch, so Admit generations against the KV cache, not just the slot count #9392's overcommit guard is intact.
  • Full studio/backend/tests suite on this branch versus main: identical failure sets, zero head-only failures. The red CI here is a stale base, not your change. Merging current main into the branch is clean and clears it.

One thing this PR cannot fix

The reporter also notes that setting max_tokens near the full context serialises slots. That is by design: the estimator reserves the output cap, and an uncapped request reserves the rest of the budget. Nothing here changes it, and I do not think it should. What it deserves is a separate issue about surfacing "queued" in the UI, since right now it is indistinguishable from a hang, and by their account that cost them two hours.

Ask

Blocking: fix the passthrough double-forward (item 2). Nice to have in this PR: raise the constant above 4098 with a comment explaining where the number comes from (item 1). Happy to take the Anthropic route and audio/video as follow-ups. Everything else looks good, and thank you for tracking this down.

… builders

Two things kept the image allowance from being the bound admission needs.

The passthrough builder spliced the legacy top-level image unconditionally,
while the GGUF chat builder skipped it when the messages already carried one.
Studio echoes the current image into both spellings, so a request with client
tools or a response_format went to llama-server with two copies of one image
against a reservation for one. Measured on llama-server b10639 with a 2048x2048
image: 4417 tokens reserved, 8466 actually charged. Across capacity x context
shapes that is a real overcommit in 12 of 30 combinations, including 4 slots at
32768 and 8 slots at 40000, which is the collision unslothai#9392 exists to stop. Both
builders now ask one shared predicate, since two copies of "does this request
already carry an image" is how they drifted apart.

The 4096 constant was also below the real ceiling. 4096 is llama.cpp's default
cap on Qwen-VL embeddings per image, but mtmd wraps them in delimiters, so a
max-resolution image measures 4098 on Qwen3-VL-4B and 258 on Gemma 3 4B. The
constant is now the embedding cap plus an explicit wrapper allowance, with the
measurements and the projector families it cannot promise anything for written
down next to it.

Also drop the unset optional fields before the dense estimate, as every other
dump of these models in this file already does. Without exclude_none a bare
{"role": "user", "content": "hi"} is priced at 34 tokens rather than 8, all of
it null padding that is never sent.

The two media equality assertions ran at a budget both sides clamped to, so
they held on the unfixed estimator too. They now run clear of the clamp, and
the new cases assert what the fix is for: every builder forwards exactly the
number of images admission charged for, and the allowance bounds the measured
cost of a real projector.
@danielhanchen

Copy link
Copy Markdown
Member

I pushed a commit to this branch rather than leaving you a list: 99ec27e. It fixes the two things from my review that made the reservation stop being an upper bound, plus the exclude_none nit, and it de-vacuums the two media assertions. Everything below is why, and what I ran to be sure it does not break anything.

What changed

Both builders now ask one shared predicate. _openai_messages_for_passthrough spliced the legacy image unconditionally; _openai_messages_for_gguf_chat skipped it when the messages already carried one. Both now call _messages_carry_an_image. Two copies of that question is how they drifted, so there is now one.

The constant is the embedding cap plus an explicit wrapper allowance (4096 + 128), not a flat 4096, with the measurements written next to it. 4098 was measured, not guessed, and reserving below the real cost is the one direction this accounting must not err in.

model_dump(exclude_none = True) in the estimate helper, matching every other dump of these models in the file.

Was it a real bug, and does the fix actually hold

Real, and the mechanism is deterministic rather than marginal. On main every vision request reserved the entire cache at every budget and every output cap, so the second one always queued. A bare llama-server on the same build overlaps 4 vision requests happily, so the serialisation was ours.

The passthrough gap was not theoretical either. Driving the real builders into a live llama-server with a 2048x2048 image:

route images forwarded reserved real KV
before gguf chat 1 4417 4368 bound holds
before passthrough 2 4417 8466 short by 4049
after gguf chat 1 4518 4368 bound holds
after passthrough 1 4518 4368 bound holds

Sweeping that shortfall over slot counts and context sizes, it is a genuine overcommit in 12 of 30 capacity-by-budget combinations, including 4 slots at 32768 and 8 slots at 40000. That is the collision #9392 exists to stop, so it was worth fixing before merge rather than after.

Simulation coverage

A 3000-cell matrix over capacity {1,2,4,8,16} x budget {2048 ... 262144} x 15 payload shapes x max_tokens {128,512,2048,8192,None}, asserting on every cell: the estimate is in [1, budget], nothing raises, the first request is never stranded, committed never exceeds budget once more than one lease is held, cost is independent of image byte size, and cost is non-decreasing in image count. Plus 24 degenerate shapes (messages None, content lists of None, image_url as a bare string, a payloadless data URL, a 200 KiB detail blob, unserialisable content, CJK and emoji, max_tokens 0).

Before the commit: 1 failure, the allowance being under the measured Qwen ceiling. After: all 3000 cells hold.

Compatibility

Python. The backend floor is 3.10 and vermin agrees nothing here needs more. I ran the whole matrix on isolated uv venv interpreters for 3.10, 3.11, 3.12, 3.13 and 3.14: 3000 cells each, and the reservations hash byte-identical across all five.

OS and browsers. Not applicable, and I checked rather than assumed: the diff is two backend Python files with no os, filesystem, subprocess, GPU, or browser construct, and no frontend, desktop or Electron file is touched. There is no rendered output to differ between Firefox, Safari, Chrome and Edge.

GPU and CPU. The thing that could have been hardware-dependent is the mtmd token count the constant has to bound. It is not: a CPU-only llama.cpp build of the same revision produces identical counts to the CUDA build at every resolution. The axis that does vary with hardware is the estimator's inputs, since VRAM downshifts --parallel and n_ctx feed the budget, and that is exactly what the capacity-by-budget matrix sweeps.

Old installs. Every client shape still admits and stays bounded: a pre-content-parts Studio sending only image_base64, current Studio sending both, a stock OpenAI SDK client sending only inline, text-only, and multi-image. All three escape hatches still switch the accounting off, including the legacy UNSLOTH_OPENAI_COMPAT_* spelling. No request or response field changes, and nothing here is persisted, so there is no forwards-compatibility surface at all: an old client talking to a new backend and a new client talking to an old backend both see the same wire format they did before.

Regressions. Full studio/backend/tests suite: 186 failures with my commit against 187 on the PR head and 187 on main, and the set difference is zero tests introduced. The one that flipped is a timing-dependent RAM-sizing test, unrelated. test_openai_tool_passthrough.py matters most here since I changed that builder: 452 tests pass across it and the four admission suites. ruff and the kwarg formatter are clean, and the floor lint passes.

One thing the de-vacuuming exposed

Once test_legacy_image_costs_what_the_same_image_inline_costs runs clear of the clamp, the two spellings are not equal: 4363 against 4384. The inline form genuinely sends a content-part wrapper the legacy form does not, and the [image] marker is itself a few tokens of JSON. So I relaxed it to a tolerance and kept the bound that does the real work. The old exact-equality assertion was only ever true because both sides clamped, which is worth knowing.

Still open, deliberately not in this commit

The Anthropic /v1/messages route and input_document PDF parts still reserve the whole cache, and audio_base64 / video_base64 still charge transport bytes. All three are over-reservation, so they are safe, just not fixed, and each is a scope expansion rather than a correctness fix to what you wrote. Happy to file them as follow-ups. The other one worth a follow-up is making the allowance projector-aware: Gemma 3 is a flat 258 per image, so 4224 over-reserves it 16x, which is free at a 40k context and still serialises Gemma vision chats at 8k.

What I did not test

Real Windows, macOS or WSL hosts, and AMD hardware. I am comfortable asserting the code is indifferent to all of them given there is no platform-specific construct in it and the interpreter matrix is identical, but that is an argument from the diff, not a measurement. Projector families beyond Qwen-VL and Gemma 3 are also untested, and tiling or multi-crop ones could exceed the cap; the comment on the constant says so.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 27, 2026

@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: 68bb28bd87

ℹ️ 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".

Comment thread studio/backend/routes/inference.py Outdated
Comment on lines 27753 to 27754
if not payload.image_base64 or _messages_carry_an_image(messages):
return messages

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 Preserve distinct legacy images in passthrough requests

When a tools or response_format request contains any message-level image plus a different image_base64 attachment—for example, an older image in history and a new legacy-only image on the current turn—this new early return silently drops the top-level image, so llama-server answers without the image the client just supplied. The existing _legacy_image_is_distinct helper already distinguishes Studio's byte-identical echo from a genuinely separate attachment; the passthrough builder should use that distinction rather than treating the presence of any message image as proof that the legacy field is redundant.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Correct, and thanks for catching it. Skipping the legacy field whenever the messages carried any image deduplicated Studio's echo but also dropped a genuinely different attachment, so llama-server answered without the image the client just sent. Fixed in b4160be: both builders and the admission estimate now key on _legacy_image_is_distinct, so the echo is charged and sent once while a real second image is charged and sent. _latest_user_image_payload now reads plain dicts as well as models, since the estimate sees whatever the caller passed and the two predicates have to agree or the reservation stops matching the prompt. Regression added: every builder must forward exactly the number of images admission charged for, with a history image plus a distinct legacy attachment among the shapes.

Comment on lines +1638 to +1642
_OPENAI_LLAMA_ADMISSION_IMAGE_EMBEDDING_CAP = 4096
_OPENAI_LLAMA_ADMISSION_IMAGE_WRAPPER_TOKENS = 128
_OPENAI_LLAMA_ADMISSION_IMAGE_TOKENS = (
_OPENAI_LLAMA_ADMISSION_IMAGE_EMBEDDING_CAP + _OPENAI_LLAMA_ADMISSION_IMAGE_WRAPPER_TOKENS
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Derive the reservation from the configured image token cap

When a load uses llama_extra_args=["--image-max-tokens", "8192"], an image may consume more than the hard-coded 4,224-token reservation, allowing the admission queue to grant concurrent requests whose real embeddings do not fit in the shared KV cache. Studio does permit this configuration: LoadRequest.llama_extra_args is forwarded verbatim (studio/backend/models/inference.py:335-341), and the pass-through validator documents that every non-managed flag is appended after Studio's flags (studio/backend/core/inference/llama_server_args.py:4-9); --image-max-tokens is not managed. The reservation therefore needs to reflect the effective launch argument or loaded projector rather than assuming Studio can never raise the cap.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed, and my comment claiming Studio never passes one was wrong. I checked validate_extra_args directly: it rejects --parallel but forwards --image-max-tokens 8192 verbatim, so the cap is reachable through llama_extra_args. I then measured it on llama-server b10639: with --image-max-tokens 8192 a 4096x4096 Qwen3-VL image costs 8102 KV positions against 4098 at the default, so the hard-coded allowance really would have admitted concurrent requests the cache cannot hold. Fixed in b4160be: _openai_llama_admission_image_tokens reads the effective cap off the running backend and falls back to the default ceiling, so a lowered cap reserves less too. Regression covers a raised, lowered, absent and malformed cap.

pre-commit-ci Bot and others added 2 commits August 27, 2026 11:01
… cap

Two holes in the per-image reservation, both found in review.

Skipping the legacy top-level image whenever the messages carried any image was
too coarse. It deduplicates Studio's echo, which is byte-equal to a part already
in the thread, but it also silently dropped a genuinely different image attached
to the current turn through the legacy field, so llama-server answered without
the image the client just sent. Both builders and the admission estimate now key
on _legacy_image_is_distinct, which compares against the one value the composer
could have echoed. The echo is still charged and sent once; a real second image
is now charged and sent, rather than dropped.

_latest_user_image_payload reads models and plain dicts alike so that predicate
can be shared: the generation paths only ever hold models, but the estimate sees
whatever the caller passed, and the two have to agree or the reservation stops
matching the prompt.

The per-image allowance was also a hard-coded default in a place that can be
configured. --image-max-tokens is not an Unsloth-managed flag, so llama_extra_args
forwards it verbatim; measured on llama-server b10639 with --image-max-tokens 8192,
a 4096x4096 Qwen3-VL image costs 8102 against 4098 at the default, so the default
allowance would have admitted concurrent requests the cache cannot hold. The
reservation now reads the effective cap off the running backend and falls back to
the default ceiling, so lowering the cap reserves less too.

Regressions cover both: every builder forwards exactly the number of images
admission charged for, now including a history image plus a distinct legacy
attachment, and the allowance tracks a raised, lowered, absent or malformed cap.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 27, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: b4160bebdc

ℹ️ 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

Copy link
Copy Markdown
Member

@codex review

@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: 0f9a62fe49

ℹ️ 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".

Comment thread studio/backend/routes/inference.py Outdated
Comment on lines +1673 to +1675
cap = _extra_args_image_max_tokens(getattr(llama_backend, "_extra_args", None))
if cap is None:
return _OPENAI_LLAMA_ADMISSION_IMAGE_TOKENS

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 Read the effective cap from the loaded projector

When no explicit argv cap exists—or when a low cap is supplied for a fixed-resolution projector—this value is not an upper bound. I checked the bundled llama-server's common/arg.cpp:2634-2639: its help says the default is “read from model” and the option applies only to dynamic-resolution models; tools/mtmd/clip.cpp:1766,1802,1965 defines supported projector maxima of 62,500, 8,000, and 16,384 tokens. Large images for those projectors can therefore occupy far more than the 4,224 positions reserved here, allowing concurrent requests into a KV cache that cannot hold them. Read the loaded projector's effective limit rather than treating 4,096 or every _extra_args value as authoritative.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Right on both counts, and I checked the sources you named. clip.cpp's set_limit_image_tokens really does differ per family: 256 lfm2, 280 gemma4v, 576 minimax_m3, 1024 pixtral/kimivl/lightonocr, 4096 the qwen mergers and glm4v, 16384 hunyuanvl, 62500 youtuvl. And the flag's own help says default: read from model and only used by vision models with dynamic resolution, so a low cap against a fixed-resolution projector is not authoritative either. A flat 4096 was a bound for most families and a quarter of what one hunyuanvl image costs. Fixed in cc311a9. /props carries no image-token limit (I started a server and dumped it: only modalities.vision), so this reads the projector file instead. The mmproj is already opened at load for its capabilities, so it now also yields clip.projector_type, and admission looks the ceiling up from a table keyed on the clip-impl.h strings, verified against the two mmproj files I have here (qwen3vl_merger, gemma3). An unrecognised family keeps the previous default rather than inventing a number. It takes the LARGER of the projector ceiling and any --image-max-tokens rather than trusting the flag, which is what covers your fixed-resolution case. Regression asserts every family in the table is bounded, that youtuvl gets at least 62500, that a small-ceiling family reserves near it, and that a low cap cannot pull a qwen reservation under 4096.

There is no universal per-image ceiling to hard-code. llama-server documents
--image-max-tokens as "read from model" and applies it only to dynamic-resolution
projectors, and clip.cpp sets a different limit per family: 256 for lfm2, 280 for
gemma4v, 576 for minimax_m3, 1024 for pixtral and kimivl, 4096 for the qwen and
glm4v mergers, 16384 for hunyuanvl and 62500 for youtuvl. A flat 4096 bound holds
for most of those and reserves a quarter of what one hunyuanvl image costs, which
admits concurrent requests the cache cannot hold.

The mmproj already gets read at load for its capabilities, so it now also yields
clip.projector_type, and admission looks the ceiling up from a table keyed on the
strings in clip-impl.h. An unrecognised family keeps the previous default rather
than inventing a number.

Takes the LARGER of the projector ceiling and any --image-max-tokens rather than
trusting the flag. It is honoured only by dynamic-resolution projectors, so a low
cap against a fixed-resolution one is ignored by llama.cpp and believing it would
reserve less than the image costs. Over-reserving is the safe direction here.

/props carries no image-token limit, so this reads the projector file rather than
the running server.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 27, 2026
@danielhanchen
danielhanchen merged commit c2c3535 into unslothai:main Aug 27, 2026
6 of 45 checks passed

@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: cc311a958f

ℹ️ 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".

# model" -- and the spread is three orders of magnitude, so assuming any one number
# under-reserves somebody. A family absent here falls back to the default ceiling
# below, which is the pre-existing behaviour rather than a new guess.
_MMPROJ_IMAGE_TOKEN_MAX = {

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 Include the GLM5Next projector ceiling

When the loaded projector reports clip.projector_type="glm5next", this table misses it and the lookup falls back to 4,096 tokens. Fresh evidence in the current revision is the bundled llama-server source at /workspace/unsloth_studio/llama.cpp/tools/mtmd/clip.cpp:1788-1802, where GLM-5.3-Flash calls set_limit_image_tokens(16, 8000). A maximum-resolution image can therefore consume about 8,000 embeddings while admission reserves only 4,224 positions, allowing concurrent GLM-5.3 vision requests into a KV cache that cannot hold their actual commitments.

Useful? React with 👍 / 👎.

known = _MMPROJ_IMAGE_TOKEN_MAX.get(str(projector).strip().lower()) if projector else None
cap = max(
known or _OPENAI_LLAMA_ADMISSION_IMAGE_EMBEDDING_CAP,
_extra_args_image_max_tokens(getattr(llama_backend, "_extra_args", None)) or 0,

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 Honor the environment-provided image token cap

When the server is launched with LLAMA_ARG_IMAGE_MAX_TOKENS and no equivalent argv flag, this reads only _extra_args, so admission continues using the projector/default ceiling. Fresh evidence in the current revision is the bundled llama-server registration at /workspace/unsloth_studio/llama.cpp/common/arg.cpp:2634-2639, which exposes --image-max-tokens through .set_env("LLAMA_ARG_IMAGE_MAX_TOKENS"). For example, an environment cap of 8192 lets a dynamic-resolution image approach that size while Studio reserves only 4,224 positions, recreating the concurrent-request KV overcommit this change is intended to prevent.

Useful? React with 👍 / 👎.

danielhanchen added a commit that referenced this pull request Aug 27, 2026
pre-commit.ci has been failing on main since #9842 and #9791, which landed
asserts written in the parenthesize-the-message style that a newer ruff
produces. The kwarg-spacing hook pins ruff==0.6.9, which writes the message
unparenthesized and the condition parenthesized instead, so it rewrote both
files on every run and the job reported 'files were modified by this hook'.

Formatting only: the AST of each file is unchanged and both still pass.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Vision blocks parallel slots

2 participants