// GENERATED by dev/embed.py from dev/attn_effect.c.in and dev/attn_kernel.cu: edit those, not this file. // Attn.f16: fused attention (FlashAttention-2 style, FP16 tensor cores, FP32 softmax) on Bend arrays, // in place. The kernel is compiled once, at the first call, by NVRTC (libnvrtc, opened with dlopen) for this GPU. #include #if BEND_CUDA static const char* attn_src = "// Fused attention, FlashAttention-2 style, head dimension HD (128: attn_f16, 64: attn_f16_64):\n" "// o[(h / hpg) * gstride + row * ldo + oo + (h % hpg) * HD + d]\n" "// = sum_t softmax_t(scale * q[h, row] . k[h / gq, t]) * v[h / gq, t, d]\n" "// over all keys t, or (causal) t <= row. q, k, v: F32, head-major ([head][row][HD], head stride n * HD); k and v have\n" "// heads / gq heads (grouped-query attention: gq query heads share one key/value head). Heads come in groups of hpg\n" "// whose outputs start gstride cells apart (the VAE's tiles); hpg = heads and gstride = 0 for one plain row-major output. A block takes 128 query rows of one head (8 warps,\n" "// 16 rows each) and walks the keys in tiles of 64. S = Q K^T and O += P V run on tensor cores (mma.sync m16n8k16, FP16\n" "// inputs, FP32 accumulation; FP16 keeps TF32's 10-bit mantissa); scores, probabilities and the output stay in\n" "// registers, and the softmax runs online in FP32 (running max and sum per row, the output rescaled as the max grows).\n" "// This file is the kernel source the effect compiles at run time with NVRTC (effs/attn.c embeds it).\n" "#include \n" "\n" "#define BM 128\n" "#define BN 64\n" "// padded row strides of the shared tiles (halves), so fragment loads hit distinct banks: KST = HD + 8, VST = BN + 8\n" "#define VST (BN + 8)\n" "#define NEG_INF __int_as_float(0xff800000) // -infinity (NVRTC has no math.h)\n" "\n" "__device__ __forceinline__ unsigned pack(float a, float b) {\n" " __half2 x = __floats2half2_rn(a, b);\n" " return *(unsigned*)&x;\n" "}\n" "\n" "__device__ __forceinline__ void mma(float* c, const unsigned* a, unsigned b0, unsigned b1) {\n" " asm volatile(\"mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};\"\n" " : \"+f\"(c[0]), \"+f\"(c[1]), \"+f\"(c[2]), \"+f\"(c[3])\n" " : \"r\"(a[0]), \"r\"(a[1]), \"r\"(a[2]), \"r\"(a[3]), \"r\"(b0), \"r\"(b1));\n" "}\n" "\n" "template \n" "__device__ __forceinline__ void attn_body(const float* __restrict__ q, const float* __restrict__ k,\n" " const float* __restrict__ v, float* __restrict__ o, int n, int ldo, int oo, float scale_log2, int gq, int causal,\n" " int hpg, long long gstride) {\n" " constexpr int KST = HD + 8;\n" " __shared__ __align__(16) __half Ks[BN * KST]; // [key][d]\n" " __shared__ __align__(16) __half Vt[HD * VST]; // [d][key], V transposed\n" " const int h = blockIdx.y, tid = threadIdx.x, w = tid >> 5, lane = tid & 31, g = lane >> 2, t = lane & 3;\n" " const long long hs = (long long)n * HD;\n" " const float* qh = q + h * hs;\n" " const float* kh = k + (h / gq) * hs;\n" " const float* vh = v + (h / gq) * hs;\n" " const int r0 = blockIdx.x * BM + w * 16 + g, r1 = r0 + 8; // this thread's two rows\n" "\n" " unsigned qa[HD / 16][4]; // Q as A fragments, one per 16 columns\n" " for (int kk = 0; kk < HD / 16; kk++) {\n" " int c = kk * 16 + 2 * t;\n" " float2 a = r0 < n ? *(const float2*)(qh + (long long)r0 * HD + c) : make_float2(0.f, 0.f);\n" " float2 b = r1 < n ? *(const float2*)(qh + (long long)r1 * HD + c) : make_float2(0.f, 0.f);\n" " float2 a8 = r0 < n ? *(const float2*)(qh + (long long)r0 * HD + c + 8) : make_float2(0.f, 0.f);\n" " float2 b8 = r1 < n ? *(const float2*)(qh + (long long)r1 * HD + c + 8) : make_float2(0.f, 0.f);\n" " qa[kk][0] = pack(a.x, a.y); qa[kk][1] = pack(b.x, b.y); qa[kk][2] = pack(a8.x, a8.y); qa[kk][3] = pack(b8.x, b8.y);\n" " }\n" " float acc[HD / 8][4]; // O: 16 tiles of 8 columns; [0..1] row r0, [2..3] row r1\n" " for (int i = 0; i < HD / 8; i++) acc[i][0] = acc[i][1] = acc[i][2] = acc[i][3] = 0.f;\n" " float m0 = NEG_INF, m1 = NEG_INF, l0 = 0.f, l1 = 0.f;\n" "\n" " const int kend = causal ? min(n, blockIdx.x * BM + BM) : n; // causal: keys past the block's last row are masked\n" " for (int k0 = 0; k0 < kend; k0 += BN) {\n" " __syncthreads();\n" " for (int i = tid; i < BN * HD / 4; i += 256) {\n" " int row = i / (HD / 4), c = (i % (HD / 4)) * 4;\n" " bool ok = k0 + row < n;\n" " float4 kv = ok ? *(const float4*)(kh + (long long)(k0 + row) * HD + c) : make_float4(0.f, 0.f, 0.f, 0.f);\n" " float4 vv = ok ? *(const float4*)(vh + (long long)(k0 + row) * HD + c) : make_float4(0.f, 0.f, 0.f, 0.f);\n" " *(unsigned*)&Ks[row * KST + c] = pack(kv.x, kv.y);\n" " *(unsigned*)&Ks[row * KST + c + 2] = pack(kv.z, kv.w);\n" " Vt[(c + 0) * VST + row] = __float2half_rn(vv.x);\n" " Vt[(c + 1) * VST + row] = __float2half_rn(vv.y);\n" " Vt[(c + 2) * VST + row] = __float2half_rn(vv.z);\n" " Vt[(c + 3) * VST + row] = __float2half_rn(vv.w);\n" " }\n" " __syncthreads();\n" "\n" " float s[BN / 8][4]; // S: 8 tiles of 8 keys\n" " for (int nb = 0; nb < BN / 8; nb++) {\n" " s[nb][0] = s[nb][1] = s[nb][2] = s[nb][3] = 0.f;\n" " const __half* kr = Ks + (nb * 8 + g) * KST + 2 * t;\n" " for (int kk = 0; kk < HD / 16; kk++)\n" " mma(s[nb], qa[kk], *(const unsigned*)(kr + kk * 16), *(const unsigned*)(kr + kk * 16 + 8));\n" " }\n" " float mx0 = NEG_INF, mx1 = NEG_INF;\n" " for (int nb = 0; nb < BN / 8; nb++) {\n" " int col = k0 + nb * 8 + 2 * t;\n" " int lim0 = causal ? min(n, r0 + 1) : n, lim1 = causal ? min(n, r1 + 1) : n; // keys allowed: col < lim\n" " s[nb][0] = col < lim0 ? s[nb][0] * scale_log2 : NEG_INF;\n" " s[nb][1] = col + 1 < lim0 ? s[nb][1] * scale_log2 : NEG_INF;\n" " s[nb][2] = col < lim1 ? s[nb][2] * scale_log2 : NEG_INF;\n" " s[nb][3] = col + 1 < lim1 ? s[nb][3] * scale_log2 : NEG_INF;\n" " mx0 = fmaxf(mx0, fmaxf(s[nb][0], s[nb][1]));\n" " mx1 = fmaxf(mx1, fmaxf(s[nb][2], s[nb][3]));\n" " }\n" " mx0 = fmaxf(mx0, __shfl_xor_sync(0xffffffffu, mx0, 1)); mx0 = fmaxf(mx0, __shfl_xor_sync(0xffffffffu, mx0, 2));\n" " mx1 = fmaxf(mx1, __shfl_xor_sync(0xffffffffu, mx1, 1)); mx1 = fmaxf(mx1, __shfl_xor_sync(0xffffffffu, mx1, 2));\n" " float n0 = fmaxf(m0, mx0), n1 = fmaxf(m1, mx1);\n" " float al0 = exp2f(m0 - n0), al1 = exp2f(m1 - n1);\n" " m0 = n0; m1 = n1;\n" " float sum0 = 0.f, sum1 = 0.f;\n" " for (int nb = 0; nb < BN / 8; nb++) {\n" " s[nb][0] = exp2f(s[nb][0] - n0); s[nb][1] = exp2f(s[nb][1] - n0);\n" " s[nb][2] = exp2f(s[nb][2] - n1); s[nb][3] = exp2f(s[nb][3] - n1);\n" " sum0 += s[nb][0] + s[nb][1]; sum1 += s[nb][2] + s[nb][3];\n" " }\n" " l0 = l0 * al0 + sum0; // a partial sum per lane; the four lanes of a row add up at the end\n" " l1 = l1 * al1 + sum1;\n" " for (int i = 0; i < HD / 8; i++) { acc[i][0] *= al0; acc[i][1] *= al0; acc[i][2] *= al1; acc[i][3] *= al1; }\n" " for (int kk = 0; kk < BN / 16; kk++) { // P as A fragments: two 8-key tiles of S make one 16-key fragment\n" " unsigned pa[4] = {pack(s[2 * kk][0], s[2 * kk][1]), pack(s[2 * kk][2], s[2 * kk][3]),\n" " pack(s[2 * kk + 1][0], s[2 * kk + 1][1]), pack(s[2 * kk + 1][2], s[2 * kk + 1][3])};\n" " for (int nb = 0; nb < HD / 8; nb++) {\n" " const __half* vr = Vt + (nb * 8 + g) * VST + kk * 16 + 2 * t;\n" " mma(acc[nb], pa, *(const unsigned*)vr, *(const unsigned*)(vr + 8));\n" " }\n" " }\n" " }\n" " l0 += __shfl_xor_sync(0xffffffffu, l0, 1); l0 += __shfl_xor_sync(0xffffffffu, l0, 2);\n" " l1 += __shfl_xor_sync(0xffffffffu, l1, 1); l1 += __shfl_xor_sync(0xffffffffu, l1, 2);\n" " float i0 = 1.f / l0, i1 = 1.f / l1;\n" " float* og = o + (h / hpg) * gstride;\n" " for (int nb = 0; nb < HD / 8; nb++) {\n" " int c = oo + (h % hpg) * HD + nb * 8 + 2 * t;\n" " if (r0 < n) *(float2*)(og + (long long)r0 * ldo + c) = make_float2(acc[nb][0] * i0, acc[nb][1] * i0);\n" " if (r1 < n) *(float2*)(og + (long long)r1 * ldo + c) = make_float2(acc[nb][2] * i1, acc[nb][3] * i1);\n" " }\n" "}\n" "\n" "extern \"C\" __global__ void __launch_bounds__(256) attn_f16(const float* __restrict__ q, const float* __restrict__ k,\n" " const float* __restrict__ v, float* __restrict__ o, int n, int ldo, int oo, float scale_log2, int gq, int causal,\n" " int hpg, long long gstride) {\n" " attn_body<128>(q, k, v, o, n, ldo, oo, scale_log2, gq, causal, hpg, gstride);\n" "}\n" "\n" "extern \"C\" __global__ void __launch_bounds__(256) attn_f16_64(const float* __restrict__ q, const float* __restrict__ k,\n" " const float* __restrict__ v, float* __restrict__ o, int n, int ldo, int oo, float scale_log2, int gq, int causal,\n" " int hpg, long long gstride) {\n" " attn_body<64>(q, k, v, o, n, ldo, oo, scale_log2, gq, causal, hpg, gstride);\n" "}\n" "\n" ; static const char* attn2_src = "#define ATTN2_PRODUCTION\n" "// Faster fused attention, head dimension 128, FlashAttention-2 style like attn_kernel.cu, in three variants:\n" "// prep_kv16: K -> FP16 [kvhead][npad][128], V -> FP16 transposed [kvhead][128][npad], once per call\n" "// attn_h (mode 0): S = Q K^T in FP16 (FP32 accumulation), O += P V in FP16 (FP32 accumulation)\n" "// attn_h (mode 1): the same, P V accumulated in FP16 within a key tile, added into FP32 after it\n" "// prep_k8 + attn_h (mode 2): S = Q K^T in int8 (mma m16n8k32, int32 accumulation): K smoothed (its per-head mean\n" "// subtracted, which shifts every score of a query row by the same amount and so leaves the softmax as it was),\n" "// quantized per 64-key tile; Q quantized per row in the kernel. P V as mode 1.\n" "// Tiles stream into shared memory with cp.async, double-buffered (dynamic shared memory).\n" "#include \n" "\n" "#define HD 128\n" "#define BM 128\n" "#ifndef BN\n" "#define BN 64\n" "#endif\n" "#define KST (HD + 8) // halves, K tile row stride (FP16)\n" "#define K8ST (HD + 16) // bytes, K tile row stride (int8)\n" "#define VST (BN + 8) // halves, V^T tile row stride\n" "#define NEG_INF __int_as_float(0xff800000)\n" "\n" "__device__ __forceinline__ unsigned pack(float a, float b) {\n" " __half2 x = __floats2half2_rn(a, b);\n" " return *(unsigned*)&x;\n" "}\n" "__device__ __forceinline__ void mma16(float* c, const unsigned* a, unsigned b0, unsigned b1) {\n" " asm volatile(\"mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};\"\n" " : \"+f\"(c[0]), \"+f\"(c[1]), \"+f\"(c[2]), \"+f\"(c[3])\n" " : \"r\"(a[0]), \"r\"(a[1]), \"r\"(a[2]), \"r\"(a[3]), \"r\"(b0), \"r\"(b1));\n" "}\n" "__device__ __forceinline__ void mma16h(unsigned* c, const unsigned* a, unsigned b0, unsigned b1) {\n" " asm volatile(\"mma.sync.aligned.m16n8k16.row.col.f16.f16.f16.f16 {%0,%1}, {%2,%3,%4,%5}, {%6,%7}, {%0,%1};\"\n" " : \"+r\"(c[0]), \"+r\"(c[1])\n" " : \"r\"(a[0]), \"r\"(a[1]), \"r\"(a[2]), \"r\"(a[3]), \"r\"(b0), \"r\"(b1));\n" "}\n" "__device__ __forceinline__ void mma8(int* c, const unsigned* a, unsigned b0, unsigned b1) {\n" " asm volatile(\"mma.sync.aligned.m16n8k32.row.col.s32.s8.s8.s32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};\"\n" " : \"+r\"(c[0]), \"+r\"(c[1]), \"+r\"(c[2]), \"+r\"(c[3])\n" " : \"r\"(a[0]), \"r\"(a[1]), \"r\"(a[2]), \"r\"(a[3]), \"r\"(b0), \"r\"(b1));\n" "}\n" "__device__ __forceinline__ void cp16(void* s, const void* g) {\n" " unsigned sa = (unsigned)__cvta_generic_to_shared(s);\n" " asm volatile(\"cp.async.cg.shared.global [%0], [%1], 16;\" :: \"r\"(sa), \"l\"(g));\n" "}\n" "__device__ __forceinline__ void cp_commit() { asm volatile(\"cp.async.commit_group;\"); }\n" "__device__ __forceinline__ void cp_wait1() { asm volatile(\"cp.async.wait_group 1;\"); }\n" "__device__ __forceinline__ void cp_wait0() { asm volatile(\"cp.async.wait_group 0;\"); }\n" "__device__ __forceinline__ int q8(float x) { return max(-127, min(127, __float2int_rn(x))); }\n" "__device__ __forceinline__ unsigned pack8(int a, int b, int c, int d) {\n" " return (unsigned)(a & 255) | ((unsigned)(b & 255) << 8) | ((unsigned)(c & 255) << 16) | ((unsigned)(d & 255) << 24);\n" "}\n" "\n" "// K and V of one kv head, a 64-key tile per block: K as FP16 rows, V transposed (rows past n are zero)\n" "extern \"C\" __global__ void __launch_bounds__(256) prep_kv16(const float* __restrict__ k, const float* __restrict__ v,\n" " __half* __restrict__ k16, __half* __restrict__ vt16, int n, int npad) {\n" " __shared__ float vs[BN][HD + 1];\n" " const int h = blockIdx.y, k0 = blockIdx.x * BN, tid = threadIdx.x;\n" " const float* kh = k + (long long)h * n * HD;\n" " const float* vh = v + (long long)h * n * HD;\n" " __half* kd = k16 + (long long)h * npad * HD;\n" " __half* vd = vt16 + (long long)h * HD * npad;\n" " for (int i = tid; i < BN * HD; i += 256) {\n" " int r = i / HD, c = i % HD;\n" " bool ok = k0 + r < n;\n" " kd[(long long)(k0 + r) * HD + c] = __float2half_rn(ok ? kh[(long long)(k0 + r) * HD + c] : 0.f);\n" " vs[r][c] = ok ? vh[(long long)(k0 + r) * HD + c] : 0.f;\n" " }\n" " __syncthreads();\n" " for (int i = tid; i < BN * HD; i += 256) {\n" " int c = i / BN, r = i % BN;\n" " vd[(long long)c * npad + k0 + r] = __float2half_rn(vs[r][c]);\n" " }\n" "}\n" "\n" "#ifndef ATTN2_PRODUCTION\n" "// per kv head, the mean of K over its n keys (for smoothing): one block a head, a thread a column (128)\n" "extern \"C\" __global__ void kmean(const float* __restrict__ k, float* __restrict__ mean, int n) {\n" " const int h = blockIdx.x, c = threadIdx.x;\n" " const float* kh = k + (long long)h * n * HD;\n" " float s = 0.f;\n" " for (int r = 0; r < n; r++) s += kh[(long long)r * HD + c];\n" " mean[h * HD + c] = s / n;\n" "}\n" "\n" "// K smoothed and quantized to int8, one scale a 64-key tile: k8 [kvhead][npad][128], kscale [kvhead][npad / 64]\n" "extern \"C\" __global__ void __launch_bounds__(256) prep_k8(const float* __restrict__ k, const float* __restrict__ mean,\n" " signed char* __restrict__ k8, float* __restrict__ kscale, int n, int npad) {\n" " __shared__ float red[256];\n" " const int h = blockIdx.y, k0 = blockIdx.x * BN, tid = threadIdx.x;\n" " const float* kh = k + (long long)h * n * HD;\n" " float mx = 0.f;\n" " for (int i = tid; i < BN * HD; i += 256) {\n" " int r = i / HD, c = i % HD;\n" " float x = k0 + r < n ? kh[(long long)(k0 + r) * HD + c] - mean[h * HD + c] : 0.f;\n" " mx = fmaxf(mx, fabsf(x));\n" " }\n" " red[tid] = mx; __syncthreads();\n" " for (int s = 128; s > 0; s >>= 1) { if (tid < s) red[tid] = fmaxf(red[tid], red[tid + s]); __syncthreads(); }\n" " float sc = fmaxf(red[0], 1e-30f) / 127.f, inv = 1.f / sc;\n" " if (tid == 0) kscale[h * (npad / BN) + blockIdx.x] = sc;\n" " signed char* kd = k8 + (long long)h * npad * HD;\n" " for (int i = tid; i < BN * HD; i += 256) {\n" " int r = i / HD, c = i % HD;\n" " float x = k0 + r < n ? kh[(long long)(k0 + r) * HD + c] - mean[h * HD + c] : 0.f;\n" " kd[(long long)(k0 + r) * HD + c] = (signed char)q8(x * inv);\n" " }\n" "}\n" "\n" "#endif\n" "\n" "// mode 0/1: FP16 S; mode 2: int8 S. o as attn_kernel.cu's (row-major output, heads at columns oo + h * HD).\n" "template \n" "__device__ __forceinline__ void attn_body(const float* __restrict__ q, const __half* __restrict__ k16,\n" " const signed char* __restrict__ k8, const float* __restrict__ kscale, const __half* __restrict__ vt16,\n" " float* __restrict__ o, int n, int npad, int ldo, int oo, float scale_log2, int gq) {\n" " extern __shared__ __align__(16) unsigned char smem[];\n" " constexpr int KBYTES = MODE == 2 ? BN * K8ST : BN * KST * 2;\n" " constexpr int STAGE = KBYTES + HD * VST * 2;\n" " const int h = blockIdx.y, tid = threadIdx.x, w = tid >> 5, lane = tid & 31, g = lane >> 2, t = lane & 3;\n" " const int kvh = h / gq;\n" " const float* qh = q + (long long)h * n * HD;\n" " const int r0 = blockIdx.x * BM + w * 16 + g, r1 = r0 + 8;\n" " const int ntile = npad / BN;\n" "\n" " auto load = [&](int tile, int buf) {\n" " unsigned char* st = smem + buf * STAGE;\n" " if (MODE == 2) {\n" " const signed char* src = k8 + ((long long)kvh * npad + tile * BN) * HD;\n" " for (int i = tid; i < BN * HD / 16; i += 256) { int r = i / (HD / 16), c = (i % (HD / 16)) * 16; cp16(st + r * K8ST + c, src + r * HD + c); }\n" " } else {\n" " const __half* src = k16 + ((long long)kvh * npad + tile * BN) * HD;\n" " __half* ks = (__half*)st;\n" " for (int i = tid; i < BN * HD / 8; i += 256) { int r = i / (HD / 8), c = (i % (HD / 8)) * 8; cp16(ks + r * KST + c, src + r * HD + c); }\n" " }\n" " const __half* vsrc = vt16 + (long long)kvh * HD * npad + tile * BN;\n" " __half* vs = (__half*)(st + KBYTES);\n" " for (int i = tid; i < HD * BN / 8; i += 256) { int d = i / (BN / 8), c = (i % (BN / 8)) * 8; cp16(vs + d * VST + c, vsrc + (long long)d * npad + c); }\n" " cp_commit();\n" " };\n" "\n" " // Q: FP16 A fragments (modes 0, 1), or int8 A fragments with a scale per row (mode 2)\n" " unsigned qa[HD / 16][4];\n" " unsigned qb[HD / 32][4];\n" " float qs0 = 1.f, qs1 = 1.f;\n" " if (MODE == 2) {\n" " float mx0 = 0.f, mx1 = 0.f;\n" " for (int kk = 0; kk < HD / 32; kk++)\n" " for (int j = 0; j < 2; j++) {\n" " int c = kk * 32 + j * 16 + 4 * t;\n" " float4 a = r0 < n ? *(const float4*)(qh + (long long)r0 * HD + c) : make_float4(0.f, 0.f, 0.f, 0.f);\n" " float4 b = r1 < n ? *(const float4*)(qh + (long long)r1 * HD + c) : make_float4(0.f, 0.f, 0.f, 0.f);\n" " mx0 = fmaxf(mx0, fmaxf(fmaxf(fabsf(a.x), fabsf(a.y)), fmaxf(fabsf(a.z), fabsf(a.w))));\n" " mx1 = fmaxf(mx1, fmaxf(fmaxf(fabsf(b.x), fabsf(b.y)), fmaxf(fabsf(b.z), fabsf(b.w))));\n" " }\n" " mx0 = fmaxf(mx0, __shfl_xor_sync(0xffffffffu, mx0, 1)); mx0 = fmaxf(mx0, __shfl_xor_sync(0xffffffffu, mx0, 2));\n" " mx1 = fmaxf(mx1, __shfl_xor_sync(0xffffffffu, mx1, 1)); mx1 = fmaxf(mx1, __shfl_xor_sync(0xffffffffu, mx1, 2));\n" " qs0 = fmaxf(mx0, 1e-30f) / 127.f; qs1 = fmaxf(mx1, 1e-30f) / 127.f;\n" " float i0 = 1.f / qs0, i1 = 1.f / qs1;\n" " for (int kk = 0; kk < HD / 32; kk++)\n" " for (int j = 0; j < 2; j++) {\n" " int c = kk * 32 + j * 16 + 4 * t;\n" " float4 a = r0 < n ? *(const float4*)(qh + (long long)r0 * HD + c) : make_float4(0.f, 0.f, 0.f, 0.f);\n" " float4 b = r1 < n ? *(const float4*)(qh + (long long)r1 * HD + c) : make_float4(0.f, 0.f, 0.f, 0.f);\n" " qb[kk][2 * j] = pack8(q8(a.x * i0), q8(a.y * i0), q8(a.z * i0), q8(a.w * i0));\n" " qb[kk][2 * j + 1] = pack8(q8(b.x * i1), q8(b.y * i1), q8(b.z * i1), q8(b.w * i1));\n" " }\n" " } else {\n" " for (int kk = 0; kk < HD / 16; kk++) {\n" " int c = kk * 16 + 2 * t;\n" " float2 a = r0 < n ? *(const float2*)(qh + (long long)r0 * HD + c) : make_float2(0.f, 0.f);\n" " float2 b = r1 < n ? *(const float2*)(qh + (long long)r1 * HD + c) : make_float2(0.f, 0.f);\n" " float2 a8 = r0 < n ? *(const float2*)(qh + (long long)r0 * HD + c + 8) : make_float2(0.f, 0.f);\n" " float2 b8 = r1 < n ? *(const float2*)(qh + (long long)r1 * HD + c + 8) : make_float2(0.f, 0.f);\n" " qa[kk][0] = pack(a.x, a.y); qa[kk][1] = pack(b.x, b.y); qa[kk][2] = pack(a8.x, a8.y); qa[kk][3] = pack(b8.x, b8.y);\n" " }\n" " }\n" " float acc[HD / 8][4];\n" " for (int i = 0; i < HD / 8; i++) acc[i][0] = acc[i][1] = acc[i][2] = acc[i][3] = 0.f;\n" " float m0 = NEG_INF, m1 = NEG_INF, l0 = 0.f, l1 = 0.f;\n" "\n" " load(0, 0);\n" " for (int tile = 0; tile < ntile; tile++) {\n" " const int buf = tile & 1;\n" " if (tile + 1 < ntile) { load(tile + 1, buf ^ 1); cp_wait1(); } else cp_wait0();\n" " __syncthreads();\n" " unsigned char* st = smem + buf * STAGE;\n" " const int k0 = tile * BN;\n" " float s[BN / 8][4];\n" " if (MODE == 2) {\n" " const signed char* ks = (const signed char*)st;\n" " const float ksc = kscale[kvh * ntile + tile];\n" " for (int nb = 0; nb < BN / 8; nb++) {\n" " int c4[4] = {0, 0, 0, 0};\n" " const signed char* kr = ks + (nb * 8 + g) * K8ST + 4 * t;\n" " for (int kk = 0; kk < HD / 32; kk++)\n" " mma8(c4, qb[kk], *(const unsigned*)(kr + kk * 32), *(const unsigned*)(kr + kk * 32 + 16));\n" " float f0 = qs0 * ksc * scale_log2, f1 = qs1 * ksc * scale_log2;\n" " s[nb][0] = c4[0] * f0; s[nb][1] = c4[1] * f0; s[nb][2] = c4[2] * f1; s[nb][3] = c4[3] * f1;\n" " }\n" " } else {\n" " const __half* ks = (const __half*)st;\n" " for (int nb = 0; nb < BN / 8; nb++) {\n" " s[nb][0] = s[nb][1] = s[nb][2] = s[nb][3] = 0.f;\n" " const __half* kr = ks + (nb * 8 + g) * KST + 2 * t;\n" " for (int kk = 0; kk < HD / 16; kk++)\n" " mma16(s[nb], qa[kk], *(const unsigned*)(kr + kk * 16), *(const unsigned*)(kr + kk * 16 + 8));\n" " s[nb][0] *= scale_log2; s[nb][1] *= scale_log2; s[nb][2] *= scale_log2; s[nb][3] *= scale_log2;\n" " }\n" " }\n" " float mx0 = NEG_INF, mx1 = NEG_INF;\n" " for (int nb = 0; nb < BN / 8; nb++) {\n" " int col = k0 + nb * 8 + 2 * t;\n" " if (col >= n) { s[nb][0] = NEG_INF; s[nb][2] = NEG_INF; }\n" " if (col + 1 >= n) { s[nb][1] = NEG_INF; s[nb][3] = NEG_INF; }\n" " mx0 = fmaxf(mx0, fmaxf(s[nb][0], s[nb][1]));\n" " mx1 = fmaxf(mx1, fmaxf(s[nb][2], s[nb][3]));\n" " }\n" " mx0 = fmaxf(mx0, __shfl_xor_sync(0xffffffffu, mx0, 1)); mx0 = fmaxf(mx0, __shfl_xor_sync(0xffffffffu, mx0, 2));\n" " mx1 = fmaxf(mx1, __shfl_xor_sync(0xffffffffu, mx1, 1)); mx1 = fmaxf(mx1, __shfl_xor_sync(0xffffffffu, mx1, 2));\n" " float n0 = fmaxf(m0, mx0), n1 = fmaxf(m1, mx1);\n" " float al0 = exp2f(m0 - n0), al1 = exp2f(m1 - n1);\n" " m0 = n0; m1 = n1;\n" " float sum0 = 0.f, sum1 = 0.f;\n" " for (int nb = 0; nb < BN / 8; nb++) {\n" " s[nb][0] = exp2f(s[nb][0] - n0); s[nb][1] = exp2f(s[nb][1] - n0);\n" " s[nb][2] = exp2f(s[nb][2] - n1); s[nb][3] = exp2f(s[nb][3] - n1);\n" " sum0 += s[nb][0] + s[nb][1]; sum1 += s[nb][2] + s[nb][3];\n" " }\n" " l0 = l0 * al0 + sum0; l1 = l1 * al1 + sum1;\n" " const __half* vs = (const __half*)(st + KBYTES);\n" " if (MODE == 0) {\n" " for (int i = 0; i < HD / 8; i++) { acc[i][0] *= al0; acc[i][1] *= al0; acc[i][2] *= al1; acc[i][3] *= al1; }\n" " for (int kk = 0; kk < BN / 16; kk++) {\n" " unsigned pa[4] = {pack(s[2 * kk][0], s[2 * kk][1]), pack(s[2 * kk][2], s[2 * kk][3]),\n" " pack(s[2 * kk + 1][0], s[2 * kk + 1][1]), pack(s[2 * kk + 1][2], s[2 * kk + 1][3])};\n" " for (int nb = 0; nb < HD / 8; nb++) {\n" " const __half* vr = vs + (nb * 8 + g) * VST + kk * 16 + 2 * t;\n" " mma16(acc[nb], pa, *(const unsigned*)vr, *(const unsigned*)(vr + 8));\n" " }\n" " }\n" " } else {\n" " unsigned pa[BN / 16][4];\n" " for (int kk = 0; kk < BN / 16; kk++) {\n" " pa[kk][0] = pack(s[2 * kk][0], s[2 * kk][1]); pa[kk][1] = pack(s[2 * kk][2], s[2 * kk][3]);\n" " pa[kk][2] = pack(s[2 * kk + 1][0], s[2 * kk + 1][1]); pa[kk][3] = pack(s[2 * kk + 1][2], s[2 * kk + 1][3]);\n" " }\n" " for (int nb = 0; nb < HD / 8; nb++) {\n" " unsigned c2[2] = {0u, 0u};\n" " const __half* vr = vs + (nb * 8 + g) * VST + 2 * t;\n" " for (int kk = 0; kk < BN / 16; kk++)\n" " mma16h(c2, pa[kk], *(const unsigned*)(vr + kk * 16), *(const unsigned*)(vr + kk * 16 + 8));\n" " float2 lo = __half22float2(*(__half2*)&c2[0]), hi = __half22float2(*(__half2*)&c2[1]);\n" " acc[nb][0] = acc[nb][0] * al0 + lo.x; acc[nb][1] = acc[nb][1] * al0 + lo.y;\n" " acc[nb][2] = acc[nb][2] * al1 + hi.x; acc[nb][3] = acc[nb][3] * al1 + hi.y;\n" " }\n" " }\n" " __syncthreads();\n" " }\n" " l0 += __shfl_xor_sync(0xffffffffu, l0, 1); l0 += __shfl_xor_sync(0xffffffffu, l0, 2);\n" " l1 += __shfl_xor_sync(0xffffffffu, l1, 1); l1 += __shfl_xor_sync(0xffffffffu, l1, 2);\n" " float i0 = 1.f / l0, i1 = 1.f / l1;\n" " for (int nb = 0; nb < HD / 8; nb++) {\n" " int c = oo + h * HD + nb * 8 + 2 * t;\n" " if (r0 < n) *(float2*)(o + (long long)r0 * ldo + c) = make_float2(acc[nb][0] * i0, acc[nb][1] * i0);\n" " if (r1 < n) *(float2*)(o + (long long)r1 * ldo + c) = make_float2(acc[nb][2] * i1, acc[nb][3] * i1);\n" " }\n" "}\n" "\n" "extern \"C\" __global__ void __launch_bounds__(256) attn_h0(const float* q, const __half* k16, const signed char* k8,\n" " const float* kscale, const __half* vt16, float* o, int n, int npad, int ldo, int oo, float scale_log2, int gq) {\n" " attn_body<0>(q, k16, k8, kscale, vt16, o, n, npad, ldo, oo, scale_log2, gq);\n" "}\n" "extern \"C\" __global__ void __launch_bounds__(256) attn_h1(const float* q, const __half* k16, const signed char* k8,\n" " const float* kscale, const __half* vt16, float* o, int n, int npad, int ldo, int oo, float scale_log2, int gq) {\n" " attn_body<1>(q, k16, k8, kscale, vt16, o, n, npad, ldo, oo, scale_log2, gq);\n" "}\n" "#ifndef ATTN2_PRODUCTION\n" "extern \"C\" __global__ void __launch_bounds__(256) attn_h2(const float* q, const __half* k16, const signed char* k8,\n" " const float* kscale, const __half* vt16, float* o, int n, int npad, int ldo, int oo, float scale_log2, int gq) {\n" " attn_body<2>(q, k16, k8, kscale, vt16, o, n, npad, ldo, oo, scale_log2, gq);\n" "}\n" "#endif\n" "\n" ; typedef int (*AttnNvCreate)(void**, const char*, const char*, int, const char* const*, const char* const*); typedef int (*AttnNvCompile)(void*, int, const char* const*); typedef int (*AttnNvSize)(void*, size_t*); typedef int (*AttnNvGet)(void*, char*); typedef int (*AttnNvDestroy)(void**); static struct { int state; CUfunction fn, fn64, prep, fast, fast16; char why[4096]; CUdeviceptr k16, vt16; size_t scratch; } attn_lib; static void* attn_dlopen(const char* name) { char path[512]; const char* home = getenv("CUDA_HOME"); void* h = NULL; if (home != NULL) { snprintf(path, sizeof path, "%s/lib64/%s", home, name); h = dlopen(path, RTLD_NOW | RTLD_GLOBAL); } if (h == NULL) { snprintf(path, sizeof path, "/usr/local/cuda/lib64/%s", name); h = dlopen(path, RTLD_NOW | RTLD_GLOBAL); } if (h == NULL) h = dlopen(name, RTLD_NOW | RTLD_GLOBAL); return h; } // the fast kernel's shared memory: two stages of a 64-key FP16 K tile and a 128 x 64 FP16 V^T tile, padded rows #define ATTN_FAST_SMEM (2 * (64 * 136 * 2 + 128 * 72 * 2)) static int attn_build(AttnNvCreate create, AttnNvCompile compile, AttnNvSize log_size, AttnNvGet get_log, AttnNvSize cubin_size, AttnNvGet get_cubin, AttnNvDestroy destroy, const char* src, const char* name, const char** opts, const char* arch, CUmodule* mod) { void* prog = NULL; if (create(&prog, src, name, 0, NULL, NULL) != 0) { snprintf(attn_lib.why, sizeof attn_lib.why, "nvrtcCreateProgram failed"); return 0; } if (compile(prog, 3, opts) != 0) { size_t n = 0; log_size(prog, &n); char* log = (char*)malloc(n + 1); get_log(prog, log); log[n] = 0; snprintf(attn_lib.why, sizeof attn_lib.why, "NVRTC compile of %s failed (%s):\n%s", name, arch, log); free(log); destroy(&prog); return 0; } size_t size = 0; cubin_size(prog, &size); char* cubin = (char*)malloc(size); get_cubin(prog, cubin); destroy(&prog); int ok = cuModuleLoadData(mod, cubin) == CUDA_SUCCESS; free(cubin); if (!ok) snprintf(attn_lib.why, sizeof attn_lib.why, "loading the compiled %s failed", name); return ok; } static void attn_open(void) { if (attn_lib.state != 0) return; attn_lib.state = -1; void* h = attn_dlopen("libnvrtc.so"); if (h == NULL) { snprintf(attn_lib.why, sizeof attn_lib.why, "libnvrtc.so not found"); return; } AttnNvCreate create = (AttnNvCreate)dlsym(h, "nvrtcCreateProgram"); AttnNvCompile compile = (AttnNvCompile)dlsym(h, "nvrtcCompileProgram"); AttnNvSize log_size = (AttnNvSize)dlsym(h, "nvrtcGetProgramLogSize"); AttnNvGet get_log = (AttnNvGet)dlsym(h, "nvrtcGetProgramLog"); AttnNvSize cubin_size = (AttnNvSize)dlsym(h, "nvrtcGetCUBINSize"); AttnNvGet get_cubin = (AttnNvGet)dlsym(h, "nvrtcGetCUBIN"); AttnNvDestroy destroy = (AttnNvDestroy)dlsym(h, "nvrtcDestroyProgram"); if (!create || !compile || !log_size || !get_log || !cubin_size || !get_cubin || !destroy) { snprintf(attn_lib.why, sizeof attn_lib.why, "NVRTC symbols missing"); return; } CUcontext ctx; if (cuDevicePrimaryCtxRetain(&ctx, gpu_dev) != CUDA_SUCCESS || cuCtxSetCurrent(ctx) != CUDA_SUCCESS) { snprintf(attn_lib.why, sizeof attn_lib.why, "no CUDA context"); return; } int major = 0, minor = 0; cuDeviceGetAttribute(&major, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR, gpu_dev); cuDeviceGetAttribute(&minor, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR, gpu_dev); char arch[64], inc[600]; snprintf(arch, sizeof arch, "--gpu-architecture=sm_%d%d", major, minor); const char* home = getenv("CUDA_HOME"); snprintf(inc, sizeof inc, "-I%s/include", home != NULL ? home : "/usr/local/cuda"); const char* opts[] = {arch, inc, "-std=c++17"}; CUmodule mod, mod2; if (!attn_build(create, compile, log_size, get_log, cubin_size, get_cubin, destroy, attn_src, "attn_kernel.cu", opts, arch, &mod) || !attn_build(create, compile, log_size, get_log, cubin_size, get_cubin, destroy, attn2_src, "attn2_kernel.cu", opts, arch, &mod2)) return; if (cuModuleGetFunction(&attn_lib.fn, mod, "attn_f16") != CUDA_SUCCESS || cuModuleGetFunction(&attn_lib.fn64, mod, "attn_f16_64") != CUDA_SUCCESS || cuModuleGetFunction(&attn_lib.prep, mod2, "prep_kv16") != CUDA_SUCCESS || cuModuleGetFunction(&attn_lib.fast, mod2, "attn_h0") != CUDA_SUCCESS || cuModuleGetFunction(&attn_lib.fast16, mod2, "attn_h1") != CUDA_SUCCESS || cuFuncSetAttribute(attn_lib.fast, CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, ATTN_FAST_SMEM) != CUDA_SUCCESS || cuFuncSetAttribute(attn_lib.fast16, CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, ATTN_FAST_SMEM) != CUDA_SUCCESS) { snprintf(attn_lib.why, sizeof attn_lib.why, "loading the compiled kernels failed"); return; } attn_lib.state = 1; } static float* attn_cells(Env e, Term a, uint64_t need, const char* name) { if (term_tag(a) != TAG_BUF) { fprintf(stderr, "Attn.f16: %s is not a 32-bit array\n", name); exit(1); } if ((1ull << blk_cls(a)) < need) { fprintf(stderr, "Attn.f16: %s holds %llu cells, needs %llu\n", name, (unsigned long long)(1ull << blk_cls(a)), (unsigned long long)need); exit(1); } float* p = (float*)(e.mem + blk_loc(e.mem, a)); unsigned int managed = 0; if (cuPointerGetAttribute(&managed, CU_POINTER_ATTRIBUTE_IS_MANAGED, (CUdeviceptr)(uintptr_t)p) != CUDA_SUCCESS || !managed) { fprintf(stderr, "Attn.f16: %s is not in CUDA managed memory (a CUDA build with a `!` call, not --gpu off)\n", name); exit(1); } return p; } #endif // f: q, k, v, o, n, heads, scale (F32 bits), ldo, oo, gq (query heads a key/value head), causal (0 or 1), // hd (64 or 128), hpg (heads a group), gstride (cells between groups' outputs) Term attn_run(Env e, Term* f, IoWork* w) { #if BEND_CUDA int n = (int)(uint32_t)f[4], heads = (int)(uint32_t)f[5], ldo = (int)(uint32_t)f[7], oo = (int)(uint32_t)f[8]; int gq = (int)(uint32_t)f[9], causal = (int)(uint32_t)f[10] != 0, hd = (int)(uint32_t)f[11], hpg = (int)(uint32_t)f[12]; long long gstride = (long long)(uint32_t)f[13]; if (hd != 64 && hd != 128) { fprintf(stderr, "Attn.f16: head dimension %d (64 or 128)\n", hd); exit(1); } if (hpg < 1 || heads % hpg != 0) { fprintf(stderr, "Attn.f16: %d heads do not split into groups of %d\n", heads, hpg); exit(1); } if (gq < 1 || heads % gq != 0) { fprintf(stderr, "Attn.f16: %d heads do not split into groups of %d\n", heads, gq); exit(1); } union { uint32_t u; float x; } sb; sb.u = (uint32_t)f[6]; float scale_log2 = sb.x * 1.4426950408889634f; attn_open(); if (attn_lib.state != 1) { fprintf(stderr, "Attn.f16: %s\n", attn_lib.why); exit(1); } uint64_t qkv = (uint64_t)heads * n * hd; float* q = attn_cells(e, f[0], qkv, "q"); float* k = attn_cells(e, f[1], qkv / gq, "k"); float* v = attn_cells(e, f[2], qkv / gq, "v"); float* o = attn_cells(e, f[3], (uint64_t)(heads / hpg - 1) * gstride + (uint64_t)(n - 1) * ldo + oo + (uint64_t)hpg * hd, "o"); if (hd == 128 && !causal && hpg == heads && gstride == 0 && !getenv("ATTN_V1")) { // the fast path: K and V converted to FP16 once (V transposed), into scratch buffers kept between calls, then tiles // streamed in double-buffered (attn2_kernel.cu): the same arithmetic as attn_f16. ATTN_PV16=1: P V accumulated in // FP16 a key tile, about 10% faster, and about twice the error. int kvh = heads / gq, npad = (n + 63) / 64 * 64; size_t need = (size_t)kvh * npad * 128 * 2; if (need > attn_lib.scratch) { if (attn_lib.scratch) { cuMemFree(attn_lib.k16); cuMemFree(attn_lib.vt16); } if (cuMemAlloc(&attn_lib.k16, need) != CUDA_SUCCESS || cuMemAlloc(&attn_lib.vt16, need) != CUDA_SUCCESS) { fprintf(stderr, "Attn.f16: no GPU memory for %zu bytes of scratch\n", 2 * need); exit(1); } attn_lib.scratch = need; } void* pargs[] = {&k, &v, &attn_lib.k16, &attn_lib.vt16, &n, &npad}; void* nul = NULL; void* fargs[] = {&q, &attn_lib.k16, &nul, &nul, &attn_lib.vt16, &o, &n, &npad, &ldo, &oo, &scale_log2, &gq}; if (cuLaunchKernel(attn_lib.prep, (unsigned)(npad / 64), (unsigned)kvh, 1, 256, 1, 1, 0, NULL, pargs, NULL) != CUDA_SUCCESS || cuLaunchKernel(getenv("ATTN_PV16") ? attn_lib.fast16 : attn_lib.fast, (unsigned)((n + 127) / 128), (unsigned)heads, 1, 256, 1, 1, ATTN_FAST_SMEM, NULL, fargs, NULL) != CUDA_SUCCESS) { fprintf(stderr, "Attn.f16: launch failed\n"); exit(1); } } else { void* args[] = {&q, &k, &v, &o, &n, &ldo, &oo, &scale_log2, &gq, &causal, &hpg, &gstride}; if (cuLaunchKernel(hd == 128 ? attn_lib.fn : attn_lib.fn64, (unsigned)((n + 127) / 128), (unsigned)heads, 1, 256, 1, 1, 0, NULL, args, NULL) != CUDA_SUCCESS) { fprintf(stderr, "Attn.f16: launch failed\n"); exit(1); } } if (cuCtxSynchronize() != CUDA_SUCCESS) { fprintf(stderr, "Attn.f16: synchronize failed\n"); exit(1); } return io_tup(e, f[0], io_tup(e, f[1], io_tup(e, f[2], f[3]))); #else fprintf(stderr, "Attn.f16 needs a CUDA build\n"); exit(1); #endif } static void __attribute__((constructor)) attn_use(void) { #ifdef CID(Attn.f16) io_eff(CID(Attn.f16), attn_run); #endif }