Commit Graph
1505 Commits
Author SHA1 Message Date
Tuan Zhang 0dc3c9ce4e Merge branch 'main' into codex/disable-remote-code-by-default 2026-12-03 21:11:31 +08:00
0bd13e7584 feat(cli): forward --trust-remote-code to SMG (#3987)
## Summary

Forward the effective `--trust-remote-code` setting from `ts serve` to
SMG so the gateway can render text chat with a checkpoint's custom
Python tokenizer. The engine receives the supplied trust flags in order.
When both forms are present, the last form determines whether the
gateway receives the opt-in.

## Dependency

This change depends on the SMG Python renderer and its startup opt-in.
[smg-project/smg#9376](https://github.com/smg-project/smg/pull/9376)

The `tokenspeed-smg` dependency is updated to `1.16.0.post20261203`.

## Test Plan

- `pre-commit run --all-files` passed.
- `python -m pytest -q test/cli/test_argsplit.py` passed 47 tests,
including defaults, both flag forms, and repeated settings.
- Exercised `ts serve` offline with a locally built SMG wheel, a local
checkpoint, and a CPU fake backend. The enabled case matched the
reference Python prompt token IDs. The disabled case returned the opt-in
error.

---------

Signed-off-by: tuanzhangCS <26617745+tuanzhangCS@users.noreply.github.com>
Signed-off-by: tuanzhangCS <tuan@lightseek.org>
Co-authored-by: tuanzhangCS <26617745+tuanzhangCS@users.noreply.github.com>
Co-authored-by: minedec <37043133+minedec@users.noreply.github.com>
2026-12-03 20:45:31 +08:00
yanlonghuandyanlonghu a9ad517549 fix(npu): enable expandable prefill allocations and handle pinned-memory exhaustion during suspend (#4131)
## Summary

Follow up on #3667 by requiring [torch-npu-memory-saver
0.1.7](https://pypi.org/project/torch-npu-memory-saver/0.1.7/) in both
the NPU kernel backend and the Ascend extra. Update the installation
hint, serving guide, and exact-version packaging test. The allocator
continues to use ABI 5.

## Why TokenSpeed NPU workers need 0.1.7

- **Prefill fragmentation.** Version 0.1.6 required
`expandable_segments:False` for the entire worker. Ordinary prefill
activations with varying shapes could therefore accumulate unusable
gaps, and enabling expandable segments caused Saver initialization to
fail. With 0.1.7 operators can start the worker with
`PYTORCH_NPU_ALLOC_CONF=expandable_segments:True`. Expansion is disabled
only around Saver-managed allocations and ACL graph capture, then
restored for ordinary allocations. The default in the launch example
stays unchanged.
- **Concurrent suspend and pinned host memory.** A Prefill/Decode pair
backing up weights or other managed bytes at the same time can exhaust
pinned host memory. Previously `aclrtMallocHost` error `207001` aborted
suspend. The new allocator logs a warning, falls back to pageable host
memory for that allocation, and completes the synchronous copy before
unmapping the device pages. Other ACL errors still propagate.
- **Failed allocator restore with waiting callers.** If PTA fails to
restore the expandable-segment setting, a thread that already passed the
initial health check may be waiting on the pool lock. Version 0.1.7
checks again after acquiring that lock. Queued `assert_active`, `pause`,
and `resume` raise a worker-restart error before changing pool state.

The implementation and platform wheel are in the [standalone library
release](https://github.com/yanlonghu/torch_npu_memory_saver/releases/tag/v0.1.7).
This TokenSpeed PR selects that release on Ascend.

## Validation

- Installed 0.1.7 by name from PyPI on A2. Independently installed the
published CPython 3.12/Linux AArch64/CANN 9.0.0 wheel after downloading
it from the GitHub release and checking its SHA-256.
- Ran the current TokenSpeed NPU adapter's four real-device cases with
expandable segments enabled and disabled (8 passes). The three
standalone NPU device cases and all three queued-failure cases passed on
the installed wheel.
- Ran Qwen3 TP2 with the release wheel in the established protocol-3
integration fixture. CPU-backed partial update and full discard/refill
passed. The refilled instance and cold start with the new checkpoint
matched at all 24 output token positions (maximum absolute logprob
difference 0).
- All 31 kernel setup tests passed in isolation, covering
backend-specific package metadata. CUDA/ROCm execution was not tested on
hardware.
- On A3 (CANN 8.5 / CPython 3.11), built and installed a separate
platform wheel from the checksum-verified PyPI sdist. The three
queue-failure cases and three device tests passed.
- LongCat Lite P8+D8 on A3, using the CANN 8.5 wheel built from the
published 0.1.7 sdist: all 16 ranks loaded the matched wheel and native
library. Prefill and Decode suspended and resumed concurrently. All
seven ordinary prefill activation samples (four before suspend and three
after resume) belonged to expandable segments in the default pool. Five
prompts matched across suspend/resume at all 40 output token positions,
with zero absolute logprob difference.

Signed-off-by: yanlonghu <19688573+yanlonghu@users.noreply.github.com>
Co-authored-by: yanlonghu <19688573+yanlonghu@users.noreply.github.com>
2026-12-03 15:41:57 +08:00
Xiangyi ZhangandEnwei Zhu 53c1c08ed5 feat(kimi-k3): route attention-TP slices under attention DP (#4004)
## Summary

Kimi-K3's attention-DP MoE path allowed routed EP only with attention TP
1 (DEP). This PR allows attention TP > 1 under attention DP when MoE TP
is 1 and `attention TP x DP == MoE EP == world size`. For example, a
16-GPU decode instance can hold two attention replicas of TP8 with KV
parallelism 8, with routed EP16 across both replicas:

```
--attn-tp-size 8 --data-parallel-size 2 --kv-parallel-size 8 \
--decode-context-parallel-size 8 --moe-tp-size 1 --expert-parallel-size 16
```

It stays one path for every attention TP size:

- Each attention-TP rank routes a disjoint, consecutive slice of its
replica's rows (`scatter_count`, in expert-parallel rank order). At
attention TP 1 the slice is the whole replica.
- The shared experts shard over the replica's attention-TP group and
read all of the replica's rows.
- A token reduce-scatter adds the shared partials onto the slices. A
token all-gather restores the replica's rows.
- The fused input projection, its packed weight and static expert
placement keep requiring attention TP 1.
- Transport is unchanged: FlashInfer all-to-all, the all-gather
fallback, or MegaMoE.

#4001 is merged; its commit is still the first one on this branch and
matches main, so please review commit 82eb424b9 only.

This PR overlaps #3838, which adds attention TP > 1 for MegaMoE only.
Coordinated with the author of #3838. #3838's MegaMoE-only guards are
replaced here by the general slice. One difference in the tail follows
from main's `KimiLinearMoEDeepEP`:

- DeepEP gathers the routed latent, shards the up projection by column
and all-reduces it with the shared output: AG(latent) + AR(hidden).
- This PR reduce-scatters the shared partials onto the slices, adds the
slice's routed output and gathers the rows: RS(hidden) + AG(hidden).
That is about one AR(hidden), so it skips DeepEP's extra latent gather.

In a decode profile of this layout with MegaMoE (below), all-reduce,
all-gather and reduce-scatter together take 3.0 ms of a 33.2 ms forward.

Masking CUDA-graph padding rows from routing, as DeepEP does, is left to
a follow-up. The attention TP 1 path on main does not mask them either.

## Results

Kimi-K3.1-Pro (MXFP4), GB300. The PD decode pool is 4 nodes (16 GPUs) in
each layout, and prefill is DWDP16 on 4 nodes. The workload is the
public agentic trace `semianalysisai/cc-traces-weka-062126` with sticky
routing, 30 minutes per point.

### MegaMoE (`--moe-backend mega_moe --all2all-backend none`), this
branch

GSM8K (1319, 5-shot) of EP16 + 2xDCP8 on this branch: 97.95% strict
match, 97.88% flexible extract.

Decode profile, 4 nodes aggregated, 96 requests of 72K prompt tokens, 30
decode forwards, mean ms per forward over ranks:

| | EP16 + 2xDCP8 | DEP16 |
|---|---|---|
| dense GEMMs | 9.0 | 20.8 |
| MegaMoE kernel (dispatch + experts + combine) | 12.9 | 15.7 |
| MegaMoE routing and top-k reduce | 1.9 | 3.0 |
| all-reduce / all-gather / reduce-scatter | 3.0 | 0 |
| attention | 2.6 | 2.5 |
| other | 3.8 | 3.7 |
| **forward** | **33.2** | **45.6** |
| median inter-token latency in the window | 27.9 | 38.4 |

Under DEP16 every rank reads the full attention and dense weights for
about six requests; attention TP8 shards those reads.

PD sweep (decode pool above, 30 minutes per concurrency point):

| concurrency | EP16 + 2xDCP8 output tok/s/GPU | DEP16 output tok/s/GPU
| EP16 + 2xDCP8 P90 interactivity | DEP16 P90 interactivity |
|---|---|---|---|---|
| 16 | 22.0 | 18.2 | 45.6 | 28.4 |
| 32 | 47.3 | 36.9 | 39.3 | 26.3 |
| 64 | 81.4 | 63.5 | 33.0 | 25.0 |
| 96 | 132.2 | 86.6 | 32.1 | 18.0 |

Output tok/s/GPU counts the 16 decode GPUs; interactivity is tok/s/user.
At concurrency 96, EP16 + 2xDCP8 gives 1.53x the throughput and 1.78x
the P90 interactivity of DEP16. Each point ran once.

### `flashinfer_trtllm` MoE, before this branch's rebase

With the FlashInfer all-to-all:

| layout | concurrency | output tok/s/GPU (decode GPUs) | P90
interactivity (tok/s/user) |
|---|---|---|---|
| EP16 + 2xDCP8 | 96 | 125.8 | 30.3 |
| DEP16 | 96 | 78.6 | 16.1 |

GSM8K (1319, 5-shot, strict match): EP16 + 2xDCP8 scores 97.88% and
DEP16 97.80%.

### Numerics

On a 12-layer subset (4 GPUs), the mean absolute logprob difference over
32 greedy requests is:

- attention TP2 x DP2 vs DEP4: 0.055 under MegaMoE and 0.054 under
trtllm.
- MegaMoE repeated runs: 0.002–0.006.
- This branch vs main at attention TP 1: 0.0054, which is within the
repeated-run range.

## Test Plan

- `test/runtime/test_kimi_k3_moe_attn_dp.py`:
- Every rank of two attention-TP2 replicas, including uneven,
fewer-rows-than-ranks and idle replicas, returns the replica's reference
output, and each row is routed exactly once.
  - Route slices cover each replica.
- Layouts whose expert group does not span every attention rank are
rejected.
  - Shared experts shard over the attention-TP group.
- Kimi-K3 runtime tests and the FlashInfer MXFP4 MegaMoE kernel test
pass on GB300.
- `pre-commit run --all-files` passes.

---------

Signed-off-by: Xiangyi Zhang <xiangyiz@nvidia.com>
Signed-off-by: Enwei Zhu <21126786+syuoni@users.noreply.github.com>
Co-authored-by: Enwei Zhu <21126786+syuoni@users.noreply.github.com>
2026-12-03 15:03:06 +08:00
Bangtian Liu 5cf4824424 perf(muse-spark): the TP4 attention two-shot all-reduce runs the layer boundary in the same launch (#3800)
For decode batches too large for the one-shot boundary, the attention
output's two-shot all-reduce and the layer boundary (residual add and
norms) used to run as separate launches. One launch now does both:
- Sender programs run the two-shot reduce-scatter and all-gather steps
unchanged.
- Finisher programs wait for each row's reduced values, then run the
existing boundary code.

The fused path is limited to TP4 CDNA4 with Lamport enabled, row counts
that divide evenly across ranks, and no post-norm weight. It extends
past the one-shot boundary through the two-shot's last whole-row count;
other cases keep the existing dispatch policy.

The sum order and the single BF16 rounding are the two-shot's, so the
outputs are bitwise equal to the unfused path's.

- Needs a separate 16.9 MB per-rank symmetric region: the two-shot's
per-tile flags can't serve the larger sender tiles.
- Tests:
- bitwise against the two-shot + boundary from 28 to 172 rows on every
rank, including graph replays with a delayed rank;
- polling codegen: uncached loads stay in the retry loop, with no
barrier;
  - no recompilation after warm-up.
- Served greedy logprobs (96, 128 and 168 rows through the new kernel)
match the unfused path's in two runs. The two states where they differed
also differ between two runs of the unfused path.

Served results (Muse Spark MXFP4, TP4 on 4x MI355X, multi-turn agentic
workload, one hour per run, same host and recipe with and without this
change; x = interactivity in tokens per second per user, y = throughput
in tokens per second per GPU):
- Concurrency 40, host A: x 78.00 -> 81.10 (+4.0 %), y 48,517 -> 48,827
(+0.6 %).
- Concurrency 40, host A repeat: x 78.00 -> 79.05 (+1.3 %), y 48,517 ->
48,526 (+0.0 %).
- Concurrency 40, host B: x 78.1 -> 78.4 (+0.4 %), y 48,263 -> 48,685
(+0.9 %).
- Concurrency 40, host B repeat: x 78.1 -> 79.2 (+1.4 %), y 48,263 ->
48,538 (+0.6 %).
- Concurrency 36: x 105.04 -> 107.53 (+2.4 %), y 45,635 -> 45,839 (+0.4
%).
- Concurrency 28: x 126.74 -> 126.26 (-0.4 %), y 41,137 -> 41,115 (-0.1
%), within noise; decode step 0.8 % faster.
- Mean decode step: 0.19-0.30 ms faster.
- Startup: the KV pool is 1,280 tokens per rank smaller (the 16 MiB
region); graph memory and free memory are unchanged.
- Fixed-batch decode at 16-28 requests on two hosts: 0.1-0.4 ms per step
faster at 16-20 requests (128-160 rows); within 0.2 ms either way at
21-28 requests, where 22 and up (176+ rows) are past the fused range and
run the unfused path.

---------

Signed-off-by: Bangtian Liu <liubangtian@gmail.com>
2026-12-03 01:14:33 -05:00
55dd6c7792 perf(deepseek-v41): fuse decode mHC boundaries with packed CuTe (#4081)
## Summary

This change ports vLLM’s CuTe DSL mHC boundary kernel, originally
adapted from TensorRT-LLM, to TokenSpeed’s DeepSeek-V4.1 decode path.
One launch updates the residual, applies the input RMSNorm, and computes
the next mHC mixing coefficients. TokenSpeed packs the mixer weights at
load time and refreshes them in place so captured CUDA graphs can reuse
them after a weight update. [vLLM PR
#66652](https://github.com/vllm-project/vllm/pull/66652) · [Kernel at
the ported
revision](https://github.com/vllm-project/vllm/blob/f5d93296c8ec82b7e7dabdb308d24d43cb1907bf/vllm/models/deepseek_v41/nvidia/ops/mhc_boundary.py)

The kernel supports BF16 activations with hidden size 5,120 on SM100 and
SM103. For target and DSpark decode under non-bitwise numerics, dispatch
uses the local row count after padding and row selection, with limits of
**16 rows before attention** and **336 rows before the FFN**.

## EP32 serving performance

We ran AgentX against TokenSpeed serving DeepSeek-V4.1-Flash at
concurrency 3,018 on 44 GB200 GPUs, with three 4-GPU prefill workers and
one 32-GPU EP32 decode worker. Each configuration ran the public
`cc-traces-weka-062126` trace from SemiAnalysis AI for one measured hour
after warmup, with a six-token DSpark verification window. The candidate
backported the patch to the earlier baseline's serving revision and
applied it on the decode workers. Its rebuilt host extension had a
different binary hash from the baseline.

| Request TPOT | Baseline (milliseconds per token) | Packed CuTe
(milliseconds per token) | Change |
|---|---:|---:|---:|
| P50 | 2.94 | 2.72 | −7.5% |
| P75 | 3.18 | 2.95 | −7.2% |
| **P90** | **3.34** | **3.07** | **−8.1%** |
| P95 | 3.49 | 3.16 | −9.5% |

The AgentX score reports TPOT through P95. In the corresponding AIPerf
exports, P99 per-request inter-token latency fell from **4.017 to 3.529
milliseconds per token (−12.2%)**.

Output throughput rose from 3,148.28 to 3,163.87 tokens per second per
GPU (+0.50%). P90 time to first token increased from 3.960 to 4.292 s
(+8.4%). The baseline recorded 484,751 successful requests and zero
client errors. The candidate recorded 486,581 successful requests and
two client errors.

## Target decode microbenchmark

We replayed the 40-layer target on four GB200 GPUs (TP1, EP4) with
checkpoint weights, routed experts, and fixed input tokens. Each of 13
randomized paired trials averages the slowest rank’s CUDA graph time per
step over the same token sequence. Width 1 is ordinary decode. Width 6
verifies six token positions per request, so 72, 96, and 108 local rows
correspond to 12, 16, and 18 requests per rank.

**Before** is the median split time from the FFN and ATTN+FFN trials.
The packed columns show median milliseconds per step, with the paired
change from each mode’s own split control in parentheses (microseconds
per step, negative is faster). ATTN-only ran separately at some sizes.
Bold marks the default.

| Local rows per rank | Verify width | Before | ATTN | FFN | ATTN+FFN |
|---:|---:|---:|---:|---:|---:|
| 12 | 6 | 9.356 | 9.100 (−256) | 9.177 (−179) | **8.940 (−418)** |
| 16 | 1 | 10.234 | 9.965 (−261) | 10.074 (−157) | **9.828 (−405)** |
| 18 | 6 | 10.257 | 10.257 (+1) | **10.129 (−128)** | 10.119 (−138) |
| 24 | 1 | 10.904 | 10.889 (−16) | **10.803 (−101)** | 10.820 (−84) |
| 24 | 6 | 10.944 | 10.958 (+14) | **10.873 (−72)** | 10.884 (−60) |
| 36 | 6 | 11.914 | 11.945 (+21) | **11.863 (−50)** | 11.883 (−30) |
| 48 | 6 | 12.514 | 12.532 (+20) | **12.511 (−2)** | 12.540 (+26) |
| 72 | 6 | 13.769 | 13.788 (+15) | **13.724 (−46)** | 13.742 (−29) |
| 96 | 6 | 14.751 | 14.775 (+19) | **14.641 (−109)** | 14.668 (−84) |
| 108 | 6 | 15.391 | 15.412 (+12) | **15.152 (−237)** | 15.179 (−213) |
| 144 | 6 | 16.625 | 16.686 (+32) | **16.544 (−84)** | 16.632 (−23) |
| 192 | 6 | 16.560 | 16.683 (−4) | **16.576 (−63)** | 16.549 (−35) |
| 240 | 6 | 17.589 | 17.635 (+46) | **17.587 (−4)** | 17.611 (+19) |
| 288 | 6 | 18.737 | 18.818 (+81) | **18.721 (−16)** | 18.791 (+52) |
| 330 | 6 | 20.085 | 20.115 (+30) | **20.107 (+20)** | 20.146 (+58) |
| 336 | 6 | 20.241 | 20.272 (+40) | **20.239 (−3)** | 20.282 (+42) |
| 342 | 6 | **20.411** | 20.631 (+209) | 20.614 (+205) | 20.825 (+414) |
| 384 | 6 | **21.210** | 21.401 (+182) | 21.330 (+114) | 21.516 (+305) |
| 480 | 6 | **21.650** | 21.915 (+112) | 21.885 (+257) | 22.089 (+414) |
| 672 | 6 | **26.781** | 26.600 (+90) | 26.928 (+261) | 27.024 (+352) |

- **Attention cutoff.** With FFN already packed, adding ATTN saved
another 237 microseconds per step at 12 rows and 246 microseconds per
step at 16. It was faster in all 13 pairs at both sizes. The gain
narrowed to 11 µs at 18 rows. At 24 rows, adding ATTN cost 18 µs at
width 1 and 11 µs at width 6. It also cost 18–27 µs at 72, 96, and 108
rows. The conservative 16-row cutoff preserves TokenSpeed’s ability to
overlap coefficient work with attention at larger sizes.
- **FFN cutoff.** FFN alone saved 46, 109, and 237 microseconds per step
at 72, 96, and 108 rows. It cost 20 µs at 330 rows and saved 3 µs at
336. The kernel’s single-wave schedule covers 14 tiles of up to 24 rows
each (336 rows). For the larger sizes we forced a benchmark-only
multi-wave version. FFN alone then cost 205 µs at 342 rows and 114–261
µs at the remaining measured sizes.

---------

Signed-off-by: chenht2022 <chenht2022@gmail.com>
Signed-off-by: lightseek-bot <243258330+lightseek-bot@users.noreply.github.com>
Co-authored-by: lightseek-bot <243258330+lightseek-bot@users.noreply.github.com>
Co-authored-by: Fan Yang <250624800+fanyang-real@users.noreply.github.com>
2026-12-02 20:56:55 -08:00
Chen Hongtaoandlightseek-bot 9304cff1ca feat(moe): support online EPLB for DeepSeek V4.1 and DSpark (#3912)
## Summary

Enable online expert parallel load balancing (EPLB) for
DeepSeek-V4.1-Flash with MegaMoE. The target and its DSpark draft have
different expert sets, so the controller samples them on the same
schedule and computes a separate placement for each.
`--no-eplb-balance-draft` enables target-only balancing.

- `--eplb-window-size W` takes the first load snapshot after `W`
forwards, then samples the last `W` forwards of each rebalance interval.
- MegaMoE maps logical expert IDs to physical slots and counts live
token rows in the input staging kernel. This removes a kernel launch per
MoE layer and excludes padding from the load sample.
- Between forwards, the runtime moves packed MXFP4 weights and scales in
layer chunks and updates routing tables in place, so captured CUDA
graphs can replay with the new placement.

## Performance

On DeepSeek-V4.1-Flash, enabling EPLB for both target and draft reduced
**P90 time per output token by 9.0%** and increased **output throughput
per GPU by 1.6%**.

| Decode EPLB | P90 TPOT (ms) | Output tokens per second per GPU |
|---|---:|---:|
| Off | 5.09 | 4,220.77 |
| Target only | 4.69 | 4,285.94 |
| Target and DSpark draft | 4.63 | 4,288.94 |

Each configuration ran once for 20 minutes at AgentX concurrency 3,018
on 28 GB200 GPUs, with three EP4 prefill workers and one EP16 decode
worker. All runs used DSpark and the same decode Engram placement. The
two EPLB runs used a backport of this PR with 16 redundant slots per
participating MoE layer, a 3,000-forward sampling window, a
15,000-forward interval, and up to eight layers per migration chunk.

## Test Plan

- Verified first-window timing, target and draft load accounting, packed
verification padding, and memory release and resume.
- On two B300 GPUs, replayed a captured target and draft forward after
migrating expert weights and scales over NCCL. Both outputs matched
their pre-migration values bit for bit.
- In a separate B300 CUDA graph microbenchmark with 240 token rows,
hidden size 5,120, and top-k 6, fused input staging took **2.28 µs**,
down from **3.69 µs** with separate EPLB routing and staging.

---------

Signed-off-by: chenht2022 <chenht2022@gmail.com>
Signed-off-by: lightseek-bot <243258330+lightseek-bot@users.noreply.github.com>
Co-authored-by: lightseek-bot <243258330+lightseek-bot@users.noreply.github.com>
2026-12-02 20:55:15 -08:00
Fan Yang 9285fd7323 perf(engram): canonicalize host MXFP8 table in place to skip per-step requantization (#3877)
## Summary
- Add `canonicalize_mxfp8_table` (`host_canonicalize_mxfp8_table`) and
`canonical_mxfp8_row_gather` (`host_canonical_mxfp8_row_gather`) under
`tokenspeed-kernel/python/tokenspeed_kernel/ops/embedding/`. They
canonicalize packed host tables in place once after loading, with no
additional persistent host memory; CUDA uses chunked, 64-bit-offset-safe
Triton UVA kernels, and an equivalent chunked CPU implementation is
available for explicit callers.
- After canonicalization, `canonical_mxfp8_row_gather` directly copies
E4M3 codes and UE8M0 scales on each lookup, emitting zero codes and
floor exponent `105` for negative or out-of-range IDs. This removes
per-lookup FP8-to-FP32 conversion, amax calculation, division, and FP8
requantization while preserving bit-for-bit output (`rtol=0`, `atol=0`)
relative to `mxfp8_row_gather`, including during CUDA graph replay.
- Wire `DeepseekV41Engram.prepare_mxfp8_rows()` into
`DeepseekV41ForCausalLM.post_load_weights()` for eligible GPU-registered
host tables whose `wkv` uses `Fp8LinearMethod` with FP8 E4M3 weights.
Shared-table ranks synchronize once after all Engram layers, including
ranks with no local layers, avoiding per-layer barrier deadlocks.
- Reset `_mxfp8_canonical` during row copies and sharded loads on
writers and followers so reloads restore the normal representation and
keep later synchronization in lockstep. Canonicalized tables are
exclusive to the two-dimensional CUDA MXFP8 gather path; BF16
dequantization now fails explicitly, and normal post-load preparation
skips canonicalization when CUDA is unavailable.

## Verification
- CPU tests in
`tokenspeed-kernel/test/ops/test_embedding_host_gather.py`: exhaustive
bit exactness across all 254 non-NaN E4M3 codes and all finite-product
E8M0 exponents `0..245`, slice isolation, idempotency, and preservation
of `data_ptr()`. `test/runtime/test_deepseek_v41_engram.py`: 37 passed.
- Added CUDA tests for bit-exact matching against `mxfp8_row_gather`
with sorted and unsorted lookups and 32-bit and 64-bit integer indices;
offsets beyond 2 GiB; no Triton recompilation across row slices and
batch sizes; three canonicalize-and-gather cycles with no growth in the
ordinary CUDA memory pool `(0, 0)`; and eager and CUDA graph
`DeepseekV41Engram` bit exactness against a GPU table.
- `pre-commit run --all-files`: passed.

---------

Signed-off-by: Fan Yang <250624800+fanyang-real@users.noreply.github.com>
2026-12-02 20:22:29 -08:00
Enwei Zhu c8780a83bc perf: overlap BF16 TP projection communication and GEMM (#4088)
## Summary

Add persistent CuTe DSL BF16 kernels for column and row TP projections,
based on the CUTLASS persistent GEMM backbone.

- Column projections multicast input K groups while GEMM computes, then
write output tiles directly into each token owner's receive buffer.
- Row projections share the GEMM implementation while preserving
progressive, rank-ordered FP32 reduction of BF16 partials.
- MLA, DSA, and KDA QKV and gate projections borrow intermediate outputs
to avoid copies; ordinary forward preserves output ownership.
- Derive peer metadata and launch geometry from the TP group and
hardware, and compile variants during startup.
- Remove the previous BF16 implementation while retaining FP8 and shared
communication routines.

## Performance

BF16 fused-projection microbenchmarks on 4× GB200, TP4, with cold-L2
CUDA graph replay. Nsight timings include TP communication. Token counts
are per rank; latencies are µs, shown as **main → PR implementation**.

| Tokens per rank | MLA and DSA QKV and gate column | KDA QKV and gate
column | Output row |
|---:|---:|---:|---:|
| 60  | 55.10 → 42.64 | 91.58 → 72.00 | 35.79 → 33.26 |
| 80  | 57.50 → 47.39 | 122.21 → 79.95 | 47.12 → 40.02 |
| 100 | 58.00 → 51.22 | 122.93 → 91.66 | 46.67 → 41.57 |
| 120 | 57.82 → 52.10 | 123.41 → 92.94 | 48.03 → 41.98 |
| 140 | 88.48 → 55.42 | 199.79 → 104.48 | 51.06 → 43.30 |
| 160 | 88.83 → 56.80 | 200.35 → 107.06 | 50.64 → 42.82 |
| 180 | 88.61 → 60.96 | 200.61 → 119.71 | 59.50 → 45.73 |

Full input and output widths:
- MLA and DSA column: 7168 → 14592.
- KDA column: 7168 → 49664.
- Output row: 12288 → 7168.

These measurements were recorded during implementation. MLA and DSA
column and row results are paired comparisons; KDA main-baseline and
optimized-column results come from separate runs.

The final column recheck stayed within 1% of the pre-extension
implementation. FP8 checks showed no latency regression. Outputs matched
bit-for-bit.

The main baseline used an equivalent compile-time guard around the
unused FP8 producer; its BF16 schedule was unchanged.

## Test Plan

- `pre-commit run --all-files` passed.
- BF16 and FP8 TP2 and TP4 correctness checks passed, including CUDA
graph replay, uneven and empty owners, 2,048-row capacity, and output
lifetimes.
- Cold-L2 Nsight benchmarks on four GB200 GPUs at 60–180 tokens per
rank:
- BF16 column latency stayed within 1% of the pre-extension column-only
implementation.
- No FP8 latency regression observed after removing the legacy BF16
code.
- Outputs matched bit-for-bit, with one fused kernel per measured
projection.
- TP8 was not run locally; left for CI.

---------

Signed-off-by: Enwei Zhu <21126786+syuoni@users.noreply.github.com>
2026-12-03 12:14:03 +08:00
Fan Yang e6f3f4c97c fix(kernel): precompile all LLBf16SplitK M-threshold variants during warmup (#3881)
## Summary

`LLBf16SplitK` compiles with symbolic `(M, K, N)` but switches
`(split_k, num_stages)` across `_SPLITK_CONFIG_BY_M` (`num_stages=4` for
`M <= 16` vs `num_stages=2` for `17 <= M <= 32`).

During startup:
- Prefill warmup often runs only large batches (`M > MAX_M`), bypassing
`ll_bf16` altogether.
- Warmup or early traffic in one `M` range (e.g. `M <= 16`) compiled
only one stage variant, leaving the other (`17 <= M <= 32`) to
JIT-compile on the forward thread during serving.

This PR closes both gaps:
1. Adds `splitk_configs()`, `LLBf16Router.supports_splitk_k(k)`, and
`LLBf16Router.warm_splitk(...)` so all split-K threshold configurations
compile together, and calls `warm_splitk` on the first split-K miss in
`LLBf16Router.__call__`. `LLBf16Router.clear_splitk_cache()` lets tests
start from a cold compile cache without touching the cache-key layout.
2. Adds `warm_ll_bf16_splitk(...)` (Hopper+ NVIDIA only, skipped while
stream capturing) and calls it under `is_warming_up()` in
`kimi3_router_projection`, `dsv4_linear_fp32`, `block_scaled_router_mm`,
and `NemotronH` router forward.
3. Adds host-only unit tests for the guard branches
(`tokenspeed-kernel/test/nvidia/ops/gemm/test_ll_bf16_splitk_warmup.py`)
and CUDA `assert_no_cute_compile` tests
(`tokenspeed-kernel/test/nvidia/ops/gemm/test_ll_bf16_router.py`)
covering the first compile, `warm_ll_bf16_splitk` on its own, and
large-M `kernel_warmup(enabled=True)` paths across `M in (5, 8, 16, 17,
24, 32)`.

## Test Plan
- [x] Host-only unit tests: `pytest
tokenspeed-kernel/test/nvidia/ops/gemm/test_ll_bf16_splitk_warmup.py` (7
passed)
- [x] `pre-commit run --all-files` (all checks passed)
- [ ] NVIDIA Hopper/Blackwell GPU test: `pytest
tokenspeed-kernel/test/nvidia/ops/gemm/test_ll_bf16_router.py
tokenspeed-kernel/test/nvidia/ops/test_dsv4_router_gemm.py`

---------

Signed-off-by: Fan Yang <250624800+fanyang-real@users.noreply.github.com>
2026-12-02 20:13:19 -08:00
Fan Yang eeb2dbc8e1 perf(dsv41): declare layer_accesses_wait_for_load on DeepseekV41CachePool (#3891)
## Summary

Declares `layer_accesses_wait_for_load: ClassVar[bool] = True` on
`DeepseekV41CachePool` so `PrefillGraph` replays overlap Host L2 and
shared-L2 cache loads layer by layer instead of stalling on
`wait_for_all_layers()` before segment 0.

Updates `docs/design/cache-concepts.md` to document DeepSeek V4.1 as
eligible for layerwise replay waits.

### Audit

Every cache view access in `DeepseekV41AttentionBackend` and
`DeepseekV41DSparkModel` goes through
`DeepseekV41CachePool.{swa,global_kv,index_k,compressor_tail,dspark_kv}`
or `get_{key,value,kv}_buffer`, all of which enter `_field(layer, name)`
and call `layerwise_load_tracker.wait_for_layer(layer)` (recording
per-segment waits under `BreakableCapture`). `swa_buffers` is bound only
for `CachePool` plane metadata and is never indexed directly during
forwards.

## Testing

- Extended `test_pool_strides_owner_fences_and_no_redundant_fields` in
`test/runtime/test_deepseek_v41_cache.py` to verify `wait_for_layer`
calls across `swa`, `global_kv`, `index_k`, `compressor_tail`,
`dspark_kv`, `get_key_buffer`, `get_value_buffer`, and `get_kv_buffer`.
- Added a CUDA replay regression test covering per-segment and
whole-load waits, including replay without a capture-time tracker and
replay with an undeclared pool. It checks that delayed host-to-device
loads preserve both loaded cache contents and rows written during
replay.
- Local verification: `py_compile` and exact `pre-commit run
--all-files` passed.

---------

Signed-off-by: Fan Yang <250624800+fanyang-real@users.noreply.github.com>
2026-12-02 20:12:25 -08:00
tuanzhangCS 898520a687 fix(runtime): disable remote code by default in ModelConfig
Signed-off-by: tuanzhangCS <26617745+tuanzhangCS@users.noreply.github.com>
2026-12-03 10:29:39 +08:00
Tuan Zhang 2490fe7dba Merge branch 'main' into codex/disable-remote-code-by-default 2026-12-03 10:24:13 +08:00
Fan Yang 638da8bcb5 perf(v41,cache): eliminate layerwise L2 transfer, compressor, and MegaMHC serving JITs (#3922)
## Summary
Eliminate remaining Triton, CuTe DSL, and DeepGEMM serving-time JIT
compilations across DeepSeek V4.1 Host L2 layerwise loads, ratio-2 KV
compressors, and MegaMHC joins:

1. **`_wait_layer_ready_kernel`
(`tokenspeed-kernel/python/tokenspeed_kernel/ops/kvcache/triton.py`):**
Add `do_not_specialize=["layer_index"]` so warmed aligned and unaligned
wait-kernel binaries are reused across consumer layers instead of
compiling per layer during serving.
2. **`HostCacheExecutor._warmup_restore_transfers`
(`python/tokenspeed/runtime/cache/l2/executor.py`):**
- Run warmup for `l2_tier` in addition to `snapshot_lcm_blocks` and NPU
when `io_backend == "kernel"`, with guards for empty groups or zero
blocks.
- Warm the unflagged H2D path. For eligible L2 host storage, also warm
the `layer_ready` H2D transfer and aligned and unaligned
`wait_layer_ready` variants once inside
`named_region("cache_transfer")`, so serving-time layerwise L2 loads
trigger zero JIT compilations and add zero ordinary allocator
allocations.
3. **`DeepseekV41ForCausalLM.post_quant_warmup`
(`python/tokenspeed/runtime/models/deepseek_v41.py`):**
- Add `_warmup_compressors` to precompile `dsv4_linear_fp32` for CUDA
`DeepseekV41Compressor(ratio=2)` modules inside
`kernel_warmup(enabled=True)`, using deduplicated buckets `{1,
min(max_tokens, 16), min(max_tokens, 32)}` plus `min(max_tokens, 64)`
when `max_tokens > 32`.
- Add `_warmup_mega_mhc` to precompile `try_mhc_shifted_post_pre_norm`
(BF16) and `try_mhc_shifted_post_pre_norm_quantize_fp8` (FP8) across
token buckets up to `max_tokens`, including dynamic prefill buckets
beyond 8192 tokens. Probe `m=1` before allocating full warmup buffers,
and skip the sweep when neither kernel is available or eligible.

## Tests
- `tokenspeed-kernel/test/ops/test_host_cache_transfer_words.py`:
`test_wait_layer_ready_reuses_warmed_binaries` (`assert_warmup_covers`
across aligned and unaligned views with varying layer indices).
- `test/runtime/test_host_executor.py`:
`test_l2_init_warms_layer_ready_transfers_without_serving_jit`
(`assert_no_triton_compile` across multi-layer L2 H2D and
`wait_for_layer`).
- `test/runtime/test_deepseek_v41_model.py`:
`test_post_quant_warmup_warms_mhc_and_caches_compressor_kernels`,
`test_mega_mhc_warmup_counts_cover_decode_and_dynamic_prefill_buckets`,
and `test_warmup_mega_mhc_stops_after_ineligible_probe`.
- Local verification: `pre-commit run --all-files`, `ruff check --select
F821,F401,F841,E9`, `py_compile`, and `git diff --check` passed (GPU
execution queued via CI or pod verification).

---------

Signed-off-by: Fan Yang <250624800+fanyang-real@users.noreply.github.com>
2026-12-02 18:14:10 -08:00
Fan Yang baa2b46ba6 perf(dsv41,kernel): eliminate serving-time Triton JIT specializations and warmup gaps (#3917)
## Summary
Fixes several serving-time Triton JIT specializations and startup warmup
gaps observed on DeepSeek V4.1-Flash workloads under
`TOKENSPEED_JIT_COMPILE_CHECK=error`:

1. **`fused_decode_input_prep_kernel`
(`python/tokenspeed/runtime/execution/cache_loc_kernel.py`):** Replace
the copy-pasted `do_not_specialize=["max_pages"]` with
`do_not_specialize=["uniform_input_length"]`. Also add
`uniform_input_length` to `compute_out_cache_loc_kernel` and use
`max_draft_prefix` for `dflash_prepare_decode_kernel`, allowing
compilation reuse as decode and verify step widths or draft-prefix
lengths change.
2. **`_normalize_candidate_blocks`
(`tokenspeed-kernel/python/tokenspeed_kernel/ops/attention/dsv41/_deep_gemm/indexer.py`):**
Launch through `kernel_launcher` and register warmup variants for the
power-of-two `BLOCK` buckets from 1 through 2048, matching
`next_power_of_2(blocks)`.
3. **`_global_rope_scatter`
(`tokenspeed-kernel/python/tokenspeed_kernel/ops/attention/dsv41/_triton/rope.py`):**
Move the runtime stride scalars `X0`, `POS0`, `CS0`, `C0`, `C1`, and
`S0` from `tl.constexpr` to `do_not_specialize`. Use an overflow-safe
slot bounds check, handle contiguous and noncontiguous cache rows
through `CONTIGUOUS_ROW`, launch through `kernel_launcher`, and register
warmup for `num_warps=(1, 4)` and both `CONTIGUOUS_ROW` values.
4. **`_dspark_rows_kernel`
(`tokenspeed-kernel/python/tokenspeed_kernel/ops/attention/dsv41/triton.py`):**
Add `X0`, `POS0`, `CS0`, `S0`, `W0`, `W1`, `O0`, and `PAGES` to
`do_not_specialize` to prevent stride and pool-size specializations, and
make the window-slot bounds check overflow-safe.
5. **Host row gathers
(`tokenspeed-kernel/python/tokenspeed_kernel/ops/embedding/triton_host_gather.py`):**
Keep MXFP8 batch dimensions, index strides, and table strides out of the
specialization key; do the same for uint8 row counts, widths, and table
and output strides while using 64-bit row indexing. Disable alignment
specialization for sliced index, code, and scale views. During
`kernel_warmup(enabled=True)`, precompile the sorted-threshold and
unsorted MXFP8 gather paths as well as `_copy_duplicate_rows_kernel`.

## Verification
- Verified `python3 -m py_compile`, `ruff check --select F821,F401,E9`,
and `pre-commit run --all-files` locally.
- Added `assert_no_triton_compile` behavioral GPU tests across
`test_cache_loc_kernel.py`, `test_attention_dsv41_rope.py`,
`test_attention_dsv41.py`, and `test_embedding_host_gather.py` (GPU run
pending on Blackwell runner).

---------

Signed-off-by: Fan Yang <250624800+fanyang-real@users.noreply.github.com>
2026-12-02 15:26:28 -08:00
Chen Hongtao 832bc8b74b perf(attention): capture DeepSeek V4.1 prefill projections and KV writes (#3872)
## Summary

Stacked on
[#3642](https://github.com/lightseekorg/tokenspeed/pull/3642).

On the supported Blackwell FP8 path, #3642 lets prefill CUDA graphs
replay the attention output projections. Query projection and
quantization, indexer query preparation, and KV writes still run inside
eager attention breaks. This change captures those operations for pure
prefill and mixed prefill and decode batches, reducing per-layer host
launches. Mixed batches now use the same fused FP8 attention output
layout and prepared output projection as pure prefill.

The backend refreshes token positions and cache write slots at fixed
addresses once per encoder or decoder stage. A captured bucket can then
serve different prefix lengths, with writes limited to live rows.
Encoder layers save the old sliding-window prefix before current tokens
reuse its slots. Decoder prefill starts its window at the first retained
row and skips this snapshot. Index selection and FlashMLA attention run
eagerly on the live rows.

At the context encoder and decoder (CED) boundary, the encoder computes
layer 20’s global KV and index keys from all live input rows, including
chunks that produce no decoder output. After row selection, the decoder
graph replays that layer’s query projections and feed-forward network on
the retained-row bucket. Changing the projection shapes can affect
rounding.

Encoder and decoder stages independently select the smallest captured
bucket that covers their rows, falling back to eager execution when no
bucket fits. Under attention DP, ranks agree on the stage capacities and
any replay veto, while decode-only and idle peers still participate in
the required collectives. This CED replay path requires the
fixed-capacity DeepGEMM MegaMoE layout; unsupported layouts retain eager
prefill.

`--prefill-graph-decoder-capture-token-sizes` configures decoder graph
capacities in retained rows independently of the encoder’s input-token
buckets. The default is a window-based ladder. Explicit sizes may exceed
the largest encoder bucket when they fit the forward token budget and
per-rank request capacity. Eligible shifted MegaMHC joins are also
captured after warmup on the capture stream.

Pure eager prefill skips the indexer’s query and head-weight projections
when top-k covers the entire history. Graph capture includes both
projections so the same bucket can serve longer histories.

## Test Plan

We benchmarked DeepSeek-V4.1-Flash-1017 with **AgentX** on the same 4×
GB200 node, using #3642 at `4404a1a3aabd` as the baseline. Each version
completed one 20-minute run at concurrency 128 with attention TP1, DP4
and EP4, hash session affinity, synthetic acceptance length 3.51, and
zero request errors.

| Metric | #3642 | This PR | Change |
|---|---:|---:|---:|
| Output tokens per second per GPU | 1,475.24 | 1,493.74 | +1.25% |
| P90 time to first token | 7.297 s | 5.314 s | −27.18% |
| P90 end-to-end latency | 15.500 s | 14.376 s | −7.25% |
| P90 full-response inter-token latency | 5.64 ms | 5.68 ms | +0.71% |
| Prompt cache hit rate | 95.340% | 95.415% | +0.075 pp |

At the same 0.85 GPU memory utilization target, the CUDA graph memory
budget grew from 14.36 to 16.51 GiB per rank, reducing KV capacity from
9,531 to 8,813 pages per rank.

On **GSM8K**, the baseline answered 1,204 of 1,319 questions correctly
(91.28%) and this PR answered 1,205 (91.36%). Both runs used the same
four B300 GPUs with DP4 and EP4, four-shot greedy decoding, and real
DSpark verification. Both completed with zero request errors.

The patch adds regression tests for CED source replay across
retained-row counts, mixed prefill and decode output handling,
sliding-window reads and KV preservation when cache slots are reused,
prepared index-query replay for dense and sparse scoring, descriptor
capture with a background pinned allocator, and stage buffer addresses
across memory release and resume.

---------

Signed-off-by: chenht2022 <chenht2022@gmail.com>
2026-12-02 14:46:54 -08:00
Nicolas Perrin 4c49c93616 perf(k3): skip two Multimem staging copies per K3 prefill layer (#4077)
## Summary

Prefill TTFT on Kimi K3.1 (TP8) improves by 1.1–1.4% at 8k, 16k, and 8k
on a cached 32k prefix. Decode does not move. Outputs are bit-identical
to base.

When a K3 forward has more than 1024 rows, the attention o-projection
writes its partial into the symmetric multimem buffer. The MoE tail
all-reduces in that same buffer. Three device-to-device copies sit
around these two all-reduces, and two of them are not needed:

- **Attention sum.** On a layer with an AttnRes prefix, the reduced sum
is a delta. The AttnRes mixer adds it into the residual in place right
after the reduce, so it is now read straight from the buffer. A
block-write layer, whose residual is the sum itself, still copies it
out.
- **Shared experts.** The shared down projection now writes its partial
straight into the buffer view (`K3MoeTailComm.acquire_shared_output`),
so the `multimem_stage` copy after the stream join is gone.
- **MoE output (kept).** This copy stays, because the residual outlives
the next layer's o-projection, which writes into the same buffer.

The lifetime rule is now: the attention delta must be added into owned
storage before the shared partial lands in the buffer, and the residual
handed to the MoE never lives in the buffer. A new distributed test
checks it (see Tests).

In an 8k prefill profile (rank 0), device-to-device copies of 10 µs or
more drop from 321 (6.40 ms) to 144 (2.91 ms).

The change adds no allocations. Batches of 1024 rows or fewer take the
same path as before; this includes every decode step measured below.
Decode verify batches above 1024 rows take the new path too. Under
attention DP with attention TP > 1, the attention-sum copy also goes
away, with the delta added in place the same way; the MoE there keeps
its own path, which this PR does not touch. The AMD and sharded-residual
paths are unchanged. `multimem_stage` has no runtime caller left; this
PR keeps the kernel API.

## Numbers

Setup:
- Kimi K3.1 Pro, TP8 over two 4-GPU nodes.
- FP8 KV cache, chunked prefill 8192, prefill CUDA graphs on, DSPARK
speculation with 8 draft tokens.
- Each arm (this PR and its base commit) ran on two servers,
interleaved: PR, base, PR, base.
- Measured before the rebase onto current main. The K3 model changes on
main since then are gfx950-only.

**Prefill.** Each request uses `max_new_tokens=1`, so its latency is its
TTFT. Each server value is the median of 3 requests, taken after 1
warmup request. The table gives the mean of the two servers in each arm;
the range columns span the two servers.

| Prefill TTFT (ms) | Base | This PR | Δ | Base range | PR range |
|---|---:|---:|---:|---:|---:|
| 2k (2,014 tokens) | 104.7 | 100.8 | −3.9 (−3.74%) | 101.7–107.6 |
100.8–100.8 |
| 8k (8,114 tokens) | 274.0 | 270.9 | −3.2 (−1.15%) | 273.7–274.3 |
270.3–271.4 |
| 16k (16,114 tokens) | 542.0 | 534.6 | −7.4 (−1.37%) | 541.0–543.0 |
534.1–535.1 |
| 8k on a cached 32k prefix (40,114 tokens, 32,114 cached) | 289.6 |
286.5 | −3.1 (−1.08%) | 287.8–291.5 | 284.8–288.2 |
| 32k uncached (the prefix request, 32,114 tokens) | 1075.6 | 1063.4 |
−12.2 (−1.13%) | 1072.8–1078.4 | 1062.4–1064.4 |

- The saving grows with the number of uncached tokens, at about 0.4 ms
per 1k tokens. A cached prefix adds nothing: 8k on top of a cached 32k
prefix saves the same 3 ms as 8k alone.
- **2k:** one base server was slow on all three of its requests. Against
the other base server, the PR is 0.9 ms faster (−0.93%), which fits 0.4
ms per 1k tokens. Read 2k as about −1%, not −3.7%.
- **8k on a cached 32k prefix:** the two ranges overlap by 0.4 ms.
Within each interleaved pair of PR and base runs, the PR is 3.0 ms and
3.3 ms faster.

**Decode.** Concurrency 1, 16 and 64 with 6k-token contexts, measured in
a steady-state window. Each arm has 4 runs (2 per server).

| Decode (ms per step) | Base | This PR | Δ | Base range | PR range |
Tokens per step (base, PR) |
|---|---:|---:|---:|---:|---:|---:|
| c1 | 8.567 | 8.567 | +0.00% | 8.552–8.581 | 8.562–8.572 | 2.48, 2.48 |
| c16 | 25.730 | 25.764 | +0.13% | 25.687–25.774 | 25.731–25.819 | 2.86,
2.80 |
| c64 | 48.157 | 48.119 | −0.08% | 48.079–48.235 | 48.078–48.234 | 2.91,
2.89 |

Decode does not move. Its steps stay below 1024 rows, so they do not
take the changed path. The ranges overlap for both step time and tokens
per step.

## Tests

- **Prompt logprobs, PR vs base, fresh servers.** Every prompt position
is bit-identical in both repetitions: 2,013 positions at 2k, 8,113 at
8k, 16,113 at 16k. On fresh prompts, the last-token logprob and the
top-20 also match.
- **GSM8K, 100 questions, greedy:** 100 out of 100 on both PR servers.
- **New:
`test_attention_sum_leaves_the_buffer_before_the_shared_partial`** in
`test/runtime/test_k3_moe_tail_equivalence.py`. It chains the real
`K3AttnComm` reduce (`reduce_for_attnres`, or `attn_reduce`),
`attn_res_fwd` and `KimiLinearMoE.forward` with the real `K3MoeTailComm`
and `StreamFork`, over the shared symmetric buffer, for two layers. It
covers block-write, delta and accumulate layers at M = 1024, 1025 and
8193 (capacity), eager and under CUDA-graph capture and replay. Every
output must be bit-identical to a run that copies each Multimem sum out
of the buffer. Three mutations each fail it: accumulating the residual
into the buffered delta, dropping the block-write copy, and dropping the
MoE-output copy.
- **Distributed, 8 ranks over 2 nodes:**
`test/runtime/test_k3_moe_tail_equivalence.py`: 19 passed on every rank
(the 10 stage-2 cases, M = 1…8193, eager and CUDA graph, plus the 9 new
cases). Its graph replays are now compared bit for bit with eager runs
on the same inputs.
`tokenspeed-kernel/test/nvidia/ops/communication/test_multimem_distributed.py`:
28 passed on every rank.
- **K3 runtime unit tests** (`test/runtime/test_*k3*.py`,
`test/runtime/test_kimi*.py`): 1372 passed, 83 skipped, 6 failed. The
same 6 fail on the base commit: three float32-logits checks in
`test_kimi_k31.py`, the bf16 MLA chunked-prefill case, the MXFP4
dense-linear case, and
`test_execution_slots_bind_once_and_survive_a_pool_rebind`. The 9 extra
skips are the new distributed cases, which skip outside torchrun.
- `pre-commit run --all-files` is clean.

---------

Signed-off-by: Nicolas Perrin <nperrin.ai@gmail.com>
2026-12-02 14:28:23 -05:00
Nicolas Perrin cd5417ae0a ci: persist the Triton cache in Slurm containers and cut fixed test waits (#4114)
## Summary

Both `runtime-1gpu` halves run within minutes of the 60-minute step
limit of a packed GB200 single-GPU task, and part-ii is cancelled for
time whenever install or a cold JIT runs a little slow. This PR shortens
the suite instead of raising the limit.

- **Persist the Triton cache in Slurm containers.** Triton caches under
`$HOME` by default, and the container discards it, so every packed task
compiled its Triton kernels cold.
- `TRITON_CACHE_DIR` now points into the shared cache mount, as
`FLASHINFER_WORKSPACE_BASE` already does.
- Measured on one GPU, cold vs warm cache: `test_sonic_backend.py` 323 s
→ 43 s, `test_sonic_vocab_shard.py` 151 s → 12 s.
- Those two files alone take about 12 minutes across the two halves
today.
- The pipeline's per-runner isolated JIT cache only fills variables that
are still unset, so it keeps this one.
- **Cut fixed waits that the tests do not check.**
- The allocator probe's deadline (`launcher.py`) and the launcher's
final per-scheduler join (`engine.py`) become named module constants.
- The probe-timeout test sets the deadline to 1 s instead of waiting the
full 60 s.
- The two stuck-rank tests, which already shorten the exit grace,
shorten the join too.
- The assertions are unchanged: the same `TimeoutExpired` is raised, the
stuck ranks are still killed, and the port is still free on restart.
- **Compare the sonic sampling configs at one vocabulary instead of
two.**
  - The test now uses 129024 columns instead of 131072 and 151936.
- At 129024 the 2k tiles end whole and the 4k, 8k and 16k tiles end
partial, so both the bitonic and the radix configs are still compared on
a whole and on a partial last tile.
  - The configs 151936 reaches are a subset of the six compared.

## Tests

- `test_ut_gpu_routing.py` now asserts that the pack script passes
`TRITON_CACHE_DIR` into the container and sets it to the shared cache.
`test/ci_system` (routing, Slurm submit, pipeline): 265 passed.
- The changed runtime tests pass. Mutation checks:
  - dropping the probe deadline makes the probe-timeout test fail;
  - an exit grace that never expires fails both stuck-rank tests;
- perturbing the RADIX_4K or BITONIC_4K output fails
`test_every_picked_config_draws_the_same_tokens[129024]`.
- `pre-commit run --all-files` passes.

---------

Signed-off-by: Nicolas Perrin <nperrin.ai@gmail.com>
2026-12-02 13:10:29 -05:00
Nicolas Perrin 52d94ab954 refactor(moe): pass the MoE output destination and top-k slot deferral as arguments (#4037)
## Summary

Kimi-K3 and the latent MoE gave the routed experts their output
destination and the top-k slot deferral by setting `_situ_output_buffer`
and `_situ_defer_topk_reduce` on the `MoELayer` before calling it.
Eleven MoE apply kernels read them back with `getattr`, and the latent
MoE saved and restored the buffer around its call. They are now
arguments.

- `moe_apply` and `MoELayer.forward` take `out`, a caller-owned
destination for the finalized rows, and `defer_topk_reduce`. A plan
advertises them as `supports_out` and `supports_defer_topk_reduce`;
`moe_apply` refuses either on a plan without the capability, as it does
`deferred_out`.
- The kernels that read the attributes (FlashInfer TRT-LLM MXFP4 and
NVFP4 SiTU, FlashInfer Cake MXFP4 SiTU, and the gfx950 and gfx1250 Gluon
MXFP4 applies) take them as parameters and declare the traits. They
still write into `out` only when its shape and layout fit.
- K3's native forward passes both to its experts calls when the selected
plan supports them, so a plan that ignored the attributes receives
neither, as before. The main forward no longer resets the buffer, and
the latent MoE passes its routed target directly.

## Tests

Tests that set the attributes pass `out=` and `defer_topk_reduce=`
instead; the stubs that stand in for `MoELayer` accept them.

On GB200: the NVIDIA SiTU kernel tests and the kernel API selection
suite (441 passed), and the MoE layer, latent MoE and Kimi-K3 runtime
suites pass. `test_kimi3_moe_execution_policy_preserves_nvidia_trtllm`
and `test_model_prepares_routed_workspace_at_serving_limit` fail on main
as well. The gfx950 and gfx1250 tests change the same way and run in AMD
CI.

Served greedy on GB200, main vs this branch, tokens and logprobs
compared bit for bit: Qwen3.5-35B-A3B-FP8, TP1, short prompts, a
2.8k-token prompt with its prefix hits and a follow-up turn are
identical. Four concurrent requests vary from run to run on main itself
(5 main runs, every rerun differs from the first, two at the step where
the shortest request leaves the batch); one branch run matched main on
them exactly.

---------

Signed-off-by: Nicolas Perrin <nperrin.ai@gmail.com>
2026-12-02 10:30:27 -05:00
SagacityandWangBo 6be794e7e8 fix(sampling): preserve request state across intermediate prefill chunks (#4078)
An unfinished prefill chunk computes a provisional sample that the
scheduler discards. Consuming that row's RNG draws or recording its
output-token penalties makes later samples depend on where the prompt
was split.

This change passes the scheduler's chunk lengths to the sampling backend
before step preparation. Pooled generators preview unfinished rows, and
the Ascend full sampler commits counts only for rows that emit tokens.

Ascend device tests cover one- and eight-draw steps, cached and uncached
prefixes, mixed completed and incomplete rows, subsequent RNG draws, and
penalty counts. Four new cases and two existing Ascend
cumulative-probability cases passed.

---------

Signed-off-by: Iridescent-gcrace <58317897+Iridescent-gcrace@users.noreply.github.com>
Co-authored-by: WangBo <wangbo981016@gmail.com>
2026-12-02 22:42:44 +08:00
Sagacity 4f4deba647 feat(pd): expose remote prefill admission metadata to attention backends (#4079)
Stateful attention backends may need the request identity, absolute
token frontier and destination block tables when accepting a remote
prefill. Passing only request slots leaves them unable to check that
transferred state belongs to the current request.

Provide an opt-in admission snapshot before advertising transfer
destinations, and forward both admission and landing notifications
through hybrid attention. Backends that use slots alone retain the
existing hook and avoid copying block tables.

Focused tests cover immutable metadata ownership, native scheduler
admission, device/executor dispatch, hybrid children, landing and
subsequent decode. Eighteen tests passed with the scheduler built from
the base revision.

---------

Signed-off-by: Iridescent-gcrace <58317897+Iridescent-gcrace@users.noreply.github.com>
2026-12-02 22:42:16 +08:00
Guoyuan LinandWangBo 20c0c5b447 feat(dflash): add batch-invariant draft forward mode (#4084)
## Summary

Under `--enable-speculative-sampling` a DFLASH draft's tokens enter the
served trajectory, so the draft's rows must not depend on the batch they
run in. Two of its operators do. The new flag
`--enable-draft-forward-batch-invariant` replaces them. It is off by
default, also under `--numerics rl-bitwise`, and the default path is
unchanged.

**Decode attention.** The adaptive Triton MHA decode splits a request's
keys by batch size and SM count, so the order in which key blocks fold
into a row's sum follows the co-batch. For a GQA block draft (32/8
heads, head dim 128, window 1024 + 16 sink, width 8) on H200 the split
count goes 5, 3, 2, 1 from 1 to 8 requests, and a request's rows
differed in 12837 of 32768 elements between batch 1 and 8.

- New leaf `triton_invariant_mha_decode_with_kvcache` declares
`batch_invariant`. Each program folds one row block's keys in index
order, with no split dimension.
- `mha_decode_with_kvcache` takes a required `batch_invariant` argument.
The draft's `MHAAttnBackend` sets it from the flag; the target's backend
does not.
- Selection fails rather than falling back, and no split schedule is
passed. The leaf takes no logit cap and no q/k/v scales.

**Context K|V write.** The write multiplies the round's context rows, a
count the accepted lengths and the co-batch decide, by `qkv_proj`.
cuBLAS moves a row between row counts for K = 4096 to 8192 projections.

- `DFlashAttention` plans the per-layer slice with
`plan_dense_gemm(batch_invariant=True)` at construction, so an unmet
flag stops the launch.
- Every round writes through the per-layer path; the stacked fused write
is off under the flag. A round takes the fused write only when no
prefill shares it, and that kernel rounds K once where the per-layer
write rounds it after the norm and again after the rotation. Left on, a
request's cached K rows would follow whether another request prefills in
the same round.

## Requirements

- A bitwise numerics envelope (`--numerics rl-bitwise`). The flag is
refused under `auto`: it replaces two operators only, and the draft's
other GEMMs (`fc`, the query side of `qkv_proj`, `o_proj`, the MLP, the
head projection) plan batch-invariantly under a bitwise envelope alone.
- A batch-invariant `gemm.mm` leaf for BF16. This tree registers one
only for gfx950, with FP32 output. Elsewhere a plugin provides it;
without one the launch stops when the draft model is built, as for any
other missing provider.
- Supported: a DFLASH GQA draft whose layers all use a sliding window,
unquantized. Any other draft fails when the draft model is built:
another speculative algorithm, a draft built from another decoder layer
class (DFlash2), an MLA draft, a draft with a full-attention layer, a
quantized draft.

## Cost

The attention leaf, on H200 under CUDA graph replay, as time against the
adaptive leaf: a windowed block draft takes 1.75x at batch 1 and
0.90-0.95x from batch 8; with no window 5-12x at batch 1 over 4K-128K
keys and parity from batch 64. The per-layer context write replaces one
fused launch with a GEMM, a norm, a rotation and a scatter per layer.

## Test Plan

- Kernel: the leaf against `torch_dense_attention` (block draft, decode,
verify width, window or not, sinks, lse); row bits alone against batches
of 2 to 16; no recompile across batch and length; K page offsets past
2**31.
- Draft: the planned GEMMs; the real attention backend with the flag on
and off, for target and draft; `_sample_block_from_q` over 1 to 64
requests with a reference GEMM provider; the structures the flag refuses
and the same drafts building without it.
- Context write: the same context row leaves the same K and V in a
decode-only round and in a mixed round (1 to 512 rows) and beside other
rows; the fused write is off under the flag and on without it.
- Arguments: the flag is refused under `auto` and for a speculative
algorithm other than DFLASH, accepted under `rl-bitwise`, and carried
into `global_server_args_dict`.
- End to end on H200, one prefill and one decode instance (4 GPUs each,
DP4/EP4), a DFLASH GQA sliding-window draft,
`--enable-speculative-sampling` on decode, the flag on both roles,
`--numerics rl-bitwise`: 620 prompts generated together and again each
alone, 620/620 identical tokens and scores; five fixed prefix-hit
lengths with 32 requests each, 160/160 identical to the cold run; and
every one of the 620 requests at its own hit length with the hit
requests running together, 620/620 identical.

---------

Signed-off-by: linguoyuan <linguoyuan@meituan.com>
Co-authored-by: WangBo <wangbo981016@gmail.com>
2026-12-02 19:57:47 +08:00
zhuhaozhecool 7fa445f4df fix(runtime): interrupt headless startup waits on shutdown (#4057)
## Summary

A headless launcher can stay blocked in `receive_ready_messages()` after
a shutdown signal when a rank keeps its ready pipe open during
initialization and survives TERM. Because Python retries `EINTR` when a
signal handler returns normally, the launcher never reaches the
supervisor's 30-second grace-period check, and the rank can keep its
listening port bound.

Add an optional `stop_requested` predicate to `receive_ready_messages()`
with bounded polling (`0.2s`, matching the polling model already used by
`_supervise_schedulers()`), leaving `_terminate_schedulers()` unchanged:

- Check `stop_requested()` before and after `connection.wait()` and
raise `InterruptedError` on shutdown.
- Catch `InterruptedError` in `launch_scheduler_headless()`, re-signal
any ranks registered after the initial signal, and hand off to
`_supervise_schedulers()` using the existing grace period measured from
the first request.

## Validation

- `python -m pytest -v test/runtime/test_headless_launcher.py
test/runtime/test_startup_process_ownership.py
test/runtime/test_ready_pipe.py`: **26 passed** (rebased on `main`
including #4048 and #3790).
- Added startup shutdown + same-port restart regression tests (single
`SIGUSR1` and `SIGTERM`, rank ignoring TERM with ready pipe open,
verified `SIGKILL` cleanup and clean restart on the same port) in
`test/runtime/test_startup_process_ownership.py`.
- Added readiness unit tests in `test/runtime/test_ready_pipe.py`
covering `stop_requested` both before and during `connection.wait()`.
- `pre-commit run --all-files`: passed.

## Related change

Follow-up to #4048 (merged, fixing nested-signal lock reentrancy after
readiness). This PR covers shutdown signals arriving during startup
readiness waits.

Signed-off-by: zhuhaozhecool <zhuhaozhecool@163.com>
2026-12-02 19:27:56 +08:00
Hanyu Weiandlongcat-ia-team 91e14dc195 feat: plan fused weight-only block FP8 projections (#4060)
## Summary
Add a kernel-registry interface for fused W8A16 projections with BF16
activations, E4M3 weights, and FP32 128×128 block scales.

- Select the projection implementation once when initializing the layer.
- Preserve canonical FP8 codes/scales and read updated weights on every
forward.
- Retain the existing dequantization + BF16 GEMM path when no fused
implementation supports the hardware or geometry.
- Reject unavailable explicit kernel overrides instead of silently
replacing them.

This PR adds the host-side dispatch interface. Provider-specific fused
kernels are registered separately.

## Validation
- 6 tests passed in
`test/runtime/layers/test_w8a16_fp8_block_linear.py`.
- Covers weight updates, storage preservation, partial blocks, strided
inputs, bias, empty batches, and invalid inputs/overrides.
- `pre-commit run --all-files` passed.

---------

Signed-off-by: Patirck <151747616+Patirck@users.noreply.github.com>
Co-authored-by: longcat-ia-team <312376714+longcat-ia-team@users.noreply.github.com>
2026-12-02 17:48:18 +08:00
84b94d72bf perf(gdn): index prefill state and reuse inline graphs (#4006)
## Summary

- Pass recurrent-state pages and their read and write indices directly
to the selected FlashInfer GDN prefill scan. The scan seeds fresh rows
from zero and writes live final state directly to the pool.
- Capture one inline graph per token bucket for indexed GDN. Default its
request capacity to rank-local `--max-num-seqs` and cap it at the
bucket's token count. An explicit list selects its largest capacity. Pad
unused slots with zero tokens and state indices of `-1`. Size the
startup probe arena for the widest candidate capture.
- Preserve in-forward checkpoints and cover full buckets, padding,
variable request counts and GPU memory release in regression tests.

## Performance

The A and B runs used Qwen3.8-Flash-Next-NVFP4 on one SM103 GPU (TP1),
BF16 recurrent state and 2048-token prefill chunks, with FlashInfer
0.7.6rc1. Timings were collected on the benchmark branch before
rebasing.

### Full-chunk replay with 63 requests

Both sides used indexed GDN state, `--max-num-seqs 64`,
`--prefill-graph-capture-batch-sizes 64` and a single `2048` token
bucket. Each wave starts one uncached prefill round. The full wave uses
32 prompts of 33 tokens and 31 of 32 tokens. TTFT is measured from the
scheduler release request and uses 64 waves per case per side (4,032
requests). Replay p50 is from 16 separate CUDA-event samples per case
per side.

| Tokens | Replay route before → after | TTFT p50 (ms) | TTFT p95 (ms) |
Replay p50 (ms) |
|---:|:---|---:|---:|---:|
| 2048 | ordinary → inline capacity 64 | 65.06 → 48.60 (−25.3%) | 69.23
→ 52.74 | 51.79 → 34.90 (−32.6%) |
| 2047 | inline capacity 64 → inline capacity 64 | 49.21 → 49.05 | 53.11
→ 53.19 | 35.27 → 35.09 |

### State indexing

At concurrency 1 with 128 samples per side, changing dense state to
indexed state reduced 2048-token ordinary-graph TTFT p50 from 51.13 to
49.73 ms (−2.7%). Inline TTFT p50 was 42.70 → 42.60 ms. The sum of GDN
scan and state-preparation GPU time across 36 layers fell from 2.80 to
2.39 ms on the ordinary route.

### AgentX trace replay

Both sides used indexed GDN state. Over 20 minutes of measured replay
(150 seconds per concurrency and variant), six token buckets and request
capacities `1,2,8,32` produced 24 → 6 inline captures. Warm recapture
went from 28.0–28.8 s to 15.2 s.

| Client concurrency | Completed requests per side | Output tokens per
second before → after | TTFT p50 (ms) | TTFT p95 (ms) |
|---:|---:|---:|---:|---:|
| 1 | 65 | 190.81 → 190.81 | 91.8 → 84.7 | 549.8 → 552.9 |
| 2 | 23 | 115.79 → 115.77 | 110.9 → 110.0 | 326.0 → 325.9 |
| 8 | 8 | 111.58 → 111.58 | 396.5 → 396.5 | 3506.9 → 3505.4 |
| 32 | 99 | 695.40 → 695.40 | 212.5 → 244.9 (+15.2%) | 4728.6 → 4729.4 |

At concurrency 32, the median per-request TTFT delta across the same 99
completed requests was +1.33 ms. The server reached 14 running requests
in both variants.

## Test Plan

- `pre-commit run --all-files` passed.
- On SM103 with the pinned FlashInfer 0.7.6, 55 kernel tests passed,
including BF16 and FP32 indexed-state CUDA graph replay with and without
checkpoints. The runtime regression run had 200 passed, 3 skipped, and
44 passed subtests.
- A freshly started Qwen3.8-Flash-Next-NVFP4 server on the PR branch
captured the 2048-token bucket, replayed one uncached wave of 63
requests through inline capacity 64, and returned one completion token
per request.
- The indexed GDN memory-release regression and the existing
managed-metadata release test both encountered
`CUDA_ERROR_INVALID_VALUE` from `cuMemFree_v2` on this host. Local
release and resume validation is pending.
- The default-capacity follow-up passed 126 focused runtime tests and 39
subtests. With the graph-memory probe enabled and `--max-num-seqs 64`, a
fresh server captured `(2048, 64)` using the default request capacity.
An uncached wave of 63 requests and 2048 tokens replayed through inline
capacity 64 with 63 successful completions.
- The review follow-up passed 59 kernel tests and 60 runtime tests on
SM103 with FlashInfer 0.7.6. CUDA Graph replay covered int32 and int64
state indices. The fused preparation tests covered mixed input dtypes
and verified that varying request counts reuses the warmed Triton
kernel.

---------

Signed-off-by: tuanzhangCS <26617745+tuanzhangCS@users.noreply.github.com>
Signed-off-by: lightseek-bot <243258330+lightseek-bot@users.noreply.github.com>
Co-authored-by: tuanzhangCS <26617745+tuanzhangCS@users.noreply.github.com>
Co-authored-by: lightseek-bot <243258330+lightseek-bot@users.noreply.github.com>
2026-12-02 16:49:23 +08:00
Enwei Zhu 60db198cd3 fix(dsa): preserve Prims plans across memory release (#4055)
## Summary

Prims-TS DSA retains plan workspaces and per-row metadata across calls,
but these allocations were not registered with the runtime memory saver.
Memory release could therefore discard buffers that retained plans still
referenced.

Register the memory saver's CPU-backed workspace region with the kernel
and use it when creating Prims plans and lazily growing row metadata.
Their addresses and contents now survive memory-saver pause and resume,
while offsets are still built on device to avoid synchronization during
serving. Standalone kernel calls continue to use the ordinary Torch
allocator unless they register a workspace region.

## Test Plan

Added `test/runtime/test_dsa_prims_memory_saver.py`, covering repeated
memory release and resume, pointer and data preservation, lazy metadata
growth, ordinary allocator release, and unchanged eager and CUDA graph
outputs.

Signed-off-by: Enwei Zhu <21126786+syuoni@users.noreply.github.com>
2026-12-02 15:22:11 +08:00
Lei Zhang b3213da8f0 fix(rocm): keep hipHostMalloc on hosts with NUMA balancing enabled (#4087)
Since #3970 the launcher defaults ROCm worker processes to parallel
pinned registration (`pinned_use_hip_host_register:True`), which turns
every pinned buffer, including the per-step staging buffers, into
`malloc` plus `hipHostRegister`. Such buffers are private anonymous
memory. With kernel NUMA balancing enabled, the kernel keeps migrating
those pages between NUMA nodes, and each migration invalidates the
registered range, so the GPU driver suspends all of the process's queues
until it revalidates it. `hipHostMalloc` memory is a shared mapping that
NUMA balancing skips.

The ROCm registration default now applies only when
`/proc/sys/kernel/numa_balancing` reads 0 (or is absent, on a kernel
built without NUMA balancing); any nonzero mode, balancing or memory
tiering, keeps PyTorch's `hipHostMalloc` default. An explicit
registration option is still the user's choice. The server configuration
and cache docs say how to keep parallel registration on such a host
(`sysctl kernel.numa_balancing=0`).

Tests: `test_launcher_pinned_allocator.py` pins the sysctl through a
temporary file, checks that both nonzero modes keep the default
allocation, reads the sysctl modes and a missing file, and has the
fresh-worker test expect registration only when the host's own NUMA
balancing is off.

Signed-off-by: Lei Zhang <antiagainst@gmail.com>
2026-12-01 22:54:44 -08:00
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
zhuhaozhecool 70d995c5e0 fix(dflash): validate YaRN capacity and size cache for target context (#3960)
## Summary

Align DFlash draft context validation and DeepSeek YaRN RoPE cache
sizing with the resolved target context `L`, without changing
`ModelConfig` or `--hf-overrides` forwarding.

### Behavior Changes (Before vs. After)

| Area | Before | After |
| --- | --- | --- |
| **YaRN cache sizing** | Read only `--max-model-len` from
`global_server_args_dict`; omitting it skipped `spec_rope_positions`
sizing. | Uses the resolved target context `L` (target `config.json` +
`--hf-overrides`, optionally capped by `--max-model-len`) and builds `L
+ 4 * verify_width` rows. Falls back to `max_model_len` only on
standalone construction. |
| **Draft capacity validation** | `--max-model-len` was checked against
the draft's declared `max_position_embeddings` (rejecting a
512K-declared draft whose native YaRN table covers 1M); omitting
`--max-model-len` skipped capacity validation entirely. | Validates
draft capacity against `L` at startup in `load_model_config`: DeepSeek
YaRN drafts use native table size `ceil(original_max_position_embeddings
* factor)` regardless of declared `max_position_embeddings`; other
DFlash drafts use their declared context. Raises `ValueError` if
capacity `< L`. |

### Examples (verify width = 8)

| Scenario | Target `L` | Draft Config | Before | After |
| --- | --- | --- | --- | --- |
| 512K target + `--hf-overrides '{"max_position_embeddings": 1048576}'`
(no `--max-model-len`) | `1,048,576` | YaRN `8192 * 128` (declares 512K
or 1M) | Skips `spec_rope_positions` sizing | Passes; builds `1,048,608`
rows |
| 512K target (no `--max-model-len`, no overrides) | `524,288` | YaRN
`8192 * 128` | Skips `spec_rope_positions` sizing | Passes; builds
`524,320` rows |
| 1M target + `--max-model-len 1048576` | `1,048,576` | YaRN `8192 *
128`, declares `524288` | Startup error (`1048576 > 524288`) | Passes
(`1,048,576 >= 1,048,576`); builds `1,048,608` rows |
| 1M target (no `--max-model-len`) | `1,048,576` | YaRN `8192 * 120`
(`983,040`), declares `1048576` | Starts silently; skips cache sizing |
Startup `ValueError` (`983040 < 1048576`) |
| 1M target (no `--max-model-len`) | `1,048,576` | Non-YaRN, declares
`524288` | Starts without capacity check | Startup `ValueError` (`524288
< 1048576`) |

## Test Plan

- `pytest test/runtime/test_dflash_rope.py -v`: all 23 tests passed on
CPU (with platform/Triton probe and `tokenspeed_engine` import stubs),
covering checkpoint default, `--hf-overrides`, explicit
`--max-model-len`, 512K-declared draft with 1M native YaRN table,
undersized YaRN table rejection, and non-YaRN draft rejection.
- `black --check`, `isort --profile black --check-only`, and `ruff check
--select F` passed on all modified Python files.

Signed-off-by: zhuhaozhecool <zhuhaozhecool@163.com>
2026-12-02 14:21:18 +08:00
Han fca1346148 perf(npu): fuse frontier and block-table updates and skip empty graph updates (#4000)
## Summary

- Enable the existing Triton kernels on Ascend for
`advance_accepted_frontier` and `expand_block_table_rows`.
- Before replaying a captured Ascend decode graph, skip copying sequence
lengths to the host and calling `graph.update()` when the selected graph
has an explicitly empty update-record list. Graphs that require updates
still receive the current lengths. Set
`TOKENSPEED_DFLASH_SKIP_EMPTY_GRAPH_UPDATE=0` to send lengths for every
bucket, with or without speculative decoding.

## Validation

- Verified both metadata operators against expected outputs on CPU and
Ascend. The 41 Ascend block-table regression cases passed.
- Exercised graph replay with empty and populated records, unavailable
record metadata, manual capture, and the environment override.
- Ran `pre-commit run --all-files`.

---------

Signed-off-by: Minsanthrope <qiuhhan.han@gmail.com>
2026-12-02 14:20:32 +08:00
kangguangli a728169447 feat(peer): Unify peer prefix sharing and fence late DMA writes after cancellation (#4056)
<!-- Headings and layout are optional. Include change context and
validation
(checks performed or planned, or why testing was not run or is not
applicable)
anywhere in the description. -->

## Summary

<!-- What changed and why? -->
Unify peer prefix sharing for single-member DP replicas and sharded
TP/KVP replicas. Both use registered layouts and the same discovery,
offer, grant, and release protocol. Remove the legacy same-layout driver
and its Lookup/`Pin`/`Release` handlers. Disk pushes now require an
active offer matching the holder incarnation and offer ID.
Decouple request cancellation from transfer retirement. A cancelled
request can return immediately. A late PeerFetchDone is matched to its
original lease and cannot publish the cancelled prefix or terminate the
engine. Once the reader irrevocably discards the result, the holder may
reuse source KV pages within the registered arena. The reader keeps
destination pages reserved until the transfer retires.
When the backend cannot confirm retirement, use
TOKENSPEED_PEER_READ_RETIREMENT_BOUND_MS (default 300000), followed by
the destination quarantine. This assumes that every physical memory
access completes within the bound after the last possible submission,
including queued work, retries, and remote writes. The hardware worst
case was not measured.

## 300-second retirement bound
TOKENSPEED_PEER_READ_RETIREMENT_BOUND_MS defaults to 300000. The
deployment must guarantee that the time from the final permitted batch
claim to the last possible memory access is within this bound. That
interval includes host scheduling pauses, native and device queues,
retries, reconnects, and accepted remote Disk pushes. Packet TTL alone
does not establish it. The smoke tests exercised the protocol and
measured transferred bytes. They did not establish a hardware worst-case
latency.

For an uncertain transfer, each reader member measures the bound on its
own monotonic clock, starting at the earlier of the attempt being sealed
and its 30-second submission window closing. Once all members report
retirement, the reader observes the existing 5-second target quarantine
before reuse. Confirmed clean completions retain their fast path.
Reusing a registered source slot after abort still requires its backing
memory and registration to remain valid.

## Test Plan

<!-- How was this validated? -->
[x] Passed all 372 control-library tests, plus 4 dual-engine tests, 4
DFLASH Disk tests, 9 general Disk integration tests, and the host
configuration test. Re-ran the 9 Disk integration tests on an MLP
worker.
[x] Model-checked source reuse after abort, missing callbacks, late
completions, and staging-slot reassignment. The model reproduced a late
write into a reused target when the configured bound was shorter than
the DMA tail.
[x] Ran four end-to-end smoke cases on Ascend 910B job psxf6xrtsp7nea
with two TP8/KVP8 Prefill replicas and one two-node DP32 Decode
deployment. All four requests generated 8 tokens.

---------

Signed-off-by: lvyongkang <kangguangli@hotmail.com>
2026-12-02 13:36:32 +08:00
bhsueh_NVandlightseek-bot 4d2e824ccc feat(kda): index retained decode records by execution slot (#3821)
## Summary

Index KDA retained decode records (FP32 U/K/decay history and shared
accepted counts) by a per-row **execution slot** instead of by
request-pool row, so PD decode nodes no longer allocate retained verify
workspace for `--disaggregation-decode-extra-slots`.

`Request::ExecutionSlot(role)` assigns each row's slot once in the
scheduler:
- **D role:** the decode permit (`1..max_batch_size`); remote-prefill
rows have no slot (`-1`).
- **Fused / P roles:** the request row (`1..max_batch_size`).

Runtime and kernels uniformly size retained records to `max_batch_size +
2` (row `0` null, row `max_batch_size + 1` CUDA-graph padding) with no
per-role branching. Recurrent state and per-request stop flags remain
indexed by request row.

## Changes

- **Scheduler:** Export per-row `execution_slots` and
`execution_slot_fresh` on `ForwardBatch`, extend `state_folds` to
`[request_row, live_page, execution_slot]`, and guard
`liveDeferredStatePages` on `Request::ExecutionSlotForwarded()` so a
restored victim retracted before its first resumed forward is not
folded.
- **Executor plumbing:** Pack `[fresh slots, execution slots, request
rows]` as a `(3, max_bs)` tensor uploaded in one H2D copy; add
`bind_execution_slots` / `reset_execution_workspace` on
`CachePoolBinding`; order fold -> fresh-slot reset -> forward on the
execution stream.
- **Kernels (Triton & AMD Gluon):** Batched retained commit reads stop
flags at `request_slots` (masked to `[0, stopped_count)`) and
records/counts at `record_slots`.
- **KDA backend & sizing:** Allocate/index retained records, counts, and
replay length by execution slot (`max_batch_size + 2` rows), align
`kda_verify_workspace_bytes` with the allocation, and left-copy decode
`execution_slots` into `_record_slots[:num_rows]` in
`refresh_decode_metadata`.
- **Docs & tests:** Update design docs (`scheduler.md`,
`cache-concepts.md`, KDA README) and fold execution-slot lifecycle
coverage into existing C++ (`StateFoldSuite`) and Python suites. No Rust
source changes.

## Verification

Verified on `7acda261b` against base `1138563a0` (GB300):

### Memory savings (12 heads/rank, default capacity 16)

| bs | T | resident | `main` (MiB) | this PR (MiB) | saving at 2x |
|---:|--:|---:|---:|---:|---:|
| 16 | 1 | 16 -> 32 | 359.04 -> 669.54 | 359.04 -> 359.04 | **46.4%** |
| 16 | 4 | 16 -> 32 | 388.20 -> 698.70 | 388.20 -> 388.20 | **44.4%** |
| 64 | 1 | 64 -> 128 | 1319.70 -> 2561.70 | 1319.70 -> 1319.70 |
**48.5%** |
| 64 | 4 | 64 -> 128 | 1436.34 -> 2678.34 | 1436.34 -> 1436.34 |
**46.4%** |

- Extra-slot workspace growth at `2x` residents: **0 B** vs **+1.21
GiB** on `main`; ratio at `1x` residents is **1.000x**; allocated and
reported bytes match on all 8 cells (`0` mismatches).

### Correctness (`0` new failures)

- **Native:** C++ `tokenspeed_scheduler_tests` **1970/1970** passed
(including 2 new `StateFoldSuite` tests), Rust `tokenspeed-engine`
**1079** passed (`0` new failures), scheduler Python **468/468** passed.
- **GPU regression:** **2,175** tests across KDA, kernel, runtime,
sizing, GDN, graph, and PD suites — **0 new failures** (4 pre-existing
`test_zero_output_prefill.py` failures reproduced identically on
`1138563a0`).
- **Static checks:** `pre-commit run --all-files`, `ruff`, DCO, and
commit trailers passed.

### Performance

- **Scheduler perf guard:** CI Callgrind instruction counts passed
(worst **+0.91%** on `decode_8k`, budget 2%); GB300 5-round timing
reported `0` regressions.
- **E2E KDA decode rounds** (4 GPUs x 2 passes = 8 pairs; 12 cells: `T
in {1, 4}`, `bs in {1, 16, 64}`, low/high acceptance):
- Device time ratio: **1.0000–1.0046** across 11/12 cells (all `T=4`
cells **<= 1.0033**); worst **1.0135** at `T=1, bs=1, high` (+5.3 us on
398 us, `launch_delta = +1` from the small D2D copy in
`refresh_decode_metadata`).
  - Wall time ratio (median): **0.9963–1.0075**.
- **Retained-commit kernel proxy** (`kda_retained_commit`, 24 cases,
cold L2): `t4-l34` (10/10), `t6-l69` (8/8), and `t8-l69 accepted=4`
(3/3) are within `-7.3%` to `+0.1%`; `t8-l69 accepted=1` at `bs=2/8`
adds ~1.3 us (within the benchmark's `2.0 us` absolute policy).

---------

Signed-off-by: bhsueh <11360707+byshiue@users.noreply.github.com>
Signed-off-by: lightseek-bot <243258330+lightseek-bot@users.noreply.github.com>
Co-authored-by: lightseek-bot <243258330+lightseek-bot@users.noreply.github.com>
2026-12-02 09:40:10 +08:00
Zhewen Yu 9bdb146b8c perf(k3.1): faster DSA prefill top-k and MXFP4 MoE prefill stage 1 on gfx950 (#3980)
## Summary

Kimi-K3 and K3.1 long-context prefill on gfx950 now moves less residual
data between layers, reads each DSA indexer row about once in the top-k,
scores and converts slots faster, and runs stage 1 of the MXFP4 MoE
faster. Selections stay exact and scores unchanged; only the MoE's SiTU
epilogue changes results, by rounding. As the top of the stack, this PR
also carries the whole stack's tests and accuracy checks.

- **DSA top-k.** For rows of at least 65,536 columns,
`_dsa_sampled_topk_kernel` estimates a threshold, builds an LDS list and
runs exact radix selection over it, reading each row about once instead
of four times. Misjudged or short rows fall back to exact whole-row
selection. Candidate order follows the source row so neighbouring rows
keep similar slot-read order.
- **Scoring, slot conversion and warmup.** The MXFP4 scorer tiles query
rows to fill the device and divides a logits budget into even launches.
Slot conversion reads the small page table instead of the int64
workspace-slot map. Runtime top-k geometry is no longer specialized, and
startup covers the scorer, selection and small eager-extend row classes
so serving compiles none.
- **K3 prefill data flow.** A row-sharded residual now stays sharded
until the first drafter-tapped layer, then gathers for that tap and the
remaining layers. Attention and shared-expert projections also publish
each owner's partial final row tile, so evenly sharded 4,608- and
5,000-token prefills use the published path instead of falling back.
- **MXFP4 MoE prefill stage 1** (K3.1's N16 banks). The SiTU epilogue
builds `tanh` and the sigmoid from `exp2` with one approximate division,
changing the output by 3–5e-5 relative L2. The K loop is unrolled with
weights prefetched two tiles ahead, and four-wave 64-row tiles cover 256
weight columns at two waves per SIMD instead of 128 at four.

Shapes and platforms outside these conditions keep the current path.

## Results

Kernel times on MI350X unless noted:

| Change | Shape | Before | After |
|---|---|---:|---:|
| Sampled top-k | 916 rows of 146,432 columns | 347 µs | 168 µs |
| List order, slot conversion | 8,192 rows of 146,432 keys | 87.9 µs |
66.8 µs |
| Scorer tiles, scorer plus top-k per layer | 8K chunk at a 138K context
| 1,071 µs | 965 µs |
| Slots from the page table | 8,192×2,048 rows over a 146,432-row
workspace | 50.7 µs | 24.2 µs |
| SiTU from `exp2`, stage 1 | 8,192 rows | 0.546 ms | 0.498 ms |
| 256-column tiles, stage 1 | 8,192 tokens (MI355X) | 0.41 ms | 0.39 ms
|

Rows with massive exact ties fall back after the sample and run at
0.66–0.71× the old speed. The unrolled K loop and the two-ahead prefetch
are each 1–2% faster.

In TP8 serving on MI355X at a 138K prefix plus an 8K chunk, the top-k
goes from 406 to 178 µs and scoring from 639 to 586 µs per DSA layer,
slot conversion from 2,222 to 612 µs per step over all layers, MoE stage
1 from 427.8 to 383.9 µs per layer, and time to first token from 403.1
to 395.8 ms. Publishing partial final tiles reduces time to first token
for a 138,240-token prefix plus 4,608 new tokens from 284.3 to 273.9 ms.

## Test Plan

On gfx950:

- [x] `test_gluon_dsa_amd.py`: the sampled top-k against exact selection
on ragged rows over seven score distributions (ties, crowded, recent and
clustered among them), its fallback when the sample misjudges a row, and
warmup coverage at both residencies.
- [x] `test_gluon_dsa_mxfp4_index_k.py`: the scorer on every tile and
under a logits budget, and its warmup coverage.
- [x] `test_attention_dsa.py`: the page-table slot conversion (int32 and
int16 indices, both top-k widths). `test_kimi_k31.py` and
`test_dsa_dcp_index_reuse.py`: the prefill top-k record's page table
gives the slot map's slots, the gathered history pages' under KVP.
- [x] `test_kimi_k3_sharded_residual.py`: the row-sharded stream gathers
at the first drafter tap. `test_gluon_a16w16_gfx950.py` and
`test_iris_published_attention.py`: partial final owner tiles publish
bit for bit on one and eight GPUs.
- [x] `test_gluon_mxfp4_situ_gfx950.py`: the 256-column stage-1 tile
bitwise against the 128-column tile.
- [x] 26 kernel and runtime test files on MI355X. Four
`test_zero_output_prefill.py` cases and one
`test_dsa_row_shard_prefill.py` case fail on main as well.
- [x] The whole stack on 8x MI355X: 125 kernel, Iris and runtime test
files. The 28 failing cases fail on main as well: 14 in
`test_nemotron_h.py`, six in `test_gluon_latent_input_gfx950.py`, four
in `test_zero_output_prefill.py`, and one each in `test_comm_ops.py`,
`test_iris_moe_tail.py`, `test_k3_moe_tail_tier.py` and
`test_dsa_row_shard_prefill.py`.
- [x] InferenceX's GSM8K eval on the whole stack scores 0.983 (1,319
questions; 0.90 required), and the acceptance-length gate measures 3.78
against the curve's 3.81 (pass).
- Not run on NVIDIA; these paths are gfx950 only.

Signed-off-by: Zhewen Yu <zhewenyu@amd.com>
2026-12-01 17:27:16 -08:00
Zhewen Yu 505e21856e perf(k3.1): faster decode MoE, dense GEMMs and AttnRes collectives on gfx950 (#3979)
## Summary

Kimi-K3 and K3.1 decode on gfx950 gets faster MoE, dense GEMM and
AttnRes collective kernels at the row counts of TP8 speculative verify
(6 tokens per request, so 16–48 requests are 96–288 rows), and the fast
paths now reach row counts they skipped.

- **MoE decode.** Sorted A8W4 SiTU starts at two rows, fuses W13 and
SiTU with W2 at 16–48 rows and splits W13's K from 24. Warp decode, the
latent-input gather and its per-rank projection now serve through 288
rows; one-launch routing reaches 512 and carries the shared down
projection with it. The gather tail projects runs of row tiles, and
startup warms its variants before serving.
- **Dense BF16 decode GEMM.** The gfx950 medium decode kernel stores
split-K partials in MFMA lane order, adds eight-wave tiles and deeper
LDS rings with re-tuned K3.1 configs at 96–288 rows, and gains a row
tail for rows just past a power-of-two bucket, which fell back to torch.
On CDNA4 the packed QKV and gate projection runs as one GEMM through 512
rows.
- **AttnRes and collectives.** The bank two-shot reduces the attention
output and applies the AttnRes mix and output norm in one launch.
Gathered MoE tails can produce the next layer's attention input; larger
AMD batches stay on the fused graph and banks, while the mix folds two
snapshots per round. Dense MLP and embedding reductions use the
attention group's Iris reducer instead of RCCL.

Tests that encoded the old row bounds now check the new ones, with new
coverage for the fused and split sorted MoE paths, row-tail GEMMs, bank
collectives and gather-tail mixing. Shapes and platforms outside these
conditions keep the current path.

## Results

Kernel times on MI355X unless noted:

| Change | Shape | Before | After |
|---|---|---:|---:|
| Sorted SiTU decode | 4 rows, clustered routing | 28.7 µs | 23.6 µs |
| One-launch routing plus shared down projection | 288 rows (MI350X) |
34.0 µs | 25.2 µs |
| Latent input projection, replicated | 288 rows | 75.1 µs | 58.8 µs |
| Split-K partials in lane order, q_a+kv_a (2112×7168) | 96 rows | 19.4
µs | 16.7 µs |
| Eight-wave tiles, 7168×1536 | 96 rows | 12.1 µs | 9.1 µs |
| Row tail, 2112×7168 | 257–288 rows | 33.9–35.0 µs | 24.4–25.6 µs |
| One packed QKV and gate GEMM, 3648×7168 | 288 rows | 56.5 µs | 32.4 µs
|
| Bank two-shot, reduce plus mix over 8 ranks | 48 rows, 4 blocks | 13.7
µs | 9.8 µs |
| AttnRes mix, two snapshots a round | 48 rows, 11 blocks | 11.8 µs |
10.5 µs |
| Iris reduce for the dense MLP and embedding, per reduce | 16 requests
| 29.8 µs | 12.8 µs |

The sorted SiTU decode is also 1.5–4.5 µs faster at 16–48 rows.

In TP8 DCP8 serving, routed experts at 288 rows take 254 instead of 275
µs per layer, while the latent projection path drops from 82 µs of
replicated projection, epilogue and quantization to 56 µs of per-rank
projection and gather. At 48 requests routing drops from 30.3 to 16.3 µs
per layer. The AttnRes changes improve decode tokens per second per
request from 121.7 to 123.0 at 16 requests and 93.8 to 96.5 at 24, and
reduce the 4-request step from 18.74 to 18.16 ms; 32 and 48 requests are
unchanged.

## Test Plan

On gfx950:

- [x] `test_iris_communication.py` on 8 GPUs: the bank two-shot against
the reduction followed by `attn_res_fwd`, with and without a residual,
eager and replayed with a slow rank.
- [x] `test_iris_moe_gather_tail.py`: the gather tail's bank finishers
against the separate mix, and the codegen of three-tile runs.
- [x] `test_gluon_mxfp4_situ_gfx950.py`: the sorted decode against the
reference from 2 to 288 rows, eager and replayed from a CUDA graph.
`test_kimi3_sorted_routing_gfx950.py`: the routing and shared down
projection bit for bit at the new row counts.
- [x] `test_gluon_a16w16_gfx950.py`: the row-tail GEMM configs against a
reference across their sub-buckets. `test_gluon_latent_input_gfx950.py`:
the split K covers every row tile. `test_iris_moe_latent_gather.py`: the
sharded latent gather bit for bit against the replicated launch through
the new row bound.
- [x] `test_kimi3_prefill_gluon_amd.py`: the AttnRes mix's two-snapshot
rounds. `test_kimi_k3_attn_res.py`, `test_kimi_k3_decode_chain.py` and
`test_kimi_k3_sharded_residual.py`: the K3 decode and sharded-residual
paths.
- [x] 51 kernel, Iris and runtime test files on 8x MI355X. Six
`test_gluon_latent_input_gfx950.py` cases, one
`test_k3_moe_tail_tier.py` case and one `test_iris_moe_tail.py` case
fail on main as well.
- [x] The whole stack's tests and accuracy checks in #3980.
- Not run on NVIDIA; these paths are gfx950 only, and the collectives
need the Iris backend.

Signed-off-by: Zhewen Yu <zhewenyu@amd.com>
2026-12-01 17:26:53 -08:00
Aaryaman VasishtaandLei Zhang 8baef5a601 fix(amd): serve Quark MXFP4 GLM-5.3 checkpoints with block-FP8 layers (#4069)
## Summary

The AMD GLM-5.3 Quark MXFP4 AttnFP8 and GLM-5.3-Flash Quark MXFP4
checkpoints keep some modules in block FP8 (`[128, 128]` weight scales,
dynamic FP8 activations). `Mxfp4Config` only accepts the two existing
per-layer FP8 schemes, so both checkpoints fail at startup with
"Unsupported per-layer quantization scheme".

Loading:

- `Mxfp4Config` accepts block FP8 as a third per-layer override and
routes those linear and MoE layers to the existing block-FP8 paths.
- `preprocess_mxfp4_checkpoint_weights` renames Quark's `weight_scale`
to the runtime's `weight_scale_inv`; the GLM-5.3 and GLM-5.3-Flash
target and MTP models load through it.
- GLM-5.3-Flash: the fused `fused_qkvbfg_a_proj` is excluded together
with the six KDA projections the checkpoint excludes.
- The GLM-5.3 MTP draft names its modules after its checkpoint layer so
its per-module overrides resolve.

gfx950 MoE kernels (needed by GLM-5.3-Flash):

- `gluon_mxfp4_a4w4_moe_apply_gfx950` supports clamped SwiGLU. The limit
is a `gl.constexpr`; 0 compiles the previous code.
- `gluon_fp8_block_dequantize` no longer overflows int32 indexing on
expert tensors past 2^31 elements (hit by the GLM-5.3-Flash MTP experts
at TP2).

Other checkpoints are unchanged.

## Test Plan

On gfx950, compared with the base branch in the same build:

- `pre-commit run --all-files` is clean.
- New and extended unit tests pass: `test_gluon_mxfp4_a4w4_gfx950.py`,
`test_gluon_fp8_block_dequantize_gfx950.py` (also with
`TRITON_DEBUG=1`), `test_mxfp4_config.py`, `test_glm53_flash_models.py`,
`test_nextn_draft_weights.py`.
- The rest of the gfx950 MoE kernel tests and the runtime tests touching
the changed modules fail in the same places as on the base branch.
- The AMD GLM-5.3-Flash Quark MXFP4 checkpoint serves at TP2 with MTP
under `TOKENSPEED_JIT_COMPILE_CHECK=error` and answers correctly,
including concurrent long prompts. Qwen3.8-Flash-Next Quark MXFP4 (no
clamp) still serves.

Not run yet: both GLM checkpoints at TP4; gfx1250 and NVIDIA CI.

---------

Signed-off-by: Aaryaman Vasishta <aaryaman.vasishta@amd.com>
Co-authored-by: Lei Zhang <antiagainst@gmail.com>
2026-12-01 15:25:31 -08:00
Chen, Zhentao b60d40e352 fix(eagle4): accept draft_moe_quantization in the EAGLE-4 draft config (#4012)
## Motivation

Since #3928, `load_model_config` (`rank_setup.py`) sets
`draft_moe_quantization` on every draft config, next to
`decode_monokernel`. The EAGLE-4 draft's strict config check
(`validate_draft_config` in `llama_eagle4.py`) does not know the key, so
every EAGLE-4 server fails at startup on main, even with the default
`--speculative-draft-moe-quantization none`.

Repro on main (60509dc6a, 1x MI355X; any EAGLE-4 draft fails the same
way):

```
tokenspeed serve Qwen3.8-27B --tensor-parallel-size 1 --dtype bfloat16 --max-model-len 65536 \
  --attention-backend mha --speculative-algorithm EAGLE4 \
  --speculative-draft-model-path EAGLE-Corp/Qwen3.8-27B-EAGLE4 \
  --speculative-eagle-topk 1 --speculative-num-steps 7 --speculative-num-draft-tokens 8
```

```
  File ".../tokenspeed/runtime/models/llama_eagle4.py", line 620, in __init__
    validate_draft_config(config)
  File ".../tokenspeed/runtime/models/llama_eagle4.py", line 208, in validate_draft_config
    raise ValueError(
ValueError: EAGLE-4 draft config has keys this model does not implement: ['draft_moe_quantization']
```

## Changes

- `llama_eagle4.py`: accept `draft_moe_quantization` as a key startup
sets on every draft config, next to `decode_monokernel` (same handling
as #3523). Only `"none"` is accepted. The EAGLE-4 draft (dense, or the
latent MoE) has no MXFP4 routed experts, and ServerArgs admits `mxfp4`
only for Qwen3.8 MTP drafts (`draft_quantization_refusal`). If the value
is anything else, the check fails explicitly instead of serving BF16
experts the user did not ask for.
- `test_llama_eagle4_draft_config.py` (new, CPU only): runs the real
`rank_setup.load_model_config` on the Qwen3.8 (dense) and Nemotron
(latent MoE) EAGLE-4 draft configs from `test_llama_eagle4.py`, with
`ModelConfig` mocked and the ServerArgs defaults. It checks that the
config it returns passes `validate_draft_config`, and that `mxfp4` is
refused. It is a separate file because `test_llama_eagle4.py` is
disabled on `amd-*` runners (no AMD kernel for the latent MoE's relu2
experts). Registered for `runtime-1gpu` without a runner restriction, so
it runs on the NVIDIA and AMD runners alike.
- `test_dspark_config.py`: the DSpark draft dtype tests call
`load_model_config` with fake server args. #3928 broke them
(`AttributeError: ... no attribute
'speculative_draft_moe_quantization'`), so the fake args now include the
field.
- `test_eagle4_serving_dummy.py` (new, `runtime-1gpu`, regression test
for this bug): serves EAGLE-4 end to end without downloading anything.
It writes the Qwen3.8-27B and Qwen3.8-27B-EAGLE4 configs shrunk (four
hybrid target layers: three GDN and one full attention, plus the vision
tower; width 512; a 4096-token vocabulary) and starts the engine with
`--load-format dummy` through the wire driver. The startup path is the
one `tokenspeed serve` takes: server args,
`rank_setup.load_model_config` (which sets `draft_moe_quantization`),
the `llama_eagle4` draft config check, draft/target construction, CUDA
graphs and speculative decoding. Three modes, each serving a batch of 8
requests of 32 tokens:
- static chain: top-k 1, 7 steps, 8 draft tokens, with
`--synthetic-acceptance-length 4` so verify rounds commit several draft
tokens;
  - static tree: top-k 4, 5 steps, 16 draft tokens;
- EAGLE-Harness (exec mode 0): top-k 4, 12 steps, 16 draft tokens, on
synthetic cost data.

It is registered without a runner restriction, so it runs on every
`runtime-1gpu` runner (h100-1gpu, b200-1gpu, gb200-1gpu and
amd-mi355-1gpu). It has only been run locally on AMD MI355X; the NVIDIA
runners are untested locally and rely on CI. It does not cover draft
quality (dummy weights do not agree, so tree/harness acceptance length
is 1 and the chain acceptance length is forced) or the harness's real
cost measurement (`measure_run`).
- Remove the `server-smoke-qwen3.8-27b-eagle4-mi355` yaml task, its
`k8s-dispatch.yml` entry, and `test/eagle4_serving/eagle4_check.py` with
its test; update `test/ci/README.md`. The yaml task downloaded
Qwen3.8-27B and its EAGLE-4 draft (about 54 GB) and took about 741 s
with warm weights (336 s of it the harness cost measurement); the
runner's HF cache is now full, so it could not run. The new test covers
its startup, config check and chain/tree/harness serving paths, but not
its minimum acceptance-length check.

No other draft model has a strict key check like this one
(`validate_draft_config` is the only one).

## Test plan

- New test fails on main with the error above and passes with this
change.
- `test/runtime/models/test_eagle4_serving_dummy.py` on 1x MI355X: main
without the fix, main with the fix, and this PR's head.
- `test/ci_system` on this PR's head and its base.
- Runner filter: `_runner_label_skip_reason` for the new test on
h100-1gpu, b200-1gpu, gb200-1gpu and amd-mi355-1gpu; `pytest
--collect-only` on the new file (CPU).
- EAGLE-4 config tests in `test/runtime/models/test_llama_eagle4.py`
(accept/refuse cases). The rest of the file needs a CUDA GPU and is
disabled on AMD runners.
- `test/runtime/test_dspark_config.py -k dtype`.
- CI plan: `runtime_suite.plan_suite` for `runtime-1gpu` on each runner
of `ut-runtime-1gpu-part-i/ii`, for both the full suite and this PR's
changed paths; `pipeline.py scan --runner-group amd` with this PR's
changed paths.
- `pre-commit run --all-files`.
- Server: EAGLE-4 on Qwen3.8-27B, TP1 bf16, 1x MI355X, chain (topk 1, 7
steps) and tree (topk 4, 12 steps), c1/c8/c32, with main plus the same
key accepted in `_STRUCTURAL_KEYS`.

## Test results

- `pytest test/runtime/models/test_llama_eagle4_draft_config.py` (CPU,
platform stub): main 1 failed (`ValueError ...
['draft_moe_quantization']`); this PR 1 passed.
- `pytest test/runtime/models/test_eagle4_serving_dummy.py` (1x MI355X):
main 3 failed in 55 s, each with `ValueError: EAGLE-4 draft config has
keys this model does not implement: ['draft_moe_quantization']`; with
the fix 3 passed; this PR's head 3 passed in 138 s (chain 64 s, tree 38
s, harness 34 s). Earlier runs took 105-146 s (the slower one includes
the first JIT compile), against about 741 s plus a 54 GB download for
the removed yaml task.
- `pytest test/runtime/models/test_llama_eagle4_draft_config.py` on 1x
MI355X at this PR's head: 1 passed.
- `pytest test/ci_system`: the same 9 failures on this PR's head and on
its base (55c40a4df), so none come from this PR (missing Rust toolchain
in the local container, plus dispatch-workflow checks that already fail
on the base); 11 fewer tests on the head because `test_eagle4_check.py`
is removed.
- Runner filter: the new test is planned on h100-1gpu, b200-1gpu,
gb200-1gpu and amd-mi355-1gpu (none skips it); `--collect-only` collects
its 3 cases (chain, tree, harness). NVIDIA results will come from CI.
- `pytest test/runtime/models/test_llama_eagle4.py -k "accepts or
refuses_draft or refuses_a_vocab"`: passed (unchanged file).
- `pytest test/runtime/test_dspark_config.py -k dtype`: main 2 failed
(`AttributeError`); this PR 2 passed.
- CI plan: `test_llama_eagle4_draft_config.py` is planned on h100-1gpu,
b200-1gpu, gb200-1gpu and amd-mi355-1gpu, both full and PR-changed;
`test_llama_eagle4.py` stays skipped on amd-mi355-1gpu. The AMD scan
selects `ut-runtime-1gpu-part-i/ii` on amd-mi355-1gpu.
- `pre-commit run --all-files`: passed.
- Server: with the key accepted, EAGLE-4 started and served every
chain/tree c1/c8/c32 run, and its chain and tree greedy-output parity
checks passed (from the #3985 A/B on 2026-11-30). Without it, every
launch failed at startup with the error above.

---------

Signed-off-by: Chen, Todd <zhentao.chen@amd.com>
2026-12-01 14:30:52 -08:00
Zhewen Yu 92a1cc6da6 perf(k3.1): fuse the KDA prefill conv and speed up the retained verify on gfx950 (#3978)
## Summary

Kimi-K3.1's KDA layers on gfx950 now fuse the prefill short convolution
into the prepare kernel, run the rest of the prefill faster and speed up
the speculative-decoding retained verify.

- **KDA prefill.** The gfx950 prepare kernel now applies the short
convolution and SiLU to the projection rows itself through
`KdaPrefillConv`, and reads beta as a strided view. Where fusion is
unavailable, the standalone convolution loads its rows earlier. The scan
prefetches decay and chain operands, uses narrower row blocks for long
single sequences, and the gated RMSNorm packs the 12 live heads instead
of padding them to 16.
- **Retained verify.** Up to 16 contiguous retained records are staged
in LDS instead of replayed through dependent global loads. The verify
also projects the `f_b` gate, applies the output norm, uses eight-wave
panel splits while the grid is small, and from four to eight tokens per
request can hold one request head's full 128×128 state in a single
workgroup. The head kernel follows the shared retained-count contract
from [#3780](https://github.com/lightseekorg/tokenspeed/pull/3780).
- **Backend naming.** The portable flash-linear-attention scan is now
named `triton` instead of `fla` in KDA prefill backend selection. NVIDIA
`auto` uses it as the fallback after CuteDSL and FlashKDA.

The fused prefill convolution changes results by rounding, through FP32
tap accumulation and an approximate SiLU reciprocal, while its
convolution windows remain bit-identical. Shapes and platforms outside
the optimized kernels' conditions keep the current path.

## Results

Kernel times on MI350X unless noted:

| Change | Shape | Before | After |
|---|---|---:|---:|
| Fused convolution (conv plus prepare) | 8,192 tokens | 124.6 µs |
100.2 µs |
| Row-load convolution | 8,192 tokens | 87.5 µs | 60.9 µs |
| Scan row blocks | 8,192 tokens | 97.9 µs | 92.4 µs |
| Gated RMSNorm | 8,192 tokens | 17.2 µs | 14.2 µs |
| Retained verify records in LDS | 16 requests of 6 tokens, many
retained records | 166.0 µs | 25.6 µs |
| Retained verify gate and output norm, per KDA layer | 48 requests
(MI355X) | 42.0 µs | 37.0 µs |
| Retained verify head kernel (verify plus norm) | 16 requests of 6
tokens, 10 records | 23.0 µs | 16.3 µs |

The strided beta saves a launch of about 7 µs per KDA layer at 4,608 and
8,192 tokens on MI355X.

## Test Plan

On gfx950:

- [x] `test_gluon_kda_prefill.py`: the fused-conv prefill against the
separate conv and the reference (chunk edges, FP16, a time split), and
its warmup coverage.
- [x] `test_gluon_kda_retained_history.py`: the retained head verify
(replay past the staged records, partial windows, a null row, unstamped
records, graph replay, BF16 state) and its compile-once check, the four-
and eight-wave verify, and the whole-head output norm.
- [x] `test_causal_conv1d_prefill_qkv.py`: the row-load conv against
conv-then-split at extreme values.
- [x] `test_gated_fp8_quantize.py`: the tiled gated RMSNorm against the
per-token kernel. `test_kimi_k3_kda_eager_commit.py`: the KDA eager
commit with the fused conv.
- [x] 27 kernel and runtime test files on MI355X, all passing.
- [x] The whole stack's tests and accuracy checks in #3980.
- Not run on NVIDIA; these paths are gfx950 only.

The diff also adds coverage for wide offsets in the whole-head verify
and row-load convolution, and for the `triton` backend selection.

---------

Signed-off-by: Zhewen Yu <zhewenyu@amd.com>
2026-12-01 12:43:53 -08:00
Lei Zhang 933e496986 fix(workspace): keep zeroed kernel state mapped across a memory release (#4031)
`zeroed_state()` hands out split-K and arrival counters that kernels
leave zeroed for the next launch: one eager buffer per stream and one
arena per capture session, both cached past the launches that use them.
They came from the ordinary allocator, so after a weights release they
pinned allocator segments, against the zero-occupancy rule of
`docs/design/event-loop.md`.

- `workspace.set_zeroed_state_region(region)` makes later eager buffers
and arenas allocate inside `region()`; `ModelExecutor` registers the
memory saver's "workspace" region before warmup and capture, which keeps
their addresses and zeros across a release.
- `add_state_region_setter` lets vendor kernel packages that cache their
own buffers (split-K partials) follow the same region.

Tests: `test_workspace.py` checks the placement and the setter
forwarding; `test_torch_memory_saver_adapter.py` runs repeated release
and resume cycles with eager split-K state and a capture arena and
checks that they keep their zeros and addresses and that ordinary
segments occupy nothing.

---------

Signed-off-by: Lei Zhang <antiagainst@gmail.com>
2026-12-01 10:59:08 -08:00
Nicolas Perrin 9f7984fc53 fix(k3): keep the prepared K3 communication state across a forward reload (#4066)
## Summary

`ts reload-forward` failed on Kimi K3: after any reload that re-executes
`kimi_k3_comm` (an edit to it, or to a module it imports, such as the
GEMM operation module or the latent tail), the warmup raised
`RuntimeError: K3 routed workspace must be prepared before forward` on
every rank, and the reload reverted.

A reload re-executes changed modules and their dependents and copies
each new class body onto the live class, data attributes included.
`K3AttnComm` and `K3MoeTailComm` keep K3's prepared communication state
as class attributes, set once at startup (`_routed_workspace`,
`_latent_tail`, `_stage2_capacity`, `_multimem_group_name`, `cute_ar`,
`attn_ar_fusion_ok`, `staged_projection`, `dummy_norm`, `iris_states`,
...). Re-executing the module reset them to their initial `None`,
`False`, or `{}` values.

Each of those attributes now takes its value from the live class when
the module is re-executed (`_kept`), the class-level counterpart of the
module-level `globals().setdefault` rule in the forward-reload guide.
The startup workspaces are kept; nothing is allocated again. The guide
notes the class-level case.

## Tests

- `test/runtime/test_kimi_k3_comm_arming.py` (new case): re-executing
`kimi_k3_comm` keeps the prepared state; fails without the fix.
- Kimi K3.1 Pro on two nodes with four GPUs each, using TP8, KVP and DCP
8 with DSpark, one server, 6 reloads in a row: no edit; an edit to the
K3 experts module; an edit to the latent tail (re-executes
`kimi_k3_comm`, the case that failed); an edit to the multimem
all-reduce; the edits reverted; no edit. Every reload succeeded and
GSM8K (first 20, greedy) stayed 20 out of 20. Decode step times after
reloads stayed within 0.35% of a fresh start at concurrency 1, 8 and 16,
which is within the run-to-run spread.
- The KV cache is allocated once and the torch allocator's cached memory
stays flat across reloads.
- `pre-commit run --all-files` passes.

Note: the K3 decode chain compiles its kernels once when it is prepared,
so an edit to a `k3_decode` kernel still needs a restart to take effect;
kernels reached through module caches or the kernel registry pick up
edits on reload.

---------

Signed-off-by: Nicolas Perrin <nperrin.ai@gmail.com>
2026-12-01 13:23:24 -05:00
Nicolas Perrin 2f509da68d fix(k3.1): size the KVP top-k merge without Iris off gfx950 (#4065)
## Summary

Since [#3976](https://github.com/lightseekorg/tokenspeed/pull/3976),
Kimi K3.1 with KVP and DCP cannot start on NVIDIA: communication
preparation calls
`KimiK31SparseMLAAttention.kvp_decode_topk_merge_capacity`, which
imports the Iris top-k merge
(`tokenspeed_kernel.ops.communication._iris.kimi_k3.topk_merge`) before
checking the platform. Iris is packaged for ROCm only, so every rank
fails with `ModuleNotFoundError: No module named 'iris'`.

The method now returns zero rows off gfx950 before the import, as
`kvp_decode_exchange_bytes` already does. Only gfx950 merges the decode
top-k through Iris.

## Tests

-
`test_kimi_k31.py::test_the_kvp_decode_topk_merge_holds_no_rows_off_gfx950`
(new): passes with the fix, fails with `ModuleNotFoundError` without it.
- Kimi K3.1 Pro (two nodes with four NVIDIA GPUs each, TP8 with both KVP
and DCP set to 8, DSpark) starts and serves with the fix; GSM8K (first
20 questions, greedy) 20 out of 20.
- `pre-commit run --all-files` passes.

---------

Signed-off-by: Nicolas Perrin <nperrin.ai@gmail.com>
2026-12-01 13:22:30 -05:00
Hanyu Weiandlongcat-ia-team f80f6d811e fix: support packed MXFP8 DSA rows with query context parallelism (#4059)
## Summary
Enable packed MXFP8 DSA KV caches under query context parallelism and
correct history-gather workspace sizing.

- Accept uint8 packed cache storage when MXFP8 is enabled and no
additional cache quantization is configured.
- Size history buffers using the physical row width, including payload,
group-32 scales, and alignment padding.
- Keep logical attention dimensions unchanged.
- Preserve existing QCP/KVP topology and prefill-role restrictions.

For example, a 576-channel packed row occupies 608 bytes. Using only the
logical width under-allocates the history workspace.

This change is independent of weight quantization and contains no W8A16
GEMM changes.

## Validation
- 17 focused DSA configuration and workspace tests passed.
- Covers packed row sizes, history-buffer budgets, and invalid
cache-format combinations.
- `pre-commit run --all-files` passed.

---------

Signed-off-by: Patirck <151747616+Patirck@users.noreply.github.com>
Co-authored-by: longcat-ia-team <312376714+longcat-ia-team@users.noreply.github.com>
2026-12-01 23:50:29 +08:00
Guoyuan Lin 0511cbef7b feat(engine): enforce a request's thinking_budget, also with json_schema (#3999)
## Motivation

A request's `thinking_budget` was parsed on the wire and in
`SamplingParams` but nothing read it, so a reasoning model kept thinking
for as long as it liked. A budget bounds the reasoning block, not the
output: once the block holds that many tokens it must close, and the
answer then follows normally. `max_new_tokens` ends the request instead.

## Changes

- `ts-grammar`: `Matcher` becomes `Grammar | Thinking`. The thinking
matcher counts the tokens inside the block and, once the budget is
spent, lets only the closing marker through the bitmask. The closer is
an ordinary sampled token (nothing is rewritten), so speculative verify,
the accepted frontier and the token history see no special case. It is
latched by the closer, so a model that closes early is not limited
afterwards, and also by a token that implicitly ends the block (DeepSeek
V4.1's tool-block opener, the same token reasoning usage stops counting
at), which is never forced. It walks a draft tree through the same
`traverse_draft_tree` path as a guarded grammar.
- A budget applies only when the prompt ends inside an open block (the
last marker in the prompt is the opener; one predicate now serves the
schema deferral, the budget and reasoning usage). Any other prompt, or a
parser without single-token markers, leaves the request alone.
- The block's markers come from `--reasoning-parser`; there is no extra
launch flag. The budget rides the grammar bitmask, so it needs
`--grammar-backend xgrammar`, set explicitly; with `none` a budget on an
open block is refused.
- `thinking_budget` with `json_schema`: the structural tag that makes
the schema wait for the reasoning block now also holds the block to the
budget, `any_tokens(exclude=[closer], max_tokens=N)` ended by the closer
as one token. Once the budget is spent only the closer is allowed. A
block ended by the closer's text instead would still allow `<` and `</`,
so the closer could take several tokens. The budget and the schema are
one grammar, so no second matcher is attached. Each distinct budget
value compiles and caches its own grammar. The host checks that a
reasoning grammar has this bounded tag exactly when it has block
markers.
- An admission holds at most one `Constraint`: a grammar (which carries
a merged budget) or a thinking budget with no grammar.
- Refused as the request's error, each with its own message: a negative
budget; a budget with `regex`, `ebnf` or `structural_tag`, or with a
json_object response or a schema that is not valid JSON (these constrain
the reply from its first token, the block included).
- `docs/configuration/server.md` documents the behavior and the
refusals.

## Tests

- `ts-grammar`: the budget matcher (spent, zero, early closer latches,
implicit closer latches but is never forced, rollback, draft chain,
early closer inside a draft chain, rejected draft closer) and the same
cases through xgrammar's structural tag on a toy vocabulary.
- `ts-control`: admission (when a budget binds, the merge into the
`json_schema` tag, every refusal, the implicit closer, markers that are
not single tokens, `--grammar-backend none`) and a two-rank serving test
that closes the block through the mask at pipeline depths 0 and 1.
- Python, now registered for CI: every parser's bounded tag driven token
by token (spent budget leaves only the closer, budget 0 and 1, the gap
some parsers require after the closer, an answer longer than the
budget).

<!-- Headings and layout are optional. Include change context and
validation
(checks performed or planned, or why testing was not run or is not
applicable)
anywhere in the description. -->

## Summary

<!-- What changed and why? -->

## Test Plan

<!-- How was this validated? -->

---------

Signed-off-by: linguoyuan <linguoyuan@meituan.com>
2026-12-01 22:41:53 +08:00
Yuxuan Sun 08dd6883f1 feat(npu): support V4.1 QCP and preserve is_dspark on Ascend (#4061)
Allow DeepSeek V4.1 QCP selection on NPU devices and preserve the model
profile's is_dspark flag in _resolve_attn_side.

<!-- Headings and layout are optional. Include change context and
validation
(checks performed or planned, or why testing was not run or is not
applicable)
anywhere in the description. -->

## Summary

<!-- What changed and why? -->

## Test Plan

<!-- How was this validated? -->

Signed-off-by: snowdusky <snowdusky@gmail.com>
2026-12-01 22:23:47 +08:00
WangBoandlongcat-ia-team 1166ca7862 feat(dwdp): support RL online weight updates and sleep/wake on CUDA (#4047)
## Summary

Extend CUDA DWDP (`CudaPeerWeightStore`) with in-place online weight
updates (Mooncake SDK and disk), co-located RL sleep and wake through
`--enable-memory-saver` (`cpu_backup` and `discard`), and `--load-format
dummy` startup, building on the lifecycle protocol introduced in
[#3876](https://github.com/lightseekorg/tokenspeed/pull/3876).

CUDA DWDP remains prefill-only (`--disaggregation-mode prefill`) and
continues to reject `update_weights_from_distributed`.

### Key Changes
1. **CUDA Peer Weight Store RL Lifecycle**
(`tokenspeed-kernel/python/tokenspeed_kernel/thirdparty/cuda/dwdp/store.py`,
`tokenspeed-kernel/python/tokenspeed_kernel/ops/communication/_cuda/peer_copy.{cu,py}`):
- Release and remap CUDA VMM physical allocations while preserving fixed
VA reservations and finalized composite full-expert view metadata
(`data_ptr`, `shape`, `stride`), using the existing `vmm.unmap` and
`vmm.release_handle` bindings.
- Implement `owned_weights`, `prepare_weight_update`, `refresh_weights`,
`release_storage(backup=...)`, and `resume_storage(backup=...)` on
`CudaPeerWeightStore`.
- Quiesce local reader and async peer-copy streams across the storage
group before modifying owned buffers or unmapping physical handles,
invalidate staging slots, re-export peer handles (`fabric` and
`posix_fd`) on resume, and refresh boundary intervals and replicated
metadata after barrier agreement.
- Reset `_flags.values` and per-slot sequence counters (`_Slot`) during
`resume_storage` so `cuStreamWaitValue64` remains consistent when
memory-saver `discard` zeroes the weights region.
2. **Runtime Guards and Design Doc**
(`python/tokenspeed/runtime/execution/model_runner.py`,
`python/tokenspeed/runtime/utils/server_args.py`):
- Remove the non-NPU immutability blocks in
`ModelRunner.update_weights_from_mooncake` and
`ModelRunner.update_weights_from_disk`, and allow
`--enable-memory-saver` (`cpu_backup` and `discard`) and `--load-format
dummy` for CUDA DWDP prefill workers.
- Add `MoEPeerWeights.enable_owned_updates()` and require peer models to
declare an owned-shard writer during request admission and before
opening a weight-update session. `DeviceHandle.check_weight_update()`
refuses ineligible requests before `WeightMemoryState.begin_update()`.
The in-tree K3 path does not opt in, so its Mooncake and disk updates
remain refused, and `discard` remains rejected at startup.
- Update `docs/design/distributed-weights.md` to reflect CUDA RL
lifecycle support while keeping decode and aggregated eager roles
NPU-only.
3. **Tests** (`tokenspeed-kernel/test/nvidia/test_cuda_peer_weights.py`,
`test/runtime/layers/test_moe_peer_weights.py`,
`test/runtime/test_dwdp_mapping.py`,
`test/runtime/test_update_weights_from_disk.py`,
`test/runtime/test_update_weights_from_mooncake.py`):
- Add CUDA multi-GPU tests for `prepare_weight_update` and
`refresh_weights` (covering unaligned page-edge bytes and replicated
tensors) and `release_storage` and `resume_storage` (`backup=True` and
`backup=False`, including prior acquire and release traffic and
discard-style `_flags` clearing).
- Update `test_dwdp_mapping.py` with CLI coverage for CUDA DWDP `dummy`,
`cpu_backup`, and `discard`, and update
`test_update_weights_from_disk.py` to verify that weight sharing alone
does not block non-peer models.
- Add admission coverage for a peer owner without
`enable_owned_updates()`: `check_weight_update` and `update_weights`
refuse before `begin_update`, leaving `WeightMemoryState` usable. Also
cover refusal by `weight_update_session` and direct
`prepare_weight_update` calls before peer storage is quiesced.

## Verification
- `pre-commit run --all-files`: passed.
- `pytest test/runtime/layers/test_moe_peer_weights.py`: 8 passed.
- `pytest tokenspeed-kernel/test/nvidia/test_cuda_peer_fds.py`: 10
passed.
- `torchrun --nproc-per-node=2 -m pytest
tokenspeed-kernel/test/nvidia/test_cuda_peer_weights.py`: 10 passed, 10
skipped (`fabric` skipped where IMEX is unavailable).
- `torchrun --nproc-per-node=8 -m pytest
tokenspeed-kernel/test/nvidia/test_cuda_peer_weights.py -k
"release_and_resume or online_weight_update"`: 3 passed, 3 skipped.
- `test/runtime/test_dwdp_mapping.py` and
`test/runtime/test_update_weights_from_disk.py`: pending GitHub CI
verification.

Co-authored-by: longcat-ia-team
<312376714+longcat-ia-team@users.noreply.github.com>

---------

Signed-off-by: wangbo981016 <wangbo981016@gmail.com>
Co-authored-by: longcat-ia-team <312376714+longcat-ia-team@users.noreply.github.com>
2026-12-01 22:07:41 +08:00
Zhewen Yu bad20df02b perf(k3.1): gather the KVP8 decode query and fuse the value tail on gfx950 (#3977)
Stacked on #3976.

## Summary

Kimi-K3.1 decode with KVP8 (TP8, DCP8) on gfx950 now runs the query side
and the value side of the DSA decode as one cross-rank launch each.

- **Value tail.** Each head's owner pulled the eight ranks' latent
partials, merged them, then projected through `w_vc` with the output
gate. `gluon_mla_dcp_value_gfx950` does it in one launch: every rank
projects its partials through W_UV and pushes the values to each head's
owner, which merges them and applies the gate. Device-side flags make it
graph-replay safe.
- **Fused query gather.** The old path projected Q_B and absorbed W_UK
locally, then carried the FP8 query with the score gather.
`gluon_dsa_query_gather_gfx950` projects normalized rows through packed
Q_B, pushes the projected blocks, absorbs every rank's heads through
replicated W_UK and writes the latent cache entries. It serves every
nonempty row in the documented six-row, 80-request graph ladder through
480 rows. Unsupported configurations retain the earlier
query-as-score-gather-rider path.
- **Numerics.** The value tail projects before merging, so it is not
bit-identical to the current path: within 2^-6 of the output's maximum
against it, and 2^-7 against the FP32 reference. The query gather sums
its projection in a different K order; at least 90% of query bytes match
the old path and the rest sit one E4M3 step apart, while latent caches
match bit for bit.

Shapes and platforms outside these conditions keep the current path.

## Results

Complete query plus owned-top-k communication boundary on eight MI355X
ranks, graph replay, slowest rank. Rows through 48 use the existing
gathered selection; rows from 192 use #3976's gather-merge.

| Rows | Query as rider | Fused query gather |
|---:|---:|---:|
| 6 | 35.9 µs | 32.4 µs |
| 24 | 44.0 µs | 38.4 µs |
| 48 | 51.5 µs | 48.2 µs |
| 192 | 71.4 µs | 54.2 µs |
| 288 | 105.5 µs | 84.5 µs |
| 336 | 113.8 µs | 94.9 µs |
| 384 | 122.6 µs | 103.5 µs |
| 432 | 133.7 µs | 111.1 µs |
| 480 | 144.8 µs | 119.6 µs |

At 480 rows the fused path also takes 120.6 µs against 145.4 µs with
wide scores, and 205.3 µs against 218.9 µs when one rank holds most of
the top-k.

## Test Plan

On gfx950:

- [x] `test_gluon_dcp_value_gfx950.py` on eight ranks: the value tail
against the FP32 reference and the current merge-then-project path
(records and partials, gated and not, eager and replayed), and its
compile check for every rank.
- [x] `test_dcp_query_gather_fused.py`: every fused launch tier through
480 rows against the gathered production BMM reference, direct
latent-cache writes, four back-to-back calls, mutated graph replay with
a slow rank, concurrent independent states and alternating grid sizes.
- [x] `test_kimi_k31.py`: 143 passed, 13 skipped after removing the
intermediate Triton path.
- [x] `test_dsa_dcp_owned_decode_topk.py`: all six TP2/4/8 cases pass,
including the pre-existing query rider fallback and graph replay.
- [x] The whole stack's tests and accuracy checks in #3980.
- Not run on NVIDIA; the new paths are gfx950 only and unsupported
configurations retain their existing implementation.

Signed-off-by: Zhewen Yu <zhewenyu@amd.com>
2026-12-01 14:00:54 +00:00
Zhewen Yu 3ecd93564a perf(k3.1): merge the KVP decode top-k across ranks and speed up DCP records on gfx950 (#3976)
## Summary

Kimi-K3.1 decode with KVP8 (TP8, DCP8) on gfx950 now selects each rank's
owned top-k in one cross-rank launch, scores verify rows on a smaller
grid and writes the DCP attention records faster. It also fixes FP8
cache keys stored past 2 GiB reading as zeros. Apart from that fix, only
the new records row kernel changes results, by rounding.

- **Top-k gather-merge.** Each KVP rank all-gathered every rank's
candidate scores, and the decode query in a second exchange, before
picking its owned share. `gluon_dsa_topk_gather_merge_gfx950` does both
in one launch over the Iris heap: ranks push a per-row header and only
the keys ahead of their cut, which usually settle the threshold;
otherwise they exchange whole rows. The selection matches
`dsa_select_owned_candidates` bit for bit. K3.1 uses it from 48 rows.
- **Indexer verify grid.** The MXFP4 owned-page scorer launched one
program per 256-key chunk for verify groups, and on wide page lists most
found no live keys. Groups now take a power-of-two number of programs
per request, about two per CU in all. Scores are unchanged.
- **DCP decode records.** The dense core vectorizes its record stores
and, with FP8 inputs, stages the next tile's indices in LDS, with
unchanged results. From 64 rows,
`gluon_dsa_decode_dcp_records_row_gfx950` attends each row in its own
programs and writes its record directly instead of splitting keys and
reducing partials. It serves FP8 queries and caches with 96 heads and
rounds its FP8 probabilities differently from the dense core.
- **Fix: FP8 cache keys past 2 GiB.** The FP8 sparse attention kernels
addressed cache keys with int32 byte offsets, so keys stored past 2^31
bytes read as zeros, and long runs silently lost context once the block
pool reached high block ids. Keys are now read through uint32 offsets,
or 64-bit pointers for caches over 4 GiB, at the same speed.

Shapes and platforms outside these conditions keep the current path.

## Results

Owned top-k selection on eight MI355X ranks, graph replay, slowest rank,
main's gathered selection (scores and query) against the gather-merge
carrying the query:

| Rows | Before | After |
|---:|---:|---:|
| 48 | 40.0 µs | 25.9 µs |
| 96 | 62.3 µs | 35.6 µs |
| 144 | 86.6 µs | 44.5 µs |
| 192 | 107.3 µs | 53.1 µs |
| 240 | 132.1 µs | 64.0 µs |
| 288 | 172.8 µs | 85.4 µs |

On the scores alone the gather-merge is 1.95–3.5× faster with uniform
and wide score distributions and 1.13–1.29× with skewed ones
(`benchmarks/amd/gfx950/kimi_k3/topk_gather_merge_bench.py`).

DCP decode records for 8 TP8 ranks with 256 live keys per row:

| Rows | Before | After |
|---:|---:|---:|
| 8 | 13.4 µs | 11.7 µs |
| 48 | 26.3 µs | 23.3 µs |
| 96 | 32.8 µs | 23.1 µs |
| 144 | 45.0 µs | 27.2 µs |
| 192 | 52.0 µs | 33.5 µs |
| 288 | 70.5 µs | 39.4 µs |

Rows mixing lengths up to 1,000 keys run up to 10% slower than the dense
core at 64–144 rows, since one program walks each row's keys.

Indexer verify scoring for K3.1 KVP8 (6 rows per request, 16K owned
keys): 29.7 → 13.0 µs at 16 requests, 39.8 → 19.6 µs at 24 and 63.9 →
33.8 µs at 48.

## Test Plan

On gfx950:

- [x] `test_gluon_dsa_topk_gather_merge.py`: the gather-merge against
`dsa_select_owned_candidates` over the gathered scores, with eight ranks
emulated on one GPU and on eight GPUs with a slow rank, back to back.
- [x] `test_dsa_dcp_owned_decode_topk.py`: the owned decode top-k
through the gather-merge at 2 and 8 ranks, including graph replay with
mutated metadata and riders.
- [x] `test_gluon_dsa_decode_dcp_records.py`: the records row kernel
against the FP32 reference and its compile-once check, and the dense
core bit for bit against the dispatched decode.
- [x] `test_dcp_exchange_nccl.py`: the leaf's records arm held to FP32
attention where the row kernel serves it (8 ranks, 128 requests), and
bit for bit to the token-major decode where the dense core does.
- [x] `test_gluon_dsa_mxfp4_index_k.py`: verify groups score exactly as
one program per chunk over any split. `test_gluon_dsa_amd.py`: FP8
decode, prefill and records read cache rows past 2 GiB.
- [x] 42 kernel, Iris and runtime test files on 8x MI355X. One
`test_comm_ops.py` case and one `test_iris_moe_tail.py` case fail on
main as well.
- [x] The whole stack's tests and accuracy checks in #3980.
- Not run on NVIDIA; these paths are gfx950 only, and the gather-merge
needs the Iris backend.

Signed-off-by: Zhewen Yu <zhewenyu@amd.com>
2026-12-01 14:00:54 +00:00
Zhigang Zhou 7e246afa6c fix(epd): recycle receive slots per item and gate the encode send ring (#3948)
## Summary

This change fixes a liveness failure in EPD (encode/prefill
disaggregation) and, in doing so, replaces the two independent resource
pools with one coordinated flow-control protocol. A prefill rank now
hands each multimodal item to the data plane as soon as its rows land
and gives its receive slot back when the copy out finishes, so the pool
bounds items in flight rather than a request's item count. On the encode
side, an item takes a send ring slot only once every prefill rank of its
room has asked for its destination, and the encode ranks agree those
admissions in every round. The two pools can therefore no longer wait on
each other in any order, and a request that outnumbers the pool
progresses instead of hanging.

The change also unifies the failure paths (timeout, cancellation, write
retirement), extends the round exchange's agreement to the admissions
that can no longer be written, and hardens the receive path's wire
counts and token ranges.

## Problem

An EPD prefill rank leased one receive slot per multimodal item but
released it only once the whole request's embeddings had landed and been
copied out. A request carrying more image items than the receive pool
has slots (observed: 17-32 items against 16 slots) therefore leased
every slot, could never reach the landed state, and hung until
`TOKENSPEED_DISAGGREGATION_WAITING_TIMEOUT`; the failed attempt then
quarantined those slots for ten seconds, producing a long-tail loop that
also delayed unrelated requests.

## Key design

- Receive slot ownership: `lease -> hand over -> awaiting -> release`
per item; the slot returns after the copy out, and a failed transfer
keeps it until retirement is confirmed.
- Encode send slot ownership: a slot is leased only for an item every
encode rank reports `Readiness::Ready`; the group agrees the ready set
by intersection and the admissions that can no longer be written by
union in the round exchange. Timed-out admissions are failed, cancelled
ones are only returned, and neither is encoded or takes a slot;
duplicates never touch the room they do not own.
- One ordering: the prefill ranks' slot leases follow the replica-agreed
admission order, and the encode batch follows the same admission order
among the ready items.

## Changes

### Receive side (prefill)

This change hands each item to the data plane as soon as its rows land
and gives its slot back as soon as the copy out finished, so the pool
bounds the items in flight instead of a request's item count. The
request-level admission barrier is unchanged: a request is admitted only
once every rank of the replica reports all its items landed. A landed
item's rows are published onto it before any forward of the request, and
a failed request reports its item's reason or the expired wait.

Receiving ranks publish in every round in which any receiving rank
landed an item, with an empty payload on the ranks that landed nothing:
the task also settles the last forward's pending draft round, and that
settlement must stay at the same point on every receiving rank. The
round's existing code reduce carries the "some rank landed" vote, so all
receiving ranks call or skip together; while embeddings are the only
outstanding work, a round waits as an idle one does instead of queueing
empty operations. The same reduce votes whether any receiving rank still
owes a handed slot's copy out; while one does, the round polls instead
of waiting as idle, so the released slot reaches the next item promptly
on every rank.

The branch is rebased onto `main`'s lease generation and remote write
retirement protocol (#3961). Each receive lease carries the receiver
incarnation, a monotonic generation and the serving encode rank;
statuses, cancels and retirement acknowledgements are filtered by them,
so a delayed or replayed message cannot settle a different lease. A
failed published slot stays leased until its encode rank confirms that
the write retired: a failure status is a request outcome, never a write
fence. A slot that was never published is released at once.

A failed or timed-out request cancels its leases at the encode ranks.
Cancels retry from the status thread over the address each room already
resolved, so elapsed time never releases a slot: a dead encode rank
keeps that slot (and the memory release waiting on it) until it answers,
and only the stall report fires. Duplicate rooms are refused for the
whole request, and a room whose item was handed over stays refused until
its slot returns, so a retry never waits on a room the encode rank
closed. An empty shard, which hands its room over without leasing a
slot, keeps it refused until its request settles.

### Encode side (encoder)

An item is handed over to the sender only once every prefill rank of its
room has asked for its destination; a room that can no longer be written
is dropped instead. Each encode rank reports the queued admissions it
can hand over and the ones it can no longer write (its room timed out
waiting for the prefill ranks, or they cancelled it); the round's
exchange agrees on the intersection of the first and the union of the
second, so every rank batches and drops the same items. A handed-over
item therefore never holds a send slot while the prefill ranks have no
receive slot to give it, and an item whose prefill ranks never asked
past the bootstrap timeout is failed and returned to the data plane
without taking a send slot at all. The expiry runs from admission: a
destination ask that arrived before it (it can create the room entry)
does not spend the item's budget. An item whose turn in the receive pool
comes later than the bootstrap timeout still expires while its prefill
rank is inside its own, longer waiting timeout, so the encode-side
timeout must be raised together with the prefill's. A cancelled room is
never encoded either: the loop concludes it and returns its admission to
the data plane instead of running the tower for rows `send` would only
discard. A duplicate admission whose room is already tombstoned is
dropped the same way, before the duplicate shortcut can mark it ready. A
request duplicated for a room another admission still holds is dropped
the same way but only gives its data back: the room belongs to the
admission that began it. This holds whatever order each side processes
its items in (the prefill grammar queue stages an admission later than
the encode intake sees it). The tower batches what the prefill ranks can
accept at a time instead of filling the send ring ahead of them.

An encode rank drops a chunk that is not being written and frees its
send slot at once instead of parking it until the bootstrap timeout; a
write already started finishes, and its retirement acknowledgement
releases the receiver's slot.

### Rebuild

The row-shard rebuild is one NCCL broadcast per item per rank and must
be issued in the same order on every attention-TP rank. Copies are
rank-local and now happen as items land, so the rebuild moved out of the
copy into a new `epd_rebuild` task issued at the replica-agreed
admission, requests in admission order and items in index order. A
deployment without row sharding queues no rebuild at all; with sharding,
every rank of the group joins, even one whose shard of an image is
empty.

### Hardening

The receive path's byte and row counts (token ranges, peer-supplied row
spans, the rows x width x element product, and the encode loop's batch
token budget) use checked arithmetic end to end and fail with a reason
instead of wrapping. Token ranges must cover at least one row of the
prompt: a reversed range such as `(5, 4)`, a negative one such as `(-1,
2)`, and one whose count overflows are all refused on both the prefill
and the encode side instead of being admitted.

### Review and hardening

| area | what the review changed |
|---|---|
| Liveness and cross-rank agreement | Destination-gated hand-over, with
the round exchange agreeing the ready set by intersection and the
unwritable set by union; admission-order batching so a cache hit cannot
take the only send slot; a duplicate follows its room's readiness, and a
terminal or reclaimed room drops it. An end-to-end test over the real
loop, sender and one-slot receiver pins the original circular wait. |
| Slot and room ownership | Per-item release with a retirement fence; an
empty shard keeps its handed room until the request settles; a cancelled
room is concluded (`input_pending` cleared) instead of leaking; a
replica-wide pending-copy vote keeps the frontend owner from idling
while a peer owes a copy out. |
| Wire and validation | Full-range u64 room ids on destination, cancel
and reply; checked row and byte counts; reversed, negative and
overflowing token ranges refused on both the ingress and the encode
side, and ranges past the prompt refused at ingress (the encoder has no
prompt). |
| Docs, tests and data plane | The encode-side send-slot rule, tombstone
lifetime and expiry anchors in `docs/design/event-loop.md`;
deterministic retirement assertions; the rebuild marker keyed to the
encoded tensor; EPD data-plane lookups name the request instead of
raising a bare lookup error. |

Pre-existing bugs found on the way are fixed with the rest: a high-bit
room id was dropped by the transfer wire parser, and a cancelled room
the loop dropped was never concluded.

## Invariants

| invariant | enforced by | tests |
|---|---|---|
| a request is admitted on every rank in the same round | replica MIN of
receive states (`event_loop.rs`) | serving/live EPD tests |
| a receive slot is released only after its copy finished |
`epd_publish`/`epd_released` + `awaiting` | `live_tests` per-item
recycling |
| a failed write keeps its slot until retirement | lease generation +
retirement ack | `serving/test_epd_retirement.rs` |
| a send slot never waits on a receive slot | readiness gating +
expiry/cancel drops, no parking | encode unit tests, `live_tests`,
end-to-end pools test |
| encode ranks batch and drop the same admissions | exchange ready
intersection / unwritable union |
`a_send_waits_until_every_rank_sees_...`, `a_room_one_rank_timed_out...`
|
| a duplicate never fails a room it does not own | `begin` ownership +
`drop_queued` duplicate check |
`a_duplicate_admission_that_times_out...` |
| wire counts never wrap | checked folds, `validate_fanout`,
`receive_bytes` | ingress/encode/receiver tests |
| a room is a u64 on every hop | ingress, `TransferInfo`, `Reply` |
`a_transfer_request_round_trips` |

## Compatibility and risks

- E and P must run matching versions of the lease-aware wire protocol.
The encode ranks' round exchange now also carries the ready and the
unwritable admissions (timed out or cancelled), so the ranks of one
encode node must run the same version.
- `EmbeddingSender` gained `readiness` and `timed_out`, `Readiness`
gained `Cancelled` and `Concluded`, and `EmbeddingReceiver` gained
`shards` and `copies_pending` (in-tree crate; both implementations
updated). No configuration defaults or environment variables changed.
- The idle gate polls instead of waiting while a handed slot's copy out
is pending, and while a peer rank owes one; the wait's latency price is
documented in `docs/design/event-loop.md`.
- Throughput tradeoff: the vision tower now batches what the receive
pools can accept instead of filling the send ring ahead of them. This is
the price of never parking on a send slot.
- Residual assumption: the prefill ranks stage in the replica-agreed
admission order (grammar readiness itself is replica-MIN reduced). If it
were violated, the ready set stays empty and the stale timeout bounds
the failure; no circular wait.
- P3: `TOKENSPEED_EPD_ENCODE_RING_SLOTS=0` is not validated at startup
(pre-existing); with the expiry path it fails each item after one
bootstrap timeout instead of hanging.

## Follow-ups (not in this PR)

- **Room lifecycle as a state enum, and the round exchange carrying a
disposition.** `Room`'s `begun` / `input_pending` / `sending` /
`cancelled` / `concluded` flags predate this branch (`#3961`) and allow
illegal combinations; the unwritable set added here does not say whether
a room timed out or was cancelled, so each rank re-derives it from local
state. One follow-up should collapse the flags into an enum, carry the
disposition on the wire, and replace the unbounded tombstone set with a
bounded, generation-checked refusal.
- **Batch ordering.** With destination-gated hand-over, the
admission-order merge of the cache-hit and miss queues no longer
prevents the circular wait; a single ready queue would be simpler.
Measure before changing it.
- **Explicit rebuild manifest.** `EmbeddingPublisher.rebuild` records
rebuilt items in weakref state keyed by the encoded tensor; returning
the rebuilt set and passing it to the forward check is a data-flow
refactor.
- **Readiness snapshot.** `hand_over_states` takes the sender's lock
once per queued admission; a per-round snapshot would bound that cost
under back-pressure.
- **Cache-answer consistency for the tower batch.** The batch shape
still depends on the per-rank embedding cache's hit/miss answers
(pre-existing): a one-sided tower failure can make them diverge. A group
consensus check (or a loud failure) before the batch is formed would
close it.
- **Bounded admission metadata.** `tombstones`, `handed_rooms` and begun
rooms have no reclamation bound (pre-existing for the first two); a
long-lived encode node accumulates them.
- **Exchange allocation cap.** `exchange` pre-allocates a set from a
peer-supplied count; cap it by the part length so a corrupt round fails
as `Exchange` instead of allocating.
- **Idle gate with finished-but-unreaped requests.**
`outputs.num_running() != staged.len()` disables the idle wait while a
staged request is finished but not reaped; express it as "no running
work other than the staged ones".

## Rollout

- Deploy matching E and P versions together; no configuration changes
required.
- Watch the encoder transfer-failure counter (rendezvous timeouts are
now counted there) and the logical queue age snapshots; the receive
pool's slot count still bounds items in flight.

## Test Plan

- `cargo test --locked` (the CI command, engine workspace): exit 0; 71
test targets, 0 failed; `tokenspeed-control --lib` 376,
`tokenspeed-control --test serving` 141, `tokenspeed-pd --lib` 160.
- `cargo clippy -p tokenspeed-pd -p tokenspeed-control --all-targets
--locked -- -D warnings`, `cargo fmt --all --check`, `pre-commit run
--all-files`: clean.
- New end-to-end test
`an_open_destination_chooses_the_transfer_when_each_pool_has_one_slot`
runs the real `EncodeLoop` over a real `Sender` and a one-slot
`Receiver` with one send slot: the miss is admitted first, the cache hit
is staged first. It fails on `5bea960` with the reported `EPD embeddings
timed out after 10s` and passes here. The empty-shard refusal test was
verified red on the unfixed receiver.
- The Python changes (`epd_publish`/`epd_rebuild` request lookup, the
forward's chunk-item filter) were syntax-checked locally; this machine
has no torch, so `pytest test/runtime/test_epd_prefill_receive.py
test/runtime/test_rust_host.py` runs in CI.
- New tests cover negative-range refusals on both sides, range
validation for every item (handshake or not), a cancelled room's
duplicate on every rank and on one rank only, a waiting duplicate held
out of the batch, a reclaimed-room duplicate dropped after its owner
concludes, the real sender's `Concluded` readiness, the
ask-before-admission expiry race, and `copies_pending` around a release.
- A four-lineage review (GPT, GLM, DeepSeek, MiniMax) of the branch
produced the review-and-hardening rows above; the follow-up fixes were
re-reviewed to no P0/P1/P2.
- Merged with the current `origin/main` (`55c40a4df`) in a scratch
worktree: merge clean, no conflicts.
- GPU end-to-end (encoder/prefill/decode deployment) is not run locally;
the repository CI and GPU matrix own it.

---------

Signed-off-by: zhouzhigang04 <zhouzhigang04@meituan.com>
2026-12-01 21:55:04 +08:00
Hanyu Weiandlongcat-ia-team b3ac56f4e8 fix(runtime): clean up ranks when engine startup or launcher fails (#3790)
## Summary

Clean up TokenSpeed processes and resources when engine startup or the
launcher fails.

- Terminate already-started ranks if a later scheduler or encode rank
fails to start.
- Close processes and pipe descriptors when host startup or bootstrap
serialization fails.
- Enable parent-death cleanup for node-zero ranks, matching
follower-node behavior.

This prepares failed instances for clean replacement. Automatic restart
policies and request replay are outside this change.

## Test Plan

- 69 lifecycle regression tests passed, including 4 new failure-cleanup
tests.
- `pre-commit run --all-files` passed.
- GPU fault-injection integration checks confirmed failed-instance
replacement while a healthy sibling instance continued serving.

---------

Signed-off-by: Patirck <151747616+Patirck@users.noreply.github.com>
Co-authored-by: longcat-ia-team <312376714+longcat-ia-team@users.noreply.github.com>
2026-12-01 21:51:43 +08:00
zhuhaozhecool 1615504324 fix(runtime): avoid signal reentrancy deadlocks in headless launcher (#4048)
## Failure and fix

The headless launcher handles rank failures via `SIGUSR1`. The old
handler calls `threading.Event.set()`, which takes a non-reentrant lock.
If another `SIGUSR1` enters the handler on the same thread while that
lock is held, the inner call waits for the outer call to release it. The
outer call cannot resume, so the launcher never reaches its shutdown
deadline and the old rank can keep the rendezvous port bound.

Replace the event with a boolean. `SIGUSR1` still records a failed run,
and the existing TERM and forced cleanup paths can continue.

## Two-NPU before and after

Both versions ran the same two-rank TCPStore/HCCL workload on the same
device pair and rendezvous endpoint (`127.0.0.1:17919`). The test used
Python communication ranks and the actual headless launcher shutdown
path. The test injected nested `SIGUSR1` to exercise reentry. Rank 0
owned the TCPStore listener and had a second AllReduce outstanding
because its peer skipped that collective. The test used the default HCCL
timeout settings and the existing launcher grace period.

| Version | Time from fault signal | Port and restart |
| --- | --- | --- |
| Before: `threading.Event` | Still hung at **48.00 s**, when
observation ended | Rank 0 still listened. A fresh bind returned
`EADDRINUSE`. |
| After: boolean | Launcher exited with status 1 after **38.17 s** |
Both old ranks had exited and the listener was gone before driver
cleanup. A new TCPStore/HCCL group started on the same port and both
ranks completed AllReduce. |

After recording the baseline result, the test driver sent `SIGKILL`
separately to the stuck launcher and both surviving rank processes. The
baseline measurement is an observation cutoff. In the fixed run, rank 0
was still in native NPU synchronization after TERM. The launcher reached
its existing timeout and performed forced cleanup itself.

## Regression tests

- 22 tests passed across launcher supervision, startup process
ownership, and readiness pipes.
- The regression test delivers exactly two nested `SIGUSR1` signals
after the launcher has consumed every readiness message. The port-owning
rank exits normally after TERM, the launcher reports status 1, and a
second launcher binds the same port. Unexpected exceptions propagate and
fail the test.
- Negative controls confirmed that the old event-based handler deadlocks
in the nested `Event.set()` call and that an injected `RecursionError`
fails the test.
- Shutdown while `receive_ready_messages()` is still waiting is a
separate existing issue. This regression test exercises signal reentry
after readiness.
- `pre-commit run --all-files` passed.

Signed-off-by: zhuhaozhecool <zhuhaozhecool@163.com>
2026-12-01 20:29:59 +08:00
Chen Hongtao 7434765564 perf(attention): keep DeepSeek V4.1 mixed-batch outputs in FP8 (#3642)
## Summary

Stacked on https://github.com/lightseekorg/tokenspeed/pull/3599.

On supported Blackwell configurations, DeepSeek V4.1 already uses
FlashMLA’s fused FP8 output for pure prefill and pure decode. Mixed
batches fall back to a BF16 attention output and then apply inverse RoPE
and FP8 quantization before the output projection.

This change enables the fused path for mixed batches. Prefill and decode
copy their FP8 codes and packed scales into disjoint token rows of a
shared buffer. The layer then runs `wo_a` and `wo_b` over the complete
batch.

In a breakable prefill CUDA Graph, eager attention fills the live rows
of a fixed-address buffer and the next graph segment replays both
projections. Pure prefill and mixed batches can reuse the same capture.
Before projection, unused rows are cleared, including the entire buffer
on an idle DP rank.

## Test Plan

- Compared mixed attention with separate prefill and decode forwards.
Exercised graph replay across pure prefill, mixed, and idle steps with
both FP8 and BF16 `wo_b`, checking output rows, padding, and KV cache
contents.
- Ran all 1,319 **GSM8K** questions on 4× B300 with DP4 and EP4, 4-shot
greedy decoding, real DSpark verification, and the graph weak-reference
extension active on all ranks. The baseline scored **1,201 of 1,319
(91.05%)** and this change scored **1,203 of 1,319 (91.21%)**. Both runs
completed with zero request errors.

**AgentX** was measured against
https://github.com/lightseekorg/tokenspeed/pull/3599 at commit
https://github.com/lightseekorg/tokenspeed/commit/1bf7b83d4cbe4241fac3b32aee74d4a1277fe3f2
on 4× GB200 with DeepSeek-V4.1-Flash-1017, DP4 and EP4, concurrency 128,
hash session affinity, synthetic acceptance length 3.51, and a 20-minute
measurement window.

| Metric | Base | This PR | Change |
|---|---:|---:|---:|
| Output tokens per second per GPU | 1,466.78 | 1,496.19 | **+2.00%** |
| P90 time to first token | 6.866 s | 5.883 s | **−14.32%** |
| User tokens per second (1 / P90 full-response ITL) | 170.07 | 172.41 |
+1.38% |
| Prompt cache hit rate | 95.306% | 95.309% | +0.003 pp |

At the same 0.85 GPU memory utilization target, the graph memory budget
increased from **13.41 to 16.34 GiB per rank**, and KV capacity
decreased from **9,846 to 8,852 pages per rank**. Each arm completed one
measurement on a separate node with zero request errors. The baseline’s
first attempt hit a CUDA OOM during warmup and was rerun with identical
settings.

---------

Signed-off-by: chenht2022 <chenht2022@gmail.com>
2026-12-01 18:40:20 +08:00