Skip to content

b12x sparse_mla: -1 selection entries gather physical record 0 into P·V #204

Closed

Description

@mark-yong

Kernel defect in local-inference-lab/flashinfer (flashinfer/experimental/b12x/attention/_shared/mla/), filed here because issues are disabled on the fork. Found by the poison tests for #116; code locations refer to FlashInfer 3c2729e7.

Problem

In b12x.attention.sparse_mla, every negative (padding) index in selected_indices gathers physical cache record 0. Its score is masked correctly, but the P·V MMA runs over the raw latent values of all 64 staged candidates, so a non-finite record 0 contaminates every row whose 64-candidate chunk is partly invalid:

  • NaN in record 0's latent bytes: NaN in every head of every affected row.
  • NaN in record 0's FP32 group scales: finite but wrong output (max diff 0.89 decode, 1.11 extend).

No other unselected record is read in the production padding layout. Finite poison (448) anywhere is harmless.

Repro

poison_sparse_mla.py (below) (needs b12x). Caps as Flare's PreparedSparseMLA for GLM: model_type=GLM_NEXT, cache_record_bytes=528, head_dim=512, v_head_dim=512, page_size=64, max_width=2051; 8192 records, live ids drawn from 1..N-1. Decode with 16, 32 and 64 heads, extend with 8 and 37 rows, 20 selection counts from 1 to 2051, -1 padding past the count. FlashInfer 3c2729e7, RTX PRO 6000 (SM120).

Poison target Result
every unselected record except record 0 exact match
NaN in record 0 latent NaN wherever the chunk is partly invalid: decode at count % 64 != 0, with -1 holes, or selected_lengths = max width; extend at every count
NaN in record 0 scales finite contamination

glm53's width of 2051 is never a multiple of 64, so nearly every row is exposed.

Separately, in decode only, stale (valid-looking) ids past selected_lengths are read: kernel.py 1185-1224 stages the first chunk up to the plan's full width (io.py 686-713). Flare writes -1 padding, so this does not affect it.

Cause (code reading, attention/_shared/mla/)

  • Negative indices gather record 0: io.py 323-327, 375-377, and the packed path at 613-618.
  • Scores are masked by selection only: decode_math.py 1435-1480.
  • P·V folds the inline scales into the weights, then runs the MMA over the raw E4M3 V of all 64 candidates (decode_math.py 2465-2496, 2564-2572).
  • For scales, NaN appears to win the shared-memory absmax (atomics.py 285-306) and collapse the normalizer (decode_math.py 2505). This chain is read from the code, not instrumented.

Expected

Zero the latent payload (and scales) of invalid candidates before P·V, as compressed_sparse_mla does for its invalid entries.

Impact

Flare glm53. Code reading at Flare b4196955; page-0 rates modelled on main 78b18b1c; not run on a deployment.

  • Record 0 is Helios page 0, token 0 of each kv-{i}-latent plane (glm53/pool.py:88, indexer.py:199). Page 0 is an ordinary page and the first one allocated (helios/src/scheduler.rs:753, 1299-1300).
  • Paths that gather it: SM120/SM121 decode, where the pooled top-k expansion leaves -1 entries uncompacted (pooled_selection.py:64-89), and DCP decode, which runs PreparedSparseMLA on the local paged cache through compacted physical indices with -1 past the count. DCP and SM103 prefill use a per-request slab and are not exposed. SM103 decode uses a different kernel.
  • How record 0 becomes non-finite: serving zeroes the cache at load and the latent writer emits finite records, so record 0 is normally finite. Snapshot rows, however, alias KV pages from the highest page ids downward, and an owned snapshot writes raw row state into them (the Released snapshot aliases hand KV pages back with stale row bytes; masked attention turns them into NaN (device error 6 under KV pressure) #116 mechanism). If the alias ranges reach page 0, record 0 holds snapshot row bytes while that snapshot is owned and after it is released, until a request rewrites token 0 of page 0.
  • How often the alias ranges reach page 0: we ported Helios's snapshot-row capacity (capacities, runtime_package/memory.rs) and alias assignment (Layout::new, cache_memory.rs, offsets floored to the 2 MiB CUDA granularity confirmed on RTX PRO 6000) to Python, with glm53's constants checked against the recipe (RankCosts.state_row_bytes for TP1/2/4 with and without MTP, 34 linear-attention + 11 indexed layers, 256-token pages, latent planes 4×64×528 B, index planes 64×132 B). Page 0 of at least one latent plane falls inside the last snapshot row's alias in 30–31% of TP2 page counts and about 60% at TP4, with and without MTP, at 16 or 32 active requests, over the page counts a TP2 rank can hold (512–6,000 pages of 1.64 MiB). Index planes are never alias-eligible. Helios before Selene: store only what a request may resume, once, and use VRAM for snapshots #168 capped snapshot rows at active × 8, which narrows TP2 exposure to about 3–6%.
  • Effect: in those geometries every decode batch with a partly invalid 64-candidate chunk reads the snapshot bytes through this defect. Whether that gives NaN or finite but wrong output depends on which row section lands on record 0; not traced (FP32 recurrent state read as E4M3 can contain NaN encodings).
  • Clear released snapshot-alias pages before their first KV use #181 clears released alias pages, which covers the window after release but not while the snapshot owns the page. The kernel fix covers both.
  • Limits: a model of the planner, not a startup log; no current glm53 export exists to read snapshot_pages from. Not tested: SM103 variant, NVFP4 records, attention_sink.

Repro scripts

poison_sparse_mla.py
"""Poison test: does b12x sparse_mla (Flare glm53 MLA) read latent records outside the selection?

Usage: poison_sparse_mla.py [CASE...]   (default: every case in CASES)

Builds each plan as ignition/components/sparse_mla.py PreparedSparseMLA does
(sparse_mla.Caps from recipes/glm53/mla.py: GLM_NEXT, 528-byte uint8 records,
64-record pages, max_width 2051; plan -> PreparationSession -> state.bind/run,
then sparse_mla.bind/run) and fills every cache record that no row selects
(including physical record 0, which the gather loads for -1 entries) with zeros,
then poison. Record = 512 E4M3 latent bytes (K and V) + 4 FP32 group scales.

Selection layouts ("variant"), each row selecting `count` distinct live records:
  pad     entries >= count are -1, selected_lengths = count (glm53 expansion contract)
  holes   as pad, plus every 5th entry below count is -1
  stale   entries >= count hold unselected (poisoned) record ids, selected_lengths = count
  lenmax  entries >= count are -1, selected_lengths = max_width
Poisons: nan_all (latent 0x7F, scales NaN), nan_latent (latent 0x7F, scales 1.0),
nan_scale (latent 0, scales NaN), big (latent 448.0, scales 1.0).
"""

import sys

import torch

from b12x.attention import sparse_mla
from b12x.attention._shared.mla.reference import pack_mla_kv_cache_reference, sparse_mla_reference
from b12x.preparation import PreparationSession, PreparedCall

from poison_common import compare

DEVICE = torch.device("cuda", 0)
PAGE, RECORD, LATENT, WIDTH = 64, 528, 512, 2051     # glm53 mla.py Caps
NUM_PAGES = 128                                      # 8192 records
HISTORY = 2100                                       # live records a request may select
SCALE = 256 ** -.5                                   # GLM_NEXT softmax scale (b12x tests)
COUNTS = (1, 15, 16, 17, 63, 64, 65, 100, 127, 128, 129, 200, 255, 256, 257, 511, 1000, 2047, 2048, 2051)
VARIANTS = ("pad", "holes", "stale", "lenmax")
F32 = {"nan": (0x00, 0x00, 0xC0, 0x7F), "one": (0x00, 0x00, 0x80, 0x3F)}
POISONS = {"nan_all": (0x7F, "nan"), "nan_latent": (0x7F, "one"), "nan_scale": (0x00, "nan"),
           "big": (0x7E, "one")}

# name: (caps mode, heads, rows, return_lse)
CASES = {
    "decode_h16": ("decode", 16, 4, False),
    "decode_h32": ("decode", 32, 4, False),
    "decode_h64": ("decode", 64, 4, False),
    "decode_h64_lse": ("decode", 64, 4, True),
    "extend_h16_r8": ("extend", 16, 8, False),
    "extend_h16_r37": ("extend", 16, 37, False),
    "extend_h64_r37": ("extend", 64, 37, False),
}


def fill(cache, slots, poison):
    raw = cache.view(cache.shape[0], cache.shape[1], RECORD)
    raw[slots] = 0
    if poison == "zero":
        return
    latent, scale = POISONS[poison]
    rows = raw[slots]
    rows[:, :LATENT] = latent
    rows[:, LATENT:].view(rows.shape[0], -1, 4)[:] = torch.tensor(F32[scale], dtype=torch.uint8, device=raw.device)
    raw[slots] = rows


def selection(rows, count, variant, history, poisoned_ids, generator):
    selected = torch.full((rows, WIDTH), -1, dtype=torch.int32, device=DEVICE)
    counts = torch.empty(rows, dtype=torch.int32, device=DEVICE)
    for row in range(rows):
        n = max(1, count - (rows - 1 - row)) if rows > 4 else count
        pick = history[torch.randperm(history.numel(), generator=generator, device=DEVICE)[:n]]
        selected[row, :n] = pick
        if variant == "holes":
            selected[row, 4:n:5] = -1
        if variant == "stale" and n < WIDTH:
            fill_ids = poisoned_ids[torch.randint(poisoned_ids.numel(), (WIDTH - n,), generator=generator,
                                                  device=DEVICE)]
            selected[row, n:] = fill_ids
        counts[row] = WIDTH if variant == "lenmax" else n
    return selected, counts


def run_case(name):
    mode, heads, rows, return_lse = CASES[name]
    torch.manual_seed(1160)
    generator = torch.Generator(device=DEVICE).manual_seed(1160)
    records = NUM_PAGES * PAGE
    latent = (torch.randn(records, LATENT, device=DEVICE) / 4).bfloat16()
    cache = pack_mla_kv_cache_reference(latent).view(NUM_PAGES, PAGE, RECORD).contiguous()
    query = (torch.randn(rows, heads, LATENT, device=DEVICE) / 4).bfloat16()
    history = 1 + torch.randperm(records - 1, generator=generator, device=DEVICE)[:HISTORY].int()
    selected = torch.full((rows, WIDTH), -1, dtype=torch.int32, device=DEVICE)
    selected_lengths = torch.ones(rows, dtype=torch.int32, device=DEVICE)
    cache_lengths = torch.full((rows,), records, dtype=torch.int32, device=DEVICE)
    selected[:, 0] = history[0]
    caps = sparse_mla.Caps(device=DEVICE, num_q_heads=heads, max_q_rows=rows, max_width=WIDTH,
                           softmax_scale=SCALE, max_batch=rows, max_kv_rows=records, kv_dtype=torch.uint8,
                           head_dim=512, v_head_dim=512, page_size=PAGE,
                           model_type=sparse_mla.ModelType.GLM_NEXT, cache_record_bytes=RECORD, mode=mode,
                           **({"return_lse": True, "lse_scale": "natural"} if return_lse else {}))
    plan = sparse_mla.plan(caps)
    storage = None
    with PreparationSession(device=DEVICE, autotune=False, compile_workers=2) as session:
        def prepare(state):
            nonlocal storage
            storage = [torch.empty(s.shape, dtype=s.dtype, device=DEVICE) for s in state.scratch_specs()]
            runtime = state.bind(scratch=storage, q=query, kv_cache=cache, selected_indices=selected,
                                 cache_seqlens_int32=cache_lengths, nsa_cache_seqlens_int32=selected_lengths)
            return PreparedCall(run=lambda: state.run(runtime, kv_cache=cache, attention_sink=None),
                                owners=(storage, runtime))

        session.prepare((plan.request(name=f"poison-{name}", prepare_call=prepare),))
        binding = sparse_mla.bind(plan, scratch=storage, q=query, kv_cache=cache, selected_indices=selected,
                                  cache_lengths=cache_lengths, selected_lengths=selected_lengths,
                                  attention_sink=None)
        print("CASE", dict(case=name, mode=mode, heads=heads, rows=rows, return_lse=return_lse), flush=True)

        def run():
            result = sparse_mla.run(binding)
            result = result[0] if isinstance(result, tuple) else result
            torch.cuda.synchronize()
            return result.clone()

        original = cache.clone()
        for variant in VARIANTS:
            for count in COUNTS:
                cache.copy_(original)
                live = torch.zeros(records, dtype=torch.bool, device=DEVICE)
                live[history.long()] = True
                poisoned_ids = (~live).nonzero().flatten().int()
                s, c = selection(rows, count, variant, history, poisoned_ids, generator)
                selected.copy_(s)
                selected_lengths.copy_(c)
                used = torch.zeros(records, dtype=torch.bool, device=DEVICE)
                for row in range(rows):
                    n = int(c[row])
                    ids = selected[row, :n]
                    used[ids[ids >= 0].long()] = True
                slots = (~used).view(NUM_PAGES, PAGE)
                fill(cache, slots, "zero")
                expected = sparse_mla_reference(q_all=query, kv_cache=cache.view(records, 1, RECORD),
                                                page_table_1=selected, active_token_counts=selected_lengths,
                                                sm_scale=SCALE, v_head_dim=LATENT)
                record0 = torch.zeros_like(slots)
                record0.view(-1)[0] = True
                # Every unselected record, only physical record 0, or every unselected record but 0.
                for where, target in (("unselected", slots), ("record0", record0), ("not_record0", slots & ~record0)):
                    results = {}
                    for poison in ("zero", *POISONS):
                        fill(cache, slots, "zero")
                        fill(cache, target, poison)
                        results[poison] = run()
                    fill(cache, slots, "zero")
                    for poison in POISONS:
                        compare(results["zero"], results[poison], expected, kernel="sparse_mla", case=name,
                                variant=variant, count=count, mod16=count % 16, mod64=count % 64,
                                min_len=int(c.min()), where=where, poisoned=poison,
                                invalid_slots=int(target.sum()))
                # Positive control: NaN in the first selected record of row 0 must change row 0.
                base = results["zero"].float()
                first = int(selected[0, 0])
                control = torch.zeros_like(slots)
                control.view(-1)[first] = True
                saved = cache.view(-1, RECORD)[first].clone()
                fill(cache, control, "nan_all")
                changed = run().float()
                cache.view(-1, RECORD)[first] = saved
                print("CONTROL", dict(case=name, variant=variant, count=count,
                                      nan_rows=int(torch.isnan(changed).flatten(1).any(-1).sum()),
                                      max_diff=float(torch.nan_to_num(changed - base, nan=float("inf"))
                                                     .abs().max())), flush=True)


def main():
    for name in [a for a in sys.argv[1:] if a in CASES] or list(CASES):
        try:
            run_case(name)
        except Exception as error:  # record unsupported geometry instead of forcing it
            print("ERROR", dict(case=name, error=f"{type(error).__name__}: {error}"), flush=True)


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 kernel repro from this issue (poison_sparse_mla.py, unchanged) on local-inference-lab/flashinfer 1f8ed8a3 on RTX PRO 6000 (SM120), single process.

    Result: 6720/6720 rows clean — zero NaN outputs and zero diff against the zero-fill baseline across every case, selection variant (pad/holes/stale/lenmax), poison (nan_all/nan_latent/nan_scale/big), and geometry. The harness is measuring: baseline (zero_err) values are nonzero across rows, so a clean row means the poisoned records genuinely do not reach the output. Log: logs/poison204-newpin.log on the fix116 scratch host.

    So on 1f8ed8a3, -1 entries no longer record poison from physical record 0 — neither the E4M3 latent bytes nor the FP32 group scales.
    The exposure side is unchanged and confirmed on current package math: the Helios capacity/layout port (glm53_alias_page0.py, Flare nvidia/main 78b18b1c, glm53 continuation layout) puts a page-0 latent alias in ~31% of page counts at TP2 and ~60% at TP4 — matching the rates in this issue. The path exists in a deployed GLM-5.3-Flash package; the kernel just no longer converts it to poison.

    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