Skip to content

fix(transformers): enforce the launch context_length on multimodal direct chat - #5729

Merged
qinxuye merged 2 commits into
xorbitsai:mainfrom
Jackmeson1:fix/mm-context-budget
Oct 18, 2026
Merged

qinxuye merged 2 commits into
xorbitsai:mainfrom
Jackmeson1:fix/mm-context-budget

Conversation

@Jackmeson1

@Jackmeson1 Jackmeson1 commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

What happens

context_length is documented as the per-request input-plus-output limit, Transformers included (doc/source/user_guide/launch.rst). At bdd7651, 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 oversized max_tokens is forwarded past the remaining budget. These CPU-mocked MiniCPM-V 4.7 direct-chat cases use synthetic prepared input_ids and a launch config with context_length=8:

request bdd7651 with this PR
3 prepared prompt tokens, max_tokens=12 generation starts with max_new_tokens=12 max_new_tokens=5
7 prepared prompt tokens, max_tokens=12 max_new_tokens=12 max_new_tokens=1
8 or 9 prepared prompt tokens, max_tokens=6 attempts to start the generation thread ContextLengthExceeded before the generation thread starts
no context_length at launch requested/default output budget same budget

The text Transformers batching path uses get_max_src_len and truncates prompt IDs in pad_prefill_tokens (transformers/utils.py); these multimodal direct-chat paths build their inputs and call generate without those checks.

Change

  • PytorchMultiModalModel._cap_context_max_new_tokens(input_length, max_new_tokens) in multimodal/core.py. With no launch context_length, it returns the adapter's resolved max_new_tokens unchanged. Otherwise it caps output to the remaining budget, and raises the existing ContextLengthExceeded when the prepared prompt (including media placeholders in input_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 ContextLengthExceeded by exception type (review feedback): before streaming starts they return HTTP 400 with context_length_exceeded and invalid_request_error respectively; once streaming, Responses emits response.failed with that code and Anthropic an error event of type invalid_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.rst already says.

Tests

xinference/model/llm/tests/test_multimodal_context_length.py has 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 or generate call), one token left, omitted/None max_tokens, unchanged defaults, absent/None launch limits, and input/config preservation. All cases supply synthetic prepared IDs: MiniCPM-V 4.7 mocks the processor; the other three mock build_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 (base bdd7651), 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 bdd7651 production files with the branch's test files: test_multimodal_context_length.py gave 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:

    uvx pre-commit run --files \
      xinference/model/llm/tests/test_multimodal_context_length.py \
      xinference/model/llm/tests/test_qwen2_vl.py \
      xinference/model/llm/transformers/multimodal/core.py \
      xinference/model/llm/transformers/multimodal/glm4_1v.py \
      xinference/model/llm/transformers/multimodal/intern_vl.py \
      xinference/model/llm/transformers/multimodal/minicpmv47.py \
      xinference/model/llm/transformers/multimodal/qwen2_vl.py
  • Endpoint cases in xinference/api/tests/test_openai_responses.py cover both routes in both modes with the real exception, plus generic-error and rate-limit controls. test_openai_responses.py, test_anthropic_messages.py and test_multimodal_context_length.py together: 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

@XprobeBot XprobeBot added bug Something isn't working gpu labels Oct 17, 2026
@XprobeBot XprobeBot added this to the v4.x milestone Oct 17, 2026

@qinxuye qinxuye left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

One API error-classification issue remains; the context-budget calculation itself passed the focused checks.

Jackmeson1 and others added 2 commits October 17, 2026 21:41
…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
Jackmeson1 force-pushed the fix/mm-context-budget branch from 8248057 to c8bfe10 Compare October 18, 2026 05:00

@qinxuye qinxuye left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working gpu

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants