okami.mom/strata

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

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

main
14.4 KiB313 linesraw
1// Adapted from topk-moe.cu/common.cuh in llama.cpp
2// 3cf03257f219afbe7334045ff7c6a06ac68c627d; finite F32, 512-expert/10-output path.
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_router.hpp"
29#include <atomic>
30#include <cfloat>
31#include <cstddef>
32#include <cstdint>
33#include <stdexcept>
34
35namespace strata::kernels {
36namespace {
37std::atomic<bool> enabled{false};
38__dpct_inline__ float warp_sum(float value) {
39#pragma unroll
40    /*
41    DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature
42    masked sub_group function which may not be supported by all compilers or
43    runtimes. You may need to adjust the code.
44    */
45    for (int mask = 16; mask; mask >>= 1) value +=
46        dpct::experimental::permute_sub_group_by_xor(
47            0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
48            value, mask);
49    return value;
50}
51__dpct_inline__ float warp_max(float value) {
52#pragma unroll
53    /*
54    DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature
55    masked sub_group function which may not be supported by all compilers or
56    runtimes. You may need to adjust the code.
57    */
58    for (int mask = 16; mask; mask >>= 1) value = sycl::fmax(
59        value,
60        dpct::experimental::permute_sub_group_by_xor(
61            0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
62            value, mask));
63    return value;
64}
65/*
66DPCT1110: The total declared local variable size in device function route
67exceeds 128 bytes and may cause high register pressure. Consult with your
68hardware vendor to find the total register size available and adjust the code,
69or use smaller sub-group size to avoid high register pressure.
70*/
71template <int NE>   // SYCL port: 512 (canonical) or 256 (the Coder) experts, 32 lanes x NE/32 values
72__dpct_inline__ void route(const float *__restrict__ logits,
73                           int32_t *__restrict__ ids,
74                           float *__restrict__ weights) {
75    // Preserve the pinned 32x8 block geometry; only row zero is active here.
76    // blockIdx.x = the token (a multi-token launch; 0 for the single one)
77    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
78    logits += (size_t)item_ct1.get_group(2) * NE;
79        ids += (size_t)item_ct1.get_group(2) * 10;
80        weights += (size_t)item_ct1.get_group(2) * 10;
81    if (item_ct1.get_local_id(1) != 0) return;
82    const int lane = item_ct1.get_local_id(2);
83    float values[NE / 32];
84#pragma unroll
85    for (int i = 0; i < NE / 32; ++i) values[i] = logits[lane + i * 32];
86    // Only subgroup row zero reaches this point (the other rows returned above): a work-group barrier here is
87    // divergent and hangs on Alchemist (A770); the subgroup barrier is the one the surviving row can meet.
88    sycl::group_barrier(item_ct1.get_sub_group());
89    float maximum = -INFINITY;
90#pragma unroll
91    for (int i = 0; i < NE / 32; ++i) maximum = sycl::max(maximum, values[i]);
92    maximum = warp_max(maximum);
93    float sum = 0.0f;
94#pragma unroll
95    for (int i = 0; i < NE / 32; ++i) {
96        values[i] = sycl::native::exp(values[i] - maximum);
97        sum += values[i];
98    }
99    const float reciprocal = 1.0f / warp_sum(sum);
100#pragma unroll
101    for (int i = 0; i < NE / 32; ++i) {
102        values[i] *= reciprocal;
103        if (sycl::isnan(values[i])) values[i] = -FLT_MAX;
104    }
105    float selected = 0.0f, selected_sum = 0.0f;
106    for (int rank = 0; rank < 10; ++rank) {
107        float best = values[0];
108        int expert = lane;
109#pragma unroll
110        for (int i = 1; i < NE / 32; ++i) {
111            if (values[i] > best) { best = values[i]; expert = lane + i * 32; }
112        }
113#pragma unroll
114        for (int mask = 16; mask; mask >>= 1) {
115            /*
116            DPCT1108: '__shfl_xor_sync' was migrated with the experimental
117            feature masked sub_group function which may not be supported by all
118            compilers or runtimes. You may need to adjust the code.
119            */
120            const float other = dpct::experimental::permute_sub_group_by_xor(
121                0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
122                best, mask);
123            /*
124            DPCT1108: '__shfl_xor_sync' was migrated with the experimental
125            feature masked sub_group function which may not be supported by all
126            compilers or runtimes. You may need to adjust the code.
127            */
128            const int other_id = dpct::experimental::permute_sub_group_by_xor(
129                0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
130                expert, mask);
131            if (other > best || (other == best && other_id < expert)) { best = other; expert = other_id; }
132        }
133        if ((expert & 31) == lane) {
134            values[expert / 32] = -INFINITY;
135            ids[rank] = expert;
136            // Deliberately accumulate by WINNING EXPERT lane, not output rank.
137            // Multiple selected experts in one lane add in selection order.
138            selected_sum += best;
139        }
140        if (rank == lane) selected = best;
141    }
142    selected_sum = sycl::max(warp_sum(selected_sum), 6.103515625e-5f);
143    const float inverse_selected_sum = 1.0f / selected_sum;
144    if (lane < 10) weights[lane] = selected * inverse_selected_sum;
145}
146/*
147DPCT1110: The total declared local variable size in device function
148route_multi exceeds 128 bytes and may cause high register pressure. Consult with
149your hardware vendor to find the total register size available and adjust the
150code, or use smaller sub-group size to avoid high register pressure.
151*/
152__dpct_inline__ void route_multi(const float *__restrict__ logits,
153                                 int32_t *__restrict__ ids,
154                                 float *__restrict__ weights, int n_tok) {
155    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
156    const int tk =
157        (int)item_ct1.get_group(2) * 8 + (int)item_ct1.get_local_id(1);
158    if (tk >= n_tok) return;
159    logits += (size_t) tk * 512; ids += (size_t) tk * 10; weights += (size_t) tk * 10;
160    const int lane = item_ct1.get_local_id(2);
161    float values[16];
162#pragma unroll
163    for (int i = 0; i < 16; ++i) values[i] = logits[lane + i * 32];
164    sycl::group_barrier(sycl::ext::oneapi::this_work_item::get_sub_group());
165    float maximum = -INFINITY;
166#pragma unroll
167    for (int i = 0; i < 16; ++i) maximum = sycl::max(maximum, values[i]);
168    maximum = warp_max(maximum);
169    float sum = 0.0f;
170#pragma unroll
171    for (int i = 0; i < 16; ++i) {
172        values[i] = sycl::native::exp(values[i] - maximum);
173        sum += values[i];
174    }
175    const float reciprocal = 1.0f / warp_sum(sum);
176#pragma unroll
177    for (int i = 0; i < 16; ++i) {
178        values[i] *= reciprocal;
179        if (sycl::isnan(values[i])) values[i] = -FLT_MAX;
180    }
181    float selected = 0.0f, selected_sum = 0.0f;
182    for (int rank = 0; rank < 10; ++rank) {
183        float best = values[0];
184        int expert = lane;
185#pragma unroll
186        for (int i = 1; i < 16; ++i) {
187            if (values[i] > best) { best = values[i]; expert = lane + i * 32; }
188        }
189#pragma unroll
190        for (int mask = 16; mask; mask >>= 1) {
191            /*
192            DPCT1108: '__shfl_xor_sync' was migrated with the experimental
193            feature masked sub_group function which may not be supported by all
194            compilers or runtimes. You may need to adjust the code.
195            */
196            const float other = dpct::experimental::permute_sub_group_by_xor(
197                0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
198                best, mask);
199            /*
200            DPCT1108: '__shfl_xor_sync' was migrated with the experimental
201            feature masked sub_group function which may not be supported by all
202            compilers or runtimes. You may need to adjust the code.
203            */
204            const int other_id = dpct::experimental::permute_sub_group_by_xor(
205                0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
206                expert, mask);
207            if (other > best || (other == best && other_id < expert)) { best = other; expert = other_id; }
208        }
209        if ((expert & 31) == lane) {
210            values[expert / 32] = -INFINITY;
211            ids[rank] = expert;
212            selected_sum += best;
213        }
214        if (rank == lane) selected = best;
215    }
216    selected_sum = sycl::max(warp_sum(selected_sum), 6.103515625e-5f);
217    const float inverse_selected_sum = 1.0f / selected_sum;
218    if (lane < 10) weights[lane] = selected * inverse_selected_sum;
219}
220bool valid(const void* p, size_t bytes) {
221    const auto address = reinterpret_cast<uintptr_t>(p);
222    return p && address % 4 == 0 && bytes <= UINTPTR_MAX - address;
223}
224bool overlap(const void* a, size_t an, const void* b, size_t bn) {
225    const auto ap = reinterpret_cast<uintptr_t>(a), bp = reinterpret_cast<uintptr_t>(b);
226    return ap < bp + bn && bp < ap + an;
227}
228}
229void native_router_set_enabled(bool value) { enabled.store(value, std::memory_order_relaxed); }
230bool native_router_enabled() { return enabled.load(std::memory_order_relaxed); }
231void native_router_top10(const float* logits, int32_t* ids, float* weights, void* stream) {
232    if (!stream || !valid(logits, 512 * 4) || !valid(ids, 10 * 4) || !valid(weights, 10 * 4)
233        || overlap(logits, 512 * 4, ids, 10 * 4) || overlap(logits, 512 * 4, weights, 10 * 4)
234        || overlap(ids, 10 * 4, weights, 10 * 4))
235        throw std::invalid_argument("native router requires a stream, aligned spans, and disjoint outputs");
236    {
237        auto exp_props = sycl::ext::oneapi::experimental::properties{
238            sycl::ext::oneapi::experimental::use_root_sync};
239
240        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
241            ->template parallel_for<dpct_kernel_name<class route_96e6fb>>(
242                sycl::nd_range<3>(sycl::range(1, 8, 32), sycl::range(1, 8, 32)),
243                exp_props,
244                [=](sycl::nd_item<3> item_ct1)
245                    [[sycl::reqd_sub_group_size(32)]] {
246                        route<512>(logits, ids, weights);
247                    });
248    }
249    /*
250    DPCT1010: SYCL uses exceptions to report errors and does not use the
251    error codes. The cudaGetLastError function call was replaced with 0. You
252    need to rewrite this code.
253    */
254    const auto error = 0;
255    /*
256    DPCT1009: SYCL reports errors using exceptions and does not use error
257    codes. Please replace the "get_error_string_dummy(...)" with a real
258    error-handling function.
259    */
260    /*
261    DPCT1001: The statement could not be removed.
262    */
263    /*
264    DPCT1000: Error handling if-stmt was detected but could not be
265    rewritten.
266    */
267    if (error !=
268        0) throw std::runtime_error(dpct::get_error_string_dummy(error));
269}
270void native_router_top10_multi(const float* logits, int32_t* ids, float* weights, int n_tok, void* stream) {
271    if (!stream || n_tok < 1 || !valid(logits, (size_t) n_tok * 512 * 4) || !valid(ids, (size_t) n_tok * 10 * 4) ||
272        !valid(weights, (size_t) n_tok * 10 * 4))
273        throw std::invalid_argument("native router (multi) requires a stream and aligned [n,512]/[n,10] buffers");
274    // SYCL port: one block per token running the single-token route<512> (the same kernel as the 256-expert multi
275    // launch below).  Upstream's one-warp-per-token route_multi gives the same bits (native_multi_parity checks
276    // that) but hung an Arc A750 (Alchemist) on its first launch.
277    strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
278        ->template parallel_for<dpct_kernel_name<class route_512_multi>>(
279            sycl::nd_range<3>(sycl::range(1, 1, (unsigned) n_tok) * sycl::range(1, 8, 32), sycl::range(1, 8, 32)),
280            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] { route<512>(logits, ids, weights); });
281    /*
282    DPCT1010: SYCL uses exceptions to report errors and does not use the
283    error codes. The cudaGetLastError function call was replaced with 0. You
284    need to rewrite this code.
285    */
286    const auto error = 0;
287    /*
288    DPCT1009: SYCL reports errors using exceptions and does not use error
289    codes. Please replace the "get_error_string_dummy(...)" with a real
290    error-handling function.
291    */
292    /*
293    DPCT1001: The statement could not be removed.
294    */
295    /*
296    DPCT1000: Error handling if-stmt was detected but could not be
297    rewritten.
298    */
299    if (error !=
300        0) throw std::runtime_error(dpct::get_error_string_dummy(error));
301}
302
303void native_router_top10_multi_ne(const float* logits, int32_t* ids, float* weights, int n_tok, int n_expert, void* stream) {
304    if (n_expert == 512) { native_router_top10_multi(logits, ids, weights, n_tok, stream); return; }
305    if (!stream || n_tok < 1 || n_expert != 256 || !valid(logits, (size_t) n_tok * 256 * 4) || !valid(ids, (size_t) n_tok * 10 * 4) ||
306        !valid(weights, (size_t) n_tok * 10 * 4))
307        throw std::invalid_argument("native router (multi, 256): a stream, 256 experts and aligned [n,256]/[n,10] buffers");
308    strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
309        ->template parallel_for<dpct_kernel_name<class route_256_multi>>(
310            sycl::nd_range<3>(sycl::range(1, 1, (unsigned) n_tok) * sycl::range(1, 8, 32), sycl::range(1, 8, 32)),
311            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] { route<256>(logits, ids, weights); });
312}
313}