From 844bea3400f477dcddd0a2355bfda52592fe642f Mon Sep 17 00:00:00 2001 From: chenht2022 Date: Sun, 28 Jun 2026 13:49:04 +0000 Subject: [PATCH 1/7] feat(disaggregation): add EPD encode pipeline Add embedding disaggregation runtime support for encode workers, transfer, scheduling, and prefill receive. Restructure disaggregation helpers into base/kv/embedding modules and add runtime coverage for EPD encode transfers. Signed-off-by: chenht2022 --- python/tokenspeed/runtime/cache/__init__.py | 3 +- .../runtime/cache/embedding_cache.py | 224 ++++ .../tokenspeed/runtime/cache/prefix_cache.py | 2 +- .../runtime/configs/model_config.py | 24 + .../runtime/disaggregation/base/__init__.py | 38 + .../base/bootstrap.py} | 141 +-- .../runtime/disaggregation/base/manager.py | 102 ++ .../base/poll.py} | 26 +- .../embedding}/__init__.py | 17 +- .../runtime/disaggregation/embedding/conn.py | 100 ++ .../embedding/embedding_transfer.py | 893 ++++++++++++++ .../embedding/encode_executor.py | 377 ++++++ .../disaggregation/embedding/encode_loop.py | 324 +++++ .../embedding/encode_scheduler.py | 114 ++ .../disaggregation/embedding/encode_worker.py | 192 +++ .../embedding/prefill_receiver.py | 1057 +++++++++++++++++ .../base => disaggregation/kv}/__init__.py | 19 +- .../kv}/decode_executor.py | 34 +- .../kv/decode_scheduler.py} | 2 +- .../{pd => disaggregation/kv}/factory.py | 16 +- .../{pd => disaggregation/kv}/kv_events.py | 0 .../kv}/mooncake/__init__.py | 10 +- .../kv}/mooncake/async_conn.py | 22 +- .../disaggregation/kv/mooncake/conn.py | 126 ++ .../kv}/mooncake/decode.py | 38 +- .../kv}/mooncake/entities.py | 4 +- .../kv}/mooncake/prefill.py | 106 +- .../kv}/mooncake/receiver.py | 36 +- .../kv}/mooncake/sender.py | 24 +- .../kv}/prefill_executor.py | 41 +- .../kv}/transfer_plan.py | 0 .../conn.py => disaggregation/kv/types.py} | 30 +- .../{pd => disaggregation/kv}/utils.py | 71 +- .../mooncake_transfer_engine.py} | 0 .../runtime/disaggregation/utils.py | 67 ++ python/tokenspeed/runtime/engine/async_llm.py | 25 +- .../tokenspeed/runtime/engine/event_loop.py | 284 ++++- .../runtime/engine/request_handler.py | 2 +- .../runtime/engine/schedule_batch.py | 8 +- .../runtime/engine/scheduler_utils.py | 3 +- .../runtime/execution/model_executor.py | 15 +- .../runtime/layers/attention/backends/base.py | 2 +- .../runtime/models/base/causal_lm.py | 17 +- python/tokenspeed/runtime/models/kimi_k25.py | 6 +- python/tokenspeed/runtime/models/qwen3_5.py | 21 +- .../tokenspeed/runtime/multimodal/inputs.py | 8 + python/tokenspeed/runtime/pd/common/conn.py | 627 ---------- python/tokenspeed/runtime/pd/fake/conn.py | 141 --- python/tokenspeed/runtime/utils/env.py | 1 + .../tokenspeed/runtime/utils/server_args.py | 17 +- test/runtime/cache/test_embedding_cache.py | 120 ++ test/runtime/distributed/test_epd_encode.py | 549 +++++++++ test/runtime/distributed/test_epd_transfer.py | 592 +++++++++ .../distributed/test_pd_transfer_plan.py | 6 +- test/runtime/test_kv_events.py | 2 +- .../csrc/fsm/forward_events.cpp | 8 + 56 files changed, 5551 insertions(+), 1183 deletions(-) create mode 100644 python/tokenspeed/runtime/cache/embedding_cache.py create mode 100644 python/tokenspeed/runtime/disaggregation/base/__init__.py rename python/tokenspeed/runtime/{pd/mooncake/conn.py => disaggregation/base/bootstrap.py} (55%) create mode 100644 python/tokenspeed/runtime/disaggregation/base/manager.py rename python/tokenspeed/runtime/{pd/common/__init__.py => disaggregation/base/poll.py} (62%) mode change 100755 => 100644 rename python/tokenspeed/runtime/{pd/fake => disaggregation/embedding}/__init__.py (59%) mode change 100755 => 100644 create mode 100644 python/tokenspeed/runtime/disaggregation/embedding/conn.py create mode 100644 python/tokenspeed/runtime/disaggregation/embedding/embedding_transfer.py create mode 100644 python/tokenspeed/runtime/disaggregation/embedding/encode_executor.py create mode 100644 python/tokenspeed/runtime/disaggregation/embedding/encode_loop.py create mode 100644 python/tokenspeed/runtime/disaggregation/embedding/encode_scheduler.py create mode 100644 python/tokenspeed/runtime/disaggregation/embedding/encode_worker.py create mode 100644 python/tokenspeed/runtime/disaggregation/embedding/prefill_receiver.py rename python/tokenspeed/runtime/{pd/base => disaggregation/kv}/__init__.py (72%) mode change 100755 => 100644 rename python/tokenspeed/runtime/{pd => disaggregation/kv}/decode_executor.py (87%) rename python/tokenspeed/runtime/{pd/disaggregation_decode_scheduler.py => disaggregation/kv/decode_scheduler.py} (99%) rename python/tokenspeed/runtime/{pd => disaggregation/kv}/factory.py (91%) rename python/tokenspeed/runtime/{pd => disaggregation/kv}/kv_events.py (100%) rename python/tokenspeed/runtime/{pd => disaggregation/kv}/mooncake/__init__.py (77%) rename python/tokenspeed/runtime/{pd => disaggregation/kv}/mooncake/async_conn.py (96%) create mode 100644 python/tokenspeed/runtime/disaggregation/kv/mooncake/conn.py rename python/tokenspeed/runtime/{pd => disaggregation/kv}/mooncake/decode.py (92%) rename python/tokenspeed/runtime/{pd => disaggregation/kv}/mooncake/entities.py (98%) rename python/tokenspeed/runtime/{pd => disaggregation/kv}/mooncake/prefill.py (91%) rename python/tokenspeed/runtime/{pd => disaggregation/kv}/mooncake/receiver.py (96%) rename python/tokenspeed/runtime/{pd => disaggregation/kv}/mooncake/sender.py (91%) rename python/tokenspeed/runtime/{pd => disaggregation/kv}/prefill_executor.py (88%) rename python/tokenspeed/runtime/{pd => disaggregation/kv}/transfer_plan.py (100%) rename python/tokenspeed/runtime/{pd/base/conn.py => disaggregation/kv/types.py} (80%) mode change 100755 => 100644 rename python/tokenspeed/runtime/{pd => disaggregation/kv}/utils.py (93%) rename python/tokenspeed/runtime/{pd/mooncake/transfer_engine.py => disaggregation/mooncake_transfer_engine.py} (100%) create mode 100644 python/tokenspeed/runtime/disaggregation/utils.py delete mode 100755 python/tokenspeed/runtime/pd/common/conn.py delete mode 100755 python/tokenspeed/runtime/pd/fake/conn.py create mode 100644 test/runtime/cache/test_embedding_cache.py create mode 100644 test/runtime/distributed/test_epd_encode.py create mode 100644 test/runtime/distributed/test_epd_transfer.py diff --git a/python/tokenspeed/runtime/cache/__init__.py b/python/tokenspeed/runtime/cache/__init__.py index aeb9caeec9d..11e4a02b105 100644 --- a/python/tokenspeed/runtime/cache/__init__.py +++ b/python/tokenspeed/runtime/cache/__init__.py @@ -21,5 +21,6 @@ """Runtime cache subsystem. This package groups KV cache data structures, allocators, storage backends, -and cache-operation executors under one top-level domain. +and cache-operation executors under one top-level domain. It also holds the +vision-embedding cache used by the EPD encode stage (:mod:`embedding_cache`). """ diff --git a/python/tokenspeed/runtime/cache/embedding_cache.py b/python/tokenspeed/runtime/cache/embedding_cache.py new file mode 100644 index 00000000000..61c7e370b85 --- /dev/null +++ b/python/tokenspeed/runtime/cache/embedding_cache.py @@ -0,0 +1,224 @@ +# Copyright (c) 2026 LightSeek Foundation +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +from __future__ import annotations + +"""Vision-embedding cache for the EPD encode stage. + +The encode server runs the vision tower only; a cache lets duplicate images +(same ``MultimodalDataItem.hash``) reuse a previously computed embedding instead +of re-running the tower. + +Two interchangeable implementations share a ``get`` / ``put`` surface: +:class:`EmbeddingCache` (single-tier, bytes-bounded LRU) and +:class:`TieredEmbeddingCache` (L1 GPU VRAM + L2 host DRAM). Both are +framework-agnostic and unit-testable without a GPU -- the caller supplies byte +sizes and the device<->host copies are injectable. +""" + +import collections +from typing import Callable, Hashable, Optional, Tuple + + +class EmbeddingCache: + """Bytes-bounded LRU cache of vision-tower outputs, keyed by content hash. + + Values are opaque (typically a ``torch.Tensor``); the caller supplies the + byte size so this stays framework-agnostic and testable without a GPU. + + ``on_evict`` is an optional ``(key, value, nbytes)`` callback fired only for + an entry dropped by capacity overflow (not an update to an existing key, + which is an in-place replace, nor an explicit :meth:`pop`). It lets a second + tier capture LRU victims and demote them (see :class:`TieredEmbeddingCache`). + """ + + def __init__( + self, + capacity_bytes: int, + on_evict: Optional[Callable[[Hashable, object, int], None]] = None, + ): + if capacity_bytes < 0: + raise ValueError(f"capacity_bytes must be >= 0, got {capacity_bytes}") + self.capacity_bytes = capacity_bytes + self._on_evict = on_evict + # key -> (value, nbytes); ordered by recency (oldest first). + self._store: "collections.OrderedDict[Hashable, Tuple[object, int]]" = ( + collections.OrderedDict() + ) + self._cur_bytes = 0 + self.hits = 0 + self.misses = 0 + + def get(self, key: Hashable) -> Optional[object]: + entry = self._store.get(key) + if entry is None: + self.misses += 1 + return None + self._store.move_to_end(key) + self.hits += 1 + return entry[0] + + def put(self, key: Hashable, value: object, nbytes: int) -> None: + if nbytes < 0: + raise ValueError(f"nbytes must be >= 0, got {nbytes}") + # An item larger than the whole cache can never be retained; skip it + # rather than evicting everything for a value dropped immediately after. + if nbytes > self.capacity_bytes: + return + existing = self._store.pop(key, None) + if existing is not None: + self._cur_bytes -= existing[1] + self._store[key] = (value, nbytes) + self._cur_bytes += nbytes + self._evict() + + def pop(self, key: Hashable) -> Optional[Tuple[object, int]]: + """Remove ``key`` and return its ``(value, nbytes)``, or ``None`` if + absent. A structural removal: it neither counts as a hit/miss nor fires + ``on_evict`` (the caller is taking ownership of the value, e.g. to + promote it to another tier).""" + existing = self._store.pop(key, None) + if existing is None: + return None + self._cur_bytes -= existing[1] + return existing + + def _evict(self) -> None: + while self._cur_bytes > self.capacity_bytes and self._store: + key, (value, nbytes) = self._store.popitem(last=False) + self._cur_bytes -= nbytes + if self._on_evict is not None: + self._on_evict(key, value, nbytes) + + def __contains__(self, key: Hashable) -> bool: + return key in self._store + + def __len__(self) -> int: + return len(self._store) + + @property + def current_bytes(self) -> int: + return self._cur_bytes + + +def _embedding_to_host(value: object) -> object: + """Default L1->L2 demote: copy a vision embedding from GPU to host memory. + + A cache value is a ``(main, deepstack)`` tuple (deepstack half may be + ``None`` for non-deepstack models) or a bare tensor. + """ + if isinstance(value, tuple): + return tuple(None if t is None else t.cpu() for t in value) + return value.cpu() + + +def _embedding_to_device(value: object, device) -> object: + """Default L2->L1 promote: copy a host-resident embedding back to ``device`` + so the executor can stage it into the GPU send ring.""" + if isinstance(value, tuple): + return tuple(None if t is None else t.to(device) for t in value) + return value.to(device) + + +class TieredEmbeddingCache: + """Two-tier vision-embedding cache: L1 in GPU VRAM, L2 in host DRAM. + + Exposes the same ``get`` / ``put`` surface as :class:`EmbeddingCache`, so the + encode worker uses either interchangeably. L2 catches L1's LRU victims in + cheaper host DRAM: a hit there skips the (much more expensive) ViT and only + pays a host->device copy. + + Tiers are kept *exclusive* -- a key lives in exactly one. An L1 eviction + demotes the victim to L2 (device->host copy); an L2 hit promotes the entry + back to L1 (host->device copy) and removes it from L2; ``put`` always lands + in L1 and drops any stale L2 duplicate. No distributed L3: image-hash routing + pins each image to one worker, so a per-worker local cache captures the reuse. + + The device<->host copies are injectable (``to_host`` / ``to_device``) so the + tiering logic is unit-testable without a GPU; the defaults copy real tensors + to/from ``device``. + """ + + def __init__( + self, + l1_capacity_bytes: int, + l2_capacity_bytes: int, + *, + device: object = None, + to_host: Optional[Callable[[object], object]] = None, + to_device: Optional[Callable[[object], object]] = None, + ): + # L1 demotes its evictions into L2 via the on_evict hook; L2 is the + # bottom tier (no hook), so its evictions are true drops -- no recursion. + self.l1 = EmbeddingCache(l1_capacity_bytes, on_evict=self._demote) + self.l2 = EmbeddingCache(l2_capacity_bytes) + self._device = device + self._to_host = to_host or _embedding_to_host + self._to_device = to_device or (lambda v: _embedding_to_device(v, self._device)) + self.l1_hits = 0 + self.l2_hits = 0 + self.misses = 0 + self.promotions = 0 + self.demotions = 0 + + def get(self, key: Hashable) -> Optional[object]: + value = self.l1.get(key) + if value is not None: + self.l1_hits += 1 + return value + promoted = self.l2.pop(key) + if promoted is None: + self.misses += 1 + return None + host_value, nbytes = promoted + device_value = self._to_device(host_value) + self.l2_hits += 1 + self.promotions += 1 + # Re-home as MRU in L1. May evict colder L1 entries, which demote to L2; + # the just-promoted key is MRU so it is never the victim. + self.l1.put(key, device_value, nbytes) + return device_value + + def put(self, key: Hashable, value: object, nbytes: int) -> None: + # L1 is the write tier. Drop any stale L2 copy first so the tiers stay + # exclusive (e.g. a key demoted earlier and now re-encoded on a miss). + self.l2.pop(key) + self.l1.put(key, value, nbytes) + + def _demote(self, key: Hashable, value: object, nbytes: int) -> None: + """L1 eviction hook: stash the victim in host DRAM instead of dropping + it. host nbytes == device nbytes (same dtype/numel). A victim larger than + all of L2 is silently dropped by ``L2.put`` (same as having no L2).""" + # Skip the wasted device->host copy for a victim L2 would just drop. + if nbytes > self.l2.capacity_bytes: + return + self.l2.put(key, self._to_host(value), nbytes) + if key in self.l2: + self.demotions += 1 + + @property + def hits(self) -> int: + return self.l1_hits + self.l2_hits + + def __contains__(self, key: Hashable) -> bool: + return key in self.l1 or key in self.l2 + + def __len__(self) -> int: + return len(self.l1) + len(self.l2) diff --git a/python/tokenspeed/runtime/cache/prefix_cache.py b/python/tokenspeed/runtime/cache/prefix_cache.py index 614a21876f7..fbdfe57d80d 100755 --- a/python/tokenspeed/runtime/cache/prefix_cache.py +++ b/python/tokenspeed/runtime/cache/prefix_cache.py @@ -54,7 +54,7 @@ # Import KV events classes if needed try: - from tokenspeed.runtime.pd.kv_events import ( + from tokenspeed.runtime.disaggregation.kv.kv_events import ( AllBlocksCleared, BlockRemoved, BlockStored, diff --git a/python/tokenspeed/runtime/configs/model_config.py b/python/tokenspeed/runtime/configs/model_config.py index 1572a672904..7b5beccc5ea 100644 --- a/python/tokenspeed/runtime/configs/model_config.py +++ b/python/tokenspeed/runtime/configs/model_config.py @@ -348,6 +348,30 @@ def __init__( ) # ``is_multimodal`` is the architectural fact; this is the runtime gate. self.is_multimodal_active = self.is_multimodal and not apply_language_model_only + # Vision-only role (EPD encode): the inverse axis of language_model_only. + # Build the vision tower (is_multimodal_active stays True) but SKIP LM + # construction + LM weight load so a full ViT fits at encode TP=1. + encoder_only = ( + getattr(server_args, "disaggregation_mode", None) == "encode" + and not is_draft_worker + ) + if encoder_only and not self.is_multimodal: + raise ValueError( + "disaggregation_mode=encode requires a multimodal checkpoint." + ) + if encoder_only and apply_language_model_only: + raise ValueError( + "disaggregation_mode=encode (encoder-only) and language_model_only " + "are mutually exclusive." + ) + if encoder_only: + # Single model-facing gate: Kimi reads hf_config.encoder_only directly; + # Qwen3_5ForConditionalGeneration reads it to skip LM construction. + self.hf_config.encoder_only = True + logger.info( + "Running in encoder-only mode: the language model will not " + "be constructed or loaded (encode role)." + ) # Cap gpu_memory_utilization for VLMs in mm mode — the vision encoder # needs headroom that the global default doesn't account for. if ( diff --git a/python/tokenspeed/runtime/disaggregation/base/__init__.py b/python/tokenspeed/runtime/disaggregation/base/__init__.py new file mode 100644 index 00000000000..15a14313374 --- /dev/null +++ b/python/tokenspeed/runtime/disaggregation/base/__init__.py @@ -0,0 +1,38 @@ +# Copyright (c) 2026 LightSeek Foundation +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +"""Role-neutral transport substrate shared by the disaggregation transfer roles. + +Both the KV (prefill->decode) and the embedding (encode->prefill) paths ship +bytes over the same Mooncake RDMA engine and rendezvous through the same HTTP +bootstrap protocol, so the mechanical (semantics-free) plumbing lives here once +and both roles compose it: + + :mod:`poll` the :class:`TransferPoll` transfer-status FSM constants + :mod:`manager` :class:`DisaggManagerBase` -- engine + ZMQ control socket + + room-keyed monotonic, Failed-sticky status tracking + :mod:`bootstrap` :class:`DisaggBootstrapServer` -- the aiohttp rendezvous + server (PUT register / GET lookup + dp-group sharding) + +The role-specific *semantics* (the buffer/arg shapes, the wire frames, the +senders/receivers) stay in :mod:`...kv` and :mod:`...embedding`; this layer +carries no KV/MLA/embedding fields, so the two paths still evolve independently. +Import entry points from the submodules directly. +""" diff --git a/python/tokenspeed/runtime/pd/mooncake/conn.py b/python/tokenspeed/runtime/disaggregation/base/bootstrap.py similarity index 55% rename from python/tokenspeed/runtime/pd/mooncake/conn.py rename to python/tokenspeed/runtime/disaggregation/base/bootstrap.py index 6cd9224967e..bf0709cc331 100644 --- a/python/tokenspeed/runtime/pd/mooncake/conn.py +++ b/python/tokenspeed/runtime/disaggregation/base/bootstrap.py @@ -23,132 +23,37 @@ import asyncio import logging import threading -from functools import cache from typing import Dict, Union -import zmq from aiohttp import web -from tokenspeed.runtime.metrics.collector import KVTransferMetrics -from tokenspeed.runtime.pd.base import KVArgs, KVPoll -from tokenspeed.runtime.pd.mooncake.entities import ManagerArgs -from tokenspeed.runtime.pd.mooncake.transfer_engine import ( - MooncakeTransferEngine, -) -from tokenspeed.runtime.pd.utils import DisaggregationMode from tokenspeed.runtime.utils import get_colorful_logger -from tokenspeed.runtime.utils.network import get_local_ip_by_remote logger = get_colorful_logger(__name__) -class MooncakeKVManagerBase: - def __init__( - self, - args: ManagerArgs, - kv_args: KVArgs, - disaggregation_mode: DisaggregationMode, - ): - self.args = args - self.kv_args = kv_args - self.attn_tp_rank = args.attn_tp_rank - self.src_mode = "ON" if bool(args.enable_mla_l1_5_cache) else "OFF" - self.is_mla_backend = args.is_mla_backend - self.draft_is_mla_backend = args.draft_is_mla_backend - self.disaggregation_mode = disaggregation_mode - self.bootstrap_port = args.bootstrap_port - self.dist_init_addr = args.dist_init_addr - self.world_size = args.world_size - self.dp_size = args.dp_size - self.attn_dp_rank = args.attn_dp_rank - self.enable_dp_attention = args.enable_dp_attention - if not args.enable_dp_attention and args.dp_size != 1: - raise ValueError( - "If dp_attention is not enabled, dp size must be 1 in disaggregation mode." - ) +class DisaggBootstrapServer: + """HTTP rendezvous server shared by both disaggregation roles. - self.engine = MooncakeTransferEngine( - hostname=get_local_ip_by_remote(), - gpu_id=self.kv_args.gpu_id, - ib_device=self.kv_args.ib_device, - ) + A data-source rank PUTs its (ip, port) keyed by (dp_group, tp_rank_in_dp); + the peer GETs that back to open a Mooncake session, and uses the sentinel + ``engine_rank == -1`` query to sync the source's parallel sizes. The routing, + dp-group sharding, and server lifecycle are role-neutral and live here; + role-specific parallel-info fields (e.g. the KV path's MLA / kv-page lengths) + are layered in by subclasses via :meth:`_ingest_put_extra` (record extra PUT + fields) and :meth:`_extra_parallel_info` (add them to the GET sync response). + """ - if hasattr(args, "enable_metrics") and args.enable_metrics: - labels = { - "model_name": args.served_model_name, - "app_key": args.app_key, - } - self.kv_transfer_metrics = KVTransferMetrics(labels, args.metrics_reporters) - else: - self.kv_transfer_metrics = None - - self.server_socket = zmq.Context().socket(zmq.PULL) - self.register_buffer_to_engine() - - self.rank_port = None - self.request_status: Dict[int, KVPoll] = {} - self.failure_records: Dict[int, str] = {} - self.failure_lock = threading.Lock() - - def register_buffer_to_engine(self): - for kv_data_ptr, kv_data_len in zip( - self.kv_args.kv_data_ptrs, self.kv_args.kv_data_lens - ): - self.engine.register(kv_data_ptr, kv_data_len) - for state_data_ptr, state_data_len in zip( - self.kv_args.state_data_ptrs, self.kv_args.state_data_lens - ): - self.engine.register(state_data_ptr, state_data_len) - - @cache - def _connect(self, endpoint: str): - socket = zmq.Context().socket(zmq.PUSH) - socket.connect(endpoint) - return socket - - def check_status(self, bootstrap_room: int): - return self.request_status[bootstrap_room] - - def update_status(self, bootstrap_room: int, status: KVPoll): - if bootstrap_room not in self.request_status: - self.request_status[bootstrap_room] = status - else: - # status is only allowed to be incremented unless either side has - # observed a failure. Failed is sticky so a late success cannot - # resurrect a broken transfer. - if ( - self.request_status[bootstrap_room] == KVPoll.Failed - or status == KVPoll.Failed - ): - self.request_status[bootstrap_room] = KVPoll.Failed - else: - self.request_status[bootstrap_room] = max( - self.request_status[bootstrap_room], status - ) - - def record_failure(self, bootstrap_room: int, failure_reason: str): - with self.failure_lock: - self.failure_records[bootstrap_room] = failure_reason - - -class MooncakeKVBootstrapServer: def __init__(self, port: int): self.port = port self.app = web.Application() - self.store = dict() self.lock = asyncio.Lock() self._setup_routes() self.world_size = None self.dp_size = None self.tp_size_per_dp_rank = None self.prefill_port_table: Dict[int, Dict[int, Dict[str, Union[str, int]]]] = {} - self.enable_mla_l1_5_cache = False - self.prefill_kv_item_lens = [] - self.prefill_kv_unit_lens = [] - self.prefill_state_item_lens = [] - self.prefill_state_unit_lens = [] - # Start bootstrap server self.thread = threading.Thread(target=self._run_server, daemon=True) self.run() @@ -181,15 +86,7 @@ async def _handle_route_put(self, request: web.Request): rank_ip = data["rank_ip"] rank_port = int(data["rank_port"]) engine_rank = int(data["engine_rank"]) - self.enable_mla_l1_5_cache = bool(data["enable_mla_l1_5_cache"]) - self.prefill_kv_item_lens = data.get("kv_item_lens", self.prefill_kv_item_lens) - self.prefill_kv_unit_lens = data.get("kv_unit_lens", self.prefill_kv_unit_lens) - self.prefill_state_item_lens = data.get( - "state_item_lens", self.prefill_state_item_lens - ) - self.prefill_state_unit_lens = data.get( - "state_unit_lens", self.prefill_state_unit_lens - ) + self._ingest_put_extra(data) if self.world_size is None: self.world_size = world_size @@ -234,12 +131,8 @@ async def _handle_route_get(self, request: web.Request): prefill_parallel_info = { "prefill_tp_size": self.world_size, "prefill_dp_size": self.dp_size, - "enable_mla_l1_5_cache": self.enable_mla_l1_5_cache, - "kv_item_lens": self.prefill_kv_item_lens, - "kv_unit_lens": self.prefill_kv_unit_lens, - "state_item_lens": self.prefill_state_item_lens, - "state_unit_lens": self.prefill_state_unit_lens, } + prefill_parallel_info.update(self._extra_parallel_info()) return web.json_response(prefill_parallel_info, status=200) # Find corresponding prefill info @@ -253,6 +146,14 @@ async def _handle_route_get(self, request: web.Request): else: return web.Response(text="Bootstrap info not Found", status=404) + def _ingest_put_extra(self, data: dict) -> None: + """Record role-specific fields off a register PUT. Default: none.""" + + def _extra_parallel_info(self) -> dict: + """Role-specific fields to merge into the GET parallel-info sync response. + Default: none.""" + return {} + def _run_server(self): try: # Event Loop @@ -285,5 +186,3 @@ def close(self): if self.thread.is_alive(): self.thread.join(timeout=2) logger.info("Server thread stopped") - - def poll(self) -> KVPoll: ... diff --git a/python/tokenspeed/runtime/disaggregation/base/manager.py b/python/tokenspeed/runtime/disaggregation/base/manager.py new file mode 100644 index 00000000000..27ab7648eef --- /dev/null +++ b/python/tokenspeed/runtime/disaggregation/base/manager.py @@ -0,0 +1,102 @@ +# Copyright (c) 2026 LightSeek Foundation +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +from __future__ import annotations + +import threading +from functools import cache +from typing import Dict + +import zmq + +from tokenspeed.runtime.disaggregation.base.poll import TransferPoll + + +class DisaggManagerBase: + """Transfer-engine handle + ZMQ control socket + room-keyed status FSM shared + by the KV (prefill->decode) and embedding (encode->prefill) managers. + + Transport-neutral: the data-plane ``engine`` is constructed by the subclass + and injected here, so this base carries no vendor (Mooncake) binding -- only + the control-plane ZMQ socket and the status FSM. It carries no + KV/MLA/embedding-specific state either; subclasses add their role args/buffers + and implement :meth:`register_buffer_to_engine`. The subclass MUST set the + attributes that :meth:`register_buffer_to_engine` reads (e.g. ``kv_args`` / + ``embedding_args``) BEFORE calling ``super().__init__`` here, because this + constructor registers the buffers as its last engine step. + + ``request_status`` is the room-keyed FSM the senders/receivers poll; + :meth:`update_status` advances it monotonically and makes ``Failed`` sticky + so a late success cannot resurrect a broken transfer. + """ + + def __init__(self, *, engine): + self.engine = engine + self.server_socket = zmq.Context().socket(zmq.PULL) + self.register_buffer_to_engine() + + self.rank_port = None + self.request_status: Dict[int, int] = {} + self.failure_records: Dict[int, str] = {} + self.failure_lock = threading.Lock() + + def register_buffer_to_engine(self): + """Register this role's RDMA buffers with the engine. Abstract.""" + raise NotImplementedError + + def get_session_id(self) -> str: + return self.engine.get_session_id() + + @cache + def _connect(self, endpoint: str): + socket = zmq.Context().socket(zmq.PUSH) + socket.connect(endpoint) + return socket + + def check_status(self, bootstrap_room: int): + """Status of ``bootstrap_room``; raises ``KeyError`` if never seen.""" + return self.request_status[bootstrap_room] + + def room_status(self, bootstrap_room: int): + """Status of ``bootstrap_room``, or ``None`` if unknown -- the non-raising + read for lease/reap probes (an unknown or already-reaped room is a normal + answer rather than a ``KeyError``).""" + return self.request_status.get(bootstrap_room) + + def update_status(self, bootstrap_room: int, status: int): + if bootstrap_room not in self.request_status: + self.request_status[bootstrap_room] = status + else: + # Status is only allowed to be incremented unless either side has + # observed a failure. Failed is sticky so a late success cannot + # resurrect a broken transfer. + if ( + self.request_status[bootstrap_room] == TransferPoll.Failed + or status == TransferPoll.Failed + ): + self.request_status[bootstrap_room] = TransferPoll.Failed + else: + self.request_status[bootstrap_room] = max( + self.request_status[bootstrap_room], status + ) + + def record_failure(self, bootstrap_room: int, failure_reason: str): + with self.failure_lock: + self.failure_records[bootstrap_room] = failure_reason diff --git a/python/tokenspeed/runtime/pd/common/__init__.py b/python/tokenspeed/runtime/disaggregation/base/poll.py old mode 100755 new mode 100644 similarity index 62% rename from python/tokenspeed/runtime/pd/common/__init__.py rename to python/tokenspeed/runtime/disaggregation/base/poll.py index cb2ae722bdd..d4c86c89b7e --- a/python/tokenspeed/runtime/pd/common/__init__.py +++ b/python/tokenspeed/runtime/disaggregation/base/poll.py @@ -18,9 +18,23 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -from tokenspeed.runtime.pd.common.conn import ( - CommonKVBootstrapServer, - CommonKVManager, - CommonKVReceiver, - CommonKVSender, -) +from __future__ import annotations + + +class TransferPoll: + """Transfer-status FSM shared by both disaggregation roles. + + Integer-ordered so :meth:`DisaggManagerBase.update_status` can enforce + monotonic, ``Failed``-sticky transitions via ``max()``. The KV + (prefill->decode) and embedding (encode->prefill) paths use this single + enum; ``WaitingForInput`` is only meaningful to the KV path (the embedding + path never sets it, but sharing one ordered enum keeps the two status FSMs + from drifting apart). + """ + + Failed = 0 + Bootstrapping = 1 + Bootstrapped = 2 + WaitingForInput = 3 + Transferring = 4 + Success = 5 diff --git a/python/tokenspeed/runtime/pd/fake/__init__.py b/python/tokenspeed/runtime/disaggregation/embedding/__init__.py old mode 100755 new mode 100644 similarity index 59% rename from python/tokenspeed/runtime/pd/fake/__init__.py rename to python/tokenspeed/runtime/disaggregation/embedding/__init__.py index f7032e037f2..48143b63971 --- a/python/tokenspeed/runtime/pd/fake/__init__.py +++ b/python/tokenspeed/runtime/disaggregation/embedding/__init__.py @@ -18,8 +18,15 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -from tokenspeed.runtime.pd.fake.conn import ( - FakeKVManager, - FakeKVReceiver, - FakeKVSender, -) +"""EPD embedding (encode->prefill) disaggregation. + +The encode role runs the vision tower only and ships image embeddings over the +Mooncake RDMA engine; the prefill role receives them and skips the tower. The +role-neutral transport substrate (the :class:`...base.poll.TransferPoll` status FSM, the +manager base, the bootstrap server) is shared from :mod:`...disaggregation.base`; +:mod:`conn` layers the embedding buffer args onto it and :mod:`embedding_transfer` +adds the wire frames and senders/receivers. The encode side lives in +:mod:`encode_loop` (entry point), :mod:`encode_worker`, :mod:`encode_scheduler`, +and :mod:`encode_executor`; the prefill side in :mod:`prefill_receiver`. Import +entry points from those submodules directly. +""" diff --git a/python/tokenspeed/runtime/disaggregation/embedding/conn.py b/python/tokenspeed/runtime/disaggregation/embedding/conn.py new file mode 100644 index 00000000000..3dd02084095 --- /dev/null +++ b/python/tokenspeed/runtime/disaggregation/embedding/conn.py @@ -0,0 +1,100 @@ +# Copyright (c) 2026 LightSeek Foundation +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +from __future__ import annotations + +"""Embedding-role transport substrate for EPD (encode -> prefill). + +The mechanical plumbing (the Mooncake engine + ZMQ control socket + room-keyed +status FSM, and the bootstrap rendezvous server) is the role-neutral shared base +in :mod:`...disaggregation.base`; this module just layers the embedding role's +buffer args onto it. The embedding-specific *semantics* -- the wire frames and +the senders/receivers -- live in :mod:`embedding_transfer`; nothing here carries +any KV/MLA/metrics state. +""" + +import dataclasses + +from tokenspeed.runtime.disaggregation.base.bootstrap import DisaggBootstrapServer +from tokenspeed.runtime.disaggregation.base.manager import DisaggManagerBase +from tokenspeed.runtime.disaggregation.mooncake_transfer_engine import ( + MooncakeTransferEngine, +) +from tokenspeed.runtime.disaggregation.utils import DisaggregationMode +from tokenspeed.runtime.utils.network import get_local_ip_by_remote + + +class EmbeddingTransferError(Exception): + """Raised on an embedding (encode->prefill) transfer failure.""" + + +@dataclasses.dataclass +class EmbeddingManagerArgs: + """Connection config for the embedding Mooncake endpoint. + + The encode role owns no KV pool / MLA / metrics, so this carries only the + transport fields the manager base reads. + """ + + bootstrap_port: int + world_size: int + dp_size: int + + +class EmbeddingManagerBase(DisaggManagerBase): + """Embedding (encode->prefill) manager: the shared engine/socket/status FSM + (:class:`...base.manager.DisaggManagerBase`) plus the embedding buffer args. + Carries none of the KV manager's KV/MLA/metrics fields. + """ + + def __init__( + self, + args: EmbeddingManagerArgs, + embedding_args, # EmbeddingArgs: embedding buffer ptrs + gpu/ib device + disaggregation_mode: DisaggregationMode, + ): + self.args = args + self.embedding_args = embedding_args + self.disaggregation_mode = disaggregation_mode + self.bootstrap_port = args.bootstrap_port + self.world_size = args.world_size + self.dp_size = args.dp_size + # Vendor binding stays out of the neutral base. embedding_args must be + # set above before super().__init__, which calls register_buffer_to_engine. + engine = MooncakeTransferEngine( + hostname=get_local_ip_by_remote(), + gpu_id=embedding_args.gpu_id, + ib_device=embedding_args.ib_device, + ) + super().__init__(engine=engine) + + def register_buffer_to_engine(self): + ea = self.embedding_args + if ea.embedding_data_ptr: + self.engine.register(ea.embedding_data_ptr, ea.embedding_data_len) + if ea.deepstack_data_ptr: + self.engine.register(ea.deepstack_data_ptr, ea.deepstack_data_len) + + +class EmbeddingBootstrapServer(DisaggBootstrapServer): + """Embedding bootstrap rendezvous: the shared server with no extra fields -- + the encode->prefill handshake needs only the base ip/port + parallel-size + sync, so there is nothing to layer onto :class:`DisaggBootstrapServer`. + """ diff --git a/python/tokenspeed/runtime/disaggregation/embedding/embedding_transfer.py b/python/tokenspeed/runtime/disaggregation/embedding/embedding_transfer.py new file mode 100644 index 00000000000..fdb9a40310f --- /dev/null +++ b/python/tokenspeed/runtime/disaggregation/embedding/embedding_transfer.py @@ -0,0 +1,893 @@ +# Copyright (c) 2026 LightSeek Foundation +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +from __future__ import annotations + +"""Mooncake transport for EPD encode->prefill image-embedding transfer. + +The encode (vision-tower-only) server is the data source: it calls +``batch_transfer_sync`` to ship a contiguous ``[num_tokens, hidden]`` tensor +per item over the same Mooncake RDMA engine the KV path uses. The prefill side +is the receiver that pre-registers buffers and registers with the bootstrap +server (direction reversed relative to prefill->decode). + +Each frame dataclass owns its byte layout via ``to_zmq()``/``from_zmq()``. The +wire-frame dataclasses are pure data plus codecs and import no torch, so the +protocol contract stays importable and unit-testable on CPU. +""" + +import concurrent.futures +import dataclasses +import os +import struct +import threading +import time +from typing import Dict, List, Optional, Tuple + +import requests +import zmq + +from tokenspeed.runtime.disaggregation.base.poll import TransferPoll +from tokenspeed.runtime.disaggregation.embedding.conn import ( + EmbeddingManagerArgs, + EmbeddingManagerBase, + EmbeddingTransferError, +) +from tokenspeed.runtime.disaggregation.utils import DisaggregationMode, FastQueue +from tokenspeed.runtime.utils import get_colorful_logger +from tokenspeed.runtime.utils.env import envs +from tokenspeed.runtime.utils.network import get_free_port, get_local_ip_by_remote + +logger = get_colorful_logger(__name__) + + +def _route_get(bootstrap_addr: str, engine_rank: int, target_dp_group: int): + """GET the bootstrap server's /route endpoint; ``None`` on any failure. + + Must never raise: callers in the receiver ``__init__`` treat ``None`` as a + per-room failure, but an uncaught exception would escape the prefill + scheduler thread and take the whole engine down via SIGUSR1. + """ + url = ( + f"http://{bootstrap_addr}/route?" + f"engine_rank={engine_rank}&target_dp_group={target_dp_group}" + ) + try: + resp = requests.get(url, timeout=5) + except Exception as e: # noqa: BLE001 -- any transport failure -> per-room fail + logger.error("EPD bootstrap /route fetch failed (%s): %s", url, e) + return None + if resp.status_code == 200: + return resp.json() + return None + + +# Sentinel room (on-wire ascii) for the one-shot registration frame; per-request +# pre-alloc frames carry an integer room. +REGISTER_ROOM_SENTINEL = "None" + + +def _pack_ptr(ptr: int) -> bytes: + """Encode a device virtual address as 8 little-endian bytes (uint64).""" + return struct.pack("Q", ptr) + + +def _unpack_ptr(frame: bytes) -> int: + return struct.unpack("Q", frame)[0] + + +def _b(value: object) -> bytes: + return str(value).encode("ascii") + + +def _bool_frame(value: bool) -> bytes: + return b"1" if value else b"0" + + +def _parse_bool(frame: bytes) -> bool: + return frame == b"1" + + +@dataclasses.dataclass +class EmbeddingArgs: + """Per-rank buffer/engine info for an embedding endpoint. + + On the encode (sender) side the buffers hold the vision tower's output; on + the prefill (receiver) side they are the pre-registered receive buffers. A + ``deepstack`` buffer is present only for models that emit deepstack + embeddings (e.g. Qwen3.5); ``0`` means absent. + """ + + engine_rank: int + gpu_id: int + ib_device: Optional[str] + embedding_data_ptr: int + embedding_data_len: int + deepstack_data_ptr: int = 0 + deepstack_data_len: int = 0 + + +@dataclasses.dataclass +class EmbeddingChunk: + """One item's embedding queued for transfer (encode-side, in-process only). + + Not serialized to ZMQ: it lives on the encode manager's transfer queue. The + pointers reference the contiguous ``item.encoded`` / ``item.encoded_deepstack`` + tensors produced by the vision tower. + """ + + room: int + src_embedding_ptr: int + n_tokens: int + hidden: int + dtype: str + nbytes: int + src_deepstack_ptr: int = 0 + deepstack_width: int = 0 # hidden * num_deepstack; 0 == no deepstack + deepstack_nbytes: int = 0 + # CUDA event recorded on the encode loop's stream after the device copy that + # filled this chunk's ring slot. The transfer worker waits it before its + # one-sided RDMA read so the read never races the copy (ViT->send corruption + # hazard). None on CPU/no-CUDA. + copy_event: Optional["torch.cuda.Event"] = None + + +@dataclasses.dataclass +class EmbeddingArgsRegisterInfo: + """Receiver(prefill)->sender(encode) one-shot endpoint registration. + + Sent once per receiver rank with room == ``REGISTER_ROOM_SENTINEL`` so the + encode side records where to PUSH completion status. The buffer pointers + are the receiver's base receive buffers (per-item row offsets are carried + later, in :class:`EmbeddingTransferInfo`). + """ + + room: str + endpoint: str + dst_port: int + mooncake_session_id: str + dst_embedding_ptr: int + dst_deepstack_ptr: int + + def to_zmq(self) -> List[bytes]: + return [ + _b(self.room), + _b(self.endpoint), + _b(self.dst_port), + _b(self.mooncake_session_id), + _pack_ptr(self.dst_embedding_ptr), + _pack_ptr(self.dst_deepstack_ptr), + ] + + @classmethod + def from_zmq(cls, msg: List[bytes]) -> "EmbeddingArgsRegisterInfo": + return cls( + room=msg[0].decode("ascii"), + endpoint=msg[1].decode("ascii"), + dst_port=int(msg[2].decode("ascii")), + mooncake_session_id=msg[3].decode("ascii"), + dst_embedding_ptr=_unpack_ptr(msg[4]), + dst_deepstack_ptr=_unpack_ptr(msg[5]), + ) + + +@dataclasses.dataclass +class EmbeddingTransferInfo: + """Receiver(prefill)->sender(encode) per-request pre-allocation frame. + + Tells the encode side where (``dst_embedding_ptr`` already includes this + request's row offset) and how big a transfer to issue. The RDMA write is + unchecked, so the encode asserts ``n_tokens``/``hidden``/``dtype`` against + the tensor it sends, else a mismatch silently writes a truncated/oversized + region. + + Row sharding: ``row_start`` + ``n_tokens`` (the SHARD's row count) select + the rows the encode writes at the shard-offset ``dst_embedding_ptr``; + ``span`` is the image's FULL row count, the cross-side token-count tripwire + regardless of shard geometry. Identity frames set ``row_start == 0`` and + ``n_tokens == span``. The encode validates shard geometry per frame: a + full-span write at a shard-offset pointer would corrupt neighboring image + rows in the same buffer. + """ + + room: int + endpoint: str + dst_port: int + mooncake_session_id: str + dst_embedding_ptr: int + dst_deepstack_ptr: int + n_tokens: int + hidden: int + dtype: str + has_deepstack: bool + required_dst_info_num: int + row_start: int = 0 + span: int = 0 + + def to_zmq(self) -> List[bytes]: + return [ + _b(self.room), + _b(self.endpoint), + _b(self.dst_port), + _b(self.mooncake_session_id), + _pack_ptr(self.dst_embedding_ptr), + _pack_ptr(self.dst_deepstack_ptr), + _b(self.n_tokens), + _b(self.hidden), + _b(self.dtype), + _bool_frame(self.has_deepstack), + _b(self.required_dst_info_num), + _b(self.row_start), + _b(self.span), + ] + + @classmethod + def from_zmq(cls, msg: List[bytes]) -> "EmbeddingTransferInfo": + # Length-guarded so a truncated frame is logged and dropped by the + # bootstrap listener instead of mis-parsing. + if len(msg) < 13: + raise ValueError( + f"malformed EmbeddingTransferInfo frame: {len(msg)} parts < 13" + ) + return cls( + room=int(msg[0].decode("ascii")), + endpoint=msg[1].decode("ascii"), + dst_port=int(msg[2].decode("ascii")), + mooncake_session_id=msg[3].decode("ascii"), + dst_embedding_ptr=_unpack_ptr(msg[4]), + dst_deepstack_ptr=_unpack_ptr(msg[5]), + n_tokens=int(msg[6].decode("ascii")), + hidden=int(msg[7].decode("ascii")), + dtype=msg[8].decode("ascii"), + has_deepstack=_parse_bool(msg[9]), + required_dst_info_num=int(msg[10].decode("ascii")), + row_start=int(msg[11].decode("ascii")), + span=int(msg[12].decode("ascii")), + ) + + +def validate_fanout_frames( + infos: List[EmbeddingTransferInfo], chunk: "EmbeddingChunk" +) -> Optional[str]: + """Pre-send contract check over a room's full fanout set; None when valid. + + Per frame: hidden/dtype must match the chunk; ``span`` (every frame carries + the image's full row count) must equal the chunk's token count (the + unchecked RDMA write silently truncates on divergence); the shard must stay + inside the chunk's rows; and deepstack presence must agree on both sides. + The set must then be either ALL identity (each frame covers the full span -- + full-copy broadcast) or a proper shard set whose non-empty shards, sorted by + ``row_start``, tile a contiguous range disjointly (an encode rank under + encode_tp>1 serves a contiguous BLOCK of the global shards). A gap/overlap + means the two sides' shard math diverged, so the room must fail loud. + """ + for info in infos: + if not (info.hidden == chunk.hidden and info.dtype == chunk.dtype): + return "embedding shape/dtype contract violated" + if info.span != chunk.n_tokens: + return ( + f"image token-count contract violated: receiver expects " + f"{info.span} rows, encode has {chunk.n_tokens} (G2)" + ) + if ( + info.row_start < 0 + or info.n_tokens < 0 + or info.row_start + info.n_tokens > chunk.n_tokens + ): + return ( + f"embedding shard out of range: rows [{info.row_start}, " + f"{info.row_start + info.n_tokens}) of {chunk.n_tokens}" + ) + if info.has_deepstack and not chunk.deepstack_width: + return ( + "receiver expects deepstack but the chunk carries none " + "(encode-side cache hit without its deepstack half?)" + ) + if chunk.deepstack_width and not info.has_deepstack: + return "chunk carries deepstack but the receiver did not allocate for it" + if all(i.row_start == 0 and i.n_tokens == chunk.n_tokens for i in infos): + return None # identity (full-copy) mode + shards = sorted((i.row_start, i.n_tokens) for i in infos if i.n_tokens > 0) + for (start, count), (next_start, _next_count) in zip(shards, shards[1:]): + if start + count != next_start: + return ( + "embedding shard frames do not tile contiguously: " + f"[{start}, {start + count}) then [{next_start}, ...)" + ) + return None + + +def shard_payload( + chunk: "EmbeddingChunk", info: EmbeddingTransferInfo +) -> Tuple[int, int, int, int]: + """Source pointer/length math for one receiver's row shard of a chunk. + + Returns ``(src_ptr, nbytes, src_deepstack_ptr, deepstack_nbytes)`` for the + rows ``[info.row_start, info.row_start + info.n_tokens)``. Identity frames + reproduce the whole-chunk payload exactly. Row strides are derived from the + chunk's own byte counts so dtype size never needs decoding here. + """ + row_bytes = chunk.nbytes // chunk.n_tokens if chunk.n_tokens else 0 + src = chunk.src_embedding_ptr + info.row_start * row_bytes + nbytes = info.n_tokens * row_bytes + deep_src = deep_nbytes = 0 + if chunk.deepstack_width and chunk.deepstack_nbytes: + deep_row_bytes = ( + chunk.deepstack_nbytes // chunk.n_tokens if chunk.n_tokens else 0 + ) + deep_src = chunk.src_deepstack_ptr + info.row_start * deep_row_bytes + deep_nbytes = info.n_tokens * deep_row_bytes + return src, nbytes, deep_src, deep_nbytes + + +class MooncakeEmbeddingSender: + """Encode-side per-request sender for one bootstrap room. + + ``poll`` / ``clear`` / ``failure_exception`` are status-only (they touch + only the manager's status maps). ``send`` queues one contiguous embedding + tensor described by scalar fields, keeping this class free of any torch + dependency. + """ + + def __init__(self, mgr, bootstrap_addr: str, bootstrap_room: int): + self.mgr = mgr # MooncakeEmbeddingManagerEncode + self.bootstrap_server_url = bootstrap_addr + self.bootstrap_room = bootstrap_room + self.mgr.update_status(bootstrap_room, TransferPoll.Bootstrapping) + self.conclude_state = None + + def send( + self, + *, + src_embedding_ptr: int, + n_tokens: int, + hidden: int, + dtype: str, + nbytes: int, + src_deepstack_ptr: int = 0, + deepstack_width: int = 0, + deepstack_nbytes: int = 0, + copy_event: Optional["torch.cuda.Event"] = None, + ) -> None: + chunk = EmbeddingChunk( + room=self.bootstrap_room, + src_embedding_ptr=src_embedding_ptr, + n_tokens=n_tokens, + hidden=hidden, + dtype=dtype, + nbytes=nbytes, + src_deepstack_ptr=src_deepstack_ptr, + deepstack_width=deepstack_width, + deepstack_nbytes=deepstack_nbytes, + copy_event=copy_event, + ) + self.mgr.add_transfer_request(self.bootstrap_room, chunk) + + def poll(self) -> int: + # No Bootstrapping timeout here: the never-registered-receiver case is + # handled by the manager's _park_reaper (it fails rooms whose parked chunk + # outlives bootstrap_time_out), so this only reports terminal status. + if self.conclude_state is None: + status = self.mgr.check_status(self.bootstrap_room) + if status in (TransferPoll.Success, TransferPoll.Failed): + self.conclude_state = status + return status + return self.conclude_state + + def clear(self) -> None: + if self.bootstrap_room in self.mgr.request_status: + self.mgr.request_status.pop(self.bootstrap_room) + + def failure_exception(self): + if self.conclude_state is None: + self.conclude_state = TransferPoll.Failed + self.clear() + with self.mgr.failure_lock: + failure_reason = self.mgr.failure_records.pop( + self.bootstrap_room, "Failed due to an unknown reason from another rank" + ) + raise EmbeddingTransferError( + self.bootstrap_room, failure_reason, self.bootstrap_server_url + ) + + +class MooncakeEmbeddingManagerEncode(EmbeddingManagerBase): + """Encode-side (data source) manager: registers itself to the bootstrap + server so the prefill receiver can find it, listens for the receiver's + registration + per-request pre-alloc frames, and a worker thread issues the + one-sided Mooncake write of the embedding. + """ + + def __init__(self, args: EmbeddingManagerArgs, embedding_args: "EmbeddingArgs"): + super().__init__(args, embedding_args, DisaggregationMode.ENCODE) + # room -> {receiver_session -> EmbeddingTransferInfo} + self.transfer_infos: Dict[int, Dict[str, EmbeddingTransferInfo]] = {} + # Bootstrap registration-wait timeout (default 120s). + self.bootstrap_time_out = envs.TOKENSPEED_DISAGGREGATION_BOOTSTRAP_TIMEOUT.get() + # room -> [(deadline, chunk), ...] chunks popped before the receiver + # registered; flushed by the bootstrap thread once its info arrives. + self._pending: Dict[int, List[tuple]] = {} + self._pending_lock = threading.Lock() + # zmq sockets are not thread-safe and status pushes come from any + # fanout-pool thread: keep one PUSH socket per (thread, endpoint). + self._status_tls = threading.local() + self._start_bootstrap_thread() + self._register_to_bootstrap() + # K queues sharded by ROOM: a single consumer per room preserves the + # park/flush/straggler-drop ordering the parking machinery relies on. + # Each queue's worker uses a pool to issue one room's per-receiver writes + # concurrently (each prefill rank is a distinct Mooncake session, so a + # single batch call cannot span them). + cpu_count = os.cpu_count() or 8 + pool_size = envs.TOKENSPEED_DISAGGREGATION_THREAD_POOL_SIZE.get_set_value_or( + min(max(4, int(0.75 * cpu_count) // 8), 12) + ) + queue_count = envs.TOKENSPEED_DISAGGREGATION_QUEUE_SIZE.get() + assert pool_size >= queue_count, ( + f"TOKENSPEED_DISAGGREGATION_THREAD_POOL_SIZE={pool_size} must be >= " + f"TOKENSPEED_DISAGGREGATION_QUEUE_SIZE={queue_count}" + ) + self._queues: List[FastQueue] = [FastQueue() for _ in range(queue_count)] + self._executors = [ + concurrent.futures.ThreadPoolExecutor(max(1, pool_size // queue_count)) + for _ in range(queue_count) + ] + for queue, executor in zip(self._queues, self._executors): + threading.Thread( + target=self._transfer_worker, args=(queue, executor), daemon=True + ).start() + threading.Thread(target=self._park_reaper, daemon=True).start() + + def _start_bootstrap_thread(self): + self.rank_port = get_free_port() + self.server_socket.bind(f"tcp://{get_local_ip_by_remote()}:{self.rank_port}") + + def loop(): + while True: + msg = self.server_socket.recv_multipart() + # A malformed frame must not kill this daemon thread: a dead + # listener drops every later registration, parking all chunks + # until the reaper fails them. Log and continue. + try: + if msg[0].decode("ascii") == REGISTER_ROOM_SENTINEL: + # registration frame: consumed, no per-session state needed + pass + else: + info = EmbeddingTransferInfo.from_zmq(msg) + self.transfer_infos.setdefault(info.room, {})[ + info.mooncake_session_id + ] = info + if ( + len(self.transfer_infos[info.room]) + >= info.required_dst_info_num + ): + self.update_status(info.room, TransferPoll.Bootstrapped) + # Re-drive any chunk parked before this room registered. + self._flush_pending(info.room) + except Exception as exc: # noqa: BLE001 + logger.error( + "dropping malformed embedding bootstrap frame " + "(%d parts): %s", + len(msg), + exc, + ) + + threading.Thread(target=loop, daemon=True).start() + + def _register_to_bootstrap(self): + ip = get_local_ip_by_remote() + payload = { + "role": "Prefill", # bootstrap-server role string for "discoverable data source" + "world_size": self.world_size, + "dp_size": self.dp_size, + "rank_ip": ip, + "rank_port": self.rank_port, + "engine_rank": self.embedding_args.engine_rank, + } + url = f"http://{ip}:{self.bootstrap_port}/route" + # The bootstrap HTTP server starts concurrently with this call, so the + # first PUTs can race it and hit connection-refused. A dropped + # registration leaves /route's parallel-info null and the encode silently + # serves no embeddings, so retry until the server accepts it. + last_err = None + for _ in range(60): + try: + resp = requests.put(url, json=payload, timeout=5) + if resp.ok: + return + last_err = f"status {resp.status_code}" + except Exception as e: # noqa: BLE001 + last_err = e + time.sleep(0.5) + logger.error( + "encode failed to register to bootstrap server after retries: %s", last_err + ) + + def add_transfer_request(self, room: int, chunk: EmbeddingChunk) -> None: + if ( + room not in self.request_status + or self.check_status(room) == TransferPoll.Failed + ): + return + self._queue_for(room).put(chunk) + + def _queue_for(self, room: int) -> FastQueue: + # Room-affinity sharding: one consumer per room keeps the park / + # _flush_pending re-enqueue / Success-straggler-drop sequence + # single-threaded per room. + return self._queues[room % len(self._queues)] + + def _transfer_worker( + self, queue: FastQueue, executor: concurrent.futures.ThreadPoolExecutor + ): + while True: + chunk: EmbeddingChunk = queue.get() + # Already concluded: a re-enqueued straggler copy from _flush_pending + # (which re-puts a parked chunk on each receiver registration). The + # room was already sent + popped, so drop it. + if self.request_status.get(chunk.room) == TransferPoll.Success: + continue + # Snapshot via list(): the bootstrap listener inserts into this inner + # dict without _pending_lock, so next(iter(...)) could raise "dict changed + # size during iteration". list() is GIL-atomic. + info_vals = list(self.transfer_infos.get(chunk.room, {}).values()) + # required_dst_info_num (= fanout) is identical across the N frames for a + # room, so read it off any registered frame; None until one registers. + need = info_vals[0].required_dst_info_num if info_vals else None + if (need is None or len(info_vals) < need) and self.request_status.get( + chunk.room + ) != TransferPoll.Failed: + # Fewer than N receivers registered (1->N broadcast not yet complete): + # park (don't drop) until the full set arrives. _flush_pending re-drives + # this chunk on every new registration; the reaper fails it on timeout. + parked = True + with self._pending_lock: + info_vals = list(self.transfer_infos.get(chunk.room, {}).values()) + need = info_vals[0].required_dst_info_num if info_vals else None + if info_vals and need is not None and len(info_vals) >= need: + # Full set landed inside the park window: send below instead. + parked = False + else: + self._pending.setdefault(chunk.room, []).append( + (time.time() + self.bootstrap_time_out, chunk) + ) + if parked: + continue + # All N receivers registered: serve every one concurrently (full copy + # in identity mode, its row shard otherwise) -- each is a distinct + # Mooncake session, so concurrency must come from threads. + infos = list(self.transfer_infos.get(chunk.room, {}).values()) + err = validate_fanout_frames(infos, chunk) + if err is not None: + self._fail_room(chunk.room, err, infos) + continue + # Wait the ring copy's completion HERE on the daemon (not the + # encode-loop thread): the one-sided RDMA reads in _send touch GPU + # memory off any CUDA stream, so they must not precede the device copy + # that filled the slot (ViT->send corruption hazard). One wait per + # chunk covers all N receivers (same slot); event.synchronize() + # releases the GIL while waiting. + if chunk.copy_event is not None: + chunk.copy_event.synchronize() + futures = [executor.submit(self._send, info, chunk) for info in infos] + failed = False + for info, future in zip(infos, futures): + ret = future.result() # _send returns <0 on error, never raises + if ret != 0: + self.record_failure(chunk.room, f"mooncake transfer ret={ret}") + failed = True + else: + # Per-receiver completion sync (each of the N prefill ranks gets + # exactly one, matching its required_response_num == 1). + self._sync_status(info, TransferPoll.Success) + if failed: + # Push Failed to EVERY receiver (idempotent on ones already + # Success'd: the rank-synced admission MIN aborts the request + # everywhere anyway). + self._fail_room(chunk.room, None, infos) + continue + # All N receivers served: mark the room Success ONCE and pop only now, + # so a partial fanout can never conclude/pop early. + self.update_status(chunk.room, TransferPoll.Success) + self.transfer_infos.pop(chunk.room, None) + + def _fail_room( + self, + room: int, + reason: Optional[str], + infos: List[EmbeddingTransferInfo], + ) -> None: + if reason is not None: + self.record_failure(room, reason) + self.update_status(room, TransferPoll.Failed) + for info in infos: + self._sync_status(info, TransferPoll.Failed) + + def is_parked(self, room: int) -> bool: + """Whether ``room`` still has a chunk parked awaiting receiver + registration. Public probe for the executor's ring-slot lease: a parked + chunk holds its slot's pointer for re-send, so the slot is not reusable + until the room unparks.""" + with self._pending_lock: + return room in self._pending + + def fail_room(self, room: int, reason: Optional[str]) -> None: + """Conclude ``room`` Failed and push Failed to all of its registered + receivers. Public seam for the encode executor, which must not reach into + ``transfer_infos`` or the status FSM directly.""" + infos = list(self.transfer_infos.get(room, {}).values()) + self._fail_room(room, reason, infos) + + def _flush_pending(self, room: int) -> None: + # Re-enqueue this room's parked chunks (in order) now that it registered. + # Same room -> same queue, so the re-driven copy is consumed by the same + # single worker that parked it. + with self._pending_lock: + parked = self._pending.pop(room, []) + for _deadline, chunk in parked: + self._queue_for(room).put(chunk) + + def _park_reaper(self): + # Fail rooms whose parked chunk outlived bootstrap_time_out (the + # receiver never registered), so an aborted request never hangs. + while True: + time.sleep(1.0) + now = time.time() + with self._pending_lock: + expired = [ + room + for room, parked in self._pending.items() + if parked and now >= parked[0][0] + ] + for room in expired: + self._pending.pop(room, None) + for room in expired: + self.record_failure( + room, f"receiver never registered within {self.bootstrap_time_out}s" + ) + self.update_status(room, TransferPoll.Failed) + + def _send(self, info: EmbeddingTransferInfo, chunk: EmbeddingChunk) -> int: + src, nbytes, deep_src, deep_nbytes = shard_payload(chunk, info) + if nbytes == 0: + # Zero-row shard (image span < shard count): nothing to write, but + # the frame already served as this receiver's registration and it + # still gets its Success push so its poll() completes. + return 0 + bufs = [src] + dsts = [info.dst_embedding_ptr] + lens = [nbytes] + if deep_nbytes and info.dst_deepstack_ptr: + bufs.append(deep_src) + dsts.append(info.dst_deepstack_ptr) + lens.append(deep_nbytes) + # Always go through the BATCH transfer API, even for a single buffer: its + # binding releases the GIL for the one-sided RDMA write + # (gil_scoped_release), while singular transfer_sync_write does not + # reliably, pinning the GIL for the whole write and freezing this daemon's + # loop + other daemons. A 1-element batch is byte-for-byte the same + # transfer. + return self.engine.batch_transfer_sync( + info.mooncake_session_id, bufs, dsts, lens + ) + + def _sync_status(self, info: EmbeddingTransferInfo, status: int) -> None: + # One socket per (thread, endpoint): pushes come from fanout-pool threads + # and zmq sockets are not thread-safe. + socks = getattr(self._status_tls, "socks", None) + if socks is None: + socks = self._status_tls.socks = {} + endpoint = f"tcp://{info.endpoint}:{info.dst_port}" + sock = socks.get(endpoint) + if sock is None: + sock = zmq.Context.instance().socket(zmq.PUSH) + sock.connect(endpoint) + socks[endpoint] = sock + sock.send_multipart( + [_b(info.room), _b(int(status)), _b(self.embedding_args.engine_rank)] + ) + + +class MooncakeEmbeddingManagerPrefill(EmbeddingManagerBase): + """Prefill-side (data sink) manager: holds the discovery caches and a thread + that consumes the encode side's per-request completion-status frames, marking + the room Success once all expected responses arrive. + """ + + def __init__(self, args: EmbeddingManagerArgs, embedding_args: "EmbeddingArgs"): + super().__init__(args, embedding_args, DisaggregationMode.PREFILL) + self.required_response_num: Dict[int, int] = {} + self.response_tracker: Dict[int, set] = {} + self.connection_pool: Dict[str, list] = {} + self.prefill_parallel_info: Dict[str, dict] = {} + self._start_status_thread() + + def _start_status_thread(self): + self.rank_port = get_free_port() + self.server_socket.bind(f"tcp://{get_local_ip_by_remote()}:{self.rank_port}") + + def loop(): + while True: + parts = self.server_socket.recv_multipart() + room = int(parts[0].decode("ascii")) + status = int(parts[1].decode("ascii")) + rank = int(parts[2].decode("ascii")) + if status == TransferPoll.Success and room in self.request_status: + self.response_tracker.setdefault(room, set()).add(rank) + if len( + self.response_tracker[room] + ) >= self.required_response_num.get(room, 1): + self.update_status(room, TransferPoll.Success) + elif status == TransferPoll.Failed: + self.record_failure(room, "encode failed to send embedding") + self.update_status(room, TransferPoll.Failed) + + threading.Thread(target=loop, daemon=True).start() + + +class MooncakeEmbeddingReceiver: + """Prefill-side per-request receiver: discovers the encode endpoint via the + bootstrap server, registers its receive buffer, and on ``pre_alloc`` tells + the encode side where/how big to write this request's embedding. 1->N + broadcast (prefill_tp a multiple of encode_tp): contiguous blocks of prefill + ranks pair one encode rank; encode_tp=1 -> all prefill ranks pair encode + rank 0 and receive the same TP-gathered embedding. + """ + + def __init__( + self, + mgr: MooncakeEmbeddingManagerPrefill, + bootstrap_addr: str, + bootstrap_room: int, + ): + self.mgr = mgr + self.bootstrap_addr = bootstrap_addr + self.bootstrap_room = bootstrap_room + self.session_id = mgr.get_session_id() + mgr.update_status(bootstrap_room, TransferPoll.Bootstrapping) + + pinfo = mgr.prefill_parallel_info.get(bootstrap_addr) + if pinfo is None or pinfo.get("prefill_tp_size") is None: + # SINGLE-attempt fail-fast: this runs in the prefill scheduler thread, + # so a retry-loop would stall the whole TP group on a slow/unreachable + # encode bootstrap. /route can answer 200 with un-populated + # parallel-info while the encode worker is still registering (startup + # race); fail this room fast and let the client retry once the encode + # has registered. A partial dict is never cached (it would crash later + # requests on int(None)). _route_get bounds its own GET at timeout=5, + # so this attempt cannot block beyond that. + cand = _route_get(bootstrap_addr, -1, -1) + if cand is None or cand.get("prefill_tp_size") is None: + mgr.record_failure( + bootstrap_room, "no (complete) parallel info from bootstrap" + ) + mgr.update_status(bootstrap_room, TransferPoll.Failed) + return + pinfo = cand + mgr.prefill_parallel_info[bootstrap_addr] = pinfo + + encode_tp = int(pinfo["prefill_tp_size"]) + encode_dp = int(pinfo["prefill_dp_size"]) + local_tp = mgr.world_size // mgr.dp_size + # prefill_tp must be a whole multiple of encode_tp. The vision tower + # output is TP-gathered (identical on every encode rank) and every prefill + # rank needs the full embedding, so encode_tp=1 -> prefill_tp=N is a 1->N + # broadcast. Contiguous blocks of `fanout` prefill ranks share one encode + # rank. + assert local_tp % encode_tp == 0, ( + f"EPD requires prefill_tp to be a multiple of encode_tp " + f"(encode_tp={encode_tp}, prefill_tp={local_tp})" + ) + fanout = local_tp // encode_tp # prefill ranks served by one encode rank + # Drives the ENCODE-side gate: how many prefill ranks register with this + # request's encode rank before it may send + conclude (1->N broadcast). + self.required_dst_info_num = fanout + # This prefill rank still pulls from exactly ONE encode rank, so it expects + # a single completion sync. The N-way fan-out is purely the encode side's + # concern; bumping this to N would hang every prefill rank. + mgr.required_response_num[bootstrap_room] = 1 + + # Which encode rank this prefill rank pulls from: contiguous grouping. + # encode_tp=1 -> fanout=local_tp -> my_encode_rank == 0 for all prefill + # ranks. Use `// fanout`, NOT `% encode_tp`: both are 0 for encode_tp=1, + # but only `// fanout` groups ranks correctly for encode_tp>1. + my_tp_rank = mgr.embedding_args.engine_rank % local_tp + my_encode_rank = my_tp_rank // fanout + target_dp_group = bootstrap_room % encode_dp + key = f"{bootstrap_addr}_{target_dp_group}_{my_encode_rank}" + if key not in mgr.connection_pool: + info = _route_get(bootstrap_addr, my_encode_rank, target_dp_group) + if info is None: + mgr.record_failure(bootstrap_room, "no encode rank info from bootstrap") + mgr.update_status(bootstrap_room, TransferPoll.Failed) + return + self.encode_infos = [info] + mgr.connection_pool[key] = self.encode_infos + self._register_args() + else: + self.encode_infos = mgr.connection_pool[key] + mgr.update_status(bootstrap_room, TransferPoll.Bootstrapped) + + def _register_args(self): + ea = self.mgr.embedding_args + reg = EmbeddingArgsRegisterInfo( + room=REGISTER_ROOM_SENTINEL, + endpoint=get_local_ip_by_remote(), + dst_port=self.mgr.rank_port, + mooncake_session_id=self.session_id, + dst_embedding_ptr=ea.embedding_data_ptr, + dst_deepstack_ptr=ea.deepstack_data_ptr, + ) + for info in self.encode_infos: + sock = self.mgr._connect(f"tcp://{info['rank_ip']}:{info['rank_port']}") + sock.send_multipart(reg.to_zmq()) + + def pre_alloc( + self, + *, + dst_embedding_ptr: int, + n_tokens: int, + hidden: int, + dtype: str, + dst_deepstack_ptr: int = 0, + has_deepstack: bool = False, + row_start: int = 0, + span: int = 0, + ) -> None: + """Tell the encode side where/how big to write. In shard mode the caller + passes this rank's row sub-range: ``row_start`` within the image and + ``n_tokens`` = the SHARD's row count, both dst pointers already offset to + the shard's first row. ``span`` is the image's FULL row count (pass it in + identity mode too: it is the encode side's token-count tripwire). A + ``n_tokens == 0`` frame is still sent: it doubles as this receiver's + registration heartbeat (the encode-side fanout gate counts frames, not + bytes).""" + for info in self.encode_infos: + ti = EmbeddingTransferInfo( + room=self.bootstrap_room, + endpoint=get_local_ip_by_remote(), + dst_port=self.mgr.rank_port, + mooncake_session_id=self.session_id, + dst_embedding_ptr=dst_embedding_ptr, + dst_deepstack_ptr=dst_deepstack_ptr, + n_tokens=n_tokens, + hidden=hidden, + dtype=dtype, + has_deepstack=has_deepstack, + required_dst_info_num=self.required_dst_info_num, + row_start=row_start, + span=span, + ) + sock = self.mgr._connect(f"tcp://{info['rank_ip']}:{info['rank_port']}") + sock.send_multipart(ti.to_zmq()) + + def poll(self) -> int: + return self.mgr.check_status(self.bootstrap_room) + + def clear(self) -> None: + """Drop this room's bookkeeping from the (singleton) prefill manager on a + terminal receive, else every request leaks its status/tracker entries. + Mirrors the KV receiver; called post-terminal so it can't race check_status.""" + room = self.bootstrap_room + self.mgr.request_status.pop(room, None) + self.mgr.required_response_num.pop(room, None) + self.mgr.response_tracker.pop(room, None) + with self.mgr.failure_lock: + self.mgr.failure_records.pop(room, None) diff --git a/python/tokenspeed/runtime/disaggregation/embedding/encode_executor.py b/python/tokenspeed/runtime/disaggregation/embedding/encode_executor.py new file mode 100644 index 00000000000..fed2597e080 --- /dev/null +++ b/python/tokenspeed/runtime/disaggregation/embedding/encode_executor.py @@ -0,0 +1,377 @@ +# Copyright (c) 2026 LightSeek Foundation +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +from __future__ import annotations + +"""EPD encode-worker execution: run the vision tower, scatter its output back +onto each item, and hand the contiguous embeddings to the Mooncake sender. +""" + +import logging +from typing import List, Tuple + +import torch + +logger = logging.getLogger(__name__) + +from tokenspeed.runtime.disaggregation.base.poll import TransferPoll +from tokenspeed.runtime.disaggregation.embedding.embedding_transfer import ( + MooncakeEmbeddingSender, +) +from tokenspeed.runtime.multimodal.embedder import _item_token_count +from tokenspeed.runtime.multimodal.inputs import Modality, MultimodalDataItem + + +def assign_encoded_embeddings( + items: List[MultimodalDataItem], + output: torch.Tensor, + model, +) -> None: + """Scatter a packed vision-tower output onto each item, in place. + + ``output`` is the tower's ``[sum_tokens, width]`` result for ``items`` in + order (``width = hidden`` for plain models, or ``hidden * (1 + n_deepstack)`` + for deepstack models like Qwen3.5). Each item's row span is its post-merge + token count (``_item_token_count``); the rows are split accordingly and, + for deepstack models, column-split via ``model.separate_deepstack_embeds`` + into the main ``[N, hidden]`` and deepstack ``[N, hidden * n_deepstack]`` + halves. Results are made contiguous because a TP-gathered tower output may + not be, and the transfer ships raw row-major bytes. + + Sets ``item.encoded`` (and ``item.encoded_deepstack`` when the model emits + deepstack, else ``None``), which is exactly the ``skip-ViT`` form the + prefill-side VisionEmbedder consumes. + """ + output = output.reshape(-1, output.shape[-1]) + per_item_tokens = [_item_token_count(item) for item in items] + total = sum(per_item_tokens) + if output.shape[0] != total: + raise ValueError( + f"vision-tower output has {output.shape[0]} rows but items sum to " + f"{total} post-merge tokens; check the token-count / grid contract" + ) + + has_deepstack = getattr(model, "num_deepstack_embeddings", 0) > 0 + per_item_embeds = torch.split(output, per_item_tokens, dim=0) + for item, emb in zip(items, per_item_embeds): + if has_deepstack: + main, deep = model.separate_deepstack_embeds(emb) + item.encoded = main.contiguous() + item.encoded_deepstack = deep.contiguous() + else: + item.encoded = emb.contiguous() + item.encoded_deepstack = None + + +class DisaggEncodeExecutor: + """Drives one encode worker: run the vision tower on a batch of items, then + ship each item's embedding to its prefill peer over Mooncake. + + Python orchestration: this is invoked by the encode loop, not the + C++ scheduler. ``execute`` groups items by modality, runs the tower once per + modality via the model's ``get_image_feature`` / ``get_video_feature``, + scatters the output onto ``item.encoded`` (see + :func:`assign_encoded_embeddings`), and queues a transfer per item through + the per-request :class:`MooncakeEmbeddingSender`. Each request must first be + ``register``-ed with its prefill peer's bootstrap (host, port, room). + """ + + def __init__( + self, + manager, + multimodal_model, + device, + *, + ring_slots: int = 64, + ring_bytes: int = 256 * 1024 * 1024, + ): + self.manager = manager + self.model = multimodal_model + self.device = device + self.senders = {} + # RDMA requires every transferred buffer to be a registered memory region, + # and mooncake rejects OVERLAPPING registrations -- registering each + # per-request ``item.encoded`` fails because the torch caching allocator + # packs freed-but-still-registered tensors so a grown region straddles + # others. Collapse every send through a fixed ring of pre-registered bounce + # buffers: each slot is registered once at a fixed size (never grows, never + # overlaps), and ``item.encoded`` is copied into a slot before its async + # send. ``ring_slots`` / ``ring_bytes`` are injectable for tests and + # env-tunable; total reservation is slots * slot_bytes PER ring (main, plus + # deepstack if present), so depth and per-slot bytes must be sized to the + # model and peak concurrency. + import os as _os + + self._ring_slots = int( + _os.environ.get("TOKENSPEED_EPD_ENCODE_RING_SLOTS", ring_slots) + ) + _slot_mb_env = _os.environ.get("TOKENSPEED_EPD_ENCODE_RING_SLOT_MB") + # Env override is in whole MiB; unset -> keep the exact ``ring_bytes`` arg. + self._ring_bytes = ( + int(_slot_mb_env) * 1024 * 1024 if _slot_mb_env else ring_bytes + ) + self._main_ring = None # lazily allocated on first send (device live by then) + self._deep_ring = None + self._ring_idx = 0 + # Per-slot lease: the room whose send last staged into the slot. A slot is + # reusable only once that room's transfer is TERMINAL and not parked (a + # parked chunk holds the slot's pointer until bootstrap_time_out and is + # re-sent on late receiver registration; see _lease_slot), so a full ring + # DEFERS the send rather than overwriting an in-flight slot. + self._slot_rooms: List = [None] * self._ring_slots + # Sends whose ViT output is ready but could not lease a free ring slot + # (all slots still hold in-flight transfers). Retried non-blocking by + # drain_deferred() each loop tick (a busy-wait here would GIL-starve the + # daemon transfer-workers that free the slots and deadlock the loop). + self._deferred_sends: List = [] + + def register(self, request_id, bootstrap_host, bootstrap_port, bootstrap_room): + self.senders[request_id] = MooncakeEmbeddingSender( + self.manager, f"{bootstrap_host}:{bootstrap_port}", bootstrap_room + ) + + def _feature_fn(self, modality): + # IMAGE dispatches through the model's ``image_encoder`` seam, NOT + # ``get_image_feature`` directly: that seam is what the encoder CUDA-graph + # wrapper overrides (see _maybe_install_encoder_cudagraph). When the graph + # is disabled the model leaves ``image_encoder = get_image_feature`` (eager); + # VIDEO has no captured graph -> always eager. + if modality == Modality.IMAGE: + return self.model.image_encoder + if modality == Modality.VIDEO: + return self.model.get_video_feature + raise ValueError(f"unsupported modality for encode: {modality}") + + def execute(self, request_items: List[Tuple[str, MultimodalDataItem]]) -> None: + by_modality = {} + for _, item in request_items: + by_modality.setdefault(item.modality, []).append(item) + with torch.inference_mode(): + for modality, items in by_modality.items(): + output = self._feature_fn(modality)(items) + assign_encoded_embeddings(items, output, self.model) + # Stage every embedding into its ring slot, then issue the async + # Mooncake sends. See _stage_and_send for the copy/RDMA + # overwrite-safety invariant (one CUDA event gates each transfer). + self._stage_and_send(request_items) + + def _ensure_rings(self) -> None: + """Lazily allocate + register the bounce-buffer ring (see ``__init__``).""" + if self._main_ring is not None: + return + self._main_ring = [ + torch.empty(self._ring_bytes, dtype=torch.uint8, device=self.device) + for _ in range(self._ring_slots) + ] + for buf in self._main_ring: + self.manager.engine.register(buf.data_ptr(), self._ring_bytes) + + def _copy_into(self, ring, slot: int, src) -> Tuple[int, int]: + """Copy ``src``'s bytes into pre-registered ring ``slot``; return its + (device pointer, byte length). Fails loud if an embedding exceeds a slot.""" + nbytes = src.numel() * src.element_size() + if nbytes > self._ring_bytes: + raise RuntimeError( + f"EPD encode embedding {nbytes} B exceeds ring slot " + f"{self._ring_bytes} B; raise EncodeExecutor._ring_bytes" + ) + buf = ring[slot] + buf[:nbytes].view(src.dtype).copy_(src.reshape(-1)) + return buf.data_ptr(), nbytes + + def _lease_slot(self) -> "int | None": + """Return a reusable ring-slot index, or ``None`` if every slot still + holds an in-flight transfer. NON-BLOCKING: the caller DEFERS rather than + spinning (a busy-wait would GIL-starve the daemon transfer-workers that + mark rooms terminal and deadlock the single-threaded loop). + + A slot is reusable once the room it last staged is TERMINAL (Success, + Failed, or None=already reaped) AND no parked chunk still holds its + pointer -- the overwrite-safety invariant.""" + from tokenspeed.runtime.disaggregation.base.poll import TransferPoll + + mgr = self.manager + n = self._ring_slots + for _ in range(n): + slot = self._ring_idx % n + self._ring_idx += 1 + room = self._slot_rooms[slot] + if room is None: + return slot + status = mgr.room_status(room) + if status is None or status in ( + TransferPoll.Success, + TransferPoll.Failed, + ): + if not mgr.is_parked(room): + return slot + return None + + def _stage_and_send(self, items: List[Tuple[str, MultimodalDataItem]]) -> None: + """Lease a ring slot per item and ship it; items that cannot lease a free + slot (ring full) are DEFERRED for a later non-blocking retry rather than + blocking the loop. Stages every leased item then issues ONE stream sync + before the sends, so the one-sided RDMA reads never race the device-to- + device copies (the ViT->send corruption hazard).""" + self._ensure_rings() + staged = [] + for rid, item in items: + if rid not in self.senders: + # Sender reaped (its room concluded/failed) -- drop this stale + # deferred send instead of crashing on senders[rid]. + continue + slot = self._lease_slot() + if slot is None: + self._deferred_sends.append((rid, item)) + continue + try: + send_args = self._stage_item( + item, self.senders[rid].bootstrap_room, slot + ) + except Exception as e: + # A staging error (most plausibly _copy_into rejecting an embedding + # larger than a ring slot) must fail only THIS item's room, never + # raise out of the single-threaded encode loop into the engine's + # SIGUSR1 handler (which kills the whole worker and every other + # in-flight image). Covers the unguarded send_item() / + # drain_deferred() callers too; the leased slot returns to the ring + # once the room is Failed (see _lease_slot). + self._fail_staged_room(rid, e) + continue + staged.append((rid, send_args)) + if not staged: + return + # Record ONE CUDA event after all the ring copies above (they ran on the + # current stream inside _stage_item) and hand it to each transfer rather + # than host-syncing on this single encode-loop thread. The daemon + # transfer-worker waits the event before its one-sided RDMA read + # (embedding_transfer._transfer_worker), so the read never races the copy; + # _lease_slot keeps the slot until its room is terminal (Success only after + # the RDMA completes). + copy_event = None + if torch.cuda.is_available(): + copy_event = torch.cuda.Event() + copy_event.record() + for rid, send_args in staged: + self.senders[rid].send(copy_event=copy_event, **send_args) + + def drain_deferred(self) -> None: + """Retry deferred sends (ViT done, waiting for a free ring slot). Non- + blocking: items that still cannot lease a slot stay deferred. Driven once + per encode-loop tick; the loop yields the GIL between ticks so the daemon + transfer-workers can free slots for the next drain.""" + if not self._deferred_sends: + return + pending = self._deferred_sends + self._deferred_sends = [] + self._stage_and_send(pending) + + def has_deferred(self) -> bool: + return bool(self._deferred_sends) + + def _conclude_room_failed(self, room: int, exc: Exception) -> None: + """Push Failed to ``room``'s prefill receivers so they abort via the + rank-synced admission path, instead of the error escaping the encode loop + and SIGUSR1-ing the worker. The single seam every failure path goes + through; delegates to the manager's public ``fail_room`` rather than + reaching into its ``transfer_infos`` / status FSM.""" + self.manager.fail_room(room, str(exc)) + + def _fail_staged_room(self, rid: str, exc: Exception) -> None: + """Per-item staging failure (the unguarded ``send_item`` / + ``drain_deferred`` callers): conclude ``rid``'s room Failed.""" + sender = self.senders.get(rid) + if sender is None: + return + self._conclude_room_failed(sender.bootstrap_room, exc) + logger.error( + "encode staging failed for room %s: %s", sender.bootstrap_room, exc + ) + + def fail_rooms(self, request_ids, exc: Exception) -> int: + """Conclude every room owned by ``request_ids`` Failed; return the count. + The owning seam for a batch-level failure that fired before any send was + issued (ViT / assign_encoded_embeddings): the worker hands its batch's + request_ids and stays out of the sender/manager internals. Rooms are + de-duped (a multi-image request shares one room).""" + rooms = set() + for rid in request_ids: + sender = self.senders.get(rid) + if sender is not None: + rooms.add(sender.bootstrap_room) + for room in rooms: + self._conclude_room_failed(room, exc) + return len(rooms) + + def reap_concluded_senders(self, pending_request_ids) -> None: + """Drop per-request senders whose room reached a terminal transfer status + (the ``senders`` dict otherwise grows forever). Senders whose request_id + is still awaiting the tower (``pending_request_ids``) are kept -- their + send has not been queued. Only the sender is dropped; the manager's + terminal ``request_status`` tombstone stays (the transfer worker's + straggler-drop and the ring-slot lease both key on it).""" + for rid in list(self.senders): + if rid in pending_request_ids: + continue + room = self.senders[rid].bootstrap_room + if self.manager.room_status(room) in ( + TransferPoll.Success, + TransferPoll.Failed, + ): + self.senders.pop(rid, None) + + def _stage_item(self, item: MultimodalDataItem, room, slot: int) -> dict: + """Copy one item's embedding (and deepstack half, if any) into the leased + ring ``slot`` and return the scalar ``send`` kwargs. The copy runs on the + current stream; the CALLER must synchronize before handing these pointers + to the transfer engine, so the one-sided RDMA read never races the device- + to-device copy (same hazard class as the ViT->send race).""" + enc = item.encoded + self._slot_rooms[slot] = room + send_ptr, nbytes = self._copy_into(self._main_ring, slot, enc) + ds_ptr = ds_width = ds_nbytes = 0 + deep = item.encoded_deepstack + if deep is not None and deep.numel() > 0: + if self._deep_ring is None: + self._deep_ring = [ + torch.empty(self._ring_bytes, dtype=torch.uint8, device=self.device) + for _ in range(self._ring_slots) + ] + for buf in self._deep_ring: + self.manager.engine.register(buf.data_ptr(), self._ring_bytes) + ds_width = deep.shape[1] + ds_ptr, ds_nbytes = self._copy_into(self._deep_ring, slot, deep) + return dict( + src_embedding_ptr=send_ptr, + n_tokens=enc.shape[0], + hidden=enc.shape[1], + dtype=str(enc.dtype), + nbytes=nbytes, + src_deepstack_ptr=ds_ptr, + deepstack_width=ds_width, + deepstack_nbytes=ds_nbytes, + ) + + def send_item(self, request_id, item: MultimodalDataItem) -> None: + """Ship an already-encoded item (``item.encoded`` set) to its prefill peer. + Used by the encode loop for cache hits, which skip the tower but still + transfer. Routes through the same lease-or-defer path as ``execute`` so a + full ring defers (non-blocking) instead of stalling the loop.""" + self._stage_and_send([(request_id, item)]) diff --git a/python/tokenspeed/runtime/disaggregation/embedding/encode_loop.py b/python/tokenspeed/runtime/disaggregation/embedding/encode_loop.py new file mode 100644 index 00000000000..938b0185d36 --- /dev/null +++ b/python/tokenspeed/runtime/disaggregation/embedding/encode_loop.py @@ -0,0 +1,324 @@ +# Copyright (c) 2026 LightSeek Foundation +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +from __future__ import annotations + +"""EPD encode-worker loop: a lightweight, LM-free scheduler subprocess. + +The encode role runs the vision tower and ships image embeddings to prefill +workers over Mooncake; it owns no KV cache and never runs the language model, so +it does NOT use the full :class:`EventLoop`/C++ scheduler (that machinery -- paged +KV, chunked prefill, retract, token budget -- is an impedance mismatch for a ViT). +Instead ``run_event_loop`` branches here when ``disaggregation_mode == "encode"``. + +The assembly is: load the model, stand up the Mooncake encode manager + bootstrap +server, the DisaggEncodeExecutor, and the EncodeWorker, reusing the SAME request +IPC the LM scheduler uses: a ZMQ PULL +on ``port_args.scheduler_input_ipc_name``. The smg grpc_servicer's TokenSpeedEncoder +handler sends an :class:`EncodeRequest` (pickled) over that channel; the loop +drains them into ``EncodeWorker.submit`` and runs ``step`` to encode + transfer. + +TP: the vision tower is TP-sharded, so all encode ranks run each batch in lockstep +-- rank 0 owns the gateway ZMQ and broadcasts every batch to the TP group. The +embedding transport is a 1->N broadcast: prefill_tp must be a multiple of +encode_tp (encode_tp=1 scales horizontally via multiple independent encode +processes = DP); dp_size == 1 on both embedding endpoints (this is process-DP, +not dp_attention). +""" + +import os +import time + +import zmq + +from tokenspeed.runtime.cache.embedding_cache import ( + EmbeddingCache, + TieredEmbeddingCache, +) +from tokenspeed.runtime.disaggregation.embedding.encode_scheduler import EncodeScheduler +from tokenspeed.runtime.disaggregation.embedding.encode_worker import EncodeWorker +from tokenspeed.runtime.utils import get_colorful_logger, get_zmq_socket +from tokenspeed.runtime.utils.env import envs + +logger = get_colorful_logger(__name__) + +# Vision-embedding cache capacity. L1 lives in GPU VRAM; the optional L2 lives in +# host DRAM and catches L1 evictions so duplicate images skip the tower even past +# the VRAM working set. Both are whole-MiB env overrides. L2 defaults to 0 +# (disabled): the host tier is opt-in. NOTE both knobs are PER ENCODE PROCESS (per +# TP rank): at encode TP>1, every co-located rank allocates its own L1+L2, so +# budget host DRAM as tp_size * EMBED_CACHE_DRAM_MB. +_DEFAULT_EMBEDDING_CACHE_L1_MB = 4096 # 4 GiB +_DEFAULT_EMBEDDING_CACHE_L2_MB = 0 # host-DRAM tier off unless opted in + + +def _embedding_cache_bytes(env_name: str, default_mb: int) -> int: + """Whole-MiB env override -> bytes (unset/empty keeps ``default_mb``). + + Rejects negative / non-integer values with an env-named error so a mis-set + knob fails fast and legibly. + """ + raw = os.environ.get(env_name) + if not raw: + return default_mb * 1024 * 1024 + try: + mb = int(raw) + except ValueError: + raise ValueError( + f"{env_name} must be a whole number of MiB, got {raw!r}" + ) from None + if mb < 0: + raise ValueError(f"{env_name} must be >= 0 MiB, got {mb}") + return mb * 1024 * 1024 + + +def _make_embedding_cache(l1_bytes: int, l2_bytes: int, device: str): + """Select the encode embedding cache: a plain single-tier VRAM + :class:`EmbeddingCache` by default, or a two-tier :class:`TieredEmbeddingCache` + (VRAM L1 + host-DRAM L2) when the L2 capacity is enabled (``l2_bytes > 0``).""" + if l2_bytes > 0: + logger.info( + "EPD encode embedding cache: L1(VRAM)=%d MiB, L2(host DRAM)=%d MiB", + l1_bytes >> 20, + l2_bytes >> 20, + ) + return TieredEmbeddingCache(l1_bytes, l2_bytes, device=device) + logger.info( + "EPD encode embedding cache: L1(VRAM)=%d MiB (host-DRAM L2 disabled)", + l1_bytes >> 20, + ) + return EmbeddingCache(l1_bytes) + + +def _build_manager_args(server_args, mapping): + """EmbeddingManagerArgs for the encode Mooncake endpoint. Forced to dp_size=1 / + enable_dp_attention=False (the base manager hard-rejects otherwise; embedding + transport allows prefill_tp = any multiple of encode_tp, dp_size==1 = process-DP). + """ + from tokenspeed.runtime.disaggregation.embedding.conn import EmbeddingManagerArgs + + return EmbeddingManagerArgs( + bootstrap_port=server_args.disaggregation_bootstrap_port, + world_size=server_args.world_size or mapping.world_size, + dp_size=1, + ) + + +def _maybe_install_encoder_cudagraph(model, server_args) -> bool: + """Install the vision-encoder CUDA-graph wrapper as ``model.image_encoder``, + mirroring the aggregated path's hook in ``execution/model_executor.py``. + + The encode loop never builds a ModelExecutor, so this is where the encode + worker opts into capture/replay of the tower instead of running it eager. Same + gate as the aggregated install: the model exposes the builder, multimodal is + active, the env flag is on, and the attention backend is graph-capturable. The + wrapper IS the model's ``image_encoder`` seam (lazy capture on first encode); + the executor's IMAGE path dispatches through ``model.image_encoder`` and falls + back to eager ``get_image_feature`` (the default) when this returns False. + Returns whether the wrapper was installed. + """ + if not ( + hasattr(model, "make_encoder_cudagraph_wrapper") + and getattr(model, "is_multimodal_active", True) + and envs.TOKENSPEED_MM_ENABLE_ENCODER_CUDA_GRAPH.get() + and server_args.mm_attention_backend != "flashinfer_cudnn" + ): + return False + model.image_encoder = model.make_encoder_cudagraph_wrapper(model.mapping) + logger.info("EPD encode worker: vision-encoder CUDA graph installed") + return True + + +def _build_encode_worker(server_args, port_args, gpu_id, global_rank): + """Assemble the encode worker: model + Mooncake manager + bootstrap server + + executor + scheduler + cache, driven from the real ServerArgs.""" + from tokenspeed.runtime.configs.model_config import ModelConfig + from tokenspeed.runtime.disaggregation.embedding.conn import ( + EmbeddingBootstrapServer, + ) + from tokenspeed.runtime.disaggregation.embedding.embedding_transfer import ( + EmbeddingArgs, + MooncakeEmbeddingManagerEncode, + ) + from tokenspeed.runtime.disaggregation.embedding.encode_executor import ( + DisaggEncodeExecutor, + ) + from tokenspeed.runtime.execution.distributed_initializer import ( + DistributedConfig, + DistributedInitializer, + ) + from tokenspeed.runtime.execution.factory import create_model_runner + + mapping = server_args.mapping + attn_tp_rank = mapping.attn.tp_rank + dp_rank = mapping.attn.dp_rank + device = f"cuda:{gpu_id}" + + model_config = ModelConfig( + server_args.model, + trust_remote_code=server_args.trust_remote_code, + revision=server_args.revision, + context_length=server_args.max_model_len, + model_override_args=server_args.hf_overrides, + dtype=server_args.dtype, + quantization=server_args.quantization, + server_args=server_args, + ) + DistributedInitializer.initialize( + DistributedConfig.from_server_args( + server_args=server_args, + port_args=port_args, + gpu_id=gpu_id, + global_rank=global_rank, + hidden_size=model_config.hidden_size, + max_num_tokens=server_args.chunked_prefill_size or 8192, + ) + ) + # The encode worker only needs the vision tower. The model is built + # vision-only (LM construction + LM weight load skipped) via the + # encoder_only gate derived from disaggregation_mode=="encode". The tower + # is used via DisaggEncodeExecutor. No KV/mamba pool is allocated: the encode + # loop never builds a ModelExecutor. + model = create_model_runner(server_args, model_config, None, gpu_id, global_rank)[ + 0 + ].model + # Opt into vision-encoder CUDA-graph capture (mirrors the aggregated path, + # which the encode worker bypasses by never building a ModelExecutor). + _maybe_install_encoder_cudagraph(model, server_args) + + manager_args = _build_manager_args(server_args, mapping) + embedding_args = EmbeddingArgs( + engine_rank=global_rank, + gpu_id=gpu_id, + ib_device=server_args.disaggregation_ib_device, + embedding_data_ptr=0, + embedding_data_len=0, + ) + # The encode worker is the Mooncake data source: it hosts its own bootstrap + # server (prefill workers discover it via the handshake the gateway injects). + # At TP>1 only rank 0 binds the port; every rank still registers its own + # rank_ip/rank_port to it (same-host PUT), so each prefill rank can look up + # the encode rank it pairs with (contiguous blocks of prefill ranks share one + # encode rank; encode_tp=1 -> all prefill ranks pair encode rank 0). + if attn_tp_rank == 0: + EmbeddingBootstrapServer(server_args.disaggregation_bootstrap_port) + manager = MooncakeEmbeddingManagerEncode(manager_args, embedding_args) + executor = DisaggEncodeExecutor(manager, model, device=device) + + l1_bytes = _embedding_cache_bytes( + "TOKENSPEED_EPD_ENCODE_EMBED_CACHE_MB", _DEFAULT_EMBEDDING_CACHE_L1_MB + ) + l2_bytes = _embedding_cache_bytes( + "TOKENSPEED_EPD_ENCODE_EMBED_CACHE_DRAM_MB", _DEFAULT_EMBEDDING_CACHE_L2_MB + ) + cache = _make_embedding_cache(l1_bytes, l2_bytes, device) + scheduler = EncodeScheduler( + max_tokens_per_batch=server_args.chunked_prefill_size or 8192, + max_items_per_batch=server_args.max_num_seqs, + ) + return EncodeWorker(executor, scheduler, cache), model_config + + +def run_encode_loop(server_args, port_args, pipe_writer, gpu_id, global_rank): + """Run the encode-worker loop until the parent process exits. + + Drains :class:`EncodeRequest`s off the shared scheduler-input ZMQ channel into + EncodeWorker.submit, then runs EncodeWorker.step to encode + ship each pending + item over Mooncake. Synchronous; no KV, no LM forward. + """ + worker, model_config = _build_encode_worker( + server_args, port_args, gpu_id, global_rank + ) + + # TP coordination: the vision tower is TP-sharded (collective ops), so every + # encode rank must run each batch in lockstep. Only rank 0 owns the gateway + # ZMQ; it broadcasts each drained batch to the TP group so all ranks submit + # the same requests and step together. (TP=1 -> rank 0 only, no broadcast.) + attn_tp_rank = server_args.mapping.attn.tp_rank + attn_tp_size = server_args.attn_tp_size or server_args.mapping.attn.tp_size + tp_cpu_group = None + broadcast_pyobj = None + attn_tp_src_rank = server_args.mapping.attn.tp_group[0] + if attn_tp_size > 1: + from tokenspeed.runtime.distributed.process_group_manager import ( + process_group_manager as pg_manager, + ) + from tokenspeed.runtime.utils.common import broadcast_pyobj as _bcast + + broadcast_pyobj = _bcast + tp_cpu_group = pg_manager.get_process_group( + "gloo", server_args.mapping.attn.tp_group + ) + + context = zmq.Context(2) + recv_from_gateway = None + if attn_tp_rank == 0: + recv_from_gateway = get_zmq_socket( + context, zmq.PULL, port_args.scheduler_input_ipc_name, False + ) + + # Unblock the launcher. The encode role has no KV pool, so the token/seq + # fields are nominal (kept for envelope compatibility with the LM ready msg). + pipe_writer.send( + { + "status": "ready", + "max_total_num_tokens": 0, + "max_req_input_len": model_config.context_len, + "max_num_seqs": server_args.max_num_seqs, + "chunked_prefill_size": server_args.chunked_prefill_size, + "max_model_len": model_config.context_len, + } + ) + + while True: + # Rank 0 drains the gateway ZMQ without blocking; other ranks get the + # same batch by broadcast below. + new_reqs = [] + if attn_tp_rank == 0: + while True: + try: + request = recv_from_gateway.recv_pyobj(flags=zmq.NOBLOCK) + except zmq.Again: + break + new_reqs.append(request) + + if attn_tp_size > 1: + # Unconditional every iteration: this is the TP rendezvous that keeps + # all ranks stepping the (collective) vision tower in lockstep. + new_reqs = broadcast_pyobj( + new_reqs, attn_tp_rank, tp_cpu_group, src=attn_tp_src_rank + ) + + for request in new_reqs: + worker.submit(request) + drained = len(new_reqs) > 0 + + # Encode + ship one scheduler batch. step() returns 0 when idle. All ranks + # hold the same pending set, so they make the same step decision together. + did = worker.step() + + # Yield the GIL when there is no fresh ZMQ work, OR when sends are deferred + # on a full ring. The daemon transfer-workers that free ring slots are + # GIL-bound, so spinning here would starve them and wedge the ring; a brief + # yield lets them free slots so the next drain_deferred() can ship. + if ( + not drained and did == 0 and not worker.has_pending() + ) or worker.has_deferred(): + time.sleep(0.0005) diff --git a/python/tokenspeed/runtime/disaggregation/embedding/encode_scheduler.py b/python/tokenspeed/runtime/disaggregation/embedding/encode_scheduler.py new file mode 100644 index 00000000000..45f834b47c3 --- /dev/null +++ b/python/tokenspeed/runtime/disaggregation/embedding/encode_scheduler.py @@ -0,0 +1,114 @@ +# Copyright (c) 2026 LightSeek Foundation +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +from __future__ import annotations + +"""Encode-stage batching for EPD disaggregation. + +The encode server runs the vision tower only, orchestrated in Python rather +than the C++ KV scheduler, so all it needs is to batch pending vision items +into a single ViT forward under a token budget -- that is +:class:`EncodeScheduler` below. + +The duplicate-image cache lives in +:mod:`tokenspeed.runtime.cache.embedding_cache`. The two are decoupled: the +encode loop checks the cache on arrival and feeds only *misses* to the +scheduler. +""" + +import dataclasses +from typing import Dict, List, Tuple + + +@dataclasses.dataclass(frozen=True) +class PendingEncodeItem: + """One vision item awaiting encode, identified within its request. + + ``cost`` is the item's vision-token (patch) count, used as the batching + budget unit. + """ + + request_id: str + item_index: int + cost: int + + @property + def key(self) -> Tuple[str, int]: + return (self.request_id, self.item_index) + + +class EncodeScheduler: + """Deterministic patch-budget batcher for the encode (vision-tower) stage. + + Collects pending vision items (cache misses) and packs them into batches + bounded by a per-batch token budget and a max item count. Ordering is + deterministic across tensor-parallel ranks -- items are sorted by + ``(request_id, item_index)`` -- so every rank forms an identical ViT batch. + This matters because the vision tower can be tensor-parallel; non-identical + batches across ranks would deadlock the NCCL collectives inside it. + + Greedy packing: items are admitted in order until the next one would exceed + ``max_tokens_per_batch`` or ``max_items_per_batch``. A single item whose + cost alone exceeds the token budget is still returned alone, so it always + makes progress. + """ + + def __init__(self, max_tokens_per_batch: int, max_items_per_batch: int): + if max_tokens_per_batch <= 0: + raise ValueError( + f"max_tokens_per_batch must be > 0, got {max_tokens_per_batch}" + ) + if max_items_per_batch <= 0: + raise ValueError( + f"max_items_per_batch must be > 0, got {max_items_per_batch}" + ) + self.max_tokens_per_batch = max_tokens_per_batch + self.max_items_per_batch = max_items_per_batch + self._pending: Dict[Tuple[str, int], PendingEncodeItem] = {} + + def add(self, item: PendingEncodeItem) -> None: + # Idempotent on (request_id, item_index): a re-added item overwrites. + self._pending[item.key] = item + + def pending_size(self) -> int: + return len(self._pending) + + def _ordered_pending(self) -> List[PendingEncodeItem]: + # Sort by (request_id, item_index) for cross-rank determinism. + return [self._pending[k] for k in sorted(self._pending.keys())] + + def next_batch(self) -> List[PendingEncodeItem]: + """Pop and return the next deterministic batch of items to encode. + + Empty when nothing is pending. Removes the returned items from the + pending set. + """ + batch: List[PendingEncodeItem] = [] + used = 0 + for it in self._ordered_pending(): + if batch and ( + used + it.cost > self.max_tokens_per_batch + or len(batch) >= self.max_items_per_batch + ): + break + batch.append(it) + used += it.cost + del self._pending[it.key] + return batch diff --git a/python/tokenspeed/runtime/disaggregation/embedding/encode_worker.py b/python/tokenspeed/runtime/disaggregation/embedding/encode_worker.py new file mode 100644 index 00000000000..7b90cd2bf0a --- /dev/null +++ b/python/tokenspeed/runtime/disaggregation/embedding/encode_worker.py @@ -0,0 +1,192 @@ +# Copyright (c) 2026 LightSeek Foundation +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +from __future__ import annotations + +"""Encode-worker control loop for EPD (Python orchestration). + +This is the body the engine's encode event loop drives: it sits between request +arrival and the vision tower. On ``submit`` it registers the request's transfer +peer and, per item, either resolves the embedding from the cache (skip the +tower, still transfer) or queues it on the scheduler. Each ``step`` pulls one +deterministic batch off the scheduler, runs the tower + ships it via the +executor, and populates the cache. + +The model load, mooncake manager construction, request transport and the +event-loop wiring are supplied by the engine integration; this class only +orchestrates them, so it is unit-testable with fakes. +""" + +import dataclasses +from typing import List, Union + +from tokenspeed.runtime.cache.embedding_cache import ( + EmbeddingCache, + TieredEmbeddingCache, +) +from tokenspeed.runtime.disaggregation.embedding.encode_scheduler import ( + EncodeScheduler, + PendingEncodeItem, +) +from tokenspeed.runtime.multimodal.embedder import _item_token_count +from tokenspeed.runtime.multimodal.inputs import MultimodalDataItem +from tokenspeed.runtime.multimodal.shm_transport import ShmTensorHandle +from tokenspeed.runtime.utils import get_colorful_logger + +logger = get_colorful_logger(__name__) + + +@dataclasses.dataclass(frozen=True) +class EncodeRequest: + """One encode request: a transfer peer plus its vision items. + + ``bootstrap_host``/``port``/``room`` identify the prefill peer this + request's embeddings are shipped to (assigned upstream, per request). + """ + + request_id: str + bootstrap_host: str + bootstrap_port: int + bootstrap_room: int + items: List[MultimodalDataItem] + + +def _nbytes(tensor) -> int: + return tensor.numel() * tensor.element_size() + + +class EncodeWorker: + """Orchestrates cache + scheduler + executor for the encode role. + + Injected with the executor (real ``DisaggEncodeExecutor`` or a fake), an + ``EncodeScheduler`` and an embedding cache (single-tier ``EmbeddingCache`` or + the two-tier ``TieredEmbeddingCache``; only ``get``/``put`` are used) so the + control flow is testable without a GPU or transport. + """ + + def __init__( + self, + executor, + scheduler: EncodeScheduler, + cache: Union[EmbeddingCache, TieredEmbeddingCache], + ): + self.executor = executor + self.scheduler = scheduler + self.cache = cache + # (request_id, item_index) -> item awaiting the tower + self._pending: dict = {} + + def submit(self, request: EncodeRequest) -> None: + self.executor.register( + request.request_id, + request.bootstrap_host, + request.bootstrap_port, + request.bootstrap_room, + ) + for idx, item in enumerate(request.items): + cached = self.cache.get(item.hash) + if isinstance(item.feature, ShmTensorHandle): + # EPD pixel-SHM: the servicer published pixels to POSIX SHM and + # the ZMQ hop carried only this handle (hash/pad_value were set on + # the real tensor before publish). consume() unlinks, so segments + # never outlive the item: materialize on a miss, and on a hit still + # consume-and-drop to unlink the unused segment. + handle, item.feature = item.feature, None + handle.attach() + if cached is None: + item.feature = handle.consume() + else: + handle.consume() + if cached is not None: + # Cache hit: tower skipped, but the embedding still must reach + # the prefill peer, so ship it directly. Entries are + # (main, deepstack) pairs and BOTH halves must be restored, else + # the prefill publishes a never-written deepstack buffer. Tolerate + # a bare tensor for legacy/test-seeded entries. + if isinstance(cached, tuple): + item.encoded, item.encoded_deepstack = cached + else: + item.encoded = cached + self.executor.send_item(request.request_id, item) + else: + self.scheduler.add( + PendingEncodeItem( + request_id=request.request_id, + item_index=idx, + cost=_item_token_count(item), + ) + ) + self._pending[(request.request_id, idx)] = item + + def step(self) -> int: + """Run one scheduler batch through the tower + transfer. Returns the + number of items encoded (0 when nothing is pending).""" + self.executor.reap_concluded_senders({rid for (rid, _idx) in self._pending}) + # Retry sends that couldn't lease a ring slot last tick (non-blocking). + self.executor.drain_deferred() + # Backpressure: if sends are STILL deferred after the drain, the bounce + # ring is saturated (all slots hold in-flight transfers). Pulling more ViT + # now would only pile fresh embeddings into _deferred_sends -- each pins a + # GPU embedding tensor with no slot to ship it, growing an unbounded + # backlog into an OOM. Skip this tick; the loop yields the GIL (encode_loop + # sees has_deferred) so the transfer daemons free slots, then we resume. + if self.executor.has_deferred(): + return 0 + batch = self.scheduler.next_batch() + if not batch: + return 0 + request_items = [(p.request_id, self._pending[p.key]) for p in batch] + try: + self.executor.execute(request_items) + except Exception as e: + # A tower-step contract violation (ViT output not matching the items' + # post-merge token count, or the forward itself) must fail only the + # rooms in THIS batch, not propagate out into the engine's SIGUSR1 + # handler, which would kill the worker and drop every other request's + # in-flight image. These raises fire before any send is issued, so + # concluding the batch Failed never poisons an already-shipped room. + # Per-item STAGING errors are handled finer-grained inside + # _stage_and_send -> _fail_staged_room. + n_failed = self.executor.fail_rooms((rid for rid, _ in request_items), e) + for p in batch: + self._pending.pop(p.key, None) + logger.error( + "encode batch failed (%d rooms concluded Failed): %s", n_failed, e + ) + return 0 + for p in batch: + item = self._pending.pop(p.key) + if item.encoded is not None: + # Cache the (main, deepstack) PAIR: caching only the main half + # would make every later hit ship a deepstack-less transfer, + # publishing uninitialized rows on the prefill. + deep = item.encoded_deepstack + nbytes = _nbytes(item.encoded) + ( + _nbytes(deep) if deep is not None else 0 + ) + self.cache.put(item.hash, (item.encoded, deep), nbytes) + return len(batch) + + def has_pending(self) -> bool: + return self.scheduler.pending_size() > 0 + + def has_deferred(self) -> bool: + """True while sends are queued waiting for a free ring slot (executor).""" + return self.executor.has_deferred() diff --git a/python/tokenspeed/runtime/disaggregation/embedding/prefill_receiver.py b/python/tokenspeed/runtime/disaggregation/embedding/prefill_receiver.py new file mode 100644 index 00000000000..28af4039d4c --- /dev/null +++ b/python/tokenspeed/runtime/disaggregation/embedding/prefill_receiver.py @@ -0,0 +1,1057 @@ +# Copyright (c) 2026 LightSeek Foundation +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +from __future__ import annotations + +"""EPD prefill-side receive glue: fill each multimodal item's ``encoded`` +tensor from the Mooncake transfer instead of running the vision tower. + +Inverse of ``encode_executor.assign_encoded_embeddings``: the encode worker +row-splits the tower output per item and column-splits the deepstack half; here +the prefill allocates a receive buffer sized to each item's post-merge token +count (and deepstack width), registers it with that item's encode worker via +:class:`MooncakeEmbeddingReceiver`, waits for the push, and assigns the result +onto ``item.encoded`` / ``item.encoded_deepstack`` -- the ``skip-ViT`` form the +prefill ``VisionEmbedder`` consumes (it never re-encodes an item whose +``encoded`` is already set). A wrong token count or deepstack width mis-sizes the +RDMA target (silent corruption), so buffer-sizing + assignment is isolated and +CPU-unit-testable with a fake receiver. + +Poll-driven state machine (:class:`EmbeddingReceiveJob`): ``start()`` does only +the non-blocking Phase-1 allocation + receiver construction (it must NEVER block +the prefill event loop); ``poll()`` advances every receiver a little each cycle +and publishes ``item.encoded`` only once EVERY handshaked item has landed. The +scheduler holds the job and does not admit the request to a prefill forward until +``poll()`` returns ``DONE``. + +``receive_encoded_embeddings`` is a thin BLOCKING wrapper (start + spin poll) for +synchronous callers and the CPU tests. +""" + +import logging +import os +import time +from collections import deque +from typing import Any, Callable, List, Mapping, Optional, Sequence, Tuple + +import torch +import torch.distributed as dist + +logger = logging.getLogger(__name__) + +from tokenspeed.runtime.disaggregation.base.poll import TransferPoll +from tokenspeed.runtime.disaggregation.embedding.embedding_transfer import ( + MooncakeEmbeddingReceiver, +) +from tokenspeed.runtime.multimodal.embedder import _item_token_count +from tokenspeed.runtime.multimodal.inputs import MultimodalDataItem + +# (manager, bootstrap_addr, bootstrap_room) -> receiver. Defaults to the real +# MooncakeEmbeddingReceiver; overridden in tests with a fake. +ReceiverFactory = Callable[[Any, str, int], Any] + +# poll() return values (the per-job lifecycle status, distinct from the +# per-receiver Poll status it aggregates). +PENDING = "pending" +DONE = "done" +FAILED = "failed" + +# Deregistering a receive MR the instant its Success notif arrives races the +# NIC's DMA placement tail (Success is the transport ACK, not proof the last +# bytes cleared HCA->PCIe), tripping `local access violation work queue error`. +# So deregistration is DEFERRED: entries hold the tensor ref (the allocator +# cannot reuse a still-registered address -- the no-double-register invariant) +# and are swept after a grace period, on the scheduler loop (no thread, no lock). +_DEREG_DELAY_S = float(os.environ.get("EPD_RECV_DEREG_DELAY_S", "0.5")) +# (due_monotonic, engine, [(tensor, ptr), ...]) in due order (delay is constant). +_pending_dereg: deque = deque() + + +def _lazy_deregister(engine: Any, tensors: List[Tuple[torch.Tensor, int]]) -> None: + _pending_dereg.append((time.monotonic() + _DEREG_DELAY_S, engine, tensors)) + _sweep_deregister() + + +def _sweep_deregister() -> None: + now = time.monotonic() + while _pending_dereg and _pending_dereg[0][0] <= now: + _, engine, tensors = _pending_dereg.popleft() + for _tensor, ptr in tensors: + try: + engine.deregister(ptr) + except Exception: # noqa: BLE001 -- best-effort; worst case the MR leaks + pass + + +class _RecvBufferPool: + """Pre-registered, lifetime-stable receive slots for E->P embedding lands. + + With per-request buffers, deregistering then re-registering a recycled + allocator address mints a NEW rkey for the same range while the encode side's + Mooncake segment cache still resolves it to the OLD rkey -- every reuse risks + a `local access violation work queue error` that kills the QP. The pool + registers ONE region for the engine's lifetime, so the sender's cached + mapping can never go stale; requests lease slots, the publish path clones the + landed rows out, and the slot returns immediately. + + Failure path: a FAILED job may still have an in-flight remote write targeting + its slot, which under a single lifetime MR would land SILENTLY in the next + tenant's data, so failed slots sit in quarantine until the transfer layer's + timeouts have expired (EPD_RECV_POOL_QUARANTINE_S). + + Single-threaded by design: all callers run on the scheduler loop (no locks). + """ + + def __init__(self, engine: Any, device: Any, slot_bytes: int, n_slots: int): + self.engine = engine + self.slot_bytes = slot_bytes + self.buf = torch.empty(n_slots * slot_bytes, dtype=torch.uint8, device=device) + engine.register(self.buf.data_ptr(), self.buf.numel()) + self._free = list(range(n_slots)) + self._quarantine: deque = deque() # (release_due_monotonic, slot) + + def lease(self, nbytes: int) -> Optional[int]: + now = time.monotonic() + while self._quarantine and self._quarantine[0][0] <= now: + self._free.append(self._quarantine.popleft()[1]) + if nbytes > self.slot_bytes or not self._free: + return None + return self._free.pop() + + def view(self, slot: int, nbytes: int, dtype: torch.dtype, shape) -> torch.Tensor: + off = slot * self.slot_bytes + return self.buf[off : off + nbytes].view(dtype).reshape(shape) + + def release(self, slot: int) -> None: + self._free.append(slot) + + def quarantine(self, slot: int, delay_s: float) -> None: + self._quarantine.append((time.monotonic() + delay_s, slot)) + + +# (id(engine), str(device)) -> _RecvBufferPool | False (False = disabled). +_POOLS: dict = {} + + +def _get_pool(engine: Any, device: Any) -> Optional[_RecvBufferPool]: + key = (id(engine), str(device)) + pool = _POOLS.get(key) + if pool is None: + n_slots = int(os.environ.get("EPD_RECV_POOL_SLOTS", "16")) + slot_mb = int(os.environ.get("EPD_RECV_POOL_SLOT_MB", "256")) + if n_slots <= 0 or slot_mb <= 0: + pool = False + else: + pool = _RecvBufferPool(engine, device, slot_mb << 20, n_slots) + logger.info( + "EPD recv pool up: %d slots x %d MB (lifetime MR)", n_slots, slot_mb + ) + _POOLS[key] = pool + return pool or None + + +def shard_rows(span: int, shard_rank: int, shard_size: int) -> tuple[int, int]: + """Balanced contiguous row shard of ``span`` rows across ``shard_size`` + ranks: returns this rank's ``(row_start, row_count)``. The first + ``span % shard_size`` ranks get one extra row; shards tile ``[0, span)`` + disjointly and in rank order, which BOTH sides of the transfer (the + receiver's pre_alloc and the post-receive reassembly) must derive from this + one function so their geometry can never diverge. ``row_count`` may be 0 + when ``span < shard_size`` (tiny images).""" + base, rem = divmod(span, shard_size) + start = shard_rank * base + min(shard_rank, rem) + count = base + (1 if shard_rank < rem else 0) + return start, count + + +class _ItemReceive: + """Per-item receive bookkeeping for one :class:`EmbeddingReceiveJob`. + + Holds the single ``[n_tokens, hidden]`` receive buffer (+ optional deepstack + column buffer) and one receiver per owned image, each targeting a contiguous + row sub-range of that buffer. The buffers are filled in place by the encode + side's RDMA writes; this object publishes them onto the item only once every + one of its receivers reaches ``Success`` (handled by the owning job). + """ + + __slots__ = ( + "item", + "recv_main", + "recv_deepstack", + "receivers", + "pre_alloced", + "main_slice_ptrs", + "deepstack_slice_ptrs", + "spans", + "row_starts", + "row_counts", + "sharded", + "n_tokens", + "hidden", + "pool", + "pool_slot", + ) + + def __init__( + self, + item: MultimodalDataItem, + recv_main: torch.Tensor, + recv_deepstack: Optional[torch.Tensor], + receivers: List[Any], + main_slice_ptrs: List[int], + deepstack_slice_ptrs: List[int], + spans: List[int], + row_starts: List[int], + row_counts: List[int], + sharded: List[bool], + n_tokens: int, + hidden: int, + pool: Optional[_RecvBufferPool] = None, + pool_slot: Optional[int] = None, + ): + self.item = item + self.recv_main = recv_main + self.recv_deepstack = recv_deepstack + self.receivers = receivers + self.pool = pool + self.pool_slot = pool_slot + # Lazy-pre_alloc latch, one per receiver (index-aligned): each receiver's + # pre_alloc must be issued exactly once, AFTER it reports Bootstrapped, and + # never again (a second pre_alloc would double-register the transfer). + self.pre_alloced = [False] * len(receivers) + self.main_slice_ptrs = main_slice_ptrs + self.deepstack_slice_ptrs = deepstack_slice_ptrs + self.spans = spans + # Per-image shard geometry (index-aligned with receivers/spans): this + # rank's row sub-range WITHIN the image, and whether the image was + # sharded at all (identity images need no reassembly broadcast). + self.row_starts = row_starts + self.row_counts = row_counts + self.sharded = sharded + self.n_tokens = n_tokens + self.hidden = hidden + + +class EmbeddingReceiveJob: + """Poll-driven, non-blocking EPD embedding receive for ONE request. + + Usage (driven by the scheduler/event loop): + + job = start_embedding_receive(items, manager, ...) + # ... each cycle, until DONE/FAILED: + status = job.poll() # PENDING | DONE | FAILED + + ``start()`` (the constructor) runs Phase-1 only: it sizes + allocates each + handshaked item's receive buffer, registers it with the Mooncake engine, and + constructs one :class:`MooncakeEmbeddingReceiver` on the item's room (the + receiver's own ``__init__`` performs the bootstrap handshake). It does NOT + wait for any transfer and does NOT call ``pre_alloc`` -- that is deferred to + ``poll()``, which issues each ``pre_alloc`` lazily once its receiver reports + Bootstrapped and then waits (across cycles, never blocking) for Success. + + HARD CONSTRAINT: one room/receiver PER ITEM. A single request's + items may be served by DIFFERENT encode workers, so collapsing to one + receiver per request is not possible. ``poll()`` returns DONE only when every + item's receiver is Success. + + Buffer lifetime: by default the receive target is a leased slot from the + lifetime-registered :class:`_RecvBufferPool`; on DONE the landed rows are + cloned onto ``item.encoded`` and the slot returns immediately (no MR churn, + see the pool docstring). Deepstack models, oversized items, pool + exhaustion, or ``EPD_RECV_POOL_SLOTS=0`` fall back to a per-request + buffer registered on start and lazily deregistered after publish. The GPU + cost per request is roughly ``n_tokens * hidden * dtype.itemsize`` (plus + ``* (1 + num_deepstack)`` with deepstack); the caller should cap the + number of in-flight jobs accordingly. + + Idempotent re-`start`/poll: items whose ``item.encoded`` is already set + (chunked prefill re-runs the receive per Path-4 forward on the same item) are + SKIPPED at start time -- no receiver is constructed for them. + """ + + def __init__( + self, + items: Sequence[MultimodalDataItem], + manager: Any, + *, + hidden: int, + num_deepstack: int, + dtype: torch.dtype, + device: torch.device | str, + receiver_factory: Optional[ReceiverFactory] = None, + shard_rank: int = 0, + shard_size: int = 1, + ): + self.manager = manager + self.hidden = hidden + self.num_deepstack = num_deepstack + # Row sharding across the attn-TP group: with shard_size > 1 this rank + # registers only its shard_rows() sub-range of each image; after the + # rank-agreed DONE the caller MUST run reassemble() (rank-lockstep) to + # rebuild the full rows before any forward consumes item.encoded. + # shard_size <= 1 is a plain full copy (no reassemble). + self._shard_rank = shard_rank + self._shard_size = shard_size + # torch.dtype is used for buffer allocation (no dtype lost in a string + # round-trip); the string is only the encode-side wire contract in pre_alloc. + self.dtype = dtype + self.dtype_str = str(dtype) + self._factory: ReceiverFactory = receiver_factory or MooncakeEmbeddingReceiver + # Terminal latch: once DONE/FAILED, poll() is a cheap no-op returning it + # (the receivers/buffers have been torn down). + self._status: str = PENDING + + # Phase 1 (non-blocking): for each item carrying an encode handshake + # (``item.encode_handshake``), allocate ONE [n_tokens, hidden] buffer + # (+ deepstack columns), register it with the Mooncake engine, and build a + # single receiver on the item's room. The handshake lives ON the item: the + # gateway mints one room per item and the encode worker row-splits the + # concatenated-subgrid embedding per item -- so one item == one room == one + # embedding. + self._items: List[_ItemReceive] = [] + for item in items: + handshake = getattr(item, "encode_handshake", None) + if handshake is None: + # No EPD-routed embedding on this item; leave it for the tower. + continue + + # Chunked prefill re-runs the receive per forward on the SAME item; + # ``encoded`` is set only after Success, so ``encoded is not None`` + # means fully received -- skip it (re-bootstrapping a Success room + # would never re-report Bootstrapped and would stick). Mirrors + # ``VisionEmbedder``, which never re-encodes an encoded item. + if item.encoded is not None: + continue + + self._items.append(self._start_item(item, handshake, device)) + + # Nothing to receive (text-only / all-already-encoded / no EPD item): + # the job is immediately DONE so the scheduler admits the request at once. + if not self._items: + self._status = DONE + + def _start_item( + self, + item: MultimodalDataItem, + handshake: Mapping[str, Any], + device: torch.device | str, + ) -> _ItemReceive: + """Allocate + register one item's receive buffer and construct its single + receiver on the item's room, recording the (possibly sharded) destination + row range so ``poll()`` can lazily issue ``pre_alloc`` once the receiver + bootstraps. Does NOT block on any transfer (no ``_wait``, no ``pre_alloc`` + here). + + One room per item: the encode worker concatenates the item's subgrid + tokens into a single ``[n_tokens, hidden]`` embedding and row-splits it per + prefill TP rank, so the receive geometry spans the item's FULL token count + (sum of its offset spans), not per offset. + """ + elt = torch.empty(0, dtype=self.dtype).element_size() + + # The item's image spans all its concatenated subgrid tokens. + span = _item_token_count(item) + addr = f"{handshake['bootstrap_host']}:{handshake['bootstrap_port']}" + # The receiver __init__ performs the bootstrap handshake (HTTP /route fetch + # + endpoint registration); on return its poll() is already Bootstrapped or + # Failed. We do NOT pre_alloc here -- poll() does it once Bootstrapped. + receiver = self._factory(self.manager, addr, int(handshake["bootstrap_room"])) + + # Row sharding across the attn-TP group: this rank registers only its + # shard_rows() sub-range, or the full image when sharding is off. + is_sharded = self._shard_size > 1 + if is_sharded: + row_start, row_count = shard_rows(span, self._shard_rank, self._shard_size) + else: + row_start, row_count = 0, span + # Length-1 per-image lists so poll()/_packed_to_full()/reassemble() iterate + # unchanged (one item == one image under per-item rooms). + receivers: List[Any] = [receiver] + spans: List[int] = [span] + row_starts: List[int] = [row_start] + row_counts: List[int] = [row_count] + sharded: List[bool] = [is_sharded] + + # The RECEIVE buffer holds only THIS rank's shard rows, packed contiguously + # (image i at rows [packed_cursor, packed_cursor + row_count)); the FULL + # embedding is rebuilt later in item.encoded (publish scatter + reassemble), + # which needs no MR. Registering just the shard rows -- not the full image + # -- keeps a big multi-image item from overflowing a recv pool slot onto + # the GIL-held per-request register fallback. With nothing sharded, + # packed_tokens == full_tokens. + full_tokens = _item_token_count(item) + packed_tokens = sum(row_counts) + nbytes = packed_tokens * self.hidden * elt + pool = None + pool_slot = None + recv_main = None + if self.num_deepstack == 0: + # Preferred path: lease a lifetime-registered pool slot (see + # _RecvBufferPool for why per-request register/deregister kills QPs). + # Deepstack models keep the legacy path (a second buffer per item, + # out of the pool's scope). + pool = _get_pool(self.manager.engine, device) + if pool is not None: + pool_slot = pool.lease(nbytes) + if pool_slot is not None: + recv_main = pool.view( + pool_slot, nbytes, self.dtype, (packed_tokens, self.hidden) + ) + else: + logger.info( + "EPD recv pool: no slot for %d B (free=%d); falling back " + "to per-request registration", + nbytes, + len(pool._free), + ) + pool = None + if recv_main is None: + recv_main = torch.empty( + (packed_tokens, self.hidden), dtype=self.dtype, device=device + ) + # Legacy fallback (pool disabled/exhausted, oversized item, or + # deepstack present): register per request; the deregister is DEFERRED + # on the publish/fail paths (lazy queue) to soften -- not eliminate -- + # the stale-rkey window. A 0-row packed buffer has nothing to register. + if packed_tokens > 0: + self.manager.engine.register( + recv_main.data_ptr(), + recv_main.numel() * recv_main.element_size(), + ) + recv_deepstack: Optional[torch.Tensor] = None + if self.num_deepstack > 0: + recv_deepstack = torch.empty( + (packed_tokens, self.hidden * self.num_deepstack), + dtype=self.dtype, + device=device, + ) + if packed_tokens > 0: + self.manager.engine.register( + recv_deepstack.data_ptr(), + recv_deepstack.numel() * recv_deepstack.element_size(), + ) + + # Destination pointers into the PACKED buffer: the encode side writes its + # n_tokens(=row_count) source rows CONTIGUOUSLY at this pointer (it does + # not re-apply row_start -- that only selects which SOURCE rows to read). + # A 0-row shard still records its (empty) pointer; its pre_alloc is the + # registration heartbeat the encode fanout gate counts. + main_slice_ptrs: List[int] = [] + deepstack_slice_ptrs: List[int] = [] + packed_cursor = 0 + for row_count in row_counts: + main_slice_ptrs.append( + recv_main[packed_cursor : packed_cursor + row_count].data_ptr() + ) + if recv_deepstack is not None: + deepstack_slice_ptrs.append( + recv_deepstack[packed_cursor : packed_cursor + row_count].data_ptr() + ) + else: + deepstack_slice_ptrs.append(0) + packed_cursor += row_count + + return _ItemReceive( + item=item, + recv_main=recv_main, + recv_deepstack=recv_deepstack, + receivers=receivers, + main_slice_ptrs=main_slice_ptrs, + deepstack_slice_ptrs=deepstack_slice_ptrs, + spans=spans, + row_starts=row_starts, + row_counts=row_counts, + sharded=sharded, + n_tokens=full_tokens, + hidden=self.hidden, + pool=pool, + pool_slot=pool_slot, + ) + + def poll(self) -> str: + """Advance the receive state machine one cheap step. + + For every still-pending receiver: if it just reached Bootstrapped, issue + its (single) ``pre_alloc`` so the encode side learns where to write; if it + reached Failed -> the whole job is FAILED; otherwise leave it. When EVERY + receiver of EVERY item is Success, deregister the buffers, publish + ``item.encoded`` / ``item.encoded_deepstack``, and return DONE. + + Returns ``PENDING`` | ``DONE`` | ``FAILED``. Idempotent after a terminal + result (the buffers/receivers are gone, so it just returns the latch). + """ + _sweep_deregister() + if self._status is not PENDING: + return self._status + + all_success = True + for it in self._items: + for idx, receiver in enumerate(it.receivers): + status = receiver.poll() + if status == TransferPoll.Failed: + self._fail() + return FAILED + if not it.pre_alloced[idx] and status in ( + TransferPoll.Bootstrapped, + TransferPoll.Transferring, + TransferPoll.Success, + ): + # Bootstrapped (or already further along on a fast/in-process + # transport): issue the one-shot pre_alloc and latch it -- a + # second would double-register the transfer on the encode side. + # In shard mode n_tokens carries this rank's row COUNT and the + # dst pointers are already offset to the shard's first row; a + # row_count of 0 is still sent (it doubles as the encode-side + # fanout-gate heartbeat). + receiver.pre_alloc( + dst_embedding_ptr=it.main_slice_ptrs[idx], + n_tokens=it.row_counts[idx], + hidden=it.hidden, + dtype=self.dtype_str, + dst_deepstack_ptr=it.deepstack_slice_ptrs[idx], + has_deepstack=self.num_deepstack > 0, + row_start=it.row_starts[idx], + span=it.spans[idx], + ) + it.pre_alloced[idx] = True + # Re-poll once after pre_alloc: an in-process/fake transport + # may flip straight to Success on pre_alloc. + status = receiver.poll() + if status == TransferPoll.Failed: + self._fail() + return FAILED + if status != TransferPoll.Success: + all_success = False + + if not all_success: + return PENDING + + # Every image of every item has landed; publish and reclaim. Pooled + # path: clone the landed rows OUT of the slot (item.encoded must outlive + # the lease) and return the slot at once. Legacy path: hand the buffer + # itself to item.encoded and queue the registration for DEFERRED drop + # (the lazy entry holds the tensor ref, so the allocator cannot recycle + # a still-registered address). + for it in self._items: + any_sharded = any(it.sharded) + if it.pool is not None: + # Pooled path is deepstack-free. Copy the rows OUT of the slot + # before releasing it. When sharded the buffer is packed (this + # rank's rows only), so scatter into a full-layout tensor at each + # image's absolute offset (reassemble fills the rest); when not + # sharded the buffer is already full -> clone it. + it.item.encoded = ( + self._packed_to_full(it, it.recv_main, self.hidden) + if any_sharded + else it.recv_main.clone() + ) + it.item.encoded_deepstack = None + it.pool.release(it.pool_slot) + else: + # Legacy path. When sharded, the packed buffers are smaller than + # the image and cannot alias item.encoded, so build separate full + # tensors; when not sharded, hand the (full) buffers over directly. + if any_sharded: + it.item.encoded = self._packed_to_full( + it, it.recv_main, self.hidden + ) + it.item.encoded_deepstack = ( + self._packed_to_full( + it, it.recv_deepstack, self.hidden * self.num_deepstack + ) + if it.recv_deepstack is not None + else None + ) + else: + it.item.encoded = it.recv_main + it.item.encoded_deepstack = it.recv_deepstack + pairs = [(it.recv_main, it.recv_main.data_ptr())] + if it.recv_deepstack is not None: + pairs.append((it.recv_deepstack, it.recv_deepstack.data_ptr())) + _lazy_deregister(self.manager.engine, pairs) + # Receive concluded: release each room's bookkeeping from the prefill manager. + self._clear_receivers() + self._status = DONE + return DONE + + def _packed_to_full( + self, it: "_ItemReceive", packed: torch.Tensor, width: int + ) -> torch.Tensor: + """Scatter a PACKED shard buffer (this rank's rows, image-contiguous) into + a full-layout ``[n_tokens, width]`` tensor, placing each image's shard at + its absolute row offset and leaving the non-owned rows for ``reassemble`` + to fill. The packed buffer holds ``sum(row_counts)`` rows; the full tensor + holds ``sum(spans)`` rows (== n_tokens). Identity images (row_count==span, + row_start==0) copy whole, so a buffer with no real sharding round-trips + unchanged.""" + full = torch.empty( + (it.n_tokens, width), dtype=packed.dtype, device=packed.device + ) + packed_cursor = 0 + full_cursor = 0 + for span, row_start, row_count in zip(it.spans, it.row_starts, it.row_counts): + if row_count > 0: + full[full_cursor + row_start : full_cursor + row_start + row_count] = ( + packed[packed_cursor : packed_cursor + row_count] + ) + packed_cursor += row_count + full_cursor += span + return full + + def reassemble(self, nccl_group: Any, group_ranks: Sequence[int]) -> None: + """Rebuild full embeddings from row shards via per-image broadcasts. + + Must be called RANK-LOCKSTEP on every attn-TP rank, only after the + rank-agreed DONE (the drain's MIN all-reduce) and BEFORE any forward + consumes ``item.encoded``: until then each rank's buffer holds only its + own shard rows, the rest is uninitialized memory. All ranks iterate the + identical items/images in identical order issuing identical collectives, + which also requires the caller to run on the NON-overlap event loop (a + second thread launching forward collectives concurrently would break the + cross-rank launch-order guarantee NCCL needs across communicators). + + ``group_ranks`` is the attn-TP group as GLOBAL ranks + (``mapping.attn.tp_group``): ``dist.broadcast`` takes a global src rank, + and group rank p == global rank p only in the no-DP single-engine case. + Per-image sub-range broadcasts (2 x shard_size x n_images launches per + request). + + No-op for identity images and when sharding is off; safe after _fail + (items were dropped). Idempotence is NOT required: called exactly once + per admitted request by the drain. + + Broadcasts target ``item.encoded`` (the PUBLISHED tensor), never + ``recv_main``: on the pooled path the publish step cloned the rows out + and RELEASED the slot, so ``recv_main`` may already belong to the next + tenant; on the legacy path ``item.encoded`` IS ``recv_main``, so the + two are equivalent there. + """ + if self._shard_size <= 1 or self._status is not DONE: + return + import torch.distributed as dist + + for it in self._items: + main = it.item.encoded + deep = it.item.encoded_deepstack + cursor = 0 + for idx, span in enumerate(it.spans): + if not it.sharded[idx]: + cursor += span + continue + for p in range(self._shard_size): + start, count = shard_rows(span, p, self._shard_size) + if count == 0: + continue + src = group_ranks[p] + dist.broadcast( + main[cursor + start : cursor + start + count], + src=src, + group=nccl_group, + ) + if deep is not None: + dist.broadcast( + deep[cursor + start : cursor + start + count], + src=src, + group=nccl_group, + ) + cursor += span + + def _clear_receivers(self) -> None: + """Release each receiver's per-room manager bookkeeping (terminal paths only; + no-op for fake receivers without clear()).""" + for it in self._items: + for receiver in it.receivers: + clear = getattr(receiver, "clear", None) + if clear is not None: + clear() + + def _fail(self) -> None: + """Tear down on failure and drop our references. A SIBLING image's + write may still be in flight into the item buffer, so reclamation is + deferred on both paths: pooled slots go to quarantine (under the + lifetime MR a late write would land SILENTLY in the next tenant's + data), legacy buffers go to the lazy-deregistration queue. + ``item.encoded`` is left unset -- the request is being failed, not + served. + """ + quarantine_s = float(os.environ.get("EPD_RECV_POOL_QUARANTINE_S", "10")) + for it in self._items: + if it.pool is not None: + it.pool.quarantine(it.pool_slot, quarantine_s) + else: + pairs = [(it.recv_main, it.recv_main.data_ptr())] + if it.recv_deepstack is not None: + pairs.append((it.recv_deepstack, it.recv_deepstack.data_ptr())) + _lazy_deregister(self.manager.engine, pairs) + self._clear_receivers() + self._items = [] + self._status = FAILED + + @property + def status(self) -> str: + return self._status + + def release(self) -> None: + """Best-effort teardown for an externally-driven abort. + + Used when a rank-agreed FAILED is reached but THIS rank had not yet seen a + local Failed poll (so its buffers are still registered): free/deregister + them so a reused allocator address is never left double-registered. + Idempotent and a no-op once terminal (poll() already tore a DONE/FAILED job + down). After release() the job is FAILED. + """ + if self._status is not PENDING: + return + self._fail() + + +def start_embedding_receive( + items: Sequence[MultimodalDataItem], + manager: Any, + *, + hidden: int, + num_deepstack: int, + dtype: torch.dtype, + device: torch.device | str, + receiver_factory: Optional[ReceiverFactory] = None, + shard_rank: int = 0, + shard_size: int = 1, +) -> EmbeddingReceiveJob: + """Begin (non-blocking) the per-item EPD embedding receive for one request. + + See :class:`EmbeddingReceiveJob`. The handshake for each EPD-routed item + rides on ``item.encode_handshake`` (a dict ``{bootstrap_room, bootstrap_host, + bootstrap_port}``); items without one are left to the vision tower. Returns a + job whose ``poll()`` the caller drives every cycle until DONE/FAILED; the + request must not be admitted to a prefill forward before then. With + ``shard_size > 1`` the caller must also run ``job.reassemble()`` rank- + lockstep after the rank-agreed DONE, before the request's first forward. + """ + return EmbeddingReceiveJob( + items, + manager, + hidden=hidden, + num_deepstack=num_deepstack, + dtype=dtype, + device=device, + receiver_factory=receiver_factory, + shard_rank=shard_rank, + shard_size=shard_size, + ) + + +def receive_encoded_embeddings( + items: Sequence[MultimodalDataItem], + manager: Any, + *, + hidden: int, + num_deepstack: int, + dtype: torch.dtype, + device: torch.device | str, + timeout: float = 60.0, + receiver_factory: Optional[ReceiverFactory] = None, +) -> None: + """BLOCKING wrapper: fill ``item.encoded`` from the per-item transfers. + + For synchronous callers and the CPU unit tests: the poll-driven + :class:`EmbeddingReceiveJob` spun to completion in place (start, then + busy-poll until DONE, raising on FAILED or timeout). Event-loop code should + drive ``poll()`` once per cycle instead. + + The handshake for each EPD-routed item rides on ``item.encode_handshake`` + (``{bootstrap_room, bootstrap_host, bootstrap_port}``). ``hidden`` is the main + embedding width, ``num_deepstack`` the deepstack level count (0 if absent), + and ``dtype`` must match the encode worker's tower output dtype (asserted on + the encode side before the unchecked RDMA write). + """ + job = start_embedding_receive( + items, + manager, + hidden=hidden, + num_deepstack=num_deepstack, + dtype=dtype, + device=device, + receiver_factory=receiver_factory, + ) + deadline = time.monotonic() + timeout + while True: + status = job.poll() + if status == DONE: + return + if status == FAILED: + raise RuntimeError("encode->prefill embedding transfer failed") + if time.monotonic() > deadline: + raise TimeoutError( + f"embedding receive timed out after {timeout:.1f}s " + f"(job still {status})" + ) + time.sleep(0.0005) + + +def build_prefill_embedding_manager( + server_args, world_size, global_rank, is_multimodal_active +): + """Stand up the EPD encode->prefill embedding sink, if applicable. + + Only a multimodal *prefill* node receives embeddings from encode workers. Built + dp_size=1 (the embedding transport allows prefill_tp = any multiple of + encode_tp) with no fixed base buffer (receive buffers are allocated per image at + receive time). Construction spawns a daemon status thread, so build it exactly + once per rank. Returns None for decode/encode/text-only nodes. + """ + if server_args.disaggregation_mode != "prefill" or not is_multimodal_active: + return None + + from tokenspeed.runtime.disaggregation.embedding.conn import EmbeddingManagerArgs + from tokenspeed.runtime.disaggregation.embedding.embedding_transfer import ( + EmbeddingArgs, + MooncakeEmbeddingManagerPrefill, + ) + + emb_mgr_args = EmbeddingManagerArgs( + bootstrap_port=server_args.disaggregation_bootstrap_port, + world_size=world_size, + dp_size=1, + ) + emb_args = EmbeddingArgs( + engine_rank=global_rank, + gpu_id=global_rank, + ib_device=server_args.disaggregation_ib_device, + embedding_data_ptr=0, + embedding_data_len=0, + ) + return MooncakeEmbeddingManagerPrefill(emb_mgr_args, emb_args) + + +class EpdPrefillAdmission: + """EPD prefill-side embedding receive + rank-synced admission. + + Owns the encode->prefill embedding sink (MooncakeEmbeddingManagerPrefill), the + set of requests whose per-image embeddings are still arriving (``_pending``), + and the optional NCCL row-shard reassembly. Exists ONLY on a multimodal prefill + node; the EventLoop holds one (or None) and drives it each non-overlap cycle. + + DECIDE/ACT split: ``drain()`` polls the staged receives, applies the rank- + lockstep MIN all-reduce + reassembly, and RETURNS ``(admitted, failed)`` + decisions. The EventLoop performs the acts those imply (P->D sender + register/abort, scheduler submit, output-processor finish) -- they touch + EventLoop collaborators, so they stay there. + """ + + def __init__( + self, + *, + manager, + device, + hidden, + num_deepstack, + dtype, + attn_tp_rank, + attn_tp_size, + attn_tp_cpu_group, + attn_tp_group, + pg_manager, + ): + from tokenspeed.runtime.utils.env import envs as _envs + + self._manager = manager + self._device = device + self._hidden = hidden + self._num_deepstack = num_deepstack + self._dtype = dtype + self._attn_tp_rank = attn_tp_rank + self._attn_tp_size = attn_tp_size + self._attn_tp_cpu_group = attn_tp_cpu_group + # Requests whose per-image encode->prefill embeddings are still arriving: + # registered but NOT yet submitted to the scheduler; drain() polls them each + # cycle and admits (rank-synced) only once ready. Rank-identical in + # length+order across attn-TP ranks (recv_reqs broadcasts the new-request + # set), which drain()'s MIN all-reduce relies on. + self._pending: list = [] + # Deadline for an EPD request's per-image embeddings to all arrive; past it + # the request is aborted (not waited on forever). Reuse the PD KV-receive + # wait knob (default 300s): the prefill waiting on the encode->prefill + # embedding transfer is the direct analog of the decode waiting on the + # prefill->decode KV transfer, so one operator knob covers both. + self._embed_timeout: float = float( + _envs.TOKENSPEED_DISAGGREGATION_WAITING_TIMEOUT.get() + ) + + # EPD embedding row-sharding: each attn-TP rank receives only 1/N of every + # image's rows over the wire; the full embedding is rebuilt by an NCCL + # all-gather in drain() (job.reassemble), which runs on the prefill's + # NON-overlap loop so the drain and the forward launch from one thread in + # the same order on every rank -- the cross-rank launch-order consistency + # NCCL requires across communicators. + self._shard_embeddings = False + self._nccl_group = None + self._group_ranks = tuple(attn_tp_group) + shard_flag = False + if attn_tp_size > 1: + shard_flag = bool(_envs.TOKENSPEED_EPD_EMBEDDING_SHARD.get()) + # The flag is a per-process env read but gates a GROUP collective: + # torn across ranks (e.g. set on one node of a multi-node prefill), + # flag-on ranks would join the warmup broadcast below while flag-off + # ranks never do -- a silent boot hang. Agree first, loud. + flag_t = torch.tensor( + [int(shard_flag), -int(shard_flag)], dtype=torch.int32 + ) + dist.all_reduce(flag_t, op=dist.ReduceOp.MIN, group=attn_tp_cpu_group) + if flag_t[0].item() != -flag_t[1].item(): + raise RuntimeError( + "TOKENSPEED_EPD_EMBEDDING_SHARD differs across attn-TP ranks; " + "set it identically on every node of the prefill engine" + ) + if shard_flag: + self._nccl_group = pg_manager.get_process_group("nccl", attn_tp_group) + self._shard_embeddings = True + # Warm the communicator at startup: NCCL initializes lazily on the + # first collective, and nothing else issues torch.distributed NCCL ops + # on this group in the scheduler process -- without this the FIRST + # admitted EPD request pays communicator init (hundreds of ms, all + # ranks) inside the drain, and a misconfigured group would surface on a + # customer request instead of at boot. + warmup = torch.zeros(1, device=device) + dist.broadcast(warmup, src=self._group_ranks[0], group=self._nccl_group) + torch.cuda.current_stream().synchronize() + logger.info( + "EPD embedding row-sharding enabled (attn_tp=%d, NCCL group warm)", + attn_tp_size, + ) + + def stage(self, request_id, mm_items) -> None: + """Begin the non-blocking per-image embedding receive and stage it by + request_id until its embeddings land (polled in drain()). The request payload + (spec/state/bootstrap) stays with the caller, keyed by request_id; this + controller tracks only the receive job (mirrors kv_transfer).""" + job = start_embedding_receive( + items=mm_items, + manager=self._manager, + hidden=self._hidden, + num_deepstack=self._num_deepstack, + dtype=self._dtype, + device=self._device, + shard_rank=self._attn_tp_rank, + shard_size=self._attn_tp_size if self._shard_embeddings else 1, + ) + self._pending.append((request_id, job, time.time())) + + def has_pending(self) -> bool: + return bool(self._pending) + + def drain(self): + """Poll staged EPD embedding receives; return ``(admitted_ids, failed_ids)``. + + poll/timeout/MIN-all-reduce/reassemble/release + ``_pending`` bookkeeping + happen here, rank-lockstep, keyed by request_id. The caller maps the ids back + to its staged request payloads and performs the acts (kv_transfer + register/abort, scheduler submit, output-processor finish). + + - admitted_ids: DONE on every rank, reassembled. + - failed_ids: FAILED/timed-out, job released. + """ + if not self._pending: + return [], [] # rank-identical emptiness -> all ranks skip the collective + + code_of = {FAILED: 0, PENDING: 1, DONE: 2} + codes = [code_of[job.poll()] for (_rid, job, _ts) in self._pending] + + # Timeout: a still-PENDING request whose per-image embeddings have not all + # arrived within the deadline is marked FAILED (-> rank-agreed abort below). + # Without this the prefill waits FOREVER if an embedding is ever lost (a + # degraded/dead encode worker, a network drop). Folded into the SAME MIN + # all-reduce: a timed-out job -> code 0 -> all ranks abort it together; + # union-of-timeout is rank-safe even if ranks cross the deadline a cycle + # apart (any rank's 0 propagates via MIN). + _now = time.time() + for _i in range(len(self._pending)): + if codes[_i] == 1 and (_now - self._pending[_i][2]) > self._embed_timeout: + codes[_i] = 0 + logger.warning( + "EPD embedding receive timed out after %.0fs for rid=%s; aborting", + self._embed_timeout, + self._pending[_i][0], + ) + + if self._attn_tp_size > 1: + t = torch.tensor(codes, dtype=torch.uint8, device="cpu") + dist.all_reduce(t, op=dist.ReduceOp.MIN, group=self._attn_tp_cpu_group) + codes = t.tolist() + + admitted = [] + failed = [] + leftover = [] + for (request_id, job, start_ts), code in zip(self._pending, codes): + if code == 2: # DONE on every rank + # Sharded receive: rebuild the full rows from the per-rank shards + # FIRST -- item.encoded is shard-only until this runs. Rank-lockstep- + # safe: codes are identical post-MIN and _pending is rank-identical + # in length/order, so every rank issues identical collectives in + # identical order this cycle. + if self._shard_embeddings: + job.reassemble(self._nccl_group, self._group_ranks) + admitted.append(request_id) + elif code == 0: # FAILED/timed-out on some rank -> abort everywhere + job.release() + failed.append(request_id) + else: # still pending on some rank + leftover.append((request_id, job, start_ts)) + self._pending = leftover + return admitted, failed + + +def make_epd_prefill_admission( + server_args, + global_rank, + *, + model_config, + model_executor, + mapping, + attn_tp_rank, + attn_tp_size, + attn_tp_cpu_group, + pg_manager, +): + """Build the EPD-prefill admission controller, or None for non-EPD nodes. + + Returns None unless this is a multimodal *prefill* node (the only node that + receives encode->prefill embeddings).""" + world_size = server_args.world_size or mapping.world_size + manager = build_prefill_embedding_manager( + server_args, world_size, global_rank, model_config.is_multimodal_active + ) + if manager is None: + return None + # Extract the narrow model facts the controller needs (vision dtype, hidden + # width, deepstack width, device) here -- the controller holds these, not the + # whole model_executor (mirrors how create_kv_transfer takes a kv_args struct). + model = model_executor.model_runner.model + return EpdPrefillAdmission( + manager=manager, + device=model_executor.device, + hidden=model.config.hidden_size, + num_deepstack=getattr(model, "num_deepstack_embeddings", 0), + dtype=(getattr(model, "visual", None) or model.vision_tower).dtype, + attn_tp_rank=attn_tp_rank, + attn_tp_size=attn_tp_size, + attn_tp_cpu_group=attn_tp_cpu_group, + attn_tp_group=mapping.attn.tp_group, + pg_manager=pg_manager, + ) diff --git a/python/tokenspeed/runtime/pd/base/__init__.py b/python/tokenspeed/runtime/disaggregation/kv/__init__.py old mode 100755 new mode 100644 similarity index 72% rename from python/tokenspeed/runtime/pd/base/__init__.py rename to python/tokenspeed/runtime/disaggregation/kv/__init__.py index 840f5a060dd..799b4746f14 --- a/python/tokenspeed/runtime/pd/base/__init__.py +++ b/python/tokenspeed/runtime/disaggregation/kv/__init__.py @@ -18,16 +18,11 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -from dataclasses import dataclass +"""KV-cache (prefill->decode) disaggregation -- the PD transfer stack. -from tokenspeed.runtime.pd.base.conn import ( - KVArgs, - KVPoll, -) - - -@dataclass -class BootstrapInfo: - bootstrap_host: str - bootstrap_port: int - bootstrap_room: int +Moves computed KV pages from a prefill server to a decode server over a +pluggable transport. The shared args/poll types live in :mod:`base`, the +backend managers in :mod:`mooncake`, the role executors in +:mod:`prefill_executor` / :mod:`decode_executor`, and transport selection in +:mod:`factory`. Import entry points from those submodules directly. +""" diff --git a/python/tokenspeed/runtime/pd/decode_executor.py b/python/tokenspeed/runtime/disaggregation/kv/decode_executor.py similarity index 87% rename from python/tokenspeed/runtime/pd/decode_executor.py rename to python/tokenspeed/runtime/disaggregation/kv/decode_executor.py index 79966917150..1f543e02427 100644 --- a/python/tokenspeed/runtime/pd/decode_executor.py +++ b/python/tokenspeed/runtime/disaggregation/kv/decode_executor.py @@ -24,12 +24,11 @@ import torch from tokenspeed_scheduler import PD, Forward -from tokenspeed.runtime.pd.base import BootstrapInfo, KVPoll -from tokenspeed.runtime.pd.mooncake import ( - MooncakeKVManagerDecode, - MooncakeKVReceiver, -) -from tokenspeed.runtime.pd.utils import ( +from tokenspeed.runtime.disaggregation.base.poll import TransferPoll +from tokenspeed.runtime.disaggregation.kv.mooncake.decode import MooncakeKVManagerDecode +from tokenspeed.runtime.disaggregation.kv.mooncake.receiver import MooncakeKVReceiver +from tokenspeed.runtime.disaggregation.kv.types import BootstrapInfo +from tokenspeed.runtime.disaggregation.kv.utils import ( TransferBackend, poll_and_all_reduce, ) @@ -114,6 +113,10 @@ def _prefill(self, op): ) for i, request_id in enumerate(op.request_ids): + if request_id not in self.receivers: + # Request failed and its receiver was cleaned up in generate_events; + # the scheduler may still dispatch its forward op one last time. + continue extend_prefix_len = op.extend_prefix_lens[i] kv_indices = np.array( op.occupied_pages[i][extend_prefix_len // self.page_size :], @@ -131,7 +134,7 @@ def _prefill(self, op): ) def register(self, request_id: str, bootstrap_info: BootstrapInfo): - self._local_states[request_id] = KVPoll.Bootstrapping + self._local_states[request_id] = TransferPoll.Bootstrapping self._bootstrap(request_id, bootstrap_info) def execute(self, op): @@ -147,29 +150,32 @@ def generate_events(self): to_remove = [] for req_id, poll in zip(list(self.receivers.keys()), polls): if ( - self._local_states[req_id] == KVPoll.Bootstrapping - and poll == KVPoll.Bootstrapped + self._local_states[req_id] == TransferPoll.Bootstrapping + and poll == TransferPoll.Bootstrapped ): logger.debug( "[decode][generate_events] rid=%s -> BootstrappedEvent", req_id ) events.append(PD.BootstrappedEvent(req_id)) - self._local_states[req_id] = KVPoll.Bootstrapped - elif poll == KVPoll.Failed: + self._local_states[req_id] = TransferPoll.Bootstrapped + elif poll == TransferPoll.Failed: logger.warning( "[decode][generate_events] rid=%s -> FailedEvent", req_id ) events.append(PD.FailedEvent(req_id)) + # Drop the failed receiver so it is not polled again. Without this + # a single failed request keeps re-emitting FailedEvent every loop + # (poll stays Failed), wedging the whole conn-1 scheduler. to_remove.append(req_id) elif ( - self._local_states[req_id] == KVPoll.Bootstrapped - and poll == KVPoll.Success + self._local_states[req_id] == TransferPoll.Bootstrapped + and poll == TransferPoll.Success ): - self._local_states[req_id] = KVPoll.Success # Read bootstrap_token from the ZMQ-delivered table in kv_manager. # The decode_thread stored it there when it received the Success status # message from the prefill side. bootstrap_room == bootstrap_info.bootstrap_room, # which is the key used in MooncakeKVReceiver. + self._local_states[req_id] = TransferPoll.Success bootstrap_room = self.receivers[req_id].bootstrap_room bootstrap_token, spec_candidate_ids = ( self.kv_manager.pop_prefill_metadata(bootstrap_room) diff --git a/python/tokenspeed/runtime/pd/disaggregation_decode_scheduler.py b/python/tokenspeed/runtime/disaggregation/kv/decode_scheduler.py similarity index 99% rename from python/tokenspeed/runtime/pd/disaggregation_decode_scheduler.py rename to python/tokenspeed/runtime/disaggregation/kv/decode_scheduler.py index eaa943411db..0793a600fc6 100755 --- a/python/tokenspeed/runtime/pd/disaggregation_decode_scheduler.py +++ b/python/tokenspeed/runtime/disaggregation/kv/decode_scheduler.py @@ -37,7 +37,7 @@ from tokenspeed.runtime.utils.server_args import ServerArgs -class DisaggregationDecodeScheduler: +class DisaggDecodeScheduler: def prepare_for_prebuilt_extend(self: ScheduleBatch): """ diff --git a/python/tokenspeed/runtime/pd/factory.py b/python/tokenspeed/runtime/disaggregation/kv/factory.py similarity index 91% rename from python/tokenspeed/runtime/pd/factory.py rename to python/tokenspeed/runtime/disaggregation/kv/factory.py index b8e6e092955..d090b7c90f6 100644 --- a/python/tokenspeed/runtime/pd/factory.py +++ b/python/tokenspeed/runtime/disaggregation/kv/factory.py @@ -20,14 +20,12 @@ """Factories for disaggregation KV transfer helpers.""" -from tokenspeed.runtime.pd.base import KVArgs -from tokenspeed.runtime.pd.decode_executor import DisaggDecodeExecutor -from tokenspeed.runtime.pd.mooncake.entities import ManagerArgs -from tokenspeed.runtime.pd.prefill_executor import DisaggPrefillExecutor -from tokenspeed.runtime.pd.utils import ( - DisaggregationMode, - TransferBackend, -) +from tokenspeed.runtime.disaggregation.kv.decode_executor import DisaggDecodeExecutor +from tokenspeed.runtime.disaggregation.kv.mooncake.entities import ManagerArgs +from tokenspeed.runtime.disaggregation.kv.prefill_executor import DisaggPrefillExecutor +from tokenspeed.runtime.disaggregation.kv.types import KVArgs +from tokenspeed.runtime.disaggregation.kv.utils import TransferBackend +from tokenspeed.runtime.disaggregation.utils import DisaggregationMode def _get_contiguous_buf_unit_lens(pool, item_lens): @@ -128,7 +126,7 @@ def get_kv_args( return kv_args -def create_pd_kv_transfer( +def create_kv_transfer( mode: DisaggregationMode, backend: TransferBackend, args: ManagerArgs, diff --git a/python/tokenspeed/runtime/pd/kv_events.py b/python/tokenspeed/runtime/disaggregation/kv/kv_events.py similarity index 100% rename from python/tokenspeed/runtime/pd/kv_events.py rename to python/tokenspeed/runtime/disaggregation/kv/kv_events.py diff --git a/python/tokenspeed/runtime/pd/mooncake/__init__.py b/python/tokenspeed/runtime/disaggregation/kv/mooncake/__init__.py similarity index 77% rename from python/tokenspeed/runtime/pd/mooncake/__init__.py rename to python/tokenspeed/runtime/disaggregation/kv/mooncake/__init__.py index 9e84196870d..0e68d40e994 100644 --- a/python/tokenspeed/runtime/pd/mooncake/__init__.py +++ b/python/tokenspeed/runtime/disaggregation/kv/mooncake/__init__.py @@ -18,16 +18,16 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -from tokenspeed.runtime.pd.mooncake.conn import MooncakeKVBootstrapServer -from tokenspeed.runtime.pd.mooncake.decode import ( +from tokenspeed.runtime.disaggregation.kv.mooncake.conn import MooncakeKVBootstrapServer +from tokenspeed.runtime.disaggregation.kv.mooncake.decode import ( MooncakeKVManagerDecode, ) -from tokenspeed.runtime.pd.mooncake.prefill import ( +from tokenspeed.runtime.disaggregation.kv.mooncake.prefill import ( MooncakeKVManagerPrefill, ) -from tokenspeed.runtime.pd.mooncake.receiver import ( +from tokenspeed.runtime.disaggregation.kv.mooncake.receiver import ( MooncakeKVReceiver, ) -from tokenspeed.runtime.pd.mooncake.sender import ( +from tokenspeed.runtime.disaggregation.kv.mooncake.sender import ( MooncakeKVSender, ) diff --git a/python/tokenspeed/runtime/pd/mooncake/async_conn.py b/python/tokenspeed/runtime/disaggregation/kv/mooncake/async_conn.py similarity index 96% rename from python/tokenspeed/runtime/pd/mooncake/async_conn.py rename to python/tokenspeed/runtime/disaggregation/kv/mooncake/async_conn.py index 05070f8a172..c6969190f40 100644 --- a/python/tokenspeed/runtime/pd/mooncake/async_conn.py +++ b/python/tokenspeed/runtime/disaggregation/kv/mooncake/async_conn.py @@ -27,20 +27,20 @@ import numpy as np import numpy.typing as npt -from tokenspeed.runtime.pd.base import KVArgs, KVPoll -from tokenspeed.runtime.pd.mooncake.entities import ( +from tokenspeed.runtime.disaggregation.base.poll import TransferPoll +from tokenspeed.runtime.disaggregation.kv.mooncake.entities import ( TransferInfo, TransferKVChunk, ) -from tokenspeed.runtime.pd.mooncake.prefill import ( +from tokenspeed.runtime.disaggregation.kv.mooncake.prefill import ( MooncakeKVManagerPrefill as MooncakeKVManager, ) -from tokenspeed.runtime.pd.utils import ( - DisaggregationMode, - FastQueue, +from tokenspeed.runtime.disaggregation.kv.types import KVArgs +from tokenspeed.runtime.disaggregation.kv.utils import ( StepCounter, group_concurrent_contiguous, ) +from tokenspeed.runtime.disaggregation.utils import DisaggregationMode, FastQueue from tokenspeed.runtime.utils import get_colorful_logger from tokenspeed.runtime.utils.server_args import ServerArgs @@ -171,7 +171,7 @@ def add_transfer_request( if ( bootstrap_room not in self.request_status - or self.check_status(bootstrap_room) == KVPoll.Failed + or self.check_status(bootstrap_room) == TransferPoll.Failed ): logger.debug( "Request with bootstrap_room=%s already failed", bootstrap_room @@ -500,9 +500,11 @@ def pop_transferred(tasks: List[LayerWiseTask]) -> List[LayerWiseTask]: def finalize(tasks: List[LayerWiseTask]) -> None: for task in tasks: kv_chunk = task.kv_chunk - status = KVPoll.Success if all(task.polls) else KVPoll.Failed + status = ( + TransferPoll.Success if all(task.polls) else TransferPoll.Failed + ) if ( - status == KVPoll.Failed or kv_chunk.is_last + status == TransferPoll.Failed or kv_chunk.is_last ): # last chunk or any failed self.update_status(kv_chunk.room, status) for packed_req in task.write_requests: @@ -513,7 +515,7 @@ def finalize(tasks: List[LayerWiseTask]) -> None: if ( kv_chunk.room not in self.request_status - or self.check_status(kv_chunk.room) == KVPoll.Success + or self.check_status(kv_chunk.room) == TransferPoll.Success ): if kv_chunk.room in self.transfer_infos: self.transfer_infos.pop(kv_chunk.room) diff --git a/python/tokenspeed/runtime/disaggregation/kv/mooncake/conn.py b/python/tokenspeed/runtime/disaggregation/kv/mooncake/conn.py new file mode 100644 index 00000000000..c85924a8e7d --- /dev/null +++ b/python/tokenspeed/runtime/disaggregation/kv/mooncake/conn.py @@ -0,0 +1,126 @@ +# Copyright (c) 2026 LightSeek Foundation +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +from __future__ import annotations + +from tokenspeed.runtime.disaggregation.base.bootstrap import DisaggBootstrapServer +from tokenspeed.runtime.disaggregation.base.manager import DisaggManagerBase +from tokenspeed.runtime.disaggregation.kv.mooncake.entities import ManagerArgs +from tokenspeed.runtime.disaggregation.kv.types import KVArgs +from tokenspeed.runtime.disaggregation.mooncake_transfer_engine import ( + MooncakeTransferEngine, +) +from tokenspeed.runtime.disaggregation.utils import DisaggregationMode +from tokenspeed.runtime.metrics.collector import KVTransferMetrics +from tokenspeed.runtime.utils.network import get_local_ip_by_remote + + +class MooncakeKVManagerBase(DisaggManagerBase): + """KV (prefill->decode) manager: the shared engine/socket/status FSM plus the + KV-specific args, MLA flags, dp-attention wiring, and metrics.""" + + def __init__( + self, + args: ManagerArgs, + kv_args: KVArgs, + disaggregation_mode: DisaggregationMode, + ): + self.args = args + self.kv_args = kv_args + self.attn_tp_rank = args.attn_tp_rank + self.src_mode = "ON" if bool(args.enable_mla_l1_5_cache) else "OFF" + self.is_mla_backend = args.is_mla_backend + self.draft_is_mla_backend = args.draft_is_mla_backend + self.disaggregation_mode = disaggregation_mode + self.bootstrap_port = args.bootstrap_port + self.dist_init_addr = args.dist_init_addr + self.world_size = args.world_size + self.dp_size = args.dp_size + self.attn_dp_rank = args.attn_dp_rank + self.enable_dp_attention = args.enable_dp_attention + if not args.enable_dp_attention and args.dp_size != 1: + raise ValueError( + "If dp_attention is not enabled, dp size must be 1 in disaggregation mode." + ) + + if hasattr(args, "enable_metrics") and args.enable_metrics: + labels = { + "model_name": args.served_model_name, + "app_key": args.app_key, + } + self.kv_transfer_metrics = KVTransferMetrics(labels, args.metrics_reporters) + else: + self.kv_transfer_metrics = None + + # Build the Mooncake data-plane engine here (the vendor binding stays in + # the mooncake package, not in the neutral base) and inject it. self.kv_args + # is set above so register_buffer_to_engine (called by the base) sees the + # KV buffers. + engine = MooncakeTransferEngine( + hostname=get_local_ip_by_remote(), + gpu_id=kv_args.gpu_id, + ib_device=kv_args.ib_device, + ) + super().__init__(engine=engine) + + def register_buffer_to_engine(self): + for kv_data_ptr, kv_data_len in zip( + self.kv_args.kv_data_ptrs, self.kv_args.kv_data_lens + ): + self.engine.register(kv_data_ptr, kv_data_len) + for state_data_ptr, state_data_len in zip( + self.kv_args.state_data_ptrs, self.kv_args.state_data_lens + ): + self.engine.register(state_data_ptr, state_data_len) + + +class MooncakeKVBootstrapServer(DisaggBootstrapServer): + """KV bootstrap rendezvous: the shared server plus the prefill-side MLA / + kv-page length fields the decode side needs in the parallel-info sync.""" + + def __init__(self, port: int): + # Set before super() -- super() starts the server thread, after which a + # register PUT can call _ingest_put_extra and read these. + self.enable_mla_l1_5_cache = False + self.prefill_kv_item_lens = [] + self.prefill_kv_unit_lens = [] + self.prefill_state_item_lens = [] + self.prefill_state_unit_lens = [] + super().__init__(port) + + def _ingest_put_extra(self, data: dict) -> None: + self.enable_mla_l1_5_cache = bool(data["enable_mla_l1_5_cache"]) + self.prefill_kv_item_lens = data.get("kv_item_lens", self.prefill_kv_item_lens) + self.prefill_kv_unit_lens = data.get("kv_unit_lens", self.prefill_kv_unit_lens) + self.prefill_state_item_lens = data.get( + "state_item_lens", self.prefill_state_item_lens + ) + self.prefill_state_unit_lens = data.get( + "state_unit_lens", self.prefill_state_unit_lens + ) + + def _extra_parallel_info(self) -> dict: + return { + "enable_mla_l1_5_cache": self.enable_mla_l1_5_cache, + "kv_item_lens": self.prefill_kv_item_lens, + "kv_unit_lens": self.prefill_kv_unit_lens, + "state_item_lens": self.prefill_state_item_lens, + "state_unit_lens": self.prefill_state_unit_lens, + } diff --git a/python/tokenspeed/runtime/pd/mooncake/decode.py b/python/tokenspeed/runtime/disaggregation/kv/mooncake/decode.py similarity index 92% rename from python/tokenspeed/runtime/pd/mooncake/decode.py rename to python/tokenspeed/runtime/disaggregation/kv/mooncake/decode.py index 10c75f4e4ab..35e9caf2720 100644 --- a/python/tokenspeed/runtime/pd/mooncake/decode.py +++ b/python/tokenspeed/runtime/disaggregation/kv/mooncake/decode.py @@ -27,15 +27,11 @@ import numpy as np import requests -from tokenspeed.runtime.pd.base.conn import ( - KVArgs, - KVPoll, -) -from tokenspeed.runtime.pd.mooncake.conn import MooncakeKVManagerBase -from tokenspeed.runtime.pd.mooncake.entities import ManagerArgs -from tokenspeed.runtime.pd.utils import ( - DisaggregationMode, -) +from tokenspeed.runtime.disaggregation.base.poll import TransferPoll +from tokenspeed.runtime.disaggregation.kv.mooncake.conn import MooncakeKVManagerBase +from tokenspeed.runtime.disaggregation.kv.mooncake.entities import ManagerArgs +from tokenspeed.runtime.disaggregation.kv.types import KVArgs +from tokenspeed.runtime.disaggregation.utils import DisaggregationMode from tokenspeed.runtime.utils import ( get_colorful_logger, ) @@ -70,7 +66,13 @@ def parse_prefill_status_message( spec_candidate_ids = None if len(parts) > 4 and parts[4] != b"": spec_candidate_ids = np.frombuffer(parts[4], dtype=np.int32).copy().tolist() - return bootstrap_room, status, prefill_rank, bootstrap_token, spec_candidate_ids + return ( + bootstrap_room, + status, + prefill_rank, + bootstrap_token, + spec_candidate_ids, + ) class MooncakeKVManagerDecode(MooncakeKVManagerBase): @@ -147,7 +149,7 @@ def heartbeat_checker(): ].copy() for bootstrap_room in current_rooms: - # Remove KVPoll.Success requests from the map + # Remove TransferPoll.Success requests from the map if bootstrap_room not in self.request_status: self.addr_to_rooms_tracker[bootstrap_addr].discard( bootstrap_room @@ -188,7 +190,7 @@ def _handle_prefill_status( bootstrap_token: int, spec_candidate_ids: list[int] | None, ) -> None: - if status == KVPoll.Success: + if status == TransferPoll.Success: if bootstrap_room not in self.request_status: return @@ -221,15 +223,15 @@ def _handle_prefill_status( self.spec_candidate_ids_table[bootstrap_room] = ( self._pending_spec_candidate_ids_table.pop(bootstrap_room) ) - self.update_status(bootstrap_room, KVPoll.Success) + self.update_status(bootstrap_room, TransferPoll.Success) return - if status == KVPoll.Failed: + if status == TransferPoll.Failed: self.record_failure( bootstrap_room, "Failed to get kvcache from prefill instance, it might be dead", ) - self.update_status(bootstrap_room, KVPoll.Failed) + self.update_status(bootstrap_room, TransferPoll.Failed) return self.update_status(bootstrap_room, status) @@ -263,18 +265,18 @@ def _handle_node_failure(self, failed_bootstrap_addr): if failed_bootstrap_addr in self.addr_to_rooms_tracker: del self.addr_to_rooms_tracker[failed_bootstrap_addr] - # Report the requests associated with the failed bootstrap addr and mark their status as KVPoll.Failed + # Report the requests associated with the failed bootstrap addr and mark their status as TransferPoll.Failed affected_rooms = [] for room in possible_affected_rooms: if ( room in self.request_status - and self.check_status(room) != KVPoll.Success + and self.check_status(room) != TransferPoll.Success ): self.record_failure( room, f"Losing connection with prefill instance (bootstrap_addr: {failed_bootstrap_addr})", ) - self.update_status(room, KVPoll.Failed) + self.update_status(room, TransferPoll.Failed) affected_rooms.append(room) logger.error( "Losing connection with prefill instance (bootstrap_addr: %s), affected %s requests", diff --git a/python/tokenspeed/runtime/pd/mooncake/entities.py b/python/tokenspeed/runtime/disaggregation/kv/mooncake/entities.py similarity index 98% rename from python/tokenspeed/runtime/pd/mooncake/entities.py rename to python/tokenspeed/runtime/disaggregation/kv/mooncake/entities.py index 5f495bb5a82..4a07f76e4ac 100644 --- a/python/tokenspeed/runtime/pd/mooncake/entities.py +++ b/python/tokenspeed/runtime/disaggregation/kv/mooncake/entities.py @@ -25,11 +25,11 @@ import numpy as np import numpy.typing as npt -from tokenspeed.runtime.pd.transfer_plan import ( +from tokenspeed.runtime.disaggregation.kv.transfer_plan import ( TransferFragment, decode_transfer_fragments, ) -from tokenspeed.runtime.pd.utils import PageTransferMetadata +from tokenspeed.runtime.disaggregation.kv.utils import PageTransferMetadata class KVTransferError(Exception): diff --git a/python/tokenspeed/runtime/pd/mooncake/prefill.py b/python/tokenspeed/runtime/disaggregation/kv/mooncake/prefill.py similarity index 91% rename from python/tokenspeed/runtime/pd/mooncake/prefill.py rename to python/tokenspeed/runtime/disaggregation/kv/mooncake/prefill.py index 92507cc14dd..8b15a9031e6 100644 --- a/python/tokenspeed/runtime/pd/mooncake/prefill.py +++ b/python/tokenspeed/runtime/disaggregation/kv/mooncake/prefill.py @@ -30,26 +30,26 @@ import numpy.typing as npt import requests -from tokenspeed.runtime.pd.base.conn import ( - KVArgs, - KVPoll, -) -from tokenspeed.runtime.pd.mooncake.conn import MooncakeKVManagerBase -from tokenspeed.runtime.pd.mooncake.entities import ( +from tokenspeed.runtime.disaggregation.base.poll import TransferPoll +from tokenspeed.runtime.disaggregation.kv.mooncake.conn import MooncakeKVManagerBase +from tokenspeed.runtime.disaggregation.kv.mooncake.entities import ( KVArgsRegisterInfo, ManagerArgs, TransferIndexResolution, TransferInfo, TransferKVChunk, ) -from tokenspeed.runtime.pd.transfer_plan import BufferKind, TransferFragment -from tokenspeed.runtime.pd.utils import ( - DisaggregationMode, - FastQueue, +from tokenspeed.runtime.disaggregation.kv.transfer_plan import ( + BufferKind, + TransferFragment, +) +from tokenspeed.runtime.disaggregation.kv.types import KVArgs +from tokenspeed.runtime.disaggregation.kv.utils import ( PageTransferMetadata, StepCounter, group_concurrent_contiguous, ) +from tokenspeed.runtime.disaggregation.utils import DisaggregationMode, FastQueue from tokenspeed.runtime.utils import ( get_colorful_logger, ) @@ -97,6 +97,8 @@ def __init__( self.layerwise_interval = 1 self.layerwise_debug = envs.TOKENSPEED_PD_LAYERWISE_DEBUG.get() self.step_counter = None + # room -> (bootstrap_token, spec_candidate_ids). Published after the prefill + # forward; the transfer thread reads it on the wait_for_bootstrap_token path. self.prefill_metadata: Dict[int, Tuple[int, Optional[list[int]]]] = {} self.expired_prefill_metadata_rooms: set[int] = set() self.bootstrap_token_cond = threading.Condition() @@ -132,7 +134,10 @@ def reserve_layerwise_cache_steps(self) -> int: return cache_step def set_prefill_metadata( - self, room: int, token: int, spec_candidate_ids: list[int] | None = None + self, + room: int, + token: int, + spec_candidate_ids: list[int] | None = None, ) -> None: with self.bootstrap_token_cond: if room in self.expired_prefill_metadata_rooms: @@ -142,7 +147,10 @@ def set_prefill_metadata( room, ) return - self.prefill_metadata[room] = (token, spec_candidate_ids) + self.prefill_metadata[room] = ( + token, + spec_candidate_ids, + ) self.bootstrap_token_cond.notify_all() def discard_expired_metadata_room(self, room: int) -> None: @@ -164,14 +172,17 @@ def _wait_prefill_metadata( next_log_time = start_time + wait_log_interval with self.bootstrap_token_cond: while room not in self.prefill_metadata: - if self.request_status.get(room) == KVPoll.Failed: + if self.request_status.get(room) == TransferPoll.Failed: self.expired_prefill_metadata_rooms.add(room) logger.warning( "Prefill metadata unavailable for failed bootstrap_room=%s; using fallback=%s", room, fallback_token, ) - return fallback_token, fallback_candidate_ids + return ( + fallback_token, + fallback_candidate_ids, + ) now = time.monotonic() if now >= next_log_time: logger.debug( @@ -344,12 +355,20 @@ def send_kvcache( prefill_kv_indices, dst_kv_indices ) + # ``_layer_transfer_blocks`` indexes ``kv_args.offsets`` by its loop var, + # and ``offsets`` is keyed by KV-LAYER INDEX (one entry per attention/KV + # layer), not by global layer id. For hybrid models (e.g. Qwen3.5 GDN + + # attention) only the attention layers carry KV, so len(offsets) is the + # KV-layer count while ``self.layer_num`` is the (larger) global layer + # count -- using ``layer_num`` here over-runs ``offsets`` and IndexErrors. + # Iterate the full KV-index space instead (the layerwise path already + # maps global->KV index via ``_kv_layer_to_index`` before calling this). transfer_blocks = self._layer_transfer_blocks( dst_ptrs=dst_kv_ptrs, src_blocks=prefill_kv_blocks, dst_blocks=dst_kv_blocks, begin_layer_id=0, - end_layer_id=self.layer_num, + end_layer_id=len(self.kv_args.offsets), transfer_fragments=transfer_fragments, ) return self._transfer_data(mooncake_session_id, transfer_blocks) @@ -661,12 +680,37 @@ def sync_status_to_decode_endpoint( ] ) + def abort_room(self, room: int, reason: str) -> None: + """Notify the decode that a room failed before any KV transfer. + + EPD: when the prefill aborts a request on embedding-receive timeout it never + sends KV, so the decode's dual-dispatched KV receiver would wait + indefinitely -- its heartbeat only trips if the prefill /health dies, and the + receiver waiting_timeout only covers the WaitingForInput state (a receiver + whose prefill never registered a sender is stuck earlier). Push a Failed + status to every decode endpoint that already pre-allocated for this room + (mirrors the in-transfer failure path), so the decode raises a FailedEvent and + the client gets an error instead of hanging. A room whose decode has not + pre-allocated yet is only marked Failed locally (no endpoint to notify). + """ + self.record_failure(room, reason) + self.update_status(room, TransferPoll.Failed) + for req in list(self.transfer_infos.get(room, {}).values()): + if not req.is_dummy: + self.sync_status_to_decode_endpoint( + req.endpoint, + req.dst_port, + req.room, + TransferPoll.Failed, + self.attn_tp_rank, + ) + def transfer_worker( self, queue: FastQueue, executor: concurrent.futures.ThreadPoolExecutor ): while True: try: - kv_chunk: TransferKVChunk = queue.get() + kv_chunk = queue.get() logger.debug( "[TRANSFER_WORKER] Got transfer request for room %s, is_last=%s, kv_indices_len=%s", kv_chunk.room, @@ -694,12 +738,12 @@ def transfer_worker( kv_chunk.room, f"Decode instance could be dead, remote mooncake session {req.mooncake_session_id} is not alive", ) - self.update_status(kv_chunk.room, KVPoll.Failed) + self.update_status(kv_chunk.room, TransferPoll.Failed) self.sync_status_to_decode_endpoint( req.endpoint, req.dst_port, req.room, - KVPoll.Failed, + TransferPoll.Failed, self.attn_tp_rank, ) break @@ -778,12 +822,12 @@ def transfer_worker( kv_chunk.room, f"Failed to send kv chunk of {kv_chunk.room} to {req.endpoint}:{req.dst_port}", ) - self.update_status(kv_chunk.room, KVPoll.Failed) + self.update_status(kv_chunk.room, TransferPoll.Failed) self.sync_status_to_decode_endpoint( req.endpoint, req.dst_port, req.room, - KVPoll.Failed, + TransferPoll.Failed, self.attn_tp_rank, ) break @@ -796,7 +840,11 @@ def transfer_worker( # Only sync status when all the dst ranks have received the kvcache if len(polls) == req.required_dst_info_num: - status = KVPoll.Success if all(polls) else KVPoll.Failed + status = ( + TransferPoll.Success + if all(polls) + else TransferPoll.Failed + ) self.update_status(req.room, status) # bootstrap_token is carried directly in the chunk (set by # DisaggPrefillExecutor._decode after prefill forward). @@ -815,8 +863,8 @@ def transfer_worker( kv_chunk.bootstrap_token, kv_chunk.spec_candidate_ids, ) - if self.check_status(req.room) == KVPoll.Failed: - status = KVPoll.Failed + if self.check_status(req.room) == TransferPoll.Failed: + status = TransferPoll.Failed for endpoint, dst_port, room in dst_ranks_infos: self.sync_status_to_decode_endpoint( endpoint, @@ -836,11 +884,11 @@ def transfer_worker( # Dummy request means the decode instance is not used, so its status can be marked as success directly # Dummy request does not need to sync status to decode endpoint if kv_chunk.is_last and req.room in self.request_status: - self.update_status(req.room, KVPoll.Success) + self.update_status(req.room, TransferPoll.Success) if ( kv_chunk.room not in self.request_status - or self.check_status(kv_chunk.room) == KVPoll.Success + or self.check_status(kv_chunk.room) == TransferPoll.Success ): if kv_chunk.room in self.transfer_infos: self.transfer_infos.pop(kv_chunk.room) @@ -856,7 +904,7 @@ def start_prefill_thread(self): def bootstrap_thread(): """This thread recvs pre-alloc notification from the decode engine""" - # KVPoll.Bootstrapping -> KVPoll.WaitingForInput + # TransferPoll.Bootstrapping -> TransferPoll.WaitingForInput while True: waiting_req_bytes = self.server_socket.recv_multipart() room = waiting_req_bytes[0].decode("ascii") @@ -899,7 +947,7 @@ def bootstrap_thread(): ), ) if len(self.transfer_infos[room]) == required_dst_info_num: - self.update_status(room, KVPoll.Bootstrapped) + self.update_status(room, TransferPoll.Bootstrapped) threading.Thread(target=bootstrap_thread).start() @@ -939,7 +987,7 @@ def add_transfer_request( assert not is_last or (is_last and aux_index is not None) if ( bootstrap_room not in self.request_status - or self.check_status(bootstrap_room) == KVPoll.Failed + or self.check_status(bootstrap_room) == TransferPoll.Failed ): logger.debug( "Request with bootstrap_room=%s already failed", bootstrap_room @@ -1034,6 +1082,6 @@ def _register_to_bootstrap(self): ) -from tokenspeed.runtime.pd.mooncake.sender import MooncakeKVSender +from tokenspeed.runtime.disaggregation.kv.mooncake.sender import MooncakeKVSender __all__ = ["MooncakeKVManagerPrefill", "MooncakeKVSender"] diff --git a/python/tokenspeed/runtime/pd/mooncake/receiver.py b/python/tokenspeed/runtime/disaggregation/kv/mooncake/receiver.py similarity index 96% rename from python/tokenspeed/runtime/pd/mooncake/receiver.py rename to python/tokenspeed/runtime/disaggregation/kv/mooncake/receiver.py index a7409e1fb4f..1ae9099c892 100644 --- a/python/tokenspeed/runtime/pd/mooncake/receiver.py +++ b/python/tokenspeed/runtime/disaggregation/kv/mooncake/receiver.py @@ -29,11 +29,9 @@ import requests import zmq -from tokenspeed.runtime.pd.base.conn import ( - KVPoll, -) -from tokenspeed.runtime.pd.mooncake.entities import KVTransferError -from tokenspeed.runtime.pd.transfer_plan import ( +from tokenspeed.runtime.disaggregation.base.poll import TransferPoll +from tokenspeed.runtime.disaggregation.kv.mooncake.entities import KVTransferError +from tokenspeed.runtime.disaggregation.kv.transfer_plan import ( BufferKind, BufferLayout, ParallelLayout, @@ -41,7 +39,7 @@ RankTransferPlan, encode_transfer_fragments, ) -from tokenspeed.runtime.pd.utils import ( +from tokenspeed.runtime.disaggregation.kv.utils import ( PageTransferMetadata, ) from tokenspeed.runtime.utils import ( @@ -51,7 +49,7 @@ logger = get_colorful_logger(__name__) -from tokenspeed.runtime.pd.mooncake.decode import ( +from tokenspeed.runtime.disaggregation.kv.mooncake.decode import ( MooncakeKVManagerDecode, PrefillParallelInfo, ) @@ -437,7 +435,7 @@ def __init__( self.prefill_enable_mla_l1_5_cache = None self.dst_enable_mla_l1_5_cache = False - self.kv_mgr.update_status(self.bootstrap_room, KVPoll.Bootstrapping) + self.kv_mgr.update_status(self.bootstrap_room, TransferPoll.Bootstrapping) logger.info( "[MooncakeKVReceiver.__init__] bootstrap_addr=%s bootstrap_room=%s session_id=%s", bootstrap_addr, @@ -451,7 +449,7 @@ def __init__( self.bootstrap_room, f"Could not fetch prefill parallel info from bootstrap_addr: {self.bootstrap_addr}", ) - self.kv_mgr.update_status(self.bootstrap_room, KVPoll.Failed) + self.kv_mgr.update_status(self.bootstrap_room, TransferPoll.Failed) route_plan = _calc(self.kv_mgr, prefill_parallel_info) self.route_plan = route_plan @@ -472,7 +470,7 @@ def __init__( self.bootstrap_room, f"Could not fetch bootstrap info for engine rank: {self.kv_mgr.kv_args.engine_rank} and target_dp_group: {target_dp_group}", ) - self.kv_mgr.update_status(self.bootstrap_room, KVPoll.Failed) + self.kv_mgr.update_status(self.bootstrap_room, TransferPoll.Failed) else: assert len(bootstrap_infos) > 0 self.bootstrap_infos = bootstrap_infos @@ -483,7 +481,7 @@ def __init__( self.bootstrap_infos = self.kv_mgr.connection_pool[bootstrap_key] self.kv_mgr.addr_to_rooms_tracker[self.bootstrap_addr].add(self.bootstrap_room) - self.kv_mgr.update_status(self.bootstrap_room, KVPoll.Bootstrapped) + self.kv_mgr.update_status(self.bootstrap_room, TransferPoll.Bootstrapped) logger.info( "[MooncakeKVReceiver.__init__] done, status set to Bootstrapped. " "bootstrap_room=%s bootstrap_addr=%s session_id=%s", @@ -675,12 +673,12 @@ def prefill( sock.send_multipart(message_parts) self.init_time = time.time() - def poll(self) -> KVPoll: + def poll(self) -> TransferPoll: if self.conclude_state is None: status = self.kv_mgr.check_status(self.bootstrap_room) - if status in (KVPoll.Success, KVPoll.Failed): + if status in (TransferPoll.Success, TransferPoll.Failed): self.conclude_state = status - elif status == KVPoll.WaitingForInput: + elif status == TransferPoll.WaitingForInput: if self.init_time is not None: now = time.time() elapsed = now - self.init_time @@ -691,11 +689,11 @@ def poll(self) -> KVPoll: ) self.kv_mgr.record_failure( self.bootstrap_room, - f"Request {self.bootstrap_room} timed out after {elapsed:.1f}s in KVPoll.WaitingForInput", + f"Request {self.bootstrap_room} timed out after {elapsed:.1f}s in TransferPoll.WaitingForInput", ) - self.conclude_state = KVPoll.Failed - return KVPoll.Failed - elif status == KVPoll.Transferring: + self.conclude_state = TransferPoll.Failed + return TransferPoll.Failed + elif status == TransferPoll.Transferring: logger.warning( "Req(room=%s) in Transferring, which is unexpected", self.bootstrap_room, @@ -718,7 +716,7 @@ def clear(self) -> None: def failure_exception(self): # Explicitly set the status to failure since this request has failed in another rank if self.conclude_state is None: - self.conclude_state = KVPoll.Failed + self.conclude_state = TransferPoll.Failed self.clear() diff --git a/python/tokenspeed/runtime/pd/mooncake/sender.py b/python/tokenspeed/runtime/disaggregation/kv/mooncake/sender.py similarity index 91% rename from python/tokenspeed/runtime/pd/mooncake/sender.py rename to python/tokenspeed/runtime/disaggregation/kv/mooncake/sender.py index 9dcdecb0b11..aedfd4547ee 100644 --- a/python/tokenspeed/runtime/pd/mooncake/sender.py +++ b/python/tokenspeed/runtime/disaggregation/kv/mooncake/sender.py @@ -24,11 +24,9 @@ import numpy as np import numpy.typing as npt -from tokenspeed.runtime.pd.base.conn import ( - KVPoll, -) -from tokenspeed.runtime.pd.mooncake.entities import KVTransferError -from tokenspeed.runtime.pd.utils import PageTransferMetadata +from tokenspeed.runtime.disaggregation.base.poll import TransferPoll +from tokenspeed.runtime.disaggregation.kv.mooncake.entities import KVTransferError +from tokenspeed.runtime.disaggregation.kv.utils import PageTransferMetadata from tokenspeed.runtime.utils import get_colorful_logger logger = get_colorful_logger(__name__) @@ -44,7 +42,7 @@ def __init__( self.kv_mgr = mgr self.bootstrap_server_url = bootstrap_addr self.bootstrap_room = bootstrap_room - self.kv_mgr.update_status(bootstrap_room, KVPoll.Bootstrapping) + self.kv_mgr.update_status(bootstrap_room, TransferPoll.Bootstrapping) logger.info( "[MooncakeKVSender.__init__] bootstrap_room=%s bootstrap_addr=%s status=Bootstrapping", bootstrap_room, @@ -157,12 +155,12 @@ def send_layerwise( mamba_indices=mamba_indices, ) - def poll(self) -> KVPoll: + def poll(self) -> TransferPoll: if self.conclude_state is None: status = self.kv_mgr.check_status(self.bootstrap_room) - if status in (KVPoll.Success, KVPoll.Failed): + if status in (TransferPoll.Success, TransferPoll.Failed): self.conclude_state = status - elif status == KVPoll.Bootstrapping: + elif status == TransferPoll.Bootstrapping: if self.init_time is not None: now = time.time() elapsed = now - self.init_time @@ -174,10 +172,10 @@ def poll(self) -> KVPoll: ) self.kv_mgr.record_failure( self.bootstrap_room, - f"Request {self.bootstrap_room} timed out after {elapsed:.1f}s in KVPoll.Bootstrapping", + f"Request {self.bootstrap_room} timed out after {elapsed:.1f}s in TransferPoll.Bootstrapping", ) - self.conclude_state = KVPoll.Failed - return KVPoll.Failed + self.conclude_state = TransferPoll.Failed + return TransferPoll.Failed return status else: @@ -190,7 +188,7 @@ def clear(self) -> None: def failure_exception(self): # Explicitly set the status to failure since this request has failed in another rank if self.conclude_state is None: - self.conclude_state = KVPoll.Failed + self.conclude_state = TransferPoll.Failed self.clear() diff --git a/python/tokenspeed/runtime/pd/prefill_executor.py b/python/tokenspeed/runtime/disaggregation/kv/prefill_executor.py similarity index 88% rename from python/tokenspeed/runtime/pd/prefill_executor.py rename to python/tokenspeed/runtime/disaggregation/kv/prefill_executor.py index a1bdfd3f7c7..482e519d199 100644 --- a/python/tokenspeed/runtime/pd/prefill_executor.py +++ b/python/tokenspeed/runtime/disaggregation/kv/prefill_executor.py @@ -24,12 +24,13 @@ import numpy as np -from tokenspeed.runtime.pd.base import BootstrapInfo, KVPoll -from tokenspeed.runtime.pd.mooncake.prefill import ( +from tokenspeed.runtime.disaggregation.base.poll import TransferPoll +from tokenspeed.runtime.disaggregation.kv.mooncake.prefill import ( MooncakeKVManagerPrefill, MooncakeKVSender, ) -from tokenspeed.runtime.pd.utils import ( +from tokenspeed.runtime.disaggregation.kv.types import BootstrapInfo +from tokenspeed.runtime.disaggregation.kv.utils import ( TransferBackend, poll_and_all_reduce, ) @@ -85,7 +86,9 @@ def store_prefill_token( ) return self.kv_manager.set_prefill_metadata( - sender.bootstrap_room, token, spec_candidate_ids + sender.bootstrap_room, + token, + spec_candidate_ids, ) self._layerwise_token_published.add(request_id) @@ -236,7 +239,9 @@ def _decode(self, op): if sender.has_layerwise_transfer(): if request_id not in self._layerwise_token_published: self.kv_manager.set_prefill_metadata( - sender.bootstrap_room, bootstrap_token, spec_candidate_ids + sender.bootstrap_room, + bootstrap_token, + spec_candidate_ids, ) self._layerwise_token_published.discard(request_id) continue @@ -269,9 +274,19 @@ def _decode(self, op): ) def register(self, request_id: str, bootstrap_info: BootstrapInfo): - self._local_states[request_id] = KVPoll.Bootstrapping + self._local_states[request_id] = TransferPoll.Bootstrapping self._bootstrap(request_id, bootstrap_info) + def abort(self, request_id: str, bootstrap_info: BootstrapInfo) -> None: + """EPD: the prefill aborted this request before registering a KV sender + (embedding receive timed out). Signal the dual-dispatched decode so its KV + receiver fails instead of waiting forever. No sender was registered, so + there is nothing to tear down on this side.""" + self.kv_manager.abort_room( + bootstrap_info.bootstrap_room, + f"EPD: prefill aborted request {request_id} (embedding receive timed out)", + ) + def execute(self, op): self._dispatcher(op) @@ -284,25 +299,25 @@ def generate_events(self): to_remove = [] for req_id, poll in zip(list(self.senders.keys()), polls): if ( - self._local_states[req_id] == KVPoll.Bootstrapping - and poll == KVPoll.Bootstrapped + self._local_states[req_id] == TransferPoll.Bootstrapping + and poll == TransferPoll.Bootstrapped ): logger.debug( "[prefill][generate_events] rid=%s -> BootstrappedEvent", req_id ) events.append(PD.BootstrappedEvent(req_id)) - self._local_states[req_id] = KVPoll.Bootstrapped - elif poll == KVPoll.Failed: + self._local_states[req_id] = TransferPoll.Bootstrapped + elif poll == TransferPoll.Failed: logger.warning( "[prefill][generate_events] rid=%s -> FailedEvent", req_id ) events.append(PD.FailedEvent(req_id)) to_remove.append(req_id) elif ( - self._local_states[req_id] == KVPoll.Bootstrapped - and poll == KVPoll.Success + self._local_states[req_id] == TransferPoll.Bootstrapped + and poll == TransferPoll.Success ): - self._local_states[req_id] = KVPoll.Success + self._local_states[req_id] = TransferPoll.Success logger.debug( "[prefill][generate_events] rid=%s -> SucceededEvent", req_id ) diff --git a/python/tokenspeed/runtime/pd/transfer_plan.py b/python/tokenspeed/runtime/disaggregation/kv/transfer_plan.py similarity index 100% rename from python/tokenspeed/runtime/pd/transfer_plan.py rename to python/tokenspeed/runtime/disaggregation/kv/transfer_plan.py diff --git a/python/tokenspeed/runtime/pd/base/conn.py b/python/tokenspeed/runtime/disaggregation/kv/types.py old mode 100755 new mode 100644 similarity index 80% rename from python/tokenspeed/runtime/pd/base/conn.py rename to python/tokenspeed/runtime/disaggregation/kv/types.py index 7c47561b17e..71f6b6c886f --- a/python/tokenspeed/runtime/pd/base/conn.py +++ b/python/tokenspeed/runtime/disaggregation/kv/types.py @@ -18,18 +18,16 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -from abc import ABC, abstractmethod -from dataclasses import dataclass, field -from typing import List, Optional, Tuple +"""Value types for the KV (prefill->decode) disaggregation path. -import numpy as np -import numpy.typing as npt +The role-specific buffer/engine args and bootstrap handshake record. The +transfer-status FSM is the shared :class:`...base.poll.TransferPoll`; the transport +mechanics are the shared :class:`...base.manager.DisaggManagerBase` / +:class:`...base.bootstrap.DisaggBootstrapServer`. +""" -from tokenspeed.runtime.pd.utils import ( - DisaggregationMode, - PageTransferMetadata, -) -from tokenspeed.runtime.utils.server_args import ServerArgs +from dataclasses import dataclass, field +from typing import List, Tuple @dataclass @@ -57,10 +55,8 @@ class KVArgs: mamba_offsets: List[int] | None = None -class KVPoll: - Failed = 0 - Bootstrapping = 1 - Bootstrapped = 2 - WaitingForInput = 3 - Transferring = 4 - Success = 5 +@dataclass +class BootstrapInfo: + bootstrap_host: str + bootstrap_port: int + bootstrap_room: int diff --git a/python/tokenspeed/runtime/pd/utils.py b/python/tokenspeed/runtime/disaggregation/kv/utils.py similarity index 93% rename from python/tokenspeed/runtime/pd/utils.py rename to python/tokenspeed/runtime/disaggregation/kv/utils.py index 42052a83280..b79aa65575a 100755 --- a/python/tokenspeed/runtime/pd/utils.py +++ b/python/tokenspeed/runtime/disaggregation/kv/utils.py @@ -26,7 +26,6 @@ import dataclasses import os import random -import threading import warnings from collections import deque from enum import Enum @@ -45,27 +44,23 @@ if TYPE_CHECKING: from tokenspeed.runtime.engine.request import Req -FAKE_BOOTSTRAP_HOST = "2.2.2.2" - # env var for testing failure, convert to float explicitly FAILURE_PROB = float(os.getenv("DISAGGREGATION_TEST_FAILURE_PROB", 0)) logger = get_colorful_logger(__name__) -class DisaggregationMode(Enum): - NULL = "null" - PREFILL = "prefill" - DECODE = "decode" - - def poll_and_all_reduce(pollers, gloo_group): """Poll transfer state and all-reduce the result across the gloo group.""" # At a certain probability, mark the poll as failed to simulate failure. if FAILURE_PROB > 0: - from tokenspeed.runtime.pd.base import KVPoll + from tokenspeed.runtime.disaggregation.base.poll import TransferPoll polls = [ - int(KVPoll.Failed) if random.random() < FAILURE_PROB else int(poller.poll()) + ( + int(TransferPoll.Failed) + if random.random() < FAILURE_PROB + else int(poller.poll()) + ) for poller in pollers ] else: @@ -101,13 +96,15 @@ def free(self, free_index: int) -> None: class TransferBackend(Enum): MOONCAKE = "mooncake" MOONCAKE_ASYNC = "mooncake_async" - FAKE = "fake" - COMMON = "common" class KVClassType(Enum): MANAGER_PREFILL = "manager_prefill" MANAGER_DECODE = "manager_decode" + # The async backend uses one role-agnostic manager (see get_kv_class's + # MOONCAKE_ASYNC branch); the sync backend splits into the prefill/decode + # managers above. + MANAGER = "manager" SENDER = "sender" RECEIVER = "receiver" BOOTSTRAP_SERVER = "bootstrap_server" @@ -115,11 +112,19 @@ class KVClassType(Enum): def get_kv_class(transfer_backend: TransferBackend, class_type: KVClassType): if transfer_backend == TransferBackend.MOONCAKE: - from tokenspeed.runtime.pd.mooncake import ( + from tokenspeed.runtime.disaggregation.kv.mooncake.conn import ( MooncakeKVBootstrapServer, + ) + from tokenspeed.runtime.disaggregation.kv.mooncake.decode import ( MooncakeKVManagerDecode, + ) + from tokenspeed.runtime.disaggregation.kv.mooncake.prefill import ( MooncakeKVManagerPrefill, + ) + from tokenspeed.runtime.disaggregation.kv.mooncake.receiver import ( MooncakeKVReceiver, + ) + from tokenspeed.runtime.disaggregation.kv.mooncake.sender import ( MooncakeKVSender, ) @@ -133,10 +138,16 @@ def get_kv_class(transfer_backend: TransferBackend, class_type: KVClassType): return class_mapping.get(class_type) if transfer_backend == TransferBackend.MOONCAKE_ASYNC: - from tokenspeed.runtime.pd.mooncake import ( + from tokenspeed.runtime.disaggregation.kv.mooncake.async_conn import ( MooncakeAsyncKVManager, + ) + from tokenspeed.runtime.disaggregation.kv.mooncake.conn import ( MooncakeKVBootstrapServer, + ) + from tokenspeed.runtime.disaggregation.kv.mooncake.receiver import ( MooncakeKVReceiver, + ) + from tokenspeed.runtime.disaggregation.kv.mooncake.sender import ( MooncakeKVSender, ) @@ -366,36 +377,6 @@ def set_buf(self, req: Req): ) -class FastQueue: - class Empty(Exception): - """Exception raised when the queue is empty.""" - - pass - - def __init__(self): - self._buf = deque() - self._cond = threading.Condition() - - def put(self, item): - with self._cond: - self._buf.append(item) - # wake up a thread of wait() - self._cond.notify() - - def get(self): - with self._cond: - # if queue is empty ,block until is notified() - while not self._buf: - self._cond.wait() - return self._buf.popleft() - - def get_nowait(self): - with self._cond: - if not self._buf: - raise FastQueue.Empty() - return self._buf.popleft() - - def group_concurrent_contiguous( src_indices: npt.NDArray[np.int64], dst_indices: npt.NDArray[np.int64] ) -> Tuple[List[npt.NDArray[np.int64]], List[npt.NDArray[np.int64]]]: diff --git a/python/tokenspeed/runtime/pd/mooncake/transfer_engine.py b/python/tokenspeed/runtime/disaggregation/mooncake_transfer_engine.py similarity index 100% rename from python/tokenspeed/runtime/pd/mooncake/transfer_engine.py rename to python/tokenspeed/runtime/disaggregation/mooncake_transfer_engine.py diff --git a/python/tokenspeed/runtime/disaggregation/utils.py b/python/tokenspeed/runtime/disaggregation/utils.py new file mode 100644 index 00000000000..80983ae71a9 --- /dev/null +++ b/python/tokenspeed/runtime/disaggregation/utils.py @@ -0,0 +1,67 @@ +# Copyright (c) 2026 LightSeek Foundation +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +from __future__ import annotations + +"""Disaggregation-wide neutral utilities shared by all roles (kv + embedding). + +These carry no KV/embedding-specific or backend-specific state, so they live at +the disaggregation root rather than inside any role package: the role/mode enum +and a small blocking queue used by the transfer workers. +""" + +import threading +from collections import deque +from enum import Enum + + +class DisaggregationMode(Enum): + NULL = "null" + PREFILL = "prefill" + DECODE = "decode" + ENCODE = "encode" + + +class FastQueue: + class Empty(Exception): + """Exception raised when the queue is empty.""" + + pass + + def __init__(self): + self._buf = deque() + self._cond = threading.Condition() + + def put(self, item): + with self._cond: + self._buf.append(item) + self._cond.notify() + + def get(self): + with self._cond: + while not self._buf: + self._cond.wait() + return self._buf.popleft() + + def get_nowait(self): + with self._cond: + if not self._buf: + raise FastQueue.Empty() + return self._buf.popleft() diff --git a/python/tokenspeed/runtime/engine/async_llm.py b/python/tokenspeed/runtime/engine/async_llm.py index 00415fa95a5..802cd1cc0c2 100755 --- a/python/tokenspeed/runtime/engine/async_llm.py +++ b/python/tokenspeed/runtime/engine/async_llm.py @@ -48,6 +48,12 @@ import uvloop from tokenspeed.runtime.configs.model_config import ModelConfig +from tokenspeed.runtime.disaggregation.kv.utils import ( + KVClassType, + TransferBackend, + get_kv_class, +) +from tokenspeed.runtime.disaggregation.utils import DisaggregationMode from tokenspeed.runtime.engine.aio_rwlock import RWLock from tokenspeed.runtime.engine.collector import RequestOutputCollector from tokenspeed.runtime.engine.core_client import EngineCoreClient @@ -84,12 +90,6 @@ SchedulerControlClient, ) from tokenspeed.runtime.metrics.collector import RequestMetrics -from tokenspeed.runtime.pd.utils import ( - DisaggregationMode, - KVClassType, - TransferBackend, - get_kv_class, -) from tokenspeed.runtime.utils import ( dataclass_to_string_truncated, get_colorful_logger, @@ -311,6 +311,19 @@ def _send_one_request( mm_inputs.publish_shm_features() self.engine_core_client.send_to_scheduler.send_pyobj(tokenized_obj) + def submit_encode(self, encode_request) -> None: + """Send an EPD encode request to the encode-worker scheduler subprocess. + + Fire-and-forget over the same scheduler-input channel the LM uses (the + encode subprocess runs ``run_encode_loop``, not the LM EventLoop). The + encode worker runs the vision tower and ships the embeddings to prefill + over Mooncake; the gateway gets no streamed response, only the gRPC ack. + ``encode_request`` is an ``encode_worker.EncodeRequest`` whose multimodal + tensors are CPU (gateway-reconstructed) and pickle over ZMQ directly; shm + publishing of the pixels is a follow-up optimization. + """ + self.engine_core_client.send_to_scheduler.send_pyobj(encode_request) + async def _wait_one_response( self, obj: GenerateReqInput | EmbeddingReqInput, diff --git a/python/tokenspeed/runtime/engine/event_loop.py b/python/tokenspeed/runtime/engine/event_loop.py index d0609f4d024..71d8c8dcef1 100644 --- a/python/tokenspeed/runtime/engine/event_loop.py +++ b/python/tokenspeed/runtime/engine/event_loop.py @@ -29,7 +29,7 @@ import torch import torch.distributed as dist import zmq -from tokenspeed_scheduler import PD, Cache, ExecutionEvent, Scheduler +from tokenspeed_scheduler import PD, Cache, ExecutionEvent, ForwardEvent, Scheduler from tokenspeed.runtime.cache.executor.memory_executor import ( MemoryExecutor, @@ -37,6 +37,20 @@ ) from tokenspeed.runtime.cache.transfer.types import CacheKind from tokenspeed.runtime.configs.model_config import ModelConfig +from tokenspeed.runtime.disaggregation.kv.decode_executor import DisaggDecodeExecutor +from tokenspeed.runtime.disaggregation.kv.factory import ( + create_kv_transfer, + get_kv_args, +) +from tokenspeed.runtime.disaggregation.kv.kv_events import ( + EventPublisherFactory, + KVEventBatch, + NullEventPublisher, + drain_scheduler_kv_events, + scheduler_kv_events_to_wire_events, +) +from tokenspeed.runtime.disaggregation.kv.mooncake.entities import ManagerArgs +from tokenspeed.runtime.disaggregation.kv.prefill_executor import DisaggPrefillExecutor from tokenspeed.runtime.distributed.process_group_manager import ( process_group_manager as pg_manager, ) @@ -70,20 +84,6 @@ from tokenspeed.runtime.grammar.capturable_grammar import GrammarStepInputs from tokenspeed.runtime.layers.attention.registry import create_attn_components from tokenspeed.runtime.metrics.collector import EngineMetrics -from tokenspeed.runtime.pd.decode_executor import DisaggDecodeExecutor -from tokenspeed.runtime.pd.factory import ( - create_pd_kv_transfer, - get_kv_args, -) -from tokenspeed.runtime.pd.kv_events import ( - EventPublisherFactory, - KVEventBatch, - NullEventPublisher, - drain_scheduler_kv_events, - scheduler_kv_events_to_wire_events, -) -from tokenspeed.runtime.pd.mooncake.entities import ManagerArgs -from tokenspeed.runtime.pd.prefill_executor import DisaggPrefillExecutor from tokenspeed.runtime.sampling.sampling_params import SamplingParams from tokenspeed.runtime.utils import ( configure_logger, @@ -478,7 +478,7 @@ def __init__( metrics_reporters=server_args.metrics_reporters, enable_dp_attention=self.has_dp, ) - self.pd_kv_transfer = create_pd_kv_transfer( + self.kv_transfer = create_kv_transfer( mode=server_args.disaggregation_mode, backend=server_args.disaggregation_transfer_backend, args=pd_manager_args, @@ -489,22 +489,152 @@ def __init__( self._setup_pd_layerwise_transfer( server_args.disaggregation_layerwise_interval ) + # EPD: a multimodal prefill node is also the encode->prefill embedding + # SINK (independent of kv_transfer, its P->D KV source) -- it receives + # each image's embedding from encode workers over Mooncake so the + # prefill skips the vision tower. The admission controller owns the + # receive jobs, the rank-synced admission drain, and the optional NCCL + # row-shard reassembly; None for decode/encode/text-only nodes. + from tokenspeed.runtime.disaggregation.embedding.prefill_receiver import ( + make_epd_prefill_admission, + ) + + self.epd_admission = make_epd_prefill_admission( + server_args, + global_rank, + model_config=self.model_config, + model_executor=self.model_executor, + mapping=mapping, + attn_tp_rank=self.attn_tp_rank, + attn_tp_size=self.attn_tp_size, + attn_tp_cpu_group=self.attn_tp_cpu_group, + pg_manager=pg_manager, + ) + # Staged EPD request payloads (request_id -> (spec, state, bootstrap)), + # held here while the controller (rid-keyed, like kv_transfer) runs the + # async receive; popped in _drain_ready_epd_embeddings on admit/abort. + self._epd_staged: dict = {} else: - self.pd_kv_transfer = None + self.kv_transfer = None + self.epd_admission = None + self._epd_staged: dict = {} def _setup_pd_layerwise_transfer(self, interval: int) -> None: - if not isinstance(self.pd_kv_transfer, DisaggPrefillExecutor): + if not isinstance(self.kv_transfer, DisaggPrefillExecutor): return if interval <= 0: return - from tokenspeed.runtime.pd.utils import StepCounter + from tokenspeed.runtime.disaggregation.kv.utils import StepCounter step_counter = StepCounter(self.model_executor.device, self.gpu_id) self.model_executor.attn_backend.register_step_counter(step_counter) if self.model_executor.draft_attn_backend is not None: self.model_executor.draft_attn_backend.register_step_counter(step_counter) - self.pd_kv_transfer.register_layerwise_step_counter(step_counter, interval) + self.kv_transfer.register_layerwise_step_counter(step_counter, interval) + + def _is_epd_request(self, state) -> bool: + """True iff this request's images are encode-routed (smg injected per-image + encode handshakes) -- it must wait for its embeddings (staged via the EPD + admission controller, polled in _drain_ready_epd_embeddings) before being + scheduled. Caller guards on self.epd_admission (only a multimodal prefill + node has one); everything else admits immediately. + """ + mm = getattr(state, "multimodal_inputs", None) + return mm is not None and any( + getattr(it, "encode_handshake", None) for it in mm.mm_items + ) + + def _assert_epd_embeddings_received(self, multimodal_context) -> None: + """EPD invariant: every handshaked item is filled with its embedding by the + async EPD admission drain (EpdPrefillAdmission.drain) BEFORE admission, so by + it is already encoded. This is a defensive check, not a receive: a handshaked + item that reached the forward un-received leaked past async admission (the + only EPD admission path) -- fail loud instead of running the tower or + publishing shard-only rows. No-op for non-EPD / text-only requests. + """ + if ( + self.epd_admission is None + or multimodal_context is None + or not multimodal_context.has_extend_inputs() + ): + return + for mm in multimodal_context.mm_inputs: + if mm is None: + continue + missing = [ + i + for i, item in enumerate(mm.mm_items) + if getattr(item, "encode_handshake", None) is not None + and item.encoded is None + ] + if missing: + raise RuntimeError( + f"EPD: handshaked items {missing} reached the prefill forward " + "un-received; they must be admitted via the EPD admission drain" + ) + + def _drain_ready_epd_embeddings(self) -> None: + """Admit EPD requests whose async embedding receives completed this cycle. + + The EpdPrefillAdmission controller DECIDES (poll + rank-lockstep MIN + all-reduce + reassemble) and returns (admitted, failed); here we ACT on + those decisions with the EventLoop's collaborators -- register/abort the + P->D sender, submit admitted requests, finish failed ones. No-op (and no + collective) on non-EPD nodes. + """ + if self.epd_admission is None: + return + # Pause gate: withhold EPD admission while paused, mirroring the non-EPD + # admit_blocked gate -- else the drain below would submit and RUN reassembled + # specs during the pause. Staged receives wait in _pending until resume. + # Rank-safe: admit_blocked is rank-identical, so all ranks skip together. + if self._pause.admit_blocked: + return + admitted_ids, failed_ids = self.epd_admission.drain() + for rid in failed_ids: + spec, state, bootstrap = self._epd_staged.pop(rid) + # Signal the dual-dispatched decode that this request failed so its KV + # receiver fails (FailedEvent -> _process_pd_events abort) instead of + # waiting forever for KV the prefill will never send. The prefill never + # registered a P->D sender (deferred to admission), so the decode has no + # other reliable way to learn (heartbeat only trips on a dead prefill + # /health). Best-effort: only reaches decodes that already pre-allocated. + if ( + isinstance(self.kv_transfer, DisaggPrefillExecutor) + and bootstrap is not None + ): + try: + self.kv_transfer.abort(rid, bootstrap) + except Exception as exc: # never let it wedge the loop + logger.warning( + "EPD abort->decode signal failed for rid=%s: %s", + rid, + exc, + ) + state.set_finish_with_abort("EPD embedding receive failed or timed out") + self.output_processor.publish_finished_at_admission(rid, state) + admitted_specs = [] + for rid in admitted_ids: + spec, state, bootstrap = self._epd_staged.pop(rid) + # Aborted mid-receive (no abort path, so drain still returns it admitted): + # don't register the P->D sender or submit -- that runs a wasted forward + # and leaks the sender. Stream its finish instead. + if state.finished: + self.output_processor.publish_finished_at_admission(rid, state) + continue + # Register the P->D sender now (deferred from admission) -- the request + # is about to enter the scheduler. + if self.kv_transfer is not None: + self.kv_transfer.register(rid, bootstrap) + admitted_specs.append(spec) + if admitted_specs: + self.scheduler.submit_requests(admitted_specs) + elif self.epd_admission.has_pending(): + # Nothing advanced this cycle but requests are still receiving; yield the + # GIL so the Python daemon transfer/recv threads run (rank-consistent: + # admitted/leftover are rank-identical here). + time.sleep(0.0005) def _commit_cache_results(self) -> None: if self.memory_executor is None: @@ -651,7 +781,7 @@ def _dispatch_forward( self.model_executor.update_block_table(forward_op) - if self.pd_kv_transfer is None: + if self.kv_transfer is None: # Path 1: normal (no disaggregation) self.model_executor.reset_valid_cache_length(forward_op) return ( @@ -668,17 +798,17 @@ def _dispatch_forward( None, ) - elif isinstance(self.pd_kv_transfer, DisaggDecodeExecutor): + elif isinstance(self.kv_transfer, DisaggDecodeExecutor): # Decode node if forward_op.num_extends() > 0: # Path 2: new requests waiting for remote KV — trigger RDMA receive - self.pd_kv_transfer.reset_valid_cache_length( + self.kv_transfer.reset_valid_cache_length( forward_op, self.model_executor.runtime_states, self.model_executor.execution_stream, self.model_executor.device, ) - self.pd_kv_transfer.execute(forward_op) + self.kv_transfer.execute(forward_op) self.model_executor.reset_remote_prefill_mamba_inputs(forward_op) return None, None else: @@ -699,15 +829,19 @@ def _dispatch_forward( else: # Prefill node (only reached from event_loop, never event_loop_overlap) - assert isinstance(self.pd_kv_transfer, DisaggPrefillExecutor) + assert isinstance(self.kv_transfer, DisaggPrefillExecutor) if forward_op.num_extends() == 0: # Path 3: all prefill done — send KV to decode side - self.pd_kv_transfer.execute(forward_op) + self.kv_transfer.execute(forward_op) return None, None else: # Path 4: extend batch — run prefill forward self.model_executor.reset_valid_cache_length(forward_op) - self.pd_kv_transfer.prepare_prefill(forward_op) + self.kv_transfer.prepare_prefill(forward_op) + # EPD invariant: handshaked items are filled by the async + # EPD admission drain before admission; assert none reached + # the forward un-received (no-op for non-EPD / text-only requests). + self._assert_epd_embeddings_received(multimodal_context) return ( self.model_executor.execute_forward_op_with_log( forward_op, @@ -720,7 +854,7 @@ def _dispatch_forward( capture_next_input_ids=True, **stats, ), - self.pd_kv_transfer.store_prefill_token, + self.kv_transfer.store_prefill_token, ) def _get_multimodal_context_for_forward(self, forward_op): @@ -1024,11 +1158,19 @@ def _process_new_requests(self): ) continue - if isinstance(self.pd_kv_transfer, DisaggDecodeExecutor): + if isinstance(self.kv_transfer, DisaggDecodeExecutor): state.computed_length = state.input_length self.output_processor.register(spec.request_id, state) - if self.pd_kv_transfer is not None: - self.pd_kv_transfer.register(spec.request_id, bootstrap) + is_epd = self.epd_admission is not None and self._is_epd_request(state) + # EPD: DEFER the P->D sender registration to admission (in + # EpdPrefillAdmission.drain, just before submit_requests). Registering + # it now -- while the request is staged and NOT yet in the C++ scheduler + # -- would let DisaggPrefillExecutor.generate_events poll the sender and + # emit a BootstrappedEvent that the scheduler's requests_.at(rid) THROWS + # on (no such request yet). Non-EPD requests register now (submitted this + # same call). + if self.kv_transfer is not None and not is_epd: + self.kv_transfer.register(spec.request_id, bootstrap) if self.memory_executor is not None: hashes = calc_l3_query_hashes(self.scheduler, spec.tokens) @@ -1043,7 +1185,20 @@ def _process_new_requests(self): ) spec.rolling_hashes = hashes spec.storage_hit_pages = hit_pages - admitted_specs.append(spec) + # EPD prefill: hold a request whose images are encode-routed OUT of the + # scheduler until its per-image embeddings have been received (started + # here, polled in EpdPrefillAdmission.drain, which registers the P->D + # sender + submits once ready). It is output_processor-registered above; + # the sender registration + submission are both deferred. Non-EPD + # requests admit immediately as before. Rank-identical because `ready` is + # rank-synced (recv_reqs broadcast + grammar gather). + if is_epd: + self.epd_admission.stage( + spec.request_id, state.multimodal_inputs.mm_items + ) + self._epd_staged[spec.request_id] = (spec, state, bootstrap) + else: + admitted_specs.append(spec) # Pause gate: while paused, withhold new requests from the scheduler # (running requests keep stepping); buffered specs are flushed on resume @@ -1089,13 +1244,14 @@ def _commit_forward_results( self.request_handler._profile_batch_predicate(forward_mode) # post_process_forward_op calls sync() — after this, CPU tensors are ready - is_prefill_instance = isinstance(self.pd_kv_transfer, DisaggPrefillExecutor) + is_prefill_instance = isinstance(self.kv_transfer, DisaggPrefillExecutor) request_changes = self.output_processor.post_process_forward_op( forward_op, results, is_prefill_instance=is_prefill_instance, on_first_token=on_first_token, ) + # Accumulate decode stats from synced results (no GPU sync) if forward_op.num_extends() <= 0: bs = len(forward_op.request_ids) @@ -1115,17 +1271,16 @@ def _process_pd_events(self, pd_events: list) -> list: for event in pd_events: processed.append(event) if isinstance(event, PD.SucceededEvent) and isinstance( - self.pd_kv_transfer, DisaggPrefillExecutor + self.kv_transfer, DisaggPrefillExecutor ): req_id = event.request_id processed.extend(self.output_processor.finish_prefill_request(req_id)) elif isinstance(event, PD.RemotePrefillDoneEvent): req_id = event.request_id bootstrap_token = event.bootstrap_token - self.output_processor.on_remote_prefill_done(req_id, bootstrap_token) - if isinstance(self.pd_kv_transfer, DisaggDecodeExecutor): - candidate_info = self.pd_kv_transfer.pop_remote_spec_candidate_ids( + if isinstance(self.kv_transfer, DisaggDecodeExecutor): + candidate_info = self.kv_transfer.pop_remote_spec_candidate_ids( req_id ) if candidate_info is not None: @@ -1133,6 +1288,25 @@ def _process_pd_events(self, pd_events: list) -> list: self.model_executor.write_remote_spec_candidate_ids( req_pool_idx, candidate_ids ) + elif isinstance(event, PD.FailedEvent): + # A PD/EPD transfer failed: the decode KV receiver timed out (e.g. the + # prefill aborted on embedding timeout so the KV never arrives), or a + # transfer errored. The C++ scheduler's FailedEvent handler is a no-op, + # so without this the request is never finished and the CLIENT HANGS + # FOREVER (the decode is its response stream). Finish it with an abort + # (streams the error to the client) and abort it in the scheduler so its + # slot/KV is freed. AbortEvent is valid from the decode-waiting state + # (forward_events.cpp: AbortEvent(Prefilling&&) -> Finished). + req_id = event.request_id + state = self.output_processor.rid_to_state.get(req_id) + if state is not None: + state.set_finish_with_abort( + "PD/EPD remote transfer failed or timed out" + ) + self.output_processor.publish_finished_at_admission(req_id, state) + abort = ForwardEvent.Abort() + abort.request_id = req_id + processed.append(abort) return processed @@ -1164,7 +1338,7 @@ def _dp_sync_and_check(self, forward_op) -> DpForwardMetadata: executes_model_forward = _forward_op_executes_model_forward( forward_op, - is_disagg_decode=isinstance(self.pd_kv_transfer, DisaggDecodeExecutor), + is_disagg_decode=isinstance(self.kv_transfer, DisaggDecodeExecutor), ) num_tokens = sum(forward_op.input_lengths) if executes_model_forward else 0 batch_size = len(forward_op.request_ids) if executes_model_forward else 0 @@ -1300,6 +1474,11 @@ def event_loop(self): """Non-overlapping scheduler loop.""" while True: self._process_new_requests() + # EPD prefill: admit requests whose async embedding receives completed + # this cycle (rank-synced). Fixed position right after + # _process_new_requests so the drain's TP collective ordering is + # rank-identical every cycle. + self._drain_ready_epd_embeddings() self._commit_cache_results() if self._pause.forward_blocked: self._paused_idle_step() @@ -1350,8 +1529,8 @@ def event_loop(self): ) ) - if self.pd_kv_transfer is not None: - pd_events = self.pd_kv_transfer.generate_events() + if self.kv_transfer is not None: + pd_events = self.kv_transfer.generate_events() request_changes.extend(self._process_pd_events(pd_events)) if request_changes: @@ -1422,6 +1601,17 @@ def event_loop_overlap(self): Overlapping scheduler loop: post-process the previous step's results while the current step's forward pass is in flight. """ + # EPD invariant: the async embedding drain (EpdPrefillAdmission.drain) + # that admits EPD requests runs ONLY in event_loop(), never here. A + # prefill node that receives encode embeddings must therefore run the + # non-overlap loop -- should_use_overlap_schedule enforces this by forcing + # prefill -> non-overlap. Assert it rather than trusting that external + # coupling: if a prefill ever reached this loop, every EPD request would + # stage into the admission controller and hang forever with no drain. + assert self.epd_admission is None, ( + "EPD prefill must run the non-overlap event_loop(); the embedding " + "drain is not wired into event_loop_overlap()" + ) prev_results: ModelExecutionResult = None prev_forward_op = None @@ -1534,8 +1724,8 @@ def event_loop_overlap(self): ) # ---- collect PD events ---- - if self.pd_kv_transfer is not None: - pd_events = self.pd_kv_transfer.generate_events() + if self.kv_transfer is not None: + pd_events = self.kv_transfer.generate_events() request_changes.extend(self._process_pd_events(pd_events)) if request_changes: @@ -1571,6 +1761,16 @@ def run_event_loop( configure_logger(server_args, prefix=prefix) try: + if server_args.disaggregation_mode == "encode": + # The encode role is LM-free; run the lightweight vision-tower loop + # instead of building the full EventLoop (KV/LM scheduler). + from tokenspeed.runtime.disaggregation.embedding.encode_loop import ( + run_encode_loop, + ) + + run_encode_loop(server_args, port_args, pipe_writer, gpu_id, global_rank) + return + event_loop = EventLoop( server_args, port_args, diff --git a/python/tokenspeed/runtime/engine/request_handler.py b/python/tokenspeed/runtime/engine/request_handler.py index 9ef1dcbf000..a515fa26338 100644 --- a/python/tokenspeed/runtime/engine/request_handler.py +++ b/python/tokenspeed/runtime/engine/request_handler.py @@ -29,6 +29,7 @@ import zmq from viztracer import VizTracer +from tokenspeed.runtime.disaggregation.kv.types import BootstrapInfo from tokenspeed.runtime.distributed.process_group_manager import ( process_group_manager as pg_manager, ) @@ -59,7 +60,6 @@ from tokenspeed.runtime.execution.forward_batch_info import ForwardMode from tokenspeed.runtime.grammar.grammar_manager import GrammarManager from tokenspeed.runtime.multimodal.shm_transport import sync_shm_features -from tokenspeed.runtime.pd.base import BootstrapInfo from tokenspeed.runtime.utils import broadcast_pyobj from tokenspeed.runtime.utils.dispatch import TypeBasedDispatcher from tokenspeed.runtime.utils.env import envs diff --git a/python/tokenspeed/runtime/engine/schedule_batch.py b/python/tokenspeed/runtime/engine/schedule_batch.py index 8368eec8912..199c6fac304 100755 --- a/python/tokenspeed/runtime/engine/schedule_batch.py +++ b/python/tokenspeed/runtime/engine/schedule_batch.py @@ -46,15 +46,15 @@ from tokenspeed.runtime.cache.base_prefix_cache import BasePrefixCache from tokenspeed.runtime.cache.req_to_token_pool import ReqToTokenPool from tokenspeed.runtime.configs.model_config import ModelConfig +from tokenspeed.runtime.disaggregation.kv.decode_scheduler import ( + DisaggDecodeScheduler, +) from tokenspeed.runtime.engine.request import Req from tokenspeed.runtime.execution.forward_batch_info import ( ForwardMode, ) from tokenspeed.runtime.layers.attention.kv_cache.base import BaseTokenToKVPool from tokenspeed.runtime.layers.logits_processor import LogitsProcessorOutput -from tokenspeed.runtime.pd.disaggregation_decode_scheduler import ( - DisaggregationDecodeScheduler, -) from tokenspeed.runtime.sampling.sampling_batch_info import SamplingBatchInfo from tokenspeed.runtime.utils import get_colorful_logger @@ -69,7 +69,7 @@ @dataclasses.dataclass -class ScheduleBatch(DisaggregationDecodeScheduler): +class ScheduleBatch(DisaggDecodeScheduler): """Store all information of a batch on the scheduler.""" # Request, memory pool, and cache diff --git a/python/tokenspeed/runtime/engine/scheduler_utils.py b/python/tokenspeed/runtime/engine/scheduler_utils.py index 1ddd72b1a7a..692f868f948 100644 --- a/python/tokenspeed/runtime/engine/scheduler_utils.py +++ b/python/tokenspeed/runtime/engine/scheduler_utils.py @@ -174,7 +174,8 @@ def should_use_overlap_schedule( if disable_overlap_schedule: return False - if disaggregation_mode == "prefill": + if disaggregation_mode in ("prefill", "encode"): + # prefill drain + KV send run only on the non-overlap loop; encode has no LM loop. return False if speculative_algorithm is not None and paged_cache_groups: return False diff --git a/python/tokenspeed/runtime/execution/model_executor.py b/python/tokenspeed/runtime/execution/model_executor.py index 413dbec8324..05882d41713 100644 --- a/python/tokenspeed/runtime/execution/model_executor.py +++ b/python/tokenspeed/runtime/execution/model_executor.py @@ -1957,11 +1957,22 @@ def _build_mrope_positions_override( mrope_chunks = [] for batch_idx, base_chunk in enumerate(pos_chunks): mm_input = mm_inputs[batch_idx] if batch_idx < len(mm_inputs) else None - if mm_input is None or mm_input.mrope_positions is None: + # Fall back to linear only when there is neither a per-token mrope table + # nor a transferred scalar delta. A decode-only mm_input may carry just + # the delta (post-image decode positions = base+delta); it must skip the + # fallback and take the base+delta branch below. + if mm_input is None or ( + mm_input.mrope_positions is None + and mm_input.mrope_position_delta is None + ): mrope_chunks.append(base_chunk.unsqueeze(0).expand(3, -1)) continue - if is_prefill and batch_idx < len(forward_op.extend_prefix_lens): + if ( + is_prefill + and mm_input.mrope_positions is not None + and batch_idx < len(forward_op.extend_prefix_lens) + ): start = int(forward_op.extend_prefix_lens[batch_idx]) end = start + int(forward_op.input_lengths[batch_idx]) positions = mm_input.mrope_positions[:, start:end] diff --git a/python/tokenspeed/runtime/layers/attention/backends/base.py b/python/tokenspeed/runtime/layers/attention/backends/base.py index fa95c3025e2..85750958f28 100644 --- a/python/tokenspeed/runtime/layers/attention/backends/base.py +++ b/python/tokenspeed/runtime/layers/attention/backends/base.py @@ -27,11 +27,11 @@ import torch if TYPE_CHECKING: + from tokenspeed.runtime.disaggregation.kv.utils import StepCounter from tokenspeed.runtime.execution.forward_batch_info import ForwardMode from tokenspeed.runtime.layers.attention.configs.base import BaseAttnConfig from tokenspeed.runtime.layers.attention.kv_cache.base import BaseTokenToKVPool from tokenspeed.runtime.layers.paged_attention import PagedAttention - from tokenspeed.runtime.pd.utils import StepCounter class AttentionBackend(ABC): diff --git a/python/tokenspeed/runtime/models/base/causal_lm.py b/python/tokenspeed/runtime/models/base/causal_lm.py index 5f3f48f0863..b0352f64328 100644 --- a/python/tokenspeed/runtime/models/base/causal_lm.py +++ b/python/tokenspeed/runtime/models/base/causal_lm.py @@ -50,6 +50,7 @@ def __init__( mapping: Mapping, quant_config: QuantizationConfig | None = None, prefix: str = "", + encoder_only: bool = False, ) -> None: super().__init__() @@ -58,9 +59,19 @@ def __init__( self.quant_config = quant_config self.capture_aux_hidden_states: bool = False - self.model = self.resolve_model(config, mapping, quant_config, prefix) - self.lm_head = self.resolve_lm_head(config, quant_config, prefix) - self.logits_processor = self.resolve_logits_processor(config) + self.encoder_only = encoder_only + if encoder_only: + # Vision-only role (EPD encode): never allocate the LM / lm_head / + # logits processor (the LM allocation is the OOM at encode TP=1). + # self.config is already set above for the vision path + # (separate_deepstack_embeds needs self.config.hidden_size). + self.model = None + self.lm_head = None + self.logits_processor = None + else: + self.model = self.resolve_model(config, mapping, quant_config, prefix) + self.lm_head = self.resolve_lm_head(config, quant_config, prefix) + self.logits_processor = self.resolve_logits_processor(config) self.post_init() def resolve_model( diff --git a/python/tokenspeed/runtime/models/kimi_k25.py b/python/tokenspeed/runtime/models/kimi_k25.py index a1ddb4611bb..bb5dcc8f29c 100644 --- a/python/tokenspeed/runtime/models/kimi_k25.py +++ b/python/tokenspeed/runtime/models/kimi_k25.py @@ -808,9 +808,9 @@ def pre_encode( """ device = self.vision_tower.device target_dtype = self.vision_tower.patch_embed.proj.weight.dtype - pixel_values = torch.cat([item.feature for item in items], dim=0).to( - device=device, dtype=target_dtype - ) + pixel_values = torch.cat( + [item.feature.to(device, non_blocking=True) for item in items], dim=0 + ).to(dtype=target_dtype) grid_thws = torch.concat([item.grid_thws for item in items], dim=0).to(device) hidden_states = self.vision_tower.patch_embed(pixel_values, grid_thws) return hidden_states, grid_thws diff --git a/python/tokenspeed/runtime/models/qwen3_5.py b/python/tokenspeed/runtime/models/qwen3_5.py index 5fbdd3dc491..22cb384fa0c 100644 --- a/python/tokenspeed/runtime/models/qwen3_5.py +++ b/python/tokenspeed/runtime/models/qwen3_5.py @@ -1161,6 +1161,7 @@ def __init__( mapping=mapping, quant_config=quant_config, prefix=prefix, + encoder_only=getattr(config, "encoder_only", False), ) rope_config = get_rope_parameters(self.config) @@ -1229,9 +1230,10 @@ def pre_encode( video, ``image_grid_thw`` otherwise) so a single shared encoder cudagraph wrapper can serve both image and video batches. """ - pixel_values = torch.cat([item.feature for item in items], dim=0).type( - self.visual.dtype - ) + device = self.visual.device + pixel_values = torch.cat( + [item.feature.to(device, non_blocking=True) for item in items], dim=0 + ).type(self.visual.dtype) grid = torch.concat( [ getattr( @@ -1407,6 +1409,12 @@ def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]): continue if not self.is_multimodal_active and "visual" in name: continue + # Vision-only role: drop every non-visual (LM / lm_head / norm / + # embed) weight up front, before any rename or params_dict lookup, + # so none is routed into a None module. self.model is None here, so + # named_parameters() exposes only visual params. + if getattr(self, "encoder_only", False) and "visual" not in name: + continue if "language_model" in name: name = name.replace(r"model.language_model.", r"model.") if ".self_attn." in name: @@ -1527,6 +1535,13 @@ def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]): continue if not self.is_multimodal_active and "visual" in name: continue + # Vision-only role: drop every non-visual (LM / lm_head / norm / + # embed / expert) weight up front, before any rename, params_dict + # lookup, or moe_loader.load (which would KeyError on a missing + # expert param). self.model is None here, so named_parameters() + # exposes only visual params. + if getattr(self, "encoder_only", False) and "visual" not in name: + continue if "language_model" in name: name = name.replace(r"model.language_model.", r"model.") if ".self_attn." in name: diff --git a/python/tokenspeed/runtime/multimodal/inputs.py b/python/tokenspeed/runtime/multimodal/inputs.py index 51f87fd52bd..269d1ebad82 100644 --- a/python/tokenspeed/runtime/multimodal/inputs.py +++ b/python/tokenspeed/runtime/multimodal/inputs.py @@ -80,6 +80,14 @@ class MultimodalDataItem: # deepstack-enabled modalities. encoded: Optional[torch.Tensor] = None encoded_deepstack: Optional[torch.Tensor] = None + # EPD (encode-prefill-decode): when set, this item's embedding is received + # from an encode worker over Mooncake into ``encoded`` instead of running the + # vision tower. A dict ``{bootstrap_room, bootstrap_host, bootstrap_port}`` + # naming the encode worker's rendezvous for this item's image (one room per + # item: the gateway splits the mm payload one item per image and the encode + # worker row-splits the concatenated-subgrid embedding per item). None for + # non-EPD items (left to the vision tower). + encode_handshake: Optional[dict] = None def __getattr__(self, name: str): if ( diff --git a/python/tokenspeed/runtime/pd/common/conn.py b/python/tokenspeed/runtime/pd/common/conn.py deleted file mode 100755 index 669d82a0b05..00000000000 --- a/python/tokenspeed/runtime/pd/common/conn.py +++ /dev/null @@ -1,627 +0,0 @@ -# Copyright (c) 2026 LightSeek Foundation -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. - -from __future__ import annotations - -import asyncio -import logging -import socket -import threading -import time -from functools import cache -from typing import Dict, Optional, Union - -import numpy as np -import numpy.typing as npt -import requests -import zmq -from aiohttp import web - -from tokenspeed.runtime.pd.base.conn import ( - BaseKVBootstrapServer, - BaseKVManager, - BaseKVReceiver, - BaseKVSender, - KVArgs, - KVPoll, -) -from tokenspeed.runtime.pd.utils import DisaggregationMode -from tokenspeed.runtime.utils.network import ( - get_free_port, - get_ip, - get_local_ip_by_remote, -) -from tokenspeed.runtime.utils.server_args import ServerArgs - -logger = logging.getLogger(__name__) - - -class CommonKVManager(BaseKVManager): - def __init__( - self, - args: KVArgs, - disaggregation_mode: DisaggregationMode, - server_args: ServerArgs, - is_mla_backend: Optional[bool] = False, - draft_is_mla_backend: Optional[bool] = False, - ): - self.kv_args = args - self.is_mla_backend = is_mla_backend - self.draft_is_mla_backend = draft_is_mla_backend - self.disaggregation_mode = disaggregation_mode - # for p/d multi node infer - self.bootstrap_port = server_args.disaggregation_bootstrap_port - self.dist_init_addr = server_args.dist_init_addr - self.world_size = server_args.mapping.world_size - self.dp_size = server_args.mapping.attn.dp_size - - self.rank_port = get_free_port() - # Store decode prefix lengths received from decode side - self.decode_prefix_lengths = {} - - if self.disaggregation_mode == DisaggregationMode.PREFILL: - self._register_to_bootstrap() - # Start bootstrap thread to receive decode prefix info from decode side - self._start_bootstrap_thread() - # For decode side receivers that need to fetch prefill info - self.prefill_tp_size_table: Dict[str, int] = {} - self.prefill_dp_size_table: Dict[str, int] = {} - # Keep this attribute populated because some decode-side callers - # still read connection_pool directly. - self.connection_pool: Dict[str, Dict[str, Union[str, int]]] = {} - elif self.disaggregation_mode == DisaggregationMode.DECODE: - self.connection_pool: Dict[str, Dict[str, Union[str, int]]] = {} - self.prefill_tp_size_table: Dict[str, int] = {} - self.prefill_dp_size_table: Dict[str, int] = {} - else: - raise ValueError( - f"Unsupported DisaggregationMode: {self.disaggregation_mode}" - ) - - def _register_to_bootstrap(self): - """Register KVSender to bootstrap server via HTTP POST.""" - if self.dist_init_addr: - ip_address = socket.gethostbyname(self.dist_init_addr.split(":")[0]) - else: - ip_address = get_ip() - - bootstrap_server_url = f"{ip_address}:{self.bootstrap_port}" - url = f"http://{bootstrap_server_url}/route" - payload = { - "role": "Prefill", - "world_size": self.world_size, - "dp_size": self.dp_size, - "rank_ip": get_local_ip_by_remote(), - "rank_port": self.rank_port, - "engine_rank": self.kv_args.engine_rank, - } - - try: - response = requests.put(url, json=payload) - if response.status_code == 200: - logger.debug("Prefill successfully registered to bootstrap server.") - else: - logger.error( - "Prefill Failed to connect to bootstrap server: %s, %s", - response.status_code, - response.text, - ) - except Exception as e: - logger.error("Prefill failed to register with bootstrap server: %s", e) - - @cache - def _connect(self, endpoint: str): - socket = zmq.Context().socket(zmq.PUSH) - socket.connect(endpoint) - return socket - - def receive_decode_prefix_info(self, bootstrap_room: int) -> int: - """Receive decode prefix info from decode side""" - return self.decode_prefix_lengths.get(bootstrap_room, 0) - - def _start_bootstrap_thread(self): - """Start thread to receive decode prefix info from decode side""" - - def bootstrap_thread(): - """This thread receives decode prefix info from decode engine""" - server_socket = zmq.Context().socket(zmq.PULL) - server_socket.bind(f"tcp://{get_local_ip_by_remote()}:{self.rank_port}") - - logger.info( - "Bootstrap thread started on port %s, waiting for decode prefix info...", - self.rank_port, - ) - - while True: - try: - # Receive message with decode_prefix_len - msg_parts = server_socket.recv_multipart() - if len(msg_parts) >= 6: - bootstrap_room = int(msg_parts[0].decode("ascii")) - # decode_prefix_len is msg_parts[5] - decode_prefix_len = int(msg_parts[5].decode("ascii")) - - # Store decode prefix length - self.decode_prefix_lengths[bootstrap_room] = decode_prefix_len - logger.debug( - "Received decode_prefix_len=%s for bootstrap_room=%s", - decode_prefix_len, - bootstrap_room, - ) - else: - logger.warning( - "Received unexpected message format with %s parts", - len(msg_parts), - ) - except Exception as e: - logger.error("Error in bootstrap thread: %s", e) - time.sleep(0.1) # Avoid busy loop - - threading.Thread(target=bootstrap_thread, daemon=True).start() - - def send_decode_prefix_info(self, bootstrap_room: int, decode_prefix_len: int): - """Send decode prefix info to prefill side - in common backend this is handled via ZMQ thread""" - # In common implementation, decode prefix info is sent via ZMQ in the bootstrap thread - # Store it for the bootstrap thread to send - self.decode_prefix_lengths[bootstrap_room] = decode_prefix_len - logger.debug( - "Stored decode_prefix_len=%s for bootstrap_room=%s", - decode_prefix_len, - bootstrap_room, - ) - - def update_status(self, bootstrap_room: int, status: KVPoll): - """Base hook for backends that track per-room status transitions.""" - # In common implementation, we don't need to track status - pass - - -class CommonKVReceiver(BaseKVReceiver): - _ctx = zmq.Context() - _socket_cache = {} - _socket_locks = {} - _global_lock = threading.Lock() - - def __init__( - self, - mgr: BaseKVManager, - bootstrap_addr: str, - bootstrap_room: Optional[int] = None, - ): - self.bootstrap_room = bootstrap_room - self.bootstrap_addr = bootstrap_addr - self.kv_mgr = mgr - - if self.bootstrap_addr not in self.kv_mgr.prefill_dp_size_table: - self.prefill_tp_size, self.prefill_dp_size = ( - self._get_prefill_dp_size_from_server() - ) - - if self.prefill_tp_size is None or self.prefill_dp_size is None: - logger.error( - "Could not fetch prefill parallel info for bootstrap_addr: %s", - self.bootstrap_addr, - ) - else: - self.kv_mgr.prefill_tp_size_table[self.bootstrap_addr] = ( - self.prefill_tp_size - ) - self.kv_mgr.prefill_dp_size_table[self.bootstrap_addr] = ( - self.prefill_dp_size - ) - else: - self.prefill_tp_size = self.kv_mgr.prefill_tp_size_table[ - self.bootstrap_addr - ] - self.prefill_dp_size = self.kv_mgr.prefill_dp_size_table[ - self.bootstrap_addr - ] - - # Currently, we don't allow prefill instance and decode instance to - # have different TP sizes per DP rank, except for models using MLA. - if self.prefill_tp_size is not None and self.prefill_dp_size is not None: - local_tp_size_per_dp_rank = self.kv_mgr.tp_size // self.kv_mgr.dp_size - prefill_tp_size_per_dp_rank = self.prefill_tp_size // self.prefill_dp_size - else: - local_tp_size_per_dp_rank = 1 # fallback - prefill_tp_size_per_dp_rank = 1 - - if not self.kv_mgr.draft_is_mla_backend: - assert ( - local_tp_size_per_dp_rank == prefill_tp_size_per_dp_rank - ), "PD with different TP sizes per DP rank is not yet supported for non-MLA models" - - if local_tp_size_per_dp_rank == prefill_tp_size_per_dp_rank: - self.target_tp_rank = ( - self.kv_mgr.kv_args.engine_rank % local_tp_size_per_dp_rank - ) - self.required_dst_info_num = 1 - self.target_tp_ranks = [self.target_tp_rank] - elif local_tp_size_per_dp_rank > prefill_tp_size_per_dp_rank: - assert ( - self.kv_mgr.is_mla_backend - ), "PD with different TP sizes per DP rank is not yet supported for non-MLA models" - self.target_tp_rank = ( - self.kv_mgr.kv_args.engine_rank % local_tp_size_per_dp_rank - ) // (local_tp_size_per_dp_rank // prefill_tp_size_per_dp_rank) - self.required_dst_info_num = ( - local_tp_size_per_dp_rank // prefill_tp_size_per_dp_rank - ) - self.target_tp_ranks = [self.target_tp_rank] - else: - assert ( - self.kv_mgr.is_mla_backend - ), "PD with different TP sizes per DP rank is not yet supported for non-MLA models" - - # For non-MLA models, one decode rank needs to retrieve KVCache from multiple prefill ranks for non MLA models; - self.target_tp_ranks = [ - rank - for rank in range( - (self.kv_mgr.kv_args.engine_rank % local_tp_size_per_dp_rank) - * (prefill_tp_size_per_dp_rank // local_tp_size_per_dp_rank), - (self.kv_mgr.kv_args.engine_rank % local_tp_size_per_dp_rank + 1) - * (prefill_tp_size_per_dp_rank // local_tp_size_per_dp_rank), - ) - ] - - # For MLA models, we can retrieve KVCache from only one prefill rank, but we still need to maintain - # multiple connections in the connection pool and have to send dummy requests to other prefill ranks, - # or the KVPoll will never be set correctly - self.target_tp_rank = self.target_tp_ranks[0] - self.required_dst_info_num = 1 - - self.target_dp_group = ( - bootstrap_room % self.prefill_dp_size - if self.prefill_dp_size is not None - else 1 - ) - - # key distinguished by bootstrap_addr, target_dp_group, and target_tp_rank - bootstrap_key = ( - f"{self.bootstrap_addr}_{self.target_dp_group}_{self.target_tp_rank}" - ) - - if bootstrap_key not in self.kv_mgr.connection_pool: - bootstrap_infos = [] - for target_tp_rank in self.target_tp_ranks: - bootstrap_info = self._get_bootstrap_info_from_server( - target_tp_rank, - self.target_dp_group, - ) - if bootstrap_info is not None: - # only support MLA for now: select one prefill rank as real rank - bootstrap_info["is_dummy"] = not bool( - target_tp_rank == self.target_tp_rank - or self.target_tp_rank is None - ) - bootstrap_infos.append(bootstrap_info) - else: - logger.error( - "Could not fetch bootstrap info for engine rank: %s and target_dp_group: %s", - self.kv_mgr.kv_args.engine_rank, - self.target_dp_group, - ) - self.bootstrap_infos = bootstrap_infos - - if len(self.bootstrap_infos) == 0: - logger.error( - "Could not fetch bootstrap info for engine rank: %s", - self.kv_mgr.kv_args.engine_rank, - ) - else: - self.kv_mgr.connection_pool[bootstrap_key] = self.bootstrap_infos - # Register kv_args only once to prefill KVManager according to the info fetched from the bootstrap server - self._register_kv_args() - else: - self.bootstrap_infos = self.kv_mgr.connection_pool[bootstrap_key] - - assert len(self.bootstrap_infos) > 0 - - def _get_bootstrap_info_from_server(self, engine_rank, target_dp_group): - """Fetch the bootstrap info from the bootstrap server.""" - try: - url = f"http://{self.bootstrap_addr}/route?engine_rank={engine_rank}&target_dp_group={target_dp_group}" - response = requests.get(url) - if response.status_code == 200: - bootstrap_info = response.json() - return bootstrap_info - else: - logger.error( - "Failed to get prefill server info: %s, %s", - response.status_code, - response.text, - ) - return None - except Exception as e: - logger.error("Error fetching prefill info from bootstrap: %s", e) - return None - - def _get_prefill_dp_size_from_server(self) -> int: - """Fetch the prefill parallel info from the bootstrap server.""" - try: - url = f"http://{self.bootstrap_addr}/route?engine_rank={-1}&target_dp_group={-1}" - response = requests.get(url) - if response.status_code == 200: - prefill_parallel_info = response.json() - return int(prefill_parallel_info["prefill_tp_size"]), int( - prefill_parallel_info["prefill_dp_size"] - ) - else: - logger.error( - "Failed to get prefill parallel info: %s, %s", - response.status_code, - response.text, - ) - return None - except Exception as e: - logger.error("Error fetching prefill parallel info from bootstrap: %s", e) - return None - - @classmethod - def _connect(cls, endpoint: str): - with cls._global_lock: - if endpoint not in cls._socket_cache: - sock = cls._ctx.socket(zmq.PUSH) - sock.connect(endpoint) - cls._socket_cache[endpoint] = sock - cls._socket_locks[endpoint] = threading.Lock() - return cls._socket_cache[endpoint], cls._socket_locks[endpoint] - - def init( - self, - kv_indices: npt.NDArray[np.int64], - aux_index: Optional[int] = None, - decode_prefix_len: Optional[int] = 0, - ): - """ - Notify prefill server about the kv indices and aux index, - and send decode prefix length to prefill side - """ - self.decode_prefix_len = decode_prefix_len - - if not self.bootstrap_infos: - logger.error( - "No bootstrap infos available for room %s", self.bootstrap_room - ) - raise RuntimeError( - f"No bootstrap infos available for room {self.bootstrap_room}" - ) - - for bootstrap_info in self.bootstrap_infos: - self.prefill_server_url = ( - f"{bootstrap_info['rank_ip']}:{bootstrap_info['rank_port']}" - ) - is_dummy = bootstrap_info["is_dummy"] - - logger.debug( - "CommonKVReceiver init to %s with bootstrap room %s, decode_prefix_len=%s, is_dummy=%s", - self.prefill_server_url, - self.bootstrap_room, - decode_prefix_len, - is_dummy, - ) - - sock, lock = self._connect("tcp://" + self.prefill_server_url) - with lock: - # Send decode_prefix_len as additional message part - sock.send_multipart( - [ - str(self.bootstrap_room).encode("ascii"), - get_local_ip_by_remote().encode("ascii"), - str(self.kv_mgr.rank_port).encode("ascii"), - kv_indices.tobytes() if not is_dummy else b"", - str(aux_index).encode("ascii") if not is_dummy else b"", - str(decode_prefix_len).encode("ascii") if not is_dummy else b"", - ] - ) - - def poll(self) -> KVPoll: - """In common implementation, return success immediately after init""" - # For common backend, we assume transfer is always successful - return KVPoll.Success - - def _register_kv_args(self): - pass - - def failure_exception(self): - raise Exception("Common KVReceiver Exception") - - -class CommonKVSender(BaseKVSender): - def __init__(self, mgr: CommonKVManager, bootstrap_addr: str, bootstrap_room: int): - self.kv_mgr = mgr - self.bootstrap_room = bootstrap_room - self.bootstrap_addr = bootstrap_addr - self.kv_mgr.update_status(bootstrap_room, KVPoll.Bootstrapping) - self.aux_index = None - self.init_time = None - self.decode_prefix_len = 0 - - def init( - self, - num_kv_indices: int, - aux_index: Optional[int] = None, - decode_prefix_len: Optional[int] = 0, - ): - """Receive decode prefix length from decode side""" - self.num_kv_indices = num_kv_indices - self.aux_index = aux_index - self.decode_prefix_len = decode_prefix_len - self.init_time = time.time() - - # Get decode_prefix_len from manager if available - manager_decode_prefix_len = self.kv_mgr.receive_decode_prefix_info( - self.bootstrap_room - ) - if manager_decode_prefix_len > 0: - self.decode_prefix_len = manager_decode_prefix_len - - logger.info( - "CommonKVSender init with decode_prefix_len=%s for room %s", - self.decode_prefix_len, - self.bootstrap_room, - ) - - def send(self, kv_indices: npt.NDArray[np.int64], start_idx: Optional[int] = 0): - """In common implementation, this is a no-op since we don't actually transfer""" - logger.debug("CommonKVSender send with kv_indices: %s", kv_indices) - - def poll(self) -> KVPoll: - """In common implementation, immediately return success after init""" - if self.init_time is None: - return KVPoll.Bootstrapping - else: - return KVPoll.Success - - def failure_exception(self): - raise Exception("Common KVSender Exception") - - -class CommonKVBootstrapServer(BaseKVBootstrapServer): - def __init__(self, port: int): - self.port = port - self.app = web.Application() - self.store = dict() - self.lock = asyncio.Lock() - self._setup_routes() - self.world_size = None - self.dp_size = None - self.tp_size_per_dp_rank = None - self.prefill_port_table: Dict[int, Dict[int, Dict[str, Union[str, int]]]] = {} - - # Start bootstrap server - self.thread = threading.Thread(target=self._run_server, daemon=True) - self.run() - - def run(self): - self.thread.start() - - def _setup_routes(self): - self.app.router.add_route("*", "/route", self._handle_route) - - async def _handle_route(self, request: web.Request): - method = request.method - if method == "PUT": - return await self._handle_route_put(request) - elif method == "GET": - return await self._handle_route_get(request) - else: - return web.Response( - text="Method not allowed", status=405, content_type="application/json" - ) - - async def _handle_route_put(self, request: web.Request): - data = await request.json() - role = data["role"] - world_size = data["world_size"] - dp_size = data["dp_size"] - rank_ip = data["rank_ip"] - rank_port = int(data["rank_port"]) - engine_rank = int(data["engine_rank"]) - - if self.world_size is None: - self.world_size = world_size - - if self.dp_size is None: - self.dp_size = dp_size - - tp_size_per_dp_rank = world_size // dp_size - if self.tp_size_per_dp_rank is None: - self.tp_size_per_dp_rank = tp_size_per_dp_rank - - # Add lock to make sure thread-safe - if role == "Prefill": - dp_group = engine_rank // tp_size_per_dp_rank - tp_rank_in_dp_group = engine_rank % tp_size_per_dp_rank - - async with self.lock: - if dp_group not in self.prefill_port_table: - self.prefill_port_table[dp_group] = {} - - self.prefill_port_table[dp_group][tp_rank_in_dp_group] = { - "rank_ip": rank_ip, - "rank_port": rank_port, - } - logger.debug( - "Register Prefill bootstrap: %s with rank_ip: %s and rank_port: %s", - engine_rank, - rank_ip, - rank_port, - ) - - return web.Response(text="OK", status=200) - - async def _handle_route_get(self, request: web.Request): - engine_rank = request.query.get("engine_rank") - target_dp_group = request.query.get("target_dp_group") - if not engine_rank or not target_dp_group: - return web.Response(text="Missing inputs for bootstrap server.", status=400) - - # Currently we use engine_rank == -1 and target_dp_group == -1 to sync dp size - if int(engine_rank) == -1 and int(target_dp_group) == -1: - prefill_parallel_info = { - "prefill_tp_size": self.world_size, - "prefill_dp_size": self.dp_size, - } - return web.json_response(prefill_parallel_info, status=200) - - # Find corresponding prefill info - async with self.lock: - bootstrap_info = self.prefill_port_table[int(target_dp_group)][ - int(engine_rank) - ] - - if bootstrap_info is not None: - return web.json_response(bootstrap_info, status=200) - else: - return web.Response(text="Bootstrap info not Found", status=404) - - def _run_server(self): - try: - # Event Loop - self._loop = asyncio.new_event_loop() - asyncio.set_event_loop(self._loop) - - self._runner = web.AppRunner(self.app) - self._loop.run_until_complete(self._runner.setup()) - - site = web.TCPSite(self._runner, port=self.port) - self._loop.run_until_complete(site.start()) - self._loop.run_forever() - except Exception as e: - logger.error("Server error: %s", str(e)) - finally: - # Cleanup - self._loop.run_until_complete(self._runner.cleanup()) - self._loop.close() - - def close(self): - """Shutdown""" - if self._loop is not None and self._loop.is_running(): - self._loop.call_soon_threadsafe(self._loop.stop) - logger.info("Stopping server loop...") - - if self.thread.is_alive(): - self.thread.join(timeout=2) - logger.info("Server thread stopped") - - def poll(self) -> KVPoll: - # For common backend, we assume transfer is always successful - return KVPoll.Success diff --git a/python/tokenspeed/runtime/pd/fake/conn.py b/python/tokenspeed/runtime/pd/fake/conn.py deleted file mode 100755 index 79ff17cb8ae..00000000000 --- a/python/tokenspeed/runtime/pd/fake/conn.py +++ /dev/null @@ -1,141 +0,0 @@ -# Copyright (c) 2026 LightSeek Foundation -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. - -import logging -from typing import Optional - -import numpy as np -import numpy.typing as npt - -from tokenspeed.runtime.pd.base.conn import ( - BaseKVManager, - BaseKVReceiver, - BaseKVSender, - KVArgs, - KVPoll, -) -from tokenspeed.runtime.pd.utils import DisaggregationMode -from tokenspeed.runtime.utils.server_args import ServerArgs - -logger = logging.getLogger(__name__) - - -# For warmup reqs, we don't kv transfer, we use the fake sender and receiver -class FakeKVSender(BaseKVSender): - def __init__(self, mgr: BaseKVManager, bootstrap_addr: str, bootstrap_room: int): - self.has_sent = False - - def poll(self) -> KVPoll: - if self.has_sent is False: - # Assume handshake completed instantly - return KVPoll.WaitingForInput - else: - # Assume transfer completed instantly - logger.info("FakeKVSender poll success") - return KVPoll.Success - - def init( - self, - kv_indices: list[int], - aux_index: Optional[int] = None, - decode_prefix_len: Optional[int] = 0, - ): - self.decode_prefix_len = decode_prefix_len - logger.info( - "FakeKVSender init with kv_indices: %s, aux_index: %s, decode_prefix_len: %s", - kv_indices, - aux_index, - decode_prefix_len, - ) - pass - - def send(self, kv_indices: npt.NDArray[np.int64], start_idx: Optional[int] = 0): - self.has_sent = True - logger.info("FakeKVSender send with kv_indices: %s", kv_indices) - - def failure_exception(self): - raise Exception("Fake KVSender Exception") - - -class FakeKVReceiver(BaseKVReceiver): - def __init__( - self, - mgr: BaseKVManager, - bootstrap_addr: str, - bootstrap_room: Optional[int] = None, - ): - self.has_init = False - self.decode_prefix_len = 0 - - def poll(self) -> KVPoll: - if self.has_init is False: - # Assume handshake completed instantly - return KVPoll.WaitingForInput - else: - # Assume transfer completed instantly - logger.info("FakeKVReceiver poll success") - return KVPoll.Success - - def init( - self, - kv_indices: list[int], - aux_index: Optional[int] = None, - decode_prefix_len: Optional[int] = 0, - ): - self.has_init = True - self.decode_prefix_len = decode_prefix_len - logger.info( - "FakeKVReceiver init with kv_indices: %s, aux_index: %s, decode_prefix_len: %s", - kv_indices, - aux_index, - decode_prefix_len, - ) - - def failure_exception(self): - raise Exception("Fake KVReceiver Exception") - - -class FakeKVManager(BaseKVManager): - def __init__( - self, - args: KVArgs, - disaggregation_mode: DisaggregationMode, - server_args: ServerArgs, - is_mla_backend: Optional[bool] = False, - draft_is_mla_backend: Optional[bool] = False, - ): - self.kv_args = args - self.is_mla_backend = is_mla_backend - self.draft_is_mla_backend = draft_is_mla_backend - self.disaggregation_mode = disaggregation_mode - self.decode_prefix_lengths = {} - - def receive_decode_prefix_info(self, bootstrap_room: int) -> int: - """Receive decode prefix info from decode side""" - return self.decode_prefix_lengths.get(bootstrap_room, 0) - - def store_decode_prefix_info(self, bootstrap_room: int, decode_prefix_len: int): - """Store decode prefix info from decode side""" - self.decode_prefix_lengths[bootstrap_room] = decode_prefix_len - - def send_decode_prefix_info(self, bootstrap_room: int, decode_prefix_len: int): - """Fake backend keeps the real interface but uses direct method calls.""" - # In fake implementation, decode prefix info is handled via direct method calls - pass diff --git a/python/tokenspeed/runtime/utils/env.py b/python/tokenspeed/runtime/utils/env.py index f651ee947ee..2edf3c2da38 100755 --- a/python/tokenspeed/runtime/utils/env.py +++ b/python/tokenspeed/runtime/utils/env.py @@ -259,6 +259,7 @@ class Envs: TOKENSPEED_DISAGGREGATION_THREAD_POOL_SIZE = EnvInt(-1) TOKENSPEED_DISAGGREGATION_BOOTSTRAP_TIMEOUT = EnvInt(120) TOKENSPEED_DISAGGREGATION_WAITING_TIMEOUT = EnvInt(300) + TOKENSPEED_EPD_EMBEDDING_SHARD = EnvBool(True) TOKENSPEED_PD_LAYERWISE_DEBUG = EnvBool(False) TOKENSPEED_PD_PREFILL_METADATA_TIMEOUT = EnvFloat(5.0) diff --git a/python/tokenspeed/runtime/utils/server_args.py b/python/tokenspeed/runtime/utils/server_args.py index 9e3154ec130..64a28aece62 100755 --- a/python/tokenspeed/runtime/utils/server_args.py +++ b/python/tokenspeed/runtime/utils/server_args.py @@ -270,7 +270,7 @@ class ServerArgs: mla_chunk_multiplier: int = 4 mm_attention_backend: str | None = None - # For PD disaggregation: can be "null" (not disaggregated), "prefill" (prefill-only), or "decode" (decode-only) + # For PD/EPD disaggregation: "null", "prefill", "decode", or "encode" (vision-tower-only). disaggregation_mode: str = "null" disaggregation_bootstrap_port: int = 8998 disaggregation_transfer_backend: str = "mooncake" @@ -586,6 +586,10 @@ def resolve_disaggregation(self): "enable_prefix_caching=%r for decode server", self.enable_prefix_caching, ) + elif self.disaggregation_mode == "encode": + # Encode server: vision tower only, no LM / KV pool / prefix cache. + # enforce_eager left as-is (the vision tower keeps its own CUDA graph). + self.enable_prefix_caching = False # Prefill graph disable logic is handled by AttnInitializer.modify_args # after the attention backend is resolved. @@ -599,9 +603,12 @@ def resolve_disaggregation(self): ), f"Not Supported when {self.disaggregation_mode=} {self.load_balance_method=} {self.mapping.attn.dp_size=}" def _handle_kvstore(self): - if self.disaggregation_mode == "decode": + if self.disaggregation_mode in ("decode", "encode"): self.enable_kvstore = False - logger.info("Decode instance has set enable_kvstore to False!") + logger.info( + "%s instance has set enable_kvstore to False!", + self.disaggregation_mode, + ) elif not self.disable_kvstore: self.enable_kvstore = True @@ -1748,8 +1755,8 @@ def add_cli_args(parser: argparse.ArgumentParser): "--disaggregation-mode", type=str, default="null", - choices=["null", "prefill", "decode"], - help='Only used for PD disaggregation. "prefill" for prefill-only server, and "decode" for decode-only server. If not specified, it is not PD disaggregated', + choices=["null", "prefill", "decode", "encode"], + help='Used for PD/EPD disaggregation. "prefill" for prefill-only server, "decode" for decode-only server, and "encode" for a vision-tower-only server that ships image embeddings to a prefill server. If not specified, it is not disaggregated', ) parser.add_argument( "--comm-fusion-max-num-tokens", diff --git a/test/runtime/cache/test_embedding_cache.py b/test/runtime/cache/test_embedding_cache.py new file mode 100644 index 00000000000..c6a17da42e7 --- /dev/null +++ b/test/runtime/cache/test_embedding_cache.py @@ -0,0 +1,120 @@ +# Copyright (c) 2026 LightSeek Foundation +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +"""Unit tests for the EPD vision-embedding cache. + +These exercise pure Python logic (no GPU, no model, no torch import): the +bytes-bounded LRU and the two-tier (L1 VRAM + L2 host DRAM) cache that let +duplicate images skip the vision tower. +""" + +from __future__ import annotations + +from tokenspeed.runtime.cache.embedding_cache import ( + EmbeddingCache, + TieredEmbeddingCache, +) + + +# --------------------------------------------------------------------------- # +# EmbeddingCache +# --------------------------------------------------------------------------- # +def test_cache_hit_miss_and_counters(): + c = EmbeddingCache(capacity_bytes=1000) + assert c.get("a") is None + assert c.misses == 1 + c.put("a", "embA", nbytes=100) + assert c.get("a") == "embA" + assert c.hits == 1 + assert len(c) == 1 + assert c.current_bytes == 100 + + +def test_cache_lru_eviction_by_bytes(): + c = EmbeddingCache(capacity_bytes=250) + c.put("a", "A", 100) + c.put("b", "B", 100) + # Touch "a" so "b" becomes the LRU victim. + assert c.get("a") == "A" + c.put("c", "C", 100) # 300 > 250 -> evict LRU ("b") + assert "a" in c + assert "c" in c + assert "b" not in c + assert c.current_bytes == 200 + + +def test_cache_skips_item_larger_than_capacity(): + c = EmbeddingCache(capacity_bytes=50) + c.put("a", "A", 10) + c.put("big", "B", 100) # too big to ever retain; must not evict "a" + assert "big" not in c + assert "a" in c + assert c.current_bytes == 10 + + +# --------------------------------------------------------------------------- # +# TieredEmbeddingCache (L1 VRAM + L2 host DRAM) +# +# Inject identity / tagging copy functions so the tiering logic is exercised +# without a GPU (the production defaults call .cpu()/.to(device) on real +# tensors). Sizes are tiny so eviction is easy to drive. +# --------------------------------------------------------------------------- # +def _tiered(l1, l2, *, to_host=lambda v: v, to_device=lambda v: v): + return TieredEmbeddingCache(l1, l2, to_host=to_host, to_device=to_device) + + +def test_tiered_demote_on_l1_eviction(): + # L1 holds one 100B entry; the second put evicts the first down to L2. + tc = _tiered(150, 1000) + tc.put("a", "A", 100) + tc.put("b", "B", 100) # 200 > 150 -> "a" demoted to L2 + assert "a" not in tc.l1 and "a" in tc.l2 # exclusive + assert "b" in tc.l1 and "b" not in tc.l2 + assert tc.demotions == 1 + # Aggregate views span both tiers. + assert "a" in tc and "b" in tc # TieredEmbeddingCache.__contains__ + assert len(tc) == 2 # __len__ = len(l1) + len(l2) + + +def test_tiered_promote_on_l2_hit_is_exclusive(): + tc = _tiered(150, 1000) + tc.put("a", "A", 100) + tc.put("b", "B", 100) # "a" -> L2 + # Hit on "a": promoted back to L1, removed from L2; "b" (now LRU) demotes. + assert tc.get("a") == "A" + assert (tc.l1_hits, tc.l2_hits, tc.misses) == (0, 1, 0) + assert tc.promotions == 1 + assert "a" in tc.l1 and "a" not in tc.l2 + assert "b" in tc.l2 and "b" not in tc.l1 + assert tc.demotions == 2 # "a" out, then "b" out + # Aggregate `hits` includes L2 hits (here l1_hits=0, l2_hits=1). + assert tc.hits == 1 + + +def test_tiered_l2_disabled_behaves_single_tier(): + # L2 capacity 0: demote is a no-op, nothing is ever promoted. + tc = _tiered(150, 0) + tc.put("a", "A", 100) + tc.put("b", "B", 100) # "a" evicted; L2 can't hold it -> truly dropped + assert "a" not in tc.l1 and "a" not in tc.l2 + assert tc.demotions == 0 + assert tc.get("a") is None + assert tc.misses == 1 + assert "b" in tc.l1 diff --git a/test/runtime/distributed/test_epd_encode.py b/test/runtime/distributed/test_epd_encode.py new file mode 100644 index 00000000000..a8bf4d49c8c --- /dev/null +++ b/test/runtime/distributed/test_epd_encode.py @@ -0,0 +1,549 @@ +# Copyright (c) 2026 LightSeek Foundation +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +"""EPD encode-side compute and scheduling: the encode worker (tower dedup, +ring-slot fault isolation), the executor row/column scatter geometry, the +batch scheduler packing, and the encode-loop config selectors.""" + +from __future__ import annotations + +import threading + +import pytest +import torch + +import tokenspeed.runtime.disaggregation.embedding.encode_loop as encode_loop +from tokenspeed.runtime.cache.embedding_cache import ( + EmbeddingCache, + TieredEmbeddingCache, +) +from tokenspeed.runtime.disaggregation.base.poll import TransferPoll +from tokenspeed.runtime.disaggregation.embedding.encode_executor import ( + DisaggEncodeExecutor, + assign_encoded_embeddings, +) +from tokenspeed.runtime.disaggregation.embedding.encode_loop import ( + _embedding_cache_bytes, + _make_embedding_cache, + _maybe_install_encoder_cudagraph, +) +from tokenspeed.runtime.disaggregation.embedding.encode_scheduler import ( + EncodeScheduler, + PendingEncodeItem, +) +from tokenspeed.runtime.disaggregation.embedding.encode_worker import ( + EncodeRequest, + EncodeWorker, +) +from tokenspeed.runtime.multimodal.inputs import ( + Modality, + MultimodalDataItem, +) + + +class _FakeExecutor: + def __init__(self): + self.registered = [] + self.executed_batches = [] # list of [item.hash, ...] the tower ran + self.sent_direct = [] # cache-hit hashes shipped without the tower + + def register(self, rid, host, port, room): + self.registered.append((rid, room)) + + def execute(self, request_items): + self.executed_batches.append([item.hash for _, item in request_items]) + for _, item in request_items: + item.encoded = torch.zeros(2, 4) # simulate tower output (shipped inside) + + def send_item(self, rid, item): + self.sent_direct.append(item.hash) + + def drain_deferred(self): + pass + + def has_deferred(self): + return False + + +def _item(h, tokens=2): + return MultimodalDataItem( + modality=Modality.IMAGE, hash=h, offsets=[(0, tokens - 1)] + ) + + +def _worker(max_tokens=10_000, max_items=99, cap_bytes=10**6): + ex = _FakeExecutor() + return ex, EncodeWorker( + ex, EncodeScheduler(max_tokens, max_items), EmbeddingCache(cap_bytes) + ) + + +def _req(rid, items, room=0): + return EncodeRequest(rid, "h", 1, room, items) + + +def test_miss_runs_tower_and_caches(): + ex, w = _worker() + w.submit(_req("r0", [_item(111)])) + assert w.has_pending() + assert w.step() == 1 + assert ex.executed_batches == [[111]] + assert 111 in w.cache + assert not w.has_pending() + assert w.step() == 0 + + +def test_cache_hit_skips_tower_but_still_ships(): + ex, w = _worker() + w.submit(_req("r0", [_item(111)], room=0)) + w.step() # tower runs, 111 cached + w.submit(_req("r1", [_item(111)], room=1)) # same image + # cache hit: shipped directly, not queued for the tower + assert ex.sent_direct == [111] + assert not w.has_pending() + assert ex.executed_batches == [[111]] # tower ran exactly once + + +# --- The encode worker drives the cache through get()/put() only, so it works +# with either the single-tier EmbeddingCache or the two-tier TieredEmbeddingCache. +# These exercise the real consumer path against the tiered cache (with cpu copies) +# and the production device<->host copy helpers the unit tests stub out. --- + + +# --- A per-item contract violation in the tower step (a bad grid/token-count -> +# ValueError, or an embedding larger than a ring slot -> RuntimeError) must fail +# only the rooms in that batch, NOT raise out of the encode loop into the +# engine's SIGUSR1 handler (which kills the whole worker and loses every other +# request's in-flight image, since the gateway round-robins images across +# workers). --- + + +class _FakeSender: + def __init__(self, room): + self.bootstrap_room = room + + +class _FakeFailManager: + def __init__(self): + self.request_status = {} + self.failed = [] # (room, reason) for each fail_room call + + def fail_room(self, room, reason): + self.request_status[room] = TransferPoll.Failed + self.failed.append((room, reason)) + + +class _RaisingExecutor: + """Tower step raises a per-item contract violation.""" + + def __init__(self, exc): + self._exc = exc + self.manager = _FakeFailManager() + self.senders = {} + self.executed = 0 + + def register(self, rid, host, port, room): + self.senders[rid] = _FakeSender(room) + + def execute(self, request_items): + self.executed += 1 + raise self._exc + + def send_item(self, rid, item): + pass + + def drain_deferred(self): + pass + + def has_deferred(self): + return False + + def fail_rooms(self, request_ids, exc): + rooms = set() + for rid in request_ids: + s = self.senders.get(rid) + if s is not None: + rooms.add(s.bootstrap_room) + for room in rooms: + self.manager.fail_room(room, str(exc)) + return len(rooms) + + +def _raising_worker(exc): + ex = _RaisingExecutor(exc) + return ex, EncodeWorker(ex, EncodeScheduler(10_000, 99), EmbeddingCache(10**6)) + + +def test_tower_valueerror_concludes_room_failed_not_crash(): + ex, w = _raising_worker(ValueError("rows != tokens")) + w.submit(_req("r0", [_item(111)], room=7)) + # the raise is swallowed: step returns 0, the worker survives + assert w.step() == 0 + assert ex.executed == 1 + # the room is concluded Failed (the receiver learns via the rank-synced abort) + assert ex.manager.failed == [(7, "rows != tokens")] + # the batch is drained from pending so the loop never re-runs the bad item + assert not w.has_pending() + + +# --- DisaggEncodeExecutor ring buffers: every transferred buffer must be a +# registered, non-overlapping memory region. Registering each fresh per-request +# ``item.encoded`` address fails on RDMA (the torch caching allocator packs +# freed-but-still-registered tensors together -> a later grown region straddles +# others -> "overlapped memory region" -> the one-sided write fails -> the prefill +# scheduler dies). The executor instead collapses every send through a fixed RING +# of pre-registered bounce buffers, each registered exactly once at a fixed size; +# ``item.encoded`` is COPIED into the next slot, so the registered set never grows, +# shrinks, or overlaps regardless of how the allocator reuses addresses. --- + + +class _RecordingEngine: + def __init__(self): + self.calls = [] # ("reg", ptr, nbytes) | ("dereg", ptr, None) + + def register(self, ptr, length): + self.calls.append(("reg", ptr, length)) + + def deregister(self, ptr): + self.calls.append(("dereg", ptr, None)) + + +class _FakeManager: + def __init__(self, engine): + self.engine = engine + + +def _encode_executor(ring_slots=3, ring_bytes=256): + # Tiny ring so the registration + staging path is exercised on CPU without a + # multi-GiB allocation (production defaults to 64 x 256 MiB). + eng = _RecordingEngine() + ex = DisaggEncodeExecutor( + _FakeManager(eng), + multimodal_model=None, + device="cpu", + ring_slots=ring_slots, + ring_bytes=ring_bytes, + ) + return eng, ex + + +def test_copy_into_rejects_oversized_embedding(): + # An embedding larger than a slot must fail loud rather than silently truncate. + eng, ex = _encode_executor(ring_slots=2, ring_bytes=8) + ex._ensure_rings() + too_big = torch.zeros(64, dtype=torch.float32) # 256 B >> 8 B slot + with pytest.raises(RuntimeError): + ex._copy_into(ex._main_ring, 0, too_big) + + +# --- Slot lease: a wrapped-around slot must not be overwritten while its last +# send can still read the pointer (in-flight, or parked for re-send). --- + + +class _LeaseManager: + """Fake manager exposing the status/parking surface the lease probes.""" + + def __init__(self, engine): + self.engine = engine + self.request_status = {} + self._pending = {} + self._pending_lock = threading.Lock() + # Deadline already in the past: a blocked lease raises immediately + # instead of stalling the test for the real 130s parking window. + self.bootstrap_time_out = -11.0 + + def room_status(self, room): + return self.request_status.get(room) + + def is_parked(self, room): + with self._pending_lock: + return room in self._pending + + +# --- Staging errors on the UNGUARDED paths must fail the room, not the worker. +# EncodeWorker.step only wraps execute(); the cache-hit send_item() and the +# deferred drain_deferred() reach _stage_and_send unguarded, so an oversized +# embedding there used to escape into the SIGUSR1 handler and kill the worker. --- + + +class _StageFailManager: + """Fake manager exposing the lease surface AND the public ``fail_room`` seam, + so a staging error inside _stage_and_send can be concluded per-room on CPU.""" + + def __init__(self, engine): + self.engine = engine + self.request_status = {} + self._pending = {} + self._pending_lock = threading.Lock() + self.bootstrap_time_out = -11.0 + self.failed = [] # (room, reason) + + def room_status(self, room): + return self.request_status.get(room) + + def is_parked(self, room): + with self._pending_lock: + return room in self._pending + + def fail_room(self, room, reason): + self.request_status[room] = TransferPoll.Failed + self.failed.append((room, reason)) + + +def _stagefail_executor(ring_slots=2, ring_bytes=8): + ex = DisaggEncodeExecutor( + _StageFailManager(_RecordingEngine()), + multimodal_model=None, + device="cpu", + ring_slots=ring_slots, + ring_bytes=ring_bytes, + ) + ex._ensure_rings() + return ex + + +def _oversized_item(ring_bytes): + # An embedding strictly larger than a ring slot -> _copy_into RuntimeError. + n = ring_bytes # float32 => 4 B/elt, so ring_bytes elts = 4x a slot + return MultimodalDataItem( + modality=Modality.IMAGE, + encoded=torch.zeros(n, 1, dtype=torch.float32), + ) + + +def test_oversized_item_does_not_poison_a_healthy_sibling(): + # A bad item fails only its own room; a well-sized sibling in the same + # _stage_and_send batch still ships. + ex = _stagefail_executor(ring_slots=2, ring_bytes=4096) + sent = [] + + class _Sender: + def __init__(self, room): + self.bootstrap_room = room + + def send(self, **kw): + sent.append(self.bootstrap_room) + + ex.senders["bad"] = _Sender(1) + ex.senders["ok"] = _Sender(2) + big = _oversized_item(ring_bytes=4096) + ok = MultimodalDataItem( + modality=Modality.IMAGE, + encoded=torch.arange(6, dtype=torch.float32).reshape(3, 2), + ) + ex._stage_and_send([("bad", big), ("ok", ok)]) # must NOT raise + assert ex.manager.request_status[1] == TransferPoll.Failed + assert sent == [2] # the healthy sibling still shipped + + +class _DeepstackModel: + """ndeep=3: encoded width is hidden*4, split into main[:hidden] + deep[hidden:].""" + + num_deepstack_embeddings = 3 + + def separate_deepstack_embeds(self, emb): + hidden = emb.shape[-1] // (1 + self.num_deepstack_embeddings) + return emb[:, :hidden], emb[:, hidden:] + + +class _PlainModel: + num_deepstack_embeddings = 0 + + +def _exec_item(*offset_pairs): + return MultimodalDataItem(modality=Modality.IMAGE, offsets=list(offset_pairs)) + + +def test_split_assigns_per_item_rows_and_deepstack(): + # item0 = 2 tokens, item1 = 3 tokens; hidden=4 -> width 16 + items = [_exec_item((0, 1)), _exec_item((0, 2))] + width = 16 + output = torch.arange(5 * width, dtype=torch.float32).reshape(5, width) + assign_encoded_embeddings(items, output, _DeepstackModel()) + + assert items[0].encoded.shape == (2, 4) + assert items[0].encoded_deepstack.shape == (2, 12) + assert items[1].encoded.shape == (3, 4) + assert items[1].encoded_deepstack.shape == (3, 12) + # value alignment: rows are contiguous in order, columns split at hidden=4 + assert torch.equal(items[0].encoded, output[0:2, :4]) + assert torch.equal(items[0].encoded_deepstack, output[0:2, 4:]) + assert torch.equal(items[1].encoded, output[2:5, :4]) + assert torch.equal(items[1].encoded_deepstack, output[2:5, 4:]) + assert items[0].encoded.is_contiguous() + assert items[1].encoded_deepstack.is_contiguous() + + +def test_token_count_mismatch_raises(): + item = _exec_item((0, 1)) # 2 tokens + output = torch.randn(5, 8) # 5 rows != 2 + with pytest.raises(ValueError): + assign_encoded_embeddings([item], output, _PlainModel()) + + +class _FeatureFnModel: + """Surfaces the three encode entry points _feature_fn dispatches between.""" + + def __init__(self): + # In a real model image_encoder defaults to get_image_feature and is + # swapped to the cudagraph wrapper by _maybe_install_encoder_cudagraph; + # use a distinct sentinel so the test proves IMAGE routes via the seam. + self.image_encoder = lambda items: "via-image_encoder-seam" + self.get_image_feature = lambda items: "eager-get_image_feature" + self.get_video_feature = lambda items: "video" + + +def test_feature_fn_image_routes_through_image_encoder_seam(): + from tokenspeed.runtime.disaggregation.embedding.encode_executor import ( + DisaggEncodeExecutor, + ) + + model = _FeatureFnModel() + exe = DisaggEncodeExecutor(object(), model, "cpu") + # IMAGE must dispatch through image_encoder (the cudagraph seam), NOT + # get_image_feature directly -- else the captured graph would be bypassed. + assert exe._feature_fn(Modality.IMAGE) is model.image_encoder + assert exe._feature_fn(Modality.IMAGE) is not model.get_image_feature + # VIDEO has no captured graph and stays on the eager entry point. + assert exe._feature_fn(Modality.VIDEO) is model.get_video_feature + + +def _sched_item(rid: str, idx: int, cost: int) -> PendingEncodeItem: + return PendingEncodeItem( + request_id=rid, + item_index=idx, + cost=cost, + ) + + +def test_scheduler_packs_until_token_budget(): + s = EncodeScheduler(max_tokens_per_batch=100, max_items_per_batch=99) + s.add(_sched_item("r0", 0, 40)) + s.add(_sched_item("r0", 1, 40)) + s.add(_sched_item("r1", 0, 40)) # 120 > 100 -> stays for next batch + b = s.next_batch() + assert [(i.request_id, i.item_index) for i in b] == [("r0", 0), ("r0", 1)] + assert s.pending_size() == 1 + b2 = s.next_batch() + assert [(i.request_id, i.item_index) for i in b2] == [("r1", 0)] + assert s.pending_size() == 0 + assert s.next_batch() == [] + + +def test_scheduler_respects_max_items(): + s = EncodeScheduler(max_tokens_per_batch=10_000, max_items_per_batch=2) + for i in range(5): + s.add(_sched_item("r0", i, 1)) + assert len(s.next_batch()) == 2 + assert len(s.next_batch()) == 2 + assert len(s.next_batch()) == 1 + + +def test_scheduler_oversized_single_item_returned_alone(): + s = EncodeScheduler(max_tokens_per_batch=50, max_items_per_batch=99) + s.add(_sched_item("r0", 0, 500)) # cost > budget: must still make progress + s.add(_sched_item("r0", 1, 10)) + b = s.next_batch() + assert [(i.request_id, i.item_index) for i in b] == [("r0", 0)] + b2 = s.next_batch() + assert [(i.request_id, i.item_index) for i in b2] == [("r0", 1)] + + +def test_scheduler_rejects_bad_budgets(): + with pytest.raises(ValueError): + EncodeScheduler(max_tokens_per_batch=0, max_items_per_batch=1) + with pytest.raises(ValueError): + EncodeScheduler(max_tokens_per_batch=1, max_items_per_batch=0) + + +_ENV = "TOKENSPEED_EPD_ENCODE_TEST_CACHE_MB" + + +# --------------------------------------------------------------------------- # +# _embedding_cache_bytes +# --------------------------------------------------------------------------- # +def test_bytes_override(monkeypatch): + monkeypatch.setenv(_ENV, "8") + assert _embedding_cache_bytes(_ENV, 4096) == 8 * 1024 * 1024 + + +def test_bytes_negative_raises_with_env_name(monkeypatch): + monkeypatch.setenv(_ENV, "-5") + with pytest.raises(ValueError) as exc: + _embedding_cache_bytes(_ENV, 4096) + assert _ENV in str(exc.value) + + +# --------------------------------------------------------------------------- # +# _make_embedding_cache (cache-type selection: the "L2 default off" property) +# --------------------------------------------------------------------------- # +def test_make_cache_l2_enabled_is_tiered_with_caps_and_device(): + cache = _make_embedding_cache(4 << 30, 8 << 30, "cuda:0") + assert type(cache) is TieredEmbeddingCache + assert cache.l1.capacity_bytes == (4 << 30) + assert cache.l2.capacity_bytes == (8 << 30) + assert cache._device == "cuda:0" + + +# --------------------------------------------------------------------------- # +# _maybe_install_encoder_cudagraph (gate parity with the aggregated ModelExecutor +# install; the actual capture is GPU-only and validated at e2e) +# --------------------------------------------------------------------------- # +_WRAPPER = object() # stands in for the EncoderCudaGraphWrapper + + +class _FakeModel: + """Minimal multimodal model surface the install gate touches.""" + + def __init__(self, *, multimodal=True): + self.is_multimodal_active = multimodal + self.mapping = object() + # The model leaves image_encoder == get_image_feature by default; the + # wrapper install overrides it. + self.image_encoder = self.get_image_feature + self.built_with = None + + def get_image_feature(self, items): + return "eager" + + def make_encoder_cudagraph_wrapper(self, mapping): + self.built_with = mapping + return _WRAPPER + + +class _FakeServerArgs: + def __init__(self, backend="trtllm_ragged"): + self.mm_attention_backend = backend + + +def _set_graph_flag(monkeypatch, value): + monkeypatch.setattr( + encode_loop.envs.TOKENSPEED_MM_ENABLE_ENCODER_CUDA_GRAPH, + "get", + lambda: value, + ) + + +def test_encoder_cudagraph_installed_when_enabled(monkeypatch): + _set_graph_flag(monkeypatch, True) + m = _FakeModel() + assert _maybe_install_encoder_cudagraph(m, _FakeServerArgs()) is True + assert m.image_encoder is _WRAPPER + assert m.built_with is m.mapping diff --git a/test/runtime/distributed/test_epd_transfer.py b/test/runtime/distributed/test_epd_transfer.py new file mode 100644 index 00000000000..ef709fb0f9e --- /dev/null +++ b/test/runtime/distributed/test_epd_transfer.py @@ -0,0 +1,592 @@ +# Copyright (c) 2026 LightSeek Foundation +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +"""EPD encode->prefill transfer: wire-codec round-trips, row-shard geometry, +and prefill receive-buffer sizing. Pure-logic silent-corruption guards (the +RDMA write itself is unchecked); no GPU, no live Mooncake hop.""" + +from __future__ import annotations + +import threading + +import pytest +import torch + +from tokenspeed.runtime.disaggregation.base.poll import TransferPoll +from tokenspeed.runtime.disaggregation.embedding.conn import ( + EmbeddingTransferError, +) +from tokenspeed.runtime.disaggregation.embedding.embedding_transfer import ( + REGISTER_ROOM_SENTINEL, + EmbeddingArgsRegisterInfo, + EmbeddingChunk, + EmbeddingTransferInfo, + MooncakeEmbeddingSender, + shard_payload, + validate_fanout_frames, +) +from tokenspeed.runtime.disaggregation.embedding.prefill_receiver import ( + DONE, + receive_encoded_embeddings, + shard_rows, + start_embedding_receive, +) +from tokenspeed.runtime.multimodal.inputs import ( + Modality, + MultimodalDataItem, +) + +# Each merged concern keeps its own per-test setup (the shard +# pointer-math tests need the legacy EPD_RECV_POOL_SLOTS=0 path, the +# receive tests need a small pool); route by test name. +_RECV_TESTS = { + "test_receive_sizes_buffers_per_item_no_deepstack", + "test_receive_allocates_deepstack_columns", + "test_receive_skips_already_encoded_item_on_recall", +} + + +def setup_function(function): + if function.__name__ in _RECV_TESTS: + _recv_setup(function) + else: + _shard_setup(function) + + +# A high device VA to catch any 32-bit truncation / wrong struct format. +HIGH_PTR = 0xFFFF_FFFF_FFFF_F000 +MID_PTR = 0x7FFF_FFFF_0000 + + +def test_register_info_round_trip(): + info = EmbeddingArgsRegisterInfo( + room=REGISTER_ROOM_SENTINEL, + endpoint="10.0.0.7", + dst_port=5123, + mooncake_session_id="10.0.0.7:41999", + dst_embedding_ptr=HIGH_PTR, + dst_deepstack_ptr=MID_PTR, + ) + frames = info.to_zmq() + assert len(frames) == 6 # layout lock + assert frames[0] == b"None" + assert EmbeddingArgsRegisterInfo.from_zmq(frames) == info + + +def test_transfer_info_round_trip_with_deepstack(): + info = EmbeddingTransferInfo( + room=42, + endpoint="10.0.0.7", + dst_port=5123, + mooncake_session_id="10.0.0.7:41999", + dst_embedding_ptr=HIGH_PTR, + dst_deepstack_ptr=MID_PTR, + n_tokens=1369, + hidden=3584, + dtype="torch.bfloat16", + has_deepstack=True, + required_dst_info_num=1, + ) + frames = info.to_zmq() + assert len(frames) == 13 # layout lock (v2: row_start + span appended) + rt = EmbeddingTransferInfo.from_zmq(frames) + assert rt == info + assert rt.dtype == "torch.bfloat16" + assert rt.has_deepstack is True + + +def test_transfer_info_round_trip_no_deepstack(): + info = EmbeddingTransferInfo( + room=0, + endpoint="::1", + dst_port=65535, + mooncake_session_id="x:0", + dst_embedding_ptr=0, + dst_deepstack_ptr=0, + n_tokens=0, + hidden=4096, + dtype="torch.float32", + has_deepstack=False, + required_dst_info_num=2, + ) + rt = EmbeddingTransferInfo.from_zmq(info.to_zmq()) + assert rt == info + assert rt.has_deepstack is False + + +def test_pointer_encoding_is_full_64bit(): + # Pack/parse the boundary directly through a frame to ensure no truncation. + info = EmbeddingArgsRegisterInfo( + room=REGISTER_ROOM_SENTINEL, + endpoint="h", + dst_port=2, + mooncake_session_id="s", + dst_embedding_ptr=HIGH_PTR, + dst_deepstack_ptr=0xDEAD_BEEF_CAFE_0000, + ) + rt = EmbeddingArgsRegisterInfo.from_zmq(info.to_zmq()) + assert rt.dst_embedding_ptr == HIGH_PTR + assert rt.dst_deepstack_ptr == 0xDEAD_BEEF_CAFE_0000 + + +def test_transfer_info_integer_room_distinct_from_sentinel(): + # The bootstrap thread routes on frame[0]: "None" => register, else int room. + reg = EmbeddingArgsRegisterInfo(REGISTER_ROOM_SENTINEL, "h", 1, "s", 1, 0).to_zmq() + xfer = EmbeddingTransferInfo( + 7, "h", 1, "s", 1, 0, 10, 8, "torch.bfloat16", False, 1 + ).to_zmq() + assert reg[0] == b"None" + assert xfer[0] == b"7" + assert xfer[0] != b"None" + + +# --------------------------------------------------------------------------- # +# MooncakeEmbeddingSender (driven by a fake manager; no Mooncake engine) +# --------------------------------------------------------------------------- # +class _SenderFakeMgr: + """Minimal stand-in for MooncakeEmbeddingManagerEncode: just the surface the + sender touches.""" + + def __init__(self): + self.request_status = {} + self.failure_records = {} + self.failure_lock = threading.Lock() + self.bootstrap_time_out = 300 + self.added = [] # (room, EmbeddingChunk) + + def update_status(self, room, status): + self.request_status[room] = status + + def check_status(self, room): + return self.request_status.get(room, TransferPoll.Bootstrapping) + + def record_failure(self, room, reason): + self.failure_records[room] = reason + + def add_transfer_request(self, room, chunk): + self.added.append((room, chunk)) + + +def test_sender_failure_exception_raises_and_clears(): + mgr = _SenderFakeMgr() + s = MooncakeEmbeddingSender(mgr, "h:9", bootstrap_room=3) + mgr.failure_records[3] = "boom on rank 1" + with pytest.raises(EmbeddingTransferError): + s.failure_exception() + assert 3 not in mgr.request_status # cleared + assert s.conclude_state == TransferPoll.Failed + + +# --- shard_rows: the single source of shard geometry for both sides --- + + +@pytest.mark.parametrize("span", [1, 2, 3, 7, 8, 128, 129]) +@pytest.mark.parametrize("size", [1, 2, 4, 8]) +def test_shard_rows_tiles_span_exactly(span, size): + cursor = 0 + for rank in range(size): + start, count = shard_rows(span, rank, size) + assert start == cursor # contiguous, in rank order + assert count >= 0 + cursor += count + assert cursor == span # disjoint cover of [0, span) + counts = [shard_rows(span, r, size)[1] for r in range(size)] + assert max(counts) - min(counts) <= 1 # balanced + + +# --- wire frame: round-trip + malformed input --- + + +def _info(**overrides) -> EmbeddingTransferInfo: + base = dict( + room=7, + endpoint="1.2.3.4", + dst_port=5555, + mooncake_session_id="s", + dst_embedding_ptr=0x1000, + dst_deepstack_ptr=0, + n_tokens=10, + hidden=64, + dtype="torch.bfloat16", + has_deepstack=False, + required_dst_info_num=4, + ) + base.update(overrides) + return EmbeddingTransferInfo(**base) + + +# --- encode-side payload math + fanout validation --- + + +def _chunk(n_tokens=10, hidden=64, deepstack_width=0) -> EmbeddingChunk: + itemsize = 2 # bf16 + return EmbeddingChunk( + room=7, + src_embedding_ptr=0x10_0000, + n_tokens=n_tokens, + hidden=hidden, + dtype="torch.bfloat16", + nbytes=n_tokens * hidden * itemsize, + src_deepstack_ptr=0x20_0000 if deepstack_width else 0, + deepstack_width=deepstack_width, + deepstack_nbytes=( + n_tokens * deepstack_width * itemsize if deepstack_width else 0 + ), + ) + + +def test_shard_payload_identity_is_whole_chunk(): + chunk = _chunk(n_tokens=10, deepstack_width=128) + src, nbytes, deep_src, deep_nbytes = shard_payload(chunk, _info(n_tokens=10)) + assert (src, nbytes) == (chunk.src_embedding_ptr, chunk.nbytes) + assert (deep_src, deep_nbytes) == (chunk.src_deepstack_ptr, chunk.deepstack_nbytes) + + +def test_shard_payload_offsets_rows(): + chunk = _chunk(n_tokens=10, hidden=64, deepstack_width=128) + row_bytes = chunk.nbytes // 10 + deep_row_bytes = chunk.deepstack_nbytes // 10 + src, nbytes, deep_src, deep_nbytes = shard_payload( + chunk, _info(n_tokens=3, row_start=5) + ) + assert src == chunk.src_embedding_ptr + 5 * row_bytes + assert nbytes == 3 * row_bytes + assert deep_src == chunk.src_deepstack_ptr + 5 * deep_row_bytes + assert deep_nbytes == 3 * deep_row_bytes + + +def test_validate_rejects_gap_overlap_range_dtype(): + chunk = _chunk(n_tokens=10) + gap = [ + _info(n_tokens=3, row_start=0, span=10), + _info(n_tokens=3, row_start=5, span=10), + ] + overlap = [ + _info(n_tokens=5, row_start=0, span=10), + _info(n_tokens=5, row_start=3, span=10), + ] + out_of_range = [_info(n_tokens=6, row_start=5, span=10)] + bad_dtype = [_info(n_tokens=10, dtype="torch.float32", span=10)] + mixed = [_info(n_tokens=10, span=10), _info(n_tokens=5, row_start=5, span=10)] + for infos in (gap, overlap, out_of_range, bad_dtype, mixed): + assert validate_fanout_frames(infos, chunk) is not None + + +def test_validate_rejects_span_mismatch_even_single_frame(): + # The G2 token-count tripwire: a cross-side row-count divergence (image + # processor / grid contract / cache-key bug) must fail LOUD even at + # fanout == 1, where a lone frame has no tiling partner to expose it. + chunk = _chunk(n_tokens=10) + # span carries the receiver's full image span -> direct check. + under = [_info(n_tokens=6, row_start=0, span=6)] + assert validate_fanout_frames(under, chunk) is not None + # matching span passes. + assert validate_fanout_frames([_info(n_tokens=10, span=10)], chunk) is None + + +def test_validate_rejects_deepstack_presence_mismatch(): + # An encode chunk that lost its deepstack half (e.g. a cache hit cached + # without it) must fail loud, not push Success while the receiver + # publishes a never-written deepstack buffer; and vice versa. + plain_chunk = _chunk(n_tokens=10) + deep_chunk = _chunk(n_tokens=10, deepstack_width=128) + wants_deep = [ + _info(n_tokens=10, span=10, has_deepstack=True, dst_deepstack_ptr=0x2000) + ] + no_deep = [_info(n_tokens=10, span=10)] + assert validate_fanout_frames(wants_deep, plain_chunk) is not None + assert validate_fanout_frames(no_deep, deep_chunk) is not None + assert validate_fanout_frames(wants_deep, deep_chunk) is None + + +# --- receiver job: PER-ITEM shard placement + reassembly schedule --- + + +class _ShardFakeEngine: + def register(self, *a, **k): + pass + + def deregister(self, *a, **k): + pass + + +class _ShardFakeMgr: + def __init__(self): + self.engine = _ShardFakeEngine() + + +class _ShardReceiver: + """Fake receiver: Bootstrapped until pre_alloc, Success after (mirrors + test_encode_receiver's _FakeReceiver).""" + + created: list["_ShardReceiver"] = [] + + def __init__(self, manager, addr, room): + self.addr = addr + self.room = room + self._pre_alloced = False + self.pre_alloc_kwargs = None + _ShardReceiver.created.append(self) + + def poll(self): + return TransferPoll.Success if self._pre_alloced else TransferPoll.Bootstrapped + + def pre_alloc(self, **kwargs): + self._pre_alloced = True + self.pre_alloc_kwargs = kwargs + + +def _shard_setup(_): + import os + + import tokenspeed.runtime.disaggregation.embedding.prefill_receiver as er + + _ShardReceiver.created.clear() + # Pin the LEGACY per-request buffer path: the pointer-math assertions below + # compare pre_alloc destinations against item.encoded, which on the pooled + # path is a post-DONE CLONE at a different address. Pool+shard interplay is + # covered separately by test_pool_shard_reassembles_into_published_clone. + os.environ["EPD_RECV_POOL_SLOTS"] = "0" + er._POOLS.clear() + + +def _shard_item(span, *, room=100, offsets=None): + # ONE item == one EPD image of `span` concatenated-subgrid tokens, carrying + # its per-item encode handshake. Multi-subgrid offsets still sum to `span` and + # are received/sharded as one image over one room (the encode worker + # concatenates the subgrids and row-splits the item's full embedding). + item = MultimodalDataItem( + modality=Modality.IMAGE, + offsets=offsets if offsets is not None else [(0, span - 1)], + ) + item.encode_handshake = { + "bootstrap_room": room, + "bootstrap_host": "h", + "bootstrap_port": 1, + } + return item + + +def _start(items, shard_rank, shard_size, factory=_ShardReceiver, num_deepstack=0): + return start_embedding_receive( + items, + manager=_ShardFakeMgr(), + hidden=8, + num_deepstack=num_deepstack, + dtype=torch.float32, + device="cpu", + receiver_factory=factory, + shard_rank=shard_rank, + shard_size=shard_size, + ) + + +def test_packed_to_full_scatters_shard_rows_to_absolute_offsets(): + # The publish scatter is the silent-corruption-critical mapping: packed shard + # rows -> their absolute offsets in the item's full embedding. rank 1 of 2 on + # a span-10 item: packed rows [0,5) -> full rows [5,10). Non-owned rows are + # left for reassemble (asserted only on the owned rows here). + import types + + job = _start([_shard_item(10)], shard_rank=1, shard_size=2) + it = types.SimpleNamespace(n_tokens=10, spans=[10], row_starts=[5], row_counts=[5]) + packed = torch.arange(5 * 8, dtype=torch.float32).reshape(5, 8) + full = job._packed_to_full(it, packed, 8) + assert full.shape == (10, 8) + assert torch.equal(full[5:10], packed[0:5]) + + +def _record_broadcasts(monkeypatch): + calls = [] + + def fake_broadcast(tensor, src=None, group=None): + calls.append((tensor, src)) + + monkeypatch.setattr(torch.distributed, "broadcast", fake_broadcast) + return calls + + +def test_reassemble_broadcasts_item_subranges(monkeypatch): + # The reassembly schedule follows the item's shard tiling: each rank + # broadcasts the contiguous row range it owns, together covering [0, span) + # exactly once (one item == one image under per-item rooms). + item = _shard_item(10) + job = _start([item], shard_rank=0, shard_size=2) + assert job.poll() == DONE + calls = _record_broadcasts(monkeypatch) + job.reassemble(nccl_group="g", group_ranks=(7, 9)) + + itemsize = item.encoded.element_size() + base = item.encoded.data_ptr() + rows = [ + ((t.data_ptr() - base) // (8 * itemsize), t.shape[0], src) for t, src in calls + ] + # span 10, 2-way: rank0 rows [0,5) from global 7, rank1 rows [5,10) from 9. + assert rows == [(0, 5, 7), (5, 5, 9)] + + +# --- encode worker: concluded-sender sweep (the O1 hygiene rider) --- + + +class _FakeReceiver: + """Drives the poll state machine without any transport: Bootstrapped until + pre_alloc, Success after. Records the pre_alloc kwargs for assertions.""" + + created: list["_FakeReceiver"] = [] + + def __init__(self, manager, addr, room): + self.manager = manager + self.addr = addr + self.room = room + self._pre_alloced = False + self.pre_alloc_kwargs = None + _FakeReceiver.created.append(self) + + def poll(self): + return TransferPoll.Success if self._pre_alloced else TransferPoll.Bootstrapped + + def pre_alloc(self, **kwargs): + self._pre_alloced = True + self.pre_alloc_kwargs = kwargs + + +class _RecvFakeEngine: + """No-op Mooncake engine: receive_encoded_embeddings register/deregisters each + receive buffer (a real RDMA NIC needs pre-registered targets); on CPU there is + nothing to register.""" + + def register(self, *args, **kwargs): + pass + + def deregister(self, *args, **kwargs): + pass + + +class _RecvFakeMgr: + def __init__(self): + self.engine = _RecvFakeEngine() + + +def _recv_item(n_tokens: int) -> MultimodalDataItem: + # _item_token_count sums (end - start + 1) over offsets; one subgrid here. + return MultimodalDataItem(modality=Modality.IMAGE, offsets=[(0, n_tokens - 1)]) + + +def _epd(item: MultimodalDataItem, *, room: int, host: str, port: int): + """Attach an EPD encode->prefill handshake onto an item (one room per item).""" + item.encode_handshake = { + "bootstrap_room": room, + "bootstrap_host": host, + "bootstrap_port": port, + } + return item + + +def _recv_setup(_): + import os + + import tokenspeed.runtime.disaggregation.embedding.prefill_receiver as er + + _FakeReceiver.created.clear() + # Small pool defaults so each test's fresh fake engine doesn't allocate + # the production 16x256MB region; pools are keyed by engine identity, so + # clear them (and the lazy-dereg queue) between tests. + os.environ["EPD_RECV_POOL_SLOTS"] = "4" + os.environ["EPD_RECV_POOL_SLOT_MB"] = "1" + er._POOLS.clear() + er._pending_dereg.clear() + + +def test_receive_sizes_buffers_per_item_no_deepstack(): + items = [ + _epd(_recv_item(6), room=11, host="h0", port=7001), + _epd(_recv_item(4), room=22, host="h1", port=7002), + ] + receive_encoded_embeddings( + items, + manager=_RecvFakeMgr(), + hidden=2048, + num_deepstack=0, + dtype=torch.bfloat16, + device="cpu", + receiver_factory=_FakeReceiver, + ) + + assert items[0].encoded.shape == (6, 2048) + assert items[1].encoded.shape == (4, 2048) + assert items[0].encoded.dtype == torch.bfloat16 + assert items[0].encoded_deepstack is None + assert items[1].encoded_deepstack is None + + # Each receiver pre_alloc'd a buffer matching its item's token count, with + # the dtype string the encode side asserts against (str(torch.bfloat16)). + r0 = next(r for r in _FakeReceiver.created if r.room == 11) + assert r0.pre_alloc_kwargs["n_tokens"] == 6 + assert r0.pre_alloc_kwargs["hidden"] == 2048 + assert r0.pre_alloc_kwargs["dtype"] == "torch.bfloat16" + assert r0.pre_alloc_kwargs["has_deepstack"] is False + assert r0.pre_alloc_kwargs["dst_deepstack_ptr"] == 0 + assert r0.addr == "h0:7001" + + +def test_receive_allocates_deepstack_columns(): + items = [_epd(_recv_item(5), room=99, host="h", port=8000)] + receive_encoded_embeddings( + items, + manager=_RecvFakeMgr(), + hidden=128, + num_deepstack=3, + dtype=torch.float32, + device="cpu", + receiver_factory=_FakeReceiver, + ) + + assert items[0].encoded.shape == (5, 128) + assert items[0].encoded_deepstack.shape == (5, 128 * 3) + r = _FakeReceiver.created[0] + assert r.pre_alloc_kwargs["has_deepstack"] is True + assert r.pre_alloc_kwargs["dst_deepstack_ptr"] != 0 + + +def test_receive_skips_already_encoded_item_on_recall(): + # Chunked prefill re-runs receive_encoded_embeddings on the SAME item object + # across forwards. After the first call sets item.encoded, a second call must + # skip the item: construct NO new receiver (re-bootstrapping a room already at + # Success would dead-wait phase-1 for Bootstrapped and time out) and leave the + # encoded buffer untouched. + item = _epd(_recv_item(5), room=77, host="h", port=9) + common = dict( + manager=_RecvFakeMgr(), + hidden=16, + num_deepstack=0, + dtype=torch.float32, + device="cpu", + receiver_factory=_FakeReceiver, + ) + + receive_encoded_embeddings([item], **common) + assert item.encoded is not None + assert len(_FakeReceiver.created) == 1 # first forward received it + first_encoded = item.encoded + + # Second forward (chunked prefill): item.encoded is already set -> skipped. + receive_encoded_embeddings([item], **common) + assert len(_FakeReceiver.created) == 1 # no new receiver constructed + assert item.encoded is first_encoded # buffer untouched diff --git a/test/runtime/distributed/test_pd_transfer_plan.py b/test/runtime/distributed/test_pd_transfer_plan.py index a027f4aeff5..6f4518b1cfa 100644 --- a/test/runtime/distributed/test_pd_transfer_plan.py +++ b/test/runtime/distributed/test_pd_transfer_plan.py @@ -1,5 +1,7 @@ -from tokenspeed.runtime.pd.mooncake.receiver import _build_buffer_layout_pair -from tokenspeed.runtime.pd.transfer_plan import ( +from tokenspeed.runtime.disaggregation.kv.mooncake.receiver import ( + _build_buffer_layout_pair, +) +from tokenspeed.runtime.disaggregation.kv.transfer_plan import ( BufferKind, ParallelLayout, PDTransferPlanner, diff --git a/test/runtime/test_kv_events.py b/test/runtime/test_kv_events.py index a28574ead86..d64af20b216 100644 --- a/test/runtime/test_kv_events.py +++ b/test/runtime/test_kv_events.py @@ -3,7 +3,7 @@ import msgspec import pytest -from tokenspeed.runtime.pd.kv_events import ( +from tokenspeed.runtime.disaggregation.kv.kv_events import ( BlockRemoved, BlockStored, EventPublisherFactory, diff --git a/tokenspeed-scheduler/csrc/fsm/forward_events.cpp b/tokenspeed-scheduler/csrc/fsm/forward_events.cpp index aab25e90b6c..bdfde8f372a 100644 --- a/tokenspeed-scheduler/csrc/fsm/forward_events.cpp +++ b/tokenspeed-scheduler/csrc/fsm/forward_events.cpp @@ -359,6 +359,14 @@ std::variant FinishEvent::apply(ForwardStateT&& state) { auto local_mamba_allocator = std::move(state).TakeLocalMambaAllocator(); auto local_allocator = std::move(state).TakeLocalKVAllocator(); + // Overlap / disagg handoff can grow the token container past the pages this + // request actually Acquired (the terminal token's Acquire is skipped). Clamp + // to owned pages, as scheduleRetract does. + const std::int32_t owned_pages = local_allocator->PageCount(); + if (alloc_count > owned_pages) { + full_paged_tokens.resize(static_cast(owned_pages) + prefix_pages.size()); + alloc_count = owned_pages; + } if (alloc_count > 0) { OwnedPages alloc_pages = local_allocator->TakeFirst(alloc_count); From a47f5c0a68974a798634b1fdf9b8ca87d564188f Mon Sep 17 00:00:00 2001 From: chenht2022 Date: Sun, 28 Jun 2026 17:27:43 +0000 Subject: [PATCH 2/7] fix Signed-off-by: chenht2022 --- .../disaggregation/embedding/__init__.py | 3 ++ .../runtime/disaggregation/embedding/conn.py | 13 ++++---- .../embedding/embedding_transfer.py | 3 +- .../embedding/encode_executor.py | 3 +- .../disaggregation/embedding/encode_loop.py | 32 ++++++++++++------- .../embedding/prefill_receiver.py | 18 ++++------- .../tokenspeed/runtime/utils/server_args.py | 6 ++++ 7 files changed, 48 insertions(+), 30 deletions(-) diff --git a/python/tokenspeed/runtime/disaggregation/embedding/__init__.py b/python/tokenspeed/runtime/disaggregation/embedding/__init__.py index 48143b63971..063fe633b37 100644 --- a/python/tokenspeed/runtime/disaggregation/embedding/__init__.py +++ b/python/tokenspeed/runtime/disaggregation/embedding/__init__.py @@ -22,6 +22,9 @@ The encode role runs the vision tower only and ships image embeddings over the Mooncake RDMA engine; the prefill role receives them and skips the tower. The +embedding transport supports TP fanout only inside one server; encode DP scale is +provided by running multiple independent encode servers rather than by attention +DP in one process group. The role-neutral transport substrate (the :class:`...base.poll.TransferPoll` status FSM, the manager base, the bootstrap server) is shared from :mod:`...disaggregation.base`; :mod:`conn` layers the embedding buffer args onto it and :mod:`embedding_transfer` diff --git a/python/tokenspeed/runtime/disaggregation/embedding/conn.py b/python/tokenspeed/runtime/disaggregation/embedding/conn.py index 3dd02084095..810f7906721 100644 --- a/python/tokenspeed/runtime/disaggregation/embedding/conn.py +++ b/python/tokenspeed/runtime/disaggregation/embedding/conn.py @@ -49,13 +49,14 @@ class EmbeddingTransferError(Exception): class EmbeddingManagerArgs: """Connection config for the embedding Mooncake endpoint. - The encode role owns no KV pool / MLA / metrics, so this carries only the - transport fields the manager base reads. + Embedding transfer has a single DP group today. ``tp_size`` is the number + of encode/prefill endpoint ranks that participate in that group; the shared + bootstrap layer still receives it as ``world_size`` with ``dp_size=1``. """ bootstrap_port: int - world_size: int - dp_size: int + tp_size: int + bootstrap_host: str | None = None class EmbeddingManagerBase(DisaggManagerBase): @@ -74,8 +75,8 @@ def __init__( self.embedding_args = embedding_args self.disaggregation_mode = disaggregation_mode self.bootstrap_port = args.bootstrap_port - self.world_size = args.world_size - self.dp_size = args.dp_size + self.world_size = args.tp_size + self.dp_size = 1 # Vendor binding stays out of the neutral base. embedding_args must be # set above before super().__init__, which calls register_buffer_to_engine. engine = MooncakeTransferEngine( diff --git a/python/tokenspeed/runtime/disaggregation/embedding/embedding_transfer.py b/python/tokenspeed/runtime/disaggregation/embedding/embedding_transfer.py index fdb9a40310f..5aaeba0d92f 100644 --- a/python/tokenspeed/runtime/disaggregation/embedding/embedding_transfer.py +++ b/python/tokenspeed/runtime/disaggregation/embedding/embedding_transfer.py @@ -493,6 +493,7 @@ def loop(): def _register_to_bootstrap(self): ip = get_local_ip_by_remote() + bootstrap_host = self.args.bootstrap_host or ip payload = { "role": "Prefill", # bootstrap-server role string for "discoverable data source" "world_size": self.world_size, @@ -501,7 +502,7 @@ def _register_to_bootstrap(self): "rank_port": self.rank_port, "engine_rank": self.embedding_args.engine_rank, } - url = f"http://{ip}:{self.bootstrap_port}/route" + url = f"http://{bootstrap_host}:{self.bootstrap_port}/route" # The bootstrap HTTP server starts concurrently with this call, so the # first PUTs can race it and hit connection-refused. A dropped # registration leaves /route's parallel-info null and the encode silently diff --git a/python/tokenspeed/runtime/disaggregation/embedding/encode_executor.py b/python/tokenspeed/runtime/disaggregation/embedding/encode_executor.py index fed2597e080..16d1231735d 100644 --- a/python/tokenspeed/runtime/disaggregation/embedding/encode_executor.py +++ b/python/tokenspeed/runtime/disaggregation/embedding/encode_executor.py @@ -190,7 +190,8 @@ def _copy_into(self, ring, slot: int, src) -> Tuple[int, int]: if nbytes > self._ring_bytes: raise RuntimeError( f"EPD encode embedding {nbytes} B exceeds ring slot " - f"{self._ring_bytes} B; raise EncodeExecutor._ring_bytes" + f"{self._ring_bytes} B; raise TOKENSPEED_EPD_ENCODE_RING_SLOT_MB " + "or the ring_bytes constructor argument" ) buf = ring[slot] buf[:nbytes].view(src.dtype).copy_(src.reshape(-1)) diff --git a/python/tokenspeed/runtime/disaggregation/embedding/encode_loop.py b/python/tokenspeed/runtime/disaggregation/embedding/encode_loop.py index 938b0185d36..2fa59f88a6a 100644 --- a/python/tokenspeed/runtime/disaggregation/embedding/encode_loop.py +++ b/python/tokenspeed/runtime/disaggregation/embedding/encode_loop.py @@ -38,9 +38,9 @@ TP: the vision tower is TP-sharded, so all encode ranks run each batch in lockstep -- rank 0 owns the gateway ZMQ and broadcasts every batch to the TP group. The embedding transport is a 1->N broadcast: prefill_tp must be a multiple of -encode_tp (encode_tp=1 scales horizontally via multiple independent encode -processes = DP); dp_size == 1 on both embedding endpoints (this is process-DP, -not dp_attention). +encode_tp. Data-parallel encode workers inside one server are not supported; +horizontal scale comes from multiple independent encode servers selected by the +gateway. """ import os @@ -108,16 +108,26 @@ def _make_embedding_cache(l1_bytes: int, l2_bytes: int, device: str): def _build_manager_args(server_args, mapping): - """EmbeddingManagerArgs for the encode Mooncake endpoint. Forced to dp_size=1 / - enable_dp_attention=False (the base manager hard-rejects otherwise; embedding - transport allows prefill_tp = any multiple of encode_tp, dp_size==1 = process-DP). + """EmbeddingManagerArgs for the encode Mooncake endpoint. + + EPD embedding transfer currently supports TP only. Horizontal scale is via + separate encode servers selected by the gateway; attention DP inside one + encode server is rejected so it cannot be accidentally advertised as TP. """ from tokenspeed.runtime.disaggregation.embedding.conn import EmbeddingManagerArgs + if mapping.attn.dp_size != 1: + raise ValueError( + "disaggregation_mode=encode currently supports encode " + f"data_parallel_size == 1, got {mapping.attn.dp_size}" + ) + bootstrap_host = None + if server_args.dist_init_addr: + bootstrap_host = server_args.dist_init_addr.split(":", 1)[0] return EmbeddingManagerArgs( bootstrap_port=server_args.disaggregation_bootstrap_port, - world_size=server_args.world_size or mapping.world_size, - dp_size=1, + tp_size=mapping.attn.tp_size, + bootstrap_host=bootstrap_host, ) @@ -214,9 +224,9 @@ def _build_encode_worker(server_args, port_args, gpu_id, global_rank): # The encode worker is the Mooncake data source: it hosts its own bootstrap # server (prefill workers discover it via the handshake the gateway injects). # At TP>1 only rank 0 binds the port; every rank still registers its own - # rank_ip/rank_port to it (same-host PUT), so each prefill rank can look up - # the encode rank it pairs with (contiguous blocks of prefill ranks share one - # encode rank; encode_tp=1 -> all prefill ranks pair encode rank 0). + # rank_ip/rank_port to the rank-0 bootstrap host, so each prefill rank can + # look up the encode rank it pairs with (contiguous blocks of prefill ranks + # share one encode rank; encode_tp=1 -> all prefill ranks pair encode rank 0). if attn_tp_rank == 0: EmbeddingBootstrapServer(server_args.disaggregation_bootstrap_port) manager = MooncakeEmbeddingManagerEncode(manager_args, embedding_args) diff --git a/python/tokenspeed/runtime/disaggregation/embedding/prefill_receiver.py b/python/tokenspeed/runtime/disaggregation/embedding/prefill_receiver.py index 28af4039d4c..67f52eef5a7 100644 --- a/python/tokenspeed/runtime/disaggregation/embedding/prefill_receiver.py +++ b/python/tokenspeed/runtime/disaggregation/embedding/prefill_receiver.py @@ -805,16 +805,14 @@ def receive_encoded_embeddings( time.sleep(0.0005) -def build_prefill_embedding_manager( - server_args, world_size, global_rank, is_multimodal_active -): +def build_prefill_embedding_manager(server_args, global_rank, is_multimodal_active): """Stand up the EPD encode->prefill embedding sink, if applicable. Only a multimodal *prefill* node receives embeddings from encode workers. Built - dp_size=1 (the embedding transport allows prefill_tp = any multiple of - encode_tp) with no fixed base buffer (receive buffers are allocated per image at - receive time). Construction spawns a daemon status thread, so build it exactly - once per rank. Returns None for decode/encode/text-only nodes. + as one TP group (the embedding transport allows prefill_tp = any multiple of + encode_tp) with no fixed base buffer (receive buffers are allocated per image + at receive time). Construction spawns a daemon status thread, so build it + exactly once per rank. Returns None for decode/encode/text-only nodes. """ if server_args.disaggregation_mode != "prefill" or not is_multimodal_active: return None @@ -827,8 +825,7 @@ def build_prefill_embedding_manager( emb_mgr_args = EmbeddingManagerArgs( bootstrap_port=server_args.disaggregation_bootstrap_port, - world_size=world_size, - dp_size=1, + tp_size=server_args.mapping.attn.tp_size, ) emb_args = EmbeddingArgs( engine_rank=global_rank, @@ -1033,9 +1030,8 @@ def make_epd_prefill_admission( Returns None unless this is a multimodal *prefill* node (the only node that receives encode->prefill embeddings).""" - world_size = server_args.world_size or mapping.world_size manager = build_prefill_embedding_manager( - server_args, world_size, global_rank, model_config.is_multimodal_active + server_args, global_rank, model_config.is_multimodal_active ) if manager is None: return None diff --git a/python/tokenspeed/runtime/utils/server_args.py b/python/tokenspeed/runtime/utils/server_args.py index 64a28aece62..c8d7a752417 100755 --- a/python/tokenspeed/runtime/utils/server_args.py +++ b/python/tokenspeed/runtime/utils/server_args.py @@ -589,6 +589,12 @@ def resolve_disaggregation(self): elif self.disaggregation_mode == "encode": # Encode server: vision tower only, no LM / KV pool / prefix cache. # enforce_eager left as-is (the vision tower keeps its own CUDA graph). + if self.mapping.has_attn_dp: + raise ValueError( + "disaggregation_mode=encode currently supports " + "data_parallel_size == 1 inside one encode server; run " + "multiple independent encode servers for horizontal scale." + ) self.enable_prefix_caching = False # Prefill graph disable logic is handled by AttnInitializer.modify_args From 30506ed3768974ad0a435fcbe56b6fc1052136db Mon Sep 17 00:00:00 2001 From: chenht2022 Date: Mon, 29 Jun 2026 08:00:57 +0000 Subject: [PATCH 3/7] cleanup Signed-off-by: chenht2022 --- .../runtime/cache/embedding_cache.py | 4 +- .../runtime/disaggregation/embedding/conn.py | 4 +- .../embedding/embedding_transfer.py | 4 +- .../embedding/encode_executor.py | 21 ++++------ .../disaggregation/embedding/encode_loop.py | 38 ++++++------------- .../embedding/encode_scheduler.py | 4 +- .../disaggregation/embedding/encode_worker.py | 4 +- .../embedding/prefill_receiver.py | 28 ++++++-------- .../disaggregation/kv/decode_executor.py | 2 +- .../runtime/disaggregation/kv/factory.py | 3 +- .../runtime/disaggregation/kv/utils.py | 4 +- .../runtime/disaggregation/utils.py | 4 +- .../tokenspeed/runtime/engine/event_loop.py | 29 ++++++++------ .../engine/generation_output_processor.py | 2 +- python/tokenspeed/runtime/utils/env.py | 6 +++ test/runtime/distributed/test_epd_encode.py | 15 ++++---- test/runtime/distributed/test_epd_transfer.py | 25 ++++++------ 17 files changed, 89 insertions(+), 108 deletions(-) diff --git a/python/tokenspeed/runtime/cache/embedding_cache.py b/python/tokenspeed/runtime/cache/embedding_cache.py index 61c7e370b85..fe9724b55d6 100644 --- a/python/tokenspeed/runtime/cache/embedding_cache.py +++ b/python/tokenspeed/runtime/cache/embedding_cache.py @@ -18,8 +18,6 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -from __future__ import annotations - """Vision-embedding cache for the EPD encode stage. The encode server runs the vision tower only; a cache lets duplicate images @@ -33,6 +31,8 @@ sizes and the device<->host copies are injectable. """ +from __future__ import annotations + import collections from typing import Callable, Hashable, Optional, Tuple diff --git a/python/tokenspeed/runtime/disaggregation/embedding/conn.py b/python/tokenspeed/runtime/disaggregation/embedding/conn.py index 810f7906721..42f4661acd3 100644 --- a/python/tokenspeed/runtime/disaggregation/embedding/conn.py +++ b/python/tokenspeed/runtime/disaggregation/embedding/conn.py @@ -18,8 +18,6 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -from __future__ import annotations - """Embedding-role transport substrate for EPD (encode -> prefill). The mechanical plumbing (the Mooncake engine + ZMQ control socket + room-keyed @@ -30,6 +28,8 @@ any KV/MLA/metrics state. """ +from __future__ import annotations + import dataclasses from tokenspeed.runtime.disaggregation.base.bootstrap import DisaggBootstrapServer diff --git a/python/tokenspeed/runtime/disaggregation/embedding/embedding_transfer.py b/python/tokenspeed/runtime/disaggregation/embedding/embedding_transfer.py index 5aaeba0d92f..9af84d6e92c 100644 --- a/python/tokenspeed/runtime/disaggregation/embedding/embedding_transfer.py +++ b/python/tokenspeed/runtime/disaggregation/embedding/embedding_transfer.py @@ -18,8 +18,6 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -from __future__ import annotations - """Mooncake transport for EPD encode->prefill image-embedding transfer. The encode (vision-tower-only) server is the data source: it calls @@ -33,6 +31,8 @@ protocol contract stays importable and unit-testable on CPU. """ +from __future__ import annotations + import concurrent.futures import dataclasses import os diff --git a/python/tokenspeed/runtime/disaggregation/embedding/encode_executor.py b/python/tokenspeed/runtime/disaggregation/embedding/encode_executor.py index 16d1231735d..e961b6eb781 100644 --- a/python/tokenspeed/runtime/disaggregation/embedding/encode_executor.py +++ b/python/tokenspeed/runtime/disaggregation/embedding/encode_executor.py @@ -18,25 +18,26 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -from __future__ import annotations - """EPD encode-worker execution: run the vision tower, scatter its output back onto each item, and hand the contiguous embeddings to the Mooncake sender. """ +from __future__ import annotations + import logging from typing import List, Tuple import torch -logger = logging.getLogger(__name__) - from tokenspeed.runtime.disaggregation.base.poll import TransferPoll from tokenspeed.runtime.disaggregation.embedding.embedding_transfer import ( MooncakeEmbeddingSender, ) from tokenspeed.runtime.multimodal.embedder import _item_token_count from tokenspeed.runtime.multimodal.inputs import Modality, MultimodalDataItem +from tokenspeed.runtime.utils.env import envs + +logger = logging.getLogger(__name__) def assign_encoded_embeddings( @@ -117,16 +118,12 @@ def __init__( # env-tunable; total reservation is slots * slot_bytes PER ring (main, plus # deepstack if present), so depth and per-slot bytes must be sized to the # model and peak concurrency. - import os as _os - self._ring_slots = int( - _os.environ.get("TOKENSPEED_EPD_ENCODE_RING_SLOTS", ring_slots) + envs.TOKENSPEED_EPD_ENCODE_RING_SLOTS.get_set_value_or(ring_slots) ) - _slot_mb_env = _os.environ.get("TOKENSPEED_EPD_ENCODE_RING_SLOT_MB") + slot_mb = envs.TOKENSPEED_EPD_ENCODE_RING_SLOT_MB.get() # Env override is in whole MiB; unset -> keep the exact ``ring_bytes`` arg. - self._ring_bytes = ( - int(_slot_mb_env) * 1024 * 1024 if _slot_mb_env else ring_bytes - ) + self._ring_bytes = slot_mb * 1024 * 1024 if slot_mb else ring_bytes self._main_ring = None # lazily allocated on first send (device live by then) self._deep_ring = None self._ring_idx = 0 @@ -206,8 +203,6 @@ def _lease_slot(self) -> "int | None": A slot is reusable once the room it last staged is TERMINAL (Success, Failed, or None=already reaped) AND no parked chunk still holds its pointer -- the overwrite-safety invariant.""" - from tokenspeed.runtime.disaggregation.base.poll import TransferPoll - mgr = self.manager n = self._ring_slots for _ in range(n): diff --git a/python/tokenspeed/runtime/disaggregation/embedding/encode_loop.py b/python/tokenspeed/runtime/disaggregation/embedding/encode_loop.py index 2fa59f88a6a..c28a873bb0c 100644 --- a/python/tokenspeed/runtime/disaggregation/embedding/encode_loop.py +++ b/python/tokenspeed/runtime/disaggregation/embedding/encode_loop.py @@ -18,8 +18,6 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -from __future__ import annotations - """EPD encode-worker loop: a lightweight, LM-free scheduler subprocess. The encode role runs the vision tower and ships image embeddings to prefill @@ -43,7 +41,8 @@ gateway. """ -import os +from __future__ import annotations + import time import zmq @@ -59,33 +58,22 @@ logger = get_colorful_logger(__name__) + # Vision-embedding cache capacity. L1 lives in GPU VRAM; the optional L2 lives in # host DRAM and catches L1 evictions so duplicate images skip the tower even past # the VRAM working set. Both are whole-MiB env overrides. L2 defaults to 0 # (disabled): the host tier is opt-in. NOTE both knobs are PER ENCODE PROCESS (per # TP rank): at encode TP>1, every co-located rank allocates its own L1+L2, so # budget host DRAM as tp_size * EMBED_CACHE_DRAM_MB. -_DEFAULT_EMBEDDING_CACHE_L1_MB = 4096 # 4 GiB -_DEFAULT_EMBEDDING_CACHE_L2_MB = 0 # host-DRAM tier off unless opted in +def _embedding_cache_bytes(env_field) -> int: + """Whole-MiB env field -> bytes. - -def _embedding_cache_bytes(env_name: str, default_mb: int) -> int: - """Whole-MiB env override -> bytes (unset/empty keeps ``default_mb``). - - Rejects negative / non-integer values with an env-named error so a mis-set - knob fails fast and legibly. + EnvField handles parsing and defaults; negative capacities are rejected here + with an env-named error. """ - raw = os.environ.get(env_name) - if not raw: - return default_mb * 1024 * 1024 - try: - mb = int(raw) - except ValueError: - raise ValueError( - f"{env_name} must be a whole number of MiB, got {raw!r}" - ) from None + mb = env_field.get() if mb < 0: - raise ValueError(f"{env_name} must be >= 0 MiB, got {mb}") + raise ValueError(f"{env_field.name} must be >= 0 MiB, got {mb}") return mb * 1024 * 1024 @@ -232,12 +220,8 @@ def _build_encode_worker(server_args, port_args, gpu_id, global_rank): manager = MooncakeEmbeddingManagerEncode(manager_args, embedding_args) executor = DisaggEncodeExecutor(manager, model, device=device) - l1_bytes = _embedding_cache_bytes( - "TOKENSPEED_EPD_ENCODE_EMBED_CACHE_MB", _DEFAULT_EMBEDDING_CACHE_L1_MB - ) - l2_bytes = _embedding_cache_bytes( - "TOKENSPEED_EPD_ENCODE_EMBED_CACHE_DRAM_MB", _DEFAULT_EMBEDDING_CACHE_L2_MB - ) + l1_bytes = _embedding_cache_bytes(envs.TOKENSPEED_EPD_ENCODE_EMBED_CACHE_MB) + l2_bytes = _embedding_cache_bytes(envs.TOKENSPEED_EPD_ENCODE_EMBED_CACHE_DRAM_MB) cache = _make_embedding_cache(l1_bytes, l2_bytes, device) scheduler = EncodeScheduler( max_tokens_per_batch=server_args.chunked_prefill_size or 8192, diff --git a/python/tokenspeed/runtime/disaggregation/embedding/encode_scheduler.py b/python/tokenspeed/runtime/disaggregation/embedding/encode_scheduler.py index 45f834b47c3..ae66e8bcec6 100644 --- a/python/tokenspeed/runtime/disaggregation/embedding/encode_scheduler.py +++ b/python/tokenspeed/runtime/disaggregation/embedding/encode_scheduler.py @@ -18,8 +18,6 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -from __future__ import annotations - """Encode-stage batching for EPD disaggregation. The encode server runs the vision tower only, orchestrated in Python rather @@ -33,6 +31,8 @@ scheduler. """ +from __future__ import annotations + import dataclasses from typing import Dict, List, Tuple diff --git a/python/tokenspeed/runtime/disaggregation/embedding/encode_worker.py b/python/tokenspeed/runtime/disaggregation/embedding/encode_worker.py index 7b90cd2bf0a..cb52b9b6a06 100644 --- a/python/tokenspeed/runtime/disaggregation/embedding/encode_worker.py +++ b/python/tokenspeed/runtime/disaggregation/embedding/encode_worker.py @@ -18,8 +18,6 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -from __future__ import annotations - """Encode-worker control loop for EPD (Python orchestration). This is the body the engine's encode event loop drives: it sits between request @@ -34,6 +32,8 @@ orchestrates them, so it is unit-testable with fakes. """ +from __future__ import annotations + import dataclasses from typing import List, Union diff --git a/python/tokenspeed/runtime/disaggregation/embedding/prefill_receiver.py b/python/tokenspeed/runtime/disaggregation/embedding/prefill_receiver.py index 67f52eef5a7..64be796d04f 100644 --- a/python/tokenspeed/runtime/disaggregation/embedding/prefill_receiver.py +++ b/python/tokenspeed/runtime/disaggregation/embedding/prefill_receiver.py @@ -18,8 +18,6 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -from __future__ import annotations - """EPD prefill-side receive glue: fill each multimodal item's ``encoded`` tensor from the Mooncake transfer instead of running the vision tower. @@ -45,8 +43,9 @@ synchronous callers and the CPU tests. """ +from __future__ import annotations + import logging -import os import time from collections import deque from typing import Any, Callable, List, Mapping, Optional, Sequence, Tuple @@ -62,6 +61,7 @@ ) from tokenspeed.runtime.multimodal.embedder import _item_token_count from tokenspeed.runtime.multimodal.inputs import MultimodalDataItem +from tokenspeed.runtime.utils.env import envs # (manager, bootstrap_addr, bootstrap_room) -> receiver. Defaults to the real # MooncakeEmbeddingReceiver; overridden in tests with a fake. @@ -79,7 +79,8 @@ # So deregistration is DEFERRED: entries hold the tensor ref (the allocator # cannot reuse a still-registered address -- the no-double-register invariant) # and are swept after a grace period, on the scheduler loop (no thread, no lock). -_DEREG_DELAY_S = float(os.environ.get("EPD_RECV_DEREG_DELAY_S", "0.5")) +_DEREG_DELAY_S = 0.5 +_RECV_POOL_QUARANTINE_S = 10.0 # (due_monotonic, engine, [(tensor, ptr), ...]) in due order (delay is constant). _pending_dereg: deque = deque() @@ -114,7 +115,7 @@ class _RecvBufferPool: Failure path: a FAILED job may still have an in-flight remote write targeting its slot, which under a single lifetime MR would land SILENTLY in the next tenant's data, so failed slots sit in quarantine until the transfer layer's - timeouts have expired (EPD_RECV_POOL_QUARANTINE_S). + timeouts have expired. Single-threaded by design: all callers run on the scheduler loop (no locks). """ @@ -154,8 +155,8 @@ def _get_pool(engine: Any, device: Any) -> Optional[_RecvBufferPool]: key = (id(engine), str(device)) pool = _POOLS.get(key) if pool is None: - n_slots = int(os.environ.get("EPD_RECV_POOL_SLOTS", "16")) - slot_mb = int(os.environ.get("EPD_RECV_POOL_SLOT_MB", "256")) + n_slots = envs.TOKENSPEED_EPD_RECV_POOL_SLOTS.get() + slot_mb = envs.TOKENSPEED_EPD_RECV_POOL_SLOT_MB.get() if n_slots <= 0 or slot_mb <= 0: pool = False else: @@ -275,7 +276,7 @@ class EmbeddingReceiveJob: lifetime-registered :class:`_RecvBufferPool`; on DONE the landed rows are cloned onto ``item.encoded`` and the slot returns immediately (no MR churn, see the pool docstring). Deepstack models, oversized items, pool - exhaustion, or ``EPD_RECV_POOL_SLOTS=0`` fall back to a per-request + exhaustion, or ``TOKENSPEED_EPD_RECV_POOL_SLOTS=0`` fall back to a per-request buffer registered on start and lazily deregistered after publish. The GPU cost per request is roughly ``n_tokens * hidden * dtype.itemsize`` (plus ``* (1 + num_deepstack)`` with deepstack); the caller should cap the @@ -645,8 +646,6 @@ def reassemble(self, nccl_group: Any, group_ranks: Sequence[int]) -> None: """ if self._shard_size <= 1 or self._status is not DONE: return - import torch.distributed as dist - for it in self._items: main = it.item.encoded deep = it.item.encoded_deepstack @@ -691,10 +690,9 @@ def _fail(self) -> None: ``item.encoded`` is left unset -- the request is being failed, not served. """ - quarantine_s = float(os.environ.get("EPD_RECV_POOL_QUARANTINE_S", "10")) for it in self._items: if it.pool is not None: - it.pool.quarantine(it.pool_slot, quarantine_s) + it.pool.quarantine(it.pool_slot, _RECV_POOL_QUARANTINE_S) else: pairs = [(it.recv_main, it.recv_main.data_ptr())] if it.recv_deepstack is not None: @@ -866,8 +864,6 @@ def __init__( attn_tp_group, pg_manager, ): - from tokenspeed.runtime.utils.env import envs as _envs - self._manager = manager self._device = device self._hidden = hidden @@ -888,7 +884,7 @@ def __init__( # embedding transfer is the direct analog of the decode waiting on the # prefill->decode KV transfer, so one operator knob covers both. self._embed_timeout: float = float( - _envs.TOKENSPEED_DISAGGREGATION_WAITING_TIMEOUT.get() + envs.TOKENSPEED_DISAGGREGATION_WAITING_TIMEOUT.get() ) # EPD embedding row-sharding: each attn-TP rank receives only 1/N of every @@ -902,7 +898,7 @@ def __init__( self._group_ranks = tuple(attn_tp_group) shard_flag = False if attn_tp_size > 1: - shard_flag = bool(_envs.TOKENSPEED_EPD_EMBEDDING_SHARD.get()) + shard_flag = bool(envs.TOKENSPEED_EPD_EMBEDDING_SHARD.get()) # The flag is a per-process env read but gates a GROUP collective: # torn across ranks (e.g. set on one node of a multi-node prefill), # flag-on ranks would join the warmup broadcast below while flag-off diff --git a/python/tokenspeed/runtime/disaggregation/kv/decode_executor.py b/python/tokenspeed/runtime/disaggregation/kv/decode_executor.py index 1f543e02427..95afb65ec7e 100644 --- a/python/tokenspeed/runtime/disaggregation/kv/decode_executor.py +++ b/python/tokenspeed/runtime/disaggregation/kv/decode_executor.py @@ -214,7 +214,7 @@ def generate_events(self): # so without explicit pop these dicts would grow unbounded across # failed requests. NOTE: _remote_spec_candidate_ids must NOT be # popped here — its consumer pop_remote_spec_candidate_ids runs - # later inside event_loop._process_pd_events, after we return. + # later inside event_loop._process_kv_transfer_events, after we return. # That dict is small (one tuple per Success request, between # generate_events emitting RemotePrefillDoneEvent and event_loop # consuming it) and is naturally drained by the pop path; an diff --git a/python/tokenspeed/runtime/disaggregation/kv/factory.py b/python/tokenspeed/runtime/disaggregation/kv/factory.py index d090b7c90f6..072b20c2f7c 100644 --- a/python/tokenspeed/runtime/disaggregation/kv/factory.py +++ b/python/tokenspeed/runtime/disaggregation/kv/factory.py @@ -25,7 +25,6 @@ from tokenspeed.runtime.disaggregation.kv.prefill_executor import DisaggPrefillExecutor from tokenspeed.runtime.disaggregation.kv.types import KVArgs from tokenspeed.runtime.disaggregation.kv.utils import TransferBackend -from tokenspeed.runtime.disaggregation.utils import DisaggregationMode def _get_contiguous_buf_unit_lens(pool, item_lens): @@ -127,7 +126,7 @@ def get_kv_args( def create_kv_transfer( - mode: DisaggregationMode, + mode: str, backend: TransferBackend, args: ManagerArgs, kv_args: KVArgs, diff --git a/python/tokenspeed/runtime/disaggregation/kv/utils.py b/python/tokenspeed/runtime/disaggregation/kv/utils.py index b79aa65575a..1b74bb6660a 100755 --- a/python/tokenspeed/runtime/disaggregation/kv/utils.py +++ b/python/tokenspeed/runtime/disaggregation/kv/utils.py @@ -18,10 +18,10 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -from __future__ import annotations - """Shared helpers for disaggregation runtime components.""" +from __future__ import annotations + import ctypes import dataclasses import os diff --git a/python/tokenspeed/runtime/disaggregation/utils.py b/python/tokenspeed/runtime/disaggregation/utils.py index 80983ae71a9..915af49ad4e 100644 --- a/python/tokenspeed/runtime/disaggregation/utils.py +++ b/python/tokenspeed/runtime/disaggregation/utils.py @@ -18,8 +18,6 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -from __future__ import annotations - """Disaggregation-wide neutral utilities shared by all roles (kv + embedding). These carry no KV/embedding-specific or backend-specific state, so they live at @@ -27,6 +25,8 @@ and a small blocking queue used by the transfer workers. """ +from __future__ import annotations + import threading from collections import deque from enum import Enum diff --git a/python/tokenspeed/runtime/engine/event_loop.py b/python/tokenspeed/runtime/engine/event_loop.py index 71d8c8dcef1..4bcabd90cf9 100644 --- a/python/tokenspeed/runtime/engine/event_loop.py +++ b/python/tokenspeed/runtime/engine/event_loop.py @@ -595,11 +595,12 @@ def _drain_ready_epd_embeddings(self) -> None: for rid in failed_ids: spec, state, bootstrap = self._epd_staged.pop(rid) # Signal the dual-dispatched decode that this request failed so its KV - # receiver fails (FailedEvent -> _process_pd_events abort) instead of - # waiting forever for KV the prefill will never send. The prefill never - # registered a P->D sender (deferred to admission), so the decode has no - # other reliable way to learn (heartbeat only trips on a dead prefill - # /health). Best-effort: only reaches decodes that already pre-allocated. + # receiver fails (FailedEvent -> _process_kv_transfer_events abort) + # instead of waiting forever for KV the prefill will never send. The + # prefill never registered a P->D sender (deferred to admission), so the + # decode has no other reliable way to learn (heartbeat only trips on a + # dead prefill /health). Best-effort: only reaches decodes that already + # pre-allocated. if ( isinstance(self.kv_transfer, DisaggPrefillExecutor) and bootstrap is not None @@ -1266,9 +1267,9 @@ def _get_forward_op(self, execution_plan): return None return forward_ops[0] - def _process_pd_events(self, pd_events: list) -> list: + def _process_kv_transfer_events(self, kv_transfer_events: list) -> list: processed = [] - for event in pd_events: + for event in kv_transfer_events: processed.append(event) if isinstance(event, PD.SucceededEvent) and isinstance( self.kv_transfer, DisaggPrefillExecutor @@ -1530,8 +1531,10 @@ def event_loop(self): ) if self.kv_transfer is not None: - pd_events = self.kv_transfer.generate_events() - request_changes.extend(self._process_pd_events(pd_events)) + kv_transfer_events = self.kv_transfer.generate_events() + request_changes.extend( + self._process_kv_transfer_events(kv_transfer_events) + ) if request_changes: advance_forward(self.scheduler, request_changes) @@ -1723,10 +1726,12 @@ def event_loop_overlap(self): self._commit_forward_results(prev_forward_op, prev_results) ) - # ---- collect PD events ---- + # ---- collect KV transfer events ---- if self.kv_transfer is not None: - pd_events = self.kv_transfer.generate_events() - request_changes.extend(self._process_pd_events(pd_events)) + kv_transfer_events = self.kv_transfer.generate_events() + request_changes.extend( + self._process_kv_transfer_events(kv_transfer_events) + ) if request_changes: advance_forward(self.scheduler, request_changes) diff --git a/python/tokenspeed/runtime/engine/generation_output_processor.py b/python/tokenspeed/runtime/engine/generation_output_processor.py index de1f6876f72..b5b9e5520dd 100644 --- a/python/tokenspeed/runtime/engine/generation_output_processor.py +++ b/python/tokenspeed/runtime/engine/generation_output_processor.py @@ -793,7 +793,7 @@ def on_remote_prefill_done(self, req_id: str, bootstrap_token: int) -> None: def finish_prefill_request(self, req_id: str) -> list: """Finish a prefill-instance request when KV transfer succeeds (SucceededEvent). - Called by event_loop._process_pd_events at the correct moment — the + Called by event_loop._process_kv_transfer_events at the correct moment — the SucceededEvent itself drives the C++ FSM transition Decoding → Finished, so we must NOT emit an additional make_finish_event here. diff --git a/python/tokenspeed/runtime/utils/env.py b/python/tokenspeed/runtime/utils/env.py index 2edf3c2da38..c1b64bfd94b 100755 --- a/python/tokenspeed/runtime/utils/env.py +++ b/python/tokenspeed/runtime/utils/env.py @@ -259,6 +259,12 @@ class Envs: TOKENSPEED_DISAGGREGATION_THREAD_POOL_SIZE = EnvInt(-1) TOKENSPEED_DISAGGREGATION_BOOTSTRAP_TIMEOUT = EnvInt(120) TOKENSPEED_DISAGGREGATION_WAITING_TIMEOUT = EnvInt(300) + TOKENSPEED_EPD_ENCODE_RING_SLOTS = EnvInt(64) + TOKENSPEED_EPD_ENCODE_RING_SLOT_MB = EnvInt(None) + TOKENSPEED_EPD_ENCODE_EMBED_CACHE_MB = EnvInt(4096) + TOKENSPEED_EPD_ENCODE_EMBED_CACHE_DRAM_MB = EnvInt(0) + TOKENSPEED_EPD_RECV_POOL_SLOTS = EnvInt(16) + TOKENSPEED_EPD_RECV_POOL_SLOT_MB = EnvInt(256) TOKENSPEED_EPD_EMBEDDING_SHARD = EnvBool(True) TOKENSPEED_PD_LAYERWISE_DEBUG = EnvBool(False) TOKENSPEED_PD_PREFILL_METADATA_TIMEOUT = EnvFloat(5.0) diff --git a/test/runtime/distributed/test_epd_encode.py b/test/runtime/distributed/test_epd_encode.py index a8bf4d49c8c..46fcd37aceb 100644 --- a/test/runtime/distributed/test_epd_encode.py +++ b/test/runtime/distributed/test_epd_encode.py @@ -473,22 +473,21 @@ def test_scheduler_rejects_bad_budgets(): EncodeScheduler(max_tokens_per_batch=1, max_items_per_batch=0) -_ENV = "TOKENSPEED_EPD_ENCODE_TEST_CACHE_MB" - - # --------------------------------------------------------------------------- # # _embedding_cache_bytes # --------------------------------------------------------------------------- # def test_bytes_override(monkeypatch): - monkeypatch.setenv(_ENV, "8") - assert _embedding_cache_bytes(_ENV, 4096) == 8 * 1024 * 1024 + env_field = encode_loop.envs.TOKENSPEED_EPD_ENCODE_EMBED_CACHE_MB + monkeypatch.setenv(env_field.name, "8") + assert _embedding_cache_bytes(env_field) == 8 * 1024 * 1024 def test_bytes_negative_raises_with_env_name(monkeypatch): - monkeypatch.setenv(_ENV, "-5") + env_field = encode_loop.envs.TOKENSPEED_EPD_ENCODE_EMBED_CACHE_MB + monkeypatch.setenv(env_field.name, "-5") with pytest.raises(ValueError) as exc: - _embedding_cache_bytes(_ENV, 4096) - assert _ENV in str(exc.value) + _embedding_cache_bytes(env_field) + assert env_field.name in str(exc.value) # --------------------------------------------------------------------------- # diff --git a/test/runtime/distributed/test_epd_transfer.py b/test/runtime/distributed/test_epd_transfer.py index ef709fb0f9e..3801c654159 100644 --- a/test/runtime/distributed/test_epd_transfer.py +++ b/test/runtime/distributed/test_epd_transfer.py @@ -54,7 +54,7 @@ ) # Each merged concern keeps its own per-test setup (the shard -# pointer-math tests need the legacy EPD_RECV_POOL_SLOTS=0 path, the +# pointer-math tests need the TOKENSPEED_EPD_RECV_POOL_SLOTS=0 path, the # receive tests need a small pool); route by test name. _RECV_TESTS = { "test_receive_sizes_buffers_per_item_no_deepstack", @@ -63,11 +63,12 @@ } -def setup_function(function): - if function.__name__ in _RECV_TESTS: - _recv_setup(function) +@pytest.fixture(autouse=True) +def _epd_transfer_env(request, monkeypatch): + if request.node.name in _RECV_TESTS: + _recv_setup(monkeypatch) else: - _shard_setup(function) + _shard_setup(monkeypatch) # A high device VA to catch any 32-bit truncation / wrong struct format. @@ -353,9 +354,7 @@ def pre_alloc(self, **kwargs): self.pre_alloc_kwargs = kwargs -def _shard_setup(_): - import os - +def _shard_setup(monkeypatch): import tokenspeed.runtime.disaggregation.embedding.prefill_receiver as er _ShardReceiver.created.clear() @@ -363,7 +362,7 @@ def _shard_setup(_): # compare pre_alloc destinations against item.encoded, which on the pooled # path is a post-DONE CLONE at a different address. Pool+shard interplay is # covered separately by test_pool_shard_reassembles_into_published_clone. - os.environ["EPD_RECV_POOL_SLOTS"] = "0" + monkeypatch.setenv("TOKENSPEED_EPD_RECV_POOL_SLOTS", "0") er._POOLS.clear() @@ -499,17 +498,15 @@ def _epd(item: MultimodalDataItem, *, room: int, host: str, port: int): return item -def _recv_setup(_): - import os - +def _recv_setup(monkeypatch): import tokenspeed.runtime.disaggregation.embedding.prefill_receiver as er _FakeReceiver.created.clear() # Small pool defaults so each test's fresh fake engine doesn't allocate # the production 16x256MB region; pools are keyed by engine identity, so # clear them (and the lazy-dereg queue) between tests. - os.environ["EPD_RECV_POOL_SLOTS"] = "4" - os.environ["EPD_RECV_POOL_SLOT_MB"] = "1" + monkeypatch.setenv("TOKENSPEED_EPD_RECV_POOL_SLOTS", "4") + monkeypatch.setenv("TOKENSPEED_EPD_RECV_POOL_SLOT_MB", "1") er._POOLS.clear() er._pending_dereg.clear() From 39cec51b439784f37a154c141444ea6475e828fc Mon Sep 17 00:00:00 2001 From: chenht2022 Date: Tue, 7 Jul 2026 18:11:46 +0000 Subject: [PATCH 4/7] chore(deps): bump tokenspeed-smg packages Signed-off-by: chenht2022 --- python/pyproject.toml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/python/pyproject.toml b/python/pyproject.toml index eebf3953007..388e7fa2de2 100755 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -65,9 +65,9 @@ dependencies = [ "setproctitle", "tiktoken", "tokenspeed-mooncake>=0.3.11.post20260527", - "tokenspeed-smg==1.7.0.post20260630", - "tokenspeed-smg-grpc-proto==0.4.12.post20260630", - "tokenspeed-smg-grpc-servicer==0.6.0.post20260630", + "tokenspeed-smg==1.7.0.post20260707", + "tokenspeed-smg-grpc-proto==0.4.12.post20260707", + "tokenspeed-smg-grpc-servicer==0.6.0.post20260707", "torch==2.11.0", # Tag-capable sleep/wake allocator (region(tag, enable_cpu_backup)/pause/ # resume). Bundles cu12/cu13 binaries; import-guarded so it's a no-op unless From 86ecd50214e9612cc1e7513891a0c680be8216cf Mon Sep 17 00:00:00 2001 From: chenht2022 Date: Wed, 8 Jul 2026 09:28:49 +0000 Subject: [PATCH 5/7] refactor: organize epd under pd runtime Signed-off-by: chenht2022 --- .../tokenspeed/runtime/cache/prefix_cache.py | 2 +- .../runtime/disaggregation/base/__init__.py | 38 --- .../runtime/disaggregation/base/poll.py | 40 --- .../disaggregation/embedding/__init__.py | 35 --- .../runtime/disaggregation/kv/types.py | 61 ----- .../runtime/disaggregation/utils.py | 67 ----- python/tokenspeed/runtime/engine/async_llm.py | 12 +- .../tokenspeed/runtime/engine/event_loop.py | 34 +-- .../runtime/engine/request_handler.py | 2 +- .../runtime/engine/schedule_batch.py | 6 +- .../runtime/layers/attention/backends/base.py | 2 +- .../{disaggregation => pd}/base/bootstrap.py | 12 +- .../{disaggregation => pd}/base/manager.py | 2 +- .../base/mooncake_engine.py} | 0 .../kv/__init__.py => pd/base/status.py} | 14 +- .../kv => pd}/decode_executor.py | 10 +- .../disaggregation_decode_scheduler.py} | 0 .../embedding => pd/epd}/conn.py | 44 +--- .../epd}/embedding_transfer.py | 211 ++------------- .../embedding => pd/epd}/encode_executor.py | 8 +- .../embedding => pd/epd}/encode_loop.py | 26 +- .../embedding => pd/epd}/encode_scheduler.py | 2 +- .../embedding => pd/epd}/encode_worker.py | 8 +- python/tokenspeed/runtime/pd/epd/entities.py | 249 ++++++++++++++++++ .../embedding => pd/epd}/prefill_receiver.py | 13 +- .../{disaggregation/kv => pd}/factory.py | 13 +- .../{disaggregation/kv => pd}/kv_events.py | 0 .../kv => pd}/mooncake/__init__.py | 10 +- .../kv => pd}/mooncake/async_conn.py | 13 +- .../kv => pd}/mooncake/conn.py | 24 +- .../kv => pd}/mooncake/decode.py | 11 +- .../kv => pd}/mooncake/entities.py | 31 ++- .../kv => pd}/mooncake/prefill.py | 21 +- .../kv => pd}/mooncake/receiver.py | 10 +- .../kv => pd}/mooncake/sender.py | 6 +- .../kv => pd}/prefill_executor.py | 8 +- .../kv => pd}/transfer_plan.py | 0 .../{disaggregation/kv => pd}/utils.py | 58 +++- test/runtime/distributed/test_epd_encode.py | 22 +- test/runtime/distributed/test_epd_transfer.py | 37 +-- .../distributed/test_pd_transfer_plan.py | 4 +- test/runtime/test_kv_events.py | 2 +- 42 files changed, 527 insertions(+), 641 deletions(-) delete mode 100644 python/tokenspeed/runtime/disaggregation/base/__init__.py delete mode 100644 python/tokenspeed/runtime/disaggregation/base/poll.py delete mode 100644 python/tokenspeed/runtime/disaggregation/embedding/__init__.py delete mode 100644 python/tokenspeed/runtime/disaggregation/kv/types.py delete mode 100644 python/tokenspeed/runtime/disaggregation/utils.py rename python/tokenspeed/runtime/{disaggregation => pd}/base/bootstrap.py (96%) rename python/tokenspeed/runtime/{disaggregation => pd}/base/manager.py (98%) rename python/tokenspeed/runtime/{disaggregation/mooncake_transfer_engine.py => pd/base/mooncake_engine.py} (100%) rename python/tokenspeed/runtime/{disaggregation/kv/__init__.py => pd/base/status.py} (72%) rename python/tokenspeed/runtime/{disaggregation/kv => pd}/decode_executor.py (96%) rename python/tokenspeed/runtime/{disaggregation/kv/decode_scheduler.py => pd/disaggregation_decode_scheduler.py} (100%) rename python/tokenspeed/runtime/{disaggregation/embedding => pd/epd}/conn.py (69%) rename python/tokenspeed/runtime/{disaggregation/embedding => pd/epd}/embedding_transfer.py (83%) rename python/tokenspeed/runtime/{disaggregation/embedding => pd/epd}/encode_executor.py (99%) rename python/tokenspeed/runtime/{disaggregation/embedding => pd/epd}/encode_loop.py (95%) rename python/tokenspeed/runtime/{disaggregation/embedding => pd/epd}/encode_scheduler.py (98%) rename python/tokenspeed/runtime/{disaggregation/embedding => pd/epd}/encode_worker.py (99%) create mode 100644 python/tokenspeed/runtime/pd/epd/entities.py rename python/tokenspeed/runtime/{disaggregation/embedding => pd/epd}/prefill_receiver.py (99%) rename python/tokenspeed/runtime/{disaggregation/kv => pd}/factory.py (91%) rename python/tokenspeed/runtime/{disaggregation/kv => pd}/kv_events.py (100%) rename python/tokenspeed/runtime/{disaggregation/kv => pd}/mooncake/__init__.py (79%) rename python/tokenspeed/runtime/{disaggregation/kv => pd}/mooncake/async_conn.py (98%) rename python/tokenspeed/runtime/{disaggregation/kv => pd}/mooncake/conn.py (86%) rename python/tokenspeed/runtime/{disaggregation/kv => pd}/mooncake/decode.py (96%) rename python/tokenspeed/runtime/{disaggregation/kv => pd}/mooncake/entities.py (87%) rename python/tokenspeed/runtime/{disaggregation/kv => pd}/mooncake/prefill.py (98%) rename python/tokenspeed/runtime/{disaggregation/kv => pd}/mooncake/receiver.py (98%) rename python/tokenspeed/runtime/{disaggregation/kv => pd}/mooncake/sender.py (97%) rename python/tokenspeed/runtime/{disaggregation/kv => pd}/prefill_executor.py (98%) rename python/tokenspeed/runtime/{disaggregation/kv => pd}/transfer_plan.py (100%) rename python/tokenspeed/runtime/{disaggregation/kv => pd}/utils.py (91%) diff --git a/python/tokenspeed/runtime/cache/prefix_cache.py b/python/tokenspeed/runtime/cache/prefix_cache.py index 3746fca522e..5fd54247bad 100755 --- a/python/tokenspeed/runtime/cache/prefix_cache.py +++ b/python/tokenspeed/runtime/cache/prefix_cache.py @@ -55,7 +55,7 @@ # Import KV events classes if needed try: - from tokenspeed.runtime.disaggregation.kv.kv_events import ( + from tokenspeed.runtime.pd.kv_events import ( AllBlocksCleared, BlockRemoved, BlockStored, diff --git a/python/tokenspeed/runtime/disaggregation/base/__init__.py b/python/tokenspeed/runtime/disaggregation/base/__init__.py deleted file mode 100644 index 15a14313374..00000000000 --- a/python/tokenspeed/runtime/disaggregation/base/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# Copyright (c) 2026 LightSeek Foundation -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. - -"""Role-neutral transport substrate shared by the disaggregation transfer roles. - -Both the KV (prefill->decode) and the embedding (encode->prefill) paths ship -bytes over the same Mooncake RDMA engine and rendezvous through the same HTTP -bootstrap protocol, so the mechanical (semantics-free) plumbing lives here once -and both roles compose it: - - :mod:`poll` the :class:`TransferPoll` transfer-status FSM constants - :mod:`manager` :class:`DisaggManagerBase` -- engine + ZMQ control socket - + room-keyed monotonic, Failed-sticky status tracking - :mod:`bootstrap` :class:`DisaggBootstrapServer` -- the aiohttp rendezvous - server (PUT register / GET lookup + dp-group sharding) - -The role-specific *semantics* (the buffer/arg shapes, the wire frames, the -senders/receivers) stay in :mod:`...kv` and :mod:`...embedding`; this layer -carries no KV/MLA/embedding fields, so the two paths still evolve independently. -Import entry points from the submodules directly. -""" diff --git a/python/tokenspeed/runtime/disaggregation/base/poll.py b/python/tokenspeed/runtime/disaggregation/base/poll.py deleted file mode 100644 index d4c86c89b7e..00000000000 --- a/python/tokenspeed/runtime/disaggregation/base/poll.py +++ /dev/null @@ -1,40 +0,0 @@ -# Copyright (c) 2026 LightSeek Foundation -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. - -from __future__ import annotations - - -class TransferPoll: - """Transfer-status FSM shared by both disaggregation roles. - - Integer-ordered so :meth:`DisaggManagerBase.update_status` can enforce - monotonic, ``Failed``-sticky transitions via ``max()``. The KV - (prefill->decode) and embedding (encode->prefill) paths use this single - enum; ``WaitingForInput`` is only meaningful to the KV path (the embedding - path never sets it, but sharing one ordered enum keeps the two status FSMs - from drifting apart). - """ - - Failed = 0 - Bootstrapping = 1 - Bootstrapped = 2 - WaitingForInput = 3 - Transferring = 4 - Success = 5 diff --git a/python/tokenspeed/runtime/disaggregation/embedding/__init__.py b/python/tokenspeed/runtime/disaggregation/embedding/__init__.py deleted file mode 100644 index 063fe633b37..00000000000 --- a/python/tokenspeed/runtime/disaggregation/embedding/__init__.py +++ /dev/null @@ -1,35 +0,0 @@ -# Copyright (c) 2026 LightSeek Foundation -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. - -"""EPD embedding (encode->prefill) disaggregation. - -The encode role runs the vision tower only and ships image embeddings over the -Mooncake RDMA engine; the prefill role receives them and skips the tower. The -embedding transport supports TP fanout only inside one server; encode DP scale is -provided by running multiple independent encode servers rather than by attention -DP in one process group. The -role-neutral transport substrate (the :class:`...base.poll.TransferPoll` status FSM, the -manager base, the bootstrap server) is shared from :mod:`...disaggregation.base`; -:mod:`conn` layers the embedding buffer args onto it and :mod:`embedding_transfer` -adds the wire frames and senders/receivers. The encode side lives in -:mod:`encode_loop` (entry point), :mod:`encode_worker`, :mod:`encode_scheduler`, -and :mod:`encode_executor`; the prefill side in :mod:`prefill_receiver`. Import -entry points from those submodules directly. -""" diff --git a/python/tokenspeed/runtime/disaggregation/kv/types.py b/python/tokenspeed/runtime/disaggregation/kv/types.py deleted file mode 100644 index 05ccc86f487..00000000000 --- a/python/tokenspeed/runtime/disaggregation/kv/types.py +++ /dev/null @@ -1,61 +0,0 @@ -# Copyright (c) 2026 LightSeek Foundation -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. - -"""Value types for the KV (prefill->decode) disaggregation path. - -The role-specific buffer/engine args and bootstrap handshake record. The -transfer-status FSM is the shared :class:`...base.poll.TransferPoll`; the transport -mechanics are the shared :class:`...base.manager.DisaggManagerBase` / -:class:`...base.bootstrap.DisaggBootstrapServer`. -""" - -from dataclasses import dataclass, field - - -@dataclass -class KVArgs: - engine_rank: int - kv_data_ptrs: list[int] - kv_data_lens: list[int] - kv_item_lens: list[int] - offsets: list[tuple[int]] - aux_data_ptrs: list[int] - aux_data_lens: list[int] - aux_item_lens: list[int] - ib_device: str - gpu_id: int - target_layer_num: int - draft_layer_num: int - kv_layer_ids: list[int] = field(default_factory=list) - kv_unit_lens: list[int] = field(default_factory=list) - state_data_ptrs: list[int] = field(default_factory=list) - state_data_lens: list[int] = field(default_factory=list) - state_item_lens: list[int] = field(default_factory=list) - state_unit_lens: list[int] = field(default_factory=list) - state_type: str = "none" - state_layer_ids: list[int] = field(default_factory=list) - mamba_offsets: list[int] | None = None - - -@dataclass -class BootstrapInfo: - bootstrap_host: str - bootstrap_port: int - bootstrap_room: int diff --git a/python/tokenspeed/runtime/disaggregation/utils.py b/python/tokenspeed/runtime/disaggregation/utils.py deleted file mode 100644 index 915af49ad4e..00000000000 --- a/python/tokenspeed/runtime/disaggregation/utils.py +++ /dev/null @@ -1,67 +0,0 @@ -# Copyright (c) 2026 LightSeek Foundation -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. - -"""Disaggregation-wide neutral utilities shared by all roles (kv + embedding). - -These carry no KV/embedding-specific or backend-specific state, so they live at -the disaggregation root rather than inside any role package: the role/mode enum -and a small blocking queue used by the transfer workers. -""" - -from __future__ import annotations - -import threading -from collections import deque -from enum import Enum - - -class DisaggregationMode(Enum): - NULL = "null" - PREFILL = "prefill" - DECODE = "decode" - ENCODE = "encode" - - -class FastQueue: - class Empty(Exception): - """Exception raised when the queue is empty.""" - - pass - - def __init__(self): - self._buf = deque() - self._cond = threading.Condition() - - def put(self, item): - with self._cond: - self._buf.append(item) - self._cond.notify() - - def get(self): - with self._cond: - while not self._buf: - self._cond.wait() - return self._buf.popleft() - - def get_nowait(self): - with self._cond: - if not self._buf: - raise FastQueue.Empty() - return self._buf.popleft() diff --git a/python/tokenspeed/runtime/engine/async_llm.py b/python/tokenspeed/runtime/engine/async_llm.py index b489461d98a..a5e532ca8e5 100755 --- a/python/tokenspeed/runtime/engine/async_llm.py +++ b/python/tokenspeed/runtime/engine/async_llm.py @@ -48,12 +48,6 @@ import uvloop from tokenspeed.runtime.configs.model_config import ModelConfig -from tokenspeed.runtime.disaggregation.kv.utils import ( - KVClassType, - TransferBackend, - get_kv_class, -) -from tokenspeed.runtime.disaggregation.utils import DisaggregationMode from tokenspeed.runtime.engine.aio_rwlock import RWLock from tokenspeed.runtime.engine.collector import RequestOutputCollector from tokenspeed.runtime.engine.core_client import EngineCoreClient @@ -90,6 +84,12 @@ SchedulerControlClient, ) from tokenspeed.runtime.metrics.collector import RequestMetrics +from tokenspeed.runtime.pd.utils import ( + DisaggregationMode, + KVClassType, + TransferBackend, + get_kv_class, +) from tokenspeed.runtime.utils import ( dataclass_to_string_truncated, get_colorful_logger, diff --git a/python/tokenspeed/runtime/engine/event_loop.py b/python/tokenspeed/runtime/engine/event_loop.py index c62a8f16693..1f604e42b95 100644 --- a/python/tokenspeed/runtime/engine/event_loop.py +++ b/python/tokenspeed/runtime/engine/event_loop.py @@ -37,20 +37,6 @@ ) from tokenspeed.runtime.cache.transfer.types import CacheKind from tokenspeed.runtime.configs.model_config import ModelConfig -from tokenspeed.runtime.disaggregation.kv.decode_executor import DisaggDecodeExecutor -from tokenspeed.runtime.disaggregation.kv.factory import ( - create_kv_transfer, - get_kv_args, -) -from tokenspeed.runtime.disaggregation.kv.kv_events import ( - EventPublisherFactory, - KVEventBatch, - NullEventPublisher, - drain_scheduler_kv_events, - scheduler_kv_events_to_wire_events, -) -from tokenspeed.runtime.disaggregation.kv.mooncake.entities import ManagerArgs -from tokenspeed.runtime.disaggregation.kv.prefill_executor import DisaggPrefillExecutor from tokenspeed.runtime.distributed.process_group_manager import ( process_group_manager as pg_manager, ) @@ -84,6 +70,20 @@ from tokenspeed.runtime.grammar.capturable_grammar import GrammarStepInputs from tokenspeed.runtime.layers.attention.registry import create_attn_components from tokenspeed.runtime.metrics.collector import EngineMetrics +from tokenspeed.runtime.pd.decode_executor import DisaggDecodeExecutor +from tokenspeed.runtime.pd.factory import ( + create_kv_transfer, + get_kv_args, +) +from tokenspeed.runtime.pd.kv_events import ( + EventPublisherFactory, + KVEventBatch, + NullEventPublisher, + drain_scheduler_kv_events, + scheduler_kv_events_to_wire_events, +) +from tokenspeed.runtime.pd.mooncake.entities import ManagerArgs +from tokenspeed.runtime.pd.prefill_executor import DisaggPrefillExecutor from tokenspeed.runtime.sampling.sampling_params import SamplingParams from tokenspeed.runtime.utils import ( configure_logger, @@ -510,7 +510,7 @@ def __init__( # prefill skips the vision tower. The admission controller owns the # receive jobs, the rank-synced admission drain, and the optional NCCL # row-shard reassembly; None for decode/encode/text-only nodes. - from tokenspeed.runtime.disaggregation.embedding.prefill_receiver import ( + from tokenspeed.runtime.pd.epd.prefill_receiver import ( make_epd_prefill_admission, ) @@ -540,7 +540,7 @@ def _setup_pd_layerwise_transfer(self, interval: int) -> None: if interval <= 0: return - from tokenspeed.runtime.disaggregation.kv.utils import StepCounter + from tokenspeed.runtime.pd.utils import StepCounter step_counter = StepCounter(self.model_executor.device, self.gpu_id) self.model_executor.attn_backend.register_step_counter(step_counter) @@ -1791,7 +1791,7 @@ def run_event_loop( if server_args.disaggregation_mode == "encode": # The encode role is LM-free; run the lightweight vision-tower loop # instead of building the full EventLoop (KV/LM scheduler). - from tokenspeed.runtime.disaggregation.embedding.encode_loop import ( + from tokenspeed.runtime.pd.epd.encode_loop import ( run_encode_loop, ) diff --git a/python/tokenspeed/runtime/engine/request_handler.py b/python/tokenspeed/runtime/engine/request_handler.py index a515fa26338..ae2515c345b 100644 --- a/python/tokenspeed/runtime/engine/request_handler.py +++ b/python/tokenspeed/runtime/engine/request_handler.py @@ -29,7 +29,6 @@ import zmq from viztracer import VizTracer -from tokenspeed.runtime.disaggregation.kv.types import BootstrapInfo from tokenspeed.runtime.distributed.process_group_manager import ( process_group_manager as pg_manager, ) @@ -60,6 +59,7 @@ from tokenspeed.runtime.execution.forward_batch_info import ForwardMode from tokenspeed.runtime.grammar.grammar_manager import GrammarManager from tokenspeed.runtime.multimodal.shm_transport import sync_shm_features +from tokenspeed.runtime.pd.base.bootstrap import BootstrapInfo from tokenspeed.runtime.utils import broadcast_pyobj from tokenspeed.runtime.utils.dispatch import TypeBasedDispatcher from tokenspeed.runtime.utils.env import envs diff --git a/python/tokenspeed/runtime/engine/schedule_batch.py b/python/tokenspeed/runtime/engine/schedule_batch.py index 199c6fac304..131b30b1b07 100755 --- a/python/tokenspeed/runtime/engine/schedule_batch.py +++ b/python/tokenspeed/runtime/engine/schedule_batch.py @@ -46,15 +46,15 @@ from tokenspeed.runtime.cache.base_prefix_cache import BasePrefixCache from tokenspeed.runtime.cache.req_to_token_pool import ReqToTokenPool from tokenspeed.runtime.configs.model_config import ModelConfig -from tokenspeed.runtime.disaggregation.kv.decode_scheduler import ( - DisaggDecodeScheduler, -) from tokenspeed.runtime.engine.request import Req from tokenspeed.runtime.execution.forward_batch_info import ( ForwardMode, ) from tokenspeed.runtime.layers.attention.kv_cache.base import BaseTokenToKVPool from tokenspeed.runtime.layers.logits_processor import LogitsProcessorOutput +from tokenspeed.runtime.pd.disaggregation_decode_scheduler import ( + DisaggDecodeScheduler, +) from tokenspeed.runtime.sampling.sampling_batch_info import SamplingBatchInfo from tokenspeed.runtime.utils import get_colorful_logger diff --git a/python/tokenspeed/runtime/layers/attention/backends/base.py b/python/tokenspeed/runtime/layers/attention/backends/base.py index c77879499b2..c52b05b5273 100644 --- a/python/tokenspeed/runtime/layers/attention/backends/base.py +++ b/python/tokenspeed/runtime/layers/attention/backends/base.py @@ -27,11 +27,11 @@ import torch if TYPE_CHECKING: - from tokenspeed.runtime.disaggregation.kv.utils import StepCounter from tokenspeed.runtime.execution.forward_batch_info import ForwardMode from tokenspeed.runtime.layers.attention.configs.base import BaseAttnConfig from tokenspeed.runtime.layers.attention.kv_cache.base import BaseTokenToKVPool from tokenspeed.runtime.layers.paged_attention import PagedAttention + from tokenspeed.runtime.pd.utils import StepCounter class AttentionBackend(ABC): diff --git a/python/tokenspeed/runtime/disaggregation/base/bootstrap.py b/python/tokenspeed/runtime/pd/base/bootstrap.py similarity index 96% rename from python/tokenspeed/runtime/disaggregation/base/bootstrap.py rename to python/tokenspeed/runtime/pd/base/bootstrap.py index a76c058b315..ad39bd23459 100644 --- a/python/tokenspeed/runtime/disaggregation/base/bootstrap.py +++ b/python/tokenspeed/runtime/pd/base/bootstrap.py @@ -23,6 +23,7 @@ import asyncio import logging import threading +from dataclasses import dataclass from aiohttp import web @@ -31,8 +32,15 @@ logger = get_colorful_logger(__name__) -class DisaggBootstrapServer: - """HTTP rendezvous server shared by both disaggregation roles. +@dataclass +class BootstrapInfo: + bootstrap_host: str + bootstrap_port: int + bootstrap_room: int + + +class DisaggBootstrapServerBase: + """HTTP rendezvous server shared by both PD and EPD transfer roles. A data-source rank PUTs its (ip, port) keyed by (dp_group, tp_rank_in_dp); the peer GETs that back to open a Mooncake session, and uses the sentinel diff --git a/python/tokenspeed/runtime/disaggregation/base/manager.py b/python/tokenspeed/runtime/pd/base/manager.py similarity index 98% rename from python/tokenspeed/runtime/disaggregation/base/manager.py rename to python/tokenspeed/runtime/pd/base/manager.py index 2a8a5f593d2..6298a567964 100644 --- a/python/tokenspeed/runtime/disaggregation/base/manager.py +++ b/python/tokenspeed/runtime/pd/base/manager.py @@ -25,7 +25,7 @@ import zmq -from tokenspeed.runtime.disaggregation.base.poll import TransferPoll +from tokenspeed.runtime.pd.base.status import TransferPoll class DisaggManagerBase: diff --git a/python/tokenspeed/runtime/disaggregation/mooncake_transfer_engine.py b/python/tokenspeed/runtime/pd/base/mooncake_engine.py similarity index 100% rename from python/tokenspeed/runtime/disaggregation/mooncake_transfer_engine.py rename to python/tokenspeed/runtime/pd/base/mooncake_engine.py diff --git a/python/tokenspeed/runtime/disaggregation/kv/__init__.py b/python/tokenspeed/runtime/pd/base/status.py similarity index 72% rename from python/tokenspeed/runtime/disaggregation/kv/__init__.py rename to python/tokenspeed/runtime/pd/base/status.py index 799b4746f14..ed0df071df7 100644 --- a/python/tokenspeed/runtime/disaggregation/kv/__init__.py +++ b/python/tokenspeed/runtime/pd/base/status.py @@ -18,11 +18,11 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -"""KV-cache (prefill->decode) disaggregation -- the PD transfer stack. -Moves computed KV pages from a prefill server to a decode server over a -pluggable transport. The shared args/poll types live in :mod:`base`, the -backend managers in :mod:`mooncake`, the role executors in -:mod:`prefill_executor` / :mod:`decode_executor`, and transport selection in -:mod:`factory`. Import entry points from those submodules directly. -""" +class TransferPoll: + Failed = 0 + Bootstrapping = 1 + Bootstrapped = 2 + WaitingForInput = 3 + Transferring = 4 + Success = 5 diff --git a/python/tokenspeed/runtime/disaggregation/kv/decode_executor.py b/python/tokenspeed/runtime/pd/decode_executor.py similarity index 96% rename from python/tokenspeed/runtime/disaggregation/kv/decode_executor.py rename to python/tokenspeed/runtime/pd/decode_executor.py index fa5482874ba..cdc198acad4 100644 --- a/python/tokenspeed/runtime/disaggregation/kv/decode_executor.py +++ b/python/tokenspeed/runtime/pd/decode_executor.py @@ -23,11 +23,11 @@ import torch from tokenspeed_scheduler import PD, Forward -from tokenspeed.runtime.disaggregation.base.poll import TransferPoll -from tokenspeed.runtime.disaggregation.kv.mooncake.decode import MooncakeKVManagerDecode -from tokenspeed.runtime.disaggregation.kv.mooncake.receiver import MooncakeKVReceiver -from tokenspeed.runtime.disaggregation.kv.types import BootstrapInfo -from tokenspeed.runtime.disaggregation.kv.utils import ( +from tokenspeed.runtime.pd.base.bootstrap import BootstrapInfo +from tokenspeed.runtime.pd.base.status import TransferPoll +from tokenspeed.runtime.pd.mooncake.decode import MooncakeKVManagerDecode +from tokenspeed.runtime.pd.mooncake.receiver import MooncakeKVReceiver +from tokenspeed.runtime.pd.utils import ( TransferBackend, poll_and_all_reduce, ) diff --git a/python/tokenspeed/runtime/disaggregation/kv/decode_scheduler.py b/python/tokenspeed/runtime/pd/disaggregation_decode_scheduler.py similarity index 100% rename from python/tokenspeed/runtime/disaggregation/kv/decode_scheduler.py rename to python/tokenspeed/runtime/pd/disaggregation_decode_scheduler.py diff --git a/python/tokenspeed/runtime/disaggregation/embedding/conn.py b/python/tokenspeed/runtime/pd/epd/conn.py similarity index 69% rename from python/tokenspeed/runtime/disaggregation/embedding/conn.py rename to python/tokenspeed/runtime/pd/epd/conn.py index 42f4661acd3..fc8908e2670 100644 --- a/python/tokenspeed/runtime/disaggregation/embedding/conn.py +++ b/python/tokenspeed/runtime/pd/epd/conn.py @@ -22,7 +22,7 @@ The mechanical plumbing (the Mooncake engine + ZMQ control socket + room-keyed status FSM, and the bootstrap rendezvous server) is the role-neutral shared base -in :mod:`...disaggregation.base`; this module just layers the embedding role's +in :mod:`tokenspeed.runtime.pd.base`; this module just layers the embedding role's buffer args onto it. The embedding-specific *semantics* -- the wire frames and the senders/receivers -- live in :mod:`embedding_transfer`; nothing here carries any KV/MLA/metrics state. @@ -30,38 +30,20 @@ from __future__ import annotations -import dataclasses - -from tokenspeed.runtime.disaggregation.base.bootstrap import DisaggBootstrapServer -from tokenspeed.runtime.disaggregation.base.manager import DisaggManagerBase -from tokenspeed.runtime.disaggregation.mooncake_transfer_engine import ( +from tokenspeed.runtime.pd.base.bootstrap import DisaggBootstrapServerBase +from tokenspeed.runtime.pd.base.manager import DisaggManagerBase +from tokenspeed.runtime.pd.base.mooncake_engine import ( MooncakeTransferEngine, ) -from tokenspeed.runtime.disaggregation.utils import DisaggregationMode +from tokenspeed.runtime.pd.epd.entities import EmbeddingManagerArgs +from tokenspeed.runtime.pd.utils import DisaggregationMode from tokenspeed.runtime.utils.network import get_local_ip_by_remote -class EmbeddingTransferError(Exception): - """Raised on an embedding (encode->prefill) transfer failure.""" - - -@dataclasses.dataclass -class EmbeddingManagerArgs: - """Connection config for the embedding Mooncake endpoint. - - Embedding transfer has a single DP group today. ``tp_size`` is the number - of encode/prefill endpoint ranks that participate in that group; the shared - bootstrap layer still receives it as ``world_size`` with ``dp_size=1``. - """ - - bootstrap_port: int - tp_size: int - bootstrap_host: str | None = None - - -class EmbeddingManagerBase(DisaggManagerBase): +class MooncakeEmbeddingManagerBase(DisaggManagerBase): """Embedding (encode->prefill) manager: the shared engine/socket/status FSM - (:class:`...base.manager.DisaggManagerBase`) plus the embedding buffer args. + (:class:`tokenspeed.runtime.pd.base.manager.DisaggManagerBase`) plus the + embedding buffer args. Carries none of the KV manager's KV/MLA/metrics fields. """ @@ -77,8 +59,8 @@ def __init__( self.bootstrap_port = args.bootstrap_port self.world_size = args.tp_size self.dp_size = 1 - # Vendor binding stays out of the neutral base. embedding_args must be - # set above before super().__init__, which calls register_buffer_to_engine. + # embedding_args must be set above before super().__init__, which calls + # register_buffer_to_engine. engine = MooncakeTransferEngine( hostname=get_local_ip_by_remote(), gpu_id=embedding_args.gpu_id, @@ -94,8 +76,8 @@ def register_buffer_to_engine(self): self.engine.register(ea.deepstack_data_ptr, ea.deepstack_data_len) -class EmbeddingBootstrapServer(DisaggBootstrapServer): +class MooncakeEmbeddingBootstrapServer(DisaggBootstrapServerBase): """Embedding bootstrap rendezvous: the shared server with no extra fields -- the encode->prefill handshake needs only the base ip/port + parallel-size - sync, so there is nothing to layer onto :class:`DisaggBootstrapServer`. + sync, so there is nothing to layer onto :class:`DisaggBootstrapServerBase`. """ diff --git a/python/tokenspeed/runtime/disaggregation/embedding/embedding_transfer.py b/python/tokenspeed/runtime/pd/epd/embedding_transfer.py similarity index 83% rename from python/tokenspeed/runtime/disaggregation/embedding/embedding_transfer.py rename to python/tokenspeed/runtime/pd/epd/embedding_transfer.py index 8f213c53791..7296780a71f 100644 --- a/python/tokenspeed/runtime/disaggregation/embedding/embedding_transfer.py +++ b/python/tokenspeed/runtime/pd/epd/embedding_transfer.py @@ -26,17 +26,15 @@ is the receiver that pre-registers buffers and registers with the bootstrap server (direction reversed relative to prefill->decode). -Each frame dataclass owns its byte layout via ``to_zmq()``/``from_zmq()``. The -wire-frame dataclasses are pure data plus codecs and import no torch, so the -protocol contract stays importable and unit-testable on CPU. +Wire-frame dataclasses live in :mod:`tokenspeed.runtime.pd.epd.entities`: they +are pure data plus codecs and import no torch, so the protocol contract stays +importable and unit-testable on CPU. """ from __future__ import annotations import concurrent.futures -import dataclasses import os -import struct import threading import time from typing import TYPE_CHECKING @@ -44,13 +42,20 @@ import requests import zmq -from tokenspeed.runtime.disaggregation.base.poll import TransferPoll -from tokenspeed.runtime.disaggregation.embedding.conn import ( +from tokenspeed.runtime.pd.base.status import TransferPoll +from tokenspeed.runtime.pd.epd.conn import ( + MooncakeEmbeddingManagerBase, +) +from tokenspeed.runtime.pd.epd.entities import ( + REGISTER_ROOM_SENTINEL, + EmbeddingArgs, + EmbeddingArgsRegisterInfo, + EmbeddingChunk, EmbeddingManagerArgs, - EmbeddingManagerBase, EmbeddingTransferError, + EmbeddingTransferInfo, ) -from tokenspeed.runtime.disaggregation.utils import DisaggregationMode, FastQueue +from tokenspeed.runtime.pd.utils import DisaggregationMode, FastQueue from tokenspeed.runtime.utils import get_colorful_logger from tokenspeed.runtime.utils.env import envs from tokenspeed.runtime.utils.network import get_free_port, get_local_ip_by_remote @@ -82,190 +87,10 @@ def _route_get(bootstrap_addr: str, engine_rank: int, target_dp_group: int): return None -# Sentinel room (on-wire ascii) for the one-shot registration frame; per-request -# pre-alloc frames carry an integer room. -REGISTER_ROOM_SENTINEL = "None" - - -def _pack_ptr(ptr: int) -> bytes: - """Encode a device virtual address as 8 little-endian bytes (uint64).""" - return struct.pack("Q", ptr) - - -def _unpack_ptr(frame: bytes) -> int: - return struct.unpack("Q", frame)[0] - - def _b(value: object) -> bytes: return str(value).encode("ascii") -def _bool_frame(value: bool) -> bytes: - return b"1" if value else b"0" - - -def _parse_bool(frame: bytes) -> bool: - return frame == b"1" - - -@dataclasses.dataclass -class EmbeddingArgs: - """Per-rank buffer/engine info for an embedding endpoint. - - On the encode (sender) side the buffers hold the vision tower's output; on - the prefill (receiver) side they are the pre-registered receive buffers. A - ``deepstack`` buffer is present only for models that emit deepstack - embeddings (e.g. Qwen3.5); ``0`` means absent. - """ - - engine_rank: int - gpu_id: int - ib_device: str | None - embedding_data_ptr: int - embedding_data_len: int - deepstack_data_ptr: int = 0 - deepstack_data_len: int = 0 - - -@dataclasses.dataclass -class EmbeddingChunk: - """One item's embedding queued for transfer (encode-side, in-process only). - - Not serialized to ZMQ: it lives on the encode manager's transfer queue. The - pointers reference the contiguous ``item.encoded`` / ``item.encoded_deepstack`` - tensors produced by the vision tower. - """ - - room: int - src_embedding_ptr: int - n_tokens: int - hidden: int - dtype: str - nbytes: int - src_deepstack_ptr: int = 0 - deepstack_width: int = 0 # hidden * num_deepstack; 0 == no deepstack - deepstack_nbytes: int = 0 - # CUDA event recorded on the encode loop's stream after the device copy that - # filled this chunk's ring slot. The transfer worker waits it before its - # one-sided RDMA read so the read never races the copy (ViT->send corruption - # hazard). None on CPU/no-CUDA. - copy_event: torch.cuda.Event | None = None - - -@dataclasses.dataclass -class EmbeddingArgsRegisterInfo: - """Receiver(prefill)->sender(encode) one-shot endpoint registration. - - Sent once per receiver rank with room == ``REGISTER_ROOM_SENTINEL`` so the - encode side records where to PUSH completion status. The buffer pointers - are the receiver's base receive buffers (per-item row offsets are carried - later, in :class:`EmbeddingTransferInfo`). - """ - - room: str - endpoint: str - dst_port: int - mooncake_session_id: str - dst_embedding_ptr: int - dst_deepstack_ptr: int - - def to_zmq(self) -> list[bytes]: - return [ - _b(self.room), - _b(self.endpoint), - _b(self.dst_port), - _b(self.mooncake_session_id), - _pack_ptr(self.dst_embedding_ptr), - _pack_ptr(self.dst_deepstack_ptr), - ] - - @classmethod - def from_zmq(cls, msg: list[bytes]) -> "EmbeddingArgsRegisterInfo": - return cls( - room=msg[0].decode("ascii"), - endpoint=msg[1].decode("ascii"), - dst_port=int(msg[2].decode("ascii")), - mooncake_session_id=msg[3].decode("ascii"), - dst_embedding_ptr=_unpack_ptr(msg[4]), - dst_deepstack_ptr=_unpack_ptr(msg[5]), - ) - - -@dataclasses.dataclass -class EmbeddingTransferInfo: - """Receiver(prefill)->sender(encode) per-request pre-allocation frame. - - Tells the encode side where (``dst_embedding_ptr`` already includes this - request's row offset) and how big a transfer to issue. The RDMA write is - unchecked, so the encode asserts ``n_tokens``/``hidden``/``dtype`` against - the tensor it sends, else a mismatch silently writes a truncated/oversized - region. - - Row sharding: ``row_start`` + ``n_tokens`` (the SHARD's row count) select - the rows the encode writes at the shard-offset ``dst_embedding_ptr``; - ``span`` is the image's FULL row count, the cross-side token-count tripwire - regardless of shard geometry. Identity frames set ``row_start == 0`` and - ``n_tokens == span``. The encode validates shard geometry per frame: a - full-span write at a shard-offset pointer would corrupt neighboring image - rows in the same buffer. - """ - - room: int - endpoint: str - dst_port: int - mooncake_session_id: str - dst_embedding_ptr: int - dst_deepstack_ptr: int - n_tokens: int - hidden: int - dtype: str - has_deepstack: bool - required_dst_info_num: int - row_start: int = 0 - span: int = 0 - - def to_zmq(self) -> list[bytes]: - return [ - _b(self.room), - _b(self.endpoint), - _b(self.dst_port), - _b(self.mooncake_session_id), - _pack_ptr(self.dst_embedding_ptr), - _pack_ptr(self.dst_deepstack_ptr), - _b(self.n_tokens), - _b(self.hidden), - _b(self.dtype), - _bool_frame(self.has_deepstack), - _b(self.required_dst_info_num), - _b(self.row_start), - _b(self.span), - ] - - @classmethod - def from_zmq(cls, msg: list[bytes]) -> "EmbeddingTransferInfo": - # Length-guarded so a truncated frame is logged and dropped by the - # bootstrap listener instead of mis-parsing. - if len(msg) < 13: - raise ValueError( - f"malformed EmbeddingTransferInfo frame: {len(msg)} parts < 13" - ) - return cls( - room=int(msg[0].decode("ascii")), - endpoint=msg[1].decode("ascii"), - dst_port=int(msg[2].decode("ascii")), - mooncake_session_id=msg[3].decode("ascii"), - dst_embedding_ptr=_unpack_ptr(msg[4]), - dst_deepstack_ptr=_unpack_ptr(msg[5]), - n_tokens=int(msg[6].decode("ascii")), - hidden=int(msg[7].decode("ascii")), - dtype=msg[8].decode("ascii"), - has_deepstack=_parse_bool(msg[9]), - required_dst_info_num=int(msg[10].decode("ascii")), - row_start=int(msg[11].decode("ascii")), - span=int(msg[12].decode("ascii")), - ) - - def validate_fanout_frames( infos: list[EmbeddingTransferInfo], chunk: "EmbeddingChunk" ) -> str | None: @@ -411,14 +236,14 @@ def failure_exception(self): ) -class MooncakeEmbeddingManagerEncode(EmbeddingManagerBase): +class MooncakeEmbeddingManagerEncode(MooncakeEmbeddingManagerBase): """Encode-side (data source) manager: registers itself to the bootstrap server so the prefill receiver can find it, listens for the receiver's registration + per-request pre-alloc frames, and a worker thread issues the one-sided Mooncake write of the embedding. """ - def __init__(self, args: EmbeddingManagerArgs, embedding_args: "EmbeddingArgs"): + def __init__(self, args: EmbeddingManagerArgs, embedding_args: EmbeddingArgs): super().__init__(args, embedding_args, DisaggregationMode.ENCODE) # room -> {receiver_session -> EmbeddingTransferInfo} self.transfer_infos: dict[int, dict[str, EmbeddingTransferInfo]] = {} @@ -709,13 +534,13 @@ def _sync_status(self, info: EmbeddingTransferInfo, status: int) -> None: ) -class MooncakeEmbeddingManagerPrefill(EmbeddingManagerBase): +class MooncakeEmbeddingManagerPrefill(MooncakeEmbeddingManagerBase): """Prefill-side (data sink) manager: holds the discovery caches and a thread that consumes the encode side's per-request completion-status frames, marking the room Success once all expected responses arrive. """ - def __init__(self, args: EmbeddingManagerArgs, embedding_args: "EmbeddingArgs"): + def __init__(self, args: EmbeddingManagerArgs, embedding_args: EmbeddingArgs): super().__init__(args, embedding_args, DisaggregationMode.PREFILL) self.required_response_num: dict[int, int] = {} self.response_tracker: dict[int, set] = {} diff --git a/python/tokenspeed/runtime/disaggregation/embedding/encode_executor.py b/python/tokenspeed/runtime/pd/epd/encode_executor.py similarity index 99% rename from python/tokenspeed/runtime/disaggregation/embedding/encode_executor.py rename to python/tokenspeed/runtime/pd/epd/encode_executor.py index f2b39ed1bc2..f928b49e0d1 100644 --- a/python/tokenspeed/runtime/disaggregation/embedding/encode_executor.py +++ b/python/tokenspeed/runtime/pd/epd/encode_executor.py @@ -28,12 +28,12 @@ import torch -from tokenspeed.runtime.disaggregation.base.poll import TransferPoll -from tokenspeed.runtime.disaggregation.embedding.embedding_transfer import ( - MooncakeEmbeddingSender, -) from tokenspeed.runtime.multimodal.embedder import _item_token_count from tokenspeed.runtime.multimodal.inputs import Modality, MultimodalDataItem +from tokenspeed.runtime.pd.base.status import TransferPoll +from tokenspeed.runtime.pd.epd.embedding_transfer import ( + MooncakeEmbeddingSender, +) from tokenspeed.runtime.utils.env import envs logger = logging.getLogger(__name__) diff --git a/python/tokenspeed/runtime/disaggregation/embedding/encode_loop.py b/python/tokenspeed/runtime/pd/epd/encode_loop.py similarity index 95% rename from python/tokenspeed/runtime/disaggregation/embedding/encode_loop.py rename to python/tokenspeed/runtime/pd/epd/encode_loop.py index 410a025e815..3c3d82b13aa 100644 --- a/python/tokenspeed/runtime/disaggregation/embedding/encode_loop.py +++ b/python/tokenspeed/runtime/pd/epd/encode_loop.py @@ -51,8 +51,8 @@ EmbeddingCache, TieredEmbeddingCache, ) -from tokenspeed.runtime.disaggregation.embedding.encode_scheduler import EncodeScheduler -from tokenspeed.runtime.disaggregation.embedding.encode_worker import EncodeWorker +from tokenspeed.runtime.pd.epd.encode_scheduler import EncodeScheduler +from tokenspeed.runtime.pd.epd.encode_worker import EncodeWorker from tokenspeed.runtime.utils import get_colorful_logger, get_zmq_socket from tokenspeed.runtime.utils.env import envs @@ -102,7 +102,7 @@ def _build_manager_args(server_args, mapping): separate encode servers selected by the gateway; attention DP inside one encode server is rejected so it cannot be accidentally advertised as TP. """ - from tokenspeed.runtime.disaggregation.embedding.conn import EmbeddingManagerArgs + from tokenspeed.runtime.pd.epd.entities import EmbeddingManagerArgs if mapping.attn.dp_size != 1: raise ValueError( @@ -148,21 +148,19 @@ def _build_encode_worker(server_args, port_args, gpu_id, global_rank): """Assemble the encode worker: model + Mooncake manager + bootstrap server + executor + scheduler + cache, driven from the real ServerArgs.""" from tokenspeed.runtime.configs.model_config import ModelConfig - from tokenspeed.runtime.disaggregation.embedding.conn import ( - EmbeddingBootstrapServer, - ) - from tokenspeed.runtime.disaggregation.embedding.embedding_transfer import ( - EmbeddingArgs, - MooncakeEmbeddingManagerEncode, - ) - from tokenspeed.runtime.disaggregation.embedding.encode_executor import ( - DisaggEncodeExecutor, - ) from tokenspeed.runtime.execution.distributed_initializer import ( DistributedConfig, DistributedInitializer, ) from tokenspeed.runtime.execution.factory import create_model_runner + from tokenspeed.runtime.pd.epd.conn import MooncakeEmbeddingBootstrapServer + from tokenspeed.runtime.pd.epd.embedding_transfer import ( + MooncakeEmbeddingManagerEncode, + ) + from tokenspeed.runtime.pd.epd.encode_executor import ( + DisaggEncodeExecutor, + ) + from tokenspeed.runtime.pd.epd.entities import EmbeddingArgs mapping = server_args.mapping attn_tp_rank = mapping.attn.tp_rank @@ -215,7 +213,7 @@ def _build_encode_worker(server_args, port_args, gpu_id, global_rank): # look up the encode rank it pairs with (contiguous blocks of prefill ranks # share one encode rank; encode_tp=1 -> all prefill ranks pair encode rank 0). if attn_tp_rank == 0: - EmbeddingBootstrapServer(server_args.disaggregation_bootstrap_port) + MooncakeEmbeddingBootstrapServer(server_args.disaggregation_bootstrap_port) manager = MooncakeEmbeddingManagerEncode(manager_args, embedding_args) executor = DisaggEncodeExecutor(manager, model, device=device) diff --git a/python/tokenspeed/runtime/disaggregation/embedding/encode_scheduler.py b/python/tokenspeed/runtime/pd/epd/encode_scheduler.py similarity index 98% rename from python/tokenspeed/runtime/disaggregation/embedding/encode_scheduler.py rename to python/tokenspeed/runtime/pd/epd/encode_scheduler.py index b8235884c37..9555a7db5b8 100644 --- a/python/tokenspeed/runtime/disaggregation/embedding/encode_scheduler.py +++ b/python/tokenspeed/runtime/pd/epd/encode_scheduler.py @@ -18,7 +18,7 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -"""Encode-stage batching for EPD disaggregation. +"""Encode-stage batching for EPD transfer. The encode server runs the vision tower only, orchestrated in Python rather than the C++ KV scheduler, so all it needs is to batch pending vision items diff --git a/python/tokenspeed/runtime/disaggregation/embedding/encode_worker.py b/python/tokenspeed/runtime/pd/epd/encode_worker.py similarity index 99% rename from python/tokenspeed/runtime/disaggregation/embedding/encode_worker.py rename to python/tokenspeed/runtime/pd/epd/encode_worker.py index c3c852aeeca..b800bfc7e86 100644 --- a/python/tokenspeed/runtime/disaggregation/embedding/encode_worker.py +++ b/python/tokenspeed/runtime/pd/epd/encode_worker.py @@ -40,13 +40,13 @@ EmbeddingCache, TieredEmbeddingCache, ) -from tokenspeed.runtime.disaggregation.embedding.encode_scheduler import ( - EncodeScheduler, - PendingEncodeItem, -) from tokenspeed.runtime.multimodal.embedder import _item_token_count from tokenspeed.runtime.multimodal.inputs import MultimodalDataItem from tokenspeed.runtime.multimodal.shm_transport import ShmTensorHandle +from tokenspeed.runtime.pd.epd.encode_scheduler import ( + EncodeScheduler, + PendingEncodeItem, +) from tokenspeed.runtime.utils import get_colorful_logger logger = get_colorful_logger(__name__) diff --git a/python/tokenspeed/runtime/pd/epd/entities.py b/python/tokenspeed/runtime/pd/epd/entities.py new file mode 100644 index 00000000000..e6e17d3817a --- /dev/null +++ b/python/tokenspeed/runtime/pd/epd/entities.py @@ -0,0 +1,249 @@ +# Copyright (c) 2026 LightSeek Foundation +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +from __future__ import annotations + +import dataclasses +import struct +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + import torch + + +# Sentinel room (on-wire ascii) for the one-shot registration frame; per-request +# pre-alloc frames carry an integer room. +REGISTER_ROOM_SENTINEL = "None" + + +def _pack_ptr(ptr: int) -> bytes: + """Encode a device virtual address as 8 little-endian bytes (uint64).""" + return struct.pack("Q", ptr) + + +def _unpack_ptr(frame: bytes) -> int: + return struct.unpack("Q", frame)[0] + + +def _b(value: object) -> bytes: + return str(value).encode("ascii") + + +def _bool_frame(value: bool) -> bytes: + return b"1" if value else b"0" + + +def _parse_bool(frame: bytes) -> bool: + return frame == b"1" + + +@dataclasses.dataclass +class EmbeddingArgs: + """Per-rank buffer/engine info for an embedding endpoint. + + On the encode (sender) side the buffers hold the vision tower's output; on + the prefill (receiver) side they are the pre-registered receive buffers. A + ``deepstack`` buffer is present only for models that emit deepstack + embeddings (e.g. Qwen3.5); ``0`` means absent. + """ + + engine_rank: int + gpu_id: int + ib_device: str | None + embedding_data_ptr: int + embedding_data_len: int + deepstack_data_ptr: int = 0 + deepstack_data_len: int = 0 + + +class EmbeddingTransferError(Exception): + def __init__( + self, bootstrap_room: int, failure_reason: str, remote_endpoint: str = None + ): + super().__init__(failure_reason) + self.bootstrap_room = bootstrap_room + self.failure_reason = failure_reason + self.remote_endpoint = remote_endpoint + + def __str__(self): + if self.remote_endpoint: + return ( + "EmbeddingTransferError(" + f"bootstrap_room={self.bootstrap_room}, " + f"remote_endpoint={self.remote_endpoint}): {self.failure_reason}" + ) + else: + return ( + f"EmbeddingTransferError(bootstrap_room={self.bootstrap_room}): " + f"{self.failure_reason}" + ) + + +@dataclasses.dataclass +class EmbeddingChunk: + """One item's embedding queued for transfer (encode-side, in-process only). + + Not serialized to ZMQ: it lives on the encode manager's transfer queue. The + pointers reference the contiguous ``item.encoded`` / ``item.encoded_deepstack`` + tensors produced by the vision tower. + """ + + room: int + src_embedding_ptr: int + n_tokens: int + hidden: int + dtype: str + nbytes: int + src_deepstack_ptr: int = 0 + deepstack_width: int = 0 # hidden * num_deepstack; 0 == no deepstack + deepstack_nbytes: int = 0 + # CUDA event recorded on the encode loop's stream after the device copy that + # filled this chunk's ring slot. The transfer worker waits it before its + # one-sided RDMA read so the read never races the copy (ViT->send corruption + # hazard). None on CPU/no-CUDA. + copy_event: "torch.cuda.Event | None" = None + + +@dataclasses.dataclass +class EmbeddingTransferInfo: + """Receiver(prefill)->sender(encode) per-request pre-allocation frame. + + Tells the encode side where (``dst_embedding_ptr`` already includes this + request's row offset) and how big a transfer to issue. The RDMA write is + unchecked, so the encode asserts ``n_tokens``/``hidden``/``dtype`` against + the tensor it sends, else a mismatch silently writes a truncated/oversized + region. + + Row sharding: ``row_start`` + ``n_tokens`` (the SHARD's row count) select + the rows the encode writes at the shard-offset ``dst_embedding_ptr``; + ``span`` is the image's FULL row count, the cross-side token-count tripwire + regardless of shard geometry. Identity frames set ``row_start == 0`` and + ``n_tokens == span``. The encode validates shard geometry per frame: a + full-span write at a shard-offset pointer would corrupt neighboring image + rows in the same buffer. + """ + + room: int + endpoint: str + dst_port: int + mooncake_session_id: str + dst_embedding_ptr: int + dst_deepstack_ptr: int + n_tokens: int + hidden: int + dtype: str + has_deepstack: bool + required_dst_info_num: int + row_start: int = 0 + span: int = 0 + + def to_zmq(self) -> list[bytes]: + return [ + _b(self.room), + _b(self.endpoint), + _b(self.dst_port), + _b(self.mooncake_session_id), + _pack_ptr(self.dst_embedding_ptr), + _pack_ptr(self.dst_deepstack_ptr), + _b(self.n_tokens), + _b(self.hidden), + _b(self.dtype), + _bool_frame(self.has_deepstack), + _b(self.required_dst_info_num), + _b(self.row_start), + _b(self.span), + ] + + @classmethod + def from_zmq(cls, msg: list[bytes]) -> "EmbeddingTransferInfo": + # Length-guarded so a truncated frame is logged and dropped by the + # bootstrap listener instead of mis-parsing. + if len(msg) < 13: + raise ValueError( + f"malformed EmbeddingTransferInfo frame: {len(msg)} parts < 13" + ) + return cls( + room=int(msg[0].decode("ascii")), + endpoint=msg[1].decode("ascii"), + dst_port=int(msg[2].decode("ascii")), + mooncake_session_id=msg[3].decode("ascii"), + dst_embedding_ptr=_unpack_ptr(msg[4]), + dst_deepstack_ptr=_unpack_ptr(msg[5]), + n_tokens=int(msg[6].decode("ascii")), + hidden=int(msg[7].decode("ascii")), + dtype=msg[8].decode("ascii"), + has_deepstack=_parse_bool(msg[9]), + required_dst_info_num=int(msg[10].decode("ascii")), + row_start=int(msg[11].decode("ascii")), + span=int(msg[12].decode("ascii")), + ) + + +@dataclasses.dataclass +class EmbeddingArgsRegisterInfo: + """Receiver(prefill)->sender(encode) one-shot endpoint registration. + + Sent once per receiver rank with room == ``REGISTER_ROOM_SENTINEL`` so the + encode side records where to PUSH completion status. The buffer pointers + are the receiver's base receive buffers (per-item row offsets are carried + later, in :class:`EmbeddingTransferInfo`). + """ + + room: str + endpoint: str + dst_port: int + mooncake_session_id: str + dst_embedding_ptr: int + dst_deepstack_ptr: int + + def to_zmq(self) -> list[bytes]: + return [ + _b(self.room), + _b(self.endpoint), + _b(self.dst_port), + _b(self.mooncake_session_id), + _pack_ptr(self.dst_embedding_ptr), + _pack_ptr(self.dst_deepstack_ptr), + ] + + @classmethod + def from_zmq(cls, msg: list[bytes]) -> "EmbeddingArgsRegisterInfo": + return cls( + room=msg[0].decode("ascii"), + endpoint=msg[1].decode("ascii"), + dst_port=int(msg[2].decode("ascii")), + mooncake_session_id=msg[3].decode("ascii"), + dst_embedding_ptr=_unpack_ptr(msg[4]), + dst_deepstack_ptr=_unpack_ptr(msg[5]), + ) + + +@dataclasses.dataclass +class EmbeddingManagerArgs: + """Connection config for the embedding Mooncake endpoint. + + Embedding transfer has a single DP group today. ``tp_size`` is the number + of encode/prefill endpoint ranks that participate in that group; the shared + bootstrap layer still receives it as ``world_size`` with ``dp_size=1``. + """ + + bootstrap_port: int + tp_size: int + bootstrap_host: str | None = None diff --git a/python/tokenspeed/runtime/disaggregation/embedding/prefill_receiver.py b/python/tokenspeed/runtime/pd/epd/prefill_receiver.py similarity index 99% rename from python/tokenspeed/runtime/disaggregation/embedding/prefill_receiver.py rename to python/tokenspeed/runtime/pd/epd/prefill_receiver.py index a7b3cd9a215..ae039cfe46f 100644 --- a/python/tokenspeed/runtime/disaggregation/embedding/prefill_receiver.py +++ b/python/tokenspeed/runtime/pd/epd/prefill_receiver.py @@ -56,12 +56,12 @@ logger = logging.getLogger(__name__) -from tokenspeed.runtime.disaggregation.base.poll import TransferPoll -from tokenspeed.runtime.disaggregation.embedding.embedding_transfer import ( - MooncakeEmbeddingReceiver, -) from tokenspeed.runtime.multimodal.embedder import _item_token_count from tokenspeed.runtime.multimodal.inputs import MultimodalDataItem +from tokenspeed.runtime.pd.base.status import TransferPoll +from tokenspeed.runtime.pd.epd.embedding_transfer import ( + MooncakeEmbeddingReceiver, +) from tokenspeed.runtime.utils.env import envs # (manager, bootstrap_addr, bootstrap_room) -> receiver. Defaults to the real @@ -816,11 +816,10 @@ def build_prefill_embedding_manager(server_args, global_rank, is_multimodal_acti if server_args.disaggregation_mode != "prefill" or not is_multimodal_active: return None - from tokenspeed.runtime.disaggregation.embedding.conn import EmbeddingManagerArgs - from tokenspeed.runtime.disaggregation.embedding.embedding_transfer import ( - EmbeddingArgs, + from tokenspeed.runtime.pd.epd.embedding_transfer import ( MooncakeEmbeddingManagerPrefill, ) + from tokenspeed.runtime.pd.epd.entities import EmbeddingArgs, EmbeddingManagerArgs emb_mgr_args = EmbeddingManagerArgs( bootstrap_port=server_args.disaggregation_bootstrap_port, diff --git a/python/tokenspeed/runtime/disaggregation/kv/factory.py b/python/tokenspeed/runtime/pd/factory.py similarity index 91% rename from python/tokenspeed/runtime/disaggregation/kv/factory.py rename to python/tokenspeed/runtime/pd/factory.py index 072b20c2f7c..5b8d1ca7c65 100644 --- a/python/tokenspeed/runtime/disaggregation/kv/factory.py +++ b/python/tokenspeed/runtime/pd/factory.py @@ -18,13 +18,12 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -"""Factories for disaggregation KV transfer helpers.""" +"""Factories for PD KV transfer helpers.""" -from tokenspeed.runtime.disaggregation.kv.decode_executor import DisaggDecodeExecutor -from tokenspeed.runtime.disaggregation.kv.mooncake.entities import ManagerArgs -from tokenspeed.runtime.disaggregation.kv.prefill_executor import DisaggPrefillExecutor -from tokenspeed.runtime.disaggregation.kv.types import KVArgs -from tokenspeed.runtime.disaggregation.kv.utils import TransferBackend +from tokenspeed.runtime.pd.decode_executor import DisaggDecodeExecutor +from tokenspeed.runtime.pd.mooncake.entities import KVArgs, KVManagerArgs +from tokenspeed.runtime.pd.prefill_executor import DisaggPrefillExecutor +from tokenspeed.runtime.pd.utils import TransferBackend def _get_contiguous_buf_unit_lens(pool, item_lens): @@ -128,7 +127,7 @@ def get_kv_args( def create_kv_transfer( mode: str, backend: TransferBackend, - args: ManagerArgs, + args: KVManagerArgs, kv_args: KVArgs, gloo_group, page_size, diff --git a/python/tokenspeed/runtime/disaggregation/kv/kv_events.py b/python/tokenspeed/runtime/pd/kv_events.py similarity index 100% rename from python/tokenspeed/runtime/disaggregation/kv/kv_events.py rename to python/tokenspeed/runtime/pd/kv_events.py diff --git a/python/tokenspeed/runtime/disaggregation/kv/mooncake/__init__.py b/python/tokenspeed/runtime/pd/mooncake/__init__.py similarity index 79% rename from python/tokenspeed/runtime/disaggregation/kv/mooncake/__init__.py rename to python/tokenspeed/runtime/pd/mooncake/__init__.py index 35367b6e400..92d95f8ff33 100644 --- a/python/tokenspeed/runtime/disaggregation/kv/mooncake/__init__.py +++ b/python/tokenspeed/runtime/pd/mooncake/__init__.py @@ -18,17 +18,17 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -from tokenspeed.runtime.disaggregation.kv.mooncake.conn import MooncakeKVBootstrapServer -from tokenspeed.runtime.disaggregation.kv.mooncake.decode import ( +from tokenspeed.runtime.pd.mooncake.conn import MooncakeKVBootstrapServer +from tokenspeed.runtime.pd.mooncake.decode import ( MooncakeKVManagerDecode, ) -from tokenspeed.runtime.disaggregation.kv.mooncake.prefill import ( +from tokenspeed.runtime.pd.mooncake.prefill import ( MooncakeKVManagerPrefill, ) -from tokenspeed.runtime.disaggregation.kv.mooncake.receiver import ( +from tokenspeed.runtime.pd.mooncake.receiver import ( MooncakeKVReceiver, ) -from tokenspeed.runtime.disaggregation.kv.mooncake.sender import ( +from tokenspeed.runtime.pd.mooncake.sender import ( MooncakeKVSender, ) diff --git a/python/tokenspeed/runtime/disaggregation/kv/mooncake/async_conn.py b/python/tokenspeed/runtime/pd/mooncake/async_conn.py similarity index 98% rename from python/tokenspeed/runtime/disaggregation/kv/mooncake/async_conn.py rename to python/tokenspeed/runtime/pd/mooncake/async_conn.py index 33776b54944..c1bc842919b 100644 --- a/python/tokenspeed/runtime/disaggregation/kv/mooncake/async_conn.py +++ b/python/tokenspeed/runtime/pd/mooncake/async_conn.py @@ -27,20 +27,21 @@ import numpy as np import numpy.typing as npt -from tokenspeed.runtime.disaggregation.base.poll import TransferPoll -from tokenspeed.runtime.disaggregation.kv.mooncake.entities import ( +from tokenspeed.runtime.pd.base.status import TransferPoll +from tokenspeed.runtime.pd.mooncake.entities import ( + KVArgs, TransferInfo, TransferKVChunk, ) -from tokenspeed.runtime.disaggregation.kv.mooncake.prefill import ( +from tokenspeed.runtime.pd.mooncake.prefill import ( MooncakeKVManagerPrefill as MooncakeKVManager, ) -from tokenspeed.runtime.disaggregation.kv.types import KVArgs -from tokenspeed.runtime.disaggregation.kv.utils import ( +from tokenspeed.runtime.pd.utils import ( + DisaggregationMode, + FastQueue, StepCounter, group_concurrent_contiguous, ) -from tokenspeed.runtime.disaggregation.utils import DisaggregationMode, FastQueue from tokenspeed.runtime.utils import get_colorful_logger from tokenspeed.runtime.utils.server_args import ServerArgs diff --git a/python/tokenspeed/runtime/disaggregation/kv/mooncake/conn.py b/python/tokenspeed/runtime/pd/mooncake/conn.py similarity index 86% rename from python/tokenspeed/runtime/disaggregation/kv/mooncake/conn.py rename to python/tokenspeed/runtime/pd/mooncake/conn.py index c85924a8e7d..0b4e50c0b8a 100644 --- a/python/tokenspeed/runtime/disaggregation/kv/mooncake/conn.py +++ b/python/tokenspeed/runtime/pd/mooncake/conn.py @@ -20,15 +20,14 @@ from __future__ import annotations -from tokenspeed.runtime.disaggregation.base.bootstrap import DisaggBootstrapServer -from tokenspeed.runtime.disaggregation.base.manager import DisaggManagerBase -from tokenspeed.runtime.disaggregation.kv.mooncake.entities import ManagerArgs -from tokenspeed.runtime.disaggregation.kv.types import KVArgs -from tokenspeed.runtime.disaggregation.mooncake_transfer_engine import ( +from tokenspeed.runtime.metrics.collector import KVTransferMetrics +from tokenspeed.runtime.pd.base.bootstrap import DisaggBootstrapServerBase +from tokenspeed.runtime.pd.base.manager import DisaggManagerBase +from tokenspeed.runtime.pd.base.mooncake_engine import ( MooncakeTransferEngine, ) -from tokenspeed.runtime.disaggregation.utils import DisaggregationMode -from tokenspeed.runtime.metrics.collector import KVTransferMetrics +from tokenspeed.runtime.pd.mooncake.entities import KVArgs, KVManagerArgs +from tokenspeed.runtime.pd.utils import DisaggregationMode from tokenspeed.runtime.utils.network import get_local_ip_by_remote @@ -38,7 +37,7 @@ class MooncakeKVManagerBase(DisaggManagerBase): def __init__( self, - args: ManagerArgs, + args: KVManagerArgs, kv_args: KVArgs, disaggregation_mode: DisaggregationMode, ): @@ -69,10 +68,9 @@ def __init__( else: self.kv_transfer_metrics = None - # Build the Mooncake data-plane engine here (the vendor binding stays in - # the mooncake package, not in the neutral base) and inject it. self.kv_args - # is set above so register_buffer_to_engine (called by the base) sees the - # KV buffers. + # Build the Mooncake data-plane engine here and inject it into the + # transfer manager. self.kv_args is set above so register_buffer_to_engine + # (called by the base) sees the KV buffers. engine = MooncakeTransferEngine( hostname=get_local_ip_by_remote(), gpu_id=kv_args.gpu_id, @@ -91,7 +89,7 @@ def register_buffer_to_engine(self): self.engine.register(state_data_ptr, state_data_len) -class MooncakeKVBootstrapServer(DisaggBootstrapServer): +class MooncakeKVBootstrapServer(DisaggBootstrapServerBase): """KV bootstrap rendezvous: the shared server plus the prefill-side MLA / kv-page length fields the decode side needs in the parallel-info sync.""" diff --git a/python/tokenspeed/runtime/disaggregation/kv/mooncake/decode.py b/python/tokenspeed/runtime/pd/mooncake/decode.py similarity index 96% rename from python/tokenspeed/runtime/disaggregation/kv/mooncake/decode.py rename to python/tokenspeed/runtime/pd/mooncake/decode.py index 881031968b0..013ee5fbba6 100644 --- a/python/tokenspeed/runtime/disaggregation/kv/mooncake/decode.py +++ b/python/tokenspeed/runtime/pd/mooncake/decode.py @@ -26,11 +26,10 @@ import numpy as np import requests -from tokenspeed.runtime.disaggregation.base.poll import TransferPoll -from tokenspeed.runtime.disaggregation.kv.mooncake.conn import MooncakeKVManagerBase -from tokenspeed.runtime.disaggregation.kv.mooncake.entities import ManagerArgs -from tokenspeed.runtime.disaggregation.kv.types import KVArgs -from tokenspeed.runtime.disaggregation.utils import DisaggregationMode +from tokenspeed.runtime.pd.base.status import TransferPoll +from tokenspeed.runtime.pd.mooncake.conn import MooncakeKVManagerBase +from tokenspeed.runtime.pd.mooncake.entities import KVArgs, KVManagerArgs +from tokenspeed.runtime.pd.utils import DisaggregationMode from tokenspeed.runtime.utils import ( get_colorful_logger, ) @@ -77,7 +76,7 @@ def parse_prefill_status_message( class MooncakeKVManagerDecode(MooncakeKVManagerBase): def __init__( self, - args: ManagerArgs, + args: KVManagerArgs, kv_args: KVArgs, ): super().__init__(args, kv_args, DisaggregationMode.DECODE) diff --git a/python/tokenspeed/runtime/disaggregation/kv/mooncake/entities.py b/python/tokenspeed/runtime/pd/mooncake/entities.py similarity index 87% rename from python/tokenspeed/runtime/disaggregation/kv/mooncake/entities.py rename to python/tokenspeed/runtime/pd/mooncake/entities.py index 48d1b5655b8..d34f5ebc2e6 100644 --- a/python/tokenspeed/runtime/disaggregation/kv/mooncake/entities.py +++ b/python/tokenspeed/runtime/pd/mooncake/entities.py @@ -24,11 +24,36 @@ import numpy as np import numpy.typing as npt -from tokenspeed.runtime.disaggregation.kv.transfer_plan import ( +from tokenspeed.runtime.pd.transfer_plan import ( TransferFragment, decode_transfer_fragments, ) -from tokenspeed.runtime.disaggregation.kv.utils import PageTransferMetadata +from tokenspeed.runtime.pd.utils import PageTransferMetadata + + +@dataclasses.dataclass +class KVArgs: + engine_rank: int + kv_data_ptrs: list[int] + kv_data_lens: list[int] + kv_item_lens: list[int] + offsets: list[tuple[int]] + aux_data_ptrs: list[int] + aux_data_lens: list[int] + aux_item_lens: list[int] + ib_device: str + gpu_id: int + target_layer_num: int + draft_layer_num: int + kv_layer_ids: list[int] = dataclasses.field(default_factory=list) + kv_unit_lens: list[int] = dataclasses.field(default_factory=list) + state_data_ptrs: list[int] = dataclasses.field(default_factory=list) + state_data_lens: list[int] = dataclasses.field(default_factory=list) + state_item_lens: list[int] = dataclasses.field(default_factory=list) + state_unit_lens: list[int] = dataclasses.field(default_factory=list) + state_type: str = "none" + state_layer_ids: list[int] = dataclasses.field(default_factory=list) + mamba_offsets: list[int] | None = None class KVTransferError(Exception): @@ -191,7 +216,7 @@ def from_zmq(cls, msg: list[bytes]): @dataclasses.dataclass -class ManagerArgs: +class KVManagerArgs: bootstrap_port: int dist_init_addr: str diff --git a/python/tokenspeed/runtime/disaggregation/kv/mooncake/prefill.py b/python/tokenspeed/runtime/pd/mooncake/prefill.py similarity index 98% rename from python/tokenspeed/runtime/disaggregation/kv/mooncake/prefill.py rename to python/tokenspeed/runtime/pd/mooncake/prefill.py index 80c4eff4ef8..8dd480d0bb4 100644 --- a/python/tokenspeed/runtime/disaggregation/kv/mooncake/prefill.py +++ b/python/tokenspeed/runtime/pd/mooncake/prefill.py @@ -29,26 +29,27 @@ import numpy.typing as npt import requests -from tokenspeed.runtime.disaggregation.base.poll import TransferPoll -from tokenspeed.runtime.disaggregation.kv.mooncake.conn import MooncakeKVManagerBase -from tokenspeed.runtime.disaggregation.kv.mooncake.entities import ( +from tokenspeed.runtime.pd.base.status import TransferPoll +from tokenspeed.runtime.pd.mooncake.conn import MooncakeKVManagerBase +from tokenspeed.runtime.pd.mooncake.entities import ( + KVArgs, KVArgsRegisterInfo, - ManagerArgs, + KVManagerArgs, TransferIndexResolution, TransferInfo, TransferKVChunk, ) -from tokenspeed.runtime.disaggregation.kv.transfer_plan import ( +from tokenspeed.runtime.pd.transfer_plan import ( BufferKind, TransferFragment, ) -from tokenspeed.runtime.disaggregation.kv.types import KVArgs -from tokenspeed.runtime.disaggregation.kv.utils import ( +from tokenspeed.runtime.pd.utils import ( + DisaggregationMode, + FastQueue, PageTransferMetadata, StepCounter, group_concurrent_contiguous, ) -from tokenspeed.runtime.disaggregation.utils import DisaggregationMode, FastQueue from tokenspeed.runtime.utils import ( get_colorful_logger, ) @@ -65,7 +66,7 @@ class MooncakeKVManagerPrefill(MooncakeKVManagerBase): def __init__( self, - args: ManagerArgs, + args: KVManagerArgs, kv_args: KVArgs, ): super().__init__(args, kv_args, DisaggregationMode.PREFILL) @@ -1094,6 +1095,6 @@ def _register_to_bootstrap(self): ) -from tokenspeed.runtime.disaggregation.kv.mooncake.sender import MooncakeKVSender +from tokenspeed.runtime.pd.mooncake.sender import MooncakeKVSender __all__ = ["MooncakeKVManagerPrefill", "MooncakeKVSender"] diff --git a/python/tokenspeed/runtime/disaggregation/kv/mooncake/receiver.py b/python/tokenspeed/runtime/pd/mooncake/receiver.py similarity index 98% rename from python/tokenspeed/runtime/disaggregation/kv/mooncake/receiver.py rename to python/tokenspeed/runtime/pd/mooncake/receiver.py index 67524cc3aa5..d9472eeedd3 100644 --- a/python/tokenspeed/runtime/disaggregation/kv/mooncake/receiver.py +++ b/python/tokenspeed/runtime/pd/mooncake/receiver.py @@ -28,9 +28,9 @@ import requests import zmq -from tokenspeed.runtime.disaggregation.base.poll import TransferPoll -from tokenspeed.runtime.disaggregation.kv.mooncake.entities import KVTransferError -from tokenspeed.runtime.disaggregation.kv.transfer_plan import ( +from tokenspeed.runtime.pd.base.status import TransferPoll +from tokenspeed.runtime.pd.mooncake.entities import KVTransferError +from tokenspeed.runtime.pd.transfer_plan import ( BufferKind, BufferLayout, ParallelLayout, @@ -38,7 +38,7 @@ RankTransferPlan, encode_transfer_fragments, ) -from tokenspeed.runtime.disaggregation.kv.utils import ( +from tokenspeed.runtime.pd.utils import ( PageTransferMetadata, ) from tokenspeed.runtime.utils import ( @@ -48,7 +48,7 @@ logger = get_colorful_logger(__name__) -from tokenspeed.runtime.disaggregation.kv.mooncake.decode import ( +from tokenspeed.runtime.pd.mooncake.decode import ( MooncakeKVManagerDecode, PrefillParallelInfo, ) diff --git a/python/tokenspeed/runtime/disaggregation/kv/mooncake/sender.py b/python/tokenspeed/runtime/pd/mooncake/sender.py similarity index 97% rename from python/tokenspeed/runtime/disaggregation/kv/mooncake/sender.py rename to python/tokenspeed/runtime/pd/mooncake/sender.py index 361040f3b8a..afb8e205734 100644 --- a/python/tokenspeed/runtime/disaggregation/kv/mooncake/sender.py +++ b/python/tokenspeed/runtime/pd/mooncake/sender.py @@ -23,9 +23,9 @@ import numpy as np import numpy.typing as npt -from tokenspeed.runtime.disaggregation.base.poll import TransferPoll -from tokenspeed.runtime.disaggregation.kv.mooncake.entities import KVTransferError -from tokenspeed.runtime.disaggregation.kv.utils import PageTransferMetadata +from tokenspeed.runtime.pd.base.status import TransferPoll +from tokenspeed.runtime.pd.mooncake.entities import KVTransferError +from tokenspeed.runtime.pd.utils import PageTransferMetadata from tokenspeed.runtime.utils import get_colorful_logger logger = get_colorful_logger(__name__) diff --git a/python/tokenspeed/runtime/disaggregation/kv/prefill_executor.py b/python/tokenspeed/runtime/pd/prefill_executor.py similarity index 98% rename from python/tokenspeed/runtime/disaggregation/kv/prefill_executor.py rename to python/tokenspeed/runtime/pd/prefill_executor.py index cc2a60d6400..edcd2beb69d 100644 --- a/python/tokenspeed/runtime/disaggregation/kv/prefill_executor.py +++ b/python/tokenspeed/runtime/pd/prefill_executor.py @@ -22,13 +22,13 @@ import numpy as np -from tokenspeed.runtime.disaggregation.base.poll import TransferPoll -from tokenspeed.runtime.disaggregation.kv.mooncake.prefill import ( +from tokenspeed.runtime.pd.base.bootstrap import BootstrapInfo +from tokenspeed.runtime.pd.base.status import TransferPoll +from tokenspeed.runtime.pd.mooncake.prefill import ( MooncakeKVManagerPrefill, MooncakeKVSender, ) -from tokenspeed.runtime.disaggregation.kv.types import BootstrapInfo -from tokenspeed.runtime.disaggregation.kv.utils import ( +from tokenspeed.runtime.pd.utils import ( TransferBackend, poll_and_all_reduce, ) diff --git a/python/tokenspeed/runtime/disaggregation/kv/transfer_plan.py b/python/tokenspeed/runtime/pd/transfer_plan.py similarity index 100% rename from python/tokenspeed/runtime/disaggregation/kv/transfer_plan.py rename to python/tokenspeed/runtime/pd/transfer_plan.py diff --git a/python/tokenspeed/runtime/disaggregation/kv/utils.py b/python/tokenspeed/runtime/pd/utils.py similarity index 91% rename from python/tokenspeed/runtime/disaggregation/kv/utils.py rename to python/tokenspeed/runtime/pd/utils.py index 8b2300fb4c3..b5f96ba67a0 100755 --- a/python/tokenspeed/runtime/disaggregation/kv/utils.py +++ b/python/tokenspeed/runtime/pd/utils.py @@ -18,7 +18,7 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -"""Shared helpers for disaggregation runtime components.""" +"""Shared helpers for PD transfer runtime components.""" from __future__ import annotations @@ -26,6 +26,7 @@ import dataclasses import os import random +import threading import warnings from collections import deque from enum import Enum @@ -49,11 +50,46 @@ logger = get_colorful_logger(__name__) +class DisaggregationMode(Enum): + NULL = "null" + PREFILL = "prefill" + DECODE = "decode" + ENCODE = "encode" + + +class FastQueue: + class Empty(Exception): + """Exception raised when the queue is empty.""" + + pass + + def __init__(self): + self._buf = deque() + self._cond = threading.Condition() + + def put(self, item): + with self._cond: + self._buf.append(item) + self._cond.notify() + + def get(self): + with self._cond: + while not self._buf: + self._cond.wait() + return self._buf.popleft() + + def get_nowait(self): + with self._cond: + if not self._buf: + raise FastQueue.Empty() + return self._buf.popleft() + + def poll_and_all_reduce(pollers, gloo_group): """Poll transfer state and all-reduce the result across the gloo group.""" # At a certain probability, mark the poll as failed to simulate failure. if FAILURE_PROB > 0: - from tokenspeed.runtime.disaggregation.base.poll import TransferPoll + from tokenspeed.runtime.pd.base.status import TransferPoll polls = [ ( @@ -112,19 +148,19 @@ class KVClassType(Enum): def get_kv_class(transfer_backend: TransferBackend, class_type: KVClassType): if transfer_backend == TransferBackend.MOONCAKE: - from tokenspeed.runtime.disaggregation.kv.mooncake.conn import ( + from tokenspeed.runtime.pd.mooncake.conn import ( MooncakeKVBootstrapServer, ) - from tokenspeed.runtime.disaggregation.kv.mooncake.decode import ( + from tokenspeed.runtime.pd.mooncake.decode import ( MooncakeKVManagerDecode, ) - from tokenspeed.runtime.disaggregation.kv.mooncake.prefill import ( + from tokenspeed.runtime.pd.mooncake.prefill import ( MooncakeKVManagerPrefill, ) - from tokenspeed.runtime.disaggregation.kv.mooncake.receiver import ( + from tokenspeed.runtime.pd.mooncake.receiver import ( MooncakeKVReceiver, ) - from tokenspeed.runtime.disaggregation.kv.mooncake.sender import ( + from tokenspeed.runtime.pd.mooncake.sender import ( MooncakeKVSender, ) @@ -138,16 +174,16 @@ def get_kv_class(transfer_backend: TransferBackend, class_type: KVClassType): return class_mapping.get(class_type) if transfer_backend == TransferBackend.MOONCAKE_ASYNC: - from tokenspeed.runtime.disaggregation.kv.mooncake.async_conn import ( + from tokenspeed.runtime.pd.mooncake.async_conn import ( MooncakeAsyncKVManager, ) - from tokenspeed.runtime.disaggregation.kv.mooncake.conn import ( + from tokenspeed.runtime.pd.mooncake.conn import ( MooncakeKVBootstrapServer, ) - from tokenspeed.runtime.disaggregation.kv.mooncake.receiver import ( + from tokenspeed.runtime.pd.mooncake.receiver import ( MooncakeKVReceiver, ) - from tokenspeed.runtime.disaggregation.kv.mooncake.sender import ( + from tokenspeed.runtime.pd.mooncake.sender import ( MooncakeKVSender, ) diff --git a/test/runtime/distributed/test_epd_encode.py b/test/runtime/distributed/test_epd_encode.py index 46fcd37aceb..2b41814f6ce 100644 --- a/test/runtime/distributed/test_epd_encode.py +++ b/test/runtime/distributed/test_epd_encode.py @@ -29,33 +29,33 @@ import pytest import torch -import tokenspeed.runtime.disaggregation.embedding.encode_loop as encode_loop +import tokenspeed.runtime.pd.epd.encode_loop as encode_loop from tokenspeed.runtime.cache.embedding_cache import ( EmbeddingCache, TieredEmbeddingCache, ) -from tokenspeed.runtime.disaggregation.base.poll import TransferPoll -from tokenspeed.runtime.disaggregation.embedding.encode_executor import ( +from tokenspeed.runtime.multimodal.inputs import ( + Modality, + MultimodalDataItem, +) +from tokenspeed.runtime.pd.base.status import TransferPoll +from tokenspeed.runtime.pd.epd.encode_executor import ( DisaggEncodeExecutor, assign_encoded_embeddings, ) -from tokenspeed.runtime.disaggregation.embedding.encode_loop import ( +from tokenspeed.runtime.pd.epd.encode_loop import ( _embedding_cache_bytes, _make_embedding_cache, _maybe_install_encoder_cudagraph, ) -from tokenspeed.runtime.disaggregation.embedding.encode_scheduler import ( +from tokenspeed.runtime.pd.epd.encode_scheduler import ( EncodeScheduler, PendingEncodeItem, ) -from tokenspeed.runtime.disaggregation.embedding.encode_worker import ( +from tokenspeed.runtime.pd.epd.encode_worker import ( EncodeRequest, EncodeWorker, ) -from tokenspeed.runtime.multimodal.inputs import ( - Modality, - MultimodalDataItem, -) class _FakeExecutor: @@ -411,7 +411,7 @@ def __init__(self): def test_feature_fn_image_routes_through_image_encoder_seam(): - from tokenspeed.runtime.disaggregation.embedding.encode_executor import ( + from tokenspeed.runtime.pd.epd.encode_executor import ( DisaggEncodeExecutor, ) diff --git a/test/runtime/distributed/test_epd_transfer.py b/test/runtime/distributed/test_epd_transfer.py index 3801c654159..e0d2063d896 100644 --- a/test/runtime/distributed/test_epd_transfer.py +++ b/test/runtime/distributed/test_epd_transfer.py @@ -29,29 +29,29 @@ import pytest import torch -from tokenspeed.runtime.disaggregation.base.poll import TransferPoll -from tokenspeed.runtime.disaggregation.embedding.conn import ( - EmbeddingTransferError, +from tokenspeed.runtime.multimodal.inputs import ( + Modality, + MultimodalDataItem, ) -from tokenspeed.runtime.disaggregation.embedding.embedding_transfer import ( +from tokenspeed.runtime.pd.base.status import TransferPoll +from tokenspeed.runtime.pd.epd.embedding_transfer import ( + MooncakeEmbeddingSender, + shard_payload, + validate_fanout_frames, +) +from tokenspeed.runtime.pd.epd.entities import ( REGISTER_ROOM_SENTINEL, EmbeddingArgsRegisterInfo, EmbeddingChunk, + EmbeddingTransferError, EmbeddingTransferInfo, - MooncakeEmbeddingSender, - shard_payload, - validate_fanout_frames, ) -from tokenspeed.runtime.disaggregation.embedding.prefill_receiver import ( +from tokenspeed.runtime.pd.epd.prefill_receiver import ( DONE, receive_encoded_embeddings, shard_rows, start_embedding_receive, ) -from tokenspeed.runtime.multimodal.inputs import ( - Modality, - MultimodalDataItem, -) # Each merged concern keeps its own per-test setup (the shard # pointer-math tests need the TOKENSPEED_EPD_RECV_POOL_SLOTS=0 path, the @@ -189,8 +189,15 @@ def test_sender_failure_exception_raises_and_clears(): mgr = _SenderFakeMgr() s = MooncakeEmbeddingSender(mgr, "h:9", bootstrap_room=3) mgr.failure_records[3] = "boom on rank 1" - with pytest.raises(EmbeddingTransferError): + with pytest.raises(EmbeddingTransferError) as exc_info: s.failure_exception() + assert exc_info.value.bootstrap_room == 3 + assert exc_info.value.failure_reason == "boom on rank 1" + assert exc_info.value.remote_endpoint == "h:9" + assert str(exc_info.value) == ( + "EmbeddingTransferError(bootstrap_room=3, remote_endpoint=h:9): " + "boom on rank 1" + ) assert 3 not in mgr.request_status # cleared assert s.conclude_state == TransferPoll.Failed @@ -355,7 +362,7 @@ def pre_alloc(self, **kwargs): def _shard_setup(monkeypatch): - import tokenspeed.runtime.disaggregation.embedding.prefill_receiver as er + import tokenspeed.runtime.pd.epd.prefill_receiver as er _ShardReceiver.created.clear() # Pin the LEGACY per-request buffer path: the pointer-math assertions below @@ -499,7 +506,7 @@ def _epd(item: MultimodalDataItem, *, room: int, host: str, port: int): def _recv_setup(monkeypatch): - import tokenspeed.runtime.disaggregation.embedding.prefill_receiver as er + import tokenspeed.runtime.pd.epd.prefill_receiver as er _FakeReceiver.created.clear() # Small pool defaults so each test's fresh fake engine doesn't allocate diff --git a/test/runtime/distributed/test_pd_transfer_plan.py b/test/runtime/distributed/test_pd_transfer_plan.py index 6f4518b1cfa..6d68a81136c 100644 --- a/test/runtime/distributed/test_pd_transfer_plan.py +++ b/test/runtime/distributed/test_pd_transfer_plan.py @@ -1,7 +1,7 @@ -from tokenspeed.runtime.disaggregation.kv.mooncake.receiver import ( +from tokenspeed.runtime.pd.mooncake.receiver import ( _build_buffer_layout_pair, ) -from tokenspeed.runtime.disaggregation.kv.transfer_plan import ( +from tokenspeed.runtime.pd.transfer_plan import ( BufferKind, ParallelLayout, PDTransferPlanner, diff --git a/test/runtime/test_kv_events.py b/test/runtime/test_kv_events.py index d64af20b216..a28574ead86 100644 --- a/test/runtime/test_kv_events.py +++ b/test/runtime/test_kv_events.py @@ -3,7 +3,7 @@ import msgspec import pytest -from tokenspeed.runtime.disaggregation.kv.kv_events import ( +from tokenspeed.runtime.pd.kv_events import ( BlockRemoved, BlockStored, EventPublisherFactory, From 3348835d27cf90d81bb272db9b34bc8e481aeac8 Mon Sep 17 00:00:00 2001 From: chenht2022 Date: Wed, 8 Jul 2026 09:41:20 +0000 Subject: [PATCH 6/7] fix: update pd manager args import Signed-off-by: chenht2022 --- python/tokenspeed/runtime/engine/event_loop.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python/tokenspeed/runtime/engine/event_loop.py b/python/tokenspeed/runtime/engine/event_loop.py index 5959fd81f90..c101991424e 100644 --- a/python/tokenspeed/runtime/engine/event_loop.py +++ b/python/tokenspeed/runtime/engine/event_loop.py @@ -82,7 +82,7 @@ drain_scheduler_kv_events, scheduler_kv_events_to_wire_events, ) -from tokenspeed.runtime.pd.mooncake.entities import ManagerArgs +from tokenspeed.runtime.pd.mooncake.entities import KVManagerArgs from tokenspeed.runtime.pd.prefill_executor import DisaggPrefillExecutor from tokenspeed.runtime.sampling.sampling_params import SamplingParams from tokenspeed.runtime.utils import ( @@ -478,7 +478,7 @@ def __init__( draft_token_to_kv_pool, mamba_pool, ) - pd_manager_args = ManagerArgs( + pd_manager_args = KVManagerArgs( bootstrap_port=server_args.disaggregation_bootstrap_port, dist_init_addr=server_args.dist_init_addr, world_size=server_args.world_size or mapping.world_size, From b1b0631446e677c8e71a0fe7d795d94b3e87e200 Mon Sep 17 00:00:00 2001 From: chenht2022 Date: Wed, 8 Jul 2026 12:10:24 +0000 Subject: [PATCH 7/7] fix Signed-off-by: chenht2022 --- .../runtime/pd/epd/prefill_receiver.py | 75 +++++++++++++++---- test/runtime/distributed/test_epd_transfer.py | 23 ++++++ 2 files changed, 82 insertions(+), 16 deletions(-) diff --git a/python/tokenspeed/runtime/pd/epd/prefill_receiver.py b/python/tokenspeed/runtime/pd/epd/prefill_receiver.py index ae039cfe46f..4b4192415a6 100644 --- a/python/tokenspeed/runtime/pd/epd/prefill_receiver.py +++ b/python/tokenspeed/runtime/pd/epd/prefill_receiver.py @@ -86,6 +86,14 @@ _pending_dereg: deque = deque() +def _record_current_stream_event(tensor: torch.Tensor) -> torch.cuda.Event | None: + if not tensor.is_cuda: + return None + event = torch.cuda.Event() + torch.cuda.current_stream(tensor.device).record_event(event) + return event + + def _lazy_deregister(engine: Any, tensors: list[tuple[torch.Tensor, int]]) -> None: _pending_dereg.append((time.monotonic() + _DEREG_DELAY_S, engine, tensors)) _sweep_deregister() @@ -111,7 +119,7 @@ class _RecvBufferPool: a `local access violation work queue error` that kills the QP. The pool registers ONE region for the engine's lifetime, so the sender's cached mapping can never go stale; requests lease slots, the publish path clones the - landed rows out, and the slot returns immediately. + landed rows out, and CUDA-backed slots return only after that clone completes. Failure path: a FAILED job may still have an in-flight remote write targeting its slot, which under a single lifetime MR would land SILENTLY in the next @@ -128,11 +136,37 @@ def __init__(self, engine: Any, device: Any, slot_bytes: int, n_slots: int): engine.register(self.buf.data_ptr(), self.buf.numel()) self._free = list(range(n_slots)) self._quarantine: deque = deque() # (release_due_monotonic, slot) + self._pending_release: deque = deque() # (cuda_event, slot) - def lease(self, nbytes: int) -> int | None: + def _sweep_pending_release(self) -> None: + kept = deque() + while self._pending_release: + event, slot = self._pending_release.popleft() + try: + ready = event.query() + except Exception: # noqa: BLE001 -- avoid permanently losing a slot + logger.warning( + "EPD recv pool: CUDA event query failed; releasing slot anyway", + exc_info=True, + ) + ready = True + if ready: + self._free.append(slot) + else: + kept.append((event, slot)) + self._pending_release = kept + + def _sweep_quarantine(self) -> None: now = time.monotonic() while self._quarantine and self._quarantine[0][0] <= now: self._free.append(self._quarantine.popleft()[1]) + + def sweep(self) -> None: + self._sweep_pending_release() + self._sweep_quarantine() + + def lease(self, nbytes: int) -> int | None: + self.sweep() if nbytes > self.slot_bytes or not self._free: return None return self._free.pop() @@ -144,6 +178,13 @@ def view(self, slot: int, nbytes: int, dtype: torch.dtype, shape) -> torch.Tenso def release(self, slot: int) -> None: self._free.append(slot) + def release_after_copy(self, slot: int, copied_tensor: torch.Tensor) -> None: + event = _record_current_stream_event(copied_tensor) + if event is None: + self.release(slot) + else: + self._pending_release.append((event, slot)) + def quarantine(self, slot: int, delay_s: float) -> None: self._quarantine.append((time.monotonic() + delay_s, slot)) @@ -275,13 +316,15 @@ class EmbeddingReceiveJob: Buffer lifetime: by default the receive target is a leased slot from the lifetime-registered :class:`_RecvBufferPool`; on DONE the landed rows are - cloned onto ``item.encoded`` and the slot returns immediately (no MR churn, - see the pool docstring). Deepstack models, oversized items, pool + cloned onto ``item.encoded`` and the slot is reused after that copy completes + (no MR churn, see the pool docstring). Deepstack models, oversized items, pool exhaustion, or ``TOKENSPEED_EPD_RECV_POOL_SLOTS=0`` fall back to a per-request - buffer registered on start and lazily deregistered after publish. The GPU - cost per request is roughly ``n_tokens * hidden * dtype.itemsize`` (plus - ``* (1 + num_deepstack)`` with deepstack); the caller should cap the - number of in-flight jobs accordingly. + buffer registered on start and lazily deregistered after publish. Pooled + slots stay leased until the CUDA copy into ``item.encoded`` has completed, + so a following request cannot overwrite rows still being cloned. The GPU cost + per request is roughly ``n_tokens * hidden * dtype.itemsize`` (plus ``* (1 + + num_deepstack)`` with deepstack); the caller should cap the number of + in-flight jobs accordingly. Idempotent re-`start`/poll: items whose ``item.encoded`` is already set (chunked prefill re-runs the receive per Path-4 forward on the same item) are @@ -547,10 +590,10 @@ def poll(self) -> str: # Every image of every item has landed; publish and reclaim. Pooled # path: clone the landed rows OUT of the slot (item.encoded must outlive - # the lease) and return the slot at once. Legacy path: hand the buffer - # itself to item.encoded and queue the registration for DEFERRED drop - # (the lazy entry holds the tensor ref, so the allocator cannot recycle - # a still-registered address). + # the lease) and release the slot only after that copy completes. Legacy + # path: hand the buffer itself to item.encoded and queue the registration + # for DEFERRED drop (the lazy entry holds the tensor ref, so the allocator + # cannot recycle a still-registered address). for it in self._items: any_sharded = any(it.sharded) if it.pool is not None: @@ -565,7 +608,7 @@ def poll(self) -> str: else it.recv_main.clone() ) it.item.encoded_deepstack = None - it.pool.release(it.pool_slot) + it.pool.release_after_copy(it.pool_slot, it.item.encoded) else: # Legacy path. When sharded, the packed buffers are smaller than # the image and cannot alias item.encoded, so build separate full @@ -641,9 +684,9 @@ def reassemble(self, nccl_group: Any, group_ranks: Sequence[int]) -> None: Broadcasts target ``item.encoded`` (the PUBLISHED tensor), never ``recv_main``: on the pooled path the publish step cloned the rows out - and RELEASED the slot, so ``recv_main`` may already belong to the next - tenant; on the legacy path ``item.encoded`` IS ``recv_main``, so the - two are equivalent there. + and queued the slot for reuse after the clone completes, so ``recv_main`` + may later belong to the next tenant; on the legacy path ``item.encoded`` + IS ``recv_main``, so the two are equivalent there. """ if self._shard_size <= 1 or self._status is not DONE: return diff --git a/test/runtime/distributed/test_epd_transfer.py b/test/runtime/distributed/test_epd_transfer.py index e0d2063d896..ea654edced2 100644 --- a/test/runtime/distributed/test_epd_transfer.py +++ b/test/runtime/distributed/test_epd_transfer.py @@ -518,6 +518,29 @@ def _recv_setup(monkeypatch): er._pending_dereg.clear() +def test_recv_pool_release_waits_for_clone_event(monkeypatch): + import tokenspeed.runtime.pd.epd.prefill_receiver as er + + class _FakeEvent: + def __init__(self): + self.ready = False + + def query(self): + return self.ready + + event = _FakeEvent() + monkeypatch.setattr(er, "_record_current_stream_event", lambda _tensor: event) + pool = er._RecvBufferPool(_RecvFakeEngine(), "cpu", slot_bytes=64, n_slots=1) + + slot = pool.lease(8) + assert slot == 0 + pool.release_after_copy(slot, torch.empty(1)) + assert pool.lease(8) is None + + event.ready = True + assert pool.lease(8) == 0 + + def test_receive_sizes_buffers_per_item_no_deepstack(): items = [ _epd(_recv_item(6), room=11, host="h0", port=7001),