← Back to Pull requests

feat(attention): add causal + bidirectional-ranges batch prefill #5189

Closed
unknown closed this pull request without merging on Sep 18, 2026 08:23 UTC
View on GitHub
unknown unknown commented on Sep 13, 2026 11:03 UTC
Author

<!-- .github/pull_request_template.md -->

📌 Description

FA2 supports custom attention variants, but there is currently no packaged batch-prefill path for sequences that are causal except for spans that attend in both directions. Callers either have to materialize a dense custom mask or use a different backend.

The dense mask is O(qo_len * kv_len). For example, 16384 scheduled query tokens against a 262144-token context require 4 GiB just for a boolean mask.

This PR adds an FA2 paged-prefill wrapper that computes the mask directly from a compact int32 [total_q, 2] range tensor:

(causal AND causal_window) OR (in_range AND range_window)

Each query row contains an inclusive [start, end] span in request-local KV positions. (-1, -1) means that the query has no bidirectional span and remains purely causal. At 16384 query tokens, this tensor is 128 KiB regardless of context length.

The implementation uses the existing variant_owns_mask path in BatchPrefillWithPagedKVCacheWrapper; it does not change the default prefill dispatch.

The public API added here is:

| Symbol | Exported from |
|---|---|
| BatchPrefillWithCausalBidirectionalRangesWrapper | flashinfer, flashinfer.attention |
| gen_batch_prefill_bidirectional_ranges_module | flashinfer.jit.attention |

The wrapper and generator share one internal spec for the URI and JIT tensor and scalar arguments.

Two kernel details are worth calling out:

  • The variant sets window_left = kv_len to keep FA2's normal sliding-window tile pruning from discarding keys that may still belong to a bidirectional range. The causal and range windows are applied inside the variant instead.

  • Padded CTA_TILE_Q lanes are clamped to the last real query row before indexing the range tensor.
  • The wrapper is FA2-only because this path relies on a custom LogitsMask being evaluated for every KV tile. Its JIT specialization is fixed in the constructor; plan() and workspace_size() inherit omitted dtype values from that specialization and reject explicit mismatches. Options that conflict with the variant-owned mask are rejected rather than silently ignored.

    Packed NVFP4 KV caches use the existing maybe_k_cache_sf and maybe_v_cache_sf JIT tensor conventions.

    🔍 Related Issues

    None.

    🚀 Pull Request Checklist

    ✅ Pre-commit Checks

  • I have installed pre-commit by running pip install pre-commit (or used your preferred method).

  • I have installed the hooks with pre-commit install.

  • I have run the hooks manually with pre-commit run --all-files and fixed any reported issues.
  • 🧪 Tests

  • Tests have been added or updated as needed.

  • All tests are passing (unittest, etc.).
  • pytest tests/attention/test_bidirectional_ranges_attention.py
    # 39 passed, 2 warnings, on one SM80 device
    

    The targeted tests cover:

  • dense-reference correctness with multiple requests, GQA and shuffled page IDs;

  • independent causal-window and bidirectional-range behavior;

  • partial query tiles and padded lanes;

  • packed NVFP4 KV, separate output dtype and non-unit Q/K/V scales;

  • CUDA graph replay while updating the same range buffer;

  • constructor/plan specialization mismatches and unsupported mask options.
  • Pre-commit hooks for the changed files also pass.

    Reviewer Notes

    This is currently JIT-only. Unlike the existing attention-sink AOT entry, it does not have a small fixed set of dtype and head-dimension combinations to precompile.

    Testing was limited to SM80. I did not run this on SM90 or SM100, and the FP8 paths were not exercised.

    This wrapper is separate from prefix_len_ptr, which selects MaskMode.MULTIITEMSCORING; the two mask modes cannot be combined.

    <!-- This is an auto-generated comment: release notes by coderabbit.ai -->

    Summary by CodeRabbit

  • New Features

  • - Added bidirectional range attention for batch prefill, combining causal masking with per-query key spans.
    - Exposed the new attention wrapper through the public API.
    - Added support for NVFP4 key-value caches and log-sum-exp results.
    - Added validation for range inputs, attention settings, data types, and configuration compatibility.
    - Added tensor-valued query, key, and value scaling support for paged prefill.

  • Documentation

  • - Documented causal and bidirectional ranges prefill functionality.
    <!-- end of auto-generated comment: release notes by coderabbit.ai -->

    Diff: 555 lines (+416 / -139) across 6 files Reviewer: lesj0610 Review duration: 7039m
    All Vouch review confidence checks passed
    Residual risk 0.19 = Change Risk (0.48) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.48 · 555 lines diff across 6 files
    0.48
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    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.378
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #5189"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 48.1% (MEDIUM) · Higher = larger blast radius
    48.1%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 19% · Safe to merge
    19%