attention.bend source
attention.bend on the hub · documented module
# 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@<version>/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<U32># 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 Basedef Attn.f16(q: Array<U32>, k: Array<U32>, v: Array<U32>, o: Array<U32>, n: U32, heads: U32, scale: U32, ldo: U32, oo: U32, gq: U32, causal: U32, hd: U32, hpg: U32, gstride: U32) -> IO(Array<U32> & Array<U32> & Array<U32> & Array<U32>): import "./effs/attn.c" import "./effs/attn.js"# Attn.i8: the same call, with S = Q K^T in int8 (Q and K rotated by the normalized 128-point Hadamard matrix, which# leaves q.k unchanged and spreads outlying channels; K's per-head mean subtracted, which shifts a row's scores alike;# a scale a row of Q and a key of K) when hd is 128, causal is 0 and the output is one row-major array; otherwise it is# Attn.f16. About 20% faster than Attn.f16 at 4,422 rows; about ten times its error on a diffusion transformer's real# activations (relative L2 1e-3 to 5e-3, against 1e-4 to 3e-4).def Attn.i8(q: Array<U32>, k: Array<U32>, v: Array<U32>, o: Array<U32>, n: U32, heads: U32, scale: U32, ldo: U32, oo: U32, gq: U32, causal: U32, hd: U32, hpg: U32, gstride: U32) -> IO(Array<U32> & Array<U32> & Array<U32> & Array<U32>): import "./effs/attn.c" import "./effs/attn_i8.js"