Skip to content

[6/6][kimi-deterministic] Use deterministic seeded coins for EAGLE rejection sampling - #30822

Merged
ch-wan merged 15 commits into
sgl-project:mainfrom
zyzshishui:kimi-deterministic/6-eagle-seeded-coins
Jul 24, 2026
Merged

ch-wan merged 15 commits into
sgl-project:mainfrom
zyzshishui:kimi-deterministic/6-eagle-seeded-coins

Conversation

@zyzshishui

@zyzshishui zyzshishui commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Stacked series (6/6, tip): stacked on kimi-deterministic/5-logsoftmax-decode-logprobs (#30821), so the diff below includes the whole series. This PR's own changes are the last 4 commits (ending 18f2f50 — incl. the murmur_hash32 relocation to sglang.kernels). CI on this PR covers the combined series.

Motivation

EAGLE verify draws rejection-sampling coins from torch.rand, so speculative outputs are not reproducible even with per-request sampling_seed. (Part 6/6 of the kimi-deterministic series.)

Modifications

When sampling_seed is set, coins come from murmur_hash32(seed, seq_lens, column) (first draft_token_num columns: rejection coins; last column: final-sampling coin), extracted into _seeded_verify_coins. Unseeded requests keep torch.rand.

Per review: the float32 cast rounds the top 129 uint32 hashes to exactly 1.0 while the sampling kernels expect half-open [0, 1) coins, so the coins are clamped to the largest float32 below one (every other coin value is bit-identical, keeping verified baselines intact).

Scope: this seeds only the verify-side RNG. Under speculative_use_rejection_sampling the draft workers still select candidates via unseeded multinomial (fast_sample in eagle_worker_v2), so classic rejection-sampling mode remains non-deterministic until the draft RNG is seeded in a follow-up; top-k/greedy draft selection (e.g. EAGLE3 topk-1) is fully deterministic with this change.

Accuracy Tests

Unseeded path unchanged. Unit tests (test/registered/unit/spec/test_eagle_seeded_coins.py) lock seeded-coin reproducibility, seed/position sensitivity, and the max-hash clamp. E2E: Kimi-K2 + EAGLE3 (steps 3 / topk 1 / draft 4, fa4 draft backend, 16 GPUs TP16/DP8/EP16) passes the full 7-phase invariance suite bitwise at temperature 0 and 1.0 with this series applied; non-greedy replay diverged before this change and is bitwise-stable after.

Speed Tests and Profiling

Hash only for seeded requests; no impact otherwise.

Checklist

Review and Merge Process

  1. Ping Merge Oncalls to start the process. See the PR Merge Process.
  2. Get approvals from CODEOWNERS and other reviewers.
  3. Trigger CI tests with comments or contact authorized users to do so.
    • Common commands include /tag-and-rerun-ci, /tag-run-ci-label, /rerun-failed-ci
  4. After green CI and required approvals, ask Merge Oncalls or people with Write permission to merge the PR.

CI States

Latest PR Test (Base): ❌ Run #29979964999
Latest PR Test (Extra): ❌ Run #29979964951

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@zyzshishui
zyzshishui force-pushed the kimi-deterministic/6-eagle-seeded-coins branch from 965f834 to ece3504 Compare July 10, 2026 22:21
@zyzshishui
zyzshishui marked this pull request as ready for review July 11, 2026 00:40
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

coins = torch.rand_like(candidates, dtype=torch.float32, device=device)
# coins for final sampling
coins_for_final_sampling = torch.rand((bs,), dtype=torch.float32, device=device)
sampling_seed = sampling_info.sampling_seed

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.

[suggestion] When sampling_seed is not None, verify-side coins become deterministic, but under speculative_use_rejection_sampling the draft path still selects candidates via fast_sample → torch.multinomial (see eagle_worker_v2.py draft_forward / draft_extend paths). Different draft tokens across runs will still produce different verify outcomes even with identical seeded coins. Tree mode without rejection sampling (deterministic fast_topk/argmax drafts) is much closer to full determinism after this change; classic rejection-sampling mode is not.

Suggestion: Either seed draft multinomial with the same murmur_hash32/multinomial_with_seed pattern (distinct column space from verify coins), or explicitly document in the PR/series that part 6 only closes the verify-coin RNG and rejection-sampling drafts remain non-deterministic until a follow-up.

cols = torch.arange(
verify_input.draft_token_num + 1, device=device, dtype=torch.int64
)
hashed = murmur_hash32(

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.

[suggestion] No unit or e2e test asserts that fixed sampling_seed yields identical EAGLE accept lengths / bonus tokens across runs (or that unseeded still uses torch.rand). The PR body acknowledges this. A small GPU unit test that mocks target_probs/draft_probs/candidates and checks eagle_sample coin-driven outputs for two identical seeds would catch regressions in column split, salt choice, and dtype conversion without a full server.

Suggestion: Add a focused test (kernel-level or eagle_sample with fixed logits) for (seeded invariance) and (seeded vs unseeded branch). Prefer also an e2e speculative invariance run once the series is complete.

verify_input.draft_token_num + 1, device=device, dtype=torch.int64
)
hashed = murmur_hash32(
sampling_seed.to(torch.uint64), batch.seq_lens.to(torch.uint64), cols

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.

[bug] hashed / UINT32_MAX is not guaranteed to remain in [0, 1) after conversion to float32. The highest 129 uint32 hash values round to exactly 1.0 (about one coin in 33 million). Both sampling kernels expect a half-open uniform range. In the rejection-sampling final CDF, coin == 1.0 makes the target equal the complete probability sum; the strict cumsum > target comparison finds no token and falls back to VOCAB_SIZE - 1, potentially selecting a zero-probability token. Endpoint rejection coins can also bias draft acceptance.

Suggestion: Clamp the float32 coins to the largest representable value below one, or construct them from truncated hash bits so the range is inherently [0, 1). Add a regression test covering the maximum hash value.

@ch-wan ch-wan removed the run-ci CI: run the baseline test suite on this PR label Jul 22, 2026
@zyzshishui

Copy link
Copy Markdown
Contributor Author

/rerun-failed-ci

FA4 could not serve DeepSeek MLA decode: the attention handler hard-coded
MHA_CHUNKED_KV, the absorbed-MLA path asserted FA3-only, and the jit wrapper
dropped the qv argument. Route fa4 through the standard MLA dispatch, plumb
qv through the FA4 varlen/kvcache wrappers, and register fa4 in the
deterministic and radix-compatible backend allowlists. The DeepSeek
deterministic-mode check now uses RADIX_SUPPORTED_DETERMINISTIC_ATTENTION_BACKEND
instead of a stale hard-coded list, which also admits ascend (the error
message already claimed that list).
…hapes

Review follow-up: flash_attn.cute implements the qv argument only on
Blackwell (SM100), so routing fa4 through the MLA dispatch unconditionally
turned the previous MHA-chunked-KV fallback into a hard kernel assert on
other archs. Keep the chunked-KV path off-SM100, reject deterministic fa4
DeepSeek on non-SM100 at startup (deterministic mode requires MLA), and add
a focused FA4 qv test for the DeepSeek absorbed shape (varlen q over paged
KV, MQA/GQA, num_splits=1). Also note in the backend that extend and decode
share the FA4 MLA path.
Review follow-up: flash_attn.cute accepts qv on capability majors 10 and 11
(not 12), while the previous gate admitted only SM100 and the qv test's
file-level skip admitted every arch >= 10 including SM120. Introduce a
single is_sm100_or_sm110_supported predicate shared by the dispatch gate,
the startup validation, and the test skip, and assert the decode-side
flash_attn_with_kvcache wrapper reproduces the varlen path bit-for-bit.
fused_qkv_a_proj_with_mqa picked batch-size-dependent kernels
(dsv3_fused_a_gemm for 1-16 rows, cuBLAS otherwise), breaking batch
invariance. dsv3_fused_a_gemm is a custom kernel outside the deterministic
aten overrides, so gate it off in deterministic mode; the projection then
runs through the batch-invariant aten.mm override at every batch size.
BF16 expert weights could enter the DeepGEMM BF16 grouped-GEMM runner only
under DeepEP low_latency; deepep normal fell back to other kernels. Lift the
low-latency-only restriction and, under deterministic inference, zero-init
the pre-permute scatter/index buffers so uninitialized pad regions cannot
leak nondeterministic values.
Review follow-up: evaluate enable_deterministic_inference once per
pre-permute instead of three times, allocate with torch.zeros instead of
empty-then-zero_, and document what the zero-fill protects: input_tensor
pad slots feeding the grouped GEMM, and scales only for FP8 activations
that share this pre-permute (BF16 dispatch never writes or consumes them).
With DP attention, MLP sync pads positions/seq_lens to the synced batch
size while SamplingBatchInfo covers only the real requests, so seeded
sampling crashes with "Seed and positions must have the same shape".
Slice positions to the sampled row count; real rows precede the padding.
Review follow-up: the non-spec arm of post_forward_mlp_sync_batch restored
batch_size and trimmed logits but left positions/seq_lens/req_pool_indices
padded, so every post-forward consumer (seeded sampling, ngram token-table
updates, prefill-only dummy ids) had to defend against the padding on its
own. Record the real token count at padding time and slice the per-request
tensors back where batch_size is restored, mirroring the draft-decode
branch. This makes the sample()-side positions slice dead; drop it.
TboForwardBatchPreparer.filter_batch allowlist-validates every non-None
ForwardBatch field when building child batches, and the new MLP-sync unpad
field _original_num_tokens was never added to the child dict, so any
TBO + DP-attention server crashed on its first extend batch (caught by the
base-c-test-deepep-4-gpu-h100 suite). Null it alongside its siblings
_original_batch_size/_original_forward_mode — TBO children carry no
MLP-sync restore state; the parent performs the post-forward unpad. Add a
filter_batch regression test with the field set.
At temperature > 0 the standard sampling path derived returned logprobs as
log(softmax(x/T)) while prefill rescoring uses F.log_softmax; the two
kernels disagree by ~1e-6, breaking bitwise prefill/decode logprob
alignment. Under deterministic inference, compute the returned logprobs
with F.log_softmax after temperature scaling.
Review follow-up: without a note here, a later cleanup could re-collapse
this branch into torch.log(probs) and silently re-break the bitwise
prefill/decode logprob alignment the kernel choice exists for.
EAGLE verify drew rejection-sampling coins from torch.rand, so speculative
outputs were not reproducible even with per-request sampling seeds. When
sampling_seed is present, derive the coins from
murmur_hash32(seed, seq_lens, column) like the main seeded-sampling path;
fall back to torch.rand otherwise.
Review follow-up: the float32 cast rounds the top 129 uint32 murmur hashes
to exactly 1.0, but the sampling kernels expect half-open [0, 1) coins — a
1.0 coin walks past the last CDF bucket and can return a zero-probability
token. Clamp to the largest float32 below one (all other coin values are
bit-identical to before, so verified baselines stand), extract the coin
derivation into _seeded_verify_coins, and lock it with unit tests
(reproducibility, seed/position sensitivity, max-hash clamp). Document that
this seeds only the verify-side RNG: rejection-sampling draft selection
still uses unseeded multinomial and stays non-deterministic until a
follow-up.
…ntract

Review follow-up: extract the seeded-vs-torch.rand branch so both sides are
unit-testable, and extend the coin tests with a structured-hash assertion of
the column split (columns [0, draft_token_num) drive rejection coins, column
draft_token_num drives the final-sampling coin), an unseeded-branch test
proving the hash is never consulted and rand draws stay independent, and a
dispatch check that seeded requests reproduce _seeded_verify_coins
bit-for-bit.
Upstream moved srt/layers/utils/hash.py to
sglang.kernels.ops.sampling.murmur_hash (RFC sgl-project#29630 phase 2.5, e9ef06c),
so the seeded verify-coin import and the coin tests' patch targets must use
the new module path; the old one no longer exists on main.
@zyzshishui
zyzshishui force-pushed the kimi-deterministic/6-eagle-seeded-coins branch from 6611339 to 18f2f50 Compare July 23, 2026 04:36
@ch-wan
ch-wan merged commit b954e9c into sgl-project:main Jul 24, 2026
96 of 112 checks passed
@zyzshishui
zyzshishui deleted the kimi-deterministic/6-eagle-seeded-coins branch July 24, 2026 23:36
efschu added a commit to efschu/htsglang that referenced this pull request Jul 27, 2026
Upstream sgl-project#30822 port (deterministic seeded coins for EAGLE verify) plus the
multi-layer draft-extend capture-time num_tokens_per_req stamp.

Semantic pre-check: no file overlap with the tip, and none with either
merge-5 branch (feat/mleagle-adaptive-len / fix/mleagle-preexisting-bugs) --
this branch is eagle_utils.py and
multi_layer_eagle_draft_extend_cuda_graph_runner.py, the mleagle pair is
multi_layer_eagle_utils.py / multi_layer_eagle_worker_v2.py / eagle_worker_v2.py
/ spec_utils.py. The test file it registers,
test_multi_layer_eagle_graph_state.py, IS load-bearing for merge 5 and is
re-run there per the ratchet requirement.
efschu pushed a commit to efschu/htsglang that referenced this pull request Jul 27, 2026
…nto integration/r3-probe

Merges feat/weightless-chain-spec (e950631) onto e1b96a2. Two content
conflicts, both resolved without dropping either side:

- FEATURES_VS_UPSTREAM.md: kept the r3-probe row (sgl-project#124 harness, per-role KV
  precision) and appended the chain-spec sentence rather than replacing it.
- speculative/eagle_utils.py: both sides add a new function at the same offset
  (_seeded_verify_coins/_verify_coins from the upstream sgl-project#30822 port, and
  spec_accept_broadcast_src from sgl-project#143). Both kept.

Two follow-on repairs that belong to the merge, not to either parent:

- test/registered/unit/spec/test_eagle_seeded_coins.py: the test pins source
  order via inspect.getsource and used str.find to locate
  capture_safe_tp_broadcast(. sgl-project#143 inserts a weightless-lane receive branch at
  the top of eagle_sample which carries its own call, so find() started
  matching that one instead of the head-side outcome broadcast the pin is
  about. Changed to rfind. Behaviour unchanged on both sides; the head-side
  broadcast still sits after the coins.
- model_executor/model_runner_kv_cache_mixin.py: the sgl-project#127 comment claimed the
  lane hard-rejects speculative decoding. sgl-project#143 makes that false. The code is
  still correct -- draft runners on the lane take the solo-host branch above --
  and the comment now says so.

Test results (CUDA_VISIBLE_DEVICES=9, CPU only):
  unit/server_args + unit/distributed + unit/spec
    merge:    1336 passed / 20 failed / 13 skipped
    baseline: 1311 passed / 20 failed / 13 skipped  (e1b96a2)
  Failure sets diffed line by line: IDENTICAL. All 20 are pre-existing and
  environmental (LOCAL_RANK, MPS pipe dir, "No CUDA GPUs are available",
  retry-exhaustion in the port-binding tests). The merge is delta-free.
  sgl-project#143's own suites: 108 passed
    (unit/distributed/test_weightless_chain_spec.py,
     unit/server_args/test_uneven_tp_args.py)
Atituiset pushed a commit to Atituiset/sglang that referenced this pull request Sep 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bypass-fastfail deepseek dependencies Pull requests that update a dependency file jit-kernel quant LLM Quantization

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants