Repository navigation
[Perf] sampling: JIT softmax and argmax for the sampler and speculative verify - #47512
Conversation
This comment has been minimized.
This comment has been minimized.
98c47a6 to
d682bf3
Compare
…ve verify Add a JIT row softmax (fp32 / bf16 / fp16 logits to fp32 probs, fused per-request temperature, one row per thread-block cluster held in registers, config chosen from the compiled candidates' real occupancy) and a JIT row argmax (int64, ties to the lowest index, NaN never selected). Wire them into the sampler (fused temperature, in-place probs, greedy argmax) and the speculative verify paths (EAGLE rows_per_request, EAGLE / DFlash / UNO / fast_sample / DSpark argmax); drop the DSpark per-model fused_argmax opt-in. Rename temperature_softmax.py to softmax_triton.py. Supersedes sgl-project#44752. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
d682bf3 to
3fb2eb5
Compare
BBuf
left a comment
There was a problem hiding this comment.
[BBuf Review Agent] A few things to fix before this can go in.
| #pragma unroll | ||
| for (uint32_t i = 0; i < kVecSize / 2; ++i) { | ||
| auto& [x, y] = vecs[n][i]; | ||
| x = ptx::ex2_approx(fmaf(x, log2_scale, -base)); |
There was a problem hiding this comment.
[BBuf Review Agent] With SGLANG_SANITIZE_NAN_LOGITS=1, a positive infinity becomes 1e30, but this FMA subtracts an already-rounded product and recreates NaN probabilities at temperature 1. Could we subtract the raw maximum before scaling and cover the sanitizer's finite sentinels?
There was a problem hiding this comment.
(auto generated by Claude)
Agreed, this is real. sanitize_nan_logits writes posinf=1e30, and fmaf(x, log2_scale, -base) with base = round(raw_max * log2_scale) leaves a residual of about half an ulp of 1.4e30 (~7e22) for the max element. ex2 then overflows to inf, and the row sum becomes inf/inf = NaN. We will subtract the raw maximum first, (x - raw_max) * log2_scale, which is exactly 0 for the max element, and add the sanitizer's ±1e30 sentinels to the tests.
There was a problem hiding this comment.
[BBuf Review Agent] The FMA is still present at this head, so the sentinel case remains broken. Could you apply the subtraction-before-scaling fix?
There was a problem hiding this comment.
(auto generated by Claude)
Applied in 76830ed: the exponent is now ex2((x - shift) * log2_scale) with shift the raw row max (0 for an all -inf row), so the max element is exactly ex2(0). The warp stats keep base = shift * log2_scale, so the merge is unchanged. test_sanitized_nan_sentinels covers +-1e30 rows with and without temperatures.
There was a problem hiding this comment.
[BBuf Review Agent] Confirmed at this head: the exponent subtracts the raw max before scaling, and the sentinel test covers ±1e30. This addresses the NaN issue.
| if (gridDim.x == 1) { | ||
| static_cast<IdxType*>(params.output)[token_id] = static_cast<IdxType>(max_idx); | ||
| } else { | ||
| const auto payload = static_cast<ArgMaxHandle>(to_ordered(max_val)) << 32 | ~max_idx; |
There was a problem hiding this comment.
[BBuf Review Agent] For a [1, 8192] fp32 row on B200 with -0.0 at index 0 and +0.0 at index 4096, the atomic key selects 4096 even though both values tie. Could we canonicalize zero before packing the key so the lowest-index rule also holds across CTAs?
There was a problem hiding this comment.
(auto generated by Claude)
Agreed. Inside a CTA the strict > treats -0.0 and +0.0 as equal and keeps the lower index, but to_ordered maps them to different keys, so the cross-CTA atomicMax prefers +0.0. We will canonicalize zero before packing (max_val + 0.0f turns -0.0 into +0.0), so the lowest-index rule holds in both stages, and we will add the -0.0 / +0.0 split-row case.
There was a problem hiding this comment.
[BBuf Review Agent] The payload still uses to_ordered(max_val) without canonicalizing zero at this head. Could you apply that change before packing the key?
There was a problem hiding this comment.
(auto generated by Claude)
Applied in 76830ed: the cross-CTA key now packs +0.0 for either signed zero (a bit test, so --use_fast_math cannot fold it away). test_argmax_signed_zero_ties_across_splits puts -0.0 at index 0 and +0.0 at index 131072 of a 262144-wide row.
There was a problem hiding this comment.
[BBuf Review Agent] Confirmed the bit check canonicalizes both signed zeros before packing the atomic key. This addresses the cross-CTA tie issue.
| return ( | ||
| 0 < vocab_size <= _MAX_SUPPORTED_VOCAB_SIZE | ||
| and vocab_size % vec_size == 0 | ||
| and logits.stride(0) % vec_size == 0 |
There was a problem hiding this comment.
[BBuf Review Agent] An fp32 view buf[:, 1:1025] from a [2, 1032] CUDA buffer passes this gate but fails the launcher's base-address alignment check; argmax has the same issue. Could we check pointer alignment in both gates so these views take the fallback?
There was a problem hiding this comment.
(auto generated by Claude)
Agreed. The gates check vocab size and row stride but not the base address, so a misaligned view reaches the launcher's ensure_alignment and raises instead of falling back. We will add data_ptr() % (vec_size * element_size) == 0 to can_softmax (input and out) and can_argmax, and cover offset views in both tests.
There was a problem hiding this comment.
[BBuf Review Agent] Both gates still omit the pointer check at this head, so offset views can still reach the launcher and raise. Could you add the alignment checks for logits and softmax's out?
There was a problem hiding this comment.
(auto generated by Claude)
Applied in 76830ed: can_softmax checks data_ptr() % (vec_size * element_size) == 0, which also covers out through its recursive call, and can_argmax checks data_ptr() % vec_bytes == 0. Misaligned buf[:, 1:1025] views fall back in both new tests.
There was a problem hiding this comment.
[BBuf Review Agent] Confirmed both gates check base alignment, including softmax's out through the recursive check. The offset views now take the fallback.
… as one, gate on base alignment Co-Authored-By: Claude Opus 5.5 <[email protected]>
…hing op Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
/rerun-test test/registered/kernels/ops/sampling/test_softmax.py test/registered/kernels/ops/sampling/test_argmax.py |
|
🚀 🚀 🚀 |
|
/rerun-test test/registered/kernels/ops/sampling/test_argmax.py |
|
🚀 🚀 |
Match main after sgl-project#47512: the forced row of the simulated-acceptance path uses sampling_argmax instead of torch.argmax. The test's frozen eager reference now follows main's body, including its generator argument and sampling_argmax's NaN rule (the JIT kernel skips NaNs and takes the first maximum; the torch fallback returns the first NaN). Co-Authored-By: Claude Opus 5.5 <[email protected]>
The stock target-only tree sampler runs one 1024-thread CTA per request over the whole vocabulary, twice (the residual sum, then the crossing). For fp32 target probabilities of 65536+ entries and at most 64 verify rows, the multi-CTA form runs the chain walk once per request, reduces each 1024 * VEC chunk of relu(q - p) in its own CTA with the stock BlockReduce, accumulates the chunk sums in the stock order on one thread, and runs the stock DeviceSamplingFromProb only on the crossing chunk. Every floating-point operation and its operand order are the stock kernel's, so predicts, accept_index, accept_token_num and the draft_probs writes are bitwise equal. The no-selection fallback follows FlashInfer 0.7.3: the largest valid index over the scanned chunks. Each thread of the crossing chunk seeds its last_valid_index with the earlier chunks' maximum, so FlashInfer's reduction over the threads returns the same index. Scratch is allocated once per device, so captured post-verify graphs allocate what the stock sampler does. The source pairs this with a multi-CTA verify softmax; main's JIT softmax (sgl-project#47512) already splits that row over CTAs, so only the tree half is ported. SGLANG_OPT_MULTI_CTA_VERIFY_TREE_SAMPLING is a hard-gated child of SGLANG_ENABLE_NV_MEGA_RUNTIME_OPTIMIZATION. Gain: sample the EAGLE verify tree over multiple CTAs; not yet measured individually. Co-Authored-By: Claude Opus 5.5 <[email protected]>
With topk 1 the EAGLE draft extend picks each request's next draft token with torch.argmax over the full vocabulary, whose reduction gives each row one block. The verify already takes its greedy tokens with the sampler's JIT argmax (sgl-project#47512), which splits a wide row over several CTAs. Under SGLANG_OPT_SPEC_DRAFT_TOP1_ARGMAX the draft extend's top-1 goes through the same argmax (it falls back to torch.argmax for logits the JIT kernel does not take). Both resolve a value tie to the lowest index, so the token is the same for finite logits; only a NaN row can differ, where the JIT kernel never picks the NaN. SGLANG_OPT_SPEC_DRAFT_TOP1_ARGMAX is a hard-gated child of SGLANG_ENABLE_NV_MEGA_RUNTIME_OPTIMIZATION. Gain: take the EAGLE draft top-1 with the sampler's argmax; not yet measured individually. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The stock target-only tree sampler runs one 1024-thread CTA per request over the whole vocabulary, twice (the residual sum, then the crossing). For fp32 target probabilities of 65536+ entries and at most 64 verify rows, the multi-CTA form runs the chain walk once per request, reduces each 1024 * VEC chunk of relu(q - p) in its own CTA with the stock BlockReduce, accumulates the chunk sums in the stock order on one thread, and runs the stock DeviceSamplingFromProb only on the crossing chunk. Every floating-point operation and its operand order are the stock kernel's, so predicts, accept_index, accept_token_num and the draft_probs writes are bitwise equal. The no-selection fallback follows FlashInfer 0.7.3: the largest valid index over the scanned chunks. Each thread of the crossing chunk seeds its last_valid_index with the earlier chunks' maximum, so FlashInfer's reduction over the threads returns the same index. Scratch is allocated once per device, so captured post-verify graphs allocate what the stock sampler does. The source pairs this with a multi-CTA verify softmax; main's JIT softmax (sgl-project#47512) already splits that row over CTAs, so only the tree half is ported. SGLANG_OPT_MULTI_CTA_VERIFY_TREE_SAMPLING is a hard-gated child of SGLANG_ENABLE_NV_MEGA_RUNTIME_OPTIMIZATION. Gain: sample the EAGLE verify tree over multiple CTAs; not yet measured individually. Co-Authored-By: Claude Opus 5.5 <[email protected]>
With topk 1 the EAGLE draft extend picks each request's next draft token with torch.argmax over the full vocabulary, whose reduction gives each row one block. The verify already takes its greedy tokens with the sampler's JIT argmax (sgl-project#47512), which splits a wide row over several CTAs. Under SGLANG_OPT_SPEC_DRAFT_TOP1_ARGMAX the draft extend's top-1 goes through the same argmax (it falls back to torch.argmax for logits the JIT kernel does not take). Both resolve a value tie to the lowest index, so the token is the same for finite logits; only a NaN row can differ, where the JIT kernel never picks the NaN. SGLANG_OPT_SPEC_DRAFT_TOP1_ARGMAX is a hard-gated child of SGLANG_ENABLE_NV_MEGA_RUNTIME_OPTIMIZATION. Gain: take the EAGLE draft top-1 with the sampler's argmax; not yet measured individually. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The stock target-only tree sampler runs one 1024-thread CTA per request over the whole vocabulary, twice (the residual sum, then the crossing). For fp32 target probabilities of 65536+ entries and at most 64 verify rows, the multi-CTA form runs the chain walk once per request, reduces each 1024 * VEC chunk of relu(q - p) in its own CTA with the stock BlockReduce, accumulates the chunk sums in the stock order on one thread, and runs the stock DeviceSamplingFromProb only on the crossing chunk. Every floating-point operation and its operand order are the stock kernel's, so predicts, accept_index, accept_token_num and the draft_probs writes are bitwise equal. The no-selection fallback follows FlashInfer 0.7.3: the largest valid index over the scanned chunks. Each thread of the crossing chunk seeds its last_valid_index with the earlier chunks' maximum, so FlashInfer's reduction over the threads returns the same index. Scratch is allocated once per device, so captured post-verify graphs allocate what the stock sampler does. The source pairs this with a multi-CTA verify softmax; main's JIT softmax (sgl-project#47512) already splits that row over CTAs, so only the tree half is ported. SGLANG_OPT_MULTI_CTA_VERIFY_TREE_SAMPLING is a hard-gated child of SGLANG_ENABLE_NV_MEGA_RUNTIME_OPTIMIZATION. Gain: sample the EAGLE verify tree over multiple CTAs; not yet measured individually. Co-Authored-By: Claude Opus 5.5 <[email protected]>
With topk 1 the EAGLE draft extend picks each request's next draft token with torch.argmax over the full vocabulary, whose reduction gives each row one block. The verify already takes its greedy tokens with the sampler's JIT argmax (sgl-project#47512), which splits a wide row over several CTAs. Under SGLANG_OPT_SPEC_DRAFT_TOP1_ARGMAX the draft extend's top-1 goes through the same argmax (it falls back to torch.argmax for logits the JIT kernel does not take). Both resolve a value tie to the lowest index, so the token is the same for finite logits; only a NaN row can differ, where the JIT kernel never picks the NaN. SGLANG_OPT_SPEC_DRAFT_TOP1_ARGMAX is a hard-gated child of SGLANG_ENABLE_NV_MEGA_RUNTIME_OPTIMIZATION. Gain: take the EAGLE draft top-1 with the sampler's argmax; not yet measured individually. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The stock target-only tree sampler runs one 1024-thread CTA per request over the whole vocabulary, twice (the residual sum, then the crossing). For fp32 target probabilities of 65536+ entries and at most 64 verify rows, the multi-CTA form runs the chain walk once per request, reduces each 1024 * VEC chunk of relu(q - p) in its own CTA with the stock BlockReduce, accumulates the chunk sums in the stock order on one thread, and runs the stock DeviceSamplingFromProb only on the crossing chunk. Every floating-point operation and its operand order are the stock kernel's, so predicts, accept_index, accept_token_num and the draft_probs writes are bitwise equal. The no-selection fallback follows FlashInfer 0.7.3: the largest valid index over the scanned chunks. Each thread of the crossing chunk seeds its last_valid_index with the earlier chunks' maximum, so FlashInfer's reduction over the threads returns the same index. Scratch is allocated once per device, so captured post-verify graphs allocate what the stock sampler does. The source pairs this with a multi-CTA verify softmax; main's JIT softmax (sgl-project#47512) already splits that row over CTAs, so only the tree half is ported. SGLANG_OPT_MULTI_CTA_VERIFY_TREE_SAMPLING is a hard-gated child of SGLANG_ENABLE_NV_MEGA_RUNTIME_OPTIMIZATION. Gain: the verify-tree sampling kernel takes 7 us instead of 39 at 1 request and 14 instead of 74 at 13 (unit microbench, bitwise); with it off, a static 13-request TP1 decode round is 1.1-1.2% longer (leave-one-out, two samples). Co-Authored-By: Claude Opus 5.5 <[email protected]>
With topk 1 the EAGLE draft extend picks each request's next draft token with torch.argmax over the full vocabulary, whose reduction gives each row one block. The verify already takes its greedy tokens with the sampler's JIT argmax (sgl-project#47512), which splits a wide row over several CTAs. Under SGLANG_OPT_SPEC_DRAFT_TOP1_ARGMAX the draft extend's top-1 goes through the same argmax (it falls back to torch.argmax for logits the JIT kernel does not take). Both resolve a value tie to the lowest index, so the token is the same for finite logits; only a NaN row can differ, where the JIT kernel never picks the NaN. SGLANG_OPT_SPEC_DRAFT_TOP1_ARGMAX is a hard-gated child of SGLANG_ENABLE_NV_MEGA_RUNTIME_OPTIMIZATION. Gain: the draft top-1 takes 2.0 us instead of 8.4 at 1 row and 12.5 instead of 46.8 at 128 rows (unit microbench); end to end below noise. Co-Authored-By: Claude Opus 5.5 <[email protected]>
With topk 1 the EAGLE draft extend picks each request's next draft token with torch.argmax over the full vocabulary, whose reduction gives each row one block. The verify already takes its greedy tokens with the sampler's JIT argmax (sgl-project#47512), which splits a wide row over several CTAs. The draft extend's top-1 now goes through the same argmax for logits of at least 2^23 entries (it falls back to torch.argmax for logits the JIT kernel does not take). Both resolve a value tie to the lowest index, so the token is the same for finite logits; only a NaN row can differ, where the JIT kernel never picks the NaN. Smaller logits keep torch.argmax: the JIT call costs 2-4 us more host time on VR200 (about 10 us on GB300), which exceeds torch.argmax's GPU time there. Gain (microbenchmark, CUDA-graph replay, median of 3, same tokens at every shape): GPU time is lower at every measured shape (1-512 rows x 32000 / 128256 / 151936 / 248320 entries, fp32 and bf16), by 63-91% on VR200 and 40-92% on GB300. In the routed range, fp32 x 248320: 64 rows 20.8 -> 4.5 us and 512 rows 144.6 -> 51.0 us on VR200; 26.7 -> 5.6 us and 120.9 -> 72.0 us on GB300; back-to-back eager calls are faster at every routed shape on both. Co-Authored-By: Claude Opus 5.5 <[email protected]>
What this PR does
kernels/ops/sampling/softmax_jit.py,jit/csrc/sampling/softmax.cuh): fp32 / bf16 / fp16 logits in, fp32 probs out, per-request temperature fused, in place for fp32. One row per thread-block cluster with the row held in registers (read once, written once). The launch config is chosen per row count from the real occupancy of the compiled candidates. Used on the SM100 family; other platforms keep the existing Triton / Cake / torch paths.kernels/ops/sampling/argmax_jit.py,jit/csrc/sampling/argmax.cuh): int64 output, a tie takes the lowest index.sampling.softmax(logits, temperatures, *, rows_per_request, out)and a newsampling.argmax(logits)dispatch to them (both registered in the kernel registry).div_and no copy back); greedy uses the JIT argmax. Deterministic mode is unchanged.rows_per_request=draft_token_numinstead of a repeat-interleaved temperature; EAGLE, DFlash, UNO,fast_sampleand DSpark use the JIT argmax. The DSpark per-modelfused_argmaxopt-in is removed.ops/sampling/temperature_softmax.pytosoftmax_triton.pyandtest_temperature_softmax.pytotest_softmax.py.Behaviour change: the JIT argmax never selects a NaN, while
torch.argmaxreturns a NaN's index. The sampler already sanitizes NaN logits; for the speculative verify paths a NaN logit no longer becomes the target token.Supersedes #44752.
Validation (B300)
Correctness:
test/registered/kernels/ops/sampling/and the speculative / DSpark unit tests pass (238 passed). Softmax matches an fp64 reference to 1.5e-6 relative error for fp32 / bf16 / fp16 input across V and row counts; argmax matchestorch.argmaxincluding planted ties.Softmax, fp32 logits, V = 163840, cold L2, CUDA graph (us):
With per-row temperature the old path adds a separate division kernel (1 row: 6.58 us, 1024 rows: 983 us); the fused temperature costs this PR about 0.07 us.
Argmax, fp32 logits, cold L2 (us):
torch.argmax)Config selection: against an exhaustive sweep of launch configs (1-4096 rows, V = 129280 / 163840, fp32 and bf16), the chosen config is within 0.6-1.9% of the best on geometric mean.
🤖 Generated with Claude Code
CI States
Latest PR Test (Base): ✅ Run #41355486436
Latest PR Test (Extra): ❌ Run #41355486264
Latest PR Test (AMD ROCm 10): ✅ Run #41355486242
Tip
Base CI only covers the core cases, and its workload may not exercise your change. Use
/rerun-testto run the tests your change touches, or copy this prompt for an agent: