Repository navigation
fix(transformers): enforce the launch context_length on multimodal direct chat - #5729
Merged
Merged
Conversation
qinxuye
reviewed
Oct 18, 2026
qinxuye
left a comment
Contributor
There was a problem hiding this comment.
One API error-classification issue remains; the context-budget calculation itself passed the focused checks.
…rect chat The MiniCPM-V 4.7, Qwen2-VL, GLM-4.1V and InternVL Transformers adapters build their inputs and call generate() directly. At bdd7651, these paths did not apply the launch context_length (documented as the per-request input-plus-output limit): full prompts still reached generation, and oversized max_tokens requests exceeded the remaining budget. Add PytorchMultiModalModel._cap_context_max_new_tokens: without a launch limit it preserves the adapter's resolved output budget; otherwise it caps output to the remaining budget and raises ContextLengthExceeded when the prepared prompt leaves no room. The four adapters call it before starting the generation thread in both response modes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019TTGAv6fe859ebbCLLfLHP
… and Anthropic routes The non-streaming chat route already maps ContextLengthExceeded to HTTP 400. At 8dd952c, the Responses and Anthropic generation-error paths classified it by message text or only special-cased rate limits, so multimodal and MLX context-limit rejections surfaced as server errors. Classify these errors by exception type. Before SSE starts, Responses returns HTTP 400 / context_length_exceeded and Anthropic returns HTTP 400 / invalid_request_error. After SSE starts, Responses emits response.failed with error.code=context_length_exceeded; Anthropic emits an error event with error.type=invalid_request_error. Preserve existing Responses text heuristics and generic/rate-limit error handling. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019TTGAv6fe859ebbCLLfLHP
Jackmeson1
force-pushed
the
fix/mm-context-budget
branch
from
October 18, 2026 05:00
8248057 to
c8bfe10
Compare
This was referenced Oct 18, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What happens
context_lengthis documented as the per-request input-plus-output limit, Transformers included (doc/source/user_guide/launch.rst). Atbdd7651, the MiniCPM-V 4.7, Qwen2-VL, GLM-4.1V and InternVL adapters ignore it on direct chat: a prompt that already fills the limit still reaches generation, and an oversizedmax_tokensis forwarded past the remaining budget. These CPU-mocked MiniCPM-V 4.7 direct-chat cases use synthetic preparedinput_idsand a launch config withcontext_length=8:bdd7651max_tokens=12max_new_tokens=12max_new_tokens=5max_tokens=12max_new_tokens=12max_new_tokens=1max_tokens=6ContextLengthExceededbefore the generation thread startscontext_lengthat launchThe text Transformers batching path uses
get_max_src_lenand truncates prompt IDs inpad_prefill_tokens(transformers/utils.py); these multimodal direct-chat paths build their inputs and callgeneratewithout those checks.Change
PytorchMultiModalModel._cap_context_max_new_tokens(input_length, max_new_tokens)inmultimodal/core.py. With no launchcontext_length, it returns the adapter's resolvedmax_new_tokensunchanged. Otherwise it caps output to the remaining budget, and raises the existingContextLengthExceededwhen the prepared prompt (including media placeholders ininput_ids) leaves no room. MLX uses the same exception class. The existing chat REST handlers return HTTP 400 for non-streaming requests and an SSE error for streaming requests.MiniCPM-V 4.7, Qwen2-VL, GLM-4.1V and InternVL call it after building inputs and before starting the generation thread, in both response modes. Prompts are not truncated, to preserve alignment with media features. Other adapters and continuous-batching paths are unchanged.
Gemma 3 and MiniCPM-V 4.6 are left out to avoid overlapping fix(transformers): use greedy decoding at temperature 0 for Gemma 3, Gemma 4, GLM-4V and MiniCPM-V 4.6 #5727; I can add them after it lands. Would you prefer the remaining multimodal adapters in this PR or as follow-ups? By default I'd send them as follow-ups.
The Responses and Anthropic routes now classify
ContextLengthExceededby exception type (review feedback): before streaming starts they return HTTP 400 withcontext_length_exceededandinvalid_request_errorrespectively; once streaming, Responses emitsresponse.failedwith that code and Anthropic anerrorevent of typeinvalid_request_error. The existing Responses text heuristics, rate-limit and generic-error handling are unchanged. MLX, which raises the same exception, benefits too.No docs change: this aligns the code with what
launch.rstalready says.Tests
xinference/model/llm/tests/test_multimodal_context_length.pyhas 360 cases: four adapters × two response modes × three message shapes (text, image, video) × 15 budget cases. It covers output caps, prompts at/over the limit (no generation thread orgeneratecall), one token left, omitted/Nonemax_tokens, unchanged defaults, absent/Nonelaunch limits, and input/config preservation. All cases supply synthetic prepared IDs: MiniCPM-V 4.7 mocks the processor; the other three mockbuild_inputs_from_messages. The media cases test plumbing, not real media tokenization or video support in every adapter.test_qwen2_vl.py's fixture gains an empty_pytorch_model_config, because it builds the model without__init__.I ran these outside the sandbox at
a011ed1(basebdd7651), on Linux under WSL with CPU torch and Transformers 5.17.0:PYTHONPATH=. python -m pytest xinference/model/llm/tests/test_multimodal_context_length.py xinference/model/llm/tests/test_qwen2_vl.py xinference/model/llm/tests/test_context_length.py -q --timeout=300: 403 passed on Python 3.12.15 (36 s) and Python 3.10.12 (34 s).Two base comparisons, using the
bdd7651production files with the branch's test files:test_multimodal_context_length.pygave 144 failed and 216 passed. The failures are 96 uncapped output budgets and 48 attempts to start the generation thread for full/oversized prompts; the passing cases are unchanged-behaviour controls.All seven changed Python files passed black, end-of-file, trailing-whitespace, ruff, isort, mypy and codespell with:
Endpoint cases in
xinference/api/tests/test_openai_responses.pycover both routes in both modes with the real exception, plus generic-error and rate-limit controls.test_openai_responses.py,test_anthropic_messages.pyandtest_multimodal_context_length.pytogether: 421 passed on Python 3.12.15 and 3.10.12; with the production files at the first commit, 6 failed and 415 passed.These tests do not load model weights, run GPU inference, or measure memory use. MiniCPM-V 4.7's loader requires Transformers >=5.18.0; the mocks bypass it.
AI-assisted: I used Claude Code to help write this change and its tests.
🤖 Generated with Claude Code
https://claude.ai/code/session_019TTGAv6fe859ebbCLLfLHP