# bend-gpu-attention Fused attention for Bend 2 on NVIDIA GPUs: one foreign call computes softmax attention for every head, in the style of FlashAttention-2, on Bend arrays in place. The scores never go to memory, so there is no n x n array per head, and no separate GEMM and softmax passes. ```python import bend-gpu-attention@/attention.bend as AT ``` ```python # 56 heads of 128 over 4,422 rows; head h's output at columns h * 128 of each 7,168-wide row of act r : Array & Array & Array & Array <- AT.Attn.f16(qh, kh, vh, act, 4422, 56, 1035273459, 7168, 0, 1, 0, 128, 56, 0) ``` ## `Attn.f16(q, k, v, o, n, heads, scale, ldo, oo, gq, causal, hd, hpg, gstride)` For every head h < heads and row r < n: ``` o[(h / hpg) * gstride + r * ldo + oo + (h % hpg) * hd + d] = sum_t softmax_t(scale * q[h, r] . k[h / gq, t]) * v[h / gq, t, d] ``` over all keys t < n, or t <= r when `causal` is 1. | argument | meaning | | - | - | | `q` | heads x n x hd, head-major (`[head][row][dim]`), F32 bits in `Array` | | `k`, `v` | (heads / gq) x n x hd, head-major | | `o` | the output (written; nothing else in it changes) | | `scale` | F32 bits, usually 1 / sqrt(hd) (`1035273459` is 1 / sqrt(128), `1040187392` is 0.125) | | `ldo`, `oo` | the output's row stride and column offset | | `gq` | query heads a key/value head (grouped-query attention; 1 for plain multi-head) | | `causal` | 1: row r attends to keys 0..r only | | `hd` | head dimension: 64 or 128 | | `hpg`, `gstride` | heads come in groups of `hpg` whose outputs start `gstride` cells apart: batched attention, such as image tiles. `hpg = heads`, `gstride = 0` for one row-major output | It answers `(q, (k, (v, o)))`. The call checks that every array holds the cells it reads or writes. ## How it computes A block takes 128 query rows of one head and walks the keys in tiles of 64. `S = Q K^T` and `O += P V` run on tensor cores (`mma.sync` m16n8k16) with FP16 inputs and FP32 accumulation; FP16 has the same 10-bit mantissa as TF32. The softmax is online in FP32 (a running max and sum per row, the output rescaled as the max grows); scores, probabilities and the output stay in registers. Causal attention skips the key tiles past a block's last row. For the commonest call (head dimension 128, all keys, one row-major output) version 0.2 takes a faster path with the same arithmetic and the same results bit for bit: a first kernel converts K and V to FP16 once (V transposed) into scratch buffers the effect keeps between calls (2 x heads/gq x n x 128 x 2 bytes, 128 MB at the first shape below), and the attention kernel streams their tiles into shared memory with `cp.async`, double-buffered, instead of every block converting the F32 arrays itself. Other calls (causal, head dimension 64, grouped outputs) use the first kernel. Two environment variables, read at each call: `ATTN_PV16=1` accumulates `P V` in FP16 within each key tile (about 10% faster again, and about twice the error); `ATTN_V1=1` turns the fast path off. ## Tests `test/attn_test.bend` runs `Attn.f16` on pseudo-random inputs and compares every output cell with attention computed in plain Bend on the CPU, in three cases: all keys at hd 128; causal grouped-query at 128; hd 64 with grouped outputs. It prints each relative error (about 3.5e-4) and exits 1 above 3e-3. With the causal flag wrong in the kernel call, the causal case reports 0.86 and the test exits 1. ```bash bend test/attn_test.bend -o attn_test && ./attn_test ``` `dev/attn2_test.cu` times the CUDA kernels by themselves at the first shape and checks them against a float64 reference, on plain and on offset keys: the first kernel, the fast path, `ATTN_PV16`, and an int8 `Q K^T` variant that is not used (its relative error is 2e-2, thirty times the FP16 paths'). `nvcc -O2 -arch=sm_120 -o attn2_test dev/attn2_test.cu`. ## Requirements - A **native CUDA build** of a program that uses `!` (`bend main.bend -o main`), so Bend's heap is CUDA managed memory. In a CPU build the effect stops with a message; the JS stub throws. - `libnvrtc` at run time (from `$CUDA_HOME/lib64`, `/usr/local/cuda/lib64` or the loader path): the kernel is compiled once, at the first call (about 0.2 s), for the GPU it finds, with `cuda_fp16.h` from the CUDA include directory. - Tensor cores with FP16 `mma.sync` (compute capability 8.0 or newer). - The C reads Bend runtime internals (`blk_loc`, `blk_cls`, `e.mem`, `gpu_dev`). Tested with **Bend 2.0.40** only; recheck after every Bend release. Foreign code: nothing here is proved.