okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
4dad59ab3
main
1// Arithmetic adapted from the MIT-licensed pinned ggml CUDA 2// moe-weighted-reduction.cu at 3cf03257f219afbe7334045ff7c6a06ac68c627d. 3// MIT License 4// Copyright (c) 2023-2026 The ggml authors 5// 6// Permission is hereby granted, free of charge, to any person obtaining a copy 7// of this software and associated documentation files (the "Software"), to deal 8// in the Software without restriction, including without limitation the rights 9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10// copies of the Software, and to permit persons to whom the Software is 11// furnished to do so, subject to the following conditions: 12// 13// The above copyright notice and this permission notice shall be included in all 14// copies or substantial portions of the Software. 15// 16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22// SOFTWARE. 23#include "strata/kernels/native_moe.hpp" 24#include "strata/kernels/verify_kernels.hpp" 25#include "strata/core/geometry.hpp" 26#include <cuda_runtime.h> 27#include <atomic> 28#include <cstddef> 29#include <cstdint> 30#include <limits> 31#include <stdexcept> 32 33namespace strata::kernels { 34namespace { 35constexpr int KU = strata::core::kCompiledGeometry.n_expert_used; // 10 for Flash-Next: the combine kernels below are written for exactly this many ranks (<= 16: the hit mask is an int) 36static_assert(KU >= 1 && KU <= 16, "native_moe: top-k must be 1..16"); 37std::atomic<bool> enabled{false}; 38// GATED (S26 STRATA_LFUSE): `shared` is the shared expert's unscaled output and sg its raw gate logit per token; 39// the row is scaled here as shared_expert_multi did (native_scalar_sigmoid_multi_kernel's expression, then one 40// rounded multiply = scale_rows_kernel's `out *= g`), then added as before 41template<bool ZADD = false, bool GATED = false> 42__global__ void combine(const float* __restrict__ parts, const float* __restrict__ weights, 43 const float* __restrict__ shared, float* __restrict__ output, 44 int64_t n_embd, int k, const float* __restrict__ sg = nullptr) { 45 // blockIdx.y = the token of a multi-token launch (0 for the single one) 46 const int64_t tk = blockIdx.y; 47 parts += tk * k * n_embd; weights += tk * k; if (shared) shared += tk * n_embd; output += tk * n_embd; 48 const int64_t col = int64_t(blockIdx.x) * blockDim.x + threadIdx.x; 49 if (col >= n_embd) return; 50 // ZADD: a part is 0.0f + hit (the zeroed row plus moe_hit_add of the verify window), rounded as that add 51 float p0 = parts[col]; 52 if (ZADD) p0 = 0.0f + p0; 53 float sum = p0 * weights[0]; 54 for (int expert = 1; expert < k; ++expert) { 55 float p = parts[int64_t(expert) * n_embd + col]; 56 if (ZADD) p = 0.0f + p; 57 sum += p * weights[expert]; 58 } 59 if constexpr (GATED) { 60 // contraction off in this block only: the product is rounded on its own (scale_rows' store), then added 61#pragma clang fp contract(off) 62 const float g = __fdividef(1.0f, 1.0f + __expf(-sg[tk])); 63 const float sh = shared[col] * g; 64 sum += sh; 65 } else { 66 if (shared) sum += shared[col]; 67 } 68 output[col] = sum; 69} 70__global__ void combine_k10_vec4(const float4* __restrict__ parts4, const float* __restrict__ weights, 71 const float4* __restrict__ shared4, float4* __restrict__ output4, 72 int64_t n4) { 73 const int64_t tk = blockIdx.y; 74 parts4 += tk * KU * n4; 75 weights += tk * KU; 76 shared4 += tk * n4; 77 output4 += tk * n4; 78 const int64_t c4 = int64_t(blockIdx.x) * blockDim.x + threadIdx.x; 79 if (c4 >= n4) return; 80 const float w0 = __ldg(weights + 0); 81 const float4 p0 = parts4[c4]; 82 float4 sum = make_float4(p0.x * w0, p0.y * w0, p0.z * w0, p0.w * w0); 83#pragma unroll 84 for (int expert = 1; expert < KU; ++expert) { 85 const float w = __ldg(weights + expert); 86 const float4 p = parts4[int64_t(expert) * n4 + c4]; 87 // the documented contract spelled out: the first product rounded, then one FMA per expert in order. Left to the 88 // compiler's contraction, a build may fuse a different product (gfx1151: the float4 kernel then differed from the 89 // scalar one, native_multi_parity) 90 sum.x = fmaf(p.x, w, sum.x); 91 sum.y = fmaf(p.y, w, sum.y); 92 sum.z = fmaf(p.z, w, sum.z); 93 sum.w = fmaf(p.w, w, sum.w); 94 } 95 const float4 sh = shared4[c4]; 96 sum.x += sh.x; 97 sum.y += sh.y; 98 sum.z += sh.z; 99 sum.w += sh.w; 100 output4[c4] = sum; 101} 102__global__ void combine_k10_vec4_hits(const float4* __restrict__ parts4, const float4* __restrict__ hits4, 103 const int32_t* __restrict__ dst, const int32_t* __restrict__ count, 104 const float* __restrict__ weights, const float4* __restrict__ shared4, 105 float4* __restrict__ output4, int64_t n4) { 106 const int64_t tk = blockIdx.y; 107 __shared__ int hit_mask; 108 if (threadIdx.x == 0) hit_mask = 0; 109 __syncthreads(); 110 const int nh = *count; 111 for (int h = threadIdx.x; h < nh; h += blockDim.x) { 112 const int r = dst[h]; 113 if (r / KU == (int) tk) atomicOr(&hit_mask, 1 << (r % KU)); 114 } 115 __syncthreads(); 116 const int mask = hit_mask; 117 parts4 += tk * KU * n4; 118 hits4 += tk * KU * n4; 119 weights += tk * KU; 120 shared4 += tk * n4; 121 output4 += tk * n4; 122 const int64_t c4 = int64_t(blockIdx.x) * blockDim.x + threadIdx.x; 123 if (c4 >= n4) return; 124 const float w0 = __ldg(weights + 0); 125 float4 p0 = parts4[c4]; 126 if (mask & 1) { const float4 hh = hits4[c4]; p0.x += hh.x; p0.y += hh.y; p0.z += hh.z; p0.w += hh.w; } 127 float4 sum = make_float4(p0.x * w0, p0.y * w0, p0.z * w0, p0.w * w0); 128#pragma unroll 129 for (int expert = 1; expert < KU; ++expert) { 130 const float w = __ldg(weights + expert); 131 float4 p = parts4[int64_t(expert) * n4 + c4]; 132 if ((mask >> expert) & 1) { const float4 hh = hits4[int64_t(expert) * n4 + c4]; p.x += hh.x; p.y += hh.y; p.z += hh.z; p.w += hh.w; } 133 sum.x = fmaf(p.x, w, sum.x); 134 sum.y = fmaf(p.y, w, sum.y); 135 sum.z = fmaf(p.z, w, sum.z); 136 sum.w = fmaf(p.w, w, sum.w); 137 } 138 const float4 sh = shared4[c4]; 139 sum.x += sh.x; 140 sum.y += sh.y; 141 sum.z += sh.z; 142 sum.w += sh.w; 143 output4[c4] = sum; 144} 145bool valid_span(const void* p, size_t bytes) { 146 const auto address = reinterpret_cast<uintptr_t>(p); 147 return p && address % alignof(float) == 0 && bytes <= UINTPTR_MAX - address; 148} 149bool overlap(const void* a, size_t an, const void* b, size_t bn) { 150 const auto ap = reinterpret_cast<uintptr_t>(a), bp = reinterpret_cast<uintptr_t>(b); 151 return ap < bp + bn && bp < ap + an; 152} 153} 154void native_moe_combine_set_enabled(bool value) { enabled.store(value, std::memory_order_relaxed); } 155bool native_moe_combine_enabled() { return enabled.load(std::memory_order_relaxed); } 156void native_moe_combine(const float* parts, const float* weights, const float* shared, 157 float* output, int64_t n_embd, int64_t k, void* stream) { 158 if (!stream || n_embd <= 0 || n_embd > std::numeric_limits<int>::max() || k < 1 || k > 15) 159 throw std::invalid_argument("native MoE combine requires a stream, positive width and 1..15 experts"); 160 const size_t row_bytes = size_t(n_embd) * sizeof(float); 161 const size_t part_bytes = row_bytes * size_t(k), weight_bytes = size_t(k) * sizeof(float); 162 if (!valid_span(parts, part_bytes) || !valid_span(weights, weight_bytes) || !valid_span(output, row_bytes) 163 || (shared && !valid_span(shared, row_bytes)) 164 || overlap(output, row_bytes, parts, part_bytes) 165 || overlap(output, row_bytes, weights, weight_bytes) 166 || (shared && overlap(output, row_bytes, shared, row_bytes))) 167 throw std::invalid_argument("native MoE combine requires aligned spans and disjoint output"); 168 if (k == KU && shared != nullptr && (n_embd & 3) == 0 && 169 (((uintptr_t) parts | (uintptr_t) shared | (uintptr_t) output) & 15u) == 0) { 170 const int64_t n4 = n_embd >> 2; 171 combine_k10_vec4<<<unsigned((n4 + 127) / 128), 128, 0, static_cast<cudaStream_t>(stream)>>>( 172 reinterpret_cast<const float4*>(parts), weights, reinterpret_cast<const float4*>(shared), 173 reinterpret_cast<float4*>(output), n4); 174 } else { 175 combine<<<unsigned((n_embd + 255) / 256), 256, 0, static_cast<cudaStream_t>(stream)>>>( 176 parts, weights, shared, output, n_embd, int(k)); 177 } 178 const auto error = cudaGetLastError(); 179 if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); 180} 181bool native_moe_combine_hits_supported(const float* parts, const float* shared, const float* output, int64_t n_embd, int64_t k, int n_tok) { 182 return k == KU && shared != nullptr && n_tok >= 1 && n_tok <= kVerifyMaxT && n_embd > 0 && (n_embd & 3) == 0 && 183 (((uintptr_t) parts | (uintptr_t) shared | (uintptr_t) output) & 15u) == 0; 184} 185void native_moe_combine_multi_hits_added(const float* parts, const float* hits, const int32_t* dst, const int32_t* count, 186 const float* weights, const float* shared, float* output, int64_t n_embd, int64_t k, 187 int n_tok, void* stream) { 188 if (!stream || !native_moe_combine_hits_supported(parts, shared, output, n_embd, k, n_tok) || ((uintptr_t) hits & 15u) != 0) 189 throw std::invalid_argument("native MoE combine (hits added) requires k = 10, aligned spans, 1..8 tokens (16 in a wide build)"); 190 const int64_t n4 = n_embd >> 2; 191 combine_k10_vec4_hits<<<dim3(unsigned((n4 + 127) / 128), (unsigned) n_tok), 128, 0, static_cast<cudaStream_t>(stream)>>>( 192 reinterpret_cast<const float4*>(parts), reinterpret_cast<const float4*>(hits), dst, count, weights, 193 reinterpret_cast<const float4*>(shared), reinterpret_cast<float4*>(output), n4); 194 const auto error = cudaGetLastError(); 195 if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); 196} 197void native_moe_combine_multi(const float* parts, const float* weights, const float* shared, float* output, 198 int64_t n_embd, int64_t k, int n_tok, void* stream) { 199 if (!stream || n_embd <= 0 || k < 1 || k > 15 || n_tok < 1) 200 throw std::invalid_argument("native MoE combine (multi) requires a stream, width, 1..15 experts, tokens"); 201 if (k == KU && shared != nullptr && (n_embd & 3) == 0 && 202 (((uintptr_t) parts | (uintptr_t) shared | (uintptr_t) output) & 15u) == 0) { 203 const int64_t n4 = n_embd >> 2; 204 combine_k10_vec4<<<dim3(unsigned((n4 + 127) / 128), (unsigned) n_tok), 128, 0, static_cast<cudaStream_t>(stream)>>>( 205 reinterpret_cast<const float4*>(parts), weights, reinterpret_cast<const float4*>(shared), 206 reinterpret_cast<float4*>(output), n4); 207 } else { 208 combine<<<dim3(unsigned((n_embd + 255) / 256), (unsigned) n_tok), 256, 0, static_cast<cudaStream_t>(stream)>>>( 209 parts, weights, shared, output, n_embd, int(k)); 210 } 211 const auto error = cudaGetLastError(); 212 if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); 213} 214void native_moe_combine_multi_hits_gated(const float* hits, const float* weights, const float* shared, 215 const float* shared_gate, float* output, int64_t n_embd, int64_t k, int n_tok, 216 void* stream) { 217 if (!stream || n_embd <= 0 || k < 1 || k > 15 || n_tok < 1 || !shared || !shared_gate) 218 throw std::invalid_argument("native MoE combine (hits, gated) requires a stream, width, 1..15 experts, tokens"); 219 combine<true, true><<<dim3(unsigned((n_embd + 255) / 256), (unsigned) n_tok), 256, 0, static_cast<cudaStream_t>(stream)>>>( 220 hits, weights, shared, output, n_embd, int(k), shared_gate); 221 const auto error = cudaGetLastError(); 222 if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); 223} 224void native_moe_combine_multi_hits(const float* hits, const float* weights, const float* shared, float* output, 225 int64_t n_embd, int64_t k, int n_tok, void* stream) { 226 if (!stream || n_embd <= 0 || k < 1 || k > 15 || n_tok < 1) 227 throw std::invalid_argument("native MoE combine (hits) requires a stream, width, 1..15 experts, tokens"); 228 combine<true><<<dim3(unsigned((n_embd + 255) / 256), (unsigned) n_tok), 256, 0, static_cast<cudaStream_t>(stream)>>>( 229 hits, weights, shared, output, n_embd, int(k)); 230 const auto error = cudaGetLastError(); 231 if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); 232} 233}