okami.mom/strata

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

Niko1221Merge f-q4-sycl (41717f29c): the Intel Arc (SYCL) engine follows the compiled geometry, so q4_lite/q4_mid/q4_big build; default build unchanged (CUDA SASS 3573/3573, HIP gfx1201 3920/3920, gfx1151 string offsets only, Metal 85/85 objects, SYCL 22/22 checksums); A750 gate 2 q4_lite 0.00021 vs floor 0.00017; one conflict with f-clean-6-0 in sycl/src/prefill/prefill.cpp resolved as tested by Q4-SYMERGE (Qwen4 prep)db137d917

main
17.1 KiB370 linesraw
1// Arithmetic adapted from the MIT-licensed pinned ggml CUDA
2// moe-weighted-reduction.cu at 3cf03257f219afbe7334045ff7c6a06ac68c627d.
3// MIT License
4// Copyright (c) 2023-2026 The ggml authors
5//
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
12//
13// The above copyright notice and this permission notice shall be included in all
14// copies or substantial portions of the Software.
15//
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22// SOFTWARE.
23#define DPCT_PROFILING_ENABLED
24#include <sycl/sycl.hpp>
25#include "strata/kprof.hpp"
26#include <dpct/dpct.hpp>
27#include "strata/sycl_queue.hpp"
28#include "strata/kernels/native_moe.hpp"
29#include "strata/core/geometry.hpp"
30#include <atomic>
31#include <cstddef>
32#include <cstdint>
33#include <limits>
34#include <stdexcept>
35#include <cmath>
36
37namespace strata::kernels {
38namespace {
39constexpr int KU = strata::core::kCompiledGeometry.n_expert_used;   // 10 for Flash-Next: the combine kernel below is written for exactly this many ranks
40static_assert(KU >= 1 && KU <= 16, "native_moe: top-k must be 1..16");
41std::atomic<bool> enabled{false};
42// GATED (S26 STRATA_LFUSE): `shared` is the shared expert's unscaled output and sg its raw gate logit per token;
43// the row is scaled here as shared_expert_multi did (native_scalar_sigmoid_multi_kernel's expression, then one
44// rounded multiply = scale_rows_kernel's `out *= g`), then added as before
45template <bool ZADD = false, bool GATED = false>
46__dpct_inline__ void
47combine(const float *__restrict__ parts, const float *__restrict__ weights,
48        const float *__restrict__ shared, float *__restrict__ output,
49        int64_t n_embd, int k, const float *__restrict__ sg = nullptr) {
50    // blockIdx.y = the token of a multi-token launch (0 for the single one)
51    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
52    const int64_t tk = item_ct1.get_group(1);
53    parts += tk * k * n_embd; weights += tk * k; if (shared) shared += tk * n_embd; output += tk * n_embd;
54    const int64_t col =
55        int64_t(item_ct1.get_group(2)) * item_ct1.get_local_range(2) +
56        item_ct1.get_local_id(2);
57    if (col >= n_embd) return;
58    // ZADD: a part is 0.0f + hit (the zeroed row plus moe_hit_add of the verify window), rounded as that add
59    float p0 = parts[col];
60    if (ZADD) p0 = 0.0f + p0;
61    float sum = p0 * weights[0];
62    for (int expert = 1; expert < k; ++expert) {
63        float p = parts[int64_t(expert) * n_embd + col];
64        if (ZADD) p = 0.0f + p;
65        sum += p * weights[expert];
66    }
67    if constexpr (GATED) {
68        // contraction off in this block only: the product is rounded on its own (scale_rows' store), then added
69#pragma clang fp contract(off)
70        const float g = 1.0f / (1.0f + sycl::native::exp(-sg[tk]));
71        const float sh = shared[col] * g;
72        sum += sh;
73    } else {
74        if (shared) sum += shared[col];
75    }
76    output[col] = sum;
77}
78__dpct_inline__ void combine_k10_vec4(const sycl::float4 *__restrict__ parts4,
79                                      const float *__restrict__ weights,
80                                      const sycl::float4 *__restrict__ shared4,
81                                      sycl::float4 *__restrict__ output4,
82                                      int64_t n4) {
83    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
84    const int64_t tk = item_ct1.get_group(1);
85    parts4 += tk * KU * n4;
86    weights += tk * KU;
87    shared4 += tk * n4;
88    output4 += tk * n4;
89    const int64_t c4 =
90        int64_t(item_ct1.get_group(2)) * item_ct1.get_local_range(2) +
91        item_ct1.get_local_id(2);
92    if (c4 >= n4) return;
93    /*
94    DPCT1098: The '*' expression is used instead of the __ldg call. These
95    two expressions do not provide the exact same functionality. Check the
96    generated code for potential precision and/or performance issues.
97    */
98    const float w0 = *(weights + 0);
99    const sycl::float4 p0 = parts4[c4];
100    sycl::float4 sum =
101        sycl::float4(p0.x() * w0, p0.y() * w0, p0.z() * w0, p0.w() * w0);
102#pragma unroll
103    for (int expert = 1; expert < KU; ++expert) {
104        /*
105        DPCT1098: The '*' expression is used instead of the __ldg call.
106        These two expressions do not provide the exact same functionality. Check
107        the generated code for potential precision and/or performance issues.
108        */
109        const float w = *(weights + expert);
110        const sycl::float4 p = parts4[int64_t(expert) * n4 + c4];
111        // the documented contract spelled out: the first product rounded, then one FMA per expert in order. Left to the
112        // compiler's contraction, a build may fuse a different product (gfx1151: the float4 kernel then differed from the
113        // scalar one, native_multi_parity)
114        sum.x() = sycl::fma((float)(p.x()), (float)w, sum.x());
115        sum.y() = sycl::fma((float)(p.y()), (float)w, sum.y());
116        sum.z() = sycl::fma((float)(p.z()), (float)w, sum.z());
117        sum.w() = sycl::fma((float)(p.w()), (float)w, sum.w());
118    }
119    const sycl::float4 sh = shared4[c4];
120    sum.x() += sh.x();
121    sum.y() += sh.y();
122    sum.z() += sh.z();
123    sum.w() += sh.w();
124    output4[c4] = sum;
125}
126bool valid_span(const void* p, size_t bytes) {
127    const auto address = reinterpret_cast<uintptr_t>(p);
128    return p && address % alignof(float) == 0 && bytes <= UINTPTR_MAX - address;
129}
130bool overlap(const void* a, size_t an, const void* b, size_t bn) {
131    const auto ap = reinterpret_cast<uintptr_t>(a), bp = reinterpret_cast<uintptr_t>(b);
132    return ap < bp + bn && bp < ap + an;
133}
134}
135void native_moe_combine_set_enabled(bool value) { enabled.store(value, std::memory_order_relaxed); }
136bool native_moe_combine_enabled() { return enabled.load(std::memory_order_relaxed); }
137void native_moe_combine(const float* parts, const float* weights, const float* shared,
138                        float* output, int64_t n_embd, int64_t k, void* stream) {
139    if (!stream || n_embd <= 0 || n_embd > std::numeric_limits<int>::max() || k < 1 || k > 15)
140        throw std::invalid_argument("native MoE combine requires a stream, positive width and 1..15 experts");
141    const size_t row_bytes = size_t(n_embd) * sizeof(float);
142    const size_t part_bytes = row_bytes * size_t(k), weight_bytes = size_t(k) * sizeof(float);
143    if (!valid_span(parts, part_bytes) || !valid_span(weights, weight_bytes) || !valid_span(output, row_bytes)
144            || (shared && !valid_span(shared, row_bytes))
145            || overlap(output, row_bytes, parts, part_bytes)
146            || overlap(output, row_bytes, weights, weight_bytes)
147            || (shared && overlap(output, row_bytes, shared, row_bytes)))
148        throw std::invalid_argument("native MoE combine requires aligned spans and disjoint output");
149    if (k == KU && shared != nullptr && (n_embd & 3) == 0 &&
150        (((uintptr_t) parts | (uintptr_t) shared | (uintptr_t) output) & 15u) == 0) {
151        const int64_t n4 = n_embd >> 2;
152        {
153            auto exp_props = sycl::ext::oneapi::experimental::properties{
154                sycl::ext::oneapi::experimental::use_root_sync};
155
156            strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
157                ->template parallel_for<dpct_kernel_name<class combine_k10_vec4_503ec2>>(
158                    sycl::nd_range<3>(
159                        sycl::range(1, 1, unsigned((n4 + 127) / 128)) *
160                            sycl::range(1, 1, 128),
161                        sycl::range(1, 1, 128)),
162                    exp_props, [=](sycl::nd_item<3> item_ct1) {
163                        combine_k10_vec4(
164                            reinterpret_cast<const sycl::float4 *>(parts),
165                            weights,
166                            reinterpret_cast<const sycl::float4 *>(shared),
167                            reinterpret_cast<sycl::float4 *>(output), n4);
168                    });
169        }
170    } else {
171        auto exp_props = sycl::ext::oneapi::experimental::properties{
172            sycl::ext::oneapi::experimental::use_root_sync};
173
174        ((sycl::queue *)(strata::q_of(stream)))
175            ->/*
176DPCT1050: The template argument of the dpct_kernel_name could not be
177deduced. You need to update this code.
178*/
179            parallel_for<
180                dpct_kernel_name<class combine_f74f36,
181                                 dpct_kernel_scalar<false>,
182                                 dpct_kernel_scalar<false>>>(
183                sycl::nd_range<3>(
184                    sycl::range(1, 1, unsigned((n_embd + 255) / 256)) *
185                        sycl::range(1, 1, 256),
186                    sycl::range(1, 1, 256)),
187                exp_props, [=](sycl::nd_item<3> item_ct1) {
188                    combine(parts, weights, shared, output, n_embd, int(k),
189                            nullptr);
190                });
191    }
192    /*
193    DPCT1010: SYCL uses exceptions to report errors and does not use the
194    error codes. The cudaGetLastError function call was replaced with 0. You
195    need to rewrite this code.
196    */
197    const auto error = 0;
198    /*
199    DPCT1009: SYCL reports errors using exceptions and does not use error
200    codes. Please replace the "get_error_string_dummy(...)" with a real
201    error-handling function.
202    */
203    /*
204    DPCT1001: The statement could not be removed.
205    */
206    /*
207    DPCT1000: Error handling if-stmt was detected but could not be
208    rewritten.
209    */
210    if (error !=
211        0) throw std::runtime_error(dpct::get_error_string_dummy(error));
212}
213void native_moe_combine_multi(const float* parts, const float* weights, const float* shared, float* output,
214                              int64_t n_embd, int64_t k, int n_tok, void* stream) {
215    if (!stream || n_embd <= 0 || k < 1 || k > 15 || n_tok < 1)
216        throw std::invalid_argument("native MoE combine (multi) requires a stream, width, 1..15 experts, tokens");
217    if (k == KU && shared != nullptr && (n_embd & 3) == 0 &&
218        (((uintptr_t) parts | (uintptr_t) shared | (uintptr_t) output) & 15u) == 0) {
219        const int64_t n4 = n_embd >> 2;
220        {
221            auto exp_props = sycl::ext::oneapi::experimental::properties{
222                sycl::ext::oneapi::experimental::use_root_sync};
223
224            strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
225                ->template parallel_for<dpct_kernel_name<class combine_k10_vec4_44a528>>(
226                    sycl::nd_range<3>(sycl::range(1, (unsigned)n_tok,
227                                                  unsigned((n4 + 127) / 128)) *
228                                          sycl::range(1, 1, 128),
229                                      sycl::range(1, 1, 128)),
230                    exp_props, [=](sycl::nd_item<3> item_ct1) {
231                        combine_k10_vec4(
232                            reinterpret_cast<const sycl::float4 *>(parts),
233                            weights,
234                            reinterpret_cast<const sycl::float4 *>(shared),
235                            reinterpret_cast<sycl::float4 *>(output), n4);
236                    });
237        }
238    } else {
239        auto exp_props = sycl::ext::oneapi::experimental::properties{
240            sycl::ext::oneapi::experimental::use_root_sync};
241
242        ((sycl::queue *)(strata::q_of(stream)))
243            ->/*
244DPCT1050: The template argument of the dpct_kernel_name could not be
245deduced. You need to update this code.
246*/
247            parallel_for<
248                dpct_kernel_name<class combine_d78bb3,
249                                 dpct_kernel_scalar<false>,
250                                 dpct_kernel_scalar<false>>>(
251                sycl::nd_range<3>(sycl::range(1, (unsigned)n_tok,
252                                              unsigned((n_embd + 255) / 256)) *
253                                      sycl::range(1, 1, 256),
254                                  sycl::range(1, 1, 256)),
255                exp_props, [=](sycl::nd_item<3> item_ct1) {
256                    combine(parts, weights, shared, output, n_embd, int(k),
257                            nullptr);
258                });
259    }
260    /*
261    DPCT1010: SYCL uses exceptions to report errors and does not use the
262    error codes. The cudaGetLastError function call was replaced with 0. You
263    need to rewrite this code.
264    */
265    const auto error = 0;
266    /*
267    DPCT1009: SYCL reports errors using exceptions and does not use error
268    codes. Please replace the "get_error_string_dummy(...)" with a real
269    error-handling function.
270    */
271    /*
272    DPCT1001: The statement could not be removed.
273    */
274    /*
275    DPCT1000: Error handling if-stmt was detected but could not be
276    rewritten.
277    */
278    if (error !=
279        0) throw std::runtime_error(dpct::get_error_string_dummy(error));
280}
281void native_moe_combine_multi_hits_gated(const float* hits, const float* weights, const float* shared,
282                                         const float* shared_gate, float* output, int64_t n_embd, int64_t k, int n_tok,
283                                         void* stream) {
284    if (!stream || n_embd <= 0 || k < 1 || k > 15 || n_tok < 1 || !shared || !shared_gate)
285        throw std::invalid_argument("native MoE combine (hits, gated) requires a stream, width, 1..15 experts, tokens");
286    {
287        auto exp_props = sycl::ext::oneapi::experimental::properties{
288            sycl::ext::oneapi::experimental::use_root_sync};
289
290        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
291            ->template parallel_for<
292                dpct_kernel_name<class combine_deb31a, dpct_kernel_scalar<true>,
293                                 dpct_kernel_scalar<true>>>(
294                sycl::nd_range<3>(sycl::range(1, (unsigned)n_tok,
295                                              unsigned((n_embd + 255) / 256)) *
296                                      sycl::range(1, 1, 256),
297                                  sycl::range(1, 1, 256)),
298                exp_props, [=](sycl::nd_item<3> item_ct1) {
299                    combine<true, true>(hits, weights, shared, output, n_embd,
300                                        int(k), shared_gate);
301                });
302    }
303    /*
304    DPCT1010: SYCL uses exceptions to report errors and does not use the
305    error codes. The cudaGetLastError function call was replaced with 0. You
306    need to rewrite this code.
307    */
308    const auto error = 0;
309    /*
310    DPCT1009: SYCL reports errors using exceptions and does not use error
311    codes. Please replace the "get_error_string_dummy(...)" with a real
312    error-handling function.
313    */
314    /*
315    DPCT1001: The statement could not be removed.
316    */
317    /*
318    DPCT1000: Error handling if-stmt was detected but could not be
319    rewritten.
320    */
321    if (error !=
322        0) throw std::runtime_error(dpct::get_error_string_dummy(error));
323}
324void native_moe_combine_multi_hits(const float* hits, const float* weights, const float* shared, float* output,
325                                   int64_t n_embd, int64_t k, int n_tok, void* stream) {
326    if (!stream || n_embd <= 0 || k < 1 || k > 15 || n_tok < 1)
327        throw std::invalid_argument("native MoE combine (hits) requires a stream, width, 1..15 experts, tokens");
328    {
329        auto exp_props = sycl::ext::oneapi::experimental::properties{
330            sycl::ext::oneapi::experimental::use_root_sync};
331
332        ((sycl::queue *)(strata::q_of(stream)))
333            ->/*
334  DPCT1050: The template argument of the dpct_kernel_name could not be
335  deduced. You need to update this code.
336  */
337            parallel_for<
338                dpct_kernel_name<class combine_772c4f, dpct_kernel_scalar<true>,
339                                 dpct_kernel_scalar<false>>>(
340                sycl::nd_range<3>(sycl::range(1, (unsigned)n_tok,
341                                              unsigned((n_embd + 255) / 256)) *
342                                      sycl::range(1, 1, 256),
343                                  sycl::range(1, 1, 256)),
344                exp_props, [=](sycl::nd_item<3> item_ct1) {
345                    combine<true>(hits, weights, shared, output, n_embd, int(k),
346                                  nullptr);
347                });
348    }
349    /*
350    DPCT1010: SYCL uses exceptions to report errors and does not use the
351    error codes. The cudaGetLastError function call was replaced with 0. You
352    need to rewrite this code.
353    */
354    const auto error = 0;
355    /*
356    DPCT1009: SYCL reports errors using exceptions and does not use error
357    codes. Please replace the "get_error_string_dummy(...)" with a real
358    error-handling function.
359    */
360    /*
361    DPCT1001: The statement could not be removed.
362    */
363    /*
364    DPCT1000: Error handling if-stmt was detected but could not be
365    rewritten.
366    */
367    if (error !=
368        0) throw std::runtime_error(dpct::get_error_string_dummy(error));
369}
370}