okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
bc6b6f87a
main
1// Adapted from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d: 2// ggml/src/ggml-cuda/{norm.cu,common.cuh,unary.cu}. 3// 4// MIT License 5// Copyright (c) 2023-2026 The ggml authors 6// 7// Permission is hereby granted, free of charge, to any person obtaining a copy 8// of this software and associated documentation files (the "Software"), to deal 9// in the Software without restriction, including without limitation the rights 10// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 11// copies of the Software, and to permit persons to whom the Software is 12// furnished to do so, subject to the following conditions: 13// 14// The above copyright notice and this permission notice shall be included in all 15// copies or substantial portions of the Software. 16// 17// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 20// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 21// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 23// SOFTWARE. 24 25#include "strata/kernels/native_qsa.hpp" 26#include <cuda_runtime.h> 27#include <atomic> 28#include <cmath> 29#include <cstddef> 30#include <cstdint> 31#include <limits> 32#include <stdexcept> 33#include <string> 34 35namespace strata::kernels { 36namespace { 37std::atomic<bool> enabled{false}; 38__device__ __forceinline__ float warp_sum(float value) { 39#pragma unroll 40 for (int offset = 16; offset; offset >>= 1) 41 value += __shfl_xor_sync(0xffffffffu, value, offset, 32); 42 return value; 43} 44template<int BlockSize> 45__global__ void norm(const float* input, const float* __restrict__ gamma, float* output, 46 int n_cols, float epsilon) { 47 const int tid = threadIdx.x; 48 const std::size_t row_offset = std::size_t(blockIdx.x) * n_cols; 49 input += row_offset; output += row_offset; 50 float partial = 0.0f; 51 for (std::size_t col = tid; col < std::size_t(n_cols); col += BlockSize) { 52 const float x = input[col]; 53 partial += x * x; 54 } 55 __shared__ float sums[32]; 56 partial = warp_sum(partial); 57 const int lane = tid % 32; 58 if (lane == 0) sums[tid / 32] = partial; 59 // All reads of input for the reduction precede this barrier. Afterwards, 60 // each thread reads/writes only its own elements, allowing exact in-place use. 61 __syncthreads(); 62 partial = lane < BlockSize / 32 ? sums[lane] : 0.0f; 63 partial = warp_sum(partial); 64 const float mean = partial / n_cols; 65 const float scale = rsqrtf(mean + epsilon); 66 for (std::size_t col = tid; col < std::size_t(n_cols); col += BlockSize) 67 output[col] = scale * input[col] * gamma[col]; 68} 69// As norm, with gamma[groups * n_cols]: row r is group r % groups and reads its own slice of gamma. 70template<int BlockSize> 71__global__ void norm_grouped(const float* input, const float* __restrict__ gamma, float* output, 72 int n_cols, int groups, float epsilon) { 73 const int tid = threadIdx.x; 74 const std::size_t row_offset = std::size_t(blockIdx.x) * n_cols; 75 input += row_offset; output += row_offset; 76 gamma += std::size_t(blockIdx.x % unsigned(groups)) * n_cols; 77 float partial = 0.0f; 78 for (std::size_t col = tid; col < std::size_t(n_cols); col += BlockSize) { 79 const float x = input[col]; 80 partial += x * x; 81 } 82 __shared__ float sums[32]; 83 partial = warp_sum(partial); 84 const int lane = tid % 32; 85 if (lane == 0) sums[tid / 32] = partial; 86 __syncthreads(); 87 partial = lane < BlockSize / 32 ? sums[lane] : 0.0f; 88 partial = warp_sum(partial); 89 const float mean = partial / n_cols; 90 const float scale = rsqrtf(mean + epsilon); 91 for (std::size_t col = tid; col < std::size_t(n_cols); col += BlockSize) 92 output[col] = scale * input[col] * gamma[col]; 93} 94__global__ void gate(const float* attn, const float* __restrict__ q_full, float* output, 95 int n_head, int head_dim) { 96 const std::size_t i = std::size_t(blockIdx.x) * blockDim.x + threadIdx.x; 97 if (i >= std::size_t(n_head) * head_dim) return; 98 const std::size_t head = i / head_dim, channel = i % head_dim; 99 const float raw = q_full[head * 2 * head_dim + head_dim + channel]; 100 const float sigmoid = 1.0f / (1.0f + expf(-raw)); 101 output[i] = attn[i] * sigmoid; 102} 103std::size_t elements(int cols, int rows) { 104 if (cols <= 0 || rows <= 0 || std::uint64_t(cols) * rows > std::uint64_t(std::numeric_limits<int>::max())) 105 throw std::invalid_argument("native QSA requires positive bounded dimensions"); 106 return std::size_t(cols) * rows; 107} 108bool valid(const void* ptr, std::size_t bytes) { 109 const auto address = reinterpret_cast<std::uintptr_t>(ptr); 110 return ptr && address % 4 == 0 && bytes <= UINTPTR_MAX - address; 111} 112bool overlap(const void* a, std::size_t an, const void* b, std::size_t bn) { 113 const auto ap = reinterpret_cast<std::uintptr_t>(a), bp = reinterpret_cast<std::uintptr_t>(b); 114 return ap < bp + bn && bp < ap + an; 115} 116void buffers(const float* input, std::size_t in_bytes, const float* weight, std::size_t weight_bytes, 117 float* output, void* stream) { 118 if (!stream || !valid(input, in_bytes) || !valid(weight, weight_bytes) || !valid(output, in_bytes) || 119 overlap(input, in_bytes, weight, weight_bytes) || overlap(output, in_bytes, weight, weight_bytes) || 120 (input != output && overlap(input, in_bytes, output, in_bytes))) 121 throw std::invalid_argument("native QSA requires a stream, aligned spans, and disjoint buffers or exact input/output alias"); 122} 123void check_launch() { 124 const auto result = cudaGetLastError(); 125 if (result != cudaSuccess) 126 throw std::runtime_error(std::string("native QSA launch: ") + cudaGetErrorString(result)); 127} 128} // namespace 129 130void native_qsa_set_enabled(bool value) { enabled.store(value, std::memory_order_relaxed); } 131bool native_qsa_enabled() { return enabled.load(std::memory_order_relaxed); } 132 133void native_qsa_rms_norm_weighted(const float* input, const float* gamma, float* output, 134 int n_cols, int n_rows, float epsilon, void* stream) { 135 const auto count = elements(n_cols, n_rows); 136 if (!std::isfinite(epsilon) || epsilon < 0.0f) 137 throw std::invalid_argument("native QSA requires finite nonnegative epsilon"); 138 buffers(input, count * 4, gamma, std::size_t(n_cols) * 4, output, stream); 139 if (n_cols < 1024) 140 norm<256><<<unsigned(n_rows), 256, 0, static_cast<cudaStream_t>(stream)>>>(input, gamma, output, n_cols, epsilon); 141 else 142 norm<1024><<<unsigned(n_rows), 1024, 0, static_cast<cudaStream_t>(stream)>>>(input, gamma, output, n_cols, epsilon); 143 check_launch(); 144} 145void native_qsa_rms_norm_grouped(const float* input, const float* gamma, float* output, 146 int n_cols, int groups, int n_rows, float epsilon, void* stream) { 147 if (groups < 1) throw std::invalid_argument("native QSA requires positive bounded dimensions"); 148 const auto count = elements(n_cols, n_rows); 149 if (!std::isfinite(epsilon) || epsilon < 0.0f) 150 throw std::invalid_argument("native QSA requires finite nonnegative epsilon"); 151 buffers(input, count * 4, gamma, std::size_t(n_cols) * groups * 4, output, stream); 152 if (n_cols < 1024) 153 norm_grouped<256><<<unsigned(n_rows), 256, 0, static_cast<cudaStream_t>(stream)>>>(input, gamma, output, n_cols, 154 groups, epsilon); 155 else 156 norm_grouped<1024><<<unsigned(n_rows), 1024, 0, static_cast<cudaStream_t>(stream)>>>(input, gamma, output, n_cols, 157 groups, epsilon); 158 check_launch(); 159} 160void native_qsa_gate_apply(const float* attn, const float* q_full, float* output, 161 int n_head, int head_dim, void* stream) { 162 const auto count = elements(head_dim, n_head); 163 buffers(attn, count * 4, q_full, count * 8, output, stream); 164 gate<<<unsigned((count + 255) / 256), 256, 0, static_cast<cudaStream_t>(stream)>>>(attn, q_full, output, n_head, head_dim); 165 check_launch(); 166} 167} // namespace strata::kernels