Skip to content

[Feat] sgl-router: Render Kimi-K3 through sglang-processor - #43608

Merged
sherlockwu merged 10 commits into
mainfrom
kan/sgl-router-kimi-k3
Oct 14, 2026
Merged

sherlockwu merged 10 commits into
mainfrom
kan/sgl-router-kimi-k3

Conversation

@sherlockwu

@sherlockwu sherlockwu commented Oct 10, 2026 •

Copy link
Copy Markdown
Collaborator

Note

Stack 2/3, merge in order: #43625 (GLM-5.3) → #43608 (Kimi-K3) → #43689 (Qwen3.8). This PR is based on #43625 (kan/sgl-router-glm53), so its diff shows only the Kimi-K3 commit. After #43625 merges it gets rebased onto main.

Adds Kimi-K3 to sglang-processor and serves its chats from the router end to end: the router renders and tokenizes every text Kimi-K3 chat exactly as SGLang does, and with the cookbook's kimi_k3 reasoning and tool parsers it also lowers them to /generate and parses the output itself (reasoning split, tool calls, usage). This follows #43000 (DeepSeek-V4.1).

Modifications

  • Render: ChatFormatter::KimiK3 (render/models/kimi_k3.rs). render_request builds the request the way serving_chat.py calls the checkpoint's encoder (_prepare_kimi_k3_messages and the kimi_k3 branch of _encode_messages), then renders it with Dynamo's KimiK3Formatter:

    • Messages: the pydantic message dump keeps only text parts, neutralizes the image placeholder, and turns developer turns into system turns. String tool arguments are parsed into objects.
    • Tools: dumped as exclude_unset does, with schema types normalized as _validate_request does (varchar becomes string). A system turn with tools renders only its declaration.
    • Thinking: kwargs win, then reasoning/effort, then the server's defaults; on by default.
    • thinking_effort: the kwarg, else a low/high/max request effort, else max.
    • tool_choice (required/none) and response_format (including the legacy schema and the kwargs response_schema) render as SGLang renders them.
    • Continuation: the continue_final_message prefix is returned on its own, since SGLang tokenizes it separately.

    render_request now returns a RenderedPrompt, so K3 keeps its special-token segments. render_prompt keeps Dynamo's K3 request semantics, which typed hosts rely on, so sglang-renderer is unchanged.

  • Left to the engine: where the pinned formatter would render differently, render_request returns an error and hosts send the request to the engine:

    • media (image, video and audio parts), as for DeepSeek-V4.1 and GLM-5.3;
    • a null thinking_effort with thinking on;
    • whitespace-only reasoning history;
    • string tool arguments that are not a JSON object;
    • numbers serde_json prints differently from Python (1e-06, integers beyond 64 bits, -0);
    • tokenizer arguments in chat_template_kwargs (including messages, which build_chat_segments rejects);
    • tool declarations Dynamo rejects.

    Requests _validate_request rejects (a required tool_choice without tools, a json_schema format without a schema) fail to render too.

  • Router:

    • Kimi-K3 renders through the processor. The router's own kimi::normalize is gone; the chunked tiktoken encode stays.
    • Every text chat forwards input_ids (AllText).
    • Kimi chats lower to /generate like other AllText models. required, named and strict tool_choice, system-turn tools, media and logprobs (no tokenizer.json) keep the engine's route.
  • Parsing (openai/, think/, tool_call/):

    • think/models/kimi_k3.rs: KimiK3Detector from parser/reasoning_parser.py (XTML think channel, response/message unwrapping, skipped-think detection, tools passthrough). ThinkConfig becomes an enum so a detector that overrides the base splitting gets its own variant.
    • tool_call/models/kimi_k3.rs: the kimi_k3 detector from function_call/kimik3_detector.py.
    • openai/kimi_k3_tag.rs: the tool_choice: auto structural tag (get_kimik3_auto_tool_call_structural_tag), with strip_structural_tag_excludes.
    • kimi_k3_format.rs: the XTML markers and helpers the three share (kimik3_format.py).
    • lower_chat / ChatResponder apply serving_chat.py's K3 rules: skip_special_tokens=False, <|close|>tools<|sep|> as a stop string, thinking on unless kwargs turn it off, non-strict json_schema unconstrained (renderer_handles_response_format), name:N tool-call ids (_process_tool_call_id), and the three-token generation stub left out of reported prompt tokens. ChatModel carries chat_encoding_spec.

Checks

  • Render: 112 cases match SGLang's prompt text and token ids at moonshotai/Kimi-K3@f831ab66, using the real tiktoken vocab. 13 are known gaps that the processor leaves to the engine. generate_parity.py records the template text for a spec that tokenizes inside apply_chat_template.
  • Parsers and OpenAI layer (fixtures from SGLang's Python):
    • reasoning_parity/kimi_k3.json: 96 cases (19 outputs × forced/unforced × streamed/not, plus force_nonempty_content for 5), chunked to split every marker.
    • tool_parity/kimik3.json: 46 chunked outputs (43 distinct), including token-level and single-character splits, truncation mid-marker, and typed argument values (integers beyond 64 bits, -0, NaN, Infinity, overflowing floats, duplicate keys, escapes, strings json.loads rejects, and an argument of 5,000 nested arrays). Values go through json.dumps(json.loads(...)) exactly (py.rs::python_json_reencode), so integers keep their digits; the scanner neither recurses nor copies per level, so nesting costs heap, not stack, and past Python 3.12's ~10,000-container RecursionError the value is treated as JSON Python cannot load.
    • openai_parity/kimi-k3.json: 24 cases recorded from OpenAIServingChat (including an 8-hop $ref chain for the tag's schema typing, which stops past 64 levels or 10,000 steps and leaves such tools to the engine) (including tools with regex: "" / ebnf: "", which Python treats as unset, so the tag stays); the /generate body (prompt ids, stop list, the auto structural tag byte for byte, including every _schema_types branch) and the OpenAI response (unary and streaming, usage, tool-call ids, n=2) match for all 22 served, and the 2 others are left to the engine.
    • Dynamo's own kimi_k3 reasoning parser, tool parser and structural tag match these Python fixtures in 13/54, 35/51 and 1/22 cases (response wrappers left in content, a different tag grammar), so the processor ports SGLang's; the three share kimi_k3_format.rs, as Python's share kimik3_format.py.
  • End to end on 8×B300 (cookbook B300 Low-Latency recipe: TP8, --mem-fraction-static 0.85, kimi_k3 parsers): each request is sent to the engine and through the real sgl-router binary.
    • Real weights (moonshotai/Kimi-K3@f831ab66):
      • 48 greedy chats (math, effort levels, thinking off, JSON output, single, parallel and serial tool calls, tool results, continuation, truncation; unary and streaming): 46 of 48 are served via /generate and the router's /generate bodies match the GenerateReqInput OpenAIServingChat builds for all 46. Responses match except two whose generations diverge mid-reasoning from identical inputs, as the engine also does between its own runs; on six repeats each, the router and the engine give the same output.

      • GSM8K (1319, chat API, reasoning_effort=low): 0.977 through the engine and 0.977 through the router, all router requests via /generate.

      • bench_serving (sglang-oai-chat, random 8192 in / 1024 out, every router request via /generate):

        concurrency path output tok/s median TTFT (ms) median ITL (ms)
        16 engine 613 5042 19.2
        16 router 654 4119 19.2
        64 engine 1071 12505 31.8
        64 router 1070 12540 31.9
    • Dummy weights with scripted K3 outputs (a custom logit processor forces think, response and tools channels): 59 cases identical, 55 via /generate; plus 159 free-form cases identical except engine-side nondeterminism and timing fields.
  • The proxy tests cover both routes: a Kimi chat lowers to /generate with the router's ids, skip_special_tokens=false, require_reasoning and the tools stop; unsupported shapes keep the chat route.
  • cargo test and cargo clippy -D warnings pass for rust/ and experimental/sgl-router.

CI States

Latest PR Test (Base): ✅ Run #38518765812
Latest PR Test (Extra): ❌ Run #38518765701
Latest PR Test (AMD ROCm 10): ➖ No AMD PR run found for this commit.

@github-actions github-actions Bot added documentation Improvements or additions to documentation deepseek npu rust-renderer labels Oct 10, 2026
@sherlockwu
sherlockwu force-pushed the kan/sgl-router-kimi-k3 branch from 83a4383 to fdecb8d Compare October 11, 2026 17:49
@sherlockwu
sherlockwu changed the base branch from main to kan/sgl-router-glm53 October 11, 2026 17:50
@sherlockwu
sherlockwu added this pull request to stack #43717 October 11, 2026 17:54
@sherlockwu sherlockwu added run-ci CI: run the baseline test suite on this PR and removed deepseek npu labels Oct 11, 2026
@sherlockwu
sherlockwu force-pushed the kan/sgl-router-kimi-k3 branch from fdecb8d to 74cc96d Compare October 12, 2026 20:29
@sherlockwu
sherlockwu force-pushed the kan/sgl-router-kimi-k3 branch from 0dcc58c to a6ad5b6 Compare October 13, 2026 07:59
Base automatically changed from kan/sgl-router-glm53 to main October 14, 2026 05:19
sherlockwu and others added 10 commits October 14, 2026 13:21
sglang-processor gains ChatFormatter::KimiK3, whose render_request builds
the request as SGLang's serving_chat.py calls the checkpoint encoder
(_prepare_kimi_k3_messages, the kimi_k3 branch of _encode_messages) and
renders it with Dynamo's KimiK3Formatter. Shapes the pinned formatter
renders differently return an error so hosts leave them to the engine.
render_request now returns a RenderedPrompt, keeping K3's special-token
segments.

sgl-router renders Kimi-K3 through the processor instead of its own
normalization and forwards input_ids for every text chat. Kimi chats stay
on the engine's OpenAI route, whose layer special-cases K3.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Normalize tool schema types (`varchar` becomes `string`) on request and
  system/developer tools, as `_validate_request` does before the encoder
  dumps them.
- Leave a `messages` template kwarg to the engine: `build_chat_segments`
  fails on it as a duplicate argument.
- Reject what `_validate_request` rejects: a required `tool_choice` without
  tools, and a `json_schema` response format without a schema.
- Regenerate kimi-k3.json with the validating generator. `image_part` is
  dropped: the generator's stub serves the checkpoint as text-only, while
  SGLang serves K3 as multimodal.
- Drop the router fixture's `choice_without_tools`, which SGLang rejects.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
render_request fails on image, video and audio parts, as for DeepSeek-V4.1
and GLM-5.3; the router already keeps multimodal chats off this path.
image_part is back in the fixture, recording the text-only rejection.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- think/: KimiK3Detector, ported from parser/reasoning_parser.py. ThinkConfig
  becomes an enum so a detector that overrides the base splitting gets its
  own variant; the tag-based detector is TagDetector. reasoning_parity gains
  an opt-in force_nonempty_content dimension, which K3's detector branches on.
- tool_call/: the kimi_k3 detector, ported from function_call/kimik3_detector.py,
  with a 51-input tool_parity fixture.
- openai/: lower_chat applies what serving_chat.py does for kimi_k3:
  special tokens kept, the tools close as a stop string, the auto tool-call
  structural tag (kimi_k3_tag.rs, byte-checked against
  get_kimik3_auto_tool_call_structural_tag), non-strict json_schema left
  unconstrained, thinking on unless kwargs turn it off, name:N tool-call ids,
  and the three-token generation stub left out of reported prompt tokens.
  ChatModel carries chat_encoding_spec.
- openai_parity/kimi-k3.json: 33 synthetic cases recorded from
  OpenAIServingChat, covering reasoning, tools, streaming and usage.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With the processor reproducing the kimi_k3 reasoning and tool parsers and
K3's OpenAI-layer rules, Kimi-K3 chats lower to /generate like other
AllText models: the router renders, tokenizes and parses them. The
kimi_k3_openai_layer gate is gone; required, named and strict tool choices,
system-turn tools, media and logprobs still take the engine's route.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- kimi_k3_format.rs holds the XTML markers and the helpers the K3 reasoning
  parser, tool parser and structural tag share, as kimik3_format.py does;
  the three modules no longer carry their own copies.
- The tag builder filters think tokens from the one excludes list that holds
  them and reads types from compact keyword lists; tool_call's unit tests are
  replaced by a fixture input (U+001F separators).
- Fixtures shrink from 13.4k to 4.9k lines with the same coverage:
  reasoning_parity opts into force_nonempty_content per input and splits
  markers with 16-character chunks; tool_parity keeps all 41 distinct texts at
  most ~12 chunks each; openai_parity groups three tokens per stream frame,
  drops cases the parser fixtures already cover, and absorbs the schema-type
  cases of kimi_k3_tool_tags.json, which is removed with its generator.

Dynamo's kimi_k3 reasoning parser, tool parser and structural tag were
checked against the same Python fixtures and match 13/54, 35/51 and 1/22,
so the SGLang ports stay.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…aints as Python does

- The kimi_k3 tool parser decoded typed argument values through
  serde_json::Value, so 18446744073709551617 came back as
  1.8446744073709552e+19 in both unary and streamed tool calls. py.rs gains
  python_json_reencode, json.dumps(json.loads(text), ensure_ascii=False) with
  integers kept as digits, which also matches Python on -0, NaN, Infinity and
  overflowing floats; python_dict renders the arguments dict. A tool_parity
  input covers these values and the strings json.loads rejects.
- lower_chat skipped the K3 auto structural tag when a request carried
  `regex: ""` or `ebnf: ""`. Python tests existing constraints by truthiness,
  so empty strings are unset; the tag now stays, with openai_parity cases for
  both.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… typing

- python_json_reencode recursed once per nested array or object, so a
  generated tool argument of 5,000 nested arrays (about 10 KB) overflowed a
  2 MiB worker stack. The scanner now parses into a node arena and dumps it
  with explicit stacks: nesting costs heap, not stack, and the work is linear
  (object keys are indexed, values are not copied up each level). Past about
  10,000 open containers, where Python 3.12's json.loads raises
  RecursionError, it returns None like other JSON Python cannot load.
  python_dict indexes keys too. tool_parity gains the 5,000-deep argument;
  a unit test runs MAX_DEPTH and 2^20 levels on a 64 KiB stack.
- The auto structural tag's _schema_types followed $ref chains recursively
  without a bound, so a client's tool schema could overflow the router's
  stack or fan out exponentially. It now stops past 64 levels or 10,000
  steps, and lower_chat leaves such tools to the engine, which does exactly
  what Python does with them. openai_parity covers an in-bound $ref chain;
  a unit test covers both bounds.
- The empty regex/ebnf openai_parity cases only lower, which is what they test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`json.loads` reads integers through `int`, which raises past
`sys.get_int_max_str_digits()` (4300) digits, so Python treats such tool
argument values as text it cannot load. `python_json_reencode` kept them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ShangmingCai
ShangmingCai force-pushed the kan/sgl-router-kimi-k3 branch from 1f5a5c6 to f9606b2 Compare October 14, 2026 05:50

@ShangmingCai ShangmingCai left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM

@ShangmingCai ShangmingCai changed the title [sgl-router] Render Kimi-K3 through sglang-processor [Feat] sgl-router: Render Kimi-K3 through sglang-processor Oct 14, 2026
@sherlockwu
sherlockwu merged commit 53a24c4 into main Oct 14, 2026
120 of 125 checks passed
@sherlockwu
sherlockwu deleted the kan/sgl-router-kimi-k3 branch October 14, 2026 06:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

deepseek documentation Improvements or additions to documentation npu run-ci CI: run the baseline test suite on this PR rust-renderer

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants