Skip to content

fix(indexer): add validated bounded compatibility policy - #82

Closed
yatesdr wants to merge 2 commits into
local-inference-lab:masterfrom
yatesdr:fix/longctx-indexer-validated-compat-pr-20260726
Closed

fix(indexer): add validated bounded compatibility policy#82
yatesdr wants to merge 2 commits into
local-inference-lab:masterfrom
yatesdr:fix/longctx-indexer-validated-compat-pr-20260726

Conversation

@yatesdr

@yatesdr yatesdr commented Jul 26, 2026

Copy link
Copy Markdown
Contributor

Summary

Add an explicit SPARKINFER_NSA_TOPK_SELECTION_POLICY=bounded_compat
policy for sparse-MLA deployments whose checkpoints were validated against
the historical bounded radix selector.

The default remains exact. Unknown values fail closed at import time.

Fixes the SparkInfer component of
local-inference-lab/vllm#182.

Root cause

The v20 exact-overflow changes (1012199e, later optimized by 83a58444)
changed the selected sparse-attention set at long context. On captured
production tensors:

  • exact v20 matches the quantized-proxy top-k 2,048/2,048;
  • historical bounded selection matches 1,872--1,896/2,048;
  • the changed exact-only candidates are all in the final quarter of context;
  • the bounded-only candidates are predominantly in the first half.

This model has no separate sliding/local window in sparse layers. The exact
proxy selector therefore reallocates part of the only 2,048-entry sparse
attention budget away from older positions. Exactness for the
E4M3-query/FP8-key proxy did not preserve end-to-end retrieval quality.

Change

bounded_compat explicitly selects the historical:

  • 8-bit coarse radix;
  • 4,096-entry candidate buffer;
  • bounded refinement without the exact overflow rescan.

All shared-memory writes remain bounds-checked. The selection policy is part
of the compile-cache key. No behavior changes unless the new policy is
explicitly enabled.

Reproduction and causal evidence

Frozen production posture:

  • GLM-5.2 NF3 hybrid weights;
  • TP4/DCP4/MTP3, MNBT 3,072;
  • NVFP4 MLA KV, FP8 RoPE;
  • i8_ring;
  • cold cache (cached_tokens=0);
  • identical rendered prompts, token IDs, and seeds.

Results:

Cell Stock exact v20 bounded_compat
250k control EXACT EXACT
350k seed 1 ABSENT EXACT
350k seed 2 ABSENT EXACT
350k seed 3 ABSENT EXACT

All recovered responses finalized normally with content 738216. The
discriminator boot remained healthy with a 507,612-token KV pool at 460k,
zero restarts, and no illegal-access, cuBLAS, EngineDead, OOM, traceback,
assertion, or worker-died signatures.

An independent cold generalization ladder on the same process also passed:

Rendered context Result Cached tokens
49,100 EXACT 0
147,275 EXACT 0
294,619 EXACT 0
441,964 EXACT 0

The trace-free production candidate then passed the established deepest cold
gate at a 480,000-token admission limit:

Rendered context Result Cached tokens Finish Content
466,493 EXACT 0 stop 738216

That candidate was derived from the clean 5517197/be0edca release image and
contained only PR #80 plus this PR. It exposed a 500,992-token KV pool, remained
healthy with zero restarts, and had zero fatal signatures.

Full reproduction, frozen prompt hashes, boundary traces, learned-tensor
replay, and evidence hashes are in
vLLM issue #182.

Validation

  • python -m py_compile passes for the changed module and policy test.
  • A derived v20 image compiled the new policy, completed production and
    speculator graph capture, and passed the frozen causal gate above.
  • Existing exact behavior remains the default and its kernel branches are
    unchanged.

The focused pytest was not run on the authoring Mac because that environment
does not have pytest installed; CI should run
tests/attention/test_nsa_topk_selection_policy.py.

Scope

This PR provides a visible compatibility policy, not a claim that bounded
selection should become the universal default. A future default should be
deterministic and justified by end-to-end model quality rather than only
quantized-proxy exactness.

Summary by CodeRabbit

  • New Features

    • Added configurable selection policies for top-k processing, including exact and bounded-compatibility modes.
    • Policy values now support whitespace trimming and normalization.
  • Bug Fixes

    • Improved handling of large candidate sets under bounded compatibility mode.
  • Tests

    • Added coverage for valid, normalized, missing, and invalid selection-policy values.

@coderabbitai

coderabbitai Bot commented Jul 26, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds environment-controlled exact and bounded_compat selection policies for tiled and row top-k kernels, changes bounded-mode overflow behavior and memory sizing, separates compilation caches by policy, and tests policy parsing.

Changes

Selection policy execution

Layer / File(s) Summary
Policy resolution and kernel sizing
sparkinfer/attention/nsa_indexer/tiled_topk.py
The module normalizes supported environment values, derives bounded-mode shared-memory settings, and stores the resolved mode on kernel instances.
Policy-gated overflow handling
sparkinfer/attention/nsa_indexer/tiled_topk.py
Bounded compatibility skips the overflow sentinel and exact rescan fallback, while exact mode retains them.
Policy-specific compilation and validation
sparkinfer/attention/nsa_indexer/tiled_topk.py, tests/attention/test_nsa_topk_selection_policy.py
Tiled and row-topk cache keys include the selection policy, and tests cover normalization and invalid values.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Environment
  participant tiled_topk
  participant TopkKernel
  participant CudaCache
  Environment->>tiled_topk: set selection policy
  tiled_topk->>TopkKernel: configure exact or bounded_compat mode
  TopkKernel->>TopkKernel: handle threshold-bin overflow
  tiled_topk->>CudaCache: compile using policy-specific cache key
Loading

Possibly related PRs

Suggested reviewers: lukealonso

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: adding and validating a bounded compatibility selection policy for the indexer.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tests/attention/test_nsa_topk_selection_policy.py`:
- Around line 10-30: Extend the CUDA tests beyond _resolve_selection_policy
parsing with an oracle case containing a threshold bin larger than 4,096
candidates. Exercise both tiled and row dispatches, asserting exact matches the
reference top-k and bounded_compat matches the historical bounded selector’s
expected outputs; include the required nonzero input and boundary/selection
correctness checks before any timing assertions.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 6d01d05c-fabb-4363-8495-eb49b8f3541c

📥 Commits

Reviewing files that changed from the base of the PR and between c39b806 and ec8052e.

📒 Files selected for processing (2)
  • sparkinfer/attention/nsa_indexer/tiled_topk.py
  • tests/attention/test_nsa_topk_selection_policy.py

Comment on lines +10 to +30
@pytest.mark.parametrize(
("raw", "expected"),
[
(None, "exact"),
("", "exact"),
("exact", "exact"),
(" EXACT ", "exact"),
("bounded_compat", "bounded_compat"),
(" BOUNDED_COMPAT ", "bounded_compat"),
],
)
def test_resolve_selection_policy(raw: str | None, expected: str) -> None:
assert _resolve_selection_policy(raw) == expected


def test_resolve_selection_policy_rejects_unknown_value() -> None:
with pytest.raises(
ValueError,
match="SPARKINFER_NSA_TOPK_SELECTION_POLICY must be one of",
):
_resolve_selection_policy("legacy")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Test the actual bounded-overflow contract.

These cases only test parsing. Add a CUDA oracle test with a threshold bin exceeding 4,096 candidates: exact must equal reference top-k, while bounded_compat must match the historical bounded selector’s expected outputs. Exercise both tiled and row dispatches.

As per coding guidelines, “Validate correctness gates—including oracles, cosine/top-k equality, nonzero tensors, quantization semantics, and boundary behavior—before interpreting timings.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/attention/test_nsa_topk_selection_policy.py` around lines 10 - 30,
Extend the CUDA tests beyond _resolve_selection_policy parsing with an oracle
case containing a threshold bin larger than 4,096 candidates. Exercise both
tiled and row dispatches, asserting exact matches the reference top-k and
bounded_compat matches the historical bounded selector’s expected outputs;
include the required nonzero input and boundary/selection correctness checks
before any timing assertions.

Source: Coding guidelines

@yatesdr

yatesdr commented Jul 28, 2026

Copy link
Copy Markdown
Contributor Author

Superseded by SparkInfer #86 and vLLM #189, which provide improved fixes.

@yatesdr yatesdr closed this Jul 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant