Skip to content

Commit fac502c

Browse files
junyyang-amdclaude
andcommitted
E/P/D: reach image embeddings through atom.ec_transfer
Review follow-up on top of #3411's interface. - ModelRunner builds the reader for a handle's "transport" through create_reader on first use, passing this server's kv_transfer_config. A reader that cannot start (unknown transport, Mooncake missing, engine or memory failure) is recorded as None and the ranks run the vision tower, the same as a failed read; P on MoRI KV no longer needs Mooncake. - The encoder-only server stores through create_writer("mooncake"); the API catches EcStoreFull. - --accept-ec-transfer-params: P takes a chat request's ec_transfer_params only when started with it, and drops them otherwise (warning once). Only a router that runs E and strips client-sent params (ATOMesh) should face a P started with it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 42b8e7a commit fac502c

5 files changed

Lines changed: 206 additions & 97 deletions

File tree

‎atom/entrypoints/openai/api_server.py‎

Lines changed: 37 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,11 @@
218218
engine = None
219219
# `EncoderOnly` under --encoder-only, which builds no engine.
220220
encoder = None
221+
# --accept-ec-transfer-params: a chat request's `ec_transfer_params` names
222+
# where this prefill server reads its image embeddings. Off, they are dropped:
223+
# only a router that runs the encoder (ATOMesh) may set them.
224+
accept_ec_transfer_params = False
225+
_warned_ec_transfer_params = False
221226
tokenizer: AutoTokenizer | None = None
222227
# The tool-call format this model emits, resolved once at startup from its
223228
# chat template. `None` means none was recognised and tool calls, if any, are
@@ -2335,8 +2340,12 @@ async def _chat_completions(
23352340
request_id, len(prompt_or_tokens), multimodal_data
23362341
)
23372342
if request.ec_transfer_params is not None:
2338-
# The prefill encode reads these rows instead of running the tower.
2339-
multimodal_data["ec_transfer_params"] = request.ec_transfer_params
2343+
if accept_ec_transfer_params:
2344+
# The prefill encode reads these rows instead of running
2345+
# the tower.
2346+
multimodal_data["ec_transfer_params"] = request.ec_transfer_params
2347+
else:
2348+
_warn_ec_transfer_params_dropped()
23402349
elif pretokenized is not None:
23412350
# Reuse prefill IDs to skip template rendering and tokenization.
23422351
prompt_or_tokens = pretokenized
@@ -2592,15 +2601,26 @@ async def _chat_completions(
25922601
raise HTTPException(status_code=500, detail=str(e)) from e
25932602

25942603

2604+
def _warn_ec_transfer_params_dropped() -> None:
2605+
global _warned_ec_transfer_params
2606+
if not _warned_ec_transfer_params:
2607+
_warned_ec_transfer_params = True
2608+
logger.warning(
2609+
"Dropping ec_transfer_params: start the server with "
2610+
"--accept-ec-transfer-params to read image embeddings from an "
2611+
"encoder server"
2612+
)
2613+
2614+
25952615
async def _encoder_only_response(
25962616
request_id: str, num_prompt_tokens: int, multimodal_data: dict[str, Any]
25972617
) -> JSONResponse:
25982618
"""No choices: where the prefill server reads the image embeddings."""
2599-
from atom.kv_transfer.disaggregation.mooncake.ec_transport import EcPoolFull
2619+
from atom.ec_transfer import EcStoreFull
26002620

26012621
try:
26022622
params = await encoder.encode(multimodal_data)
2603-
except EcPoolFull as e:
2623+
except EcStoreFull as e:
26042624
# The router sends the request on without these, and prefill encodes.
26052625
logger.warning("Embedding pool full for %s: %s", request_id, e)
26062626
return JSONResponse(
@@ -3950,6 +3970,17 @@ def main():
39503970
"concurrency). 1 serves everything in one process."
39513971
),
39523972
)
3973+
parser.add_argument(
3974+
"--accept-ec-transfer-params",
3975+
action="store_true",
3976+
help=(
3977+
"Read a chat request's image embeddings from the encoder server its "
3978+
"ec_transfer_params name (E/P/D prefill). Set it only where clients "
3979+
"cannot reach this server except through a router that runs the "
3980+
"encoder and replaces any client-sent ec_transfer_params (ATOMesh); "
3981+
"without it they are dropped and this server encodes images itself."
3982+
),
3983+
)
39533984
parser.add_argument(
39543985
"--request-log",
39553986
type=str,
@@ -4020,7 +4051,8 @@ def _setup_frontend(args) -> None:
40204051
"""Request log, tokenizer, chat template and model name: everything a
40214052
front end needs before the engine exists (shared with front-end workers)."""
40224053
global tokenizer, model_name, default_chat_template_kwargs, _request_logger
4023-
global custom_message_encoder, fim_format
4054+
global custom_message_encoder, fim_format, accept_ec_transfer_params
4055+
accept_ec_transfer_params = getattr(args, "accept_ec_transfer_params", False)
40244056
if args.request_log:
40254057
_request_logger = logging.getLogger("atom.request_log")
40264058
_request_logger.setLevel(logging.INFO)

‎atom/model_engine/encoder_only.py‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,9 @@
55
66
The server builds a model's vision modules alone on one GPU and loads their
77
weights, skipping the language model's. Each image request is encoded on one
8-
thread, in arrival order, into an ``EcPool`` that a prefill server reads; the
9-
chat handler answers with the pool's ``ec_transfer_params``.
8+
thread, in arrival order, into an ``atom.ec_transfer`` writer (Mooncake) that
9+
a prefill server reads; the chat handler answers with the writer's handle as
10+
``ec_transfer_params``.
1011
"""
1112

1213
import asyncio
@@ -102,7 +103,7 @@ def __init__(
102103
self,
103104
config: Config,
104105
encoder: nn.Module,
105-
pool: Any,
106+
pool: Any, # an atom.ec_transfer.EcWriter
106107
device: torch.device | str,
107108
) -> None:
108109
self.config = config
@@ -114,7 +115,7 @@ def __init__(
114115

115116
async def encode(self, data: dict[str, Any]) -> dict[str, Any]:
116117
"""``ec_transfer_params`` for ``data`` as ``_prepare_multimodal_inputs``
117-
built it. Raises ``EcPoolFull`` when the pool has no room past its
118+
built it. Raises ``EcStoreFull`` when the pool has no room past its
118119
leases."""
119120
loop = asyncio.get_running_loop()
120121
return await loop.run_in_executor(self._thread, self._encode, data)
@@ -140,7 +141,7 @@ def close(self) -> None:
140141
def create_encoder_only(config: Config) -> EncoderOnly:
141142
"""Build and load the vision modules on GPU 0, then give the pool what
142143
``gpu_memory_utilization`` of the GPU leaves."""
143-
from atom.kv_transfer.disaggregation.mooncake.ec_transport import EcPool
144+
from atom.ec_transfer import create_writer
144145

145146
arch = config.hf_config.architectures[0]
146147
build = VISION_BUILDERS.get(arch)
@@ -171,4 +172,6 @@ def create_encoder_only(config: Config) -> EncoderOnly:
171172
f"{total >> 20} MiB are in use after the vision modules"
172173
)
173174
logger.info("Encoder-only: %d MiB embedding pool", pool_bytes >> 20)
174-
return EncoderOnly(config, encoder, EcPool(pool_bytes, device), device)
175+
return EncoderOnly(
176+
config, encoder, create_writer("mooncake", pool_bytes, device), device
177+
)

‎atom/model_engine/model_runner.py‎

Lines changed: 42 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -876,8 +876,9 @@ def __init__(self, rank: int, config: Config):
876876
from atom.model_engine.multimodal_runtime import VisionEmbeddingCache
877877

878878
self.vision_embeddings = VisionEmbeddingCache()
879-
# Reads an encoder server's image embeddings; built on first use.
880-
self.ec_reader = None
879+
# Readers of an encoder server's image embeddings, one per transport,
880+
# built on first use; None where the transport cannot start here.
881+
self.ec_readers = {}
881882
self.mark_trace = getattr(config, "mark_trace", False)
882883
from atom.utils.graph_marker import set_graph_marker_enabled
883884

@@ -1211,25 +1212,48 @@ def _get_cumsum_and_arange(
12111212

12121213
return cu_num_tokens, arange
12131214

1214-
def read_image_embeddings(self, params, cache_seed, dtype):
1215-
"""The rows an encoder server stored for ``cache_seed``, or None when
1216-
this rank must run its own vision tower."""
1217-
if self.ec_reader is None:
1218-
from atom.kv_transfer.disaggregation.mooncake.ec_transport import (
1219-
EcReader,
1220-
)
1215+
def _ec_reader(self, handle, dtype):
1216+
"""This rank's reader for ``handle``'s transport, built on first use,
1217+
or None where it cannot start: this rank then encodes the images."""
1218+
transport = handle.get("transport") if isinstance(handle, dict) else None
1219+
if not isinstance(transport, str):
1220+
return None
1221+
if transport not in self.ec_readers:
1222+
from atom.ec_transfer import create_reader
12211223

12221224
# Sized for the first request's rows and grown on demand: a
12231225
# buffer for the longest prompt is 12 GiB at MiniMax-M3's 1M
12241226
# context, allocated outside the KV cache's share of the GPU. A
12251227
# request's image rows never outnumber its prompt's tokens.
1226-
max_bytes = self.config.max_model_len * (
1227-
self.config.hf_config.hidden_size * dtype.itemsize
1228-
)
1229-
self.ec_reader = EcReader(
1230-
min(params["length"], max_bytes), self.device, max_bytes=max_bytes
1231-
)
1232-
rows = self.ec_reader.read(params, cache_seed, dtype)
1228+
row_bytes = self.config.hf_config.hidden_size * dtype.itemsize
1229+
max_bytes = self.config.max_model_len * row_bytes
1230+
rows = handle.get("rows")
1231+
first = rows * row_bytes if type(rows) is int and rows > 0 else row_bytes
1232+
try:
1233+
self.ec_readers[transport] = create_reader(
1234+
transport,
1235+
min(first, max_bytes),
1236+
self.device,
1237+
max_bytes=max_bytes,
1238+
kv_transfer_config=getattr(self.config, "kv_transfer_config", None),
1239+
)
1240+
# Unknown transport (ValueError), missing library (RuntimeError,
1241+
# ImportError), or no memory or HCA for the engine (RuntimeError).
1242+
except (ImportError, OSError, RuntimeError, ValueError) as e:
1243+
logger.warning(
1244+
"Cannot read image embeddings over %r here (%s); "
1245+
"this server runs the vision tower for them",
1246+
transport,
1247+
e,
1248+
)
1249+
self.ec_readers[transport] = None
1250+
return self.ec_readers[transport]
1251+
1252+
def read_image_embeddings(self, handle, cache_seed, dtype):
1253+
"""The rows an encoder server stored for ``cache_seed``, or None when
1254+
this rank must run its own vision tower."""
1255+
reader = self._ec_reader(handle, dtype)
1256+
rows = None if reader is None else reader.get(handle, cache_seed, dtype)
12331257
# Every rank of the forward takes E's rows, or none does: E's rows and
12341258
# a rank's own tower's need not be bit-identical, and mixing them
12351259
# would split the ranks' activations. Each rank reaches this call for
@@ -1239,8 +1263,8 @@ def read_image_embeddings(self, params, cache_seed, dtype):
12391263
agreed = group_agree(agreed, group)
12401264
if not agreed:
12411265
logger.warning(
1242-
"Image embeddings from %s are unavailable%s; running the vision tower",
1243-
params["session"],
1266+
"Image embeddings over %r are unavailable%s; running the vision tower",
1267+
handle.get("transport") if isinstance(handle, dict) else None,
12441268
"" if rows is None else " on another rank",
12451269
)
12461270
return None

‎tests/test_encoder_only.py‎

Lines changed: 8 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,8 @@
99
import ctypes
1010
import io
1111
import sys
12-
import types
1312
from types import SimpleNamespace
1413
from typing import ClassVar
15-
from unittest.mock import MagicMock
1614

1715
import httpx
1816
import pytest
@@ -21,24 +19,7 @@
2119
from safetensors.torch import save_file
2220
from torch import nn
2321

24-
# The pool's module imports the KV connector, which imports aiter's parallel
25-
# state: stub what a CPU runner lacks, as tests/test_ec_transport.py does.
26-
_stubbed = []
27-
for _name in ("aiter", "aiter.dist", "aiter.dist.parallel_state"):
28-
if _name not in sys.modules:
29-
sys.modules[_name] = types.ModuleType(_name)
30-
sys.modules[_name].__path__ = []
31-
_stubbed.append(_name)
32-
for _fn in ("get_dp_group", "get_tp_group"):
33-
if not hasattr(sys.modules["aiter.dist.parallel_state"], _fn):
34-
setattr(sys.modules["aiter.dist.parallel_state"], _fn, MagicMock())
35-
36-
from atom.kv_transfer.disaggregation.mooncake import ec_transport as ec
37-
from atom.kv_transfer.disaggregation.mooncake import mooncake_connector as mc
38-
39-
if "aiter" in _stubbed:
40-
del sys.modules["aiter"]
41-
22+
from atom.ec_transfer import mooncake as ec
4223
from atom.entrypoints.openai import api_server
4324
from atom.model_engine import encoder_only
4425
from atom.model_engine.arg_utils import EngineArgs
@@ -102,9 +83,9 @@ def _encoder():
10283
def server(monkeypatch):
10384
"""An encoder-only app; the model's processor returns two images' spans."""
10485
sessions = {}
105-
monkeypatch.setattr(mc, "_MOONCAKE_AVAILABLE", True)
86+
monkeypatch.setattr(ec, "MOONCAKE_AVAILABLE", True)
10687
monkeypatch.setattr(
107-
mc, "TransferEngine", lambda: FakeEngine(sessions), raising=False
88+
ec, "TransferEngine", lambda: FakeEngine(sessions), raising=False
10889
)
10990
monkeypatch.setattr(ec, "get_ip", lambda: "192.0.2.7")
11091
monkeypatch.setenv("ATOM_MOONCAKE_IB_DEVICE", "rocep139s0")
@@ -130,7 +111,7 @@ def fake_prepare(_config, _processor, conversation, media, _kwargs, tools=None):
130111
)
131112

132113
def make(pool_bytes=1 << 16, encoder=None):
133-
pool = ec.EcPool(pool_bytes, "cpu")
114+
pool = ec.MooncakeEcWriter(pool_bytes, "cpu")
134115
server_encoder = encoder_only.EncoderOnly(
135116
config, encoder or _encoder(), pool, "cpu"
136117
)
@@ -187,11 +168,12 @@ def test_two_image_request_answers_with_ec_transfer_params(server):
187168
_conversation, media, data = server.prepared[0]
188169
assert len(media["image"]) == 2
189170
assert params["rows"] == sum(count for _, count in SPANS)
190-
assert params["cache_seed"] == multimodal_cache_seed(data)
171+
assert params["transport"] == "mooncake"
172+
assert params["key"] == multimodal_cache_seed(data)
191173

192174
# The pool holds the tower's output for P to read.
193-
reader = ec.EcReader(1 << 12, "cpu")
194-
rows = reader.read(params, params["cache_seed"], torch.float32)
175+
reader = ec.MooncakeEcReader(1 << 12, "cpu")
176+
rows = reader.get(params, params["key"], torch.float32)
195177
assert torch.equal(rows, data["pixel_values"] * 2)
196178

197179

0 commit comments

Comments
 (0)