Skip to content

Studio GGUF: charge images in the fit and tool-result sizing counts (#14968) - #15014

Merged
danielhanchen merged 10 commits into
unslothai:mainfrom
debojyoti-dev:fix/gguf-image-token-pricing-14968
Oct 26, 2026
Merged

danielhanchen merged 10 commits into
unslothai:mainfrom
debojyoti-dev:fix/gguf-image-token-pricing-14968

Conversation

@debojyoti-dev

@debojyoti-dev debojyoti-dev commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #14968

Before: on a local GGUF vision model with Auto-compact on, the token counts behind compaction and tool-result sizing dropped images entirely. A chat with ten screenshots (~20k image tokens) looked ~20k tokens smaller than it was, so nothing was evicted and no tool result was trimmed until llama-server refused the prompt with "Message too long: 66651 tokens exceeds the 65536-token context window".

After: each image is charged what it will actually cost the prompt. Older tool exchanges are evicted, and tool results are sized to the room that is really left, the same way text-only chats have behaved since #5562. The request itself still sends the real images; only the counting copy changes.

How:

  • context_window.py: messages_with_priced_images builds the counting copy with each image_url / input_image part replaced by a text stand-in of N single-token repeats, so /apply-template + /tokenize count it as N tokens. Audio and video stay unpriced and are dropped as before. estimate_message_tokens_with_priced_images adds the image prices to the cheap estimate instead of serialising the stand-in. image_dimensions reads an inline data-URL image's size with PIL (cached per URL, since the same image is priced on every count in a tool loop).
  • llama_cpp.py: _image_token_price charges the same per-image admission ceiling the OpenAI admission gate uses (_mcp_image_tokens). On Qwen2/2.5/3-VL projectors, where an image's size gives a close count, it uses (w / s) * (h / s) merged patches (s = 28 or 32 px) plus mtmd's wrapper tokens, capped by --image-max-tokens and never above the ceiling. A text-only model is charged nothing, and an image whose size can't be read cheaply (remote URL, unknown projector) is charged the ceiling.
  • Every fit and size probe in the GGUF chat and tool loop (fit_rolling_context counts and estimates, the tool-result room probes, the final-answer fit) now goes through LlamaCppBackend._countable_messages / _estimate_countable_message instead of messages_without_unpriced_media / estimate_message_tokens_without_unpriced_media.

Tests: studio/backend/tests/test_image_token_pricing_14968.py (13 tests) covers the stand-in, audio/video staying unpriced, the no-media fast path, the estimate, reading dimensions, Qwen3-VL pricing from size, the --image-max-tokens cap, the ceiling bound, the ceiling fallback, text-only models, and the report's shape: ten 1920x1080 screenshots plus a long tool loop, which the old count kept whole (~46k text under the 49k budget) and which now evicts older tool rounds while keeping the screenshots.

test_llama_cpp_tool_loop.py::test_repeated_note_on_an_mcp_image_keeps_the_base64_out_of_the_tool_text now gives its fake backend a Qwen3-VL projector: with a 4096-token window and no projector, each screenshot is charged the ~4.2k admission ceiling (the same one admission charges), so the loop correctly reported no room before reaching the repeat note the test checks.

Ran the 43 backend suites that touch these counts on Windows 11 (Python 3.13, no GPU needed). The new tests pass, and the remaining failures are environmental and also fail on unchanged main: missing optional packages (transformers, ddgs, sqlite-vec), symlinks needing admin rights on Windows, a case-insensitive filesystem check, a console encoding error, and a /proc/self/fd check. The GGUF over-the-per-turn-cap tests (test_tool_call_cap_notice_extra.py::test_cap_notice_does_not_invite_a_spent_one_shot_retry[...-gguf] and the test_gguf_*over_cap* tests in test_llama_cpp_tool_loop.py) stall on this machine with and without this change, at the same test. Not tested against a live llama-server with a vision GGUF.

Follow-up changes

  • Gemma 3 images are priced at their fixed cost (256 embeddings plus the wrapper allowance) instead of the 4,224-token admission ceiling. llama-server charges 258 per image on Gemma 3 4B at every size, so the ceiling was a 16x overcharge that would evict history that fits.
  • The image size cache is keyed on a hash of the data URL instead of the URL itself, so it no longer keeps up to 256 multi-MB base64 payloads alive in a long Studio session.
  • Ministral image turns are balanced before images become stand-ins. The stand-in text hid the synthetic image turn from the alternation fix-up, so the counting copy failed Ministral's role check and the fit fell back to estimates.
  • The prompt offset taken from the fit now subtracts the image-aware estimate, so the fallback size estimate no longer charges retained images twice.
  • The Qwen-VL patch grid uses ceil instead of round, so the price stays an upper bound. With --image-min-tokens set, images are charged the ceiling, since mtmd resizes against it on its own rounded grid.
  • Dropped the now unused estimate_message_tokens_without_unpriced_media import that tripped the import hoist check.

Verification against a live llama-server

Reporter's build (b11798-mix-f8a7950, CPU), Qwen3-VL-2B with its mmproj, 65536 context, max_tokens 32768 (prompt budget 49152). One user message with ten 1920x1080 screenshots plus 13 tool rounds, fitted with each tree's counting code, then sent with the real images:

Counted before fit Messages dropped Images kept llama-server
main 48,679 0 10 request (69099 tokens) exceeds the available context size (65536 tokens)
this PR 70,359 16 10 accepted, 39,459 prompt tokens

Per-image price vs what llama-server charged (prompt_tokens with the image minus without):

Projector Image Server Price
qwen3vl_merger 1920x1080 2,042 2,168
qwen3vl_merger 2560x1440 3,602 3,728
qwen3vl_merger 800x600 477 603
qwen3vl_merger, --image-max-tokens 2048 2560x1440 1,982 2,176
gemma3 any size 258 384

The text stand-in tokenizes to exactly N tokens on both the Qwen3 and Gemma 3 tokenizers.

…nslothai#14968)

The counting copy used by fit_rolling_context and the tool-loop room probes
dropped image parts, so a vision chat with many screenshots looked ~20k tokens
smaller than it was and was never compacted before llama-server refused it.

Images now become a text stand-in of what they will cost: the admission
ceiling, or on Qwen-VL projectors a size-based merged-patch count capped by
--image-max-tokens. Audio and video stay unpriced, and the request still sends
the real images.
pre-commit-ci Bot and others added 2 commits October 23, 2026 18:23
… charged (unslothai#14968)

The fake backend has a 4096-token window and no projector, so each MCP
screenshot was charged the ~4.2k admission ceiling and the loop reported no
room before the repeat note. Give it a Qwen3-VL projector so the 6 px image
costs what it would.
@danielhanchen

Copy link
Copy Markdown
Member

The Source lint failure here comes from this PR's change, not from main. scripts/verify_import_hoist.py blocks on studio/backend/core/inference/llama_cpp.py:

[BLOCKER] HOISTED-IMPORT-UNUSED 'estimate_message_tokens_without_unpriced_media'
(['from:core.inference.context_window:estimate_message_tokens_without_unpriced_media'])
was used before, now unused (references re-pointed)

After this change the import is no longer referenced in llama_cpp.py. Dropping it, or using it if the re-pointed call sites should still go through it, clears the check.

The codespell and shellcheck output in that job is informational and passes on main as well. The (Python 3.13, a-k) reds elsewhere in the queue were fixed on main by #15015 and #15017.

…ion cache keyed off the payload, drop the unused import

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 25, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-25T12:56:43.876295Z
We couldn’t complete this review. Comment @codex review to try again.
c055cd4 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.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

An unknown error occurred
ℹ️ 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

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

An unknown error occurred
ℹ️ 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 8b3f6fe into unslothai:main Oct 26, 2026
55 checks passed
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] Auto-compact ignores image tokens on local GGUF chats, so tool loops with screenshots overflow the context window

2 participants