Skip to content

cuda: sparse gather attention over listed cache rows (Kolibri 1.1, slice 1 of #4846) - #5166

Merged
ashhart merged 12 commits into
ashhart:mainfrom
jschmied:kolibri11-core-pr
Nov 26, 2026
Merged

ashhart merged 12 commits into
ashhart:mainfrom
jschmied:kolibri11-core-pr

Conversation

@jschmied

@jschmied jschmied commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Refs #4846

Head: 4118f86beb, rebased onto main 67ae36c4dc after #5051 landed. The kernel contract and the full CI set ran on this
head; the SASS comparison ran before the rebase (see "Against main"). The gradient-serving pins of cuda/kernels.zig and cuda/root.zig are
refreshed for the new image and export.

Slice 1 of Kolibri 1.1 (#4846): a core CUDA kernel that attends each query row to its own list of cache rows, the
attention a sparse indexer's picks (top-k, local and sink keys) need. No family calls it yet; nothing served changes.

What changes

Piece Where What it does
gather attention kernels/cuda/sparse_attention.cu, cuda/sparse_attention.zig each (row, key head) over list[row][g][0 .. counts[row][g]) of the cache's keys rows, stride elements apart: GQA up to 16 query heads a key head, head dim 128, the list cut into four warps' slices folded in warp order; NaN and infinite values replayed as block_attention.cu does
shared fold kernels/cuda/attn_fold.cuh the per-warp online-softmax fold block_attention.cu had inline, now included by both
contract tests/cuda/contract_sparse_attn.zig, core/contract/sparse_attention_records.zig float64 reference, the gates and a planted control
contract set tests/cuda/contract_family_sets.zig the sparse attention set next to #5051's topk_rows and sparse_index pair; on a failed init those two unwind in reverse init order

The kernel's stated rules (in the kernel and the wrapper's doc comment):

  • a count is taken in [0, cap]; a list entry outside [0, keys) names no key: it weighs nothing and nothing is read
    for it (a per-tile ballot mask, and the same check on the NaN/infinity replay path);
  • a list of no keys gives NaN, as float64's 0 / 0; a cache row listed twice weighs twice;
  • numerators are fp32, as in block_attention.cu's fold: past fp32's range (for example 128 equal keys with V
    2^122) a head is +-inf in both kernels; this PR keeps that behaviour and those bits rather than a new order.

Shapes the wrapper refuses before any launch (check, error.SparseShape; the key-head count is checked before any
product with it): no query heads, more than 65,535 key heads, a head count not a whole
number of key heads, more than 16 query heads a key head, an empty list capacity, no cache rows or more than i32
holds, a row stride under hk x 128 elements or not a multiple of 8, a list capacity past max_cap (INT_MAX - 31: the
last 32-key tile's indices stay in i32). The kernel counts a list's tiles as n / 32 + (n % 32 != 0), which cannot
overflow at that capacity.

Against main

block_attention.cu now includes attn_fold.cuh; its machine code is unchanged: tools/zig/cuda_sass_compare.py --images block_attention (base 9961ca4920, then the merge base, against 9803062e39; nvcc 13.0; main up to 67ae36c4dc changes none of the
files block_attention.cu compiles from, and the commits since 9803062e39 touch only sparse_attention.cu, the wrapper
and tests) gives SUMMARY PASS images=1 functions=5: tf_block_attention's SASS and encoding sha256 equal on sm_80, sm_86, sm_89, sm_120 and sm_121 (sm_120/121 SASS a54ab7a9..., sm_80 486667ad..., sm_86 c57e7dba..., sm_89 29a74df8...). No other kernel
includes the header. Nothing is wired into a family, so there is no served path to compare (no seeded, resume or
concurrency claim); those come with the Kolibri 1.1 forward PR.

Evidence

Kernel contract on 4118f86beb (tf-cuda-test kernel-contract 'sparse attention' 'block attention', GB10, nvcc 13.0), exit code 0:

SUMMARY 3 kernels: 3 pass gates 1-4, 0 fail, 0 known findings; 1 controls: 1 red as planted, 0 missed; 0 limit problems
FAIL shapes cuda sparse attention tf_sparse_attention, control: the kernel told one key fewer: at 4x48x700: head 4 element 0 is -3.881836e-2 where float64 gives -3.091259e-2: 1.27 of attention_ref's bound
  • Served shapes: 1 row over 2,184 listed keys (Kolibri 1.1's 2,048 + 128 + 8), 4 rows over 700, 17 rows over 129,
    48 query heads over 4 key heads; the shapes gate adds each dimension's tile edges.
  • Planted lists in gates 1-3 (row 1, zig/tests/cuda/contract_sparse_attn.zig:163): an empty list, a list filling
    every slot and told cap + 5, and entries -1 and one past the last cache row inside the count. Gate 4 leaves them
    out: its mirrored sums need every head finite.
  • Planted control, red as planted: zig/tests/cuda/contract_sparse_attn.zig:33, the kernel told one key fewer.
  • Test first: the contract and wrapper changes alone (1db7c5c365, the old kernel body) fail the shapes gate on the
    planted lists; with the clamp and the mask (83efd3cca5) they pass. The h = 0 refusal has its unit test in
    cuda/sparse_attention.zig.
  • The capacity bound: cuda/sparse_attention.zig "check takes Kolibri 1.1's groups ..." accepts max_cap and refuses
    max_cap + 1 (fails on 571c1a0364, before 1424b1d075). The tile count at max_cap is checked by a host mirror of
    the kernel's i32 arithmetic ("the tile count at max_cap ..."): a device run at that capacity needs an 8 GiB list per
    (row, key head), so the kernel itself is not run there.
  • The key-head bound: the same test refuses h = hk = 2^57 (rows, cap and keys 1, stride 0); on 7079d36011, before
    ce328e4ac1, hk x 128 overflowed first and the test build panicked.
  • The block attention cells run unchanged next to it (the shared fold).

Full CI set (x86 lane) on 4118f86beb: 25583/25729 tests passed (146 skipped), gradient-serving pins,
cuda-host, pr-check, fmt, diff-check and lean all rc 0. Lean check: 0 new problems (152 on the base, 152 on the head).

Not here (later PRs): the indexer that produces the lists (#5051), and the Kolibri 1.1 forward that wires both.

Proposed CHANGELOG line: cuda: sparse gather attention over listed cache rows (tf_sparse_attention, with contract); block attention's fold shared in attn_fold.cuh.

@ashhart

ashhart commented Nov 26, 2026

Copy link
Copy Markdown
Owner

Thank you, @jschmied.

CHANGES REQUESTED at d7ddcb1f7e708b28d68d63f6a28ee4d614026455.

The shared fold in zig/kernels/cuda/attn_fold.cuh preserves the block-attention operation order, including FP32 scaling, reductions, BF16 probability rounding, and P×V accumulation. The sparse kernel's gather masks, duplicate handling, empty-list NaN behavior, and nonfinite replay are consistent in source. No family calls the new kernel, so the new sparse path cannot change current served tokens. I found no external copied implementation.

One host refusal defect remains at zig/src/cuda/sparse_attention.zig:31-34. The second guard evaluates sh.hk * dim before checking sh.hk > 65535. For example, h = hk = 1 << 57, rows = cap = keys = 1, and stride = 0 passes the first guard, then overflows the multiplication. A safety-checked build panics instead of returning error.SparseShape.

Please check the excessive key-head count before any multiplication by hk, and add that case to the host unit test. The later focused device contract can then remain small: the new sparse kernel beside both existing block-attention variants, including the planted control and list boundary cases. No model checkpoint is needed until a family wires this kernel into serving.

  • Synthena

@jschmied

Copy link
Copy Markdown
Contributor Author

Done on 4118f86beb, rebased onto 67ae36c4dc after #5051 landed:

  • Key-head guard (your review): check now refuses hk > 65535 before any product with hk. The test
    (7079d36011) passes h = hk = 2^57 with rows, cap and keys 1 and stride 0 and expects error.SparseShape; on the
    old guard it panicked on hk x 128 first. The fix is ce328e4ac1. The device contract is unchanged.
  • Rebase: the core: exact row top-k, sparse index scores and block summaries for sparse indexers #5051 commits already on main are dropped; contract_family_sets.zig keeps main's topk_rows and
    sparse_index pair and adds the sparse attention set after them (on a failed init the pair unwinds in reverse init
    order, 4118f86beb). The gradient-serving pins are re-hashed for this head.
  • On this head: kernel contract 3 kernels pass gates 1-4, the planted control red; full x86 CI set green (25583/25729
    passed, 146 skipped); lean 0 new. block_attention's SASS result carries: main up to 67ae36c4dc touches none of
    the files it compiles from. Body updated.

@ashhart

ashhart commented Nov 26, 2026

Copy link
Copy Markdown
Owner

Thank you—the key-head guard now rejects the overflowing shape before any multiplication by hk, and the regression captures the exact failure mode. The contract-set ordering and reverse unwinding are preserved, the refreshed pins match, and the shared block-attention fold remains operation-for-operation unchanged.

The sparse gather, duplicate and empty-list behavior, index masking, nonfinite replay, and warp-order fold are consistent in source. Nothing served calls the new kernel, so I have no remaining code defect to request.

The only residual coverage I would add is one focused CUDA case combining a negative count, a duplicate across a tile boundary, invalid indices during forced nonfinite replay, and one query head per key head, beside the planted control and existing block-attention checks. No checkpoint is needed for this unwired kernel.

  • Synthena

jschmied and others added 12 commits November 26, 2026 13:27
…shared in attn_fold.cuh

tf_sparse_attention attends each (row, key head) to its own list of cache rows: GQA up to 16 query heads a key
head, head dim 128, the list cut into four warps' slices folded in warp order, NaN and infinite values replayed as
block_attention.cu does. block_attention.cu takes its Fold from attn_fold.cuh, unchanged (SASS identical on every
SM built). Contract cells for Kolibri 1.1's 48 over 4 heads with a planted control (the kernel told one key fewer).
…e contract lists nothing, every slot, past cap and unnamed rows
… the cache rows weighs nothing and is not read
…is refused (its count's 32-key tiles round up in i32)
… 31), where a count's tile round-up would overflow i32
…; n + 31 overflowed i32 at max_cap, a host mirror checks the boundary
…fused before hk x 128 is taken (2^57 heads overflowed it)
…n excessive count is refused, not an overflow
@ashhart
ashhart merged commit c21d201 into ashhart:main Nov 26, 2026
2 of 12 checks passed
@ashhart

ashhart commented Nov 26, 2026

Copy link
Copy Markdown
Owner

Thank you @jschmied. This is merged into main with your commits under your own name, so you're listed as a TensorFold contributor. It ships in the next release, credited to you in the changelog and the release notes.

@jschmied

Copy link
Copy Markdown
Contributor Author

The focused CUDA case from your review (7187194600) is in #5242: one query head per key head, a negative count, a duplicate across a 32-key tile edge, and unnamed entries during a forced nonfinite replay, beside the planted control and the block attention checks. It is green on the real kernel; with the replay's named-entry check planted out, only the new case goes red. Test only, no kernel change.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants