okami.mom/strata

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

Niko1221Merge branch 'f-132-pr' into rel-0.1.32b0abdeb44

main
9.1 KiB199 linesraw
1// Adapted from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d:
2// ggml/src/ggml-cuda/{norm.cu,common.cuh,unary.cu,unary.cuh,ssm-conv.cu,scale.cu}.
3// Compile with --use_fast_math, as the pinned backend does.
4//
5// MIT License
6// Copyright (c) 2023-2026 The ggml authors
7//
8// Permission is hereby granted, free of charge, to any person obtaining a copy
9// of this software and associated documentation files (the "Software"), to deal
10// in the Software without restriction, including without limitation the rights
11// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12// copies of the Software, and to permit persons to whom the Software is
13// furnished to do so, subject to the following conditions:
14//
15// The above copyright notice and this permission notice shall be included in all
16// copies or substantial portions of the Software.
17//
18// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24// SOFTWARE.
25#include "strata/kernels/native_gdn_preprocess.hpp"
26#include <cuda_runtime.h>
27#include <cmath>
28#include <cstddef>
29#include <cstdint>
30#include <initializer_list>
31#include <stdexcept>
32
33namespace strata::kernels {
34namespace {
35constexpr int S = 128;
36
37__device__ __forceinline__ float warp_sum(float value) {
38#pragma unroll
39    for (int offset = 16; offset > 0; offset >>= 1)
40        value += __shfl_xor_sync(0xffffffffu, value, offset, 32);
41    return value;
42}
43__device__ __forceinline__ float norm_sum(float value, float* sums) {
44    const int lane = threadIdx.x % 32;
45    value = warp_sum(value);
46    if (lane == 0) sums[threadIdx.x / 32] = value;
47    __syncthreads();
48    value = lane < 8 ? sums[lane] : 0.0f;
49    return warp_sum(value);
50}
51__device__ __forceinline__ float sigmoid(float value) { return 1.0f / (1.0f + expf(-value)); }
52
53__global__ void conv_silu(float* __restrict__ history, const float* __restrict__ input,
54                           const float* __restrict__ weights, float* __restrict__ raw_output,
55                           float* __restrict__ silu_output, int channels) {
56    const int c = blockIdx.x * blockDim.x + threadIdx.x;
57    if (c >= channels) return;
58    float values[4] = {history[c * 3], history[c * 3 + 1], history[c * 3 + 2], input[c]};
59    float sum = 0.0f;
60#pragma unroll
61    for (int tap = 0; tap < 4; ++tap) sum += values[tap] * weights[c * 4 + tap];
62    // The native SSM kernel adds its zero bias even when there is no bias input.
63    sum = __fadd_rn(sum, 0.0f);
64    raw_output[c] = sum;
65    silu_output[c] = sum / (1.0f + expf(-sum));
66#pragma unroll
67    for (int tap = 0; tap < 3; ++tap) history[c * 3 + tap] = values[tap + 1];
68}
69
70__global__ void l2_norm(float* input, float epsilon, float scale_after) {
71    const int col = threadIdx.x;
72    input += size_t(blockIdx.x) * S;
73    const float value = col < S ? input[col] : 0.0f;
74    float partial = 0.0f;
75    if (col < S) partial += value * value;
76    __shared__ float sums[32];
77    partial = norm_sum(partial, sums);
78    const float scale = rsqrtf(partial / S + epsilon);
79    if (col < S) {
80        // Preserve the FP32 store boundary between RMSNorm and ggml_scale.
81        const float normalized = __fmul_rn(scale, value);
82        input[col] = __fmaf_rn(normalized, scale_after, 0.0f);
83    }
84}
85
86__global__ void beta_sigmoid(float* beta, int count) {
87    const int i = blockIdx.x * blockDim.x + threadIdx.x;
88    if (i < count) beta[i] = sigmoid(beta[i]);
89}
90__global__ void gate_softplus(const float* __restrict__ alpha, const float* __restrict__ dt,
91                               const float* __restrict__ ssm_a, float* __restrict__ gate, int count) {
92    const int i = blockIdx.x * blockDim.x + threadIdx.x;
93    if (i >= count) return;
94    const float value = __fadd_rn(alpha[i], dt[i]);
95    const float softplus = value > 20.0f ? value : log1pf(expf(value));   // 1 + e^v loses e^v below ~1e-7
96    gate[i] = softplus * ssm_a[i];
97}
98
99__global__ void out_norm(const float* __restrict__ input, const float* __restrict__ z,
100                          const float* __restrict__ gamma, float* __restrict__ output, float epsilon) {
101    const int col = threadIdx.x;
102    const size_t offset = size_t(blockIdx.x) * S;
103    const float value = col < S ? input[offset + col] : 0.0f;
104    float partial = 0.0f;
105    if (col < S) partial += value * value;
106    __shared__ float sums[32];
107    partial = norm_sum(partial, sums);
108    const float scale = rsqrtf(partial / S + epsilon);
109    if (col < S) {
110        // RMSNorm+gamma is one pinned fused operator, followed by sigmoid*mul.
111        const float weighted = __fmul_rn(__fmul_rn(scale, value), gamma[col]);
112        output[offset + col] = weighted * sigmoid(z[offset + col]);
113    }
114}
115
116struct Span { const void* pointer; size_t bytes; };
117void valid(Span span) {
118    const auto address = reinterpret_cast<uintptr_t>(span.pointer);
119    if (!span.pointer || address % sizeof(float) || span.bytes > UINTPTR_MAX - address)
120        throw std::invalid_argument("native GDN preprocessing requires aligned nonnull valid spans");
121}
122void disjoint(Span a, Span b) {
123    const auto ap = reinterpret_cast<uintptr_t>(a.pointer), bp = reinterpret_cast<uintptr_t>(b.pointer);
124    if (ap < bp + b.bytes && bp < ap + a.bytes)
125        throw std::invalid_argument("native GDN preprocessing requires disjoint writable spans");
126}
127void count_and_stream(int64_t count, void* stream) {
128    if (!stream || count <= 0 || count > 65535)
129        throw std::invalid_argument("native GDN preprocessing requires a stream and count in [1,65535]");
130}
131void norm_geometry(int64_t rows, int64_t cols, float epsilon, void* stream) {
132    count_and_stream(rows, stream);
133    if (cols != S || !std::isfinite(epsilon) || epsilon < 0.0f)
134        throw std::invalid_argument("native GDN norm requires width 128 and finite nonnegative epsilon");
135}
136void check_launch() {
137    const auto error = cudaGetLastError();
138    if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error));
139}
140}
141
142void native_gdn_conv_silu(float* history, const float* input, const float* weights,
143                          float* raw_output, float* silu_output, int64_t channels,
144                          int64_t d_conv, void* stream) {
145    count_and_stream(channels, stream);
146    if (d_conv != 4) throw std::invalid_argument("native GDN convolution requires four taps");
147    const size_t bytes = size_t(channels) * sizeof(float);
148    const Span writable[] = {{history, 3 * bytes}, {raw_output, bytes}, {silu_output, bytes}};
149    const Span inputs[] = {{input, bytes}, {weights, 4 * bytes}};
150    for (auto span : writable) valid(span);
151    for (auto span : inputs) valid(span);
152    for (int i = 0; i < 3; ++i) {
153        for (int j = 0; j < i; ++j) disjoint(writable[i], writable[j]);
154        for (auto span : inputs) disjoint(writable[i], span);
155    }
156    conv_silu<<<unsigned((channels + 255) / 256), 256, 0, static_cast<cudaStream_t>(stream)>>>(
157        history, input, weights, raw_output, silu_output, int(channels));
158    check_launch();
159}
160void native_gdn_l2_norm(float* input, int64_t rows, int64_t cols, float epsilon, void* stream) {
161    norm_geometry(rows, cols, epsilon, stream);
162    valid({input, size_t(rows) * S * sizeof(float)});
163    l2_norm<<<unsigned(rows), 256, 0, static_cast<cudaStream_t>(stream)>>>(input, epsilon / S, 1.0f / sqrtf(float(S)));
164    check_launch();
165}
166void native_gdn_beta_gate(float* beta, int64_t heads, void* stream) {
167    count_and_stream(heads, stream);
168    valid({beta, size_t(heads) * sizeof(float)});
169    beta_sigmoid<<<unsigned((heads + 255) / 256), 256, 0, static_cast<cudaStream_t>(stream)>>>(beta, int(heads));
170    check_launch();
171}
172void native_gdn_gate(const float* alpha, const float* dt, const float* ssm_a,
173                     float* gate, int64_t heads, void* stream) {
174    count_and_stream(heads, stream);
175    const size_t bytes = size_t(heads) * sizeof(float);
176    const Span output{gate, bytes};
177    valid(output);
178    for (auto input : {Span{alpha, bytes}, Span{dt, bytes}, Span{ssm_a, bytes}}) {
179        valid(input);
180        disjoint(output, input);
181    }
182    gate_softplus<<<unsigned((heads + 255) / 256), 256, 0, static_cast<cudaStream_t>(stream)>>>(alpha, dt, ssm_a, gate, int(heads));
183    check_launch();
184}
185void native_gdn_out_norm(const float* output, const float* z, const float* gamma,
186                         float* destination, int64_t heads, int64_t cols,
187                         float epsilon, void* stream) {
188    norm_geometry(heads, cols, epsilon, stream);
189    const size_t bytes = size_t(heads) * S * sizeof(float);
190    const Span writable{destination, bytes};
191    valid(writable);
192    for (auto input : {Span{output, bytes}, Span{z, bytes}, Span{gamma, S * sizeof(float)}}) {
193        valid(input);
194        disjoint(writable, input);
195    }
196    out_norm<<<unsigned(heads), 256, 0, static_cast<cudaStream_t>(stream)>>>(output, z, gamma, destination, epsilon);
197    check_launch();
198}
199} // namespace strata::kernels