Skip to content

[Kimi K3 Bug] Fix kimi k3 reasoning parser - #57098

Merged
vllm-bot merged 3 commits into
mainfrom
wentao-fix-reasoning-parser
Sep 17, 2026
Merged

vllm-bot merged 3 commits into
mainfrom
wentao-fix-reasoning-parser

Conversation

@yewentao256

Copy link
Copy Markdown
Member

Purpose

This bug from a real user case, minimal reproduce command:

vllm serve moonshotai/Kimi-K3 \
  --trust-remote-code \
  --tensor-parallel-size 8 \
  --load-format fastsafetensors \
  --gpu-memory-utilization 0.9 \
  --enable-prefix-caching \
  --reasoning-parser kimi_k3 \
  --enable-auto-tool-choice \
  --tool-call-parser kimi_k3 \
  --host 0.0.0.0 \
  --port 30000 \
  --max-model-len auto \
  --speculative-config '{"model":"RedHatAI/Kimi-K3-speculator.dspark","method":"dspark","num_speculative_tokens":8,"draft_sample_method":"probabilistic","rejection_sample_method":"standard"}'   --use-replayssm   --max-num-seqs 48

Test

Use this script

#!/usr/bin/env python3
"""Reproduce Kimi-K3 truncated-reasoning classification through vLLM."""

import json
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen


URL = "http://127.0.0.1:30000/v1/chat/completions"
MODEL = "moonshotai/Kimi-K3"

payload = {
    "model": MODEL,
    "messages": [
        {
            "role": "user",
            "content": (
                "Solve this carefully: find the exact number of distinct ways to "
                "color the vertices of a dodecahedron with four colors, modulo all "
                "rotational symmetries. Return only the required JSON after reasoning."
            ),
        }
    ],
    "temperature": 0,
    # Deliberately stop K3 before it can finish its reasoning.
    "max_tokens": 16,
    "stream": False,
    "response_format": {
        "type": "json_schema",
        "json_schema": {
            "name": "answer",
            "strict": True,
            "schema": {
                "type": "object",
                "properties": {"answer": {"type": "string"}},
                "required": ["answer"],
                "additionalProperties": False,
            },
        },
    },
    "chat_template_kwargs": {
        "thinking": True,
        "enable_thinking": True,
    },
}

request = Request(
    URL,
    data=json.dumps(payload).encode("utf-8"),
    headers={
        "Authorization": "Bearer EMPTY",
        "Content-Type": "application/json",
    },
    method="POST",
)

try:
    with urlopen(request, timeout=120) as response:
        result = json.load(response)
except HTTPError as error:
    print(f"HTTP {error.code}: {error.read().decode('utf-8', errors='replace')}")
    raise SystemExit(1) from error
except URLError as error:
    print(f"Cannot connect to {URL}: {error.reason}")
    raise SystemExit(1) from error

choice = result["choices"][0]
message = choice["message"]
content = message.get("content")
reasoning = message.get("reasoning") or message.get("reasoning_content")

print(f"finish_reason: {choice.get('finish_reason')}")
print(f"content: {content!r}")
print(f"reasoning: {reasoning!r}")

if choice.get("finish_reason") == "length" and content and not reasoning:
    print("\nBUG reproduced: truncated reasoning was incorrectly returned as content.")
elif choice.get("finish_reason") == "length" and reasoning and not content:
    print("\nFIX verified: truncated text is reasoning; content is empty.")
else:
    print("\nThe model did not take the expected truncation path; rerun the request.")

Before:

python repro_kimi_k3_truncated_reasoning.py 
finish_reason: length
content: 'We need solve. Need return only JSON after reasoning. Need compute exact number of'
reasoning: None

BUG reproduced: truncated reasoning was incorrectly returned as content.

Now

python repro_kimi_k3_truncated_reasoning.py
finish_reason: length
content: None
reasoning: 'We need solve. Need return only JSON after reasoning. Need compute exact number of'

FIX verified: truncated text is reasoning; content is empty.

Signed-off-by: yewentao256 <zhyanwentao@126.com>

@claude claude 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.

Claude Code Review

This repository is configured for manual code reviews. Comment @claude review for a one-time review, or @claude review always to subscribe this PR to a review on every future push.

Tip: disable this comment in your organization's Code Review settings.

@yewentao256 yewentao256 added the ready ONLY add when PR is ready to merge/full CI is needed label Sep 16, 2026
@yewentao256

Copy link
Copy Markdown
Member Author

/ci run

@github-actions

Copy link
Copy Markdown

❌ This PR is 2 commits behind upstream main. Your branch must contain every commit currently on upstream main. No new CI build was started. Merge or rebase onto the latest main, then rerun /ci run. To test this branch at your own risk, use /ci run --allow-stale.

@sfeng33 sfeng33 left a comment

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.

Thanks for the work! The truncation fix makes sense: the non-streaming path was inconsistent with is_reasoning_end, _extract_content_ids, and streaming, which already treat markerless output as ongoing reasoning.

However, removing the guard unconditionally may regress cases where thinking parsing is enabled but the prompt did not open a <|open|>think<|sep|> channel. For example, output beginning with <|open|>response<|sep|> is now returned entirely as reasoning with content=None. Since no remainder reaches KimiK3Parser._extract_tool_calls, any tools channel is also silently lost.

Suggestion: take the truncated-reasoning path only when the text has no _response_open_re match (a response opener is positive evidence the think channel was never in play); otherwise keep the old content fallthrough.

Signed-off-by: yewentao256 <zhyanwentao@126.com>

@yewentao256 yewentao256 left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Thanks @sfeng33 fixed, could you take another look?

@sfeng33 sfeng33 left a comment

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.

Thank you, LGTM!

@sfeng33

sfeng33 commented Sep 16, 2026

Copy link
Copy Markdown
Member

/ci run

@github-actions

Copy link
Copy Markdown

βœ… Triggered Buildkite CI #89422 for commit 1c5ae3aea3f6.

@yewentao256
yewentao256 enabled auto-merge (squash) September 16, 2026 20:05
linnea-lin-00638949 added a commit to linnea-lin-00638949/vllm that referenced this pull request Sep 30, 2026
… and response-opener parse

Follow-up to vllm-project#57098: cover the three non-stream fallback shapes it
introduced -- marker-free truncated output stays reasoning, an open
marker without a close stays reasoning, and a response opener without
any think marker stays content.

Signed-off-by: linnea-lin-00638949 <247557940+linnea-lin-00638949@users.noreply.github.com>
he-yufeng added a commit to he-yufeng/vllm that referenced this pull request Oct 1, 2026
extract_reasoning gained the four-shape split in vllm-project#57098, but
extract_reasoning_streaming still falls through to "everything is
reasoning" whenever no think-close marker exists. A completion that
opens straight into the response channel (no think markers at all) is
content in the non-streaming path, yet streamed entirely as
reasoning_content (raw XTML markers included) with content left empty.

Latch the response-only shape once the opener completes, route the
stream through strip_content_streaming from then on, and hold back a
partial response opener in _reasoning_text_ready_to_emit so the first
ambiguous chunks are not emitted as reasoning while the marker is
still arriving. Reasoning that already streamed before a mid-stream
response opener (think prefix consumed, close never sent) stays
reasoning; only the response body switches.

Fixes vllm-project#57688

Co-authored-by: Kimi Code <kimi-code@moonshot.cn>
Signed-off-by: Yufeng He <40085740+he-yufeng@users.noreply.github.com>
michael-gpu pushed a commit to practical-inference/vllm-ampere-extended that referenced this pull request Oct 20, 2026
Signed-off-by: yewentao256 <zhyanwentao@126.com>
Co-authored-by: Flora Feng <4florafeng@gmail.com>
he-yufeng added a commit to he-yufeng/vllm that referenced this pull request Oct 20, 2026
extract_reasoning gained the four-shape split in vllm-project#57098, but
extract_reasoning_streaming still falls through to "everything is
reasoning" whenever no think-close marker exists. A completion that
opens straight into the response channel (no think markers at all) is
content in the non-streaming path, yet streamed entirely as
reasoning_content (raw XTML markers included) with content left empty.

Latch the response-only shape once the opener completes, route the
stream through strip_content_streaming from then on, and hold back a
partial response opener in _reasoning_text_ready_to_emit so the first
ambiguous chunks are not emitted as reasoning while the marker is
still arriving. Reasoning that already streamed before a mid-stream
response opener (think prefix consumed, close never sent) stays
reasoning; only the response body switches.

Fixes vllm-project#57688

Co-authored-by: Kimi Code <kimi-code@moonshot.cn>
Signed-off-by: Yufeng He <40085740+he-yufeng@users.noreply.github.com>
@arpera arpera removed this from Tool Calling Oct 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working k3 kimi ready ONLY add when PR is ready to merge/full CI is needed tool-calling

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants