Skip to content

[atomesh] Rust frontend down to LLMEngine, replacing the Python standalone service - #3698

Merged
Yuechguo merged 20 commits into
mainfrom
yuechguo/mesh-llmengine-bridge
Nov 24, 2026
Merged

Yuechguo merged 20 commits into
mainfrom
yuechguo/mesh-llmengine-bridge

Conversation

@Yuechguo

@Yuechguo Yuechguo commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

ATOM standalone (USE_ATOMESH_ENTRYPOINTS=1) served the OpenAI API from Python (AtomStandaloneService) behind the mesh HTTP server: JSON, the chat template, tokenization, detokenization, the reasoning / tool parsers and the SSE all ran on one GIL.

This PR moves that work into the mesh router (Rust) and stops at LLMEngine: Rust renders, tokenizes, detokenizes, parses and writes the SSE; Python only takes the prompt's token ids into io_processor.preprocess_fanout and CoreManager.add_request, exactly as the OpenAI server does, and hands each engine step's tokens back in one push. LLMEngine, CoreManager and the EngineCores are unchanged, so everything below the frontend keeps working as it is: DP routing (share_cache, prefix_spread), back-pressure, PP, P/D, metrics.

Relation to #3372 / #3489 / #3507 (Rust directly to the EngineCores over engine_v1): this is the smaller first step. Standalone keeps serving throughout (the atomesh accuracy job does not need gating), and the EngineCore client can be added on top later as a second, opt-in backend.

Technical Details

Python (atom/entrypoints/atomesh/)

  • token_bridge.py (new): TokenBridge — submit (SamplingParams built and checked as the OpenAI server does: defaults, the deployment's output cap, context / pool checks, n coerced as _coerce_n), abort, is_healthy, and a per-step flush through CoreManager's _flush_stream_batch_fn hook (one StepSink.push per output thread per step). ChatRenderer renders the prompt of a model whose template Rust cannot render (DeepSeek-V4 / V4.1's Python encoder, Kimi-K3's code template) with the OpenAI server's own steps (ChatCompletionRequest → normalize_chat_tools → get_messages → apply_chat_template), including thinking / reasoning_effort and a string tool_choice.
  • server.py: builds the bridge, and hands the router the tool-call / reasoning parsers ATOM reads off the model (--tool-call-parser / --reasoning-parser in the router's names), unless the launch named them.
  • atom_standalone_service.py and its tests are removed.

Rust (atom/mesh/src/)

  • routers/atom_bridge/: AtomBridgeRouter over the gRPC Pipeline with a one-engine planner and BridgeDispatcher injected; events.rs turns step events into TokenChunks (siblings in index order, per-sequence timing, abort on client disconnect on either side of the submit); py_bridge.rs holds StepSink and the request checks. routers/atom_standalone.rs is removed.
  • routers/prepare and routers/render (shared with gRPC routing): prepare_chat_with / Pipeline::execute_chat_with take a prompt rendered outside the router; ResponseContext.prompt_opener lets the reasoning parser read the channel opener the prompt ended on (<think>, K3's think / response); long non-streamed replies are split instead of answering 500 (ported from [3/N atomesh rust runtime] feat(mesh): Rust EngineCore client and the atom_engine router #3372); render/atom_usage.rs adds ATOM's usage fields (cached_tokens, ttft_s / tpot_s / latency_s) on chat (ported from [3/N atomesh rust runtime] feat(mesh): Rust EngineCore client and the atom_engine router #3372; only this backend sets WorkerMeta.timing, so gRPC usage is unchanged).
  • reasoning/kimi_k3.rs: a Kimi-K3 reasoning parser, which reasoning-parser 1.0.0 lacks.

Supported through the Rust frontend: /v1/chat/completions, /v1/completions, /generate (streamed and not), /v1/models, /health_generate; n > 1 (not streamed); data_parallel_rank; --default-chat-template-kwargs; tool_choice required / named function (read by the model's own tool parser, as before; required uses Kimi-K3's required_channel); DeepSeek-V4.1's reasoning controls.

Known differences from the Python service (listed in docs/atomesh_rust_frontend.md):

  • Refused with a 400 for now: streaming with n > 1, image / video / audio content, logprobs, structured output.
  • /v1/completions requires model in the body.
  • A completion's usage does not carry timing yet.

Test Plan

  1. Unit tests: cargo test (mesh) and pytest tests/entrypoints tests/test_required_channel.py; black / ruff / cargo fmt.
  2. Accuracy: GSM8K 3-shot on Qwen3-30B-A3B, TP1, MI300X, through /v1/completions against the Python standalone service on the same build, and through /v1/chat/completions (thinking on).
  3. Prompt parity for Python-rendered templates: 13 chat requests (thinking on / off three ways, content lists, tools with tool_choice auto / required, multi-turn tool calls with reasoning_content), token by token against _chat_completions's render, on the body as the router serializes it — DeepSeek-V4.1-Flash, DeepSeek-V4-Flash, Kimi-K3.
  4. Live probes on GPU: reasoning split, enable_thinking=false, n=2, streamed n=2 refused, data_parallel_rank, image content refused, usage fields.
  5. Frontend cost (benchmark-only branch, not part of this PR): a fake CoreManager (no GPU), 16 pinned cores, measuring from request arrival to core_mgr.add_request; both sides tokenize with llm-tokenizer 2.0.0.

Test Result

  1. cargo test: all pass. pytest: 3301 passed; the 3 failures in test_structured_output.py fail on main as well.

  2. GSM8K (Qwen3-30B-A3B):

    Frontend Endpoint flexible-extract strict-match
    Python standalone service /v1/completions 0.6808 0.8825
    Rust (this PR) /v1/completions 0.6876 0.8901
    Rust (this PR) /v1/chat/completions 0.8704 0.6748
  3. Prompt parity: 13/13 identical on each of the three models.

  4. All probes behave as listed above.

  5. Frontend cost, 16 cores:

    Rust Python, same tokenizer
    Max req/s, completions 1k / 8k tokens 2,689 / 932 901 / 409
    Max req/s, chat 1k / 8k tokens 2,395 / 892 696 / 352
    Arrival → add_request, concurrency 1, 1k / 8k tokens 0.36 / 2.13 ms 0.92 / 2.95 ms

    Both sides are capped by a single-threaded Python section; for Rust that is the preprocess_fanout + add_request part of TokenBridge.submit. Follow-ups: drop the per-request INFO log, compute the prompt hash chain in Rust, and batch submits.

@github-actions

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every eligible PR before approval:

  • ✅ Pre Checkin: Black, Ruff, catalog schema validation, non-GPU unit tests

Heavy model tests:

  • ✅ Gate checks are published on every PR so required checks do not stay missing
  • ✅ Expensive jobs run only after the PR is approved, or when a matching ci:* label is present
  • ✅ Pre Checkin must pass before approved heavy jobs continue
  • ✅ Without a matching label, expensive jobs also require a relevant path
  • ✅ A matching ci:* label is an explicit request and can open the gate even when paths would otherwise skip it

Path scope:

  • Native ATOM, vLLM, and SGLang use ignore lists: docs/markdown and unrelated plugin or Mesh paths are skipped
  • ATOMesh uses an include list: Mesh code, ATOMesh scripts/workflows/catalogs, OpenAI entrypoints, and Slurm helpers
  • Relevant path alone does not start expensive jobs; approval still opens the automatic path-scoped gate
Label Tests
ci:full Run all heavy PR model tests: native ATOM, vLLM, SGLang, and ATOMesh
ci:atom Run native ATOM model accuracy tests
ci:vllm Run ATOM vLLM OOT model accuracy tests
ci:sglang Run ATOM SGLang model accuracy tests
ci:mesh Run ATOMesh accuracy/benchmark gates for Mesh-related changes

Without a matching ci:* label, heavy jobs are skipped when the path is not relevant or the PR is not approved.
Add labels via the sidebar or gh pr edit 3698 --add-label <label>

@valar-cop valar-cop 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.

some changes needed..

ci Offline inference smoke test failed — not sure yet (low): The captured log is empty (0 bytes), so the failure cannot be attributed; the same job passes 7/7 on recent main runs.

(log file .valar/ci/job_137240356977.log is empty)
next: Re-run the job or fetch its console log; classify from the traceback before assuming the PR caused it. https://github.com/ROCm/ATOM/actions/runs/45032923199/job/137240356977

ci ATOM Test Gate failed — not sure yet (low): Log is empty; this gate already fails on main in 3 of the last 7 runs, so it looks like a pre-existing/flaky gate rather than this PR, but there is no log to confirm.

(log file .valar/ci/job_137242290687.log is empty)
same job on main: 2026-11-21T16:08 failure, 2026-11-20T16:09 failure, 2026-11-20T14:40 failure
next: Confirm from the upstream job it gates; if the smoke test is re-run green, this clears with it. https://github.com/ROCm/ATOM/actions/runs/45032923199/job/137242290687

@Yuechguo

Copy link
Copy Markdown
Contributor Author

some changes needed..

ci Offline inference smoke test failed — not sure yet (low): The captured log is empty (0 bytes), so the failure cannot be attributed; the same job passes 7/7 on recent main runs.

(log file .valar/ci/job_137240356977.log is empty)
next: Re-run the job or fetch its console log; classify from the traceback before assuming the PR caused it. https://github.com/ROCm/ATOM/actions/runs/45032923199/job/137240356977

ci ATOM Test Gate failed — not sure yet (low): Log is empty; this gate already fails on main in 3 of the last 7 runs, so it looks like a pre-existing/flaky gate rather than this PR, but there is no log to confirm.

(log file .valar/ci/job_137242290687.log is empty)
same job on main: 2026-11-21T16:08 failure, 2026-11-20T16:09 failure, 2026-11-20T14:40 failure
next: Confirm from the upstream job it gates; if the smoke test is re-run green, this clears with it. https://github.com/ROCm/ATOM/actions/runs/45032923199/job/137242290687

Re-run is green for both. The earlier failure was docker run exiting 125 at Start CI container (before any ATOM code ran); the gate failed only as a consequence. Not related to this PR.

@ZhangLirong-amd

Copy link
Copy Markdown
Collaborator

Session affinity does not reach CoreManager through the Rust frontend (at e2a327cfe).

TokenBridge.submit (token_bridge.py:244) passes dp_session_id=params.get("dp_session_id"), but nothing ever puts it into params:

  • BridgeRequest::params (py_bridge.rs:153) sets request_id, the sampling fields, stop, ignore_eos, data_parallel_rank and tool_choice_required only. dp_session appears nowhere under atom/mesh/.
  • dp_parent_session_id is not passed to preprocess_fanout at all.

What this breaks: with ATOM_DP_SESSION_AFFINITY=1, the OpenAI server takes the session from x-dynamo-session-id / x-session-id / x-correlation-id, plus x-dynamo-parent-session-id for the parent (_get_dp_session_affinity_ids, api_server.py:467). CoreManager's SessionPolicy (dp_routing/policies.py:62) routes only on seq.dp_session_id. Through this frontend the field is always None, so every request falls back to plain DP load balancing: an agentic session's turns land on different ranks, and its prefix cache is lost. The mesh router's own dp_sticky policy does not cover this, since the bridge has one worker and CoreManager places requests on DP ranks itself.

The removed Python standalone service did not read these headers either, so this is not a regression of this PR. But the description says DP routing "keeps working as it is", the read in submit is currently dead, and session affinity is the DP mode agentic benchmarks run with (and the baseline share_cache is measured against).

Suggested fix:

  • In the bridge's request handler, read the same three headers (and the parent header) as _get_dp_session_affinity_ids, gated on ATOM_DP_SESSION_AFFINITY. Put them into RequestExtras next to data_parallel_rank.
  • Set dp_session_id / dp_parent_session_id in BridgeRequest::params, and pass dp_parent_session_id through TokenBridge.submit.
  • Add a test that a request with x-session-id reaches preprocess_fanout with dp_session_id set.

If that is out of scope here, please drop the dead dp_session_id read and list session affinity under "Known differences" in docs/atomesh_rust_frontend.md.

@ZhangLirong-amd

Copy link
Copy Markdown
Collaborator

Two more, smaller than the session-affinity one (at e2a327cfe):

1. The prompt's block-hash chain is computed twice on Python-rendered models (DeepSeek-V4 / V4.1, Kimi-K3), and the tokenizer cache's chain is thrown away.

  • TokenBridge.render_chat calls io_processor.encode_prompt(prompt). With ATOM_FRONTEND_PREFIX_HASH set, that runs segment_tokenizer.encode_with_prefix and returns a PrefixEncoding that carries block_hashes. render_chat keeps only token_ids (token_ids = getattr(encoded, "token_ids", encoded)).
  • Rust then submits those ids, so preprocess_fanout(token_ids, ...) has no PrefixEncoding, and ship_prompt_hash_chain (prefix_hash.py:80) rehashes the whole prompt with chained_block_hashes.
  • The cost is a second full hash of every prompt, inside the single-threaded submit section the PR names as the throughput cap. It also loses the incremental reuse the segment cache gives a multi-turn agentic session, the case share_cache / prefix_spread routing is for.
  • Suggested fix: keep the PrefixEncoding that render_chat built (e.g. by key until submit) and pass it to preprocess_fanout; or render without the prefix encoding and hash once there. For Jinja-rendered models the PR's follow-up ("compute the prompt hash chain in Rust") covers the same cost.

2. A failed StepSink.push drops a step's outputs for good.

  • TokenBridge._flush sets self._local.pending = None before self.sink.push(pending). If the push raises, CoreManager only logs flush_stream_batch failed and moves on.
  • That step's tokens, possibly including a finished, never reach Rust, so the affected streams never end.
  • Suggested fix: on a push failure, end those keys with an error (or fail_all) rather than dropping them silently.

@Yuechguo

Copy link
Copy Markdown
Contributor Author

Session affinity does not reach CoreManager through the Rust frontend (at e2a327cfe).

TokenBridge.submit (token_bridge.py:244) passes dp_session_id=params.get("dp_session_id"), but nothing ever puts it into params:

  • BridgeRequest::params (py_bridge.rs:153) sets request_id, the sampling fields, stop, ignore_eos, data_parallel_rank and tool_choice_required only. dp_session appears nowhere under atom/mesh/.
  • dp_parent_session_id is not passed to preprocess_fanout at all.

What this breaks: with ATOM_DP_SESSION_AFFINITY=1, the OpenAI server takes the session from x-dynamo-session-id / x-session-id / x-correlation-id, plus x-dynamo-parent-session-id for the parent (_get_dp_session_affinity_ids, api_server.py:467). CoreManager's SessionPolicy (dp_routing/policies.py:62) routes only on seq.dp_session_id. Through this frontend the field is always None, so every request falls back to plain DP load balancing: an agentic session's turns land on different ranks, and its prefix cache is lost. The mesh router's own dp_sticky policy does not cover this, since the bridge has one worker and CoreManager places requests on DP ranks itself.

The removed Python standalone service did not read these headers either, so this is not a regression of this PR. But the description says DP routing "keeps working as it is", the read in submit is currently dead, and session affinity is the DP mode agentic benchmarks run with (and the baseline share_cache is measured against).

Suggested fix:

  • In the bridge's request handler, read the same three headers (and the parent header) as _get_dp_session_affinity_ids, gated on ATOM_DP_SESSION_AFFINITY. Put them into RequestExtras next to data_parallel_rank.
  • Set dp_session_id / dp_parent_session_id in BridgeRequest::params, and pass dp_parent_session_id through TokenBridge.submit.
  • Add a test that a request with x-session-id reaches preprocess_fanout with dp_session_id set.

If that is out of scope here, please drop the dead dp_session_id read and list session affinity under "Known differences" in docs/atomesh_rust_frontend.md.

Thanks, fixed in 46539a7 as suggested. The router now reads x-dynamo-session-id / x-session-id / x-correlation-id and x-dynamo-parent-session-id in the OpenAI server's order (session_ids) into RequestExtras. BridgeRequest hands both ids to Python, and TokenBridge.submit passes dp_session_id and dp_parent_session_id to preprocess_fanout under ATOM_DP_SESSION_AFFINITY, the same switch _get_dp_session_affinity_ids checks. Tests: the header order on the Rust side, and that the ids reach preprocess_fanout only with the switch on (test_session_ids_reach_preprocess_only_with_session_affinity). Session affinity is now listed as supported in docs/atomesh_rust_frontend.md.

@Yuechguo

Yuechguo commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor Author

Two more, smaller than the session-affinity one (at e2a327cfe):

1. The prompt's block-hash chain is computed twice on Python-rendered models (DeepSeek-V4 / V4.1, Kimi-K3), and the tokenizer cache's chain is thrown away.

  • TokenBridge.render_chat calls io_processor.encode_prompt(prompt). With ATOM_FRONTEND_PREFIX_HASH set, that runs segment_tokenizer.encode_with_prefix and returns a PrefixEncoding that carries block_hashes. render_chat keeps only token_ids (token_ids = getattr(encoded, "token_ids", encoded)).
  • Rust then submits those ids, so preprocess_fanout(token_ids, ...) has no PrefixEncoding, and ship_prompt_hash_chain (prefix_hash.py:80) rehashes the whole prompt with chained_block_hashes.
  • The cost is a second full hash of every prompt, inside the single-threaded submit section the PR names as the throughput cap. It also loses the incremental reuse the segment cache gives a multi-turn agentic session, the case share_cache / prefix_spread routing is for.
  • Suggested fix: keep the PrefixEncoding that render_chat built (e.g. by key until submit) and pass it to preprocess_fanout; or render without the prefix encoding and hash once there. For Jinja-rendered models the PR's follow-up ("compute the prompt hash chain in Rust") covers the same cost.

2. A failed StepSink.push drops a step's outputs for good.

  • TokenBridge._flush sets self._local.pending = None before self.sink.push(pending). If the push raises, CoreManager only logs flush_stream_batch failed and moves on.
  • That step's tokens, possibly including a finished, never reach Rust, so the affected streams never end.
  • Suggested fix: on a push failure, end those keys with an error (or fail_all) rather than dropping them silently.

Both fixed in 986141e.

  1. render_chat now keeps the PrefixEncoding encode_prompt built under a handle. The router carries the handle in RequestExtras to the submit, and submit hands the encoding to preprocess_fanout when its ids match the submitted ones, so the tokenizer cache's chain is reused and the prompt is hashed once (about 0.5 ms saved per 8k-token prompt inside the submit section). An entry a refused request never collects is dropped after 30 s or beyond 1024 entries. Tests: test_the_encoding_render_chat_built_reaches_preprocessing_once, test_without_a_matching_encoding_the_ids_go_as_they_are, test_uncollected_encodings_are_bounded_by_count_and_age.
  2. A failed StepSink.push now ends those keys' streams with an error (new StepSink.fail) and aborts their sequences in the engine, guarded against re-entry. Test: test_a_step_rust_could_not_take_ends_its_requests_with_an_error.

Yuechguo pushed a commit that referenced this pull request Nov 23, 2026
… of a lost step

Two from the #3698 review:

- render_chat kept only the token ids of the PrefixEncoding
  io_processor.encode_prompt built, so the tokenizer cache's block-hash
  chain (extended turn by turn in a session) was thrown away and
  preprocess_fanout hashed the whole prompt again, inside the
  single-threaded submit section (about 0.5 ms for an 8k-token prompt).
  render_chat now keeps the encoding under a handle, the router carries
  the handle in RequestExtras to the submit, and submit hands the
  encoding to preprocess_fanout when its ids are the ones submitted. An
  entry a refused request never collects goes after 30 s, or beyond 1024
  entries.
- _flush cleared a step's buffer before StepSink.push, and CoreManager
  only logs a failed flush, so a push that raised lost the step for good:
  a finish in it never reached Rust and the stream never ended. A failed
  push now ends those keys' streams with an error (StepSink.fail) and
  stops their sequences in the engine.
@ZhangLirong-amd

Copy link
Copy Markdown
Collaborator

Thanks, the three earlier fixes check out at 986141ea7. Session ids are read in route_inference, so chat, completions and generate all carry them, gated on ATOM_DP_SESSION_AFFINITY in Python. render_chat's PrefixEncoding reaches preprocess_fanout (both sides plain list[int]). A failed push fails its keys and aborts their sequences.

I went through the whole PR this time (Python bridge and server, atom_bridge/*, the shared prepare/render changes, the parsers, docs and tests), so this is the complete list from my side:

1. Kimi-K3 tool calls are no longer held to their schemas (medium; missing from "Known differences").

  • Since feat(api): hold Kimi-K3 tool calls to their schemas with the structured-output grammar #3061 the OpenAI server compiles the K3 tool-call grammar by default for any chat with tools and no response_format (configure_tool_call_grammar → SamplingParams.structured_tool_format). That grammar is what stops K3 from copying an empty write {} call out of its history.
  • The bridge builds SamplingParams without it, so such a chat is accepted and sampled unconstrained, with no error.
  • The old Python standalone service did not apply it either, so this is not a regression of this PR. Please list it under "Known differences" (and in the P2 structured-output item), or refuse K3 chats with tools until the grammar is wired.

2. No parity check for output parsing on the agentic models (medium).

  • Tool-call and reasoning parsing now go through the mesh's Rust parsers (tool_parser/parsers/*, last synced on 09-21) and the new reasoning/kimi_k3.rs, instead of ATOM's Python parsers. The Python parsers have been hardened since, e.g. marker-less or malformed DSML invoke, and K3's skipped think channel ([Kimi-K3] Return the reply as content when the model skips its think channel #2910).
  • The prompt parity (13/13) and GSM8K checks exercise neither tool calls nor the reasoning split.
  • Please feed recorded raw outputs of DeepSeek-V4.1-Flash and Kimi-K3 through both sides and compare content, reasoning_content and tool_calls. Cover normal, multiple and malformed calls, an unclosed think and a skipped think channel.

3. The shared gRPC chat path changes too, not only this backend (medium).

  • prepare_chat_with now sets prompt_opener for every chat it renders itself (response_context::prompt_opener: the prompt ends with <think>).
  • chat_aggregator::split_reasoning and chat_streaming::process_reasoning_stream then feed that <think> to the reasoning parser before the reply. That includes the existing gRPC router's chats, for any reasoning parser.
  • For a parser that already starts inside reasoning (e.g. deepseek_r1), the opener arrives on top of that state. The description says only this backend's usage changes, and the gRPC tests only add the field.
  • Please either add gRPC tests showing unchanged output for a parser that starts in reasoning and one that does not, or set the opener only on this router's path.

4. P/D requests are silently served as plain requests.

  • Neither BridgeRequest nor TokenBridge.submit carries kv_transfer_params, and nothing refuses a body that has it. A prefill or decode request through this frontend is therefore answered without the transfer, and the P/D router later fails with prefill_missing_kv_transfer_params, or the decode side recomputes.
  • The doc's comparison table says P/D is "unchanged", while P4 lists kv_transfer_params as not done.
  • Please refuse a body carrying kv_transfer_params with a 400, as images are refused, list it under "Known differences", and correct the table.

5. --frontend python / --frontend rust do not exist. structured_output_refused tells clients to "use --frontend python", and atom_bridge/mod.rs / app_context.rs say it starts with --frontend rust. server.py has no such flag, and the Python frontend in atomesh is removed. Please point the message at the OpenAI server (USE_ATOMESH_ENTRYPOINTS=0) and fix the two doc comments.

6. Jinja-rendered prompts are not checked token for token (low). Prompt parity covers only Python-rendered models. Please run atom_token_parity.py (#3596) on one Jinja model (Qwen3 or DeepSeek-R1) with tools and multi-turn messages.

7. The chat GSM8K row has no baseline (low). Please add the same-build /v1/chat/completions numbers from the OpenAI server next to 0.8704 / 0.6748.

Everything else I checked looks right:

  • Per-step deltas.
  • The finish-reason mapping.
  • Abort on disconnect on both sides of the submit.
  • n > 1 completes in index order.
  • add_request does not block under _engine_lock.
  • No middleware injects x-correlation-id into requests.
  • The sampling defaults match the chat/completions endpoints.
  • The endpoint coverage is a superset of the old router's.

Yuechguo pushed a commit that referenced this pull request Nov 23, 2026
…asoning start

From the #3698 review:

- With ATOM_TOOL_CALL_GRAMMAR (and the structured-output extras) the
  OpenAI server holds a Kimi-K3 chat's tool calls to their schemas
  (configure_tool_call_grammar); the bridge has no such grammar, so the
  chat was sampled unconstrained. render_chat now refuses it with a 400,
  deciding as the server does (tool_call_grammar_format); a format with no
  grammar, the switch off, or tool_choice "none" is served as before. The
  grammar itself comes with structured output (P2).
- A P/D request was served as a plain one: kv_transfer_params (and
  /generate's bootstrap fields) were dropped. Both are refused with a 400
  until P4.
- prepare_chat_with read a prompt's `<think>` opener for every chat the
  router renders, so the shared gRPC chat path fed it to its reasoning
  parsers too. Only a Pipeline built reading_prompt_opener (the ATOM
  bridge's) reads it now; gRPC keeps its parsers' own start.
- The refusal message and two doc comments named a --frontend flag that no
  longer exists; they point at the OpenAI server (USE_ATOMESH_ENTRYPOINTS=0).

docs/atomesh_rust_frontend.md lists the K3 tool-call and P/D refusals as
known differences and corrects the comparison table, which called P/D
unchanged.
@Yuechguo

Copy link
Copy Markdown
Contributor Author

Thanks, the three earlier fixes check out at 986141ea7. Session ids are read in route_inference, so chat, completions and generate all carry them, gated on ATOM_DP_SESSION_AFFINITY in Python. render_chat's PrefixEncoding reaches preprocess_fanout (both sides plain list[int]). A failed push fails its keys and aborts their sequences.

I went through the whole PR this time (Python bridge and server, atom_bridge/*, the shared prepare/render changes, the parsers, docs and tests), so this is the complete list from my side:

1. Kimi-K3 tool calls are no longer held to their schemas (medium; missing from "Known differences").

  • Since feat(api): hold Kimi-K3 tool calls to their schemas with the structured-output grammar #3061 the OpenAI server compiles the K3 tool-call grammar by default for any chat with tools and no response_format (configure_tool_call_grammar → SamplingParams.structured_tool_format). That grammar is what stops K3 from copying an empty write {} call out of its history.
  • The bridge builds SamplingParams without it, so such a chat is accepted and sampled unconstrained, with no error.
  • The old Python standalone service did not apply it either, so this is not a regression of this PR. Please list it under "Known differences" (and in the P2 structured-output item), or refuse K3 chats with tools until the grammar is wired.

2. No parity check for output parsing on the agentic models (medium).

  • Tool-call and reasoning parsing now go through the mesh's Rust parsers (tool_parser/parsers/*, last synced on 09-21) and the new reasoning/kimi_k3.rs, instead of ATOM's Python parsers. The Python parsers have been hardened since, e.g. marker-less or malformed DSML invoke, and K3's skipped think channel ([Kimi-K3] Return the reply as content when the model skips its think channel #2910).
  • The prompt parity (13/13) and GSM8K checks exercise neither tool calls nor the reasoning split.
  • Please feed recorded raw outputs of DeepSeek-V4.1-Flash and Kimi-K3 through both sides and compare content, reasoning_content and tool_calls. Cover normal, multiple and malformed calls, an unclosed think and a skipped think channel.

3. The shared gRPC chat path changes too, not only this backend (medium).

  • prepare_chat_with now sets prompt_opener for every chat it renders itself (response_context::prompt_opener: the prompt ends with <think>).
  • chat_aggregator::split_reasoning and chat_streaming::process_reasoning_stream then feed that <think> to the reasoning parser before the reply. That includes the existing gRPC router's chats, for any reasoning parser.
  • For a parser that already starts inside reasoning (e.g. deepseek_r1), the opener arrives on top of that state. The description says only this backend's usage changes, and the gRPC tests only add the field.
  • Please either add gRPC tests showing unchanged output for a parser that starts in reasoning and one that does not, or set the opener only on this router's path.

4. P/D requests are silently served as plain requests.

  • Neither BridgeRequest nor TokenBridge.submit carries kv_transfer_params, and nothing refuses a body that has it. A prefill or decode request through this frontend is therefore answered without the transfer, and the P/D router later fails with prefill_missing_kv_transfer_params, or the decode side recomputes.
  • The doc's comparison table says P/D is "unchanged", while P4 lists kv_transfer_params as not done.
  • Please refuse a body carrying kv_transfer_params with a 400, as images are refused, list it under "Known differences", and correct the table.

5. --frontend python / --frontend rust do not exist. structured_output_refused tells clients to "use --frontend python", and atom_bridge/mod.rs / app_context.rs say it starts with --frontend rust. server.py has no such flag, and the Python frontend in atomesh is removed. Please point the message at the OpenAI server (USE_ATOMESH_ENTRYPOINTS=0) and fix the two doc comments.

6. Jinja-rendered prompts are not checked token for token (low). Prompt parity covers only Python-rendered models. Please run atom_token_parity.py (#3596) on one Jinja model (Qwen3 or DeepSeek-R1) with tools and multi-turn messages.

7. The chat GSM8K row has no baseline (low). Please add the same-build /v1/chat/completions numbers from the OpenAI server next to 0.8704 / 0.6748.

Everything else I checked looks right:

  • Per-step deltas.
  • The finish-reason mapping.
  • Abort on disconnect on both sides of the submit.
  • n > 1 completes in index order.
  • add_request does not block under _engine_lock.
  • No middleware injects x-correlation-id into requests.
  • The sampling defaults match the chat/completions endpoints.
  • The endpoint coverage is a superset of the old router's.

Thanks for the full pass. Fixed in d96ac0a, with a cleanup on top in de21d23:

  1. Kimi-K3 tool calls. A chat whose tool calls the OpenAI server would hold to their schemas is now refused with a 400 rather than sampled unconstrained. The decision is made the way the server makes it: tool_call_grammar_format is called on every declared tool (request_tools, so K3's in-message tools count too), the tool_choice, and whether the prompt opened the think channel. A format with no grammar, tool_choice: "none", or a schema the server would leave unconstrained is served as before. One note: the grammar is opt-in (ATOM_TOOL_CALL_GRAMMAR defaults to 0, and the structured-output extras must be installed), so with the defaults K3 tool calls are still served. Wiring the grammar itself will come with structured output (P2); both "Known differences" and the P2 row say so.

  2. Output-parsing parity on the agentic models. Agreed, this is the gap that matters most. Next step: feed the same raw outputs of DeepSeek-V4.1-Flash and Kimi-K3 to both frontends — normal, multiple and malformed calls (including marker-less DSML), an unclosed think, and a skipped think channel as in [Kimi-K3] Return the reply as content when the model skips its think channel #2910 — and compare content, reasoning_content and tool_calls. I'll do this with a fake engine on CPU, since V4.1 on gfx942 needs the FP4PTPC checkpoint. Any differences will be fixed in the Rust parsers. Results to follow.

  3. Shared gRPC path. Only a Pipeline built with reading_prompt_opener() reads the prompt's opener now, and that is only this router's; gRPC routing keeps its parsers' own start. test_only_a_router_that_asks_reads_the_prompts_opener renders the same -ending prompt both ways: None on the gRPC path, on this router's.

  4. P/D. A body carrying kv_transfer_params is refused with a 400 on chat, completions and generate. So are /generate's bootstrap fields (pd_metadata), which were dropped the same way. Both are listed under "Known differences", and the comparison table no longer says P/D is unchanged.

  5. --frontend. The structured-output refusal now points at the OpenAI server (USE_ATOMESH_ENTRYPOINTS=0), and both doc comments are fixed. No mention of the flag is left.

  6. Jinja prompt parity. Will run on Qwen3 with tools and multi-turn messages, against the OpenAI server's render, and post the result here.

  7. Chat GSM8K baseline. Will add the same-build /v1/chat/completions numbers from the OpenAI server next to 0.8704 / 0.6748.

Also from de21d23: BridgeRequest now carries the request's extras instead of copying five fields; RequestExtras::read takes them in one pass, session headers included; and /generate's data_parallel_rank is now checked like the other endpoints'.

yuechguo added 14 commits November 23, 2026 14:33
The mesh router serves ATOM standalone's OpenAI API: Rust renders the chat
template, tokenizes, detokenizes, runs the reasoning and tool parsers and
writes the SSE; Python takes the prompt's token ids into
LLMEngine.io_processor and CoreManager as the OpenAI server does, and hands
each engine step back in one push. LLMEngine, CoreManager and the
EngineCores are unchanged.

- token_bridge.py: TokenBridge (submit, abort, is_healthy, the per-step
  flush), with the OpenAI server's admission (defaults, the deployment's
  output cap, a defaulted max_tokens shrunk to the context left, the
  context and pool checks).
- routers/atom_bridge: AtomBridgeRouter over the gRPC Pipeline with a
  one-engine planner and BridgeDispatcher injected; events.rs keeps the
  request-level parts (EventRegistry, SeqEventSource, Admission) free of
  Python; py_bridge.rs holds StepSink and what a request may carry.
- server.py: --frontend {python,rust}, python by default.

Refused with a 400 for now: n > 1, logprobs, stop_token_ids, a
constraining tool_choice, structured output, return_hidden_states.
… kwargs

The two the Python standalone service honours and the Rust frontend
dropped.

- data_parallel_rank: the typed chat and completion bodies have no field
  for it, so AtomBridgeRouter reads it off the raw body in route_inference
  (a generate body carries it typed), refuses one that is not a
  non-negative integer, and hands it to the dispatcher in a task-local
  around the request's pipeline. TokenBridge passes it to
  preprocess_fanout, and CoreManager checks it against the DP size.
- --default-chat-template-kwargs: launch_mesh takes it as JSON and the
  router merges it under each chat request's own chat_template_kwargs.
The router picks its tool-call and reasoning parsers by the served name,
which misses a model served under a path or a name of its own. ATOM
already reads both off the chat template (resolve_tool_call_parser,
resolve_dialect); the launcher now hands the router the same choice as
--tool-call-parser / --reasoning-parser, unless the launch named one.

- MESH_TOOL_CALL_PARSERS: ATOM's format names by the router's name for the
  same syntax (ATOM's XML `qwen` is the router's `qwen_xml`, `kimi` its
  `kimik2`); a --tool-call-parser in ATOM's vocabulary is translated too.
- The K3 channel dialect is `kimi_k3`; the `<think>` one is `qwen3`, which
  starts outside reasoning: a prompt that opened the block is read per
  request (next commit).
…-streamed replies

Ported from the atom_engine router's fix (e8d0ed0), for the Pipeline's
prepare and render, which the Rust frontend shares with gRPC routing:

- A template whose generation prompt opens <think> (DeepSeek-R1, GLM-5.x,
  Qwen3.5, DeepSeek-V4 with thinking on) leaves the reply inside
  reasoning, but the parser never sees an opener and returned the
  reasoning as content. prepare_chat now checks the rendered prompt per
  request, as api_server's prompt_starts_in_reasoning does
  (ResponseContext.prompt_opens_reasoning), and the render puts the
  opener before the reply, streamed or not. A parser already in reasoning
  strips the opener and stays there.
- A non-streamed chat over 64 KiB of text answered 500: the one-shot
  detect_and_parse_reasoning refuses text over the parser's
  max_buffer_size. A reply that long now goes through a fresh parser's
  streaming path a decoded piece at a time.
DeepSeek-V4's template is a Python message encoder and Kimi-K3's is the
tokenizer's own code: neither is Jinja, so the router cannot render them.
For such a model the Rust frontend now asks Python for the prompt and runs
the rest -- dispatch, detokenize, the parsers, the SSE -- itself.

- TokenBridge.renders_chat says so at launch (ChatRenderer: a custom
  message encoder, or a chat_template that is not a Jinja string), and
  render_chat renders a chat request as the Python standalone service
  does (apply_chat_template over the joined text parts, the request's
  chat_template_kwargs with the defaults under them), encodes it as the
  engine encodes a prompt, and names the channel opener the prompt ends
  on: the dialect's reasoning opener (`<think>`, K3's
  `<|open|>think<|sep|>`), or its answer opener (K3's response channel
  with thinking off).
- prepare_chat_with / Pipeline::execute_chat_with take that rendered
  prompt in place of the router's own render; prepare_chat is the same
  call without one.
- ResponseContext.prompt_opener (was prompt_opens_reasoning) carries the
  opener itself, so the reasoning parser reads the model's own, not
  always `<think>`.
The reasoning-parser crate mesh builds against (1.0.0) has no parser for
Kimi-K3's channels, so `--reasoning-parser kimi_k3` (which the ATOM
launcher now passes for a K3 model) found none and left the think channel
in the content.

src/reasoning registers the parsers that crate lacks into its factory;
kimi_k3 reads the channels as ATOM's Python server does
(kimi_k3_tokens.py, the channel dialect): the think channel is the
reasoning, the answer's framing (response / message markers) is dropped
from the content, and the tools section is left whole for the kimi_k3
tool parser. A think block the model never closed ends where the
response or tools channel opens. The prompt's own opener (think, or
response with thinking off) is fed first by the render.
The Python standalone service fans a request out to n siblings; the Rust
frontend refused it.

- TokenBridge.submit gives each sibling its own callback, tags each step
  output with the sibling's index, and returns how many sequences it made
  (n as the OpenAI server coerces it: greedy sampling collapses n to 1).
- SeqEventSource keeps each sibling's tokens and hands out their
  Completes in index order, so the chat, generate and completion renders
  give one choice per sibling. A sibling's finish no longer closes the
  request's event stream; the request ends when every sibling has. Only
  the first sibling reports the shared prompt, since the renders sum
  what each reports.
- Streaming with n > 1 is still refused: the streamed chat render writes
  one choice.
…st frontend

The router's render reads a reply to tool_choice "required" or a named
function as JSON, because a gRPC worker holds such a reply to the tool's
schema. ATOM's engine does not: the Python standalone service reads the
calls as the model writes them, and holds a "required" reply to the
format's tool-call channel where the format has one (Kimi-K3's).

The Rust frontend now does the same instead of refusing:

- route_chat reads "required", a named function and allowed_tools as
  "auto" for the render and prepare, so the model's own tool parser reads
  the calls and no JSON constraint is built;
- a string "required" with tools sets RequestExtras.tool_choice_required,
  and TokenBridge gives that request the required channel it derived at
  launch (resolve_tool_call_parser + required_call_channel, with
  --tool-call-parser), as SamplingParams.required_channel.
ATOM standalone (USE_ATOMESH_ENTRYPOINTS=1) now serves the OpenAI API in
Rust down to LLMEngine (TokenBridge) and nothing else: --frontend goes,
and with it AtomStandaloneService (atom_standalone_service.py) and the
Rust router that forwarded each request to it (routers/atom_standalone.rs).

What the Python service did that the Rust frontend now does too: n > 1,
data_parallel_rank, the default chat template kwargs, tool_choice
"required" (the K3 channel), reasoning a prompt opened, and models whose
template is Python (DeepSeek-V4, Kimi-K3). What it did and the Rust
frontend refuses: streaming with n > 1 (docs/atomesh_rust_frontend.md
lists the differences).

Checked on Qwen3-30B-A3B, TP 1, GSM8K 3-shot through /v1/completions
against the Python service on the same build: 0.6876 / 0.8901
(flexible / strict) against 0.6808 / 0.8825.

- launch_mesh takes token_bridge (with served_model_name and
  default_chat_template_kwargs) and no standalone_service; mesh-only
  passes neither.
- The tests that read the Python service's source now read the token
  bridge's (ChatRenderer asks chat_template_source, not chat_template), and
  the required-channel one checks TokenBridge's sampling params.
The Python server's chat usage carries prompt_tokens_details.cached_tokens
and, not streamed, ttft_s / tpot_s / latency_s (num_choices past one).

- WorkerMeta.timing (SeqTiming): only the token bridge's source sets it,
  timing each sibling as api_server.py does -- from the dispatch to its
  first token, per output token after the first, and to its finish -- so
  the gRPC path's usage is unchanged.
- render/atom_usage.rs (from the atom_engine router's, 6eb6410) adds
  the fields: the first sibling's cache hit, the slowest sibling's times;
  the non-streamed chat render extends its response with them, the
  streamed one its usage chunk with the cache hit.

A completion's timing is not carried yet: its render is the generate one,
re-wrapped.
Two gaps for DeepSeek-V4.1 through the Rust frontend:

- `thinking` and `reasoning_effort` were ignored: the prompt always took
  the encoder's default mode. A model whose prompt ATOM renders now gets
  them as the OpenAI server's `_chat_completions` threads them through:
  resolve_reasoning_controls / apply_reasoning_controls with the
  encoder's own rules (V4.1's effort aliases, `none` switching thinking
  off, integer budgets through `thinking.effort`; an effort it refuses is
  a 400), plus a string `tool_choice` into the template kwargs. The typed
  chat body drops `thinking`, so RequestExtras reads it off the raw body,
  and the prompt is rendered before tool_choice is rewritten for the
  render. An encoder that joins a content list itself (V4.1's) now gets
  the list as sent.
- Image, video and audio content was dropped without a word: the engine
  is handed token ids only. It is refused with a 400 until multimodal
  input is carried.
ChatRenderer built the template's messages itself (text parts joined, a
few keys copied), which is not what the OpenAI server hands the encoder:
it reads the request into its ChatCompletionRequest, normalizes and
checks the tools, and renders ChatMessages through to_template_dict, with
the history tool-call arguments as sent where the template keeps or
needs them so (preserve_tool_call_arguments, decided at startup from the
tools probe).

render_chat now takes those same steps on the request as the router
serializes it. Checked token for token against `_chat_completions`'s
render on 13 requests (thinking on and off three ways, content lists,
tools with tool_choice auto and required, multi-turn tool calls with
reasoning_content): all match on DeepSeek-V4.1-Flash, DeepSeek-V4-Flash
and Kimi-K3.
The Rust frontend passed an engine reason it did not list through as
FinishReason::Other, so `stop_<token_id>` (any model with more than one
EOS ends a turn this way), `rejected`, `unschedulable: ...` or an empty
reason reached the client as a finish_reason OpenAI does not define, and
the render, which upgrades only `stop` to `tool_calls`, left a reply that
called a tool reporting the raw reason.

finish_reason now maps as the Python server's openai_stop_reason does: a
length cap is `length`, every other end is `stop`.
- tests/entrypoints/test_token_bridge.py: admission as the OpenAI
  server's (defaults, the deployment cap on a defaulted and an explicit
  max_tokens, greedy n, the required channel only when asked), the
  context and pool checks, submit with its routing fields, a step's
  outputs reaching Rust in one push, a finish cleaning up, abort of every
  sibling, and a refused submit leaving nothing behind.
- chat_aggregator: split_reasoning gives a reply over the one-shot limit
  the same split as a short one, and reads a prompt's opener first.

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

APPROVE @ bbfed13: my review's points are resolved, LGTM.

@valarLip this PR is large (42 files, about 3.4K lines each way); could you take a look as well?

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

⚠️ Action required before merge (1)

  1. Please split this PR into pieces of at most ~1000 changed lines each. At +3764/-3242 over 47 files, it is too large to review in one pass to the depth a change to the serving front end needs. Rounds on PRs this size keep turning up new findings and do not converge. A split along the PR's own seams would let each part be reviewed and merged on its own, for example:

    • the Rust frontend → LLMEngine path, with its tests;
    • removal of the Python standalone service, plus the launcher/CLI switch;
    • CI, docs and recipe updates.

    Stack the parts, or keep them independent where possible, and say in each description which earlier part it needs. I will review each part as it comes.


Not reviewed in depth at bbfed13: our policy is to ask for a split first when a PR we have not reviewed before is over ~1000 changed lines.

@Yuechguo

Copy link
Copy Markdown
Contributor Author

⚠️ Action required before merge (1)

  1. Please split this PR into pieces of at most ~1000 changed lines each. At +3764/-3242 over 47 files, it is too large to review in one pass to the depth a change to the serving front end needs. Rounds on PRs this size keep turning up new findings and do not converge. A split along the PR's own seams would let each part be reviewed and merged on its own, for example:

    • the Rust frontend → LLMEngine path, with its tests;
    • removal of the Python standalone service, plus the launcher/CLI switch;
    • CI, docs and recipe updates.

    Stack the parts, or keep them independent where possible, and say in each description which earlier part it needs. I will review each part as it comes.

Not reviewed in depth at bbfed13: our policy is to ask for a split first when a PR we have not reviewed before is over ~1000 changed lines.

I'd push back on splitting this one. The size reads larger than the change is, and the proposed seams would leave parts that can't run or be tested on their own.

What the +3764/-3242 actually is

Area Lines Note
Python main path (atom/model_engine, atom/entrypoints/openai, atom/config.py) 0 LLMEngine, CoreManager, EngineCore, scheduler and the OpenAI server are untouched
Old Python standalone service and its tests removed -2,621 One mechanical commit (76b6391: +125/-3280)
Python, new +624 in atom/entrypoints/atomesh/ Mostly token_bridge.py (~500), a thin adapter over the existing preprocess_fanout / add_request
Rust (mesh) +2,499/-613, of which ~560 are tests Almost all in the new routers/atom_bridge/ module, plus small hooks in the shared prepare/render
Docs +237 One new file
CI / recipes 0 Nothing to split out here

Net, the PR adds about 500 lines. The serving front end that matters for risk, the OpenAI server and everything below it, has no diff at all. What changes is the mesh, plus the switch that decides which front end standalone starts.

Why the suggested seams don't work

  1. There is no smaller unit that runs. The Rust frontend → LLMEngine path is one loop: the router, TokenBridge.submit, the per-step StepSink push, abort on disconnect, and the launcher that wires them together. Without the launcher, part 1 would be a router that nothing starts: dead code on main with no end-to-end coverage. Part 2 (launcher + removal) can't be reviewed or tested without part 1 underneath it. Neither part is mergeable on its own merits.
  2. The evidence covers the whole path, not the pieces. GSM8K against the old Python front end, prompt token parity on DeepSeek-V4.1 / V4 / Kimi-K3, the fake-engine throughput runs and today's GPU smoke were all run on the assembled path. A split resets that: each part would land unvalidated, and the validation would only be valid again once the last part is in.
  3. Two standalone front ends would coexist on main in between. An earlier revision kept both behind a --frontend switch, and review rightly flagged it: two paths to maintain, and a flag that drifted from what was documented. Splitting "add" from "remove" brings that intermediate state back, this time on main.
  4. The review has converged. The last rounds (ZhangLirong's seven items, valar-cop's, and Jasen's twelve) were all fixed and re-checked. Jasen's latest comment at bbfed13 reads "No blocking issues left". The findings were behavioural, not a symptom of size, and a split would restart those rounds on code that has already passed them.

What I can do instead

  • The branch is already one commit per feature (20 commits, each building and testing on its own). I'll add a review guide to the description: the commit order, what each one touches, and which ones are mechanical (the removal) and can be skimmed.
  • If an independent piece is still wanted, the only parts that stand alone without breaking the path are the Kimi-K3 reasoning parser (reasoning/kimi_k3.rs, ~200 lines) and the shared render fixes. I can move those out first if that helps. The bridge itself should stay one unit.
  • Everything not yet in scope is listed in docs/atomesh_rust_frontend.md and will come as separate PRs under ~1000 lines each: shared admission, P/D, structured output, /metrics.

@ZhangLirong-amd

Copy link
Copy Markdown
Collaborator

LGTM from my side at bbfed133b, with two open questions to close before merge:

  1. Jinja prompt parity: could you post the atom_token_parity.py result on a Jinja-rendered model (Qwen3, with tools and multi-turn messages) against the OpenAI server's render?
  2. Chat GSM8K baseline: could you add the same-build /v1/chat/completions GSM8K numbers from the OpenAI server next to the Rust frontend's 0.8704 / 0.6748?

@Yuechguo

Copy link
Copy Markdown
Contributor Author

LGTM from my side at bbfed133b, with two open questions to close before merge:

  1. Jinja prompt parity: could you post the atom_token_parity.py result on a Jinja-rendered model (Qwen3, with tools and multi-turn messages) against the OpenAI server's render?
  2. Chat GSM8K baseline: could you add the same-build /v1/chat/completions GSM8K numbers from the OpenAI server next to the Rust frontend's 0.8704 / 0.6748?

Thanks. Both are now run at bbfed13.

Jinja prompt parity. I ran atom_token_parity.py on Qwen3-30B-A3B with the built-in request set, then test_requests_tokenize_as_on_atom against it. All 19 requests are identical with both tokenizer backends, HuggingFace and fastokens. The set covers:

  • tools, with reasoning_effort and thinking switches;
  • tool-call history, with and without reasoning_content;
  • parallel tool calls;
  • multi-turn, plain, with drop_thinking: false, and with tool history;
  • special tokens and mixed scripts in the text;
  • a completion;
  • two ~2 MiB prompts (738,112 and 735,655 tokens).

The test renders through prepare::chat_template::process_chat_messages, which is the same render the bridge uses for a Jinja chat.

request tokens huggingface fastokens
plain 23 identical identical
tools_effort_high 154 identical identical
tool_history 190 identical identical
tool_history_reasoning 200 identical identical
parallel_tool_calls 216 identical identical
multi_turn 44 identical identical
multi_turn_keep_thinking 44 identical identical
multi_turn_tool_history 211 identical identical
scripts_and_special_text 46 identical identical
agentic_history_2mib 738112 identical identical
completion_2mib 735655 identical identical
(+ 8 reasoning-control variants and a completion, all identical)

Chat GSM8K, same build. Qwen3-30B-A3B, TP1, GSM8K 3-shot, num_concurrent=65. Both servers were built from bbfed13 and run side by side on two GPUs.

Endpoint Rust frontend (flexible / strict) OpenAI server (flexible / strict)
/v1/chat/completions 0.8613 / 0.6702 0.8673 / 0.6770
/v1/completions 0.6641 / 0.8848 0.6801 / 0.8840

All differences are within about one standard error (±0.009–0.013), with no retries or errors on either side. The earlier Rust chat number, 0.8704 / 0.6748, came from an older build; the ~0.01 between the two Rust runs is batching variance at this concurrency.

@Yuechguo
Yuechguo dismissed valarLip’s stale review November 24, 2026 02:53

All requested changes were addressed in bbfed13. The reviewer confirmed this ("No blocking issues left") and gave LGTM at that commit; the two follow-up questions are answered above.

@Yuechguo
Yuechguo merged commit 59444c3 into main Nov 24, 2026
124 of 135 checks passed
@Yuechguo
Yuechguo deleted the yuechguo/mesh-llmengine-bridge branch November 24, 2026 03:31
junyyang-amd added a commit that referenced this pull request Nov 24, 2026
#3698 launches the router with a token bridge in place of the standalone
service; mesh-only passes the server config alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
junyyang-amd added a commit that referenced this pull request Nov 24, 2026
#3698 replaced the Python standalone service, which #3413 extended, with a
Rust frontend that refuses images. The CI case was never served through it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Jasen2201 added a commit that referenced this pull request Nov 24, 2026
…omesh client

main moved the HTTP P/D router's idx2idx onto the planner's idx2idx (#3493)
and added the standalone backend's SeqTiming (#3698). The idx2idx change
goes into apply_atom_pd_rank_mapping_policy, which this branch moved to
core/placement/backend/atom.rs; one SeqTiming remains, main's ttft, tpot
and latency, which ATOM gRPC workers fill from their GenerateComplete.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
wanzhenchn added a commit that referenced this pull request Nov 24, 2026
ATOM standalone serving renders chats in the router since #3698, and
1.4.2 gives chat templates neither strftime_now nor raise_exception,
which transformers does, so every gpt-oss-120b chat is refused with
"value of type undefined is not callable (in chat:264)". 2.0.0 defines
both.

2.0.0 also renders DeepSeek-V4.1 checkpoints with its port of V4.1's
encoder, as it renders V3.2, so they are probed as rendering without
the template; a V4 checkpoint with a template of its own now renders
that template.

CacheConfig gains l0_max_memory, which keeps its default.
Jasen2201 added a commit that referenced this pull request Nov 24, 2026
…to discovery and P/D

main's prepare_chat_with takes a prompt rendered outside the router (#3698).
The template checks this branch adds run on prompts atomesh renders, through
prepare_chat_checked, which also hands the pipeline the template a prompt
rendered with for the placement check; a prompt rendered outside is checked
against no template.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Jasen2201 added a commit that referenced this pull request Nov 24, 2026
…f main into structured output and render

main's ATOM bridge (#3698) brought its own AtomOutput, prompt opener and
usage additions, from an earlier version of this branch's. This branch's
stand: the pipeline reads a placed ATOM worker's output as ATOM's, its
prepare renders ATOM's reasoning controls and message tools, and
atom_usage carries completions' timing too. main's bridge keeps its
entries: prepare_chat_with and execute_chat_with take a prompt rendered
outside the router, and a router that reads ATOM's output reads a
rendered-here prompt's <think> opener. One SeqTiming remains, main's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Yuechguo pushed a commit that referenced this pull request Nov 25, 2026
…oning controls as ATOM does (#3684)

* feat(mesh): encode the prompts of listed models with fastokens

--fastokens-models names the models, by the name or source their
tokenizer registers under, or `*`, whose prompts the router encodes with
fastokens 0.3.6 rather than HuggingFace `tokenizers`. Decoding, chat
templates and vocabulary lookups stay with the HuggingFace tokenizer.

A model encodes with fastokens only once fastokens encodes a set of
probe texts exactly as its HuggingFace tokenizer does, with special
tokens and without: added tokens, digits, whitespace, several scripts, a
chat and a 1 MiB text. The ids the HuggingFace post-processor puts
around a text are added to fastokens' own, so a tokenizer_config.json
that adds a BOS the tokenizer.json does not still gets it. Otherwise the
model keeps HuggingFace with a warning, or under --fastokens-strict its
tokenizer fails to register; mesh_fastokens_tokenizers_total{outcome}
counts tokenizers as loaded, fallback or refused. Tokens only
tokenizer_config.json declares encode as the tokens they declare, as in
transformers and so on the engine.

These models tokenize up to --fastokens-max-tokenize-bytes, /v1/tokenize
included: 64 MiB by default, or --prepare-max-tokenize-bytes if that is
larger. --fastokens-segment-cache-mb sizes fastokens' segment cache,
which takes the place of --tokenizer-cache-* for these models.

test_requests_tokenize_as_on_atom checks, with either backend, that the
DeepSeek-V4.1-Flash requests of tests/fixtures/atom_tokens tokenize for
routing as on ATOM, two prompts over 2 MiB among them, with the tokenizer
files of the revision recorded there, which it downloads.
scripts/atom_token_parity.py records the fixture, or another checkpoint's
requests, by sending them to ATOM's own chat and completion endpoints in
process, with an engine that keeps the prompt tokens it is given.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(mesh): check fastokens' ids for config-only tokens, and probe more

Tokens only tokenizer_config.json declares must have the ids
transformers gives them: the ones after the vocabulary's and the added
tokens', in the order of the ids they declare. fastokens gives them the
ids they declare, so a model whose tokens declare others is refused.
The probe texts leave those tokens out instead of being skipped where
they have one. The chat probe renders without a system message for a
template that has no system role, and a template that renders neither
is logged. A 256 KiB text with no newline makes fastokens search for
added tokens across its threads, which split a text only at newlines.

A --fastokens-strict refusal is what the probe found, so registering is
not retried. test_requests_tokenize_as_on_atom downloads, so it is
ignored by default and runs in a CI step of its own; a checkpoint may
have no config.json or chat_template.jinja. The help of the byte limits
fastokens models do not have names --fastokens-max-tokenize-bytes, and
the registration's docs and log say which tokenizers fastokens encodes.
A test checks that --fastokens-segment-cache-mb 0 turns the cache off,
and two tests the registration and ingress tests repeat are dropped.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(mesh): decode fastokens' config-only tokens, and retry downloads

A tokenizer.json fastokens cannot find or download says nothing of how
it encodes, so under --fastokens-strict the registration fails and is
retried, not refused, and without it the model keeps HuggingFace with a
warning that says so. Only what fastokens' probe finds is a refusal.

HuggingFace tokenizers does not have the tokens only
tokenizer_config.json declares and dropped their ids when decoding, so
/v1/detokenize lost the text /v1/tokenize encoded as them. fastokens
now looks them up and decodes the ids that include them, at once and
token by token, and a model with such tokens must also decode the probe
texts as HuggingFace does, keeping special tokens and skipping them. A
model with a normalizer and such a token that is not special and does
not say whether it is normalized is refused: transformers takes it as
normalized, fastokens as not.

The tokenization byte limits resolve once, as the app context is built.
The help and docs say fastokens models have the larger of 64 MiB and the
other models' limit, which falls back to --ext-proc-max-tokenize-bytes;
the fastokens options are under the Tokenizer heading, and the
--tokenizer-cache-* help says it is for the models fastokens does not
encode. A test sends a fastokens prompt over its own limit, one sets
FASTOKENS_SEGMENT_CACHE where --fastokens-segment-cache-mb 0 turns the
cache off, the parity test's downloads time out, and the recorder stores
a checkpoint path absolute. The unreachable set_chat_template is gone.

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(mesh): render DeepSeek-V4.1 chats under ATOM's reasoning controls

The router renders the chats it tokenizes by passing the request's
reasoning_effort and chat_template_kwargs straight to the template. ATOM
renders DeepSeek-V4.1 chats under the model's own rules instead, so for
most reasoning controls the router's prompt, and the tokens prefix_hash
and cache_aware with --kv-events route by, were not the engine's: a
minimal, medium, xhigh or none effort, a disabled thinking, a
thinking.effort budget, and content sent as text blocks.

A tokenizer whose config.json has model_type deepseek_v41 now registers with
those rules, and the router renders its chats as ATOM's _check_chat and
V4.1 encoder adapter do:

- thinking, which the typed request does not keep, is read from the body as
  sent. thinking, reasoning_effort and chat_template_kwargs resolve as in
  reasoning_controls under V4.1's rules, and prepare_kwargs maps the effort
  aliases and takes a none effort as chat mode.
- Only the kwargs V4.1's encode_messages takes reach the template, and
  message content keeps its text blocks, which the template joins with blank
  lines as the encoder does.
- add_default_bos_token false drops the BOS. A chat after a context kwarg,
  which the template does not render, is 501 token_routing_unsupported, and
  controls ATOM refuses are 400.

The token parity fixture gets the 10 requests that tokenized otherwise
than on ATOM before, and all 29 now tokenize as on ATOM with both
HuggingFace and fastokens.

Co-authored-by: Cursor <cursoragent@cursor.com>

* test(mesh): check token parity against ATOM in CI, not a recorded fixture

The token parity step now has ATOM tokenize the requests in the job, with this
commit's code: it installs ATOM and a CPU torch in a venv, and
atom_token_parity.py downloads a DeepSeek-V4.1-Flash revision's tokenizer files
and chat encoder from HuggingFace and writes ATOM's tokens, which the test
compares the router's with. A change to ATOM's rendering and one to the
router's are checked together, where a fixture recorded from another ATOM
could go stale. The fixture and the test's own download are gone.

The script takes a HuggingFace repo@revision for the checkpoint and downloads
its tokenizer files and the chat encoder some models ship, which ATOM renders
DeepSeek-V4.1's chats with. The test reads $ATOM_TOKEN_PARITY only, and takes
the median of 5 encodes of every prompt.

* perf(mesh): turn fastokens' segment cache on by default

An agent re-sends its history with every request, and fastokens encodes
the text between special tokens one segment after another on the calling
thread, so without its segment cache the router encodes the whole history
again on every turn. The cache keeps the ids of those segments, checked
against their text on every hit, so a turn encodes little more than its
newest segments.

--fastokens-segment-cache-mb now defaults to 1024 MiB per tokenizer, which
the cache grows into as it fills; 0 turns it off. The token parity test
turns it off, as its timed encodes repeat a prompt.

* refactor(mesh): load fastokens from tokenizer.json alone

fastokens' `from_file` also adds the tokens only `tokenizer_config.json`
declares, which HuggingFace `tokenizers` encodes as text. Giving them the ids
`transformers` gives took an id check, a normalization check, a decode check
and a decode path through fastokens. Of 54 local checkpoints, only Qwen3.5
declares such tokens (7 audio and TTS tokens), and main's HuggingFace tokenizer
encodes them as text too.

Loading `tokenizer.json` alone keeps fastokens' tokens HuggingFace's, so
decoding and lookups stay with HuggingFace and the probe only compares
encodings. fast_tokenizer.rs goes from 944 to 664 lines.

* docs(mesh): fastokens' segment cache is on by default

* fix(mesh): retry a registration whose tokenizer cannot be downloaded for chat controls

* fix(mesh): take DeepSeek-V4.1 reasoning efforts as ATOM does

Keep the HTTP change small, as Jasen2201 asked: over HTTP, ATOM renders
the chat again, so the router's tokens only pick a worker. V4.1's full
reasoning controls (c872a6d) wait for the ATOM gRPC stack, whose
prepare path runs the router's tokens.

HTTP routing renders a chat it tokenizes with the request's effort as
sent. V4.1's template rejects `minimal`, `xhigh` and `none`, which
ATOM's V4.1 encoder accepts, so `prefix_hash` refused those chats with
400, and it renders `medium` with a smaller budget than the `high` ATOM
takes it as. For a checkpoint whose config.json has `model_type`
`deepseek_v41`, the router now takes the effort as the encoder does:
`minimal` as `low`, `medium` and `xhigh` as `high`, and `none` as chat
mode.

Back to main's rendering: `thinking` as sent (`SentControls`), the
kwargs filter, text blocks, `add_default_bos_token` and `context`.

* build(mesh): upgrade llm-tokenizer to 2.0.0

ATOM standalone serving renders chats in the router since #3698, and
1.4.2 gives chat templates neither strftime_now nor raise_exception,
which transformers does, so every gpt-oss-120b chat is refused with
"value of type undefined is not callable (in chat:264)". 2.0.0 defines
both.

2.0.0 also renders DeepSeek-V4.1 checkpoints with its port of V4.1's
encoder, as it renders V3.2, so they are probed as rendering without
the template; a V4 checkpoint with a template of its own now renders
that template.

CacheConfig gains l0_max_memory, which keeps its default.

* test(mesh): render templates that call strftime_now and raise_exception

A toy template in gpt-oss's style, checked against transformers 5.16.1.
On 1.4.2 it fails with "unknown function: strftime_now is unknown".

* fix(mesh): give llm-tokenizer's DeepSeek-V4.1 port ATOM's mode

llm-tokenizer 2.0.0 renders DeepSeek-V4.1 checkpoints with its port of
V4.1's encoder, which reads the mode from `thinking` alone. The V4.1
controls now give it the mode as ATOM's encoder takes it: from
`thinking_mode`, or chat mode where `enable_thinking` is false. A model
with controls is therefore no longer recorded among those whose chats
HTTP routing does not tokenize; the probe only warns that
`--chat-template` does not apply to it.

test_requests_tokenize_as_on_atom: 24 of 25 DeepSeek-V4.1-Flash chats
tokenize as on ATOM, and the other is rejected as on ATOM.

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
zhuyuhua-v pushed a commit that referenced this pull request Nov 26, 2026
* feat(mesh): count in-flight prefill tokens per worker (url@rank)

Each worker now carries a prefill-token counter next to its request count:
the prompt tokens placed on it whose prefill has not finished, exported as
mesh_worker_prefill_tokens{worker}. DP-aware workers keep one per rank.

The planner charges the prompt's tokens, when the router has them, to the
worker that prefills it, and the load guard holds the charge until the
prefill is done:

- P/D: on the prefill worker's guard, released when the prefill response
  completes. Under idx2idx it follows the remapped prefill rank; the idx2idx
  reservation test carries a nonzero charge and checks where it lands.
- Regular HTTP, streaming: until the response's first frame.
- Regular HTTP, non-streaming: not charged, since its first frame arrives
  only after decoding.

ext-proc single-worker and gRPC placements do not charge yet. A release
larger than the charge saturates at zero and logs a warning.

Ported from #3210 with its review addressed: non-streaming requests are not
charged, with a test, and the charge lives on WorkerLoadGuard rather than a
public PrefillTokenGuard.

Co-authored-by: Jasen2201 <yajizhan@amd.com>

* fix(mesh): assert the prefill release on P/D cancel and error paths

- The cancel and stalled error-body P/D tests check the prefill charge is
  taken and released, not only the request load.
- WorkerLoadGuard::with_prefill_tokens debug-asserts a fresh guard
  instead of releasing a charge no caller has.
- The mesh_worker_prefill_tokens help names the paths that charge it.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(mesh): charge no prefill tokens on the atom_local plan

main's LocalPlanner (#3698) builds a PlacementPlan::Single without
prefill_tokens. The gRPC pipeline it feeds builds its load guards
without the count, so 0 changes nothing.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Jasen2201 <yajizhan@amd.com>
Co-authored-by: mengqing.cao@amd.com <mengqing.cao@amd.com@pit2-vm-amd-xl-02.amd.pit2.tensorwave.lan>
Co-authored-by: Cursor <cursoragent@cursor.com>
zhuyuhua-v pushed a commit that referenced this pull request Nov 26, 2026
… selection (#3407)

* feat(mesh): key routing by image identity and log one routing decision per selection

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(engine): multimodal PD through the chat path

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* up-m1: move the vendored proto manifest out of the routing change (#136)

fix(mesh): drop the vendored proto manifest from up-m1

atom/mesh/proto/manifest.json fixes tests/proto_vendor_tests.rs, not image
routing, so it leaves this branch for its own upstream fix(mesh) change on
the fork's up-manifest branch (one commit on origin/main, the file
byte-identical to 5356d07's).

Closes #131.

* mesh: log the request's media count on Selected worker; one media predicate, one digested chat (#137)

mesh: log the request's media count on Selected worker; one media predicate, one digested chat

The sampled `Selected worker` route trace event (and `No worker selected`)
now carries `media_count`, set once at ingress, so every policy logs the
real count; the per-selection `routing decision` debug line and
`routing_key_hash` are gone. Chat media detection is one helper,
`media_parts`, shared by the count and `with_media_digests`.
`AtomAdapter::can_chunk_request` takes ingress's `carries_media` (through
`BackendAdapter::prepare_pair`) instead of rescanning the JSON. The
digested chat is built once and shared by routing metadata and
tokenization. Image routing keys are HTTP chat only: the gRPC descriptor
keeps `carries_media: false` and `media_count: 0`.

Closes #132.

* mesh: test that chat tokens differ by image URL, and run #3407's tests in CI (#140)

mesh: test that chat tokens differ by image URL, and run #3407's tests in CI

A new ingress test runs chats that differ only in an image URL through
IngressRouting's token path with Qwen2-VL's real chat template and asserts
different tokens, and identical tokens for the same URL. The KV-events step
of atomesh-mocker-benchmark.yaml now also filters on `core::placement` and
`observability::route_trace`, so upstream CI runs every test the image
routing change adds.

Closes #133.

* up-m1: key ATOM media chats by all their media at the routing prefix (#144)

mesh: key ATOM media chats by all their media at the routing prefix

ATOM's engine seeds a media request's whole block-hash chain from all its
media, so chats that share text but differ in images share no KV block.
Under `--backend atom`, the routing copy of a media chat now also carries
one digest of all its media, in order, at the front of the routing text
and of the templated prompt, so prefix_hash and cache_aware separate such
chats even when the image sits past the prefix window. In-place digests
stay; vLLM and SGLang routing is unchanged, and the forwarded body is
untouched.

Also: /generate's media_count counts the items nested image_data holds
([] and [[],[]] count 0), a PD-router test for an image_url chat through
ingress, and docstrings that say what each backend gets.

Closes #143.

* up-m1: say which blocks each backend keys by a prompt's media (#146)

mesh: say which blocks each backend keys by a prompt's media

The docstrings of ParsedInference::media_count and
CacheAwarePolicy::routed said every engine keys a whole prompt by its
media. That holds for ATOM only; vLLM and SGLang key the blocks from the
media part on. Both now say what each backend keys. Prose only.

Closes #145.

* PD image decode: MRoPE delta reaches decode positions, cache_seed gate, handoff key checks (#155)

fix(engine): image PD decode positions, cache_seed gate, handoff key checks

Answers valarLip's review on #3410:
- A decode leg's mrope_position_delta reaches the batch
  (ScheduledBatch.mrope_position_deltas keeps a seq without mrope_positions
  whose delta is nonzero), so MRoPE models decode at the right positions.
- A decode leg skips its media only when kv_transfer_params carries
  cache_seed; otherwise the media is preprocessed as before.
- cache_seed and mrope_position_delta in kv_transfer_params must be ints,
  else 400 before enqueue (check_media_handoff).
- Preemption reads Sequence.media_on_prefill_instance.
- generate_async_multimodal reads kv_transfer_params_output directly.

MiniMax-M3.1-Flash full MMStar through 1P1D scores 0.7305 against 0.7070
for the single instance at this head, 0 failed requests.

Closes #147.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(engine): image PD decode positions, cache_seed gate, handoff key checks

Answers the review on #3410:
- A decode leg's mrope_position_delta reaches the batch
  (ScheduledBatch.mrope_position_deltas keeps a seq without mrope_positions
  whose delta is nonzero), so MRoPE models decode at the right positions.
- A decode leg skips its media only when kv_transfer_params carries
  cache_seed; otherwise the media is preprocessed as before.
- cache_seed and mrope_position_delta in kv_transfer_params must be ints,
  else 400 before enqueue (check_media_handoff).
- Preemption reads Sequence.media_on_prefill_instance.
- generate_async_multimodal reads kv_transfer_params_output directly.

MiniMax-M3.1-Flash full MMStar through 1P1D scores 0.7305 against 0.7070
for the single instance at this commit, 0 failed requests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* style(tests): sort imports in test_pd_prompt_token_ids.py

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mesh: one media_count, prepare_pair unchanged, media count on the route trace, routing_tests in CI (#177)

mesh: simplify the media plumbing behind image routing keys

One field, media_count, with a carries_media() method on
InferenceMetadata and RequestDescriptor. prepare_pair keeps its
signature; prepare_pair_with_media defaults to it and only the ATOM
adapter overrides it. The planner sets media_count once on the
task-local route trace, so the trace functions keep their signatures.
The routing copy of a chat maps its messages instead of cloning the
request, media_parts yields (kind, url), and a routed chat counts its
media once. Test literals end in ..Default::default().

CI: the KV-events filter no longer repeats core::placement, and the
routing_tests target now runs.

Closes #165.

* up-m1: key the ATOM front digest by the chat up to its last media, plus detail (#178)

mesh: key the ATOM front digest by the chat up to its last media

ATOM's cache_seed hashes each image's token position and its decoded
pixels, not only its URL. Under --backend atom the front digest now
covers the chat with media digested in place, up to and including the
last media part, plus whether each image's detail is "low" (the only
setting that changes pixels). Different text before the same image, or
[a,b] vs [a,c], now get different keys; a later turn over the same
images keeps its key. vLLM and SGLang keys are unchanged. The docs say
what stays unmatched: DeepSeek-V4.1's per-token types, and an image
that changes behind an unchanged URL.

Closes #166.

* mesh-only: route to ATOM workers with --backend atom, and document it (#176)

mesh: launch_atomesh passes --backend atom; tokenizers survive served aliases

launch_atomesh (mesh-only) now passes --backend atom unless the command
line names a backend, so regular ATOM deployments get the ATOM routing
keys. With an OpenAI-compatible backend, discovery labels the
/v1/models card's id served_model_name and a non-empty root model_path:
an aliased ATOM worker (no root) loads its tokenizer from
--tokenizer-path / --model-path instead of fetching the alias, while a
vLLM worker's load path still beats the router-wide path.
served_model_name is the last tokenizer fallback. The README and the
--backend help say ATOM workers need --backend atom and how discovery
then names the model.

Closes #168. Closes #175.

* mesh: test that the ATOM media relay needs prefill's handoff (#179)

mesh: an ATOM media relay needs prefill's handoff, and says so

A media chat takes the response relay because decode needs prefill's
expanded prompt ids and cache_seed, which ATOM's prefill hands off once
#3410 lands. execute_atom_relay now treats a null
kv_transfer_params, which ATOM's prefill answers when it hands nothing
off, like a missing one: 502 prefill_missing_kv_transfer_params instead
of a 500 from enrich_decode_kv. The PD test's mock prefill answers an
image chat as #3410's does, and covers the null and absent cases.

Closes #167.

* tests: drop the duplicate conftest import the up-e1 sync merge left

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* up-e1: no local prefill of a media-dropped image decode leg; handoff keys checked on every endpoint (#181)

A chat decode leg whose prefill kept the image is no longer prefilled
locally (no KV connector, an offload resume, a moriio requeue, a tier load
declined after allocation): the scheduler finishes it as unschedulable.
`leaves_media_on_prefill` in `sequence.py` marks such a leg, and only it
reads `cache_seed` and `mrope_position_delta`.

Both keys are range-checked as a 400 on chat, completions, `/v1/messages`,
`/v1/responses` and the standalone service when `kv_transfer_params` is
set. The decode-position arithmetic moves to `token_layout/decode.py`
(`mrope_decode_positions`). `docs/api_image_input.md` describes the chat
image P/D contract, including that an offload-tier D refuses image decode
legs.

Closes #180.

* ci(mesh): keep the launch test out of the stdlib-only glob; run routing_tests serially

tests/entrypoints/test_atomesh_launch.py matched the Atomesh Benchmark
step `unittest discover -p "test_atomesh_*.py"`, which has no pytest;
it is renamed test_mesh_only_launch.py and still runs in the CPU suite.

The routing_tests step ran its server-spawning tests in parallel, and
test_power_of_two_prefers_less_loaded, which times 30 concurrent
requests against a slow worker, failed under that load. The step now
runs them one at a time, as the local gate does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci(mesh): skip the runner-only power-of-two load test instead of serializing routing_tests

test_power_of_two_prefers_less_loaded still failed on the GitHub-hosted
runner with the routing tests run one at a time, and passes with CI's
own command on MI355X hosts, so serializing fixed nothing. Run the
routing tests in parallel again and skip that one test in this step
until its cause is known.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Media-dropped leg test: main's connector interface and its early-load way in

The test's SimpleNamespace connectors lacked the scheduler capability
defaults main added (lookup_pending, supports_early_load); build them on
the shared KVConnectorSchedulerBase stub instead. Add main's early tier
load as a way in: the leg resumes from it and is refused there too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(mesh): pin the prepare pool in the power-of-two load test; run it in CI again

test_power_of_two_prefers_less_loaded sends 30 concurrent requests and
expects at least 25 to succeed, but the router's default preparation pool
scales with the host's CPUs: on a 4-CPU runner it is 2 threads and 20
queue slots, so exactly 8 requests got 503 prepare_queue_full. Reproduced
on pit2-p03-g24 under --cpus=4 (10 of 12 runs failed, always 22/30).
The test now fixes its pool at 2 threads and 64 slots, and the routing
tests run in CI without the skip.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* up-e1: no per-request cost on the text path; prompt-bounded MRoPE delta; DSpark and RapidServe refuse a media-dropped leg

- Sequence: media_on_prefill_instance is a class default, set only when a
  request carries kv_transfer_params; the scheduler's refusals and the HTTP
  and standalone handoff checks run only for a request with params.
- The engine intake refuses a handed-off mrope_position_delta outside
  [1 - prompt length, 0], refuses a media-dropped leg on RapidServe (whose
  prefill never reaches Scheduler.schedule), and tells the model's request
  validator about it: DeepSeek-V4.1 refuses DSpark on it.
- mrope_decode_positions is decode_positions plus the repeated deltas.
- The offload-tier D text is gone; the refusal's ways in are tested as they
  arise: a failed receive is new, the tier cases run on an offload-only
  instance.
- A fresh image leg waits for its remote KV; stale test and proto text fixed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(mesh): the fake runner takes main's launch_mesh keywords

#3698 launches the router with a token bridge in place of the standalone
service; mesh-only passes the server config alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
zhuyuhua-v pushed a commit that referenced this pull request Nov 27, 2026
…eddings (#3412)

* feat(mesh): key routing by image identity and log one routing decision per selection

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(engine): multimodal PD through the chat path

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(engine): image embedding transport over Mooncake

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(engine): encoder-only openai_server; prefill reads E's image embeddings

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* up-m1: move the vendored proto manifest out of the routing change (#136)

fix(mesh): drop the vendored proto manifest from up-m1

atom/mesh/proto/manifest.json fixes tests/proto_vendor_tests.rs, not image
routing, so it leaves this branch for its own upstream fix(mesh) change on
the fork's up-manifest branch (one commit on origin/main, the file
byte-identical to 5356d07's).

Closes #131.

* mesh: log the request's media count on Selected worker; one media predicate, one digested chat (#137)

mesh: log the request's media count on Selected worker; one media predicate, one digested chat

The sampled `Selected worker` route trace event (and `No worker selected`)
now carries `media_count`, set once at ingress, so every policy logs the
real count; the per-selection `routing decision` debug line and
`routing_key_hash` are gone. Chat media detection is one helper,
`media_parts`, shared by the count and `with_media_digests`.
`AtomAdapter::can_chunk_request` takes ingress's `carries_media` (through
`BackendAdapter::prepare_pair`) instead of rescanning the JSON. The
digested chat is built once and shared by routing metadata and
tokenization. Image routing keys are HTTP chat only: the gRPC descriptor
keeps `carries_media: false` and `media_count: 0`.

Closes #132.

* mesh: test that chat tokens differ by image URL, and run #3407's tests in CI (#140)

mesh: test that chat tokens differ by image URL, and run #3407's tests in CI

A new ingress test runs chats that differ only in an image URL through
IngressRouting's token path with Qwen2-VL's real chat template and asserts
different tokens, and identical tokens for the same URL. The KV-events step
of atomesh-mocker-benchmark.yaml now also filters on `core::placement` and
`observability::route_trace`, so upstream CI runs every test the image
routing change adds.

Closes #133.

* up-m1: key ATOM media chats by all their media at the routing prefix (#144)

mesh: key ATOM media chats by all their media at the routing prefix

ATOM's engine seeds a media request's whole block-hash chain from all its
media, so chats that share text but differ in images share no KV block.
Under `--backend atom`, the routing copy of a media chat now also carries
one digest of all its media, in order, at the front of the routing text
and of the templated prompt, so prefix_hash and cache_aware separate such
chats even when the image sits past the prefix window. In-place digests
stay; vLLM and SGLang routing is unchanged, and the forwarded body is
untouched.

Also: /generate's media_count counts the items nested image_data holds
([] and [[],[]] count 0), a PD-router test for an image_url chat through
ingress, and docstrings that say what each backend gets.

Closes #143.

* up-m1: say which blocks each backend keys by a prompt's media (#146)

mesh: say which blocks each backend keys by a prompt's media

The docstrings of ParsedInference::media_count and
CacheAwarePolicy::routed said every engine keys a whole prompt by its
media. That holds for ATOM only; vLLM and SGLang key the blocks from the
media part on. Both now say what each backend keys. Prose only.

Closes #145.

* PD image decode: MRoPE delta reaches decode positions, cache_seed gate, handoff key checks (#155)

fix(engine): image PD decode positions, cache_seed gate, handoff key checks

Answers valarLip's review on #3410:
- A decode leg's mrope_position_delta reaches the batch
  (ScheduledBatch.mrope_position_deltas keeps a seq without mrope_positions
  whose delta is nonzero), so MRoPE models decode at the right positions.
- A decode leg skips its media only when kv_transfer_params carries
  cache_seed; otherwise the media is preprocessed as before.
- cache_seed and mrope_position_delta in kv_transfer_params must be ints,
  else 400 before enqueue (check_media_handoff).
- Preemption reads Sequence.media_on_prefill_instance.
- generate_async_multimodal reads kv_transfer_params_output directly.

MiniMax-M3.1-Flash full MMStar through 1P1D scores 0.7305 against 0.7070
for the single instance at this head, 0 failed requests.

Closes #147.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(engine): image PD decode positions, cache_seed gate, handoff key checks

Answers the review on #3410:
- A decode leg's mrope_position_delta reaches the batch
  (ScheduledBatch.mrope_position_deltas keeps a seq without mrope_positions
  whose delta is nonzero), so MRoPE models decode at the right positions.
- A decode leg skips its media only when kv_transfer_params carries
  cache_seed; otherwise the media is preprocessed as before.
- cache_seed and mrope_position_delta in kv_transfer_params must be ints,
  else 400 before enqueue (check_media_handoff).
- Preemption reads Sequence.media_on_prefill_instance.
- generate_async_multimodal reads kv_transfer_params_output directly.

MiniMax-M3.1-Flash full MMStar through 1P1D scores 0.7305 against 0.7070
for the single instance at this commit, 0 failed requests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* style(tests): sort imports in test_pd_prompt_token_ids.py

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mesh: one media_count, prepare_pair unchanged, media count on the route trace, routing_tests in CI (#177)

mesh: simplify the media plumbing behind image routing keys

One field, media_count, with a carries_media() method on
InferenceMetadata and RequestDescriptor. prepare_pair keeps its
signature; prepare_pair_with_media defaults to it and only the ATOM
adapter overrides it. The planner sets media_count once on the
task-local route trace, so the trace functions keep their signatures.
The routing copy of a chat maps its messages instead of cloning the
request, media_parts yields (kind, url), and a routed chat counts its
media once. Test literals end in ..Default::default().

CI: the KV-events filter no longer repeats core::placement, and the
routing_tests target now runs.

Closes #165.

* up-m1: key the ATOM front digest by the chat up to its last media, plus detail (#178)

mesh: key the ATOM front digest by the chat up to its last media

ATOM's cache_seed hashes each image's token position and its decoded
pixels, not only its URL. Under --backend atom the front digest now
covers the chat with media digested in place, up to and including the
last media part, plus whether each image's detail is "low" (the only
setting that changes pixels). Different text before the same image, or
[a,b] vs [a,c], now get different keys; a later turn over the same
images keeps its key. vLLM and SGLang keys are unchanged. The docs say
what stays unmatched: DeepSeek-V4.1's per-token types, and an image
that changes behind an unchanged URL.

Closes #166.

* mesh-only: route to ATOM workers with --backend atom, and document it (#176)

mesh: launch_atomesh passes --backend atom; tokenizers survive served aliases

launch_atomesh (mesh-only) now passes --backend atom unless the command
line names a backend, so regular ATOM deployments get the ATOM routing
keys. With an OpenAI-compatible backend, discovery labels the
/v1/models card's id served_model_name and a non-empty root model_path:
an aliased ATOM worker (no root) loads its tokenizer from
--tokenizer-path / --model-path instead of fetching the alias, while a
vLLM worker's load path still beats the router-wide path.
served_model_name is the last tokenizer fallback. The README and the
--backend help say ATOM workers need --backend atom and how discovery
then names the model.

Closes #168. Closes #175.

* mesh: test that the ATOM media relay needs prefill's handoff (#179)

mesh: an ATOM media relay needs prefill's handoff, and says so

A media chat takes the response relay because decode needs prefill's
expanded prompt ids and cache_seed, which ATOM's prefill hands off once
#3410 lands. execute_atom_relay now treats a null
kv_transfer_params, which ATOM's prefill answers when it hands nothing
off, like a missing one: 502 prefill_missing_kv_transfer_params instead
of a 500 from enrich_decode_kv. The PD test's mock prefill answers an
image chat as #3410's does, and covers the null and absent cases.

Closes #167.

* tests: drop the duplicate conftest import the up-e1 sync merge left

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* up-e1: no local prefill of a media-dropped image decode leg; handoff keys checked on every endpoint (#181)

A chat decode leg whose prefill kept the image is no longer prefilled
locally (no KV connector, an offload resume, a moriio requeue, a tier load
declined after allocation): the scheduler finishes it as unschedulable.
`leaves_media_on_prefill` in `sequence.py` marks such a leg, and only it
reads `cache_seed` and `mrope_position_delta`.

Both keys are range-checked as a 400 on chat, completions, `/v1/messages`,
`/v1/responses` and the standalone service when `kv_transfer_params` is
set. The decode-position arithmetic moves to `token_layout/decode.py`
(`mrope_decode_positions`). `docs/api_image_input.md` describes the chat
image P/D contract, including that an offload-tier D refuses image decode
legs.

Closes #180.

* ci(mesh): keep the launch test out of the stdlib-only glob; run routing_tests serially

tests/entrypoints/test_atomesh_launch.py matched the Atomesh Benchmark
step `unittest discover -p "test_atomesh_*.py"`, which has no pytest;
it is renamed test_mesh_only_launch.py and still runs in the CPU suite.

The routing_tests step ran its server-spawning tests in parallel, and
test_power_of_two_prefers_less_loaded, which times 30 concurrent
requests against a slow worker, failed under that load. The step now
runs them one at a time, as the local gate does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci(mesh): skip the runner-only power-of-two load test instead of serializing routing_tests

test_power_of_two_prefers_less_loaded still failed on the GitHub-hosted
runner with the routing tests run one at a time, and passes with CI's
own command on MI355X hosts, so serializing fixed nothing. Run the
routing tests in parallel again and skip that one test in this step
until its cause is known.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Media-dropped leg test: main's connector interface and its early-load way in

The test's SimpleNamespace connectors lacked the scheduler capability
defaults main added (lookup_pending, supports_early_load); build them on
the shared KVConnectorSchedulerBase stub instead. Add main's early tier
load as a way in: the leg resumes from it and is refused there too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(mesh): pin the prepare pool in the power-of-two load test; run it in CI again

test_power_of_two_prefers_less_loaded sends 30 concurrent requests and
expects at least 25 to succeed, but the router's default preparation pool
scales with the host's CPUs: on a 4-CPU runner it is 2 threads and 20
queue slots, so exactly 8 requests got 503 prepare_queue_full. Reproduced
on pit2-p03-g24 under --cpus=4 (10 of 12 runs failed, always 22/30).
The test now fixes its pool at 2 threads and 64 slots, and the routing
tests run in CI without the skip.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* up-e1: no per-request cost on the text path; prompt-bounded MRoPE delta; DSpark and RapidServe refuse a media-dropped leg

- Sequence: media_on_prefill_instance is a class default, set only when a
  request carries kv_transfer_params; the scheduler's refusals and the HTTP
  and standalone handoff checks run only for a request with params.
- The engine intake refuses a handed-off mrope_position_delta outside
  [1 - prompt length, 0], refuses a media-dropped leg on RapidServe (whose
  prefill never reaches Scheduler.schedule), and tells the model's request
  validator about it: DeepSeek-V4.1 refuses DSpark on it.
- mrope_decode_positions is decode_positions plus the repeated deltas.
- The offload-tier D text is gone; the refusal's ways in are tested as they
  arise: a failed receive is new, the tier cases run on an offload-only
  instance.
- A fresh image leg waits for its remote KV; stale test and proto text fixed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ec_transport: carry dtype, sync only the writing stream, warn on matched rails

Review of #3411:
- ec_transfer_params carries the rows' dtype; P returns None and encodes
  itself when it would read them as another dtype.
- _place syncs only after giving up victims, and _sync waits on the current
  stream instead of the whole device.
- _open_engine warns that ATOM_MOONCAKE_MATCHED_RAILS is not honoured here.
- The module docstring states the one-thread-at-a-time contract.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(engine): P's ranks take E's image embeddings only when every read succeeded

Each P rank read E's rows and fell back to its own vision tower alone,
so one request could run on E's rows on some ranks and on the local
tower's on others. E's rows and a rank's own need not be bit-identical,
so the ranks' activations could diverge.

`ModelRunner.read_image_embeddings` now passes its verdict through
`group_agree` on the forward's TP group, then its PCP group (as
`agree_kv_budget` does), and every rank runs its tower when any read
failed. Every rank reaches the call for the same request at the same
point of the step, so the collective lines up.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(engine): encoder-only skips MiniMax LM names, grows P's reader, refuses engine routes

- VisionEncoder also skips `model.language_model.`: skipping matches
  checkpoint names before MiniMax-M3's weights_mapping renames them.
- EcReader starts at the first request's rows and grows, at least
  doubling, up to max_model_len rows; a failed grow falls back to the
  tower. A max_model_len buffer was 12 GiB per prefill rank at
  MiniMax-M3's 1M context, allocated past the KV cache's share.
- Under --encoder-only every route but chat, /v1/models, /health and
  /metrics answers 400 instead of a 500 from the absent engine.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(mesh): the fake runner takes main's launch_mesh keywords

#3698 launches the router with a token bridge in place of the standalone
service; mesh-only passes the server config alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(engine): image embedding transport over Mooncake

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ec_transport: carry dtype, sync only the writing stream, warn on matched rails

Review of #3411:
- ec_transfer_params carries the rows' dtype; P returns None and encodes
  itself when it would read them as another dtype.
- _place syncs only after giving up victims, and _sync waits on the current
  stream instead of the whole device.
- _open_engine warns that ATOM_MOONCAKE_MATCHED_RAILS is not honoured here.
- The module docstring states the one-thread-at-a-time contract.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ec_transfer: own interface, Mooncake as one backend

Review: keep the E->P embedding transfer out of the Mooncake KV connector.

- atom/ec_transfer/base.py: EcWriter.put(key, rows) -> handle and
  EcReader.get(handle, key, dtype) -> rows | None, with create_writer /
  create_reader by transport name. A handle carries "transport", "key",
  "rows" and "dtype"; a backend's own fields sit under its name.
- atom/ec_transfer/mooncake.py: the former kv_transfer/.../ec_transport.py
  (EcPool -> MooncakeEcWriter, EcReader -> MooncakeEcReader). It imports
  nothing from kv_transfer. The reader takes the server's kv_transfer_config
  ib_device / ib_enable_alternate_hca / ib_hca_count as the KV connector does.
- atom/utils/mooncake_hca.py: HCA selection and the TCP override, public and
  shared by the KV connector and the EC backend.
- get() rejects generation <= 0 and returns None on a malformed handle
  instead of raising inside P's forward.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* E/P/D: reach image embeddings through atom.ec_transfer

Review follow-up on top of #3411's interface.

- ModelRunner builds the reader for a handle's "transport" through
  create_reader on first use, passing this server's kv_transfer_config. A
  reader that cannot start (unknown transport, Mooncake missing, engine or
  memory failure) is recorded as None and the ranks run the vision tower,
  the same as a failed read; P on MoRI KV no longer needs Mooncake.
- The encoder-only server stores through create_writer("mooncake"); the API
  catches EcStoreFull.
- --accept-ec-transfer-params: P takes a chat request's ec_transfer_params
  only when started with it, and drops them otherwise (warning once). Only a
  router that runs E and strips client-sent params (ATOMesh) should face a P
  started with it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ec_transfer/mooncake: slot table, reader sync, logged fallbacks

Review round 4 on #3411.

- Each entry's generation, address and length live in a slot table at the
  front of E's registered region, never inside the pool, so a later entry's
  rows cannot land on them. The handle carries the slot's address; P reads
  the rows, then the slot, and takes the rows only if all three match.
  Slots run out like space does: evicted oldest-first past the lease, else
  EcStoreFull. A fourth field, ack, is written 0 and reserved for P to
  acknowledge a read.
- The reader synchronizes its buffer's stream before the NIC writes into
  it, so a queued zero fill or the previous read's clone cannot land after.
- Every read that returns None logs its reason and the running counts per
  reason (MooncakeEcReader.fallbacks). handle_matches becomes
  handle_mismatch, which returns the reason.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* encoder-only: builders on the model class, MiniMax-M3 only

Review on #3412 (jgong5):
- The vision modules come from the model class's encoder_only_modules,
  found through support_model_arch_dict, instead of a table of
  MiniMax-M3 and Kimi-K3 builders in atom/model_engine.
- Kimi-K3 is dropped: no test or GPU run covered it, and its
  packed_modules_mapping is set per instance while VisionEncoder takes the
  class attribute. --encoder-only refuses it.
- The ATOM Project Contributors header line on encoder_only.py and its test.
- A test that the reader syncs a grown buffer before the NIC writes it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* encoder-only: Kimi-K3 through its model class

KimiK3ForConditionalGeneration.encoder_only_modules builds vision_tower and
mm_projector with kimi_k3_vl.build_vision_modules; the vision_config check
moves into _vision_config, shared with __init__.

Checked on one MI355X with Kimi-K3.1-Pro: the --encoder-only server answers
three image requests (192, 414 and 256 rows) and refuses a text one, and its
rows equal, bit for bit, those of the vision modules loaded with
load_state_dict(strict=True) straight from the checkpoint.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ec_transfer/mooncake: slots follow the region; PCI topology moves to utils

Review round 5 on #3411.

- Slot count: one slot per 64 KiB of E's region (default_slots), so a
  1 GiB region holds 16384 entries, ~273 puts/s past a 60 s lease, and an
  image-sized entry (hundreds of KiB) runs out of space before slots. The
  table is carved from size_bytes, so the registration stays exactly the
  region E sized (whole GiB), as Mooncake's slice alignment needs.
- gpu_pci_bdf and rail_rdma_device move from
  kv_transfer/offload/mooncake_store/nic.py to atom/utils/pci_topology.py.
  nic.py, mooncake_hca, the P/D connector and the EC backend import them
  from there, so neither atom.utils nor atom.ec_transfer imports
  atom.kv_transfer; a test checks it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants