Commit Graph
104 Commits
Author SHA1 Message Date
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
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
30a43c1152 feat(cache): support configurable chunked Host L2 registration (#4017)
## Summary

Add opt-in chunked CUDA registration for Host L2 buffers.
`--kvstore-host-register-chunk-size` limits each registration call in
GiB; `0` retains the existing PyTorch allocator.
`--kvstore-host-register-serialize` optionally serializes registration
across local workers using validated private per-user lock files.

The allocation remains contiguous and page-aligned, with registration
boundaries aligned to Host LCM blocks. Budgeting uses the actual
page-rounded allocation. Tensor views retain the mapping, cleanup waits
for device work, and failed registration rolls back completed chunks.
Snapshot and slot-state pools keep their existing allocation policy.

This is the main-branch counterpart of #4016, including its lock-file
hardening fix.

## Test Plan

- `pre-commit run --all-files`: passed.
- Local filesystem and multiprocessing lock tests: 7 passed.
- Main-revision Linux/CUDA regression with matching kernel source: 127
tests and 24 subtests passed, 1 skipped. Covers registration, DMA and
mapped-host transfers, tensor-view lifetime, failure cleanup, memory
budgets, Host storage, and lock exclusion. The initially installed
kernel lacked a current-main API; rerunning with the matching source
passed.

## Previous startup measurements

The same registration implementation was measured on the release-branch
counterpart with 8 H200 GPUs, one prefill and one decode instance (4
ranks each), real checkpoint loading, 128 GB Host L2 per prefill rank,
and decode L2 disabled. Each row is one startup, from concurrently
launching both instances until both WireDrivers return Ready;
scheduling, image setup, and imports before the measured entry point are
excluded. Checkpoint-cache release and registration serialization were
disabled.

| Host L2 allocation | Startup to Ready |
| --- | ---: |
| Existing PyTorch allocator, 8 page-touch tasks | 99.10 s |
| 1 GiB registration chunks | 110.76 s |
| 8 GiB registration chunks | 110.78 s |

Chunking bounds registration size and avoids pinned-allocator bucket
rounding; these measurements do not show a startup-speed improvement.
Startup and full inference benchmarks have not been rerun on this main
revision. The detailed measurements and earlier inference comparison are
recorded in #4016.

---------

Signed-off-by: lyzuu <349859374+lyzuu@users.noreply.github.com>
Co-authored-by: lyzuu <349859374+lyzuu@users.noreply.github.com>
Co-authored-by: longcat-ia-team <312376714+longcat-ia-team@users.noreply.github.com>
2026-12-01 16:29:05 +08:00
Chen Hongtao 5bb83ea374 perf(graph): enable DeepSeek V4.1 CED prefill graph replay under attention DP (#3599)
## Summary

DeepSeek V4.1’s context encoder processes every input token. Its decoder
retains a request-dependent subset, so two attention-DP ranks with the
same input length can need different decoder shapes. The baseline runs
these stages eagerly under attention DP because expert-parallel
collectives require all ranks to agree on the graph shape.

This PR enables staged CUDA graph replay for prefill rounds and mixed
prefill-and-decode rounds on the TP1, full-world DeepGEMM MegaMoE
layout.

- Select the encoder bucket from the maximum input count already
available in scheduler metadata. One Gloo `MAX` reduction per eligible
round collects the largest retained decoder row count and whether any
rank requires eager execution. Idle ranks contribute zero rows and
participate in the same collectives.
- Select encoder and decoder buckets independently. If the encoder
exceeds its largest capture, it can run eagerly and feed a captured
decoder. `--prefill-graph-decoder-capture-token-sizes` sets optional
decoder capacities in retained rows.
- Reuse MegaMoE’s live-row counts to exclude padding from expert
dispatch. Keep attention indexer scratch alive across the stage
boundaries and allow eligible shifted MegaMHC joins inside captured
segments.

## Test Plan

- Passed the four-rank Gloo bucket-selection test and the CUDA test for
an eager encoder feeding a captured decoder.
- Ran all 1,319 GSM8K questions on 4× B300 with DP4 and EP4, greedy
decoding, and real DSpark verification. The baseline scored **1,205 of
1,319 (91.36%)**. This change scored **1,204 of 1,319 (91.28%)**. Both
runs had zero request errors.

The GSM8K and AgentX results were collected before the rebase. Ran
AgentX on 4× GB200 with DeepSeek V4.1 Flash, DP4 and EP4, concurrency
128, and a 20-minute measurement window. Each arm ran once on a separate
node with identical hash session affinity and a synthetic acceptance
length of 3.51. The candidate log confirmed CED decoder graph replay.

| Metric | Baseline | This PR | Change |
|---|---:|---:|---:|
| Output tokens per second per GPU | 1,463.45 | 1,477.35 | +0.95% |
| P90 time to first token | 6.10 s | 5.96 s | −2.35% |
| User tokens per second (reciprocal of the P90 full-response ITL) |
158.48 | 168.63 | +6.41% |
| Prompt cache hit rate | 95.28% | 95.32% | +0.04 pp |

At the same 0.85 GPU memory utilization target, the CUDA graph reserve
grew from **9.59 to 14.43 GiB**, reducing KV capacity from **11,118 to
9,505 pages per rank**.

---------

Signed-off-by: Chen Hongtao <56470055+chenht2022@users.noreply.github.com>
2026-11-30 20:13:24 -08:00
Xiangyi ZhangandLightSeek Foundation 6b49389308 perf(kda): plan CuTe prefill once per forward (#3782)
## Summary

Plan the CuTe KDA prefill once per forward instead of once per layer, on
both the ordinary and the persistent route.

Every `cutedsl_kda` prefill launch starts with a single-CTA metadata
kernel that depends only on the batch's boundaries: FlashInfer's
`packed_metadata_kernel` on the ordinary route, `_persistent_kda_plan`
(task lists and a handoff-flag reset) on the persistent route.
Kimi-K3/K3.1 runs it in each of its 69 KDA layers.

- `build_kda_prefill_plan` fills both routes' schedules in one Triton
launch. The persistent handoff flags are allocated as `[layers,
workers]` and zeroed together in that launch, so no layer resets its own
flags.
- Each layer passes the plan and its own `plan_layer` row to
`kda_paged_prefill`; the ordinary launch skips FlashInfer's metadata
generation. The route test is main's shape test (heads divisible by 8,
two CTAs per (sequence, head) above FlashInfer's SM count), now
evaluated once in the plan (`plan.persistent`) so a launch never takes
the persistent route without its task lists; each launch still adds its
gate-dtype and `lower_bound` checks.
- The KDA backend builds the plan in `init_forward_metadata` when the
selected prefill kernel declares the `prefill_plan` trait
(`kda_prefill_takes_plan`). Capacity metadata keeps its plan and
refreshes it in place before replay (`refresh_kda_prefill_plan`), so a
replayed forward runs two plan launches: its live plan and the refresh.
- `plan=None` makes a call plan alone (standalone calls, the
prefix-state checkpoint scan).

Other KDA prefill solutions are unchanged. Outputs and states are
bitwise identical to main.

## Performance

GB300, 69 `cutedsl_kda` launches over one 8,192-token batch with
runtime-shaped strided inputs. Median summed GPU kernel time over 21
warmed eager samples with L2 flushed (Nsight Systems). 12 heads is
Kimi-K3.1 at TP8 (ordinary route); 96 heads takes the persistent route
from 4 requests on.

| Heads | Requests | Metadata kernels | Metadata time | Total kernel
time |
|---:|---:|---:|---:|---:|
| 12 | 1 | 69 → 1 | 107 → 14 µs | 18.76 → 18.71 ms (−0.3%) |
| 12 | 16 | 69 → 1 | 264 → 14 µs | 5.64 → 5.40 ms (−4.3%) |
| 12 | 64 | 69 → 1 | 872 → 14 µs | 7.53 → 6.69 ms (−11.1%) |
| 96 | 1 | 69 → 1 | 140 → 16 µs | 25.98 → 25.88 ms (−0.4%) |
| 96 | 16 | 69 → 1 | 1,145 → 35 µs | 21.68 → 20.55 ms (−5.2%) |
| 96 | 64 | 69 → 1 | 4,657 → 85 µs | 30.98 → 26.44 ms (−14.7%) |

Scan time is unchanged; the saving grows with heads per rank and
requests per batch.

End to end, on the Kimi-K3.1 recipe at TP8 (2×4 GB300, 12 heads per
rank, ordinary route), prefill latency for 1×8,192 to 64×128 requests
stays within −0.8% to −0.1% of main, which is run-to-run noise. The
expected saving there is 0.1–0.9 ms per forward, 0.03–0.2% of a 325–400
ms prefill in which all 69 KDA scans take 5–18 ms. Greedy outputs match
main where main itself is deterministic (prompts up to 2,048 tokens).

## Test Plan

- [x] Plan contract: FlashInfer's longest-first order and chunk prefix;
no recompilation across batch shapes; only `prefill_plan` kernels get a
shared plan; non-128×128 state is rejected.
- [x] Capacity graph replay with new boundaries, two layers sharing a
plan refreshed in place, ordinary and persistent routes with handoffs:
bitwise equal to exact-shape scans.
- [x] Each layer's scan reads its own flag row (`plan_layer`).
- [x] Memory release/resume with a retained two-layer plan: 0 ordinary
allocator bytes, unchanged addresses, identical results.
- [x] GB300: KDA kernel tests (134 passed); runtime KDA, Nemotron-H,
KDA/GDN/Mamba2 prefill-graph and memory-saver tests (245 passed).
- [x] `pre-commit run --all-files`.
- [x] Kimi-K3.1 end-to-end prefill latency and greedy outputs against
main.

---------

Signed-off-by: Xiangyi Zhang <xiangyiz@nvidia.com>
Co-authored-by: LightSeek Foundation <243258330+lightseek-bot@users.noreply.github.com>
2026-12-01 10:48:43 +08:00
Nicolas Perrin 1769eedaff perf(kernel): run Kimi K3.1's MXFP4 MoE, KDA and all-reduce fusion kernels on SM107 (#4035)
## Summary

- On main, Kimi K3.1 Pro at TP8 cannot start on GPUs with compute
capability 10.7: the K3 MoE tail's fused all-reduce and RMSNorm rejects
that capability, and `--moe-backend flashinfer_trtllm` finds no MXFP4
SiTU kernel registered past SM103.
- This PR enables the four kernel groups K3.1 uses on this path: the
TRT-LLM-Gen MXFP4 SiTU MoE, routed all-reduce and RMSNorm fusion, CuTe
DSL KDA prefill and verify kernels, and one-hop LL all-gather and
all-to-all exchange.
- On compute capability 10.7, the fusion routes every M above 32 to
FlashInfer's BT protocol. BT measured faster than the GB300 HT presets
at every measured M above 1024, covering 1025 to 8192 rows at TP4 and
TP8.
- The author reports that two nodes with four compute capability 10.7
GPUs each, running TP8, DCP 8 and DSpark, deliver decode steps 1.65 to
1.86 times faster and an 8,000-token prefill chunk 2.1 times faster than
the Marlin reference below. GSM8K accuracy is 100 out of 100 for both.

## Why the gates stopped at SM103, and why they can include compute
capability 10.7

The caps record where the kernels were validated on GB300, not a
hardware requirement:

- MXFP4 SiTU MoE: FlashInfer 0.7.6 provides a build for compute
capability 10.7 from its architecture-specific cubins. Its manifest has
the same 60 MXFP8 by MXFP4 SiTU tile configurations as SM100, with 106
cubins in each set; the sets differ only in architecture suffix,
scheduler tag and MMA instruction shape. The MXFP4 SwiGLU registrations
are not widened.
- KDA, LL exchange and the all-reduce fusion are CuTe DSL kernels that
compile for the current device.
- The author reports that the affected kernel tests pass on compute
capability 10.7 and that the full model serves with all four kernel
groups selected across two NVLink trays.

## Changes

- `flashinfer_trtllm_mxfp4_situ_moe_apply`: raise the maximum
architecture from 10.3 to 10.7.
- `flashinfer_allreduce_fusion` and `allreduce_fusion_support_error`:
admit compute capabilities 10.0 through 10.7. `allreduce_fusion_config`
builds routes from named targets: a `StaticProfile` keyed to compute
capability `(10, 7)` routes LL through 32 rows and BT above 32; other
architectures retain LL through 32, BT through 1024 and HT above 1024.
- KDA CuTe DSL support checks and registrations, including
`_SUPPORTED_ARCHES`, `cutedsl_kda_nvidia_paged_prefill`,
`cute_dsl_kda_recoverssm_verify`, `cute_dsl_kda_fused_paged_verify_step`
and `cute_dsl_kda_fused_paged_verify_window`: admit compute capability
10.7.
- `create_ll_exchange_state`, `cute_dsl_ll_all_gather`,
`cute_dsl_ll_all_gather_floats` and `cute_dsl_ll_all_to_all`: admit
compute capability 10.7. The paged-row all-gather registration is also
widened, although K3.1 does not use it on this path.
- Tests now gate on the kernel registry through `kernel_supported` or on
the kernel's own support predicate rather than duplicated architecture
lists. This covers the MXFP4 SiTU and SwiGLU registrations, LL exchange
kernel and runtime tests, and KDA prefill tests by backend. cuDNN KDA
remains limited to SM100 and SM103.
- `test_mxfp4_situ_flashinfer_trtllm.py`: compare SiTU against
`torch_moe_experts` using MXFP8 GEMM inputs from
`fake_quantize_block_scaled_mxfp8` and the FP32 fc1 output. Bound
relative L2 error to 1e-2 for the whole output and 1e-1 for each row,
and cover 1, 65, 513 and 8192 tokens. Inputs are scaled so the SiTU cap
binds, with about half the gates exceeding beta, so a SwiGLU result
fails. The old absolute tolerance of 8e-2 on outputs of about 2e-3 also
accepted zeros.
- `test_allreduce_fusion.py`: add a CPU test that pins the routes and
protocol workspaces resolved for SM100, SM103 and compute capability
10.7 at TP4, TP8 and TP16.
- `test_outer_graph_replays_lengths_pages_and_states`: use 128 KDA heads
instead of 96 in the many-head case so the reference and padded capture
select the same scan, as explained under Tests.
- `test_kda_cute_dsl_fused_verify_step.py`: place gate-projection inputs
on grids where every FP32 summation order is exact, round the exact
reference projection once, and require the recorded gates to match
exactly.
- Update the MoE, KDA and communication READMEs, `--kda-backend` help
and error text, unified-path regression notes, and Kimi K3.1 Pro NVIDIA
recipe.

Not changed: GEMM reduce-scatter, fused TP projections and the
block-scaled MoE routes, which K3.1 does not run on this path. MXFP4
SwiGLU also remains limited to SM100 and SM103.

## Numbers

The author reports measurements on two nodes with four compute
capability 10.7 GPUs each, using TP8, KVP 8, DCP 8 and a DSpark draft
with an eight-token verify window. The serving command is the recipe
command plus `--kv-parallel-size 8 --decode-context-parallel-size 8`.
Decode uses concurrent streams of approximately 6,000-token prompts at
temperature 0; step time is the time between streamed chunks over a
15-second window.

Main cannot start this model at TP8 on compute capability 10.7, so the
reference runs `--moe-backend marlin` with the fused MoE tail bypassed
by a local patch that is not part of this PR.

| Concurrency | Marlin reference, milliseconds per step | This PR,
milliseconds per step | Speedup | Reference tokens per step | PR tokens
per step |
|---:|---:|---:|---:|---:|---:|
| 1 | 16.4 | 8.8 | 1.86x | 2.58 | 2.42 |
| 16 | 42.6 | 25.9 | 1.65x | 2.90 | 2.89 |
| 64 | 80.7 | 48.2 | 1.67x | 2.87 | 2.94 |

- GSM8K, first 100 test questions, greedy: Marlin reference 100 out of
100; this PR 100 out of 100.
- One 8,113-token prefill chunk: the forward takes 297 milliseconds,
including 279 milliseconds of busy GPU time, and the request takes 0.30
seconds end to end. The Marlin reference takes 618 milliseconds,
including 597 milliseconds busy, and 0.60 seconds end to end.

## Tests

The author reports the following validation on compute capability 10.7
using one tray of four GPUs:

- `test_mxfp4_situ_flashinfer_trtllm.py`: 14 passed, covering all SiTU
tests from 1 to 8192 tokens; the eight SwiGLU tests skip because that
kernel remains limited to SM100 and SM103. The strengthened comparison
rejects zeros, a SwiGLU-activated output, output scaled by 10 or 1.05,
negated output, row-shuffled output and one zeroed row. The kernel's
relative L2 error is 2.1e-3 to 2.6e-3.
- KDA tests in `test_kda_cute_dsl_fused_verify_step.py`,
`test_kda_cute_dsl_fused_verify_window.py`,
`test_kda_cute_dsl_recoverssm_verify.py`,
`test_kda_retained_history.py`, `test_cutedsl_kda_prefill.py` and
`test_kda_prefill_native_layout.py`: 409 passed and 22 skipped, with the
skips being cuDNN prefill cases. The fused verify step's gates are
bit-identical to the split path's in all cases.
- `test_ll_exchange.py` with two and four ranks: 4 passed.
`test/runtime/distributed/test_small_exchange.py` with degrees two and
four: 2 passed.
- `test_allreduce_fusion_distributed.py` at TP4, covering M from 1 to
8193, both input forms and graphs: 18 passed per rank.
`test_allreduce_fusion.py`: 13 passed, including the route test for
SM100, SM103 and compute capability 10.7.
- `test/test_kernel_api_selection.py`: 367 passed and 270 skipped, as on
main.
- Runtime tests gated on these kernels, including `test_kimi_k3_kda.py`,
`test_kda_prefill_graph_cache.py`, `test_gdn_state_paging.py`,
`test_torch_memory_saver_adapter.py`,
`test_server_args_attention_backends.py` and the K3 MoE tail tests: the
cases enabled by this PR pass, while the rest match main.

On main in the same environment, these kernel test files skip on compute
capability 10.7 except `test_allreduce_fusion_distributed.py`, which
errors during workspace creation.

After support was widened,
`test_fused_step_matches_split_producers[-5.0-64]` exposed one recorded
gate out of 101,376 that differed from the reference by 1.3 BF16 steps.
The exact projection lay just past a BF16 rounding midpoint, while
cuBLAS's FP32 summation in `F.linear` landed on the other side; the gate
slope then amplified one raw-gate step. The test now draws `f_a` from
multiples of 2^-6 and `f_b` from multiples of 2^-9, each below 256
steps. Every product is a multiple of 2^-15 below 2, and every partial
sum of the 128 products is a multiple of 2^-15 below 2^8, so FP32
represents every sum exactly regardless of evaluation order. The
reference computes the projection in FP64 and rounds once to BF16. Both
kernels therefore evaluate the same gate expression on the same raw
gate, including near-ties and ties, and the recorded gates must now
match exactly. Output and correction tolerances are unchanged.


`test_outer_graph_replays_lengths_pages_and_states[cutedsl_kda-96-{2,4}]`
also failed after CuTe KDA prefill was enabled. CuTe prefill selects its
persistent scan when 2 times requests times heads exceeds the SM count.
With 96 heads, the one-request reference used the persistent scan on
GB300 but the ordinary scan on a 212-SM GPU, while padded capture used
the persistent scan. The two scans' FP32 states differed by up to
1.3e-3, exceeding the test's FMA-level tolerance of 2e-6. With 128
heads, one request also selects the persistent scan below 256 SMs, so
both sides use the same scan and the case passes at the unchanged
tolerance.

## Notes

### All-reduce fusion at large M

With the GB300 HT presets, the fusion was slower than a separate
all-reduce and RMSNorm above about 1024 rows. For example, TP4 finalized
input at 2048 rows took 57.9 microseconds with fusion versus 35.0
microseconds separately. FlashInfer's BT protocol, already used through
1024 rows, was faster than HT at every M measured above 1024 on compute
capability 10.7: 1025 to 8192 rows at TP4 on one tray and TP8 across
two. TP16 and more than 8192 rows remain unmeasured.

For TP8 across two trays, using a CUDA graph of ten back-to-back calls,
the following values are microseconds per call:

| Rows | HT, deferred expert rows | HT, finalized input | BT, deferred
expert rows | BT, finalized input |
|---:|---:|---:|---:|---:|
| 1025 | 45.6 | 38.1 | 29.3 | 18.5 |
| 2048 | 64.5 | 56.7 | 54.0 | 33.4 |
| 4096 | 103.8 | 97.7 | 98.2 | 60.0 |
| 8192 | 188.2 | 182.9 | 179.5 | 105.9 |

K3.1 defers expert finalization into this fusion; all 92 calls in the
8,113-token prefill above ran the BT kernels. Across its 92 MoE layers,
an 8192-token prefill chunk saves about 0.8 milliseconds, or 8.7
microseconds per layer; 1025- to 2048-token chunks save 1.0 to 1.5
milliseconds. Decode, with at most 512 rows, keeps its LL and BT routes.

BT holds three Lamport generations of two mailboxes, requiring about 43
KB of symmetric memory per row of capacity compared with 14 KB for HT.
At 8192-row capacity, the workspace therefore takes 352 MB per rank
instead of 161 MB for HT plus BT through 1024 rows. With the serving
command above, the KV cache is 53.06 GB per GPU instead of 53.18 GB with
the HT route, in a run that differed only in this route.

### LL exchange workspace

Under KVP, a DSA model prepares the LL exchange with a float-word
workspace for owned decode top-k selection through
`dsa_select_owned_candidates`. That selection remains limited to SM100
and SM103, so on compute capability 10.7 the workspace is reserved but
unused. At KVP 8 it takes 2 x 8 x 8 MiB, or 128 MiB per rank, beside the
32 MiB byte workspace, calculated as 4 x 8 x 1 MiB, that the KVP
exchanges use. This allocation is included in the KV cache figure above.
Main does not prepare the exchange on compute capability 10.7 at all,
and its reference run differs in too many other respects to isolate the
difference from logs.

---------

Signed-off-by: Nicolas Perrin <nperrin.ai@gmail.com>
2026-11-30 21:07:15 -05:00
Chen Hongtao d28be1af93 perf(graph): reduce CUDA graph memory across DeepSeek V4.1 capture buckets (#3591)
## Summary

DeepSeek V4.1 prefill keeps encoder activations alive for every captured
token bucket and allocates a separate decoder input for every decoder
row bucket. These allocations accumulate even though the graphs replay
serially.

This change lets `narrowing_forward()` read the hidden state, mHC
pre-mix, and DSpark taps directly from the addresses written by encoder
replay. The encoder holds non-owning views, so later captures can reuse
those graph-pool blocks. Before decoder replay, the runner writes the
selected rows into a persistent input buffer. Smaller decoder buckets
use leading views of the widest allocation. The PyTorch fallback also
preserves non-owning views when the native weak-reference extension is
unavailable.

## Benchmark

**Worker memory dropped by 7.97 GiB per GPU** serving
`DeepSeek-V4.1-Flash-1017` on 4× B300 with TP4, EP4, and DP1. Both
revisions used a fixed KV capacity of 65,536 tokens and captured 72
encoder buckets and 48 decoder buckets with a 16,384-token prefill
limit. Two cold starts per revision reproduced the same NVML readings.

| Worker memory per GPU | Benchmark base `9060c508c` | This change |
|---|---:|---:|
| Ready to serve | 98.74 GiB | 90.77 GiB |
| After the same HTTP workload | 100.63 GiB | 92.66 GiB |

For a 16,000-token prompt generating one token, median end-to-end HTTP
latency was 196.95 ms on the benchmark base and 196.64 ms with this
change.

## Test Plan

- 94 focused tests and 39 subtests passed, including alternating encoder
buckets, decoder buffer reuse, and a 40-layer split-prefill comparison
against eager execution.
- With the native weak-reference extension disabled, 44 tests and 2
subtests passed.
- All 43 serial HTTP requests matched across revisions. Fixed
four-prompt HTTP batches also matched. Four independently arriving
clients showed output differences across repeated runs of both
revisions.
- Broader validation reproduced three failures on the benchmark base as
well, involving checkpoint expert width, TP4 decode logits dtype, and
four-rank QCP numerical tolerance.
- `pre-commit run --all-files` and the runtime Ruff checks passed.

---------

Signed-off-by: Chen Hongtao <56470055+chenht2022@users.noreply.github.com>
2026-11-30 12:13:13 -08:00
WangBo d41c0b3927 refactor(cache): use int64 token write slots across backends (#3986)
## Summary

Use int64 for token write locations throughout the runtime. In a sharded
or strided cache, expanding an int32 page ID into a token slot can
exceed `INT32_MAX` even when the page table and the owner-local
allocation both fit. Widening before multiplication lets the runtime
address the full planned pool.

- The group router, DFlash, QSA (including the gfx950 decode monokernel)
and sparse KV offload produce and retain int64 write locations through
metadata refresh, graph replay and cache writes. The offload planner
accounts for the wider metadata.
- Scheduler page IDs and page tables remain int32. Backends that pass
flattened int32 read indices to attention kernels check their own read
ranges when binding a pool. A failed rebind preserves the previous pool.
- The group specification and the cache-transfer protocol keep their
existing layout. Model integrations inherit the slot width from the
host.

## Verification

- Added boundary coverage for sharded and strided tables, sparse reads,
graph replay, and offload metadata sizing and writeback.
- Ran the runtime and kernel suites on NVIDIA B300. They covered group
routing and pool rebinding, DFlash, QSA, FlashMLA, DSA, MSA,
cache-transfer serialization, and KV offload. Result: 1,157 passed and
19 skipped.
- On gfx950, the Muse Spark target launcher accepts the router’s int64
slot vector; its sequence lengths stay int32.
- The gfx950 verify-versus-decode test stages a recent slot above 2³¹
and checks the staged keys, positions and output against single-token
decode steps.
- A 260 GiB cache allocation resolved virtual slots 2,181,020,817 and
2,181,020,818 to different owner-local rows. BF16 keys read back
byte-for-byte after replaying graph-captured metadata refresh.
- `pre-commit run --all-files` passed. Ascend device execution remains
unverified.

---------

Signed-off-by: wangbo981016 <wangbo981016@gmail.com>
2026-11-30 21:33:12 +08:00
FC.Li 86a6ee2efe refactor(plugins): unify registration with lazy implementation references (#3939)
Plugin startup currently splits configuration hooks from runtime
registration, then undoes and replays them for headless startup.
Reporters and model policies can need those registrations before the
replay, and registering models eagerly imports unrelated
implementations.

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

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

Validation:

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

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

---------

Signed-off-by: FC-Li <33271309+FC-Li@users.noreply.github.com>
Signed-off-by: FC.Li <33271309+FC-Li@users.noreply.github.com>
2026-11-30 20:40:14 +08:00
183791d31e feat: add opt-in full-vocabulary binary output (#3989)
## Summary

Carry accepted-token head and tail scores through the unified sampling
and result transport path, including P/D handoff.

Preserve ordinary logprob transfers. Allocate binary buffers and send
additional P/D frames only when full-vocabulary output is enabled.

## Test Plan

- cargo test -p tokenspeed-pd --locked --offline — 154 tests passed.
- cargo test -p tokenspeed-wire --locked --offline — 52 tests passed.
- python3 -m pytest -q test/runtime/test_ts_wire_fixtures.py — 31 tests
passed.
- pre-commit run --all-files — passed.
- FP8 generation versus full-sequence replay — 620/620 samples matched
bitwise across 16,132,932 prompt logprobs and 19,840 decode logprobs,
with DFLASH disabled. This checked logprob self-consistency, not
full-vocabulary Top-K output.
- Controlled 32-token comparison with DFLASH enabled — token IDs and
FP32 logprobs matched bitwise with full-vocabulary output enabled and
disabled.
- Ran 89×8 token-ID replay benchmarks in 1P1D and 2P2D configurations,
collecting throughput, TTFT, TPOT, running batch size, GPU memory and
host memory usage.

## Performance Results

The same-build 1P1D comparison used eight H200 GPUs, DFLASH enabled and
Top-128 output. Each run lasted 20 minutes; metrics below exclude the
first three minutes.

| Metric | Enabled | Disabled | Change |
|---|---:|---:|---:|
| Decode throughput | 9,459 tokens/s | 9,829 tokens/s | −3.8% |
| Decode TPOT | 9.220 ms | 8.859 ms | +4.1% |
| Request-level E2E TPOT | 6.075 ms | 5.864 ms | +3.6% |
| Prefill TTFT | 423.4 ms | 453.2 ms | −6.6% |
| Running batch size per rank | 15.49 | 15.39 | +0.6% |
| Mean speculative acceptance length | 2.455 | 2.459 | Approximately
unchanged |
| Completed requests | 5,693 | 5,945 | Zero failures in both runs |

Enabling full-vocabulary output increased mean decode GPU memory by
approximately 0.316 GiB per GPU; prefill GPU memory was approximately
unchanged. Mean host PSS increased by approximately 0.12 GiB for prefill
and 1.53 GiB for decode. The shared result store and coordinator added
approximately 5.34 GiB of host PSS.

The lower TTFT includes queueing and cache effects and does not
establish faster prefill computation.

---------

Signed-off-by: lyzuu <349859374+lyzuu@users.noreply.github.com>
Co-authored-by: lyzuu <349859374+lyzuu@users.noreply.github.com>
Co-authored-by: longcat-ia-team <312376714+longcat-ia-team@users.noreply.github.com>
2026-11-30 19:44:19 +08:00
Lei Zhang 729331c7be feat(spec): opt-in draft-only FP8 LM head and MXFP4 experts for MTP (#3928)
The Qwen3.8-Flash-Next MTP draft reads the full BF16 LM head (1.27 GB)
on each of its steps and runs BF16 routed experts. Add two opt-in server
flags that change only the draft, so target outputs are unchanged:

- --speculative-draft-lm-head-quantization fp8_weight_only gives the
draft its own per-row-scaled FP8 copy of the shared head, projected with
mv_fp8_weight.
- --speculative-draft-moe-quantization mxfp4 quantizes the draft's
routed experts to MXFP4 at load with Quark's rounding, so they run the
target's A4W4 path.

Both default to none and are refused outside Qwen3.8 MTP, with
--numerics rl-bitwise or --model-update-config; MXFP4 experts are
refused with --decode-monokernel. The FP8 GEMV uses 64 output columns
per program for very wide outputs.

MI350X: draft head 229 -> 123 us per call at 1-8 rows (slower than BF16
above 32 rows); draft MoE 2.5-3.6x faster.

Signed-off-by: Lei Zhang <antiagainst@gmail.com>
2026-11-28 11:00:21 -08:00
Lei Zhang 6e629cdee2 test(execution): give the weight-update executor double target and draft models (#3901)
#3876 made DeviceHandle.check_weight_update look up peer-weight
controllers on executor.model_runner.model and
executor.draft_model_runner. The executor double in
test_device_weight_update_notifies_drafter_before_returning carried
neither, so update_weights raised AttributeError before reaching the
drafter refresh.

Give the runner double a model and the executor a draft runner, both
without peer expert weights, so the distributed update is still admitted
and the test keeps checking that the drafter is refreshed.

Fixing
https://github.com/lightseekorg/tokenspeed/actions/runs/46052566900/job/140742491887

Signed-off-by: Lei Zhang <antiagainst@gmail.com>
2026-11-27 18:35:33 -08:00
bhsueh_NV 7f3b98e0f2 feat(kda): share the retained-history count across KDA layers (#3780)
## Summary

Follow-up to #3635 (KDA retained SSM history) on top of `main`
(`bd3b9d6e7`):

1. **Share the KDA accepted-record count across layers** (`d698ede6d`,
refined in `d9fa4a02b`, `c40aed809`).
- Each resident request slot holds a single INT32 accepted-record count
(`_replay_length`) shared by all KDA layers instead of one count per
layer, with no round-start snapshot buffer and no per-layer
verdict/fault scratch.
- **Prepare (`resolve_kda_batched_retained_prepare`).** Runs in one
launch that only reads the shared count `H` (no reset launch). For
verify window `T` and capacity `C`, if `H` overflows (`H` outside `[0, C
- T]`), every layer folds records `[0, H)` into its live page (in place
when pages did not move; `H > C` applies none). Otherwise, a layer whose
live page differs from its source page copies the dense base there
without applying records so the `H` records remain valid on top of the
copy.
- **Verify.** Each verify kernel derives the effective replay length
`eff` (`0` when `H` overflows, else `H`) with a scalar select from
compile-time `C` and `T`, then writes candidate records after `eff`
without modifying the base or count.
- **Commit.** The convolution launch reads `H` and validates stamps
across `(layer, row)` programs; a second 1-D launch writes each carried
row's count once to `eff + accepted` (or `0` for an ended request). An
ending request whose commit a carrying layer rejects raises
`REQUEST_ENDED_INCOMPLETE` via compare-and-swap on `request_ends`.
- **Prefill & Retraction.** Layers gather/fold from the shared count,
followed by one ordered `kda_reset_retained_length` clear after the last
KDA layer.

2. **Default `--kda-history-capacity` to `16` when unset** (`ef914060b`,
`0789fed95`).
- When `--kda-history-capacity` is unset, `kda_history_capacity()`
defaults to `16` (removing both `max(16, T)` and the intermediate `T +
12` default).
- Preserves the invariant `kda_history_capacity >= draft_token_num`;
verify windows wider than `16` must specify `--kda-history-capacity`
explicitly.
- Aligns the KDA retained benchmark generators (`kda_fused_paged_verify`
and `kda_retained_commit`) to accept an optional `history_capacity`
parameter (default `16`, validated `>= draft_token_num`) instead of
`max(16, window)`.
- Updates `docs/configuration/server.md`,
`docs/design/cache-concepts.md`, and
`tokenspeed-kernel/python/tokenspeed_kernel/ops/attention/kda/README.md`.

3. **AMD retained conv SMEM descriptor fix** (`fe50df13d`).
- Restores SMEM descriptor loads in the AMD Gluon retained commit
convolution kernel.

## Memory & Launches

- **Shared count & single-launch prepare.** Replaces per-layer accepted
counts with one INT32 `[slots, 1]` tensor per request slot, eliminates
the prepare reset launch (153 launches/round vs 154 on a 69-layer KDA
model), and removes the verdict/fault scratch buffers.
- **Default capacity (`16`).** Keeps the default per-slot retained
workspace at 16 records per KDA layer (`19.4 MiB/slot` for 69 KDA
layers, 12 heads, head dim 128) for any verify width `T <= 16`; windows
wider than `16` require setting `--kda-history-capacity` explicitly.

## Validation

- **Unit & integration tests (Blackwell GPU):**
- Runtime KDA / cache-spec / linear-attn / eval-config / eager-commit
suite: `246 passed` (`0789fed95` builds on `ef914060b` where all 246
passed).
- KDA benchmark generator suite
(`tokenspeed-kernel/test/benchmark/test_benchmark_kda_generator.py`):
`15 passed` (including default `16`, explicit `history_capacity`, and
invalid `< draft_token_num` / non-int rejection).
- Earlier shared-count & overflow-copy rework (`d9fa4a02b`, `c40aed809`)
validated across kernel retained/window/step tests, runtime
KDA/slot-state/recipe/executor tests, and `ts-control` tests.
- **Lint:** `pre-commit run --all-files` passed on the final head
(`0789fed95`).

---------

Signed-off-by: bhsueh <11360707+byshiue@users.noreply.github.com>
2026-11-27 11:35:51 +08:00
yanlonghuandyanlonghu 382da44551 feat(ascend): suspend and resume ACL graphs with torch-npu-memory-saver (#3667)
## Purpose

Allow Ascend workers to suspend selected weights, KV and ACL graph
storage between rollout windows and resume at the original virtual
addresses. The original graph executable and HCCL communicator stay
resident. This is the standalone-allocator alternative to #3530.

## Design and use

TokenSpeed controls tensor ownership, transfer ordering, weight-update
commits and replica agreement. Protocol 3 extends protocol 2's
weight-update agreement to release/resume preflight and per-rank
completion. The [standalone
allocator](https://github.com/yanlonghu/torch_npu_memory_saver/commit/7d1a06db2a36b725ef270c6a62e5f78f0eeeae60)
owns the PTA pools, remapping, backup and the final allocator cache
trim.

Use `--device npu --enable-memory-saver` with `--weight-memory-policy
cpu_backup` or `discard`.

| Target state | KV and prefix behavior |
| --- | --- |
| Fully CPU-backed, weights unchanged | Resume restores the KV payload
and keeps valid prefix hits. |
| Weight update, including a same-version partial update | Flush old
prefixes before writing weights. Clear a stale sleeping KV image before
registering it for transfer. |
| Discard target | Drop old KV. After a weight release, restore
mappings, reload the complete target and commit before waking KV. |

The immutable KV layout uses the existing runtime allocator.
Page-transfer staging wakes with KV, so cache-only work can proceed
while the graph remains asleep. Model and idle forwards still require
their pools to be active. CUDA/ROCm retain their current adapter,
allocation lifetime and cache policy.

## Installation

With matching CANN, PyTorch and PTA installed, run:

```bash
TOKENSPEED_KERNEL_BACKEND=npu python -m pip install -e ./tokenspeed-kernel/python ./tokenspeed-engine -e ./python
```

The NPU backend resolves [torch-npu-memory-saver 0.1.6 on
PyPI](https://pypi.org/project/torch-npu-memory-saver/0.1.6/) (native
ABI 5). The source distribution builds against the active toolkit. A
[prebuilt CPython 3.12 / Linux AArch64
wheel](https://github.com/yanlonghu/torch_npu_memory_saver/releases/tag/v0.1.6)
is available for the tested A2 CANN 9.0.0 stack. The [serving
guide](https://github.com/yanlonghu/tokenspeed/blob/a03a9a083bbe78670518551111d7a13f2fa86518/docs/serving/ascend-memory-saver.md)
lists the six PTA 2.9.0-730 backports and install constraints.

## Validation

Latest KV changes:
[a03a9a08](https://github.com/yanlonghu/tokenspeed/commit/a03a9a083bbe78670518551111d7a13f2fa86518).

| Coverage | Observed result |
| --- | --- |
| A2 / 910B3, CANN 9.0.0, patched PTA 2.9, Qwen3-0.6B TP2 | An unchanged
CPU-backed target kept all 256 cached prefix tokens. Same-version
partial updates, full updates and discard refills each went from 256
hits to zero on the first request and back to 256 on the second. Eight
generated tokens per update path matched an independent launch in the
corresponding cold or warm state. |
| A3 / 910C, CANN 8.5.0, PTA 2.9, two-layer Qwen3 | The same cache-hit
transitions passed. Updating only the first value projection changed all
267 shared-prefix V rows. All eight resulting tokens and their
selected-token log probabilities matched a separate cold launch of the
modified checkpoint. Separate TP2 AIV graph coverage also passed. |
| Independent KV wake on both boards | With the graph pool still
unmapped, the device copied and zeroed KV pages. The original graph
subsequently replayed after its own wake. |
| Platform isolation | CUDA/HIP CPU adapter fixtures, cache arena
coverage and package dependency tests passed. Physical GPU regression
was unavailable. |

The CPU backup covers the allocated KV arena. If weights change while a
snapshot is asleep, the current allocator copies it back before
TokenSpeed clears it. That transfer is redundant; its latency and peak
host memory were not benchmarked in this round.

<details>
<summary>Earlier integration and operator qualification (prior allocator
versions)</summary>

The host and runtime use the same bootstrap API. Ascend ranks agree on
the memory protocol before saver-specific HCCL initialization. Release
and resume carry an optional transition ID separate from the request ID.
The feature uses upstream MHA dispatch. General multi-query
FIA/Triton/RoPE changes have been split out. Historical multi-query
results below used that additional operator support.

- **A2 / CANN 9.0.0 / patched PTA 2.9.** Reproduced the KV and MoE
failures on the old head. The frozen build passed all 9 targeted device
tests and 23 selected startup tests. After discarding Qwen3-0.6B TP2
weights and reloading all 313 checkpoint entries, both prompts matched
checkpoint B's cold launch across 24 generated positions with zero
selected-token log-probability difference.
- **A3 / CANN 8.5.0 / PTA 2.9.** All 10 device/startup tests and 17
native lifecycle tests passed. Both HCCL AIV TP2 ranks rejected mixed
protocol versions. For three suspend/resume cycles the managed graph
pool reached zero mapped bytes and the original graph reproduced all
4,096 AllGather values per rank at the same output address.
- **Isolation.** The MoE test exercises real NPU workspace allocation
with a small test kernel plan. The CUDA/HIP communication and allocation
fixtures passed on CPU. No physical GPU run was available in this round.

Packaging commit
[`6b24fbad`](https://github.com/yanlonghu/tokenspeed/commit/6b24fbad4feb3a93ef0188bcabd6d8427fe0fe49)
was checked separately. Pip downloaded the public source archive and
release wheel, and both SHA256 digests matched. Only the NPU kernel
metadata requires the saver. The 29 packaging tests passed. On A2/CANN
9.0.0 with patched PTA 2.9, the wheel loaded its own ABI 4 library. The
standalone replay test and both TokenSpeed graph policies (`discard`,
`cpu_backup`) passed with three suspend/resume cycles each and exact
output checks.

Serving integration
[`fb681265`](https://github.com/yanlonghu/tokenspeed/commit/fb68126554bc57d597149909eb2b1d1261764d88)
includes upstream main `67573412`. The Ascend saver device forwards the
host's recurrent-state retirement slots and fence after checking that
managed pools are active. Full Qwen3 disk recovery accepts known rotary
metadata and an output head owned by another pipeline stage. Required
local checkpoint entries remain mandatory and duplicates still fail. If
a Mooncake update and cleanup both fail, the NPU saver returns the first
update error.

- A2 / CANN 9.0.0 / patched PTA 2.9, Qwen3-0.6B TP2 eager: two ranks
consumed 313 entries each. After discarding weights and KV, reloading
checkpoint B and then resuming KV, all 24 generated tokens matched a
separate cold launch of B. The maximum absolute difference in the
selected tokens' log probabilities was 0.0. The initial checkpoint A
produced a different first token.
- A2 native MHA, one input token, verification width four, captured
batch two: 12 active output tokens matched across the eager, ACL replay
and restored runs. The standalone and bundled implementations shared the
same eager reference. The installed A2 kernel registry lacks a
compatible GDN/Mamba2 multi-token verify backend, so this does not
qualify a hybrid model.
- The matching Linux ARM64 host, control and serving suites passed 48
tests. The A2-host Python regression passed 12
protocol/weight-error/device-guard tests. Native ABI 4 rejects stale ABI
3 library overrides before allocator use. An actual old native binary
and matching ABI 4 binary were tested through both Python loaders.
- The hardware runs used `0907c0a4`. Only a unit-test mock changed
between that revision and `fb681265`.

### November 24 validation

At
[`62e77514`](https://github.com/yanlonghu/tokenspeed/commit/62e775143770627aad22f01422adf0e1b5972c48),
install the pinned [standalone 0.1.4
source](https://github.com/yanlonghu/torch_npu_memory_saver/commit/866357c48048459d69522e311d56b8e1f6dfaed7).
The native library retains mapped storage when an HCCL registration
result leaves peer state uncertain. A cache-trim callback failure is
reported on the same pause call. TokenSpeed cancels an agreed protocol 3
release before a deferred L3 flush can yield to release processing.

- On A2/910B3, CANN 9.0.0 and patched PTA 2.9, the installed standalone
wheel supplied the native library loaded by both Qwen3-0.6B BF16 TP2
workers. All 32 generated token positions matched after release/resume,
and the launcher exited normally. Both single-device graph policy tests
passed. Both rank logs placed the first AIV-buffer release after
restored generation.
- In a separate two-rank AIV AllGather test, each rank captured once and
replayed its original graph through three suspend/resume cycles. The
graph output address and the 401 MiB HCCL arena per rank stayed stable.
Managed mapped and physical bytes reached zero on both ranks during
every pause.
- All 13 native fault and lifecycle tests passed, including errors
before and after state changes in each HCCL registration call. These
faults were injected into the native allocator test harness. The Rust
gate and its regression test are byte-identical to [the fix verified in
#3530](https://github.com/lightseekorg/tokenspeed/pull/3530/commits/bb684a4f2b7b69282bdba0f96902d0ec2d47cc85),
including one-sided cancellation while a two-rank L3 flush is pending.
Production A3 ACK failures were not injected.

- The supplemental mixed-platform Python run had 73 passes, two
CUDA-only skips and four failures during lazy FlashInfer import with the
inherited mock CUDA version `test`. With the actual Ascend cache
metadata imported before the fixture, all eight cache-table cases passed
on the same source.

### Earlier validation

For the 0.1.3 update, the source package and the installed A2 wheel were
checked separately. The wheel passed its A2 graph test and mapped its
bundled native library. Through the TokenSpeed adapter, both A2
single-device graph policies passed. Under TP2 AIV, each rank captured
once and replayed the same graph for three suspend/resume cycles,
verifying 524,288 bytes of AllGather output per rank per cycle. The A2
adapter skipped HCCL registration. A freshly built Qwen3-0.6B BF16 TP2
service also released and resumed weights, KV and graph memory. All 32
output tokens matched and the launcher exited with status zero. A3
full-model and segment-reuse runs remain pending access to the hardware.

Earlier results with 0.1.1:

- Atlas A2 / 910B3, CANN 9, patched PTA 2.9, Qwen3-0.6B TP2, protocol 3,
HCCL AIV. All three full suspend/resume cycles reproduced all 32 tokens
for each of four prompts. Both ranks loaded the native library installed
from the PyPI release.
- A two-tensor partial disk update under `cpu_backup` and a complete
311-tensor disk refill under `discard` matched a fresh launch of the
updated checkpoint. KV resume before the complete refill was rejected.
- The opt-in real-device integration test passed. Host/runtime
regressions without the optional package had 398 passes, three skips and
one failure: `test_the_guard_rejects_cuda_factories_before_they_run`
also fails on unmodified main with this CPU build of PyTorch. CUDA/ROCm
hardware was unavailable.

</details>

---------

Signed-off-by: yanlonghu <19688573+yanlonghu@users.noreply.github.com>
Co-authored-by: yanlonghu <19688573+yanlonghu@users.noreply.github.com>
2026-11-27 01:42:41 +08:00
Q.Yao eafdfc2178 perf(runtime): batch checkpoint metadata uploads (#3784)
Preparing in-forward state checkpoints makes separate host-to-device
index copies, and checkpoint writers repeat some of those uploads. Pack
related metadata into asynchronous transfers and reuse the resulting
device views. The token and block slots used by prefill graphs remain
fixed, while row and offset mirrors follow the live batch.

This extracts the runtime metadata optimization from
[#3677](https://github.com/lightseekorg/tokenspeed/pull/3677).
Checkpoint retention and scheduler policy are unchanged. The tests cover
upload synchronization, graph metadata refresh, and retained storage
through buffer growth and repeated memory release and resume.

Validation:
- `pre-commit run --all-files` passed.
- CPU checkpoint semantics: 7 passed; packed-upload semantics: 3 passed.
Four CUDA cases were skipped in the CPU-only environment.
- The same metadata implementation passed four CUDA regressions before
rebasing: checkpoint uploads, scan-index uploads, checkpoint-writer host
synchronization, and repeated memory release and resume with stable
addresses, restored values, and zero ordinary allocator occupancy.
- The rebased revision has not been rerun on GPU; the functional
metadata changes are preserved.

Signed-off-by: q.yao <street@lightseek.org>
2026-11-25 23:56:21 +08:00
Tuan ZhangandtuanzhangCS 4fb7872166 perf(gdn): defer recurrent replay into the next verification step (#3582)
## Summary

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

### Performance

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

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

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

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

## Validation

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

### Original implementation validation

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

---------

Signed-off-by: tuanzhangCS <26617745+tuanzhangCS@users.noreply.github.com>
Co-authored-by: tuanzhangCS <26617745+tuanzhangCS@users.noreply.github.com>
2026-11-25 15:55:32 +08:00
bhsueh_NV fbfb1f2376 feat(kda): retain SSM history across verify rounds (#3635)
## Summary

- KDA speculative decoding keeps the accepted tokens' SSM history across
verify rounds, instead of committing every layer's dense recurrent state
each round. The dense state is brought up to date only when the retained
history fills or a request's state page changes.
- Covers the NVIDIA and AMD verify paths, cache allocation, transfer and
restore, and CUDA graph replay, with documentation and regression tests.
- Adds `--kda-history-capacity`, which sets how much history each
request keeps (by default 16 records, or the verify width if larger): a
smaller value uses less memory but folds the history into the dense
state more often.

## Performance

GB300, Kimi-K3 TP8 per-rank KDA shape (12 heads, head dim 128, 69 KDA
layers). `main` is `8f161919b`, this PR's merge base; main's later
commits do not touch KDA. This PR is at `56756ead2`. Times are kernel
GPU time from `torch.profiler` in the KDA decode test harness, with
eager launches. Acceptance is synthetic: high accepts all T draft tokens
every round, low accepts one.

### Fused verify kernel

Batch 1, high acceptance. Mean GPU time per launch over 16 rounds of 69
layers. Both trees run the same kernel: `FusedVerifyStep` at T = 1 and
`FusedVerifyWindow` at T ≥ 2.

| T | main | this PR | this PR / main |
| ---: | ---: | ---: | ---: |
| 1 | 3.95 µs | 3.86 µs | 0.98 |
| 2 | 3.75 µs | 4.38 µs | 1.17 |
| 4 | 4.26 µs | 4.87 µs | 1.14 |
| 8 | 5.65 µs | 5.93 µs | 1.05 |

At T ≥ 2 this PR's verify also applies the retained history; the decode
round below shows the net effect.

### Decode round

GPU time of one decode round of the 69 KDA layers: metadata refresh,
every layer's verify, and the commit. Each cell is the mean of 8 paired
runs on 4 GPUs. A second run reproduced every ratio within 0.007.

Ratio this PR / main, high / low acceptance (below 1 means this PR is
faster):

| T \ batch | 1 | 4 | 16 | 64 |
| ---: | ---: | ---: | ---: | ---: |
| 1 | 1.002 / 0.990 | 0.930 / 0.933 | 0.794 / 0.802 | 0.717 / 0.714 |
| 2 | 1.112 / 1.119 | 1.024 / 1.019 | 0.863 / 0.843 | 0.785 / 0.753 |
| 4 | 1.107 / 1.108 | 1.093 / 1.071 | 0.947 / 0.878 | 0.889 / 0.794 |
| 8 | 1.073 / 1.077 | 1.085 / 1.063 | 1.036 / 0.919 | 1.049 / 0.867 |

GPU time per round at high acceptance, main → this PR (µs):

| T \ batch | 1 | 4 | 16 | 64 |
| ---: | ---: | ---: | ---: | ---: |
| 1 | 393 → 394 | 485 → 451 | 818 → 650 | 2309 → 1655 |
| 2 | 394 → 438 | 513 → 526 | 917 → 791 | 2888 → 2266 |
| 4 | 431 → 477 | 558 → 610 | 1039 → 985 | 3348 → 2978 |
| 8 | 529 → 568 | 773 → 838 | 1401 → 1452 | 4209 → 4414 |

Where this PR is faster or slower:

- Faster at batch 16-64, except T = 8 at high acceptance, and at T = 1
from batch 4, by up to 29%.
- On par at T = 1, batch 1.
- 2-12% slower at batch 1-4 with T ≥ 2.
- 4-5% slower at T = 8, batch 16-64, high acceptance.

## Memory

Verify workspace each GPU allocates at startup, taken out of the KV
cache budget, in MiB. Same per-rank shape as above, at `94126efff`;
batch is the maximum batch size. Cache checkpoints are the same size as
on main: the difference is the history each request keeps, about 1.2 MiB
per request for each record of capacity (19.4 MiB at the default 16). It
scales with the KDA heads each GPU holds: at KDA TP1 (96 heads) each
request takes eight times as much.

| batch | T | main | this PR | capacity 8 | capacity 4 |
| ---: | ---: | ---: | ---: | ---: | ---: |
| 16 | 1 | 52 | 360 (+308) | 184 (+133) | 98 (+46) |
| 16 | 4 | 120 | 389 (+269) | 214 (+94) | 127 (+7) |
| 64 | 1 | 208 | 1320 (+1112) | 679 (+472) | 359 (+152) |
| 64 | 4 | 479 | 1437 (+958) | 797 (+318) | 477 (-3) |
| 256 | 1 | 828 | 5163 (+4335) | 2660 (+1832) | 1408 (+580) |
| 256 | 4 | 1916 | 5630 (+3714) | 3128 (+1212) | 1876 (-40) |

"this PR" is the default capacity; the capacity columns set
`--kda-history-capacity`. A smaller capacity folds the history into the
dense state more often, every round that accepts a token when it equals
T; the decode-round times above use the default. Memory allocated during
a round is the same as on main.

## Validation

- `pre-commit run --all-files` passed.
- GB300: KDA kernel tests (447 passed) and runtime KDA tests (133
passed, 1 skipped) on `56756ead2`.
- GB300 after the review fixes (`94126efff`): KDA kernel tests (449
passed) and configuration and cache-spec tests (341 passed, 4 skipped);
the retained verify's outputs and records are unchanged bit for bit.
- AMD: no AMD hardware in this validation; AMD coverage comes from CI.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: bhsueh <11360707+byshiue@users.noreply.github.com>
2026-11-25 10:06:14 +08:00
FC.Liandlongcat-ia-team ed1be7f2cb feat(disk): add a local SSD tier below the Host cache (#3695)
## Summary

Adds the node's local NVMe as a third prefix-cache tier, `kDisk`, below
Device and Host (RFC 0006, `docs/rfcs/0006-disk-tier.md`). It extends
RFC 0004 peer prefix sharing directly, not through L3 storage.

- **One tier model.** `kDisk` lives in the same coordinator,
`BoundaryTree`, `CheckpointTree` and prefix indexes as Device and Host.
A page still has one owner, and hybrid models (sliding windows, State
checkpoints) need no special case.
- **Write-back and prefetch.** Host cleans dirty entries to Disk in the
background. A request whose prefix sits on Disk has it read into Host
before admission (Prefetching plus a Ready hold), then admits as an
ordinary Host hit. Disk contents never outlive the process.
- **Executor (`ts-disk`).** Block I/O on io_uring with fixed buffers (or
a psync thread pool) and `O_DIRECT`. Reads go first; writes are paced by
a token bucket. It runs on the engine host and the data plane
(`ts-control` `disk.rs`) with its own metrics.
- **Peer landing tier.** `--peer-prefix-landing-tier device|host`
(required with peer sharing, no default). A Host landing reserves Host
blocks, waits in Prefetching, and publishes under a Ready hold once the
fetch is done.
- **Holder Disk push.** A holder lists Disk-resident blocks, reads them
into a staging ring registered with both the executor and the transfer
engine, and writes each chunk into the reader's landing as soon as it is
read. It has a budget and CANCEL with acknowledgement.
- **KV events.** Adds a `DISK` medium for lower-tier residency.
- **Host credit units.** Disk prefetch, peer Host landings and L3 now
share one bound: Host credits count blocks in any group, up to
`SchedulerConfig::HostBlockCapacity()` (usable Host parents × the
densest packing).
- Before, the credits were sized in parents. A hybrid GET holds every KV
page under the State checkpoint it restores, so long hybrid prompts were
never prefetched from Disk or restored from L3.

New server args: `--disk-tier-paths`, `--disk-tier-size-gb`,
`--disk-tier-io`, `--disk-tier-write-mbps`, `--disk-tier-config`,
`--peer-prefix-landing-tier`. They are documented in
`docs/configuration/server.md`.

## Validation

GPU end-to-end runs used the CUDA 13 CI environment. Each check compares
the output of a lower-tier hit with the output of a Device hit on the
same prompt:

- **Dense (Qwen3-8B, TP1).** A 17.7K-token prompt evicted to Disk only
comes back as 276 blocks (2.6 GB) in about 370 ms. Output equals the
Device hit, with both io_uring and psync.
- **Hybrid (Qwen3.5-4B, `--enable-state-checkpoint-in-forward`).** A
Disk hit whose checkpoint ends one token before the prompt's end equals
the Device hit.
- **Peer sharing (two servers over RDMA).**
- Host and Device landings of an 8192-token prefix equal the holder's
output.
  - A holder pushes 96 Disk blocks (0.9 GB) in 131 ms.
- **L3 (memory backend) on the hybrid model** with a Host smaller than
the restore's block count. The restore now runs; before this change the
credits refused it.

Unit tests:
- C++ scheduler suite.
- Rust: `tokenspeed-control` (including the Disk integration test),
`ts-disk`, scheduler, metrics.
- Python: cache, L3, disk, peer, rank-setup and server-args tests.
- `pre-commit run --all-files`.

## Known issue found during validation (pre-existing on `main`, not
changed here)

A Qwen3.5-4B prefix restored from Host L2 decodes differently from the
same prefix hit on Device when a multi-token suffix after the restored
checkpoint runs through the prefill breakable graph.
- Main reproduces it with plain Host L2 under both write-back and
write-through.
- `--disable-prefill-graph` makes the outputs equal.

Disk hits and the L3 restores this PR unlocks both land through Host, so
they show the same difference until that is fixed.

## Test plan

- [x] C++ / Rust / Python unit tests above
- [x] GPU e2e: Disk hit (dense and hybrid), peer Host and Device
landings, holder Disk push, L3 hybrid restore
- [ ] Load benchmark across sequence lengths and batch sizes with Disk
hit vs miss (in progress)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: FC-Li <robert_lexis@163.com>
Co-authored-by: longcat-ia-team <longcat_ia_team@meituan.com>
2026-11-21 23:58:09 +08:00
Enwei Zhu f8acfc3a30 perf(kda): replace binary prefill with FlashInfer CuTe kernels (#3665)
<!-- 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

Replace the binary KDA prefill dependency with FlashInfer CuTe kernels
under the existing `cutedsl_kda` backend.

- Consume strided Q/K/V directly from convolution output and remove
obsolete preparation and installation code.
- Select ordinary or persistent CuTe using kernel eligibility,
request/head count, and SM count. Build persistent schedules from live
GPU boundaries for eager execution and graph replay, with
invocation-owned scratch and startup warmup.
- Optimize recurrent-state scatter with a request × tile grid and
fixed-layout specialization.

Preserve FP32 scan state, the existing zero-padding contract, and LCM
state ownership.

Persistent integration adapted from
[8fcc2985](https://github.com/lightseekorg/tokenspeed/commit/8fcc298526068cff2840c017837aefcdc3a388f3).

## Test Plan

- [x] Focused numerical, strided-input, graph-replay, and compile-reuse
tests.
- [x] State-scatter correctness, partial-tile, and large-offset tests.
- [x] Memory release/resume with zero ordinary CUDA allocation
occupancy.
- [x] Installer validation and `pre-commit run --all-files`.
- [x] GB200 profiling across 24/48/96/144 heads, 4k–16k tokens, and 1–16
requests.

Example: 96 heads, 16,384 total tokens, BF16 inputs/cache and FP32 scan
state:

| Requests | Ordinary FlashInfer CuTe | New dispatch | Speedup |
|---:|---:|---:|---:|
| 1 | 885.44 µs | 753.25 µs | 1.18× |
| 2 | 899.87 µs | 522.18 µs | 1.72× |

Both paths use the optimized scatter. Timings include gather,
input/metadata preparation, scan, and scatter: median Nsight GPU time
from 21 warmed eager calls, flushing L2 before each sequence.

Separately, the scatter optimization reduces the single-request, 96-head
scatter from ~12.6 µs to ~3.2 µs. These are kernel measurements, not an
end-to-end serving benchmark.

---------

Signed-off-by: Enwei Zhu <21126786+syuoni@users.noreply.github.com>
2026-11-21 00:15:23 +08:00
sjqgogogogo 6a5b9947e4 fix(sampling): key chain MTP randomness by token position (#3490)
## Summary

FlashInfer chain verification used per-slot generators that advanced
during prefill preparation. Under `--sampling-stream per-request`,
FlashInfer and FlashInfer Full now derive accept and final-draw coins
from the request seed and the first target position in the verify round.
The two kinds of draws use distinct counters.

Sampled draft proposals use the accepted frontier after the round and
the draft step. The verifier retains its target-only and recorded-q
rejection rules, and uses the same fixed-order residual scan with
replicated and batch-DP logits layouts under per-request sampling.

## Test Plan

- `pre-commit run --all-files` passed.
- On H200, 64 sampler and kernel tests passed and one existing test was
skipped. This covers extra prefill preparation, changed slots and mixed
batches, CUDA graph replay, sampler snapshot restore, and recorded-q
verification.
- Real chain MTP passed ten-bin distribution calibration for 10,000
committed tokens each with greedy draft proposals and with sampled
proposals using recorded q. Both configurations accepted draft tokens.
- Per-request DP layout equivalence remains unverified. End-to-end
`auto` runs already showed first-token logprob differences before
speculative verification. The sampler tests compare runs with matching
numerical inputs.

---------

Signed-off-by: sjqgogogogo <sjqgogogogo@gmail.com>
2026-11-19 13:29:31 +08:00
dingyuqing05andlongcat-ia-team 401d29b693 fix(pd): propagate hybrid cache readiness to state backends (#3563)
Summary
- Register the hybrid producer step counter on the linear-attention
child.
- Let state backends publish staged prefill fields before the wrapper
signals readiness, without recording the same producer step twice.
- Document the final-write and single-barrier contract for hybrid
producers.

Results
- The rebased source passes 21 focused producer-readiness,
destination-validation and FP8 state-transfer regression cases with real
GPU backends.
- Before the base update, an eight-GPU disaggregated comparison passed
18 requests and matched all 523 output token IDs and FP32 logprob bit
patterns. It covered concurrency, chunked prefill and cached prefixes,
with native layerwise sends.

Test plan
- Passed: pre-commit run --all-files.
- Passed: cargo fmt --all --check in tokenspeed-engine, with
/opt/cargo/bin on PATH and RUSTUP_HOME=/opt/rustup.
- Passed: 21 focused integration regression cases against the rebased
source.
- Full-model comparison was run before the base update, not repeated
afterward.

---------

Signed-off-by: dingyuqing05 <13126694060@163.com>
Co-authored-by: longcat-ia-team <longcat_ia_team@meituan.com>
2026-11-18 20:05:06 +08:00
WangBo a887ffbc4c feat(dspark): select decode graphs per attention-DP rank (#3516)
Attention-DP ranks currently replay a shared decode graph bucket, so a
lightly loaded rank pays for its busiest peer's physical request and
query capacity. This adds `--enable-dp-local-cuda-graph` so each
supported rank selects its own captured request bucket B and target
query capacity Q. Stacked on
[#3479](https://github.com/lightseekorg/tokenspeed/pull/3479); merge
that parent first.

- Keep the generic drafter capability and runner selection contract.
Initially enable native DeepSeek V4.1 DSpark with target and draft
MegaMoE, attention, dense, MoE, and LM-head TP1, PP1, and no context
parallelism or DP sampling. Validate loaded backends as well as CLI
options.
- Preserve group-wide forward-mode and graph-or-eager agreement, then
select B and Q locally. Idle ranks replay an anchor in the smallest
capture bucket. A peer outside the capture ladder retains group-wide
eager execution.
- Use existing fixed-capacity MegaMoE communication storage while
allowing different local row counts and tile sizes. Cover fused shared
experts and consecutive graph replays without host barriers.
- Preserve request-slot indexing independently of execution capacity.
Scheduler and KV reservations and acceptance and commit semantics remain
at the configured maximum verify length; no scheduler or engine feature
path is added.

Validation:

- Restacked onto main `53df8e924`: parent `d56d9df3c`, child
`6f434173c`. Each PR is one commit ahead of its base with zero commits
behind. `pre-commit run --all-files` passed on both branches after
rebase.
- Fixed the installed-wheel failure found by the B200 runtime suite: the
CuTe sampling helper directory now has a package initializer. A real
pre-fix wheel reproduced the exact missing-module error; the corrected
wheel passed all 14 packed-DSpark sampling cases. Kernel imports were
audited to come from the installed wheel, with kernel source paths
excluded.
- The corrected candidate also passed 26 local-graph/packed-attention
tests. These focused checks used candidate parent `583e1c5ea` / child
`58be371cd` before the final base update; stable patch IDs confirm that
the final rebase preserves each feature patch.
- Earlier integration checks on main `f3f1ddde8`: rebuilt embedded
scheduler/engine bootstrap and three source-import checks passed; 20
focused C++ prepared-prefix/storage cases passed. Parent contract: 14
passed. Stacked runtime: 203 passed, 2 reference-snapshot skips. Main
integration: 70 passed, 7 ROCm-only skips. DP2: 4 passed and 1
four-rank-only skip per rank; DP4: 5 passed per rank; heterogeneous
shared-expert MegaMoE graph replay: 1 passed per rank.
- The earlier broader regression passed 137 kernel tests and 1194
runtime tests (8 skipped, 37 subtests). Its fixed CUDA native inputs
were compared before reuse; Python source tests and installed-wheel
tests are distinguished above.

Paired serving results below used frozen main and feature revisions from
before the final upstream merges. They are separate from the
current-head checks above.

| Quality evaluation | main | adaptive + local graphs |
|---|---:|---:|
| GSM8K, all 1319 problems | 1281 of 1319 (97.12%) | 1286 of 1319
(97.50%) |
| AIME25, 30 problems × four seeds | 120 of 120 | 120 of 120 |

Temperature 1, top-p 0.95, top-k disabled; matched inputs and request
seeds. These sampled scores establish observed alignment, not bitwise
equality.

The completed multi-turn sweep used DeepSeek V4.1 Flash on 8 × B300,
colocated EP8, attention-DP8, and TP1. Initial contexts were 8K, 32K,
64K, and 128K and concurrency per DP rank was 8, 32, 128, and 256. Each
conversation ran 10 real service turns with 500 actual output tokens per
turn, `ignore_eos=true`, temperature 1, top-p 0.95, top-k disabled and
seed 42. The baseline used fixed verify=6; the feature used sampled
adaptive verify≤6 plus local graphs. All 32 load points completed:
378,880 requests, 189,440,000 actual output tokens, zero request errors,
matching server completion counts and observed batch peaks on all eight
DP ranks.

| Initial context | BS8 throughput change | BS32 | BS128 | BS256 |
|---|---:|---:|---:|---:|
| 8K | +6.0% | +9.1% | +17.6% | +24.0% |
| 32K | +5.0% | +8.5% | +12.4% | +15.7% |
| 64K | +10.2% | +10.7% | +12.4% | +13.1% |
| 128K | +10.2% | +9.1% | +7.1% | +6.6% |

Throughput is successful actual output tokens divided by the full
request makespan and eight GPUs, including prefill and queueing; no
acceptance-length normalization. At 128K with BS256 it rose from 1756 to
1872 output tokens per second per GPU. This compares the complete
sampled-proposal, adaptive, and local-graph stack, not the isolated
contribution of local graphs. Single run per point, without confidence
intervals. Median request TPOT regressed 3.43% at 8K with BS8 and 2.40%
at 32K with BS8; throughput gains do not imply every latency metric
improved.

SWE-Smith user and tool text supplies the input skeleton; each service
generates its own later replies. The 128K case is a constructed context
workload preserving truncated source-text remainders. The model cap is
1M, while actual prompts in this sweep reached 143,231 tokens. This is a
multi-turn generation load test, not a real tool-agent task-success
evaluation. A fresh PD+Dynamo comparison and the production 4P→8D
topology remain outside this final validation.

See the adaptive guide `docs/guides/dsv41-adaptive-dspark.md` and the
unified execution contract `docs/design/unified_path.md`.

Signed-off-by: wangbo981016 <wangbo981016@gmail.com>
2026-11-17 02:03:05 -08:00
LightSeek Foundation cf1e2923f7 build: serve the scheduler Python API from tokenspeed-engine (#3511)
TokenSpeed currently installs two copies of the scheduler: the
standalone `tokenspeed-scheduler` wheel, and the build that
tokenspeed-engine links into `_host`. Each rank already serves the
runtime's `tokenspeed_scheduler` imports from the linked build. The
standalone wheel is only an extra dependency to build, pin and release
in step.

`tokenspeed_engine.scheduler` exposes the linked module with the same
names as `tokenspeed_scheduler`. The runtime and tests import it, and
`python/pyproject.toml` drops `tokenspeed-scheduler`. CI installs,
Docker images and the release image stop installing or pinning it. The
Mooncake L3 jobs now install the full engine, because their tests drive
the scheduler.

The standalone wheel is still published, and its release pipeline keeps
the version and publish stages. The stage that bumped TokenSpeed's
requirement and the scheduler check in the TokenSpeed preflight are
gone, since nothing downstream requires that wheel anymore.

Follow-up: stable TokenSpeed still requires `tokenspeed-engine>=0.1.0`.
That range includes engines without `tokenspeed_engine.scheduler`, so an
upgrade over an old engine needs an engine version bump to be enforced.

---------

Signed-off-by: lightseek-bot <243258330+lightseek-bot@users.noreply.github.com>
2026-11-16 16:37:59 -08:00
simple-sun 34eaef6da1 feat(pd): decode-extra-slots (#3362)
## Summary

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

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

## Default extra slots and capacity cost

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

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

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

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

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

## Retraction and snapshot limits

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

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

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

### Long-output, high-occupancy validation

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

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

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

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

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

## Upgrade requirements and cancellation scope

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

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

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

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

## Benchmark results and benefits

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

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

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

### Decode batch occupancy

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

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

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

### Latency and outcome tradeoff

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

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

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

### Error codes and failure rates

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

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

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

### Where the feature helps

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

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

## Test Plan

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

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

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

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

---------

Signed-off-by: sunshengqi <69040952+simple-sun@users.noreply.github.com>
2026-11-17 00:31:38 +08:00
47daf2b3ad perf(dsv41): add adaptive DSpark verification (#3216)
## Summary

Adapt DeepSeek V4.1 DSpark target verification using draft confidence
and
startup-profiled execution costs. Allocate verification rows across
requests
and execute packed target queries with matching CUDA graphs. Draft
generation
remains full width, and token acceptance checks are unchanged.

- Profile eligible graph capacities at startup and reuse compatible
cached costs;
  no calibration dataset or external cost table is required.
- Coordinate a common verification capacity across attention DP ranks
while
  allocating rows locally using the latest available draft confidence.
- Support uneven, padded and idle attention DP ranks with a shared
physical
  graph capacity and per-rank allocation over real requests.
- Build packed verification layouts with Triton and integrate them with
attention,
KV writeback and greedy sampling; retain a PyTorch reference only in
tests.
- Retain asynchronous confidence feedback and conservative
full-verification
fallback; remove serving-time cost collectors, timing histories and
their
  synchronization.

## Usage

~~~bash
--enable-dsv41-adaptive-dspark \
--dsv41-dspark-min-batch-size 4
~~~

The threshold uses the **largest actual local batch among attention
ranks**,
not client concurrency. Balanced DP8 reaches local BS4 at C32. Reaching
it
permits adaptation; the cost model can still select full verification.


## Performance

PD deployment: one 8-GPU H20 prefill worker (QCP8/EP8) and one 8-GPU H20
decode worker (DP8/EP8), host Engram, with DP-balanced SMG routing.
Both arms use **10,240 input / 4,096 output tokens**,
greedy sampling, real DSpark acceptance and minimum local BS4.
The baseline disables adaptive verification while retaining native
DSpark.

Inputs are derived from 32 LongBench templates. Each request
has a distinct leading ID; these are not 256 independent documents.
Paired
arms use identical payloads. Each concurrency runs one warmup and three
formal rounds; tables average **formal rounds 2 and 3**, excluding
warmup
and formal round 1 consistently.

- **No prefix cache:** P and D disable prefix caching. Request IDs
change across
rounds and concurrency levels. Every request reports zero cached tokens.
- **Cached prefixes:** P enables prefix caching; D still disables it.
Stable
session IDs allow reuse across rounds. Every formal request hits 9,984
of
  10,240 input tokens.

### Without prefix cache

| Concurrency | Native TPOT (ms) | Adaptive TPOT (ms) | TPOT change |
Native output (tokens/s) | Adaptive output (tokens/s) | Throughput
change |
| ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| 32 | 8.998 | 8.915 | **-0.92%** | 2,484.5 | 2,493.1 | **+0.34%** |
| 64 | 12.365 | 10.892 | **-11.92%** | 3,330.9 | 3,658.9 | **+9.85%** |
| 128 | 18.659 | 14.789 | **-20.74%** | 4,064.0 | 4,836.8 | **+19.02%**
|
| 256 | 30.165 | 21.847 | **-27.58%** | 4,886.1 | 6,076.3 | **+24.36%**
|

### With cached prefixes

| Concurrency | Native TPOT (ms) | Adaptive TPOT (ms) | TPOT change |
Native output (tokens/s) | Adaptive output (tokens/s) | Throughput
change |
| ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| 32 | 9.171 | 9.270 | **+1.08%** | 2,809.3 | 2,709.1 | **-3.57%** |
| 64 | 12.859 | 11.425 | **-11.16%** | 3,983.6 | 4,224.8 | **+6.06%** |
| 128 | 19.539 | 15.277 | **-21.82%** | 5,058.8 | 5,659.1 | **+11.87%**
|
| 256 | 32.951 | 25.053 | **-23.97%** | 6,027.8 | 7,663.6 | **+27.14%**
|


## Validation

- Full repository pre-commit passed for the tested code commit.
- Budget selection, confidence feedback, startup profiling and packed
layout
  tests cover native fallback and adaptive execution.
- Distributed runtime coverage includes uneven/padded/idle attention
ranks
  and common-capacity agreement.
- PD C32/C64/C128/C256 paired serving tests completed with and without
prefix
  cache; all request-level payload, length and cache checks passed.

---------

Signed-off-by: wangchangran <shinewang96@gmail.com>
Signed-off-by: jumper <shinewang96@gmail.com>
Signed-off-by: wangbo981016 <wangbo981016@gmail.com>
Co-authored-by: longcat-ia-team <longcat_ia_team@meituan.com>
Co-authored-by: WangBo <wangbo981016@gmail.com>
2026-11-16 20:16:48 +08:00
Nicolas Perrin 0974eedb40 perf(prefill-graph): capture four requests per bucket by default (#3462)
## Summary

Prefill graphs capture each token bucket's recurrent layers (GDN, KDA,
Mamba2) inline at fixed request capacities,
`--prefill-graph-capture-batch-sizes`. Unset, the capacity was one
request, so a prefill round that admits two to four requests found no
capacity and ran every recurrent layer at an eager break: about 50 ms
instead of 17 to 30 ms for short prompts on Qwen3.5-35B, and most of the
stall time under streaming load. This PR makes the unset default four
requests; fewer requests replay the same graph padded.

- **Default.** `resolve_prefill_capture_batch_sizes` resolves unset to
`PREFILL_DEFAULT_CAPTURE_REQUESTS` (4), capped by `max_num_seqs` per DP
rank and by the bucket, and never below the bucket's minimum count. A
configured list is unchanged. Below `--max-num-seqs 4` the default
follows it, where a configured 4 is refused.
- **Startup probe.** `probe_arena_floor` sizes the probe arena for the
default count, as it did for a configured one; a server without a chain
drafter would otherwise fabricate four dummy requests in an arena sized
for one or two.
- Only backends that capture recurrent layers inline
(`admits_prefill_graph`), without DP, record these variants; other
models capture what they did.

**Why four, alone.** It is still one inline graph per bucket, so it
costs what one request did; every further count is another graph per
bucket. Qwen3.5-35B-A3B-FP8 + MTP (a chain of 3), TP4:

| `--prefill-graph-capture-batch-sizes` | 1 (old default) | 4 (new
default) | 1 2 4 |
|---|---|---|---|
| Streamed chunks, decode-heavy / mixed | | +4.5% / +8.3% | +4.7% /
+9.0% |
| Time in rounds over 3x the median after an admission, decode-heavy /
mixed | 3.9% / 10.1% | 0.6% / 1.2% | 0.6% / 0.9% |
| CUDA-graph reserve per GPU | 5.22 GB | 5.22 GB | 7.19 GB |
| Prefill graph capture at startup | 154 s | 153 s | 296 s |

A padded single request costs nothing measurable (below), so `1 2 4`
buys no latency for 1.84 GB less KV cache per GPU and 140 s more
startup.

**Padding takes rows.** Each padded request holds one token row, so a
forward within three tokens of its bucket's top replays the next bucket
up, and a single request that fills the largest bucket (a full
8192-token chunk) replays the ordinary graph. Single prompts of 4000 to
12000 tokens measured within 2% of `1` with `4`, as with `1 4`, which
replays them as one request.

## Serving

GB200, one fresh server per arm, `--max-model-len 16384 --max-num-seqs
64`, old default (`1`) against this PR's. Idle: median of 24 trials of N
requests of random tokens sent together, `max_tokens=1`. Mixed: 64
streaming requests in flight (1024 in, 512 out; each finished request is
replaced). Then GSM8K (400 questions) at temperature 1.0.

| | Qwen3.5-35B-A3B-FP8 + MTP, TP4 | Qwen3.5-35B-A3B-FP8, TP4 |
Qwen3.8-Flash-Next-NVFP4 + MTP, attention TP4 + MoE EP4 |
|---|---|---|---|
| 1 request x 256 tokens (ms) | 18.0 → 18.2 | 15.1 → 15.1 | 35.2 → 34.9
|
| 2 requests x 256 | 51.4 → 19.5 | 47.2 → 16.6 | 86.7 → 44.0 |
| 4 requests x 256 | 53.2 → 22.1 | 47.6 → 18.3 | 88.1 → 44.2 |
| 3 requests x 1024 | 51.6 → 29.9 | 46.1 → 33.9 | 88.5 → 50.9 |
| 4 requests x 2048 | 76.4 → 75.6 | 71.3 → 70.3 | 146.5 → 125.1 |
| Streamed chunks, mixed | +8.3% | +2.1% | +6.4% |
| Time in rounds over 3x the median, mixed | 10.3% → 1.5% | 10.1% → 7.8%
| 18.0% → 11.6% |
| GSM8K | 96.5% → 95.8% | 96.3% → 96.5% | 96.8% → 97.5% |
| KV cache per GPU | unchanged | unchanged | unchanged |

Rounds of more than four requests keep the ordinary route (a third of
the rounds in the run without speculation). Greedy outputs (four
prompts, one at a time) match the old default's on both Qwen3.5 servers
and on three of four on Qwen3.8: its other prompt has 15 tokens, which
with three padded rows replays the 32-token bucket instead of the
16-token one, and the target's GEMMs round that first token differently.
Qwen3.8's mixed run includes one 0.6 s round, a CuTe DSL recompile in
the hyperconnection mix that both arms hit once while serving.

KDA: the Kimi-K3.1 recipe already captures `1 64` and measured 40% to
55% lower time-to-first-token for 2 to 64 concurrent prompts.

## Test Plan

All on GB200.

- [x] pre-commit on the changed files.
- [x] `test_prefill_graph.py` (unset resolves to 4, or `max_num_seqs`
below it), `test_kda_prefill_graph_cache.py` (unset per bucket: 4,
capped by a 2-token bucket), `test_cudagraph_probe_arena.py` (the boot
floor covers the default count, capped by `max_num_seqs`),
`test_cudagraph_probe_ladder.py`, `test_prefill_graph_admission.py`,
`test_gdn_prefill_capture.py`, `test_mamba2_prefill_capture.py`,
`test_cudagraph_memory_projection.py`,
`test_cudagraph_capture_sizes.py`, `test_drafter_prefill_graph.py`,
`test_prefill_history_embedding.py`: 285 passed.
- [x] Qwen3.5-35B-A3B-FP8 without speculation at `--max-num-seqs 2`:
starts, captures two requests per bucket, serves.
- [x] The serving runs above.

Signed-off-by: Nicolas <nperrin.ai@gmail.com>
2026-11-15 17:00:11 -05:00
Nicolas Perrin e42bfdcf4a perf(spec): split Qwen4-Exp MTP extend rounds and drop the step-0 graphs (#3437)
## Summary

An earlier change split Qwen3.5 MTP's extend round into a draft KV
writer over every row (one graph over a 2048-row tile) and decode steps
from each request's last row. This PR gives Qwen4-Exp's MTP head the
same split, which also needs its QSA index keys, and removes the step-0
graphs per (prefill bucket, request count) that the split replaces.

- **Write locations come from the model.**
`SplitExtendDraft.begin_split_round(ctx, rows)` runs eagerly once per
round and returns each row's draft cache write locations; the KV
writer's graph stages them tile by tile beside the token, position and
hidden rows, zero for a padded row. Qwen3.5 returns its attention write
slots. Qwen4-Exp returns its attention write slots and the QSA indexer's
per-row logical positions, request indices, compressed-cache and
recent-cache slots (`QSAIndexer.split_round_locations`, the extend
layout a narrowed step 0 builds), and resets the draft steps' staged-key
tags, which a narrowed step 0 resets otherwise.
- **Qwen4-Exp's writer.** `write_draft_kv` runs the MTP input fusion,
the hyper-connection mix and the QKV projection over every row, writes
the KV (`PagedAttention.write_kv_at`) and writes and compresses the
index key (`QSAIndexer.write_split_keys`, the kernels the extend step
runs). A compression group that spans tiles reads its earlier members
from the recent cache, as the target's chunked prefill does. Step 0 then
runs from each request's last row as a decode step one below the
frontier and selects that row's top-k, as the narrowed step 0 does for
it.
- **Removed:** the step-0 graph series (`prefill:drafter-step0`),
`--enable-drafter-prefill-graph` with its `ServerArgs` and executor
refusals, `supports_breakable_draft_extend`, and `extend_graph_plan`'s
request-count argument. Drafts that do not split (Eagle3 and the rest)
run step 0 eagerly and replay the decode steps, as they did by default.
A draft that carries its top-k across steps
(`index_share_for_mtp_iteration`) keeps step 0 whole and its decode
steps eager, as before.

## Serving

GB200, Qwen3.8-Flash-Next-NVFP4 + MTP (a chain of 3), attention TP4 +
MoE EP4, `--attention-backend trtllm --moe-backend flashinfer_trtllm
--kv-cache-dtype bfloat16`, one fresh server per arm on one node. 64
streaming requests stay in flight (each finished request is replaced)
and every streamed chunk is timestamped. Decode-heavy: 256-token
prompts, 2048 tokens out, a 192 s window. Mixed: 1024 in, 512 out, a 122
s window. Then GSM8K (400 questions) at temperature 1.0. On main,
Qwen4-Exp under TP runs step 0 eagerly in every prefill round (its
step-0 graphs ran on one rank only).

| | main | this PR |
|---|---|---|
| Streamed chunks per second, decode-heavy | 4631 | 4770 (+3.0%) |
| Streamed chunks per second, mixed | 4036 | 4321 (+7.0%) |
| Time in rounds over 3x the median round after an admission,
decode-heavy | 14.7% | 11.0% |
| Time in rounds over 3x the median round after an admission, mixed |
24.7% | 21.2% |
| p90 round after an admission (ms), decode-heavy and mixed | 51.5 and
39.5 | 40.3 and 37.0 |
| GSM8K accuracy and acceptance length | 97.3% and 3.22 | 97.5% and 3.21
|
| CUDA-graph reserve per rank | 6.57 GB | 6.45 GB |
| Drafter captures at startup (probe + full) | 23 s | 25 s |

Greedy outputs (four prompts) repeat exactly across fresh servers of
each build, and this PR's differ from main's on two of the four. Drafts
alone move them on main too: main without speculation matches its
chain-of-3 output on one prompt of four, and main with a chain of 2 on
none. A different draft moves where each verify window starts, and the
target's attention and linear-attention rounding for a token depends on
that; the split's step 0 runs as a decode step, so its drafts can round
differently from a narrowed extend step 0's.

Most of the remaining stall time is the target's own: rounds that admit
several requests run its linear-attention layers at eager breaks (the
`ordinary` prefill route), which capturing 1, 2 and 4 requests per
bucket addresses in a follow-up.

## Test Plan

All on GB200.

- [x] pre-commit on the changed files.
- [x] `test_drafter_prefill_graph.py`: the plan (decode steps up to 16
requests, a split draft's writer tile), the capture order the probe
pairs its readings with, the static buffers' sizing, which rounds replay
the decode steps (none of a split draft's), and a split round with two
location tensors leaving the narrowed round's window and cache.
- [x] `test_drafter_prefill_graph_cuda.py`: decode steps replayed after
an eager step 0 leave the eager round's window and cache; replayed split
rounds (past one tile, padded tiles, one to four requests, cached
prefixes, mid chunks) leave the narrowed eager round's; the writer
refuses target hidden rows of another width or dtype and lands after a
Host load into the draft cache.
- [x] `test_qsa_backend.py`: a split round's index keys written in
zero-padded tiles leave the raw, compressed and position caches one
write leaves, across two requests and a compression group spanning tiles
(real QSA kernels).
- [x] `test_cudagraph_memory_projection.py`,
`test_cudagraph_probe_arena.py`, `test_executor_rebind.py`,
`test_dspark_proposal.py`, `test_dispatch_autotune.py`,
`test_cudagraph_capture_sizes.py`, `test_prefill_graph.py`,
`test_paged_attention_prologue.py`, `test_nextn_shard_filter.py`,
`test_qwen_draft_fp8_projection.py`,
`test_prefill_history_embedding.py`,
`test_dflash2_speculative_sampling.py`. `test_qwen4_exp.py` and
`test_decoder_input_embedding.py` fail the same 24 tests on main (8-rank
groups, `enable_fp8_attn_proj`, `PrefillGraph`'s
`memory_saver_adapter`).
- [x] The serving and greedy runs above.
- [ ] CI's Qwen3.8-Flash-Next-FP8 GSM8K eval (TP2, MTP chain of 3,
greedy) runs the split path.

Signed-off-by: Nicolas <nperrin.ai@gmail.com>
2026-11-14 21:20:15 -08:00
Zhewen Yu 16a2b307c8 perf(k3.1): support prefill graphs and mixed batches for KVP8 (#3270)
Stacked on #3184.

## Summary

Two changes that speed up Kimi-K3.1's KVP8 prefill on gfx950 for agentic
turns: a few thousand new tokens on a 32K–140K cached prefix. Mixed
batches are opt-in; by default only the prefill-graph admission changes.

- **Prefill graphs.** K3.1's padded prefill replay was admitted on
NVIDIA only, and a KVP history prefill turned prefill capture off. The
replay is now admitted on every platform and capture stays on under a
KVP history prefill: the history gather and attention run in the eager
break, and the captured segments are narrowed to live rows. Deployments
cap capture with `--prefill-graph-max-tokens`, since chunks of 4K new
tokens and up are faster eager.
- **Mixed batches** (`--enable-mixed-batch`). Aggregated DCP refused
mixed batches, so every KVP prefill chunk stalled the resident decodes
for its whole forward. A mixed round now runs its KVP extend rows and
DCP decode rows in one forward, each through the path it already takes:
the extend rows get the KVP history-prefill plan, and the padded replay
keeps the decode rows in the eager break.

## Results

Kimi-K3.1 KVP8; throughput is tokens per second per GPU:

| Change | Measurement | Before | After |
|---|---|---:|---:|
| Prefill graphs | AgentX fast mode, C16, 8x MI355X (throughput and
interactivity) | 7,073 / 54.1 | 7,155 / 56.7 |
| Prefill graphs | AgentX fast mode, C32, 8x MI355X (throughput) |
11,052 | 11,333 |
| Prefill graphs | 131K cached prefix, 512 new tokens, 8x MI350X (ms) |
274 | 115 |
| Prefill graphs | 131K cached prefix, 2K new tokens, 8x MI350X (ms) |
300 | 205 |
| Mixed batches | 8K-token chunk riding with 16 decodes, 8x MI355X (ms)
| 507 | 364 |
| Mixed batches | AgentX, C32, 3600 s, 8x MI355X (throughput and
interactivity) | 15,147 / 45.2 | 15,470 / 46.9 |

- The 8K-chunk row compares a mixed round without and with the
history-prefill plan; the same chunk alone takes 364 ms. The mixed-batch
runs used prefill graphs and EAGLE3.1 drafts.

## Test Plan

On gfx950:

- [x] KVP8 prefill graphs on MI350X (131K cached prefix): greedy outputs
match eager.
- [x] K3.1 and DSA runtime tests for the touched modules on MI350X, and
the 8-GPU Iris attention and MoE-tail tests.
- [x] Mixed batches on MI350X: DCP page-metadata, rank-setup,
server-args, DSA query-shard and K3.1 runtime tests.

---------

Signed-off-by: Zhewen Yu <zhewenyu@amd.com>
Signed-off-by: Yu-Zhewen <zhewenyu@amd.com>
2026-11-14 19:14:45 -08:00
lipanpan03andFC-Li cff8263007 fix(runtime): release persistent buffers during memory-saver sleep (#3407)
## Summary

Memory-saver sleep releases model weights and KV pages, but persistent
attention metadata and shared scratch buffers can remain allocated. Put
attention/backend initialization, runtime inputs and history,
decode/prefill graph metadata, and workspace growth in a separate
CPU-backed pool under the existing `weights` tag. Sleep/wake preserves
their contents and virtual addresses, including when model parameters
use `discard`.

- Resolve owner-specific `named_region` aliases (`executor_inputs`,
`runtime_states`, `attention_state`, `workspace`) to the shared
CPU-backed pool. Nested aliases reuse that pool across adapter
instances. The executor owns the adapter and passes it to prefill
graphs; neither depends on the KV arena's adapter.
- Include already-created split NCCL communicators before their first
collective, without initializing unused groups.
- Drain device work before suspend, clear allocator caches, and restore
the previous CUDA stack limit before resuming communication. Skip NVIDIA
driver stack operations on ROCm. Clear cuBLAS workspaces only in CUDA
eager mode; retain graph-referenced workspaces.
- Coordinate NCCL-containing release and resume through the existing
attention-DP gates. A peer's completed KV release cannot authorize a
later NCCL release, and NCCL resume waits for every DP engine's request.
Ordinary memory regions retain their local resume behavior.
- Preserve explicitly supplied `NCCL_CUMEM_ENABLE` and
`CUDA_MODULE_LOADING` settings. Keep the existing communication backend
and worker lifecycle. No native NCCL or PyTorch changes.
- Update affected executor configurations and all prefill-graph
constructor fixtures, including capture-failure coverage, plus
memory-policy and event-loop documentation.

## Validation

- `cargo test --locked -p tokenspeed-control --lib --test serving`:
**167 unit tests and 63 serving tests passed**. These use the real C++
scheduler with scripted device/DP boundaries, including the two NCCL
transition regressions; they do not execute GPU collectives.
- Focused CPU runtime checks: **142 passed, 10 skipped**, plus 34
passing subtests. Covered prefill/drafter graph behavior, all 16
executor-capacity parametrizations, cache-state allocation, executor
rebind, CUDA/ROCm cleanup guards, named allocation regions, cached
split-communicator discovery, and stack restoration. The 10 skips
require CUDA.
- CPU harness limitation: real runtime classes, CPU metadata routines
and the built scheduler were used; unavailable GPU kernel/compiler and
profiling imports, GPU capacity queries, and optional vision/audio
dependencies were isolated. This is not CUDA allocation or ROCm
execution evidence.
- A broader `DeviceHandle` run reached an unchanged control-plane guard
test that fails on the local CPU-only PyTorch 2.9 build: CUDA factory
initialization raises before its dispatch guard. That case is not
counted as passing; the full runtime suite is not claimed to pass.
- `pre-commit run --all-files` and `cargo fmt --all --check`:
**passed**.
- `cargo clippy --locked -p tokenspeed-control --all-targets -- -D
warnings`: **passed**.
- Full distributed CUDA sleep/wake, physical-memory reclamation,
captured graph replay, and suspend/resume followed by the first
collective on a cached split communicator remain **pending GPU
validation**. Measure physical device memory rather than inferring
reclamation from retained virtual Tensor storage.

---------

Signed-off-by: lipanpan03 <41904587+lipanpan03@users.noreply.github.com>
Signed-off-by: FC-Li <robert_lexis@163.com>
Co-authored-by: FC-Li <robert_lexis@163.com>
2026-11-14 15:00:27 +08:00
Nicolas Perrin df646c9c9f fix(kimi): answer stores_capture_taps from the multimodal wrappers (#3378)
## Summary

Since #3233, a block drafter asks its target `stores_capture_taps(ctx)`
before it arms the capture sink. Only `BaseCausalLM` answers, so a
DFlash or DSpark draft over Kimi-K3, Kimi-K3.1, or Kimi-K2.5 (whose
served model wraps the language model) fails in decode warmup:

```
AttributeError: 'KimiK31ForConditionalGeneration' object has no attribute 'stores_capture_taps'
```

- `KimiK3ForConditionalGeneration` and `KimiK25ForConditionalGeneration`
delegate `stores_capture_taps` to their language model, as they already
do for `set_dflash_layers_to_capture`. In encoder-only mode, where there
is no language model, a wrapper raises a clear `AttributeError` instead.

## Validation

- `test_draft_target_wiring.py`: new tests check that every registered
model accepting DFlash capture layers answers `stores_capture_taps` (on
main the check lists the Kimi wrappers), that both wrappers answer for
their language model, and that an encoder-only wrapper refuses with
`AttributeError`. All 7 new tests fail on main; the file passes here (91
tests) on GB300.
- Kimi-K3.1-Pro TP8 on two GB300 nodes with eight DSpark drafts (with
#3365, which fixes the next failure on the same path): the server boots
and decodes (batch 1 at 1.10 ms per token with synthetic acceptance); on
main it dies in decode warmup with the error above.

---------

Signed-off-by: Nicolas Perrin <nperrin.ai@gmail.com>
2026-11-12 21:28:45 -05:00
Nicolas Perrin aca58193cf fix(dspark): write context KV over every verify row in the draft's pages (#3365)
## Summary

Since [#3352](https://github.com/lightseekorg/tokenspeed/pull/3352),
Kimi-K3.1-Pro with DSpark fails in decode warmup with `ValueError:
positions and loc must hold 64 rows` (from
`mla_latent_norm_rope_scatter`, reached through
`DFlash.on_target_capture`).
[#3352](https://github.com/lightseekorg/tokenspeed/pull/3352) moved
block-drafter context writes onto the draft's own router and read its
decode window. A DSpark draft attends one row fewer than the target
verifies, so that window is one row per request narrower than the rows
the target wrote, and each request's rows start one position late. Mixed
rounds lose a row per decode request the same way.

- `DFlash._context_cache_locations` serves both the capture-tap write
and the fallback write. Each decode request's verify rows are resolved
from its first verify position over the draft's own table with
`draft_write_locations_uniform`; extend rows keep the draft's extend
span.
- One path for DFlash, DFlash2, DSpark, and K3 DSpark. The router, the
registry, and the token-sink retention are unchanged.
- `docs/design/unified_path.md` states the verify-width rule in the
"Context writes" bullet.

## Validation

- New tests in `test_dflash2.py` cover decode and mixed DSpark rounds
over a real `CacheGroupRouter` at the width a DSpark draft gets. They
fail on main (two rows short and shifted; the decode request's first row
missing) and pass here. Mutants caught: the
[#3352](https://github.com/lightseekorg/tokenspeed/pull/3352) window
lookup, the query width, a late start, and a missing extend offset.
- Tests that build drafter state by hand get the two new buffers and the
router method; what they assert is unchanged. The 20 drafter and DSpark
test files give the same results as main on GB300.
- Kimi-K3.1-Pro TP8 on two GB300 nodes, DSpark with 8 drafts: the server
boots; batch 1 decodes at 1.09 ms per token with synthetic acceptance;
GSM8K with real acceptance scores 195 out of 200.

---------

Signed-off-by: Nicolas Perrin <nperrin.ai@gmail.com>
2026-11-12 21:27:42 -05:00
Nicolas PerrinandStanley Winata c485a46a13 feat(model): day 0 support for Inkling 2 Small (#3371)
Day 0 support for Inkling 2 Small. Serving recipe:
`docs/recipes/models.md`.

## Summary

This change adds end-to-end serving support for Inkling 2 Small, the
1T-parameter NVFP4 sibling of Inkling: a block-scaled mixture-of-experts
model with a vision tower, a native multi-token prediction drafter,
relative-bias attention with per-head norms plus an output gate and
sink, depth-wise attention residuals in the style of the Kimi K3
attention residuals, and structured JSON answers. The pull request spans
checkpoint admission, the model definition, new kernels, engine wiring,
and grammar support.

The motivating problem is fidelity. The checkpoint defines its
arithmetic precisely: quantization denominators, rounding points, where
the activation cap is applied, how residuals are mixed, and how the
drafter scores continuations. Serving must reproduce that arithmetic bit
for bit while staying batch-invariant and CUDA-graph safe. Each
subsystem in this change exists to hold one of those boundaries, which
is why the pieces hang together as a single design rather than a
collection of unrelated kernels.

## The checkpoint contract

- **NVFP4 experts.** Per-token quantization with denominator 1536.
Per-16-element E4M3 scales are chosen between 4 and 6 by mean absolute
error, with ties keeping 6. FP4 values round ties to even. The outer
scale is `(x_amax * w_amax) * rcp(1536 * den)` with the denominator
owned by the checkpoint. The capped SwiGLU applies its gamma cap inside
the expert, in BF16, before the second quantization, and uses the
reference PTX sigmoid and tanh approximations on NVIDIA so results match
the reference byte for byte.
- **MXFP8 key-value cache.** E4M3 values with per-32 UE8M0 scales on
128-token pages. The new SM100 decode kernel carries a fifth warpgroup
that dequantizes keys and values to BF16 in shared memory, bit-for-bit
identical to the BF16 kernel.
- **Relative attention.** Query, key, and relative-position heads are
L2-clipped, values are RMS-normed, and attention produces FP32 outputs
with log-sum-exp. The split-reduction epilogue applies `(o *
sigmoid(gate)) * sigmoid(lse - sink)`, where the gate and sink are rows
of the query projection.
- **Depth residuals.** Attention residuals mix layer outputs with an
FP32 online softmax. Each candidate is an FP32 sum of up to three terms,
rounded once before the rounded value is mixed.
- **Native drafter.** The multi-token prediction drafter reproduces the
checkpoint's draft arithmetic exactly, including FP64 folds in the
Markov head and seeding proposals from the last accepted verify row, and
loads only the weight files belonging to its NextN shards.
- **JSON framing.** Answers are structured JSON, and framing is enforced
in the Rust grammar layer rather than by prompt convention.

## Design invariants

Four rules unify the diff.

1. **Bit-exact arithmetic with explicit rounding boundaries.** `l2_clip`
rounds to the input dtype before the FP32 token scale; the softcap is
byte-for-byte; log-scaling tau gains a `torch_order` mode; FP32 logits
are multicast as two BF16 words. New small precision ops
(`rmsnorm_precision`, `add_rmsnorm_precision`, `l2_clip`,
`rel_mha_gate_sink`, `rel_mha_head_norms`) exist because approximate
fusions cannot hold these boundaries.
2. **Batch invariance and CUDA-graph safety.** Per-element arithmetic
does not depend on batch composition: `skinny_mm` always tiles 32 rows;
block-scaled GEMMs sum each element's reduction blocks in the same order
under every tile configuration; the decode split-KV count is a runtime
argument of a single compiled kernel chosen from an SM-count heuristic;
buffers are preallocated outside capture.
3. **Programmatic dependent launch, trigger first.** Kernels release
their dependents before waiting when their early reads are older than
the predecessor, with the ordering documented per kernel; the expert
GEMMs stream weights before their wait.
4. **Registry-trait kernel selection.** Traits such as `fp32_output`,
`gate_sink`, `head_dim`, and `page_size` select the FP32 attention,
MXFP8 decode, portable Triton, or gfx950 Gluon implementations without
model-side policy, and also drive graph-capture compile guards.

Communication primitives make tensor, sequence, and expert parallelism
work without extra synchronization: Lamport mailboxes whose slots are
armed as BF16 `-0.0` and published as `+0.0` across two parities, row
reduce-scatter plus `MulticastRows` symmetric buffers for
sequence-parallel layers, and a fused all-reduce feeding the decode ring
convolution with early release.

## What changes, area by area

### Attention

- FP32-output registrations for prefill, extend, and decode, including
`fa4_rel_mha_decode_with_kvcache_fp32_mxfp8_kv`.
- A new SM100 cute-dsl decode kernel: 128-token pages, head dim 128, 512
scale bytes per page per KV head, the dequantizing fifth warpgroup
described above, log-sum-exp output, and the gate and sink fused into
the split-reduction epilogue.
- `rel_mha_head_norms`: one launch clips the query, key, and relative
heads, RMS-norms the values, optionally fuses the relative projection
(bit-for-bit with a matmul up to 128 tokens, otherwise a GEMM),
optionally stores native or MXFP8 KV, and optionally fuses the decode
ring convolution.
- The `rel_mha_gate_sink` epilogue kernel; portable Triton attention
with uniform scalar splits, log-sum-exp, programmatic dependent launch,
and windowed splits up to 16; `HeadNorm.round_before_rope`.

### Key-value cache

`dequant_gather_kv_mxfp8` materializes BF16 scratch pages plus a page
table for the extend path; heterogeneous cache capacity and a native
draft workspace are added.

### Mixture of experts

- `block_scaled_moe_routes` implements the quantization contract above.
Implementations: a torch oracle, portable Triton, Blackwell `dot_scaled`
(SM100 through SM103), SM103 tiled routes using the vendored TRT-LLM-gen
kernels under `thirdparty/flashinfer/trtllm_block_scaled_bmm` (tile size
equals the mean routes per expert rounded to a power of two between 8
and 256, with in-place weight rewrite via
`block_scaled_moe_routes_process_tensor`), and gfx950 Gluon.
- `block_scaled_topk` performs sigmoid-plus-bias selection with
logsigmoid weights and ExpertDispatch replica tables.
- The router projection runs in FP32: `cute_dsl_ll_bf16_router` up to 16
tokens, then `skinny_mm`, then `mm` with FP32 output.
- `fold_slots` computes the per-token FP32 slot-order sum starting from
+0.0 and rounded once into `[T, 1, H]`, so the expert-parallel
all-reduce carries `[T, H]` instead of `[T, K, H]`; it can publish into
a mailbox or a tensor. `zero_remote_routes` supports the all-reduce.

### Communication

`mailbox.py` implements the Lamport mailbox all-reduce described above,
including the CuTe-DSL projection publish path; `row_reduce_scatter`
computes FP32 rank-order sums of listed rows and pairs with
`MulticastRows`; `allreduce_sconv` fuses the workspace all-reduce into
the decode ring convolution.

### Short convolutions

`inkling_ring_sconv` accepts dynamic weights `[T, heads, W]` that are
rounded to the input dtype on load and added to the static taps in FP32,
a finite FP32 `output_scale` applied after the residual, and `[T, S, D]`
slot-row inputs with MoE route rows folded on load. `token_range`
supports sequence-parallel prefill, where a rank computes its share yet
writes every request's ring and published window. A mailbox variant
polls, sums, and re-arms slots, and `select_decode_config` captures the
tuning.

### Attention residuals

`attention_residual_partials`, `attention_residual_combine`, and
`attention_residual_mix` implement the FP32 online-softmax depth mixes,
with optional value normalization, `round_mix`, and RMSNorm output; the
single-launch mix kernel covers the full hidden width, and
`ResidualShare` handles the sequence-parallel case.

### GEMM

`mm` gains an FP32-output contract; `triton_skinny.skinny_mm` handles up
to 32 BF16 rows with weight-major split-K, an in-order final fold, one
rounding, batch invariance, and programmatic dependent launch prefetch;
gfx950 adds `gluon_mm_bf16_fp32`.

### Native drafter

Native draft arithmetic (Markov head FP64 folds, `capped_logit_sum`,
`gated_tanh_recurrence`, `projected_gated_tanh_recurrence`),
`gather_last_accepted_rows` to seed proposals from the last accepted
verify row, exact weight-file selection for NextN shards
(`CheckpointFileSelection`, with `weight_files` plumbed through the
loader, prefetch, and update-from-disk paths), slot state for the native
block drafter, context-limit speculative padding, side-stream cache
writes, and the inkling2_mtp context KV writer registration.

### Model and loading

Config values for the checkpoint, draft, and multimodal towers with norm
and softcap validation, a multimodal pad substitute, weight-manifest
admission, expert shard loading, loader precision handling, and the
vision encoder requirement.

### Multimodal

The vision tower (position-embedding geometry, rotary, bidirectional
segments, preprocessing), image scatter, encoder contract validation,
and the encoded-offload rule that a consumed image cannot supply a fresh
same-hash request.

### Grammar (Rust)

ts-control gains `JsonFraming` and `MessageBoundary` with admission
refusal ("JSON responses require a closed message or an empty assistant
text header"); ts-grammar gains `JsonStringGuard`, which keeps protocol
tokens out of JSON strings; the guarded matcher and
`traverse_draft_tree` operate under the guard; `compile_framed_answer`
and the ts-host wiring complete the path.

### AMD gfx950

BF16-to-FP32 GEMM, a row-major block-scaled expert GEMM for NVFP4 and
MXFP8, and a HIP tanh softcap.

### Adjacent models

muse_spark_iris gains `round_before_rope`; dspark gains
`sample_from_anchor` from checkpoint metadata,
`_prepare_proposal_features`, and MHA leaf buffer widths; packed-output
device-to-host decode and verify equivalence for the single-request
case; a capturable grammar host in `join_post_sampler`; a shared
multi-CTA KV counter buffer in the flashinfer integration; prep-tape
widening. The removed `_set_graph_state_write_indices` tests reflect the
metadata refactor.

## Compatibility

- Existing BF16 attention paths are retained and remain the selection
when the `fp32_output` trait is not set.
- MXFP8-KV decode is gated to SM100, BF16, 128-token pages, and head dim
128, with the gather path as fallback.
- `round_before_rope` is plumbed through existing models without
behavior change.
- The removed dp_sampling and zero_output_prefill tests correspond to
the metadata refactor, not a behavior regression.

## Testing

The change adds coverage for byte-for-byte kernel contracts against FP64
host oracles and the checkpoint reference kernels, drafter decode and
verify equivalence, quantization manifest admission, vision encoder
contracts, and JSON grammar fixtures.

---------

Signed-off-by: Stanley Winata <68087699+raikonenfnu@users.noreply.github.com>
Signed-off-by: Nicolas Perrin <nperrin.ai@gmail.com>
Co-authored-by: Stanley Winata <68087699+raikonenfnu@users.noreply.github.com>
2026-11-12 16:05:59 -08:00
Bangtian Liu e43c28a7c2 feat(monokernel): Muse Spark single-request decode monokernels on gfx950 (#3233)
Decode monokernels for the Muse Spark Open (Quark MXFP4) checkpoint and
its DFlash2 draft, on `main`. This PR builds
on the monokernel framework of
[#2662](https://github.com/lightseekorg/tokenspeed/pull/2662) and its
`--decode-monokernel` switch, and extends the framework to a
tensor-parallel group. It needs no other PR: the
checkpoint already serves on `main` (with
[#3118](https://github.com/lightseekorg/tokenspeed/pull/3118) to
[#3123](https://github.com/lightseekorg/tokenspeed/pull/3123)). This PR
serves decode steps with 1 request (an 8-row
verify). The kernels take the row count as a compile-time parameter up
to two requests' rows (16), but the runtime
serves one request a launch (`MAX_REQUESTS = 1`); serving 2 requests in
one launch comes in a follow-up PR, on top of
this one.

## Summary

A decode monokernel runs one decoder layer's decode step as one
persistent Gluon launch. Every block of the layer
becomes a stage on fixed CTAs, and stages hand values to each other
through tagged mailboxes, not through kernel
boundaries. On the regular path, one Muse Spark layer is about twenty
kernels.

The checkpoint's routed experts are MXFP4 with MXFP4 activations. The
attention, output, pooler and post-expert
projections are BF16. Layers 0 and 61 keep BF16 experts (they stay on
the regular path, below). The KV cache is FP8. The serving layout is
attention TP8 and
MoE TP8 and EP1 on 8 GPUs, so every layer exchanges data between GPUs
inside its launch.


**1. The framework for a tensor-parallel group**
(`tokenspeed_kernel_amd/ops/gfx950/monokernel/`, no model)

- Peer regions across ranks: `Plan(world=..., peers=...)`, `put_peer`
and `load_peers`. The scratch lives on Iris's
symmetric heap, so a region has the same offset on every rank. A peer
region holds two copies, and the launches pick
one by a parity that alternates every launch: a rank one launch ahead
cannot overwrite the copy that a slower rank
  still reads. Puts and polls of a peer region use system scope.
- Plain words and one flag (`store_words`, `raise_flag`, `load_words`,
and their `_peer` forms): for bulk hand-offs,
the producer stores plain words, waits until its stores land, and then
puts one tagged flag. A tagged pair carries
  32 bits of payload in 64, so this halves the bytes of a bulk hand-off.
- A stuck poll: a poll that waits more than about 59 s (realtime clock)
writes what it waited for (tag, address,
observed value, clocks) and traps. This is the production deadlock
diagnostic: `--monokernel-stuck-record-dir`
keeps the records in files that outlive the process, and
`muse_spark.stuck_report` names the earliest stuck stage. The directory
must be on tmpfs (for example `/dev/shm`): the record file is registered
as GPU-visible host memory, and a disk filesystem's periodic writeback
of its pages stalled decode for 1-2 s every few seconds; startup refuses
any other filesystem. A deadlock stops the process with a GPU error
instead of a hang, and a rank whose
  host submits a launch seconds late only stalls its peers.
- `code_warm.py`: a launch's code (about 92-100 KB) is larger than the
64 KB instruction cache. A short task reads the
  launch's own code into every XCD's L2 at the start of the launch.
- `docs/design/monokernel.md`: a tensor-parallel group runs one plan,
and the deadlock rule holds across ranks; a
model's boundary layers may keep the regular code; a draft model follows
the same one-switch rule.

**2. Muse Spark layer monokernels**

- One launch per decoder layer for layers 1 to 60: attention (sliding
with RoPE, or full), the output projection and
its reduce-scatter, the norms and residual gate, routing (router, top-8,
the slot table of distinct experts), the
pooler, the MXFP4 experts and the layer boundary. Sliding and full
layers are two binaries.
- The expert weights are read with non-temporal loads: they are read
once per step, and default loads let them evict
the code, the KV cache and other reused data from L2 and the last-level
cache.
- A launch ends with the next layer's q, k and v projection on CTAs that
are free after the experts, so the next
launch's attention starts at once. The launch count stays one per layer.
- The kernel boundary is
`tokenspeed_kernel.ops.model.muse_spark.monokernel`, as for Qwen3.8. The
runtime imports
nothing from `tokenspeed_kernel_amd`: it passes the regular MoE's
prepared expert tensors and apply-kernel name, and
the gluon shim takes their storage and refuses a layout the kernel does
not read.
- Standalone benches launch the layer, the draft layer and the draft
head over the Iris heap, standing in for absent
ranks on runs with fewer than 8 GPUs:
`tokenspeed-kernel/benchmarks/amd/gfx950/muse_spark/monokernel/`.

**3. DFlash2 draft monokernels**

- One launch per draft layer, one for the draft head, and one for the
draft context write after a verify.
- A block drafter's KV cache stays BF16 unless the drafter's attention
backend is `trtllm` (the draft monokernels read
  and write the cache in place).

**4. `--decode-monokernel` for Muse Spark**

- `DECODE_MONOKERNEL_ARCHITECTURES` gets the Muse Spark architecture.
- Startup packs every layer from 1 to 60 and the draft after loading,
and fails with each piece that cannot be packed,
  with its reasons. The switch never serves a layer without its kernel.
- Layers 0 and 61 keep the regular path, a stated exception to "every
layer or none": they hand over to the
embedding and the LM head, and fusing them changes their summation
order, a numerics change that needs accuracy
evidence first (TODO in the seam). Their BF16 experts therefore have no
monokernel stages in this PR.
- Only attention TP8 with MoE TP8 and EP1 is served; other MoE splits
keep the regular path.
- The monokernels' Iris heap buffers (the mailbox scratch and the draft
taps) are reserved before the heap exists and added to its planned size;
models without them keep main's heap. With the DFlash2 draft at TP8,
startup reserves 17.1 MiB for the layer monokernels and 22.0 MiB for the
draft's (heap 801.3 MiB, against main's 762.2 MiB); without
`--decode-monokernel` the heap is byte-identical to main's.
- `--disable-dflash-incremental-projection` is not needed: the seam
derives whether the target stores the draft's
  taps.
- The DFlash draft keeps the target's dense TP layout at attention DP 1
(as [#3314](https://github.com/lightseekorg/tokenspeed/pull/3314) does
for `main`):
[#3303](https://github.com/lightseekorg/tokenspeed/pull/3303)'s
replicated draft MLP is needed only under attention DP. With it, the
drafter hands the draft's first layer a partial whose sum is the
embedding, since that layer reduces its input over the dense group;
summing the vocab shards in the lookup as well would start the draft
from the embedding summed once per rank (8x at TP8), which lowered
speculative acceptance. The final norm reduces the last layer's partial,
fused with the norm as the layers' input norms are.
- Prefill, and decode steps of 2 or more requests, keep the regular path
in this PR. The kernels read the regular
  path's paged KV cache in place.
- The tiled copies of the BF16 projections take about 4.3 GB per GPU,
and the draft head's copy of the LM-head shard
  about 0.4 GB; both are made before the KV cache is sized.

## Results

Checkpoints (Hugging Face Hub revisions): Muse Spark Open 816B A42B
Quark MXFP4
@ `17159bf7d2e7d6c79961efe1530ff40aea608ae2` and Muse Spark Open DFlash2
@ `46c90f412549c472941a68382d91a99e5e6372a0`.

GSM8K (the CI task below, 8x MI35x, `--decode-monokernel`): 125 of 128
correct in every CI run on this branch, at 758 to
775 tokens per second mean decode per request (the task gates the rate
at 0.9 of 770).

Muse Spark Open (Quark MXFP4), 8x MI355X, attention TP8, MoE TP8 and
EP1, FP8 KV cache, DFlash2, a recorded multi-turn agentic workload at
concurrency 1 (`--max-num-seqs 1`, 1800 s):

| | Time per output token | Mean decode tokens per second per request |
Time per decode step (32-96k context) | Accept length | Accuracy |
|---|---|---|---|---|---|
| Regular path (same build, switch off) | 2.485 ms | 402 | 7.82 ms |
3.643 | AIME26 28.0 of 30, NIAH 9 of 9 |
| This PR, `--decode-monokernel` | 2.081 ms (-16.2%) | 480 (1.19x) |
6.43 ms (-17.8%) | 3.621 | AIME26 28.0 of 30, NIAH 9 of 9 |

Both rows are one build of this branch on `main` 1d4d48ab4, one run each
on the same host, with only the switch
different; the build also carried the 2-request follow-up, which a
concurrency-1 run does not use. A second run with
the switch gave 2.023 ms, and a second host's pair gave 2.036 and 2.475
ms (-17.7%). The decode step is 16-18% faster in
every context bin. Accept length moves by a few percent between runs,
because the workload sends no sampling seed; the
decode step time does not depend on it.

The output is not bit-identical to the regular path, because the kernels
add FP32 partial sums in a different order.
Greedy text moves off the regular path after a median of about 20
tokens; task accuracy is the same.

The server command is the CI task's (below) with `--max-model-len
1048576`, `--cudagraph-capture-sizes 1 2 3 4 5 6 8
12 16 32 64 --max-cudagraph-capture-size 64`, `--enable-prefix-caching`,
`--parser symphony`,
`--enable-speculative-sampling`, `--seed 42` (the requests carry seed 42
too), `--init-expert-location trivial`,
`--all2all-backend none`, `--enable-metrics` and
`--disable-dflash-incremental-projection` (that build predates the seam
deriving it), with `DEBUG_HIP_GRAPH_BATCH_SIZE=1
DEBUG_HIP_FORCE_GRAPH_QUEUES=1`. These rows served the MXFP4
checkpoint at revision `c7bc74fd64371315a091bc15f9723882eead0dc1`.

## Design measurements

The measurements behind the main placement and batching choices (8x
MI355X, one launch, warm unless noted):

- Full-attention splits: 128 instead of 64 at 200k keys, 192 -> 156 us a
full layer.
- Attention rows split over two warp groups at 8 rows and 340k keys:
167.5 -> 156.2 us a full layer.
- Plain words and one flag instead of tagged pairs: target attention
partials ~8 us, draft attention partials ~18 us
  (draft layer 105.9 -> 91.2 us).
- The slot table built once instead of on all 256 CTAs: ~5 us of each
ex1 task's prelude.
- exr (K sums plus MXFP4 requantization once): 8 rows, sliding at 100k
109.0 -> 104.4 us, full at 200k 145.5 ->
  143.0 us.
- ex2's first weights issued after ex1's products: full layer at 200k
148.6 -> 145.9 us.
- The draft head's best-16 passes as runtime loops instead of unrolled:
131.7 -> 119.5 us a step (cold).
- Code warm: without it a launch loses ~20 us, ~30 more after a binary
switch.
- Warm stage (next layer's QKVG into the MALL): GSM8K with DFlash2, 9.15
-> 8.86 ms a round.

## Test Plan

- Kernel tests: the monokernel tests pass on 8 MI355X GPUs (525 passed,
6 skipped by design) and on MI350X; the
  one-GPU kernel CI job passes. They include:
- every stage against a torch reference of the regular path's math, with
tight tolerances;
- each launch's layer outputs against the commit before it, bit for bit,
on sliding and full layers and at 16-95
    distinct experts;
  - the inline-asm hazard gate of #3118 on these kernels;
  - recompile guards, and a stuck poll stops its process.
- Runtime tests: the seam's packing, startup failures and routing. The
full one-GPU runtime suite fails only the tests
  that fail on `main` too (platform-gated), on MI355X and MI350X.
- Replays: greedy replays of recorded turns of the workload give 37,829
identical tokens with bit-identical logprobs, and seeded
sampled replays give 20 of 20 identical prompts (build vs build), on the
build of the table above.
- The draft's first-layer input: a multi-GPU test (2, 4 and 8 GPUs,
sharded and whole embedding) checks that the first layer's reduce yields
the embedding exactly once; seeded sampled replays against the build
before `main`'s #3303 give 20 of 20 identical prompts with identical
acceptance.
- Serving safety: the monokernel launches are compiled at startup,
before the first request; with the JIT monitor on,
none compiles while serving. Under this recipe the regular path still
compiles some kernels after the first request
(startup warm-up gaps on `main`, the reason the CI task runs the check
at `warn`). A soak of the layer kernels on
this branch, with the peer parity check on, ran 600 launches per CUDA
graph at 1 and 2 requests, sliding and full,
warm and cold, with no stuck poll (and more than 8,000 launches without
a failure on the earlier build).
- CI:
`test/ci/perf/muse-spark-mxfp4-monokernel-gsm8k-single-request-mi35x.yaml`
serves this recipe with
`--decode-monokernel` on an MI35x 8-GPU runner and runs the first 128
GSM8K test questions one at a time (greedy,
up to 2048 tokens, `reasoning_effort` low), gating accuracy at 0.88; its
decode-rate reference is set from that
runner's runs. `test/ci/ut/ut-tokenspeed-kernel-amd-8gpu.yaml` runs the
monokernel kernel tests on an MI35x 8-GPU
  runner.
- The agentic table's server runs, with and without
`--decode-monokernel` (command above).

---------

Signed-off-by: Bangtian Liu <liubangtian@gmail.com>
2026-11-12 09:18:43 -08:00
Nicolas Perrin 9146d8b5d8 fix(prefill-graph): hold a break's frozen-dataclass tensors weakly when it has scalars (#3349)
## Summary

Kimi-K3.1-Pro at TP8 on two GB300 nodes, launched with the recipe's
flags (prefill CUDA graphs on by default), runs out of memory while
capturing the prefill graph ladder. Bisected to #3279.

A breakable capture holds a break's tensor args as non-owning views, so
later captures that share the pool reuse their blocks. A frozen
dataclass got that treatment only when every field held a tensor or
`None`. KDA's `KdaOutputNorm` (from #3279) carries a float epsilon, so
it was held as is. Each KDA layer's break then kept its output gate, a
view of the layer's whole input projection, alive in every captured
bucket: about 6.7 GB per sampled 8K-token bucket. The CUDA-graph memory
reserve came out too small, and the ladder capture ran out of memory.

- `_weak_ref_arg` now copies every frozen dataclass with each tensor
field held as a non-owning view and every other field kept as is, as
loose scalar args already are.
- Docstrings of `_record_break` and `break_point` updated to match.

## Validation

- `test_tensor_bundle_break_args_reuse_pool` gains a bundle with a float
field. It fails on main and passes here; `test_breakable_cuda_graph.py`
passes (31 tests) on GB300.
- Kimi-K3.1-Pro TP8 on two GB300 nodes, DSpark with 8 drafts, the
recipe's flags:
- main: the sampling captures keep 6 to 12 GB each, and the boot runs
out of memory capturing the ladder;
- this change: free memory stays flat across the sampled buckets (76.8,
76.8, 76.7 GB), the reserve is 9.1 GB, all 56 buckets are captured in
11.7 GB, and the server comes up;
- batch 1 TTFT 0.10 s, and decode at 1.09 ms per token, the same as main
with prefill graphs off.

---------

Signed-off-by: Nicolas Perrin <nperrin.ai@gmail.com>
2026-11-12 09:53:04 -05:00
Guoyuan Lin 22b9db337c feat(dflash): support dflash for PD (#3303)
<!-- 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? -->
2026-11-11 22:09:41 +08:00
AN Qiandlongcat-ia-team 14b1c38b19 fix(prefill): support eager history-dependent embeddings (#3267)
Prefill graphs reject models that require request-token history even when only their embedding needs it. Add an opt-in `HistoryEmbeddingModel` protocol on the inner model: ordinary forward and graph replay share `compute_input_embeddings(input_ids, ctx, *, request_token_history)`. An initialization helper resolves one `_compute_input_embeddings` callable, selecting that method or a plain embedding adapter. Replay calls it before padding and lands its output in the existing static buffer.

The graph stores no separate `_embed_tokens` or `_embedding_model` aliases. Capture uses zero embeddings for every model, without invoking embedding computation or touching live history; buffer metadata comes from `inner_model.embed_tokens.weight`. `BaseCausalLM` is unchanged. History-dependent models without the protocol remain eager. Multimodal replay is gated by actual history requirements, so implementing the shared method alone does not disable it. The DP multimodal guard follows `is_multimodal_active`.

Tests compare a small model through real `BaseCausalLM.forward()` and CUDA Graph replay for plain embeddings, shared embeddings without history, and history-dependent embeddings. They check exact output/history agreement across changing slots, token counts, padding and recapture, supplied-embedding passthrough, and model-owned decode embeddings. Capture fixtures provide the buffer they exercise; unused fixture initialization has been removed.

Validation on `a264ca439`: `pre-commit run --all-files` passed. On H200, 145 tests and 36 subtests passed with no failures across `test_prefill_history_embedding.py`, `test_prefill_graph.py`, `test_prefill_graph_admission.py`, `test_cudagraph_probe_ladder.py`, `test_gdn_prefill_capture.py`, `test_kda_prefill_graph_cache.py`, and `test_mamba2_prefill_capture.py`. There were 18 expected skips: 12 GDN cases unavailable with the selected kernels and 6 native CuteDSL KDA cases requiring SM100/SM103. Full-model and multi-GPU acceptance were not run.

Signed-off-by: aqni <72963199+aqni@users.noreply.github.com>
Co-authored-by: longcat-ia-team <312376714+longcat-ia-team@users.noreply.github.com>
2026-11-11 05:38:13 -08:00
dongjiyingdjy f7126b4f1d fix(cache): wait for Host load-backs in every cache accessor and per captured prefill-graph segment (#2812)
## Summary

With Host L2
([#2762](https://github.com/lightseekorg/tokenspeed/pull/2762)), a
prefix hit is loaded back layer by layer on a copy stream. Before the
forward touches a layer's cache, it waits for that layer inside the
pool's accessors (`layerwise_load_tracker.wait_for_layer`). This PR has
three parts:

1. **Fence fixes (commits 1-3).** On main, three accessors touch
Host-loaded bytes without that wait. If the copy lands late, it
overwrites rows the forward has just written, or the forward reads stale
bytes. Nothing reports an error. The three are:
   - the GQA draft context write (DFLASH, DSpark);
   - GLM-5.3-Flash index-K and KPool access;
   - the Inkling K and V short-conv checkpoint read.

Each one now waits for its layer. With an injected H2D delay, all three
reproduce on main (17e5853ec) on both copy paths. Two more gaps this PR
first fixed, the MLA draft context write and the DSA index-K write, are
fixed on main by
[#3015](https://github.com/lightseekorg/tokenspeed/pull/3015)
(Kimi-K3.1), which took the same change and its two fence tests; this PR
no longer carries them. Commit 7 makes one more reader wait: the
per-token-head branch of `get_mla_kv_buffer`. No caller reads stale rows
through it today (the DeepSeek-V3 prefix replay writes the layer, which
waits, before it reads the history), so that one is defensive.

**When they bite.** On a default GB300 deployment the three are latent.
A prefill-graph replay (forwards up to 8192 tokens by default) first
waits for the whole Host load, and on the default `kernel` copy path
that wait also covers the draft's layers. They are live wherever a
forward with a load runs eagerly: forwards larger than the largest
captured bucket (for example with `--chunked-prefill-size 16384`),
DeepEP MoE (which turns the prefill graph off) and `--enforce-eager`.
The GQA draft write (commit 1) is live on replays too with
`--kvstore-io-backend direct` or without layer-ready PTX: there the
copies record one event per layer, and the target's last event does not
cover the draft. Commit 4 drops the whole-load wait for Kimi-K3, so from
then on its draft context write relies on `set_mla_kv_buffer`'s own wait
(on main since #3015).

**What goes wrong.** A late copy overwrites fresh rows only when the
Host hit ends inside a page that the new tokens share; a stale read
needs only a Host hit. A race on a draft's cache (commit 1, and the MTP
draft path of commit 2) lowers the acceptance rate but not the output,
since the target verifies every drafted token. A race on the target's
cache (commits 2-3) changes the output silently.
2. **Per-segment wait for prefill-graph replays (commit 4).**
[#2762](https://github.com/lightseekorg/tokenspeed/pull/2762) made
`PrefillGraph.replay` wait for the whole Host load before the first
segment. So every replayed forward that carries a load pays for the full
H2D. Now the capture records, for each captured segment, the highest
layer its cache accesses wait for. At replay, each segment waits only
for that layer, which restores the layer-by-layer overlap of the eager
path. A pool class has to opt in. Only the Kimi-K3 pool does, after an
audit; every other pool keeps the whole-load wait.
3. **Host load-backs and restores ordered behind the forwards in flight
(commit 5).** This is the reverse direction of the fence fixes: a copy
must not land before an in-flight forward's write to a block that an
abort freed. On main, a plan's copies waited for the forwards in flight
only when the plan also copied or zeroed pages. Now every plan with
cache ops orders its loads and restores behind them.

The fence fixes come first because the per-segment wait depends on them.
On the Triton copy path, the whole-load wait also covered the draft
view's layers, by accident. A K3 replay that skips it relies on the
draft context write's own wait, which main has since #3015.

Without Host L2, replays are unchanged: there is no tracker and no wait.
The only change is the startup order (see below).

## What changes

### Fence fixes (commits 1-3 and 7)

| Commit | Accessor | Path that hits it during a load | On main, when
the race fires |
|---|---|---|---|
| 1 | `MHATokenToKVPool.set_kv_buffer` and the MXFP8 override | GQA
DFLASH and DSpark draft context writes | A late copy overwrites the
context rows on a tail hit |
| 2 | `HybridGlm53FlashTokenToKVPool.get_index_k_buffer` (so
`get_kpool_buffers`) | GLM-5.3-Flash KPool prefill top-k read and
prefill write, for the target and the MTP draft | The top-k scores stale
keys, and the write is overwritten |
| 3 | `HybridInklingTokenToKVPool.kvconv_checkpoint_buffers` | Inkling K
and V short conv, which runs before the layer's first wait | The conv
starts from a stale checkpoint |
| 7 | `MLATokenToKVPool.get_mla_kv_buffer`, per-token-head branch |
DeepSeek-V3 chunked prefix history read with per-token-head MLA KV | Not
reached stale today: the layer's prologue write waits first. The reader
now waits itself |

- Each accessor now waits for its layer (by the view's own layer id),
either directly or by taking its plane from an accessor that waits
(`get_key_buffer`, `get_index_k_buffer`).
- A draft view has its own tracker, and its layers land after all of the
target's on both copy paths. So no wait in the target forward covers a
draft layer. On main, the draft window was closed only by a replayed
target graph on the Triton copy path, and only by accident.
- `KPoolRuntime.ensure_prefill_plan` needs only the plane's shape, and
now reads it from the arena field. So the first DSA layer no longer
waits for its load just to plan.
- `test/runtime/test_l2_layerwise_fences.py` (on main since #3015 with
the MLA draft and DSA index-K cases) gets 17 more cases: 13 for commits
1-3, and 2 each for commits 5 and 7:
- Each case builds the pool through the recipe, arena and factory, with
the real `HostCacheExecutor` and `DeviceHandle`.
- It holds the load stream back and runs the model's accessor sequence.
It then asserts that the copy had not landed yet, and compares bytes
once it has.
- One case reads Inkling layer 1 with a tracker driven by hand, where
only layer 1's copy is held back. It catches a wait on the wrong layer.

### Per-segment wait for prefill-graph replays (commit 4)

- **Capture.** During a breakable capture,
`LayerwiseLoadTracker.wait_for_layer` enqueues nothing. Instead it calls
`BreakableCapture.wait_before_segment(wait, layer)`.
- `segment_waits` runs parallel to `segments`. A captured segment gets
one (wait, highest layer) pair per tracker. An eager break gets none,
because it waits by itself.
  - No model or attention backend changes.
- **Replay.** `BreakableCapture.replay` runs a segment's noted waits
before the segment.
- Layers land in order on both copy paths. DMA records one event per
layer on one stream. In the Triton kernel, every CTA copies the layers
in order, and the last CTA releases a layer's flag.
- So waiting for the highest layer covers every lower layer the segment
touches.
- **Opt-in per class.** The opt-in is the class attribute
`CachePool.layer_accesses_wait_for_load`, False by default.
`__init_subclass__` resets it to False on any subclass that does not set
it in its own body.
- Only `HybridKDATokenToKVPool`, the Kimi-K3 target pool, sets it. The
audit behind that covered every access a K3 replay makes: TP8 with KVP8
and DCP8, ordinary and inline captures.
- In captured segments, latent rows are written through
`kv_write_target`, and KDA State is read and written through
`get_component`.
- In eager breaks, the history is read through `get_mla_kv_buffer` or,
when the history is dealt over KVP owners, through the gather's
`get_key_buffer`. All of these wait.
- In a mixed round with speculative decoding, the verify rows also reach
State through pointer tables built once, with no wait per layer (verify
seeding, replay descriptors, the post-acceptance commit). That relies on
a Host load-back filling only freshly granted pages of an extending
request, never a decoding request's committed State page. The
declaration's comment states this: a load into running requests' pages
would void the declaration.
- Its subclasses do not set it: GLM-5.3-Flash, and Kimi-K3.1's
`HybridKDADSATokenToKVPool`
([#3015](https://github.com/lightseekorg/tokenspeed/pull/3015)), whose
replays keep the whole-load wait.
- **Guard.** `PrefillGraph.capture` records the tracker it captured
against. `replay` relies on the noted waits only when two things hold:
  - the pool's class declares the attribute;
- the pool's current tracker is the one the graphs were captured
against.

Otherwise it waits for the pool's whole Host load before the first
segment, as on main. It then skips the noted waits (`noted_waits_done`),
because that wait already covers them. A wrong startup order therefore
costs the overlap but cannot reopen the race.
- **Startup order.** The trackers must exist at capture time. So
`build_device_side` now builds the retraction pool request and the Host
cache executor before graph capture (`_capture_serving_graphs`): after
the probe rebind and the DFLASH warmup, instead of after the capture. A
forward reload's recapture
([#3168](https://github.com/lightseekorg/tokenspeed/pull/3168)) runs
with the executor built, so its captures note the waits too.
- The construction reads nothing the capture produces, and starts no
thread.
  - It allocates only small Device tables beside pinned Host memory.
- Its sizing collectives on the CPU group run at the same point on every
rank.
- On current main the construction also warms the restore copies
([#2851](https://github.com/lightseekorg/tokenspeed/pull/2851)) when the
retraction snapshot pool is on and the kvstore input and output backend
is `kernel` (both defaults): a one-block D2H and H2D round trip that
leaves the Device bytes as they were. So that warm-up now runs before
the capture too. A server boot covers it (see Validation).
- **Log.** The ordinary prefill capture line reports how many segments
run behind per-layer Host-load waits: 24 of 187 on Kimi-K3 with Host L2;
0 without Host L2 and on every undeclared pool, whose replays take the
whole-load wait.
- **Eagle drafter prefill graphs**
([#2980](https://github.com/lightseekorg/tokenspeed/pull/2980)) are
breakable captures too, so their captures now note waits on the draft
tracker. Their replays keep main's waits: step 0 after the draft pool's
whole load (`wait_for_all_layers`), the decode steps after step 0, both
with `noted_waits_done=True`.
- **Docs.** `cache-concepts.md`, `event-loop.md` and `unified_path.md`
are updated.
- **Draft after a declared K3 replay.** The replay no longer waits for
the draft layers' copy, on either copy path.
- The DSpark and DFLASH2 context write (`set_mla_kv_buffer` on the draft
view, which waits on main since #3015) and the draft forward wait on the
draft tracker themselves.
- The DFLASH fused writers run only in decode-only rounds, and those
carry no load.
- **Tests.** In `test_kda_prefill_graph_cache.py`, the fixture's owner
captures through `PrefillGraph.capture` after the Host cache executor
exists, as a server does, so the capture records the tracker.
- A new replay test runs on the real K3 pool with the executor's
tracker. It captures a KDA State read, a break, and an MLA page write
plus a second State read.
- The load releases its layers in order, by flag with the Triton copy
path's waiter or by event (the DMA protocol), and holds back only the
MLA layer's copy.
- The first segment and the break must finish before that copy lands,
and the written rows must survive it.

**Why opt-in.** Per-segment waits are only as complete as the accessor
waits behind them. Commits 1-3 and #3015 fixed five accessors that
missed the wait.
- Other engines keep finding the same kind of gap: a consumer the
per-layer wait missed, or a graph replay that skips it. vLLM and SGLang
have each reported several instances.
- These races stay hidden in normal runs because the copy usually wins.
They reproduce reliably only with an injected H2D delay.
- So the safe default stays the whole-load wait. A pool class switches
to per-segment waits only after the accesses its replays make have been
audited.

### Load-backs and restores behind the forwards in flight (commit 5)

- **The race.** An abort frees a request's blocks at once, while that
request's forward may still be in flight. (Since
[#2956](https://github.com/lightseekorg/tokenspeed/pull/2956), a request
whose PD transfer is in flight parks until the transfer stops instead.)
The next plan may grant such a block to a Host hit or a restore.
- The copies start behind the default stream. On main, that stream
waited for the execution stream only when the plan copied or zeroed
pages.
- A plan with neither is, for example, a pure-attention Host hit whose
new tokens fit its tail block, with nothing else growing. Its copy could
land before the old forward's write, which then overwrote a row of the
loaded block.
  - So the race needs an abort in the same window. It is rare.
- **The fix.** The device handle now makes the default stream wait for
the execution stream before it submits a plan's cache ops to the Host
cache. So loads and restores start after the forwards in flight in every
plan.
- Plans without cache ops, and deployments without Host L2, are
unchanged.
- Models with State, Kimi-K3 among them, already had this wait: every
admission zeroes or copies a State slot.
- **Docs.** The comments, `cache-concepts.md` and `event-loop.md` said
that a load-back lands on zeroed pages. Load-back destinations are never
zeroed, and they now state the actual order.
- **Tests.** `test_a_load_lands_after_the_forwards_in_flight`
(`test_l2_layerwise_fences.py`, both copy paths) holds a forward back on
the execution stream while a plan with only a load fills the block that
forward writes. The plan-order tests in `test_device_handle.py` now see
the wait.

## Validation

GPU results are from one GB300 GPU. The branch is now seven commits on
main at e2b673adc (rebased 2026-11-10; commits 1 and 3 of the previous
nine landed on main with #3015 at the 2026-11-09 rebase). The results
below ran on the previous head b8750bd7f (nine commits on fe58cfcd4)
unless marked otherwise; there, and in the tables, commits are numbered
as before: 1 MLA draft write, 2 GQA draft write, 3 DSA index-K write, 4
GLM-5.3-Flash, 5 Inkling, 6 per-segment wait, 7 load-back order, 9
per-token-head read. "Also fails on main" means the same failure on that
branch's base.

**GPU rerun on the rebased head a931bc848** (2026-11-10): the 16 most
affected GPU test files pass here and on main e2b673adc, with no
failures on either. The fence file passes 21 of 21 here; on main it has
only the 4 cases from #3015.

**GPU rerun on the previous head c5f6031a1** (2026-11-09, on main
89dffb754):
- Making declared pools take the whole-load wait fails both cases of the
new K3 replay test.
- A Kimi-K3 boot in the boot-smoke configuration below ran the restore
warm-up before the capture, with 24 of 187 segments behind per-layer
Host-load waits.
- A 100K-token Host hit then replayed a prefill graph with per-segment
waits on all 8 ranks, and its 32 output tokens equal the Device hit's. A
200K-token run was inconclusive: two Device hits of the same request
already differed at output 14.

**Fence repro (main, then commit 6).** Each race is reproduced by
holding the load stream back with an injected delay. Each cell shows the
result on the Triton and DMA copy paths, which agreed in every case.

Rerun on main 17e5853ec (2026-11-02): this branch's
`test_l2_layerwise_fences.py` fails all 21 cases there, each at its
final byte check (commits 1-5, 7 and 9, both copy paths), and passes all
21 on this branch in the same run on the same GPU.

| Gap | main, as is | main + manual wait at the fix site | commit 6 |
|---|---|---|---|
| K3 MLA draft context write | FAIL | PASS | PASS |
| GQA draft context write, bf16 | FAIL | PASS | PASS |
| GQA draft context write, MXFP8 | FAIL | PASS | PASS |
| DSA index-K write | FAIL | PASS | PASS |
| GLM-5.3-Flash KPool read, target | FAIL | PASS | PASS |
| GLM-5.3-Flash KPool read, draft | FAIL | PASS | PASS |
| GLM-5.3-Flash KPool write | FAIL | PASS | PASS |
| Inkling K and V conv checkpoint read | FAIL | PASS | PASS |

**Mutations.** Each mutation fails exactly the tests it should, and the
unmutated control passes:
- On b8750bd7f, reverting the code of commit 1, 2, 3, 4, 5, 7 or 9 fails
exactly that commit's fence tests (2, 4, 2, 6, 3, 2 and 2 cases), on
both copy paths. The unmutated file passes 21 of 21.
- On commit 6:
- Reverting the code of commit 1, 2, 3, 4 or 5 fails that commit's tests
on both copy paths.
- Commit 1 failing on both paths shows that, after a K3 replay, the
draft context write is ordered only by its own wait.
- An Inkling fence on layer 0 instead of the accessed layer fails the
later-layer test.
- These commit-6 mutations each fail the expected replay tests
(tail-page write, inline KDA State read, or the earlier revision's
segment-selection test):
    - letting subclasses inherit the declaration;
    - dropping the declaration check;
    - dropping the per-segment wait loop;
    - dropping the tracker-identity check.
- On the final code before the rebase, making declared pools take the
whole-load wait fails both cases of the new K3 replay test (flag and
event release), at the check that the first segment and the break finish
before the held-back copy lands. The other 50 tests of the file pass,
and the unmutated file passes 52 of 52.
- Without commit 7's wait, its new fence test fails on both copy paths.
- Without commit 9's change, its new test fails on both copy paths: the
read returns the page's old bytes.
- Two more mutations ran on an earlier revision of commit 6 and failed
the expected tests:
  - noting the last layer instead of the highest;
- building the executor after the capture (caught by the boot-order
test).

**Test suites**
- **Per-commit CPU checks** on the rebased head: pre-commit passes on
all seven commits. (Before the rebase: C++ unit tests (1104), CPU-only
Python tests (344), pre-commit and the commit-message check on all
nine.)
- **On b8750bd7f**, one process per file:
- **Changed and new GPU tests**, plus the layerwise-load,
breakable-graph, probe-arena, MLA KV buffer, device-handle, K3 and
GLM-5.3-Flash cache-pool and retraction-image executor tests (12 files):
425 passed, 1 skipped (needs a second GPU).
- **25 other test files that use the changed code** (DSA, GLM-5.3-Flash,
Inkling, K3, DSpark, DFLASH2, MXFP8 KV pool, Dots3, cache setup,
FlashMLA DCP, other models' prefill captures and more): 537 passed, 11
skipped (FlashMLA cases that need SM90), 9 failed. The failures also
fail on main.
  - **The rest of the runtime test set** (12 files): 214 passed.
- **`test_l2_layerwise_fences.py` at each commit** passes: 2, 6, 8, 14,
17, 17, 19, 19 and 21 cases on commits 1 to 9.
- **Commit 7's plan-order tests** in `test_device_handle.py` pass, and
so does the whole file (48 passed, 1 skipped).
- **Commit 8** skips the flag-released case of the new K3 replay test
where layer-ready flags are unavailable. They need NVIDIA PTX; other
GPUs release layers by events, and the event-released case still runs
there.
- **The failures that also fail on main**, with the same test IDs:
`test_zero_output_prefill.py` (8 cases) and
`test_glm53_flash_cache_spec.py` (1 case). The six DFLASH boot cases of
`test_device_handle.py` and the `test_mxfp8_kv_pool.py` case, which
failed on the old base, pass after the rebase.

**End-to-end correctness gates.** All gates run Kimi-K3 NVFP4 on GB300
with the prefill graph on. Each compares a Host hit against a Device hit
bit for bit. All four ran on commit 6. Commit 7 adds only a stream wait
that Kimi-K3 plans already had (every K3 admission zeroes or copies a
State slot), so it does not change these runs. It is covered by its unit
tests and mutation check.

| Gate | Result |
|---|---|
| Fused, KVP8 and DCP8, Triton copy path, EAGLE3 MLA draft. Covers an
aligned page, a tail page, a State checkpoint, and an 8-request window
batch replayed while every prefix loads from the Host | 14 of 14 bitwise
equal, cold controls 4 of 4. The capture logged 187 segments, 24 of them
behind per-layer Host-load waits |
| Prefill, KVP8 and DCP8: the KV sent to decode after a Host hit vs a
Device hit, every page | 9 of 9 Host-loaded pages bitwise equal, cold
controls equal |
| Fused, forced retraction: write_back run twice, compared on requests
with matching chunking | No mismatch |
| Fused, delayed copies: the Host-vs-Device cells with a sleep before
every write-back copy, then before every load copy | 4 of 4 equal in
each mode, cold controls 2 of 2 |

The last three gates also passed earlier with commit 6 alone on top of
[#2762](https://github.com/lightseekorg/tokenspeed/pull/2762).

**Boot smoke on the previous head (b8750bd7f).** With commit 6, main's
restore warm-up
([#2851](https://github.com/lightseekorg/tokenspeed/pull/2851)) runs
before graph capture on a default boot. One server boot covered that
order: Kimi-K3 NVFP4 TP8, KVP8 and DCP8 with the DSpark draft,
write-through Host L2, the `kernel` kvstore input and output backend and
the retraction snapshot pool on (both defaults).
- On all 8 ranks the restore warm-up ended before the capture started.
The capture completed with 24 of 187 segments behind per-layer Host-load
waits, and the server reached READY.
- Short prompts were answered correctly. A ~100K-token conversation was
pushed out of the Device cache by 175 other ~100K-token prompts, then
asked again. The repeat hit 99,840 cached tokens, and its forward was a
prefill-graph replay with a Host load-back and per-segment waits on all
8 ranks. The answer was correct.
- All 181 requests returned HTTP 200, and the server log has no
traceback, assert, NaN or CUDA error.

## Performance

**Fence fixes.** No cost without Host L2, and none in rounds that carry
no load. In a load round, each fenced access adds one wait. See the
double waits under known limitations.

**Load-back order (commit 5).** One stream wait per plan that carries
cache ops, and only with Host L2. Kimi-K3 plans already waited there.

**Per-segment wait, microbenchmark (one GB300).**
- **Setup.** The benchmark uses the real Kimi-K3 TP8 hybrid pool (93
layers: 69 KDA, 24 MLA), with the real Host cache executor, tracker and
Triton copy path. It runs `PrefillGraph.replay` of a synthetic 93-layer
forward over an 8K-token bucket.
- MLA layers write their latent rows inside the captured segment, and
read them in an eager attention break.
- KDA layers read their State either in an eager break (ordinary
capture) or inside the captured segment (inline capture).
  - The GEMM width sets the forward time to about 138 ms or about 39 ms.
- **What a cell shows.** Each cell is the time a Host load adds to a
replay (median replay with the load minus median without, 40 replays
each). The same quantity for a no-wait reference is subtracted from it.
That reference is main with the whole-load wait removed: it is racy, and
serves as a lower bound. Each cell gives two values in ms: the
whole-load wait (main) first, the per-segment wait (this PR) second.
- **Code measured.** An earlier revision of commit 4 (then commit 6), on
top of [#2762](https://github.com/lightseekorg/tokenspeed/pull/2762). A
K3 replay runs the same code on this head.

| Host hit (load per rank, H2D alone) | Ordinary capture, 138 ms forward
| Inline capture, 137 ms forward | Ordinary capture, 39 ms forward |
Inline capture, 38 ms forward |
|---|---|---|---|---|
| 1 x 8K, KVP1 (169 MB, 1.9 ms) | +0.84, +0.10 | +0.34, -0.04 | +0.87,
+0.10 | +1.16, +0.71 |
| 1 x 64K, KVP1 (962 MB, 8.5 ms) | +3.41, -0.10 | +4.29, -0.18 | +5.30,
+0.15 | +5.39, +0.80 |
| 6 x 24K, KVP1 (2.4 GB, 20.2 ms) | +12.13, -0.09 | +12.00, +0.18 |
+13.32, +0.17 | +13.30, +0.95 |
| 1 x 8K, KVP8 (70 MB, 1.1 ms) | +0.31, +0.04 | -0.01, +0.22 | +0.38,
+0.18 | +0.51, +0.37 |
| 1 x 64K, KVP8 (169 MB, 1.9 ms) | +0.73, -0.02 | +0.54, +0.18 | +0.89,
+0.12 | +0.87, +0.27 |
| 6 x 24K, KVP8 (592 MB, 5.3 ms) | +1.28, +0.20 | +2.61, +0.31 | +3.29,
+0.12 | +3.34, +0.58 |

- **Main.** The whole-load wait exposes most of the H2D. It exposes less
than the H2D alone because the reference pays for the copy too: the copy
runs beside the GEMMs and slows them.
- **This PR.** The per-segment wait is at or below main in every cell
except inline 1 x 8K KVP8 at 138 ms (+0.22 vs -0.01). That difference is
within the noise: p10-p90 is 1.1-2.9 ms at that forward length.
- **Where the inline 38 ms column's remaining 0.3-0.95 ms comes from:**
- **Pure waiting.** The 24 noted waits cost about 3 us each, or
0.05-0.09 ms per forward.
- **The first wait.** In an inline capture the first segment also holds
the first MLA layer, so it waits for layer 3's copy: up to 0.8 ms on the
2.4 GB load.
- **The rest is not waiting.** With a load in flight, the reference's
inline segments run 1.2-1.6% faster than without one: 1553-1558 us per
late segment, against 1571-1579 us. Main after its whole-load wait shows
the same speed-up. This PR's segments run at the no-load rate whether or
not a load is present.
- **In ordinary captures,** this PR's waiting segments run as fast as
the reference's.
- **Open question.** The cause of the reference's speed-up is not
identified. It looks like a clock state of the whole forward rather than
a cost of the waits.

**End to end.** We ran a Kimi-K3 KVP8 and DCP8 prefill engine at
concurrency 768, with `--chunked-prefill-size 8192`, so every forward
replays a graph with its Host load. One run per arm, on the same nodes:
- whole-load wait: 14.55 requests per second;
- per-segment wait: 14.63 requests per second.

That difference is within run-to-run noise. Under KVP8 each rank loads
only one eighth of the KV pages, so the wait removed is small. This was
measured with commit 4 (then commit 6) alone, on top of
[#2762](https://github.com/lightseekorg/tokenspeed/pull/2762). The gain
should be largest where a rank loads a lot per forward (KVP1, attention
DP). That configuration has not been run end to end.

## Known limitations and follow-ups

- **Double waits on the Triton copy path (perf only, left as is).** Some
accesses wait for a layer that an earlier access in the same forward
already waited for.
- Each extra wait costs one stream wait plus one 1-CTA spin-kernel
launch. On the DMA path it costs only an extra event wait.
  - Where they happen:
    - DSA: index-K write, then the top-k read (2 per indexer layer).
- GLM-5.3-Flash KPool: prefill write, prefill top-k, decode calls and
`kv_write_target` (up to about 4-5 per DSA layer).
    - Inkling: kvconv, then the prologue (2 per layer).
- Drafts: the context write, then the draft forward (2 per draft layer).
  - Rounds without a load, and deployments without Host L2, pay nothing.
- **No end-to-end Host L2 run for the models of commits 1-3**
(GLM-5.3-Flash, Inkling, and the GQA DSpark and DFLASH drafts). These
races need a copy that lands after the access. The unit tests force that
with an injected delay. Commit 5's race (a block freed by an abort while
its forward is in flight, then granted to a Host hit in a plan with no
page copy or zeroing) has no end-to-end repro either; its unit test
forces it by holding the forward back.
- **A remaining gap for draft layers on the Triton path.**
  - The draft layers are no longer covered by a K3 replay.
- Today every round that carries a load accesses each draft layer
through a waiting accessor.
- If a load round ever skipped all draft access, a later round's draft
access would wait only on its own plan's load. This gap already exists
on the DMA path.
- **Startup.**
- The Host cache executor's small Device tables and streams now count
toward the capture's peak memory.
- `check_host_memory` now sizes the Host tiers before the pinned buffers
that the capture allocates.
- **Granularity.** A segment's wait is placed at its start. Work earlier
in the segment therefore waits for the segment's highest layer: the
previous layer's MoE, or the earlier KDA layers of an inline segment.
This is correct, but coarser than the eager path.

---------

Signed-off-by: Jiying Dong <87510204+dongjiyingdjy@users.noreply.github.com>
2026-11-11 13:47:28 +08:00
Nicolas Perrin b9623586f3 perf(dspark): shard the K3 draft's context projection and fuse its KV writes (#3276)
## Summary

After each target forward, the Kimi-K3 DSpark draft injects the accepted
context through `context_proj` and a per-layer KV write. Both were slow:

- `context_proj` was a replicated linear, so every rank streamed the
whole `[7168, 5 x 7168]` BF16 weight (514 MB) per step. It is now
column-parallel over the attention TP group, like DFlash's `fc`: each
rank projects its own share of the columns (the hidden size divided by
the TP size) and one small all-gather assembles the rows before
`context_norm`. Each output is still one full dot product; only the
GEMM's tile choice can change, so proposals can differ at near-ties. The
per-rank weight memory drops by the replicated share.
- `write_context_kv` ran about twelve launches per draft layer. The five
layers' KV GEMMs now write into one buffer, and one Triton launch
(`mla_latent_norm_rope_scatter`) applies the kv_a RMSNorm, the rope on
the k_pe tail and the cache write for every layer, with the per-layer
chain's arithmetic.

## Validation

- New `test_mla_latent_norm_rope_scatter.py` (bitwise against the
per-layer chain) and `test_kimi_k3_dspark_context_projection.py` (split
projection against the replicated one at TP 1, 2 and 4); the draft,
DFlash and KV-cache test files that import the touched modules pass on
GB300.
- Kimi-K3.1-Pro TP8 on two GB300 nodes, DSpark with 8 drafts at
synthetic acceptance 8, 512-token decode, nsys; time outside the target
forward per decode step (µs):

| batch | before | after |
|---|---|---|
| 1 | 1303 | 966 |
| 2 | 1425 | 1058 |
| 4 | 1533 | 1125 |
| 8 | 1790 | 1322 |
| 16 | 2505 | 1693 |

---------

Signed-off-by: Nicolas Perrin <nperrin.ai@gmail.com>
2026-11-10 18:17:58 -05:00
minedec 07f628c8d4 feat(lm-head): support tensor parallel heads across attention DP groups (#3098)
## Summary

- Support vocab-sharded LM heads under attention DP, including when
attention TP is greater than one. Set `--lm-head-tp-size` to configure
the head. Omitting it preserves the default layout.
- Deduplicate replicated attention rows before the LM-head GEMM. Skip
the input row exchange when the head TP group fits within one attention
TP group, where all peers already hold the same rows.
- For eligible greedy calls, reduce argmax candidates across vocab
shards before taking each DP group's rows. Use fused argmax with
ping-pong slots when supported, with packed-key AllReduce as the
fallback. Calls that need full logits still restore the full vocabulary.
- Share row preparation and GEMM between the logits and greedy paths.
Greedy token selection runs separately on the projected logits.
- Validate TP group alignment and replicated row counts. Preserve
narrowed MTP row counts through metadata construction and the LM-head
exchange, including Qwen3.5 and DeepSeek.
- Bound the multicast gather workspace by request and speculative
verification capacity. Use NCCL for larger batches and paths that
require a private full-vocabulary result.

## Performance

The AIME26 results below compare the default LM-head TP1 layout with
LM-head TP8 and were collected before the distributed argmax
optimization. Both configurations use DP4, attention TP2, EP8, MTP3,
MegaMoE, and the same full native build with FlashInfer 0.7.3.

Concurrency 1 uses 30 requests. Concurrency 16 and 32 use 60 requests
each. The measured runs completed without serving-time JIT compilation,
request errors, or observed server-side queuing.

| Concurrency | TP1 decode (tokens per second) | TP8 decode (tokens per
second) | Improvement |
| --- | ---: | ---: | ---: |
| 1 | 115.47 | 131.94 | +14.27% |
| 16 | 87.39 | 91.47 | +4.67% |
| 32 | 75.75 | 78.97 | +4.26% |

Decode throughput is the mean of the per-request reciprocal of TPOT over
natural-length completions. Output lengths and accuracy differed between
configurations.

| Concurrency | TP1 mean output tokens | TP8 mean output tokens | TP1
accuracy | TP8 accuracy |
| --- | ---: | ---: | ---: | ---: |
| 1 | 7,678 | 8,201 | 100.00% | 96.67% |
| 16 | 10,410 | 7,630 | 96.67% | 95.00% |
| 32 | 8,347 | 8,623 | 100.00% | 96.67% |

Separate one-output-token tests measured mean TTFT after two consecutive
JIT-free warmup rounds.

| Concurrency | TP1 mean TTFT (ms) | TP8 mean TTFT (ms) | Change |
| --- | ---: | ---: | ---: |
| 1 | 231.23 | 237.22 | +2.59% |
| 16 | 454.82 | 428.62 | −5.76% |
| 32 | 514.60 | 530.25 | +3.04% |

TTFT showed mixed results. It includes scheduling and response overhead,
and the tests allowed dynamic prefill batch sizes to differ.

## Test Plan

- Passed `pre-commit run --all-files`.
- Built all 24 native kernel groups, the scheduler, engine, and MLA.
Verified native module loading, SM103 cache availability, and TRTLLM MoE
entrypoints.
- Completed and independently checked all 12 measured AIME26 runs.
Verified request counts, unique indices, errors, JIT logs, and reported
metrics, then checked TP8 service health and generation.
- Validated FP32 and BF16 fused argmax and packed-key fallback on eight
GPUs before separating projection and token selection. Covered head TP2
and TP8, uneven and idle DP ranks, narrowed MTP row counts, consecutive
target and draft calls, and CUDA Graph replay.
- After the split, passed 58 CPU logits regression tests and six DP
cases with simulated collectives, covering greedy, full-vocabulary
fallback, and logits-only output on active and idle ranks. The known
logprob precision failure was excluded. The eight-GPU tests were not
rerun after the split.
- Added regression coverage for narrowed row counts and sizing-context
cleanup in Qwen3.5 and DeepSeek MTP. All 85 targeted tests passed.

---------

Signed-off-by: minedec <jiandong@lightseek.org>
2026-11-10 11:13:48 +08:00
Eric 885ede9ebc perf(spec): shorten the dflash2 draft step and keep sampling vocab-sharded (#3122)
## Summary

The DFlash2 draft step and vocab-parallel sampling. Stacked on #2893
(DFlash2), whose draft model and sampling path these commits change.

- **Take the block draft's small-row dense GEMMs off hipBLASLt**
(formerly #3051).
- Table entries for the draft's projection, QKV, selector, gate and up,
and down shapes at 8 and 16 rows. 0.8-2.5 microseconds lower per GEMM.
- **Fuse the vocab-parallel top-k around its all-gather** (formerly
#3052).
- `vocab_shard_topk` and `vocab_topk_merge`, two portable Triton ops,
replace about 25 launches per step. Greedy outputs byte-identical; 8.9 +
2.4 microseconds against 31 microseconds for `torch.topk` alone.
- **Project the block draft's context inline on a column-split `fc`**
(formerly #3053).
- The last captured tap runs the context projection and KV write on the
forward's stream, with `fc` column-split over attention TP; no auxiliary
stream. About 0.1 milliseconds lower per decode step.
- **Fuse the block draft's all-reduce with its residual RMSNorm**
(formerly #3054).
- `iris_lamport_residual_rmsnorm` reduces, adds the residual, and
normalizes in one launch. Reduced rows bitwise; 0.03-0.12 milliseconds
lower per step.
- **Keep the target's sampled logits vocab-sharded under TP** (formerly
#3055).
- Top-k routes select per shard and gather only packed (value, id)
pairs. Tokens and accept decisions bitwise; 100.5 → 47.0 microseconds at
8 rows after the LM-head GEMM.
- Startup warms `sample` and `verify` at both candidate counts (64 and
128), with and without grammar masks, so eager steps compile nothing
while serving.
- **Stream the DFlash2 draft's MLP, `o_proj`, and head weights in FP8**
(formerly #3056).
- `--speculative-draft-model-quantization fp8_weight_only` with
`gluon_gemv_a16w8_gfx950`; the MI355X Muse Spark recipe passes the flag.
Greedy acceptance -0.006 ± 0.012 tokens per step; draft step 863 → 793
microseconds at one request.

## Test Plan:

- CPU: the draft, sampling, FP8 weight-only, and vocab top-k runtime
suites 131 passed, 38 skipped; failures need a GPU.
- `pre-commit run --all-files` clean.
- GPU, validated earlier on identical PR content (8x MI355X): kernels
277 passed, Iris 2 passed, runtime 247 passed, 3 skipped.

---------

Signed-off-by: Eric Feng <Eric.Feng@amd.com>
2026-11-07 19:06:46 -08:00
Fan Yang 397fe7bee1 perf(spec): replay the Eagle drafter's prefill work from CUDA graphs (#2980)
## Summary

- Add `--enable-drafter-prefill-graph` (off by default). An Eagle chain
drafter records its work inside a prefill forward as breakable CUDA
graphs: step 0 per prefill token bucket at each exact request count, the
decode steps per request count. Attention, the QSA indexer and the
drafter's backend publications stay at eager breaks. Only the Qwen4-Exp
MTP head declares support (`supports_breakable_draft_extend`).
- Pure-extend rounds at a captured request count replay; MIXED rounds
and other shapes draft eagerly. The capture and the CUDA-graph memory
projection read one plan. A step-0 replay waits for the draft pool's
Host load, as the target's replay does.
- Startup refuses launches the graphs cannot serve: no chain drafter,
draft trees, speculative sampling, more than one rank, the prefill graph
off, or a draft model without support. With the flag off nothing
changes.
- Measured effect: on our benchmark stack, with separate single-GPU
(TP1) engines serving Qwen3.8-Flash-Next NVFP4 with MTP, this change and
the GDN-in-prefill-graph change (#2926), measured together, gave
+3.5-3.9% single-server throughput. The drafter graph alone was not
measured, and this PR head is not measured yet. The in-repo recipes for
the model are multi-GPU (TP4; TP2 on AMD) and cannot use the switch: it
is refused for TP > 1.

## Test Plan

- [x] CPU: `test/runtime/test_drafter_prefill_graph.py` (plan, capture
order, buffer sizing, the target's hidden-row spec, replay routing, flag
validation): 29 passed
- [x] CPU: 141 runtime test files (those importing the touched modules,
`test/runtime/execution`, and the Kimi-K3/KDA/DSA/DSpark tests) on this
branch and on main `876d100bd`: no new failures
- [x] `pre-commit run --all-files` (markdownlint skipped locally; it
only checks the AMD ops README)
- [x] GB300 (main `876d100bd` + this PR), 17 test files including
`test/runtime/test_drafter_prefill_graph_cuda.py`, the new case in
`test/runtime/execution/test_breakable_cuda_graph.py`, and captures that
do not pass `run_segments_while_capturing` (`test_kimi_k31.py`,
`distributed/test_dsa_dcp_k31_indexer.py` on 2 and 4 GPUs): 1040 passed,
27 skipped (real-checkpoint, gfx950, 8-GPU and torchrun cases)
- [ ] Real Qwen4-Exp MTP checkpoint
(`TOKENSPEED_DRAFTER_PREFILL_GRAPH_MODEL`) and throughput re-measurement
on this head (pending)

---------

Signed-off-by: Fan Yang <250624800+fanyang-real@users.noreply.github.com>
2026-11-07 00:18:24 -08:00
Fan Yang 2a5deee14a perf(gdn): capture Qwen4-Exp GDN layers inside prefill graphs (#2926)
## Summary

- Qwen4-Exp's composite attention backend now passes the prefill-graph
hooks to its GDN child, so captured prefills run the GDN layers inside
the graph instead of at eager breaks. This is on whenever Qwen4-Exp
prefill graphs are on; capture and replay are bit-identical to eager.
- With `--enable-state-checkpoint-in-forward`, forwards that write a
checkpoint stay inline too: one fixed checkpoint slot per request slot
and one shared float32 scratch. Without the flag, nothing extra is
allocated.
- `scrub_padding` (shared by the KDA, Mamba2 and GDN capacity layouts)
now zeroes only the padding rows.

## Performance

GB300, Qwen3.8-Flash-Next NVFP4, FP8 KV, AgentX agentic replay, 3600 s
per point, same nodes. Measured before the rebase onto current main; to
be re-measured on this branch.

| Setup | Without | With |
|---|---|---|
| Single server, c56 | 199.8k tokens per second per GPU, P90 40.3 |
206.9k, P90 41.8 (+3.5%) |
| PD 2P1D, c152 | 186.6k | 184.2k (noise) |

Host CPU time per 8192-token prefill forward: 152 -> 27 ms (single
server), 142 -> 34 ms (PD prefill). GSM8K 0.978.

## Test Plan

- [x] CPU: new `test_prefill_capacity_checkpoints.py` (5 passed);
related runtime tests match main
- [x] The padding scrub matches a masked-fill reference in the Triton
interpreter (91 cases, including a row past 2^31 elements)
- [x] `pre-commit run` (markdownlint skipped)
- [x] GB300: `test_gdn_prefill_capture.py`,
`test_kda_prefill_graph_cache.py`,
`test_gdn_state_checkpoint_in_forward.py` in our build of main plus our
open PRs (FlashInfer 0.7.2.post1 and 0.7.3): passed

---------

Signed-off-by: Fan Yang <250624800+fanyang-real@users.noreply.github.com>
2026-11-06 23:38:54 -08:00
Eric c3a53cbe44 perf(spec): drop redundant launches from each DFLASH decode step (#2893)
## Summary

- Before: each DFLASH (DFlash2) decode step ran four launches it did not
need.
- Now each is folded into a neighbor or dropped:
- `VocabParallelTopK` writes its global ids with one `torch.add(...,
out=...)` instead of a copy to FP32 plus an add.
- `fused_softcap` applies the logit scale itself, rounded to the logits'
dtype as the separate `mul_` did.
- `LogitsMetadata.from_forward_context` skips the tap concatenation
while `ctx.target_capture_sink` takes every tap; an idle forward is not
attached.
- `drafter_accept_lengths` clamps the decode rows of the clone in place
instead of a separate clamp and copy.
- Numerics: outputs, draft KV and accept lengths are bitwise unchanged.
- Applies to DFLASH decode steps. The softcap change reaches every
`LogitsProcessor` with both a logit scale and a softcap; the
accept-length change every drafter.
- Measured effect, graph replay on one MI355X, at 8 and 128 rows: top-k
ids 5.2 → 3.6 and 7.0 → 5.0 us, scaled softcap 5.6 → 3.6 and 33.8 → 29.8
us, the dropped concatenation 2.6 and 6.3 us; accept lengths 5.0 → 3.3
us.

## Test Plan:

- 8x MI355X at this PR's head on main `95ebe6197`:
- `test_sampling_rejection.py` and `test_sampling_triton.py`: 57 passed.
- Runtime `test_dflash2.py`, `test_dflash2_speculative_sampling.py`,
`test_speculative_sampling_args.py`, `test_draft_target_wiring.py`,
`test_vocab_parallel_topk.py` and `test_logits_processor.py`: 198
passed, 3 skipped.
- New tests compare packed ids, the scaled softcap and gathered TP
logits bitwise against the old sequence, check that an attached sink
stores no capture and that an idle forward is not attached (both fail on
the old code), and check the accept-length clamp.

Signed-off-by: Eric Feng <Eric.Feng@amd.com>
2026-11-06 17:11:07 -08:00
Stanley Winata bcd94c1f72 feat(monokernel): opt-in decode monokernels on gfx950 for Qwen3.8-Flash-Next-Quark-MXFP4 (#2662) 2026-11-06 12:56:38 -08:00
60875e9f34 fix(runtime): separate input token bounds from output vocabulary (#3104)
Keep `ModelConfig.vocab_size` as the runtime output vocabulary and
introduce `input_vocab_size` for input token clamps, n-gram validation,
and multimodal draft substitutions. Input-only prompt tokens reach the
embedding while sampling, grammar masks, and probability buffers retain
output bounds.

Checkpoint `vocab_size` sizes the input embedding; optional
`output_vocab_size` sizes the output head and falls back to the input
size when missing or null. Validate integer sizes and `0 < output <=
input`, verify the target model's logical logits width at startup, and
retain the output bound on speculative draft candidates.

Prompt-logprob admission validates only scored next-token targets,
`input_ids[logprob_start_len + 1..]`, against the output vocabulary. For
example, with input/output sizes 128/64, `[100, 10, 11, 12]` is accepted
with `logprob_start_len=1`; an input-only token among the scored targets
is rejected. The Rust host interface remains unchanged.

Validation:
- Full `pre-commit run --all-files`, Rust formatting, and `cargo clippy
--locked -p tokenspeed-control --all-targets -- -D warnings`: passed.
- Rust control unit tests: 140 passed. The new unscored-context
regression fails before the admission fix and passes after it.
- Input/output vocabulary configuration tests: 13 passed.
- Earlier implementation validation: 313 relevant runtime CPU/CUDA
regressions passed, 3 skipped. A repeat of those Python tests in the
follow-up environment is blocked by missing optional CUDA build
dependencies; CI validates the updated head.

---------

Signed-off-by: wc222 <cwang16@link.cuhk.edu.hk>
Signed-off-by: FC-Li <robert_lexis@163.com>
Co-authored-by: longcat-ia-team <longcat_ia_team@meituan.com>
Co-authored-by: FC-Li <robert_lexis@163.com>
2026-11-07 02:43:17 +08:00
23791cea04 feat(kimi-k31): support Kimi-K3.1 (#3015)
Add support for Kimi-K3.1 (`KimiK31ForConditionalGeneration`, model type
`kimi_k31`). K3.1 keeps the Kimi-K3 hybrid design — KDA linear attention
interleaved with MLA full-attention layers — and puts a
DeepSeek-V3.2-style DSA lightning indexer on every MLA layer, so each
token attends over a top-k selection of 2048 history positions instead
of the whole cache. The DSpark speculative variant is supported as well,
with the decode and verify window raised to 8 rows (7 draft tokens plus
the bonus token) end to end. Kernel support spans NVIDIA Hopper and
Blackwell and AMD CDNA4 (gfx950, MI350X).

**Model and cache.** The model and its indexer build on the GLM-DSA
sparse-attention core, refactored into a shared
`GlmDsaSparseAttentionMixin`, and indexer weights are strictly validated
at load. The hybrid KDA token pool gains per-DSA-layer index-K planes
(bf16 or fp8-scaled), and cache writes fuse the indexer key LayerNorm —
plus per-group E4M3 quantization for the fp8 plane — into a single
scatter with an ownership write-mask. The MoE uses 896 experts with
top-16 sigmoid routing on a 7168-wide hidden state (MoE latent 3584,
shared expert 768); the MLA gathers 96 query heads over a 576-wide head
dim (512 latent and 64 rope) against 64-token pages.

## DSA indexer and selection (Triton, cross-platform)

- **Fused index-K cache writes**: `index_k_layernorm_scatter` and
`index_k_layernorm_fp8_scatter` apply a full FP32 LayerNorm and scatter
the result straight into the paged index-K cache, the fp8 variant
emitting E4M3 codes plus per-group FP32 scales into the fp8_scaled
plane. Both honor a `write_mask`, so in KV-parallel layouts only the
owning rank writes a slot.
- **Multi-CTA decode top-k**: new histogram and select kernels serve
small decode batches at long context, with the plan (multi-CTA,
one-block or trivial) chosen by row count and logit width, and
deterministic tie ordering by low bits. `_prepare_logits_for_topk`
scrubs non-finite logits within each row's own candidate count, in
place.
- **Bounded candidate-page planning**: `compact_index_pages` compacts
each rank's owned index pages once per forward in one bounded kernel,
sized to the widest row with per-row overflow accounting and shared
across all DSA layers; `mask_index_scores` masks by per-row lengths and
leaves the tail untouched.
- **Candidate exchange**: `merge_packed_index_candidates`,
`rank_major_scores` and `select_through_threshold` merge packed per-rank
candidate records. Ties resolve through a threshold rule so every KVP
rank selects identically, and an owner merging only its slice of the
rows selects what the full merge selects, which the KVP prefill's
row-owner exchange relies on to merge each row on a single rank.
- **Facade**: `plan_dsa_index_candidates` returns
`DSAIndexCandidatePages` (pages, positions, lengths, overflow and row
tiles via `.rows(start, end)`) to leaves declaring
`INDEX_CANDIDATE_PAGES_FEATURE`; `dsa_merge_candidates` offers the
`cuda` and `triton` solutions; FP8 query planes pass `q_scales`;
`slot_order="selection"` reaches only declaring kernels.

## NVIDIA sparse-MLA backends

Scoring uses the best available selector — DeepSelect on Hopper, the
ragged CUDA persistent top-k on Blackwell, `torch.topk` otherwise.

- **CUDA ragged top-k**: `has_ragged_decode_topk` and
`ragged_decode_topk`, a persistent selector that reads padded ragged
rows in place instead of copying them, is safe under graph capture and
replay, and declines unsupported shapes so the caller falls back. It is
wired into the DeepGEMM DCP selection through `_dcp_ragged_rows`.
- **TRTLLM-gen sparse MLA**: returns the natural-log FP32 LSE the DCP
merge needs (`return_lse`), giving a row with no owned slots the merge
identity's -inf LSE; query head counts of 65 to 127 pad to 128, covering
the 96-head K3.1 geometry; workspace and counter buffers are reserved up
front (`reserve_flashinfer_trtllm_dsa_buffers`) so graph capture never
allocates, and tactic selection stays safe inside startup autotune.
- **FlashInfer Prims-TS (optional)**: a new wrapper around
`BatchSparseMLADecodePagedTSWrapper` adds native-FP8 sparse MLA
attention on Blackwell (SM100 and SM103), with a per-stream plan cache,
capture-safe plan retention, BF16 outputs and an optional LSE. It is
exposed as `solution="flashinfer_prims"` under a strict contract: native
E4M3 KV cache, PDL enabled, contiguous INT32 slots.

## KV-parallel sharding (DCP and KVP)

- **Slot compaction**: `compact_owned_slots` packs one owner's selected
slots at the front of each row, preserving selection order within the
rank, and returns per-row owned counts (Triton kernel with a CPU
reference path); the virtual-slot translation leaves the slot count
unspecialized so one binary serves every batch size.
- **Prefill DCP records**: `dsa_prefill_dcp_records` emits prefill DCP
partial and LSE records directly as rank-major dispatch records
(`[degree, tokens, local_heads, 257]`), one program per token, refusing
shapes that would split the launch; `dsa_prefill_dcp_records_supported`
reports the supported geometry.
- **Compacted partials**: each rank attends its compacted owned slots,
stopping rows at the owned count, and the LSE merge of the per-rank
partials reproduces the unsplit attention. FlashMLA sparse prefill
serves the BF16 KV core, with each rank's `topk_length` set to its owned
counts.

## CUDA graphs

Padded, breakable prefill graphs are narrowed to live rows, with a
rank-uniform plan check and layerwise host-load fences, so capture and
replay cover the indexer and the sparse cores under changing inputs.

## Iris K3 fused collectives (8-GPU CDNA4)

The Iris row-sharded residual stream is extended throughout, so
attention and MoE epilogues ride on the collectives:

- **Transport**: the Lamport one-shot window grows to 7 rows; a two-shot
region covers 8 to 64 rows; optional FP32 outputs (`OUTPUT_FP32`); a
fused all-reduce and RMSNorm Lamport path for 16 rows or fewer skips the
input copy and device barrier and is bitwise equal to the unfused pair
(`iris_residual_rmsnorm_rows`); `PEER_LOAD_HINT` tuning on peer loads.
- **Attention**: `project_attention` and `take_published` let the
output-projection GEMM publish completed row tiles that peers poll
through int32-wrapping completion counters, scattering on a
high-priority, capture-safe side stream; `attention_mix` gains
`residual_is_sharded`, `published` and `defer_gather` modes, with
`join_gather` joining the deferred gather.
- **MoE**: `reduce_moe(..., routed_partials=)` absorbs the top-k slot
reduce into the all-reduce; `project_moe_shared` publishes the
shared-expert projection beside the routed reduction; `moe_tail` and
`moe_tail_mix` fold the row-sharded residual, the AttnRes history mix
and optionally the next layer's input projection (the gathered 2112-wide
MLA qkv projection or the column-sharded 6288-wide KDA one) into the
same collective; `moe_gather_tail` (GEMV senders for 4 rows or fewer,
MFMA tiles above) projects `norm(routed) @ W.T` plus prefix and shared,
column-blocked through the mailbox; `latent_input_gather` computes the
sharded replicated-column MoE input projection with optional per-tensor
FP8 quantization, bitwise equal except for negative-zero router logits;
`moe_row_sharded_inputs` packs the 6016-wide fused input (896 router
scores, 3584 latent, two 768-wide shared halves) into per-rank E2M1 row
shards, bitwise equal to replicated-input results; `gather_prefill_topk`
all-gathers K3.1 DSA prefill selections as int16 slots and lengths,
double-buffered.
- **All-gather**: a new column all-gather with `column_gather_num_warps`
tuning.

## gfx950 Gluon kernels (AMD CDNA4)

- **DSA top-k**: `gluon_dsa_decode_topk_bf16_gfx950` and
`gluon_dsa_prefill_topk_bf16_gfx950` read the checkpoint's bf16 index-K
plane directly, while `gluon_dsa_decode_topk_fp8_rows_gfx950` and
`gluon_dsa_prefill_topk_fp8_rows_gfx950` score E4M3 queries against
fp8_scaled pages, registered for packed and page-planar layouts. Launch
tuning (key tile, chunk, stages, waves) only reschedules scores and
keeps the selection bitwise, and graph capture replays changed inputs.
The dense split kernels compile once per power-of-two split bucket
(`_select_num_kv_splits`, `_fp8_rows_decode_splits`), with
`warm_split_variants` pre-warming the variants, so batch-size sweeps no
longer recompile.
- **GEMM**: the large-M a16w16 prefill GEMM gains `publish_rows` and
`skip_rows` variants, bitwise equal to the base kernel, whose
column-tile completion counters feed the Iris publication path;
`gluon_grouped_mla_project_value_gfx950` fuses the sigmoid gate into the
grouped decode GEMM epilogue, with a `torch.bmm` fallback;
`gluon_grouped_bmm_a16w16_decode_gfx950` serves the absorbed MLA
projections; `gluon_linear_attnres_partials_gemv_gfx950` fuses the
decode projection of the 6288-wide KDA weight with the two AttnRes
history reductions for 5 to 16 tokens, bitwise equal to the unfused
path; `kimi3_mla_gate_projection` covers the K3 gate projection.
- **MoE**: sorted and deduplicated stage-1 decode kernels; prefill
declares `supports_prequantized_input`, accepting packed E2M1 with CDNA4
scales, and takes one-call upstream FP8 inputs; a deferred top-k reduce
returns per-slot rows for the fused collective reduce; the XCD-aware
tile order stays bitwise equal to the linear order; the single-pass
dynamic-FP8 quantization bound moves to 4 rows (the verify window), with
larger batches taking a grid reduce;
`warm_gluon_mxfp4_situ_prefill_rows` pre-warms serving row counts.
- **Routing**: `triton_kimi3_packed_sigmoid_bias_topk_gfx950`, a packed
sigmoid and bias top-k for 2 to 512 rows at priority SPECIALIZED+1, with
the Gluon kernel taking over past 512 rows.

## Miscellaneous

- `causal_conv1d_qkv_fn`: the prefill convolution writes query, key and
value rows directly into separate contiguous outputs, bitwise equal to
convolution plus split; channel widths must be multiples of 256.
- AMD AttnRes activations: `[2, 4096]` pair tiles for `attnres_partial`
and `attnres_partial_dual`, bitwise equal to the row kernels.
- The MLA kv-buffer prologue leaves the token count unspecialized
(`select_mla_kv_block_n`), so one binary per token tile serves every
count.
- `priority_band_name` on the kernel registry reports human-readable
priority bands.

## Testing

New tests cover dense-MLA equivalence in BF16 and FP8, prefix caching,
graph capture and replay with changed inputs, loader strictness, and
bitwise agreement of the new selection and communication kernels with
their references. In detail:

- Bitwise-equality tests for the fused paths against their unfused
decompositions: index-K scatters, the publish-rows GEMM, linear-attnres
partials, row-sharded MoE inputs, latent-input gather, AttnRes pair
tiles and the qkv convolution.
- DSA selection tests: the multi-CTA top-k against the one-block kernel
and the reference across distributions and ragged lengths, tie ordering
at the threshold, logit scrubbing, bounded candidate-page compaction and
overflow, length-aware tail masking, row-slice against full candidate
merges, and the CUDA ragged top-k against `torch.topk`.
- Backend tests: Prims-TS through the public facade (plan reuse,
capture-safe retention, BF16 and LSE outputs, cache layouts,
disabled-PDL rejection), TRTLLM LSE against Triton and merged back to
the unsplit attention, head padding at 65, 96 and 127 heads, 7-row and
8-row block verify against expanded causal queries, and FlashMLA DCP
compacted partials against masked ones.
- Compile-stability sweeps (unspecialized counts, split buckets, token
tiles) asserting no recompilation, plus CUDA graph capture and replay
tests with changed inputs across the graph-safe kernels.
- 8-GPU Iris tests covering the fused collectives: attention mix and
published projections, MoE reduces with routed partials, tail mix,
gather tail, latent-input gather, row-sharded inputs, prefill top-k
gather and the column all-gather.

---------

Signed-off-by: Nicolas Perrin <nperrin.ai@gmail.com>
Signed-off-by: Zhewen Yu <zhewenyu@amd.com>
Co-authored-by: Enwei Zhu <21126786+syuoni@users.noreply.github.com>
Co-authored-by: Zhewen Yu <42230979+Yu-Zhewen@users.noreply.github.com>
Co-authored-by: Stanley Winata <68087699+raikonenfnu@users.noreply.github.com>
Co-authored-by: Cheng Hang <15108866+Njuapp@users.noreply.github.com>
Co-authored-by: Jacky Mick <30545757+JimpleMa@users.noreply.github.com>
Co-authored-by: Zhewen Yu <zhewenyu@amd.com>
2026-11-05 13:30:00 -08:00
Enwei Zhu 42d5f8f5e5 feat(kda): add cuDNN prefill and CUDA graph support (#3005)
<!-- 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

Pick & refactor
https://github.com/lightseekorg/tokenspeed/pull/2661/changes/ab0974f752abae95008c146f3dec849fff0678cc
and
https://github.com/lightseekorg/tokenspeed/pull/2661/changes/8e0eefe7beb104b5b4dbdd5e777bab5d8bb3751d

Add `--kda-backend cudnn` for SM100/SM103 through the kernel registry,
reducing KDA prefill preparation overhead.

- Keep convolution output token-major and pass strided Q/K/V views
directly to cuDNN, avoiding QKV packing and separate gate/beta
preparation copies.
- Gather BF16 cache state directly into FP32 scan buffers. Final
writeback retains its fused conversion to the cache dtype.
- Integrate cuDNN with existing prefill graph buckets, padding, metadata
refresh, and startup warmup.
- Switch existing explicit K3 launch configurations to cuDNN; automatic
backend selection remains unchanged.

Graph replay matches eager execution bitwise at the same capacity.
Different capacities may select different cuDNN scan partitions and
produce small rounding differences.

## Performance

GB200/SM100, one request, FP32 recurrent state. Median summed GPU kernel
time over 21 cold-L2 Nsight samples, including state gather,
convolution, KDA scan, and state writeback. Projection GEMMs and Python
launch gaps are excluded.

| Shape | Tokens | Binary CuTeDSL | cuDNN | Speedup |
|---|---:|---:|---:|---:|
| 12 heads — K3 TP8 shape | 256 | 46.72 µs | 64.19 µs | 0.73× |
| 12 heads | 8,192 | 375.26 µs | 236.26 µs | 1.59× |
| 12 heads | 16,384 | 714.21 µs | 355.04 µs | 2.01× |
| 96 heads — K3 attention-DP shape | 256 | 71.04 µs | 53.60 µs | 1.33× |
| 96 heads | 8,192 | 1,165.50 µs | 723.17 µs | 1.61× |
| 96 heads | 16,384 | 2,283.55 µs | 1,402.14 µs | 1.63× |

cuDNN improves the measured 8K–16K cases by **1.59–2.01×**. The 12-head,
256-token case is **37% slower**.

These eager-component measurements predate the final CUDA graph
integration. Separately, BF16-cache tracing confirmed removal of one
state-conversion kernel per KDA layer. The graph integration’s
performance benefit and full-model serving throughput have not been
measured.

## Test Plan

- [x] Focused correctness tests on GB200/SM100 covering strided inputs,
BF16/FP32 cache storage, and fresh/resumed prefills.
- [x] Graph replay with changing sequence lengths, request counts, and
cache pages.
- [x] Four retained captures and 24 alternating replays across workspace
growth, with no CuTe compilation after warmup.
- [x] Nsight verification of eliminated preparation copies and
standalone state-conversion kernels.
- [x] Pre-commit checks.
- [ ] Full-model serving and end-to-end performance validation.

---------

Signed-off-by: Enwei Zhu <21126786+syuoni@users.noreply.github.com>
2026-11-05 16:21:09 +08:00
zhuhaozhecool 84304c1714 fix(runtime): warm disaggregated decode workers on decode (#2990)
## Summary

Disaggregated Decode workers never execute local Prefill: remote
admission
receives the peer's cache, and retraction recovery restores a snapshot.
Startup currently selects a decode-shaped warmup only for
`mapping.attn.head_tp_serves_decode_only`. Ordinary TP and TP1
attention-DP
Decode workers therefore still build and execute an extend-shaped dummy
forward, which fails for a backend configured to serve Decode only.

- Select the existing Decode warmup from `disaggregation_mode ==
"decode"`,
  including ordinary TP and TP1 attention DP.
- Resolve the Prefill graph token ceiling to zero on Decode workers, so
startup cannot capture extend-shaped graphs even with explicit buckets.
- Preserve Prefill and aggregated warmup behavior, existing head-TP role
  validation, and the existing Decode traversal for speculative workers.
- Add regression coverage through real `ServerArgs`, `ModelConfig`, and
`ModelExecutorConfig`, and exercise `ModelExecutor.autotune` with device
  and distributed boundaries replaced by the existing test doubles.

## Test Plan

- Relevant CPU policy regressions: **418 passed, 20 skipped**, plus
**20 subtests passed**. Covers role resolution, ordinary TP and
attention-DP
Decode warmup, autotune enabled/disabled, speculative traversal and
failure
  cleanup, Prefill graph buckets, and probe arena sizing.
  - `test/runtime/test_dispatch_autotune.py`
-
`test/runtime/test_prefill_graph.py::{TestPrefillCaptureArgsTest,TestPrefillRoleGraphsTest}`
-
`test/runtime/execution/test_breakable_cuda_graph.py::{TestPrefillTokenBuckets,TestPrefillGraphMaxTokensResolution}`
-
`test/runtime/test_cudagraph_probe_arena.py::test_the_boot_floor_reads_both_knobs`
- The role/warmup regressions reproduce **40 failures** on unmodified
main
  (`25ecfc4b7a7231dcb1a90d338387362ac9fdafc7`) and pass with this fix.
- `pre-commit run --all-files`: passed.

Local tests ran on a CPU host with device discovery overridden; the
20 skipped cases require NVIDIA-only FlashInfer MXFP4 SiTU registration.
No GPU/NPU kernel, graph capture, or end-to-end serving result is
claimed.

Signed-off-by: zhuhaozhecool <zhuhaozhecool@163.com>
2026-11-03 21:24:16 -08:00
FC.Liandlongcat-ia-team 0dcb71840b ci: always arm the data-plane sync check and serve CI with it raising (#2860)
## Summary

The forward thread must not synchronize with the device on the per-round
path (`docs/design/event-loop.md`): a `.cpu()`, `.item()`, `.tolist()`,
boolean-mask index or pageable copy there waits for the step in flight
and degrades overlap scheduling to depth 0. The check that enforces this
(torch's sync-debug mode, armed in `enter_serving`) was off unless
`TOKENSPEED_DATA_PLANE_SYNC_DEBUG` was set. No CI task set it, although
the design doc said CI served with `error`, and `test_host_sync.py` was
not registered with any CI suite.

- **Always on.** Serving always arms the check.
`TOKENSPEED_DATA_PLANE_SYNC_DEBUG` only picks whether a report warns
(the default) or raises; any other value, the old `default` included, is
refused at startup.
- **CI raises.** `test/ci_system/pipeline.py` serves every
`server_smoke`, `eval`, and `perf` task with `error`, overriding a value
inherited from the runner. `validate_task` rejects a task or
`runner.env` that sets the variable.
- **Fixes for the violations found on CI paths:**
- A PD decode destination landed each remote prefill's speculative
candidates with `spec_candidates_ready[idx] = True`, which stages the
Python scalar through a pageable host tensor (a host sync per landed
request). It now uses `fill_`. Found by the survey below.
- `deepep_scatter` (DeepEP normal-mode MoE) uploaded the per-expert
block starts and counts from pageable memory. They now share one pinned,
non-blocking upload. Found by this PR's CI
(`eval-qwen3.5-35b-a3b-fp8-deepep-tp2dp2ep4-gsm8k`).
- `MultimodalRuntime.build_positions_override` uploaded a prefill
chunk's M-RoPE positions table, and a delta-only input's delta, from
pageable memory. The chunk, a strided slice of the table, is now
gathered into a contiguous pinned buffer and copied without blocking (a
strided pinned source still goes through a pageable temporary), and the
delta is read as a host scalar, as the decode path does. Found by this
PR's CI (`eval-qwen3.5-122b-a10b-nvfp4-epd-1e1p2d-ocr-bench`).
- GLM-5.3 KPool prefill plans uploaded about a dozen host-built index
lists, Qwen4-exp PLE ragged batch indices uploaded the request lengths,
MoonViT (Kimi-K2.5 vision) moved the image grid to the device only to
read it back on the host, and encoder CUDA graph replay padded
`cu_seqlens` from pageable memory. Found by this PR's CI (GLM-5.3 MTP on
B200 and MI35x, Qwen3.8-flash-next on MI35x, Kimi-K2.5 OCR). They now go
through a new helper, `host_to_device` (`utils/host_sync.py`):
contiguous pinned memory and a non-blocking copy, refused under graph
capture. The MoonViT grid stays on the host, as Qwen3.5 already keeps
it.
- `test_host_sync.py` and
`test/runtime/execution/test_multimodal_runtime.py` are registered in
`runtime-1gpu`; neither ran in CI before. The new
`test/runtime/test_kpool_prefill_plan.py` is registered with them.

## Survey (warn mode, before this change)

Served the main branch on 8×H20 with
`TOKENSPEED_DATA_PLANE_SYNC_DEBUG=warn` and a hook that reports every
distinct Python stack of a flagged sync. A positive control (one
injected `.tolist()` on the forward thread after arming) confirmed the
hook catches syncs inside the Rust host's embedded interpreter. Each run
sent greedy and sampled requests (temperature, top-p, top-k and min-p,
penalties, seed, stop strings, `n=2`, `ignore_eos`), output and prompt
logprobs, chunked-prefill prompts and their prefix-cache hits, streams,
client disconnects mid-stream, and a burst after idling.

| Config | Violations |
|---|---|
| Qwen3-0.6B, TP1 | 0 |
| Qwen3-30B-A3B, attention DP4 + EP4 | 0 |
| DeepSeek-V4.1-Flash, TP8 + EP | 0 |
| DeepSeek-V4.1-Flash, TP8 + EP, DSPARK, text | 0 |
| DeepSeek-V4.1-Flash, TP8 + EP, DSPARK, image requests | 4, all in the
vision tower |
| DeepSeek-V4.1-Flash, 1P1D (TP4 + EP4 each), DSPARK | 1 on decode,
every landed request (fixed here) |

The four vision-tower sites (`deepseek_v41_vision.py`: the RoPE table
and `cu_seqlens` uploads, the `types` upload, `block[types == 1] =
embeds`) run only on image prefill rounds, and no CI task sends images
to this model, so they are left for a follow-up; under the new default
they warn. Not covered by the survey: EAGLE3 and MTP speculation, the
Kimi and Qwen3.5 vision towers, and AMD paths. This PR's CI runs the
per-commit tasks for those with `error`.

## Test plan

- [x] `test/ci_system/test_pipeline.py` and `test_eval_configs.py`: 234
passed. The new sync-check tests fail without the pipeline change.
- [x] `test/runtime/test_host_sync.py`: 7 passed.
`test/runtime/test_runtime_states.py`: 13 passed; the new landing test
raises without the fix.
- [x] DeepSeek-V4.1-Flash 1P1D with DSPARK, this branch,
`TOKENSPEED_DATA_PLANE_SYNC_DEBUG=error`: every request served and no
sync raised (before the fix, warn mode reported the landing site on
every request).
- [x] `test/runtime/execution/test_multimodal_runtime.py`: 12 passed.
`tokenspeed-kernel/test/ops/moe/test_deepep_permute.py`: 17 passed. Each
new sync-debug test raises without its fix; the M-RoPE test also holds
the stream behind a long kernel and asserts the call returns before it
finishes, which fails with a strided pinned copy.
- [x] `host_to_device` tests (values, strided sources, no wait behind a
long kernel, capture refused), a KPool plan built on CUDA that matches
the host build without waiting, PLE ragged indices and `cu_seqlens`
padding under sync-debug error mode; each fails without its fix.
- [x] All per-commit model tests pass with `error` (B200, GB200, MI35x).
GB300 tests run nightly, so
`eval-deepseek-v4.1-flash-pd-1p1d-dspark-gsm8k-gb300-slurm` was
dispatched for this PR through Slurm Dispatch: passed, GSM8K 0.98.
- [x] `pre-commit run --all-files`.

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

---------

Signed-off-by: FC-Li <robert_lexis@163.com>
2026-10-31 15:45:32 -07:00
Nicolas Perrin e815bc88f4 fix(spec): refuse EAGLE3/DFLASH on targets that return no aux taps (#2840)
## Problem

`BaseCausalLM.set_eagle3_layers_to_capture` and
`set_dflash_layers_to_capture` write `model.layers_to_capture`, but
several backbones never read it: Qwen3, Qwen3-MoE, Qwen3-Omni, DeepSeek
V4.1, MuseSpark (overrides `forward`, returns `None` aux) and Qwen4-Exp
(returns its own residual). `configure_draft_target` only checked
`hasattr`, so EAGLE3 on these targets started normally. The logits
processor then stored the final hidden state, and the Eagle3 draft,
seeing a hidden-size input, skipped its `fc` and drafted from the wrong
features.

Qwen3-8B with the AngelSlim Qwen3-8B EAGLE3 draft on main (GB200, TP1,
32 GSM8K prompts): `avg_accept_len 1.00, accept_rate 0.00` over 179
windows, no error.

## Fix

- `BaseCausalLM.supports_aux_capture` (opt-in, like
`supports_expert_placement`); every capture setter calls
`require_aux_capture()` first.
- Opted in where the backbone forward returns the named taps: Llama,
GPT-OSS, Beam, MiniMax-M3, DeepSeek-V3 (and GLM-5, V3.2, dots3 and
Kimi-K2.5 through it), LongCat, Nemotron-H, Qwen3.5, Kimi-K3. Qwen4-Exp
CG opts out of the flag it inherits from Qwen3.5.
- The factory calls the EAGLE3 setter unconditionally, so a target
without one (Inkling, Qwen3-ASR, GLM-5.3-Flash) fails setup instead of
being skipped.
- GLM-5.3-Flash's unread `layers_to_capture` is removed. DeepSeek V4.1
DSpark keeps its own `set_dspark_layers_to_capture`.

## Validation (GB200)

- Same Qwen3-8B EAGLE3 launch on this branch: refused at startup with
`NotImplementedError: Qwen3ForCausalLM does not return aux hidden
states, so EAGLE3 and DFLASH drafts cannot attach to it`.
- New tests: refusal for the six non-capturing targets, acceptance for
opted-in ones, factory refusal for a target without a setter. The six
refusal cases fail on main.
- Targeted runtime tests (aux capture, draft wiring, DSpark config, K3
DSpark and EAGLE3, Nemotron-H, Llama EAGLE3, DFlash2, MiniMax-M3, V4.1
DSpark, Qwen4-Exp, GPT-OSS): 511 passed on the branch, 501 on main (+10
new), no failures.
- `pre-commit run --all-files` clean.

## Not changed

A DFLASH draft that names the last target layer still gets no tap on
LongCat and Nemotron-H: the base setter maps layer `N-1` to capture id
`N+1`, which those backbones do not honor. This predates the PR and is
left for a separate fix.

Signed-off-by: Nicolas <nperrin.ai@gmail.com>
2026-10-30 22:38:13 -04:00