okami.mom/strata

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

Niko1221Merge branch 'f-1402-d1' into f-14027dbd8c09f

main
8.2 KiB161 linesraw
1// Adapted from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d:
2// ggml/src/ggml-cuda/{dsv4-hc.cu,scale.cu,unary.cu,unary.cuh}.
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_gr_postops.hpp"
26#include <cuda_runtime.h>
27#include <cstddef>
28#include <cstdint>
29#include <limits>
30#include <stdexcept>
31#include <string>
32
33namespace strata::kernels {
34namespace {
35constexpr int THREADS = 256;
36__device__ __forceinline__ float sigmoid(float x) { return 1.0f / (1.0f + expf(-x)); }
37// ggml SCALE uses scale*x+bias, including its +0 bias. Retain this operation
38// explicitly so compile-time zero does not change signed-zero behavior.
39__device__ __forceinline__ float scale_zero_bias(float x, float scale) {
40    return __fmaf_rn(scale, x, 0.0f);
41}
42__global__ void down_silu(float* lo, int count, float scale) {
43    const std::size_t i = std::size_t(blockIdx.x) * blockDim.x + threadIdx.x;
44    if (i >= std::size_t(count)) return;
45    const float x = scale_zero_bias(lo[i], scale);
46    lo[i] = x / (1.0f + expf(-x));
47}
48template<bool Fused>
49__global__ void pre_gated(const float* __restrict__ xn, float* __restrict__ gate,
50                          float* __restrict__ mixed, int n_embd, int hc, float scale) {
51    const std::size_t d = std::size_t(blockIdx.x) * blockDim.x + threadIdx.x;
52    if (d >= std::size_t(n_embd)) return;
53    const std::size_t t = blockIdx.y;
54    xn += t * std::size_t(n_embd) * hc;
55    gate += t * std::size_t(n_embd) * hc;
56    mixed += t * std::size_t(n_embd);
57    float sum = 0.0f;
58    for (int c = 0; c < hc; ++c) {
59        const std::size_t i = std::size_t(c) * n_embd + d;
60        const float x = xn[i], w = sigmoid(gate[i]);
61        const float product = __fmul_rn(x, w);
62        gate[i] = product;
63        if constexpr (Fused) sum = __fmaf_rn(x, w, sum);
64        else sum = c == 0 ? product : __fadd_rn(sum, product);
65    }
66    if constexpr (Fused) mixed[d] = scale * sum;
67    else mixed[d] = scale_zero_bias(sum, scale);
68}
69__global__ void post(const float* residual, const float* __restrict__ block_out,
70                     const float* __restrict__ inject, float* output,
71                     int n_embd, int hc, float scale) {
72    const std::size_t i = std::size_t(blockIdx.x) * blockDim.x + threadIdx.x;
73    if (i >= std::size_t(n_embd) * hc) return;
74    const std::size_t t = blockIdx.y;
75    residual += t * std::size_t(n_embd) * hc;
76    block_out += t * std::size_t(n_embd);
77    inject += t * std::size_t(hc);
78    output += t * std::size_t(n_embd) * hc;
79    const int c = int(i / n_embd), d = int(i % n_embd);
80    const float weight = scale_zero_bias(sigmoid(scale_zero_bias(inject[c], scale)), 2.0f);
81    // Exact residual/output alias is supported; no other thread reads residual[i].
82    output[i] = __fmaf_rn(block_out[d], weight, residual[i]);
83}
84// `post` for n tokens (blockIdx.y = token): the same expression per element
85__global__ void post_multi(const float* residual, const float* __restrict__ block_out,
86                           const float* __restrict__ inject, float* output, int n_embd, int hc, float scale,
87                           long long r_stride, long long b_stride, long long i_stride) {
88    const std::size_t i = std::size_t(blockIdx.x) * blockDim.x + threadIdx.x;
89    if (i >= std::size_t(n_embd) * hc) return;
90    const long long t = blockIdx.y;
91    residual += t * r_stride; output += t * r_stride; block_out += t * b_stride; inject += t * i_stride;
92    const int c = int(i / n_embd), d = int(i % n_embd);
93    const float weight = scale_zero_bias(sigmoid(scale_zero_bias(inject[c], scale)), 2.0f);
94    // Exact residual/output alias is supported; no other thread reads residual[i].
95    output[i] = __fmaf_rn(block_out[d], weight, residual[i]);
96}
97void check_pointer(const void* p) {
98    if (!p || reinterpret_cast<std::uintptr_t>(p) % alignof(float))
99        throw std::invalid_argument("native GR postops require non-null four-byte aligned pointers");
100}
101void check_shape(int n, int hc) {
102    if (n <= 0 || hc <= 0 || std::uint64_t(n) * hc > std::uint64_t(std::numeric_limits<int>::max()))
103        throw std::invalid_argument("native GR postops require positive bounded dimensions");
104}
105unsigned blocks(std::size_t n) { return unsigned((n + THREADS - 1) / THREADS); }
106void check_launch() {
107    const auto error = cudaGetLastError();
108    if (error != cudaSuccess)
109        throw std::runtime_error(std::string("native GR postops launch: ") + cudaGetErrorString(error));
110}
111} // namespace
112
113void native_gr_down_silu(float* lo, int hc_lr, int hc, void* stream) {
114    check_shape(hc_lr, hc);
115    check_pointer(lo);
116    down_silu<<<blocks(hc_lr), THREADS, 0, static_cast<cudaStream_t>(stream)>>>(lo, hc_lr, 1.0f / float(hc));
117    check_launch();
118}
119void native_gr_pre_gated(const float* xn, float* gate, float* mixed,
120                         int n_embd, int hc, bool fused_layer, void* stream) {
121    native_gr_pre_gated_multi(xn, gate, mixed, n_embd, hc, 1, fused_layer, stream);
122}
123void native_gr_pre_gated_multi(const float* xn, float* gate, float* mixed,
124                               int n_embd, int hc, int n_tok, bool fused_layer, void* stream) {
125    if (n_tok <= 0)
126        throw std::invalid_argument("native GR postops require positive n_tok");
127    check_shape(n_embd, hc);
128    check_pointer(xn); check_pointer(gate); check_pointer(mixed);
129    const dim3 grid{blocks(n_embd), unsigned(n_tok), 1u};
130    if (fused_layer)
131        pre_gated<true><<<grid, THREADS, 0, static_cast<cudaStream_t>(stream)>>>(xn, gate, mixed, n_embd, hc, 1.0f / float(hc));
132    else
133        pre_gated<false><<<grid, THREADS, 0, static_cast<cudaStream_t>(stream)>>>(xn, gate, mixed, n_embd, hc, 1.0f / float(hc));
134    check_launch();
135}
136void native_gr_post(const float* residual, const float* block_out, const float* inject,
137                    float* output, int n_embd, int hc, void* stream) {
138    native_gr_post_multi(residual, block_out, inject, output, n_embd, hc, 1, stream);
139}
140void native_gr_post_multi(const float* residual, const float* block_out, const float* inject,
141                          float* output, int n_embd, int hc, int n_tok, void* stream) {
142    if (n_tok <= 0)
143        throw std::invalid_argument("native GR postops require positive n_tok");
144    check_shape(n_embd, hc);
145    check_pointer(residual); check_pointer(block_out); check_pointer(inject); check_pointer(output);
146    const dim3 grid{blocks(std::size_t(n_embd) * hc), unsigned(n_tok), 1u};
147    post<<<grid, THREADS, 0, static_cast<cudaStream_t>(stream)>>>(
148        residual, block_out, inject, output, n_embd, hc, 1.0f / float(hc));
149    check_launch();
150}
151void native_gr_post_multi(const float* residual, const float* block_out, const float* inject, float* output,
152                          int n_embd, int hc, int n_tok, long long r_stride, long long b_stride, long long i_stride,
153                          void* stream) {
154    check_shape(n_embd, hc);
155    check_pointer(residual); check_pointer(block_out); check_pointer(inject); check_pointer(output);
156    if (n_tok < 1) return;
157    post_multi<<<dim3(blocks(std::size_t(n_embd) * hc), unsigned(n_tok)), THREADS, 0, static_cast<cudaStream_t>(stream)>>>(
158        residual, block_out, inject, output, n_embd, hc, 1.0f / float(hc), r_stride, b_stride, i_stride);
159    check_launch();
160}
161} // namespace strata::kernels