|
| 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