Skip to content

[4/6][kimi-deterministic] Fix sampling positions under DP-attention MLP-sync padding - #30820

Closed
zyzshishui wants to merge 9 commits into
sgl-project:mainfrom
zyzshishui:kimi-deterministic/4-dp-attention-sampling-positions
Closed

zyzshishui wants to merge 9 commits into
sgl-project:mainfrom
zyzshishui:kimi-deterministic/4-dp-attention-sampling-positions

Conversation

@zyzshishui

@zyzshishui zyzshishui commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Stacked series (4/6): stacked on kimi-deterministic/3-deepep-normal-bf16-deepgemm (#30819), so the diff below includes 1-3/6. This PR's own changes are the last 3 commits (ending b8f498f — the last clears the new MLP-sync field on TBO child batches). Combined CI: #30822.

Motivation

With DP attention, seeded sampling crashes ("Seed and positions must have the same shape"): MLP-sync padding extends positions/seq_lens while SamplingBatchInfo covers only real requests. Repro: --enable-dp-attention --dp-size 2, /generate with temperature > 0 + sampling_seed. (Part 4/6 of the kimi-deterministic series.)

Modifications

Fix at the root instead of at the consumer (per review): prepare_mlp_sync_batch records the pre-padding token count, and the non-speculative arm of post_forward_mlp_sync_batch now slices positions/seq_lens/req_pool_indices/seq_lens_cpu back to the real rows, mirroring the existing draft-decode unpadding. This keeps every post-forward consumer (seeded sampling, ngram token-table updates, prefill-only dummy ids) free of padding; the earlier ModelRunner.sample-side slice is removed as dead. A unit test locks the pad/unpad round-trip (test/registered/unit/model_executor/test_mlp_sync_pad_unpad.py).

Accuracy Tests

Repro fixed (dp2: crash before, samples after; e2e campaign below ran with the original sample-side slice — the reworked fix feeds the sampler the same rows, and the new unit test covers the round-trip directly). Kimi-K2-Instruct-BF16, 16 GPUs (TP16 / DP8-attention / EP16, fa4 + deep_gemm + deepep normal, radix on), 128 prompts (1k-16k) x 512 tokens, abs tol 0.0: replay, shuffled concurrency-32, bs1 vs bs128, cached-prefix extend vs cold prefill, decode logprobs vs prefill rescoring (65,536 tokens) — all bitwise identical.

Speed Tests and Profiling

No impact (tensor slices in the once-per-forward post-sync path).

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 #29979964703
Latest PR Test (Extra): ❌ Run #29979964525

@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/4-dp-attention-sampling-positions branch from 0be0f7c to 471f441 Compare July 10, 2026 22:21
@zyzshishui
zyzshishui marked this pull request as ready for review July 11, 2026 00:40
@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!

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

)
num_sampled = forward_batch.sampling_info.temperatures.shape[0]
if positions.shape[0] != num_sampled:
positions = positions[:num_sampled]

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] The mismatch is created in ForwardBatch.prepare_mlp_sync_batch / _pad_inputs_to_size and only partially cleaned up in post_forward_mlp_sync_batch. Non-speculative post-forward restores batch_size and trims logits, but leaves positions/seq_lens/req_pool_indices padded; the draft-decode branch already unpads positions and seq_lens. Fixing only at ModelRunner.sample works for this crash, but other post-forward consumers (e.g. maybe_update_ngram_token_table assigning seq_lens into a [:batch_size] slice, or prefill-only dummy ids sized with len(seq_lens)) can still see padded tensors.

Suggestion: Prefer unpadding positions/seq_lens (and related per-req tensors) to _original_batch_size inside non-spec post_forward_mlp_sync_batch, mirroring the draft-decode path; keep this sample-side slice as a defensive belt if desired.

if forward_batch.forward_mode.is_decode()
else forward_batch.seq_lens - 1
)
num_sampled = forward_batch.sampling_info.temperatures.shape[0]

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.

[nit] forward_batch.sampling_info.temperatures.shape[0] is correct (temperatures is shaped [num_reqs, 1] and matches sampling_seed / logits rows), but it is an indirect way to spell "number of sampled rows". After post-forward, forward_batch.batch_size is restored to the real request count, and len(forward_batch.sampling_info) is defined as len(self.temperatures).

Suggestion: Prefer len(forward_batch.sampling_info) or forward_batch.batch_size for readability, unless there is a known case where temperatures diverge from restored batch size (none found for this path).

else forward_batch.seq_lens - 1
)
num_sampled = forward_batch.sampling_info.temperatures.shape[0]
if positions.shape[0] != num_sampled:

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] The branch only handles positions.shape[0] != num_sampled by prefix-slicing. That is right when MLP-sync appends padding (verified: _pad_tensor_to_size always concatenates dummy rows after real data). If positions were ever shorter than num_sampled, the slice is a no-op and the original murmur assert still fires with little diagnosis. No unit test is included in this PR to lock the DP-attention + sampling_seed contract.

Suggestion: Optionally assert positions.shape[0] >= num_sampled before slicing. Add a small unit/integration test that builds a padded positions/seq_lens with real rows first and asserts seeded sample succeeds and uses only the first num_sampled positions (repro from the PR description: dp-attention, temperature > 0, sampling_seed).

@zyzshishui
zyzshishui force-pushed the kimi-deterministic/4-dp-attention-sampling-positions branch from fa81b68 to 3a1520c Compare July 19, 2026 20:55
@github-actions github-actions Bot added the dependencies Pull requests that update a dependency file label Jul 19, 2026
@zyzshishui
zyzshishui force-pushed the kimi-deterministic/4-dp-attention-sampling-positions branch from 3a1520c to b68e572 Compare July 20, 2026 22:09
@zyzshishui
zyzshishui force-pushed the kimi-deterministic/4-dp-attention-sampling-positions branch 3 times, most recently from 082bc5f to d21e57b Compare July 22, 2026 20:23
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.
@zyzshishui
zyzshishui force-pushed the kimi-deterministic/4-dp-attention-sampling-positions branch from d21e57b to b8f498f Compare July 23, 2026 04:36
@zyzshishui zyzshishui closed this Jul 24, 2026
@zyzshishui
zyzshishui deleted the kimi-deterministic/4-dp-attention-sampling-positions branch August 3, 2026 20:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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