Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
45 commits
Select commit Hold shift + click to select a range
a64797c
[ATOM gRPC] atomesh: the Session link to an ATOM instance
Jasen2201 Nov 21, 2026
be6bff5
[ATOM gRPC] atomesh: route ATOM requests over the Session (--atom-grp…
Jasen2201 Nov 21, 2026
c0a9d53
Merge the Generate review fixes (#3673) into atomesh Session routing
Jasen2201 Nov 22, 2026
6a2fa51
Merge Abort before submission (#3673) into atomesh Session routing
Jasen2201 Nov 22, 2026
5c947e4
Merge the chat-template and top_logprobs review fixes (#3673) into at…
Jasen2201 Nov 22, 2026
f009a78
Merge the stop-string review fixes (#3675) into the Session routes
Jasen2201 Nov 22, 2026
8ea9871
Merge the logprobs refusal (#3677) into the Session routes
Jasen2201 Nov 22, 2026
18367a4
Merge the step-flush ordering fix (#3673) into atomesh Session routing
Jasen2201 Nov 22, 2026
1ba90fa
Merge structured output and render (#3677) into routes over the Session
Jasen2201 Nov 22, 2026
5343238
Merge structured output and render (#3677) into routes over the Session
Jasen2201 Nov 23, 2026
6bbc2c5
Merge the Session link (#3678) into routes over the Session
Jasen2201 Nov 23, 2026
02ea667
Merge the Session link (#3678) into routes over the Session
Jasen2201 Nov 23, 2026
6e1fd33
tests: the Session test's AtomEngine leaves GetServerInfo's newer fie…
Jasen2201 Nov 23, 2026
3b88add
Merge the Session link (#3678) into routes over the Session
Jasen2201 Nov 23, 2026
d005687
Merge the Session link (#3678) into routes over the Session
Jasen2201 Nov 23, 2026
788972c
Merge the Session link (#3678) into routes over the Session
Jasen2201 Nov 23, 2026
96e9e1f
Merge the Session link (#3678) into routes over the Session
Jasen2201 Nov 23, 2026
c850f14
Merge main into atomesh routes over the Session
Jasen2201 Nov 23, 2026
cab6cec
Merge the atomesh Session link into atomesh routes over the Session
Jasen2201 Nov 23, 2026
7ffa84a
Merge the D and E fixes into atomesh routes over the Session
Jasen2201 Nov 23, 2026
0e6bc89
Merge the G fixes into atomesh routes over the Session
Jasen2201 Nov 23, 2026
f71c1c2
Merge the G fixes into atomesh routes over the Session
Jasen2201 Nov 23, 2026
230bf7d
Merge the Session link's headers and fixes into the routes over the S…
Jasen2201 Nov 23, 2026
de8e2d3
Merge the Session link's merged fixes into the routes over the Session
Jasen2201 Nov 23, 2026
28cad11
Merge the Session link's opening, buffer, release and timing fixes in…
Jasen2201 Nov 23, 2026
e625ec1
atomesh: the gRPC routers release a removed instance's Session
Jasen2201 Nov 23, 2026
4d024d1
atomesh: the Session's RequestSpec carries the request's session ids
Jasen2201 Nov 23, 2026
993883e
atomesh: RouterConfigBuilder sets atom_grpc_session
Jasen2201 Nov 23, 2026
f7da43b
Merge the Session link's merged F and E fixes into the routes over th…
Jasen2201 Nov 24, 2026
68fa138
Merge the Session link's merged readiness and greedy-n fixes into the…
Jasen2201 Nov 24, 2026
8db13b9
Merge the Session link's merged test-fixture fix into the routes over…
Jasen2201 Nov 24, 2026
e3f26c0
atomesh: routed Session chat tests record the worker template
Jasen2201 Nov 24, 2026
0d862ad
Merge the Session link's merged reasoning, kwargs, template and Sessi…
Jasen2201 Nov 24, 2026
6e9bd4a
Merge the Session link's unsent-prompt bound and merged fixes into th…
Jasen2201 Nov 24, 2026
4df7932
Merge the Session link's merged render and stamping fixes into the ro…
Jasen2201 Nov 24, 2026
11b3a5f
Merge the Session link's merged review fixes and merge of main into S…
Jasen2201 Nov 24, 2026
24938ee
Merge the Session link's merged tool-call fixes and template binding …
Jasen2201 Nov 24, 2026
03290b4
Merge the Session link's unsent-budget refusal and merged render and …
Jasen2201 Nov 24, 2026
38d9d8f
Merge the Session link's merged render and discovery fixes into Sessi…
Jasen2201 Nov 24, 2026
e1041c8
Merge the Session link's merged render and discovery fixes into Sessi…
Jasen2201 Nov 24, 2026
cf4a0c0
Merge the Session link's merges of structured output and render (temp…
Jasen2201 Nov 24, 2026
945279a
Merge the Session link's merge of the tokenizer handover on a last wo…
Jasen2201 Nov 24, 2026
3159fd0
Merge the Session link's reader shutdown, dropped-request ids and str…
Jasen2201 Nov 24, 2026
32850a6
Merge the engine's skip of a turned-off prefix chain store into the r…
Jasen2201 Nov 26, 2026
0f8bd2d
Merge main into the routes over the Session
Jasen2201 Nov 27, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions atom/mesh/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,26 @@ USE_ATOMESH_ENTRYPOINTS=1 python -m atom.entrypoints.openai_server mesh-only \
Supported reasoning parsers: `deepseek-r1`, `qwen3`, `qwen3-thinking`, `kimi`, `glm45`, `glm47`, `step3`, `minimax`.
Supported tool parsers: `json`, `python`, `xml`.

#### ATOM gRPC workers

An ATOM instance started with `--grpc-port` serves its own gRPC service,
`atom.grpc.v1.AtomEngine` (`atom/entrypoints/grpc/atom_grpc.proto`). atomesh detects it
without a runtime flag (probing SGLang, then vLLM, then ATOM) and reads its model,
tokenizer path, chat template, default template kwargs and reasoning markers from
GetModelInfo; with `--dp-aware`, its DP size from GetServerInfo.

```bash
python -m atom.entrypoints.openai_server --model <model> --server-port 8000 --grpc-port 31001
./target/release/atomesh launch --worker-urls grpc://worker1:31001
```

atomesh renders and tokenizes each chat and sends ATOM token ids, the stop strings as
token ids and the chat's structured-output fields; ATOM P/D pairs keep ATOM's relay or
chunked KV transfer. Image, video, audio and embedding input is refused for ATOM
workers, as is `/v1/responses`. Each request is one Generate call; with
`--atom-grpc-session`, every request to an instance shares one Session stream instead,
one message per engine step.

## Architecture

### Control plane
Expand Down
17 changes: 17 additions & 0 deletions atom/mesh/src/cliargs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -521,6 +521,11 @@ pub struct CliArgs {
#[arg(long, value_enum, default_value_t = Backend::Sglang, alias = "runtime", help_heading = "Backend")]
pub backend: Backend,

/// Send every request to an ATOM gRPC worker over one Session per instance,
/// rather than a Generate call per request
#[arg(long, default_value_t = false, help_heading = "Backend")]
pub atom_grpc_session: bool,

// ==================== Control Plane Authentication ====================
/// API key for worker connections
#[arg(long, help_heading = "Control Plane Authentication")]
Expand Down Expand Up @@ -724,6 +729,7 @@ impl CliArgs {
.kv_storage_weight(self.kv_storage_weight)
.retries(!self.disable_retries)
.circuit_breaker(!self.disable_circuit_breaker)
.atom_grpc_session(self.atom_grpc_session)
.build()
}

Expand Down Expand Up @@ -858,6 +864,16 @@ mod tests {
}
}

#[test]
fn atom_grpc_session_reaches_the_router_config() {
let session = |args: &[&str]| {
let args = CliArgs::try_parse_from(args).unwrap();
args.to_router_config(Vec::new()).unwrap().atom_grpc_session
};
assert!(!session(&["atomesh"]));
assert!(session(&["atomesh", "--atom-grpc-session"]));
}

#[test]
fn cli_kv_storage_options_map_to_router_config() {
let args = CliArgs::try_parse_from([
Expand Down Expand Up @@ -1057,6 +1073,7 @@ impl Default for CliArgs {
reasoning_parser: None,
tool_call_parser: None,
backend: Backend::Sglang,
atom_grpc_session: false,
api_key: None,
tls_cert_path: None,
tls_key_path: None,
Expand Down
17 changes: 17 additions & 0 deletions atom/mesh/src/config/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,12 @@ impl RouterConfigBuilder {
self
}

/// Sends every request to an ATOM gRPC worker over its instance's Session.
pub fn atom_grpc_session(mut self, enable: bool) -> Self {
self.config.atom_grpc_session = enable;
self
}

pub fn atom_pd_concurrent(mut self, enable: bool) -> Self {
self.config.atom_pd_concurrent = enable;
self
Expand Down Expand Up @@ -507,6 +513,17 @@ impl RouterConfig {
mod tests {
use super::*;

/// An embedder sends ATOM requests over the Session with the builder alone.
#[test]
fn test_atom_grpc_session_is_set_by_the_builder() {
let built = |enable| {
let builder = RouterConfigBuilder::new().regular_mode(Vec::new());
builder.atom_grpc_session(enable).build().unwrap()
};
assert!(built(true).atom_grpc_session);
assert!(!built(false).atom_grpc_session);
}

/// Test that .to_builder() round-trip conversion works correctly
#[test]
fn test_builder_from_existing_config() {
Expand Down
4 changes: 4 additions & 0 deletions atom/mesh/src/config/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,9 @@ pub struct RouterConfig {
pub atom_standalone: bool,
#[serde(default)]
pub atom_pd_rank_mapping_policy: AtomPdRankMappingPolicy,
/// Send every request to an ATOM gRPC worker over its instance's Session.
#[serde(default)]
pub atom_grpc_session: bool,
/// ATOM PD relay: open D's leg together with P's and send P's KV metadata
/// late (`--atom-pd-concurrent`; D needs `ATOM_PD_LATE_KV=1`).
#[serde(default)]
Expand Down Expand Up @@ -555,6 +558,7 @@ impl Default for RouterConfig {
connection_mode: ConnectionMode::Http,
atom_standalone: false,
atom_pd_rank_mapping_policy: AtomPdRankMappingPolicy::None,
atom_grpc_session: false,
atom_pd_concurrent: false,
model_path: None,
tokenizer_path: None,
Expand Down
103 changes: 95 additions & 8 deletions atom/mesh/src/routers/grpc/engine/atom/mod.rs
Original file line number Diff line number Diff line change
@@ -1,26 +1,103 @@
// SPDX-License-Identifier: MIT
// Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved.
// Copyright (c) 2026 ATOM Project Contributors
//! ATOM workers over `atom.grpc.v1`: the client, a payload as a GenerateRequest,
//! a Generate stream as `TokenChunk`s, ATOM's P/D flow for a pair, and the Session.
//! ATOM workers over `atom.grpc.v1`: the client, a payload as a GenerateRequest sent
//! on a Generate call or the Session, its stream as `TokenChunk`s, and ATOM's P/D flow.

pub(crate) mod pair;
pub(crate) mod request;
// No router sends requests over a Session yet; its tests do.
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) mod session;
pub(crate) mod stream;

use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;

use futures::Stream;
use http::StatusCode;
use tonic::{transport::Channel, Status, Streaming};

use self::session::AtomSessions;
use self::stream::http_error;
use crate::atom_engine::grpc::{
atom_engine_client::AtomEngineClient, Frames, GenerateRequest, GenerateResponse,
GetModelInfoRequest, GetModelInfoResponse, GetServerInfoRequest, GetServerInfoResponse,
HealthCheckRequest, HealthCheckResponse,
atom_engine_client::AtomEngineClient, prepare_structured_output_response::Response as Prepared,
Frames, GenerateRequest, GenerateResponse, GetModelInfoRequest, GetModelInfoResponse,
GetServerInfoRequest, GetServerInfoResponse, HealthCheckRequest, HealthCheckResponse,
PrepareStructuredOutputRequest, PrepareStructuredOutputResponse,
};
use crate::core::Worker;
use crate::routers::token_handle::engine_error::EngineError;

/// A request's messages from ATOM, as its Generate call sends them.
pub(crate) type Responses = Pin<Box<dyn Stream<Item = Result<GenerateResponse, Status>> + Send>>;

/// How each request reaches its ATOM instance: a Generate call of its own, or the
/// instance's Session (`--atom-grpc-session`).
#[derive(Clone, Default)]
pub(crate) enum AtomCalls {
#[default]
Generate,
Session(Arc<AtomSessions>),
}

impl AtomCalls {
/// Starts `request` on `worker`'s instance, which `client` reaches. Dropping the
/// stream before its last message ends the request at ATOM.
pub(crate) async fn start(
&self,
worker: &Arc<dyn Worker>,
client: &AtomClient,
request: GenerateRequest,
) -> Result<Responses, EngineError> {
match self {
Self::Generate => {
let call = client.generate(request).await;
Ok(Box::pin(call.map_err(EngineError::Transport)?))
}
Self::Session(sessions) => {
let request = prepare_structured_output(client, request).await?;
let stream = request.stream;
let (spec, prompt) = request::request_spec(request)?;
let submitted = sessions.submit(worker, spec, prompt, stream).await?;
Ok(Box::pin(submitted))
}
}
}
}

/// `request` with the fields ATOM's PrepareStructuredOutput derives from its chat's
/// StructuredOutput in its sampling; a request without one, as it is.
async fn prepare_structured_output(
client: &AtomClient,
mut request: GenerateRequest,
) -> Result<GenerateRequest, EngineError> {
let Some(structured_output) = request.structured_output.take() else {
return Ok(request);
};
let asked = PrepareStructuredOutputRequest {
structured_output: Some(structured_output),
sampling: request.sampling.clone(),
stop_token_sequences: request.stop_token_sequences.clone(),
kv_transfer_params_json: request.kv_transfer_params_json.clone(),
};
let answer = client.prepare_structured_output(asked).await;
let derived = match answer.map_err(EngineError::Transport)?.response {
Some(Prepared::Sampling(derived)) => derived,
Some(Prepared::Error(error)) => return Err(http_error(error)),
None => {
return Err(EngineError::Http {
status: StatusCode::INTERNAL_SERVER_ERROR,
message: "PrepareStructuredOutput answered neither sampling nor error".into(),
})
}
};
let sampling = request.sampling.get_or_insert_default();
sampling.required_channel = derived.required_channel;
sampling.json_schema = derived.json_schema;
sampling.structured_tool_format = derived.structured_tool_format;
sampling.structured_reasoning_end = derived.structured_reasoning_end;
Ok(request)
}

/// One ATOM instance's `AtomEngine` service.
#[derive(Clone)]
Expand Down Expand Up @@ -87,14 +164,24 @@ impl AtomClient {

/// The Session call: ATOM reads `frames` as they come and answers on the
/// returned stream.
#[cfg_attr(not(test), allow(dead_code))]
pub async fn session(
&self,
frames: impl Stream<Item = Frames> + Send + 'static,
) -> Result<Streaming<Frames>, Status> {
let mut client = self.client.clone();
Ok(client.session(frames).await?.into_inner())
}

pub async fn prepare_structured_output(
&self,
request: PrepareStructuredOutputRequest,
) -> Result<PrepareStructuredOutputResponse, Status> {
let mut client = self.client.clone();
Ok(client
.prepare_structured_output(request)
.await?
.into_inner())
}
}

#[cfg(test)]
Expand Down
54 changes: 33 additions & 21 deletions atom/mesh/src/routers/grpc/engine/atom/pair.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use tracing::error;

use super::request::generate_request;
use super::stream::{http_error, AtomStream};
use super::AtomClient;
use super::{AtomCalls, AtomClient};
use crate::atom_engine::grpc::{
generate_response::Response, GenerateComplete, GenerateRequest, GenerateResponse,
};
Expand Down Expand Up @@ -235,10 +235,11 @@ impl AtomPairs {
Ok(AtomAdapter::new(info.clone()))
}

/// One attempt on the planned pair, P picked by the rank mapping. Both loads
/// are taken first, as `ReservedPair` takes them; P's ends when P completes.
/// One attempt on the planned pair (P by the rank mapping), each leg through `calls`. Both
/// loads are taken first, as `ReservedPair` takes them; P's ends when P completes.
pub(crate) async fn dispatch(
&self,
calls: &AtomCalls,
prefill: &Arc<dyn Worker>,
decode: &Arc<dyn Worker>,
payload: &GenerationPayload,
Expand All @@ -256,7 +257,7 @@ impl AtomPairs {
}
.emit();
let stream = self
.run(&prefill, decode, payload, tokenizer, prefill_load)
.run(calls, &prefill, decode, payload, tokenizer, prefill_load)
.await
.inspect_err(|e| {
error!(prefill = prefill.url(), decode = decode.url(), error = %e, "ATOM P/D failed")
Expand All @@ -270,6 +271,7 @@ impl AtomPairs {

async fn run(
&self,
calls: &AtomCalls,
prefill: &Arc<dyn Worker>,
decode: &Arc<dyn Worker>,
payload: &GenerationPayload,
Expand Down Expand Up @@ -306,15 +308,15 @@ impl AtomPairs {
// and so cancels, the other's call.
let (_, stream) = tokio::try_join!(
async {
run_prefill(&prefill_client, prefill_request).await?;
run_prefill(calls, prefill, &prefill_client, prefill_request).await?;
drop(prefill_load);
Ok::<_, EngineError>(())
},
open_decode(&decode_client, decode_request),
open_decode(calls, decode, &decode_client, decode_request),
)?;
return Ok(stream);
}
let complete = run_prefill(&prefill_client, prefill_request).await?;
let complete = run_prefill(calls, prefill, &prefill_client, prefill_request).await?;
// P has completed; D's stream must not keep P loaded.
drop(prefill_load);
let kv = complete
Expand All @@ -324,7 +326,7 @@ impl AtomPairs {
.map_err(|e| bad_gateway(format!("Prefill kv_transfer_params parse error: {e}")))?;
adapter.enrich_decode_kv(&mut kv, &ctx).map_err(internal)?;
decode_request.kv_transfer_params_json = Some(kv.to_string());
open_decode(&decode_client, decode_request).await
open_decode(calls, decode, &decode_client, decode_request).await
}
}

Expand Down Expand Up @@ -430,36 +432,46 @@ fn take_view(request: &mut GenerateRequest, view: &Value) {
/// P's call up to its Complete. Failures that are not ATOM's own GenerateError
/// take the 502 ATOM's HTTP P/D router answers them with.
async fn run_prefill(
calls: &AtomCalls,
prefill: &Arc<dyn Worker>,
client: &AtomClient,
request: GenerateRequest,
) -> Result<GenerateComplete, EngineError> {
let mut stream = client
.generate(request)
let mut stream = calls
.start(prefill, client, request)
.await
.map_err(|s| bad_gateway(format!("Prefill server error: {s}")))?;
.map_err(|e| match e {
EngineError::Transport(s) => bad_gateway(format!("Prefill server error: {s}")),
e => e,
})?;
loop {
match stream.message().await {
Ok(Some(GenerateResponse { response })) => match response {
match stream.next().await {
Some(Ok(GenerateResponse { response })) => match response {
Some(Response::Complete(complete)) => return Ok(complete),
Some(Response::Error(error)) => return Err(http_error(error)),
Some(Response::Chunk(_)) | None => {}
},
Ok(None) => return Err(bad_gateway("Prefill stream ended without Complete".into())),
Err(s) => return Err(bad_gateway(format!("Prefill read error: {s}"))),
None => return Err(bad_gateway("Prefill stream ended without Complete".into())),
Some(Err(s)) => return Err(bad_gateway(format!("Prefill read error: {s}"))),
}
}
}

async fn open_decode(
calls: &AtomCalls,
decode: &Arc<dyn Worker>,
client: &AtomClient,
request: GenerateRequest,
) -> Result<AtomStream, EngineError> {
AtomStream::open(client, request)
.await
.map_err(|e| match e {
EngineError::Transport(s) => bad_gateway(format!("Decode server error: {s}")),
e => e,
})
let (streamed, started) = (request.stream, Instant::now());
let opened = match calls.start(decode, client, request).await {
Ok(responses) => AtomStream::start(responses, streamed, started).await,
Err(e) => Err(e),
};
opened.map_err(|e| match e {
EngineError::Transport(s) => bad_gateway(format!("Decode server error: {s}")),
e => e,
})
}

fn no_client(worker: &Arc<dyn Worker>) -> EngineError {
Expand Down
Loading
Loading