Repository navigation
[atomesh] Rust frontend down to LLMEngine, replacing the Python standalone service - #3698
Conversation
🏷️ CI GuideRuns automatically on every eligible PR before approval:
Heavy model tests:
Path scope:
|
valar-cop
left a comment
There was a problem hiding this comment.
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. |
|
Session affinity does not reach CoreManager through the Rust frontend (at
What this breaks: with 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 Suggested fix:
If that is out of scope here, please drop the dead |
|
Two more, smaller than the session-affinity one (at 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.
2. A failed
|
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. |
Both fixed in 986141e.
|
… 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.
|
Thanks, the three earlier fixes check out at I went through the whole PR this time (Python bridge and server, 1. Kimi-K3 tool calls are no longer held to their schemas (medium; missing from "Known differences").
2. No parity check for output parsing on the agentic models (medium).
3. The shared gRPC chat path changes too, not only this backend (medium).
4. P/D requests are silently served as plain requests.
5. 6. Jinja-rendered prompts are not checked token for token (low). Prompt parity covers only Python-rendered models. Please run 7. The chat GSM8K row has no baseline (low). Please add the same-build Everything else I checked looks right:
|
…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.
Thanks for the full pass. Fixed in d96ac0a, with a cleanup on top in de21d23:
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'. |
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.
valarLip
left a comment
There was a problem hiding this comment.
⚠️ Action required before merge (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 →
LLMEnginepath, 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.
- the Rust frontend →
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
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
What I can do instead
|
|
LGTM from my side at
|
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:
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 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.
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. |
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.
#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>
…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>
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.
…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>
…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>
…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>
* 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>
… 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>
…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>
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_fanoutandCoreManager.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,ncoerced as_coerce_n),abort,is_healthy, and a per-step flush through CoreManager's_flush_stream_batch_fnhook (oneStepSink.pushper output thread per step).ChatRendererrenders 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), includingthinking/reasoning_effortand a stringtool_choice.server.py: builds the bridge, and hands the router the tool-call / reasoning parsers ATOM reads off the model (--tool-call-parser/--reasoning-parserin the router's names), unless the launch named them.atom_standalone_service.pyand its tests are removed.Rust (
atom/mesh/src/)routers/atom_bridge/:AtomBridgeRouterover the gRPCPipelinewith a one-engine planner andBridgeDispatcherinjected;events.rsturns step events intoTokenChunks (siblings in index order, per-sequence timing, abort on client disconnect on either side of the submit);py_bridge.rsholdsStepSinkand the request checks.routers/atom_standalone.rsis removed.routers/prepareandrouters/render(shared with gRPC routing):prepare_chat_with/Pipeline::execute_chat_withtake a prompt rendered outside the router;ResponseContext.prompt_openerlets 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.rsadds 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 setsWorkerMeta.timing, so gRPC usage is unchanged).reasoning/kimi_k3.rs: a Kimi-K3 reasoning parser, whichreasoning-parser1.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_choicerequired/ named function (read by the model's own tool parser, as before;requireduses Kimi-K3'srequired_channel); DeepSeek-V4.1's reasoning controls.Known differences from the Python service (listed in
docs/atomesh_rust_frontend.md):n > 1, image / video / audio content, logprobs, structured output./v1/completionsrequiresmodelin the body.Test Plan
cargo test(mesh) andpytest tests/entrypoints tests/test_required_channel.py;black/ruff/cargo fmt./v1/completionsagainst the Python standalone service on the same build, and through/v1/chat/completions(thinking on).tool_choiceauto / required, multi-turn tool calls withreasoning_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.enable_thinking=false,n=2, streamedn=2refused,data_parallel_rank, image content refused, usage fields.core_mgr.add_request; both sides tokenize with llm-tokenizer 2.0.0.Test Result
cargo test: all pass.pytest: 3301 passed; the 3 failures intest_structured_output.pyfail onmainas well.GSM8K (Qwen3-30B-A3B):
/v1/completions/v1/completions/v1/chat/completionsPrompt parity: 13/13 identical on each of the three models.
All probes behave as listed above.
Frontend cost, 16 cores:
add_request, concurrency 1, 1k / 8k tokensBoth sides are capped by a single-threaded Python section; for Rust that is the
preprocess_fanout+add_requestpart ofTokenBridge.submit. Follow-ups: drop the per-request INFO log, compute the prompt hash chain in Rust, and batch submits.