okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Shawn Jacksoncore: the model's geometry is read from its GGUF metadata and checked against the shape the kernels are compiled forf812e9a16

main
5.8 KiB124 linesraw
1// Arithmetic adapted from gated_delta_net.cu at pinned llama.cpp
2// 3cf03257f219afbe7334045ff7c6a06ac68c627d. Only state addressing differs:
3// each warp owns one Strata (head,column) and retains its four rows in registers.
4// Compile with --use_fast_math to match the pinned CUDA implementation.
5//
6// MIT License
7// Copyright (c) 2023-2026 The ggml authors
8//
9// Permission is hereby granted, free of charge, to any person obtaining a copy
10// of this software and associated documentation files (the "Software"), to deal
11// in the Software without restriction, including without limitation the rights
12// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13// copies of the Software, and to permit persons to whom the Software is
14// furnished to do so, subject to the following conditions:
15//
16// The above copyright notice and this permission notice shall be included in all
17// copies or substantial portions of the Software.
18//
19// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25// SOFTWARE.
26#include "strata/kernels/native_gdn.hpp"
27#include "strata/core/geometry.hpp"
28#include <cuda_runtime.h>
29#include <atomic>
30#include <cmath>
31#include <cstddef>
32#include <cstdint>
33#include <stdexcept>
34
35namespace strata::kernels {
36namespace {
37std::atomic<bool> enabled{false};
38constexpr int S = 128;
39static_assert(S == strata::core::kCompiledGeometry.ssm_state_size, "native_gdn is compiled for core/geometry.hpp");
40
41__device__ __forceinline__ float warp_sum(float value) {
42#pragma unroll
43    for (int offset = 16; offset > 0; offset >>= 1)
44        value += __shfl_xor_sync(0xffffffff, value, offset, 32);
45    return value;
46}
47
48__global__ void __launch_bounds__(128, 2)
49step(float* __restrict__ state, const float* __restrict__ q, const float* __restrict__ k,
50     const float* __restrict__ v, const float* __restrict__ gate, const float* __restrict__ beta,
51     float* __restrict__ output, int h_k, int h_v, float scale) {
52    const int head = blockIdx.x;
53    const int lane = threadIdx.x;
54    const int col = blockIdx.z * blockDim.y + threadIdx.y;
55    const int q_head = head % h_k;
56    float s_shard[4], k_reg[4], q_reg[4];
57#pragma unroll
58    for (int r = 0; r < 4; ++r) {
59        const int i = r * 32 + lane;
60        s_shard[r] = state[(size_t(i) * h_v + head) * S + col];
61        k_reg[r] = k[q_head * S + i];
62        q_reg[r] = q[q_head * S + i];
63    }
64    const float g_val = expf(gate[head]);
65    float kv_shard = 0.0f;
66#pragma unroll
67    for (int r = 0; r < 4; ++r) kv_shard += s_shard[r] * k_reg[r];
68    const float kv_col = warp_sum(kv_shard);
69    const float delta_col = (v[head * S + col] - g_val * kv_col) * beta[head];
70    float attn_partial = 0.0f;
71#pragma unroll
72    for (int r = 0; r < 4; ++r) {
73        s_shard[r] = g_val * s_shard[r] + k_reg[r] * delta_col;
74        attn_partial += s_shard[r] * q_reg[r];
75    }
76    const float attn_col = warp_sum(attn_partial);
77    if (lane == 0) output[head * S + col] = attn_col * scale;
78#pragma unroll
79    for (int r = 0; r < 4; ++r) {
80        const int i = r * 32 + lane;
81        state[(size_t(i) * h_v + head) * S + col] = s_shard[r];
82    }
83}
84
85bool valid_span(const void* pointer, size_t bytes) {
86    const auto address = reinterpret_cast<uintptr_t>(pointer);
87    return pointer && address % sizeof(float) == 0 && bytes <= UINTPTR_MAX - address;
88}
89bool overlap(const void* a, size_t an, const void* b, size_t bn) {
90    const auto ap = reinterpret_cast<uintptr_t>(a), bp = reinterpret_cast<uintptr_t>(b);
91    return ap < bp + bn && bp < ap + an;
92}
93}
94
95void native_gdn_set_enabled(bool value) { enabled.store(value, std::memory_order_relaxed); }
96bool native_gdn_enabled() { return enabled.load(std::memory_order_relaxed); }
97
98void native_gdn_step(float* state, const float* q, const float* k, const float* v,
99                     const float* gate, const float* beta, float* output,
100                     const GdnShapes& shape, void* stream) {
101    if (!stream || shape.S != S || shape.h_k <= 0 || shape.h_v <= 0 ||
102        shape.h_v > 65535 || shape.h_v % shape.h_k != 0)
103        throw std::invalid_argument("native GDN requires a stream, S=128 and positive divisible head counts <=65535");
104    const size_t state_bytes = size_t(S) * S * size_t(shape.h_v) * sizeof(float);
105    const size_t qk_bytes = size_t(S) * size_t(shape.h_k) * sizeof(float);
106    const size_t output_bytes = size_t(S) * size_t(shape.h_v) * sizeof(float);
107    const size_t head_bytes = size_t(shape.h_v) * sizeof(float);
108    if (!valid_span(state, state_bytes) || !valid_span(output, output_bytes) ||
109        overlap(state, state_bytes, output, output_bytes))
110        throw std::invalid_argument("native GDN requires aligned, disjoint state and output spans");
111    const void* inputs[] = {q, k, v, gate, beta};
112    const size_t bytes[] = {qk_bytes, qk_bytes, output_bytes, head_bytes, head_bytes};
113    for (int i = 0; i < 5; ++i) {
114        if (!valid_span(inputs[i], bytes[i]) || overlap(state, state_bytes, inputs[i], bytes[i]) ||
115            overlap(output, output_bytes, inputs[i], bytes[i]))
116            throw std::invalid_argument("native GDN requires aligned input spans disjoint from state and output");
117    }
118    const float scale = 1.0f / sqrtf(float(S));
119    step<<<dim3(unsigned(shape.h_v), 1, S / 4), dim3(32, 4), 0, static_cast<cudaStream_t>(stream)>>>(
120        state, q, k, v, gate, beta, output, int(shape.h_k), int(shape.h_v), scale);
121    const auto error = cudaGetLastError();
122    if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error));
123}
124} // namespace strata::kernels