Skip to content

Released snapshot aliases hand KV pages back with stale row bytes; masked attention turns them into NaN (device error 6 under KV pressure) #116

Open

Description

@shadowpa0327

Summary

When the KV pool fills, requests that resume from the prefix cache start failing with prepared model reported device error 6. The cause is stale snapshot bytes in reused KV pages:

  1. Snapshot rows borrow KV page bytes (runtime_package/cache_memory.rs).
  2. When the last owner releases a snapshot, release_snapshot returns its pages to the free list. Nothing clears the row bytes still in them.
  3. A request then receives one of those pages as its partly filled tail page. Positions past the request's last token keep the old row bytes, and in the KV format some of them decode as NaN.
  4. Attention masks those positions, but a masked position still contributes 0 × NaN = NaN to P·V. The target logits come out non-finite.
  5. PreparedStochasticVerification marks the row invalid, and the commit reports INVALID_SPECULATION (6).

It only shows up once pages cycle between snapshot rows and KV use, which is why it needs a full pool. That makes it hit long multi-turn and agent workloads, the ones the prefix cache is for.

This may also explain #61. That issue fails the same way (verification rejects the row, then the commit reports INVALID_SPECULATION), and its failing target column sits in a newly granted page. We haven't tested Gemma 4.

Environment

  • DGX Spark (GB10, SM121), single GPU, CUDA 13.0
  • nvidia/Qwen3.8-27B-NVFP4, exported with the qwen38_dense recipe defaults: 32 requests, MTP up to 5 drafts, FP8 KV
  • Flare ca1f960e plus the scratch-copy fix from 317c1ec. The code involved is unchanged on main (6256cf08).
  • flare run PACKAGE --gpus 0 with default flags (adaptive MTP verification on)

Reproduction

The repro runs on a fresh server. It sends alternating distinct ~16k- and ~32k-token prompts. Each prompt is sent once with max_tokens=1 to cache it, then again with max_tokens=64. Requests run one at a time. We used the low-entropy prompts from SPEED-Bench's throughput split.

Server First failure
--memory-limit 50G (3,760 KV pages, 101 snapshot slots) prompt 15–17, every run, about 5 minutes in
Default memory prompt 67, nine prompts after the pool first filled

The failing request is always the second (cached) send. Under --memory-limit 50G, the 101 snapshot slots' alias ranges overlap and together cover every KV page.

Repro script
"""Feed a fresh Flare server distinct long prompts (prime with 1 token, then resend with 64) until the first failure.
Usage: repro.py OUT.csv DATA_DIR   (DATA_DIR holds SPEED-Bench throughput_16k.jsonl / throughput_32k.jsonl)"""
import csv, json, re, sys, time, urllib.error, urllib.request
out, data = sys.argv[1], sys.argv[2]
prompts = [[(ctx, r["messages"]) for r in map(json.loads, open(f"{data}/throughput_{ctx}.jsonl"))
            if r["category"] == "low_entropy"] for ctx in ("16k", "32k")]
order = [p for pair in zip(*prompts) for p in pair]
KEYS = ("flare_free_kv_tokens", "flare_cached_kv_tokens", "flare_free_snapshots", "flare_requests_failed_total")
def metrics():
    text = urllib.request.urlopen("http://127.0.0.1:8000/metrics", timeout=10).read().decode()
    return {k: float(m.group(1)) for k in KEYS for m in [re.search(rf"^{k} (\S+)$", text, re.M)] if m}
def ask(messages, max_tokens):
    body = {"model": "Qwen3.8-27B", "messages": messages, "max_tokens": max_tokens, "temperature": 1.0}
    req = urllib.request.Request("http://127.0.0.1:8000/v1/chat/completions", json.dumps(body).encode(),
                                 {"Content-Type": "application/json"})
    try:
        urllib.request.urlopen(req, timeout=900).read()
        return "ok"
    except urllib.error.HTTPError as e:
        return "fail: " + e.read().decode()[:120]
with open(out, "w", newline="") as f:
    w = csv.writer(f)
    w.writerow(["i", "context", "prime", "warm", "seconds", *KEYS])
    for i, (ctx, messages) in enumerate(order):
        t = time.time()
        prime, warm = ask(messages, 1), ask(messages, 64)
        m = metrics()
        w.writerow([i, ctx, prime, warm, round(time.time() - t, 1), *[m.get(k) for k in KEYS]]); f.flush()
        print(i, ctx, prime[:40], warm[:40], m, flush=True)
        if prime != "ok" or warm != "ok":
            break

Narrowing

We collected these with temporary logging in Helios and a re-exported package. None of the logging is part of this issue.

Which check fails. We made the commit report a bitmask of its shape checks in place of a bare 6. The failing round reports proposed >= 1 and accepted == proposed - 1 as failed. Verification set proposed_count = 0, so it rejected the row (speculation.py L329, L355). The first round after the restore already fails at width 1, with no drafts. That leaves the target distribution as the cause: it is non-finite, and the drafts play no part.

What we ruled out.

  • Page ownership. Before every submit we checked that each page id has exactly one owner: free list, checkpoint, retirement, request, retired request, inbound ticket or snapshot alias. There were no conflicts.
  • Reuse while in flight. We tracked, per page, the last fence that used it as KV and as snapshot backing. No page was used in one role while work in the other role was still in flight.
  • Alias range rounding. Widening every alias range by 8 pages on each side still fails.
  • Snapshot exhaustion. Free snapshots stayed above 60 throughout.
  • The row index. See the dedicated-pages rows in the table below.

What fixes it.

--memory-limit 50G, default MTP Result
As is fails at prompt 15–17
Snapshots 0–47 on dedicated pages, never handed to KV no failures through the 25-minute cap (89 prompts)
Snapshots 53–100 on dedicated pages no failures through the 25-minute cap (87 prompts)
Released alias pages zeroed before reuse no failures in 143 of 143 prompts. Default memory also passes 143 of 143, where it failed at prompt 67 before

With zeroing on, warm-request latency and benchmark throughput are unchanged. At 8k, N=1 to 32: 27.6 / 50.4 / 93.0 / 159 / 242 / 305 tok/s, against 28.2 / 49.0 / 92.8 / 154 / 244 / 308 tok/s without it.

Why only the tail page matters. _copy_pages (state_transfer.py L153) saves and restores the request's whole tail page, including positions past the endpoint. Startup zeroes every cache byte once (runtime_package/cache_memory.rs L478, "before any graph or transfer can read an alias"). After that, nothing clears a page when it goes from row storage back to the KV pool (scheduler/cache_memory.rs L153–165).

Potential fix

These are three options. The first is the one we tested.

  1. Zero pages leaving alias use. When release_snapshot drops a page's alias count to zero, queue the page. The executor then zeroes it on the model stream before the next graph launch, so the clear happens after the snapshot's last reader and before any KV writer. A single-GPU version of this is on a fork branch: shadowpa0327/flare-local-inference@b83d347a. It uses a global page list and host-to-device copies from pinned zeros, and doesn't cover the multi-process tensor-parallel executor. Treat it as a reference, not a proposed patch.
  2. Clear only the dead tail. When a page is granted to a request, or a tail page is restored, zero the positions past the endpoint. This moves less data than option 1, but every writer of a partial page has to honor it.
  3. Make masked positions inert in attention. Skip or zero masked K/V positions in the paged kernels, instead of relying on 0 × value staying finite. This also protects any other path that leaves undefined bytes in a page.

Separately, as #61 also notes, a row the verifier rejects reaches the commit as INVALID_SPECULATION. Reporting it as INVALID_DISTRIBUTION would have pointed at the cause much sooner. The state-transfer validator also uses 6, for an unmapped page, which sent us looking at page tables first.


Found and written up with Claude Code (Claude Opus 5.5) while benchmarking Flare on DGX Spark.

Activity

  1. fahrenhe1t commented on Nov 3, 2026

    @fahrenhe1t

    Second data point: Qwen3.8-27B NVFP4 + DFlash2 on SM120 (RTX PRO 6000 Blackwell), agentic traffic

    Same signature as this issue, on a different GPU class and with the DFlash2 speculative path. Filing as a data point per the issue's request for more reproductions.

    Environment

    • RTX PRO 6000 Blackwell Workstation Edition (SM120, 95.6 GiB), single GPU
    • Driver 615.71.10, CUDA 13.2 (torch 2.14.1+cu132), Ubuntu 24.04.5, kernel 6.8.0-147-generic
    • Flare cc696a6b (2026-11-02, current main), release build
    • flashinfer pin: local-inference-lab/flashinfer@f5f5341 (as locked in the repo at that commit)
    • Package: local export of the Qwen3.8-27B NVFP4 checkpoint via qwen38_dense, DFlash2 draft (incoai/Qwen3.8-27B-DFlash2), 7 draft tokens, adaptive packed verification, FP8 KV (reports under the mtp proposal-source label in metrics)
    • Serve: flare run PACKAGE --gpus 0 --host 0.0.0.0 --port 8080 --memory-limit 0.56 --max-concurrency 3 (systemd unit)

    Workload

    An OpenClaw agentic session against /v1/chat/completions (streaming, tool calls, multi-turn). Long growing contexts with heavy prefix-cache reuse — the same "long multi-turn / agent" profile the issue identifies. No benchmark harness; organic traffic.

    Observed

    • 32 requests failed mid-stream with prepared model reported device error 6 over ~15 minutes of agentic use (07:19–07:33 UTC on 2026-11-03), in bursts of several consecutive failures separated by quiet periods — consistent with pool-fill / page-cycling conditions rather than a per-request deterministic trigger.
    • Failing request sequence numbers from the server log: 26, 27, 29, 30, 32–35, 37–47, 49, 51–62 (gaps are successful requests in the same window).
    • Server stays up after every failure; subsequent requests succeed. flare_requests_failed_total = 32, matching the log exactly.
    • At the time of capture: flare_cached_kv_tokens ≈ 208,768 (prefix cache heavily populated), flare_free_kv_tokens ≈ 8,320, flare_free_snapshots = 43 — i.e. the KV pool was under real pressure with snapshot aliasing active, matching the issue's trigger conditions.

    Notes

    • Round shapes (from /metrics, cumulative since process start — the failure window is contained in these): batch=1,width=8: 5,382 rounds; batch=2,width=8: 54; batch=1,width=1: 88; batch=2,width=1: 1. No batch-4 rounds at all — the agentic traffic is effectively sequential (one request in flight), so the failures occurred almost entirely in single-request width-8 packed rounds with up to 7 drafts. That matches the issue's finding that the first round after a restore fails even at width 1 with no drafts: the trigger is the target distribution, not draft content.
    • Draft acceptance was healthy overall (19,740 / 33,193 offered drafts accepted ≈ 59.5%; depth-1 ≈ 86.5%), so the DFlash2 draft model itself is not the problem — again consistent with a non-finite target logit rather than a proposal defect.
    • Note on terminology: this deployment uses the DFlash2 draft, which reports under the mtp proposal-source label in metrics (flare_speculative_drafts_total{source="mtp"}).
    • I have not yet instrumented the commit bitmask or done the dedicated-pages / zero-on-release A/B that the issue describes.
    • Also relevant to this setup: the flashinfer pin at cc696a6b predates Paged attention decode propagates NaNs from unused V-cache tails into live outputs (intermittent invalid-distribution errors on main) #14's paged-attention tail fix (local-inference-lab/flashinfer#43), so a re-export will be needed regardless once that lands.
  2. mark-yong commented on Nov 4, 2026

    @mark-yong
    Contributor

    Which attention kernels read past the valid length (poison test)

    Instead of zeroing released pages (#181), we looked for every attention kernel that lets cache bytes it should not read reach the output. For each component, every slot a request must not read (past its length, outside its window, unselected, unreferenced pages) was filled with zeros, then NaN bytes, and the outputs were compared with each other and with a reference. K and V were poisoned separately.

    Setup: RTX PRO 6000 (SM120), FlashInfer 3c2729e7, Flare b4196955. Components were built as the recipes build them, through PreparedPagedAttention and the other component constructors, with representative geometries.

    Result

    Score masking is correct everywhere: poisoning K alone never changed an output. Four kernels let masked V (or MLA latent) rows into P·V, where 0 × NaN = NaN:

    Kernel Rows that leak Flare paths Issue
    b12x paged_decode V past the length in the last partial 16-key subtile (len % 16 != 0); with a sliding window, also V before the window start qwen38_dense decode/verify, dflash2 drafts, gemma4 sliding layers; mimo_v2/muse_spark window decode over the ring for requests shorter than the window (confirmed at MiMo-V2.6-Flash geometry, TP 1/2/4; Muse swept over head counts) #201
    SM120 FP8 TMA paged prefill (Flare paged_tma) V past the length in the last 128-key tile (len % 128 != 0) qwen38_dense prefill/extend #202
    b12x paged selected-block prefill (msa_union_tile) V past the length in the last selected 128-token block minimax_m3 prefill #203
    b12x sparse_mla physical record 0, gathered for every -1 index glm53 (SM120/SM121 decode), when page 0 is inside a snapshot-alias range and holds snapshot bytes; page 0 is otherwise zeroed and finite #204

    The first two are the qwen38_dense paths in this issue's reproduction, which matches the mechanism described above.

    Safe as tested (no NaN and an exact match between the zero and poison runs):

    • b12x paged: plain decode, verify and extend, sliding window, sinks, selected-block decode and verify.
    • window_attention (selected-position kernel), MSA indexer and packed prepare.
    • dense_mla (kimi3) and compressed_mla (deepseek4/41).

    compressed_sparse_mla already zeroes masked V explicitly ("Mask V itself: MMA still propagates NaNs when P is zero"), which is the pattern the kernel fixes need.

    Next steps

    Not covered

    • SM121 (this issue's original GB10 setup) and SM103 paths. The paged_tma kernel is built for SM120 and SM121, and paged_decode runs on both, but neither was run on SM121.
    • CUDA graph replay; all runs were eager.
    • sm103_sparse_attention (QSA).

    Poison scripts are available for each component.

  3. jwnand commented on Nov 5, 2026

    @jwnand

    Data point: DeepSeek-V4.1-Flash on GB10/SM121, TP4 across four Sparks, two engine builds

    Same surface symptom as this issue, on a model and topology the poison table above does not cover.
    Environment

    • 4x DGX Spark, GB10 (SM121), driver 580.173.02, CUDA 13.0, kernel 6.17.0-1031-nvidia, one rank per host over a closed 4-node RoCE ring (--roce-ring)
    • Flare 585159c9 (flashinfer 42ba2f16) and Flare 0009b89d (flashinfer 1f8ed8a3), source builds
    • Package A: official local-inference-lab/DeepSeek-V4.1-Flash-1017-FLARE@gb10 revision ef5c848b (deployment db20209d), TP4, prefill 8192, C=32
    • Package B: local re-export of a DeepSeek-V4.1-Flash-1017 derivative (gb10-tp4-202611050533, deployment e8e692d6), same flags
    • Serve flags: --max-concurrency 32 --mtp-draft-tokens 5 --mtp-adaptive-verification --embedding-table-storage disk --host 0.0.0.0 --port 8015
      Workload
      One-hour steady soak, OpenAI-compatible /v1/chat/completions, streaming, one short prompt repeated (57 prompt tokens, 256 max output tokens), so the prefix cache is heavily reused and pages cycle between snapshot aliases and KV use. Concurrency mixed under the C=32 ceiling.
      Observed
      HTTP 200, stream starts, then ends with a server_error chunk instead of the final usage/finish chunk:
    [Thu, 05 Nov 2026 02:12:41 GMT] request_id=chatcmpl-f578caf475382aac-1123 stage=stream code=server_error message="prepared model reported device error 6"
    [Thu, 05 Nov 2026 09:40:03 GMT] request_id=chatcmpl-276a4bb157e0d444-1155 stage=stream code=server_error message="prepared model reported device error 6"
    
    • The server stays up; the next request succeeds.
    • First line: engine 585159c9, package A, 1 failure in 694 samples over 1,322 s (soak aborted at the first error).
    • Second line: engine 0009b89d, package B, 1 failure in 951 samples over 2,040 s.
    • The same two configurations pass a full 3,600 s soak on retry (1,827 and 1,696 samples, 0 errors), so it is intermittent.
    • It has never appeared at C1–C8 or in 16-minute benchmarks on either package; only under sustained load with cached prefixes.
    • It survives package re-export and the engine upgrade, so it is not an export artifact.
      Why I am adding it here
      The poison table above lists compressed_mla (deepseek4/41) as safe, and the "not covered" section lists SM121 and TP4-on-Spark. So either DeepSeek V4.1 reaches the same stale-page condition through a kernel/path not in the table, or there is a separate leaking path on SM121. Two questions:
    1. Does the zero-on-release fix in Clear released snapshot-alias pages before their first KV use #181 cover this case, or is a DeepSeek/SM121-specific kernel in scope for b12x paged_decode: V rows past cache_seqlens (and before the window start) reach P·V #201–b12x sparse_mla: -1 selection entries gather physical record 0 into P·V #204?
    2. Is there a diagnostic build (the bitmask that replaces code 6 with the failing check) I can run on this TP4 SM121 setup to report which check fails?
      I can provide the full request bodies, raw client logs and /metrics scrapes around each failure.
  4. added
    triage:partial
    bug
    priority:P1
    on Nov 5, 2026
  5. original-el8 commented on Nov 5, 2026

    @original-el8
    Collaborator

    The original dense-Qwen cache-pressure failure now has integrated fix evidence. Flare 5a1640c8 pins FlashInfer 1f8ed8a3. That dependency commit reports an exported Qwen3.8-27B package passing 143 paired 16k/32k prompts (286 requests), with a 50 GiB budget, 409 evictions, 285 restores and no failures; the unpatched package failed at pair 22.

    This ticket is partially addressed. The later DeepSeek/SM121 TP4 failure needs its own reproduction and failing-check diagnosis before it can be attributed to the same mechanism. Record the preparation revision, package/deployment identity, runtime revision and effective sampling controls. Packages retain their prepared kernels and sampling ranges until re-export.

    Draft PR #181 has not established that its page-clearing change is required after the kernel fixes. Validate any remaining failure against the pinned kernels before choosing that mitigation. The measurements above are from the commit report; no additional soak was run for this triage.

  6. added
    area:caching
    area:kernels
    on Nov 5, 2026
  7. added a commit that references this issue on Nov 5, 2026
  8. jwnand commented on Nov 6, 2026

    @jwnand

    The DeepSeek/SM121 case below was measured on the pinned kernels: runtime 0009b89d
    (contains 5a1640c8), FlashInfer 1f8ed8a3. So the Qwen fix is in that build and this failure
    remains after it. Records you asked for:

    Preparation and package identity

    official package WARMIND package
    source local-inference-lab/DeepSeek-V4.1-Flash-1017-FLARE@gb10, revision ef5c848b3894f38d13c5a4b3fe6719c696435c96 local re-export from deepseek-ai/DeepSeek-V4.1-Flash-1017 @ 1bae0e108899 plus the jcartu/WARMIND-1017 derivative (revision 4fbce630)
    deployment db20209d361f473b8452f24ad517fa0d e8e692d63b4846dfbafb12477b861db3
    prepared with vendor build (their ignition revision is not recorded in the package metadata) ignition from 0009b89d + FlashInfer 1f8ed8a3, exported 2026-11-05T05:33Z
    contract TP4, prefill 8,192, C=32, MTP 5 adaptive, disk Engram, native-size KV paging identical flags; native expert scales

    Runtime for both: 0009b89de948e6b06c47252c777890c0a071c45c, FlashInfer
    1f8ed8a3c46e27d03cff54e08f23e9bc50476d57. Four DGX Spark GB10 (SM121), driver 580.173.02,
    one rank per host over a closed RoCE ring.

    Effective sampling

    Package metadata from /v1/models: temperature default 1.0 with no request range (fixed at
    1.0), top_p 1.0 with range [0.95, 1.0], top_k -1 fixed, min_p 0 fixed,
    repetition_penalty 1.0 with range [1.0, 1.1], seed request-controlled. So this is not greedy:
    the soak sent temperature: 1.0, seed: 0, max_tokens: 256, reasoning_effort: high.

    The failure

    [2026-11-05T09:40:03Z] request_id=chatcmpl-276a4bb157e0d444-1155
    stage=stream code=server_error message="prepared model reported device error 6"
    

    HTTP 200, content 89 chars and reasoning 146 chars already streamed, then the stream ended with no
    usage/final chunk. Sample 950 of 951 in a 2,040 s soak at mixed concurrency under C=32, on the
    short (58-token) heavily prefix-cached soak prompt. The same package/runtime completed a full
    3,600 s soak (1,696 samples) on retry, and an earlier soak on the previous runtime (585159c9,
    FlashInfer 42ba2f16) failed the same way once in 694 samples. It has never appeared at C1–C8 or
    in 16-minute benchmarks.

    Diagnosis

    I do not have your bitmask build. If you point me at the branch/commit that replaces code 6 with
    the failing check (ignition/components/speculation.py), I can build it on this SM121 TP4 setup,
    reproduce under the same soak, and report which shape/probability check fails — with and without
    #181 if you want the comparison. The full request bodies, raw client logs and /metrics around the
    failure are available.

  9. added
    model:deepseek-v4.1
    model:qwen3.8-27b
    on Nov 8, 2026
  10. yatesdr commented on Nov 19, 2026

    @yatesdr
    Collaborator

    @mark-yong, could you share the scripts you used for compressed_mla, and for the MXFP4 indexer if you covered it? The DeepSeek V4.1 failure @jwnand reports runs on SM121 under CUDA graph replay, which your run above did not cover. We have GB10 (SM121) hardware this week and will run them on current main, eager and under graph replay, and post the results here.

    @jwnand, on a build that reports the failing check: main has none. Verification marks a row invalid when it is not live, a draft or target distribution is flagged invalid, a draft token is outside the vocabulary, its token limit is out of range, or its probabilities are non-finite, negative or off by more than 1e-4 in total mass (ignition/components/speculation.py:412-428). The commit then reports code 6 for every invalid row (:674-703), and no metric or log records which condition fired.

  11. mark-yong commented on Nov 19, 2026

    @mark-yong
    Contributor

    Both below. poison_compressed_mla.py imports poison_common.py.

    They ran eager on SM120 with FlashInfer 3c2729e7 and Flare b4196955; neither has been run on SM121 or under graph replay.

    In the MXFP4 indexer, selection sets differ between identical runs at the top-512 cutoff, so compare scores rather than sets on a rerun.

    poison_compressed_mla.py
    """Poison test: does b12x compressed_sparse_mla read cache slots no valid index references?
    
    Usage: poison_compressed_mla.py [GROUP...]
    GROUP is v4-decode, v4-verify, v4-extend, v41-decode, v41-verify, v41-extend or tp2
    (default: all). Plans are built as Flare's PreparedCompressedMLA builds them
    (ignition/components/compressed_mla.py at b4196955), with DeepSeek V4 (deepseek4)
    and V4.1 (deepseek41) geometry. SWA indices follow PreparedWindowIndices; indexed
    indices follow the recipes' compressed lengths (C4 top-512, C128 dense pages,
    V4.1 ratio 1/2 logical top-512 through the token page table).
    
    For every case, every cache slot that no row's valid prefix references (including
    physical slot 0, the slot the kernel's IO clamps invalid entries to) and the page
    padding bytes are filled with zeros, then with NaN patterns per field: E4M3 payload
    0x7F, BF16 rope 0x7FC0, UE8M0 scales 0xFF, V4.1 E4M3 indexed scales 0x7F (FP4 payload
    0x77), and with the largest finite encodings ("big"). SWA and indexed caches are
    poisoned together, then separately. Positive controls additionally poison one slot
    row 0 validly reads, so NaN must appear. Index entries past each row's length are
    -1 (what Flare writes) or stale slots ("stale").
    """
    
    import sys
    import traceback
    from dataclasses import asdict, dataclass, field, replace
    
    import torch
    
    from b12x.attention import compressed_sparse_mla as mla
    from b12x.attention.compressed_sparse_mla._tuning import _default_config
    from b12x.attention._shared.mla.compressed_reference import (
        compressed_sparse_mla_page_nbytes,
        compressed_sparse_mla_reference,
        pack_compressed_sparse_mla_kv_cache_reference,
        pack_deepseek_v41_cache_reference,
    )
    from b12x.preparation import PreparationSession, PreparedCall
    
    from poison_common import compare
    
    DEVICE = torch.device("cuda", 0)
    SCALE = 512 ** -0.5
    INDEX_TOPK = 512
    MAX_POSITION = 4200
    DECODE_POSITIONS = (0, 6, 16, 62, 63, 64, 99, 127, 200, 255, 777, 1000, 1300, 2047, 2100, 4095)
    VERIFY_STARTS = (0, 3, 60, 125, 127, 200, 1000, 2100, 4000)
    EXTEND_STARTS = (0, 5, 100, 127, 130, 1000, 2100, 4000)
    
    
    class CacheLayout:
        """Byte geometry of one compressed cache: per-slot field offsets and NaN pattern."""
    
        def __init__(self, fmt, kind, page_size, pages):
            self.fmt, self.kind, self.page_size, self.pages = fmt, kind, page_size, pages
            t = torch.arange(page_size)[:, None]
            if fmt == "v4":
                self.page_nbytes = compressed_sparse_mla_page_nbytes(page_size)
                data = t * 576 + torch.arange(576)
                scales = page_size * 576 + t * 8 + torch.arange(8)
                self.slot_offsets = torch.cat((data, scales), 1)
                nan = [0x7F] * 448 + [0xC0, 0x7F] * 64 + [0xFF] * 8
                big = [0x7E] * 448 + [0x7F, 0x7F] * 64 + [0xFE] * 8
                self.pad_offsets = torch.arange(page_size * 584, self.page_nbytes)
            else:
                record = 528 if kind == "swa" else 288
                self.page_nbytes = page_size * record
                self.slot_offsets = t * record + torch.arange(record)
                nan = [0x7F] * 512 + [0xFF] * 16 if kind == "swa" else [0x77] * 256 + [0x7F] * 32
                big = [0x7E] * 512 + [0xFE] * 16 if kind == "swa" else [0x77] * 256 + [0x7E] * 32
                self.pad_offsets = torch.arange(0)
            # "big" is the largest finite encoding of each field (E4M3 448, BF16 3.39e38,
            # UE8M0 2^127, FP4 6): it exposes unmasked scores and overflow in P.V.
            self.patterns = {name: torch.tensor(p, dtype=torch.uint8, device=DEVICE)
                             for name, p in (("nan", nan), ("big", big))}
            self.slot_offsets = self.slot_offsets.to(DEVICE)
            self.pad_offsets = self.pad_offsets.to(DEVICE)
    
        def pack(self, generator):
            tokens = self.pages * self.page_size
            values = torch.randn((tokens, 512), device=DEVICE, generator=generator) * 0.3
            if self.fmt == "v4":
                values = values.bfloat16()
                return pack_compressed_sparse_mla_kv_cache_reference(
                    values[:, :448], values[:, 448:], page_size=self.page_size, num_pages=self.pages)
            return pack_deepseek_v41_cache_reference(
                values.bfloat16(), page_size=self.page_size, cache_kind=self.kind)
    
        def fill(self, cache, valid_slots, mode, extra=()):
            """Overwrite every slot outside valid_slots (plus `extra` slots), and page padding."""
            valid = torch.zeros(self.pages * self.page_size, dtype=torch.bool, device=DEVICE)
            if valid_slots:
                valid[torch.tensor(sorted(valid_slots), device=DEVICE)] = True
            if extra:
                valid[torch.tensor(list(extra), device=DEVICE)] = False
            invalid = (~valid).nonzero().flatten()
            flat = cache.view(-1)
            offsets = (invalid // self.page_size)[:, None] * self.page_nbytes + self.slot_offsets[invalid % self.page_size]
            if mode == "zero":
                flat[offsets.flatten()] = 0
            else:
                flat[offsets.flatten()] = self.patterns[mode].repeat(invalid.numel())
            if self.pad_offsets.numel():
                pad = (torch.arange(self.pages, device=DEVICE)[:, None] * self.page_nbytes + self.pad_offsets).flatten()
                flat[pad] = 0 if mode == "zero" else 0x7F
            return invalid.numel()
    
    
    @dataclass(frozen=True)
    class Spec:
        name: str
        group: str
        fmt: str          # v4 (deepseek4, cache_format deepseek_v4) or v41 (deepseek41)
        mode: str         # decode, verify or extend (recipe mode)
        ratio: int        # 0 (SWA only); v4: 4 or 128; v41: 1 or 2
        heads: int = 64
        batch: int = 4
        tokens: int = 1   # max query tokens per request
        rows: int = 5     # query row capacity
        override: dict = field(default_factory=dict)
    
        @property
        def window_page(self):
            return 128 if self.mode == "decode" else 128 + self.tokens
    
        @property
        def kernel_mode(self):
            return "extend" if self.mode == "extend" else "decode"
    
        @property
        def page_tokens(self):
            return 256 if self.fmt == "v4" else 128
    
        @property
        def indexed_page(self):
            return self.page_tokens // self.ratio if self.ratio else 0
    
        @property
        def table_width(self):
            return (MAX_POSITION + self.page_tokens - 1) // self.page_tokens
    
        @property
        def indexed_width(self):
            if not self.ratio:
                return 0
            if self.fmt == "v4" and self.ratio == 128:
                return self.table_width * (self.page_tokens // 128)
            return INDEX_TOPK
    
        @property
        def mapped(self):
            return self.fmt == "v41" and bool(self.ratio)
    
    
    def specs():
        out = []
        for fmt, ratios in (("v4", (0, 4, 128)), ("v41", (0, 2, 1))):
            group = f"{fmt}-decode"
            for ratio in ratios:
                out.append(Spec(f"{fmt}.decode.r{ratio}", group, fmt, "decode", ratio))
            if fmt == "v4":
                out.append(Spec("v4.decode.r4.chunk1", group, fmt, "decode", 4,
                                override=dict(max_chunks_per_row=1, split_chunk_size=1024)))
            else:
                out += [
                    Spec("v41.decode.r2.fp8h8", group, fmt, "decode", 2, override=dict(v41_heads_per_block=8)),
                    Spec("v41.decode.r2.bf16", group, fmt, "decode", 2, override=dict(v41_compute_mode="bf16")),
                    Spec("v41.decode.r1.bf16", group, fmt, "decode", 1, override=dict(v41_compute_mode="bf16")),
                    Spec("v41.decode.r2.chunk1", group, fmt, "decode", 2,
                         override=dict(max_chunks_per_row=1, split_chunk_size=1024)),
                ]
            ratio = 4 if fmt == "v4" else 2
            out.append(Spec(f"{fmt}.verify.r{ratio}", f"{fmt}-verify", fmt, "verify", ratio, batch=2, tokens=4, rows=8))
            if fmt == "v41":
                out.append(Spec("v41.verify.r2.bf16", "v41-verify", fmt, "verify", 2, batch=2, tokens=4, rows=8,
                                override=dict(v41_compute_mode="bf16")))
            for ratio in ratios:
                out.append(Spec(f"{fmt}.extend.r{ratio}", f"{fmt}-extend", fmt, "extend", ratio,
                                batch=2, tokens=40, rows=80))
            if fmt == "v41":
                out.append(Spec("v41.extend.r2.bf16", "v41-extend", fmt, "extend", 2, batch=2, tokens=40, rows=80,
                                override=dict(v41_compute_mode="bf16")))
        out += [
            Spec("v4.decode.r4.h32", "tp2", "v4", "decode", 4, heads=32),
            Spec("v41.decode.r2.h32", "tp2", "v41", "decode", 2, heads=32),
            Spec("v41.decode.r2.h32.fp8h8", "tp2", "v41", "decode", 2, heads=32, override=dict(v41_heads_per_block=8)),
            Spec("v41.extend.r2.h32", "tp2", "v41", "extend", 2, heads=32, batch=2, tokens=40, rows=80),
            Spec("v41.decode.r2.h16", "tp4", "v41", "decode", 2, heads=16),
            Spec("v41.decode.r2.h16.fp8h8", "tp4", "v41", "decode", 2, heads=16, override=dict(v41_heads_per_block=8)),
            Spec("v41.extend.r2.h16", "tp4", "v41", "extend", 2, heads=16, batch=2, tokens=40, rows=80),
        ]
        return out
    
    
    def scenarios(spec):
        if spec.mode == "decode":
            return [[(p, 1)] * spec.batch for p in DECODE_POSITIONS]
        starts = VERIFY_STARTS if spec.mode == "verify" else EXTEND_STARTS
        counts = (spec.tokens, 2) if spec.mode == "verify" else (spec.tokens, 13, 1)
        return [[(s, n)] * spec.batch for s in starts for n in counts]
    
    
    class Harness:
        def __init__(self, spec):
            self.spec = s = spec
            generator = torch.Generator(device=DEVICE).manual_seed(1160)
            self.swa_layout = CacheLayout(s.fmt, "swa", s.window_page,
                                          s.batch + 3 if s.mode == "decode" else s.batch)
            self.swa_pristine = self.swa_layout.pack(generator)
            self.swa = self.swa_pristine.clone()
            self.indexed_layout = self.indexed = self.indexed_pristine = None
            self.tables = None
            if s.ratio:
                pages = 1 + s.batch * s.table_width + 4
                self.indexed_layout = CacheLayout(s.fmt, "indexed", s.indexed_page, pages)
                self.indexed_pristine = self.indexed_layout.pack(generator)
                self.indexed = self.indexed_pristine.clone()
                order = torch.randperm(pages - 1, generator=torch.Generator().manual_seed(116))[: s.batch * s.table_width] + 1
                self.tables = order.view(s.batch, s.table_width).tolist()
            self.q = (torch.randn((s.rows, s.heads, 512), device=DEVICE, generator=generator) * 0.2).bfloat16()
            self.out = torch.zeros_like(self.q)
            self.sink = torch.randn(s.heads, device=DEVICE, generator=generator) * 0.5
            self.swa_indices = torch.full((s.rows, 128), -1, dtype=torch.int32, device=DEVICE)
            self.swa_lengths = torch.zeros(s.rows, dtype=torch.int32, device=DEVICE)
            self.indexed_indices = self.indexed_lengths = self.page_table = None
            if s.ratio:
                self.indexed_indices = torch.full((s.rows, s.indexed_width), -1, dtype=torch.int32, device=DEVICE)
                self.indexed_lengths = torch.zeros(s.rows, dtype=torch.int32, device=DEVICE)
            if s.mapped:
                self.page_table = torch.full((s.rows, s.table_width), -1, dtype=torch.int32, device=DEVICE)
            self.inputs = dict(q=self.q, swa_indices=self.swa_indices, swa_lengths=self.swa_lengths,
                               indexed_indices=self.indexed_indices, indexed_lengths=self.indexed_lengths,
                               indexed_page_table=self.page_table)
    
        def plan(self):
            s = self.spec
            caps = mla.Caps(device=DEVICE, num_q_heads=s.heads, max_q_rows=s.rows,
                            max_width=128 + s.indexed_width, swa_width=128, indexed_width=s.indexed_width,
                            max_page_table_width=s.table_width if s.mapped else 1,
                            swa_page_size=s.window_page, indexed_page_size=s.indexed_page or 64,
                            cache_format="deepseek_v4" if s.fmt == "v4" else "deepseek_v41",
                            mode=s.kernel_mode,
                            decode_row_capacity=s.rows if s.fmt == "v41" and s.kernel_mode == "decode" else None,
                            compute_mode="auto")
            invocation = mla.invocation_from_tensors(q=self.q, swa_k_cache=self.swa, indexed_k_cache=self.indexed,
                                                     attn_sink=self.sink, out=self.out)
            plan = mla.plan(caps, invocation=invocation)
            if s.override:
                plan = mla.plan(caps, invocation=invocation, override=replace(_default_config(plan.query, None), **s.override))
            return plan
    
        def run(self, binding):
            mla.run(binding=binding, swa_k_cache=self.swa, indexed_k_cache=self.indexed,
                    attn_sink=self.sink, sm_scale=SCALE, out=self.out)
    
        def build(self, requests, pad):
            """Fill index tensors for packed rows; return valid slot sets and reference indices."""
            s = self.spec
            rows = []
            for r, (start, count) in enumerate(requests):
                rows += [(r, start, start + k) for k in range(count)]
            if len(rows) > s.rows:
                raise ValueError("scenario exceeds row capacity")
            gen = torch.Generator().manual_seed(len(rows) * 7919 + rows[0][2])
            swa_idx = [[-1] * 128 for _ in range(s.rows)]
            swa_len = [0] * s.rows
            width = s.indexed_width
            idx = [[-1] * width for _ in range(s.rows)]
            phys = [[-1] * width for _ in range(s.rows)]
            idx_len = [0] * s.rows
            table = [[-1] * s.table_width for _ in range(s.rows)]
            swa_valid, indexed_valid = set(), set()
            W = s.window_page
            for row, (r, start, q) in enumerate(rows):
                left = max(q - 127, 0)
                length = q - left + 1
                swa_len[row] = length
                for j in range(128):
                    pos = left + j
                    if s.mode == "decode":
                        slot = (r + 1) * 128 + pos % 128
                    elif j < length:
                        slot = r * W + (pos % 128 if pos < start else 128 + pos - start)
                    else:
                        slot = r * W + (length + j) % W
                    if j < length:
                        swa_valid.add(slot)
                        swa_idx[row][j] = slot
                    elif pad == "stale":
                        swa_idx[row][j] = slot
                if not s.ratio:
                    continue
                ps = s.indexed_page
                pages = self.tables[r]
                table[row] = list(pages)
                compressed = (q + 1) // s.ratio
                capacity = s.table_width * ps
                if s.fmt == "v4" and s.ratio == 128:
                    logical = list(range(capacity))
                    count = compressed
                else:
                    count = min(compressed, INDEX_TOPK)
                    chosen = torch.randperm(compressed, generator=gen)[:count].tolist() if compressed else []
                    future = (torch.randperm(capacity - compressed, generator=gen)[: width - count] + compressed).tolist()
                    logical = chosen + future
                    logical += [-1] * (width - len(logical))
                idx_len[row] = count
                for j in range(width):
                    c = logical[j]
                    if c < 0:
                        continue
                    p = pages[c // ps] * ps + c % ps
                    if j < count:
                        indexed_valid.add(p)
                        phys[row][j] = p
                    if j < count or pad == "stale":
                        idx[row][j] = c if s.mapped else p
            self.swa_indices.copy_(torch.tensor(swa_idx, dtype=torch.int32))
            self.swa_lengths.copy_(torch.tensor(swa_len, dtype=torch.int32))
            if s.ratio:
                self.indexed_indices.copy_(torch.tensor(idx, dtype=torch.int32))
                self.indexed_lengths.copy_(torch.tensor(idx_len, dtype=torch.int32))
            if s.mapped:
                self.page_table.copy_(torch.tensor(table, dtype=torch.int32))
            live_swa = swa_len[: len(rows)]
            live_idx = idx_len[: len(rows)]
            summary = dict(live_rows=len(rows), swa_len=(min(live_swa), max(live_swa)),
                           idx_len=(min(live_idx), max(live_idx)) if s.ratio else None,
                           swa_mod16=sorted({x % 16 for x in live_swa}),
                           idx_mod64=sorted({x % 64 for x in live_idx}) if s.ratio else None,
                           swa_slot0_poisoned=0 not in swa_valid,
                           idx_slot0_poisoned=(0 not in indexed_valid) if s.ratio else None)
            phys_tensor = torch.tensor(phys, dtype=torch.int32, device=DEVICE) if s.ratio else None
            controls = dict(swa=swa_idx[0][0] if swa_len[0] else None,
                            indexed=phys[0][0] if s.ratio and idx_len[0] else None)
            return swa_valid, indexed_valid, phys_tensor, summary, controls
    
        def poison(self, swa_valid, indexed_valid, swa_mode, indexed_mode, swa_extra=(), indexed_extra=()):
            self.swa.copy_(self.swa_pristine)
            counts = [self.swa_layout.fill(self.swa, swa_valid, swa_mode, swa_extra)]
            if self.indexed is not None:
                self.indexed.copy_(self.indexed_pristine)
                counts.append(self.indexed_layout.fill(self.indexed, indexed_valid, indexed_mode, indexed_extra))
            return counts
    
        def reference(self, phys):
            s = self.spec
            extra = {}
            if s.ratio:
                extra = dict(extra_k_cache=self.indexed, extra_indices=phys, extra_topk_lengths=self.indexed_lengths,
                             extra_page_size=s.indexed_page)
            return compressed_sparse_mla_reference(
                self.q, self.swa, self.swa_indices, self.swa_lengths, sm_scale=SCALE, attn_sink=self.sink,
                swa_page_size=s.window_page, cache_format="deepseek_v4" if s.fmt == "v4" else "deepseek_v41", **extra)
    
    
    def run_spec(spec):
        torch.manual_seed(1160)
        h = Harness(spec)
        plan = h.plan()
        scratch = None
        with PreparationSession(device=DEVICE, autotune=False, compile_workers=2) as session:
            def prepare(state):
                nonlocal scratch
                scratch = [torch.empty(x.shape, dtype=x.dtype, device=DEVICE) for x in state.scratch_specs()]
                binding = state.bind_for_preparation(scratch=scratch[0], **h.inputs)
                return PreparedCall(run=lambda: state.run(binding, swa_k_cache=h.swa, indexed_k_cache=h.indexed,
                                                          attn_sink=h.sink, sm_scale=SCALE, out=h.out),
                                    owners=(scratch, binding))
    
            session.prepare((plan.request(name=f"poison-{spec.name}", prepare_call=prepare),))
            config = asdict(plan.selection.config)
            print("PLAN", dict(spec=spec.name, fmt=spec.fmt, mode=spec.mode, kernel_mode=spec.kernel_mode,
                               ratio=spec.ratio, heads=spec.heads, rows=spec.rows, swa_page=spec.window_page,
                               indexed_page=spec.indexed_page, indexed_width=spec.indexed_width,
                               mapped=spec.mapped, config=config, source=str(plan.selection.source)), flush=True)
            binding = mla.bind(plan, scratch=scratch[0], **h.inputs)
            for requests in scenarios(spec):
                for pad in ("neg", "stale"):
                    swa_valid, indexed_valid, phys, summary, controls = h.build(requests, pad)
                    h.poison(swa_valid, indexed_valid, "zero", "zero")
                    expected = h.reference(phys)
                    fields = dict(spec=spec.name, start=requests[0][0], count=requests[0][1], pad=pad, **summary)
                    runs = [(which, which in ("both", "swa"), which in ("both", "indexed"), (), ())
                            for which in (("both", "swa", "indexed") if spec.ratio else ("swa",))]
                    # Positive controls: also NaN-poison one slot that row 0 validly reads.
                    if controls["swa"] is not None:
                        runs.append(("control-swa", True, False, (controls["swa"],), ()))
                    if controls["indexed"] is not None:
                        runs.append(("control-indexed", False, True, (), (controls["indexed"],)))
                    for which, swa_on, indexed_on, swa_extra, indexed_extra in runs:
                        results = {}
                        for poison in ("zero", "nan", "big"):
                            counts = h.poison(swa_valid, indexed_valid, poison if swa_on else "zero",
                                              poison if indexed_on else "zero",
                                              swa_extra if poison != "zero" else (),
                                              indexed_extra if poison != "zero" else ())
                            h.out.fill_(0)
                            h.run(binding)
                            torch.cuda.synchronize()
                            results[poison] = h.out.clone().float()
                        big = results["big"]
                        compare(results["zero"], results["nan"], expected, poisoned=which, poisoned_slots=counts,
                                big_nonfinite=int((~torch.isfinite(big)).sum()),
                                big_max_diff=float(torch.nan_to_num(big - results["zero"], nan=float("inf")).abs().max()),
                                **fields)
    
    
    def main():
        groups = set(sys.argv[1:])
        print("DEVICE", torch.cuda.get_device_name(DEVICE), torch.cuda.get_device_capability(DEVICE), flush=True)
        for spec in specs():
            if groups and spec.group not in groups:
                continue
            try:
                run_spec(spec)
            except Exception:
                print("ERROR", spec.name, traceback.format_exc().replace("\n", " | "), 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
    poison_indexer.py
    """Poison test for b12x dsa_indexer selection (GLM-5.3-Flash, DeepSeek V4, DeepSeek V4.1).
    
    Usage: poison_indexer.py CONFIG [MODE ...]   CONFIG: glm, ds4, ds41; MODE: decode, prefill
    
    Each case builds a prepared dsa_indexer plan at the recipe's geometry, fills the index
    cache with random keys, then runs selection with the records a row must not read
    zero-filled and then poisoned:
      tail_{keys,scales,both}   records at or past each row's cache length in its last page
      unref_{keys,scales,both}  index pages no page-table row references
    FP8 poison is key byte 0x7F (E4M3 NaN) and a NaN FP32 scale; MXFP4 poison is code 0x77
    (+6, the largest E2M1 value) and scale 0xFF (E8M0 NaN). The selected indices (as sets per
    row) and their scores must not change, and every index must be below the row's length.
    """
    
    from __future__ import annotations
    
    import sys
    import traceback
    
    import torch
    
    from b12x.attention import dsa_indexer as dsa
    from b12x.preparation import PreparationSession, PreparedCall
    
    DEVICE = torch.device("cuda", 0)
    TOPK = 512
    
    CONFIGS = {
        # GLM: recipes/glm53/indexer.py (32 replicated heads, FP8 64-record pages, no active_width).
        "glm": dict(fmt="fp8", heads=32, page=64, active=False),
        # DeepSeek V4: recipes/deepseek4/attention.py via components/fp8_indexer.py (64 heads).
        "ds4": dict(fmt="fp8", heads=64, page=64, active=True),
        # DeepSeek V4.1: recipes/deepseek41/attention.py via components/mxfp4_indexer.py (page 128 // 4).
        "ds41": dict(fmt="mxfp4", heads=32, page=32, active=True),
    }
    
    DECODE_LENGTHS = (37, 500, 1000, 2311, 5000)
    PREFILL = ((300, 32), (3000, 64))  # (request length in records, query rows ending there)
    
    
    def gen(seed):
        return torch.Generator(device="cpu").manual_seed(seed)
    
    
    def randn(shape, seed, scale=1.0):
        return torch.randn(shape, generator=gen(seed)) * scale
    
    
    def page_layout(cfg):
        """(key bytes per record, key region bytes, scale bytes per record, page bytes)."""
        page = cfg["page"]
        if cfg["fmt"] == "fp8":
            return 128, page * 128, 4, page * 132
        return 64, page * 64, 4, dsa.index_mxfp4_page_bytes(page)
    
    
    def build(cfg, mode):
        page = cfg["page"]
        if mode == "decode":
            lengths = list(DECODE_LENGTHS)
            rows_per = [1] * len(lengths)
        else:
            lengths = [length for length, _ in PREFILL]
            rows_per = [rows for _, rows in PREFILL]
        # Prefill plans take one shared page table: one request per plan.
        requests = list(range(len(lengths)))
        width = max(-(-length // page) for length in lengths)
        pool_pages = sum(-(-length // page) for length in lengths) + 40
        order = torch.randperm(pool_pages, generator=gen(5))
        tables, cursor = [], 0
        for length in lengths:
            used = -(-length // page)
            table = torch.full((width,), -1, dtype=torch.int32)
            table[:used] = order[cursor:cursor + used].int()
            cursor += used
            tables.append(table)
        return lengths, rows_per, requests, width, pool_pages, tables
    
    
    def prepare_plan(cfg, mode, rows, width, inputs):
        caps = dsa.Caps(device=DEVICE, num_q_heads=cfg["heads"], max_q_rows=rows, max_page_table_width=width,
                        topk=TOPK, mode=mode, page_size=cfg["page"], cache_format=cfg["fmt"])
        plan = dsa.plan(caps, invocation=dsa.invocation_from_tensors(caps, **inputs))
    
        def prime(state):
            specs = state.layout.scratch_specs()
            scratch = [torch.empty(s.shape, dtype=s.dtype, device=DEVICE) for s in specs]
            scratch = scratch[0] if len(scratch) == 1 else scratch
            if cfg["fmt"] == "fp8":
                c = state.layout.caps
                runtime = state.bind(scratch=scratch, real_page_table=inputs["page_table"],
                    cache_seqlens_int32=inputs["cache_lengths"], active_width=inputs["active_width"],
                    expected_num_q_heads=c.num_q_heads, shared_page_table=c.shared_page_table,
                    output_physical_slots=c.output_physical_slots)
                run = lambda: state.run(runtime, **{k: inputs[k] for k in
                    ("q_fp8", "query_weights", "index_k_cache", "output_indices", "output_scores")})
            else:
                binding = state.bind(scratch=scratch, **inputs)
                run = lambda: state.run(binding)
            return PreparedCall(run=run, owners=(scratch,))
    
        session = PreparationSession(device=DEVICE, autotune=False, compile_workers=2)
        session.__enter__()
        session.prepare((plan.request(name="poison", prepare_call=prime),))
        return plan, session
    
    
    def bind(plan, inputs):
        specs = dsa.scratch_specs(plan, device=DEVICE)
        scratch = [torch.empty(s.shape, dtype=s.dtype, device=DEVICE) for s in specs]
        return dsa.bind(plan, scratch=scratch[0] if len(scratch) == 1 else scratch, **inputs), scratch
    
    
    def case(config, mode):
        cfg = CONFIGS[config]
        lengths, rows_per, requests, width, pool_pages, tables = build(cfg, mode)
        key_bytes, key_region, scale_bytes, page_bytes = page_layout(cfg)
        page = cfg["page"]
        groups = [(r,) for r in requests] if mode == "prefill" else [tuple(requests)]
        for group_id, group in enumerate(groups):
            # Row r of the plan: its request, its visible length.
            row_req, row_len = [], []
            for r in group:
                for i in range(rows_per[r]):
                    row_req.append(r)
                    row_len.append(lengths[r] - rows_per[r] + 1 + i)
            rows = len(row_req)
            if mode == "prefill":
                page_table = tables[group[0]].to(DEVICE)[None].expand(rows, -1)
            else:
                page_table = torch.stack([tables[r] for r in row_req]).to(DEVICE).contiguous()
            cache = torch.zeros((pool_pages, page_bytes), dtype=torch.uint8, device=DEVICE)
            cache_lengths = torch.tensor(row_len, dtype=torch.int32, device=DEVICE)
            active = torch.tensor([max(row_len)], dtype=torch.int32, device=DEVICE) if cfg["active"] else None
            out = torch.full((rows, TOPK), -7, dtype=torch.int32, device=DEVICE)
            scores = torch.empty((rows, TOPK), dtype=torch.float32, device=DEVICE)
            weights = (randn((rows, cfg["heads"]), 31, 1 / 64)).to(DEVICE)
            query = randn((rows, cfg["heads"], 128), 32, 0.5).to(DEVICE)
            if cfg["fmt"] == "fp8":
                inputs = dict(q_fp8=query.to(torch.float8_e4m3fn), query_weights=weights.float(),
                              index_k_cache=cache, page_table=page_table, cache_lengths=cache_lengths,
                              active_width=active, output_indices=out, output_scores=scores)
            else:
                inputs = dict(q_mxfp4=torch.zeros((rows, cfg["heads"], 64), dtype=torch.uint8, device=DEVICE),
                              q_scales=torch.full((rows, cfg["heads"], 4), 127, dtype=torch.uint8, device=DEVICE),
                              query_weights=weights.bfloat16(), index_k_cache=cache, page_table=page_table,
                              cache_lengths=cache_lengths, active_width=active, output_indices=out,
                              output_scores=scores)
            plan, session = prepare_plan(cfg, mode, rows, width, inputs)
            try:
                # Valid records: random keys written in the cache's own encoding.
                if cfg["fmt"] == "fp8":
                    keys = randn((pool_pages, page * 128), 41).to(DEVICE).to(torch.float8_e4m3fn)
                    cache[:, :key_region].copy_(keys.view(torch.uint8))
                    cache[:, key_region:].view(torch.float32).copy_(
                        (randn((pool_pages, page), 42).abs() * 0.1 + 0.05).to(DEVICE))
                else:
                    slots = torch.arange(pool_pages * page, dtype=torch.int64, device=DEVICE)
                    keys = randn((pool_pages * page, 128), 43).to(DEVICE).bfloat16()
                    dsa.quantize_write_index_k_mxfp4(plan, keys, index_k_cache=cache, slot_mapping=slots)
                    dsa.quantize_q_mxfp4(plan, query.bfloat16(), q_mxfp4=inputs["q_mxfp4"],
                                         q_scales=inputs["q_scales"])
                binding, _scratch = bind(plan, inputs)
                base = cache.clone()
    
                def run():
                    out.fill_(-7)
                    scores.fill_(0)
                    dsa.run(binding)
                    torch.cuda.synchronize()
                    return out.clone(), scores.clone()
    
                clean_idx, clean_scores = run()
                again_idx, again_scores = run()
                deterministic = bool(torch.equal(clean_idx, again_idx))
                rerun_rows = 0
                for _ in range(4):
                    ri, _rs = run()
                    rerun_rows = max(rerun_rows, sum(1 for row in range(rows) if
                                                     set(ri[row].tolist()) != set(clean_idx[row].tolist())))
    
                def shared_score_rows(ai, as_, bi, bs):
                    changed = 0
                    for row in range(rows):
                        a = dict(zip(ai[row].tolist(), as_[row].tolist()))
                        b = dict(zip(bi[row].tolist(), bs[row].tolist()))
                        if any(k >= 0 and a[k] != b[k] and not (a[k] != a[k] and b[k] != b[k])
                               for k in a.keys() & b.keys()):
                            changed += 1
                    return changed
                # Regions.
                referenced = set()
                tail_page, tail_rec = [], []
                for r in group:
                    used = -(-lengths[r] // page)
                    referenced.update(tables[r][:used].tolist())
                    last = int(tables[r][used - 1])
                    for rec in range(lengths[r] % page or page, page):
                        tail_page.append(last)
                        tail_rec.append(rec)
                unref = [p for p in range(pool_pages) if p not in referenced]
                regions = {"tail": (tail_page, tail_rec), "unref": (unref, None)}
                for region, (pages_, recs) in regions.items():
                    for part in ("keys", "scales", "both"):
                        results = {}
                        for nan in (False, True):
                            cache.copy_(base)
                            for p_i, p in enumerate(pages_):
                                records = range(page) if recs is None else (recs[p_i],)
                                for rec in records:
                                    if part in ("keys", "both"):
                                        span = slice(rec * key_bytes, (rec + 1) * key_bytes)
                                        cache[p, span] = (0x7F if cfg["fmt"] == "fp8" else 0x77) if nan else 0
                                    if part in ("scales", "both"):
                                        span = slice(key_region + rec * scale_bytes, key_region + (rec + 1) * scale_bytes)
                                        if cfg["fmt"] == "fp8":
                                            cache[p, span].view(torch.float32).fill_(float("nan") if nan else 0.0)
                                        else:
                                            cache[p, span] = 0xFF if nan else 0
                            results[nan] = run()
                        (zi, zs), (pi, ps) = results[False], results[True]
                        lens = cache_lengths.long()[:, None]
                        bad_index = int(((pi >= lens) | (pi < -1)).sum())
                        idx_rows = sum(1 for row in range(rows) if
                                       set(zi[row].tolist()) != set(pi[row].tolist()))
                        zero_rows = sum(1 for row in range(rows) if
                                        set(zi[row].tolist()) != set(clean_idx[row].tolist()))
                        # Slot order is not deterministic; compare each index's score.
                        exact = lambda t: torch.nan_to_num(t, nan=12345.0)
                        zo, po = zi.argsort(1), pi.argsort(1)
                        score_rows = int((exact(zs.gather(1, zo)) != exact(ps.gather(1, po))).any(1).sum()) \
                            if idx_rows == 0 else -1
                        slot_rows = int((zi != pi).any(1).sum())
                        nan_scores = int(torch.isnan(ps).sum())
                        print("ROW", dict(config=config, mode=mode, group=group_id, region=f"{region}_{part}",
                                          records=len(pages_) if recs is not None else len(pages_) * page,
                                          rows=rows, lengths=sorted({lengths[r] for r in group}),
                                          index_rows_changed=idx_rows, slot_rows_changed=slot_rows,
                                          score_rows_changed=score_rows, deterministic=deterministic,
                                          out_of_range=bad_index, nan_scores=nan_scores,
                                          zero_vs_clean_rows=zero_rows, rerun_set_rows=rerun_rows,
                                          shared_score_rows=shared_score_rows(zi, zs, pi, ps),
                                          selected=int((clean_idx >= 0).sum(1).max())), flush=True)
            finally:
                session.__exit__(None, None, None)
    
    
    def main():
        config = sys.argv[1]
        modes = sys.argv[2:] or ["decode", "prefill"]
        for mode in modes:
            try:
                case(config, mode)
            except Exception:
                traceback.print_exc()
                print("CASE_FAILED", config, mode, flush=True)
    
    
    if __name__ == "__main__":
        main()
  12. yatesdr commented on Nov 19, 2026

    @yatesdr
    Collaborator

    Results of the scripts above on one DGX Spark GB10 (SM121), eager, at Flare main eb8a062 with its pinned FlashInfer 2cce3e67 (b12x from the FlashInfer package):

    • poison_compressed_mla.py, all groups: 2,836 poisoned cases (SWA, indexed and both; NaN, largest-finite and zero fills; -1 and stale index padding) gave no non-finite output and a maximum difference of 0.0 from the zero-filled run. All 1,848 positive controls produced NaN, so the poison reaches a slot when a row reads it.
    • poison_indexer.py glm and ds4: 18 cases each, with no changed index set, no changed score, no NaN score and no index at or past a row's length.
    • poison_indexer.py ds41: no NaN score and no out-of-range index. Index sets changed in 12 of 18 cases, but clean reruns without poison changed as many rows or more (1 decode row; 32 prefill rows in group 1), and no index present in both runs changed its score. That matches the top-512 nondeterminism noted above.

    So on SM121, eager, the compressed sparse MLA and DSA indexer read no unreferenced or tail slot. Not run: CUDA graph replay, and the four kernels listed as leaking in the 2026-11-04 comment.

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

    area:cachingarea:kernelsbugmodel:deepseek-v4.1model:qwen3.8-27bpriority:P1triage:partial

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions