Skip to content

[Speculative] Add opt-in block verification - #42297

Merged
Qiaolin-Yu merged 7 commits into
sgl-project:mainfrom
maocheng23:codex/block-verification
Oct 5, 2026
Merged

Qiaolin-Yu merged 7 commits into
sgl-project:mainfrom
maocheng23:codex/block-verification

Conversation

@maocheng23

@maocheng23 maocheng23 commented Oct 3, 2026 •

Copy link
Copy Markdown
Collaborator

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

  • Add opt-in --speculative-use-block-verification; this flag automatically enables the required proposal sampling and draft-probability storage. --speculative-use-rejection-sampling alone 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.
  • Extend the existing Triton chain sampler with a compile-time branch. Compute 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.
  • Skip a prefix's vocabulary reduction when its coin is already at least r_i, using h_i <= r_i for 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.
  • Add a reproducible sampler benchmark with optional comparison against a saved baseline kernel.
  • Reuse proposal buffers, output indices, TP synchronization, and the greedy verification path. No scheduler or KV-cache changes; the existing verification defaults remain unchanged.
  • Document the option and add focused kernel and configuration tests.

Accuracy Tests

The optimized sampler at 42d866ccd5 was validated on one NVIDIA GB300 (Torch 2.13.0+cu130, Triton 3.7.1):

PYTHONPATH=python CUDA_VISIBLE_DEVICES=0 python -m pytest -q \
  test/registered/kernels/ops/speculative/test_block_verification.py \
  test/registered/unit/spec/test_block_verification_args.py

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/9 versus 11/9 accepted-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 the h_i <= r_i shortcut across draft lengths 0–6.

Local configuration tests and CLI parsing passed. All pre-commit hooks applicable to the changed files passed; git diff --check passed. 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 a 1e-6 probability 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.

Metric Token-wise Block Change
Acceptance length (includes bonus) 2.9802 3.0063 +0.88%
Output throughput (tokens/s) 988.43 995.36 +0.70%
Boxed score over entire response 76/90 (84.44%) 77/90 (85.56%) +1.11 pp
Boxed score after </think> 70/90 (77.78%) 65/90 (72.22%) -5.56 pp
Responses hitting the 32,768-token cap 20/90 22/90

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 b40ee2c99a17341d35ff1e47684bc8a471797d74 and --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.

Seed Token AL Block AL Token tok/s Block tok/s Token entire-response correct Block entire-response correct
980406 2.9725 3.0225 959.37 985.39 26/30 25/30
981406 2.9736 2.9890 995.39 999.45 25/30 25/30
982406 2.9947 3.0069 1011.64 1001.61 25/30 27/30

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 three triton.testing.do_bench runs with 100 ms warmup and 500 ms measurement; implementation order alternates between repetitions.

Batch Token before Token after Block before Block after Block latency reduction
1 62.08 µs 61.97 µs 159.69 µs 58.07 µs 63.6%
16 104.81 µs 105.12 µs 207.87 µs 132.83 µs 36.1%
128 133.91 µs 133.39 µs 250.78 µs 146.25 µs 41.7%

Additional paired block-sampler measurements (before → after):

Drafts Vocabulary Batch 1 Batch 16 Batch 128
3 131072 127.61 → 57.32 µs 163.45 → 113.39 µs 184.65 → 131.07 µs
5 131073 233.53 → 79.08 µs 334.14 → 166.65 µs 334.20 → 166.38 µs

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

The 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

  • Format code with pre-commit.
  • Add registered unit tests.
  • Update documentation.
  • Provide output-distribution checks and sampler speed measurements.
  • Follow SGLang code style.

CI States

Latest PR Test (Base): ❌ Run #37232790252
Latest PR Test (Extra): ⚠️ Not enabled -- add run-ci-extra label to opt in.
Latest PR Test (AMD ROCm 10): ❌ Run #37232790196

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

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.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I think its a good idea

@Qiaolin-Yu Qiaolin-Yu self-assigned this Oct 3, 2026
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.
@Qiaolin-Yu Qiaolin-Yu added run-ci CI: run the baseline test suite on this PR bypass-fail-fast CI: a failing job no longer aborts its siblings (lint still gates) labels Oct 4, 2026
@Qiaolin-Yu

Copy link
Copy Markdown
Collaborator

/tag-and-rerun-ci

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.
@Qiaolin-Yu
Qiaolin-Yu merged commit 57826a6 into sgl-project:main Oct 5, 2026
229 of 256 checks passed
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.
@Qiaolin-Yu Qiaolin-Yu added the release-highlight Candidate PR for release note highlight label Oct 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bypass-fail-fast CI: a failing job no longer aborts its siblings (lint still gates) documentation Improvements or additions to documentation jit-kernel release-highlight Candidate PR for release note highlight run-ci CI: run the baseline test suite on this PR speculative-decoding

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants