Commit Graph
5 Commits
Author SHA1 Message Date
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
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
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
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
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