Repository navigation
[Speculative] Add opt-in block verification - #42297
Merged
Merged
Conversation
maocheng23
marked this pull request as ready for review
October 3, 2026 09:20
maocheng23
requested review from
BBuf,
DarkSharpness,
HaiShaw,
HydraQYH,
JustinTong0323,
Qiaolin-Yu,
Ying1123,
celve,
hnyls2002,
merrymercy,
sogalin,
wisclmy0611,
yuan-luo and
zijiexia
as code owners
October 3, 2026 09:20
Qiaolin-Yu
reviewed
Oct 3, 2026
Comment on lines
116
to
+123
| speculative_use_rejection_sampling: A[ | ||
| bool, "Use rejection sampling for speculative decoding (requires topk=1)." | ||
| ] = False | ||
| speculative_use_block_verification: A[ | ||
| bool, | ||
| "Use block verification for EAGLE/EAGLE3/NEXTN on CUDA or ROCm " | ||
| "(requires --speculative-use-rejection-sampling and topk=1).", | ||
| ] = False |
Collaborator
There was a problem hiding this comment.
shall we deprecate speculative_use_rejection_sampling and change it to speculative_accept_strategy:string and pass in target_only (default), rejection_sampling, or block_verification? It's fine to do in the seperate prs.
Collaborator
Author
There was a problem hiding this comment.
I think its a good idea
Resolve the shared rejection-sampling setting automatically before compatibility validation and worker initialization. Preserve raw arguments and existing token verification modes; update CLI help, documentation, and configuration tests. Addresses review feedback from @Qiaolin-Yu on sgl-project#42297.
Collaborator
|
/tag-and-rerun-ci |
Qiaolin-Yu
approved these changes
Oct 4, 2026
Initialize the new opt-in field to false in the custom algorithm fixture so argument resolution reaches the plugin hook. This fixes the missing-attribute error in CPU CI and the duplicate registration reported by its retry.
Remove obsolete topology arguments and explicitly disable deferred bootstrap in the immediate-registration fixture. This fixes the separate CPU partition failure after merging main.
FP32 CDF reductions can choose neighboring token IDs when the uniform draw lies within rounding error of a boundary. Keep accepted lengths, draft tokens, and output indices exact, and validate the final token against an FP64 CDF with a 1e-6 probability tolerance and positive support. Validated all 23 sampler cases on GB300; no production sampler changes.
4 of 5 tasks
Merged
6 tasks done
nvpohanh
added a commit
to ajit283/sglang
that referenced
this pull request
Oct 6, 2026
Block verification forces rejection sampling, which this PR makes deterministic via seeded draft and verify draws, so --enable-deterministic-inference is no longer rejected on CUDA. Update the test from sgl-project#42297 accordingly. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ischencheng
added a commit
to ischencheng/sglang
that referenced
this pull request
Oct 6, 2026
Resolve the reject_sampling.py conflict with sgl-project#42297: apply the _Q_PROB_MAX tolerance and clamp to the new block-verification guard as well as the token-verification one.
ischencheng
added a commit
to ischencheng/sglang
that referenced
this pull request
Oct 6, 2026
Run the chain-verify q tolerance tests with block_verification on and off, since sgl-project#42297 added a second guard on q.
5 tasks done
5 tasks done
5 tasks done
Open
1 task done
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Motivation
Add the block verifier from Block Verification Accelerates Speculative Decoding, Algorithm 2. Standard rejection sampling stops at the first rejected draft token. Block verification selects the longest accepted prefix and can accept a longer prefix after an earlier rejection, with a scaled correction distribution that preserves target sampling.
Modifications
--speculative-use-block-verification; this flag automatically enables the required proposal sampling and draft-probability storage.--speculative-use-rejection-samplingalone selects token-wise rejection sampling, and passing both flags remains supported. Support the existing linear EAGLE/EAGLE3/NEXTN proposal path (--speculative-eagle-topk 1) on CUDA/ROCm, with startup validation for unsupported configurations.r_i = min(1, r_(i-1) * p(x_i) / q(x_i))forward, then test prefixes longest-first and stop at the first acceptance. The original per-prefix random samples are retained, so skipped shorter-prefix tests cannot change the selected prefix. Commit that prefix once and sample correction from normalized(r_tau * p - q)+; full acceptance samples the bonus token from the target.r_i, usingh_i <= r_ifor normalized distributions. Reuse the selected prefix's residual mass for correction normalization. Use a separate reduction tile capped at 32768 with 8 warps for large vocabularies; keep the final CDF tile at 4096. Token verification retains its original acceptance loop and 4-warps launch.Accuracy Tests
The optimized sampler at
42d866ccd5was validated on one NVIDIA GB300 (Torch 2.13.0+cu130, Triton 3.7.1):25 passed, 12 configuration subtests passed. Coverage includes both token/block paths against a reference, accepting past an earlier rejection, longest-prefix selection for every accepted length, strict acceptance-threshold boundaries (including
h_i == r_i), scaled residuals, zero/unit probabilities, zero/one/multiple drafts, strided tensors, vocabulary tails up to 131073, and global output-index mapping. Statistical tests use 65,536 samples each to check the paper's expected acceptance lengths and the complete output joint distribution, including context-dependent targets with two and five drafts.Compute Sanitizer memcheck passed all 17 non-statistical kernel cases with 0 errors. An additional 4800 per-sequence comparisons against the pre-optimization kernel covered three seeds, 0/1/3/5/8 drafts, five vocabulary sizes through 131073, and both verification modes: accepted lengths, output indices, and all valid output tokens matched exactly in these cases. This is observed parity, not a general bitwise guarantee for block verification after changing floating-point reduction order.
Independent exact rational enumeration reproduced the paper's
10/9versus11/9accepted-draft example and target joint distributions for context-dependent binary models with draft lengths 1–5. A separate 42,252-case rational check validates longest-first selection and theh_i <= r_ishortcut across draft lengths 0–6.Local configuration tests and CLI parsing passed. All pre-commit hooks applicable to the changed files passed;
git diff --checkpassed. The full-model results below were obtained before this sampler optimization and have not been rerun on the optimized kernel. ROCm execution is not yet validated.The subsequent CLI change (
25fca89325) passed 17 CPU tests and 23 subtests across block-verification configuration, EAGLE gate routing / ROCm defaults, and CLI metadata. A block-only CLI smoke test also verified that the published scheduler configuration enables both required sampler settings while preserving raw user arguments. The kernel is unchanged; GPU benchmarks were not repeated for this CLI change. Mintlify validation could not run locally because its CLI is unavailable.The CI follow-up (
3e5cd56c29) fixes the custom-algorithm and bootstrap-registration test fixtures. The random sampler reference now uses FP64 arithmetic and checks the final token's CDF interval with a1e-6probability tolerance; accepted lengths, draft tokens, and output indices remain exact. This handles FP32 boundary rounding without tolerating arbitrary token-ID differences. Validation: 57 CPU tests and 21 subtests passed, plus all 23 sampler tests on GB300 (Torch 2.13.0 / Triton 3.7.1). No production code changed in this follow-up; the original H100 job will be checked by the CI rerun.Speed Tests and Profiling
Qwen3.8-27B / AIME25 end-to-end
These are historical measurements at
b40ee2c99a17341d35ff1e47684bc8a471797d74, before the sampler optimization.</think>AL increased in all three seed pairs. The pooled throughput increase is small (+0.70%); per-seed changes were +2.71%, +0.41%, and -0.99%, so this does not establish a consistent throughput speedup. The original entire-response score counts boxes inside reasoning, including 6 token-wise and 12 block responses that hit the cap. The added post-
</think>score uses only the answer text after that marker and counts missing answers as incorrect. The 32k cap and three sampled runs limit quality comparisons; neither score difference establishes a quality change. All 23 responses without a parsed integer hit the token cap.One NVIDIA GB300, TP1, Qwen/Qwen3.8-27B BF16 revision
1d4bf0f2ff6012fd82039f2fa52739d0dd7c60c0, native MTP, three proposed tokens (EAGLE, steps=3, topk=1, draft-tokens=4). BF16 KV cache, FP32 recurrent state, FlashInfer attention and Triton GDN, CUDA graphs enabled, concurrency 8. Thinking enabled, xhigh template setting, temperature 1.0, top-p 0.95, top-k 20, maximum 32,768 new tokens. All 30 MathArena/aime_2025 questions for each of three seeds; 90 attempts per arm, 180 total.Both arms use commit
b40ee2c99a17341d35ff1e47684bc8a471797d74and--speculative-use-rejection-sampling. The block arm adds only--speculative-use-block-verification. Each run warms eight slots and flushes the cache before timing. Arm order alternates by seed. Startup and warmup are excluded. Incremental native streaming avoids repeatedly transferring the entire output prefix.Acceptance length is total completion tokens / total verification steps, including the bonus token. Throughput is total output tokens / total measured wall time, including prefill and the final partially occupied batches. Both answer scores use the last boxed integer in their specified text region; cap hits are retained in the denominator. These are stochastic runs at one concurrency and draft length.
Torch 2.13.0+cu130, Triton 3.7.1, sglang-kernel 0.4.8, FlashInfer 0.7.0.post1, Transformers 5.17.0, NVIDIA driver 590.48.01.
Sampler microbenchmark
Paired sampler-only measurements of the pre-optimization kernel (
b40ee2c99a17341d35ff1e47684bc8a471797d74) and optimized kernel on the same GB300, Torch 2.13.0+cu130 / Triton 3.7.1. FP32, five drafts, vocabulary 131072,q = 0.7*p + 0.3*softmax(random logits), seed 2026. Each cell is the median of threetriton.testing.do_benchruns with 100 ms warmup and 500 ms measurement; implementation order alternates between repetitions.Additional paired block-sampler measurements (before → after):
Reproduce the primary comparison:
git show b40ee2c99a17341d35ff1e47684bc8a471797d74:python/sglang/kernels/ops/speculative/reject_sampling.py > /tmp/reject_sampling_before.py PYTHONPATH=python python benchmark/kernels/bench_block_verification.py \ --baseline-file /tmp/reject_sampling_before.pyThe final CDF sampling still scans vocabulary tiles; block verification additionally reduces vocabulary rows only for unresolved candidate prefixes. Longest-first selection eliminates those extra reductions when the full block is accepted. The remaining cost depends on the sampled proposals and prefix acceptance, so these results do not establish that block verification is always faster than token verification. They measure sampler cost only; the historical end-to-end results above have not been rerun after this optimization.
Checklist
CI States
Latest PR Test (Base): ❌ Run #37232790252⚠️ Not enabled -- add
Latest PR Test (Extra):
run-ci-extralabel to opt in.Latest PR Test (AMD ROCm 10): ❌ Run #37232790196