Skip to content

SM120 FP8 TMA paged prefill (paged_tma): V rows past the sequence length reach P·V #202

Closed

Description

@mark-yong

Contract conflict between Flare and local-inference-lab/flashinfer (flashinfer/cute_dsl/attention/fmha/sm120/), filed here because issues are disabled on the fork. Found by the poison tests for #116; code locations refer to FlashInfer 3c2729e7.

The kernel documents that paged pools must be finite in every slot, so under its contract this is Flare passing non-finite bytes rather than a kernel bug. A maintainer decision on which side owns the guarantee is needed before a fix (see Decision needed).

Problem

The kernel from flashinfer.cute_dsl.attention.fmha.sm120.compile_sm120_fmha_fp8_paged_kernel includes V rows past the sequence length of the last 128-key tile in P·V. Causal masking zeroes their probabilities, but 0 × NaN = NaN, so non-finite bytes past the length in the last page turn every live query row NaN.

K is safe: poisoning only K never changes the output.

Contract

The kernel requires finite values in every paged K/V slot, including unused padding (fmha_prefill_fp8_tma.py):

:param k: Packed key ``(total_k, Hkv, D)`` or HND paged K pool
    ``(num_pages, Hkv, num_tokens_per_page, D)``. Paged pools must
    contain finite values in every slot, including unused padding.
:param v: Packed or paged value with the same shape and finite-value
    contract as K.

Partial tiles depend on it: resolve_paged_kv_tile_pages points page chunks past seqlen_kv at the request's last page so TMA always has a legal full-page address ("Paged pools, including unused slots, are required to contain finite values", line 670).

Flare does not guarantee this. Snapshot-alias rows write raw state bytes into borrowable KV pages, and released pages return to the pool unscrubbed, so a later request's last page can hold non-finite bytes past its length (#116, #181).

Repro

poison_paged_tma.py (below) (plus poison_common.py; needs flashinfer, cutlass and b12x for the reference). It calls the kernel as Flare's paged_tma component does:

compile_sm120_fmha_fp8_paged_kernel(
    in_dtype=torch.float8_e4m3fn, out_dtype=torch.bfloat16, num_qo_heads=24, num_kv_heads=4,
    head_dim=256, is_causal=True, kv_tile=128, q_tile=128, num_tokens_per_page=128,
    device=device, balanced_scheduler=True, kv_layout="NHD", with_output_gate=False)

One request, query capacity 256, with 37, 128 or 256 live rows. Every cache slot past the length is filled with zeros, then NaN (0x7F). FlashInfer 3c2729e7, RTX PRO 6000 (SM120).

Lengths Poisoned NaN output
129, 135, 143, 144, 160, 200, 255, 257, 272, 383, 511 K and V, or V only every live query row
same K only none
256 any none

Zero-fill output matches the reference.

Decision needed

Either side can own the guarantee:

  • FlashInfer relaxes the contract: zero V rows at or past seqlen_kv in registers after the TMA stage arrives and before P·V, deriving validity from the logical tile position rather than the redirected page. Only the last partial tile needs it (tile_start + kv_tile > seqlen_kv), so full tiles stay on the current path. This makes the kernel robust on its own, at a cost to be benchmarked.
  • Flare enforces the contract: guarantee finite bytes in every slot a full-tile TMA load can reach, at every cache lifecycle boundary (release, snapshot-alias handoff, restore). Clear released snapshot-alias pages before their first KV use #181 is the current form of this for released alias pages.

The b12x kernels with the same symptom (#201, #203, #204) have no such documented contract, so they are fixed in the kernel either way.

Impact

Flare uses this kernel for qwen3.8-27B causal FP8 prefill/extend (ignition/components/paged_tma.py). Almost every prefill has length % 128 != 0, so any non-finite stale bytes in the last page poison the whole chunk. Not tested: SM121 (the kernel is built for SM120 and SM121), CUDA graph replay.

Repro scripts

poison_paged_tma.py
"""Poison test: does Flare paged_tma (FlashInfer SM120 FP8 TMA prefill) read KV past the length?

Calls the kernel exactly as ignition/components/paged_tma.py State.run does on
Flare main b4196955: FP8 NHD KV, 128-token pages, head 256, one request, causal.
"""

import math

import torch
from cutlass import Float32, Int32
from flashinfer.cute_dsl.attention.fmha.sm120 import compile_sm120_fmha_fp8_paged_kernel
from b12x.attention.paged.reference import paged_attention_reference

from poison_common import compare, fill, invalid_slots

DEVICE = torch.device("cuda", 0)
Q_HEADS, KV_HEADS, DIM, PAGE = 24, 4, 256, 128
PAGES_PER_REQ, NUM_PAGES, CAPACITY = 4, 16, 256
FP8 = torch.float8_e4m3fn
LENGTHS = (129, 135, 143, 200, 255, 256, 257, 383, 511, 144, 160, 272)
LIVE_ROWS = (128, 37, 256)


def main():
    torch.manual_seed(1160)
    key = (torch.randn(NUM_PAGES, PAGE, KV_HEADS, DIM, device=DEVICE) * 0.1).to(FP8)
    value = (torch.randn(NUM_PAGES, PAGE, KV_HEADS, DIM, device=DEVICE) * 0.1).to(FP8)
    query = (torch.randn(CAPACITY, Q_HEADS, DIM, device=DEVICE) * 0.1).to(FP8)
    output = torch.empty(CAPACITY, Q_HEADS, DIM, device=DEVICE, dtype=torch.bfloat16)
    table = torch.randperm(NUM_PAGES, device=DEVICE)[:PAGES_PER_REQ].int().view(1, PAGES_PER_REQ).contiguous()
    lengths = torch.zeros(1, device=DEVICE, dtype=torch.int32)
    cu = torch.zeros(2, device=DEVICE, dtype=torch.int32)
    kernel = compile_sm120_fmha_fp8_paged_kernel(
        in_dtype=FP8, out_dtype=torch.bfloat16, num_qo_heads=Q_HEADS, num_kv_heads=KV_HEADS,
        head_dim=DIM, is_causal=True, kv_tile=128, q_tile=128, num_tokens_per_page=PAGE,
        device=DEVICE, balanced_scheduler=True, kv_layout="NHD", with_output_gate=False)

    def run():
        output.zero_()
        kernel(query, key.permute(0, 2, 1, 3), value.permute(0, 2, 1, 3), output, None,
               Float32(math.log2(math.e) / math.sqrt(DIM)), Float32(1), None,
               lengths, cu, table, None, Int32(CAPACITY), False)

    for live in LIVE_ROWS:
        for length in LENGTHS:
            if length < live:
                continue
            lengths.fill_(length)
            cu[1] = live
            slots = invalid_slots(NUM_PAGES, PAGE, table, lengths)
            for which in ("kv", "k", "v"):
                results = {}
                for poison in ("zero", "nan"):
                    fill(key, slots, poison if "k" in which else "zero")
                    fill(value, slots, poison if "v" in which else "zero")
                    run()
                    torch.cuda.synchronize()
                    results[poison] = output[:live].clone()
                fill(key, slots, "zero")
                fill(value, slots, "zero")
                expected, _ = paged_attention_reference(
                    query[:live].bfloat16(), key, value, table, lengths, cu, causal=True,
                    window_left=-1, attention_sink_bias=None,
                    k_descale=torch.ones(1, device=DEVICE), v_descale=torch.ones(1, device=DEVICE))
                compare(results["zero"], results["nan"], expected, kernel="paged_tma", live=live,
                        length=length, mod16=length % 16, poisoned=which)


if __name__ == "__main__":
    main()
poison_common.py
"""Shared poisoning and comparison for the #116 attention poison tests."""

import torch

NAN_BYTES = {torch.float8_e4m3fn: (0x7F,), torch.bfloat16: (0xC0, 0x7F)}


def invalid_slots(num_pages, page, table, lengths):
    """Mask of [page, row] cache slots that no request may read."""
    valid = torch.zeros(num_pages, page, dtype=torch.bool, device=table.device)
    positions = torch.arange(table.shape[1] * page, device=table.device)
    for request in range(table.shape[0]):
        live = positions[positions < int(lengths[request])]
        valid[table[request, live // page].long(), live % page] = True
    return ~valid


def fill(cache, slots, mode):
    raw = cache.view(torch.uint8).view(cache.shape[0], cache.shape[1], -1)
    if mode == "zero":
        raw[slots] = 0
        return
    pattern = torch.tensor(NAN_BYTES[cache.dtype], dtype=torch.uint8, device=raw.device)
    rows = raw[slots]
    rows.view(rows.shape[0], -1, pattern.numel())[:] = pattern
    raw[slots] = rows


def compare(zero, nan, expected, **fields):
    zero, nan = zero.float(), nan.float()
    row = dict(fields,
               zero_err=float((zero - expected.float()).abs().max()),
               nan_outputs=int(torch.isnan(nan).sum()),
               nan_rows=int(torch.isnan(nan).flatten(1).any(-1).sum()),
               max_diff=float(torch.nan_to_num(nan - zero, nan=float("inf")).abs().max()))
    print("ROW", row, flush=True)
    return row

Activity

  1. mark-yong commented on Nov 5, 2026

    @mark-yong
    ContributorAuthor

    Reran the repro from this issue (poison_paged_tma.py + poison_common.py, unchanged) on local-inference-lab/flashinfer 1f8ed8a3 — the operand-masking commit Flare's spark-local-inference pin 5a1640c8 moved to — on RTX PRO 6000 (SM120), GPU 2, single process.
    Result: every case is clean. 87/87 rows — all 12 lengths at live rows 128 and 37, plus the 5 lengths that fit 256 live rows, each poisoned with K+V, K only, and V only — report zero NaN outputs and zero diff against the zero-fill reference. On 3c2729e7 the same run poisoned every live query row for K+V and V-only. Log: logs/poison202-newpin.log on the fix116 scratch host.

    So the masking added in 1f8ed8a3 covers the SM120 FP8 TMA paged prefill's P·V as well: V rows past the sequence length in the last partial tile no longer reach the accumulator with non-finite bytes.

    Two follow-ups on the issue text:

    1. The "Decision needed" question is moot for the NaN symptom. Neither side needs to own the finite-padding guarantee for this kernel's correctness anymore — 0 × NaN can no longer reach the output. Flare does not need to enforce finite bytes in unused slots for this path.

    2. The docstring on fmha_prefill_fp8_tma.py still says paged pools "must contain finite values in every slot, including unused padding". With masking in place that requirement no longer looks load-bearing for this kernel; whether to relax the wording (here or for other kernels that share it) is your call.

    Still untested, carried from the issue: SM121, and CUDA graph replay (the repro calls bind/run directly).

    Closing this issue as fixed by the operand-masking commit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions