okami.mom/strata

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

Niko1221Merge f-q4-geometry (fc1c4e429): the model shape is fixed at build time (-DSTRATA_GEOMETRY / -DSTRATA_GEOMETRY_FILE); the default Flash-Next build is unchanged (CUDA SASS 3573/3573, HIP gfx1201 3920/3920, gfx1151 path-string offsets only, SYCL 22/22 checksums, Metal 10/10 tokens, CUDA 130/130 tokens); Qwen4 test shapes q4_lite/q4_mid/q4_big pass logits gate 2 on CUDA (Qwen4 prep)4dad59ab3

main
14.8 KiB291 linesraw
1// Arithmetic adapted from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d:
2// src/models/qwen4exp.cpp and ggml-cuda/{reduce_rows.cuh,sumrows.cu,unary.cu}.
3// MIT License
4// Copyright (c) 2023-2026 The ggml authors
5// Permission is hereby granted, free of charge, to any person obtaining a copy
6// of this software and associated documentation files (the "Software"), to deal
7// in the Software without restriction, including without limitation the rights
8// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9// copies of the Software, and to permit persons to whom the Software is
10// furnished to do so, subject to the following conditions:
11// The above copyright notice and this permission notice shall be included in all
12// copies or substantial portions of the Software.
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19// SOFTWARE.
20
21#include "strata/kernels/native_ple_postops.hpp"
22#include "strata/core/geometry.hpp"
23#include "strata/kernels/native_gr_norm.hpp"
24#include "strata/kernels/ngram.hpp"
25#include <cuda_runtime.h>
26#include <cuda_fp16.h>
27#include <cmath>
28#include <cstddef>
29#include <cstdint>
30#include <limits>
31#include <stdexcept>
32#include <string>
33
34namespace strata::kernels {
35namespace {
36constexpr int N = strata::core::kCompiledGeometry.n_embd, H = strata::core::kCompiledGeometry.hc, D = N * H, HISTORY = 9;
37static_assert(N == strata::core::kCompiledGeometry.n_embd && H == strata::core::kCompiledGeometry.hc, "native_ple_postops is compiled for core/geometry.hpp");
38__device__ float warp_sum(float x) {
39    for (int offset = 16; offset; offset >>= 1) x += __shfl_xor_sync(0xffffffffu, x, offset);
40    return x;
41}
42__global__ void gate_kernel(const float* key, const float* query, float* gate, float scale) {
43    // SUM_ROWS selects 512 threads for four rows on the target GPU. Preserve
44    // its eight partial lanes and materialized MUL rounding (never a dot FMA).
45    float sums[8] = {};
46#pragma unroll
47    for (int j = 0; j < 8; ++j) {
48        const int d = threadIdx.x + j * 512;
49        const float p = d < N ? __fmul_rn(key[blockIdx.x * N + d], query[blockIdx.x * N + d]) : 0.0f;
50        sums[j] += p;
51    }
52    float sum = 0;
53#pragma unroll
54    for (int j = 0; j < 8; ++j) sum += sums[j];
55    __shared__ float partials[32];
56    sum = warp_sum(sum);
57    const int lane = threadIdx.x % 32;
58    if (!lane) partials[threadIdx.x / 32] = sum;
59    __syncthreads();
60    sum = lane < 16 ? partials[lane] : 0.0f;
61    sum = warp_sum(sum);
62    if (threadIdx.x == 0) {
63        const float s = __fmaf_rn(scale, sum, 0.0f); // ggml SCALE's zero bias
64        const float mag = sqrtf(fmaxf(fabsf(s), 1e-6f));
65        const float sign = float((s > 0.0f) - (s < 0.0f));
66        gate[blockIdx.x] = 1.0f / (1.0f + expf(-__fmul_rn(sign, mag)));
67    }
68}
69__global__ void broadcast_kernel(const float* value, const float* gate, float* gated) {
70    const int i = blockIdx.x * blockDim.x + threadIdx.x;
71    if (i < D) gated[i] = __fmul_rn(value[i % N], gate[i / N]);
72}
73__global__ void conv_residual_kernel(const float* history, const float* normalized,
74                                    const uint16_t* weights, const float* hidden,
75                                    const float* gated, float* conv, float* result) {
76    const int c = blockIdx.x * blockDim.x + threadIdx.x;
77    if (c >= D) return;
78    float sum = 0;
79#pragma unroll
80    for (int k = 0; k < 4; ++k) {
81        const float x = k == 3 ? normalized[c] : history[c * HISTORY + 3 * k];
82        const float w = __half2float(__ushort_as_half(weights[c * 4 + k]));
83        const float term = __fmul_rn(x, w);
84        sum = k == 0 ? term : __fadd_rn(sum, term);
85    }
86    const float activation = sum / (1.0f + expf(-sum));
87    conv[c] = activation;
88    // Exact hidden/result alias is safe: each thread owns one element.
89    result[c] = __fadd_rn(hidden[c], __fadd_rn(gated[c], activation));
90}
91// ---- the batch: T tokens, the same arithmetic per element as the kernels above
92// weighted_rms_norm (native_gr_norm.cu) with the gamma row repeating every H rows (one token's H groups)
93__device__ float norm_warp_sum(float value) {
94#pragma unroll
95    for (int offset = 16; offset > 0; offset >>= 1) value += __shfl_xor_sync(0xffffffffu, value, offset, 32);
96    return value;
97}
98__global__ void rms_rep_kernel(const float* __restrict__ input, const float* __restrict__ gamma,
99                               float* __restrict__ output) {
100    constexpr int BlockSize = 1024;             // native_gr_rms_norm_weighted's choice for 2560 columns
101    const int tid = threadIdx.x;
102    const size_t row_offset = size_t(blockIdx.x) * N;
103    input += row_offset;
104    output += row_offset;
105    gamma += size_t(blockIdx.x % H) * N;
106    float partial = 0.0f;
107    for (int col = tid; col < N; col += BlockSize) {
108        const float value = input[col];
109        partial += value * value;
110    }
111    __shared__ float sums[32];
112    partial = norm_warp_sum(partial);
113    const int lane = tid % 32;
114    if (lane == 0) sums[tid / 32] = partial;
115    __syncthreads();
116    partial = 0.0f;
117    if (lane < BlockSize / 32) partial = sums[lane];
118    partial = norm_warp_sum(partial);
119    const float mean = partial / N;
120    const float scale = rsqrtf(mean + NG_RMS_EPS);
121    for (int col = tid; col < N; col += BlockSize) output[col] = scale * input[col] * gamma[col];
122}
123// rms_rep_kernel with the column count as a RUN-TIME divisor, as weighted_rms_norm<1024> (native_gr_rms_norm_weighted,
124// the per-token path) divides: under --use_fast_math a division by the constant N may become a multiplication by its
125// rounded reciprocal, which is not bitwise the run-time division.
126__global__ void rms_rep_rt_kernel(const float* __restrict__ input, const float* __restrict__ gamma,
127                                  float* __restrict__ output, int n_cols, float epsilon) {
128    constexpr int BlockSize = 1024;
129    const int tid = threadIdx.x;
130    const size_t row_offset = size_t(blockIdx.x) * n_cols;
131    input += row_offset;
132    output += row_offset;
133    gamma += size_t(blockIdx.x % H) * n_cols;
134    float partial = 0.0f;
135    for (int col = tid; col < n_cols; col += BlockSize) {
136        const float value = input[col];
137        partial += value * value;
138    }
139    __shared__ float sums[32];
140    partial = norm_warp_sum(partial);
141    const int lane = tid % 32;
142    if (lane == 0) sums[tid / 32] = partial;
143    __syncthreads();
144    partial = 0.0f;
145    if (lane < BlockSize / 32) partial = sums[lane];
146    partial = norm_warp_sum(partial);
147    const float mean = partial / n_cols;
148    const float scale = rsqrtf(mean + epsilon);
149    for (int col = tid; col < n_cols; col += BlockSize) output[col] = scale * input[col] * gamma[col];
150}
151__global__ void broadcast_batch_kernel(const float* value, const float* gate, float* gated, int T) {
152    const size_t i = size_t(blockIdx.x) * blockDim.x + threadIdx.x;
153    if (i >= size_t(T) * D) return;
154    const size_t t = i / D, d = i % D;
155    gated[i] = __fmul_rn(value[t * N + d % N], gate[t * H + d / N]);
156}
157// the dilated conv (taps 9, 6, 3 tokens back and this one) and the residual; a tap before the chunk reads the history
158__global__ void conv_residual_batch_kernel(const float* history, const float* normalized, const uint16_t* weights,
159                                           float* hidden, const float* gated, int T) {
160    const size_t i = size_t(blockIdx.x) * blockDim.x + threadIdx.x;
161    if (i >= size_t(T) * D) return;
162    const int t = int(i / D), c = int(i % D);
163    float sum = 0;
164#pragma unroll
165    for (int k = 0; k < 4; ++k) {
166        const int p = t - 9 + 3 * k;             // the token this tap reads (k == 3: this one)
167        const float x = p >= 0 ? normalized[size_t(p) * D + c] : history[size_t(c) * HISTORY + (9 + p)];
168        const float wk = __half2float(__ushort_as_half(weights[c * 4 + k]));
169        const float term = __fmul_rn(x, wk);
170        sum = k == 0 ? term : __fadd_rn(sum, term);
171    }
172    const float activation = sum / (1.0f + expf(-sum));
173    hidden[i] = __fadd_rn(hidden[i], __fadd_rn(gated[i], activation));
174}
175// the history after the chunk: the last nine normalized rows (older ones from the history when T < 9)
176__global__ void history_batch_kernel(float* history, const float* normalized, int T) {
177    const int c = blockIdx.x * blockDim.x + threadIdx.x;
178    if (c >= D) return;
179    float h[HISTORY];
180#pragma unroll
181    for (int r = 0; r < HISTORY; ++r) {
182        const int p = T - HISTORY + r;
183        h[r] = p >= 0 ? normalized[size_t(p) * D + c] : history[size_t(c) * HISTORY + (T + r)];
184    }
185#pragma unroll
186    for (int r = 0; r < HISTORY; ++r) history[size_t(c) * HISTORY + r] = h[r];
187}
188
189// history_batch_kernel that also writes the history after each of the T tokens (`snap`, T x 9 x 10240): pure copies,
190// the values T history advances (ple_history_advance) leave
191__global__ void history_batch_snap_kernel(float* history, const float* normalized, int T, float* snap) {
192    const int c = blockIdx.x * blockDim.x + threadIdx.x;
193    if (c >= D) return;
194    float h0[HISTORY];
195#pragma unroll
196    for (int r = 0; r < HISTORY; ++r) h0[r] = history[size_t(c) * HISTORY + r];
197    for (int t = 0; t < T; ++t) {
198        float* out = snap + size_t(t) * HISTORY * D + size_t(c) * HISTORY;
199#pragma unroll
200        for (int r = 0; r < HISTORY; ++r) {
201            const int p = r + t + 1 - HISTORY;      // after t + 1 advances row r holds token p, or an older row
202            out[r] = p >= 0 ? normalized[size_t(p) * D + c] : h0[r + t + 1];
203        }
204    }
205#pragma unroll
206    for (int r = 0; r < HISTORY; ++r) {
207        const int p = r + T - HISTORY;
208        history[size_t(c) * HISTORY + r] = p >= 0 ? normalized[size_t(p) * D + c] : h0[r + T];
209    }
210}
211
212struct Span { const void* p; size_t bytes; size_t alignment; };
213bool overlaps(Span a, Span b) {
214    const auto x = reinterpret_cast<uintptr_t>(a.p), y = reinterpret_cast<uintptr_t>(b.p);
215    return x < y + b.bytes && y < x + a.bytes;
216}
217void validate(Span span) {
218    const auto p = reinterpret_cast<uintptr_t>(span.p);
219    if (!p || p % span.alignment || p > std::numeric_limits<uintptr_t>::max() - span.bytes)
220        throw std::invalid_argument("native PLE postops require nonnull aligned bounded spans");
221}
222void launch_check() {
223    const auto error = cudaGetLastError();
224    if (error != cudaSuccess) throw std::runtime_error(std::string("native PLE postops launch: ") + cudaGetErrorString(error));
225}
226} // namespace
227
228void native_ple_postops(const float* projected_key, const float* hidden,
229                        const float* value, const float* history,
230                        const PleWeights& w, const NativePlePostopsBuffers& b, void* stream) {
231    if (!stream) throw std::invalid_argument("native PLE postops require an explicit stream");
232    const Span inputs[] = {{projected_key,D*4,4}, {hidden,D*4,4}, {value,N*4,4},
233        {history,HISTORY*D*4,4}, {w.norm_key,D*4,4}, {w.norm_query,D*4,4},
234        {w.norm_conv,D*4,4}, {w.conv1d_f16,4*D*2,2}};
235    const Span outputs[] = {{b.key,D*4,4}, {b.query,D*4,4}, {b.gate,H*4,4},
236        {b.gated,D*4,4}, {b.normalized,D*4,4}, {b.conv,D*4,4}, {b.result,D*4,4}};
237    for (const auto& span : inputs) validate(span);
238    for (const auto& span : outputs) validate(span);
239    for (size_t i = 0; i < 7; ++i) {
240        for (size_t j = 0; j < 8; ++j)
241            if (!(i == 6 && j == 1 && b.result == hidden) && overlaps(outputs[i], inputs[j]))
242                throw std::invalid_argument("native PLE postops output overlaps an input or weight");
243        for (size_t j = i + 1; j < 7; ++j)
244            if (!(i == 1 && j == 4 && b.query == b.normalized) && overlaps(outputs[i], outputs[j]))
245                throw std::invalid_argument("native PLE postops writable spans overlap");
246    }
247    native_gr_rms_norm_weighted(projected_key,w.norm_key,b.key,N,H,NG_RMS_EPS,stream);
248    native_gr_rms_norm_weighted(hidden,w.norm_query,b.query,N,H,NG_RMS_EPS,stream);
249    auto st = static_cast<cudaStream_t>(stream);
250    gate_kernel<<<H,512,0,st>>>(b.key,b.query,b.gate,1.0f / std::sqrt(float(N)));
251    broadcast_kernel<<<D/256,256,0,st>>>(value,b.gate,b.gated);
252    launch_check();
253    native_gr_rms_norm_weighted(b.gated,w.norm_conv,b.normalized,N,H,NG_RMS_EPS,stream);
254    conv_residual_kernel<<<D/256,256,0,st>>>(history,b.normalized,w.conv1d_f16,hidden,b.gated,b.conv,b.result);
255    launch_check();
256}
257
258void native_ple_postops_batch(float* key, float* hidden, const float* value, float* history, const PleWeights& w,
259                              float* query_norm, float* gated, float* gate, int T, void* stream) {
260    if (!stream || T <= 0 || !key || !hidden || !value || !history || !query_norm || !gated || !gate)
261        throw std::invalid_argument("native PLE postops batch: null input or empty batch");
262    auto st = static_cast<cudaStream_t>(stream);
263    const unsigned rows = unsigned(T) * H;
264    const unsigned blocks = unsigned((size_t(T) * D + 255) / 256);
265    rms_rep_kernel<<<rows, 1024, 0, st>>>(key, w.norm_key, key);
266    rms_rep_kernel<<<rows, 1024, 0, st>>>(hidden, w.norm_query, query_norm);
267    gate_kernel<<<rows, 512, 0, st>>>(key, query_norm, gate, 1.0f / std::sqrt(float(N)));
268    broadcast_batch_kernel<<<blocks, 256, 0, st>>>(value, gate, gated, T);
269    rms_rep_kernel<<<rows, 1024, 0, st>>>(gated, w.norm_conv, query_norm);
270    conv_residual_batch_kernel<<<blocks, 256, 0, st>>>(history, query_norm, w.conv1d_f16, hidden, gated, T);
271    history_batch_kernel<<<D / 256, 256, 0, st>>>(history, query_norm, T);
272    launch_check();
273}
274
275void native_ple_postops_batch_snap(float* key, float* hidden, const float* value, float* history, const PleWeights& w,
276                                   float* query_norm, float* gated, float* gate, int T, float* snap, void* stream) {
277    if (!stream || T <= 0 || !key || !hidden || !value || !history || !query_norm || !gated || !gate || !snap)
278        throw std::invalid_argument("native PLE postops batch (snapshots): null input or empty batch");
279    auto st = static_cast<cudaStream_t>(stream);
280    const unsigned rows = unsigned(T) * H;
281    const unsigned blocks = unsigned((size_t(T) * D + 255) / 256);
282    rms_rep_rt_kernel<<<rows, 1024, 0, st>>>(key, w.norm_key, key, N, NG_RMS_EPS);
283    rms_rep_rt_kernel<<<rows, 1024, 0, st>>>(hidden, w.norm_query, query_norm, N, NG_RMS_EPS);
284    gate_kernel<<<rows, 512, 0, st>>>(key, query_norm, gate, 1.0f / std::sqrt(float(N)));
285    broadcast_batch_kernel<<<blocks, 256, 0, st>>>(value, gate, gated, T);
286    rms_rep_rt_kernel<<<rows, 1024, 0, st>>>(gated, w.norm_conv, query_norm, N, NG_RMS_EPS);
287    conv_residual_batch_kernel<<<blocks, 256, 0, st>>>(history, query_norm, w.conv1d_f16, hidden, gated, T);
288    history_batch_snap_kernel<<<D / 256, 256, 0, st>>>(history, query_norm, T, snap);
289    launch_check();
290}
291} // namespace strata::kernels