# bend-gpu-attention: fused FlashAttention-style attention on Bend arrays, one foreign call for all heads, no score matrix in memory. # import bend-gpu-attention@/attention.bend as AT # # Attn.f16(q, k, v, o, n, heads, scale, ldo, oo, gq, causal, hd, hpg, gstride), for every head h 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], d < hd # over all keys t < n, or t <= r when causal is 1. # q: heads x n x hd, k and v: (heads / gq) x n x hd, all head-major ([head][row][dim]), F32 bits in Array # hd: 64 or 128; scale: F32 bits (usually 1 / sqrt(hd)); gq: query heads a key/value head (grouped-query attention) # hpg, gstride: heads come in groups of hpg whose outputs start gstride cells apart (batched attention, such as image # tiles); hpg = heads and gstride = 0 for one row-major output, head h at columns oo + h * hd of each ldo-wide row. # The products run on tensor cores in FP16 (the 10-bit mantissa of TF32) with FP32 accumulation, the softmax online # in FP32. q, k, v and o are read and written in place; the call answers them back. # # The kernels (dev/attn_kernel.cu, and dev/attn2_kernel.cu's faster path for head dimension 128 over all keys with one # output, the same arithmetic) are compiled once, at the first call, by NVRTC for the GPU it finds. # Needs a native CUDA build of a program that uses `!` (Bend's heap in CUDA managed memory), libnvrtc at run time, # and Bend 2.0.40 (the C reads runtime internals). Foreign code: nothing here is proved. import Base def Attn.f16(q: Array, k: Array, v: Array, o: Array, n: U32, heads: U32, scale: U32, ldo: U32, oo: U32, gq: U32, causal: U32, hd: U32, hpg: U32, gstride: U32) -> IO(Array & Array & Array & Array): import "./effs/attn.c" import "./effs/attn.js"