okami.mom/strata

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

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

main
17.5 KiB383 linesraw
1// Specialized from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d,
2// ggml/src/ggml-cuda/{fattn-vec.cuh,fattn-common.cuh,common.cuh}.
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#define DPCT_PROFILING_ENABLED
22#include <sycl/sycl.hpp>
23#include "strata/kprof.hpp"
24#include <dpct/dpct.hpp>
25#include "strata/sycl_queue.hpp"
26#include "strata/kernels/native_flash_attn.hpp"
27#include <cfloat>
28#include <cstddef>
29#include <cstdint>
30#include <limits>
31#include <stdexcept>
32#include <string>
33#include <cmath>
34
35namespace strata::kernels {
36namespace {
37template <int Width> __dpct_inline__ float warp_sum(float x) {
38#pragma unroll
39    for (int offset = Width / 2; offset; offset >>= 1)
40        /*
41        DPCT1108: '__shfl_xor_sync' was migrated with the experimental
42        feature masked sub_group function which may not be supported by all
43        compilers or runtimes. You may need to adjust the code.
44        */
45        x += dpct::experimental::permute_sub_group_by_xor(
46            0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), x,
47            offset, Width);
48    return x;
49}
50__dpct_inline__ float warp_max(float x) {
51#pragma unroll
52    for (int offset = 16; offset; offset >>= 1)
53        /*
54        DPCT1108: '__shfl_xor_sync' was migrated with the experimental
55        feature masked sub_group function which may not be supported by all
56        compilers or runtimes. You may need to adjust the code.
57        */
58        x = sycl::fmax(x,
59                       dpct::experimental::permute_sub_group_by_xor(
60                           0xffffffffu,
61                           sycl::ext::oneapi::this_work_item::get_sub_group(),
62                           x, offset));
63    return x;
64}
65
66// D=256,ncols=1,F16/F16; 128 threads, nthreads_KQ=nthreads_V=8,
67// four values (float2) per load, four V columns per iteration. Padded length256
68// gives ntiles_KV=ceil(256/D)=1, so the pinned launcher selects grid.y=1.
69/*
70DPCT1110: The total declared local variable size in device function attend
71exceeds 128 bytes and may cause high register pressure. Consult with your
72hardware vendor to find the total register size available and adjust the code,
73or use smaller sub-group size to avoid high register pressure.
74*/
75__dpct_inline__ void
76attend(const float *__restrict__ q, const sycl::half *__restrict__ k,
77       const sycl::half *__restrict__ v, const int32_t *__restrict__ step,
78       int max_context, int padded_length, float scale, float *__restrict__ out,
79       int32_t *__restrict__ status, const sycl::half *__restrict__ mask) {
80    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
81    const int lane = item_ct1.get_local_id(2), warp = item_ct1.get_local_id(1),
82              tid = warp * 32 + lane;
83    const int head = item_ct1.get_group(2), kv = head / 12;
84    const int width = step[kStepWidth], nkv = step[kStepNKv];
85    const bool valid = width >= 1 && width <= max_context && nkv == width &&
86                       step[kStepPos] == width - 1 && step[kStepNBid] == width / 4;
87    if (head == 0 && tid == 0)
88        *status = valid ? kNativeFlashAttnSuccess : kNativeFlashAttnUnsupportedStep;
89    if (!valid) {
90        out[head * 256 + tid] = sycl::bit_cast<float>(0x7fc00000);
91        out[head * 256 + tid + 128] = sycl::bit_cast<float>(0x7fc00000);
92        return;
93    }
94    sycl::float2 qreg[16];
95    sycl::float2 vkq[16] = {};
96    auto &tile = *sycl::ext::oneapi::group_local_memory_for_overwrite<
97        float[4 * 4 * 256]>(
98        sycl::ext::oneapi::this_work_item::get_work_group<3>());
99    auto &max_shared =
100        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(
101            sycl::ext::oneapi::this_work_item::get_work_group<3>());
102    auto &sum_shared =
103        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(
104            sycl::ext::oneapi::this_work_item::get_work_group<3>());
105    float maximum = -FLT_MAX / 2.0f, sum = 0.0f;
106#pragma unroll
107    for (int i0 = 0; i0 < 128; i0 += 32) {
108        const int i = i0 + (lane % 8) * 4;
109#pragma unroll
110        for (int j = 0; j < 4; ++j) {
111            const int d = 2 * (i + j);
112            qreg[i0 / 8 + j] = sycl::float2(q[head * 256 + d] * scale,
113                                            q[head * 256 + d + 1] * scale);
114        }
115    }
116    for (int base = 0; base < padded_length; base += 128) {
117        float score = 0.0f, next_max = maximum;
118#pragma unroll
119        for (int row = 0; row < 8; ++row) {
120            const int cell = base + warp * 32 + (lane & ~7) + row;
121            float dot = 0.0f;
122#pragma unroll
123            for (int i0 = 0; i0 < 128; i0 += 32) {
124                const int i = i0 + (lane % 8) * 4;
125#pragma unroll
126                for (int j = 0; j < 4; ++j) {
127                    const int d = 2 * (i + j);
128                    const float a =
129                        cell < width
130                            ? sycl::vec<sycl::half, 1>(
131                                  k[(cell * 2 + kv) * 256 + d])
132                                  .convert<float,
133                                           sycl::rounding_mode::automatic>()[0]
134                            : 0.0f;
135                    const float b =
136                        cell < width
137                            ? sycl::vec<sycl::half, 1>(
138                                  k[(cell * 2 + kv) * 256 + d + 1])
139                                  .convert<float,
140                                           sycl::rounding_mode::automatic>()[0]
141                            : 0.0f;
142                    dot += a * qreg[i0 / 8 + j].x();
143                    dot += b * qreg[i0 / 8 + j].y();
144                }
145            }
146            dot = warp_sum<8>(dot);
147            dot +=
148                cell < width
149                    ? (mask ? sycl::vec<sycl::half, 1>(mask[cell])
150                                  .convert<float,
151                                           sycl::rounding_mode::automatic>()[0]
152                            : 0.0f)
153                    : sycl::bit_cast<float, int>(0xff800000u);
154            next_max = sycl::fmax(next_max, dot + (3.0f * 0.6931f));
155            if (lane % 8 == row) score = dot;
156        }
157#pragma unroll
158        for (int offset = 8; offset < 32; offset <<= 1)
159            /*
160            DPCT1108: '__shfl_xor_sync' was migrated with the experimental
161            feature masked sub_group function which may not be supported by all
162            compilers or runtimes. You may need to adjust the code.
163            */
164            next_max = sycl::fmax(
165                next_max,
166                dpct::experimental::permute_sub_group_by_xor(
167                    0xffffffffu,
168                    sycl::ext::oneapi::this_work_item::get_sub_group(),
169                    next_max, offset));
170        const float rescale = sycl::native::exp(maximum - next_max);
171        maximum = next_max;
172        score = sycl::native::exp(score - maximum);
173        sum = sum * rescale + score;
174        tile[tid] = score;
175        sycl::group_barrier(sycl::ext::oneapi::this_work_item::get_sub_group());
176#pragma unroll
177        for (int k0 = 0; k0 < 32; k0 += 4) {
178            const int local = warp * 32 + k0 + lane / 8, cell = base + local;
179            const float weight = tile[local];
180#pragma unroll
181            for (int i0 = 0; i0 < 128; i0 += 32) {
182                const int i = i0 + (lane % 8) * 4;
183#pragma unroll
184                for (int j = 0; j < 4; ++j) {
185                    const int d = 2 * (i + j);
186                    const float a =
187                        cell < width
188                            ? sycl::vec<sycl::half, 1>(
189                                  v[(cell * 2 + kv) * 256 + d])
190                                  .convert<float,
191                                           sycl::rounding_mode::automatic>()[0]
192                            : 0.0f;
193                    const float b =
194                        cell < width
195                            ? sycl::vec<sycl::half, 1>(
196                                  v[(cell * 2 + kv) * 256 + d + 1])
197                                  .convert<float,
198                                           sycl::rounding_mode::automatic>()[0]
199                            : 0.0f;
200                    // The pinned sm120a binary contracts the old-accumulator
201                    // rescale with the FIRST addition: fma(rescale,old,round(V*w)).
202                    // Later columns use fma(V,w,acc). Explicit intrinsics retain
203                    // that order despite this adapter's masked-load branches.
204                    if (k0 == 0) {
205                        /*
206                        DPCT1013: The rounding mode could not be specified
207                        and the generated code may have different accuracy than
208                        the original code. Verify the correctness. SYCL math
209                        built-in function rounding mode is aligned with OpenCL
210                        C 1.2 standard.
211                        */
212                        vkq[i0 / 8 + j].x() =
213                            sycl::fma(rescale, vkq[i0 / 8 + j].x(), a * weight);
214                        /*
215                        DPCT1013: The rounding mode could not be specified
216                        and the generated code may have different accuracy than
217                        the original code. Verify the correctness. SYCL math
218                        built-in function rounding mode is aligned with OpenCL
219                        C 1.2 standard.
220                        */
221                        vkq[i0 / 8 + j].y() =
222                            sycl::fma(rescale, vkq[i0 / 8 + j].y(), b * weight);
223                    } else {
224                        /*
225                        DPCT1013: The rounding mode could not be specified
226                        and the generated code may have different accuracy than
227                        the original code. Verify the correctness. SYCL math
228                        built-in function rounding mode is aligned with OpenCL
229                        C 1.2 standard.
230                        */
231                        vkq[i0 / 8 + j].x() =
232                            sycl::fma(a, weight, vkq[i0 / 8 + j].x());
233                        /*
234                        DPCT1013: The rounding mode could not be specified
235                        and the generated code may have different accuracy than
236                        the original code. Verify the correctness. SYCL math
237                        built-in function rounding mode is aligned with OpenCL
238                        C 1.2 standard.
239                        */
240                        vkq[i0 / 8 + j].y() =
241                            sycl::fma(b, weight, vkq[i0 / 8 + j].y());
242                    }
243                }
244            }
245        }
246    }
247    if (warp == 0) { max_shared[lane] = -FLT_MAX / 2.0f; sum_shared[lane] = 0.0f; }
248    /*
249    DPCT1065: Consider replacing sycl::nd_item::barrier() with
250    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
251    performance if there is no access to global memory.
252    */
253    item_ct1.barrier();
254    if (lane == 0) max_shared[warp] = maximum;
255    /*
256    DPCT1065: Consider replacing sycl::nd_item::barrier() with
257    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
258    performance if there is no access to global memory.
259    */
260    item_ct1.barrier();
261    const float global_max = warp_max(max_shared[lane]);
262    const float rescale = sycl::native::exp(maximum - global_max);
263#pragma unroll
264    for (int i = 0; i < 16; ++i) {
265        /*
266        DPCT1013: The rounding mode could not be specified and the
267        generated code may have different accuracy than the original code.
268        Verify the correctness. SYCL math built-in function rounding mode is
269        aligned with OpenCL C 1.2 standard.
270        */
271        vkq[i].x() = vkq[i].x() * rescale;
272        /*
273        DPCT1013: The rounding mode could not be specified and the
274        generated code may have different accuracy than the original code.
275        Verify the correctness. SYCL math built-in function rounding mode is
276        aligned with OpenCL C 1.2 standard.
277        */
278        vkq[i].y() = vkq[i].y() * rescale;
279    }
280#pragma unroll
281    for (int i0 = 0; i0 < 128; i0 += 32) {
282        const int start = warp * 4 * 256 + (lane / 8) * 256 + 2 * (i0 + (lane % 8) * 4);
283#pragma unroll
284        for (int j = 0; j < 4; ++j) {
285            tile[start + 2 * j] = vkq[i0 / 8 + j].x();
286            tile[start + 2 * j + 1] = vkq[i0 / 8 + j].y();
287        }
288    }
289    sum *= rescale;
290    sum = warp_sum<32>(sum);
291    if (lane == 0) sum_shared[warp] = sum;
292    /*
293    DPCT1065: Consider replacing sycl::nd_item::barrier() with
294    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
295    performance if there is no access to global memory.
296    */
297    item_ct1.barrier();
298    sum = warp_sum<32>(sum_shared[lane]);
299#pragma unroll
300    for (int i0 = 0; i0 < 256; i0 += 128) {
301        float result = 0.0f;
302#pragma unroll
303        for (int w = 0; w < 4; ++w) {
304#pragma unroll
305            for (int group = 0; group < 4; ++group)
306                result += tile[w * 4 * 256 + group * 256 + i0 + tid];
307        }
308        out[head * 256 + i0 + tid] = result / sum;
309    }
310}
311struct Span { const void* p; std::size_t n, alignment; };
312void validate_spans(const Span* spans, int count) {
313    for (int i = 0; i < count; ++i) {
314        const auto a = reinterpret_cast<std::uintptr_t>(spans[i].p);
315        if (!a || a % spans[i].alignment || spans[i].n > UINTPTR_MAX - a)
316            throw std::invalid_argument("native FlashAttention requires nonnull aligned bounded spans");
317        for (int j = 0; j < i; ++j) {
318            const auto b = reinterpret_cast<std::uintptr_t>(spans[j].p);
319            if (a < b + spans[j].n && b < a + spans[i].n)
320                throw std::invalid_argument("native FlashAttention requires disjoint buffers");
321        }
322    }
323}
324} // namespace
325
326void native_flash_attn_short_step(const float* q, const uint16_t* k, const uint16_t* v,
327                                  const int32_t* step, int64_t capacity, int max_context,
328                                  const QsaShapes& shapes, float* output, int32_t* status,
329                                  const uint16_t* mask, void* stream) {
330    if (!stream || shapes.n_head != 24 || shapes.n_head_kv != 2 || shapes.head_dim != 256 ||
331        shapes.idx_block != 4 || shapes.idx_top_k < 256 || capacity < 256 ||
332        uint64_t(capacity) > std::numeric_limits<std::size_t>::max() / 1024 ||
333        max_context < 1 || max_context > 256)
334        throw std::invalid_argument("native FlashAttention supports only Q24x256/KV2x256, capacity>=256 and context1..256 on an explicit stream");
335    const std::size_t kv_bytes = std::size_t(capacity) * 1024;
336    const Span spans[] = {{q, 24 * 256 * 4, 4}, {k, kv_bytes, 2}, {v, kv_bytes, 2},
337                          {step, kStepCount * 4, 4}, {output, 24 * 256 * 4, 4},
338                          {status, 4, 4}, {mask, 256 * 2, 2}};
339    validate_spans(spans, mask ? 7 : 6);
340    {
341        auto exp_props = sycl::ext::oneapi::experimental::properties{
342            sycl::ext::oneapi::experimental::use_root_sync};
343        dpct::has_capability_or_fail(
344            ((sycl::queue *)(strata::q_of(stream)))
345                ->get_device(),
346            {sycl::aspect::fp16});
347
348        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
349            ->template parallel_for<dpct_kernel_name<class attend_9d5505>>(
350                sycl::nd_range<3>(sycl::range(1, 1, 24) * sycl::range(1, 4, 32),
351                                  sycl::range(1, 4, 32)),
352                exp_props,
353                [=](sycl::nd_item<3> item_ct1)
354                    [[sycl::reqd_sub_group_size(32)]] {
355                        attend(q, reinterpret_cast<const sycl::half *>(k),
356                               reinterpret_cast<const sycl::half *>(v), step,
357                               max_context, 256, 0.0625f, output, status,
358                               reinterpret_cast<const sycl::half *>(mask));
359                    });
360    }
361    /*
362    DPCT1010: SYCL uses exceptions to report errors and does not use the
363    error codes. The cudaGetLastError function call was replaced with 0. You
364    need to rewrite this code.
365    */
366    const auto result = 0;
367    /*
368    DPCT1000: Error handling if-stmt was detected but could not be
369    rewritten.
370    */
371    if (result != 0)
372        /*
373        DPCT1009: SYCL reports errors using exceptions and does not use
374        error codes. Please replace the "get_error_string_dummy(...)" with a
375        real error-handling function.
376        */
377        /*
378        DPCT1001: The statement could not be removed.
379        */
380        throw std::runtime_error(std::string("native FlashAttention launch: ") +
381                                 dpct::get_error_string_dummy(result));
382}
383} // namespace strata::kernels