mirror of
https://github.com/lightseekorg/tokenspeed.git
synced 2026-12-04 10:26:50 +08:00
## Summary Every engine rank now runs the control plane in Rust, as [RFC 0002](docs/rfcs/0002-rust-control-plane.md) proposes. A rank is one `ts-host` process: the scheduling loop, request state and output processing, the per-round agreements among ranks, control operations, PD and EPD transfers with their planning, the L3 storage tier, grammars, the expert rebalance, metrics and KV events run in Rust, and the embedded interpreter runs only the data plane (`DeviceHandle`, models, kernels) on the host's forward thread. An EPD encode server's ranks are `ts-host` processes too, in an encode mode whose data plane runs only the vision tower. The Python event loop and its hooks are deleted in the same change; there is no second path. `docs/design/event-loop.md` is rewritten against the Rust loop. The branch is rebased onto current `main`; the control-plane changes `main` made meanwhile are ported to the Rust host in their own commit (asynchronous L3 #2483, the grammar host node #2542, the EAGLE-4 settle #2547, #2596, #2605). Commits: 1. `feat(engine): run every engine rank on the Rust control plane (RFC 0002)` 2. `fix(engine): cancel grammar-queued requests on a drain, drop finished aborts` 3. `chore(engine): port main's control-plane changes to the Rust host` 4. `refactor(engine): fold the pump thread into the forward thread`: one forward thread runs the data plane's device work; the control thread runs the completion queries itself, taking the GIL for the call (a commit waits on the torch copy event, which releases it), with no native event waits. 5. `feat(engine): run the L3 storage tier in the Rust host`: the L3 executor, its stores (Mooncake through the store's C ABI, an in-memory store for tests) and its metrics are the new `ts-l3`, so neither the per-round storage poll nor the I/O workers take the GIL. 6. `fix(engine): answer every refused request as a client error`: every ingress refusal finishes with status 400, so a wire client can tell the request's own error from an engine failure. 7. `fix(engine): close the Rust control plane review's findings`: PD rooms no request claimed expire instead of blocking memory releases, a landing without its first token fails its room, a drain cancels the EPD requests still receiving, frozen rounds plan their cache work without L3, a closed frontend input stops the engine, and the L3 reports ride the round's relay exchange. 8. `feat(engine): port the PD transfer planner to ts-pd`: the cache transfer contract, block manifests, routes between unequal Prefill and Decode rank sets (head partitions, pipeline stages, KVP owner filters) and copy planning, checked against a fixture of every call the Python planner's tests made. 9. `feat(engine): plan PD transfers in the host, serve the bootstrap from Rust`: the PD peer's threads no longer call into Python. The scheduler facade exposes a batch's transfer columns and block tables, the forward thread stages each plan's remote stream for the peer, layerwise chunks are armed in Rust, and the bootstrap server is `ts-pd`'s. 10. `feat(engine): receive EPD embeddings in the host`: the prefill node's embedding receiver is `ts-pd`'s (encode-rank handshakes, receive slots, the agreement on landed embeddings); the data plane keeps the receive pools' memory, the publish copies and the row-shard reassembly. 11. `feat(engine): run EPD encode ranks in the host`: `ts-control`'s encode loop relays, batches and leases send-ring slots, rank-identically across the attention-TP group, and `ts-pd`'s sender writes the embeddings; the data plane keeps the vision tower, the embedding cache and the ring copies. ## What changes **`tokenspeed-engine/`** (Cargo workspace): | Crate | Role | | --- | --- | | `ts-wire` | The engine IPC schema and its msgpack codec, checked byte for byte against fixtures the Python encoder writes | | `ts-client` | A frontend's connection to the engines: handshake, routing across attention-DP ranks, output streams, aborts, control operations | | `ts-py` | `tokenspeed_engine._native`: `ts-client` for the Python frontend, the launcher's bootstrap server (`tokenspeed_engine.BootstrapServer`), and the L3 executor for tests (`tokenspeed_engine.L3Executor`) | | `ts-collective` | CPU collectives among a rank's peers over a TCP mesh | | `ts-scheduler` | The C++ scheduler compiled into the binary, with a `cxx` facade; its nanobind module is a built-in of the embedded interpreter | | `ts-control` | The loop and its subsystems: ingress, output commit, cache-op acknowledgment, the L3 agreement, pause and memory release, the same-round gate for weight operations, grammars, EPLB, KV events, PD bookkeeping, EPD staging; and an EPD encode rank's loop | | `ts-grammar` | Grammar compilation and matchers on xgrammar's C++ library | | `ts-metrics` | Prometheus multiprocess files written directly, and the events the node's plugin relay runs output plugins on | | `ts-mooncake` / `ts-pd` | The Mooncake transfer engine and store client through their C APIs; the PD transfer peer with its planning (routes, block manifests, layerwise chunks, copies); the bootstrap server; the EPD embedding receiver and sender | | `ts-l3` | The L3 storage tier's Host-only executor: object naming, the Host pool's layout and KV-parallel ownership, bounded queues and workers, backend health, the stores | | `ts-host` | The rank binary: an engine rank, or an EPD encode rank | **Python.** Deleted: the event loop and its hooks, the request handler, the generation output processor, the data-parallel controller, the engine core client and pickle IPC, the Python headless msgpack transport, the Python PD transfer executors and Mooncake sender/receiver, the PD transfer planner (`pd/transfer_plan.py`, `pd/mooncake/`, the manifest half of `pd/cache_protocol.py`) and the aiohttp bootstrap server, the grammar manager and xgrammar backend, the EPD prefill hooks and embedding receive job, the EPD encode loop, worker, executor and scheduler with their Mooncake manager and sender (`pd/base` with them), the Python L3 executor and its stores, and the control-plane tests that covered them (their behaviour is covered by `ts-control`'s unit and serving tests, which run the real scheduler against a stand-in device, by `ts-pd`'s and `ts-l3`'s tests, and by the planning fixture). Kept: the data plane; for PD, the cache transfer contract built at startup and the device fences a plan's remote stream waits on (`pd/host_peer.py`); for EPD, the receive pools and their publish (`epd/prefill_receive.py`) and an encode rank's vision tower, embedding cache and send ring (`epd/encode_host.py`); the L3 namespace identity and settings (`cache/l3/identity.py`, `factory.py`); and `AsyncLLM` as the in-process frontend over `ts-py`. `engine/rust_host.py` builds a rank inside the host. **Launching.** Every launch path (`Engine`, `ts serve`, `ts serve --headless`) starts its ranks through `start_rust_host`, an EPD encode server too (its ranks bind the request channel the frontend pushes encode requests to). `TOKENSPEED_HOST_BINARY` overrides the binary the new `tokenspeed-engine` wheel installs. A rank keeps its `tokenspeed::scheduler_tp…` process title, an encode rank its `tokenspeed::encode_tp…`. **Packaging and CI.** `tokenspeed-engine` is a setuptools package that builds `_native` and `ts-host` with cargo. `python/pyproject.toml` depends on it. The CI installers and the source-built Dockerfiles build it from the checkout (installing a Rust toolchain when the runner has none), the engine workflow builds the wheel, and engine changes trigger the GPU workflows. ## Deviations from the RFC's Phase 4 - `AsyncLLM` stays, as the in-process frontend over `ts-py`: tokenization, detokenization, stop strings, `n > 1` fan-out and the `Engine` API stay in Python, and so does the Python encoding of requests onto the wire. - `ts serve` keeps its gRPC servicer, now over that `AsyncLLM`. SMG's msgpack backend does not yet carry MRoPE multimodal inputs, EPD encode handshakes, shared-memory features or top-k/prompt logprobs, which the CI model jobs need. Moving `ts serve` onto SMG's msgpack mode, and deleting the servicer, waits for SMG. - The control thread waits on a launched forward's torch copy event (vendor-neutral, releasing the GIL) instead of native event handles through `tokenspeed-kernel` C entries. - The L3 store client moves into the host instead of staying on the data plane. ## Behaviour changes - `--zmq-msgpack` is removed: every engine speaks the msgpack wire. - PD needs a `tokenspeed-mooncake` build with the TokenSpeed C entry points (`libtokenspeed_transfer_engine.so`), and the Mooncake L3 store one that ships the store's C ABI (`libmooncake_store.so`); a companion change to the packaging repository adds both. Until that wheel is published, `TOKENSPEED_MOONCAKE_LIBRARY` and `TOKENSPEED_MOONCAKE_STORE_LIBRARY` name local builds, and the CI jobs that install the wheel the runtime requires and need either library fail: the Mooncake L3 workflow's live tests and the PD and EPD serving jobs. - A grammar that does not compile, or timed out past its retries, aborts its request with status 400, and a grammar unusable on one rank fails its request alike on every rank. - Every request the engine refuses at ingress (invalid sampling parameters, logprobs it cannot compute, too many stop token ids, a session id, a disaggregated engine's missing bootstrap) finishes with status 400; before, only the stop token ids refusal carried it. - An EPD prefill node receives embeddings into its receive pool only: with `TOKENSPEED_EPD_RECV_POOL_SLOTS=0` every handshaked item fails, an item larger than a slot fails with a message naming `TOKENSPEED_EPD_RECV_POOL_SLOT_MB`, and an exhausted pool keeps the request waiting within its deadline (before, these fell back to a buffer registered per request). A deepstack model's deepstack rows share their item's slot (its bytes split 1 : num_deepstack), so the pool stays within the bytes the cache budget leaves out. - An EPD encode rank allocates its send ring at startup (same size as before, which it allocated on the first send) and batches the waiting items in arrival order, those the embedding cache holds first (before, sorted by request id). An item whose prefill ranks did not all ask within the bootstrap timeout now fails toward the ones that asked, instead of leaving them to their own timeout, and a request for an already failed room is answered at once. - The host's Mooncake engines start with `MC_USE_IPV6` when the local address is IPv6, as the Python engine did. The PD and EPD messages and the bootstrap routes are unchanged. ## Validation - `cargo fmt --check`, `cargo clippy --all-targets -- -D warnings` and `cargo test` pass for the whole workspace; the `ts-pd` transfer tests pass over RDMA, and `ts-l3`'s live tests (round trips, objects outliving their writer, owner relocation, tenant isolation, recovery after a master restart) against a local master, with a local Mooncake build. - `pytest` over `test/` (without the distributed and model e2e files): the failures that remain also fail on `main` here (kernels this Hopper node lacks, checkpoints and tokenizers not cached offline) or only in the full run's order (log-capture tests that pass alone). The L3 Python tests (scheduler tail round trips through the in-memory and live stores, the settings factory, the GPU D2H/PUT/GET/H2D byte tests including native Mooncake over TCP and RDMA, and the two-GPU KV-parallel owner relocation over RDMA) pass on the Rust executor. - Parity with `main`'s Python control plane on one 8-GPU Hopper node, Qwen3-0.6B-Base, headless over the msgpack wire, 27 mixed requests (sampling, stop tokens, prefix hits, chunked prefill): identical tokens, finish reasons and cached-token counts in each of single GPU, TP2, attention DP2, DUMMY speculation (TP1 and TP2), forced retraction, L3 with the in-memory store, and L3 with a Mooncake store over RDMA (single GPU, and TP2 at concurrency 27). - L3 across a restart: a fresh engine (empty L1/L2) restores a 2048-token prefix from Mooncake and continues exactly as a device prefix hit does, single GPU and TP2; a flush deletes the namespace and a weight update moves later pages to the new version's namespace; the L3 metrics are exported. - PD 1P1D (Qwen3-0.6B-Base, both roles on the Rust host), concurrency 1: every greedy request is identical to the aggregated run (sampled requests draw from a different stream across the two roles). - PD planning: the Rust planner gives every call the Python planner's test suite made the same answer or refusal (the recorded fixture). PD 1P1D on GPU (Qwen3-0.6B-Base) is token-identical to the branch before the planner moved, for TP 1→1 (concurrency 1 and 8, layerwise and full sends), 2→1, 1→2 and 2→2 (concurrency 1; at 8 the earlier build varies run to run by itself). - EPD: the Rust sender and receiver pass live RDMA tests together (one prefill rank, two row-sharded ranks, a failed room, an incomplete fanout). On GPU, Qwen3.5-0.8B behind SMG's EPD gateway, in 1E1P1D, encode TP2 with prefill TP2, and encode TP1 with a row-sharded prefill TP2, 15 sequential and concurrent requests (18 images, with two-image requests and embedding-cache hits): every image's embedding reached every prefill rank byte for byte as the encode rank computed it; the new receiver also served the Python encode node unchanged. - Earlier on this branch, before the rebase: `ts serve` completions and chat matched `main`, each subsystem was checked against the Python loop (also KV and context parallelism, layerwise PD, EPLB, grammars, multimodal inputs, KV events, control operations and logprobs), and DeepSeek-V4.1-Flash PD 1P1D (TP4+TP4, DSpark) served coherent text with the same run-to-run variation as `main`. - Seen on `main` too, not changed here: an idle attention-DP rank of a dense model crashes in its zero-row forward (`silu_and_mul`), which L3's pre-admission prefetch makes easy to hit with DP2. ## Known gaps - PyPI wheels for `tokenspeed-engine` are not published yet; `ts-host` links the libpython of the interpreter that builds it, so portable wheels need a release recipe of their own. The release Dockerfile installs published packages and needs that release first. - Heterogeneous-TP PD sends a destination-contiguous, source-strided fragment row by row; the Python sender packed it on the GPU first. - Not run on GPU here: pipeline-parallel serving, the capturable grammar path (needs a newer host compiler), request token history (needs an out-of-tree model) and `--emulate-rank-zero` (AMD only). Their control-plane paths are covered by the serving tests. - SMG's `--servicer-impl rust` launcher imports the deleted Python launch internals and needs an SMG update. - SMG's encode servicer ingests requests off its event loop by default through the deleted engine core client; until SMG submits through `AsyncLLM.submit_encode` there as well, run it with `EPD_INGEST_OFFLOOP=0`. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: FC-Li <robert_lexis@163.com> Co-authored-by: longcat-ia-team <longcat_ia_team@meituan.com>
218 lines
6.7 KiB
Python
218 lines
6.7 KiB
Python
# 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 dataclasses import dataclass
|
|
from math import prod
|
|
|
|
from tokenspeed.runtime.layers.attention.kv_cache.recipes.plan import (
|
|
CacheFieldLayout,
|
|
CacheGroupLayout,
|
|
CacheMemoryPlan,
|
|
CachePlaneLayout,
|
|
cache_dtype_bytes,
|
|
)
|
|
from tokenspeed.runtime.layers.attention.kv_cache.recipes.spec import (
|
|
CacheGroupSpec,
|
|
)
|
|
from tokenspeed.runtime.pd.cache_protocol import (
|
|
CacheFieldPartition,
|
|
CacheFieldTransferSpec,
|
|
CacheProducerSchedule,
|
|
CacheTransferContract,
|
|
CacheTransferSchema,
|
|
)
|
|
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class _TestCacheField:
|
|
"""Unplanned field input used by the compact PD test builders."""
|
|
|
|
field_id: str
|
|
dtype: str
|
|
page_zero_offset: int
|
|
page_stride_bytes: int
|
|
shape: tuple[int, ...]
|
|
partition: CacheFieldPartition | None
|
|
producer_step: int | None
|
|
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class _TestCacheGroup:
|
|
"""Semantic group input awaiting the shared memory plan."""
|
|
|
|
group_id: str
|
|
attn_kind: str
|
|
prefix_granularity: int
|
|
sliding_window_tokens: int | None
|
|
fields: tuple[_TestCacheField, ...]
|
|
cache_blocks_per_lcm_block: int
|
|
# KVP owners the group's virtual blocks are dealt to; 1 is replicated.
|
|
shard_count: int
|
|
|
|
@property
|
|
def transfer_policy(self) -> str:
|
|
return "latest_snapshot" if self.attn_kind == "state" else "full_suffix"
|
|
|
|
|
|
def segment(
|
|
field_id: str,
|
|
*,
|
|
shape: tuple[int, ...] = (1,),
|
|
dtype: str = "uint8",
|
|
offset: int = 0,
|
|
stride: int | None = None,
|
|
axis: int | None = None,
|
|
extent: int | None = None,
|
|
parts: tuple[int, ...] = (),
|
|
producer_step: int | None = None,
|
|
) -> _TestCacheField:
|
|
payload = prod(shape) * cache_dtype_bytes(dtype)
|
|
partition = (
|
|
None
|
|
if extent is None
|
|
else CacheFieldPartition(
|
|
axis=0 if axis is None else axis,
|
|
global_extent=extent,
|
|
global_parts=parts,
|
|
)
|
|
)
|
|
return _TestCacheField(
|
|
field_id,
|
|
dtype,
|
|
offset,
|
|
payload if stride is None else stride,
|
|
shape,
|
|
partition,
|
|
producer_step,
|
|
)
|
|
|
|
|
|
def group(
|
|
group_id: str,
|
|
*segments: _TestCacheField,
|
|
attn_kind: str = "full_history",
|
|
q: int = 2,
|
|
window: int | None = None,
|
|
packing: int = 1,
|
|
shard_count: int = 1,
|
|
) -> _TestCacheGroup:
|
|
return _TestCacheGroup(
|
|
group_id, attn_kind, q, window, segments, packing, shard_count
|
|
)
|
|
|
|
|
|
def layout(
|
|
*groups: _TestCacheGroup,
|
|
block_size: int = 2,
|
|
capacity: int = 16,
|
|
page_bytes: int = 32,
|
|
) -> CacheTransferContract:
|
|
plan_groups = tuple(
|
|
CacheGroupLayout(
|
|
group_id=entry.group_id,
|
|
cache_blocks_per_lcm_block=entry.cache_blocks_per_lcm_block,
|
|
page_count=(1 + (capacity - 1) * entry.cache_blocks_per_lcm_block),
|
|
)
|
|
for entry in groups
|
|
)
|
|
specs = tuple(
|
|
(
|
|
CacheGroupSpec(
|
|
group_id=entry.group_id,
|
|
attn_kind=entry.attn_kind,
|
|
transfer_policy=entry.transfer_policy,
|
|
replayable=False,
|
|
shard_count=entry.shard_count,
|
|
)
|
|
if entry.attn_kind == "state"
|
|
else CacheGroupSpec(
|
|
group_id=entry.group_id,
|
|
attn_kind=entry.attn_kind,
|
|
rows_per_page=entry.prefix_granularity,
|
|
entry_stride_tokens=1,
|
|
sliding_window_tokens=entry.sliding_window_tokens,
|
|
transfer_policy=entry.transfer_policy,
|
|
replayable=False,
|
|
shard_count=entry.shard_count,
|
|
)
|
|
)
|
|
for entry in groups
|
|
)
|
|
|
|
fields: list[CacheFieldLayout] = []
|
|
planes: list[CachePlaneLayout] = []
|
|
for group_position, entry in enumerate(groups):
|
|
for field_position, field in enumerate(entry.fields):
|
|
plane_id = f"test.{group_position}.{field_position}.{field.field_id}"
|
|
planes.append(
|
|
CachePlaneLayout(
|
|
plane_id=plane_id,
|
|
bytes_per_lcm_block=field.page_stride_bytes,
|
|
arena_offset_bytes=field.page_zero_offset,
|
|
)
|
|
)
|
|
fields.append(
|
|
CacheFieldLayout(
|
|
group_id=entry.group_id,
|
|
field_id=field.field_id,
|
|
plane_id=plane_id,
|
|
shape=field.shape,
|
|
dtype=field.dtype,
|
|
field_offset_bytes=0,
|
|
page_stride_bytes=field.page_stride_bytes,
|
|
)
|
|
)
|
|
|
|
return CacheTransferContract(
|
|
plan=CacheMemoryPlan(
|
|
prefix_granularity=block_size,
|
|
lcm_block_bytes=page_bytes,
|
|
num_lcm_blocks=capacity - 1,
|
|
groups=plan_groups,
|
|
planes=tuple(planes),
|
|
fields=tuple(fields),
|
|
),
|
|
group_specs=specs,
|
|
transfer_schema=CacheTransferSchema(
|
|
tuple(
|
|
CacheFieldTransferSpec(field.field_id, field.partition)
|
|
for entry in groups
|
|
for field in entry.fields
|
|
if field.partition is not None
|
|
)
|
|
),
|
|
)
|
|
|
|
|
|
def producer_schedule(
|
|
*groups: _TestCacheGroup,
|
|
steps: int,
|
|
) -> CacheProducerSchedule:
|
|
fields_by_step: list[list[str]] = [[] for _ in range(steps)]
|
|
for entry in groups:
|
|
for field in entry.fields:
|
|
assert field.producer_step is not None
|
|
fields_by_step[field.producer_step].append(field.field_id)
|
|
return CacheProducerSchedule(
|
|
tuple(tuple(step_fields) for step_fields in fields_by_step)
|
|
)
|