Skip to content
Open
Show file tree
Hide file tree
Changes from 55 commits
Commits
Show all changes
56 commits
Select commit Hold shift + click to select a range
a6c782d
[ATOM gRPC] The Session RPC: many requests on one stream, one message…
Jasen2201 Nov 21, 2026
f6851bd
Merge the Generate review fixes (#3673) into the Session RPC
Jasen2201 Nov 22, 2026
8c9babc
[ATOM gRPC] Session: grammar failures as Rejected INTERNAL, cancel du…
Jasen2201 Nov 22, 2026
fe12c9f
Merge Abort before submission (#3673) into the Session RPC
Jasen2201 Nov 22, 2026
03d499f
Merge the chat-template and top_logprobs review fixes (#3673) into th…
Jasen2201 Nov 22, 2026
cbf2a5e
Merge the step-flush ordering fix (#3673) into the Session RPC
Jasen2201 Nov 22, 2026
b237266
Merge B's gRPC shutdown fix (#3673) into the Session RPC
Jasen2201 Nov 22, 2026
c9cbb2a
Merge B's gRPC receive limit and stream buffering fix (#3673) into th…
Jasen2201 Nov 22, 2026
57a7816
Merge B's gRPC stop race fix (#3673) into the Session RPC
Jasen2201 Nov 23, 2026
906f082
Merge the proto and ATOM gRPC server (#3673) into the Session RPC
Jasen2201 Nov 23, 2026
0d433d9
Merge the proto and ATOM gRPC server (#3673) into the Session RPC
Jasen2201 Nov 23, 2026
3e8f3e2
Merge the proto and ATOM gRPC server (#3673) into the Session RPC
Jasen2201 Nov 23, 2026
a8992bd
grpc Session: hold a window through preprocess; a prompt only in kv_t…
Jasen2201 Nov 23, 2026
73ba40e
Merge main into the Session RPC
Jasen2201 Nov 23, 2026
b63cb50
Merge the proto and ATOM gRPC server into the Session RPC
Jasen2201 Nov 23, 2026
1fe0ea6
Merge the proto and ATOM gRPC server into the Session RPC
Jasen2201 Nov 23, 2026
8b1b15d
Test the Session's frames codec and the Session RPC over the wire
Jasen2201 Nov 23, 2026
7abd3a3
Session rejects RequestSpec fields it does not read instead of droppi…
Jasen2201 Nov 23, 2026
c0a7665
Session holds a request cancelled after it reached the engine until i…
Jasen2201 Nov 23, 2026
8320ab9
Session gives each request a new engine id, not one derived from its …
Jasen2201 Nov 23, 2026
bd917c1
Session fails a client that leaves 4096 messages unread
Jasen2201 Nov 23, 2026
208c06b
Document the Session's seq_id window and outbox bound in its proto co…
Jasen2201 Nov 23, 2026
7fa2fa5
Merge the proto and ATOM gRPC server into the Session RPC
Jasen2201 Nov 23, 2026
054f9a6
Session aborts a seq whose failed submission may have reached an engine
Jasen2201 Nov 23, 2026
5d36070
A failed Session stops reading, so it admits nothing after close()
Jasen2201 Nov 23, 2026
eea774f
Test that the Session codec keeps explicit zero and false sampling fi…
Jasen2201 Nov 23, 2026
66f060f
Merge the proto and ATOM gRPC server into the Session RPC
Jasen2201 Nov 23, 2026
3284b5a
A failed Session cancels its reader once
Jasen2201 Nov 23, 2026
8db037c
The Session refuses stop strings that arrive without their ids
Jasen2201 Nov 23, 2026
b470894
Merge the proto and ATOM gRPC server into the Session RPC
Jasen2201 Nov 23, 2026
19c1f2a
Merge the proto and ATOM gRPC server into the Session RPC
Jasen2201 Nov 23, 2026
1162172
The Session holds a required call only to the server's own channel
Jasen2201 Nov 23, 2026
fd79ae7
CoreManager refuses a bad rank hint before registering callbacks
Jasen2201 Nov 23, 2026
a4965a9
Merge the proto and server's headers and rank-hint fix into the Sessi…
Jasen2201 Nov 23, 2026
0b1c74a
Give the Session's new files the full source header
Jasen2201 Nov 23, 2026
e8172a5
Settle a structured submission through a second cancel
Jasen2201 Nov 23, 2026
9473dd1
Merge the proto and server's dropped-callback fix into the Session RPC
Jasen2201 Nov 23, 2026
d69f551
Test the Session's caller-assigned ids through the real InputOutputPr…
Jasen2201 Nov 23, 2026
4f80de0
The Session reads an Abort while a submission is still in admission
Jasen2201 Nov 23, 2026
42393db
A Session submission preprocessed after its Session closed never runs
Jasen2201 Nov 23, 2026
2f1584f
The Session reads an Abort while its admissions are at their cap
Jasen2201 Nov 23, 2026
9f27526
The Session rejects submissions past a bounded wait for admission
Jasen2201 Nov 23, 2026
fa427cb
A Session seq_id is free again once its request ends, even mid-admission
Jasen2201 Nov 23, 2026
5db7368
The Session serves a greedy n above 1 as one request, as Generate does
Jasen2201 Nov 24, 2026
c00f608
A Session request that fails after it ended leaves its reused seq_id …
Jasen2201 Nov 24, 2026
e9bcf72
The Session refuses a duplicate of a running seq_id as it is read
Jasen2201 Nov 24, 2026
96e0f6e
The Session refuses a structured request with custom stops, as Genera…
Jasen2201 Nov 24, 2026
2651588
The Session times a request's tokens as the engine delivers them
Jasen2201 Nov 24, 2026
767c30d
A Session request arrives when the Session reads it
Jasen2201 Nov 24, 2026
6a2f003
The end of a Session's client side aborts its requests at once
Jasen2201 Nov 24, 2026
26ae57b
Merge the atom.grpc.v1 service's merge of main into the Session RPC
Jasen2201 Nov 24, 2026
1078f03
Merge the atom.grpc.v1 service's double-cancel settlement into the Se…
Jasen2201 Nov 24, 2026
404a7f3
The end of a Session's client side aborts what runs before admissions…
Jasen2201 Nov 24, 2026
8b1a3cb
Merge the atom.grpc.v1 service's merge of main into the Session RPC
Jasen2201 Nov 24, 2026
70ef2c1
Merge the engine's skip of a turned-off prefix chain store into the S…
Jasen2201 Nov 26, 2026
23ad653
Merge main into the Session RPC
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
5 changes: 4 additions & 1 deletion atom/entrypoints/grpc/atom_grpc.proto
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,10 @@ service AtomEngine {
rpc GetModelInfo(GetModelInfoRequest) returns (GetModelInfoResponse);
rpc GetServerInfo(GetServerInfoRequest) returns (GetServerInfoResponse);
rpc HealthCheck(HealthCheckRequest) returns (HealthCheckResponse);
// Many requests on one stream: each Frames is one engine_v1 message.
// Many requests on one stream: each Frames is one engine_v1 message. A client's
// seq_ids lie below 2^24, 1 << _SEQ_ID_SHIFT (frontend_workers.py), which SEQ_IDS
// in atom/mesh/src/routers/grpc/engine/atom/session.rs must equal. A client that
// leaves 4096 messages unread ends its Session with RESOURCE_EXHAUSTED.
rpc Session(stream Frames) returns (stream Frames);
// The structured-output fields of a chat sent over the Session, derived as the
// HTTP chat route derives them; the request's SamplingParams takes them.
Expand Down
5 changes: 4 additions & 1 deletion atom/entrypoints/grpc/atom_grpc_pb2_grpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,10 @@ def HealthCheck(self, request, context):
raise NotImplementedError('Method not implemented!')

def Session(self, request_iterator, context):
"""Many requests on one stream: each Frames is one engine_v1 message.
"""Many requests on one stream: each Frames is one engine_v1 message. A client's
seq_ids lie below 2^24, 1 << _SEQ_ID_SHIFT (frontend_workers.py), which SEQ_IDS
in atom/mesh/src/routers/grpc/engine/atom/session.rs must equal. A client that
leaves 4096 messages unread ends its Session with RESOURCE_EXHAUSTED.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
Expand Down
323 changes: 323 additions & 0 deletions atom/entrypoints/grpc/frames.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,323 @@
# SPDX-License-Identifier: MIT
# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved.
# Copyright (c) 2026 ATOM Project Contributors
"""Codec for the Session's engine_v1 messages, each an Envelope then the frames its
BufferRefs name: what the server reads from its client and writes back."""

from dataclasses import dataclass, field
from itertools import chain
from typing import NamedTuple

import numpy as np
from google.protobuf.message import DecodeError

from atom.entrypoints.openai.protocol import DEFAULT_MAX_TOKENS
from atom.model_engine.request import RequestOutput
from atom.model_engine.zmq_protocol import engine_v1_pb2 as pb
from atom.sampling_params import RequiredChannel, SamplingParams

PROTOCOL_VERSION = 1 # engine_v1's: atom_engine::wire::PROTOCOL_VERSION in Rust
INVALID = pb.RejectedRequest.INVALID
_DEFAULTED = ("temperature", "top_k", "top_p") # absent: SamplingParams' defaults
_ROUTING = ("data_parallel_rank", "dp_session_id", "dp_parent_session_id")
# RequestSpec fields the Session does not read: it stamps arrival on its own clock,
# hashes the prompt itself, takes no siblings and does not trace.
_UNREAD = ("arrive_time", "prompt_hash_chain", "parent_request_id", "trace")
_COMPLETION_SCALARS = (
"leave_reason",
"num_prompt_tokens",
"num_cached_tokens",
"arrive_time",
"first_token_time",
"leave_time",
)


class FrameError(ValueError):
"""A message, or one request in it, that this codec cannot read."""


@dataclass
class SubmitRequest:
"""One RequestSpec, as `InputOutputProcessor.preprocess` takes it."""

seq_id: int
prompt_token_ids: list[int]
sampling_params: SamplingParams
stop_token_sequences: list[list[int]] = field(default_factory=list)
kv_transfer_params: dict | None = None
request_id: str | None = None
data_parallel_rank: int | None = None
dp_session_id: str | None = None
dp_parent_session_id: str | None = None


@dataclass
class Completion:
"""A finished request's Completions item: ids, usage, times and leave reason."""

seq_id: int
completion_token_ids: list[int]
leave_reason: str
num_prompt_tokens: int = 0
num_cached_tokens: int = 0
arrive_time: float = 0.0
first_token_time: float = 0.0
leave_time: float = 0.0
logprobs: list[float] | None = None
kv_transfer_params_output: dict | None = None
external_request_id: str | None = None


class Rejection(NamedTuple):
seq_id: int
reason: str
code: int # a RejectedRequest.Code


def decode_client(frames) -> tuple[str, list]:
"""("submit", a SubmitRequest or an INVALID Rejection per request) or ("abort",
seq ids). Raises FrameError for any other message, or one of another version."""
envelope = _envelope(frames)
body = envelope.WhichOneof("body")
if body == "abort":
return body, list(envelope.abort.seq_ids)
if body != "submit":
raise FrameError(f"a Session client sends SubmitBatch or Abort, not {body}")
items = []
for spec in envelope.submit.requests:
try:
items.append(_request(spec, frames))
except ValueError as e: # FrameError, or a value SamplingParams refuses
items.append(Rejection(spec.seq_id, str(e), INVALID))
return body, items


def encode_ready(max_pool_tokens: int | None = None) -> list[bytes]:
return _finish(pb.Envelope(ready=pb.Ready(max_pool_tokens=max_pool_tokens)), [])


def encode_stream(entries: list[tuple[int, RequestOutput]]) -> list[bytes]:
"""One StreamBatch: a step's (seq_id, RequestOutput) entries, column by column."""
envelope, data = pb.Envelope(stream=pb.StreamBatch()), []
msg = envelope.stream
outputs = [output for _, output in entries]
msg.seq_ids.extend([seq_id for seq_id, _ in entries])
msg.token_counts.extend([len(o.output_tokens) for o in outputs])
msg.tokens.extend(chain.from_iterable(o.output_tokens for o in outputs))
msg.finished.extend([o.finished for o in outputs])
msg.num_cached_tokens.extend([o.num_cached_tokens for o in outputs])
floats, ints = [], []
for i, o in enumerate(outputs):
if o.finish_reason is not None:
msg.finish_reasons[i] = o.finish_reason
if o.kv_transfer_params_output is not None:
_put_value(o.kv_transfer_params_output, msg.kv_transfer_params_outputs[i])
if o.logprobs is not None:
_put_records(i, o.logprobs, msg, floats, ints)
if msg.logprob_entries:
_attach(data, floats, "<f8", msg.logprob_floats)
_attach(data, ints, "<i4", msg.logprob_ints)
return _finish(envelope, data)


def encode_completions(items: list[Completion]) -> list[bytes]:
envelope, data = pb.Envelope(completions=pb.Completions()), []
for c in items:
msg = envelope.completions.items.add(
seq_id=c.seq_id,
external_request_id=c.external_request_id,
**{name: getattr(c, name) for name in _COMPLETION_SCALARS},
)
_attach(data, c.completion_token_ids, "<i4", msg.completion_token_ids)
if c.logprobs is not None:
_attach(data, c.logprobs, "<f8", msg.logprobs)
if c.kv_transfer_params_output is not None:
_put_value(c.kv_transfer_params_output, msg.kv_transfer_params_output)
return _finish(envelope, data)


def encode_rejected(items: list[Rejection]) -> list[bytes]:
rejected = [pb.RejectedRequest(seq_id=s, reason=r, code=c) for s, r, c in items]
return _finish(pb.Envelope(rejected=pb.Rejected(items=rejected)), [])


# ---------------------------------------------------------------- frames ---


def _envelope(frames) -> pb.Envelope:
if not frames:
raise FrameError("a message needs its Envelope frame")
try:
envelope = pb.Envelope.FromString(frames[0])
except DecodeError as e:
raise FrameError(f"frame 0 is not an Envelope: {e}") from e
if envelope.protocol_version != PROTOCOL_VERSION:
raise FrameError(
f"protocol version {envelope.protocol_version}, "
f"expected {PROTOCOL_VERSION}"
)
return envelope


def _finish(envelope: pb.Envelope, data: list[bytes]) -> list[bytes]:
envelope.protocol_version = PROTOCOL_VERSION
return [envelope.SerializeToString(), *data]


def _attach(data: list[bytes], values, dtype: str, ref: pb.BufferRef) -> None:
"""`values` as a little-endian data frame of their own, which `ref` names."""
data.append(np.asarray(values, dtype).tobytes())
ref.frame, ref.nbytes = len(data), len(data[-1])


def _read(frames, parent, name: str, dtype: str) -> np.ndarray:
"""The little-endian values BufferRef `parent.name` names; none when absent."""
if not parent.HasField(name):
return np.empty(0, dtype)
ref, size = getattr(parent, name), np.dtype(dtype).itemsize
if not 0 < ref.frame < len(frames):
raise FrameError(f"{name} names frame {ref.frame} of {len(frames)}")
if ref.offset + ref.nbytes > len(frames[ref.frame]) or ref.nbytes % size:
raise FrameError(f"{name} is not whole {dtype} values inside its frame")
return np.frombuffer(frames[ref.frame], dtype, ref.nbytes // size, ref.offset)


def _is_set(msg, name: str) -> bool:
"""Whether field `name` is set: present, or not its default where it has no
presence."""
if msg.DESCRIPTOR.fields_by_name[name].has_presence:
return msg.HasField(name)
return bool(getattr(msg, name))


def _optional(msg, name: str):
return getattr(msg, name) if msg.HasField(name) else None


# -------------------------------------------------------------- requests ---


def _request(spec: pb.RequestSpec, frames) -> SubmitRequest:
media = ("multimodal_data", "mrope_positions", "cache_seed")
if spec.mrope_position_delta or any(spec.HasField(name) for name in media):
raise FrameError("the Session takes text prompts; this request carries media")
if spec.needs_independent_noise or spec.sibling_index:
raise FrameError("the Session takes n=1; this request is one sibling of n")
unread = [name for name in _UNREAD if _is_set(spec, name)]
if unread:
raise FrameError(f"the Session does not read {', '.join(unread)}")
prompt = _read(frames, spec, "prompt_token_ids", "<i4")
if (prompt < 0).any():
raise FrameError("prompt token ids must be non-negative")
kv = _value_field(spec, "kv_transfer_params")
if kv is not None and not isinstance(kv, dict):
raise FrameError("kv_transfer_params must be a map")
return SubmitRequest(
seq_id=spec.seq_id,
prompt_token_ids=prompt.tolist(),
sampling_params=_sampling(spec.sampling),
# An empty one would match at once; the HTTP path drops it as well.
stop_token_sequences=[list(s.ids) for s in spec.stop_token_sequences if s.ids],
kv_transfer_params=kv,
request_id=_optional(spec, "external_request_id"),
**{name: _optional(spec, name) for name in _ROUTING},

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

arrive_time and trace are silently dropped.. carry them through or refuse like media so the client gets INVALID.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 7abd3a3: the codec now rejects a request that sets arrive_time, trace, prompt_hash_chain or parent_request_id as INVALID, as it rejects media. The Session stamps arrival on its own clock, hashes the prompt itself, takes no siblings and does not trace; atomesh sets none of them. test_a_field_the_session_does_not_read_is_rejected_not_dropped covers each.

)


def _sampling(msg: pb.SamplingParams) -> SamplingParams:
"""Absent fields read as the HTTP routes fill omitted ones (max_tokens their
default, logprobs False), and n below 1 as 1, as those routes coerce it."""
stops, which = msg.stop_strings, msg.stop_strings.WhichOneof("value")
stop_strings = None
if which == "single":
stop_strings = stops.single
elif which == "many":
stop_strings = list(stops.many.items)
channel = None
if msg.HasField("required_channel"):
c = msg.required_channel
channel = RequiredChannel(
tuple(c.after), tuple(c.opening), c.opens_at, tuple(c.end_ids)
)
logprobs = msg.WhichOneof("logprobs")
has_max = msg.HasField("max_tokens")
return SamplingParams(
**{name: getattr(msg, name) for name in _DEFAULTED if msg.HasField(name)},
max_tokens=msg.max_tokens if has_max else DEFAULT_MAX_TOKENS,
max_tokens_is_default=msg.max_tokens_is_default or not has_max,
Comment on lines +244 to +248

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tests/test_grpc_frames.py (8b1b15d) covers omitted fields (test_absent_sampling_fields_read_as_the_http_routes_fill_them) and a value SamplingParams refuses becoming a per-request INVALID (top_p=2.0 in test_a_request_the_session_cannot_read_is_rejected_alone). eea774f adds explicit zero/false values kept as sent.

n=max(msg.n, 1),
ignore_eos=msg.ignore_eos,
stop_strings=stop_strings,
logprobs=False if logprobs is None else getattr(msg, logprobs),
required_channel=channel,
top_logprobs=msg.top_logprobs,
json_schema=_optional(msg, "json_schema"),
structured_tool_format=_optional(msg, "structured_tool_format"),
structured_reasoning_end=msg.structured_reasoning_end,
)


# --------------------------------------------------------------- outputs ---


def _put_records(entry: int, records, msg: pb.StreamBatch, floats, ints) -> None:
"""An entry's TokenLogprob records, (logprob, rank, id_0, logprob_0, ...)."""
width = (len(records[0]) - 2) // 2 if records else 0
for record in records:
if len(record) != 2 * width + 2:
raise FrameError(f"entry {entry}'s logprob records differ in width")
floats += (record[0], *record[3::2])
ints += (record[1], *record[2::2])
msg.logprob_entries.append(entry)
msg.logprob_counts.append(len(records))
msg.logprob_widths.append(width)


# ---------------------------------------------------------------- values ---


def _put_value(value, msg: pb.Value) -> None:
"""A JSON-shaped value; tuples go as lists, as json.dumps writes them."""
if value is None:
msg.null_value = True
elif isinstance(value, bool):
msg.bool_value = value
elif isinstance(value, int):
msg.int_value = value
elif isinstance(value, float):
msg.float_value = value
elif isinstance(value, str):
msg.string_value = value
elif isinstance(value, (list, tuple)):
msg.list_value.SetInParent()
for item in value:
_put_value(item, msg.list_value.items.add())
elif isinstance(value, dict) and all(isinstance(key, str) for key in value):
msg.map_value.SetInParent()
for key, item in value.items():
entry = msg.map_value.entries.add()
entry.key.string_value = key
_put_value(item, entry.value)
else:
raise TypeError(f"{value!r} is not JSON-shaped")


def _get_value(msg: pb.Value):
"""`msg`'s JSON-shaped value; bytes, tuples, tensors and pickles are refused."""
kind = msg.WhichOneof("kind")
if kind == "null_value":
return None
if kind in ("bool_value", "int_value", "float_value", "string_value"):
return getattr(msg, kind)
if kind == "list_value":
return [_get_value(item) for item in msg.list_value.items]
if kind == "map_value":
entries = msg.map_value.entries
if all(e.key.HasField("string_value") for e in entries):
return {e.key.string_value: _get_value(e.value) for e in entries}
raise FrameError(f"a Value of kind {kind} is not JSON-shaped")


def _value_field(parent, name: str):
return _get_value(getattr(parent, name)) if parent.HasField(name) else None
Loading