Repository navigation
[Feat] sgl-router: Render Kimi-K3 through sglang-processor - #43608
Merged
Merged
Conversation
sherlockwu
force-pushed
the
kan/sgl-router-kimi-k3
branch
from
October 11, 2026 17:49
83a4383 to
fdecb8d
Compare
sherlockwu
force-pushed
the
kan/sgl-router-kimi-k3
branch
from
October 12, 2026 20:29
fdecb8d to
74cc96d
Compare
sherlockwu
force-pushed
the
kan/sgl-router-kimi-k3
branch
from
October 13, 2026 07:59
0dcc58c to
a6ad5b6
Compare
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]>
…generate 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
force-pushed
the
kan/sgl-router-kimi-k3
branch
from
October 14, 2026 05:50
1f5a5c6 to
f9606b2
Compare
3 of 5 tasks
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.
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 ontomain.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_k3reasoning and tool parsers it also lowers them to/generateand 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_requestbuilds the request the wayserving_chat.pycalls the checkpoint's encoder (_prepare_kimi_k3_messagesand thekimi_k3branch of_encode_messages), then renders it with Dynamo'sKimiK3Formatter:exclude_unsetdoes, with schema types normalized as_validate_requestdoes (varcharbecomesstring). A system turn with tools renders only its declaration.reasoning/effort, then the server's defaults; on by default.thinking_effort: the kwarg, else alow/high/maxrequest effort, elsemax.tool_choice(required/none) andresponse_format(including the legacyschemaand the kwargsresponse_schema) render as SGLang renders them.continue_final_messageprefix is returned on its own, since SGLang tokenizes it separately.render_requestnow returns aRenderedPrompt, so K3 keeps its special-token segments.render_promptkeeps 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_requestreturns an error and hosts send the request to the engine:thinking_effortwith thinking on;1e-06, integers beyond 64 bits,-0);chat_template_kwargs(includingmessages, whichbuild_chat_segmentsrejects);Requests
_validate_requestrejects (a requiredtool_choicewithout tools, ajson_schemaformat without a schema) fail to render too.Router:
kimi::normalizeis gone; the chunked tiktoken encode stays.input_ids(AllText)./generatelike otherAllTextmodels.required, named and stricttool_choice, system-turn tools, media andlogprobs(notokenizer.json) keep the engine's route.Parsing (
openai/,think/,tool_call/):think/models/kimi_k3.rs:KimiK3Detectorfromparser/reasoning_parser.py(XTML think channel, response/message unwrapping, skipped-think detection, tools passthrough).ThinkConfigbecomes an enum so a detector that overrides the base splitting gets its own variant.tool_call/models/kimi_k3.rs: thekimi_k3detector fromfunction_call/kimik3_detector.py.openai/kimi_k3_tag.rs: thetool_choice: autostructural tag (get_kimik3_auto_tool_call_structural_tag), withstrip_structural_tag_excludes.kimi_k3_format.rs: the XTML markers and helpers the three share (kimik3_format.py).lower_chat/ChatResponderapplyserving_chat.py's K3 rules:skip_special_tokens=False,<|close|>tools<|sep|>as a stop string, thinking on unless kwargs turn it off, non-strictjson_schemaunconstrained (renderer_handles_response_format),name:Ntool-call ids (_process_tool_call_id), and the three-token generation stub left out of reported prompt tokens.ChatModelcarrieschat_encoding_spec.Checks
moonshotai/Kimi-K3@f831ab66, using the real tiktoken vocab. 13 are known gaps that the processor leaves to the engine.generate_parity.pyrecords the template text for a spec that tokenizes insideapply_chat_template.reasoning_parity/kimi_k3.json: 96 cases (19 outputs × forced/unforced × streamed/not, plusforce_nonempty_contentfor 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, stringsjson.loadsrejects, and an argument of 5,000 nested arrays). Values go throughjson.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-containerRecursionErrorthe value is treated as JSON Python cannot load.openai_parity/kimi-k3.json: 24 cases recorded fromOpenAIServingChat(including an 8-hop$refchain for the tag's schema typing, which stops past 64 levels or 10,000 steps and leaves such tools to the engine) (including tools withregex: ""/ebnf: "", which Python treats as unset, so the tag stays); the/generatebody (prompt ids, stop list, the auto structural tag byte for byte, including every_schema_typesbranch) 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.kimi_k3reasoning 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 sharekimi_k3_format.rs, as Python's sharekimik3_format.py.--mem-fraction-static 0.85,kimi_k3parsers): each request is sent to the engine and through the realsgl-routerbinary.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
/generateand the router's/generatebodies match theGenerateReqInputOpenAIServingChatbuilds 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):/generate; plus 159 free-form cases identical except engine-side nondeterminism and timing fields./generatewith the router's ids,skip_special_tokens=false,require_reasoningand the tools stop; unsupported shapes keep the chat route.cargo testandcargo clippy -D warningspass forrust/andexperimental/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.