okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
01529aaa8
main
1// Specialized from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d, 2// ggml/src/ggml-cuda/{fattn-vec.cuh,fattn-common.cuh,common.cuh}. 3// MIT License 4// Copyright (c) 2023-2026 The ggml authors 5// Permission is hereby granted, free of charge, to any person obtaining a copy 6// of this software and associated documentation files (the "Software"), to deal 7// in the Software without restriction, including without limitation the rights 8// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9// copies of the Software, and to permit persons to whom the Software is 10// furnished to do so, subject to the following conditions: 11// The above copyright notice and this permission notice shall be included in all 12// copies or substantial portions of the Software. 13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19// SOFTWARE. 20 21#include "strata/kernels/native_flash_attn.hpp" 22#include <cuda_runtime.h> 23#include <cuda_fp16.h> 24#include <cfloat> 25#include <cstddef> 26#include <cstdint> 27#include <limits> 28#include <stdexcept> 29#include <string> 30 31namespace strata::kernels { 32namespace { 33template<int Width> __device__ __forceinline__ float warp_sum(float x) { 34#pragma unroll 35 for (int offset = Width / 2; offset; offset >>= 1) 36 x += __shfl_xor_sync(0xffffffffu, x, offset, Width); 37 return x; 38} 39__device__ __forceinline__ float warp_max(float x) { 40#pragma unroll 41 for (int offset = 16; offset; offset >>= 1) 42 x = fmaxf(x, __shfl_xor_sync(0xffffffffu, x, offset, 32)); 43 return x; 44} 45 46// D=256,ncols=1,F16/F16; 128 threads, nthreads_KQ=nthreads_V=8, 47// four values (float2) per load, four V columns per iteration. Padded length256 48// gives ntiles_KV=ceil(256/D)=1, so the pinned launcher selects grid.y=1. 49__launch_bounds__(128, 1) 50__global__ void attend(const float* __restrict__ q, const half* __restrict__ k, 51 const half* __restrict__ v, const int32_t* __restrict__ step, 52 int max_context, int padded_length, float scale, float* __restrict__ out, int32_t* __restrict__ status, 53 const half* __restrict__ mask) { 54 const int lane = threadIdx.x, warp = threadIdx.y, tid = warp * 32 + lane; 55 const int head = blockIdx.x, kv = head / 12; 56 const int width = step[kStepWidth], nkv = step[kStepNKv]; 57 const bool valid = width >= 1 && width <= max_context && nkv == width && 58 step[kStepPos] == width - 1 && step[kStepNBid] == width / 4; 59 if (head == 0 && tid == 0) 60 *status = valid ? kNativeFlashAttnSuccess : kNativeFlashAttnUnsupportedStep; 61 if (!valid) { 62 out[head * 256 + tid] = __int_as_float(0x7fc00000); 63 out[head * 256 + tid + 128] = __int_as_float(0x7fc00000); 64 return; 65 } 66 float2 qreg[16]; 67 float2 vkq[16] = {}; 68 __shared__ float tile[4 * 4 * 256]; 69 __shared__ float max_shared[32], sum_shared[32]; 70 float maximum = -FLT_MAX / 2.0f, sum = 0.0f; 71#pragma unroll 72 for (int i0 = 0; i0 < 128; i0 += 32) { 73 const int i = i0 + (lane % 8) * 4; 74#pragma unroll 75 for (int j = 0; j < 4; ++j) { 76 const int d = 2 * (i + j); 77 qreg[i0 / 8 + j] = make_float2(q[head * 256 + d] * scale, 78 q[head * 256 + d + 1] * scale); 79 } 80 } 81 for (int base = 0; base < padded_length; base += 128) { 82 float score = 0.0f, next_max = maximum; 83#pragma unroll 84 for (int row = 0; row < 8; ++row) { 85 const int cell = base + warp * 32 + (lane & ~7) + row; 86 float dot = 0.0f; 87#pragma unroll 88 for (int i0 = 0; i0 < 128; i0 += 32) { 89 const int i = i0 + (lane % 8) * 4; 90#pragma unroll 91 for (int j = 0; j < 4; ++j) { 92 const int d = 2 * (i + j); 93 const float a = cell < width ? __half2float(k[(cell * 2 + kv) * 256 + d]) : 0.0f; 94 const float b = cell < width ? __half2float(k[(cell * 2 + kv) * 256 + d + 1]) : 0.0f; 95 dot += a * qreg[i0 / 8 + j].x; 96 dot += b * qreg[i0 / 8 + j].y; 97 } 98 } 99 dot = warp_sum<8>(dot); 100 dot += cell < width ? (mask ? __half2float(mask[cell]) : 0.0f) : __int_as_float(0xff800000u); 101 next_max = fmaxf(next_max, dot + (3.0f * 0.6931f)); 102 if (lane % 8 == row) score = dot; 103 } 104#pragma unroll 105 for (int offset = 8; offset < 32; offset <<= 1) 106 next_max = fmaxf(next_max, __shfl_xor_sync(0xffffffffu, next_max, offset, 32)); 107 const float rescale = expf(maximum - next_max); 108 maximum = next_max; 109 score = expf(score - maximum); 110 sum = sum * rescale + score; 111 tile[tid] = score; 112 __syncwarp(); 113#pragma unroll 114 for (int k0 = 0; k0 < 32; k0 += 4) { 115 const int local = warp * 32 + k0 + lane / 8, cell = base + local; 116 const float weight = tile[local]; 117#pragma unroll 118 for (int i0 = 0; i0 < 128; i0 += 32) { 119 const int i = i0 + (lane % 8) * 4; 120#pragma unroll 121 for (int j = 0; j < 4; ++j) { 122 const int d = 2 * (i + j); 123 const float a = cell < width ? __half2float(v[(cell * 2 + kv) * 256 + d]) : 0.0f; 124 const float b = cell < width ? __half2float(v[(cell * 2 + kv) * 256 + d + 1]) : 0.0f; 125 // The pinned sm120a binary contracts the old-accumulator 126 // rescale with the FIRST addition: fma(rescale,old,round(V*w)). 127 // Later columns use fma(V,w,acc). Explicit intrinsics retain 128 // that order despite this adapter's masked-load branches. 129 if (k0 == 0) { 130 vkq[i0 / 8 + j].x = __fmaf_rn(rescale, vkq[i0 / 8 + j].x, __fmul_rn(a, weight)); 131 vkq[i0 / 8 + j].y = __fmaf_rn(rescale, vkq[i0 / 8 + j].y, __fmul_rn(b, weight)); 132 } else { 133 vkq[i0 / 8 + j].x = __fmaf_rn(a, weight, vkq[i0 / 8 + j].x); 134 vkq[i0 / 8 + j].y = __fmaf_rn(b, weight, vkq[i0 / 8 + j].y); 135 } 136 } 137 } 138 } 139 } 140 if (warp == 0) { max_shared[lane] = -FLT_MAX / 2.0f; sum_shared[lane] = 0.0f; } 141 __syncthreads(); 142 if (lane == 0) max_shared[warp] = maximum; 143 __syncthreads(); 144 const float global_max = warp_max(max_shared[lane]); 145 const float rescale = expf(maximum - global_max); 146#pragma unroll 147 for (int i = 0; i < 16; ++i) { 148 vkq[i].x = __fmul_rn(vkq[i].x, rescale); 149 vkq[i].y = __fmul_rn(vkq[i].y, rescale); 150 } 151#pragma unroll 152 for (int i0 = 0; i0 < 128; i0 += 32) { 153 const int start = warp * 4 * 256 + (lane / 8) * 256 + 2 * (i0 + (lane % 8) * 4); 154#pragma unroll 155 for (int j = 0; j < 4; ++j) { 156 tile[start + 2 * j] = vkq[i0 / 8 + j].x; 157 tile[start + 2 * j + 1] = vkq[i0 / 8 + j].y; 158 } 159 } 160 sum *= rescale; 161 sum = warp_sum<32>(sum); 162 if (lane == 0) sum_shared[warp] = sum; 163 __syncthreads(); 164 sum = warp_sum<32>(sum_shared[lane]); 165#pragma unroll 166 for (int i0 = 0; i0 < 256; i0 += 128) { 167 float result = 0.0f; 168#pragma unroll 169 for (int w = 0; w < 4; ++w) { 170#pragma unroll 171 for (int group = 0; group < 4; ++group) 172 result += tile[w * 4 * 256 + group * 256 + i0 + tid]; 173 } 174 out[head * 256 + i0 + tid] = result / sum; 175 } 176} 177struct Span { const void* p; std::size_t n, alignment; }; 178void validate_spans(const Span* spans, int count) { 179 for (int i = 0; i < count; ++i) { 180 const auto a = reinterpret_cast<std::uintptr_t>(spans[i].p); 181 if (!a || a % spans[i].alignment || spans[i].n > UINTPTR_MAX - a) 182 throw std::invalid_argument("native FlashAttention requires nonnull aligned bounded spans"); 183 for (int j = 0; j < i; ++j) { 184 const auto b = reinterpret_cast<std::uintptr_t>(spans[j].p); 185 if (a < b + spans[j].n && b < a + spans[i].n) 186 throw std::invalid_argument("native FlashAttention requires disjoint buffers"); 187 } 188 } 189} 190} // namespace 191 192void native_flash_attn_short_step(const float* q, const uint16_t* k, const uint16_t* v, 193 const int32_t* step, int64_t capacity, int max_context, 194 const QsaShapes& shapes, float* output, int32_t* status, 195 const uint16_t* mask, void* stream) { 196 if (!stream || shapes.n_head != 24 || shapes.n_head_kv != 2 || shapes.head_dim != 256 || 197 shapes.idx_block != 4 || shapes.idx_top_k < 256 || capacity < 256 || 198 uint64_t(capacity) > std::numeric_limits<std::size_t>::max() / 1024 || 199 max_context < 1 || max_context > 256) 200 throw std::invalid_argument("native FlashAttention supports only Q24x256/KV2x256, capacity>=256 and context1..256 on an explicit stream"); 201 const std::size_t kv_bytes = std::size_t(capacity) * 1024; 202 const Span spans[] = {{q, 24 * 256 * 4, 4}, {k, kv_bytes, 2}, {v, kv_bytes, 2}, 203 {step, kStepCount * 4, 4}, {output, 24 * 256 * 4, 4}, 204 {status, 4, 4}, {mask, 256 * 2, 2}}; 205 validate_spans(spans, mask ? 7 : 6); 206 attend<<<24, dim3(32, 4), 0, static_cast<cudaStream_t>(stream)>>>(q, reinterpret_cast<const half*>(k), 207 reinterpret_cast<const half*>(v), step, max_context, 256, 0.0625f, output, status, reinterpret_cast<const half*>(mask)); 208 const auto result = cudaGetLastError(); 209 if (result != cudaSuccess) 210 throw std::runtime_error(std::string("native FlashAttention launch: ") + cudaGetErrorString(result)); 211} 212} // namespace strata::kernels