Commit Graph
69 Commits
Author SHA1 Message Date
Hang Yuandlongcat-ia-team cbd98b38e6 feat(epd): gate decode admission on prefill embedding readiness (#4080)
## Summary

With early prefill/decode (PD) allocation, decode can reserve KV pages
and send a destination manifest while prefill is still waiting for an
external encoder. The manifest starts prefill's timeout for an unclaimed
room. A slow image can arrive within the embedding deadline and still
fail KV transfer. In the meantime, that request occupies decode capacity
that text requests could use.

This change lets decode admit a multimodal request once prefill has
received all its embeddings and claimed the PD room on every required
rank. Text requests continue through ordinary admission. Enable the
policy with `--epd-admission-max-waiting` on both workers and
`--epd-embedding-budget-mib` on prefill. It applies to early PD pools
where all multimodal requests use external encoders.

## Changes

- **Prefill.** Reserve the full request's embedding bytes on each
receiving rank before advertising a destination. Reuse receive slots as
individual items land. Return the byte credit after the published
storage, including tensor aliases, is released and device copies and
reads have completed. Prefill still scans staged requests and agrees on
their status each round.
- **Decode.** Hold waiting requests in a bounded host table ahead of the
scheduler and KV receiver. Only attention-TP rank 0 queries prefill, off
the scheduling thread. It relays ready and failed decisions through the
existing replica control channel so all ranks admit the same requests in
the same order.
- **PD bootstrap.** Add `/epd-route` to the existing bootstrap service
so decode can discover each prefill rank's `/ready` endpoint. A lookup
for an unknown room returns pending and leaves the room table untouched.
Bind the KV handshake to the route version that reported readiness so a
restarted rank cannot inherit a stale decision.
- **Multimodal execution.** Add `replace_received_encoding` so model
adapters that project received codes into embeddings can preserve the
tensor's reconstruction state across prefill chunks.

## Test Plan

- Passed 227 PD unit and integration tests and 146 control-plane serving
tests. Regressions cover an embedding arriving after the unclaimed-room
timeout, a route replacement after readiness, cancellation, and
consistent admission across eight decode TP ranks.
- Passed 81 Python embedding-receiver tests, including storage-alias
lifetime and byte accounting. One CUDA-dependent test was skipped.
`pre-commit run --all-files` passed.
- In an end-to-end run, held one prefill rank pending. A concurrent text
request completed while the three-image request waited. After release,
the model identified all three images in order. Also exercised rejection
at the prefill byte limit and recovery with a fresh request.
- Verified image order after permuting the inputs. Both three-turn
EvalScope sessions completed, with the expected image content and order
in all six responses.

---------

Signed-off-by: cnStevenYu <cnstevenyu1991@163.com>
Co-authored-by: longcat-ia-team <longcat_ia_team@meituan.com>
2026-12-02 14:26:21 +08:00
FC.Li 86a6ee2efe refactor(plugins): unify registration with lazy implementation references (#3939)
Plugin startup currently splits configuration hooks from runtime
registration, then undoes and replays them for headless startup.
Reporters and model policies can need those registrations before the
replay, and registering models eagerly imports unrelated
implementations.

Use one `ensure_loaded()` and `register()` lifecycle for every launcher.
Register model profiles and implementation references independently,
index built-in model, backend, cache and sampling declarations without
importing their implementations, and resolve implementations during
component construction or kernel planning. Reporters retain early
validation and relay provenance without requiring an empty argument
hook.

Kernel registries own resolved callables and stateful instances. This
preserves shared weight preparation, concurrent construction, rollback,
overrides and hot reload. Optional provider callbacks retain capability
checks at selection and ABI checks at initialization. Existing concrete
registrations remain supported; the design and migration boundary are
documented in `docs/design/plugin-registration.md`.

Validation:

- 212 kernel registration, selection, planning, rollback and hot-reload
tests passed.
- 180 runtime-plugin, argument, draft wiring and draft-quantization
tests passed after rebasing on main.
- 9 provider-admission tests passed, including validating an optional
MoE provider's name before loading its SDK.
- 21 registration and metrics tests passed, including relay subprocess
delivery and cleanup; broader cache and runtime integration also passed.
- Fresh GPU wire-engine smoke passed for prefill, decode and
prefix-cache resume in eager and decode-graph modes, with explicit
Triton MoE selection.
- `pre-commit run --all-files` passed.

Ascend hardware execution was not available. GPU cache failures in a
separate DeepSeek V4.1 suite were reproduced on unchanged main in the
same environment.

---------

Signed-off-by: FC-Li <33271309+FC-Li@users.noreply.github.com>
Signed-off-by: FC.Li <33271309+FC-Li@users.noreply.github.com>
2026-11-30 20:40:14 +08:00
dongjiyingdjy bb58198f6e feat(cache): share one Host L2 pool across prefill ranks (#3421)
## Summary

One Host L2 cache shared by the prefill and fused ranks of a deployment,
so a turn that lands on another rank or node reuses the KV an earlier
rank computed. Ports the shared L2 design
(https://github.com/lightseekorg/tokenspeed/pull/2661/changes/ee30bd5bd76eb8fdfc2c0d4ad3a30bd809ec7e7f)
of https://github.com/lightseekorg/tokenspeed/pull/2661 to main's
scheduler and event loop. Off by default: without `--shared-l2-config`,
plans and the loop are unchanged.

- **Owner** (one process): index, prefix matching, placement, eviction
and pins; no bytes pass through it. Its `SharedL2Pool` reuses the Host
L2 matching, retention and eviction code. Its request loop runs in the
engine host (`ts-control/src/shared_l2/owner.rs`); Python launches it
and builds the pool.
- **Provider** (one or more per node): RDMA-registered host memory, on
the engine's transfer engine.
- **Rank**: the scheduler's Host tier holds proxy entries for the pool
pages a lookup pinned, so admission, junction cuts and load-back stay
the Host L2 code. Writes are fed from the write-through store queue. The
rank's client of the owner runs in the engine host
(`ts-control/src/shared_l2`): lookups on the loop's thread, writes and
notices on threads of its own, blocks copied directly between Device
memory and providers over RDMA, loads layer by layer behind the forward.

## Behaviour

- Lookups: before a plan, the loop asks the owner about every waiting
prompt not yet looked up in one request and waits for the answer,
bounded by `request_timeout_ms`, as in the earlier shared L2 design. It
is the one blocking call on the per-round path and is registered as such
in `docs/design/event-loop.md`; under attention DP the other ranks'
rounds wait with it.
- Failures stop the rank's engine (under attention DP, the instance), as
a failed forward does: a lookup, write, release, touch or ping that the
owner does not answer or answers with an error, a failed RDMA copy, a
failed load-back, a panic of one of the client's threads. A lookup with
no matching prefix is a miss, and a block the pool has no room for is
not written.
- Lone-request compaction waits while pool writes are queued: a queued
write pins nothing, and its RDMA read is not ordered with the plan's
page copies.
- First version: attention TP 1, pipeline parallelism 1, no KV sharding
(the pool's keys carry a shard field that is always 0 here; KV sharding
is the follow-up), prefill and fused roles, write-through only. Requires
prefix caching and `--disable-kvstore`; refuses L3, KV offload, peer
prefix sharing, the memory saver, retraction snapshots, startup
requests, weight loads and forward reloads.
- Known limits:
- An owner that is paused or unreachable for longer than
`request_timeout_ms` stops every rank that uses the pool. The owner, its
providers and the ranks restart together; after an owner restart a rank
stops on the timeout of its next request.
- A rank process frozen for longer than the owner's client timeout can
read or write pool pages the owner has given to another rank (clear the
pool after such a freeze).
- The owner serves on one thread, socket reads and writes included. A
lookup queued behind others waits about 0.1 ms for each hit ahead of it
(103 us per queued hit with 41 KB requests, 36 us of it receiving the
request; the Python owner of this pull request's earlier commits took 88
us, its ZeroMQ library reading on a separate thread for input and
output). A reply larger than the socket buffer (about 3 MB) to a client
that has stopped reading holds the owner until that client is gone.
- With `TOKENSPEED_CACHE_EVENT_LOG=1`, a rank that joined a pool logs no
`prefix_load_completed` record: the engine host runs its loads.
Recording them there is a follow-up.

## Performance

K3 NVFP4, attention DP8 + MoE EP8 on two GB300 nodes, 2 x 32 GiB pool,
chunked prefill 512, 32K max context. One pass per arm. The multi-turn
and cold-pool arms ran one after the other on the same node pair; the
same-rank row used two node pairs. 1P1D ran with
`--disaggregation-decode-allocation-policy deferred`. Outputs are
token-identical with and without the pool.

| Median | without pool | with pool |
|---|---|---|
| Fused, 32 conversations x 4 turns, next turn on another rank: TTFT,
turn 1 | 2.29 s | 2.30 s |
| same: turns 2, 3 and 4 | 2.88, 3.64 and 4.35 s | 1.53, 1.77 and 1.78 s
|
| same: throughput | 1.86 requests per second | 2.77 requests per second
|
| same: tokens computed | 1054K | 352K |
| Fused, cold pool, every lookup misses: TTFT | 2.27 s | 2.26 s |
| Fused, same rank, Device copy evicted: TTFT, turn 2 | 8.75–9.29 s |
1.86 s |
| 1P1D, pool on P, 16 conversations x 3 turns: prefill time, turn 1 |
4.78 s | 3.92 s |
| same: turns 2 and 3 | 5.29 and 6.53 s | 2.83 and 2.96 s |
| same: throughput | 1.18 requests per second | 1.68 requests per second
|

A fused turn that misses the pool is not slower than without a pool. The
1P1D first turn differs between the two arms; with one pass each its
cause is not separated. One lookup round trip takes 0.4 ms at the median
(0.3 ms a miss, 0.6 ms a hit) and 1.1 ms at most (216 lookups).

## Test plan

- CPU: scheduler gtest (1785) and Python tests (463); Rust tests of the
loop, the pool's client and its owner over the real C++ pool, the host
and the facade (638 + 53); runtime pytest of the rank's join, the
owner's command line and the data path.
- GB300, with pool vs without (on the head before the last merge of
main): GPU data-path tests; token-identical output after a reload from
the pool on the same rank and across ranks and nodes (32 of 32), with
the second turn on another rank served from the pool (16 of 16); owner
paused for longer than the request timeout: every rank stops within the
documented bound and no streamed token differs from the reference; owner
killed and restarted: every rank stops on its request timeout; ranks
killed: the owner drops them after the client timeout and their pins and
reservations return to 0; a provider killed under load: the engine stops
and no streamed token differs from the reference; 1P1D with the pool on
P; a pool instance with `TOKENSPEED_CACHE_EVENT_LOG=1`; two providers
per node, one per NUMA domain.

---------

Signed-off-by: Jiying Dong <87510204+dongjiyingdjy@users.noreply.github.com>
2026-11-26 16:56:32 +08:00
Tuan ZhangandtuanzhangCS 4fb7872166 perf(gdn): defer recurrent replay into the next verification step (#3582)
## Summary

- Add the opt-in `--enable-deferred-gdn-state` for NVIDIA BF16 K128 and
V128 chain verification with MTP3 (T4). Keep accepted replay in two
batch-sized payload banks and fuse it into the next layer’s WY state
read. Commit convolution during acceptance.
- Put replay writeback and discard at the start of the execution plan.
The scheduler can reassign pages and slots in that plan, and the device
retires the old replay before cache copies and reuse.
- Track one completion fence per retirement batch separately from cache
operations. New peer Device State pins, cache clear, and drain wait for
replica agreement. The request follows the existing finish, abort, or
retraction transition.
- Share the host launch setup for both deferred WY kernels and reuse the
existing runtime test fixtures.
- Reuse resolved acceptance pages and share WY coefficient loads across
both V16 subtiles. Separate query and retained-key shared-memory banks
and keep replay synchronization within each warp.

### Performance

Qwen3.8-Flash-Next-NVFP4 on B300 with Sonic, greedy MTP3, and device
prefix caching. Each concurrent session runs three turns at 2,048 output
tokens per turn and carries forward the previous output token IDs. Both
builds use `main` at `c5a765fac` as the base.

| TP and EP | Batch | End-to-end output (tokens per second) | Full-batch
decode (tokens per second) | Full-batch GPU step (ms) | GDN per step
(ms) |
| --- | ---: | ---: | ---: | ---: | ---: |
| 1 / 1 | 64 | 13,809 → 14,464 (**+4.7%**) | 14,382 → 15,052 (**+4.7%**)
| 17.63 → 16.92 (**−4.0%**) | 2.617 → 1.602 |
| 1 / 1 | 128 | 17,883 → 19,286 (**+7.8%**) | 18,548 → 20,104
(**+8.4%**) | 27.69 → 25.45 (**−8.1%**) | 5.051 → 2.848 |
| 4 / 4 | 128 | 34,979 → 36,241 (**+3.6%**) | 38,274 → 39,371
(**+2.9%**) | 13.34 → 13.10 (**−1.8%**) | 1.404 → 0.996 |

Values are shown from `main` to the PR. Throughput is the median of
three trials with tracing off. Full-batch decode throughput measures the
interval after every request has emitted its first token and before any
request finishes. GPU times are means from a separate Nsight Systems
capture. GDN time sums WY, replay commit, and pending metadata.

Prefill and mixed forwards account for about 2% of GPU-active time at
TP1 and 5–8% at TP4. TP4 third-turn prefix hits varied across trials.
Request throughput across the first two turns, which had matching cache
hit rates, improved 2.1%.

## Validation

- `pre-commit run --all-files` and Rust formatting passed. The Rust
control, serving, peer, and host suites passed 304 tests, with three
ignored.
- The B300 runtime suites passed 312 tests with one skip. The GPU
retirement test checks that one batch writes back preserved state,
discards cancelled replay, and produces one completion.
- All seven targeted C++ regressions passed, covering same-plan reuse,
capacity recovery, cache-only drain, and peer PIN readiness. The full
C++ suite passed 1,607 tests with one skip. The sole failure,
`ClosedLoopRandomTest.MirroredPrefillSchedulersPlanAlike`, also failed
on an earlier PR head.
- The peer regressions exercise scheduling and lease handling. The test
container has no RDMA device for an end-to-end GPU transfer.
- The updated B300 deferred WY and WY kernel suites passed 142 tests,
including CUDA Graph replay across both payload banks.

### Original implementation validation

- `pre-commit run --all-files`, Rust formatting, Rust control and host
tests, and 1,601 C++ scheduler tests passed.
- Tests passed for eager and CUDA Graph GDN replay, slot lifecycle, and
materialization. The kernel suites had 237 passing tests and one FP32
replay tolerance failure, reproduced with the same error on `main`.

---------

Signed-off-by: tuanzhangCS <26617745+tuanzhangCS@users.noreply.github.com>
Co-authored-by: tuanzhangCS <26617745+tuanzhangCS@users.noreply.github.com>
2026-11-25 15:55:32 +08:00
minedec 87a6c2995a perf(ple): optimize rank-local host gather and verify state writes (#3381)
## Summary

Qwen4-Exp PLE can spend over a millisecond reading an offloaded
embedding table during a long prefill. Its convolution also reloads the
same channel weights across tokens, and speculative verification writes
a full convolution-state window for every candidate. This PR reduces
those three costs.

- Batch multiple rows per CTA in the regular UVA gather. For a complete
table and at least 131,072 n-gram IDs, sort the IDs before the
persistent gather and write the results directly into their original
positions.
- Add a rank-local HBM cache for offloaded Qwen4-Exp PLE tables on
NVIDIA Hopper and Blackwell. It supports 16 n-gram heads, head
dimensions of 160 or 512, and BF16 lookup output. Tables can use BF16
storage or per-tensor FP8 storage, including FP8 checkpoints and BF16
weights quantized online. The gather deduplicates IDs within eligible
64-token windows per head and stages cache misses for asynchronous fill.
Lookups below 256 tokens and CUDA Graph capture and replay use the
regular UVA gather.
- Add `--enable-ple-hot-cache` to enable the cache when PLE offloading
is active. The cache is off by default.
`TOKENSPEED_PLE_HOST_CACHE_SLOTS` sets the capacity per rank and
defaults to 524,288 slots. It must be a power of two greater than one.
At the default capacity, a 160-wide FP8 table uses 84 MiB of cache
memory per rank, plus temporary miss staging.
- Tile long BF16 prefill convolution across 8 tokens and 128 channels on
NVIDIA Blackwell so one CTA can reuse the channel weights. For
speculative verify, store the carried state and one normalized input per
candidate, then reconstruct the accepted window in its destination page
with `copy_state_rows_compact`. Regular GPU convolution and the AMD
monokernel share the compact layout.

## Performance

Qwen3.8-Flash-Next-NVFP4 on a single NVIDIA SM103 GPU, TP1 unless noted.

### Agentic Bench with All Optimizations Enabled

The baseline and optimized builds ran sequentially on the same GPU with
MTP3, FP8 KV cache, FP8 PLE offload, CUDA Graph, and 16K prefill chunks.
The optimized run enabled `--enable-ple-hot-cache` with 524,288 slots
and used the branch's UVA, convolution, and compact verify paths as
applicable.

Both variants used `TOKENSPEED_SPEC_SIMULATED_ACCEPT_LEN=2.32`,
including the verification token, matching the InferenceX golden
accept-length distribution for Flash-Next native MTP3 with thinking
enabled.

EvalScope measured one round per variant and concurrency after warmup
and a prefix-cache flush, with 4 conversations at BS1, 32 at BS32, and
500 output tokens per turn. All measured requests succeeded.

| Concurrency | Metric | Baseline | This PR | Change |
| ---: | --- | ---: | ---: | ---: |
| 1 | TTFT (ms) | 282.59 | 280.44 | -0.76% |
| 1 | Decode (tokens per second per request) | 442.48 | 444.44 | +0.44%
|
| 1 | Aggregate output (tokens per second) | 353.65 | 355.46 | +0.51% |
| 1 | Decoded tokens per iteration | 2.2924 | 2.2934 | +0.04% |
| 32 | TTFT (ms) | 4,313.30 | 4,299.87 | -0.31% |
| 32 | Decode (tokens per second per request) | 67.07 | 67.34 | +0.40% |
| 32 | Aggregate output (tokens per second) | 1,284.40 | 1,288.59 |
+0.33% |
| 32 | Decoded tokens per iteration | 2.2934 | 2.2931 | -0.01% |

End-to-end changes were below 1% in this run. At BS1 and BS32, MTP3
verifies at most 128 tokens per batch, below the 256-token hot-cache
threshold. Compact verify saves 1.40 µs at BS1 and 8.31 µs at BS32 for
convolution and state commit together, a small part of the full decode
step. In the earlier 16K prefill profiles below, the host gather already
finished before its consumer in both variants, and convolution tiling
reduced the full target GPU span by 0.23%.

### Prefill convolution

Flash-Next TP1 geometry (10,240 BF16 channels, four taps, dilation 3),
with PDL and CUDA Graph enabled in the microbenchmark. The A and B
comparison isolates the tile change and compares 1 token × 256 channels
with 8 tokens × 128 channels. The convolution and final state matched
bit for bit.

| Prefill case | Baseline (µs) | Tiled (µs) | Change |
| --- | ---: | ---: | ---: |
| 2,048 tokens | 106.58 | 65.50 | −38.5% |
| 8,192 tokens | 395.25 | 217.10 | −45.1% |
| 8,192 tokens, ragged requests | 398.24 | 217.01 | −45.5% |
| 16,384 tokens | 779.66 | 423.94 | −45.6% |

In a separate Nsight Systems capture of one real 16K prefill step with
the same hot-cache path on both sides, convolution took 776.04 → 417.92
µs (−46.1%). The target GPU span was 364.08 → 363.25 ms (−0.23%).

### Host gather

#### Regular UVA gather

Both variants use the same complete FP8 PLE table with hot cache
disabled. The A and B comparison uses six measured Agentic prefill
windows. Each 8K case uses the first half of its 16K window. Timing
includes sorting and output reordering. The table reports means of
per-window medians, and all 12 outputs matched bit for bit.

| Prefill tokens | Direct UVA gather | Sort and persistent UVA gather |
Change |
| --- | ---: | ---: | ---: |
| 8K | 976.07 µs | 744.36 µs | −23.7% |
| 16K | 1,889.63 µs | 1,299.11 µs | −31.3% |

#### HBM hot cache

One Nsight Systems trace per variant measures a 16,384-token prefill
step on a live Flash-Next TP1 server. The comparison uses the baseline
and an early hot-cache implementation.

| Metric | Regular gather | HBM hot cache | Change |
| --- | ---: | ---: | ---: |
| Host gather kernel | 1,462.35 µs | 372.13 µs | −74.6% |
| Cache fill on a separate CUDA stream | — | 14.82 µs | — |

### Decode convolution and state commit

This microbenchmark compares full-window → compact verify using
`_ple_conv_state_kernel`; the state commit replaces `copy_state_rows`
with `copy_state_rows_compact`. Both use 10,240 BF16 channels with CUDA
Graph and PDL enabled. Values are medians of five alternating A and B
trials. The combined column times both launches together. Convolution
output and reconstructed state matched for every accepted length.

| Speculative steps | Batch size | Verify conv (µs) | State commit (µs)
| Combined (µs) | Combined change |
| --- | ---: | ---: | ---: | ---: | ---: |
| MTP3 | 1 | 4.78 → 3.08 | 1.11 → 1.43 | 6.02 → 4.62 | -23.3% |
| MTP3 | 8 | 11.31 → 7.66 | 1.37 → 4.07 | 13.33 → 9.75 | -26.8% |
| MTP3 | 32 | 34.10 → 15.65 | 2.35 → 12.53 | 36.76 → 28.45 | -22.6% |
| MTP7 | 1 | 5.00 → 3.22 | 1.05 → 1.31 | 6.49 → 4.77 | -26.4% |
| MTP7 | 8 | 17.80 → 7.99 | 1.28 → 3.88 | 19.38 → 11.74 | -39.4% |
| MTP7 | 32 | 61.23 → 19.24 | 2.36 → 12.55 | 64.84 → 32.06 | -50.5% |

Compact verify reduces the writes in the convolution kernel. The state
commit does more work to reconstruct the window, and the two launches
together take less time across the measured cases.

For single-token decode, both variants use the same tile geometry. With
identical inputs and output buffers, convolution latency was 2.87 → 2.87
µs at BS1, 4.84 → 4.84 µs at BS8, 14.99 → 14.93 µs at BS32. Outputs and
final states matched bit for bit.

## Test Plan

- With the fast math CUDA library on SM103, ran 39 focused kernel tests
covering FP8 and BF16 cache lookup, shard masking, validity checks,
dynamic prefill bounds, and convolution across request boundaries.
- On SM103, ran the PLE backend and cache setup tests against the
workspace and compact state-commit changes (55 passed). Coverage
includes accepted lengths, invalid pages, mixed per-layer page strides,
cache-pool rebinding, and graph replay.
- During sharded cache integration, ran the TP4 and DP4 lookup tests
against an unsharded reference, including a DP rank with zero local
tokens. Compiled the prefill tiles for SM100 and the compact monokernel
PLE stages for gfx950.
- Compared the CUDA host gather builds with and without fast math. The
Flash-Next checkpoint's FP8 scale produced bitwise-identical BF16 output
across all 256 FP8 byte encodings in the tested cold and prepopulated
caches. BF16 copies also matched. Synthetic scales near the FP32
subnormal range produced differences.

---------

Signed-off-by: minedec <jiandong@lightseek.org>
2026-11-20 00:47:43 -08:00
FC.Li 99a809afe2 test: repair startup fixtures and select NCCL for EAGLE4 (#3647)
Device startup's new collective preparation exposed incomplete test
fixtures: 24 receive-pool cache-budget cases lacked the mapping
contract, and four CUDA graph probe cases lacked the model dtype. Supply
a real single-rank Mapping and Gloo group for cache budgeting and
complete both model fixtures, preserving the existing memory-budget
assertions.

The EAGLE4 candidate-head test initialized a Torch NCCL process group
but left TokenSpeed's automatic communication backend active. Its
candidate all-gather could therefore lazily initialize Triton RSAG and
stall in symmetric-memory rendezvous. Explicitly select NcclBackend for
this test's documented NCCL contract, while retaining distributed-argmax
preparation and all numerical checks. Independent workers now report
failures promptly, dump timed stacks before the 300-second limit, and
clean up without masking the original failure.

Validation:

- Startup and MLA metadata regression tests after synchronizing main:
319 passed, 6 skipped; Muse tests: 52 passed, 22 skipped.
- Both repaired fixture files passed in B200 CI's full 167-file runtime
batch.
- The explicit-NCCL EAGLE4 test passed locally and in five independent
B200 invocations.
- `pre-commit run --all-files` passed before each commit.

---------

Signed-off-by: FC-Li <robert_lexis@163.com>
2026-11-19 13:58:50 -05:00
zhuhaozhecooland7huahua 3786263e1b refactor(npu): rework Ascend attention metadata, Prefill workspaces and MoE execution contracts (#3618)
## Scope

Refactor Ascend runtime attention, cache workspace preparation and MoE
execution contracts. This consolidates #3498, #3573 and #3596 on top of
#3563.

- Separate DSA decode resources from shared context-parallel metadata,
and reuse the metadata lifecycle across DSA and MLA.
- Share recipe-sized QCP Prefill workspace preparation and transport
across attention backends, with explicit layout and capacity contracts.
- Centralize scheduler-derived MoE source counts and refresh the
graph-owned buffer before replay.
- Clarify W4A4 weight preparation and common-registry ownership, while
retaining FP32 normalization scales for BF16 inputs.

Model plugins select their numerical execution paths through these
runtime interfaces. Sampling and logprob reduction retain the existing
runtime policy.

## Review fixes

- Reject DP-local decode graphs for models requiring global MoE source
counts; use the communication layer's scatter calculation. Startup
profiling uploads the selected packed tier's row count and restores
capture metadata, including on failure.
- Keep persistent CUDA count buffers in the memory saver's CPU-backed
runtime region. Cover repeated release/resume, contents and addresses.
Register the packed profiling regression in CUDA CI.
- Pass cache-recipe workspace layouts through the shared QCP Prefill
preparation path, removing the NPU package's reverse dependency. Restore
transport input validation and cover dynamic metadata parameters without
recompilation.
- Make W4A4 layout choices explicit, update the common registry
regression, and test fused DSA operator rejection at binding time.
Restore KVP 2/4/8/16 LSE coverage, exact FP32-scale sensitivity, invalid
FlatQuant clip checks and both cache-probe sizing cases.
- Update the scheduler test fixture for the cache-storage contract
reported by NVIDIA and AMD CI, and refresh the renamed NPU metadata test
entry point.

The existing DSA constructor's optional decode flag remains compatible
with callers that previously supplied only `prefill_enabled`. Low-level
packing helpers retain their separately tested geometry; the model
support constraints remain unchanged.

## Validation

CPU contract tests passed: 413 runtime/kernel tests and a follow-up
selection of 126 runner tests (with overlap). `pre-commit run
--all-files` passes.

Ascend 910B: 297 metadata graph/stream regressions, 25 transport-kernel
cases, 10 normalization cases and 8 real INT4 NZ/GMM cases passed. The
two-rank QCP transport run passed 34 byte-exact scenarios per rank,
covering KV-only and KV+index layouts, empty owners, shared pages and
fragmented history. The two scheduler fixture regressions also passed
with the matching engine package.

CUDA packed profiling regressions passed on NVIDIA B200 and AMD MI350.
The attention contract follow-up passed 160 CPU tests and 25 subtests;
`pre-commit run --all-files` passes.

---------

Signed-off-by: zhuhaozhecool <zhuhaozhecool@163.com>
Signed-off-by: 7huahua <26763681+7huahua@users.noreply.github.com>
Co-authored-by: 7huahua <26763681+7huahua@users.noreply.github.com>
2026-11-20 01:49:56 +08:00
Tuan Zhang 25872a5ca0 feat(cache): enable FlatKV by default for Qwen4-Exp (#3389)
## Summary

Reduce padding in Qwen4-Exp caches by packing target and draft KV, GDN,
PLE and QSA into one physical plane. FlatKV is enabled by default.
Qwen3.8-Flash-Next uses five logical groups: full attention, one GDN
state group, PLE, compressed QSA and recent QSA. Each parent remains
owned by one group.

- Translate full-history KV and QSA page IDs and write locations into
atom addresses; retain explicit strides for state and recent-window
caches.
- Select stride-capable GDN kernels, including MTP and tree
verification, using the actual input and output layouts.
- Bound parent capacity by every target and draft field's int32 atom
page and write slot limit, retaining startup overflow checks. Derive L3
namespaces from the actual layout, and preserve existing DeepSeek and
Dots byte-page layouts.

Use `--no-qwen4-exp-flat-kv` for the ordinary layout. FlatKV currently
requires PP=1, uniform per-view K and V heads and non-MXFP8 KV.

## Measurements

NVIDIA Qwen3.8-Flash-Next-NVFP4 on B300, TP1, BF16 KV, FP32 GDN, MTP 3
steps and 4 verify tokens, forward checkpoints enabled and L2
`write_back` (192 GB).

| Metric | FlatKV disabled | FlatKV enabled |
| --- | ---: | ---: |
| GDN checkpoint allocation | 2 × 78 MiB | 110.5 MiB |
| GDN checkpoint padding | 29.42% | 0.35% |
| API L1+L2 hit rate | 86.90% | **88.81%** |
| Output tokens per second | 1078.40 | **1157.56** |
| TTFT P50 | 8.24 s | 6.47 s |
| Mean ITL | 22.68 ms | 22.29 ms |
| Snapshot reservation | 23.56 GB | 37.08 GB |

InferenceX AgentX: concurrency 64, 256K context, seed 42, 702 warmup
requests and a 900-second measurement window per configuration. Hit rate
is cached prompt tokens divided by prompt tokens for completed profiling
requests; both runs had zero request errors.

These are historical runs from separate rounds with different GPUs and
peer workloads. They used FlashInfer 0.7.3 with common compatibility
adapters; current kernel validation uses pinned 0.7.4. Useful KV payload
is unchanged. The larger parent also increases null-parent and
small-group allocation costs, so total memory use depends on the live
group mix.

<details>
<summary>GDN grouping comparison</summary>

| Metric | 1 group (selected) | 6 groups | 18 groups |
| --- | ---: | ---: | ---: |
| Total cache groups | 5 | 10 | 22 |
| Parent size | 110.5 MiB | 19.5 MiB | 6.5 MiB |
| API L1+L2 hit rate | **88.81%** | 88.22% | 88.05% |
| Output tokens per second | 1157.56 | 1189.93 | 1199.22 |
| TTFT P50 | 6.47 s | **4.31 s** | 5.58 s |
| TTFT P90 | **32.44 s** | 34.63 s | 33.09 s |
| Mean ITL | **22.29 ms** | 23.34 ms | 26.57 ms |
| Snapshot reservation | 37.08 GB | 13.09 GB | 9.60 GB |

One group prioritizes checkpoint packing and the observed hit rate, ITL
and P90 TTFT. More groups reduce snapshot reservation and improve
throughput. Each configuration was measured once; the results show this
workload's trade-offs.

</details>

Accuracy comparison: main `cdeb32aa7` vs PR `fb4cc01f9`, using the same
serving configuration and complete test splits.

| Evaluation | Main | PR | PR-only repeat |
| --- | ---: | ---: | ---: |
| GSM8K, 1K output budget | 1276 of 1319 (96.74%) | 1274 of 1319
(96.59%) | — |
| GSM8K, 4K output budget | 1287 of 1319 (97.57%) | 1283 of 1319
(97.27%) | 1287 of 1319 (97.57%) |
| AIME26, 64K output budget | 28 of 30 (93.33%) | 28 of 30 (93.33%) | —
|

GSM8K used 4-shot greedy decoding with thinking disabled; AIME26 used
zero-shot thinking, temperature 1.0, top-p 0.95 and top-k 20. Both used
EvalScope 1.11.1, batch size 16 and seed 42. All requests succeeded.
GSM8K scores varied between PR runs; the repeat matched main's aggregate
score with different per-question results. The cause of this variation
has not been isolated. AIME26 answer extractions matched on all 30
questions, including the same truncated output.

## Test plan

- **444 runtime and cache tests passed** at `4692d6cf6` (7 skipped),
plus 7 subtests. Includes metadata-only capacity boundaries, differing
target and draft payloads and existing layout regressions. Inkling
activation parity also passes across prefill and page-crossing decode.
- **279 GDN and fused decode-metadata kernel tests passed** (36
skipped), including 17 far-page cases beyond 2^31 elements, independent
state strides, padding guards and CUDA Graph execution.
- Real Qwen4 target and draft D2H → L3 → H2D round trips compare every
arena byte, including padding and untouched blocks.
- Fresh B300 TP2 service at 0.95 memory utilization, with forward
checkpoints and L2 `write_back`: capacity safely capped at **2,372
parents and 137.48 GB per GPU**. All three requests returned the
expected answer; a repeated 18,029-token prompt reused **17,920
tokens**.
- `pre-commit run --all-files` passed. Hardware CI status is tracked by
the checks on this PR.

---------

Signed-off-by: tuanzhangCS <tuan@lightseek.org>
2026-11-18 17:19:05 +08:00
3bd08baacc feat: share cached prefixes between engine replicas (peer prefix sharing) (#3531)
## Summary

A replica can reuse a prefix that another replica already caches, in
that replica's GPU or pinned Host cache, by reading it over RDMA instead
of recomputing it. The design is in
`docs/rfcs/0004-peer-prefix-sharing.md`.

There is no central store and no L3. The router names a holder with the
request (`peer_holder`, the holder's `host:port`). The reader then:

1. **Looks up.** It asks the holder how much of the prompt it caches.
The lookup soft-pins those blocks.
2. **Pins.** At admission it hard-pins exactly the pages it will read.
3. **Reads.** It pulls them with one-sided Mooncake Transfer Engine
READs into its own GPU blocks. Each member of the replica reads its own
shard from the holder's member of the same index.
4. **Releases.** If the read was complete, the release asks the holder
to demote its copy, so the two replicas don't both keep it.

Any failure falls back to computing locally. The landing is given up
whole and the request is admitted again from its local hit.

Opt in with `--peer-prefix-port PORT`; attention-DP rank `r` binds `PORT
+ r`. Peer sharing requires the Host tier (`--enable-kvstore`) and
prefix caching. It is refused with `--disaggregation-mode decode`,
`--kvstore-storage-backend`, pipeline stages and query context
parallelism.

## What changes

- **Scheduler (C++).**
- The holder answers lookups, pins and releases from const reads between
rounds. The changes those answers imply are applied by every replica
member at the next round's head.
- The reader gains a `PeerLooking` state, and a `PeerLanding` state that
generalizes the PD decode landing.
- The landing's pages are kept out of the plan's copies, loads and
zeroing.
- Leases are protected by deadlines, incarnations and namespace checks.
- **Control loop (Rust, `ts-control::peer`).**
- The servicer, the per-request landing state machine, read geometry for
Device and Host sources, and the endpoint over ZMQ.
- The loop holds the scheduler under a mutex, released while it waits on
a forward result, an idle frontend or a paused round's sleep, and handed
once per round to a waiting servicer, so the endpoint can answer without
waiting for a round. That last hand-over matters to a loop waiting on a
transfer (a prefill engine's PD sends, a landing's reads), which reaches
neither wait and spins through empty rounds.
  - Peer reports ride the replica relay.
- **Engine host and runtime.**
- Startup: a transfer engine per rank with the Device arena and Host
pool registered, and the replica's geometries exchanged over the rank
mesh.
- Read fence: a plan with landings records an event behind its stores,
copies, zeroing and the forwards in flight. Reads start only after that
event. Every plan with a landing goes to the data plane, also when it
has no other device work, as a prefill engine's landing may not.
- The namespace is the L3 deployment id (`cache_deployment_id`, now
shared by L3 and peer sharing) plus the weight version. A flushed weight
update moves it, under the same weight-version rule L3 already enforces.
- **KV events.** With Host L2, the event stream now also covers Host
blocks, published with their medium in vLLM's layout. Device events gain
trailing `nil` fields (`lora_id`, `medium`), which vLLM-format consumers
already read. Each medium's stream is prefix-closed for a router that
continues a GPU match into the Host tier.

## Testing

- **C++.** The scheduler suite passes, including new peer tests run on
both full-history and hybrid (sliding window + State) layouts. The
closed-loop random test now checks each KV event medium's stream and its
closure rule.
- **Rust.** `ts-control`, `ts-pd`, `ts-mooncake`, `ts-scheduler` and
`ts-host` pass, including in-process two-replica tests over real
sockets. `cargo fmt` and `clippy` are clean.
- **Python.** Tests for the geometry, server args, the device fence, the
L3 factory refactor and the KV event layout pass.
- **GPU.** Two replicas of Qwen3-0.6B on one node, with RDMA loopback
through the NIC, using a locally built transfer engine:
- From the holder's GPU cache: the reader landed 1536 prompt tokens and
computed 1, and its greedy output was token-identical to the holder's.
- From the holder's Host cache (write-back with a small GPU cache): same
result.
  - A failed READ fell back to local compute with correct output.
- **Prefill and decode, end to end through the Dynamo router** (with the
router-side change on top): this found two bugs, fixed in the last two
commits.
- **A servicer starved by a spinning loop.** A loop waiting on a
transfer spun without releasing the scheduler, so its servicer never
answered. A test runs a loop waiting on a PD transfer and checks that
another thread gets the scheduler.
- **A landing that never read.** `plan_needs_device` ignored peer
fetches, so a prefill engine's landing plan, with no other device work,
never reached the data plane and its reads never started. A test lands a
prefix on a prefill replica from such a plan.

  Both tests fail without their fix.
- Some runtime test files need a newer GPU stack than the machine this
was developed on, so CI covers those.

## Not in this PR

- Router-side placement: peer credit with same-node and cross-node cost
models, and the hint itself. That lands separately in the Dynamo router.
- KV-page sharding, the decode role, and pipeline stages.

Co-authored-by: longcat-ia-team <longcat_ia_team@meituan.com>

---------

Signed-off-by: FC-Li <robert_lexis@163.com>
Signed-off-by: lightseek-bot <243258330+lightseek-bot@users.noreply.github.com>
Co-authored-by: longcat-ia-team <longcat_ia_team@meituan.com>
Co-authored-by: lightseek-bot <243258330+lightseek-bot@users.noreply.github.com>
2026-11-18 16:07:10 +08:00
2e172b8926 feat(k3.1): serve the released DSpark GQA draft at KVP1 and KVP8 (#3545)
## Summary

The released Kimi-K3.1 DSpark draft (`Inferact/Kimi-K3.1-Pro-DSpark`,
e4e6e626) ships in the speculators format: a five-layer GQA stack whose
every layer slides over a 2048-token window and attends causally within
its block. TokenSpeed could not load it, and refused it under KVP. This
PR serves it at KVP1 and KVP8, then speeds up its draft step. The
loading and cache-plan commits are ported from #2653.

- **Loading.** The speculators config is converted to the DFlash layout,
the draft's own mask-token embedding row is kept, and the MHA leaf gains
causal block decode. The GQA draft's K and V planes join the K3 cache
plan.
- **KVP.** PD cannot transfer K/V head rows out of a page-sharded group,
so a draft whose every layer slides now owns a window group: it retains
window + 1 tokens, is packed like the MLA group, and is left unsharded
by KVP. Its config is built without KVP, and the registry refuses a plan
that page-shards its K/V.
- **Eight verify rows.** Under KVP the owned-page DSA scorer took at
most six verify rows per request; seven drafts verify eight. The scorer
already pads groups to its 8-row tile.
- **Fixes.** On AMD, the draft's row-parallel partials are reduced
before the final norm. The MHA draft's block causality passes through
`model_wide_kwargs`.

Speed-ups:

- **Packed causal rows.** A causal block kept one decode entry per
position, and each re-read its request's keys. It now keeps one entry
per request and decodes its positions as packed causal query rows, as a
verify does. It no longer requests the non-causal `block_draft` kernel
trait.
- **GEMM tiles.** The draft's q|k|v, stacked context k|v, MLP and
context projection take listed gfx950 decode tiles instead of hipBLASLt.
The MLP down-projection and context-projection tiles match #3494's.

## Results

8x MI355X, greedy, measured with this work on top of #3496:

| Check | KVP1 | KVP8 | Golden |
|---|---:|---:|---:|
| Acceptance length, 5 drafts | 3.73 | 3.70 | 3.81 |
| Acceptance length, 7 drafts | 4.08 | 4.14 | 4.16 |
| GSM8K, 7 drafts | 98.0% | 98.1% | |

Decode step at c1, TP0 kernel time per step, averaged over two nodes at
128K and 384K contexts:

| Kernels | Before | After |
|---|---:|---:|
| Draft attention | 155 µs | 80 µs |
| Draft GEMMs that move off hipBLASLt | 148 µs | 110 µs |

AgentX, 3600 s, same recipe, released draft against the preview draft at
c1–c48: throughput per GPU +5% to +12%, interactivity +11% to +26%, no
errors.

## Test Plan

On gfx950:

- [x] The acceptance and GSM8K checks above, and AgentX at KVP1 (c1, c4)
and KVP8 (c8–c48), 3600 s, no errors.
- [x] `test_kimi_k3_cache_pool.py`: the window group's fields, packing
and KVP shard counts; the registry refuses a page-sharded draft; the
drafter checks the plan before its groups are bound.
- [x] `test_dspark_config.py`: speculators config conversion and
rejection; `test_mha_backend_selection.py`: causal block decode lengths.
- [x] `test_gluon_dsa_index_candidates.py` with 8-row groups, and
`test_gluon_a16w16_gfx950.py` on the new buckets.
- [x] Runtime suites on MI350X against this branch's engine: the
DFlash/DSpark, Kimi-K3, MHA and cache tests pass; one CUTLASS test fails
on main too.
- Not run on NVIDIA.

---------

Signed-off-by: Stanley Winata <raikonenfnu@users.noreply.github.com>
Signed-off-by: Zhewen Yu <zhewenyu@amd.com>
Co-authored-by: Stanley Winata <raikonenfnu@users.noreply.github.com>
Co-authored-by: Stanley Winata <stanley.winata@amd.com>
2026-11-17 16:05:51 -08:00
simple-sun 34eaef6da1 feat(pd): decode-extra-slots (#3362)
## Summary

Allow a PD decode worker to receive and retain more requests than it
executes concurrently. With B execution slots and E additional resident
slots, up to B + E requests can own request rows and KV while at most B
hold decode permits. A request whose KV arrives while all B permits are
held waits without enlarging forward batches or CUDA graphs.

- Add --disaggregation-decode-extra-slots. On a decode rank, omission
resolves to E=B, where B=max-num-seqs // attention-DP size, so C=B+E=2B
by default. Explicit E is rank-local; set E=0 to retain C=B. Size
request-local state and cache reservations by C while keeping execution
scratch sized by B.
- Apply decode execution permits only to the disaggregated decode role;
fused and prefill roles do not acquire these permits. Keep permits with
requests and in-flight restore/forward operations until their work
retires, including cancellation.
- Default snapshot rows to rank-local resident capacity C, preserving
explicit positive overrides; document the separate Host-memory limits
and add recovery tests.
- Export resident, active-decode, and KV-ready waiting gauges, plus
tokenspeed:decode_ready_wait_seconds from complete KV arrival observed
by the decode host to first decode dispatch. Include a 100 ms histogram
bucket.
- Update design documentation and behavior tests. Most existing test
edits supply the newly explicit resident-capacity argument.

## Default extra slots and capacity cost

The E=B default targets workloads where an efficient decode execution
batch leaves KV headroom, including long-input, short-output agent
traffic. Additional resident rows let requests receiving remote
prefill/KV and requests ready for their first decode coexist with that
execution batch. This default takes effect on decode servers even when
the flag is omitted; it does not guarantee a full batch if prefill
supplies too little ready work.

Receiving, ready and decoding requests share one KV pool. E adds no KV
memory or separate partition. Request-indexed persistent state grows
with C, and the capacity model accounts for C residents' working sets.
Depending on the model and cache layout, this can reduce reported token
capacity for the same arena; the additional persistent tensors can also
leave less GPU memory for the arena. Forward batches, CUDA graphs and
single-forward scratch remain bounded by B.

A synthetic CapacityModel example, checked against the native
implementation, holds B=32 and the arena at 4,096 usable LCM blocks. It
uses one full-history group with 64-token pages and one State group,
both with packing 1; D role, prefix caching and speculation disabled,
decode width 1, overlap depth 1, context limit 65,536. The required
blocks are ceil(T/64)+3C for a concurrent token budget T.

| Capacity-model example | Explicit E=0 | Default E=B |
|---|---:|---:|
| Resident capacity C | 32 | 64 |
| Physical request rows, including null and padding | 34 | 66 |
| Usable LCM blocks | 4,096 | 4,096 |
| Maximum concurrent token budget T | 256,000 | 249,856 |

This example loses 6,144 tokens (2.4%) of modeled capacity. It isolates
the capacity-model cost and excludes additional persistent tensor
memory; it is not a GPU measurement or a general percentage for other
models. The historical 2P1D throughput benchmark used explicit E=128 and
does not measure the default E=B configuration.

## Retraction and snapshot limits

Extra residency does not change the shared capacity-recovery policy.
PrefillDone requests waiting for their first decode permit are eligible
victims alongside Decoding requests, subject to the reserve exemption,
scheduling and in-flight guards. RemotePrefilling requests are excluded.
Ready-waiting requests have no unconditional first-victim priority:
among eligible requests whose images fit, the policy favors more newly
releasable blocks, then fewer generated tokens. A retracted PrefillDone
request resumes in that state and obtains its permit at first decode; a
Decoding restore reserves its permit before restoring.

The default snapshot request limit now follows rank-local resident
capacity C: B+E on decode and B on fused. An explicit positive
--retraction-snapshot-max-requests is preserved. E has already been
resolved per rank and is not divided by attention-DP size again. Prefill
and encode roles do not use a snapshot pool. The existing no-pool
behavior for KV offloading and explicitly disabled snapshots is
unchanged.

Slot-state image rows, snapshot KV storage and Host L2 space remain
separate limits. Increasing the row cap allocates more slot-state rows.
With Host KVStore enabled and neither snapshot size nor ratio specified,
the derived tail pool also grows with the cap. With Host KVStore
disabled, the default snapshot KV pool remains 0.1 of Device KV;
explicit snapshot sizes and ratios are unchanged. Retraction frees a
Device request row for new admissions, so continued admissions can
create demand for more than C suspended images. C is a default budget,
not a guarantee that every image fits. If no eligible resident's
complete image fits, the existing fallback aborts the newest eligible
resident and reports the limiting resource. Victim ordering is
unchanged.

### Long-output, high-occupancy validation

The snapshot-cap change was tested with 1P1D RDMA, 8×H20 per worker,
TP8, B=36 and 72 requests submitted concurrently once per run. Extra
slots and snapshot sizing knobs were omitted: E resolved to 36 and the
snapshot row cap to 72. Each request had exactly 100 input tokens and
generated exactly 20,000 output tokens, verified from usage and the
length finish reason, with EOS stopping disabled. Host KVStore was
disabled, so snapshots held whole images and used the default 10% of
Device KV. The pressure run capped Device KV at 524,288 tokens; the
reference used automatic Device KV capacity.

| Measurement | Automatic Device KV | Device KV capped at 524,288 tokens
|
|---|---:|---:|
| Successful requests | 72/72 | 72/72 |
| Peak sampled Device KV occupancy | 3.25% | 100% |
| Natural retraction events | 0 | 27 |
| Capacity aborts | 0 | 0 |
| Aggregate output throughput | 4,875 tokens/s | 4,855 tokens/s |
| Mean TTFT | 74.752 s | 74.748 s |
| Mean TPOT | 7.327 ms | 7.332 ms |
| Mean end-to-end request time | 221.293 s | 221.381 s |

**At 100% sampled Device KV occupancy, all 72 requests completed despite
27 natural retraction events, with no capacity aborts.** No
forced-retraction flag was used. Resident, active-decode and retracted
counts returned to zero, and all 144 concatenated output-text SHA-256
hashes matched across both runs. This verifies output-text equality for
this synthetic workload, not internal-state equality for arbitrary
workloads.

Throughput is completed output tokens divided by the interval from first
submission to last completion. These are single runs, not a statistical
performance comparison or an E=0 comparison. The synthetic repeated
prompt had near-perfect speculative acceptance. Mean TTFT includes
waiting for 36 execution permits across 72 concurrent requests.

The retracted queue's observed peak was 5 at one-second sampling, below
B=36. This run exercises GPU snapshot/restore at high Device KV
occupancy but does not demonstrate the benefit of raising the row cap
from B to C, exhaust the 72-row budget, or cover the Host
KVStore-enabled path. Separate native scheduler tests cover more than B
simultaneous suspended requests, ready-waiting retraction/restoration,
snapshot-row and snapshot-KV exhaustion, aborts, subsequent progress and
resource return.

## Upgrade requirements and cancellation scope

This PR changes the runtime/scheduler configuration API. Matching
runtime and native components are required, including when E=0; mixing
components from before this change with components that include it is
unsupported. For source deployments, rebuild and install
tokenspeed-engine and any standalone tokenspeed-scheduler from the same
revision as the Python runtime. The serving host uses the scheduler
embedded in tokenspeed-engine, so upgrading only the standalone
scheduler wheel does not update serving's scheduler.

Package versions and dependency requirements are unchanged in this PR.
Publication and dependency updates remain separate release steps under
the repository's release process: publish the new scheduler before
raising the runtime's scheduler dependency requirement. The existing
dependency lower bound does not establish compatibility with this new
API.

Cancellation lifetime handling applies to every engine role, including
E=0. Already-dispatched forwards retain the request row, KV pages and
any decode permit until their results return; aborted requests do not
publish their completed pages. PD transfers retain their separate
retirement fence.

The ready-waiting gauge counts resident PrefillDone requests awaiting
their first decode. It excludes Retracted, Restoring and Finishing
requests; on PD nodes, tokenspeed:num_retracted_queue_reqs separately
counts Retracted and Restoring requests.

## Benchmark results and benefits

A 2P1D RDMA replay compared main 04ab2e0 (B36) with this PR at ed64cd0
(B36 + E128). Each worker used TP8/EP8 and DSPARK. Both P workers kept
B8, chunk size 8192, and a 262144-token cache budget; D kept the same
B36 execution and CUDA-graph ceiling in both runs.

Every 5 seconds, the client sent 36 fast-path requests and 5 slow-path
requests for 300 seconds: 60 overlapping bursts, 2460 requests per run,
averaging 8.2 requests/s. Total input length stayed at 169481 tokens.
The paths added unique 500-token and 10000-token tails to cached
prefixes; actual forward input was approximately 649 and 10377 tokens
after cache-page boundaries and state replay. Both versions replayed the
same tail pools. Gateway overload filtering remained enabled, and errors
were counted without stopping submissions.

- **Higher observed steady decode throughput: 2904.3 to 3000.8 output
tokens/s, a 3.32% increase.**
- **More consistently full decode batches: actual batch=36 rose from
16.9% to 77.8% of decode log samples; mean batch rose from 33.66 to
35.76.**
- **More successful requests from the same offered workload: 1757 to
1949; failures fell from 703 to 511, a net gain of 192 successful
requests.**

### Decode batch occupancy

| Steady decode metric | Main B36 | PR B36 + E128 |
|---|---:|---:|
| Mean actual running batch | 33.66 | 35.76 |
| Actual batch=36, share of decode log samples | 16.9% | 77.8% |

**The share of logged decode batches running at the full B36 increased
by 60.9 percentage points.** These are actual running-request counts
from decode logs over seconds 60–300, rather than padded CUDA-graph
sizes or active-permit counts. The percentages describe log samples, not
time-weighted utilization.

Throughput and batch statistics use seconds 60–300. Request outcomes
include drain: total elapsed time was 420.85 seconds for main and 450.27
seconds for the PR, with the same 240-second per-request and drain
limits. Main still occasionally reached batch36: requests waiting for
prefill KV averaged 2.07, rather than occupying the entire window
continuously. With this PR, active permits averaged 36.00 while the
KV-ready waiting queue averaged 125.93 and resident requests averaged
163.98; the extra ready requests could fill execution permits as they
became available. KV-page utilization increased from 19.7% to 90.0%
within the allocated cache pool.

### Latency and outcome tradeoff

The offered rate exceeded D's service capacity. Higher throughput and
fewer failures did not remove queueing. Latency comparisons below pair
requests by path and exact random-tail SHA256, with matching request
indices.

| Mean latency, including drain | Both-success cohort: main |
Both-success cohort: PR | Main-failed/PR-success cohort: PR |
|---|---:|---:|---:|
| Request count | 1677 | 1677 | 272 |
| TTFT, seconds | 82.21 | 88.62 | 132.49 |
| TPOT, ms/token | 11.27 | 11.65 | 11.56 |
| End-to-end request time, seconds | 90.04 | 96.69 | 140.49 |

For the both-success cohort, end-to-end P50 improved from 105.41 to
97.40 seconds, while P99 increased from 129.49 to 158.11 seconds. The
272 additional successes also waited longer, raising the
successful-sample latency distribution. Thus the TTFT difference
reflects both a changed success population and longer waits within the
common-success cohort.

### Error codes and failure rates

All percentages below use all 2460 submitted requests per run as the
denominator; counts include the drain phase. No HTTP429 responses were
observed.

| Outcome | Main: count / all requests | PR: count / all requests |
|---|---:|---:|
| HTTP429 | 0 / 0.00% | 0 / 0.00% |
| HTTP503 | 50 / 2.03% | 45 / 1.83% |
| Other non-200 HTTP responses | 0 / 0.00% | 0 / 0.00% |
| HTTP200 followed by a failed stream | 653 / 26.54% | 466 / 18.94% |
| All failures | 703 / 28.58% | 511 / 20.77% |
| Successfully completed requests | 1757 / 71.42% | 1949 / 79.23% |

**The overall request failure rate decreased from 28.58% to 20.77%, a
reduction of 7.80 percentage points using the unrounded rates.** HTTP200
followed by a failed stream counted as a failure, not a successful
request. Streamed failures were reported as RuntimeError by the client.
PR fast-path failures clustered around 120 seconds with long bootstrap
waits, consistent with the configured bootstrap deadline. The observed
HTTP503 code was no_available_workers. No D rank exits or D engine-error
log lines were observed during either formal run.

### Where the feature helps

**Separating resident capacity from execution permits helps when pending
prefill/KV requests occupy main's execution window while other requests
already have KV ready to decode.** Increasing the number or duration of
pending requests may increase the relative benefit when enough ready
work remains available. This is an expected operating regime, not a
measured scaling result; extra slots remain bounded by KV capacity, and
cannot fill D when prefill supplies too little ready work. Sustained
overload still grows queues and can hit bootstrap deadlines.

Each version was measured once, and the two public SHAs contain changes
beyond this feature, so the observed difference does not isolate E-only
causality. These are workload-specific overload results.

## Test Plan

The original PR validation below is retained as historical evidence. The
subsequent D-only permit change was validated on base 1a1c26c48 plus
that change: Linux scheduler C++ tests passed 1,529 with one
sanitizer-only skip; scheduler Python tests passed 425; five-minute
Fused and RDMA PD runs completed 860/860 and 1,272/1,272 requests,
respectively. The PD run used client concurrency 36 and did not fill all
B+E resident slots. These earlier runs did not include the snapshot-cap
change and do not validate AMD performance. After incorporating the
latest upstream merge, the 20 extra-slots regression tests were rerun
successfully.

- Passed: pre-commit run --all-files.
- Passed: scheduler Python suite, 422 tests.
- Passed: Rust control library suite, 160 tests; Rust metrics unit
tests, 2 tests; metrics Prometheus integration suite, 5 tests.
- Blocked locally: runtime CLI tests could not run beyond imports
because this environment lacks the required
transformers.models.minimax_m3_vl module and tokenspeed_kernel package.
No runtime behavior was exercised by that attempt.
- Passed: end-to-end 2P1D RDMA replay on benchmark commit ed64cd0; all
planned requests were accounted for, paired inputs matched, and D ranks
remained alive. Application-level failures are reported above.
- The full GPU runtime unit/integration suites have not been run
locally; the targeted GPU serving runs are listed separately. A fork PR
may need maintainer assistance for CI that requires repository secrets.

Snapshot-cap validation for 84644abef (the tested patch on f2457e444,
unchanged when committed):

- Passed: snapshot argument-resolution tests, 31; extra-slots
CLI/argument regressions, 21 (GPU cases excluded).
- Passed: native scheduler Python suite, 429 tests, including four new
recovery tests. A scheduler test advances 8,192 decode steps to trigger
natural capacity retraction without forced-retraction flags.
- Passed: the two GPU long-output RDMA runs reported above, 72/72
requests each.
- Passed: pre-commit run --all-files and git diff --check.
- Not covered by these runs: exhausting all C snapshot rows on GPU, Host
KVStore-enabled GPU recovery, or AMD performance. Component exhaustion
tests and the GPU run exercise different parts of recovery; neither
substitutes for the other.

---------

Signed-off-by: sunshengqi <69040952+simple-sun@users.noreply.github.com>
2026-11-17 00:31:38 +08:00
9159a6443d feat(k3.1): support KV/context parallelism on gfx950 and serve startup requests (#3082)
## Summary

Kimi-K3.1 on AMD gfx950 with the DSA KV cache sharded over eight
KV-parallel ranks (`--kv-parallel-size 8 --decode-context-parallel-size
8` at TP8). KVP1, NVIDIA and the bitwise numerics envelopes keep main's
paths.

**How a DSA layer runs, per GPU**

| | KVP1 | KVP8 decode | KVP8 prefill |
|---|---|---|---|
| Projections (q, kv, o) | 12 of 96 heads | 12 of 96 heads | 12 of 96
heads |
| KV cache held | every page | one eighth of the pages | one eighth of
the pages |
| Index scoring | full history; every row in decode, one eighth of the
rows in prefill | every row over its own pages | one eighth of the rows
over the full history |
| Top-k it attends | the full top-k | its share of the global top-k (the
keys it holds) | the full top-k |
| Attention core | 12 heads over the top-k | all 96 heads over its share
| 12 heads over the top-k |
| Moved between GPUs | prefill's top-k selections | index scores with
the 96-head query riding along; then each head's partial output and LSE
to the GPU that owns the head | the chunk's history pages it lacks
(index-K, then latent); prefill's top-k selections |

**Optimizations**
- **Prefill over gathered history:** the sharded prefill exchanges each
chunk's 96-head query and partials, and its index scoring grows faster
with history. Instead, each rank gathers the history pages it lacks,
which moves less and keeps KVP1's kernels and numerics. The gather
buffer is reserved from the cache budget, so memory planning counts it.
- **Owned top-k decode:** each rank scores only the pages it holds
(`launch_gluon_dsa_index_candidates_gfx950`, now the default), then
selects only its share of the global top-k from the gathered scores in
one launch (`_select_owned_from_gathered_kernel`), instead of every rank
merging every rank's candidates. The query rides in the same score
gather, saving a separate query gather.
- **Records exchange over Iris:** the decode core writes each head's
partial output and LSE straight into the exchange's layout, splitting
keys by each row's live length
(`launch_gluon_dsa_decode_dcp_records_gfx950`). These exchanges are
small and latency-bound, so the target and the EAGLE drafter send them
as GPU-side pulls instead of NCCL and combine records as they arrive
(`IrisPullExchange`, `try_combine_records`). The Iris heap reserves room
for it, so collectives created later still fit.
- **Startup requests:** model-only warmup runs on a probe cache and
never takes the request path (prefix extends, partial prefill chunks,
draft verify), so first requests still compiled kernels. With the opt-in
`--enable-startup-requests` (on in the Kimi-K3.1 AMD recipe), the Rust
event loop serves a few requests of its own, from one token up to a full
batch of prefill chunks, before it reports ready, then drops their
prefixes. PD disaggregation and L3 KV stores refuse the flag for now.
- **Warmup variants:** kernels that pick a compile variant from the
batch (a row tile, a config bucket, a K split, a warp count) either keep
the row count out of the specialization or compile every variant they
can pick while warming up, so a batch size the startup requests did not
run does not compile while serving.
- **MLA decode under context parallelism:** the MLA backend serves
decode over the sharded cache as well (`_forward_dcp_decode`): the Gluon
MLA decode returns the per-head LSEs the cross-rank combine needs, and
its partials reduce takes the key-split count as a runtime value in
power-of-two buckets (`_mla_softmax_reducev_kernel`), so an eager batch
of any size runs on its bucket's binaries. Block drafts, batch-invariant
numerics, sliding windows and logit caps refuse DCP decode for now.
- **Smaller savings:** KVP write slots resolve once per forward instead
of at every cache write; query gathers move 8-byte words instead of
strided bytes; Kimi-K3 side streams get their own hardware queues
instead of sharing the forward's.

## Performance

Kimi-K3.1 on 8x MI350X, TP8, EAGLE3, the recipe's command with
`--max-num-seqs 48` and `--max-model-len 1048576`. Each row sends its
requests at once. Total tokens per second counts every prompt token,
cached or not, plus output tokens, over the run's duration; latency is
per request, from send to last token, averaged over requests.

| Workload | Mode | Output tokens per second | Total tokens per second |
Mean TTFT | Mean E2E latency | Running at once |
|---|---|---|---|---|---|---|
| 1K input and 750 output tokens, 64 requests | KVP1 | 1,767 | 4,124 |
1.2 s | 14.6 s | 48 |
| | KVP8 | 1,763 | 4,113 | 1.1 s | 15.4 s | 48 |
| 50K input and 500 output tokens, 64 requests | KVP1 | 174 | 17,623 |
75.9 s | 106.7 s | 13 |
| | KVP8 | **184** | **18,566** | **48.9 s** | 126.4 s | 48 |
| 650K input and 800 output tokens, 4 fresh requests | KVP1 | 19 |
15,602 | 100.7 s | 104.2 s | 1 |
| | KVP8 | 19 | 15,695 | 98.9 s | 164.4 s | 4 |
| 650K second turn (+1.8K new tokens), 800 output tokens, 4 requests |
KVP1 | 177 | 144,101 | 7.2 s | 11.3 s | 1 |
| | KVP8 | **348** | **283,787** | **0.77 s** | **7.5 s** | 4 |
| 1M input and 800 output tokens, 8 requests | KVP1 | rejected (at most
748K prompt tokens) | | | | |
| | KVP8 | **11** | **14,226** | 310 s | 471 s | 8 |

KVP8 is for long-context serving: each GPU holds one eighth of the KV
cache instead of all of it, so KVP8 serves reused long contexts (agentic
multi-turn) about 2x faster with a 9x faster first token, runs more long
requests at once, and serves prompts beyond KVP1's 748K limit. At short
context it matches KVP1.

- **Second turn:** the same four 650K conversations come back with 1.8K
new tokens each, with the prefix cache and host KV store on in both
modes (`--enable-prefix-caching --kvstore-ratio 8`); 99.7% of its prompt
tokens are cache hits.
- KVP8's higher latency on fresh long prompts comes from the scheduler
processing all admitted prompts before decoding.

**Startup**, cold compile cache, with and without
`--enable-startup-requests`; steady-state C16 latency and throughput are
unchanged:

| | KVP1 | KVP8 |
|---|---|---|
| First 50K-token request after ready | 6.70 s → 2.6 s | 7.42 s → 2.8 s
|
| Kernel compiles after ready | 37 → 0 | 35 → 0 |
| Time to ready | 233 s → 258 s | 240 s → 268 s |

## Test Plan

- gfx950 kernel tests for the touched kernels on MI350X: 1,755 passed.
The 11 `test_k3_prefill_dispatch` cases fail, as on main.
- Multi-GPU tests at two and eight ranks (Iris pull exchange, column
gather and Lamport all-reduce, owned top-k, DCP exchange, history
gather, Kimi-K3.1 DCP): 145 passed.
- Runtime unit tests for the touched modules: 919 passed.
`test_registered_pool_and_router_bind_distinct_leaf_geometries` (it
expects NVIDIA's TRTLLM MLA backend) and four
`test_qwen4_backend_composition` cases fail the same way on main.
- `ts-control` Rust tests, including the startup requests: 156 unit and
60 serving tests pass.
- Teacher-forced logprobs, KVP8 vs KVP1: mean |delta logprob| 0.056 on
short prompts and 0.153 on 40K-token prompts.

---------

Signed-off-by: Zhewen Yu <zhewenyu@amd.com>
Signed-off-by: Max Dawkins <max.dawkins@gmail.com>
Signed-off-by: Lei Zhang <antiagainst@gmail.com>
Co-authored-by: Max Dawkins <max.dawkins@gmail.com>
Co-authored-by: Lei Zhang <antiagainst@gmail.com>
2026-11-14 17:51:04 +00:00
Fan Yang 4d0bc47f8f perf(qsa): run large FP8 prefill calls on a BF16 KV scratch (#2933)
## Summary

- Add `--enable-qsa-prefill-bf16-scratch` (off by default) for Qwen4-Exp
QSA with an FP8 E4M3 KV cache. A target prefill call of at least 2048
rows copies the FP8 KV pages it can read into a BF16 scratch (exact),
remaps its slots and runs the CuTe kernel's BF16 path. Decode, verify,
drafts, mixed and small calls keep the FP8 path; the cache stays FP8.
- The scratch is a fixed workspace of the cache recipe: reserved from
the KV budget before the pool is sized and allocated once at startup;
serving only takes views. The KV pool shrinks by about 721 MiB (8k
chunks) or 897 MiB (16k chunks) at 262k context.
- Startup refuses unsupported setups (no QSA layers, another KV dtype,
chunked prefill below 2048, no CuTe QSA kernel).
- The CuTe BF16 gathers now zero-fill padded entries instead of reading
slot 1 (same output). FP8 PTX is unchanged.

## Performance

GB300, Qwen3.8-Flash-Next NVFP4, FP8 KV. Measured against the CuTe FP8
prefill path (kernel override); the default FA2 prefill was not
measured.

- 18 captured 16k-row prefill calls: -37.2% per call including copy and
remap, bitwise equal to the BF16 kernel on the dequantized cache.
- AgentX agentic replay, 3600 s, same-session A/B: single server 8k c108
+3.7% tok/s/GPU and +5.9% P90 interactivity; PD 3P2D c336 +0.9%.
- The pre-rebase head, re-measured with #2943 (the single-server crashes
seen while testing it came from that upstream top-k overflow, not from
the scratch): 16k c84 304.8k @ P90 49.0 vs 304.7k @ 49.5 for the earlier
revision, 8k c108 341.9k @ 32.5 vs 343.0k @ 32.3; PD 3P2D c336 (prefill
role, without #2943) 272.3k vs 271.8k.

## Test Plan

- [x] `pre-commit run --all-files`
- [x] CPU: sizing, reservation before pool sizing, startup refusals,
routing and fallbacks, view-only serving; Triton kernels against the
PyTorch reference under `TRITON_INTERPRET=1`; offline CuTe compile (FP8
PTX unchanged)
- [x] GPU (GB300, before the rebase, FlashInfer 0.7.2.post1, in a build
that merges our other open PRs onto main): kernel and runtime CUDA
tests, against both FP8 prefill paths, bitwise against the BF16 kernel,
no allocation or compile after warm-up (312 kernel and 73 runtime tests
passed)
- [x] Rebased onto main `8808f143b`: one conflict, the `ForwardMode`
type-checking import that #2897 also added to `paged/qsa.py`; the
kernels, `bf16_scratch.py` and the tests are unchanged. CPU, rebased
head against main: the runtime and kernel tests importing the touched
modules fail the same tests on both, none new; the 31 CPU tests added
here pass.
- [x] GPU on the rebased head (GB300, main `8808f143b`, FlashInfer
0.7.3): this PR's QSA kernel and runtime tests pass (918 kernel and 574
runtime tests passed); the 32 failures are main's PrimTS QSA tests,
which fail without this PR too (`qsa_prims.py` passes `seq_len_q`, which
FlashInfer 0.7.3 renamed `group_size`).
- [ ] BF16-KV decode timing (the zero-filled gathers apply to every
BF16-KV call)
- [x] Re-measure the PR head on GB300 (above)
- [ ] Measure against the default FA2 prefill

---------

Signed-off-by: Fan Yang <250624800+fanyang-real@users.noreply.github.com>
2026-11-06 23:24:28 -08:00
dongjiyingdjy 1f03f5ee4e perf(kvp): gather MLA prefix history with a fused all-gather on GB300
## Summary

On SM100 and SM103 GPUs with KV page sharding (KVP), the MLA prefix-history gather of chunked prefill now runs one CuteDSL kernel per window instead of an `index_select` pack plus an NCCL all-gather. Each rank reads the rows it owns straight out of the paged KV cache and stores them into every rank's receive slot, through NVLink multicast, or with one store per peer where multicast is unavailable. The reads get the same bytes as from the all-gather.

## Behavior changes

- **No new flag.** Each KVP group votes once at startup for multicast, then peer stores, else the existing NCCL all-gather. It keeps NCCL and allocates nothing when the GPU is not SM100 or SM103, chunked prefill is off, the model reads no MLA prefix history through `PrefixHistoryGather`, the KV cache is `per_token_head` quantized, the role is PD decode, one receive slot would take 2 GiB or more (such as at KVP8 with an FP8 cache and `--chunked-prefill-size 131072`), or a configured kernel could deadlock with a window in flight (MegaMoE, DeepEP's low-latency all-to-all, fused DP projections).
- **Windows.** A receive slot holds the MLA history capacity per rank (`chunked_prefill_size x mla_chunk_multiplier` rows), so any prefix loop fits however its pages are owned. A fused window joins consecutive loops while its busiest owner still fits, counted from the host page tables, so every rank plans the same windows. NCCL windows keep four loops, and a reader whose rows the transport does not take (another row width or dtype) uses them.
- **CTAs depend only on the group size**: multicast launches 8, 4 and 2 CTAs for 2, 4 and 8 ranks. Each CTA sends about 40 GB per second and each GPU receives near 600 GB per second from all ranks, so the fewest CTAs that saturate the receiver follow from the group size (CTAs x ranks = 16); more only slow the overlapping compute. Calibrated on GB300; peer mode keeps 24.
- **Memory**: `2 x kvp_size x capacity x row bytes` per GPU, reserved before the KV cache is sized: 288 MiB at KVP8 with FP8 MLA rows, 0.6% of the KV budget in the configuration below.

## Performance

Measured before the rebase onto main 4a80b2b71.

Kimi-K3 NVFP4, KVP8 on 8 GB300 GPUs, one server alternating the NCCL and fused paths by forward (95% CI). 1M-token prefix rounds:

| | NCCL all-gather | Fused | Change |
| --- | --- | --- | --- |
| Request cycle | 1092.1 ms | 1025.4 ms | -5.9% [-7.4, -4.5] |
| Forward | 743.9 ms | 676.2 ms | -9.6% [-10.2, -9.0] |
| Host time per window | 248 us | 110 us | -138 us |

Per-window timeline (forward GPU span, and the wait before consuming windows summed per forward):

| Prefix + new tokens | Windows per layer, NCCL and fused | Forward change | Wait per forward, NCCL and fused |
| --- | --- | --- | --- |
| 500K + 128 | 4 and 2 | -6.4% | 61 and 1 ms |
| 1M + 128 | 8 and 4 | -8.5% | 273 and 91 ms |
| 8 requests, 8K to 1M | 16 and 9 | -8.3% | 895 and 706 ms |

Windows 0 and 1 wait about 3 us on both paths; later windows wait for the last rank's host to issue its share, not for the transfer.

Gather alone, GPU time, pack + NCCL -> fused (us):

| Rows per rank | 2 ranks, 8 CTAs | 4 ranks, 4 CTAs | 8 ranks, 2 CTAs |
| --- | --- | --- | --- |
| 512 | 22.3 -> 20.5 | 26.8 -> 22.9 | 39.2 -> 28.7 |
| 8192 | 47.1 -> 32.8 | 75.8 -> 49.2 | 137.2 -> 78.1 |
| 32768 | 88.0 -> 73.7 | 144.0 -> 127.1 | 262.3 -> 237.6 |

Agentic serving on an earlier revision (Kimi-K3, DCP8, concurrency 56, by @Xiangyi1996): within noise end to end ([details](https://github.com/lightseekorg/tokenspeed/pull/2871#issuecomment-6594191985)).

## Test Plan

Byte-exact against the NCCL path in kernel tests (2 and 4 GPUs), runtime tests (2, 4 and 8 ranks, including skewed ownership and shared-capacity layouts), and 788,544 server-side loop comparisons, 0 mismatches. The 2-GPU runtime test that CI runs also covers the startup refusals, the poisoning of a failed launch or drain, and the kernel's entry and window-header traps; the trap cases pass at 2, 4 and 8 ranks. Run on GB300; compiled for sm_100a.


Signed-off-by: dongjiyingdjy <87510204+dongjiyingdjy@users.noreply.github.com>
2026-11-06 06:57:38 -08:00
78f9dc00a2 fix(cache): share Qwen4-Exp PLE state planes under FP8 KV (#2726)
## Summary

Under FP8 KV, Qwen4-Exp's PLE state (180 KiB per block) is wider than
one FP8 K page (128 KiB), so `Qwen4ExpRecipe.groups()` gave it a plane
of its own. Every parent lays out every plane, and a parent belongs to
one cache group at a time, so that plane sits empty in every K and
recurrent-state parent. For Qwen3.8-Flash-Next with FP8 KV that is 36.6%
of the cache arena: 64,489,472-byte parents instead of 40,894,464.

A side group is now checked against the largest decoder field on each
plane, since every plane is at least that wide (the recurrent state is
twelve FP8 K pages). The PLE state packs eight per parent on the shared
planes, and the same cache budget holds 57.7% more parents. Sharing can
put a group's layers on planes of different widths, so the PLE verify
and commit path now copies each layer's state at its own page stride
instead of requiring one stride for all layers.

A group wider than one K page shares only if no pipeline stage of this
engine then holds more bytes: a stage allocates every plane its layers'
fields touch, whole, so a field on a plane that no other layer of its
stage uses costs that stage the whole plane, which can exceed the plane
of its own that sharing saves. Without PP the one stage holds every
plane anyway. BF16 KV, where the PLE state already fit one K page, keeps
its layout, and the compressed QSA keys keep their exact-stride check.

## Test Plan

- New
`test_qwen4_exp_ple_state_wider_than_an_fp8_k_page_adds_no_parent_bytes`:
fails before the change (84,224-byte vs 65,536-byte parents) and passes
after.
- New `test_cache_setup.py` cases: the verify workspace accepts uneven
PLE page strides, commit writes each layer at its own page stride,
sharing is kept only while no pipeline stage grows (the last stage also
holds the drafter), and the served Qwen3.8-Flash-Next shape costs no
parents with one or two pipeline stages.
- `test_qwen4_exp.py`, `test_cache_setup.py`,
`test_qwen4_exp_cache_without_gdn.py`, `test_qwen4_exp_ple_backend.py`,
`test_unified_kv_slab_pool.py`, `test_cache_group_router.py`,
`test_ple_state_checkpoint_in_forward.py`, `test_host_cache_storage.py`:
519 passed.
- `pre-commit run --all-files` (markdownlint skipped: its npm install is
blocked on my machine).
- GB300, Qwen3.8-Flash-Next NVFP4, FP8 KV, `--gpu-memory-utilization
0.94`: the server now logs 4,750 parents of 40,894,464 bytes on a fused
server (3,012 of 64,489,472 before) from the same 194.3 GB arena, and
4,764-4,797 on PD prefill and decode servers (3,029 on decode before).
Same servers, AgentX replay for 3600 s, the `nightly-621b53` image with
and without this change:
  - GSM8K: single 0.9765 (0.9750 without), 2P1D 0.9795 (0.9795).
- 1P1D c72: 113.1k tokens per second per GPU at P90 95.7 tokens per
second per user vs 83.7k at 110.7. The prefill's prefix-hit rate holds
at 85.7% (81.8% without).
- 2P1D c144, decode `--max-num-seqs 88`: 128.5k at P90 73.0, 0 errors.
Without the change the best 2P1D point is 111.8k at P90 84.2 (decode
window 56); the decode's cache overflows above about 56 long contexts.
- Single: no throughput change (c56 155.8k vs a 154.8k peak); the fused
server is compute-bound there.

---------

Signed-off-by: Fan Yang <250624800+fanyang-real@users.noreply.github.com>
Signed-off-by: lightseek-bot <243258330+lightseek-bot@users.noreply.github.com>
Co-authored-by: Tuan Zhang <tuan@lightseek.org>
Co-authored-by: lightseek-bot <243258330+lightseek-bot@users.noreply.github.com>
2026-11-02 22:25:14 -08:00
Eric fdd4a90c51 feat(muse): serve Muse Spark with a DFlash2 draft (#2891)
## Summary

- Before: Muse Spark could not serve a DFLASH draft. Startup failed in
cache planning, and the forward handed the draft no target hidden
states.
- Cache planning: the ordinary recipe appends the draft's layer types
after the target's, but took the sliding windows from the target config
alone, so a target that lists one window per layer failed with
"sliding_window_tokens has 62 entries but layer_types has 67".
`OrdinaryRecipe.sliding_window_tokens` now resolves target and draft
windows against their own layer types and concatenates them. A single
target window is returned unchanged, so existing models plan as before.
- Hidden-state taps: Muse Spark's decoder loop overrides the base
forward and returned no taps. It now rounds the FP32 residual stream
entering each capture layer (and the final stream before the output
norm) to BF16, the dtype the draft reads, and hands it to the forward's
capture sink.
- When each rank holds only its share of the token rows, it all-gathers
only the tapped streams; the other layers keep that layout.
- `get_input_embeddings` exposes the raw token embedding, without Muse's
input norm, which is how the draft embeds its own tokens.
- `supports_aux_capture` opts Muse Spark in, so the capture setters
accept the draft instead of refusing it at startup.
- Applies to Muse Spark with a DFLASH or DSpark draft. The
cache-planning fix also covers any target that lists one window per
layer and has a draft; such targets previously failed to start.
- Measured effect: DFlash2 draft on 8x MI355X (MXFP4 target, verify
width 8), GSM8K test[:200], C16: with tensor parallelism 8 and expert
parallelism 1, 96.5% (no-spec 96.5%), accept length 4.94; with tensor
parallelism 8 and expert parallelism 8, 97.5%, accept length 4.95.

## Test Plan

- Rebased onto main `c242ed0ce` and re-run on 8x MI355X at this PR's
tip: `test_aux_capture.py`, `test_muse_spark.py` and
`test_cache_setup.py`, 221 passed, 1 skipped. The accuracy runs above
are from the earlier main `96c45352b`. The split was checked on CPU
(compile, `pre-commit run --all-files`).
- New tests check the taps' values and order, that an idle forward taps
nothing, and that split rows are gathered to full rows; the taps and
split-row tests fail on the old code.
- `test_cache_setup.py` plans a per-layer-window target with a two-layer
draft; it fails on the old code with the startup error above.

---------

Signed-off-by: Eric Feng <Eric.Feng@amd.com>
2026-11-02 20:16:41 -08:00
Nicolas Perrin 62739995d4 refactor(cache): read the GDN SSM state dtype from server args (#2862)
## Summary

The GDN and Mamba2 cache recipes (`QwenGDNRecipe`, and through it
`Mamba2Recipe` and `Qwen4ExpRecipe`) got `--mamba-ssm-dtype` through an
environment variable:

1. `ServerArgs` wrote `TOKENSPEED_MAMBA_SSM_DTYPE`.
2. The recipe read it back.

The recipe already holds `server_args`, so it now reads
`server_args.mamba_ssm_dtype` directly, as the KDA recipes do through
`kda_recurrent_state_dtype`. The environment variable is removed.

The selected dtype is unchanged: `ServerArgs` always overwrote the
variable from the flag before any recipe read it.

## Testing

- `test_qwen4_side_caches_preserve_kv_capacity` now sets the dtype on
its `server_args` stub instead of patching the environment. It still
covers both dtypes.
- The cache-recipe tests that build `server_args` as a `SimpleNamespace`
now set `mamba_ssm_dtype` (`test_cache_setup.py`, `test_nemotron_h.py`,
`test_qwen4_exp.py`).
- `ruff check --select F` is clean on the touched files.
- `pre-commit run --all-files` passes.
- The 150 runtime test files that import a touched module or build a
cache recipe were run on this branch and on its base. Both runs have the
same 91 failures and the same 2 collection errors. They come from an
environment whose compiled scheduler and kernel packages predate the
base, so tests that need newer scheduler or kernel symbols fail on both.

Signed-off-by: Nicolas Perrin <nperrin.ai@gmail.com>
2026-10-31 11:45:42 -04:00
FC.Liandlongcat-ia-team 73ab3056b9 refactor(cache): let each cache recipe declare its prefix granularity (#2830)
## Summary

The prefix granularity used to be chosen through three layers: the
`--prefix-granularity` flag (alias `--block-size`, default 64), a family
or `ModelProfile` default that applied only when the flag still read 64,
and recipes that overrode the value outright. Four recipes (Qwen3.5 GDN,
Kimi-K3, Inkling, GLM-5.3-Flash) hardcoded it and silently ignored an
explicit flag. In practice the usable value is fixed by the kernels that
read the cache, so this makes the cache recipe its only owner.

- `CacheRecipe.prefix_granularity` is abstract. Every recipe declares
its grain, and the memory plan carries it to the scheduler, PD, L3 and
KV events as before.
- The ordinary MHA, MLA, DSA and MSA recipe makes one block span the
grain, so it uses the lcm of 64, a fixed-page leaf's kernel page, the
MSA sparse page (128) and the MXFP8 scale tile (128). The registry pins
a fixed-page leaf's page on the side's `AttnConfig.kernel_page_size`
before planning; the leaf resolves the same value from it.
- DeepSeek V4.1 declares 256 and dots3-note 128, the values their family
defaults used to set.
- Removed: `--prefix-granularity`, `--block-size`,
`_AttentionFamilySpec.default_prefix_granularity`,
`ModelProfile.default_prefix_granularity` and
`AttnConfig.prefix_granularity`. There is no override.
- GDN decides whether its scan can store in-forward checkpoints when a
pool binds, using the contract's grain instead of the launch value.
- Removed code left without users: `ServerArgs.mamba_cache_chunk_size`,
`AscendPrefillOptions.from_config` and `DEEPSEEK_V4_PAGE_SIZE`.

`docs/design/cache-concepts.md` now records where the grain comes from.
Server docs, model recipes and CI and benchmark configs no longer pass
the flag.

## Behavior changes

- GPU defaults stay the same for every in-tree family that has a model.
DeepSeek V4 (not V4.1) has had no model since #2310, so its family spec,
which still set 256, now falls to the ordinary 64; #2835 removes the V4
leftovers.
- MXFP8 KV no longer needs `--prefix-granularity 128`; the recipe widens
to the scale tile.
- Ascend MLA and DSA (128-token kernel pages) now get 128 without a
flag.
- The NPU Qwen3-0.6B recipe used to pass 128 and now runs at 64; the NPU
MHA kernels accept 64 and 128.
- Launch scripts that still pass `--block-size` or
`--prefix-granularity` now fail with an unknown-argument error.
- Out-of-tree plugins must drop `default_prefix_granularity` from their
`ModelProfile` and declare `prefix_granularity` on their recipes.

## Test Plan

- Ran the 115 test files that touch the grain, recipes or kernel pages
on this branch and on its base, in the same environment (8x H20). No new
failures; the remaining failures fail on the base too.
- New tests: the ordinary recipe's grain for flexible, fixed-page, MSA,
MXFP8 and draft-side pages; the registry pins a fixed page and leaves
flexible and MSA leaves alone; MXFP8 widens to 128 and rejects a wider
page; dots3-note's grain holds whole pages of both groups.
- `pre-commit run --all-files` passes.
- The GDN in-forward checkpoint test is skipped on H20, which has no
checkpointing GDN prefill kernel.

Co-authored-by: longcat-ia-team <longcat_ia_team@meituan.com>

Signed-off-by: FC-Li <robert_lexis@163.com>
Co-authored-by: longcat-ia-team <longcat_ia_team@meituan.com>
2026-10-31 08:10:38 +08:00
Hang Yuandlongcat-ia-team 92bc207202 fix(cache): resolve the PP and QCP KV cache logical-capacity issue (#2741)
## Summary

PP and QCP could reserve the wrong amount of L1 KV cache. Capacity was
chosen
from the full model's per-parent cost before PP ownership reduced the
resident
planes, so a stage kept the full-model parent count while allocating
only its
local planes and left usable cache budget idle. QCP's fixed
gathered-history
workspace was also not consistently charged before parent selection in
`OrdinaryRecipe`, so the advertised logical token capacity could exceed
the
bytes the rank could actually allocate.

This change keeps the logical layout global but sizes capacity from each
rank's
resident planes. It projects the complete layout onto the PP window,
charges the
recipe's fixed workspace, reserves the null parent, agrees on one parent
limit
across the rollout group, and only then applies the model/token caps.
The full
layout is bound once; PP narrows physical allocation afterward without
changing
capacity, so group packing, global field IDs, KVP shard semantics, and
the PD
contract stay common.

## Test Plan

- `pytest test/runtime/test_cache_capacity.py
test/runtime/test_cache_setup.py
  test/runtime/test_cudagraph_probe_arena.py
  test/runtime/test_glm53_flash_cache_spec.py`
- `pre-commit run --all-files`
- Four-card LongCat A3B capacity matrix: 15 startup/exit cases on 4×H800
covering
PP1/PP2/PP4, TP4/TP2/TP1, QCP1/2/4, KVP, and host/device OE. Every case
checks the capacity contract and `arena + fixed workspace <= cache
budget`.
  - PP2×TP2: 6,751 → 13,504 parents; arena 7.74 → 15.49 GB/rank.
- PP4×TP1: 19,728 → 69,052 parents; arena 9.70–12.93 → 33.94–45.25
GB/rank.
- PP2×TP2 + QCP2/KVP2: 19,817 → 39,635 parents; arena 22.73 → 45.46
GB/rank.
- PP1×TP4 + QCP4/KVP4: 18,728 parents and 42.96 GB/rank before and
after;
    the LongCat recipe already reserved the QCP workspace.
- QCP workspace: 92,274,688 bytes/rank for the 65K cases, verified
separately
  from arena bytes.
- Numeric smoke: the PP2 fixed-capacity and auto-capacity groups
completed seven
first-token requests each; greedy token IDs matched and the
sampled-token
  logprob maximum difference was 0.

Co-authored-by: longcat-ia-team <longcat_ia_team@meituan.com>
2026-10-27 23:43:43 +08:00
Wang changran 593f306242 feat(epd): support external encoders with aggregated serving (#2714)
## Summary

Support external encoders with aggregated serving via
--enable-external-encoder.

Reuse the existing embedding receive pools and admission flow with a
standalone Mooncake transport, allowing one LLM worker to perform both
prefill and decode. Preserve the existing EPD path and use the
platform-selected transport protocol.

## Test Plan

- EPD and server argument tests: 167 passed, 25 subtests passed.
- pre-commit run --all-files: passed.
- Text, local image paths, and Base64 image requests: passed.

---------

Signed-off-by: wangchangran <shinewang96@gmail.com>
2026-10-27 13:38:09 +08:00
Lei Zhang b9927ec411 test(runtime): trim duplicated and low-value runtime-1gpu tests (#2680)
Cut CI time of the runtime-1gpu suite on gfx950 runners, where most of
each file's cost is process startup:

- Drop parametrizations that repeat a covered path in the slowest file,
test_startup_process_ownership.py: SIGUSR1 and SIGQUIT share one
handler.
- Disable files whose every test skips off NVIDIA on amd-* runners, so
they no longer pay startup only to skip.
- Remove test_deepseek_v4_slot_mappings.py (field-absence check) and
test_table_export_fast.py (covered by test_block_tables_bridge.py).
- Avoid a needless spawned process in test_metrics_server.py.
- Remove trivial argument-validation tests (types, positivity, lengths,
required fields) and structure-only checks (field, method placement,
signature), and fold one-flag CLI round trips into one table test.
- Narrow the lm_head dtype matrix to the bounding shards and dtypes.

Signed-off-by: Lei Zhang <antiagainst@gmail.com>
2026-10-24 22:48:16 -07:00
FC.Liandlongcat-ia-team eb67f44237 feat(engine): run every engine rank on the Rust control plane (RFC 0002) (#2603)
## 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>
2026-10-25 11:48:13 +08:00
df97067396 feat(kda): use RecoverSSM records for accepted-state commit (#2240)
KDA currently replays accepted speculative tokens to recompute their
recurrent state. This PR uses vLLM RecoverSSM records produced during
verification to reconstruct that state.

**The latest pooled E2E speedups are 1.027× at C8, 1.014× at C16, and
1.013× at C32.** These correspond to median latency reductions of 2.67%,
1.41%, and 1.24%, respectively, at fixed synthetic acceptance. These are
modest improvements in pooled medians; individual runs and scheduler
groupings still vary.

The implementation:

- Adapts RecoverSSM from vLLM commit
`c77b3faa1cc2c39edbe82365f28ce96981af1438`, retaining the Apache-2.0
license. Integration stays behind `tokenspeed-kernel`, without a vLLM
runtime dependency.
- Runs convolution and gate projection before verification. Verify keeps
the upstream recurrence, preloads candidate inputs before recurrent
stores, limits register use, and saves FP32 corrections (`U`), BF16
unnormalized keys (`K`), and BF16 raw gates. Explicit metadata
assertions remain enabled; automatic integer-overflow instrumentation is
disabled for verify.
- Recovers the accepted state by recomputing key normalization and gate
decay, then applying the saved corrections. Commit avoids recomputing
the state-dependent corrections and gate projection.
- Batches recurrent recovery across KDA layers and retains the
convolution-state commit.
- Integrates with scheduler-owned input and live state pages. Generation
and position stamps identify records from the current verification
round.
- Updates workspace accounting and supports eager execution, CUDA
graphs, padded rows, strided pages, and in-place commits.
- Retains pre-existing tests, with updates for the record format and
state-page interface.

Records cover the current speculative window. Persistent history across
rounds is outside this PR.

Validation completed on PR1 commit `1c5d7660`:

- 141 RecoverSSM kernel cases passed.
- 21 runtime commit tests passed.
- 40 pinned-upstream verify/commit comparisons passed; verify outputs
and FP32 corrections matched upstream bit for bit.
- The deterministic acceptance schedule passed GPU checks with CUDA
graph replay and reordered rows.
- `pre-commit run --all-files` passed.

Numerical tests cover verify outputs, recovered states, every accepted
prefix at window lengths 1/2/3/4/8, multiple layers and rounds,
convolution state, page selection, non-power-of-two rings, and absolute
record positions beyond 32 bits. References account for each
implementation’s producer precision. These checks do not establish
bitwise equivalence with main.

Performance compares main `d5a4c0b0da8ba74c1867912c59920ab3de88236e`
with PR1 `b1c0f473ce399170323fd2d793791c2f451163ec`. PR1 includes that
main revision, the NVIDIA QKV retention optimization, and the debug-mode
cleanup. Both commits were tested in isolated worktrees with the same
benchmark-only acceptance schedule.

The workload uses an NVFP4 KDA model, TP8 on eight GB300 GPUs, BF16
activations, FP8 KV cache, MTP3 (the same EAGLE3 drafter as the previous
comparison, with three draft steps and four verify tokens), and greedy
sampling with seed 1. Each measured request has 51,936 input tokens,
including a 51,840-token cached prefix, and generates 371 tokens. MTP3
commits at most four tokens per round, so this workload selects CUDA
Core recovery; it does not exercise the TF32x3 recovery path.

Both implementations use `--synthetic-acceptance-length 3.7` and
`--sampling-backend greedy`, with an identical benchmark-only
position-based 3/4 acceptance schedule. Each request has 100 productive
verify rounds: seven four-token rounds and three three-token rounds per
ten-round cycle. The 371 output tokens include one bootstrap token and
370 tokens accepted in these rounds.

Every comparison below is **main latency → PR1 latency (speedup)**.
Speedup is main latency divided by PR1 latency; values below 1× indicate
a slowdown. E2E is the time from client barrier release until all
requests in the wave complete.

| Concurrency | Requests per implementation | E2E (ms) | Avg. accepted
length, both | Draft acceptance rate, both |
|---:|---:|---:|---:|---:|
| 8 | 144 | 2998.731 → 2918.762 (**1.027× speedup**) | 3.700 | 90.0% |
| 16 | 288 | 3660.375 → 3608.588 (**1.014× speedup**) | 3.700 | 90.0% |
| 32 | 576 | 5064.591 → 5001.995 (**1.013× speedup**) | 3.700 | 90.0% |

PR1's pooled median latency decreases by 2.67%, 1.41%, and 1.24% at C8,
C16, and C32, respectively. The primary table retains all measured
waves, including waves with compilation or different prefill groupings.
All measured waves have 100 productive decode rounds at the requested
full batch size.

Both implementations run on the same eight GPUs and package versions in
main → PR1 → PR1 → main order. Each server start has two warmup waves
and nine measured waves per concurrency. Each table entry is the median
of 18 measured waves across two independent server starts. There are 108
measured waves and 2,016 measured requests in total: 1,008 requests per
implementation. Startup, cache priming, and warmup are excluded from
timing.

The profiler and GPU stage markers are disabled. Acceptance and request
logging are enabled identically in both implementations. This run
provides E2E measurements only; separate full-model verify, KDA
recurrence, and commit stage timings were not collected. Earlier stage
measurements used older revisions and different instrumentation.

Per-request statistics verify 270 accepted draft tokens out of 300
candidates for every measured request. Average accepted length includes
the target token; draft acceptance rate is `(3.7 − 1) / 3 = 90%`.

For comparison, the subset with no logged Triton compilation and all 100
productive rounds at the requested full batch size gives:

| Concurrency | Retained waves, main / PR1 | E2E (ms) |
|---:|---:|---:|
| 8 | 17 / 17 | 2998.058 → 2921.182 (**1.026× speedup**) |
| 16 | 16 / 15 | 3639.813 → 3586.042 (**1.015× speedup**) |
| 32 | 18 / 18 | 5064.591 → 5001.995 (**1.013× speedup**) |

This subset retains all prefill groupings. It does not force matching
scheduler behavior. Each wave releases requests with identical input
tokens and stable request indices through a shared client barrier, but
HTTP arrival order, initial prefill grouping, generated tokens, and MoE
routing are not forced to match.

All 2,016 measured requests passed the workload checks for input length,
cached prefix, output length, verify-round count, and accepted draft
tokens. GPU identities, package versions, frozen source hashes, and
shared native-library hashes were verified across all four starts. The
benchmark-only acceptance schedule also passed GPU checks for CUDA graph
replay, reordered rows, and bootstrap rows.

Synthetic acceptance controls the amount of accepted work; it does not
measure natural acceptance or model accuracy. Benchmark instrumentation
and the deterministic acceptance schedule are excluded from the PR.
Compare main and PR1 within this run; the baseline and instrumentation
differ from earlier measurements.

---------

Signed-off-by: Bo Hsueh <11360707+byshiue@users.noreply.github.com>
Signed-off-by: Yu-Zhewen <zhewenyu@amd.com>
Co-authored-by: Zhewen Yu <zhewenyu@amd.com>
Co-authored-by: Pengzhan Zhao <borontion@gmail.com>
2026-10-23 21:13:08 -07:00
Nicolas Perrin d64e1dd574 feat(spec): add EAGLE-4 speculative decoding (#2547)
## Summary

Adds EAGLE-4 speculative decoding: the `LlamaForCausalLMEagle4` draft
model with its low-rank candidate head (`--speculative-algorithm
EAGLE4`), and EAGLE-Harness, a drafter that sizes every round's draft
tree or chain on the device from measured cost data
(`--speculative-exec-mode` modes 0 and 1, measured with exec mode `2`).

**Draft model** (`models/llama_eagle4.py`)
- EAGLE-3 layer plus per-aux `fc_norm`, `norm_output`, an optional
sliding-window draft layer, optional `attn_norm` and `eh_proj`,
`use_rope: false`, and Nemotron-H's latent MoE (`moe_architecture:
nemotron_latent_relu2`).
- Candidate head: rank-r scores over the vocab shard, shard top-k, exact
logits for the candidates (`eagle4_candidate.cu`,
`ops/sampling/triton/candidate_head.py`); under TP the ranks gather
their candidates and keep the top `nc` by exact logits.
- Loading refuses unknown config keys, unused or repeated checkpoint
tensors, missing Q, K, V, gate or up shards, and a vocab its LM heads
pad across TP shards (a shard's top-k could pick the zero rows).

**EAGLE-Harness** (`execution/drafter/eagle_harness/`)
- `DevicePolicy` picks each round's draft depth and verify width on the
device from cost tables keyed by batch size and context; chains can also
follow `--speculative-chain-width-table`.
- Each depth is a captured graph that, after its on-device decision,
launches the next depth or the finalize (`eagle_harness_chain.cu`), so
the host launches only depth 1; eager rounds poll a pinned go flag
instead.
- A round drafts on its own stream after the forward returns and is
joined in the next forward's settle (`BaseDrafter.finish_round` and
`complete_round`).
- `measure_run` serves exec mode `2` engines over a batch-size sweep and
writes the cost data serving reads from `--speculative-data-path`.

**Sampling**
- `TreeRejectionSampler` (flashinfer backend) verifies sampled trees by
recursive rejection sampling against the draft q that drew each node's
children (`RuntimeStates.future_draft_q`); children without a draft q
are accepted by p'(child) over the mass their rejected siblings left, so
the emitted tokens follow the target distribution.
- `tree_window_attention` takes a `causal_prefix` flag, so a
sliding-window draft layer reads its window frozen at the round's prefix
end (each row's partial then covers its whole prefix).

Docs: `docs/configuration/server.md` (flags, limits, measurement
workflow) and `docs/design/tree-speculation.md`, `event-loop.md` and
`unified_path.md`.

**Design notes**
- Under TP the candidate head keeps the top `nc` of the gathered shard
candidates by exact logits, as the EAGLE-4 reference does, so TP>1 can
draft different candidates than TP1.
- The sliding-window draft layer reads the window frozen at the prefix
end for the whole round; this changes acceptance only, never the output
distribution (verification is against the target).

**Review fixes in this round**
- `tree_reject_sample_kernel` accepts a child the draft did not sample
with exactly p'(child) over the mass its rejected siblings left (the
additive offsets biased acceptance) and never reads an out-of-vocab
token; a distribution test covers it.
- `fused_topk_topp` computes row offsets in `size_t` (8192 rows of a
300k vocab overflow int32).
- Cost data must have strictly increasing widths, and exec mode `1`
batch cuts must fit the verify budget.
- Under attention TP, rank 0 reads the cost data, `measure_config.json`
and `benchmark_config.json` and broadcasts them over a named gloo group,
so ranks never decide from different files.
- `shutdown_cache` settles the last pending round on the forward thread
even without a host cache.
- Comments trimmed to one line; tests drive real classes (`Eagle4`,
`MHATokenToKVPool`, `PagedAttention`, the scheduler's decode batch)
instead of stand-ins.
- `robust_mean` converges on identical samples (they were all dropped on
a NaN z-score, so a stable batch failed measurement); chain cost data
must measure exactly widths 1, 2, 4, ..., 16; EAGLE-4 lanes copy per-row
page tables only when a draft layer slides, through a `_make_tree_lanes`
hook instead of bind-then-rebind; `DevicePolicy` takes `file_group` as a
required keyword; the EAGLE-Harness kernel tests skip cleanly without a
GPU. The missing docstrings (`load_records`, `Eagle4LlamaModel`,
`LlamaForCausalLMEagle4`) are added.
- Merged with main's asynchronous L3
(https://github.com/lightseekorg/tokenspeed/pull/2483). Its startup
preparation of every logits processor's distributed argmax would hand
EAGLE-4's `num_candidates`-wide candidate logits to the fused
vocab-shard argmax at TP>1, which asserts on the first draft step; the
candidate head now argmaxes locally, as before, and a two-GPU test
(`test_eagle4_candidate_head_tp.py`) fails without that. The L3 key
carries EAGLE-4's captured aux layers like EAGLE-3's.

## Test Plan

All GPU runs on GB200, TP1 unless noted. Serving ran on the review-fix
state of the branch (the cleanup after it changes comments and tests
only), with the regression arms on main; the last review round was
compared against it (below).

**Unit tests**
- `runtime-1gpu` suite (`run_ci_suite.py`): 237 of 239 files pass; the
two failures (`test_generation_models::test_others`,
`test_instanttensor_loader`) fail identically on main.
- Kernel tests touched by the PR
(`tokenspeed-kernel/test/ops/{test_candidate_head,test_sampling,test_tree_speculative}.py`,
`test/nvidia/thirdparty/`, `test_softmax_flashinfer.py`): 605 passed.
- Unregistered runtime tests the PR edits: all pass except failures main
shares (`test_device_handle` dflash_rebound x6: its platform fake lacks
`is_cdna4`; `test_zero_output_prefill` x7: its fakes lack `kvp_size`,
`global_num_decodes` and `attn_backend`).
- New tests: deterministic-children distribution (8192 x 24 trials, atol
0.005), cost-width validation, first-rank file reads over a 2-process
gloo group, `shutdown_cache` without a host cache, padded-vocab,
missing-shard and repeated-expert loader refusals.
- `pre-commit run --all-files` clean.
- Last review round: the EAGLE-4 and harness runtime tests (204) and
kernel tests (544) pass; serving it against the review-fix state gives
identical outputs (greedy 64 of 64, long 6 of 6, sampled 32 of 32) and
matching GSM8K and throughput on the Qwen3.8 static tree, the Qwen3.8
harness tree (5x4, 16) and the Nemotron tree.

**Regression A versus B vs main** (2 rounds each; greedy c=1 x64, long
x6, sampled x32 compared on round 2; GSM8K 200 at c=32)

| Config | Outputs main vs PR | GSM8K main and PR | tokens per second
c=1 main and PR | c=32 main and PR | accept main and PR |
|---|---|---|---|---|---|
| Qwen3.5-35B-A3B-FP8 non-spec | identical 64 of 64, 6 of 6, 32 of 32 |
0.965 and 0.965 | 300.0 and 302.2 | 4401 and 4394 | - |
| Qwen3.5-35B-A3B-FP8 MTP chain (3 steps) | identical | 0.955 and 0.960
| 472.5 and 474.6 | 6273 and 6293 | 2.985 and 2.990 |
| Qwen3.5-35B-A3B-FP8 MTP tree (5x4, 16) | identical | 0.960 and 0.965 |
522.5 and 526.3 | 5450 and 5524 | 4.445 and 4.425 |
| Qwen3.8-27B DFlash2 (fp8 KV) | identical | 0.975 and 0.975 | 261.7 and
261.4 | 3722 and 3667 | 4.414 and 4.400 |
| Llama-3.1-8B EAGLE-3 chain (3 steps) | identical | 0.870 and 0.870 |
569.9 and 566.2 | 8124 and 8125 | 2.288 and 2.285 |
| Llama-3.1-8B EAGLE-3 tree (5x4, 16) | identical | 0.875 and 0.875 |
557.4 and 568.2 | 6383 and 6329 | 3.168 and 3.176 |

KV capacity (`max_total_num_tokens`) matches main in every config
(run-to-run spread under 0.05%). The Llama runs need
`TOKENSPEED_ALLOW_OVERWRITE_LONGER_CONTEXT_LEN=1` (the EAGLE-3 draft
caps context at 2048); in the tree config's first round, main and this
branch both hit an illegal memory access at the same point of the
long-output dump, and the second round was clean.

**Kimi-K2.5-NVFP4 EAGLE-3** (the `eval-kimi-k2.5-nvfp4-eagle3-aime25`
server flags, TP4, main against this branch, 2 rounds each): greedy c=1
outputs are identical across all four runs (GSM8K 64 of 64, long 6 of 6,
AIME25 30 of 30 at 2048 tokens), and acceptance matches (1.88 to 1.90).
Full AIME25 at c=16 scores 29 then 27 of 30 on main and 28 of 30 twice
on this branch: batched greedy decoding is not deterministic, so this
check's 0.93 threshold (28 of 30) also fails on main, and its 0.900 runs
here are noise.

**After merging main** (GB200)
- `runtime-1gpu` suite: 241 of 243 files pass;
`test_instanttensor_loader` fails on main too, and
`test_generation_models::test_others` fails on main too and now hangs
there until the file timeout. The PR's kernel tests pass (605), and
`test_eagle4_candidate_head_tp.py` passes on two GPUs and fails with the
candidate head's opt-out removed.
- Against main (round 2): Llama-3.1-8B EAGLE-3 chain identical (greedy
64 of 64, sampled 32 of 32), Qwen3.5-35B-A3B MTP tree identical (greedy
64 of 64, long 6 of 6, sampled 32 of 32).
- EAGLE-4 matches the tables below: Qwen3.8 tree TP1 0.965, 303 tokens
per second at c=1, 3118 at c=32; TP2 0.965, 464, 4745; harness tree
(5x4, 16) 0.970, 311, 3131; chain 0.975, 242, 3967; Nemotron tree 0.950,
390, 2362. KV capacity is 1 to 2% lower, from main's larger default
prefill-graph capture (8192 tokens).
-
`test_startup_process_ownership::test_repeated_failure_signals_cannot_interrupt_owner_cleanup`,
new on main, is flaky: it failed 1 of 8 runs on main and 2 of 8 on this
branch on GB200, and once each on this branch's B200 and MI355 unit-test
jobs.
- Merged main again (the conflict with
https://github.com/lightseekorg/tokenspeed/pull/2620's pad-tape tails
keeps main's block in `fill_input_buffers`): `runtime-1gpu` 241 of 243
(the same two main failures); against main, Qwen3.5 MTP tree, Qwen3.5
MTP chain and Llama EAGLE-3 chain stay identical (greedy, long,
sampled), and with `--grammar-backend xgrammar` the chains' JSON-schema
outputs are identical too (16 of 16, all valid). Static EAGLE-4 chains
serve JSON-schema requests (16 of 16 valid); trees and EAGLE-Harness
rounds, chains included, refuse a grammar backend at startup, as
documented.

**EAGLE-4** (GSM8K 200 at c=32; throughput over 512-token outputs)

| Qwen3.8-27B | GSM8K | tokens per second c=1 | c=8 | c=32 | accept len
| KV tokens |
|---|---|---|---|---|---|---|
| non-spec | 0.970 | 112.0 | 790 | 2534 | - | 1.97M |
| MTP chain, 3 steps | 0.980 | 228.0 | 1421 | 4171 | 3.10 | 1.78M |
| DFlash2, 8 tokens (fp8 KV) | 0.975 | 261.4 | 1493 | 3667 | 4.40 |
2.25M |
| EAGLE-4 chain, 3 steps | 0.975 | 241.8 | 1473 | 4114 | 2.95 | 1.43M |
| EAGLE-4 tree, 5x4, 16 nodes | 0.965 | 304.8 | 1740 | 3134 | 4.38 |
1.39M |
| EAGLE-4 tree, 5x4, 16 nodes, TP2 | 0.965 | 463.2 | 2501 | 4731 | 4.41
| 3.47M |
| EAGLE-Harness chain, 15 steps of 16, width table `9:6,25:4` | 0.970 |
259.9 | 1358 | 2365 | 4.14 | 1.39M |
| EAGLE-Harness chain, 15 steps of 16, `--max-num-seqs 8` | 0.965 |
260.2 | 1367 | 1411 (8 live) | 4.36 | 1.46M |
| EAGLE-Harness tree, 8 steps x topk 4, 32 tokens | 0.975 | 268.1 | 1115
| 1583 | 5.36 | 1.37M |
| same, `--enable-speculative-sampling --sampling-backend flashinfer` |
0.970 | 273.1 | 1185 | 1580 | 5.32 | 1.36M |
| EAGLE-Harness tree, 5 steps x topk 4, 16 tokens | 0.975 | 311.1 | 1737
| 3113 | 4.42 | 1.43M |
| EAGLE-4 static tree, 5x4, 16 nodes, same session (control) | 0.965 |
304.2 | 1742 | 3148 | 4.37 | 1.43M |

| Nemotron-3.5-Super-120B-A12B NVFP4 | GSM8K | tokens per second c=1 |
c=8 | c=32 | accept len | KV tokens |
|---|---|---|---|---|---|---|
| non-spec | 0.935 | 281.1 | 1285 | 2835 | - | 26.5M |
| MTP chain, 3 steps | 0.965 | 503.6 | 1904 | 4610 | 3.16 | 20.4M |
| EAGLE-4 chain, 3 steps | 0.965 | 453.3 | 1698 | 4072 | 3.08 | 4.93M |
| EAGLE-4 tree, 5x4, 16 nodes | 0.955 | 368.8 | 1311 | 2313 | 4.42 |
4.71M |

EAGLE-Harness cost data measured with `measure_run --tp-size 1 --fast
--mamba-ssm-dtype float32`: the 32-token tree and the chain up to
`--max-bs 8` (larger tree batches take the bs 8 tables, larger chain
rounds the width table), the 16-token tree up to `--max-bs 32`. Harness
trees run with `--max-num-seqs 32` (their per-rank cap). No CUDA errors
in any EAGLE-4 serve log.

**Notes from validation**
- Harness rounds verify the whole `--speculative-num-draft-tokens`
window (narrower rounds leave the other slots unaccepted), so the
window, not the chosen width, sets the target's verify cost. At the
static tree's shape the harness matches the static tree; the 32-token
tree accepts more (5.36) but is slower at every concurrency, and at c=32
the 16-token harness chain runs at 0.57x the 3-step static chain with
the same acceptance. Size the window for the batch regime.
- The Nemotron EAGLE-4 draft's sliding-window layer has 32 bf16 KV heads
(16 KB per token) and keeps KV for the full context, 4x the target's own
KV per token: capacity drops from 20.4M (MTP) to 4.9M tokens. A
window-bounded draft pool would recover it (follow-up).

---------

Signed-off-by: Nicolas Perrin <nperrin.ai@gmail.com>
2026-10-22 12:25:42 -07:00
Xuchun Shang a7926dbf8d fix(cache): make Qwen3.8 TP1/MTP3 PD cache offload reusable and resilient (#2406)
This PR fixes a cache reuse failure in Qwen3.8-Flash-Next NVFP4 serving
with SMG and TokenSpeed prefill and decode disaggregation. A hybrid
model needs more than restored KV pages: it also needs a compatible
recurrent-State checkpoint to resume from a reused prefix. Previously,
L3 probing skipped State groups, so restoring KV did not restore the
State needed to resume: bytes could be fetched successfully from L3
while the request still had to recompute its prefix.

L3 probing no longer skips State groups. The storage probe now records
the State checkpoints available within the matched KV coverage, from the
Host index and the registered storage keys, so prefetch restores sparse
State checkpoints together with the KV pages. The probe also carries
each checkpoint's required sliding-window blocks, so an earlier
checkpoint remains usable when the KV coverage extends farther. Missing
intermediate checkpoints do not truncate the KV prefix; Host admission
revalidates the landed entries and resumes only at a boundary with every
required State group, including after a partial landing.

The change uses generic cache-group semantics. Models without State
groups skip State-checkpoint collection.

## Related cache changes

The same change set includes the long-prompt State checkpoint and Host
publication work the measurements below build on, plus supporting cache
fixes:

- With prefix caching enabled, a prompt longer than
`max_scheduled_tokens` leaves one extra page-aligned State checkpoint at
the last prefix-page boundary before its replay tail (the tail is at
least one token, `prefix_replay_tokens`, and the largest replayable
group's window), so a second request with a changed ending reuses the
common prefix immediately: the prompt-end state cannot serve a hit that
must replay its final token. The cut uses the same rotation and
publication as a junction, costs at most one additional forward, and
retains an evictable cache block per State group. Prompts within one
configured chunk and models without State groups do not add this
checkpoint; the D role still lands remote prefill in one transfer.
- Publishing one Host block only appends its key to the L3 storage-key
shadow and trims excess keys from the front, keeping the eviction order
without scanning the whole shadow for every block; bulk removals compact
the order themselves.
- A Mooncake backup that meets allocation pressure
(`NO_AVAILABLE_HANDLE`) retries only the unwritten pages on the backup
worker, with at most three retries after 10, 50, and 200 ms, while their
Host pages remain pinned; exhausted retries, other errors, and malformed
replies keep the existing failure path.
- Prefill autotune and graph capture use distinct writable pages per
fabricated request and disjoint physical parents per cache group,
because groups can share byte planes and a parent reused across groups
corrupts their state even when the group-local page IDs differ. The
probe arena reserves the sum of each group's rounded-up parent demand,
using its virtual packing for sharded groups; decode capture continues
to use the reserved null page.
- Qwen4-Exp reuses the attention planes for its PLE and QSA groups when
their fields fit: a parent belongs to one cache group at a time, so
these groups no longer need separate planes reserved in every attention
or recurrent-state parent. Compressed QSA keeps its exact page stride;
groups whose fields do not fit the attention planes, or whose exact
strides require inconsistent packing ratios, retain separate planes. A
Qwen4 PD prefill role retains the target and draft cache layout for
transfer but reserves no speculative verify workspace: only the decode
role verifies.

## Test setup and measurement scope

The measurements below compare successive versions of this deployment.
They were collected on the original combined implementation before
rebasing. The rebased code has regression validation, but its model
benchmarks have not been rerun.

- Two B300 GPUs: one prefill worker and one decode worker, each TP1 and
EP1, with all client requests entering through SMG.
- Model: NVIDIA Qwen3.8-Flash-Next NVFP4; MTP3 and BF16 KV and SSM
state.
- AgentX 1.0.7 with the cc-traces-weka-062126-256k trace dataset, a
393-trace input pool, seed 42. AgentX performance runs used simulated
Golden acceptance length 2.32; their output-length checks do not
validate answer quality.
- Prefill Host cache 128 GB and decode Host cache 32 GB, in decimal
units; Mooncake memory store 96 GiB per endpoint, 192 GiB total. PD
transfer used local NVLink; Store used TCP.
- Maximum sequence count 32 per worker, prefill chunk size 16,384,
maximum model length 262,132, memory utilization 0.9, and QSA logits cap
8,192 MiB. The recorded engine, launcher, and Mooncake configuration
files were identical across the stages below.

Warmup is excluded. Throughput is completed-request output tokens
divided by the measured span from the first measured request start to
the last completed request end. Per-GPU values include both GPUs. Each
run requested a 900-second load phase; its measured span includes
completed requests draining afterward. C40 is AgentX client concurrency,
not a fixed decode batch size. The p90 tokens per second per user value
is the reciprocal of p90 inter-token latency, matching the benchmark
aggregation convention.

These are single-run engineering observations. AgentX is a closed-loop
workload, so faster runs advance through different request mixes.
Shared-host interference, cache occupancy, and autotuning were not
eliminated.

## Before and after results at matched concurrency

### C32: reusable checkpoints and cheaper cache publication

| Implementation stage | Request outcomes | Measured span (s) | Output
tokens per second per GPU | Mean TTFT (s) | p90 TTFT (s) | Cache-read
share of input tokens |
|---|---:|---:|---:|---:|---:|---:|
| Runnable baseline, before the long-prompt checkpoint change | 837
completed, 4 cancelled, 0 errors | 929.872 | 349.041 | 24.019 | 52.490 |
82.431% |
| Add the long-prompt State checkpoint | 950 completed, 11 cancelled, 0
errors | 919.261 | 397.085 | 19.456 | 45.324 | 90.622% |
| Also remove the publication-time full scan | 1,499 completed, 1
cancelled, 0 errors | 928.571 | 660.823 | 3.910 | 8.853 | 90.922% |

The checkpoint run measured **13.76% higher throughput** and **19.00%
lower mean TTFT** than the runnable baseline. The publication-change run
then measured **66.42% higher throughput** and **79.90% lower mean
TTFT** than the checkpoint run.

### C40: restoring State along with KV

Both runs below already included the long-prompt State checkpoint and
Host publication changes described above, so the comparison isolates the
sparse-State L3 restoration.

| Implementation stage | Request outcomes | Measured span (s) | Output
tokens per second per GPU | Mean TTFT (s) | p50 and p90 tokens per
second per user | Cache-read share of input tokens |
|---|---:|---:|---:|---:|---:|---:|
| Before sparse-State L3 restoration | 1,541 completed, 1 cancelled, 0
errors | 920.720 | 691.470 | 6.132 | 144.379 and 112.475 | 88.473% |
| After sparse-State L3 restoration | 1,665 completed, 0 cancelled, 0
errors | 908.435 | 777.697 | 4.094 | 159.717 and 124.306 | 91.497% |

Measured throughput increased by **12.47%**, mean TTFT decreased by
**33.24%**, and the cache-read fraction increased by **3.024 percentage
points**. This fraction includes all cache tiers; it is not an L3-only
hit rate.

The cancellation shown above occurred during end-of-run draining.
Completed requests had zero output-length mismatches, and both runs
passed the harness validity checks. The cancellation remains part of the
reported outcome.

---------

Signed-off-by: Xuchun Shang <xuchun.shang@gmail.com>
2026-10-18 19:46:56 -07:00
Nicolas Perrin 7db845c248 perf(cache): pack Qwen3.5 conv windows into a free state segment (#2385)
## Summary

[#2360](https://github.com/lightseekorg/tokenspeed/pull/2360) gave each
Qwen3.5 conv window a plane of its own. The KV group skips those planes,
but every group's page spans the whole LCM parent, so each KV page
padded by them. That cost 1.6-1.8% of the token capacity for
Qwen3.5-35B-A3B and 0.8% for Qwen3.8-27B with DFlash2 over an FP8 cache.
KV capacity is what bounds long context, so it is the part worth getting
back.

With three GDN layers per attention layer, the state groups leave
segments free. Qwen3.5-35B-A3B deals its 30 SSM states into two groups
of 15 over 20 K and V segments, and one segment holds dozens of conv
windows. The conv windows now pack into the last segments their state
group leaves free.

The three layouts for Qwen3.5-35B-A3B (10 attention layers, 30 GDN
layers) follow. Each row is one LCM block (P): 20 slots (segments) of 2
MiB. A slot holds one SSM state `S`, or one layer's K or V for the 2048
tokens of a KV block. `c` is a 48 KiB conv window.

**Before
[#2360](https://github.com/lightseekorg/tokenspeed/pull/2360)**: slots
pair up (a and b), and all three GDN groups share this arrangement.

```
slot    a0  b0  a1  b1  a2  b2  ...  a9  b9
KV     [K ][V ][K ][V ][K ][V ] ... [K ][V ]    full
GDN-0  [S ][c ][S ][c ][S ][c ] ... [S ][c ]    a b slot holds only a small conv window
GDN-1  [S ][c ][S ][c ][S ][c ] ... [S ][c ]
GDN-2  [S ][c ][S ][c ][S ][c ] ... [S ][c ]
             ^^^ a V-sized slot, ~2% used
```

**[#2360](https://github.com/lightseekorg/tokenspeed/pull/2360)
(main)**: slots no longer pair up, and the conv windows get a row of
small slots of their own.

```
slot    u0 ... u14  u15 ... u19 | c0 ... c14
KV     [K ] ... [K ][V ] ... [V ] | .  ...  .     <- 720 KiB wasted in every KV P
GDN-0  [S ] ... [S ][  ] ... [  ] | c  ...  c     <- 15 states, 10 MiB empty
GDN-1  [S ] ... [S ][  ] ... [  ] | c  ...  c
```

**This change**: the conv windows move into a slot their state group
leaves empty.

```
slot    u0 ... u14  u15 ... u19
KV     [K ] ... [K ][V ] ... [V ]                 <- no waste, P back to 40 MiB
GDN-0  [S ] ... [S ][  ] ... [ccc]                <- 15 conv windows packed into u19
GDN-1  [S ] ... [S ][  ] ... [ccc]
```

- The planner already lays out several fields of one group in a plane at
offsets, and every consumer addresses a field by its offset. Nothing
outside the recipe changes.
- When the states fill every segment (for example two GDN layers per
attention layer), each conv window keeps a plane of its own, as in
[#2360](https://github.com/lightseekorg/tokenspeed/pull/2360).
- KV pages carry no padding, so token capacity is back to its size
before [#2360](https://github.com/lightseekorg/tokenspeed/pull/2360).

| | before [#2360](https://github.com/lightseekorg/tokenspeed/pull/2360)
| main ([#2360](https://github.com/lightseekorg/tokenspeed/pull/2360)) |
this change |
|---|---|---|---|
| KV page padding, Qwen3.5-35B-A3B | 0 | 1.8% | 0 |
| a request's state blocks, Qwen3.5-35B-A3B | 240 MiB | 163 MiB | 160
MiB |
| the same with MTP | 264 MiB | 179 MiB | 176 MiB |
| the same for Qwen3.8-27B, FP8 KV, DFlash2 | 936 MiB | 630 MiB | 624
MiB |

## Tests


`test_cache_setup.py::test_qwen_conv_windows_fill_a_free_state_segment`,
on a real `prepare_cache_setup` plan: two blocks of three GDN layers and
one attention layer put six SSM states over four segments, in two groups
of three. The parent is four SSM states, the KV group pads nothing, and
each state group pads only the rest of its conv segment. On main the
conv planes enlarge the parent and the KV group pads them.
`test_qwen_state_blocks_carry_no_attention_planes` (two GDN layers per
attention layer) keeps covering the fallback.

On GB200, against main:

- Cache, pool, offload and router suites (17 files): 552 passed vs
main's 551. The extra pass is the new test.
`test_mxfp8_kv_pool.py::test_config_selects_mxfp8_pool_and_sizes` fails
on both.
- GDN, Qwen4-Exp, Nemotron-H and tree-spec suites (18 files): 544 passed
on both. The same 12 Qwen4-Exp tests fail on both.

## Validation (GB200)

TP1 unless noted, two rounds per arm, round-2 numbers. "Identical"
compares this change with main on GSM8K: greedy 64 of 64 at c=1, long
prompts (6.5-6.9k tokens) 6 of 6, and seeded sampling 32 of 32.

| config | main | this change |
|---|---|---|
| Qwen3.5-35B-A3B-FP8, no speculation | 7049216 tokens; 308.6 and 1683.1
tokens per second at c=1 and c=8 | 7174144 tokens (+1.8%); 307.2 and
1680.5 tokens per second; identical |
| Qwen3.5-35B-A3B-FP8 + MTP chain (3 steps), KVStore 64 GB, a forced
retraction every 7 rounds | 6330368 tokens; acceptance 2.977; 297.3 and
1597.1 tokens per second | 6432768 tokens (+1.6%); acceptance 2.973;
307.8 and 1676.2 tokens per second; identical |
| Qwen3.5-35B-A3B-FP8 + MTP tree (5 steps, top-4, 16 tokens) | 6193152
tokens; acceptance 4.552; 522.6 and 2488.1 tokens per second | 6291456
tokens (+1.6%); acceptance 4.547; 523.2 and 2508.5 tokens per second;
identical |
| the same tree at TP2 | 13959168 tokens; acceptance 4.516; 592.9 and
2857.7 tokens per second | 14182400 tokens (+1.6%); acceptance 4.518;
590.0 and 2877.3 tokens per second; identical |
| Qwen3.8-27B + DFlash2, FP8 KV, `--drafter-attention-backend fa4`, 8
draft tokens | 2236416 tokens; acceptance 4.453; 270.5 and 1521.6 tokens
per second | 2254848 tokens (+0.8%); acceptance 4.441; 269.3 and 1516.9
tokens per second; identical |

Throughput is within noise. The forced-retraction run swings by about 5%
between rounds on both arms; round 1 had main at 1690.9 tokens per
second and this change at 1632.2 at c=8. Retraction fired about 3,200
times per run.

Against main before
[#2360](https://github.com/lightseekorg/tokenspeed/pull/2360), the same
five configs gave identical outputs and the same token capacity in every
one.

Signed-off-by: Nicolas <nperrin.ai@gmail.com>
2026-10-16 13:24:28 -04:00
Lei Zhang acea46354f fix(cache): size an LCM parent by its planes, refuse a probe arena cannot fit (#2404)
pack() rounded a parent up to the LCM of every group's packing on top of
its planes. The arena lays planes out end to end and each plane is
already a multiple of its tenants' packings, so the rounding only added
bytes no field addresses, and it multiplies with the packings.
Qwen3.8-Flash-Next's PLE and QSA side planes pack 313, 293 and 4590
blocks per parent at TP1 (156, 146 and 2295 at TP2): the 255 MB parent
grew to 54 GB, and the CUDA-graph probe arena (9 parents) asked for 452
GiB on a 252 GiB device. At TP2 the parent was 557 MB for 131 MB of
planes, so 76% of the arena was never addressed.

A probe arena is sized by block count, not by budget, so nothing
compared it with the memory profile. It is now refused with both numbers
before it is allocated, and the serving budget floor names its sizes
too.

Signed-off-by: Lei Zhang <antiagainst@gmail.com>
2026-10-15 21:05:38 -07:00
Pengzhan Zhao 933fc22650 refactor: remove deepseek v4 runtime leftovers (#2352)
## Summary

Follow-up to #2310 and #2315. Remove the remaining DeepSeek V4 runtime
code that no live model uses, while keeping DeepSeek V4.1 Flash working.

Deleted modules:

- `python/tokenspeed/runtime/execution/drafter/deepseek_v4_dspark.py`
- `python/tokenspeed/runtime/models/deepseek_v4_dspark_ops/` (V4 DSpark
attention ops and the unused `DSparkConfidenceHead`)
- `python/tokenspeed/runtime/layers/attention/deepseek_v4_geometry.py`
- `python/tokenspeed/runtime/layers/attention/deepseek_v4_ops.py`
-
`python/tokenspeed/runtime/layers/attention/kv_cache/hybrid_deepseek_v4.py`
-
`python/tokenspeed/runtime/layers/attention/kv_cache/recipes/deepseek_v4.py`

Kept for V4.1:

- `DSparkVanillaMarkov`, `dspark_greedy_workspace` and
`sample_dspark_block_greedy` move unchanged to
`python/tokenspeed/runtime/models/deepseek_v41_dspark_heads.py`.
- The V4.1 DSpark drafter owns the TP-only mapping check it used to
borrow from the V4 drafter.

Removed dependent V4 paths:

- `deepseek_v4` cache recipe and pool factory registrations.
- Attention registry: V4 backend override, V4 cache family, V4 draft PD
gate and the `is_deepseek_v4` side flag. `DeepseekV4ForCausalLMDSpark`
is no longer a DSpark draft architecture.
- `AttnConfig`: the V4-only KVP decode branch
(`dsv4_decode_supports_partials`).
- `page_table.mask_invalid_graph_tokens`, used only by the V4 pool.

Tests of the removed code are deleted. Shared drafter tests now use
`DeepseekV41DSpark` or generic owners. The remaining workspace
all-reduce gate tests move to
`test/runtime/test_workspace_allreduce_gates.py`.
`docs/design/cache-concepts.md` drops statements about the deleted V4
pool and geometry.

V4 config, tokenizer, CLI and server-arg compatibility, DSpark prefix
replay, and newly unused `tokenspeed_kernel` DSV4 APIs are left for
follow-up PRs.

## Test Plan

- `pre-commit run --all-files`
- `ruff check --select F` on changed Python files
- Repository search finds no remaining imports of the deleted modules.
- CI dispatch on this PR:
- Pass: `ut-runtime-1gpu` (B200), `ut-runtime-1gpu-part-i` and
`ut-runtime-1gpu-part-ii` (MI355), `ut-tokenspeed-kernel` (MI355),
`ut-tokenspeed-kernel-part-i` and `ut-tokenspeed-kernel-part-ii` (B200).
  - Pass: DeepSeek V4.1 Flash DSpark GSM8K eval on B200 and MI35x.
- Fail, also on main `0e6c81c9`: `deepseek-v4.1-flash-pd-1p1d`
(`test_quality`). Mooncake NVLink transfer reports `Requested address
... not found!` in both runs.

---------

Signed-off-by: Pengzhan Zhao <borontion@gmail.com>
2026-10-15 00:31:43 -07:00
Nicolas Perrin c1885c0f06 perf(cache): give Qwen3.5 GDN state pages only their own planes (#2360)
## Summary

Every cache group's page spans the whole LCM parent. The Qwen3.5 recipe
put each attention layer's K and V on a plane pair (`unit.i.a` and
`unit.i.b`) that each of its three state groups shared with one SSM
state and its conv window. A state block therefore carried a V-sized
plane per state it held, plus every draft layer's K and V planes. That
came to 95% padding without a draft, 115% with an MTP layer
(Qwen3.5-35B-A3B) and 219% for Qwen3.8-27B's DFlash2 draft over an FP8
cache. A request holds two blocks of every state group, so these blocks
were most of a short request's cache.

Plane segments are now sized to one SSM state, as in the Mamba2 recipe:

- An attention layer's K and V take a segment each (`unit.{2i}`,
`unit.{2i+1}`).
- A state layer's SSM state takes a segment (`unit.{i}`), and its conv
window gets a plane of its own (`conv.{i}`).
- The attention layers stay one KV group, `full_attention`. That is the
full-history group drafters write through, so token capacity and
`--max-total-tokens` keep their meaning.
- State layers are dealt round-robin into as few groups as hold them at
that group's segment count: two for Qwen3.5 (3 GDN layers per attention
layer).
- A draft layer with a target attention layer's K and V bytes fills
segments too. Any other draft pads only the state groups, within the
allowance from
[#2356](https://github.com/lightseekorg/tokenspeed/pull/2356).

| a request's state blocks | before | after |
|---|---|---|
| Qwen3.5-35B-A3B | 240 MiB | 163 MiB |
| Qwen3.5-35B-A3B + MTP | 264 MiB | 179 MiB |
| Qwen3.8-27B, FP8 KV, DFlash2 | 936 MiB | 630 MiB |

A token's KV pages grow by their share of the conv planes, 0.9-1.8%. A
retracted request's snapshot image also takes one fewer LCM block (3
instead of 4 with MTP).

## Tests

`test_cache_setup.py`, on real `prepare_cache_setup` plans:

- `test_qwen_state_blocks_carry_no_attention_planes`: with 2 × (2 GDN +
1 full) layers, the state group pads nothing and the KV group pads only
the conv planes. Main pads the state groups.
- `test_qwen_mtp_draft_layer_fills_state_segments`: with 2 × (3 GDN + 1
full) layers plus a draft layer of a target layer's width, the draft K
and V join `full_attention` and sit in SSM segments, and the state group
pads nothing.
- The wide-draft test from
[#2356](https://github.com/lightseekorg/tokenspeed/pull/2356) moves onto
a shared setup helper, with its assertions unchanged.

On GB200, against main:

- Cache, pool, offload and router suites (17 files): 564 passed vs
main's 562. The two extra passes are the new tests.
`test_mxfp8_kv_pool.py::test_config_selects_mxfp8_pool_and_sizes` fails
on both.
- GDN, Qwen4-Exp, Nemotron-H and tree-spec suites (18 files): 544 passed
on both. The same 12 Qwen4-Exp tests fail on both.

## Validation (GB200)

TP1, two rounds per arm, round-2 numbers. "Identical" compares this
change with main on GSM8K: greedy 64 of 64 at c=1, long prompts
(6.5-6.9k tokens) 6 of 6, and seeded sampling 32 of 32.

| config | main | this change |
|---|---|---|
| Qwen3.5-35B-A3B-FP8, no speculation | 7174144 tokens; 302.5 and 1681.8
tokens per second at c=1 and c=8 | 7049216 tokens; 301.5 and 1680.7
tokens per second; identical |
| Qwen3.5-35B-A3B-FP8 + MTP chain (3 steps), KVStore 64 GB, a forced
retraction every 7 rounds | 6432768 tokens; acceptance 2.962; 294.0 and
1706.2 tokens per second | 6330368 tokens; acceptance 2.964; 290.9 and
1725.1 tokens per second; identical |
| Qwen3.8-27B, no speculation | 1967616 tokens; 112.8 and 792.9 tokens
per second | 1939968 tokens; 112.8 and 793.6 tokens per second;
identical |
| Qwen3.8-27B + DFlash2, FP8 KV, `--drafter-attention-backend fa4`, 8
draft tokens | 2254848 tokens; acceptance 4.388; 257.8 and 1500.3 tokens
per second | 2236416 tokens; acceptance 4.387; 257.7 and 1510.7 tokens
per second; identical |

Against [#2356](https://github.com/lightseekorg/tokenspeed/pull/2356)'s
head (before it merged), the layout gave identical outputs for MTP
chain, MTP tree (5 steps, top-4, 16 tokens) at TP1 and TP2, with
acceptance and throughput within noise. Token capacity was 1.6% lower,
for example 14182400 → 13959168 for the TP2 tree.

Signed-off-by: Nicolas <nperrin.ai@gmail.com>
2026-10-14 18:03:16 -07:00
Nicolas Perrin 8f9a0a424e fix(cache): count a wide draft layer's K/V bytes in the Qwen3.5 padding allowance (#2356)
## Summary

Draft layers join the Qwen3.5 target's full-attention cache group as
continuation layers. Every LCM parent therefore carries their K and V
planes, which the GDN state groups pad over. The padding allowance
assumed each draft layer is as wide as a target attention layer (an MTP
layer): `1 + 2 * draft_layers / full_attention_layers`. A draft layer
whose per-rank K and V are wider in bytes overran it, and cache planning
failed at startup. That happens with an EAGLE-3 draft that has more KV
heads than a target attention layer, and with a draft cached in bf16
over an FP8 target even at the same width (a block drafter off trtllm
keeps bf16 draft KV). For Qwen3.8-27B with the DFlash2 draft model, an
FP8 KV cache and the fa4 drafter backend:

```text
ValueError: cache group 'linear_attention_0': padding fraction 2.187739 exceeds limit 1.625000
```

A draft layer now counts as the bytes of the K and V fields the recipe
declares for it (MXFP8 scales included), measured in target attention
layers and at least one. A draft of the target's width and dtype keeps
the old bound. The Mamba2 recipe inherits the allowance and gets the
same fix; Qwen4-Exp has no limit.

The padding itself comes from the Qwen GDN layout, where a state group's
page spans the whole parent. That is unchanged here: this commit only
lets the allowance count a wide draft's bytes.

## Tests

`test_cache_setup.py`: a Qwen3.5 plan (2 × (3 GDN + 1 full), head_dim
128, one KV head) with one draft layer wider than a target attention
layer, parametrized over a 4-KV-head draft over a bf16 target and a
1-KV-head bf16 draft over an FP8 target. It checks the target and draft
K shapes, the draft K and V dtype and a positive token capacity. Main
fails both parameters on the padding limit, and an element-count ratio
still fails the FP8 one. The existing MTP allowance test now uses a real
MHA config.

On GB200, the cache suites (`test_cache_setup.py`,
`test_cache_memory_plan.py`, `test_cache_pool.py`,
`test_offload_budget.py`, `test_mxfp8_kv_pool.py`,
`test_kvp_cache_contract.py`) pass 213.
`test_mxfp8_kv_pool.py::test_config_selects_mxfp8_pool_and_sizes` fails
the same way on main.

## Validation (GB200)

TP1, against main:

| | main | this change |
|---|---|---|
| Qwen3.8-27B + DFlash2, FP8 KV, `--drafter-attention-backend fa4`, 8
draft tokens | refuses at startup (error above) | starts; acceptance
4.51; 262 tokens per second at c=1; no errors |
| Qwen3.5-35B-A3B-FP8 + MTP (3 steps) | 6432768 tokens; acceptance
3.054; 480.6 tokens per second | 6432768 tokens; acceptance 3.054; 481.3
tokens per second; greedy 64 out of 64 GSM8K identical to main |

Signed-off-by: Nicolas <nperrin.ai@gmail.com>
2026-10-14 17:46:10 -04:00
Hang Yuandlongcat-ia-team c5dc9ab47f feat(epd): support pipeline admission, synchronize encoder SHM access and discrete encoder output (#2342)
## Summary

Support pipeline-parallel EPD prefill for multimodal models, including
plugins that produce discrete encoder tokens. A request becomes runnable
on every pipeline stage only after the first stage has received the
complete encoder output.

## Changes

- Add `PipelineEpdPrefillAdmission` to hold multimodal requests outside
the scheduler until PP0 has received the complete encoder output and its
attention TP ranks agree on admission.
- Broadcast admitted and failed request IDs from PP0 through pipeline
CPU groups, so every PP stage admits or fails the same requests in the
same loop iteration.
- Keep encoder communication and receive-buffer allocation on PP0; later
stages track pending request IDs and follow PP0's admission decisions.
Decode does not create an EPD admission controller.
- Attach pixel shared-memory segments on every encoder TP rank before
any rank can consume or unlink them, covering both encoder cache hits
and misses.
- Preserve plugin-provided composite multimodal configurations and
resolve text-only speculative drafts without losing their architecture.
- Resolve encoder output width and dtype from the model's output
contract, including integer payloads, independently of the language
embedding width.


## Test Plan

- Passed 220 configuration, device, receive-pool, pipeline-admission,
encoder, SHM, and transfer regression tests, including the two-process
encoder TP SHM tests.
- Passed `pre-commit run --all-files` and `git diff --check`.

---------

Signed-off-by: cnStevenYu <cnstevenyu1991@163.com>
Co-authored-by: longcat-ia-team <longcat_ia_team@meituan.com>
2026-10-14 23:01:19 +08:00
FC.Liandlongcat-ia-team 110bc51760 refactor(cache): fold cache-group retention and family into one attn_kind (#2329)
## Summary

A cache group carried two classification fields, `retention`
(`full_history` | `sliding_window`) and `family` (`history` | `state`),
with a validation rule forbidding the `(state, sliding_window)` cell. A
2×2 with one forbidden cell is a three-valued enum, and the C++
scheduler already read only that enum: `CacheGroupConfig::Kind()` folded
the pair into `AttnKind` at the bridge, and no scheduler logic touched
the two fields. This PR makes the attention kind the one classification
on both sides.

* **Python** `CacheGroupSpec.attn_kind: Literal["full_history",
"sliding_window", "state"]` replaces `retention` + `family`.
`__post_init__` holds each kind to its shape (window only on a sliding
group, row geometry only on a history group, bounded replay only on a
sliding group) and rejects an unknown kind at construction. One
`_LAYER_TYPE_ATTN_KIND` table replaces `_LAYER_TYPE_RETENTION` plus the
separate state label set; state groups no longer carry a placeholder
`full_history` retention.
* **C++** `CacheGroupConfig.attn_kind: AttnKind` crosses the bridge
directly (the scheduling-form `CacheGroupSpec` carries the same name).
`CacheGroupConfig::Retention`, `CacheGroupFamily` and `Kind()` are gone;
`AttnKind::kMambaState` is renamed `kState`. The nanobind constructor
requires `attn_kind` (the old `retention` / `family` defaults selected
behaviour, which AGENTS.md forbids) and exposes `AttnKind` as the only
cache-group enum. The field is qualified because bare `kind` is already
taken in the same headers (`StateStep::kind`, `boundary_kind`).
* **Backends** claim the kinds they read: `cache_consumer_families` →
`cache_consumer_attn_kinds`; paged backends declare both history kinds,
state consumers `state`. `validate_scheduler_config` now also catches a
sliding group with no consumer that handles windows.
`CacheGroupGeometry.families` / `retentions` → `attn_kinds` + `windows`
(the window stays part of rebind equality).
* **PD** `validate_cache_peer_layout` compares `attn_kind`.
`CacheGroupSpec` rides the bootstrap wire, so prefill and decode peers
must be upgraded together.
* "Retention" remains the name of the reclaim policy (`ExpiredBlocksAt`
/ `ReclaimExpired`); only the classification field and its types go.
`docs/design/cache-concepts.md`, `scheduler.md` and `unified_path.md`
are updated to the attention-kind vocabulary, and stale `family` /
`retention` wording in comments and tests is swept.

The second commit bumps `tokenspeed-scheduler` to 0.1.37 and pins the
runtime to it; the release is triggered from this branch.

## Test plan

- [x] `tokenspeed-scheduler` C++ tests: 579 passed
- [x] `tokenspeed-scheduler/python/tests`: 235 passed against the
rebuilt extension
- [x] `test/runtime`: the 81 test files touching `CacheGroupSpec` / the
bridge / backend claims run file by file; every file with failures has
identical fail/pass counts on an untouched `main` checkout with its own
scheduler build (stale local `flash_mla`, mock gaps, pre-existing
capacity assertions) — no regressions
- [x] `pre-commit run --all-files`
- [ ] CI model tests

🤖 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>
2026-10-14 14:32:31 +08:00
Pengzhan Zhao 0c1bc3ed35 refactor: remove deepseek v4 attention state and dependent runtime paths (#2310)
## Summary
Delete the DeepSeek V4 attention state implementations. Do not
consolidate them or keep a replacement/fallback.

- Remove `python/tokenspeed/runtime/layers/attention/deepseek_v4/` and
the proposed `deepseek_v4_state.py` replacement.
- Remove the V4 attention backend and V4 target, NextN, and DSpark model
files that depend on these states.
- Preserve V4.1 Flash by retaining its shared MoE/MLP code and DSpark
logits helper without importing the deleted V4 model.
- Move the existing DSpark stage-count helper to
`utils/spec_block_geometry.py` so configuration no longer imports the
deleted model.
- Remove the deleted model/backend imports and V4 model dispatch; update
only affected existing tests.

The net change touches 29 files. Cache implementations, tokenizer
handling, documentation, kernel implementations, and unrelated
configuration and registry cleanup are unchanged and deferred. Existing
independent cache, configuration, tokenizer, and drafter tests remain.

## Validation
- `pre-commit run --all-files`: passed.
- Existing source-only MoE routing test: 1 passed.
- Existing DSpark stage-count tests: 3 passed in isolation.
- All seven retained MoE classes/helpers and the DSpark logits helper
match their original implementations.
- Runtime Python AST parsing and deleted-module/state-reference checks:
passed.
- Scope check confirms no replacement states and no unrelated cleanup.
- Static correctness review found no code regressions; the required
extracted MoE module is included in the commit.
- Full runtime/GPU tests could not run locally because the environment
lacks `torch`.

---------

Signed-off-by: Pengzhan Zhao <borontion@gmail.com>
2026-10-13 22:11:46 -07:00
FC.Liandlongcat-ia-team 438df60f4c feat(cache): token-level prefix hits; state checkpoints at natural points on a two-slot table (#2230)
Signed-off-by: FC-Li <robert_lexis@163.com>
Co-authored-by: longcat-ia-team <longcat_ia_team@meituan.com>
2026-10-13 23:42:39 +08:00
Hang Yuandlongcat-ia-team b9c265eb24 feat(cache): add sparse KV offloading with fixed GPU hot pools and cross-layer prefetch (#1950)
Signed-off-by: cnStevenYu <397729364@qq.com>
Co-authored-by: longcat-ia-team <longcat_ia_team@meituan.com>
2026-10-13 19:45:37 +08:00
02cf29b930 feat(dcp): support PD transfers and GPU speculative execution (#2113)
Signed-off-by: Xurui Yang <50316220+OftenDream@users.noreply.github.com>
Signed-off-by: FC-Li <robert_lexis@163.com>
Co-authored-by: longcat-ia-team <312376714+longcat-ia-team@users.noreply.github.com>
Co-authored-by: FC-Li <robert_lexis@163.com>
2026-10-12 22:57:33 -07:00
FC.Li bbd633a5fa refactor(parallelism): rename decode context parallel to KV parallelism (KVP); keep DCP for the decode compute (#2170)
## Summary

Rename "decode context parallel" to **KV parallelism (KVP)** where the code means the *storage* layout, and keep **DCP** for the *decode-side compute*. The three context-parallel terms now mean exactly one thing each (`docs/serving/parallelism.md`, "KV parallelism"):

- **KVP** — storage: the full-history KV pages are sharded page-cyclically over a consecutive attention-TP subgroup by virtual block id; each rank stores `1/N`. Selected by **`--kv-parallel-size`** (was `--decode-context-parallel-size`, no alias); described by `Mapping.attn.kvp_size / kvp_rank / kvp_group / has_kvp` (was `dcp_*`); reasoned about by the cache, scheduler feedback, Host tiers and PD transfer (page ownership, residue classes, owner translation, sharded page tables).
- **DCP** — decode compute over KVP pages: all heads, partial attention over the owned pages, LSE merge across the group. Backend decode algorithms, kernels and the merge code keep the name (`attention/dcp/`, `CompactDCPLayout`, `combine_attention_partials`, `dsv4/_triton/dcp.py`, `supports_mla_dcp`, …).
- **QCP** — prefill query-row sharding with gathered KV; unchanged (`--prefill-context-parallel-size`).

## Changes

- `ServerArgs.kv_parallel_size` / `--kv-parallel-size`; `validate_kvp_disaggregation_role(has_kvp=)`, `validate_qcp(kvp_size=)`; refusal messages name the new flag.
- `Mapping(attn_kvp_size=)`, `AttentionLayerMapping(kvp_size=)`, `_resolve_kvp_size`, `kvp_replica_rank`, process title `_kvpN`; consumers (`distributed_initializer`, `ModelExecutor._cache_kvp_rank`, `HostCacheExecutor(kvp_rank=)`, `device.py`, the cache recipes, `AttnConfig.kvp_*`, `registry._validate_hybrid_kvp_cache`).
- Attention backends read the KVP topology (`self.kvp_size / kvp_rank / kvp_group`, `kvp_block_granularity`, `kvp_virtual_block_count`) and keep their DCP-named decode paths; DeepSeek V4's prefill history exchange (owner gather, no LSE merge) is `KvpPrefillChunk` / `kvp_prefill`.
- Kernel placement wrappers (plain Python, no registered signature changed): `compact_kvp_pages`, `kvp_local_visible_lengths`.
- Storage wording in docs and comments (`cache-concepts.md`, `event-loop.md`, `scheduler.md`, `numerics.md`, `server.md`, PD transfer modules) says KVP; test files and scripts whose names described the storage contract are renamed (`test_kvp_cache_contract.py`, `attn_tp8_kvp4_moe_tp8.sh`, `run_cutedsl_mla_dcp.py --kvp-size`).
- Scheduler C++ is untouched (it already speaks `shard_count`); no scheduler release.
- Deliberately unchanged: the frontend handshake field `WireEngineCoreReadyResponse.decode_context_parallel_size` (the frontend's named-map contract; now sourced from `kv_parallel_size` and annotated), and the separately released `tokenspeed-mla` package.

## Tests

`test/runtime`: `911 passed, 5 skipped` on the parallelism commit (26 files incl. gloo `distributed/test_snapshot_op_ownership.py`, PD transfer/executor tests), `396 passed, 5 skipped` after the test renames; final sweep `315 passed, 69 subtests` (`test_kvp_cache_contract`, `test_server_args_qcp`, `test_cli_config_compat`, `test_cache_setup`, `test_flashmla_dcp`, `test_dcp_page_metadata`). Kernel placement op on GPU: `76 passed`. No end-to-end serving run with `--kv-parallel-size`; the out-of-tree model plugin will follow the renamed `Mapping.attn.kvp_*` surface in its own change.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-10-11 02:50:59 +08:00
Q.Yao 9d5eb8ee39 refactor(attention): delegate component setup from registry to backends (#2067)
Signed-off-by: q.yao <streetyao@live.com>
2026-10-07 22:44:38 -07:00
Nicolas Perrin e6b5e9ae45 perf(gdn): verify draft trees in the chunked form (#2039)
Signed-off-by: Nicolas Perrin <nperrin.ai@gmail.com>
2026-10-07 14:47:32 -04:00
Nicolas Perrin bc4f5c2d35 perf(memory): reserve the startup residue, restore the tuning stack limit, drop the multimodal 0.9 clamp (#1940)
Signed-off-by: Nicolas <nperrin.ai@gmail.com>
2026-10-07 14:30:10 -04:00
Nicolas Perrin 4112f54b58 fix(epd): leave the receive pool out of the KV cache budget (#1998)
Signed-off-by: Nicolas <nperrin.ai@gmail.com>
2026-10-05 19:12:22 -04:00
1f767364c9 feat(qcp): query-context-parallel prefill (#1979)
## Summary

Query-context-parallel prefill (QCP): on a `--disaggregation-mode prefill` engine, `--prefill-context-parallel-size N` (= attention TP) lets each attention-TP rank compute 1/N of a chunk's query rows while every rank keeps the full KV it needs, instead of replicating the prefill compute across the TP group.

- **Phase 0**: the dead `ENABLE_CP` / `CP_METADATA` context-parallel path is deleted (env switch, module-global metadata, the `cp` world dimension, its control-plane and L3-key plumbing).
- **Layout**: one server arg → `Mapping.attn.qcp_*`; the shard is the RSAG scatter of the chunk (`QueryShardPlan`, plain ints on `ForwardContext.query_shard`; a required `query_shard` kwarg on every `init_forward_metadata`). Attention legs are identity on a query-sharded `CommManager`; dense/MoE reuse the existing scattered-token paths; `VocabParallelEmbedding` takes the shard; the model exit gathers only the sampled rows.
- **Attention** (DSA): per request group, the history KV and index-K are gathered from the owning ranks (KVP page-cyclic placement, or replicated pages) into a page-padded workspace reserved from the cache budget; the sparse kernel runs over local query rows with full heads and no LSE merge — bitwise a single-GPU computation. The KV write rotates the local latent, all-gathers it and stores through the owner mask (`latent_prologue(key_rows=...)`, `mla_prologue(cache=None)` + `latent_store`). Empty shards still join every collective.
- **Drafter**: Eagle step 0 and the multi-depth MTP extend depths run the shard; decode-step rows stay replicated and use the DCP compute (partial attention over owned KVP pages + LSE merge) with a full-head combine (the combine's head form follows the layer).
- Phase 1 scope: prefill role, eager, DSA family, bf16 KV, dense TP and MoE TP×EP ∈ {1, attn TP}; scheduler, cache allocation and PD transfer are unchanged (the P→D route is a function of page ownership only).
- Also fixes a pre-existing bug: the NCCL backend's gloo fallbacks named non-existent `torch.distributed.all_gather_single` / `reduce_scatter_single`.

Vocabulary: **KVP** = page-cyclic KV sharding across the attention-TP ranks (storage); **DCP** = decode-side compute over KVP pages (partial attention + LSE merge); **QCP** = prefill-side compute (query-row sharding, full gathered KV, no LSE merge). QCP pairs with KVP on the prefill role as DCP pairs with KVP on decode. Builds on #1974 (KVP on the prefill role, merged).

## Tests

635 passed (query-shard plan arithmetic; gloo history gather over a fake cyclic placement; DSA shard metadata; `latent_prologue(key_rows=)` byte-equality against the composite and the Triton fused write; sharded embedding and MTP depths; PD topology/device build; server-arg refusal matrix). Not verified on GPU end to end.

Docs: `docs/design/unified_path.md` (QCP contract), `attention-prologue.md`, `cache-concepts.md`, `numerics.md`, `docs/serving/parallelism.md`, `docs/configuration/server.md`.

🤖 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>
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-10-04 22:18:13 +08:00
Nicolas Perrin 338f6df46f feat(spec): draft-tree speculative decoding (#1916)
Signed-off-by: Nicolas Perrin <nperrin.ai@gmail.com>
2026-10-03 21:06:26 -04:00
Q.Yao 5905f205c3 feat(DCP): Add Kimi K3 DCP support to the CuTe MLA backend (#1853)
Signed-off-by: q.yao <streetyao@live.com>
2026-09-30 20:28:48 -07:00
Yechan Kim 3c3de31664 fix(cache): allow uneven ordinary cache groups
Signed-off-by: yechank <161688079+yechank-nvidia@users.noreply.github.com>
2026-09-29 00:58:06 -07:00
FC.Liandlongcat-ia-team f96e7e02c0 feat(plugins): load out-of-tree models through entry points and model profiles (RFC 0001) (#1774)
Signed-off-by: FC-Li <robert_lexis@163.com>
Co-authored-by: longcat-ia-team <longcat_ia_team@meituan.com>
2026-09-25 22:19:56 -07:00
Nicolas Perrin b121eb0890 feat(memory): reserve the CUDA-graph pools in the KV cache budget (#1509)
Signed-off-by: Nicolas <nperrin.ai@gmail.com>
2026-09-25 14:57:02 -04:00
Enwei Zhu 8ee62dfad3 refactor: establish coding guidelines and simplify attribute access (#1640)
Signed-off-by: Enwei Zhu <21126786+syuoni@users.noreply.github.com>
2026-09-18 19:06:34 -07:00
FC.Liandlongcat-ia-team 78c6518720 refactor(cache): require every cache group spec to state replayable (#1617)
Signed-off-by: FC-Li <robert_lexis@163.com>
Co-authored-by: longcat-ia-team <longcat_ia_team@meituan.com>
2026-09-17 16:57:59 +08:00
tuanzhangCS d3b2998c79 refactor(attention): compose Qwen4-Exp QSA and PLE backends (#1416)
Signed-off-by: tuanzhangCS <tuan@lightseek.org>
2026-09-12 17:20:23 -07:00