# Share the allocator with a target worker.
# Draft and target worker own their own KV cache pools.
self.req_to_token_pool, self.token_to_kv_pool_allocator = (
target_worker.get_memory_pool()
)
Review code for latent bugs in MiniCPM-SALA's --dense-as-sparse=False mixed-batch path. This is a SGLang fork. Codebase at /user_4813494d/openbmb. Working directory state: HEAD 7ef0eb0 clean (no working-tree changes on the files you'll be reading; some other unrelated files are dirty, ignore them).
Context
When --dense-as-sparse is OFF, dense layers (8 of 32) go through standard FA path while sparse layers go through InfLLM-v2 sparse path. When mixed in one batch (some bs have seq_len < dense_len = 8192 → dense, others ≥ dense_len → sparse), the code follows a special path under if forward_batch.sparse_batch_size < bs: that allocates a sparse_page_table covering BOTH sparse and dense bs, then patches the dense bs entries.
This mixed-batch path is dead-code in production (we always run with --dense-as-sparse ON in submission), but the user wants to enable it for accuracy comparison and just hit 2 bugs. I already fixed:
Bug 1: minicpm_attention_kernels.py:417-427 — _get_or_create_prefill_wrapper() (and sibling decode getters at lines 383, 398) were lazily creating FlashInfer wrappers without protecting against being called inside torch.inference_mode() (which happens during model_runner._flashinfer_autotune at line 1730). The wrapper's internal _kv_lens_buffer would then become an inference tensor, and later wrapper.plan() would throw RuntimeError: Inplace update to inference tensor outside InferenceMode is not allowed. Fixed by wrapping the construction in with torch.inference_mode(False):.
Bug 2: minicpm_sparse_utils.py:1741 in build_sparse_prefill_metadata() — max_sparse_cache_len was being computed using extend_seq_lens_cpu[i] for dense bs, but the writer at minicpm_backend.py:1613 reads kv_len = seq_lens_cpu[dense_bs] (total = prefix + extend). On chunked prefill 2nd chunk this caused RuntimeError: The expanded size of the tensor (630) must match the existing size (632). Fixed by changing to seq_lens_cpu[i].
Your task
Read the dense-as-sparse=False mixed-batch path end-to-end and find OTHER latent bugs in the same family — places where the code assumes "all bs are sparse" (or "all are dense") but the mixed case isn't handled, where dense bs and sparse bs metadata have different semantics, where chunked prefill (prefix > 0) breaks assumptions, or where stage1/stage2/FlashInfer downstream consumers can't handle the mixed layout.
Files to read
Assistant
I'll review the dense-as-sparse=False mixed-batch path systematically. Let me start by reading the key files.
Assistant
Now let me look at the dispatch path in minicpm.py and the standard FA path for dense bs in forward_extend:
Assistant
Let me find the dense-as-sparse dispatch:
Assistant
The dense-as-sparse dispatch is on the backend side. Let me look at forward_extend in the backend to find the dense_as_sparse path:
Assistant
Now look at the section around line 380-440 for wrapper getters and look at FlashInfer indptr setup:
Assistant
Now let me look at the build_sequence_lengths to understand how it handles dense vs sparse, and identify_sparse_batches:
Assistant
Now let me look at cu_seqlens_q_adjusted and max_seqlen_q_adjusted at line ~630, which is used in stage1:
Assistant
Now let me look around line 380-440 for the wrapper getters (mentioned bug 1):
Assistant
Now let me look at the cu_seqlens_q_adjusted usage - this is used for stage1. Notice line 626-629: this only includes batches where seq_lens_cpu[i] >= dense_len. Let me trace where cu_seqlens_q_adjusted is consumed:
Assistant
Note this is sparse_get_topk_impl — when running with all_sparse path (line 977), cu_seqlens_q is metadata.cu_seqlens_q (full batch including dense bs), but in line 1282 it passes metadata.cu_seqlens_q_adjusted. Let me re-read to confirm.
Internally passes self.forward_metadata.cu_seqlens_q_adjusted (computed at line 634 from sparse-only list)
Then for non-all_sparse (line 1047+), it calls build_prefill_topk_metadata which builds cu_seqlens_q_sparse only over sparse_bs — and then passes that to sparse_get_topk_impl. But it ALSO passes self.forward_metadata.cu_seqlens_q_adjusted (computed at line 634 which is only built when all_sparse was true).
Actually wait — let me re-read the gating logic at line 626-635. The cu_seqlens_q_adjusted is built using only sparse-bs entries for i in range(batch_size): if forward_batch.seq_lens_cpu[i] >= self.dense_len. So in mixed batch, this filters to sparse-only. That matches build_prefill_topk_metadata's cu_seqlens_q_sparse.
But notice line 976: all_sparse = forward_batch.sparse_batch_size == forward_batch.batch_size. In the all_sparse path, cu_seqlens_q = metadata.cu_seqlens_q is the FULL batch's cu_seqlens_q. But cu_seqlens_q_adjusted (line 634) is computed over sparse-only entries. If all_sparse is True, all bs are sparse, so these match. OK.
Now let me check the flashinfer indptr setup for CUDA graph in init_cuda_graph_state. Specifically, is it ever planned for sparse_bs = 2 * bs where bs represents full batch_size? In decode CUDA graph mode, mixed batch can't easily happen (decode is per-token, all bs have seq_len > prefill so all sparse in normal case). Still let me check the decode handling:
Assistant
Now let me look at how forward_batch.sparse_idx is used downstream and what indexing is expected when it's slice(None) (all_sparse_prefill) vs a list (mixed):
Assistant
At line 1544 and 1563, the code writes to metadata.sparse_page_table[forward_batch.sparse_idx, :num_sparse_topk_tokens] = sparse_page_table_sparse_bs. In mixed batch, sparse_idx is a list of indices into the sparse_page_table corresponding to sparse-bs rows. The sparse_page_table is shape (sparse_page_table_bs, max_sparse_cache_len), where max_sparse_cache_len = max(sparse_topk*block_size, max(seq_lens_cpu of dense bs)).
Now, line 1613-1614: metadata.sparse_page_table[start, :kv_len] = page_table[dense_bs, :kv_len] * 2. This writes to FULL kv_len (which may be > num_sparse_topk_tokens). Good — the row is sized to max_sparse_cache_len.
But wait — at line 1563, the sparse-bs rows are only written up to :num_sparse_topk_tokens. What about the rest of those rows? Looking at line 1755-1759, sparse_page_table = torch.zeros(...) — so rest is zero. That's fine because sparse_cache_seqlens_int32 (derived at line 1636-1640) counts non-zero entries → would only count the topk tokens. OK.
But for the dense-bs rows, line 1613 writes page_table[dense_bs, :kv_len] * 2. The *2 multiplication — if page_table entries are valid kv slot ids, this could be wrong. Let me investigate. The page_table is the kv slot index, but the FA path uses page_size=1 with these kv slots interleaved by head_group: key_cache_by_head_group = key_cache.reshape(-1, page_size, tp_k_head_num // 2, head_dim). So *2 and *2+1 is the right way to address head_group 0 and 1 separately. OK, looks intentional.
Now potential issues - check (metadata.sparse_page_table != 0).sum(dim=1) at line 1636-1640 for dense bs:
Dense bs rows: page_table[dense_bs, :kv_len] * 2 — but some of those values could be 0 (slot 0 IS valid!) → that gets counted as not present → undercount. Plus * 2 + 1 (odd rows) are never 0. So odd row gets count = kv_len but even row could be less if any slot=0 exists.
This is a potential bug. Let me check if slot 0 is ever used:
Assistant
Slot 0 is generally the first valid slot in the pool. The (sparse_page_table != 0).sum(dim=1) derivation is structurally suspect - if dense_bs has its first cached token at slot id 0, this would either miscount or get even/odd mismatch.
Let me look at the standard FA path for sparse layers — but wait, the question is about Standard Attention layers (8 of 32) vs Lightning. Looking at minicpm.py:
Assistant
Wait - I don't see a separate "standard FA path" branch in MiniCPMAttention.forward. It just calls self.attn (RadixAttention). The forward_extend of the backend is what gets called. Let me re-read forward_extend to find the dense/sparse branching:
Looking at line 1464-1466:
python
bs = forward_batch.batch_size
use_topk_to_fi_indices = False
if max(forward_batch.seq_lens_cpu) >= self.dense_len:
If ALL seq_lens are below dense_len, the code goes through the else at line 1566 and falls through... but then at line 1582-1583 q_reshaped = q.contiguous().view(-1, layer.tp_q_head_num // 2, layer.head_dim) and there's an unconditional sparse path applied.
Wait, this is the all-dense case where max(seq_lens) < dense_len. In that case topk_idx is never computed but the code still flows to the sparse FA path. Let me re-look:
Assistant
OK, now I have enough context. Let me check a few more specific things. First, look at how max_seq_len_q_adjusted is used and how the forward_metadata.cu_seqlens_q_adjusted will interact for mixed batch.
In mixed batch (where max(seq_lens) >= dense_len BUT some bs are dense and some sparse), at line 626-635:
seqlens_q_sparse_list only includes bs with seq_lens >= dense_len (sparse-bs only)
cu_seqlens_q_adjusted is sparse-bs only, multiplied by heads_per_group
q_reshaped is the FULL extend (all bs tokens). But topk path will call build_prefill_topk_metadata which gathers only the sparse-bs queries (line 2030 batched_gather). Good.
Now wait - looking carefully at line 977 all_sparse = forward_batch.sparse_batch_size == forward_batch.batch_size. In mixed mode that's False, so it goes to the topk_metadata = self.sparse_metadata_builder.build_prefill_topk_metadata(...) branch. That looks OK.
Now key question: when forward_batch.sparse_batch_size < bs and the dense bs's seqlen < dense_len BUT another bs's seqlen ≥ dense_len, the code at line 1466 if max(forward_batch.seq_lens_cpu) >= self.dense_len: is True → goes into the topk branch. The dense bs's queries are in q_reshaped but no topk is computed for them. The sparse_page_table for dense rows still gets filled (line 1613-1614) — good.
BUT what about the case where ALL bs have seq_lens < dense_len? Then the if max(seq_lens) >= self.dense_len is False → goes to else branch (line 1566-1580) which only allocates compress keys, doesn't compute topk. Then falls through to sparse FA at line 1582+. But here forward_batch.sparse_batch_size = 0 and bs = N, so all bs are dense. metadata.sparse_page_table has been allocated for N * head_group_num rows (each with max_sparse_cache_len = max(seq_lens_cpu)). The page table gets filled at line 1613-1614 for each dense_bs. OK so this path looks usable.
Now the question - the comment on line 583-586 says extend_prefix_lens_sparse uses forward_batch.extend_prefix_lens_cpu[bs]. Let me check if it works correctly for chunked prefill when one dense bs has prefix>0.
The dense bs is filtered OUT from , so the prefix issue would only affect dense bs in their own handling. Looking at line 1613, — full prefix+extend. And the q_reshaped slice at line 1609-1611 is where (extend only). OK.
Assistant
Now look at convert_sparse_page_table_to_flashinfer to see how it handles dense bs pages (which have entries even at position 0 sometimes due to *2 multiplication):
Assistant
This is decode-only (kv_last_page_len = 1, page_size = 1). The convert relies on cache_seqlens per-row, so it doesn't matter if entries are 0; it just uses num_valid count. So the FlashInfer convert path itself is robust.
But the question is — cache_seqlens is metadata.sparse_cache_seqlens_int32, which for dense bs in prefill is derived at line 1636-1640 by (sparse_page_table != 0).sum(dim=1). For dense bs, the row contains page_table[dense_bs, :kv_len] * 2 or *2+1. If any of those slot indices is 0, then *2=0 → masked out as zero. So even-rows undercount, odd-rows (with +1) always show full kv_len.
Now: is slot 0 ever a valid slot id used by req_to_token? In SGLang's standard kv pool, slot 0 IS a valid free-list slot. Let me verify by quickly checking the page_table source - it comes from req_to_token_pool.req_to_token[req_pool_indices, :]. Yes, typical SGLang code uses 0 as a valid slot. So this is a real correctness bug for the dense-bs path with mixed batch.
Now: this branch only executes when _MINICPM_DERIVED_SPARSE_SEQLENS is False OR sparse_batch_size != bs. In mixed batch (sparse_batch_size < bs), we always go through the (sparse_page_table != 0).sum(dim=1) path. So this IS triggered.
Now let me verify the rest of the flow: metadata.sparse_cache_seqlens_int32 for mixed-batch prefill is used downstream as the FA k cache_seqlens. If dense bs's even row reports kv_len_undercounted, that's a CORRECTNESS bug — the FA call would skip some K tokens.
Now check the second post-attention loop at line 1809-1833 — interleaving output rows. Let me also check cache_seqlens usage at line 1737 (cache_seqlens=metadata.sparse_cache_seqlens_int32) — yes confirmed.
Now let me check the page_table dtype carefully. The page_table values are int32/int64. The *2 and *2+1 multiplication assumes they fit. If slot ids can be very large (e.g., max_total_num_tokens > 2^30), *2 overflows int32. But max_context_len=524288 so max slot ≤ that, *2 fits in int32. OK.
Let me also check what happens at metadata.sparse_page_table shape for dense bs kv_len. The allocated size is max_sparse_cache_len. In build_sparse_prefill_metadata line 1744-1746: max_sparse_cache_len = max(max_sparse_cache_len, forward_batch.seq_lens_cpu[i]). And max could be from sparse-bs branch as sparse_topk * block_size. The dense bs kv_len could be ≤ dense_len=8192 < sparse_topk*block_size? Let me check.
Assistant
OK FA returns shape (total_q, num_heads, head_dim). In our forward_extend at line 1777, result shape is (total_tokens * 2, tp_q_head_num // 2, head_dim) — total leading dim doubled because q was reshaped.
So result.view(-1, layer.tp_q_head_num * layer.head_dim) at line 1835 reshapes to (total_tokens, tp_q_head_num * head_dim). ✓
Now let me check one more important spot: line 1601-1602 reads metadata.sparse_cu_seqlens_q_cpu[sparse_page_table_idx_start + 1] - ps. But metadata.sparse_cu_seqlens_q_cpu is built on CPU as int (probably int32 or int64). Subtraction of CPU tensor element returns a 0-dim tensor, not a Python int. Compared to forward_batch.extend_seq_lens_cpu[dense_bs] (likely an int) at line 1604-1607 with ==. Should work but type-mismatch might cause subtle issues.
Now let me revisit extend_prefix_lens access at line 581-585. This is forward_batch.extend_prefix_lens_cpu[bs] for sparse-bs only. The build_token_mappings then uses these prefix lengths to set token positions. Looks correct.
Now let me check one critical area: metadata.cache_seqlens_int32_stage1 = metadata.cache_seqlens_int32 - 1 at line 625. cache_seqlens_int32 is the full-batch standard cache_seqlens (one entry per bs). For dense bs in mixed batch this entry is still the full kv_len from metadata.cache_seqlens_int32. Then cu_seqlens_q_adjusted only includes sparse-bs entries. So stage1's cache_lens (line 1246) is the full-batch tensor, but cu_seqlens_q_adjusted only covers sparse-bs. These two would be mismatched in size in mixed batch!
Let me check stage1 kernel access:
Assistant
compressed_attention is called for sparse-bs only via build_prefill_topk_metadata's gathered queries (line 2030). The cu_seqlens_q passed in is cu_seqlens_q_sparse (line 2053), only sparse-bs entries. But cu_seqlens_q_adjusted is from forward_metadata.cu_seqlens_q_adjusted (line 1282 from sparse_get_topk_impl), which is built at line 634 with sparse-bs only. So sizes match.
But cache_lens (line 1246) is cache_seqlens_int32_stage1 = cache_seqlens_int32 - 1. The full-batch cache_seqlens has size bs, but stage1 should only need sparse-bs sized. Let me check how it's consumed:
In compressed_attention, cache_lens is passed to pool_func (line 853) and used to set up causal masking. The cu_seqlens_q and cu_seqlens_k sizes are based on sparse-bs only. If cache_lens is full-batch sized but cu_seqlens_q is sparse-bs sized, there's a size mismatch.
Wait let me check: cu_seqlens_q passed into compressed_attention is topk_metadata["cu_seqlens_q"] which is cu_seqlens_q_sparse. From line 2032, it has length len(sparse_bs)+1. cache_lens from line 1246 is cache_seqlens_int32_stage1 which is from metadata.cache_seqlens_int32 - 1 — full bs size. So in mixed batch, this mismatches.
Actually, this is also a bug — cache_lens should be subset to sparse-bs only when in mixed batch.
But wait, let me check the path. In mixed batch, the topk branch at line 1047+ calls sparse_get_topk_impl(cu_seqlens_q=topk_metadata["cu_seqlens_q"], ...). Then inside sparse_get_topk_impl, when max_seqlen_q == 1 (decode-like), uses cache_seqlens_int32_stage1 (line 1246). But when max_seqlen_q > 1 (prefill — this is the case for mixed batch), it goes to line 1248-1250 cache_lens = seq_lens_k - seq_lens_q from the passed cu_seqlens_k/cu_seqlens_q tensors. These ARE the sparse-bs sized ones.
So the line 1246 path (decode-like with max_seqlen_q==1) is the concern. In mixed-batch DECODE this could trigger, but mixed batch in decode is unusual (all bs are mid-decode → all sparse). Even in mixed-batch decode it would also be wrong size. Let me check if cache_seqlens_int32_stage1 for decode is the size that matches sparse-only cu_seqlens_q:
Line 655-657 in update_batch_for_sparse (decode path):
Assistant
Now let me check the standard FA path which IS what's called for the entire mixed batch (FlashAttention flash_attn_with_kvcache):
Looking back at line 1732-1765, the AttentionParams is built with page_table=metadata.sparse_page_table (which is the mixed-layout table where sparse rows hold topk pages and dense rows hold direct page_table*2). Then cache_seqlens=metadata.sparse_cache_seqlens_int32 (the derived (sparse_page_table != 0).sum). This is the FA call's page table.
In FlashAttentionKernel.forward, this just passes through to flash_attn_with_kvcache (line 228). So FA processes mixed-layout page_table. The kernel flash_attn_with_kvcache doesn't care about semantics — it just reads page_table[batch, :cache_seqlens[batch]] and does causal attention.
Critical question: For dense bs rows, causal=True is set. The causal mask aligns the query at position cache_seqlens - max_seqlen_q + qpos. For dense bs: q_len = extend_seq_lens_cpu[dense_bs], k_len = seq_lens_cpu[dense_bs]. That's a normal chunked-prefill setup. Causal should work. ✓
But wait, look at line 1740: max_seqlen_q=metadata.sparse_max_seq_len_q. sparse_max_seq_len_q is computed in build_sparse_prefill_metadata (line 1751-1753) as max(1, max_dense_extend). For mixed batch with all dense extends = 200 and any sparse bs (extend doesn't matter, sparse rows have q-len 1), max_seqlen_q = 200. So FA's max_seqlen_q is the dense max extend. That's correct for FA dispatch.
Now is_prefill is decided by max_seqlen_q > 1 (line 644 in flashinfer kernel). If only sparse bs exist (all dense extend = 0), then sparse_max_seq_len_q would be 1 → would mistakenly route to decode path even though we're in prefill. But this can't happen because if all bs are sparse, the all-sparse path was taken earlier (line 977). For mixed batch with dense bs present, dense extend > 0 → max_seq_len_q > 1 unless dense extend == 1 (chunked-prefill 1-token-last-chunk for the dense bs). Hmm — interesting edge case.
If dense bs has extend=1 AND all sparse bs trivially have rows with q-len 1, then sparse_max_seq_len_q = max(1, 1) = 1 → flashinfer kernel routes to decode path. That's wrong — this is a prefill batch.
Let me verify. Line 644 in attention kernel: is_prefill = params.max_seqlen_q > 1. If max_seqlen_q == 1, decode path. But the dense bs has a non-zero prefix (it's chunked prefill 2nd+ chunk), so KV is properly sized. Hmm, decode path with max_seqlen_q==1 should still be valid mathematically as "single query token per row"... but for dense_bs rows the q comes from q_reshaped[ps:ps+2*len_=2] with len_=1. So 2 rows × 1 token = 2 q rows for the dense bs. For sparse bs, each token is its own row.
Assistant
page64 path is gated to all-sparse (line 1715 in backend).
Now let me check the FlashInfer decode wrapper path / prefill case when max_seqlen_q == 1 but actually prefill in flashinfer mode:
Assistant
Now I have enough context. Let me also verify one more important thing - look at the extend_prefix_lens_sparse line 579-586 which is a list with len = len(sparse_bs_list). But build_token_mappings expects extend_prefix_lens_sparse indexed by sparse-bs order (line 1449 extend_prefix_lens_sparse[i].item()). Good.
Let me also verify the dense bs q-data placement. Notice line 1582 q_reshaped = q.contiguous().view(-1, layer.tp_q_head_num // 2, layer.head_dim). The original q is total_tokens × (num_heads*head_dim). For each token, the heads are laid out contiguously. When viewed as (-1, num_heads//2, head_dim), the leading dim becomes 2 * total_tokens, and each pair of consecutive rows IS the two head_groups of a single token. So q_reshaped[2*token + 0] is token's head_group 0, q_reshaped[2*token + 1] is head_group 1.
Now in mixed batch, suppose batch order is bs0 (sparse, extend=5), bs1 (dense, extend=3). Total tokens = 8.
After this, q_reshaped[10:13] = h0 of bs1 tokens, q_reshaped[13:16] = h1 of bs1 tokens. ✓
Now in FA, cu_seqlens_q = sparse_cu_seqlens_q. For bs0 rows (0-9), each is a "batch element" with q_start = i, q_end = i+1. For bs1 rows (10-11), batch element 10 has q_start=10, q_end=13 (head_group 0 q), batch element 11 has q_start=13, q_end=16 (head_group 1 q).
But wait — bs1's rows 10 and 11 share the same page_table indices? No — line 1613-1614 sets sparse_page_table[10] = page_table[bs1] * 2 (h0 cache) and sparse_page_table[11] = page_table[bs1]*2+1 (h1 cache). So each row uses its own cache. ✓
OK now one more very subtle thing. The q_reshaped interleave is applied IN-PLACE. So after the loop at line 1583-1614 runs, q_reshaped has been mutated. Then FA reads q_sparse = q.contiguous().view(...) at line 1728 — wait, that's q (the original), not q_reshaped. Let me re-check:
Assistant
Hmm — q_sparse = q.contiguous().view(-1, layer.tp_q_head_num // 2, layer.head_dim). So q_sparse is a NEW view via .contiguous().view(). But q_reshaped was created at line 1582 also as q.contiguous().view(...). If q.contiguous() returns q itself (because q was already contiguous), then q_reshaped and q_sparse share the same underlying storage. Mutating q_reshaped in-place mutates q_sparse via the shared storage.
But if q wasn't contiguous (or contiguous() returns a new tensor), then q_reshaped's in-place mutations don't affect q_sparse. That would be a bug.
Let me check. q comes from qkv.split([...]) which produces non-contiguous tensors (split is a view). Then q.contiguous() would call .contiguous() which returns a NEW contiguous tensor (because the strided view is non-contiguous). So at line 1582, q_reshaped is a new tensor backing. At line 1728, q.contiguous() is called AGAIN — but PyTorch's .contiguous() does NOT cache. It re-creates a new contiguous tensor (or returns the same one if already contiguous). Since q was non-contiguous, both calls to .contiguous() produce different storage.
Wait no - q.contiguous() returns the same tensor (q itself) if q is ALREADY contiguous. If q is not contiguous, it returns a new tensor. So q_reshaped and q_sparse would each be a different tensor.
Hmm, but actually qkv.split ... let me think. qkv is (total_tokens, hidden_size_total). Split along dim=-1 produces views with non-contiguous strides (because of the split). So q is non-contiguous. Then q.contiguous() creates a new tensor. The two calls at line 1582 and 1728 each return a different new tensor.
So writes to q_reshaped[ps:ps+len_, :, :] = ... mutate the q_reshaped temp tensor but NOT the q_sparse used in FA. This is a real bug in mixed batch.
Wait but let me re-check. The q at line 1582 — does q.contiguous() copy or alias? If q was already contiguous before .contiguous(), returns self. After the qkv split, q is a strided view of qkv but its memory may or may not be contiguous depending on dim order.
Actually, this code has been running in some mode. Let me check what code path is used in non-mixed cases. In all-sparse mode, mix-batch dense write is skipped (the code at line 1609-1611 doesn't run because forward_batch.sparse_batch_size == bs). So the bug only triggers in mixed mode.
This could be a significant bug. Let me check .contiguous() semantics more carefully. From PyTorch docs: "Returns a contiguous in memory tensor containing the same data as self tensor. If self tensor is already in the specified memory format, this function returns the self tensor."
Assistant
OK confirmed. q.contiguous() at 1582 and 1728 are separate calls. If q is non-contiguous, both allocate independent storage. So in mixed batch, the pre-FA q-shuffle is lost. SILENT WRONG OUTPUT for dense bs.
But wait — let me also reconsider. Possibly q IS contiguous after MiniCPMAttention's forward. Let me look at it:
Assistant
q, k = self.rotary_emb(positions, q, k). The rotary_emb returns a new tensor typically. Let me check:
Assistant
Ah - apply_rope_with_cos_sin_cache_inplace — INPLACE. So rotary_emb returns the SAME tensor (modifying in place). And the same split-view q is still passed to self.attn, still non-contiguous.
So q is non-contiguous, hence q.contiguous() called twice produces different tensors.
But wait, this would have been a problem in ALL cases that use the path, including all-sparse... let me re-examine. In all-sparse, the if forward_batch.sparse_batch_size < bs: is False, so no q-mutation happens between line 1582 and 1728. So q_reshaped (line 1582) is unused (just created for the in-place mutation that didn't fire). Then q_sparse = q.contiguous().view(...) at 1728 creates a new contiguous tensor used by FA. ✓
So in all-sparse path, this works because no in-place writes happen. In mixed path, the in-place writes are on a different tensor than what FA reads.
Actually wait - let me reconsider once more. Maybe in mixed case the intent was to write q_reshaped and then re-derive q_sparse. The fact that there are TWO calls to q.contiguous().view() is suspicious — perhaps the second was supposed to be q_sparse = q_reshaped to preserve the mutations.
OK this is definitely a bug. Now let me also check one more thing - line 1582 creates q_reshaped just for the dense bs mutation block. After the block, q_reshaped is dropped (no further refs). At line 1728, q is read again via contiguous() — but q has NOT been modified (the mutations were on q_reshaped which is a separate buffer when q is non-contiguous). So mutations are LOST.
Now let me look at one more thing related to the dense bs k/v writeback. When FA reads from KV cache for dense bs (with sparse_page_table rows containing direct page_table * 2 / *2+1), these slot indices come from forward_batch.req_to_token_pool.req_to_token[req_pool, :]. The kv cache values at those slots — were they written with proper head_group splitting?
Look at line 1340-1343: forward_batch.token_to_kv_pool.set_kv_buffer(layer, cache_loc, k, v, ...). This is the standard SGLang KV writeback. The cache_loc is forward_batch.out_cache_loc — the slot ids for THIS chunk's new tokens. So the writeback uses slot id directly. The KV cache layout is (slot_id, page_size, num_kv_heads, head_dim). With page_size=1: (slot_id, 1, num_kv_heads, head_dim).
But our sparse_page_table for dense bs sets [start, :kv_len] = page_table[dense_bs] * 2 and [start+1, :kv_len] = page_table[dense_bs] * 2 + 1. So FA reads kv_cache_by_head_group[slot2] for h0 and kv_cache_by_head_group[slot2+1] for h1.
key_cache_by_head_group = key_cache.reshape(-1, page_size, tp_k_head_num // 2, head_dim) (line 1701-1703). This reshape splits the slot dimension by 2 (since we cut head_dim in half by splitting heads). After reshape, is h0 cache at slot, is h1 cache at slot. So slot originally has shape , reshape splits the head dim into two halves, doubling slot count.
Assistant
So q is passed to forward_extend as is (sliced view of qkv). It's non-contiguous. Yes, my analysis stands.
But wait — I want to double-check this. Maybe q.contiguous() is being cached or there's some optimization. Let me write a quick test:
Assistant
Confirmed. q.contiguous() on a non-contiguous q returns DIFFERENT tensors on each call. Bug confirmed.
Now let me look at one more concern — the metadata.cu_seqlens_q_adjusted and stage1 cache_lens size mismatch. Re-examining: in compressed_attention for prefill, what's cu_seqlens_q size?
Going back to flow:
In mixed batch with max(seq_lens) >= dense_len: goes to topk_metadata branch
topk_metadata's cu_seqlens_q = cu_seqlens_q_sparse (sparse-bs only, line 2032)
topk_metadata also has query_states (sparse-bs only via batched_gather)
Then calls sparse_get_topk_impl(query_states, cu_seqlens_q_sparse, ...) at line 1128
In sparse_get_topk_impl:
Line 1244-1250: if max_q < max_k, derive cache_lens. If max_q == 1, use forward_metadata.cache_seqlens_int32_stage1 (full-bs sized). Else cu_seqlens_k - cu_seqlens_q (sparse-bs sized).
Then compressed_attention is called with cu_seqlens_q = cu_seqlens_q_sparse_bs+1, cache_lens = full-bs size. The pool_func uses cache_lens[batch] indexed by batch (where batch index ∈ [0, num_sparse_bs)). So cache_lens[0] would refer to bs0's stage1 cache_len, but the kernel expects cache_lens[sparse_bs_idx] to correspond to the i-th sparse-bs entry in cu_seqlens_q.
E.g., bs0 (dense), bs1 (sparse). cu_seqlens_q_sparse has 2 entries: [0, sparse_q_len]. The kernel iterates batch=0 expecting bs1's q. cache_lens[0] is actually bs0's (dense's) stage1 cache_len. Wrong batch!
But this only fires when max_seqlen_q == 1 in sparse_get_topk_impl. max_seqlen_q here is topk_metadata["max_seqlen_q"] = max(seqlens_q_sparse_bs). If all sparse bs have extend=1, this triggers. So chunked-prefill 1-token-last-chunk path with mixed batch has wrong stage1 cache_lens.
Now let me also verify line 1246 — cache_seqlens_int32_stage1. Actually wait — even in all-sparse with max_seqlen_q==1 (chunked-prefill last chunk all sparse), is cache_seqlens_int32_stage1 indexed correctly? cache_seqlens_int32 is from line 868-870 (where cache_seqlens is built per-bs in the FA metadata setup). In all-sparse with all-sparse bs, full-bs == sparse-bs, so indexing is fine. In mixed, full-bs != sparse-bs, so indexing is misaligned.
Now let me also look at one more spot — the use of seqlens_q[i] at line 2017 / 2018 in build_prefill_topk_metadata:
Assistant
Line 2055 max(seqlens_q_sparse_bs) could error if sparse_bs is empty (no sparse bs). But that scenario is when max(seq_lens) < dense_len, where we go to the else branch at line 1566. So no issue.
Now check that I understand the q-shuffle bug fix would look like:
The bug fix would be q_sparse = q_reshaped (reuse the already-mutated buffer) instead of q_sparse = q.contiguous().view(...) at line 1728.
Or alternatively, hoist q.contiguous() once at line 1582 and use the same q_contig variable everywhere. But this is read-only — I just need to report.
Now let me check the prefill_topk_metadata's cu_seqlens_q derivation — it uses full seqlens_q (line 2020-2026, ALL bs including dense). And then it does batched_gather(query_states_reshaped, cu_seqlens_q, sparse_bs). So the gather extracts only sparse-bs queries from the full layout, producing a tensor with only sparse-bs Q. This is independent of the FA path's q layout. Just used for topk. OK.
Let me check batched_gather:
Assistant
OK batched_gather is correct. Note that line 277 starts = cu_seqlen_q[select] does CPU-vs-GPU mixing. cu_seqlen_q is on GPU (line 2022 device=query_states.device), select is on CPU. PyTorch may auto-move. Probably works.
Let me now also check what happens for the all-dense case (max(seq_lens) < dense_len):
At line 1466, if max(forward_batch.seq_lens_cpu) >= self.dense_len: is False → goes to else branch (line 1566-1580). No topk_idx computed. Then falls through to 1582+.
At 1583, if forward_batch.sparse_batch_size < bs: — yes, sparse_batch_size = 0, bs = N → True. Goes into the dense_bs_list loop for ALL bs. This processes all bs as "dense" by writing their pages to sparse_page_table.
But cu_seqlens_q_adjusted (line 626-635) was built with only seq_lens_cpu[i] >= dense_len entries → empty list! seqlen_q_sparse_tensor = torch.tensor([], ...) and cu_seqlen_q_sparse_tensor = cumsum on empty = [0]. So cu_seqlens_q_adjusted = [0] * heads_per_group = [0]. And max_seqlen_q_adjusted = 0.
Then FA: metadata.sparse_max_seq_len_q could be > 1 (dense bs extends). FA call uses cu_seqlens_q=metadata.sparse_cu_seqlens_q (full layout including dense bs) — wait, sparse_cu_seqlens_q_cpu includes dense bs rows. So it's NOT empty for all-dense.
OK but at line 1247-1250 in sparse_get_topk_impl, this isn't called in all-dense case because topk is never computed. So cu_seqlens_q_adjusted = [0] doesn't bite. Good.
Now one more concern - check sparse_get_topk_impl at line 1247-1250: seq_lens_k = cu_seqlens_k[1:] - cu_seqlens_k[:-1]. The cu_seqlens_k here is topk_metadata["cu_seqlens_k"] = cu_seqlens_k_sparse (line 2054 — sparse-bs only). And cu_seqlens_q = cu_seqlens_q_sparse. So sizes match.
Now let me look at one last spot: the all-sparse-prefill metadata path with sparse_idx = slice(None). When that's the case, metadata.sparse_page_table[forward_batch.sparse_idx, :num_sparse_topk_tokens] = sparse_page_table_sparse_bs (line 1562) → writes to all rows. Fine, only triggered in all-sparse.
Let me now also check that sparse_max_seq_len_q propagates correctly. For ALL-DENSE batch (all bs have seq < dense_len), sparse_max_seq_len_q is max(1, max(extend_seq_lens_cpu of dense bs)) from line 1751-1753. OK.
For MIXED batch where dense bs extend = 1 (and sparse bs trivially have sparse_max_seq_len_q = 1), sparse_max_seq_len_q = 1. FA decodes max_seqlen_q=1. But the actual q has dense_extend = 1, so q-len 1 per dense row. That's effectively decode. OK functionally.
Bug 1: Dense-bs q reshuffling is lost — q.contiguous() called twice produces independent buffers
File:/user_4813494d/openbmb/demo-sala/sglang/python/sglang/srt/layers/attention/minicpm_backend.py:1582 and :1728
Two separate q.contiguous().view(...) calls. q is a slice of qkv.split(...) and is non-contiguous (verified empirically: each .contiguous() on a non-contiguous tensor allocates fresh storage). The dense-bs pre-FA shuffle at lines 1609-1611 (q_reshaped[ps:ps+len_] = t[0::2], etc.) mutates q_reshaped, but at line 1728 FA reads from a different new buffer q_sparse. The shuffle is silently dropped, so dense-bs rows get fed FA in the original [h0_t0, h1_t0, h0_t1, h1_t1, …] layout while sparse_cu_seqlens_q expects [h0_t0, h0_t1, …, h1_t0, h1_t1, …]. Severity: silent wrong output for all mixed-batch prefill with at least one dense bs whose extend>1. (Triggers from the first mixed chunk onward; extend=1 case is innocuous because the h0/h1 swap is a no-op.) All-sparse path is unaffected since the mutation block is gated by sparse_batch_size < bs. Fix candidate: replace line 1728 with q_sparse = q_reshaped.
Bug 2: sparse_cache_seqlens_int32 derivation via (sparse_page_table != 0).sum(dim=1) undercounts when KV slot 0 is in the page table
File:minicpm_backend.py:1636-1640
Mixed batch always falls into this fallback branch (the derived path at lines 1621-1633 is gated sparse_batch_size == bs). For dense bs rows, line 1613 writes page_table[dense_bs, :kv_len] * 2. If any kv slot id in that row equals 0 (slot 0 IS a valid SGLang KV pool slot), *2 = 0 is then counted as "not present" and the even (h0) row under-reports cache_seqlens by 1 per zero-slot. The odd row (*2+1) is fine. Downstream this sparse_cache_seqlens_int32 is the FA cache_seqlens (line 1737) and feeds sparse_cu_seqlens_k (line 1694). Severity: silent wrong output / occasional under-attention on dense bs h0 whenever slot 0 is in scope (which happens regularly for fresh sequences or after eviction). Sparse-bs rows are unaffected (topk pages can include 0 just the same, but path applies to them too, so they have the same conceptual fragility — but they're built differently and may not legitimately contain non-zero sentinel in valid positions).
User
研究 EAGLE-style speculative decoding 的 draft model 在长上下文场景下做 prefix 截断的合理性,并设计一个干净的生产质量实现。
是否有论文/blog/issue 讨论:"draft model 不需要 full long-context"、"draft prefix is short-range"、"sliding window for draft"?关键词:speculative decoding long context, EAGLE long prompt, draft model context window, draft prefix truncation, draft sliding window
SpecExtend (arXiv:2505.20776):训练免费的 drop-in enhancement,用 target attention score 选 top-k chunks 喂 draft KV,up to 2.84× speedup on 16K inputs;明确"chunk retention < full prefix"等价于我们的"draft 不需要看全 prefix"假设。
EAGLE Llama at scale (arXiv:2508.08192):Llama4 iRoPE 实现里写了"opted for a simpler solution: truncating the draft to fit entirely within one sub-sequence",且"impact on acceptance rate is negligible"。
Let me check what init_forward_metadata_capture_cuda_graph does for flashinfer with draft setting (specifically how kv_indices buffer is sized & maintained at decode).
Note the cuda_graph_kv_indices buffer is sized max_num_tokens * max_context_len. So it's a pre-allocated big buffer that can hold up to max_context_len entries per token. Critical info: kv_indices length per request can vary at replay time without recapturing the graph (because flashinfer reads from kv_indptr which slices into the buffer).
Now let's look at draft FlashInferMultiStepDraftBackend used for draft_attn_backend.init_forward_metadata_capture_cuda_graph.
Assistant
重要发现:decode 阶段 draft_forward 在 line 1651-1655 从 spec_info.{topk_p,topk_index,hidden_states} 取输入。
Excellent — now I have the critical answer for the kv_indices algorithm in draft decode. Let me read the generate_draft_decode_kv_indices triton kernel:
让我看看 line 953 行附近 last_hidden(这是 NO_SPEC → SPEC 转换处理):
Assistant
Now let me look at how update_single_wrapper (decode) computes kv_indices for draft prefill mode. Let me check the FlashInferIndicesUpdaterDecode update_single_wrapper.
Assistant
I see — for sliding-window dispatch, the backend ALREADY supports kv_start_idx + clamp on paged_kernel_lens. This is built-in flashinfer sliding-window. Let me check create_flashinfer_kv_indices_triton to understand what kv_start_idx does:
Assistant
So for prefill the kv_start_idx parameter directly maps to "start position in req_to_token row". If we set kv_start_idx = max(0, seq_len - N) and paged_kernel_lens = min(seq_len, N), we get trailing-N kv_indices for free.
Now let's look at update_single_wrapper for prefill (FlashInferIndicesUpdaterPrefill):
Now I understand the prefill path. Critically — for draft prefill (forward_draft_extend), spec_info = EagleDraftInput (with hidden_states, no kv_indptr/kv_indices), and generate_attn_arg_prefill is what builds kv_indices. Let me look at that again carefully — line 226: paged_kernel_lens = paged_kernel_lens + self.draft_token_num. But for EagleDraftInput (draft EXTEND), is that the right path? Let me check:
Assistant
Got it. So for draft prefill (extend_after_decode and forward_draft_extend), EagleDraftInput.generate_attn_arg_prefill builds kv_indices by reading from req_to_token rows with no kv_start_idx (None). To clip we'd need to either (a) pre-shift paged_kernel_lens and pass a kv_start_idx, or (b) override seq_lens at worker level.
Now check forward_batch positions and how draft model consumes them. Let me look at draft model forward.
Assistant
So positions is what the draft RoPE sees — comes from forward_batch.positions. For draft prefill, these are the absolute positions. For draft decode, look at how positions in eagle_info.py are seeded (e.g., line 1193): spec_info.positions = batch.seq_lens.repeat_interleave(self.topk, dim=0). So positions are ABSOLUTE (seq_len-based).
Now let's check the draft worker flow more carefully — how forward_batch.positions is set just before draft_model_runner.forward.
Assistant
Let me check the EagleDraftExtendCudaGraphRunner (used for draft prefill / extend after decode).
Assistant
Good. Now let me check init_forward_metadata for non-cuda-graph (eager) path entry to see hook points (init_forward_metadata in flashinfer_backend):
Assistant
Now I have enough info to write the report. Let me also confirm whether draft decode uses cuda graph and how decode positions work.
启动 EAGLE3 server 时,eagle_worker_v2.py 里 EagleDraftWorker.forward_draft_extend 会被调用到吗?
如果不会,我把 v2 文件的实验代码 git checkout HEAD -- 还原是否安全?
200 字以内简洁回答 + 关键 file:line。
Assistant
我来验证这两点。
Assistant
Good. Now I can see in forward_batch_generation (extend branch), after forward_draft_extend returns the function just returns GenerationBatchResult — no immediate consumption of spec_info happens this round. Now let me check the scheduler / batch path to see whether batch.spec_info is read between chunks.
Assistant
Now let me check process_batch_result_prefill to see if it reads spec_info.
Good — process_batch_result_prefill doesn't read batch.spec_info. Now let me check prepare_for_extend (called at line 2107) to understand what state it leaves behind, and how EagleDraftInput is constructed.
Assistant
MiniCPMForCausalLM 分支没有强制 disable_overlap_schedule。但是看到 line 2018, 2100 还有别的强制。让我查:
Assistant
Now let me check capture_for_decode to see exactly what fields it writes.
Now let me look at how draft KV is written during draft prefill, and check chunked prefill semantics — confirm last chunk satisfies seq_lens == req_total.
Assistant
Now let me look at prepare_for_extend in ScheduleBatch and confirm seq_lens semantics on chunked-prefill (does it reflect actual completed prefix or end-of-chunk position?).
Good — seq_lens = len(r.fill_ids) which includes all tokens already filled (prefix + current chunk). Now check init_next_round_input to confirm chunked-prefill flow.
Assistant
Now let me look at PrefillAdder's add_one_req chunked logic to understand which chunk is the "last chunk" and what fill_ids looks like at that point.
So on a chunked-prefill round, req.fill_ids is truncated to prefix_indices + extend_input_len (line 463), and seq_lens = len(r.fill_ids). For the final chunk, the request is no longer chunked — add_chunked_req returns None (line 476, when truncated == False), meaning extend_input_len was small enough that fill_ids reached the full origin length.
Let me also see what process_batch_result_prefill does with chunked vs final chunk.
Assistant
Good. No spec_info access in either prefill chunk path. Now let me verify the draft model's KV write path during prefill — confirm whether skipping forward leaves KV slots unwritten and how decode reads them.
Assistant
Now check how draft KV cache slot is allocated and written during forward_draft_extend (so I can confirm whether skip leaves slots unwritten or unallocated).
Assistant
Now the key — the draft model uses a separate KV cache pool from the target. Let me confirm.
Assistant
Now I need to confirm that during the chunked draft prefill, KV slots ARE allocated for the chunk (so the slot is "owned") — and whether the model forward, if skipped, just skips writing to those slots. Let me trace out_cache_loc and confirm the draft model runner forward writes KV via the model's forward (writes through save_kv_cache).
Assistant
So KV cache is written inside the model forward call via attention backend. If forward_draft_extend skips draft_model_runner.forward(...), the draft KV slots for that chunk are NOT written. Now let me confirm: are slots actually allocated for the draft KV (would create a leak), or is alloc tied to a different path?
Assistant
OK — this prepare_for_extend is on the target ScheduleBatch. The target slots get allocated and written via the target forward (which happened before forward_draft_extend is called). So out_cache_loc is the target model's slots.
But the draft model uses self.draft_model_runner.token_to_kv_pool. Is the draft model's KV pool shared with the target model? Let me check.
Assistant
Now let me see how draft and target share. Check eagle_worker init.
Assistant
Key fact: Draft and target worker share req_to_token_pool and token_to_kv_pool_allocator, BUT own separate KV cache pools (line 334 comment, line 1719 says "allocator and kv cache pool are shared with target worker" — actually that comment in clear_cache_pool says they're shared. Conflicting comments). Let me check further.
Assistant
Important: the draft model owns its own KV cache pool (memory_pool.py per-model), but the allocator (which assigns slot indices) is shared. So when target prefill alloc's slot N, the draft also uses slot N to write its KV. Skip → draft slot N is unwritten.
Now confirm: at decode time, will the draft attention paged FA read those skipped slot positions? Let me check the _draft_preprocess_decode to understand which KV slots get read.
Assistant
Key point: draft decode reads KV from positions 0..seq_len-1 via req_to_token mapping; those slots were populated during target prefill (target's KV cache) AND draft prefill (draft's KV cache) — but if we skipped the draft forward for chunk, the draft's KV slots for those positions are never written. So draft attention during decode WILL read uninitialized values for the skipped range.
But the user's comment at line 2138 acknowledges this — "Draft KV slots for skipped positions remain zero-initialized". Let me verify zero-init. Check memory_pool init.
Assistant
Good — KV cache buffers are torch.zeros initialized. So skipped slots ARE truly zero (not residual from a previous request, assuming the buffer wasn't reused for another request — but the allocator's free returns slot indices to the free list, so previously freed slots COULD be reused). Wait — slots are freed and re-allocated per request. So if request A was here before and wrote draft KV into slot X, then was freed, and request B is allocated slot X for chunk skip, the draft KV at slot X is residual from request A, not zero.
Let me verify slot reuse behavior.
Assistant
Confirmed: freed slot indices are returned to the free pool and reused without zeroing the underlying KV memory. So skipped slots will hold residual data from prior requests, not zero. The user's comment ("zero-initialized") is incorrect in the general case. Empirically the model still works because:
Sliding window cuts to 32K most-recent tokens (positions that ARE written this request)
The skipped positions (outside the window) ARE still pointed to by req_to_token[req_pool_idx][:seq_len] and reachable through paged FA at decode time
Long-context draft attention is dominated by recency
But "zero-initialized" is not what happens for slot reuse. Now let me also confirm what prepare_for_extend does in EagleDraftInput (line 2107) — specifically the line batch.input_ids[pt : pt + extend_len] = torch.cat((input_ids[1:], self.verified_id[i].reshape(1))).
The EagleDraftInput prepare_for_extend (eagle_info.py line 855) modifies batch.input_ids in place — this is a side effect on the target's ScheduleBatch input_ids. Let me check if anyone reads batch.input_ids after forward_draft_extend returns.
Assistant
No direct reads of batch.input_ids. Good. Now let me confirm question 2's edge case: when chunk_size aligns exactly with the last chunk, what is seq_lens?
Looking back: in add_chunked_req (line 461), truncated = req.extend_input_len > _rem_tokens. If _rem_tokens >= req.extend_input_len, truncated=False, the chunk is the LAST chunk. After set_extend_input_len(min(...)), fill_ids is truncated to prefix + extend_input_len. Since extend_input_len is the remaining (full) extension needed, len(fill_ids) == prefix + extend_input_len = origin_input_ids (since the last round had fill_ids = origin_input_ids set in init_next_round_input line 863).
Hold on — init_next_round_input line 863: self.fill_ids = self.origin_input_ids + self.output_ids. For prefill (no output_ids yet), this equals origin_input_ids. So seq_lens = len(fill_ids) for the last chunk = len(origin_input_ids) = req_total_lens[i]. The skip condition seq_lens < req_total - N is False for the last chunk. Confirmed last chunk always runs.
Edge case: what if the request is so short it fits in a single chunk (no chunking)? Then add_one_req (line 545-555 non-chunked path): extend_input_len is full, fill_ids is unmodified (still = full origin_input_ids), so seq_lens = req_total. Skip condition False. Single-chunk also fine.
Now let me look at whether there's CUDA graph state maintenance that could break.
Assistant
This is forward_draft_extend_after_decode (different code path, called after decode). In our forward_draft_extend (chunked prefill path, line 2086), looking at line 2187-2196, there's no cuda graph for this path — it's plain eager draft_model_runner.forward(forward_batch). So skipping is safe for cuda graph state.
I have enough evidence. Let me write up the summary.
Findings per question:
read path between chunks: NO. After forward_draft_extend returns in the extend branch (eagle_worker.py:742), forward_batch_generation returns immediately with GenerationBatchResult (line 746-751). Scheduler's process_batch_result_prefill (scheduler_output_processor_mixin.py:85-237) never reads batch.spec_info. No code consumes topk_p/topk_index/hidden_states between chunks. They stay at default None from EagleDraftInput field defaults (eagle_info.py:816-819).
last-chunk guarantee: YES. init_next_round_input (schedule_batch.py:863) sets fill_ids = origin_input_ids + output_ids; for prefill output_ids=[] so fill_ids = origin_input_ids. add_chunked_req (schedule_policy.py:461-463) sets truncated = extend_input_len > _rem_tokens; the final chunk satisfies truncated=False and leaves fill_ids full-length. seq_lens = len(fill_ids) (schedule_batch.py:1471) thus equals req_total. Skip condition seq_lens < req_total - N is False. Single-chunk case (add_one_req line 545-555) also leaves fill_ids full-length. No boundary case mis-skips.
spec_info rebuild: YES. Line 2100-2107 unconditionally reconstructs batch.spec_info = EagleDraftInput(...) and reruns prepare_for_extend at every forward_draft_extend call. The skipped chunk's leftover topk_p=None / topk_index=None / hidden_states=None is overwritten by the next chunk's fresh constructor. No state pollution.
draft KV not written: YES, slots are unwritten — but the user's comment "zero-initialized" is misleading. KV pool buffers are torch.zeros-initialized at startup (memory_pool.py:972,980,1220+), BUT the allocator (allocator.py:155-163) returns freed slots to a reusable pool without zeroing the underlying KV memory. So skipped slots can hold residual data from that previously used those slot indices. At decode, draft paged FA does read these positions (req_to_token covers full seq_len). Empirically it works because draft attention is recency-dominated and the trailing 32K window is the only meaningful KV. : replace "zero-initialized (memory_pool default)" with something like "unwritten — may contain residual from prior requests sharing the same slot index; draft attention tolerates this because the trailing N-token window dominates softmax". This is a doc fix, not a correctness bug.
Now let me check the prefill SWA path more carefully — particularly the paged_kernel_lens = min(seq_lens, sliding_window + seq_lens - prefix_lens) math, and what prefix_lens is in chunked-prefill.
Now I have enough. Let me also peek at how cache_loc / out_cache_loc is constructed in chunked prefill — specifically whether the trailing chunk's draft prefill writes only the chunk's tokens.
数值改变:a3f2b5e 引入了 stage1 kernel dispatch 的 32×64 warp tile 快速路径。原注释称"bitwise-equal claim from offline microbench did not hold under production data"。线上观察到精度回归。
if use_stage1_blockmax: # only enabled when _SGLANG_MINICPM_STAGE1_BLOCKMAX_FUSION==1
block_score = _infllmv2_attn_stage1_blockmax(...)
elif stage1_k1_blockmask is not None: # only when k2_score_selective gated by env
score_actual = _infllmv2_attn_stage1_k1_mask(...)
else:
score_actual = _infllmv2_attn_stage1(...)
_infllmv2_attn_stage1()
_SGLANG_MINICPM_STAGE1_BLOCKMAX_FUSION
_SGLANG_MINICPM_STAGE1_K2_SCORE_SELECTIVE
use_stage1_direct_pool
风险
blockmax路径跳过后续pooling(line 1184: if not block_score_from_stage1:)
getenv("INFLLM_V2_STAGE1_EMPTY_P") modes gate P tensor initialization (line 953-967)
getenv("INFLLM_V2_STAGE1_FIRST_PASS_ONLY") gates second K1 pass (line 1043)
Line 1109-1123: zero_stage1_future() kernel call gates on empty_stage1_p_mode == 2
类 C: 2 项
Line 956-970 (P tensor allocation logic):
cpp
// Default path: torch::full(..., 0) or torch::full(..., -inf)
// But now conditionally switches to torch::empty() if INFLLM_V2_STAGE1_EMPTY_P set
p = use_empty_stage1_p && !zero_tensors && !use_stage1_k1_mask
? torch::empty({...})
: torch::full({...}, use_stage1_k1_mask ? -inf : 0);
line ~580-660 (sparse_metadata_builder setup, sparse_page_table assignment)
line ~970-1010 (all_sparse checks around line 976)
line ~1470-1620 (prefill block_table / direct write / mixed batch fill — this is where Bug 2 was)
line ~1620-1810 (use_derived_sparse_seqlens, sparse_cache_seqlens_int32 derivation, plan caching)
line ~1850-1990 (forward_extend + standard FA dispatch for dense bs)
/user_4813494d/openbmb/demo-sala/sglang/python/sglang/srt/layers/attention/minicpm_sparse_utils.py — build_sparse_prefill_metadata function (line 1650-1900) and build_sparse_decode_metadata (find via grep)
/user_4813494d/openbmb/demo-sala/sglang/python/sglang/srt/models/minicpm.py — self_attn.forward around line 830-900 (dense-as-sparse dispatch)
What to look for
Places that check forward_batch.sparse_batch_size == bs to gate something — if the gate is missing somewhere, mixed batch breaks.
Tensor shape assumptions that hold for all-sparse but fail when dense bs is mixed in.
seq_lens_cpu vs extend_seq_lens_cpu confusion in chunked prefill contexts.
sparse_cache_seqlens derivation for dense bs (when use_derived_sparse_seqlens is False, line ~1635 uses (sparse_page_table != 0).sum(dim=1) — is this correct for dense bs which writes page_table[dense_bs] * 2 and +1?).
CUDA graph metadata (init_cuda_graph_state, init_forward_metadata_capture_cuda_graph, init_forward_metadata_replay_cuda_graph) — does it support mixed batch?
The old_bs_to_new_bs_range indexing — dense bs uses head_group_num=2 rows (asserted at line 1593), but is that consistent with how downstream code indexes?
Whether _USE_TRTLLM_STAGE2 / stage1_blockmax / other optional kernels assume all-sparse.
Any flashinfer_kv_indptr / params.flashinfer_* setup that's only built for sparse bs.
Report format
Return a short (under 600 words) report:
One section per distinct bug you find (numbered). For each: file:line, what the buggy assumption is, when it triggers (prefill 1st chunk / chunked 2nd chunk / decode / mixed bs / etc.), and severity (crash / silent wrong output / perf).
One section "No-bug-but-suspicious": places that look fragile but you can't confirm are wrong from the code alone.
One section "Verified-OK": paths you checked that handle mixed batch correctly (so the user knows you covered them).
Do NOT fix anything. Read-only review. Do NOT recurse into spec/eagle code — the bugs are in the attention layer path.
But wait - at line 1599 ps = metadata.sparse_cu_seqlens_q_cpu[sparse_page_table_idx_start]. The sparse_cu_seqlens_q_cpu is built layout-aware. Let me trace through this for a mixed case:
Say bs=2: bs0 is sparse (seq=10000, extend=200), bs1 is dense (seq=500, extend=200).
q_reshaped[400:400+400, ...] — but q_reshaped is shape (total_q=200+200=400, num_heads//2, head_dim). q_reshaped[400:800] is out of bounds!
Wait — total_q is the extend tokens across all bs, so q.shape[0] = 200 + 200 = 400. But ps=400, len_=200, ps+2*len_=800 exceeds q.shape[0]=400.
Let me re-check the logic. Hmm actually the ordering is bs0 (sparse) first then bs1 (dense). bs0's extend is 200 tokens but bs0 is sparse, meaning its sparse_page_table has 200*2=400 rows (every-token-every-group). For bs1's q tokens, q_reshaped[200:400] would be the dense bs's q. But ps=400 is interpreted as a position into q_reshaped...
Actually wait, q_reshaped was view'd as (-1, layer.tp_q_head_num // 2, layer.head_dim) at line 1582. The first dim is total_q * 2 because we split heads into 2 groups. So q_reshaped.shape[0] = (total_extend_tokens) * 2. For our example: 400 * 2 = 800. So ps=400, ps+2*len_=800 exactly maps to bs1's tokens. ✓
OK that works. Let me think about a chunked prefill scenario:
Wait, in chunked prefill, the "dense" condition is seq_lens_cpu[i] < dense_len. For chunked-prefill 2nd chunk, seq_lens_cpu = prefix + this_chunk_extend. So bs1 dense means prefix + extend_chunk < dense_len.
Let me see another subtle issue. In build_sparse_prefill_metadata at lines 1751-1753:
This is only updated in the dense branch (when seq_lens < dense_len). The sparse branch never updates sparse_max_seq_len_q. For mixed batch with all-sparse-bs of seq=1 (decode-like) but with one dense bs of extend=500, the sparse_max_seq_len_q would be 500. For pure sparse-bs in prefill (seq=10000, extend=1 = chunked-prefill last chunk), sparse_max_seq_len_q=1 which seems WRONG because the sparse bs's actual q length is 1 — OK that's correct for sparse.
But wait — what if a sparse bs has extend > 1 (extend prefill chunk with seq_lens >= dense_len)? E.g., bs0: seq=10000, extend=2000. The sparse path puts each q token in its own row (one row per token per head group), so sparse_max_seq_len_q per-row IS 1. Each row has q-length 1, k-length = sparse_topk * block_size. OK that's correct.
Now I see a potential bug: in mixed prefill batch where one sparse bs has extend>1 AND a dense bs has extend > 1, the layout differs:
Sparse bs rows: each row has q-len 1, but there are extend * head_group_num rows
Dense bs rows: each row has q-len extend, only head_group_num rows
So sparse_cu_seqlens_q_cpu interleaves differently per-bs. The sparse_max_seq_len_q would be max across all rows. Sparse rows contribute q-len 1, dense rows contribute q-len extend_seq_lens_cpu[dense_bs]. So sparse_max_seq_len_q = max(1, max_dense_extend). Initial value is 1 (line 1725), and only dense branch updates. So sparse_max_seq_len_q = max(1, max_dense_extend). OK seems right.
Let me look for one more thing — the all-sparse-prefill metadata path (line 1690-1720) has different old_bs_to_new_bs_range indexing. In mixed batch, _SGLANG_MINICPM_ALL_SPARSE_PREFILL_METADATA won't apply because line 1687 checks all(seq_lens >= dense_len). So mixed batch always goes to the second branch. OK.
Now let me look at one specific thing - the extend_prefix_lens_sparse at line 579-586:
python
extend_prefix_lens_sparse = torch.tensor(
[forward_batch.extend_prefix_lens_cpu[bs] for bs in metadata.sparse_bs_list],
...
)
This is built for sparse_bs_list. Then passed to build_token_mappings which builds token_pos_in_bs. That's used downstream by stage1 / block_table for sparse bs. In mixed batch the dense bs's tokens aren't represented here — which is correct since they go through standard FA (?). But wait, dense bs ALSO uses the sparse_page_table layout via lines 1613-1614, they just don't have a topk to compute. Where does dense bs's token_to_bs / token_pos go?
Look at line 1539-1564 — the block_table writer uses metadata.token_to_bs, metadata.token_pos_in_bs to map topk_idx to sparse_page_table rows. These only cover sparse-bs tokens. For dense bs, the sparse_page_table rows are filled separately at line 1613-1614 with the full kv_len. That's a different code path. So this is consistent.
Now let me verify: in mixed batch, metadata.sparse_page_table[forward_batch.sparse_idx, :num_sparse_topk_tokens] = sparse_page_table_sparse_bs. Here sparse_page_table_sparse_bs has shape (sum_sparse_extend_tokens * head_group_num, num_sparse_topk_tokens). And forward_batch.sparse_idx is a list of indices in the FULL sparse_page_table corresponding to sparse-bs rows. So this writes to the right rows. ✓
Now let me check the indexing for _MINICPM_DIRECT_SPARSE_PAGE_TABLE path (line 1535-1559). The check forward_batch.sparse_batch_size == bs gates it to ALL-sparse only. Good.
Let me now check use_topk_to_fi_indices at line 1478-1483 - also gated to sparse_batch_size == bs. Good.
Check use_block_page64 at line 1710-1716 - gated to sparse_batch_size == bs. Good.
shape_only_plan_cache at line 1749 - (sparse_batch_size == bs). Good.
Now let me check the FlashInfer convert path / plan downstream:
sparse_topk = topk + window_blocks where topk=hf_config.sparse_topk. Typically sparse_topk * block_size is much smaller than 8192. So for mixed batch where a dense bs has kv_len ≈ 7000-8000, max_sparse_cache_len could be set from dense bs's seq_len. OK row capacity = max across all dense bs. So write at line 1613 [dense_bs, :kv_len] works since kv_len ≤ max_sparse_cache_len. ✓
Now, one more thing to check — line 1809-1834 (post-FA un-interleave). The result tensor shape is (total_tokens * head_group_num, head_dim) because the FA was run with q_sparse = q.view(-1, layer.tp_q_head_num // 2, layer.head_dim). For sparse bs the layout is per-row (each token-headgroup is a "batch element"). For dense bs the layout is (extend_len * 2) for that bs (2 head_groups concatenated). The line 1832-1833 interleaves them back.
But wait at line 1832: result[ps : ps + 2 * len_ : 2, :, :] = t[0:len_, :, :]. The clone t = result[ps : ps + 2 * len_, :, :].clone(). So t is shape (2*len_, ...). Then result[ps:ps+2*len_:2] is the even indices (positions ps, ps+2, ...). t[0:len_] is the first len_ rows of the clone (those came from result[ps : ps+len_] which we wrote in the pre-FA step as head_group 0's q tokens). So we're un-interleaving from [h0_tokens, h1_tokens] to [h0_t0, h1_t0, h0_t1, h1_t1, ...].
Wait, that's a sequential q layout. But the original q at line 1582 was reshaped as (-1, layer.tp_q_head_num // 2, layer.head_dim). The original q (before view) was probably (total_tokens, tp_q_head_num * head_dim). View → first dim becomes 2 * total_tokens. Then the layout per-token would be [token0_h0, token0_h1, token1_h0, token1_h1, ...] (since head dim doubles into the leading dim by factor 2). So originally, even rows are head_group 0 and odd rows are head_group 1.
Pre-FA at line 1610-1611: take q_reshaped[ps:ps+2*len_] (interleaved), separate into even (h0) and odd (h1), put h0 first then h1. So after pre-FA: [h0_t0, h0_t1, ..., h0_tN-1, h1_t0, ..., h1_tN-1].
But why? Because the sparse_page_table for dense_bs has 2 rows (one per head_group), and sparse_cu_seqlens_q_cpu[start] = ps, [start+1] = ps+len, [start+2] = ps+2*len. So FA processes:
OK that makes sense. The post-FA un-interleave restores original interleaved layout. ✓
Now check the result.view(-1, layer.tp_q_head_num * layer.head_dim) reshape at line 1835. The result before this is (total_tokens * 2, head_dim_per_group, head_dim) (because the FA output groups). Actually let me check what shape FA returns:
The attention_kernel forward returns... let me peek:
In decode, cu_seqlens_q_adjusted is full-batch. And build_decode_topk_metadata returns cu_seqlens_q = base_metadata.cu_seqlens_q (full batch). So decode path is full-batch consistent. ✓
In mixed-batch prefill where any bs has extend_seq_lens_cpu == 1 (last chunk of a chunked prefill), max_seqlen_q could equal 1 for the sparse subset. But max_seqlen_q is computed at line 2055 as max(seqlens_q_sparse_bs). If all sparse bs have extend=1, max=1. Then in sparse_get_topk_impl, max_seqlen_in_batch_q == 1 and max_seqlen_in_batch_k > 1 (since prefill kv ≥ 8192), so line 1246 triggers: cache_lens = self.forward_metadata.cache_seqlens_int32_stage1 — FULL batch sized (size = bs). But cu_seqlens_q passed is sparse-only sized (len(sparse_bs)+1). MISMATCH. So pool kernel would access wrong cache_lens entries.
This is a real bug for mixed-batch chunked prefill where ALL sparse_bs have extend=1 (last single-token chunk).
Now let me also check the FlashInfer plan path / Stage2 for whether it handles dense bs rows correctly:
Actually wait — when len_=1 (dense extend=1), the q-len of dense rows IS 1, same as sparse rows. So the FA dispatch is "all q-len=1" which the kernel can handle as decode. The "prefill" vs "decode" distinction in FlashAttention is really just "max_seqlen_q > 1 needs varlen kernel". So this is likely OK.
Actually let me cross-check — the FlashInfer kernel forward call branches on is_prefill = max_seqlen_q > 1. If False, it goes to decode-wrapper path (line 668) but params.decode_wrapper is not None and not is_prefill. In non-CUDA-graph prefill mode, decode_wrapper is None, so this is False. It falls through to line 715 "Non-CUDA graph mode" and creates a wrapper. Looking at the rest of the code, the flashinfer path uses decode wrapper when max_seqlen_q==1 (line 716+ then 869+). This could mis-handle the mixed case but may still be functionally correct if the decode wrapper supports all the head_group splitting.
OK let me look at the page64 / using_block_pages path which is for decode:
So if q is contiguous, it returns self. If not, it allocates a new tensor and copies.
For qkv = X @ W (a matmul), qkv is contiguous. Then qkv.split([q, kv, kv], dim=-1) returns views. These views are NOT contiguous in memory (only the first one is, the second and third have offset). Actually wait - in PyTorch when you split along the last dim and the split is into equally-sized chunks, you get non-contiguous tensors. Even the first chunk is non-contiguous because stride pattern doesn't match.
Hmm, actually for split([q, kv, kv], dim=-1), the first chunk has stride pattern (hidden_size, 1) — which IS contiguous IF the last-dim stride is 1 AND num_elements_per_row * stride == row_stride. For a (M, N) tensor split into (M, n1), the first slice has stride (N, 1) and shape (M, n1). For it to be contiguous, we'd need stride to be (n1, 1), but it's (N, 1). So NOT contiguous.
So q.contiguous() returns a new tensor on each call. So q_reshaped (line 1582) ≠ q_sparse (line 1728). The pre-FA mutations are LOST. This is a bug.
But wait — maybe this is fine if the dense bs path is actually NOT supposed to interleave q? Let me re-read the intent. The comment line 1584 says "copy dense page table for dense bs". The q reshape at line 1609-1611 is meant to re-layout q so dense bs's q is in [h0..., h1...] order matching the sparse_cu_seqlens_q layout. If this mutation is lost, then FA would read q in the wrong order for dense bs rows.
I want to verify by looking at git history / how this was tested. Let me check the bench command and run the code to check for the contiguous bug:
Actually, let me read more carefully — maybe q IS contiguous in some scenarios. After qkv_proj returns, the qkv tensor is the output of a linear. Linear's output is contiguous. Split returns non-contiguous slices. So q is non-contiguous → q.contiguous() allocates a new tensor.
Actually let me verify: q is contiguous only if N (full hidden) == n_q. If q occupies the FULL last dim of qkv (which it doesn't because qkv contains q, k, v), then q is not contiguous.
So I'm confident this is a bug. But the user said this path was tested for accuracy. Let me reread the user note... they said:
This mixed-batch path is dead-code in production (we always run with --dense-as-sparse ON in submission), but the user wants to enable it for accuracy comparison and just hit 2 bugs.
So the bugs already found are crash bugs. This silent-correctness bug might be silently producing wrong outputs.
Hmm wait, let me look more carefully again at line 1728 — it's INSIDE the forward_extend function and the same q parameter. Let me confirm the prior q.contiguous() at 1582 and that's a top-level statement, not nested.
key_cache_by_head_group[2*slot]
[2*slot+1]
s
(page_size, num_kv_heads, head_dim)
Hmm but does this reshape preserve data layout? key_cache shape is (num_slots, page_size, num_kv_heads, head_dim). Reshape to (2 * num_slots, page_size, num_kv_heads // 2, head_dim). The reshape interprets the data as the leading dim grows by 2x. For a contiguous tensor with original shape (N, P, H, D) (stride PHD, H*D, D, 1), the reshape to (2N, P, H/2, D) requires:
New stride: (P*H/2*D, H/2*D, D, 1)
Old element (n, p, h, d) maps to new element (2n + ???, p, ???, d)
Actually, reshape key_cache.reshape(-1, page_size, num_kv_heads // 2, head_dim) — the original tensor is contiguous with shape (N, P, H, D) and total elements N*P*H*D. Reshape gives (N*P*H*D / (P*H/2*D)) = 2N. So shape (2N, P, H/2, D). Element (n, p, h, d) in original → flat idx n*P*H*D + p*H*D + h*D + d. In new view, flat idx → (new_n, new_p, new_h, d) where new_n = flat / (PH/2D), etc.
So if original token n has h0 and h1 packed into [n, p, 0:H/2, :] and [n, p, H/2:H, :], the reshape splits these into two consecutive slots in the new view. Specifically:
new slot 2*n corresponds to original [n, p, 0:H/2, :] (h0)
new slot 2*n+1 corresponds to [n, p, H/2:H, :] (h1)
OK so the *2 / *2+1 mapping is correct. ✓
Now, finally let me check the head order assumption. The original q is laid out as (total_tokens, tp_q_head_num * head_dim). q.view(-1, tp_q_head_num // 2, head_dim) splits the inner dim. Inner dim is tp_q_head_num * head_dim. Splitting into tp_q_head_num/2 * head_dim gives 2 slots per token. Per token, slot 0 = heads[0:H/2], slot 1 = heads[H/2:H]. So q_reshaped[2*token + 0] = token's heads[0:H/2] = head_group 0, and [2*token+1] = head_group 1. ✓
But wait - q has tp_q_head_num = 32 heads (nq), and num_kv_heads=2 (nkv). Each kv head is shared by 32/2=16 query heads. So heads_per_group=16, head_group_num=2. With 16 q-heads per group: q_reshaped[2*token+0] = 16 query heads belonging to head_group 0. ✓
Now FA: each row of q_sparse is fed to FA as (num_qo_heads = 16, head_dim). The page_table row points to slots in the half-cache (which has 1 kv head per "slot"). For each q head among 16, attend to that single kv head. So MQA with 16:1 grouping per head_group. ✓
OK that all checks out. The remaining bug is the q_reshaped vs q_sparse contiguity issue.
Let me now check one more thing - whether q.contiguous() actually returns the same memory if q is already laid out contiguously. Let me trace one more way - the q in forward_extend is what's passed in by self.attn(q, k, v, forward_batch). The RadixAttention.forward will reshape this. Let me look:
Let me also re-verify if there's an issue when max(seq_lens) < dense_len AND sparse_batch_size < bs. In that case metadata.sparse_bs_list is empty (line 564 / 1322-1326 only adds bs with seq_lens >= dense_len). So dense_bs_list = [0..bs). The loop at line 1587-1614 writes all bs as dense. metadata.sparse_page_table was allocated with shape (sparse_page_table_bs, max_sparse_cache_len) where sparse_page_table_bs = bs * head_group_num and max_sparse_cache_len = max(seq_lens_cpu). OK.
Alright, I think I have enough now. Let me also quickly verify how the prefill metadata calls extend_prefix_lens_cpu for empty sparse_bs_list:
At line 579-586: extend_prefix_lens_sparse = torch.tensor([forward_batch.extend_prefix_lens_cpu[bs] for bs in metadata.sparse_bs_list], dtype=torch.long, device="cpu"). If sparse_bs_list is empty, this is an empty tensor of dtype long, device cpu. Then build_token_mappings at line 1414 — q_shape_sparse_bs = int(cu_seqlens_q_sparse_bs[-1].item()) — cu_seqlens_q_sparse_bs from line 575-577 is [0].cumsum() = [0], so cu_seqlens_q_sparse_bs[-1] = 0. token_to_bs = repeat_interleave(arange(0), empty) → empty. token_pos_in_bs = empty. OK. Then loop at 1447 for i in range(0) — no-op. Returns empty tensors.
OK that's fine. But then at line 595 they're moved to device. Empty tensors. Fine.
Then prefill_metadata is built normally. sparse_idx is empty list (since sparse_bs_list is empty). And sparse_page_table_bs = bs * head_group_num. old_bs_to_new_bs_range = [0, 2, 4, ..., 2*bs]. sparse_max_seq_len_q = max(extend). OK.
Now line 622 forward_batch.sparse_idx = []. At line 1543-1545 (check path), _old_sparse_page_table[forward_batch.sparse_idx, ...] = sparse_page_table_sparse_bs — empty assign. OK.
Then at line 1583+, forward_batch.sparse_batch_size < bs is True (sparse_batch_size=0 < bs). Goes into dense loop, writes all bs. OK.
Now let me also check init_forward_metadata explicitly for chunked prefill vs first chunk:
Looking back at line 1739: cu_seqlens_k_new=metadata.sparse_cu_seqlens_k. Where sparse_cu_seqlens_k is computed at line 1694: F.pad(torch.cumsum(metadata.sparse_cache_seqlens_int32, dim=0, dtype=cu_seqlens_k.dtype), (1, 0)). So this is cumulative of cache_seqlens — i.e., total k tokens cumulated across rows. The k tokens are read from the page_table; total k tokens is sum of cache_seqlens. For FA's varlen interface this is right. ✓
Alright I think I have enough. Let me compile the report.
_MINICPM_DERIVED_SPARSE_SEQLENS=False
0
Bug 3: Stage1 cache_lens size mismatch when sparse-bs max_seqlen_q == 1 in mixed batch
File:minicpm_backend.py:1246 (consumer in compressed_attention at minicpm_sparse_utils.py:853)
When max_seqlen_q==1 (chunked-prefill last-1-token chunk for sparse bs), sparse_get_topk_impl picks cache_lens = self.forward_metadata.cache_seqlens_int32_stage1. That tensor has length bs (full batch). But the surrounding cu_seqlens_q it's paired with (topk_metadata["cu_seqlens_q"] = cu_seqlens_q_sparse) has length len(sparse_bs)+1. The pool kernel indexes cache_lens[batch] where batch is the sparse-bs position; in mixed batch this picks up dense-bs entries instead of sparse-bs entries. Severity: silent wrong output for stage1 topk on mixed-batch chunked-prefill final 1-token-extend chunk. Other max_seqlen_q values are safe (the else branch at line 1248-1250 derives cache_lens from the sparse-only cu_seqlens).
Bug 4: metadata.cu_seqlens_q_adjusted / max_seqlen_q_adjusted are sparse-bs-filtered, but stage1 also runs on the all-sparse branch
File:minicpm_backend.py:624-635 (build) and :1282-1283 (consume)
In the all-sparse path (line 977) the topk call uses metadata.cu_seqlens_q (full bs == sparse bs, fine) but inside sparse_get_topk_impl passes forward_metadata.cu_seqlens_q_adjusted. The build at line 626-635 only includes seq_lens_cpu[i] >= dense_len. In the all-sparse path under dense_as_sparse=False, this still includes all bs (because all-sparse means all bs have seq>=dense_len). OK there. But in the mixed-batch path the FA call at line 1740 uses metadata.sparse_max_seq_len_q (built in build_sparse_prefill_metadata, sees both dense+sparse) while stage1's max_seqlen_q_adjusted (line 635) is sparse-only. The two max_seqlen_qs now describe different layouts — fine if they only flow into their respective kernels, but worth flagging: any future code that grabs cu_seqlens_q_adjusted and tries to align with metadata.cu_seqlens_q (full layout) will mis-align. Severity: latent / no current crash, but tightly coupled to Bug 3.
No-bug-but-suspicious
metadata.sparse_cu_seqlens_q_cpu dtype: line 1599-1603 subtracts CPU-tensor elements; arithmetic returns 0-dim tensors compared via == to Python ints from extend_seq_lens_cpu. Works under PyTorch, but fragile if extend_seq_lens_cpu ever becomes a tensor field rather than a list.
build_token_mappings empty path (mixed-batch where every bs is dense, i.e. sparse_bs_list = []): produces empty token_to_bs / token_pos_in_bs. Downstream consumers (block_table builder at line 1487-1503) are gated by max(seq_lens) >= dense_len, so they don't fire. OK today, but a future change that runs the block_table v2/v3 path unconditionally would crash on empty inputs.
get_block_table_v3 decode signature (line 1929-1936) passes cache_seqlens twice (as both seqlen_k_sparse_bs_tensor and the previous parameter). Looks intentional for decode, but the symmetry differs from prefill (line 1487-1494) where token_pos_in_bs and seqlen_k_sparse_bs_tensor are separate. Hard to verify without the kernel source.
_USE_TRTLLM_STAGE2: per CLAUDE.md the implementation isn't in the current tree; nothing to check.
Verified-OK (mixed-batch handles correctly)
_MINICPM_DIRECT_SPARSE_PAGE_TABLE, _MINICPM_TOPK_TO_FI_INDICES, use_block_page64, shape_only_plan_cache — all gated on sparse_batch_size == bs, correctly disabled in mixed batch (minicpm_backend.py:1481, 1536, 1715, 1749).
_MINICPM_DERIVED_SPARSE_SEQLENS — gated on sparse_batch_size == bs (line 1618), correctly disabled in mixed batch (it would be wrong because it doesn't see dense-bs rows).
sparse_cu_seqlens_q_cpu layout in mixed batch (build_sparse_prefill_metadata line 1764-1780): interleaves sparse-bs rows (q-len 1 each, extend*head_group_num rows) and dense-bs rows (q-len extend, head_group_num rows) consistently with old_bs_to_new_bs_range.
The previously-fixed Bug 2 (max_sparse_cache_len using seq_lens_cpu[i] not extend_seq_lens_cpu[i]) — confirmed by the inline comment at 1740-1743.
The previously-fixed Bug 1 (lazy wrapper creation under inference_mode) — with torch.inference_mode(False): wraps lines 394-399, 412-417, 427-432.
CUDA-graph state init/replay (init_cuda_graph_state / init_forward_metadata_capture_cuda_graph / init_forward_metadata_replay_cuda_graph) is decode-only and assumes sparse_bs = 2*bs (all-sparse decode); mixed batch isn't reachable through CUDA-graph since chunked prefill doesn't capture graphs. Safe today.
Post-FA un-interleave at line 1809-1834 is the inverse of the pre-FA shuffle and is symmetric, so once Bug 1 is fixed it will be consistent.
extend_prefix_lens_sparse (line 579-586) is correctly indexed by sparse_bs_list only; build_token_mappings (line 1447-1456) loops over the same list.
FlashInfer page-table convert path (convert_sparse_to_flashinfer_two_kernel) uses cache_seqlens per-row to size the slice and is robust to slot-id 0 in entries — the upstream sparse_cache_seqlens_int32 is the weak link (Bug 2), not the convert itself.
正确性等价:在 last_N 足够大时(如 32K),accept rate 不退化
一等公民:不是 env hack,是 server arg / config 的合法参数(如 --speculative-draft-prefix-window 32768)
# Speculative decoding — draft prefix window
speculative_draft_prefix_window: int = 0
speculative_draft_prefix_strategy: Literal["full", "skip", "truncate"] = "full"
speculative_draft_prefix_min_seq_len: int = 0 # 短于此 → 自动 full
python
parser.add_argument(
"--speculative-draft-prefix-window",
type=int, default=0,
help="Window size (tokens) for EAGLE draft prefill on long prompts. "
"0 = unlimited (use full prefix, baseline). >0 = clip draft prefill "
"to the trailing `window` tokens of each request when seq_len exceeds it.",
)
parser.add_argument(
"--speculative-draft-prefix-strategy",
type=str, choices=["full", "skip", "truncate"], default="full",
help="How the draft handles prompts longer than --speculative-draft-prefix-window: "
"'full' (always full prefill, baseline), "
"'skip' (skip draft prefill entirely, seed via prepare_extend_after_decode — current hack semantics), "
"'truncate' (draft attends to only the last `window` tokens; KV pool stores window tokens at correct positions).",
)
parser.add_argument(
"--speculative-draft-prefix-min-seq-len",
type=int, default=0,
help="Per-request threshold below which to always use full draft prefill regardless of strategy.",
)
forward_batch side effects: NO observable issue. ForwardBatch.init_new is pure construction, return_logprob = False, forward(...) and capture_for_decode are the only side effects skipped — which is intentional. prepare_for_extend (line 2107) ran already, so batch.input_ids is in-place updated with verified_id shifted; no consumer between chunks anyway. forward_draft_extend has no cuda graph for this code path (line 2187-2191 is plain eager forward; cuda_graph_runner_for_draft_extend is only used in forward_draft_extend_after_decode at line 2283). No KV allocator state or graph state goes stale.
NO — 该路径无 cuda graph (line 2187-2191 eager forward);prepare_for_extend 已跑,batch.input_ids 副作用完成且无下游消费;没有遗漏副作用。
唯一建议:修正 line 2138-2142 行内注释,把 "Draft KV slots ... remain zero-initialized (memory_pool default)" 改为 "unwritten — may hold residual KV from prior requests reusing the same slot index; draft attention tolerates this because the trailing N-token window dominates softmax"。这是文档准确性问题,不是 bug。
SWA pool 写映射:/user_4813494d/openbmb/demo-sala/sglang/python/sglang/srt/mem_cache/swa_memory_pool.py:141-185
allocator slot 复用不清零:/user_4813494d/openbmb/demo-sala/sglang/python/sglang/srt/mem_cache/allocator.py:131-163(free() 只把 index 推回 free_pages,无 zero_())
translate_loc_from_full_to_swa ring buffer 映射:/user_4813494d/openbmb/demo-sala/sglang/python/sglang/srt/layers/attention/flashinfer_backend.py:1407-1413