Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
4 changes: 1 addition & 3 deletions atom/entrypoints/grpc/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,9 +331,7 @@ async def _submit(self, session, request: frames.SubmitRequest) -> None:
api.engine.io_processor.preprocess,
prompt,
params,
stream_callback=self.steps.callback(
session.put(request.seq_id), session.flush
),
stream_callback=self.steps.callback(session.put, session.flush),
kv_transfer_params=api._engine_kv_transfer_params(kv_transfer_params),
data_parallel_rank=request.data_parallel_rank,
dp_session_id=request.dp_session_id,
Expand Down
43 changes: 20 additions & 23 deletions atom/entrypoints/grpc/session.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
# SPDX-License-Identifier: MIT
# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved.
"""The Session RPC's state: each Session's seq ids in a window of their own, and per
engine step one StreamBatch per Session, then one item per request the step ended."""
engine step one StreamBatch per Session, then an id-free item per request it ended."""

import asyncio
import logging
import time
from collections import deque
from dataclasses import dataclass, field, replace
from functools import partial
from dataclasses import dataclass, replace

from atom.entrypoints.grpc import frames
from atom.entrypoints.openai.frontend_workers import worker_seq_id_base
Expand All @@ -25,7 +24,6 @@
class _Request:
seq: object # its Sequence, under the engine's id for it
external_request_id: str | None
ids: list[int] = field(default_factory=list) # its output ids so far
first_token_time: float = 0.0


Expand All @@ -49,7 +47,8 @@ def __init__(self, sessions: Sessions, window: int):
self.sessions, self.api = sessions, sessions.api
self.window, self.base = window, worker_seq_id_base(window)
self.requests: dict[int, _Request] = {}
self.pending: list[tuple[int, RequestOutput]] = [] # the step being delivered
self.pending: list[RequestOutput] = [] # the step being delivered
self.put = self.pending.append # where each output goes as a step is delivered
self.outbox: asyncio.Queue = asyncio.Queue() # message frames; None ends them
self.open = True

Expand All @@ -61,13 +60,6 @@ def seq_id(self, client_id: int) -> int:
raise ValueError(f"seq_id {client_id} is already in flight")
return self.base | client_id

def put(self, client_id: int):
"""Where `client_id`'s outputs go as a step is delivered; `flush` sends them."""
return partial(self._put, client_id)

def _put(self, client_id: int, output: RequestOutput) -> None:
self.pending.append((client_id, output))

def add(self, client_id: int, seq, external_request_id: str | None) -> None:
self.requests[client_id] = _Request(seq, external_request_id)

Expand Down Expand Up @@ -98,16 +90,22 @@ def close(self) -> None:
def flush(self) -> None:
"""The step's outputs: one StreamBatch of those carrying ids, then a Completions
item, or a Rejected one, for each request the step ended."""
pending, self.pending = self.pending, []
entries, done, now = [], [], time.time()
for client_id, output in pending:
request = self.requests.get(client_id)
pending = self.pending[:]
self.pending.clear() # the list `put` appends to
requests, base, now = self.requests, self.base, time.time()
entries, done = [], []
for output in pending:
client_id = output.request_id - base # the engine's id is base | client id
request = requests.get(client_id)
if request is None: # dropped when its submission failed
continue
if output.output_tokens:
request.ids += output.output_tokens
request.first_token_time = request.first_token_time or now
entries.append((client_id, _streamed(output)))
if not request.first_token_time:
request.first_token_time = now
streamed = output
if output.kv_transfer_params_output is not None:
streamed = _streamed(output)
entries.append((client_id, streamed))
if output.finished:
done.append(_completion(client_id, request, output, now))
if self.open and entries:
Expand All @@ -131,19 +129,18 @@ def _release(self) -> None:

def _streamed(output: RequestOutput) -> RequestOutput:
"""`output` for a StreamBatch: its kv_transfer_params go in its Completions item."""
if output.kv_transfer_params_output is None:
return output
return replace(output, kv_transfer_params_output=None)


def _completion(client_id, request, output, now: float) -> frames.Completion:
"""Its Completions item: no ids, which its StreamBatch entries carried."""
seq = request.seq
return frames.Completion(
seq_id=client_id,
completion_token_ids=request.ids,
completion_token_ids=[],
leave_reason=output.finish_reason or "",
num_prompt_tokens=seq.num_prompt_tokens,
num_cached_tokens=seq.num_prompt_tokens if request.ids else 0,
num_cached_tokens=seq.num_prompt_tokens if request.first_token_time else 0,
arrive_time=seq.arrive_time,
first_token_time=request.first_token_time,
leave_time=now,
Expand Down
115 changes: 85 additions & 30 deletions atom/mesh/src/routers/grpc/engine/atom/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,18 @@ use std::collections::HashMap;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use std::thread;

use futures::{stream, Stream, StreamExt};
use http::StatusCode;
use parking_lot::Mutex;
use serde_json::Value as Json;
use tokio::sync::mpsc;
use tokio::runtime;
use tokio::sync::{mpsc, oneshot};
use tonic::{Status, Streaming};
use tracing::warn;

use super::{pair::atom_client, AtomClient};
use super::AtomClient;
use crate::atom_engine::grpc::{
generate_response::Response, Frames, GenerateComplete, GenerateError, GenerateResponse,
GenerateStreamChunk,
Expand Down Expand Up @@ -64,10 +66,7 @@ impl AtomSessions {
if let Some(session) = slot.as_ref().filter(|session| session.is_open()) {
return Ok(session.clone());
}
let client = atom_client(worker)
.await
.ok_or_else(|| EngineError::ConnectionAcquireFailed(worker.url().to_string()))?;
Ok(slot.insert(Session::open(&client, url).await?).clone())
Ok(slot.insert(Session::open(url).await?).clone())
}
}

Expand All @@ -85,21 +84,19 @@ enum Command {
}

impl Session {
/// Opens the call and waits for ATOM's Ready, refusing one of another protocol version.
async fn open(client: &AtomClient, url: &str) -> Result<Self, EngineError> {
/// Opens the call on a connection and thread of its own, off the router's runtime;
/// waits for ATOM's Ready, refusing one of another protocol version.
async fn open(url: &str) -> Result<Self, EngineError> {
let (commands, queued) = mpsc::unbounded_channel();
let mut inbound = client
.session(writer(queued))
.await
.map_err(EngineError::Transport)?;
let first = inbound.message().await.map_err(EngineError::Transport)?;
match first.map(|message| Inbound::decode(message.frames).map(|m| m.body)) {
Some(Ok(Body::Ready(_))) => {}
Some(Err(e)) => return Err(refused(&e)),
_ => return Err(refused("the call did not start with Ready")),
}
let routes = Arc::new(Mutex::new(Routes::default()));
tokio::spawn(read(inbound, routes.clone(), url.to_string()));
let (opened, ready) = oneshot::channel();
let (url, read_into) = (url.to_string(), routes.clone());
thread::Builder::new()
.name("atom-session".into())
.spawn(move || run(url, queued, read_into, opened))
.map_err(|e| EngineError::Transport(Status::internal(e.to_string())))?;
let gone = |_| EngineError::Transport(Status::internal("the Session thread ended"));
ready.await.map_err(gone)??;
Ok(Self { routes, commands })
}

Expand All @@ -126,6 +123,7 @@ impl Session {
prompt_tokens: prompt.len() as u32,
completion_tokens: 0,
cached_tokens: 0,
ids: Vec::new(),
};
let command = Command::Submit(Box::new(spec), prompt);
if routes.closed || self.commands.send(command).is_err() {
Expand All @@ -142,6 +140,55 @@ impl Session {
}
}

/// The Session's thread: a runtime of its own, which connects, opens the call and reads
/// it until it ends; `opened` gets how the opening went.
fn run(
url: String,
queued: mpsc::UnboundedReceiver<Command>,
routes: Arc<Mutex<Routes>>,
opened: oneshot::Sender<Result<(), EngineError>>,
) {
let runtime = match runtime::Builder::new_current_thread().enable_all().build() {
Ok(runtime) => runtime,
Err(e) => {
let _ = opened.send(Err(EngineError::Transport(Status::internal(e.to_string()))));
return;
}
};
runtime.block_on(async move {
match start(&url, queued).await {
Ok((_client, inbound)) => {
let _ = opened.send(Ok(()));
read(inbound, routes, url).await;
}
Err(e) => {
let _ = opened.send(Err(e));
}
}
});
}

/// Connects to `url`, opens the call and reads ATOM's Ready; the client keeps the
/// connection the call runs on.
async fn start(
url: &str,
queued: mpsc::UnboundedReceiver<Command>,
) -> Result<(AtomClient, Streaming<Frames>), EngineError> {
let client = AtomClient::connect(url)
.await
.map_err(|_| EngineError::ConnectionAcquireFailed(url.to_string()))?;
let mut inbound = client
.session(writer(queued))
.await
.map_err(EngineError::Transport)?;
let first = inbound.message().await.map_err(EngineError::Transport)?;
match first.map(|message| Inbound::decode(message.frames).map(|m| m.body)) {
Some(Ok(Body::Ready(_))) => Ok((client, inbound)),
Some(Err(e)) => Err(refused(&e)),
_ => Err(refused("the call did not start with Ready")),
}
}

fn refused(reason: &str) -> EngineError {
EngineError::Transport(Status::failed_precondition(format!(
"ATOM Session refused: {reason}"
Expand Down Expand Up @@ -229,6 +276,8 @@ struct Route {
completion_tokens: u32,
/// The last nonzero prefix-cache hit, as ATOM's HTTP routes keep it.
cached_tokens: u32,
/// A request that does not stream: its ids so far, which its Complete carries.
ids: Vec<u32>,
}

impl Route {
Expand Down Expand Up @@ -256,20 +305,21 @@ impl Routes {
match &message.body {
Body::Stream(batch) => self.step(batch),
Body::Completions(completions) => {
// Every item is read before any request ends.
// Every item is read before any request ends. An item carries no ids:
// its request's StreamBatch entries did.
let mut read = Vec::with_capacity(completions.items.len());
for item in &completions.items {
let ids = message.tokens(item.completion_token_ids.as_ref())?;
let kv = item.kv_transfer_params_output.as_ref();
read.push((item, ids, kv.map(json).transpose()?));
read.push((item, kv.map(json).transpose()?));
}
for (item, ids, kv) in read {
let Some(route) = self.open.remove(&item.seq_id) else {
for (item, kv) in read {
let Some(mut route) = self.open.remove(&item.seq_id) else {
continue;
};
let output_ids = std::mem::take(&mut route.ids);
route.send(Response::Complete(GenerateComplete {
completion_tokens: ids.len() as u32,
output_ids: if route.stream { Vec::new() } else { ids },
completion_tokens: route.completion_tokens,
output_ids,
finish_reason: item.leave_reason.clone(),
prompt_tokens: item.num_prompt_tokens,
cached_tokens: route.cached_tokens,
Expand All @@ -293,7 +343,8 @@ impl Routes {
}
}

/// One engine step's entries: each request's ids, as one chunk when it streams.
/// One engine step's entries: each request's ids, as one chunk when it streams,
/// else kept for its Complete.
fn step(&mut self, batch: &pb::StreamBatch) -> Result<(), String> {
let entries = batch.seq_ids.len();
let counted: usize = batch.token_counts.iter().map(|&n| n as usize).sum();
Expand All @@ -303,24 +354,28 @@ impl Routes {
{
return Err("StreamBatch columns disagree in length".into());
}
let mut tokens = batch.tokens.iter().map(|&id| id as u32);
let mut start = 0;
let columns = batch.token_counts.iter().zip(&batch.num_cached_tokens);
for (seq_id, (&count, &cached)) in batch.seq_ids.iter().zip(columns) {
let token_ids: Vec<u32> = tokens.by_ref().take(count as usize).collect();
let tokens = &batch.tokens[start..start + count as usize];
start += count as usize;
let Some(route) = self.open.get_mut(seq_id) else {
continue;
};
route.completion_tokens += count;
if cached > 0 {
route.cached_tokens = cached as u32;
}
let token_ids = tokens.iter().map(|&id| id as u32);
if route.stream {
route.send(Response::Chunk(GenerateStreamChunk {
token_ids,
token_ids: token_ids.collect(),
prompt_tokens: route.prompt_tokens,
completion_tokens: route.completion_tokens,
cached_tokens: route.cached_tokens,
}));
} else {
route.ids.extend(token_ids);
}
}
Ok(())
Expand Down
44 changes: 42 additions & 2 deletions atom/mesh/src/routers/grpc/engine/atom/session_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,40 @@ async fn one_session_serves_both_ranks_and_each_request_gets_only_its_outputs_in
assert!(calls.try_recv().is_err(), "a second Session call opened");
}

#[tokio::test]
async fn a_request_that_does_not_stream_completes_with_the_ids_its_entries_carried() {
let (ranks, mut calls) = instance().await;
let sessions = AtomSessions::default();
let first = sessions.submit(&ranks[0], spec("whole"), vec![1, 2, 3], false);
let (mut call, whole) = opening(&mut calls, PROTOCOL_VERSION, first).await;
let id = submitted(&mut call, 1).await["whole"].0.seq_id;
for message in [
step(&[(id, vec![31], 4)]),
step(&[(id, vec![32, 33], 0)]),
// As ATOM sends it: the item carries none of the ids the entries did.
done(vec![(completion(id, "max_tokens"), Vec::new())]),
] {
call.outbound.send(message).unwrap();
}

let whole: Vec<_> = timeout(HANG, whole.unwrap().collect()).await.unwrap();
let complete = GenerateComplete {
output_ids: vec![31, 32, 33],
finish_reason: "max_tokens".to_string(),
prompt_tokens: 3,
completion_tokens: 3,
cached_tokens: 4,
kv_transfer_params_json: None,
};
let expected = GenerateResponse {
response: Some(Response::Complete(complete)),
};
assert!(
matches!(&whole[..], [Ok(response)] if *response == expected),
"{whole:?}"
);
}

#[tokio::test]
async fn a_rejected_request_fails_with_the_http_status_its_code_reads_back_to() {
let (ranks, mut calls) = instance().await;
Expand Down Expand Up @@ -507,7 +541,10 @@ async fn a_broken_session_fails_its_requests_and_the_next_request_reopens_it() {
let last = sessions.submit(&ranks[0], spec("after"), vec![3], false);
let (mut call, after) = opening(&mut calls, PROTOCOL_VERSION, last).await;
let after_id = submitted(&mut call, 1).await["after"].0.seq_id;
let ended = done(vec![(completion(after_id, "eos"), vec![41])]);
call.outbound
.send(step(&[(after_id, vec![41], 0)]))
.unwrap();
let ended = done(vec![(completion(after_id, "eos"), Vec::new())]);
call.outbound.send(ended).unwrap();
let after = chunks(after.unwrap()).await;
assert!(
Expand Down Expand Up @@ -552,6 +589,7 @@ fn seq_ids_stay_below_2_24_and_skip_those_open_requests_hold() {
prompt_tokens: 0,
completion_tokens: 0,
cached_tokens: 0,
ids: Vec::new(),
};
routes.open.insert(held, route);
}
Expand Down Expand Up @@ -773,7 +811,9 @@ mod routed {
assert_eq!(max_tokens(&d_spec), Some(8));

// D completes first; the answer waits for P, whose load is still held.
let d_done = done(vec![(completion(d_spec.seq_id, "stop_22"), vec![21, 22])]);
let d_step = step(&[(d_spec.seq_id, vec![21, 22], 0)]);
d_call.outbound.send(d_step).unwrap();
let d_done = done(vec![(completion(d_spec.seq_id, "stop_22"), Vec::new())]);
d_call.outbound.send(d_done).unwrap();
assert_eq!((pw.load(), dw.load()), (1, 1));
let p_done = done(vec![(completion(p_spec.seq_id, "max_tokens"), vec![5])]);
Expand Down