← Back to Pull requests

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

Closed
unknown closed this pull request without merging on Oct 18, 2026 06:40 UTC
View on GitHub
unknown unknown commented on Oct 17, 2026 19:15 UTC
Author

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 #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

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: Jackmeson1 Review duration: 685m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #5729"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%