Skip to content

Commit bd80828

Browse files
Jasen2201claude
andcommitted
Merge the atomesh client (#3675) into discovery and P/D
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2 parents a51cd72 + 4aa43b1 commit bd80828

19 files changed

Lines changed: 1361 additions & 92 deletions

‎atom/config.py‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1487,11 +1487,6 @@ def _resolve_synthetic_acceptance(self) -> None:
14871487
form is converted to a length and everything downstream reads only
14881488
``synthetic_acceptance_rates``.
14891489
"""
1490-
# Local import: the schedule lives next to the kernel that consumes it,
1491-
# and that module pulls in triton, which has no business loading just
1492-
# because someone imported a config.
1493-
from atom.model_ops.rejection_sampler import acceptance_length_to_rates
1494-
14951490
if (
14961491
self.synthetic_acceptance_length is not None
14971492
and self.synthetic_acceptance_rate is not None
@@ -1503,6 +1498,9 @@ def _resolve_synthetic_acceptance(self) -> None:
15031498
length = self.synthetic_acceptance_length
15041499
if self.synthetic_acceptance_rate is None and length is None:
15051500
return
1501+
# Below the return: the rejection sampler pulls in triton, which a config
1502+
# without forced acceptance has no business loading.
1503+
from atom.model_ops.rejection_sampler import acceptance_length_to_rates
15061504

15071505
n = self.num_speculative_tokens
15081506
if not n:

‎atom/distributed/dcp_layout.py‎

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,13 @@
33

44
"""DCP token-ownership arithmetic shared by attention and KV transfer.
55
6-
These helpers are pure ``//`` / ``%`` so they stay elementwise over Python
7-
ints, numpy arrays, and torch tensors. They live outside ``dcp_ops`` so P/D
6+
These helpers are ``//``, ``%`` and ``np.clip``, so they stay elementwise over
7+
Python ints, numpy arrays, and torch tensors. They live outside ``dcp_ops`` so P/D
88
relayout can follow the same rule without importing Triton or aiter.
99
"""
1010

11+
import numpy as np
12+
1113

1214
def dcp_owner_rank(pos, dcp_size, cp_kv_cache_interleave_size=1):
1315
"""Which DCP rank owns global token ``pos`` under interleaved KV storage.
@@ -44,3 +46,30 @@ def dcp_global_pos(local_index, dcp_rank, dcp_size, cp_kv_cache_interleave_size=
4446
return (
4547
(local_index // cp_kv_cache_interleave_size) * dcp_size + dcp_rank
4648
) * cp_kv_cache_interleave_size + (local_index % cp_kv_cache_interleave_size)
49+
50+
51+
def get_dcp_local_seq_lens(seq_lens, dcp_size, dcp_rank, cp_kv_cache_interleave_size=1):
52+
"""Compute per-DCP-rank local sequence lengths.
53+
54+
With interleaved storage, token i is stored on rank
55+
(i // cp_kv_cache_interleave_size) % dcp_size.
56+
57+
Args:
58+
seq_lens: numpy array of sequence lengths
59+
dcp_size: DCP world size
60+
dcp_rank: this rank's DCP rank
61+
cp_kv_cache_interleave_size: interleaving granularity (default 1 = token-level)
62+
63+
Returns:
64+
local_seq_lens: numpy array of local sequence lengths
65+
"""
66+
full_chunks = seq_lens // (cp_kv_cache_interleave_size * dcp_size)
67+
base = full_chunks * cp_kv_cache_interleave_size
68+
69+
remainder_total = seq_lens - base * dcp_size
70+
remainder = np.clip(
71+
remainder_total - dcp_rank * cp_kv_cache_interleave_size,
72+
0,
73+
cp_kv_cache_interleave_size,
74+
)
75+
return base + remainder

‎atom/entrypoints/grpc/frames.py‎

Lines changed: 308 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,308 @@
1+
# SPDX-License-Identifier: MIT
2+
# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved.
3+
"""Codec for the Session's engine_v1 messages, each an Envelope then the frames its
4+
BufferRefs name: what the server reads from its client and writes back."""
5+
6+
from dataclasses import dataclass, field
7+
from itertools import chain
8+
from typing import NamedTuple
9+
10+
import numpy as np
11+
from google.protobuf.message import DecodeError
12+
13+
from atom.entrypoints.openai.protocol import DEFAULT_MAX_TOKENS
14+
from atom.model_engine.request import RequestOutput
15+
from atom.model_engine.zmq_protocol import engine_v1_pb2 as pb
16+
from atom.sampling_params import RequiredChannel, SamplingParams
17+
18+
PROTOCOL_VERSION = 1 # engine_v1's: atom_engine::wire::PROTOCOL_VERSION in Rust
19+
INVALID = pb.RejectedRequest.INVALID
20+
_DEFAULTED = ("temperature", "top_k", "top_p") # absent: SamplingParams' defaults
21+
_ROUTING = ("data_parallel_rank", "dp_session_id", "dp_parent_session_id")
22+
_COMPLETION_SCALARS = (
23+
"leave_reason",
24+
"num_prompt_tokens",
25+
"num_cached_tokens",
26+
"arrive_time",
27+
"first_token_time",
28+
"leave_time",
29+
)
30+
31+
32+
class FrameError(ValueError):
33+
"""A message, or one request in it, that this codec cannot read."""
34+
35+
36+
@dataclass
37+
class SubmitRequest:
38+
"""One RequestSpec, as `InputOutputProcessor.preprocess` takes it."""
39+
40+
seq_id: int
41+
prompt_token_ids: list[int]
42+
sampling_params: SamplingParams
43+
stop_token_sequences: list[list[int]] = field(default_factory=list)
44+
kv_transfer_params: dict | None = None
45+
request_id: str | None = None
46+
data_parallel_rank: int | None = None
47+
dp_session_id: str | None = None
48+
dp_parent_session_id: str | None = None
49+
50+
51+
@dataclass
52+
class Completion:
53+
"""A finished request's Completions item: ids, usage, times and leave reason."""
54+
55+
seq_id: int
56+
completion_token_ids: list[int]
57+
leave_reason: str
58+
num_prompt_tokens: int = 0
59+
num_cached_tokens: int = 0
60+
arrive_time: float = 0.0
61+
first_token_time: float = 0.0
62+
leave_time: float = 0.0
63+
logprobs: list[float] | None = None
64+
kv_transfer_params_output: dict | None = None
65+
external_request_id: str | None = None
66+
67+
68+
class Rejection(NamedTuple):
69+
seq_id: int
70+
reason: str
71+
code: int # a RejectedRequest.Code
72+
73+
74+
def decode_client(frames) -> tuple[str, list]:
75+
"""("submit", a SubmitRequest or an INVALID Rejection per request) or ("abort",
76+
seq ids). Raises FrameError for any other message, or one of another version."""
77+
envelope = _envelope(frames)
78+
body = envelope.WhichOneof("body")
79+
if body == "abort":
80+
return body, list(envelope.abort.seq_ids)
81+
if body != "submit":
82+
raise FrameError(f"a Session client sends SubmitBatch or Abort, not {body}")
83+
items = []
84+
for spec in envelope.submit.requests:
85+
try:
86+
items.append(_request(spec, frames))
87+
except ValueError as e: # FrameError, or a value SamplingParams refuses
88+
items.append(Rejection(spec.seq_id, str(e), INVALID))
89+
return body, items
90+
91+
92+
def encode_ready(max_pool_tokens: int | None = None) -> list[bytes]:
93+
return _finish(pb.Envelope(ready=pb.Ready(max_pool_tokens=max_pool_tokens)), [])
94+
95+
96+
def encode_stream(entries: list[tuple[int, RequestOutput]]) -> list[bytes]:
97+
"""One StreamBatch: a step's (seq_id, RequestOutput) entries, column by column."""
98+
envelope, data = pb.Envelope(stream=pb.StreamBatch()), []
99+
msg = envelope.stream
100+
outputs = [output for _, output in entries]
101+
msg.seq_ids.extend([seq_id for seq_id, _ in entries])
102+
msg.token_counts.extend([len(o.output_tokens) for o in outputs])
103+
msg.tokens.extend(chain.from_iterable(o.output_tokens for o in outputs))
104+
msg.finished.extend([o.finished for o in outputs])
105+
msg.num_cached_tokens.extend([o.num_cached_tokens for o in outputs])
106+
floats, ints = [], []
107+
for i, o in enumerate(outputs):
108+
if o.finish_reason is not None:
109+
msg.finish_reasons[i] = o.finish_reason
110+
if o.kv_transfer_params_output is not None:
111+
_put_value(o.kv_transfer_params_output, msg.kv_transfer_params_outputs[i])
112+
if o.logprobs is not None:
113+
_put_records(i, o.logprobs, msg, floats, ints)
114+
if msg.logprob_entries:
115+
_attach(data, floats, "<f8", msg.logprob_floats)
116+
_attach(data, ints, "<i4", msg.logprob_ints)
117+
return _finish(envelope, data)
118+
119+
120+
def encode_completions(items: list[Completion]) -> list[bytes]:
121+
envelope, data = pb.Envelope(completions=pb.Completions()), []
122+
for c in items:
123+
msg = envelope.completions.items.add(
124+
seq_id=c.seq_id,
125+
external_request_id=c.external_request_id,
126+
**{name: getattr(c, name) for name in _COMPLETION_SCALARS},
127+
)
128+
_attach(data, c.completion_token_ids, "<i4", msg.completion_token_ids)
129+
if c.logprobs is not None:
130+
_attach(data, c.logprobs, "<f8", msg.logprobs)
131+
if c.kv_transfer_params_output is not None:
132+
_put_value(c.kv_transfer_params_output, msg.kv_transfer_params_output)
133+
return _finish(envelope, data)
134+
135+
136+
def encode_rejected(items: list[Rejection]) -> list[bytes]:
137+
rejected = [pb.RejectedRequest(seq_id=s, reason=r, code=c) for s, r, c in items]
138+
return _finish(pb.Envelope(rejected=pb.Rejected(items=rejected)), [])
139+
140+
141+
# ---------------------------------------------------------------- frames ---
142+
143+
144+
def _envelope(frames) -> pb.Envelope:
145+
if not frames:
146+
raise FrameError("a message needs its Envelope frame")
147+
try:
148+
envelope = pb.Envelope.FromString(frames[0])
149+
except DecodeError as e:
150+
raise FrameError(f"frame 0 is not an Envelope: {e}") from e
151+
if envelope.protocol_version != PROTOCOL_VERSION:
152+
raise FrameError(
153+
f"protocol version {envelope.protocol_version}, "
154+
f"expected {PROTOCOL_VERSION}"
155+
)
156+
return envelope
157+
158+
159+
def _finish(envelope: pb.Envelope, data: list[bytes]) -> list[bytes]:
160+
envelope.protocol_version = PROTOCOL_VERSION
161+
return [envelope.SerializeToString(), *data]
162+
163+
164+
def _attach(data: list[bytes], values, dtype: str, ref: pb.BufferRef) -> None:
165+
"""`values` as a little-endian data frame of their own, which `ref` names."""
166+
data.append(np.asarray(values, dtype).tobytes())
167+
ref.frame, ref.nbytes = len(data), len(data[-1])
168+
169+
170+
def _read(frames, parent, name: str, dtype: str) -> np.ndarray:
171+
"""The little-endian values BufferRef `parent.name` names; none when absent."""
172+
if not parent.HasField(name):
173+
return np.empty(0, dtype)
174+
ref, size = getattr(parent, name), np.dtype(dtype).itemsize
175+
if not 0 < ref.frame < len(frames):
176+
raise FrameError(f"{name} names frame {ref.frame} of {len(frames)}")
177+
if ref.offset + ref.nbytes > len(frames[ref.frame]) or ref.nbytes % size:
178+
raise FrameError(f"{name} is not whole {dtype} values inside its frame")
179+
return np.frombuffer(frames[ref.frame], dtype, ref.nbytes // size, ref.offset)
180+
181+
182+
def _optional(msg, name: str):
183+
return getattr(msg, name) if msg.HasField(name) else None
184+
185+
186+
# -------------------------------------------------------------- requests ---
187+
188+
189+
def _request(spec: pb.RequestSpec, frames) -> SubmitRequest:
190+
media = ("multimodal_data", "mrope_positions", "cache_seed")
191+
if spec.mrope_position_delta or any(spec.HasField(name) for name in media):
192+
raise FrameError("the Session takes text prompts; this request carries media")
193+
if spec.needs_independent_noise or spec.sibling_index:
194+
raise FrameError("the Session takes n=1; this request is one sibling of n")
195+
prompt = _read(frames, spec, "prompt_token_ids", "<i4")
196+
if (prompt < 0).any():
197+
raise FrameError("prompt token ids must be non-negative")
198+
kv = _value_field(spec, "kv_transfer_params")
199+
if kv is not None and not isinstance(kv, dict):
200+
raise FrameError("kv_transfer_params must be a map")
201+
return SubmitRequest(
202+
seq_id=spec.seq_id,
203+
prompt_token_ids=prompt.tolist(),
204+
sampling_params=_sampling(spec.sampling),
205+
# An empty one would match at once; the HTTP path drops it as well.
206+
stop_token_sequences=[list(s.ids) for s in spec.stop_token_sequences if s.ids],
207+
kv_transfer_params=kv,
208+
request_id=_optional(spec, "external_request_id"),
209+
**{name: _optional(spec, name) for name in _ROUTING},
210+
)
211+
212+
213+
def _sampling(msg: pb.SamplingParams) -> SamplingParams:
214+
"""Absent fields read as the HTTP routes fill omitted ones (max_tokens their
215+
default, logprobs False), and n below 1 as 1, as those routes coerce it."""
216+
stops, which = msg.stop_strings, msg.stop_strings.WhichOneof("value")
217+
stop_strings = None
218+
if which == "single":
219+
stop_strings = stops.single
220+
elif which == "many":
221+
stop_strings = list(stops.many.items)
222+
channel = None
223+
if msg.HasField("required_channel"):
224+
c = msg.required_channel
225+
channel = RequiredChannel(
226+
tuple(c.after), tuple(c.opening), c.opens_at, tuple(c.end_ids)
227+
)
228+
logprobs = msg.WhichOneof("logprobs")
229+
has_max = msg.HasField("max_tokens")
230+
return SamplingParams(
231+
**{name: getattr(msg, name) for name in _DEFAULTED if msg.HasField(name)},
232+
max_tokens=msg.max_tokens if has_max else DEFAULT_MAX_TOKENS,
233+
max_tokens_is_default=msg.max_tokens_is_default or not has_max,
234+
n=max(msg.n, 1),
235+
ignore_eos=msg.ignore_eos,
236+
stop_strings=stop_strings,
237+
logprobs=False if logprobs is None else getattr(msg, logprobs),
238+
required_channel=channel,
239+
top_logprobs=msg.top_logprobs,
240+
json_schema=_optional(msg, "json_schema"),
241+
structured_tool_format=_optional(msg, "structured_tool_format"),
242+
structured_reasoning_end=msg.structured_reasoning_end,
243+
)
244+
245+
246+
# --------------------------------------------------------------- outputs ---
247+
248+
249+
def _put_records(entry: int, records, msg: pb.StreamBatch, floats, ints) -> None:
250+
"""An entry's TokenLogprob records, (logprob, rank, id_0, logprob_0, ...)."""
251+
width = (len(records[0]) - 2) // 2 if records else 0
252+
for record in records:
253+
if len(record) != 2 * width + 2:
254+
raise FrameError(f"entry {entry}'s logprob records differ in width")
255+
floats += (record[0], *record[3::2])
256+
ints += (record[1], *record[2::2])
257+
msg.logprob_entries.append(entry)
258+
msg.logprob_counts.append(len(records))
259+
msg.logprob_widths.append(width)
260+
261+
262+
# ---------------------------------------------------------------- values ---
263+
264+
265+
def _put_value(value, msg: pb.Value) -> None:
266+
"""A JSON-shaped value; tuples go as lists, as json.dumps writes them."""
267+
if value is None:
268+
msg.null_value = True
269+
elif isinstance(value, bool):
270+
msg.bool_value = value
271+
elif isinstance(value, int):
272+
msg.int_value = value
273+
elif isinstance(value, float):
274+
msg.float_value = value
275+
elif isinstance(value, str):
276+
msg.string_value = value
277+
elif isinstance(value, (list, tuple)):
278+
msg.list_value.SetInParent()
279+
for item in value:
280+
_put_value(item, msg.list_value.items.add())
281+
elif isinstance(value, dict) and all(isinstance(key, str) for key in value):
282+
msg.map_value.SetInParent()
283+
for key, item in value.items():
284+
entry = msg.map_value.entries.add()
285+
entry.key.string_value = key
286+
_put_value(item, entry.value)
287+
else:
288+
raise TypeError(f"{value!r} is not JSON-shaped")
289+
290+
291+
def _get_value(msg: pb.Value):
292+
"""`msg`'s JSON-shaped value; bytes, tuples, tensors and pickles are refused."""
293+
kind = msg.WhichOneof("kind")
294+
if kind == "null_value":
295+
return None
296+
if kind in ("bool_value", "int_value", "float_value", "string_value"):
297+
return getattr(msg, kind)
298+
if kind == "list_value":
299+
return [_get_value(item) for item in msg.list_value.items]
300+
if kind == "map_value":
301+
entries = msg.map_value.entries
302+
if all(e.key.HasField("string_value") for e in entries):
303+
return {e.key.string_value: _get_value(e.value) for e in entries}
304+
raise FrameError(f"a Value of kind {kind} is not JSON-shaped")
305+
306+
307+
def _value_field(parent, name: str):
308+
return _get_value(getattr(parent, name)) if parent.HasField(name) else None

0 commit comments

Comments
 (0)