You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[TRTLLM-16622][perf] DeepSeek-V4.1: fused sampling with a parallel inverse-CDF walk and a pipelined first sweep - #22356
This pull request changes one file: cpp/tensorrt_llm/kernels/fusedSampling/fusedSamplingKernelsCommon.cuh (+194/−28). It makes three changes:
Adds forEachLogitPipelined. This helper issues the next vector load before it processes the current one. The cached online-softmax pass uses it. Element order per thread does not change.
Adds walkSupport, a helper for the rejection-path inverse-CDF walk. It sets kMaxWalkers = 4. When 1 to 4 walkers match and the row is 16-byte aligned, warp 0 stages vector weights in shared memory. Lane 0 then sums them in ascending thread order. Otherwise, the per-thread walk runs.
Adds walkers, walkerTid[], and walkerBase[] to FusedSamplingShared. The rejection path calls walkSupport instead of an inline per-thread rescan.
No public declarations change. No API, configuration, or default changes appear in the diff.
Dev Engineer Review
Fallback coverage: The per-thread walk runs when walkers exceed kMaxWalkers or the row is unaligned. This keeps the old behavior for those cases.
Synchronization: Threads outside warp 0 return early in walkSupport. No later __syncthreads() runs inside the helper, so the early return is safe. The __shfl_sync and __syncwarp calls sit outside the lane-0 branch and the loop condition is warp-uniform, so all lanes in warp 0 reach them.
Shared buffer reuse: The parallel path writes weights into shared.cand. The diff does not show whether that buffer also holds candidate data at this point in the kernel. Verify that no live candidate state is overwritten. The static_assert only checks that kChunk * kWidth <= kCandCap.
Shared scalar names: The diff replaces sCandIdx and sCandWeight writes with shared.candIdx and shared.candWeight. Confirm that the old names alias these fields.
Ordering: Walkers are sorted by thread ID before the walk. This matches the ascending-order rule stated in the code comment.
Performance and correctness claims: The PR reports per-launch latency reductions on GB300 and bit-identical tokens across 365,808 draws. This review did not run those measurements or the test suite. The results are author-reported only.
QA Engineer Review
No test changes.
Per-File QA Perspective
cpp/tensorrt_llm/kernels/fusedSampling/fusedSamplingKernelsCommon.cuh: Rejection-path sampling and the temperature-only first sweep now use new code paths. QA should check sampled tokens against the previous kernel for BF16 logits, including unaligned rows and cases with more than four matching walkers. The PR description references tests/unittest/_torch/speculative/test_fused_sampling_op.py as coverage for these paths. This PR does not modify that file.
Description
Summary
The fused sampling kernel's tokens-only rejection path draws a token with an inverse-CDF walk: the one thread whose
scan interval holds the target re-adds its own strided weights until the running mass passes it. That thread issued
one dependent 16-byte load per step over its whole slice (32 vectors of a 129K-entry BF16 row) while the block's
other threads waited, about a third of the kernel at large batches. Plain temperature sampling (no top-k or min-p)
also waited on each load of its first sweep before processing it.
This PR keeps the walk's arithmetic and order and removes the waiting: warp 0 loads the walker's vectors in parallel
and one lane sums them, and the first sweep issues the next vector's load before it processes the current one. The
sampled tokens are bit-identical.
walkSupport replaces the per-thread walk. Each thread whose interval holds the target registers itself as a
walker in shared memory. For up to kMaxWalkers (4) walkers, warp 0 loads 32 of the walker's vectors at a time,
computes their weights with the walk's own expression into the cand scratch buffer (unused by the rejection path
at that point), and lane 0 adds them in the walker's order, then walks the scalar tail.
More than four walkers, or a row that is not 16-byte aligned, keep the per-thread walk unchanged.
forEachLogitPipelined is forEachLogit with the next vector's load issued first; the first sweep of a row whose
rejection path reuses the per-thread online-softmax partials uses it.
Performance
GB300, vocabulary 129,280, BF16 logits, temperature 1, one launch:
Rows
Before
After
1,280
168.0 us
117.8 us
1,264
165.3 us
118.0 us
150
45.9 us
27.1 us
DeepSeek-V4.1 runs one launch per generation step. The end-to-end effect was measured only together with two other
generation-step changes (row-bounded CSA2 page tables and the padded Engram decode refresh): at the high-throughput
attention-DP point (320 sequences per rank), the steady-state generation step went 31.06 -> 30.66 ms (-1.3%) and
output throughput +1.5%. This PR alone was not measured end to end.
Compatibility
Shared code, ungated: the kernel serves every model and GPU that uses fused sampling. The change is bit-identical
by construction (above), so it is not gated.
No API, configuration or default changes. Only the tokens-only rejection path (walk) and the first sweep of a
temperature-only row change; probability outputs and the descent path are untouched.
Dependencies
None. Independent of the other PRs of this set.
Test Coverage
No new test: the old walk is gone, so there is no plain path left to compare against in the tree. The existing tests/unittest/_torch/speculative/test_fused_sampling_op.py covers the rejection path (tokens in the filtered
support, the filtered distribution, rejection rounds that narrow the support, seed reproducibility, the rejection
and descent kept sets) and the plain temperature path.
PR Checklist
Please review the following before submitting your PR:
PR description clearly explains what and why. If using CodeRabbit's summary, please make sure it makes sense.
If PR introduces API changes, an appropriate PR label is added - either api-compatible or api-breaking. For api-breaking, include BREAKING in the PR title.
Any new dependencies have been scanned for license and vulnerabilities
Reviewing files that changed from the base of the PR and between ba38829 and 7bd6ddc.
You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.
Use the checkbox below for a quick retry:
Trigger review
No actionable comments were generated in the recent review.
Walkthrough
The fused sampling kernel adds a pipelined logit sweep for the cached online-softmax pass. Rejection sampling uses a bounded parallel inverse-CDF walk, with the existing per-thread ordered scan used for unaligned rows or when more than four threads qualify.
Adds forEachLogitPipelined to preload the next aligned vector while preserving per-thread element order. The cached online-softmax pass uses this sweep. Unaligned rows use the original sweep, and trailing elements remain scalar.
Inverse-CDF walk cpp/tensorrt_llm/kernels/fusedSampling/fusedSamplingKernelsCommon.cuh
Adds shared walker state and walkSupport. For aligned rows with at most four qualifying threads, warp 0 processes staged vector weights in ascending thread order, including scalar tail elements. Otherwise, qualifying threads use the per-thread ordered scan. Rejection sampling calls the helper to record the matching token index and weight.
This change speeds up fused sampling in the rejection and temperature-only paths without changing any API or default. The reported results are bit-identical sampled tokens and lower per-launch latency. No concrete defect was found, so the merge risk is minimal.
Architecture risk: Low · up to 6a313
The change affects 1 system.
Changed systems:cpp
Architecture concerns
No architecture-level concerns identified.
Review details
Systems and components
observed — cpp (service) was modified; 1 changed file maps to changed impact.
Before / after behavior
observed — Modified behavior in cpp/tensorrt_llm/kernels/fusedSampling/fusedSamplingKernelsCommon.cuh: Adds kMaxWalkers = 4, the maximum number of parallel walkers handled by walkSupport; larger counts use its fallback walk.
observed — Modified behavior in cpp/tensorrt_llm/kernels/fusedSampling/fusedSamplingKernelsCommon.cuh: Adds forEachLogitPipelined, which preloads the next aligned vector while processing the same elements in the same per-thread order as forEachLogit. Unaligned rows delegate to the original sweep; trailing elements remain scalar.
observed — Modified behavior in cpp/tensorrt_llm/kernels/fusedSampling/fusedSamplingKernelsCommon.cuh: Adds shared state for the number of walkers and each walker's thread ID and starting scan base.
observed — Modified behavior in cpp/tensorrt_llm/kernels/fusedSampling/fusedSamplingKernelsCommon.cuh: Adds walkSupport to locate the inverse-CDF crossing. It counts threads whose scan intervals contain the target; when the count is at most four and the logits are aligned, warp 0 stages vector weights and processes walkers in ascending thread order, including scalar tail elements. When the count exceeds four or the row is unaligned, each eligible thread uses the original per-thread ordered scan. The helper records the matching token index and weight in shared state.
Pre-merge checks: 4
Check name
Status
Explanation
Title check
The title names the main change: a fused sampling kernel update with a parallel inverse-CDF walk and a pipelined first sweep, which matches the changeset. It includes the ticket and type tag in the te…
Description check
The description follows the repository template closely. It covers the problem, the solution, performance numbers, compatibility, and dependencies. The Test Coverage section names existing tests that …
Linked Issues check
Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check
Check skipped because no linked issues were found for this pull request.
Full details: Title check
Explanation
The title names the main change: a fused sampling kernel update with a parallel inverse-CDF walk and a pipelined first sweep, which matches the changeset. It includes the ticket and type tag in the template format. The title is long at 111 characters, but it stays on topic and specific.
Full details: Description check
Explanation
The description follows the repository template closely. It covers the problem, the solution, performance numbers, compatibility, and dependencies. The Test Coverage section names existing tests that cover the changed paths, and it states that no new test was added and why. The PR checklist is present and checked. The description does not fill in the template's HTML comment prompts as separate content, but the required information is present and clear.
Finishing Touches
Generate unit tests (beta)
Create a new PR
Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 7 remain after this review.
…verse-CDF walk and a pipelined first sweep
The tokens-only rejection path draws a token with an inverse-CDF walk: the
thread whose scan interval holds the target re-adds its strided weights until
the running mass passes it. That thread issued one dependent 16-byte load per
step over its whole slice while the block waited, about a third of the kernel
at large batches. The first sweep of a temperature-only row also waited on
each load before processing it.
Now warp 0 loads up to four walkers' vectors in parallel and stages their
weights, computed with the same expression, in shared memory; one lane adds
them in the walker's order from the walker's scan base, so the running sum and
the chosen element are those of the per-thread walk. Overlapping walkers (a
rounding overlap of scan intervals) resolve in ascending thread order. More
than four walkers or an unaligned row keep the per-thread walk. The first sweep
issues the next vector's load before processing the current one, over the
same elements in the same per-thread order.
Same tokens bit for bit: a standalone build of the old and new kernels with
the production flags drew 365,808 tokens with zero mismatches (1,280 to 6
rows, narrow and wide blocks, peaked and all-zero BF16 rows, temperature 1 and
0.7, top-p 0.8-0.95, min-p 0.05, per-row and shared Philox streams).
GB300, vocabulary 129,280, BF16, temperature 1, per launch: 1,280 rows
168.0 -> 117.8 us, 1,264 rows 165.3 -> 118.0 us, 150 rows 45.9 -> 27.1 us.
Test: tests/unittest/_torch/speculative/test_fused_sampling_op.py.
Signed-off-by: ziyixiong-nv <[email protected]>
Signed-off-by: Jin Li <[email protected]>
Automatically added "ci: full pre-merge approved" because this PR has satisfied the required GitHub review approvals. Unresolved review conversations and other required checks remain independent merge requirements.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
This pull request changes one file:
cpp/tensorrt_llm/kernels/fusedSampling/fusedSamplingKernelsCommon.cuh(+194/−28). It makes three changes:forEachLogitPipelined. This helper issues the next vector load before it processes the current one. The cached online-softmax pass uses it. Element order per thread does not change.walkSupport, a helper for the rejection-path inverse-CDF walk. It setskMaxWalkers = 4. When 1 to 4 walkers match and the row is 16-byte aligned, warp 0 stages vector weights in shared memory. Lane 0 then sums them in ascending thread order. Otherwise, the per-thread walk runs.walkers,walkerTid[], andwalkerBase[]toFusedSamplingShared. The rejection path callswalkSupportinstead of an inline per-thread rescan.No public declarations change. No API, configuration, or default changes appear in the diff.
Dev Engineer Review
kMaxWalkersor the row is unaligned. This keeps the old behavior for those cases.walkSupport. No later__syncthreads()runs inside the helper, so the early return is safe. The__shfl_syncand__syncwarpcalls sit outside the lane-0 branch and the loop condition is warp-uniform, so all lanes in warp 0 reach them.shared.cand. The diff does not show whether that buffer also holds candidate data at this point in the kernel. Verify that no live candidate state is overwritten. Thestatic_assertonly checks thatkChunk * kWidth <= kCandCap.sCandIdxandsCandWeightwrites withshared.candIdxandshared.candWeight. Confirm that the old names alias these fields.QA Engineer Review
No test changes.
Per-File QA Perspective
cpp/tensorrt_llm/kernels/fusedSampling/fusedSamplingKernelsCommon.cuh: Rejection-path sampling and the temperature-only first sweep now use new code paths. QA should check sampled tokens against the previous kernel for BF16 logits, including unaligned rows and cases with more than four matching walkers. The PR description referencestests/unittest/_torch/speculative/test_fused_sampling_op.pyas coverage for these paths. This PR does not modify that file.Description
Summary
The fused sampling kernel's tokens-only rejection path draws a token with an inverse-CDF walk: the one thread whose
scan interval holds the target re-adds its own strided weights until the running mass passes it. That thread issued
one dependent 16-byte load per step over its whole slice (32 vectors of a 129K-entry BF16 row) while the block's
other threads waited, about a third of the kernel at large batches. Plain temperature sampling (no top-k or min-p)
also waited on each load of its first sweep before processing it.
This PR keeps the walk's arithmetic and order and removes the waiting: warp 0 loads the walker's vectors in parallel
and one lane sums them, and the first sweep issues the next vector's load before it processes the current one. The
sampled tokens are bit-identical.
Changes
cpp/tensorrt_llm/kernels/fusedSampling/fusedSamplingKernelsCommon.cuhonly:walkSupportreplaces the per-thread walk. Each thread whose interval holds the target registers itself as awalker in shared memory. For up to
kMaxWalkers(4) walkers, warp 0 loads 32 of the walker's vectors at a time,computes their weights with the walk's own expression into the
candscratch buffer (unused by the rejection pathat that point), and lane 0 adds them in the walker's order, then walks the scalar tail.
forEachLogitPipelinedisforEachLogitwith the next vector's load issued first; the first sweep of a row whoserejection path reuses the per-thread online-softmax partials uses it.
Performance
GB300, vocabulary 129,280, BF16 logits, temperature 1, one launch:
DeepSeek-V4.1 runs one launch per generation step. The end-to-end effect was measured only together with two other
generation-step changes (row-bounded CSA2 page tables and the padded Engram decode refresh): at the high-throughput
attention-DP point (320 sequences per rank), the steady-state generation step went 31.06 -> 30.66 ms (-1.3%) and
output throughput +1.5%. This PR alone was not measured end to end.
Compatibility
by construction (above), so it is not gated.
temperature-only row change; probability outputs and the descent path are untouched.
Dependencies
None. Independent of the other PRs of this set.
Test Coverage
No new test: the old walk is gone, so there is no plain path left to compare against in the tree. The existing
tests/unittest/_torch/speculative/test_fused_sampling_op.pycovers the rejection path (tokens in the filteredsupport, the filtered distribution, rejection rounds that narrow the support, seed reproducibility, the rejection
and descent kept sets) and the plain temperature path.
PR Checklist
Please review the following before submitting your PR:
PR description clearly explains what and why. If using CodeRabbit's summary, please make sure it makes sense.
PR Follows TRT-LLM CODING GUIDELINES to the best of your knowledge.
Test cases are provided for new code paths (see test instructions)
If PR introduces API changes, an appropriate PR label is added - either
api-compatibleorapi-breaking. Forapi-breaking, includeBREAKINGin the PR title.Any new dependencies have been scanned for license and vulnerabilities
CODEOWNERS updated if ownership changes
Documentation updated as needed
Update tava architecture diagram if there is a significant design change in PR.
The reviewers assigned automatically/manually are appropriate for the PR.
Please check this after reviewing the above items as appropriate for this PR.