fix(attention): accept non-contiguous index tensors in plan() #5385
All Vouch review confidence checks passed
Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)).
Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.52 · 650 lines diff across 8 files
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.17 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size
diff_size
0.388
Shallow Review Depth
shallow_review_depth
0.289
Real PR Conversation Timeline
1 comments
"Review active on #5385"
general
weight: 0.35
LiRunGuo
<!-- .github/pull_request_template.md -->
📌 Description
plan()passes user-supplied index tensors (indptr/indices/last_page_len) to the C++ planner and the kernels as raw data pointers without checking contiguity. A strided view (e.g.indptr_full[::2]) is therefore misread, in two ways:self.__buf = indptr.to(self.device)is a no-op for a strided CUDA view, so the kernel buffers stay strided.indptr.to("cpu"), on the other hand, returns a contiguous host copy for the planner. The plan and the kernel then disagree about the layout..to("cpu")is a no-op, so the strided host tensor goes straight into the C++ planner.Measured on H200 (SM90) with stride-2 views holding identical values (fp16, 8/2 heads, head_dim 128, page_size 16, 4 requests):
| wrapper / backend | strided metadata on CUDA | strided metadata on CPU |
|---|---|---|
| Ragged prefill, fa2 | illegal memory access |
PrefillSplitQOKVIndptrcheck fails || Ragged prefill, fa3 | OK |
PrefillSM90Plancheck fails || Paged prefill, fa2 | illegal memory access |
PrefillSplitQOKVIndptrcheck fails || Paged prefill, fa3 | wrong output (max abs diff 3.3) |
PrefillSM90Plancheck fails || Paged decode, CUDA cores | wrong output (max abs diff 3.0) | wrong output (max abs diff 4.6), no error |
| Paged decode, tensor cores | wrong output (max abs diff 2.6) |
PrefillSplitQOKVIndptrcheck fails ||
BlockSparseAttentionWrapper(auto) | fails (not isolated: ran after an IMA in the same process) | wrong output (93% of elements mismatched) |Fix: call
.contiguous()on the index tensors at the top ofplan()in:BatchPrefillWithPagedKVCacheWrapper.plan:qo_indptr,paged_kv_indptr,paged_kv_indices,paged_kv_last_page_lenBatchPrefillWithRaggedKVCacheWrapper.plan:qo_indptr,kv_indptr, and the optionalo_indptr/v_indptrBatchDecodeWithPagedKVCacheWrapper._plan_implandfast_decode_plan:indptr,indices,last_page_lenBlockSparseAttentionWrapper.plan:indptr,indicesseq_lens(when given) in the paged prefillplan()and decode_plan_impl: it is copied to the host withseq_lens.cpu(), which is a no-op for a strided CPU view, and the host copy goes to the native planner. With fa3 paged prefill a strided CPUseq_lenswas an illegal memory access._plan_indptr_host(the ragged wrapper'sqo_indptr_cpu/kv_indptr_cpu, which it validated for device/shape/dtype but not contiguity) andfast_decode_plan'sglobal_override_indptr_cpu. These parameters were added upstream after the first version of this PR.workspace_size()on the paged prefill and decode wrappers, which mirrorsplan()'s host copies: the same tensors, includingseq_lens. Without it, strided CPU indptrs failed the native size query'sPrefillSplitQOKVIndptrcheck (tensor-core decode, fa2 prefill). Thanks to the CodeRabbit review for flagging this one.These tensors are tiny, and
plan()already copies them between host and device..contiguous()returnsselffor contiguous inputs, so the usual path is unchanged. The CUDA-graph pathscopy_()into preallocated buffers and were already correct.Out of scope:
mla/_batch_mla/_planning.py).VariableBlockSparseAttentionWrapperbuilds its own indptr viacat/cumsum, so it is always contiguous.🔍 Related Issues
Fixes #5260
🚀 Pull Request Checklist
✅ Pre-commit Checks
pre-commitby runningpip install pre-commit(or used your preferred method).pre-commit install.pre-commit run --all-filesand fixed any reported issues.🧪 Tests
unittest, etc.).New file
tests/attention/test_plan_noncontiguous_metadata.py(32 cases): ragged and paged prefill (fa2/fa3), paged decode (with and without tensor cores),fast_decode_plan, and block-sparse, with metadata on CUDA and on CPU, and with and withoutseq_lensfor paged prefill and decode. Each case plans the same problem with contiguous metadata and with stride-2 views of the same values, then compares outputs. Aworkspace_size()case checks that strided and contiguous metadata give the same sizes.Verified on H200 (SM90, CUDA 12.8, torch 2.14, flashinfer at main
9cab083+ this branch), each case in its own process so an illegal access cannot mask later cases:| arm | result |
|---|---|
| main, unpatched | 24 of 29 fail (of the cases that existed then) (illegal memory access / planner check failure / output mismatch) |
| this branch | 32 of 32 pass |
The three cases added in the last round (
qo_indptr_cpu/kv_indptr_cpuandglobal_override_indptr_cpu) also fail with only those two normalizations reverted on top of this branch, so they cover a distinct bug rather than the plan() one.Regression check on H200, sampled from
test_batch_prefill_kernels.py,test_batch_decode_kernels.py,test_block_sparse.py,test_workspace_size.py,test_lse_base.pyand this new file (all cases of functions with <=300 parametrizations, every 25th case of the larger sweeps, 1,498 ids over 3 GPUs): 1,140 passed, 358 skipped, 0 failed.pre-commit run --files <changed>passes (ruff, ruff-format, mypy and the whitespace hooks).Reviewer Notes
ValueErrorfor non-contiguous metadata, andattention/_core.pyrejects a non-contiguousbidirectional_rangeswith the rationale that copying "would hand the kernel a fresh pointer on every call, which a captured CUDA graph would then replay against freed memory". That hazard does not apply here:.contiguous()returns the same object for an already-contiguous tensor, so the common path is unchanged, and a pointer only changes for input that was previously misread. Where a copy can happen, the wrapper retains it — the non-graph paths assign it toself.__buf, and the CUDA-graph pathscopy_()into their preallocated buffers instead of rebinding (fast_decode_planrebinds only in its non-graph branch). I am happy to switch to rejecting if maintainers prefer the strict contract; the tests would just invert.BatchAttentionWithAttentionSinkWrappersubclassesBatchPrefillWithPagedKVCacheWrapper, so it inherits the fix and needs no separate change.CHECK_INPUT) on indptr. This PR keeps the change at the Python boundary. Adding C++ checks would also cover direct callers of the low-level modules, and could be a follow-up.seq_lensandworkspace_size()coverage came from the earlier CodeRabbit comment, andfast_decode_plancoverage was added in this round.<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
<!-- coderabbit-ai-generated:v1 -->
Summary by CodeRabbit
Bug Fixes
Improved handling of non-contiguous metadata during attention planning and workspace sizing, helping ensure correct results and consistent workspace requirements.
Applied across decode, prefill, and block-sparse attention workflows, including planning inputs and optional metadata.
Tests
* Added regression coverage comparing contiguous and non-contiguous metadata behavior across decode, prefill, and block-sparse attention, including CPU and CUDA cases where applicable.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->