# 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. ## `Attn.i8`: int8 scores `Attn.i8` takes the same arguments as `Attn.f16` and computes `S = Q K^T` on int8 tensor cores (`mma.sync` m16n8k32) when the head dimension is 128, all keys attend and the output is one row-major array; any other call is `Attn.f16`. Three small kernels prepare Q and K first: - both are multiplied by the normalized 128-point Hadamard matrix, which leaves every `q . k` unchanged and spreads a vector's outlying channels over all 128, so int8 scales lose less; - K's per-head mean is subtracted (every score of a query row moves by the same amount, so the softmax is unchanged); - Q is quantized with a scale a row, K with a scale a key (round to nearest, clamped to +-127). The softmax, `P V` and the output are as `Attn.f16`'s fast path. The rotation matters: on a diffusion transformer's real activations, int8 without it failed where some scores reached the thousands (relative error 0.16), and with it stayed near 3e-3. ## Speed and accuracy (RTX 5090) | q, k, v | `Attn.f16` | `Attn.i8` | | - | - | - | | random, 56 heads x 4,422 rows, hd 128 | 3.5 ms (5.1 ms in 0.1), rel. L2 7e-4 | 2.9 ms, 1.7e-2 | | random, four channels ten times larger in q | 3.5 ms, 7.6e-4 | 3.0 ms, 2.4e-2 | | a 50-block diffusion transformer's own, blocks 0, 25, 49 | 1.2e-4, 2.8e-4, 2.7e-4 | 1.2e-3, 4.5e-3, 2.6e-3 | | random, 64 query heads on 8 key/value heads x 326 rows, causal | 0.05 ms | (`Attn.f16`) | `ATTN_PV16=1` makes `Attn.f16`'s fast path 3.1 ms at the first shape (7.7e-4). In that transformer's six-step sampler at 512 x 512, the latent's error against a float64-attention reference, as a multiple of the reference's own int8 noise floor after six steps: 1.38 with `Attn.f16`, 1.41 with `Attn.i8`, 1.56 with `ATTN_PV16=1`. At 2048 x 2048 both `Attn.i8` and `ATTN_PV16` keep the image's composition and move details. Whether that is worth about 20% of attention's time is the caller's call. ## 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; a fourth case runs `Attn.i8` (about 1.2e-2 on these random inputs, limit 5e-2). 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 keys, offset keys and four outlying channels: the first kernel, the fast path, `ATTN_PV16`, int8 without rotation, and `Attn.i8`'s path; `dev/attn_real.cu` does the same on real q, k, v files. `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.