Skip to content

[TRTLLM-16622][perf] DeepSeek-V4.1: fused sampling with a parallel inverse-CDF walk and a pipelined first sweep - #22356

Merged
liji-nv merged 1 commit into
NVIDIA:mainfrom
ziyixiong-nv:dsv41-mb/pr05-fused-sampling-walk
Nov 18, 2026
Merged

liji-nv merged 1 commit into
NVIDIA:mainfrom
ziyixiong-nv:dsv41-mb/pr05-fused-sampling-walk

Conversation

@ziyixiong-nv

@ziyixiong-nv ziyixiong-nv commented Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

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.

Changes

cpp/tensorrt_llm/kernels/fusedSampling/fusedSamplingKernelsCommon.cuh only:

  • 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.

  • 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-compatible or api-breaking. For api-breaking, include BREAKING in 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.

@coderabbitai

coderabbitai Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Important

Review skipped

Review was skipped as selected files did not have any reviewable changes.

Run configuration

Commits

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.

Changes

Fused sampling kernel

Layer / File(s) Summary
Pipelined logit sweep
cpp/tensorrt_llm/kernels/fusedSampling/fusedSamplingKernelsCommon.cuh
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.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Refactor

Suggested reviewers: qijune, lori-ren

Merge Risk: Minimal · previous review 6a313

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: Passed 4

Check name Status Explanation
Title check Passed 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 Passed 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 Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed 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
Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 3a426e2 and 6a3135d.

Files selected for processing: 1

  • cpp/tensorrt_llm/kernels/fusedSampling/fusedSamplingKernelsCommon.cuh

Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 7 remain after this review.

@liji-nv
liji-nv force-pushed the dsv41-mb/pr05-fused-sampling-walk branch from 6a3135d to ba38829 Compare November 17, 2026 05:53
…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]>
@liji-nv
liji-nv force-pushed the dsv41-mb/pr05-fused-sampling-walk branch from ba38829 to 7bd6ddc Compare November 17, 2026 06:08
@github-actions

Copy link
Copy Markdown

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.

@liji-nv

liji-nv commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #85385 [ run ] triggered by Bot. Commit: 7bd6ddc Link to invocation

@liji-nv
liji-nv enabled auto-merge (squash) November 17, 2026 10:08
@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #85385 [ run ] completed with state SUCCESS. Commit: 7bd6ddc
/LLM/main/L0_MergeRequest_PR pipeline #70684 completed with status: 'FAILURE'

CI Report

⚠️ Action Required:

  • Please check the failed tests and fix your PR
  • If you cannot view the failures, ask the CI triggerer to share details
  • Once fixed, request an NVIDIA team member to trigger CI again

CI Agent Failure Analysis

Link to invocation

@liji-nv

liji-nv commented Nov 18, 2026

Copy link
Copy Markdown
Collaborator

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #85632 [ run ] triggered by Bot. Commit: 7bd6ddc Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #85632 [ run ] completed with state SUCCESS. Commit: 7bd6ddc
/LLM/main/L0_MergeRequest_PR pipeline #70889 completed with status: 'SUCCESS'

CI Report

Link to invocation

@liji-nv
liji-nv merged commit 1e61f3b into NVIDIA:main Nov 18, 2026
14 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants