okami.mom/strata

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

Niko1221Merge f-037-arc (5eaee81a4)86bed1c92

main
7.5 KiB170 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#define DPCT_PROFILING_ENABLED
27#include <sycl/sycl.hpp>
28#include "strata/kprof.hpp"
29#include "strata/core/geometry.hpp"
30#include <dpct/dpct.hpp>
31#include "strata/sycl_queue.hpp"
32#include "strata/kernels/native_gdn.hpp"
33#include <atomic>
34#include <cmath>
35#include <cstddef>
36#include <cstdint>
37#include <stdexcept>
38
39namespace strata::kernels {
40namespace {
41std::atomic<bool> enabled{false};
42constexpr int S = 128;
43static_assert(S == strata::core::kCompiledGeometry.ssm_state_size, "native_gdn is compiled for core/geometry.hpp");
44
45__dpct_inline__ float warp_sum(float value) {
46#pragma unroll
47    for (int offset = 16; offset > 0; offset >>= 1)
48        /*
49        DPCT1108: '__shfl_xor_sync' was migrated with the experimental
50        feature masked sub_group function which may not be supported by all
51        compilers or runtimes. You may need to adjust the code.
52        */
53        value += dpct::experimental::permute_sub_group_by_xor(
54            0xffffffff, sycl::ext::oneapi::this_work_item::get_sub_group(),
55            value, offset);
56    return value;
57}
58
59__dpct_inline__ void
60step(float *__restrict__ state, const float *__restrict__ q,
61     const float *__restrict__ k, const float *__restrict__ v,
62     const float *__restrict__ gate, const float *__restrict__ beta,
63     float *__restrict__ output, int h_k, int h_v, float scale) {
64    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
65    const int head = item_ct1.get_group(2);
66    const int lane = item_ct1.get_local_id(2);
67    const int col = item_ct1.get_group(0) * item_ct1.get_local_range(1) +
68                    item_ct1.get_local_id(1);
69    const int q_head = head % h_k;
70    float s_shard[4], k_reg[4], q_reg[4];
71#pragma unroll
72    for (int r = 0; r < 4; ++r) {
73        const int i = r * 32 + lane;
74        s_shard[r] = state[(size_t(i) * h_v + head) * S + col];
75        k_reg[r] = k[q_head * S + i];
76        q_reg[r] = q[q_head * S + i];
77    }
78    const float g_val = sycl::native::exp(gate[head]);
79    float kv_shard = 0.0f;
80#pragma unroll
81    for (int r = 0; r < 4; ++r) kv_shard += s_shard[r] * k_reg[r];
82    const float kv_col = warp_sum(kv_shard);
83    const float delta_col = (v[head * S + col] - g_val * kv_col) * beta[head];
84    float attn_partial = 0.0f;
85#pragma unroll
86    for (int r = 0; r < 4; ++r) {
87        s_shard[r] = g_val * s_shard[r] + k_reg[r] * delta_col;
88        attn_partial += s_shard[r] * q_reg[r];
89    }
90    const float attn_col = warp_sum(attn_partial);
91    if (lane == 0) output[head * S + col] = attn_col * scale;
92#pragma unroll
93    for (int r = 0; r < 4; ++r) {
94        const int i = r * 32 + lane;
95        state[(size_t(i) * h_v + head) * S + col] = s_shard[r];
96    }
97}
98
99bool valid_span(const void* pointer, size_t bytes) {
100    const auto address = reinterpret_cast<uintptr_t>(pointer);
101    return pointer && address % sizeof(float) == 0 && bytes <= UINTPTR_MAX - address;
102}
103bool overlap(const void* a, size_t an, const void* b, size_t bn) {
104    const auto ap = reinterpret_cast<uintptr_t>(a), bp = reinterpret_cast<uintptr_t>(b);
105    return ap < bp + bn && bp < ap + an;
106}
107}
108
109void native_gdn_set_enabled(bool value) { enabled.store(value, std::memory_order_relaxed); }
110bool native_gdn_enabled() { return enabled.load(std::memory_order_relaxed); }
111
112void native_gdn_step(float* state, const float* q, const float* k, const float* v,
113                     const float* gate, const float* beta, float* output,
114                     const GdnShapes& shape, void* stream) {
115    if (!stream || shape.S != S || shape.h_k <= 0 || shape.h_v <= 0 ||
116        shape.h_v > 65535 || shape.h_v % shape.h_k != 0)
117        throw std::invalid_argument("native GDN requires a stream, S=128 and positive divisible head counts <=65535");
118    const size_t state_bytes = size_t(S) * S * size_t(shape.h_v) * sizeof(float);
119    const size_t qk_bytes = size_t(S) * size_t(shape.h_k) * sizeof(float);
120    const size_t output_bytes = size_t(S) * size_t(shape.h_v) * sizeof(float);
121    const size_t head_bytes = size_t(shape.h_v) * sizeof(float);
122    if (!valid_span(state, state_bytes) || !valid_span(output, output_bytes) ||
123        overlap(state, state_bytes, output, output_bytes))
124        throw std::invalid_argument("native GDN requires aligned, disjoint state and output spans");
125    const void* inputs[] = {q, k, v, gate, beta};
126    const size_t bytes[] = {qk_bytes, qk_bytes, output_bytes, head_bytes, head_bytes};
127    for (int i = 0; i < 5; ++i) {
128        if (!valid_span(inputs[i], bytes[i]) || overlap(state, state_bytes, inputs[i], bytes[i]) ||
129            overlap(output, output_bytes, inputs[i], bytes[i]))
130            throw std::invalid_argument("native GDN requires aligned input spans disjoint from state and output");
131    }
132    const float scale = 1.0f / sqrtf(float(S));
133    {
134        auto exp_props = sycl::ext::oneapi::experimental::properties{
135            sycl::ext::oneapi::experimental::use_root_sync};
136
137        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
138            ->template parallel_for<dpct_kernel_name<class step_134598>>(
139                sycl::nd_range<3>(sycl::range(S / 4, 1, unsigned(shape.h_v)) *
140                                      sycl::range(1, 4, 32),
141                                  sycl::range(1, 4, 32)),
142                exp_props,
143                [=](sycl::nd_item<3> item_ct1)
144                    [[sycl::reqd_sub_group_size(32)]] {
145                        step(state, q, k, v, gate, beta, output, int(shape.h_k),
146                             int(shape.h_v), scale);
147                    });
148    }
149    /*
150    DPCT1010: SYCL uses exceptions to report errors and does not use the
151    error codes. The cudaGetLastError function call was replaced with 0. You
152    need to rewrite this code.
153    */
154    const auto error = 0;
155    /*
156    DPCT1009: SYCL reports errors using exceptions and does not use error
157    codes. Please replace the "get_error_string_dummy(...)" with a real
158    error-handling function.
159    */
160    /*
161    DPCT1001: The statement could not be removed.
162    */
163    /*
164    DPCT1000: Error handling if-stmt was detected but could not be
165    rewritten.
166    */
167    if (error !=
168        0) throw std::runtime_error(dpct::get_error_string_dummy(error));
169}
170} // namespace strata::kernels