Skip to content

Add an opt-in BF16 R2S-K backend for token sampling - #95

Open
SiraajR wants to merge 13 commits into
modelscope:mainfrom
SiraajR:r2sk-bf16-sampling
Open

SiraajR wants to merge 13 commits into
modelscope:mainfrom
SiraajR:r2sk-bf16-sampling

Conversation

@SiraajR

@SiraajR SiraajR commented Nov 23, 2026 •

Copy link
Copy Markdown

Summary

Add an opt-in BF16 R2S-K backend for token sampling. It preserves confirmed winners during radix refinement and can finish by sorting a small candidate superset. It uses DashInfer's shared top-k/top-p arena and returns descending BF16 scores with row-relative token IDs.

Both opt-ins default to off. Enable the build with ENABLE_R2SK_SAMPLING=ON and the runtime with AS_ENABLE_R2SK_SAMPLING=1. The backend supports Ampere and newer GPUs, finite BF16 logits, and 2 <= k <= 256 with k < vocabulary. Unsupported inputs use the existing sampling paths. Equal BF16 scores can select different valid token IDs at the cutoff.

Sampling error handling. RunSample now propagates errors returned by the sampling launcher through AS_CHECK_STATUS, including when R2S-K is disabled. For example, when max_k exceeds the vocabulary size, RunSample now returns the launcher error. Previously the launcher logged the error and RunSample continued.

Results on NVIDIA L40S

Both selectors used the same DashInfer checkout, CUDA 12.4.131, and BF16 logits captured from Qwen2.5-1.5B-Instruct. Vocabulary was 151,936 and k was 20. Each shape used one real capture, with 101 measured calls per backend after 10 warmups. Both outputs passed an exact CPU reference for sorted values and input occurrence indices.

Batch RadiK selector median R2S-K selector median Lower selector latency RadiK scratch R2S-K scratch
1 73.95 µs 47.79 µs 35.4% 1,231,900 B 1,874,176 B
16 80.79 µs 69.26 µs 14.3% 19,710,340 B 29,975,552 B

The selector requires about 52% more scratch on these shapes. The shared engine arena was 63,205,712 bytes in both arms at configured maximum batch 16 because the top-p scratch reservation already covered the larger requirement.

A separate source-built Qwen benchmark measured request submission through completion, including prefill, decode and sampling. It used 20 timed cohorts per arm and batch size across four paired process blocks, with 96 output tokens per request. Prefix caching and early stopping were disabled to match work, and dispatch tracing was off during timing.

Concurrent requests RadiK median R2S-K median RadiK output throughput R2S-K output throughput
1 622.90 ms 621.88 ms 154.1 tokens/s 154.4 tokens/s
16 819.48 ms 812.30 ms 1,874.4 tokens/s 1,890.9 tokens/s

Batch 1 was effectively even. Batch 16 median latency was 0.88% lower, with all four paired block medians favoring R2S-K. These are results for one checkpoint and GPU. Answer-quality equivalence remains unverified.

Validation

  • CUDA-enabled source build, x86 CPU-only default build, and CMake-built selector test on L40S passed.
  • Compute Sanitizer memcheck, synccheck and racecheck reported zero errors or hazards in the selector suite.
  • In a separate traced generation test, both backends completed 16 matched BF16 requests and reached active batch 16. R2S-K dispatched on 62 of 62 eligible calls. All 32 calls at k=512 used RadiK with R2S-K enabled.
  • Both log-probability arms returned finite values for all 32 generated tokens. This check used ALLSPARK_DISABLE_WARMUP=1 in both arms after default warm-up left insufficient allocator memory for the RadiK arm's log-probability buffer.

Reproduction

See the build, correctness, and replay guide. The build was tested against upstream 06669fa30816f828c53ea144a7a9ac01507df5b5.

AS_BUILD_R2SK_SAMPLING=ON AS_CUDA_VERSION=12.4 AS_CUDA_SM=89 bash build.sh
ctest --test-dir build -R '^cpp_r2sk_sampling_test$' --output-on-failure

@kzjeef kzjeef left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the careful PR. The writeup is unusually honest about its limits, and the opt-in design keeps the default path safe. I tested it on a GB300 (sm_103, CUDA 13.1). The base tree needs conan 1.x and x86 NCCL, so I couldn't build the full engine there. Instead I built the R2S-K selector and the in-tree RadiK on their own with nvcc and compared them directly.

Correctness: looks solid

  • cpp_r2sk_sampling_test passes. compute-sanitizer memcheck, racecheck, synccheck and initcheck all report 0 errors.
  • I compared it against a CPU reference with randomized inputs: 544 cases and 2.1M outputs. Vocab sizes ran from 3 to 248,320, batch from 1 to 255 and k from 2 to 256. Inputs included tie-heavy rows, all-equal rows, mixed ±0, outliers and values near the largest finite negative. There were 0 mismatches and 0 unexpected fallbacks, and the input was never modified.

Performance (GB300, median host µs per call, including the stream sync)

vocab batch k=20 k=50 k=256
151,936 1 +18 to +22% +5 to +19% −16% to +10%
151,936 16 +11 to +12% +11% −13% to +1%
151,936 64 +17% +16 to +17% −16% to +4%
151,936 256 +18 to +21% +19 to +21% +5 to +13%
248,320 1 to 256 +7 to +28% +5 to +24% +3 to +23%

Positive numbers mean R2S-K is faster. The negative cells are Gaussian logits at k=256. Scratch is about 1.5× RadiK's at every shape, for example 776 MB against 513 MB at batch 256 and vocab 248,320.

Concerns before merging

  1. CUDA graphs. Try() declines whenever the stream is capturing. The batch driver also synchronizes the stream several times per call to read decisions and counters back to the host (r2sk.cu:671, :702), and it creates its own stream. Decode sampling is moving toward graph capture, where this backend would never dispatch. Could the per-pass decisions stay on the device, for example with a fixed number of passes or device-side scheduling, so that it can be captured?
  2. End-to-end benefit. The reported gain is 0.88% at batch 16 and flat at batch 1, on one model and one GPU. Answer-quality equivalence is unverified. Numbers on a larger model or on Hopper/Blackwell would help, ideally with a quality check under top-k/top-p sampling.
  3. Slower at large k. k=256 is 13–16% slower in the cases above. Please consider a dispatch threshold on k, or explain the cause.
  4. No CI coverage. The CMake option defaults to OFF, and the test is only built when it is ON, so CI never compiles or runs this code. Please add at least one CI configuration that builds with ENABLE_R2SK_SAMPLING=ON and runs cpp_r2sk_sampling_test.
  5. Code style. r2sk.cu (844 lines) and the headers are written as dense one-statement-per-line code. Please reformat to the project's clang-format style. That would make long-term maintenance and review practical.

Minor

  • RunSample now wraps the launcher in AS_CHECK_STATUS, which changes default-build behavior. For example, max_k > length used to log and continue, and now it returns an error. That seems like a good fix, but please call it out in the description.
  • Licensing: only sampling.cu/.h carry an SPDX header. r2sk.cu and the six r2sk/*.hpp headers have no license or copyright notice. Please add SPDX headers to every new file (the RadiK-derived parts are already credited via LICENSE.RadiK).
  • Provenance: is R2S-K derived from a separate project or publication? If so, please link it and state its license.

Happy to re-test on GB300 once these are addressed.

@SiraajR

SiraajR commented Nov 24, 2026 •

Copy link
Copy Markdown
Author

Hi @kzjeef, thanks for the careful review and the GB300 measurements. Here’s where the updates stand.

  1. CUDA graphs. The opt-in sampler subgraph keeps the radix decisions on the GPU and replayed top-k, top-p and token sampling during Qwen decode. That result is limited to the graph DashInfer owns. Eager Try() still synchronizes for host decisions and declines an already-capturing stream. Prepare() also declines outer capture and reads a nonfinite flag back to the host before the sampler graph runs. Whole-decode capture is still open. Selector · Sampler graph · HIE-DNN event handling · Graph integration
  2. End-to-end and quality. The H100 run still uses Qwen2.5-1.5B-Instruct. Graph R2S-K had 1.90% and 0.95% lower median request latency than eager RadiK at concurrency 1 and 16, respectively. At 16 the timing ranges overlap and eager R2S-K has a slightly lower median than graph R2S-K. The sampled GSM8K intervals still allow a quality drop. Validation report
  3. Large k. Your GB300 cases consistently favored R2S-K at k=50. Eager Try() now declines above that cutoff, and the existing launcher routes those calls to RadiK. Eligible opt-in graph calls still support ranks through 256. In the pre-cutoff B200 Gaussian test at k=256, eager R2S-K was 4.1% slower at batch 16 and 23.3% slower at batch 64. The cutoff routes around those eager regressions. Dispatch change
  4. CI. The CUDA package job gives compile coverage. The earlier CPU runner skipped the CUDA tests, and the H100 passes came from a separate GPU run. The new manual GPU workflow requires a configured GPU runner and runs the eager selector, selector graph, and decode parity tests directly. Its GitHub Actions execution is still unverified.
  5. Formatting. I reformatted the CUDA and C++ sources using DashInfer’s clang-format rules. Formatting commit

The PR description calls out the RunSample error propagation change. I also added SPDX headers to the new files. SPDX commit

R2S-K comes from my private radik-design prototype, which has no repository-wide license. The DashInfer contribution is Apache-2.0 and retains the MIT notice for the RadiK-derived portions. Source attribution

If you have time to retest on GB300, a check that k=50 still dispatches and k=256 takes the eager RadiK fallback would be helpful.

@SiraajR SiraajR closed this Nov 24, 2026
@SiraajR SiraajR reopened this Nov 24, 2026
@SiraajR

SiraajR commented Nov 25, 2026 •

Copy link
Copy Markdown
Author

Hi @kzjeef, I explored few other ideas and have an update on the large-k regression. The opt-in eager backend now uses the BF16 device controller through k=256, replacing the earlier host-controlled path and its k=50 cutoff. It launches on the regular CUDA stream and reads the fused finite-input flag during DashInfer's existing synchronization. The sampler graph remains a separate opt-in. Implementation (SiraajR@b65f08d)
On H100, the integrated eager path was 1.31×–2.18× faster than eager RadiK in all 48 BF16 selector cases, with separated timing IQRs. At k=256, the range was 1.31×–1.96×. I used your vocabulary, batch and rank matrix with generated Gaussian and uniform inputs. Selector scratch was about 24% smaller. Sweep and reproduction commands validation
In the Qwen2.5-1.5B-Instruct streaming run at concurrency 16, eager R2S-K lowered median cohort latency by 2.95% at k=20 and 1.75% at k=256. The k=256 timing IQRs overlapped, and traces confirmed R2S-K eager dispatch at that rank. All three CUDA correctness tests passed on H100. Serving and validation details validation
Sorry if these are too many changes in too short of a time, I could make a PR related to this later if thats convenient to you or update the PR description. If you do go ahead with this , if you could test it on the GB300s it would be interesting to see whether the Gaussian k=256 cases show the same improvement.

@kzjeef
kzjeef requested a review from leefige November 26, 2026 09:03
@SiraajR
SiraajR requested a review from kzjeef November 27, 2026 03:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants