okami.mom/strata

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

Niko1221Merge f-sycl-prs e106b4c86 into the batch 16 candidate (SYCL pull requests 4185 and 3153)a8a51b280

main
185.1 KiB3845 linesraw
1#include "b60_weight_cache.hpp"
2#include "b60_layout_state.hpp"
3#include "strata/kernels/q8_1_finite.hpp"
4// src/kernels/cuda/fused_gr.cu - see include/strata/kernels/fused_gr.hpp.
5#define DPCT_PROFILING_ENABLED
6#include <mutex>
7#include "strata/kprof.hpp"
8#include <sycl/ext/intel/esimd.hpp>
9#include <sycl/ext/intel/experimental/esimd/math.hpp>
10#include "strata/core/geometry.hpp"
11#include <unordered_map>
12#include <sycl/sycl.hpp>
13#include <utility>
14#include <sycl/ext/intel/experimental/grf_size_properties.hpp>
15#include <dpct/dpct.hpp>
16#include "strata/sycl_queue.hpp"
17#include "strata/workload_trace.hpp"
18#include "strata/core/emulate.hpp"
19#include "strata/kernels/fused_gr.hpp"
20#include "strata/kernels/bf16_bits.hpp"
21#include "strata/kernels/verify_kernels.hpp"
22
23#include <atomic>
24#include <cstdio>
25#include <cstdlib>
26#include <cstring>
27#include <random>
28#include <string>
29#include <vector>
30
31namespace strata::kernels {
32namespace {
33
34constexpr int N = strata::core::kCompiledGeometry.n_embd;         // 2560 in Flash-Next
35constexpr int HC = strata::core::kCompiledGeometry.hc;           // streams
36constexpr int D = N * HC;       // 10240
37constexpr int LR = strata::core::kCompiledGeometry.hc_lr;         // 320
38static_assert(N % 512 == 0 && LR % 64 == 0 && LR >= 256 && LR <= 512, "fused_gr: n_embd must be a multiple of 512 and hc_lr one of 256..512 in steps of 64 (the lane rule `lane < LR / 8 - 32` and the 128-column slices)");
39constexpr int THREADS = 256;
40constexpr int WARPS = THREADS / 32;
41#if defined(__HIPCC__)
42constexpr int TILE = N / 2;            // eight-token tile fits gfx1100's 64 KiB LDS limit
43#else
44constexpr int TILE = N;                // xn floats per token staged at a time: 320 chunks of 8, 10 per lane (Flash-Next)
45#endif
46// The single-token down kernel keeps the whole normalised hidden row (D floats) in work-group local memory: static while that
47// fits 48 KB (Flash-Next: 40 KB).  Beyond it (hidden 3072 and up) fused_gr_read takes the multi-token read of one token, which is
48// bitwise the same read (the sliced / split kernels need 4 KB of local memory) and the default path anyway.
49constexpr bool kDownXnTooBig = (size_t) D * 4 + 512 > 48 * 1024;
50constexpr int TQ = TILE / 8 / 32;      // uint4 weight chunks per lane per tile
51// SYCL port: the down kernel's 41 work-groups filled 15% of the B70's threads (metrics 2026-09-30); each row's
52// D = 4 tiles are split over DOWN_SPLIT work-groups that write partial sums, summed in a fixed order by the up
53// kernel (deterministic, unlike atomics) before the row's nonlinearity.
54#ifndef STRATA_GR_DOWN_SPLIT
55#define STRATA_GR_DOWN_SPLIT (D / TILE)   // 4: one tile per split (1: the unsplit order, for A/B)
56#endif
57constexpr int DOWN_SPLIT = STRATA_GR_DOWN_SPLIT;
58constexpr int DOWN_BLOCKS = LR / WARPS;          // 40 blocks of 8 rows; one more for the inject rows
59constexpr int UP_COLS = 32;                      // columns d per `up` block (x 4 streams = 128 rows)
60constexpr int UP_BLOCKS = N / UP_COLS;           // 80
61
62__dpct_inline__ float warp_sum(float v) {
63#pragma unroll
64    /*
65    DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature
66    masked sub_group function which may not be supported by all compilers or
67    runtimes. You may need to adjust the code.
68    */
69    for (int o = 16; o > 0; o >>= 1) v +=
70        dpct::experimental::permute_sub_group_by_xor(
71            0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), v,
72            o);
73    return v;
74}
75
76int g_gr_cached_norm_mode=[](){
77    const char* e=std::getenv("STRATA_SYCL_GR_CACHED_NORM");
78    return e&&std::atoi(e)==3?3:0;
79}();
80bool gr_overlap(const void* a,size_t as,const void* b,size_t bs){
81    if(!a||!b||!as||!bs)return false;
82    const uintptr_t av=reinterpret_cast<uintptr_t>(a),bv=reinterpret_cast<uintptr_t>(b);
83    return av<=bv?bv-av<as:av-bv<bs;
84}
85bool gr_cached_norm_safe(const FusedGrArgs* a,int T,const float* xn){
86    for(int k=0;k<T;++k){
87        if(!a[k].apply)continue;
88        const auto* out=a[k].R_out;
89        if(!out||(reinterpret_cast<uintptr_t>(out)&15u)||gr_overlap(out,D*4,xn,size_t(T)*D*4))return false;
90        for(int j=0;j<T;++j){
91            if(!(j==k&&out==a[j].R)&&gr_overlap(out,D*4,a[j].R,D*4))return false;
92            if(j!=k&&a[j].apply&&gr_overlap(out,D*4,a[j].R_out,D*4))return false;
93            if(gr_overlap(out,D*4,a[j].bo_prev,N*4)||
94               gr_overlap(out,D*4,a[j].inj_prev,HC*4)||
95               gr_overlap(out,D*4,a[j].w_norm,D*4)||
96               gr_overlap(out,D*4,a[j].w_down,size_t(LR)*D*2)||
97               gr_overlap(out,D*4,a[j].w_up,size_t(D)*LR*2)||
98               gr_overlap(out,D*4,a[j].w_inject,size_t(HC)*D*2)||
99               gr_overlap(out,D*4,a[j].lo,LR*4)||
100               gr_overlap(out,D*4,a[j].rs,HC*4)||
101               gr_overlap(out,D*4,a[j].inject_out,HC*4)||
102               gr_overlap(out,D*4,a[j].mixed,N*4))return false;
103        }
104    }
105    return true;
106}
107__dpct_inline__ float sigmoidf_(float x) {
108    return 1.0f / (1.0f + sycl::native::exp(-x));
109}
110
111// 8 bf16 packed in a uint4 against 8 floats.
112__dpct_inline__ float dot8(const sycl::uint4 w, const float *x) {
113    float acc = 0.0f;
114    const uint32_t v[4] = {w.x(), w.y(), w.z(), w.w()};
115#pragma unroll
116    for (int j = 0; j < 4; ++j) {
117        acc = sycl::fma(sycl::bit_cast<float>(v[j] << 16), (float)(x[2 * j]),
118                        acc);
119        acc = sycl::fma(sycl::bit_cast<float>(v[j] & 0xffff0000u),
120                        (float)(x[2 * j + 1]), acc);
121    }
122    return acc;
123}
124
125/*
126DPCT1110: The total declared local variable size in device function
127gr_down_kernel exceeds 128 bytes and may cause high register pressure. Consult
128with your hardware vendor to find the total register size available and adjust
129the code, or use smaller sub-group size to avoid high register pressure.
130*/
131__dpct_inline__ void gr_down_kernel(FusedGrArgs a) {
132    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
133auto &xn = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[kDownXnTooBig ? 1 : D]>(
134    sycl::ext::oneapi::this_work_item::get_work_group<3>());
135    auto &part =
136        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[WARPS][HC]>(
137            sycl::ext::oneapi::this_work_item::get_work_group<3>());
138    auto &s_rs =
139        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[HC]>(
140            sycl::ext::oneapi::this_work_item::get_work_group<3>());
141    const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
142    float gw[HC];
143#pragma unroll
144    for (int c = 0; c < HC; ++c) gw[c] = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f;
145    // 1. R' * w_norm into shared memory, and the per-stream sums of squares of R'.
146    float ss[HC] = {0.0f, 0.0f, 0.0f, 0.0f};
147    for (int i = t * 4; i < D; i += THREADS * 4) {
148        const int c = i / N, d = i - c * N;
149        sycl::float4 r = *reinterpret_cast<const sycl::float4 *>(a.R + i);
150        if (a.apply) {
151            const sycl::float4 b =
152                *reinterpret_cast<const sycl::float4 *>(a.bo_prev + d);
153            r.x() = sycl::fma((float)(b.x()), gw[c], r.x());
154                r.y() = sycl::fma((float)(b.y()), gw[c], r.y());
155            r.z() = sycl::fma((float)(b.z()), gw[c], r.z());
156                r.w() = sycl::fma((float)(b.w()), gw[c], r.w());
157        }
158        const sycl::float4 g =
159            *reinterpret_cast<const sycl::float4 *>(a.w_norm + i);
160        float sq =
161            r.x() * r.x() + r.y() * r.y() + r.z() * r.z() + r.w() * r.w();
162#pragma unroll
163        for (int cc = 0; cc < HC; ++cc) if (cc == c) ss[cc] += sq;
164        *reinterpret_cast<sycl::float4 *>(xn + i) = sycl::float4(
165            r.x() * g.x(), r.y() * g.y(), r.z() * g.z(), r.w() * g.w());
166    }
167#pragma unroll
168    for (int c = 0; c < HC; ++c) {
169        const float v = warp_sum(ss[c]);
170        if (lane == 0) part[warp][c] = v;
171    }
172    /*
173    DPCT1065: Consider replacing sycl::nd_item::barrier() with
174    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
175    performance if there is no access to global memory.
176    */
177    item_ct1.barrier();
178    if (t < HC) {
179        float s = 0.0f;
180#pragma unroll
181        for (int w = 0; w < WARPS; ++w) s += part[w][t];
182        s_rs[t] = sycl::rsqrt(s / (float)N + a.eps);
183        if (item_ct1.get_group(2) == 0) a.rs[t] = s_rs[t];
184    }
185    /*
186    DPCT1065: Consider replacing sycl::nd_item::barrier() with
187    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
188    performance if there is no access to global memory.
189    */
190    item_ct1.barrier();
191#pragma unroll
192    for (int i = t; i < D; i += THREADS) xn[i] *= s_rs[i / N];
193    /*
194    DPCT1065: Consider replacing sycl::nd_item::barrier() with
195    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
196    performance if there is no access to global memory.
197    */
198    item_ct1.barrier();
199    // 2. one warp per output row: 10240 bf16 = 1280 chunks of 8, 40 per lane.
200    const bool inject_block = item_ct1.get_group(2) == DOWN_BLOCKS;
201    const int row = inject_block ? warp : item_ct1.get_group(2) * WARPS + warp;
202    if (inject_block && (a.w_inject == nullptr || warp >= HC)) return;
203    const uint16_t* wrow = (inject_block ? a.w_inject : a.w_down) + (size_t) row * D;
204    const sycl::uint4 *w4 = reinterpret_cast<const sycl::uint4 *>(wrow);
205    // SYCL port: the multi kernel's order - per-tile partial sums for the split rows (gr_parity: bit-identical),
206    // the inject rows still one accumulation over the whole row (their block is not split there)
207    float acc = 0.0f;
208    if (inject_block) {
209#pragma unroll 4
210        for (int j = lane; j < D / 8; j += 32) acc += dot8(*(w4 + j), xn + j * 8);
211        acc = warp_sum(acc);
212    } else {
213        for (int sp = 0; sp < DOWN_SPLIT; ++sp) {
214            float part = 0.0f;
215#pragma unroll 5
216            for (int j = lane + sp * (TILE / 8); j < (sp + 1) * (TILE / 8); j += 32) part += dot8(*(w4 + j), xn + j * 8);
217            acc += warp_sum(part);
218        }
219    }
220    if (lane != 0) return;
221    if (inject_block) {
222        a.inject_out[row] = acc;
223    } else {
224        const float x = acc / (float) HC;
225        a.lo[row] = x / (1.0f + sycl::native::exp(-x));
226    }
227}
228
229__dpct_inline__ void gr_up_kernel(FusedGrArgs a) {
230    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
231auto &lo = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[LR]>(
232    sycl::ext::oneapi::this_work_item::get_work_group<3>());
233    auto &g = *sycl::ext::oneapi::group_local_memory_for_overwrite<
234        float[HC][UP_COLS]>(
235        sycl::ext::oneapi::this_work_item::get_work_group<3>());
236    const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
237    const int d0 = item_ct1.get_group(2) * UP_COLS;
238#pragma unroll
239    for (int k = t; k < LR; k += THREADS) lo[k] = a.lo[k];
240    /*
241    DPCT1065: Consider replacing sycl::nd_item::barrier() with
242    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
243    performance if there is no access to global memory.
244    */
245    item_ct1.barrier();
246    // 128 rows (4 streams x 32 columns), 16 per warp: 320 bf16 = 40 chunks of 8.
247    for (int r = warp; r < HC * UP_COLS; r += WARPS) {
248        const int c = r / UP_COLS, dd = r - c * UP_COLS, i = c * N + d0 + dd;
249        const sycl::uint4 *w4 =
250            reinterpret_cast<const sycl::uint4 *>(a.w_up + (size_t)i * LR);
251        /*
252        DPCT1098: The '*' expression is used instead of the __ldg call.
253        These two expressions do not provide the exact same functionality. Check
254        the generated code for potential precision and/or performance issues.
255        */
256        float acc = dot8(*(w4 + lane), lo + lane * 8);
257        /*
258        DPCT1098: The '*' expression is used instead of the __ldg call.
259        These two expressions do not provide the exact same functionality. Check
260        the generated code for potential precision and/or performance issues.
261        */
262        if (lane < LR / 8 - 32) acc +=
263            dot8(*(w4 + 32 + lane), lo + (32 + lane) * 8);
264        acc = warp_sum(acc);
265        if (lane == 0) {
266            float rv = a.R[i];
267            if (a.apply) {
268                rv = sycl::fma((float)(a.bo_prev[d0 + dd]),
269                               2.0f * sigmoidf_(a.inj_prev[c] / (float)HC), rv);
270                a.R_out[i] = rv;                       // this block owns column d0+dd of every stream
271            }
272            const float x = rv * a.w_norm[i] * a.rs[c];
273            g[c][dd] = x * sigmoidf_(acc);
274        }
275    }
276    /*
277    DPCT1065: Consider replacing sycl::nd_item::barrier() with
278    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
279    performance if there is no access to global memory.
280    */
281    item_ct1.barrier();
282    if (t < UP_COLS) {
283        float s = 0.0f;
284#pragma unroll
285        for (int c = 0; c < HC; ++c) s += g[c][t];
286        a.mixed[d0 + t] = s / (float) HC;
287    }
288}
289
290// ================================ plan v0.3 P6: T tokens, one weight read ================================
291struct GrMulti {
292    FusedGrArgs a[kFusedGrMaxT];
293    float* xn;
294    int T;
295    float* part;   ///< [DOWN_SPLIT][kFusedGrMaxT][LR] partial row sums of the down kernel
296    int nsplit = DOWN_SPLIT;   ///< SYCL port: splits the up kernel sums (1 after the sliced down kernel's reduce)
297    float* part2 = nullptr;    ///< SYCL port: [GRS_SLICES][kFusedGrMaxT][LR + HC] slice partials of the sliced kernel
298    bool cached_norm = false;
299    bool cached_lo = false;
300};
301
302// gr_overlap: defined once above (the #3153 helper; the #4185 port's copy of it was the same function)
303
304bool gr_reuse_safe(const FusedGrArgs* a, int T, const float* xn) {
305    for (int k = 0; k < T; ++k) {
306        const std::pair<const void*, size_t> spans[] = {
307            {a[k].R, D * sizeof(float)}, {a[k].R_out, D * sizeof(float)},
308            {a[k].bo_prev, N * sizeof(float)}, {a[k].inj_prev, HC * sizeof(float)},
309            {a[k].w_norm, D * sizeof(float)}, {a[k].w_down, size_t(LR) * D * sizeof(uint16_t)},
310            {a[k].w_up, size_t(D) * LR * sizeof(uint16_t)},
311            {a[k].w_inject, size_t(HC) * D * sizeof(uint16_t)},
312            {a[k].rs, HC * sizeof(float)}, {a[k].inject_out, HC * sizeof(float)},
313            {a[k].mixed, N * sizeof(float)},
314        };
315        if (gr_overlap(xn, size_t(T) * D * sizeof(float), a[k].lo, LR * sizeof(float)))
316            return false;
317        for (const auto& span : spans) {
318            if (gr_overlap(xn, size_t(T) * D * sizeof(float), span.first, span.second))
319                return false;
320            for (int j = 0; j < T; ++j)
321                if (gr_overlap(a[j].lo, LR * sizeof(float), span.first, span.second))
322                    return false;
323        }
324        for (int j = 0; j < k; ++j)
325            if (gr_overlap(a[j].lo, LR * sizeof(float), a[k].lo, LR * sizeof(float)))
326                return false;
327    }
328    return true;
329}
330
331// SYCL port (Arc): a RUNTIME index into the by-value kernel argument (m.a[k]) makes IGC copy the whole GrMulti
332// (~1.2 KB) into every work-item's private scratch - unitrace: ~40 KB private per SIMD32 thread on the A770 for
333// gr_up_multi / gr_down_reduce / gr_norm_split. GR_PICK selects ONE field with compile-time indices only (a chain
334// of selects over uniform kernel arguments), so nothing is copied. Addressing only: values and orders unchanged.
335template <class F, std::size_t... J>
336__dpct_inline__ auto gr_pick_impl(const GrMulti& m, int k, F f, std::index_sequence<J...>) {
337    auto v = f(m.a[0]);
338    ((v = (k == (int) J) ? f(m.a[J]) : v), ...);
339    return v;
340}
341#define GR_PICK(m, k, field) \
342    gr_pick_impl((m), (k), [](const FusedGrArgs& x_) { return x_.field; }, std::make_index_sequence<kFusedGrMaxT>{})
343
344// Step 1 of `gr_down_kernel`, one block per token, same threads and reduction order: rs[t] and xn[t] to global.
345/*
346DPCT1110: The total declared local variable size in device function
347gr_norm_multi_kernel exceeds 128 bytes and may cause high register pressure.
348Consult with your hardware vendor to find the total register size available and
349adjust the code, or use smaller sub-group size to avoid high register pressure.
350*/
351__dpct_inline__ void gr_norm_multi_kernel(GrMulti m) {
352    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
353auto &part =
354    *sycl::ext::oneapi::group_local_memory_for_overwrite<float[WARPS][HC]>(
355        sycl::ext::oneapi::this_work_item::get_work_group<3>());
356    auto &s_rs =
357        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[HC]>(
358            sycl::ext::oneapi::this_work_item::get_work_group<3>());
359    const FusedGrArgs &a = m.a[item_ct1.get_group(2)];
360    float *xn = m.xn + (size_t)item_ct1.get_group(2) * D;
361    const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
362    float gw[HC];
363#pragma unroll
364    for (int c = 0; c < HC; ++c) gw[c] = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f;
365    float ss[HC] = {0.0f, 0.0f, 0.0f, 0.0f};
366    for (int i = t * 4; i < D; i += THREADS * 4) {
367        const int c = i / N, d = i - c * N;
368        sycl::float4 r = *reinterpret_cast<const sycl::float4 *>(a.R + i);
369        if (a.apply) {
370            const sycl::float4 b =
371                *reinterpret_cast<const sycl::float4 *>(a.bo_prev + d);
372            r.x() = sycl::fma((float)(b.x()), gw[c], r.x());
373                r.y() = sycl::fma((float)(b.y()), gw[c], r.y());
374            r.z() = sycl::fma((float)(b.z()), gw[c], r.z());
375                r.w() = sycl::fma((float)(b.w()), gw[c], r.w());
376        }
377        const sycl::float4 g =
378            *reinterpret_cast<const sycl::float4 *>(a.w_norm + i);
379        float sq =
380            r.x() * r.x() + r.y() * r.y() + r.z() * r.z() + r.w() * r.w();
381#pragma unroll
382        for (int cc = 0; cc < HC; ++cc) if (cc == c) ss[cc] += sq;
383        *reinterpret_cast<sycl::float4 *>(xn + i) = sycl::float4(
384            r.x() * g.x(), r.y() * g.y(), r.z() * g.z(), r.w() * g.w());
385    }
386#pragma unroll
387    for (int c = 0; c < HC; ++c) {
388        const float v = warp_sum(ss[c]);
389        if (lane == 0) part[warp][c] = v;
390    }
391    /*
392    DPCT1065: Consider replacing sycl::nd_item::barrier() with
393    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
394    performance if there is no access to global memory.
395    */
396    item_ct1.barrier();
397    if (t < HC) {
398        float s = 0.0f;
399#pragma unroll
400        for (int w = 0; w < WARPS; ++w) s += part[w][t];
401        s_rs[t] = sycl::rsqrt(s / (float)N + a.eps);
402        a.rs[t] = s_rs[t];
403    }
404    /*
405    DPCT1065: Consider replacing sycl::nd_item::barrier() with
406    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
407    performance if there is no access to global memory.
408    */
409    item_ct1.barrier();
410#pragma unroll
411    for (int i = t; i < D; i += THREADS) xn[i] *= s_rs[i / N];
412}
413
414
415// SYCL port: gr_norm_multi_kernel with one work-group per (token, stream) instead of per token: T groups left the
416// B70 nearly idle (16 us a call). rs is per stream, so a group owns its stream outright. Thread t visits the same
417// elements of stream c in the same order as in the per-token kernel (i = 4t + 1024k), and the warp and cross-warp
418// sums run in the same order, so rs and xn are bitwise the old kernel's. The scaled values stay in registers
419// (at most 3 float4 per thread) instead of a second pass over global memory.
420__dpct_inline__ void gr_norm_split_port_kernel(GrMulti m) {
421    auto item = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
422    auto& part = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[WARPS]>(item.get_group());
423    auto& s_rs = *sycl::ext::oneapi::group_local_memory_for_overwrite<float>(item.get_group());
424    const int tok = (int) item.get_group(2) / HC, c = (int) item.get_group(2) % HC;
425    const float* const aR = GR_PICK(m, tok, R);
426    const bool aapply = GR_PICK(m, tok, apply);
427    const float* const abo = GR_PICK(m, tok, bo_prev);
428    const float* const awn = GR_PICK(m, tok, w_norm);
429    const float aeps = GR_PICK(m, tok, eps);
430    float* const ars = GR_PICK(m, tok, rs);
431    float* xn = m.xn + (size_t) tok * D;
432    const int t = (int) item.get_local_id(2), lane = t & 31, warp = t >> 5;
433    const float gw = aapply ? 2.0f * sigmoidf_(GR_PICK(m, tok, inj_prev)[c] / (float) HC) : 0.0f;
434    constexpr int MAXK = (N + THREADS * 4 - 1) / (THREADS * 4) + 1;   // 3: float4s of one stream per thread
435    sycl::float4 keep[MAXK];
436    int kept = 0;
437    float ss = 0.0f;
438    for (int i = t * 4; i < D; i += THREADS * 4) {
439        if (i / N != c) continue;
440        const int d = i - c * N;
441        sycl::float4 r = *reinterpret_cast<const sycl::float4*>(aR + i);
442        if (aapply) {
443            const sycl::float4 b = *reinterpret_cast<const sycl::float4*>(abo + d);
444            r.x() = sycl::fma((float) (b.x()), gw, r.x());
445            r.y() = sycl::fma((float) (b.y()), gw, r.y());
446            r.z() = sycl::fma((float) (b.z()), gw, r.z());
447            r.w() = sycl::fma((float) (b.w()), gw, r.w());
448        }
449        const sycl::float4 g = *reinterpret_cast<const sycl::float4*>(awn + i);
450        ss += r.x() * r.x() + r.y() * r.y() + r.z() * r.z() + r.w() * r.w();
451        if (kept < MAXK) keep[kept++] = sycl::float4(r.x() * g.x(), r.y() * g.y(), r.z() * g.z(), r.w() * g.w());
452    }
453    const float v = warp_sum(ss);
454    if (lane == 0) part[warp] = v;
455    item.barrier(sycl::access::fence_space::local_space);
456    if (t == 0) {
457        float sum = 0.0f;
458#pragma unroll
459        for (int w = 0; w < WARPS; ++w) sum += part[w];
460        s_rs = sycl::rsqrt(sum / (float) N + aeps);
461        ars[c] = s_rs;
462    }
463    item.barrier(sycl::access::fence_space::local_space);
464    const float rs = s_rs;
465    int k = 0;
466    for (int i = t * 4; i < D && k < kept; i += THREADS * 4) {
467        if (i / N != c) continue;
468        const sycl::float4 x = keep[k++];
469        *reinterpret_cast<sycl::float4*>(xn + i) = sycl::float4(x.x() * rs, x.y() * rs, x.z() * rs, x.w() * rs);
470    }
471}
472// Visit only the owned stream, preserving thread ownership and reduction order.
473__dpct_inline__ void gr_norm_bounds_port_kernel(GrMulti m) {
474    auto item = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
475    auto& part = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[WARPS]>(item.get_group());
476    auto& s_rs = *sycl::ext::oneapi::group_local_memory_for_overwrite<float>(item.get_group());
477    const int tok = (int) item.get_group(2) / HC, c = (int) item.get_group(2) % HC;
478    const FusedGrArgs& a = m.a[tok];
479    float* xn = m.xn + (size_t) tok * D;
480    const int t = (int) item.get_local_id(2), lane = t & 31, warp = t >> 5;
481    const float gw = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f;
482    constexpr int MAXK = (N + THREADS * 4 - 1) / (THREADS * 4) + 1;   // 3: float4s of one stream per thread
483    sycl::float4 keep[MAXK];
484    int kept = 0;
485    float ss = 0.0f;
486    const int first_i = t * 4 + ((c * N - t * 4 + THREADS * 4 - 1) / (THREADS * 4)) * (THREADS * 4);
487    const int end_i = (c + 1) * N;
488    for (int i = first_i; i < end_i; i += THREADS * 4) {
489        const int d = i - c * N;
490        sycl::float4 r = *reinterpret_cast<const sycl::float4*>(a.R + i);
491        if (a.apply) {
492            const sycl::float4 b = *reinterpret_cast<const sycl::float4*>(a.bo_prev + d);
493            r.x() = sycl::fma((float) (b.x()), gw, r.x());
494            r.y() = sycl::fma((float) (b.y()), gw, r.y());
495            r.z() = sycl::fma((float) (b.z()), gw, r.z());
496            r.w() = sycl::fma((float) (b.w()), gw, r.w());
497        }
498        const sycl::float4 g = *reinterpret_cast<const sycl::float4*>(a.w_norm + i);
499        ss += r.x() * r.x() + r.y() * r.y() + r.z() * r.z() + r.w() * r.w();
500        if (kept < MAXK) keep[kept++] = sycl::float4(r.x() * g.x(), r.y() * g.y(), r.z() * g.z(), r.w() * g.w());
501    }
502    const float v = warp_sum(ss);
503    if (lane == 0) part[warp] = v;
504    item.barrier(sycl::access::fence_space::local_space);
505    if (t == 0) {
506        float sum = 0.0f;
507#pragma unroll
508        for (int w = 0; w < WARPS; ++w) sum += part[w];
509        s_rs = sycl::rsqrt(sum / (float) N + a.eps);
510        a.rs[c] = s_rs;
511    }
512    item.barrier(sycl::access::fence_space::local_space);
513    const float rs = s_rs;
514    int k = 0;
515    for (int i = first_i; i < end_i && k < kept; i += THREADS * 4) {
516        const sycl::float4 x = keep[k++];
517        *reinterpret_cast<sycl::float4*>(xn + i) = sycl::float4(x.x() * rs, x.y() * rs, x.z() * rs, x.w() * rs);
518    }
519}
520// Cached normalized product with the original optional pending write.
521__dpct_inline__ void gr_norm_cached_write_kernel(GrMulti m) {
522    auto item = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
523    auto& part = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[WARPS]>(item.get_group());
524    auto& s_rs = *sycl::ext::oneapi::group_local_memory_for_overwrite<float>(item.get_group());
525    const int tok = (int) item.get_group(2) / HC, c = (int) item.get_group(2) % HC;
526    const FusedGrArgs& a = m.a[tok];
527    float* xn = m.xn + (size_t) tok * D;
528    const int t = (int) item.get_local_id(2), lane = t & 31, warp = t >> 5;
529    const float gw = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f;
530    constexpr int MAXK = (N + THREADS * 4 - 1) / (THREADS * 4) + 1;   // 3: float4s of one stream per thread
531    sycl::float4 keep[MAXK];
532    int kept = 0;
533    float ss = 0.0f;
534    const int first_i = t * 4 + ((c * N - t * 4 + THREADS * 4 - 1) / (THREADS * 4)) * (THREADS * 4);
535    const int end_i = (c + 1) * N;
536    for (int i = first_i; i < end_i; i += THREADS * 4) {
537        const int d = i - c * N;
538        sycl::float4 r = *reinterpret_cast<const sycl::float4*>(a.R + i);
539        if (a.apply) {
540            const sycl::float4 b = *reinterpret_cast<const sycl::float4*>(a.bo_prev + d);
541            r.x() = sycl::fma((float) (b.x()), gw, r.x());
542            r.y() = sycl::fma((float) (b.y()), gw, r.y());
543            r.z() = sycl::fma((float) (b.z()), gw, r.z());
544            r.w() = sycl::fma((float) (b.w()), gw, r.w());
545        }
546        if(a.apply)*reinterpret_cast<sycl::float4*>(a.R_out+i)=r;
547        const sycl::float4 g = *reinterpret_cast<const sycl::float4*>(a.w_norm + i);
548        ss += r.x() * r.x() + r.y() * r.y() + r.z() * r.z() + r.w() * r.w();
549        if (kept < MAXK) keep[kept++] = sycl::float4(r.x() * g.x(), r.y() * g.y(), r.z() * g.z(), r.w() * g.w());
550    }
551    const float v = warp_sum(ss);
552    if (lane == 0) part[warp] = v;
553    item.barrier(sycl::access::fence_space::local_space);
554    if (t == 0) {
555        float sum = 0.0f;
556#pragma unroll
557        for (int w = 0; w < WARPS; ++w) sum += part[w];
558        s_rs = sycl::rsqrt(sum / (float) N + a.eps);
559        a.rs[c] = s_rs;
560    }
561    item.barrier(sycl::access::fence_space::local_space);
562    const float rs = s_rs;
563    int k = 0;
564    for (int i = first_i; i < end_i && k < kept; i += THREADS * 4) {
565        const sycl::float4 x = keep[k++];
566        *reinterpret_cast<sycl::float4*>(xn + i) = sycl::float4(x.x() * rs, x.y() * rs, x.z() * rs, x.w() * rs);
567    }
568}
569const bool g_gr_norm_direct_bounds = [] {
570    const char* value = std::getenv("STRATA_SYCL_GR_NORM_BOUNDS");
571    return value && value[0] == '1';
572}();
573
574bool gr_norm_split() {   // default; STRATA_GR_NORM_SPLIT=0: one work-group per token
575    static const bool v = std::getenv("STRATA_GR_NORM_SPLIT") == nullptr || std::atoi(std::getenv("STRATA_GR_NORM_SPLIT")) != 0;
576    return v;
577}
578
579// Step 2 of `gr_down_kernel` for T tokens.  One warp per row (so each lane accumulates the same chunks in the
580// same order as the single-token kernel); per tile the lane's weight chunks are loaded BEFORE the activation
581// tile is staged, so the DRAM and L2 traffic are in flight together.
582//
583// TILEV = xn floats per token staged at a time.  The tile only changes the staging granularity: the lane's chunk
584// order (lane + 32*q within the tile, tiles ascending) is strictly increasing for either value, so the results are
585// bitwise identical to `gr_down_kernel` for both.  2560 stages 320 chunks of 8 per tile (10 per lane); cards whose
586// opt-in below 8 * 2560 * 4 B slices the tokens - sm_75 (64 KiB) carries 6 tokens of it - run TILEV 1280 instead,
587// which fits all eight tokens in one 40 KiB launch and stages 160 chunks of 8 (5 per lane, half the registers held
588// for the weight prefetch); smaller tiles raise how many blocks share an SM (the 41-block grid), e.g. three blocks
589// of four tokens instead of one on sm_75.
590template <int TILEV, int MAX_T = kFusedGrMaxT>
591/*
592DPCT1110: The total declared local variable size in device function
593gr_down_multi_kernel exceeds 128 bytes and may cause high register pressure.
594Consult with your hardware vendor to find the total register size available and
595adjust the code, or use smaller sub-group size to avoid high register pressure.
596*/
597__dpct_inline__ void gr_down_multi_kernel(GrMulti m, uint8_t *dpct_local) {
598    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
599    constexpr int TQ = TILEV / 8 / 32; // uint4 weight chunks per lane per tile
600    auto tile = (float *)dpct_local;   // [T][TILEV]
601    const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
602    const int T = m.T;
603    const int gid = (int) item_ct1.get_group(2);
604    const bool inject_block = gid == DOWN_BLOCKS * DOWN_SPLIT;
605    const int split = inject_block ? 0 : gid % DOWN_SPLIT, rb = inject_block ? 0 : gid / DOWN_SPLIT;
606    const int row = inject_block ? warp : rb * WARPS + warp;
607    const bool active = !(inject_block && (m.a[0].w_inject == nullptr || warp >= HC));
608    const uint16_t* wrow = (inject_block ? m.a[0].w_inject : m.a[0].w_down) + (size_t) (active ? row : 0) * D;
609    const sycl::uint4 *w4 = reinterpret_cast<const sycl::uint4 *>(wrow);
610    float acc[MAX_T];
611#pragma unroll
612    for (int k = 0; k < MAX_T; ++k) acc[k] = 0.0f;
613    for (int base = inject_block ? 0 : split * TILEV; base < D; base += inject_block ? TILEV : TILEV * DOWN_SPLIT) {
614        sycl::uint4 wv[TQ];
615        if (active) {
616#pragma unroll
617            /*
618            DPCT1098: The '*' expression is used instead of the __ldg call.
619            These two expressions do not provide the exact same functionality.
620            Check the generated code for potential precision and/or performance
621            issues.
622            */
623            for (int q = 0; q < TQ; ++q)
624                wv[q] = *(w4 + base / 8 + lane + 32 * q);
625        }
626        /*
627        DPCT1118: SYCL group functions and algorithms must be encountered in
628        converged control flow. You may need to adjust the code.
629        */
630        /*
631        DPCT1065: Consider replacing sycl::nd_item::barrier() with
632        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
633        better performance if there is no access to global memory.
634        */
635        item_ct1.barrier(); // the previous tile is consumed
636        const sycl::float4 *src4 = reinterpret_cast<const sycl::float4 *>(m.xn);
637        sycl::float4 *tile4 = reinterpret_cast<sycl::float4 *>(tile);
638        for (int i = t; i < T * (TILEV / 4); i += THREADS) {
639            const int k = i / (TILEV / 4), off = i - k * (TILEV / 4);
640            tile4[i] = src4[((size_t) k * D + base) / 4 + off];
641        }
642        /*
643        DPCT1118: SYCL group functions and algorithms must be encountered in
644        converged control flow. You may need to adjust the code.
645        */
646        /*
647        DPCT1065: Consider replacing sycl::nd_item::barrier() with
648        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
649        better performance if there is no access to global memory.
650        */
651        item_ct1.barrier();
652        if (!active) continue;
653#pragma unroll
654        for (int q = 0; q < TQ; ++q) {
655            const int j = lane + 32 * q;
656#pragma unroll
657            for (int k = 0; k < MAX_T; ++k)
658                if (k < T) acc[k] += dot8(wv[q], tile + k * TILEV + j * 8);
659        }
660    }
661    if (!active) return;
662    float s[MAX_T];
663#pragma unroll
664    for (int k = 0; k < MAX_T; ++k) s[k] = k < T ? warp_sum(acc[k]) : 0.0f;
665    // lane k writes token k (every lane holds every sum after the xor reduction)
666#pragma unroll
667    for (int k = 0; k < MAX_T; ++k) {
668        if (k >= T || lane != k) continue;
669        if (inject_block) {
670            m.a[k].inject_out[row] = s[k];
671        } else {
672            m.part[((size_t) split * kFusedGrMaxT + k) * LR + row] = s[k];   // the up kernel sums the splits
673        }
674    }
675}
676
677// SYCL port: gr_down_multi_kernel without the shared-memory tile. The tiled kernel stages T x 2560 floats per
678// work-group (60 KB at T = 6) for 8 rows (40 KB of weights): the copy outweighs the weights and the SLM caps the
679// B70 at ~2 groups per Xe core (unitrace: 64 us per call, ~100 GB/s). Here each lane reads its 8 xn floats per
680// token straight from global memory (T x 40 KB in all, L1/L2-resident, shared by every group). Same per-lane
681// order of the sums, so the outputs are bitwise the tiled kernel's.
682__dpct_inline__ void gr_down_multi_direct_kernel(GrMulti m) {
683    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
684    const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
685    const int T = m.T;
686    const int gid = (int) item_ct1.get_group(2);
687    const bool inject_block = gid == DOWN_BLOCKS * DOWN_SPLIT;
688    const int split = inject_block ? 0 : gid % DOWN_SPLIT, rb = inject_block ? 0 : gid / DOWN_SPLIT;
689    const int row = inject_block ? warp : rb * WARPS + warp;
690    const bool active = !(inject_block && (m.a[0].w_inject == nullptr || warp >= HC));
691    if (!active) return;
692    const uint16_t* wrow = (inject_block ? m.a[0].w_inject : m.a[0].w_down) + (size_t) row * D;
693    const sycl::uint4* w4 = reinterpret_cast<const sycl::uint4*>(wrow);
694    float acc[kFusedGrMaxT];
695#pragma unroll
696    for (int k = 0; k < kFusedGrMaxT; ++k) acc[k] = 0.0f;
697    for (int base = inject_block ? 0 : split * TILE; base < D; base += inject_block ? TILE : TILE * DOWN_SPLIT) {
698        sycl::uint4 wv[TQ];
699#pragma unroll
700        for (int q = 0; q < TQ; ++q) wv[q] = *(w4 + base / 8 + lane + 32 * q);
701#pragma unroll
702        for (int q = 0; q < TQ; ++q) {
703            const int j = lane + 32 * q;
704#pragma unroll
705            for (int k = 0; k < kFusedGrMaxT; ++k)
706                if (k < T) {
707                    const sycl::float4* x4 = reinterpret_cast<const sycl::float4*>(m.xn + (size_t) k * D + base + j * 8);
708                    const sycl::float4 a0 = x4[0], a1 = x4[1];
709                    const float xv[8] = {a0.x(), a0.y(), a0.z(), a0.w(), a1.x(), a1.y(), a1.z(), a1.w()};
710                    acc[k] += dot8(wv[q], xv);
711                }
712        }
713    }
714    float s[kFusedGrMaxT];
715#pragma unroll
716    for (int k = 0; k < kFusedGrMaxT; ++k) s[k] = k < T ? warp_sum(acc[k]) : 0.0f;
717#pragma unroll
718    for (int k = 0; k < kFusedGrMaxT; ++k) {
719        if (k >= T || lane != k) continue;
720        if (inject_block) m.a[k].inject_out[row] = s[k];
721        else m.part[((size_t) split * kFusedGrMaxT + k) * LR + row] = s[k];
722    }
723}
724// SYCL port: the down projection sliced by columns. The direct kernel above has each warp read T x 32 bytes of
725// activations (L2) per 16 bytes of weights - 12x the weight traffic at 6 tokens, ~134 GB/s. Here work-group s owns
726// columns [128 s, 128 s + 128) of all 324 rows (320 down + 4 inject): it stages that slice of xn for the T tokens
727// once (<= 4 KB of SLM) and streams the rows through it, 4 lanes per row (one 64-byte line per step), reducing over
728// those 4 lanes once per row. gr_down_reduce then sums the 80 slice partials in a fixed order.
729constexpr int GRS_COLS = 128, GRS_SLICES = D / GRS_COLS, GRS_ROWS = LR + HC;   // 80 slices, 324 rows
730constexpr int GRS_RB = (GRS_ROWS + WARPS * 8 - 1) / (WARPS * 8);                // 6 blocks of 64 rows
731// MORE (gr_more_groups): one work-group per (slice, row block) - 480 groups instead of 80; every row's sum is the same
732template <bool MORE = false>
733__dpct_inline__ void gr_down_sliced_kernel(GrMulti m, float* tile) {
734    auto item = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
735    const int t = (int) item.get_local_id(2), lane = t & 31, warp = t >> 5;
736    const int g = (int) item.get_group(2);
737    const int T = m.T, sl = MORE ? g / GRS_RB : g, c0 = sl * GRS_COLS;
738    const int r_first = MORE ? (g % GRS_RB) * WARPS * 8 : 0, r_end = MORE ? r_first + WARPS * 8 : GRS_ROWS;
739    for (int i = t; i < T * GRS_COLS; i += THREADS) {
740        const int k = i / GRS_COLS, c = i - k * GRS_COLS;
741        tile[i] = m.xn[(size_t) k * D + c0 + c];
742    }
743    item.barrier(sycl::access::fence_space::local_space);
744    const int rsub = lane >> 2, q = lane & 3;
745    const bool inj = m.a[0].w_inject != nullptr;
746    for (int r0 = r_first; r0 < r_end; r0 += WARPS * 8) {
747        const int r = r0 + warp * 8 + rsub;
748        const bool ok = r < LR || (r < GRS_ROWS && inj);
749        const uint16_t* wrow = r < LR ? m.a[0].w_down + (size_t) r * D : m.a[0].w_inject + (size_t) (ok ? r - LR : 0) * D;
750        sycl::uint4 wv[4];
751#pragma unroll
752        for (int cc = 0; cc < 4; ++cc)
753            wv[cc] = ok ? reinterpret_cast<const sycl::uint4*>(wrow + c0)[q + 4 * cc] : sycl::uint4(0, 0, 0, 0);
754        float acc[kFusedGrMaxT];
755#pragma unroll
756        for (int k = 0; k < kFusedGrMaxT; ++k) {
757            acc[k] = 0.0f;
758            if (k < T) {
759#pragma unroll
760                for (int cc = 0; cc < 4; ++cc) acc[k] += dot8(wv[cc], tile + k * GRS_COLS + (q + 4 * cc) * 8);
761            }
762        }
763        auto sg = item.get_sub_group();
764#pragma unroll
765        for (int k = 0; k < kFusedGrMaxT; ++k) {
766            if (k >= T) break;
767            float v = acc[k];
768            v += sycl::permute_group_by_xor(sg, v, 1);
769            v += sycl::permute_group_by_xor(sg, v, 2);
770            if (q == 0 && ok) m.part2[((size_t) sl * kFusedGrMaxT + k) * GRS_ROWS + r] = v;
771        }
772    }
773}
774static_assert(GRS_SLICES % 8 == 0, "the 8-at-a-time reduce reads whole groups of 8 slices");
775template <bool MORE = false, bool REUSE_LO = false>
776__dpct_inline__ void gr_down_reduce_kernel(GrMulti m) {
777    auto item = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
778    const int i = (int) item.get_global_id(2);
779    if (i >= m.T * GRS_ROWS) return;
780    const int k = i / GRS_ROWS, r = i - k * GRS_ROWS;
781    if (r >= LR && m.a[0].w_inject == nullptr) return;
782    float x = 0.0f;
783    if constexpr (MORE) {
784        // 8 loads in flight per step (the one-at-a-time loop was load-latency bound on the A770), then added one by
785        // one: x += slice 0, 1, 2, ... 79, the same sequence of float adds as the loop below (-fp-model=precise)
786        const float* src = m.part2 + (size_t) k * GRS_ROWS + r;
787        constexpr size_t SL_STRIDE = (size_t) kFusedGrMaxT * GRS_ROWS;
788        for (int sl = 0; sl < GRS_SLICES; sl += 8) {
789            float pv[8];
790#pragma unroll
791            for (int j = 0; j < 8; ++j) pv[j] = src[(size_t) (sl + j) * SL_STRIDE];
792#pragma unroll
793            for (int j = 0; j < 8; ++j) x += pv[j];
794        }
795    } else {
796        for (int sl = 0; sl < GRS_SLICES; ++sl) x += m.part2[((size_t) sl * kFusedGrMaxT + k) * GRS_ROWS + r];
797    }
798    if (r < LR) {
799        m.part[(size_t) k * LR + r] = x;   // split 0
800        if constexpr (REUSE_LO) {
801            float v = 0.0f;
802            v += x;
803            v /= (float) HC;
804            GR_PICK(m, k, lo)[r] = v / (1.0f + sycl::native::exp(-v));
805        }
806    } else GR_PICK(m, k, inject_out)[r - LR] = x;
807}
808// Large-GRF mode (256 registers per thread instead of 128) for the sliced down kernel and the multi-token up kernel.
809// On the A770 the up kernel spills ~3.4 KB per thread at 128 (unitrace). Large GRF halves the threads an Xe core keeps
810// resident, so it is the default on Arc A-series (Alchemist) only, where it was measured; Battlemage and anything else
811// keep the compiler's default GRF and the same kernels as before. STRATA_GR_LARGE_GRF=1 forces it on, =0 off.
812bool gr_large_grf(sycl::queue* q) {
813    static const bool v = [q] {
814        const char* e = std::getenv("STRATA_GR_LARGE_GRF");
815        if (e != nullptr) return std::atoi(e) != 0;
816        return strata::intel_gpu_gen(q->get_device()) == strata::IntelGpuGen::Alchemist;
817    }();
818    return v;
819}
820// More, smaller work-groups for the multi-token read on Arc A-series: the sliced down kernel as (slice, row block)
821// = 480 groups instead of 80, its reduce with 8 loads in flight, and the up kernel with 8 columns per group (320
822// groups instead of 160), where only group 0 writes the per-token lo values (every group computes the same ones). Every
823// output is the same float sum in the same order (gr_bench checksums unchanged). A770, gr_bench 1-6 tokens:
824// 117-180 -> 87-149 us; decode 28.04-28.54 -> 29.99-30.00 tok/s. Default on Alchemist only, where it was measured;
825// elsewhere the 80 / 160-group kernels as before. STRATA_GR_MORE_GROUPS=1 forces it on, =0 off.
826bool gr_more_groups(sycl::queue* q) {
827    static const bool v = [q] {
828        const char* e = std::getenv("STRATA_GR_MORE_GROUPS");
829        if (e != nullptr) return std::atoi(e) != 0;
830        return strata::intel_gpu_gen(q->get_device()) == strata::IntelGpuGen::Alchemist;
831    }();
832    return v;
833}
834bool gr_down_sliced() {   // default (gr_bench: GR read 108.6 -> 76.5 us at 6 tokens); STRATA_GR_DOWN_SLICED=0: direct
835    static const bool v = std::getenv("STRATA_GR_DOWN_SLICED") == nullptr || std::atoi(std::getenv("STRATA_GR_DOWN_SLICED")) != 0;
836    return v;
837}
838float* slice_partials(sycl::queue* q) {
839    static std::mutex mu;
840    static std::unordered_map<sycl::queue*, float*> bufs;
841    std::lock_guard<std::mutex> lk(mu);
842    auto it = bufs.find(q);
843    if (it != bufs.end()) return it->second;
844    float* p = sycl::malloc_device<float>((size_t) GRS_SLICES * kFusedGrMaxT * GRS_ROWS, *q);
845    bufs[q] = p;
846    return p;
847}
848bool gr_down_direct() {   // default; STRATA_GR_DOWN_DIRECT=0: the tiled kernel (gr_bench: 13-19% slower at 3-6 tokens)
849    static const bool v = std::getenv("STRATA_GR_DOWN_DIRECT") == nullptr || std::atoi(std::getenv("STRATA_GR_DOWN_DIRECT")) != 0;
850    return v;
851}
852
853constexpr int UPM_COLS = 16;                      // columns per block (x 4 streams = 64 rows, 8 per warp)
854constexpr int UPM_BLOCKS = N / UPM_COLS;          // 160
855constexpr int UPM_COLS_MORE = 8;                  // gr_more_groups: 8 columns (32 rows, 4 per warp)
856constexpr int UPM_BLOCKS_MORE = N / UPM_COLS_MORE;   // 320
857
858// `gr_up_kernel` for T tokens: each row of w_up read once; the T dots reduced by xor so every lane holds every
859// sum, and lane k runs token k's epilogue - the T epilogues in parallel instead of one after another.
860/*
861DPCT1110: The total declared local variable size in device function
862gr_up_multi_kernel exceeds 128 bytes and may cause high register pressure.
863Consult with your hardware vendor to find the total register size available and
864adjust the code, or use smaller sub-group size to avoid high register pressure.
865*/
866// COLS: columns per block (UPM_COLS, or UPM_COLS_MORE with LO_ONCE under gr_more_groups)
867template <int COLS = UPM_COLS, bool ILP = false, bool LO_ONCE = false, bool REUSE = false>
868__dpct_inline__ void gr_up_multi_kernel(GrMulti m) {   // stream sum unchanged, so the same bits; more blocks, fewer serial rows per warp
869    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
870auto &lo = *sycl::ext::oneapi::group_local_memory_for_overwrite<
871    float[kFusedGrMaxT][LR]>(
872    sycl::ext::oneapi::this_work_item::get_work_group<3>());
873    auto &g = *sycl::ext::oneapi::group_local_memory_for_overwrite<
874        float[kFusedGrMaxT][HC][COLS]>(
875        sycl::ext::oneapi::this_work_item::get_work_group<3>());
876    const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
877    const int T = m.T;
878    const int d0 = item_ct1.get_group(2) * COLS;
879#pragma unroll
880    for (int i = t; i < T * LR; i += THREADS) {   // the down kernel's partial sums, in split order, then silu
881        const int k = i / LR, r = i % LR;
882        if constexpr (REUSE) {
883            if (m.cached_lo) {
884                lo[k][r] = GR_PICK(m, k, lo)[r];
885                continue;
886            }
887        }
888        float x = 0.0f;
889#pragma unroll
890        for (int sp = 0; sp < DOWN_SPLIT; ++sp) if (sp < m.nsplit) x += m.part[((size_t) sp * kFusedGrMaxT + k) * LR + r];
891        x /= (float) HC;
892        const float v = x / (1.0f + sycl::native::exp(-x));
893        lo[k][r] = v;
894        if (!LO_ONCE || item_ct1.get_group(2) == 0) GR_PICK(m, k, lo)[r] = v;   // the same values in every block
895    }
896    /*
897    DPCT1065: Consider replacing sycl::nd_item::barrier() with
898    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
899    performance if there is no access to global memory.
900    */
901    item_ct1.barrier();
902    // this lane's token (lane < T), picked once - not per row
903    const int pk = lane < T ? lane : 0;
904    const float* const pR = GR_PICK(m, pk, R);
905    const float* const pWn = GR_PICK(m, pk, w_norm);
906    const float* const pRs = GR_PICK(m, pk, rs);
907    const bool pApply = GR_PICK(m, pk, apply);
908    const float* const pBo = GR_PICK(m, pk, bo_prev);
909    const float* const pIp = GR_PICK(m, pk, inj_prev);
910    float* const pRout = GR_PICK(m, pk, R_out);
911    for (int r = warp; r < HC * COLS; r += WARPS) {
912        const int c = r / COLS, dd = r - c * COLS, i = c * N + d0 + dd;
913        const sycl::uint4 *w4 =
914            reinterpret_cast<const sycl::uint4 *>(m.a[0].w_up + (size_t)i * LR);
915        /*
916        DPCT1098: The '*' expression is used instead of the __ldg call.
917        These two expressions do not provide the exact same functionality. Check
918        the generated code for potential precision and/or performance issues.
919        */
920        const sycl::uint4 wa = *(w4 + lane);
921        /*
922        DPCT1098: The '*' expression is used instead of the __ldg call.
923        These two expressions do not provide the exact same functionality. Check
924        the generated code for potential precision and/or performance issues.
925        */
926        const sycl::uint4 wb =
927            lane < LR / 8 - 32 ? *(w4 + 32 + lane) : sycl::uint4(0, 0, 0, 0);
928        // the epilogue inputs of this lane's token, fetched while the dots run
929        float rv = 0.0f, wn = 0.0f, rsc = 0.0f, bo = 0.0f, ip = 0.0f;
930        bool apply = false;
931        if (lane < T) {
932            if (!REUSE || !m.cached_norm || pApply) rv = pR[i];
933            if (!REUSE || !m.cached_norm) {
934                wn = pWn[i];
935                rsc = pRs[c];
936            }
937            apply = pApply;
938            if (apply) { bo = pBo[d0 + dd]; ip = pIp[c]; }
939        }
940        float mine = 0.0f;
941        if constexpr (ILP) {   // STRATA_GR_UP_ILP: the T dots first, then their butterflies interleaved step by step -
942            float accs[kFusedGrMaxT];   // each value sees warp_sum's shuffles in warp_sum's order: the same bits
943#pragma unroll
944            for (int k = 0; k < kFusedGrMaxT; ++k) {
945                float acc = 0.0f;
946                if (k < T) {
947                    acc = dot8(wa, lo[k] + lane * 8);
948                    if (lane < LR / 8 - 32) acc += dot8(wb, lo[k] + (32 + lane) * 8);
949                }
950                accs[k] = acc;
951            }
952#pragma unroll
953            for (int o = 16; o > 0; o >>= 1)
954#pragma unroll
955                for (int k = 0; k < kFusedGrMaxT; ++k)
956                    if (k < T) accs[k] += dpct::experimental::permute_sub_group_by_xor(
957                                   0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), accs[k], o);
958#pragma unroll
959            for (int k = 0; k < kFusedGrMaxT; ++k) if (k < T && lane == k) mine = accs[k];
960        } else {
961#pragma unroll
962        for (int k = 0; k < kFusedGrMaxT; ++k) {
963            if (k >= T) break;
964            float acc = dot8(wa, lo[k] + lane * 8);
965            if (lane < LR / 8 - 32) acc += dot8(wb, lo[k] + (32 + lane) * 8);
966            acc = warp_sum(acc);
967            if (lane == k) mine = acc;
968        }
969        }
970        if (lane < T) {
971            if (apply) {
972                rv = sycl::fma(bo, 2.0f * sigmoidf_(ip / (float)HC), rv);
973                pRout[i] = rv;
974            }
975            const float x = REUSE && m.cached_norm ? m.xn[(size_t) lane * D + i] : rv * wn * rsc;
976            g[lane][c][dd] = x * sigmoidf_(mine);
977        }
978    }
979    /*
980    DPCT1065: Consider replacing sycl::nd_item::barrier() with
981    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
982    performance if there is no access to global memory.
983    */
984    item_ct1.barrier();
985    for (int i = t; i < T * COLS; i += THREADS) {
986        const int k = i / COLS, col = i - k * COLS;
987        float s = 0.0f;
988#pragma unroll
989        for (int c = 0; c < HC; ++c) s += g[k][c][col];
990        GR_PICK(m, k, mixed)[d0 + col] = s / (float) HC;
991    }
992}
993
994// Consume the normalized product without changing its multiply order.
995template<bool LoReady = false>
996__dpct_inline__ void gr_up_cached_norm_kernel(GrMulti m) {
997    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
998auto &lo = *sycl::ext::oneapi::group_local_memory_for_overwrite<
999    float[kFusedGrMaxT][LR]>(
1000    sycl::ext::oneapi::this_work_item::get_work_group<3>());
1001    auto &g = *sycl::ext::oneapi::group_local_memory_for_overwrite<
1002        float[kFusedGrMaxT][HC][UPM_COLS]>(
1003        sycl::ext::oneapi::this_work_item::get_work_group<3>());
1004    const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
1005    const int T = m.T;
1006    const int d0 = item_ct1.get_group(2) * UPM_COLS;
1007#pragma unroll
1008    for (int i = t; i < T * LR; i += THREADS) {   // the down kernel's partial sums, in split order, then silu
1009        const int k = i / LR, r = i % LR;
1010        if constexpr (LoReady) {
1011            lo[k][r] = m.a[k].lo[r];
1012        } else {
1013            float x = 0.0f;
1014#pragma unroll
1015            for (int sp = 0; sp < DOWN_SPLIT; ++sp) if (sp < m.nsplit) x += m.part[((size_t) sp * kFusedGrMaxT + k) * LR + r];
1016            x /= (float) HC;
1017            const float v = x / (1.0f + sycl::native::exp(-x));
1018            lo[k][r] = v;
1019            m.a[k].lo[r] = v;
1020        }
1021    }
1022    /*
1023    DPCT1065: Consider replacing sycl::nd_item::barrier() with
1024    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
1025    performance if there is no access to global memory.
1026    */
1027    item_ct1.barrier();
1028    for (int r = warp; r < HC * UPM_COLS; r += WARPS) {
1029        const int c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd;
1030        const sycl::uint4 *w4 =
1031            reinterpret_cast<const sycl::uint4 *>(m.a[0].w_up + (size_t)i * LR);
1032        /*
1033        DPCT1098: The '*' expression is used instead of the __ldg call.
1034        These two expressions do not provide the exact same functionality. Check
1035        the generated code for potential precision and/or performance issues.
1036        */
1037        const sycl::uint4 wa = *(w4 + lane);
1038        /*
1039        DPCT1098: The '*' expression is used instead of the __ldg call.
1040        These two expressions do not provide the exact same functionality. Check
1041        the generated code for potential precision and/or performance issues.
1042        */
1043        const sycl::uint4 wb =
1044            lane < LR / 8 - 32 ? *(w4 + 32 + lane) : sycl::uint4(0, 0, 0, 0);
1045        float normalized=0.f;
1046        if(lane<T)normalized=m.xn[size_t(lane)*D+i];
1047        float mine = 0.0f;
1048#pragma unroll
1049        for (int k = 0; k < kFusedGrMaxT; ++k) {
1050            if (k >= T) break;
1051            float acc = dot8(wa, lo[k] + lane * 8);
1052            if (lane < LR / 8 - 32) acc += dot8(wb, lo[k] + (32 + lane) * 8);
1053            acc = warp_sum(acc);
1054            if (lane == k) mine = acc;
1055        }
1056        if(lane<T)g[lane][c][dd]=normalized*sigmoidf_(mine);
1057    }
1058    /*
1059    DPCT1065: Consider replacing sycl::nd_item::barrier() with
1060    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
1061    performance if there is no access to global memory.
1062    */
1063    item_ct1.barrier();
1064    for (int i = t; i < T * UPM_COLS; i += THREADS) {
1065        const int k = i / UPM_COLS, col = i - k * UPM_COLS;
1066        float s = 0.0f;
1067#pragma unroll
1068        for (int c = 0; c < HC; ++c) s += g[k][c][col];
1069        m.a[k].mixed[d0 + col] = s / (float) HC;
1070    }
1071}
1072
1073// Pass only the fields used by the prepared-up kernel.
1074struct GrUpCompactReady {
1075    const uint16_t* w_up;
1076    const float* xn;
1077    const float* lo[kFusedGrMaxT];
1078    float* mixed[kFusedGrMaxT];
1079    int T;
1080};
1081static_assert(sizeof(GrUpCompactReady)==152);
1082__dpct_inline__ void gr_up_compact_ready_kernel(GrUpCompactReady m) {
1083    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1084auto &lo = *sycl::ext::oneapi::group_local_memory_for_overwrite<
1085    float[kFusedGrMaxT][LR]>(
1086    sycl::ext::oneapi::this_work_item::get_work_group<3>());
1087    auto &g = *sycl::ext::oneapi::group_local_memory_for_overwrite<
1088        float[kFusedGrMaxT][HC][UPM_COLS]>(
1089        sycl::ext::oneapi::this_work_item::get_work_group<3>());
1090    const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
1091    const int T = m.T;
1092    const int d0 = item_ct1.get_group(2) * UPM_COLS;
1093#pragma unroll
1094    for (int i = t; i < T * LR; i += THREADS) {   // the down kernel's partial sums, in split order, then silu
1095        const int k = i / LR, r = i % LR;
1096        lo[k][r]=m.lo[k][r];
1097    }
1098    /*
1099    DPCT1065: Consider replacing sycl::nd_item::barrier() with
1100    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
1101    performance if there is no access to global memory.
1102    */
1103    item_ct1.barrier();
1104    for (int r = warp; r < HC * UPM_COLS; r += WARPS) {
1105        const int c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd;
1106        const sycl::uint4 *w4 =
1107            reinterpret_cast<const sycl::uint4 *>(m.w_up + (size_t)i * LR);
1108        /*
1109        DPCT1098: The '*' expression is used instead of the __ldg call.
1110        These two expressions do not provide the exact same functionality. Check
1111        the generated code for potential precision and/or performance issues.
1112        */
1113        const sycl::uint4 wa = *(w4 + lane);
1114        /*
1115        DPCT1098: The '*' expression is used instead of the __ldg call.
1116        These two expressions do not provide the exact same functionality. Check
1117        the generated code for potential precision and/or performance issues.
1118        */
1119        const sycl::uint4 wb =
1120            lane < LR / 8 - 32 ? *(w4 + 32 + lane) : sycl::uint4(0, 0, 0, 0);
1121        float normalized=0.f;
1122        if(lane<T)normalized=m.xn[size_t(lane)*D+i];
1123        float mine = 0.0f;
1124#pragma unroll
1125        for (int k = 0; k < kFusedGrMaxT; ++k) {
1126            if (k >= T) break;
1127            float acc = dot8(wa, lo[k] + lane * 8);
1128            if (lane < LR / 8 - 32) acc += dot8(wb, lo[k] + (32 + lane) * 8);
1129            acc = warp_sum(acc);
1130            if (lane == k) mine = acc;
1131        }
1132        if(lane<T)g[lane][c][dd]=normalized*sigmoidf_(mine);
1133    }
1134    /*
1135    DPCT1065: Consider replacing sycl::nd_item::barrier() with
1136    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
1137    performance if there is no access to global memory.
1138    */
1139    item_ct1.barrier();
1140    for (int i = t; i < T * UPM_COLS; i += THREADS) {
1141        const int k = i / UPM_COLS, col = i - k * UPM_COLS;
1142        float s = 0.0f;
1143#pragma unroll
1144        for (int c = 0; c < HC; ++c) s += g[k][c][col];
1145        m.mixed[k][d0 + col] = s / (float) HC;
1146    }
1147}
1148
1149bool g_gr_lo_once = [] {
1150    const char* value = std::getenv("STRATA_SYCL_GR_LO_ONCE");
1151    return value && std::atoi(value) != 0;
1152}();
1153void launch_gr_up_prepared_lo(const GrMulti& m0, dpct::queue_ptr stream) {
1154    // #3153's "lo ready" up kernel is the head's REUSE instance of gr_up_multi_kernel with cached_lo set (it reads the rows
1155    // the reduce wrote, GR_PICK(m, k, lo)); the normalized activation is recomputed (cached_norm off).
1156    GrMulti m = m0;
1157    m.cached_lo = true;
1158    m.cached_norm = false;
1159    auto properties = sycl::ext::oneapi::experimental::properties{
1160        sycl::ext::oneapi::experimental::use_root_sync};
1161    stream->parallel_for<dpct_kernel_name<class gr_up_prepared_lo_kernel>>(
1162        sycl::nd_range<3>(sycl::range(1, 1, UPM_BLOCKS) * sycl::range(1, 1, THREADS),
1163                          sycl::range(1, 1, THREADS)), properties,
1164        [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] { gr_up_multi_kernel<UPM_COLS, false, false, true>(m); });
1165}
1166// gr_more_groups launches (BIG: large GRF, as gr_large_grf)
1167template <bool BIG>
1168void launch_gr_down_more(dpct::queue_ptr st, const GrMulti& m) {
1169    strata::kprof::kp(st, __FILE__, __func__, __LINE__)->submit([&](sycl::handler& cgh) {
1170        sycl::local_accessor<float, 1> tl(sycl::range<1>((size_t) kFusedGrMaxT * GRS_COLS), cgh);
1171        const sycl::nd_range<3> nr(sycl::range(1, 1, GRS_SLICES * GRS_RB) * sycl::range(1, 1, THREADS), sycl::range(1, 1, THREADS));
1172        auto body = [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] {
1173            gr_down_sliced_kernel<true>(m, tl.get_multi_ptr<sycl::access::decorated::no>().get());
1174        };
1175        if constexpr (BIG)
1176            cgh.parallel_for<dpct_kernel_name<class gr_down_sliced_more, dpct_kernel_scalar<1>>>(
1177                nr, sycl::ext::oneapi::experimental::properties{sycl::ext::intel::experimental::grf_size<256>}, body);
1178        else
1179            cgh.parallel_for<dpct_kernel_name<class gr_down_sliced_more, dpct_kernel_scalar<0>>>(nr, body);
1180    });
1181    const unsigned nred = unsigned((m.T * GRS_ROWS + 127) / 128);
1182    strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class gr_down_reduce_more, dpct_kernel_scalar<BIG ? 1 : 0>>>(
1183        sycl::nd_range<3>(sycl::range(1, 1, nred) * sycl::range(1, 1, 128), sycl::range(1, 1, 128)),
1184        [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] { gr_down_reduce_kernel<true>(m); });
1185}
1186template <bool BIG>
1187void launch_gr_up_more(dpct::queue_ptr st, const GrMulti& m) {
1188    const sycl::nd_range<3> nr(sycl::range(1, 1, UPM_BLOCKS_MORE) * sycl::range(1, 1, THREADS), sycl::range(1, 1, THREADS));
1189    auto body = [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] { gr_up_multi_kernel<UPM_COLS_MORE, false, true>(m); };
1190    if constexpr (BIG)
1191        strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class gr_up_multi_more, dpct_kernel_scalar<1>>>(
1192            nr, sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync,
1193                                                            sycl::ext::intel::experimental::grf_size<256>}, body);
1194    else
1195        strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class gr_up_multi_more, dpct_kernel_scalar<0>>>(
1196            nr, sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync}, body);
1197}
1198
1199
1200// SYCL port: the up step with COLS columns per block. 16 (160 blocks, 8 rows per warp one after another) was
1201// latency-bound on Xe2 (B70: 23.7 us for 6.55 MB of BF16, 46% of the bandwidth). STRATA_GR_UP_COLS=8 / 4 run 320 /
1202// 640 blocks with 4 / 2 rows per warp; every row's dot and butterfly and every column's stream sum are the same.
1203inline int gr_up_cols() {
1204    static const int v = [] { const char* e = std::getenv("STRATA_GR_UP_COLS"); const int c = e ? std::atoi(e) : UPM_COLS;
1205                              return c == 4 || c == 8 || c == 32 || c == 64 ? c : UPM_COLS; }();
1206    return v;
1207}
1208inline bool gr_up_ilp() {
1209    static const bool v = [] { const char* e = std::getenv("STRATA_GR_UP_ILP"); return e && e[0] == '1'; }();
1210    return v;
1211}
1212template <int C>
1213void launch_gr_up_cols(dpct::queue_ptr st, const GrMulti& m, bool grf) {
1214    auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};
1215    const sycl::nd_range<3> r(sycl::range(1, 1, N / C) * sycl::range(1, 1, THREADS), sycl::range(1, 1, THREADS));
1216    if constexpr (C == UPM_COLS) {
1217        if (m.cached_norm || m.cached_lo) {
1218            st->parallel_for<dpct_kernel_name<class gr_up_multi_reuse>>(r, exp_props,
1219                [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] {
1220                    gr_up_multi_kernel<C, false, false, true>(m);
1221                });
1222            return;
1223        }
1224    }
1225    if (grf) {   // Arc A-series: large-GRF mode (256 regs/thread); at 128 this kernel spills ~3.4 KB/thread on the A770
1226        strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class gr_up_multi_cols_grf256, dpct_kernel_scalar<C>>>(r,
1227            sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync,
1228                                                        sycl::ext::intel::experimental::grf_size<256>},
1229            [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] { gr_up_multi_kernel<C>(m); });
1230        return;
1231    }
1232    if (gr_up_ilp())
1233        strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class gr_up_multi_cols_ilp, dpct_kernel_scalar<C>>>(r, exp_props,
1234            [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] { gr_up_multi_kernel<C, true>(m); });
1235    else
1236        strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class gr_up_multi_cols, dpct_kernel_scalar<C>>>(r, exp_props,
1237            [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] { gr_up_multi_kernel<C>(m); });
1238}
1239inline void launch_gr_up_multi(dpct::queue_ptr st, const GrMulti& m, bool grf = false) {
1240    switch (gr_up_cols()) {
1241        case 4: launch_gr_up_cols<4>(st, m, grf); return;
1242        case 8: launch_gr_up_cols<8>(st, m, grf); return;
1243        case 32: launch_gr_up_cols<32>(st, m, grf); return;
1244        case 64: launch_gr_up_cols<64>(st, m, grf); return;
1245        default: launch_gr_up_cols<UPM_COLS>(st, m, grf); return;
1246    }
1247}
1248
1249// ================================ hc read v3 (opt-in: STRATA_GR_V3=1) - two kernels, stream-split ================
1250// The norm kernel runs on only T blocks (~16 us of pure latency per call) and `down` on 41 blocks (~280 GB/s).
1251// v3: `down` is split over (row group, stream[, column half]) = 164 or 328 blocks; each block stages its slice of
1252// R' * w_norm for the T tokens, reduces that slice's sum of squares itself, and writes UNSCALED partial dots.  The
1253// rms scale is per stream, so  w_down . xn = sum_c rs[c] * (w_down[:, c] . (R'[c] * w_norm[c]))  - `up` applies it
1254// in its prologue (lo, inject, rs).  Same maths, ANOTHER SUMMATION ORDER: not bitwise the default kernels, hence
1255// opt-in.  Dynamic shared memory is T * (N / S) floats: S (1 or 2 column halves) is the smallest that fits the
1256// card's opt-in limit at kFusedGrMaxT tokens (Ampere 99 KB: S = 1; Turing / HIP 64 KB: S = 2); a card where
1257// neither fits keeps the default kernels.
1258constexpr int PR = LR + HC;                        // partial rows per (token, stream): 320 down + 4 inject
1259constexpr int TQ3 = N / 8 / 32;                    // uint4 weight chunks per lane in one stream's slice (10)
1260
1261template <int S>
1262/*
1263DPCT1110: The total declared local variable size in device function
1264gr_down_v3_kernel exceeds 128 bytes and may cause high register pressure.
1265Consult with your hardware vendor to find the total register size available and
1266adjust the code, or use smaller sub-group size to avoid high register pressure.
1267*/
1268__dpct_inline__ void gr_down_v3_kernel(GrMulti m, float *__restrict__ part,
1269                                       float *__restrict__ ssg,
1270                                       uint8_t *dpct_local) {
1271    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1272    auto xs = (float *)dpct_local;                 // [T][N / S]
1273    constexpr int R2 = 1;                          // down rows per warp
1274    auto &red = *sycl::ext::oneapi::group_local_memory_for_overwrite<
1275        float[WARPS][kFusedGrMaxT]>(
1276        sycl::ext::oneapi::this_work_item::get_work_group<3>());
1277    const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
1278    const int T = m.T;
1279    // S = 2: each stream's 2560 columns in two halves (blockIdx.y = stream * S + half): twice the blocks
1280    constexpr int SL = N / S, TQS = SL / 8 / 32;
1281    const int rg = item_ct1.get_group(2), c = item_ct1.get_group(1) / S,
1282              h = item_ct1.get_group(1) - (item_ct1.get_group(1) / S) * S;
1283    constexpr int NDB = LR / (WARPS * R2);          // down row blocks per stream; block NDB = the inject rows
1284    const bool inject_block = rg == NDB;
1285    // warp w owns rows row0 + w * R2 + r (r < R2); the inject block: warps 0-3, one row each
1286    const int row0 = inject_block ? warp : (rg * WARPS + warp) * R2;
1287    const int nrows = inject_block ? ((m.a[0].w_inject != nullptr && warp < HC) ? 1 : 0) : R2;
1288    const bool active = nrows > 0;
1289    const uint16_t* wbase = inject_block ? m.a[0].w_inject : m.a[0].w_down;
1290    sycl::uint4 wv[R2][TQS];
1291#pragma unroll
1292    for (int r = 0; r < R2; ++r) {
1293        if (r >= nrows) break;
1294        const sycl::uint4 *w4 = reinterpret_cast<const sycl::uint4 *>(
1295            wbase + (size_t)(row0 + r) * D + (size_t)c * N + (size_t)h * SL);
1296#pragma unroll
1297        /*
1298        DPCT1098: The '*' expression is used instead of the __ldg call.
1299        These two expressions do not provide the exact same functionality. Check
1300        the generated code for potential precision and/or performance issues.
1301        */
1302        for (int q = 0; q < TQS; ++q) wv[r][q] = *(w4 + lane + 32 * q);
1303    }
1304    float ssp[kFusedGrMaxT];
1305#pragma unroll
1306    for (int k = 0; k < kFusedGrMaxT; ++k) {
1307        ssp[k] = 0.0f;
1308        if (k >= T) continue;
1309        const FusedGrArgs& a = m.a[k];
1310        const float gw = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f;
1311        const sycl::float4 *R4 = reinterpret_cast<const sycl::float4 *>(
1312            a.R + (size_t)c * N + (size_t)h * SL);
1313        const sycl::float4 *G4 = reinterpret_cast<const sycl::float4 *>(
1314            a.w_norm + (size_t)c * N + (size_t)h * SL);
1315        const sycl::float4 *B4 =
1316            reinterpret_cast<const sycl::float4 *>(a.bo_prev + (size_t)h * SL);
1317        sycl::float4 *X4 =
1318            reinterpret_cast<sycl::float4 *>(xs + (size_t)k * SL);
1319        for (int i = t; i < SL / 4; i += THREADS) {
1320            sycl::float4 r = R4[i];
1321            if (a.apply) {
1322                const sycl::float4 b = B4[i];
1323                r.x() = sycl::fma((float)(b.x()), (float)gw, r.x());
1324                    r.y() = sycl::fma((float)(b.y()), (float)gw, r.y());
1325                r.z() = sycl::fma((float)(b.z()), (float)gw, r.z());
1326                    r.w() = sycl::fma((float)(b.w()), (float)gw, r.w());
1327            }
1328            const sycl::float4 g = G4[i];
1329            ssp[k] +=
1330                r.x() * r.x() + r.y() * r.y() + r.z() * r.z() + r.w() * r.w();
1331            X4[i] = sycl::float4(r.x() * g.x(), r.y() * g.y(), r.z() * g.z(),
1332                                 r.w() * g.w());
1333        }
1334    }
1335#pragma unroll
1336    for (int k = 0; k < kFusedGrMaxT; ++k) {
1337        if (k >= T) break;
1338        const float v = warp_sum(ssp[k]);
1339        if (lane == 0) red[warp][k] = v;
1340    }
1341    /*
1342    DPCT1065: Consider replacing sycl::nd_item::barrier() with
1343    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
1344    performance if there is no access to global memory.
1345    */
1346    item_ct1.barrier();
1347    if (rg == 0 && t < T) {
1348        float sum = 0.0f;
1349#pragma unroll
1350        for (int w = 0; w < WARPS; ++w) sum += red[w][t];
1351        ssg[(t * HC + c) * S + h] = sum;
1352    }
1353    if (!active) return;
1354#pragma unroll
1355    for (int r = 0; r < R2; ++r) {
1356        if (r >= nrows) break;
1357        float acc[kFusedGrMaxT];
1358#pragma unroll
1359        for (int k = 0; k < kFusedGrMaxT; ++k) acc[k] = 0.0f;
1360#pragma unroll
1361        for (int q = 0; q < TQS; ++q) {
1362            const int j = lane + 32 * q;
1363#pragma unroll
1364            for (int k = 0; k < kFusedGrMaxT; ++k)
1365                if (k < T) acc[k] += dot8(wv[r][q], xs + (size_t) k * SL + j * 8);
1366        }
1367        const int prow = inject_block ? LR + warp : row0 + r;
1368#pragma unroll
1369        for (int k = 0; k < kFusedGrMaxT; ++k) {
1370            if (k >= T) break;
1371            const float v = warp_sum(acc[k]);
1372            if (lane == 0) part[(((size_t) k * HC + c) * S + h) * PR + prow] = v;
1373        }
1374    }
1375}
1376
1377template <int S>
1378/*
1379DPCT1110: The total declared local variable size in device function
1380gr_up_v3_kernel exceeds 128 bytes and may cause high register pressure. Consult
1381with your hardware vendor to find the total register size available and adjust
1382the code, or use smaller sub-group size to avoid high register pressure.
1383*/
1384__dpct_inline__ void gr_up_v3_kernel(GrMulti m, const float *__restrict__ part,
1385                                     const float *__restrict__ ssg) {
1386    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1387auto &lo = *sycl::ext::oneapi::group_local_memory_for_overwrite<
1388    float[kFusedGrMaxT][LR]>(
1389    sycl::ext::oneapi::this_work_item::get_work_group<3>());
1390    auto &rsS = *sycl::ext::oneapi::group_local_memory_for_overwrite<
1391        float[kFusedGrMaxT][HC]>(
1392        sycl::ext::oneapi::this_work_item::get_work_group<3>());
1393    auto &g = *sycl::ext::oneapi::group_local_memory_for_overwrite<
1394        float[kFusedGrMaxT][HC][UPM_COLS]>(
1395        sycl::ext::oneapi::this_work_item::get_work_group<3>());
1396    const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
1397    const int T = m.T;
1398    const int d0 = item_ct1.get_group(2) * UPM_COLS;
1399    constexpr int RPW = HC * UPM_COLS / WARPS;     // 8 rows per warp
1400    if (t < T * HC) {
1401        const int k = t / HC, c = t - k * HC;
1402        float ss = 0.0f;
1403#pragma unroll
1404        for (int h = 0; h < S; ++h) ss += ssg[t * S + h];
1405        const float r = sycl::rsqrt(ss / (float)N + m.a[k].eps);
1406        rsS[k][c] = r;
1407        if (item_ct1.get_group(2) == 0) m.a[k].rs[c] = r;
1408    }
1409    /*
1410    DPCT1065: Consider replacing sycl::nd_item::barrier() with
1411    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
1412    performance if there is no access to global memory.
1413    */
1414    item_ct1.barrier();
1415    for (int i = t; i < T * LR; i += THREADS) {
1416        const int k = i / LR, r = i - k * LR;
1417        float sum = 0.0f;
1418#pragma unroll
1419        for (int c = 0; c < HC; ++c) {
1420            float p = 0.0f;
1421#pragma unroll
1422            for (int h = 0; h < S; ++h) p += part[(((size_t) k * HC + c) * S + h) * PR + r];
1423            sum = sycl::fma(rsS[k][c], p, sum);
1424        }
1425        const float x = sum / (float) HC;
1426        lo[k][r] = x / (1.0f + sycl::native::exp(-x));
1427    }
1428    if (item_ct1.get_group(2) == 0 && t < T * HC) {
1429        const int k = t / HC, cc = t - k * HC;
1430        if (m.a[k].w_inject != nullptr) {
1431            float sum = 0.0f;
1432#pragma unroll
1433            for (int c = 0; c < HC; ++c) {
1434                float p = 0.0f;
1435#pragma unroll
1436                for (int h = 0; h < S; ++h) p += part[(((size_t) k * HC + c) * S + h) * PR + LR + cc];
1437                sum = sycl::fma(rsS[k][c], p, sum);
1438            }
1439            m.a[k].inject_out[cc] = sum;
1440        }
1441    }
1442    /*
1443    DPCT1065: Consider replacing sycl::nd_item::barrier() with
1444    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
1445    performance if there is no access to global memory.
1446    */
1447    item_ct1.barrier();
1448#pragma unroll
1449    for (int q = 0; q < RPW; ++q) {
1450        const int r = warp + q * WARPS;
1451        const int c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd;
1452        const sycl::uint4 *w4 =
1453            reinterpret_cast<const sycl::uint4 *>(m.a[0].w_up + (size_t)i * LR);
1454        /*
1455        DPCT1098: The '*' expression is used instead of the __ldg call.
1456        These two expressions do not provide the exact same functionality. Check
1457        the generated code for potential precision and/or performance issues.
1458        */
1459        const sycl::uint4 wa = *(w4 + lane);
1460        /*
1461        DPCT1098: The '*' expression is used instead of the __ldg call.
1462        These two expressions do not provide the exact same functionality. Check
1463        the generated code for potential precision and/or performance issues.
1464        */
1465        const sycl::uint4 wb =
1466            lane < LR / 8 - 32 ? *(w4 + 32 + lane) : sycl::uint4(0, 0, 0, 0);
1467        float rv = 0.0f, wn = 0.0f, bo = 0.0f, ip = 0.0f;
1468        bool apply = false;
1469        if (lane < T) {
1470            const FusedGrArgs& a = m.a[lane];
1471            rv = a.R[i];
1472            wn = a.w_norm[i];
1473            apply = a.apply;
1474            if (apply) { bo = a.bo_prev[d0 + dd]; ip = a.inj_prev[c]; }
1475        }
1476        float mine = 0.0f;
1477#pragma unroll
1478        for (int k = 0; k < kFusedGrMaxT; ++k) {
1479            if (k >= T) break;
1480            float acc = dot8(wa, lo[k] + lane * 8);
1481            if (lane < LR / 8 - 32) acc += dot8(wb, lo[k] + (32 + lane) * 8);
1482            acc = warp_sum(acc);
1483            if (lane == k) mine = acc;
1484        }
1485        if (lane < T) {
1486            if (apply) {
1487                rv = sycl::fma(bo, 2.0f * sigmoidf_(ip / (float)HC), rv);
1488                m.a[lane].R_out[i] = rv;
1489            }
1490            const float x = rv * wn * rsS[lane][c];
1491            g[lane][c][dd] = x * sigmoidf_(mine);
1492        }
1493    }
1494    /*
1495    DPCT1065: Consider replacing sycl::nd_item::barrier() with
1496    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
1497    performance if there is no access to global memory.
1498    */
1499    item_ct1.barrier();
1500    for (int i = t; i < T * UPM_COLS; i += THREADS) {
1501        const int k = i / UPM_COLS, col = i - k * UPM_COLS;
1502        float sum = 0.0f;
1503#pragma unroll
1504        for (int c = 0; c < HC; ++c) sum += g[k][c][col];
1505        m.a[k].mixed[d0 + col] = sum / (float) HC;
1506    }
1507}
1508// ================================ #315: split / staged - the same arithmetic, split differently ==================
1509// The multi read's variants beside the plain read (0.1.31's default; not main's opt-in STRATA_GR_V3 read, which sums
1510// in another order).  Every variant computes each output with exactly the plain read's operations in its order (so
1511// bitwise the plain read and the single-token read); only who does what, and when, changes.  `fused_gr_check`
1512// compares them on the card before a verify window uses them (STRATA_HC_SPLIT below).
1513//  - the norm (split and staged): one block per token AND stream instead of one per token.  Each thread visits
1514//    exactly the elements, in the order, it visited for that stream in the plain read, so every sum of squares and rs
1515//    is the same; then it recomputes its R' * w_norm and writes it times rs (the plain read stored the product and
1516//    scaled it in place: the same two roundings).  On an RTX 4080 SUPER, the plain read's norm took 0.58 ms per
1517//    4-token round (96 launches of 1-4 blocks), this one 0.23 ms.
1518//  - the down projection, split: the plain read's kernel.
1519//  - the down projection, staged: the plain read's 8 rows per block and lane order, but the activations arrive by
1520//    cp.async in half-stream tiles, two in flight, so no thread waits on a chain of loads, and they sit in shared
1521//    memory as two planes (floats 0-3 and 4-7 of every 8), so a warp's reads hit no bank twice.  The next tile's
1522//    weights are loaded while the current one is used.  A tile is 160 = 5 x 32 chunks of 8, so a lane still
1523//    accumulates its chunks lane + 32 q in ascending order, as in the plain read with either tile.  Before sm_80
1524//    (and on HIP) the staging is a plain copy: the same bits, only not asynchronous.
1525constexpr int kHcPlain = 1, kHcSplit = 2, kHcStaged = 3;
1526constexpr int H_TILE = N / 2;                         // staged tile: half a stream = 160 chunks of 8, 5 per lane (1280 for Flash-Next)
1527constexpr int HQ = H_TILE / 8 / 32;
1528constexpr int N_HTILES = D / H_TILE;                  // 8
1529static_assert(N % H_TILE == 0 && N % 512 == 0, "a staged tile never straddles two streams");
1530static_assert(H_TILE % 256 == 0, "a staged tile holds whole rounds of 32 chunks: the plain read's lane order");
1531
1532/*
1533DPCT1110: The total declared local variable size in device function
1534gr_norm_split_kernel exceeds 128 bytes and may cause high register pressure.
1535Consult with your hardware vendor to find the total register size available and
1536adjust the code, or use smaller sub-group size to avoid high register pressure.
1537*/
1538__dpct_inline__ void gr_norm_split_kernel(GrMulti m) {
1539    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1540auto &part = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[WARPS]>(
1541    sycl::ext::oneapi::this_work_item::get_work_group<3>());
1542    auto &s_rs = *sycl::ext::oneapi::group_local_memory_for_overwrite<float>(
1543        sycl::ext::oneapi::this_work_item::get_work_group<3>());
1544    const FusedGrArgs &a = m.a[item_ct1.get_group(2)];
1545    const int c = item_ct1.get_group(1);
1546    float *xn = m.xn + (size_t)item_ct1.get_group(2) * D;
1547    const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
1548    const float gw = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f;
1549    float ss = 0.0f;
1550    for (int i = t * 4; i < D; i += THREADS * 4) {
1551        if (i / N != c) continue;                       // another stream's element: another block's
1552        const int d = i - c * N;
1553        sycl::float4 r = *reinterpret_cast<const sycl::float4 *>(a.R + i);
1554        if (a.apply) {
1555            const sycl::float4 b =
1556                *reinterpret_cast<const sycl::float4 *>(a.bo_prev + d);
1557            r.x() = sycl::fma((float)(b.x()), (float)gw, r.x());
1558                r.y() = sycl::fma((float)(b.y()), (float)gw, r.y());
1559            r.z() = sycl::fma((float)(b.z()), (float)gw, r.z());
1560                r.w() = sycl::fma((float)(b.w()), (float)gw, r.w());
1561        }
1562        const float sq =
1563            r.x() * r.x() + r.y() * r.y() + r.z() * r.z() + r.w() * r.w();
1564        ss += sq;
1565    }
1566    const float v = warp_sum(ss);
1567    if (lane == 0) part[warp] = v;
1568    /*
1569    DPCT1065: Consider replacing sycl::nd_item::barrier() with
1570    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
1571    performance if there is no access to global memory.
1572    */
1573    item_ct1.barrier();
1574    if (t == 0) {
1575        float s = 0.0f;
1576#pragma unroll
1577        for (int w = 0; w < WARPS; ++w) s += part[w];
1578        s_rs = sycl::rsqrt(s / (float)N + a.eps);
1579        a.rs[c] = s_rs;
1580    }
1581    /*
1582    DPCT1065: Consider replacing sycl::nd_item::barrier() with
1583    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
1584    performance if there is no access to global memory.
1585    */
1586    item_ct1.barrier();
1587    const float rs = s_rs;
1588    for (int i = t * 4; i < D; i += THREADS * 4) {
1589        if (i / N != c) continue;
1590        const int d = i - c * N;
1591        sycl::float4 r = *reinterpret_cast<const sycl::float4 *>(a.R + i);
1592        if (a.apply) {
1593            const sycl::float4 b =
1594                *reinterpret_cast<const sycl::float4 *>(a.bo_prev + d);
1595            r.x() = sycl::fma((float)(b.x()), (float)gw, r.x());
1596                r.y() = sycl::fma((float)(b.y()), (float)gw, r.y());
1597            r.z() = sycl::fma((float)(b.z()), (float)gw, r.z());
1598                r.w() = sycl::fma((float)(b.w()), (float)gw, r.w());
1599        }
1600        const sycl::float4 g =
1601            *reinterpret_cast<const sycl::float4 *>(a.w_norm + i);
1602        const float px = r.x() * g.x(), py = r.y() * g.y(), pz = r.z() * g.z(),
1603                    pw = r.w() * g.w();
1604        *reinterpret_cast<sycl::float4 *>(xn + i) =
1605            sycl::float4(px * rs, py * rs, pz * rs, pw * rs);
1606    }
1607}
1608
1609#if defined(DPCT_COMPATIBILITY_TEMP) && DPCT_COMPATIBILITY_TEMP >= 800 &&      \
1610    !defined(__HIPCC__)
1611#define STRATA_GR_CP_ASYNC 1
1612#endif
1613__dpct_inline__ void cp_async16(void *smem, const void *gmem) {
1614#if defined(STRATA_GR_CP_ASYNC)
1615    auto sa = smem;
1616#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)
1617    asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"(sa),
1618                 "l"(gmem)
1619                 : "memory");
1620#else
1621    *(((uint32_t *)(uintptr_t)sa)) = *(((uint32_t *)(uintptr_t)gmem));
1622    if (16 > 4)
1623        *(((uint32_t *)(uintptr_t)sa) + 1) =
1624            *(((uint32_t *)(uintptr_t)gmem) + 1);
1625    if (16 > 8)
1626        *(((uint32_t *)(uintptr_t)sa) + 2) =
1627            *(((uint32_t *)(uintptr_t)gmem) + 2);
1628    if (16 > 12)
1629        *(((uint32_t *)(uintptr_t)sa) + 3) =
1630            *(((uint32_t *)(uintptr_t)gmem) + 3);
1631#endif
1632#else
1633    *reinterpret_cast<float4*>(smem) = *reinterpret_cast<const float4*>(gmem);
1634#endif
1635}
1636__dpct_inline__ void cp_async_commit() {
1637#if defined(STRATA_GR_CP_ASYNC)
1638#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)
1639    asm volatile("cp.async.commit_group;\n" ::: "memory");
1640#else
1641
1642#endif
1643#endif
1644}
1645__dpct_inline__ void cp_async_wait1() {
1646#if defined(STRATA_GR_CP_ASYNC)
1647#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)
1648    asm volatile("cp.async.wait_group 1;\n" ::: "memory");
1649#else
1650
1651#endif
1652#endif
1653}
1654__dpct_inline__ void cp_async_wait0() {
1655#if defined(STRATA_GR_CP_ASYNC)
1656#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)
1657    asm volatile("cp.async.wait_group 0;\n" ::: "memory");
1658#else
1659
1660#endif
1661#endif
1662}
1663
1664// `dot8` with its 8 activations as two float4: the same eight fmaf in the same order
1665__dpct_inline__ float dot8v(const sycl::uint4 w, const sycl::float4 x0,
1666                            const sycl::float4 x1) {
1667    float acc = 0.0f;
1668    acc = sycl::fma(sycl::bit_cast<float>(w.x() << 16), (float)(x0.x()), acc);
1669    acc = sycl::fma(sycl::bit_cast<float>(w.x() & 0xffff0000u), (float)(x0.y()),
1670                    acc);
1671    acc = sycl::fma(sycl::bit_cast<float>(w.y() << 16), (float)(x0.z()), acc);
1672    acc = sycl::fma(sycl::bit_cast<float>(w.y() & 0xffff0000u), (float)(x0.w()),
1673                    acc);
1674    acc = sycl::fma(sycl::bit_cast<float>(w.z() << 16), (float)(x1.x()), acc);
1675    acc = sycl::fma(sycl::bit_cast<float>(w.z() & 0xffff0000u), (float)(x1.y()),
1676                    acc);
1677    acc = sycl::fma(sycl::bit_cast<float>(w.w() << 16), (float)(x1.z()), acc);
1678    acc = sycl::fma(sycl::bit_cast<float>(w.w() & 0xffff0000u), (float)(x1.w()),
1679                    acc);
1680    return acc;
1681}
1682
1683// Stage tile `h` of every token into `buf`: [T][2 planes][160 chunks] float4, plane 0 = floats 0-3 of a chunk.
1684__dpct_inline__ void stage_htile(const GrMulti &m, int T, int h,
1685                                 sycl::float4 *buf, int t) {
1686    for (int i = t; i < T * (H_TILE / 4); i += THREADS) {
1687        const int k = i / (H_TILE / 4), s4 = i - k * (H_TILE / 4);   // s4: float4 of the tile, chunk s4/2, half s4&1
1688        const float* src = m.xn + (size_t) k * D + (size_t) h * H_TILE + (size_t) s4 * 4;
1689        cp_async16(buf + (size_t) k * (H_TILE / 4) + (s4 & 1) * (H_TILE / 8) + (s4 >> 1), src);
1690    }
1691}
1692
1693template <int MAX_T = kFusedGrMaxT>
1694/*
1695DPCT1110: The total declared local variable size in device function
1696gr_down_staged_kernel exceeds 128 bytes and may cause high register pressure.
1697Consult with your hardware vendor to find the total register size available and
1698adjust the code, or use smaller sub-group size to avoid high register pressure.
1699*/
1700__dpct_inline__ void gr_down_staged_kernel(GrMulti m, uint8_t *dpct_local) {
1701    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1702    auto hbuf = (sycl::float4 *)dpct_local; // 2 buffers x [T][2][160] float4
1703    const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
1704    const int T = m.T;
1705    const bool inject_block = item_ct1.get_group(2) == DOWN_BLOCKS;
1706    const int row = inject_block ? warp : item_ct1.get_group(2) * WARPS + warp;
1707    const bool active = !(inject_block && (m.a[0].w_inject == nullptr || warp >= HC));
1708    const uint16_t* wrow = (inject_block ? m.a[0].w_inject : m.a[0].w_down) + (size_t) (active ? row : 0) * D;
1709    const sycl::uint4 *w4 = reinterpret_cast<const sycl::uint4 *>(wrow);
1710    const size_t buf_f4 = (size_t) T * (H_TILE / 4);    // float4 per buffer (the second one follows the first)
1711    float acc[MAX_T];
1712#pragma unroll
1713    for (int k = 0; k < MAX_T; ++k) acc[k] = 0.0f;
1714    sycl::uint4 wv[HQ], wnext[HQ];
1715    if (active) {
1716#pragma unroll
1717        /*
1718        DPCT1098: The '*' expression is used instead of the __ldg call.
1719        These two expressions do not provide the exact same functionality. Check
1720        the generated code for potential precision and/or performance issues.
1721        */
1722        for (int q = 0; q < HQ; ++q) wv[q] = *(w4 + lane + 32 * q);
1723    }
1724    stage_htile(m, T, 0, hbuf, t);
1725    cp_async_commit();
1726    stage_htile(m, T, 1, hbuf + buf_f4, t);
1727    cp_async_commit();
1728#pragma unroll 1
1729    for (int h = 0; h < N_HTILES; ++h) {
1730        if (active && h + 1 < N_HTILES) {
1731#pragma unroll
1732            /*
1733            DPCT1098: The '*' expression is used instead of the __ldg call.
1734            These two expressions do not provide the exact same functionality.
1735            Check the generated code for potential precision and/or performance
1736            issues.
1737            */
1738            for (int q = 0; q < HQ; ++q)
1739                wnext[q] = *(w4 + (h + 1) * (H_TILE / 8) + lane + 32 * q);
1740        }
1741        if (h + 1 < N_HTILES) cp_async_wait1();         // tile h has landed (h + 1 may still be on its way)
1742        else cp_async_wait0();
1743        /*
1744        DPCT1118: SYCL group functions and algorithms must be encountered in
1745        converged control flow. You may need to adjust the code.
1746        */
1747        /*
1748        DPCT1065: Consider replacing sycl::nd_item::barrier() with
1749        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
1750        better performance if there is no access to global memory.
1751        */
1752        item_ct1.barrier();
1753        const sycl::float4 *cur = hbuf + (h & 1) * buf_f4;
1754        if (active) {
1755#pragma unroll
1756            for (int q = 0; q < HQ; ++q) {
1757                const int j = lane + 32 * q;
1758#pragma unroll
1759                for (int k = 0; k < MAX_T; ++k) {
1760                    if (k < T) {
1761                        const sycl::float4 *pk = cur + (size_t)k * (H_TILE / 4);
1762                        acc[k] += dot8v(wv[q], pk[j], pk[H_TILE / 8 + j]);
1763                    }
1764                }
1765            }
1766        }
1767        /*
1768        DPCT1118: SYCL group functions and algorithms must be encountered in
1769        converged control flow. You may need to adjust the code.
1770        */
1771        /*
1772        DPCT1065: Consider replacing sycl::nd_item::barrier() with
1773        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
1774        better performance if there is no access to global memory.
1775        */
1776        item_ct1.barrier(); // every warp is done with buffer h & 1
1777        if (h + 2 < N_HTILES) stage_htile(m, T, h + 2, hbuf + (h & 1) * buf_f4, t);
1778        cp_async_commit();                              // an empty group at the end keeps the wait counts simple
1779        if (h + 1 < N_HTILES) {
1780#pragma unroll
1781            for (int q = 0; q < HQ; ++q) wv[q] = wnext[q];
1782        }
1783    }
1784    if (!active) return;
1785    float s[MAX_T];
1786#pragma unroll
1787    for (int k = 0; k < MAX_T; ++k) s[k] = k < T ? warp_sum(acc[k]) : 0.0f;
1788    // lane k writes token k (every lane holds every sum after the xor reduction)
1789#pragma unroll
1790    for (int k = 0; k < MAX_T; ++k) {
1791        if (k >= T || lane != k) continue;
1792        if (inject_block) {
1793            m.a[k].inject_out[row] = s[k];
1794        } else {
1795            const float x = s[k] / (float) HC;
1796            m.a[k].lo[row] = x / (1.0f + sycl::native::exp(-x));
1797        }
1798    }
1799}
1800
1801// The tokens a down kernel may carry in one launch on the current card, and the plain read's tile: the plain read
1802// stages n_tok * TILEV floats (1280 on sm_75, 2560 elsewhere), staged two tiles of n_tok * H_TILE.  The shared-memory
1803// opt-in is set here once per device (a per-DEVICE setting: a layer split runs these kernels on two cards).
1804int down_chunk(bool staged, int* tile_out) {
1805    static bool attr[64] = {};
1806    static int chunk[64] = {};   // tokens the plain down kernel may carry in one launch on this card
1807    static int chunk_staged[64] = {};  // the same for staged
1808    static int tile[64] = {};    // the plain down kernel's TILEV on this card (1280 on sm_75, 2560 elsewhere)
1809    int dev = 0;
1810    dev = dpct::get_current_device_id();
1811    if (dev < 0 || dev >= 64) {
1812        *tile_out = N;
1813        return kFusedGrMaxT;
1814    }
1815    if (!attr[dev]) {
1816        int optin = 0;
1817        /*
1818        DPCT1019: local_mem_size in SYCL is not a complete equivalent of
1819        cudaDevAttrMaxSharedMemoryPerBlockOptin in CUDA. You may need to adjust
1820        the code.
1821        */
1822        optin = dpct::get_device(dev).get_local_mem_size();
1823        optin = strata::smem_optin_of(optin);   // STRATA_EMULATE_CC (tests only)
1824        // the down kernel stages n_tok*TILEV floats of dynamic shared memory - 80 KB at the full 8 tokens of the
1825        // CUDA tile.  sm_75 gets the smaller tile: all eight tokens fit one 40 KiB launch there (no more slicing),
1826        // the TQ-5 prefetch holds half the registers, and the smaller blocks raise how many of the 41-block grid
1827        // share an SM.  Cards whose opt-in is still below that (or that report no opt-in at all) slice the tokens;
1828        // the down kernel's outputs (lo, inject_out) are strictly per-token, so the chunk boundaries are safe, and
1829        // the up kernel below still sees every token of the batch in one launch.
1830#if defined(__HIPCC__)
1831        const bool small_tile = true;   // all eight tokens fit gfx1100's 64 KiB LDS at this tile
1832#else
1833        int cc_maj = 0, cc_min = 0;
1834        cc_maj = dpct::get_device(dev).get_major_version();
1835        cc_min = dpct::get_device(dev).get_minor_version();
1836        const bool small_tile = strata::cc_major_of(cc_maj) * 10 + strata::cc_minor_of(cc_min) == 75;
1837#endif
1838        const int tv = small_tile ? (N / 2) : N;
1839        tile[dev] = tv;
1840        int want = (int) (kFusedGrMaxT * tv * sizeof(float));
1841        if (optin > 0 && want > optin) want = optin;
1842        if (small_tile) {
1843            /*
1844            DPCT1026: The call to cudaFuncSetAttribute was removed because
1845            SYCL currently does not support corresponding setting.
1846            */
1847        } else {
1848            /*
1849            DPCT1026: The call to cudaFuncSetAttribute was removed because
1850            SYCL currently does not support corresponding setting.
1851            */
1852        }
1853        int want_staged = (int) (2 * kFusedGrMaxT * H_TILE * sizeof(float));
1854        if (optin > 0 && want_staged > optin) want_staged = optin;
1855        /*
1856        DPCT1026: The call to cudaFuncSetAttribute was removed because SYCL
1857        currently does not support corresponding setting.
1858        */
1859        /*
1860        DPCT1026: The call to cudaGetLastError was removed because this
1861        functionality is redundant in SYCL.
1862        */
1863; // drop any error the attempt left behind
1864  // The opt-in is a promise a pre-Volta card does not keep: an sm_60 answers
1865  // 65536 and accepts the cudaFuncSetAttribute for 61440 B, then fails the
1866  // LAUNCH with "invalid argument".  What such a card will launch is its
1867  // per-block limit, so the capacity comes from that below sm_70 - the same
1868  // tokens the "no opt-in" branch assumes, but taken from the attribute that is
1869  // actually enforced.
1870#if defined(__HIPCC__)
1871        const int usable = optin > 0 ? optin : 48 * 1024;
1872#else
1873        int cc = 0, per_block = 0;
1874        cc = dpct::get_device(dev).get_major_version();
1875        per_block = (int) dpct::get_device(dev).get_local_mem_size();   // SYCL: the work-group local memory
1876        cc = strata::cc_major_of(cc);
1877        const int usable = (cc >= 7 && optin > 0) ? optin : per_block;
1878#endif
1879        const int capacity = usable / (int) (tv * sizeof(float));
1880        chunk[dev] = capacity < 1 ? 1 : (capacity > kFusedGrMaxT ? kFusedGrMaxT : capacity);
1881        const int capacity_staged = usable / (int) (2 * H_TILE * sizeof(float));
1882        chunk_staged[dev] = capacity_staged < 1 ? 1 : (capacity_staged > kFusedGrMaxT ? kFusedGrMaxT : capacity_staged);
1883        attr[dev] = true;
1884    }
1885    *tile_out = tile[dev] ? tile[dev] : N;
1886    return staged ? chunk_staged[dev] : chunk[dev];
1887}
1888
1889// The multi read as `variant` (kHcPlain, kHcSplit or kHcStaged): the norm, the down projection in launches of as
1890// many tokens as fit the card, the up projection; the profile's stamps after the norm and after the down projection.
1891// kHcPlain is the default read exactly as before (never main's opt-in STRATA_GR_V3 path, which fused_gr_read_multi
1892// takes first).
1893void launch_multi(const GrMulti &m, int variant, dpct::queue_ptr st,
1894                  unsigned long long *stamp_buf, int stamp_i0) {
1895    const int n_tok = m.T;
1896    if (variant >= kHcSplit) {
1897        auto exp_props = sycl::ext::oneapi::experimental::properties{
1898            sycl::ext::oneapi::experimental::use_root_sync};
1899
1900        strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class gr_norm_split_kernel_200589>>(
1901            sycl::nd_range<3>(sycl::range(1, HC, (unsigned)n_tok) *
1902                                  sycl::range(1, 1, THREADS),
1903                              sycl::range(1, 1, THREADS)),
1904            exp_props,
1905            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
1906                gr_norm_split_kernel(m);
1907            });
1908    } else {
1909        auto exp_props = sycl::ext::oneapi::experimental::properties{
1910            sycl::ext::oneapi::experimental::use_root_sync};
1911
1912        strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class gr_norm_multi_kernel_2f4d93>>(
1913            sycl::nd_range<3>(sycl::range(1, 1, n_tok) *
1914                                  sycl::range(1, 1, THREADS),
1915                              sycl::range(1, 1, THREADS)),
1916            exp_props,
1917            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
1918                gr_norm_multi_kernel(m);
1919            });
1920    }
1921    if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0, (void*) st);
1922    const bool staged = variant >= kHcStaged;
1923    int tv = N;
1924    const int chunk_tok = down_chunk(staged, &tv);
1925    /*
1926    DPCT1083: The size of local memory in the migrated code may be different
1927    from the original code. Check that the allocated memory size in the migrated
1928    code is correct.
1929    */
1930    const size_t per_tok =
1931        (staged ? (size_t)2 * H_TILE : (size_t)tv) * sizeof(float);
1932    for (int c0 = 0; c0 < n_tok; c0 += chunk_tok) {
1933        const int ct = n_tok - c0 < chunk_tok ? n_tok - c0 : chunk_tok;
1934        GrMulti c{};
1935        if (ct == n_tok) {
1936            c = m;
1937        } else {
1938            c.xn = m.xn + (size_t) c0 * D;
1939            c.T = ct;
1940            for (int k = 0; k < ct; ++k) c.a[k] = m.a[c0 + k];
1941        }
1942        const size_t smem = (size_t) ct * per_tok;
1943        // #443, opt-in STRATA_GR_DOWN_MAX4=1: launches of up to 4 tokens hold 4 tokens' sums per thread instead of
1944        // kFusedGrMaxT - the same tile, block size, accumulation order and plain/split/staged path, so the same bits
1945        // (read once: this runs per layer when decode is not captured)
1946        static const bool max4_on = [] { const char* v = std::getenv("STRATA_GR_DOWN_MAX4"); return v && std::atoi(v) != 0; }();
1947        const bool max4 = max4_on && ct <= 4;
1948        if (staged) {
1949            if (max4) {
1950                auto exp_props = sycl::ext::oneapi::experimental::properties{
1951                    sycl::ext::oneapi::experimental::use_root_sync};
1952
1953                strata::kprof::kp(st, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
1954                    sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
1955                        sycl::range(smem), cgh);
1956
1957                    cgh.parallel_for<
1958                        dpct_kernel_name<class gr_down_staged_kernel_41b428,
1959                                         dpct_kernel_scalar<4>>>(
1960                        sycl::nd_range<3>(sycl::range(1, 1, DOWN_BLOCKS + 1) *
1961                                              sycl::range(1, 1, THREADS),
1962                                          sycl::range(1, 1, THREADS)),
1963                        exp_props,
1964                        [=](sycl::nd_item<3> item_ct1)
1965                            [[sycl::reqd_sub_group_size(32)]] {
1966                                gr_down_staged_kernel<4>(
1967                                    c, dpct_local_acc_ct1
1968                                           .get_multi_ptr<
1969                                               sycl::access::decorated::no>()
1970                                           .get());
1971                            });
1972                });
1973            } else {
1974                auto exp_props = sycl::ext::oneapi::experimental::properties{
1975                    sycl::ext::oneapi::experimental::use_root_sync};
1976
1977                strata::kprof::kp(st, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
1978                    sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
1979                        sycl::range(smem), cgh);
1980
1981                    /*
1982                    DPCT1050: The template argument of the dpct_kernel_name
1983                    could not be deduced. You need to update this code.
1984                    */
1985                    cgh.parallel_for<dpct_kernel_name<
1986                        class gr_down_staged_kernel_41b428>>(
1987                        sycl::nd_range<3>(sycl::range(1, 1, DOWN_BLOCKS + 1) *
1988                                              sycl::range(1, 1, THREADS),
1989                                          sycl::range(1, 1, THREADS)),
1990                        exp_props,
1991                        [=](sycl::nd_item<3> item_ct1)
1992                            [[sycl::reqd_sub_group_size(32)]] {
1993                                gr_down_staged_kernel(
1994                                    c, dpct_local_acc_ct1
1995                                           .get_multi_ptr<
1996                                               sycl::access::decorated::no>()
1997                                           .get());
1998                            });
1999                });
2000            }
2001        } else if (tv == (N / 2)) {
2002            if (max4) {
2003                auto exp_props = sycl::ext::oneapi::experimental::properties{
2004                    sycl::ext::oneapi::experimental::use_root_sync};
2005
2006                strata::kprof::kp(st, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
2007                    sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
2008                        sycl::range(smem), cgh);
2009
2010                    cgh.parallel_for<dpct_kernel_name<
2011                        class gr_down_multi_kernel_4a9670,
2012                        dpct_kernel_scalar<(N / 2)>, dpct_kernel_scalar<4>>>(
2013                        sycl::nd_range<3>(sycl::range(1, 1, DOWN_BLOCKS + 1) *
2014                                              sycl::range(1, 1, THREADS),
2015                                          sycl::range(1, 1, THREADS)),
2016                        exp_props,
2017                        [=](sycl::nd_item<3> item_ct1)
2018                            [[sycl::reqd_sub_group_size(32)]] {
2019                                gr_down_multi_kernel<(N / 2), 4>(
2020                                    c, dpct_local_acc_ct1
2021                                           .get_multi_ptr<
2022                                               sycl::access::decorated::no>()
2023                                           .get());
2024                            });
2025                });
2026            } else {
2027                auto exp_props = sycl::ext::oneapi::experimental::properties{
2028                    sycl::ext::oneapi::experimental::use_root_sync};
2029
2030                strata::kprof::kp(st, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
2031                    sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
2032                        sycl::range(smem), cgh);
2033
2034                    /*
2035                    DPCT1050: The template argument of the dpct_kernel_name
2036                    could not be deduced. You need to update this code.
2037                    */
2038                    cgh.parallel_for<dpct_kernel_name<
2039                        class gr_down_multi_kernel_6a749c,
2040                        dpct_kernel_scalar<(N / 2)>, dpct_kernel_scalar<(N / 2)>>>(
2041                        sycl::nd_range<3>(sycl::range(1, 1, DOWN_BLOCKS + 1) *
2042                                              sycl::range(1, 1, THREADS),
2043                                          sycl::range(1, 1, THREADS)),
2044                        exp_props,
2045                        [=](sycl::nd_item<3> item_ct1)
2046                            [[sycl::reqd_sub_group_size(32)]] {
2047                                gr_down_multi_kernel<(N / 2)>(
2048                                    c, dpct_local_acc_ct1
2049                                           .get_multi_ptr<
2050                                               sycl::access::decorated::no>()
2051                                           .get());
2052                            });
2053                });
2054            }
2055        } else {
2056            if (max4) {
2057                auto exp_props = sycl::ext::oneapi::experimental::properties{
2058                    sycl::ext::oneapi::experimental::use_root_sync};
2059
2060                strata::kprof::kp(st, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
2061                    sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
2062                        sycl::range(smem), cgh);
2063
2064                    cgh.parallel_for<dpct_kernel_name<
2065                        class gr_down_multi_kernel_2d8885,
2066                        dpct_kernel_scalar<N>, dpct_kernel_scalar<4>>>(
2067                        sycl::nd_range<3>(sycl::range(1, 1, DOWN_BLOCKS + 1) *
2068                                              sycl::range(1, 1, THREADS),
2069                                          sycl::range(1, 1, THREADS)),
2070                        exp_props,
2071                        [=](sycl::nd_item<3> item_ct1)
2072                            [[sycl::reqd_sub_group_size(32)]] {
2073                                gr_down_multi_kernel<N, 4>(
2074                                    c, dpct_local_acc_ct1
2075                                           .get_multi_ptr<
2076                                               sycl::access::decorated::no>()
2077                                           .get());
2078                            });
2079                });
2080            } else {
2081                auto exp_props = sycl::ext::oneapi::experimental::properties{
2082                    sycl::ext::oneapi::experimental::use_root_sync};
2083
2084                strata::kprof::kp(st, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
2085                    sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
2086                        sycl::range(smem), cgh);
2087
2088                    /*
2089                    DPCT1050: The template argument of the dpct_kernel_name
2090                    could not be deduced. You need to update this code.
2091                    */
2092                    cgh.parallel_for<dpct_kernel_name<
2093                        class gr_down_multi_kernel_df2ead,
2094                        dpct_kernel_scalar<N>, dpct_kernel_scalar<N>>>(
2095                        sycl::nd_range<3>(sycl::range(1, 1, DOWN_BLOCKS + 1) *
2096                                              sycl::range(1, 1, THREADS),
2097                                          sycl::range(1, 1, THREADS)),
2098                        exp_props,
2099                        [=](sycl::nd_item<3> item_ct1)
2100                            [[sycl::reqd_sub_group_size(32)]] {
2101                                gr_down_multi_kernel<N>(
2102                                    c, dpct_local_acc_ct1
2103                                           .get_multi_ptr<
2104                                               sycl::access::decorated::no>()
2105                                           .get());
2106                            });
2107                });
2108            }
2109        }
2110    }
2111    if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0 + 1, (void*) st);
2112    launch_gr_up_multi(st, m);   // STRATA_GR_UP_COLS (16 default, 8, 4): the same bits
2113}
2114
2115/// STRATA_HC_SPLIT: unset or 2 = the newest the check accepts (staged), 1 = at most split, 0 = the plain read
2116int env_variant() {
2117    const char* e = std::getenv("STRATA_HC_SPLIT");
2118    if (e == nullptr || e[0] == '\0') return kHcStaged;
2119    if (e[0] == '0') return kHcPlain;
2120    if (e[0] == '1') return kHcSplit;
2121    return kHcStaged;
2122}
2123
2124// per device: the variant `fused_gr_check` chose (0 = not checked yet)
2125std::atomic<int> g_variant[64];
2126
2127// BEGIN PRIVATE UP FROM LO
2128
2129__dpct_inline__ void gr_up_from_lo_kernel(GrMulti m) {   // stream sum unchanged, so the same bits; more blocks, fewer serial rows per warp
2130    constexpr int COLS=UPM_COLS;
2131    constexpr bool ILP=false;
2132    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
2133auto &lo = *sycl::ext::oneapi::group_local_memory_for_overwrite<
2134    float[kFusedGrMaxT][LR]>(
2135    sycl::ext::oneapi::this_work_item::get_work_group<3>());
2136    auto &g = *sycl::ext::oneapi::group_local_memory_for_overwrite<
2137        float[kFusedGrMaxT][HC][COLS]>(
2138        sycl::ext::oneapi::this_work_item::get_work_group<3>());
2139    const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
2140    const int T = m.T;
2141    const int d0 = item_ct1.get_group(2) * COLS;
2142#pragma unroll 1
2143    for (int i=t;i<T*LR;i+=THREADS) {
2144        const int k=i/LR,r=i%LR;
2145        lo[k][r]=GR_PICK(m,k,lo)[r];
2146    }
2147    /*
2148    DPCT1065: Consider replacing sycl::nd_item::barrier() with
2149    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
2150    performance if there is no access to global memory.
2151    */
2152    item_ct1.barrier();
2153    // this lane's token (lane < T), picked once - not per row
2154    const int pk = lane < T ? lane : 0;
2155    const float* const pR = GR_PICK(m, pk, R);
2156    const float* const pWn = GR_PICK(m, pk, w_norm);
2157    const float* const pRs = GR_PICK(m, pk, rs);
2158    const bool pApply = GR_PICK(m, pk, apply);
2159    const float* const pBo = GR_PICK(m, pk, bo_prev);
2160    const float* const pIp = GR_PICK(m, pk, inj_prev);
2161    float* const pRout = GR_PICK(m, pk, R_out);
2162    for (int r = warp; r < HC * COLS; r += WARPS) {
2163        const int c = r / COLS, dd = r - c * COLS, i = c * N + d0 + dd;
2164        const sycl::uint4 *w4 =
2165            reinterpret_cast<const sycl::uint4 *>(m.a[0].w_up + (size_t)i * LR);
2166        /*
2167        DPCT1098: The '*' expression is used instead of the __ldg call.
2168        These two expressions do not provide the exact same functionality. Check
2169        the generated code for potential precision and/or performance issues.
2170        */
2171        const sycl::uint4 wa = *(w4 + lane);
2172        /*
2173        DPCT1098: The '*' expression is used instead of the __ldg call.
2174        These two expressions do not provide the exact same functionality. Check
2175        the generated code for potential precision and/or performance issues.
2176        */
2177        const sycl::uint4 wb =
2178            lane < LR / 8 - 32 ? *(w4 + 32 + lane) : sycl::uint4(0, 0, 0, 0);
2179        // the epilogue inputs of this lane's token, fetched while the dots run
2180        float rv = 0.0f, wn = 0.0f, rsc = 0.0f, bo = 0.0f, ip = 0.0f;
2181        bool apply = false;
2182        if (lane < T) {
2183            rv = pR[i];
2184            wn = pWn[i];
2185            rsc = pRs[c];
2186            apply = pApply;
2187            if (apply) { bo = pBo[d0 + dd]; ip = pIp[c]; }
2188        }
2189        float mine = 0.0f;
2190        if constexpr (ILP) {   // STRATA_GR_UP_ILP: the T dots first, then their butterflies interleaved step by step -
2191            float accs[kFusedGrMaxT];   // each value sees warp_sum's shuffles in warp_sum's order: the same bits
2192#pragma unroll
2193            for (int k = 0; k < kFusedGrMaxT; ++k) {
2194                float acc = 0.0f;
2195                if (k < T) {
2196                    acc = dot8(wa, lo[k] + lane * 8);
2197                    if (lane < LR / 8 - 32) acc += dot8(wb, lo[k] + (32 + lane) * 8);
2198                }
2199                accs[k] = acc;
2200            }
2201#pragma unroll
2202            for (int o = 16; o > 0; o >>= 1)
2203#pragma unroll
2204                for (int k = 0; k < kFusedGrMaxT; ++k)
2205                    if (k < T) accs[k] += dpct::experimental::permute_sub_group_by_xor(
2206                                   0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), accs[k], o);
2207#pragma unroll
2208            for (int k = 0; k < kFusedGrMaxT; ++k) if (k < T && lane == k) mine = accs[k];
2209        } else {
2210#pragma unroll
2211        for (int k = 0; k < kFusedGrMaxT; ++k) {
2212            if (k >= T) break;
2213            float acc = dot8(wa, lo[k] + lane * 8);
2214            if (lane < LR / 8 - 32) acc += dot8(wb, lo[k] + (32 + lane) * 8);
2215            acc = warp_sum(acc);
2216            if (lane == k) mine = acc;
2217        }
2218        }
2219        if (lane < T) {
2220            if (apply) {
2221                rv = sycl::fma(bo, 2.0f * sigmoidf_(ip / (float)HC), rv);
2222                pRout[i] = rv;
2223            }
2224            const float x = rv * wn * rsc;
2225            g[lane][c][dd] = x * sigmoidf_(mine);
2226        }
2227    }
2228    /*
2229    DPCT1065: Consider replacing sycl::nd_item::barrier() with
2230    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
2231    performance if there is no access to global memory.
2232    */
2233    item_ct1.barrier();
2234    for (int i = t; i < T * COLS; i += THREADS) {
2235        const int k = i / COLS, col = i - k * COLS;
2236        float s = 0.0f;
2237#pragma unroll
2238        for (int c = 0; c < HC; ++c) s += g[k][c][col];
2239        GR_PICK(m, k, mixed)[d0 + col] = s / (float) HC;
2240    }
2241}
2242
2243// END PRIVATE UP FROM LO
2244// BEGIN PRIVATE LO VEC4
2245struct alignas(16) GrLoVec4Storage {float values[kFusedGrMaxT][2][LR/2];};
2246static_assert(sizeof(GrLoVec4Storage)==kFusedGrMaxT*LR*sizeof(float));
2247__dpct_inline__ float gr_lo_vec4_dot(sycl::uint4 w,const float* low,const float* high) {
2248    const sycl::float4 a(low[0],low[1],low[2],low[3]);
2249    const sycl::float4 b(high[0],high[1],high[2],high[3]);
2250    return dot8v(w,a,b);
2251}
2252__dpct_inline__ void gr_up_lo_vec4_kernel(GrMulti m) {   // stream sum unchanged, so the same bits; more blocks, fewer serial rows per warp
2253    constexpr int COLS=UPM_COLS;
2254    constexpr bool ILP=false;
2255    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
2256auto &lo = (*sycl::ext::oneapi::group_local_memory_for_overwrite<
2257    GrLoVec4Storage>(sycl::ext::oneapi::this_work_item::get_work_group<3>())).values;
2258    auto &g = *sycl::ext::oneapi::group_local_memory_for_overwrite<
2259        float[kFusedGrMaxT][HC][COLS]>(
2260        sycl::ext::oneapi::this_work_item::get_work_group<3>());
2261    const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
2262    const int T = m.T;
2263    const int d0 = item_ct1.get_group(2) * COLS;
2264#pragma unroll 1
2265    for (int i=t;i<T*LR;i+=THREADS) {
2266        const int k=i/LR,r=i%LR;
2267        lo[k][(r>>2)&1][(r>>3)*4+(r&3)]=GR_PICK(m,k,lo)[r];
2268    }
2269    /*
2270    DPCT1065: Consider replacing sycl::nd_item::barrier() with
2271    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
2272    performance if there is no access to global memory.
2273    */
2274    item_ct1.barrier();
2275    // this lane's token (lane < T), picked once - not per row
2276    const int pk = lane < T ? lane : 0;
2277    const float* const pR = GR_PICK(m, pk, R);
2278    const float* const pWn = GR_PICK(m, pk, w_norm);
2279    const float* const pRs = GR_PICK(m, pk, rs);
2280    const bool pApply = GR_PICK(m, pk, apply);
2281    const float* const pBo = GR_PICK(m, pk, bo_prev);
2282    const float* const pIp = GR_PICK(m, pk, inj_prev);
2283    float* const pRout = GR_PICK(m, pk, R_out);
2284    for (int r = warp; r < HC * COLS; r += WARPS) {
2285        const int c = r / COLS, dd = r - c * COLS, i = c * N + d0 + dd;
2286        const sycl::uint4 *w4 =
2287            reinterpret_cast<const sycl::uint4 *>(m.a[0].w_up + (size_t)i * LR);
2288        /*
2289        DPCT1098: The '*' expression is used instead of the __ldg call.
2290        These two expressions do not provide the exact same functionality. Check
2291        the generated code for potential precision and/or performance issues.
2292        */
2293        const sycl::uint4 wa = *(w4 + lane);
2294        /*
2295        DPCT1098: The '*' expression is used instead of the __ldg call.
2296        These two expressions do not provide the exact same functionality. Check
2297        the generated code for potential precision and/or performance issues.
2298        */
2299        const sycl::uint4 wb =
2300            lane < LR / 8 - 32 ? *(w4 + 32 + lane) : sycl::uint4(0, 0, 0, 0);
2301        // the epilogue inputs of this lane's token, fetched while the dots run
2302        float rv = 0.0f, wn = 0.0f, rsc = 0.0f, bo = 0.0f, ip = 0.0f;
2303        bool apply = false;
2304        if (lane < T) {
2305            rv = pR[i];
2306            wn = pWn[i];
2307            rsc = pRs[c];
2308            apply = pApply;
2309            if (apply) { bo = pBo[d0 + dd]; ip = pIp[c]; }
2310        }
2311        float mine = 0.0f;
2312        if constexpr (ILP) {   // STRATA_GR_UP_ILP: the T dots first, then their butterflies interleaved step by step -
2313            float accs[kFusedGrMaxT];   // each value sees warp_sum's shuffles in warp_sum's order: the same bits
2314#pragma unroll
2315            for (int k = 0; k < kFusedGrMaxT; ++k) {
2316                float acc = 0.0f;
2317                if (k < T) {
2318                    acc = gr_lo_vec4_dot(wa,lo[k][0]+lane*4,lo[k][1]+lane*4);
2319                    if (lane < LR / 8 - 32) acc += gr_lo_vec4_dot(wb,lo[k][0]+(32+lane)*4,lo[k][1]+(32+lane)*4);
2320                }
2321                accs[k] = acc;
2322            }
2323#pragma unroll
2324            for (int o = 16; o > 0; o >>= 1)
2325#pragma unroll
2326                for (int k = 0; k < kFusedGrMaxT; ++k)
2327                    if (k < T) accs[k] += dpct::experimental::permute_sub_group_by_xor(
2328                                   0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), accs[k], o);
2329#pragma unroll
2330            for (int k = 0; k < kFusedGrMaxT; ++k) if (k < T && lane == k) mine = accs[k];
2331        } else {
2332#pragma unroll
2333        for (int k = 0; k < kFusedGrMaxT; ++k) {
2334            if (k >= T) break;
2335            float acc = gr_lo_vec4_dot(wa,lo[k][0]+lane*4,lo[k][1]+lane*4);
2336            if (lane < LR / 8 - 32) acc += gr_lo_vec4_dot(wb,lo[k][0]+(32+lane)*4,lo[k][1]+(32+lane)*4);
2337            acc = warp_sum(acc);
2338            if (lane == k) mine = acc;
2339        }
2340        }
2341        if (lane < T) {
2342            if (apply) {
2343                rv = sycl::fma(bo, 2.0f * sigmoidf_(ip / (float)HC), rv);
2344                pRout[i] = rv;
2345            }
2346            const float x = rv * wn * rsc;
2347            g[lane][c][dd] = x * sigmoidf_(mine);
2348        }
2349    }
2350    /*
2351    DPCT1065: Consider replacing sycl::nd_item::barrier() with
2352    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
2353    performance if there is no access to global memory.
2354    */
2355    item_ct1.barrier();
2356    for (int i = t; i < T * COLS; i += THREADS) {
2357        const int k = i / COLS, col = i - k * COLS;
2358        float s = 0.0f;
2359#pragma unroll
2360        for (int c = 0; c < HC; ++c) s += g[k][c][col];
2361        GR_PICK(m, k, mixed)[d0 + col] = s / (float) HC;
2362    }
2363}
2364
2365class GrUpLoVec4;
2366inline bool gr_lo_vec4_enabled() {
2367    static const bool on=[] {const char* p=std::getenv("STRATA_PRIVATE_GR_LO_VEC4");return p&&std::atoi(p)!=0;}();
2368    return on;
2369}
2370void launch_gr_up_lo_vec4(dpct::queue_ptr st,const GrMulti& m) {
2371    const sycl::nd_range<3> r(sycl::range<3>(1,1,UPM_BLOCKS*THREADS),sycl::range<3>(1,1,THREADS));
2372    const auto props=sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};
2373    st->parallel_for<GrUpLoVec4>(r,props,[=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] {gr_up_lo_vec4_kernel(m);});
2374}
2375// END PRIVATE LO VEC4
2376
2377
2378// Match the original quantizer type name: AOT coalesces identical layouts.
2379struct Q81Block {sycl::half2 ds;int8_t qs[32];};
2380static_assert(sizeof(Q81Block)==36 && offsetof(Q81Block,qs)==4);
2381__dpct_inline__ float b60_gr_q8_warp_max(float value){
2382 #pragma unroll
2383 for(int off=16;off>0;off>>=1)value=sycl::fmax(value,dpct::experimental::permute_sub_group_by_xor(0xffffffffu,sycl::ext::oneapi::this_work_item::get_sub_group(),value,off));
2384 return value;
2385}
2386inline bool b60_gr_q8_up32_enabled(){static const bool on=[] {const char*p=std::getenv("STRATA_PRIVATE_GR_Q8_UP32");return p&&p[0]=='1';}();return on&&b60_layout_requested();}
2387__dpct_inline__ void b60_gr_q8_up32_t1_kernel(GrMulti m) {   // stream sum unchanged, so the same bits; more blocks, fewer serial rows per warp
2388    constexpr int COLS=32;
2389    constexpr bool ILP=false;
2390    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
2391auto &lo = *sycl::ext::oneapi::group_local_memory_for_overwrite<
2392    float[1][LR]>(
2393    sycl::ext::oneapi::this_work_item::get_work_group<3>());
2394    auto &g = *sycl::ext::oneapi::group_local_memory_for_overwrite<
2395        float[1][HC][COLS]>(
2396        sycl::ext::oneapi::this_work_item::get_work_group<3>());
2397    const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
2398    constexpr int T = 1;
2399    const int d0 = item_ct1.get_group(2) * COLS;
2400#pragma unroll 1
2401    for (int i=t;i<T*LR;i+=THREADS) {
2402        const int k=i/LR,r=i%LR;
2403        lo[k][r]=GR_PICK(m,k,lo)[r];
2404    }
2405    /*
2406    DPCT1065: Consider replacing sycl::nd_item::barrier() with
2407    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
2408    performance if there is no access to global memory.
2409    */
2410    item_ct1.barrier();
2411    // this lane's token (lane < T), picked once - not per row
2412    const int pk = lane < T ? lane : 0;
2413    const float* const pR = GR_PICK(m, pk, R);
2414    const float* const pWn = GR_PICK(m, pk, w_norm);
2415    const float* const pRs = GR_PICK(m, pk, rs);
2416    const bool pApply = GR_PICK(m, pk, apply);
2417    const float* const pBo = GR_PICK(m, pk, bo_prev);
2418    const float* const pIp = GR_PICK(m, pk, inj_prev);
2419    float* const pRout = GR_PICK(m, pk, R_out);
2420    for (int r = warp; r < HC * COLS; r += WARPS) {
2421        const int c = r / COLS, dd = r - c * COLS, i = c * N + d0 + dd;
2422        const sycl::uint4 *w4 =
2423            reinterpret_cast<const sycl::uint4 *>(m.a[0].w_up + (size_t)i * LR);
2424        /*
2425        DPCT1098: The '*' expression is used instead of the __ldg call.
2426        These two expressions do not provide the exact same functionality. Check
2427        the generated code for potential precision and/or performance issues.
2428        */
2429        const sycl::uint4 wa = *(w4 + lane);
2430        /*
2431        DPCT1098: The '*' expression is used instead of the __ldg call.
2432        These two expressions do not provide the exact same functionality. Check
2433        the generated code for potential precision and/or performance issues.
2434        */
2435        const sycl::uint4 wb =
2436            lane < LR / 8 - 32 ? *(w4 + 32 + lane) : sycl::uint4(0, 0, 0, 0);
2437        // the epilogue inputs of this lane's token, fetched while the dots run
2438        float rv = 0.0f, wn = 0.0f, rsc = 0.0f, bo = 0.0f, ip = 0.0f;
2439        bool apply = false;
2440        if (lane < T) {
2441            rv = pR[i];
2442            wn = pWn[i];
2443            rsc = pRs[c];
2444            apply = pApply;
2445            if (apply) { bo = pBo[d0 + dd]; ip = pIp[c]; }
2446        }
2447        float mine = 0.0f;
2448        if constexpr (ILP) {   // STRATA_GR_UP_ILP: the T dots first, then their butterflies interleaved step by step -
2449            float accs[1];   // each value sees warp_sum's shuffles in warp_sum's order: the same bits
2450#pragma unroll
2451            for (int k = 0; k < 1; ++k) {
2452                float acc = 0.0f;
2453                if (k < T) {
2454                    acc = dot8(wa, lo[k] + lane * 8);
2455                    if (lane < LR / 8 - 32) acc += dot8(wb, lo[k] + (32 + lane) * 8);
2456                }
2457                accs[k] = acc;
2458            }
2459#pragma unroll
2460            for (int o = 16; o > 0; o >>= 1)
2461#pragma unroll
2462                for (int k = 0; k < 1; ++k)
2463                    if (k < T) accs[k] += dpct::experimental::permute_sub_group_by_xor(
2464                                   0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), accs[k], o);
2465#pragma unroll
2466            for (int k = 0; k < 1; ++k) if (k < T && lane == k) mine = accs[k];
2467        } else {
2468#pragma unroll
2469        for (int k = 0; k < 1; ++k) {
2470            if (k >= T) break;
2471            float acc = dot8(wa, lo[k] + lane * 8);
2472            if (lane < LR / 8 - 32) acc += dot8(wb, lo[k] + (32 + lane) * 8);
2473            acc = warp_sum(acc);
2474            if (lane == k) mine = acc;
2475        }
2476        }
2477        if (lane < T) {
2478            if (apply) {
2479                rv = sycl::fma(bo, 2.0f * sigmoidf_(ip / (float)HC), rv);
2480                pRout[i] = rv;
2481            }
2482            const float x = rv * wn * rsc;
2483            g[lane][c][dd] = x * sigmoidf_(mine);
2484        }
2485    }
2486    /*
2487    DPCT1065: Consider replacing sycl::nd_item::barrier() with
2488    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
2489    performance if there is no access to global memory.
2490    */
2491    item_ct1.barrier();
2492    for (int i = t; i < T * COLS; i += THREADS) {
2493        const int k = i / COLS, col = i - k * COLS;
2494        float s = 0.0f;
2495#pragma unroll
2496        for (int c = 0; c < HC; ++c) s += g[k][c][col];
2497        const float xi=s/(float)HC;
2498        GR_PICK(m,k,mixed)[d0+col]=xi;
2499        const float amax=b60_gr_q8_warp_max(sycl::fabs(xi));
2500        const float sum=warp_sum(xi);
2501        const float scale=q8_1_finite(amax/127.0f);
2502        const int8_t quant=q8_1_quant(xi,scale,amax);
2503        auto* image=reinterpret_cast<Q81Block*>(GR_PICK(m,k,q8_mixed));
2504        image[(d0+col)/32].qs[col&31]=quant;
2505        if((col&31)==0)image[(d0+col)/32].ds=q8_1_ds(scale,sum);
2506    }
2507}
2508
2509
2510class B60GrQ8Up32T1;
2511void launch_b60_gr_q8_up32_t1(dpct::queue_ptr st,GrMulti m){
2512 const sycl::nd_range<3> r(sycl::range<3>(1,1,(N/32)*THREADS),sycl::range<3>(1,1,THREADS));
2513 const auto props=sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};
2514 st->parallel_for<B60GrQ8Up32T1>(r,props,[=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] {b60_gr_q8_up32_t1_kernel(m);});
2515}
2516
2517inline bool gr_up_rows16_enabled(){static const bool on=[] {const char*p=std::getenv("STRATA_PRIVATE_GR_UP_ROWS16");return p&&p[0]=='1';}();return on&&b60_layout_requested()&&b60_main_actor();}
2518void gf_dispatch_up(dpct::queue_ptr,GrMulti);
2519class GrUpFromLo;
2520class GrReduceSilu;
2521void launch_gr_up_from_lo(dpct::queue_ptr st,const GrMulti& m) {
2522    if(gr_up_rows16_enabled() && m.T==4){gf_dispatch_up(st,m);return;}
2523    if(gr_lo_vec4_enabled() && m.T>=2 && m.T<=4) {launch_gr_up_lo_vec4(st,m);return;}
2524    const sycl::nd_range<3> r(sycl::range<3>(1,1,UPM_BLOCKS*THREADS),sycl::range<3>(1,1,THREADS));
2525    const auto p=sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};
2526    st->parallel_for<GrUpFromLo>(r,p,[=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] {gr_up_from_lo_kernel(m);});
2527}
2528
2529inline bool gr_combo_silu_enabled() {
2530    static const bool enabled=[] {const char* p=std::getenv("STRATA_PRIVATE_GR_SILU_FROM_LO");return p&&std::atoi(p)!=0;}();
2531    return enabled;
2532}
2533
2534
2535// Private decode-only GR experiment. FP32 inputs; original dot8 and XOR trees.
2536namespace gf = sycl::ext::intel::esimd;
2537namespace gfm = sycl::ext::intel::experimental::esimd;
2538
2539template<int O>
2540SYCL_ESIMD_FUNCTION ESIMD_INLINE gf::simd<float,32> gf_xor(gf::simd<float,32> v) {
2541    gf::simd<float,32> w;
2542#pragma unroll
2543    for(int i=0;i<32;i+=2*O) {
2544        w.template select<O,1>(i)=v.template select<O,1>(i+O);
2545        w.template select<O,1>(i+O)=v.template select<O,1>(i);
2546    }
2547    return v+w;
2548}
2549
2550template<int E>
2551SYCL_ESIMD_FUNCTION ESIMD_INLINE void gf_up(GrMulti m,int d) {
2552#pragma clang fp contract(off)
2553    gf::simd<float,LR> lo[E];
2554#pragma unroll
2555    for(int e=0;e<E;++e) {
2556        lo[e].template select<128,1>(0)=gf::block_load<float,128>(m.a[e].lo);
2557        lo[e].template select<128,1>(128)=gf::block_load<float,128>(m.a[e].lo+128);
2558        lo[e].template select<64,1>(256)=gf::block_load<float,64>(m.a[e].lo+256);
2559    }
2560    for(int c=0;c<HC;++c) {
2561        const auto* p=reinterpret_cast<const uint32_t*>(m.a[0].w_up+(size_t)(c*N+d)*LR);
2562        auto wa=gf::block_load<uint32_t,128>(p);
2563        auto wb=gf::block_load<uint32_t,32>(p+128);
2564#pragma unroll
2565        for(int e=0;e<E;++e) {
2566            gf::simd<float,32> a=0.f;
2567#pragma unroll
2568            for(int j=0;j<4;++j) {
2569                gf::simd<uint32_t,32> bits=wa.template select<32,4>(j);
2570                gf::simd<uint32_t,32> low=bits<<16,high=bits&0xffff0000u;
2571                gf::simd<float,32> w0=low.template bit_cast_view<float>(),w1=high.template bit_cast_view<float>();
2572                gf::simd<float,32> x0=lo[e].template select<32,8>(2*j),x1=lo[e].template select<32,8>(2*j+1);
2573                a=gfm::fma(w0,x0,a);
2574                a=gfm::fma(w1,x1,a);
2575            }
2576            gf::simd<float,8> b=0.f;
2577#pragma unroll
2578            for(int j=0;j<4;++j) {
2579                gf::simd<uint32_t,8> bits=wb.template select<8,4>(j);
2580                gf::simd<uint32_t,8> low=bits<<16,high=bits&0xffff0000u;
2581                gf::simd<float,8> w0=low.template bit_cast_view<float>(),w1=high.template bit_cast_view<float>();
2582                gf::simd<float,8> x0=lo[e].template select<8,8>(256+2*j),x1=lo[e].template select<8,8>(257+2*j);
2583                b=gfm::fma(w0,x0,b);
2584                b=gfm::fma(w1,x1,b);
2585            }
2586            a.template select<8,1>(0)=a.template select<8,1>(0)+b;
2587            a=gf_xor<16>(a);a=gf_xor<8>(a);a=gf_xor<4>(a);a=gf_xor<2>(a);a=gf_xor<1>(a);
2588            // xn is no longer read by down. Postop restores every scratch value.
2589            m.xn[(size_t)e*D+c*N+d]=a[e];
2590        }
2591    }
2592}
2593
2594template<int E>
2595SYCL_ESIMD_FUNCTION ESIMD_INLINE void gf_down(GrMulti m,int sl,int tile) {
2596#pragma clang fp contract(off)
2597    if(tile>=21 || (tile==20 && !m.a[0].w_inject))return;
2598    gf::simd<uint32_t,16> rows(tile*16,1);
2599    auto valid=rows<uint32_t(GRS_ROWS);
2600    const auto* base=reinterpret_cast<const uint32_t*>(tile==20?m.a[0].w_inject:m.a[0].w_down);
2601    gf::simd<uint32_t,16> off=(rows-uint32_t(tile==20?LR:0))*uint32_t(D*2)+uint32_t(sl*GRS_COLS*2);
2602    gf::simd<float,128> x[E];
2603    gf::simd<float,16> acc[E][4];
2604#pragma unroll
2605    for(int e=0;e<E;++e) {
2606        x[e]=gf::block_load<float,128>(m.xn+(size_t)e*D+sl*GRS_COLS);
2607#pragma unroll
2608        for(int q=0;q<4;++q)acc[e][q]=0.f;
2609    }
2610#pragma unroll
2611    for(int cc=0;cc<4;++cc) {
2612        auto first=gf::gather<uint32_t,128,8>(base,off+uint32_t(cc*64),valid,gf::simd<uint32_t,128>(0));
2613        auto last=gf::gather<uint32_t,128,8>(base,off+uint32_t(cc*64+32),valid,gf::simd<uint32_t,128>(0));
2614#pragma unroll
2615        for(int q=0;q<4;++q) {
2616            gf::simd<float,16> dot[E];
2617#pragma unroll
2618            for(int e=0;e<E;++e)dot[e]=0.f;
2619#pragma unroll
2620            for(int j=0;j<4;++j) {
2621                gf::simd<uint32_t,16> bits;
2622                // VS8 gather returns component-major: word j across all16 rows.
2623                if(q<2)bits=first.template select<16,1>((q*4+j)*16);
2624                else bits=last.template select<16,1>(((q-2)*4+j)*16);
2625                gf::simd<uint32_t,16> low=bits<<16,high=bits&0xffff0000u;
2626                gf::simd<float,16> w0=low.template bit_cast_view<float>(),w1=high.template bit_cast_view<float>();
2627#pragma unroll
2628                for(int e=0;e<E;++e) {
2629                    dot[e]=gfm::fma(w0,gf::simd<float,16>(x[e][cc*32+q*8+2*j]),dot[e]);
2630                    dot[e]=gfm::fma(w1,gf::simd<float,16>(x[e][cc*32+q*8+2*j+1]),dot[e]);
2631                }
2632            }
2633#pragma unroll
2634            for(int e=0;e<E;++e)acc[e][q]=acc[e][q]+dot[e];
2635        }
2636    }
2637#pragma unroll
2638    for(int e=0;e<E;++e) {
2639        auto value=(acc[e][0]+acc[e][1])+(acc[e][2]+acc[e][3]);
2640        gf::scatter<float,16>(m.part2,((uint32_t(sl*kFusedGrMaxT+e)*GRS_ROWS)+rows)*4u,value,valid);
2641    }
2642}
2643
2644__dpct_inline__ void gf_reduce_silu(GrMulti m) {
2645    const int i=int(sycl::ext::oneapi::this_work_item::get_nd_item<3>().get_global_id(2));
2646    if(i>=m.T*GRS_ROWS)return;
2647    const int k=i/GRS_ROWS,r=i%GRS_ROWS;
2648    if(r>=LR && !m.a[0].w_inject)return;
2649    float x=0.f;
2650    for(int sl=0;sl<GRS_SLICES;++sl)x+=m.part2[((size_t)sl*kFusedGrMaxT+k)*GRS_ROWS+r];
2651    if(r<LR) {
2652        m.part[(size_t)k*LR+r]=x;
2653        float value=0.f;value+=x;value/=(float)HC;
2654        GR_PICK(m,k,lo)[r]=value/(1.f+sycl::native::exp(-value));
2655    } else GR_PICK(m,k,inject_out)[r-LR]=x;
2656}
2657
2658__dpct_inline__ void gf_postop(GrMulti m) {
2659#pragma clang fp contract(off)
2660    const int i=int(sycl::ext::oneapi::this_work_item::get_nd_item<3>().get_global_id(2));
2661    if(i>=m.T*N)return;
2662    const int k=i/N,d=i%N;
2663    const float* R=GR_PICK(m,k,R);
2664    const float* wn=GR_PICK(m,k,w_norm);
2665    const float* rs=GR_PICK(m,k,rs);
2666    float sum=0.f;
2667#pragma unroll
2668    for(int c=0;c<HC;++c) {
2669        const int j=c*N+d;
2670        const float score=m.xn[(size_t)k*D+j];
2671        float rv=R[j];
2672        if(GR_PICK(m,k,apply)) {
2673            const float bo=GR_PICK(m,k,bo_prev)[d],ip=GR_PICK(m,k,inj_prev)[c];
2674            rv=sycl::fma(bo,2.f*sigmoidf_(ip/(float)HC),rv);
2675            GR_PICK(m,k,R_out)[j]=rv;
2676        }
2677        const float x=rv*wn[j]*rs[c];
2678        m.xn[(size_t)k*D+j]=x;
2679        const float gate=x*sigmoidf_(score);
2680        sum+=gate;
2681    }
2682    GR_PICK(m,k,mixed)[d]=sum/(float)HC;
2683}
2684
2685bool gf_enabled(dpct::queue_ptr st,const GrMulti& m) {
2686    static const bool enabled=[] {const char* s=std::getenv("STRATA_PRIVATE_GR_F32_REG");return s&&std::atoi(s)!=0;}();
2687    return enabled && m.T>=1 && m.T<=4 && gr_down_sliced() && !gr_more_groups(st) && !gr_large_grf(st) &&
2688        gr_norm_split() && gr_up_cols()==16 && !gr_up_ilp() && strata::intel_gpu_gen(st->get_device())==strata::IntelGpuGen::Battlemage;
2689}
2690bool gf_phase(const char* phase) {
2691    const char* p=std::getenv("STRATA_PRIVATE_GR_F32_PHASE");
2692    return !p || std::strcmp(p,"both")==0 || std::strcmp(p,phase)==0;
2693}
2694template<int E> class GfDown;
2695template<int E> class GfUp;
2696class GfReduce;
2697template<int E> class GfPostop;
2698template<int E> void gf_launch_down(dpct::queue_ptr st,GrMulti m) {
2699    st->parallel_for<GfDown<E>>(sycl::nd_range<1>(GRS_SLICES*24,8),[=](sycl::nd_item<1> it) SYCL_ESIMD_KERNEL {
2700        const int id=int(it.get_global_id(0));gf_down<E>(m,id/24,id%24);
2701    });
2702}
2703// SIMD across16 output rows, preserving the original BF16 dot8/XOR arithmetic.
2704template<int E,int Lane>
2705SYCL_ESIMD_FUNCTION ESIMD_INLINE gf::simd<float,E*16> gp_leaf(GrMulti m,int row) {
2706#pragma clang fp contract(off)
2707 const auto* w=reinterpret_cast<const uint32_t*>(m.a[0].w_up);
2708 auto wa=gf::load_2d<uint32_t,4,16,1,true,false>(w,LR*2-1,D-1,LR*2-1,Lane*4,row);
2709 gf::simd<float,8> x[E];gf::simd<float,16> dot[E];
2710#pragma unroll
2711 for(int e=0;e<E;++e){x[e]=gf::block_load<float,8>(m.a[e].lo+Lane*8);dot[e]=0.f;}
2712#pragma unroll
2713 for(int j=0;j<4;++j){
2714  gf::simd<uint32_t,16> bits=wa.template select<16,1>(j*16),low=bits<<16,high=bits&0xffff0000u;
2715  gf::simd<float,16> a=low.template bit_cast_view<float>(),b=high.template bit_cast_view<float>();
2716#pragma unroll
2717  for(int e=0;e<E;++e){dot[e]=gfm::fma(a,gf::simd<float,16>(x[e][2*j]),dot[e]);dot[e]=gfm::fma(b,gf::simd<float,16>(x[e][2*j+1]),dot[e]);}
2718 }
2719 if constexpr(Lane<8){
2720  auto wb=gf::load_2d<uint32_t,4,16,1,true,false>(w,LR*2-1,D-1,LR*2-1,128+Lane*4,row);
2721  gf::simd<float,16> extra[E];
2722#pragma unroll
2723  for(int e=0;e<E;++e){x[e]=gf::block_load<float,8>(m.a[e].lo+256+Lane*8);extra[e]=0.f;}
2724#pragma unroll
2725  for(int j=0;j<4;++j){
2726   gf::simd<uint32_t,16> bits=wb.template select<16,1>(j*16),low=bits<<16,high=bits&0xffff0000u;
2727   gf::simd<float,16> a=low.template bit_cast_view<float>(),b=high.template bit_cast_view<float>();
2728#pragma unroll
2729   for(int e=0;e<E;++e){extra[e]=gfm::fma(a,gf::simd<float,16>(x[e][2*j]),extra[e]);extra[e]=gfm::fma(b,gf::simd<float,16>(x[e][2*j+1]),extra[e]);}
2730  }
2731#pragma unroll
2732  for(int e=0;e<E;++e)dot[e]=dot[e]+extra[e];
2733 }
2734 gf::simd<float,E*16> result;
2735#pragma unroll
2736 for(int e=0;e<E;++e)result.template select<16,1>(e*16)=dot[e];
2737 return result;
2738}
2739template<int E,int Lane,int Offset>
2740SYCL_ESIMD_FUNCTION ESIMD_INLINE gf::simd<float,E*16> gp_tree(GrMulti m,int row){
2741#pragma clang fp contract(off)
2742 if constexpr(Offset==32)return gp_leaf<E,Lane>(m,row);
2743 else return gp_tree<E,Lane,Offset*2>(m,row)+gp_tree<E,Lane^Offset,Offset*2>(m,row);
2744}
2745template<int E>class GrUpRows16;
2746template<int E>void gp_launch_compute(dpct::queue_ptr st,GrMulti m){
2747 st->parallel_for<GrUpRows16<E>>(sycl::nd_range<1>(D/16,4),[=](sycl::nd_item<1> it) SYCL_ESIMD_KERNEL {
2748#pragma clang fp contract(off)
2749  const int row=int(it.get_global_id(0))*16;
2750  gf::simd<float,E*16> partial[4];
2751  partial[0]=gp_tree<E,0,4>(m,row);partial[1]=gp_tree<E,1,4>(m,row);
2752  partial[2]=gp_tree<E,2,4>(m,row);partial[3]=gp_tree<E,3,4>(m,row);
2753#pragma unroll
2754  for(int e=0;e<E;++e){
2755   gf::simd<float,16> a=partial[e].template select<16,1>(e*16),b=partial[e^2].template select<16,1>(e*16);
2756   gf::simd<float,16> c=partial[e^1].template select<16,1>(e*16),d=partial[e^3].template select<16,1>(e*16);
2757   gf::simd<float,16> result=(a+b)+(c+d);
2758   gf::block_store<float,16>(m.xn+size_t(e)*D+row,result);
2759  }
2760 });
2761}
2762
2763
2764inline bool gr_2d_pair_enabled(){static const bool enabled=[] {const char*p=std::getenv("STRATA_PRIVATE_GR_2D_PAIR");return p&&p[0]=='1';}();return enabled&&b60_main_actor();}
2765template<int E>
2766SYCL_ESIMD_FUNCTION ESIMD_INLINE void gf_down_2d(GrMulti m,int sl,int tile) {
2767#pragma clang fp contract(off)
2768    if(tile>=21 || (tile==20 && !m.a[0].w_inject))return;
2769    gf::simd<uint32_t,16> rows(tile*16,1);
2770    auto valid=rows<uint32_t(GRS_ROWS);
2771    const auto* base=reinterpret_cast<const uint32_t*>(tile==20?m.a[0].w_inject:m.a[0].w_down);
2772    gf::simd<uint32_t,16> off=(rows-uint32_t(tile==20?LR:0))*uint32_t(D*2)+uint32_t(sl*GRS_COLS*2);
2773    gf::simd<float,128> x[E];
2774    gf::simd<float,16> acc[E][4];
2775#pragma unroll
2776    for(int e=0;e<E;++e) {
2777        x[e]=gf::block_load<float,128>(m.xn+(size_t)e*D+sl*GRS_COLS);
2778#pragma unroll
2779        for(int q=0;q<4;++q)acc[e][q]=0.f;
2780    }
2781#pragma unroll
2782    for(int cc=0;cc<4;++cc) {
2783        const int height=(tile==20?HC:LR);
2784        const int row0=tile==20?0:tile*16;
2785        const int col0=sl*(GRS_COLS/2)+cc*16;
2786        auto first=gf::load_2d<uint32_t,8,16,1,true,false>(base,D*2-1,height-1,D*2-1,col0,row0);
2787        auto last=gf::load_2d<uint32_t,8,16,1,true,false>(base,D*2-1,height-1,D*2-1,col0+8,row0);
2788#pragma unroll
2789        for(int q=0;q<4;++q) {
2790            gf::simd<float,16> dot[E];
2791#pragma unroll
2792            for(int e=0;e<E;++e)dot[e]=0.f;
2793#pragma unroll
2794            for(int j=0;j<4;++j) {
2795                gf::simd<uint32_t,16> bits;
2796                // VS8 gather returns component-major: word j across all16 rows.
2797                if(q<2)bits=first.template select<16,1>((q*4+j)*16);
2798                else bits=last.template select<16,1>(((q-2)*4+j)*16);
2799                gf::simd<uint32_t,16> low=bits<<16,high=bits&0xffff0000u;
2800                gf::simd<float,16> w0=low.template bit_cast_view<float>(),w1=high.template bit_cast_view<float>();
2801#pragma unroll
2802                for(int e=0;e<E;++e) {
2803                    dot[e]=gfm::fma(w0,gf::simd<float,16>(x[e][cc*32+q*8+2*j]),dot[e]);
2804                    dot[e]=gfm::fma(w1,gf::simd<float,16>(x[e][cc*32+q*8+2*j+1]),dot[e]);
2805                }
2806            }
2807#pragma unroll
2808            for(int e=0;e<E;++e)acc[e][q]=acc[e][q]+dot[e];
2809        }
2810    }
2811#pragma unroll
2812    for(int e=0;e<E;++e) {
2813        auto value=(acc[e][0]+acc[e][1])+(acc[e][2]+acc[e][3]);
2814        gf::scatter<float,16>(m.part2,((uint32_t(sl*kFusedGrMaxT+e)*GRS_ROWS)+rows)*4u,value,valid);
2815    }
2816}
2817
2818template<int E,int Even>
2819SYCL_ESIMD_FUNCTION ESIMD_INLINE gf::simd<float,E*32> gp_leaf_pair(GrMulti m,int row){
2820#pragma clang fp contract(off)
2821 const auto*w=reinterpret_cast<const uint32_t*>(m.a[0].w_up);
2822 auto wa=gf::load_2d<uint32_t,8,16,1,true,false>(w,LR*2-1,D-1,LR*2-1,Even*4,row);
2823 gf::simd<uint32_t,128> wb;
2824 if constexpr(Even<8)wb=gf::load_2d<uint32_t,8,16,1,true,false>(w,LR*2-1,D-1,LR*2-1,128+Even*4,row);
2825 gf::simd<float,E*32> result;
2826#pragma unroll
2827 for(int parity=0;parity<2;++parity){
2828 gf::simd<float,8> x[E];gf::simd<float,16> dot[E];
2829#pragma unroll
2830 for(int e=0;e<E;++e){x[e]=gf::block_load<float,8>(m.a[e].lo+(Even+parity)*8);dot[e]=0.f;}
2831#pragma unroll
2832 for(int j=0;j<4;++j){
2833  gf::simd<uint32_t,16> bits=wa.template select<16,1>((parity*4+j)*16),low=bits<<16,high=bits&0xffff0000u;
2834  gf::simd<float,16> a=low.template bit_cast_view<float>(),b=high.template bit_cast_view<float>();
2835#pragma unroll
2836  for(int e=0;e<E;++e){dot[e]=gfm::fma(a,gf::simd<float,16>(x[e][2*j]),dot[e]);dot[e]=gfm::fma(b,gf::simd<float,16>(x[e][2*j+1]),dot[e]);}
2837 }
2838 if constexpr(Even<8){
2839  gf::simd<float,16> extra[E];
2840#pragma unroll
2841  for(int e=0;e<E;++e){x[e]=gf::block_load<float,8>(m.a[e].lo+256+(Even+parity)*8);extra[e]=0.f;}
2842#pragma unroll
2843  for(int j=0;j<4;++j){
2844   gf::simd<uint32_t,16> bits=wb.template select<16,1>((parity*4+j)*16),low=bits<<16,high=bits&0xffff0000u;
2845   gf::simd<float,16> a=low.template bit_cast_view<float>(),b=high.template bit_cast_view<float>();
2846#pragma unroll
2847   for(int e=0;e<E;++e){extra[e]=gfm::fma(a,gf::simd<float,16>(x[e][2*j]),extra[e]);extra[e]=gfm::fma(b,gf::simd<float,16>(x[e][2*j+1]),extra[e]);}
2848  }
2849#pragma unroll
2850  for(int e=0;e<E;++e)dot[e]=dot[e]+extra[e];
2851 }
2852#pragma unroll
2853 for(int e=0;e<E;++e)result.template select<16,1>((parity*E+e)*16)=dot[e];
2854 }
2855 return result;
2856}
2857template<int E,int Even,int Offset>
2858SYCL_ESIMD_FUNCTION ESIMD_INLINE gf::simd<float,E*32> gp_tree_pair(GrMulti m,int row){
2859#pragma clang fp contract(off)
2860 if constexpr(Offset==32)return gp_leaf_pair<E,Even>(m,row);
2861 else return gp_tree_pair<E,Even,Offset*2>(m,row)+gp_tree_pair<E,Even^Offset,Offset*2>(m,row);
2862}
2863template<int E>class GrUpRows16Pair;
2864template<int E>void gp_launch_compute_pair(dpct::queue_ptr st,GrMulti m){
2865 st->parallel_for<GrUpRows16Pair<E>>(sycl::nd_range<1>(D/16,4),[=](sycl::nd_item<1> it) SYCL_ESIMD_KERNEL {
2866#pragma clang fp contract(off)
2867  const int row=int(it.get_global_id(0))*16;
2868  gf::simd<float,E*16> partial[4];
2869  auto p01=gp_tree_pair<E,0,4>(m,row),p23=gp_tree_pair<E,2,4>(m,row);
2870  partial[0]=p01.template select<E*16,1>(0);partial[1]=p01.template select<E*16,1>(E*16);
2871  partial[2]=p23.template select<E*16,1>(0);partial[3]=p23.template select<E*16,1>(E*16);
2872#pragma unroll
2873  for(int e=0;e<E;++e){
2874   gf::simd<float,16> a=partial[e].template select<16,1>(e*16),b=partial[e^2].template select<16,1>(e*16);
2875   gf::simd<float,16> c=partial[e^1].template select<16,1>(e*16),d=partial[e^3].template select<16,1>(e*16);
2876   gf::simd<float,16> result=(a+b)+(c+d);
2877   gf::block_store<float,16>(m.xn+size_t(e)*D+row,result);
2878  }
2879 });
2880}
2881
2882template<int E>class GfDown2D;
2883template<int E>void gf_launch_down_2d(dpct::queue_ptr st,GrMulti m){
2884 st->parallel_for<GfDown2D<E>>(sycl::nd_range<1>(GRS_SLICES*24,8),[=](sycl::nd_item<1>it) SYCL_ESIMD_KERNEL {
2885  const int id=int(it.get_global_id(0));gf_down_2d<E>(m,id/24,id%24);
2886 });
2887}
2888
2889
2890struct GcDown {const uint16_t *w_down,*w_inject;float *xn,*part2;};
2891// Upstream added two optional HC-Q8 scale pointers to each FusedGrArgs.
2892// Merge with the head: GrMulti gained two bools (cached_norm, cached_lo, the #4185 port) after the PR measured 1384; they sit at the end, so every earlier
2893// field keeps its offset and the PR's kernels (which read fields by name) are unaffected; the size is 1384 plus at most the padding of the two bools.
2894static_assert(sizeof(FusedGrArgs)==168 && sizeof(GrMulti)==1392 && sizeof(GcDown)==32);
2895inline bool gc_enabled(){static const bool on=[] {const char*p=std::getenv("STRATA_PRIVATE_B60_NEXT_POOL");return p&&p[0]=='1';}();return on&&b60_main_actor();}
2896template<int E>
2897SYCL_ESIMD_FUNCTION ESIMD_INLINE void gc_down(GcDown m,int sl,int tile) {
2898#pragma clang fp contract(off)
2899    if(tile>=21 || (tile==20 && !m.w_inject))return;
2900    gf::simd<uint32_t,16> rows(tile*16,1);
2901    auto valid=rows<uint32_t(GRS_ROWS);
2902    const auto* base=reinterpret_cast<const uint32_t*>(tile==20?m.w_inject:m.w_down);
2903    gf::simd<uint32_t,16> off=(rows-uint32_t(tile==20?LR:0))*uint32_t(D*2)+uint32_t(sl*GRS_COLS*2);
2904    gf::simd<float,128> x[E];
2905    gf::simd<float,16> acc[E][4];
2906#pragma unroll
2907    for(int e=0;e<E;++e) {
2908        x[e]=gf::block_load<float,128>(m.xn+(size_t)e*D+sl*GRS_COLS);
2909#pragma unroll
2910        for(int q=0;q<4;++q)acc[e][q]=0.f;
2911    }
2912#pragma unroll
2913    for(int cc=0;cc<4;++cc) {
2914        const int height=(tile==20?HC:LR);
2915        const int row0=tile==20?0:tile*16;
2916        const int col0=sl*(GRS_COLS/2)+cc*16;
2917        gf::simd<uint32_t,128> first,last;
2918        if(tile==20){
2919          first=gf::load_2d<uint32_t,8,16,1,true,false>(base,D*2-1,height-1,D*2-1,col0,row0);
2920          last=gf::load_2d<uint32_t,8,16,1,true,false>(base,D*2-1,height-1,D*2-1,col0+8,row0);
2921        }else{
2922          const auto* packed=base+size_t(tile)*16*(D/2);
2923          first=gf::block_load<uint32_t,128>(packed+size_t(col0)*16);
2924          last=gf::block_load<uint32_t,128>(packed+size_t(col0+8)*16);
2925        }
2926#pragma unroll
2927        for(int q=0;q<4;++q) {
2928            gf::simd<float,16> dot[E];
2929#pragma unroll
2930            for(int e=0;e<E;++e)dot[e]=0.f;
2931#pragma unroll
2932            for(int j=0;j<4;++j) {
2933                gf::simd<uint32_t,16> bits;
2934                // VS8 gather returns component-major: word j across all16 rows.
2935                if(q<2)bits=first.template select<16,1>((q*4+j)*16);
2936                else bits=last.template select<16,1>(((q-2)*4+j)*16);
2937                gf::simd<uint32_t,16> low=bits<<16,high=bits&0xffff0000u;
2938                gf::simd<float,16> w0=low.template bit_cast_view<float>(),w1=high.template bit_cast_view<float>();
2939#pragma unroll
2940                for(int e=0;e<E;++e) {
2941                    dot[e]=gfm::fma(w0,gf::simd<float,16>(x[e][cc*32+q*8+2*j]),dot[e]);
2942                    dot[e]=gfm::fma(w1,gf::simd<float,16>(x[e][cc*32+q*8+2*j+1]),dot[e]);
2943                }
2944            }
2945#pragma unroll
2946            for(int e=0;e<E;++e)acc[e][q]=acc[e][q]+dot[e];
2947        }
2948    }
2949#pragma unroll
2950    for(int e=0;e<E;++e) {
2951        auto value=(acc[e][0]+acc[e][1])+(acc[e][2]+acc[e][3]);
2952        gf::scatter<float,16>(m.part2,((uint32_t(sl*kFusedGrMaxT+e)*GRS_ROWS)+rows)*4u,value,valid);
2953    }
2954}
2955
2956template<int E>class GcDownKernel;
2957template<int E>void gc_launch_down(dpct::queue_ptr st,GrMulti full){
2958 GcDown m{full.a[0].w_down,full.a[0].w_inject,full.xn,full.part2};
2959 const unsigned device=dpct::get_device_id(st->get_device());
2960 static std::atomic<unsigned> reported{0};
2961 if(device<8 && !(reported.fetch_or(1u<<device,std::memory_order_relaxed)&(1u<<device)))
2962  std::fprintf(stderr,"[B60_GR_COMPACT_DOWN] capture device=%u T=%d\n",device,E);
2963
2964 st->parallel_for<GcDownKernel<E>>(sycl::nd_range<1>(GRS_SLICES*24,8),[=](sycl::nd_item<1>it) SYCL_ESIMD_KERNEL {
2965  const int id=int(it.get_global_id(0));gc_down<E>(m,id/24,id%24);
2966 });
2967}
2968
2969inline bool gr_soa_enabled(){static const bool enabled=[] {const char*p=std::getenv("STRATA_PRIVATE_GR_SOA_CACHE");return p&&p[0]=='1';}();return enabled&&b60_main_actor();}
2970template<int E>
2971SYCL_ESIMD_FUNCTION ESIMD_INLINE void gf_down_soa(GrMulti m,int sl,int tile) {
2972#pragma clang fp contract(off)
2973    if(tile>=21 || (tile==20 && !m.a[0].w_inject))return;
2974    gf::simd<uint32_t,16> rows(tile*16,1);
2975    auto valid=rows<uint32_t(GRS_ROWS);
2976    const auto* base=reinterpret_cast<const uint32_t*>(tile==20?m.a[0].w_inject:m.a[0].w_down);
2977    gf::simd<uint32_t,16> off=(rows-uint32_t(tile==20?LR:0))*uint32_t(D*2)+uint32_t(sl*GRS_COLS*2);
2978    gf::simd<float,128> x[E];
2979    gf::simd<float,16> acc[E][4];
2980#pragma unroll
2981    for(int e=0;e<E;++e) {
2982        x[e]=gf::block_load<float,128>(m.xn+(size_t)e*D+sl*GRS_COLS);
2983#pragma unroll
2984        for(int q=0;q<4;++q)acc[e][q]=0.f;
2985    }
2986#pragma unroll
2987    for(int cc=0;cc<4;++cc) {
2988        const int height=(tile==20?HC:LR);
2989        const int row0=tile==20?0:tile*16;
2990        const int col0=sl*(GRS_COLS/2)+cc*16;
2991        gf::simd<uint32_t,128> first,last;
2992        if(tile==20){
2993          first=gf::load_2d<uint32_t,8,16,1,true,false>(base,D*2-1,height-1,D*2-1,col0,row0);
2994          last=gf::load_2d<uint32_t,8,16,1,true,false>(base,D*2-1,height-1,D*2-1,col0+8,row0);
2995        }else{
2996          const auto* packed=base+size_t(tile)*16*(D/2);
2997          first=gf::block_load<uint32_t,128>(packed+size_t(col0)*16);
2998          last=gf::block_load<uint32_t,128>(packed+size_t(col0+8)*16);
2999        }
3000#pragma unroll
3001        for(int q=0;q<4;++q) {
3002            gf::simd<float,16> dot[E];
3003#pragma unroll
3004            for(int e=0;e<E;++e)dot[e]=0.f;
3005#pragma unroll
3006            for(int j=0;j<4;++j) {
3007                gf::simd<uint32_t,16> bits;
3008                // VS8 gather returns component-major: word j across all16 rows.
3009                if(q<2)bits=first.template select<16,1>((q*4+j)*16);
3010                else bits=last.template select<16,1>(((q-2)*4+j)*16);
3011                gf::simd<uint32_t,16> low=bits<<16,high=bits&0xffff0000u;
3012                gf::simd<float,16> w0=low.template bit_cast_view<float>(),w1=high.template bit_cast_view<float>();
3013#pragma unroll
3014                for(int e=0;e<E;++e) {
3015                    dot[e]=gfm::fma(w0,gf::simd<float,16>(x[e][cc*32+q*8+2*j]),dot[e]);
3016                    dot[e]=gfm::fma(w1,gf::simd<float,16>(x[e][cc*32+q*8+2*j+1]),dot[e]);
3017                }
3018            }
3019#pragma unroll
3020            for(int e=0;e<E;++e)acc[e][q]=acc[e][q]+dot[e];
3021        }
3022    }
3023#pragma unroll
3024    for(int e=0;e<E;++e) {
3025        auto value=(acc[e][0]+acc[e][1])+(acc[e][2]+acc[e][3]);
3026        gf::scatter<float,16>(m.part2,((uint32_t(sl*kFusedGrMaxT+e)*GRS_ROWS)+rows)*4u,value,valid);
3027    }
3028}
3029
3030template<int E,int Even>
3031SYCL_ESIMD_FUNCTION ESIMD_INLINE gf::simd<float,E*32> gp_leaf_soa(GrMulti m,int row){
3032#pragma clang fp contract(off)
3033 const auto*w=reinterpret_cast<const uint32_t*>(m.a[0].w_up);
3034 const auto* packed=w+size_t(row)*(LR/2);
3035 auto wa=gf::block_load<uint32_t,128>(packed+size_t(Even*4)*16);
3036 gf::simd<uint32_t,128> wb;
3037 if constexpr(Even<8)wb=gf::block_load<uint32_t,128>(packed+size_t(128+Even*4)*16);
3038 gf::simd<float,E*32> result;
3039#pragma unroll
3040 for(int parity=0;parity<2;++parity){
3041 gf::simd<float,8> x[E];gf::simd<float,16> dot[E];
3042#pragma unroll
3043 for(int e=0;e<E;++e){x[e]=gf::block_load<float,8>(m.a[e].lo+(Even+parity)*8);dot[e]=0.f;}
3044#pragma unroll
3045 for(int j=0;j<4;++j){
3046  gf::simd<uint32_t,16> bits=wa.template select<16,1>((parity*4+j)*16),low=bits<<16,high=bits&0xffff0000u;
3047  gf::simd<float,16> a=low.template bit_cast_view<float>(),b=high.template bit_cast_view<float>();
3048#pragma unroll
3049  for(int e=0;e<E;++e){dot[e]=gfm::fma(a,gf::simd<float,16>(x[e][2*j]),dot[e]);dot[e]=gfm::fma(b,gf::simd<float,16>(x[e][2*j+1]),dot[e]);}
3050 }
3051 if constexpr(Even<8){
3052  gf::simd<float,16> extra[E];
3053#pragma unroll
3054  for(int e=0;e<E;++e){x[e]=gf::block_load<float,8>(m.a[e].lo+256+(Even+parity)*8);extra[e]=0.f;}
3055#pragma unroll
3056  for(int j=0;j<4;++j){
3057   gf::simd<uint32_t,16> bits=wb.template select<16,1>((parity*4+j)*16),low=bits<<16,high=bits&0xffff0000u;
3058   gf::simd<float,16> a=low.template bit_cast_view<float>(),b=high.template bit_cast_view<float>();
3059#pragma unroll
3060   for(int e=0;e<E;++e){extra[e]=gfm::fma(a,gf::simd<float,16>(x[e][2*j]),extra[e]);extra[e]=gfm::fma(b,gf::simd<float,16>(x[e][2*j+1]),extra[e]);}
3061  }
3062#pragma unroll
3063  for(int e=0;e<E;++e)dot[e]=dot[e]+extra[e];
3064 }
3065#pragma unroll
3066 for(int e=0;e<E;++e)result.template select<16,1>((parity*E+e)*16)=dot[e];
3067 }
3068 return result;
3069}
3070template<int E,int Even,int Offset>
3071SYCL_ESIMD_FUNCTION ESIMD_INLINE gf::simd<float,E*32> gp_tree_soa(GrMulti m,int row){
3072#pragma clang fp contract(off)
3073 if constexpr(Offset==32)return gp_leaf_soa<E,Even>(m,row);
3074 else return gp_tree_soa<E,Even,Offset*2>(m,row)+gp_tree_soa<E,Even^Offset,Offset*2>(m,row);
3075}
3076template<int E>class GrUpRows16Soa;
3077template<int E>void gp_launch_compute_soa(dpct::queue_ptr st,GrMulti m){
3078 st->parallel_for<GrUpRows16Soa<E>>(sycl::nd_range<1>(D/16,4),[=](sycl::nd_item<1> it) SYCL_ESIMD_KERNEL {
3079#pragma clang fp contract(off)
3080  const int row=int(it.get_global_id(0))*16;
3081  gf::simd<float,E*16> partial[4];
3082  auto p01=gp_tree_soa<E,0,4>(m,row),p23=gp_tree_soa<E,2,4>(m,row);
3083  partial[0]=p01.template select<E*16,1>(0);partial[1]=p01.template select<E*16,1>(E*16);
3084  partial[2]=p23.template select<E*16,1>(0);partial[3]=p23.template select<E*16,1>(E*16);
3085#pragma unroll
3086  for(int e=0;e<E;++e){
3087   gf::simd<float,16> a=partial[e].template select<16,1>(e*16),b=partial[e^2].template select<16,1>(e*16);
3088   gf::simd<float,16> c=partial[e^1].template select<16,1>(e*16),d=partial[e^3].template select<16,1>(e*16);
3089   gf::simd<float,16> result=(a+b)+(c+d);
3090   gf::block_store<float,16>(m.xn+size_t(e)*D+row,result);
3091  }
3092 });
3093}
3094
3095template<int E>class GfDownSoa;
3096template<int E>void gf_launch_down_soa(dpct::queue_ptr st,GrMulti m){
3097 if constexpr(E==1 || E==2 || E==4){if(gc_enabled()){gc_launch_down<E>(st,m);return;}}
3098 st->parallel_for<GfDownSoa<E>>(sycl::nd_range<1>(GRS_SLICES*24,8),[=](sycl::nd_item<1>it) SYCL_ESIMD_KERNEL {
3099  const int id=int(it.get_global_id(0));gf_down_soa<E>(m,id/24,id%24);
3100 });
3101}
3102
3103template<int E> void gf_launch_up(dpct::queue_ptr st,GrMulti m) {
3104    if(gr_up_rows16_enabled() && m.T==4){if(gr_soa_enabled())gp_launch_compute_soa<E>(st,m);else if(gr_2d_pair_enabled())gp_launch_compute_pair<E>(st,m);else gp_launch_compute<E>(st,m);}
3105    else
3106    st->parallel_for<GfUp<E>>(sycl::nd_range<1>(N,8),[=](sycl::nd_item<1> it) SYCL_ESIMD_KERNEL {gf_up<E>(m,int(it.get_global_id(0)));});
3107    st->parallel_for<GfPostop<E>>(sycl::nd_range<3>(sycl::range<3>(1,1,((m.T*N+127)/128)*128),sycl::range<3>(1,1,128)),
3108        [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] {gf_postop(m);});
3109}
3110void gf_dispatch_down(dpct::queue_ptr st,GrMulti m) {
3111    if(gr_soa_enabled()){
3112        switch(m.T){case 1:gf_launch_down_soa<1>(st,m);return;case 2:gf_launch_down_soa<2>(st,m);return;case 4:gf_launch_down_soa<4>(st,m);return;}
3113    }
3114    if(gr_2d_pair_enabled() && m.T==4){switch(m.T){case 1:gf_launch_down_2d<1>(st,m);break;case 2:gf_launch_down_2d<2>(st,m);break;case 4:gf_launch_down_2d<4>(st,m);break;}return;}
3115    switch(m.T) {case 1:gf_launch_down<1>(st,m);break;case 2:gf_launch_down<2>(st,m);break;case 3:gf_launch_down<3>(st,m);break;case 4:gf_launch_down<4>(st,m);break;}
3116}
3117void gf_dispatch_up(dpct::queue_ptr st,GrMulti m) {
3118    switch(m.T) {case 1:gf_launch_up<1>(st,m);break;case 2:gf_launch_up<2>(st,m);break;case 3:gf_launch_up<3>(st,m);break;case 4:gf_launch_up<4>(st,m);break;}
3119}
3120
3121
3122}  // namespace
3123
3124// one partials buffer per queue (the verifier's and the drafter's launches never share a queue; within a queue the
3125// launches are ordered, and a graph capture records the pointer)
3126
3127
3128static float* down_partials(sycl::queue* q) {
3129    static std::mutex mu;
3130    static std::unordered_map<sycl::queue*, float*> bufs;
3131    std::lock_guard<std::mutex> lk(mu);
3132    auto it = bufs.find(q);
3133    if (it != bufs.end()) return it->second;
3134    float* p = sycl::malloc_device<float>((size_t) DOWN_SPLIT * kFusedGrMaxT * LR, *q);
3135    bufs[q] = p;
3136    return p;
3137}
3138
3139bool fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream, unsigned long long* stamp_buf,
3140                         int stamp_i0) {
3141    strata::workload_trace::Scope trace("decode.gr_read_api", stream, n_tok, D, LR, HC, N, 30);
3142    if (n_tok < 1 || n_tok > kFusedGrMaxT || xn_scratch == nullptr) {
3143        std::fprintf(stderr, "fused_gr_read_multi: invalid arguments\n");
3144        std::exit(1);
3145    }
3146    GrMulti m;
3147    for (int t = 0; t < n_tok; ++t) {
3148        m.a[t] = a[t];
3149        const FusedGrArgs& x = a[t];
3150        if (!x.R || !x.w_norm || !x.w_down || !x.w_up || !x.lo || !x.rs || !x.mixed || (x.w_inject && !x.inject_out) ||
3151            (x.apply && (!x.bo_prev || !x.inj_prev || !x.R_out)) || x.w_down != a[0].w_down || x.w_up != a[0].w_up ||
3152            x.w_inject != a[0].w_inject || x.w_norm != a[0].w_norm) {
3153            std::fprintf(stderr, "fused_gr_read_multi: invalid arguments for token %d\n", t);
3154            std::exit(1);
3155        }
3156    }
3157    m.xn = xn_scratch;
3158    m.T = n_tok;
3159    dpct::queue_ptr st = strata::q_of(stream);
3160    if(gr_soa_enabled() && (n_tok==1||n_tok==2||n_tok==4)){
3161        if(!gf_enabled(st,m)||!gf_phase("down")||gf_phase("up")||!gr_combo_silu_enabled()||!gr_up_rows16_enabled())
3162            throw std::logic_error("B60 GR cache requires the measured GR control combination");
3163        const auto* down=static_cast<const uint16_t*>(b60_cached_weight(a[0].w_down,30));
3164        const auto* up=static_cast<const uint16_t*>(b60_cached_weight(a[0].w_up,30));
3165        if(!down||!up)throw std::logic_error("B60 missing GR decode cache");
3166        for(int t=0;t<n_tok;++t){m.a[t].w_down=down;if(n_tok==4)m.a[t].w_up=up;}
3167    }
3168    // STRATA_GR_V3=1: the two-kernel read above (another summation order - opt-in)
3169    static const bool v3 = [] { const char* v = std::getenv("STRATA_GR_V3"); return v != nullptr && std::atoi(v) != 0; }();
3170    static int split3[64] = {};   // per device: 0 = not decided yet, 1 / 2 = column halves S, -1 = does not fit
3171    int dev3 = 0;
3172    if (v3) {
3173        dev3 = dpct::get_current_device_id();
3174        if (dev3 >= 0 && dev3 < 64 && split3[dev3] == 0) {
3175            int optin = 0;
3176            // SYCL port: the device's local memory is the limit (no per-kernel opt-in to raise)
3177            optin = (int) dpct::get_device(dev3).get_local_mem_size();
3178            const int limit = optin > 0 ? optin : 48 * 1024;
3179            const int need1 = (int) (kFusedGrMaxT * N * sizeof(float)), need2 = need1 / 2;
3180            int split = -1;
3181            if (need1 <= limit &&
3182                /*
3183                DPCT1027: The call to cudaFuncSetAttribute was replaced with
3184                0 because SYCL currently does not support corresponding setting.
3185                */
3186                0 == 0)
3187                split = 1;
3188            else if (need2 <= limit)
3189                // #375 (kenh0u): the S = 2 split (a 64 KB opt-in card: Turing) disagrees with itself in gr_parity
3190                // (graph replay vs direct call) - such a card keeps the default read until that split is fixed
3191                std::fprintf(stderr, "strata: STRATA_GR_V3=1 needs the two-half split on this card, which fails its "
3192                                     "checks (#375): the default read is used\n");
3193            /*
3194            DPCT1026: The call to cudaGetLastError was removed because this
3195            functionality is redundant in SYCL.
3196            */
3197; // drop any error the attempts left behind
3198            split3[dev3] = split;
3199        }
3200    }
3201    const int split = v3 && dev3 >= 0 && dev3 < 64 ? split3[dev3] : -1;
3202    if (split > 0) {   // 2 kernels; scratch = partials + sums of squares
3203        float* part = xn_scratch;
3204        float* ssg = xn_scratch + (size_t) n_tok * HC * 2 * PR;   // room for S = 2
3205        /*
3206        DPCT1083: The size of local memory in the migrated code may be
3207        different from the original code. Check that the allocated memory size
3208        in the migrated code is correct.
3209        */
3210        const size_t sm = (size_t)n_tok * (N / split) * sizeof(float);
3211        if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0, stream);
3212        if (split == 2) {
3213            auto exp_props = sycl::ext::oneapi::experimental::properties{
3214                sycl::ext::oneapi::experimental::use_root_sync};
3215
3216            strata::kprof::kp(st, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
3217                sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
3218                    sycl::range(sm), cgh);
3219
3220                cgh.parallel_for<dpct_kernel_name<
3221                    class gr_down_v3_kernel_c14ff7, dpct_kernel_scalar<2>>>(
3222                    sycl::nd_range<3>(sycl::range(1, HC * 2, LR / WARPS + 1) *
3223                                          sycl::range(1, 1, THREADS),
3224                                      sycl::range(1, 1, THREADS)),
3225                    exp_props,
3226                    [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(
3227                        32)]] {
3228                        gr_down_v3_kernel<2>(
3229                            m, part, ssg,
3230                            dpct_local_acc_ct1
3231                                .get_multi_ptr<sycl::access::decorated::no>()
3232                                .get());
3233                    });
3234            });
3235        } else {
3236            auto exp_props = sycl::ext::oneapi::experimental::properties{
3237                sycl::ext::oneapi::experimental::use_root_sync};
3238
3239            strata::kprof::kp(st, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
3240                sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
3241                    sycl::range(sm), cgh);
3242
3243                cgh.parallel_for<dpct_kernel_name<
3244                    class gr_down_v3_kernel_88bc89, dpct_kernel_scalar<1>>>(
3245                    sycl::nd_range<3>(sycl::range(1, HC, LR / WARPS + 1) *
3246                                          sycl::range(1, 1, THREADS),
3247                                      sycl::range(1, 1, THREADS)),
3248                    exp_props,
3249                    [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(
3250                        32)]] {
3251                        gr_down_v3_kernel<1>(
3252                            m, part, ssg,
3253                            dpct_local_acc_ct1
3254                                .get_multi_ptr<sycl::access::decorated::no>()
3255                                .get());
3256                    });
3257            });
3258        }
3259        if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0 + 1, stream);
3260        if (split == 2) {
3261            auto exp_props = sycl::ext::oneapi::experimental::properties{
3262                sycl::ext::oneapi::experimental::use_root_sync};
3263
3264            strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class gr_up_v3_kernel_6e945c,
3265                                              dpct_kernel_scalar<2>>>(
3266                sycl::nd_range<3>(sycl::range(1, 1, UPM_BLOCKS) *
3267                                      sycl::range(1, 1, THREADS),
3268                                  sycl::range(1, 1, THREADS)),
3269                exp_props,
3270                [=](sycl::nd_item<3> item_ct1)
3271                    [[sycl::reqd_sub_group_size(32)]] {
3272                        gr_up_v3_kernel<2>(m, part, ssg);
3273                    });
3274        } else {
3275            auto exp_props = sycl::ext::oneapi::experimental::properties{
3276                sycl::ext::oneapi::experimental::use_root_sync};
3277
3278            strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class gr_up_v3_kernel_716779,
3279                                              dpct_kernel_scalar<1>>>(
3280                sycl::nd_range<3>(sycl::range(1, 1, UPM_BLOCKS) *
3281                                      sycl::range(1, 1, THREADS),
3282                                  sycl::range(1, 1, THREADS)),
3283                exp_props,
3284                [=](sycl::nd_item<3> item_ct1)
3285                    [[sycl::reqd_sub_group_size(32)]] {
3286                        gr_up_v3_kernel<1>(m, part, ssg);
3287                    });
3288        }
3289        /*
3290        DPCT1010: SYCL uses exceptions to report errors and does not use the
3291        error codes. The cudaGetLastError function call was replaced with 0. You
3292        need to rewrite this code.
3293        */
3294        const dpct::err0 e3 = 0;
3295
3296        return false;   // SYCL port: never writes the q8_1 images (STRATA_QFUSE is not supported here)
3297    }
3298    const bool cached_norm=!gf_enabled(st,m)&&g_gr_cached_norm_mode>0&&g_gr_norm_direct_bounds&&gr_norm_split()&&
3299        gr_down_sliced()&&gr_cached_norm_safe(a,n_tok,xn_scratch);
3300    m.part = down_partials(st);
3301    static const bool reuse_norm = strata::bm_default_on("STRATA_GR_CACHED_NORM", st->get_device(), false);
3302    static const bool reuse_lo = strata::bm_default_on("STRATA_GR_LO_REUSE", st->get_device());
3303    if ((reuse_norm || reuse_lo) && !cached_norm && !gf_enabled(st, m) && gr_norm_split() && gr_down_sliced() &&
3304        !gr_more_groups(st) && !gr_large_grf(st) && !gr_up_ilp() && gr_up_cols() == UPM_COLS &&
3305        strata::intel_gpu_gen(st->get_device()) == strata::IntelGpuGen::Battlemage &&
3306        gr_reuse_safe(a, n_tok, xn_scratch)) {
3307        m.cached_norm = reuse_norm;
3308        m.cached_lo = reuse_lo;
3309        static const bool note = [] {
3310            std::fprintf(stderr, "strata: GR reuse enabled: normalized activation %d, low-rank SiLU %d\n",
3311                         (int) reuse_norm, (int) reuse_lo);
3312            return true;
3313        }();
3314        (void) note;
3315    }
3316    {
3317        auto exp_props = sycl::ext::oneapi::experimental::properties{
3318            sycl::ext::oneapi::experimental::use_root_sync};
3319
3320        if(cached_norm)
3321            strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class gr_norm_cached_write>>(
3322                sycl::nd_range<3>(sycl::range(1,1,n_tok*HC)*sycl::range(1,1,THREADS),sycl::range(1,1,THREADS)),
3323                [=](sycl::nd_item<3>)[[sycl::reqd_sub_group_size(32)]]{gr_norm_cached_write_kernel(m);});
3324        else if (g_gr_norm_direct_bounds && gr_norm_split())
3325            strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class gr_norm_bounds_k>>(
3326                sycl::nd_range<3>(sycl::range(1, 1, n_tok * HC) * sycl::range(1, 1, THREADS), sycl::range(1, 1, THREADS)),
3327                [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] { gr_norm_bounds_port_kernel(m); });
3328        else if (gr_norm_split())
3329            strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class gr_norm_split_k>>(
3330                sycl::nd_range<3>(sycl::range(1, 1, n_tok * HC) * sycl::range(1, 1, THREADS), sycl::range(1, 1, THREADS)),
3331                [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] { gr_norm_split_port_kernel(m); });
3332        else
3333        strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class gr_norm_multi_kernel_2f4d92>>(
3334            sycl::nd_range<3>(sycl::range(1, 1, n_tok) *
3335                                  sycl::range(1, 1, THREADS),
3336                              sycl::range(1, 1, THREADS)),
3337            exp_props,
3338            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
3339                gr_norm_multi_kernel(m);
3340            });
3341    }
3342    if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0, stream);
3343    // the local-memory capacity is a per-DEVICE property: once per device (a layer split runs this on two cards).
3344    // SYCL port: upstream picks TILEV 1280 on sm_75 and takes the per-block limit below sm_70 (CUDA compute
3345    // capabilities, cudaFuncSetAttribute opt-ins); here the tile is the port's TILE and the device's local memory is
3346    // the only limit. The tiled kernel is the fallback (STRATA_GR_DOWN_SLICED=0 STRATA_GR_DOWN_DIRECT=0); the
3347    // default is the sliced kernel below.
3348    static bool attr[64] = {};
3349    static int chunk[64] = {};   // tokens the tiled down kernel may carry in one launch on this card
3350    int dev = 0;
3351    dev = dpct::get_current_device_id();
3352    if (dev >= 0 && dev < 64 && !attr[dev]) {
3353        const int optin = (int) dpct::get_device(dev).get_local_mem_size();
3354        const int capacity = (optin > 0 ? optin : 48 * 1024) / (int) (TILE * sizeof(float));
3355        chunk[dev] = capacity < 1 ? 1 : (capacity > kFusedGrMaxT ? kFusedGrMaxT : capacity);
3356        attr[dev] = true;
3357    }
3358    const int chunk_tok = (dev >= 0 && dev < 64 && chunk[dev]) ? chunk[dev] : kFusedGrMaxT;
3359    const bool lo_once = (g_gr_lo_once||(cached_norm&&g_gr_cached_norm_mode>=2))&&gr_down_sliced();
3360    if (gr_down_sliced() && gr_more_groups(st) && !lo_once) {
3361        m.part2 = slice_partials(st);
3362        m.nsplit = 1;
3363        if (gr_large_grf(st)) launch_gr_down_more<true>(st, m);
3364        else launch_gr_down_more<false>(st, m);
3365    } else if (gr_down_sliced()) {
3366        m.part2 = slice_partials(st);
3367        m.nsplit = 1;
3368        const bool big = gr_large_grf(st);
3369        if(gf_enabled(st,m) && gf_phase("down")) gf_dispatch_down(st,m);
3370        else strata::kprof::kp(st, __FILE__, __func__, __LINE__)->submit([&](sycl::handler& cgh) {
3371            sycl::local_accessor<float, 1> tl(sycl::range<1>((size_t) kFusedGrMaxT * GRS_COLS), cgh);
3372            const sycl::nd_range<3> nr(sycl::range(1, 1, GRS_SLICES) * sycl::range(1, 1, THREADS), sycl::range(1, 1, THREADS));
3373            if (big)
3374                cgh.parallel_for<dpct_kernel_name<class gr_down_sliced_k_grf256>>(
3375                    nr, sycl::ext::oneapi::experimental::properties{sycl::ext::intel::experimental::grf_size<256>},
3376                    [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] {
3377                        gr_down_sliced_kernel(m, tl.get_multi_ptr<sycl::access::decorated::no>().get());
3378                    });
3379            else
3380                cgh.parallel_for<dpct_kernel_name<class gr_down_sliced_k>>(
3381                    nr, [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] {
3382                        gr_down_sliced_kernel(m, tl.get_multi_ptr<sycl::access::decorated::no>().get());
3383                    });
3384        });
3385        const unsigned nred = unsigned((n_tok * GRS_ROWS + 127) / 128);
3386        const sycl::nd_range<3> nr(sycl::range(1, 1, nred) * sycl::range(1, 1, 128),
3387                                    sycl::range(1, 1, 128));
3388        if(gf_enabled(st,m) && (gf_phase("up") || gr_combo_silu_enabled())) {
3389            st->parallel_for<GfReduce>(
3390                sycl::nd_range<3>(sycl::range(1,1,nred*128),sycl::range(1,1,128)),
3391                [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] {gf_reduce_silu(m);});
3392        } else if (lo_once) {   // #3153: the reduce writes the low-rank SiLU rows (PrepareLo, the same kernel as the head's REUSE_LO)
3393            strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class gr_down_reduce_lo_once_k>>(nr,
3394                [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] { gr_down_reduce_kernel<false, true>(m); });
3395        } else if (m.cached_lo) {   // #4185 port (Battlemage default / STRATA_GR_LO_REUSE)
3396            static const bool reduce_ilp = strata::bm_default_on("STRATA_GR_REDUCE_ILP", st->get_device(), false);
3397            if (reduce_ilp) {
3398                strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class gr_down_reduce_lo_ilp>>(nr,
3399                    [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] {
3400                        gr_down_reduce_kernel<true, true>(m);
3401                    });
3402            } else {
3403                strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class gr_down_reduce_lo>>(nr,
3404                    [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] {
3405                        gr_down_reduce_kernel<false, true>(m);
3406                    });
3407            }
3408        } else
3409            strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class gr_down_reduce_k>>(nr,
3410                [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] { gr_down_reduce_kernel(m); });
3411    } else if (gr_down_direct()) {
3412        strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class gr_down_multi_direct>>(
3413            sycl::nd_range<3>(sycl::range(1, 1, DOWN_BLOCKS * DOWN_SPLIT + 1) * sycl::range(1, 1, THREADS),
3414                              sycl::range(1, 1, THREADS)),
3415            [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] { gr_down_multi_direct_kernel(m); });
3416    } else if (chunk_tok >= n_tok) {
3417        auto exp_props = sycl::ext::oneapi::experimental::properties{
3418            sycl::ext::oneapi::experimental::use_root_sync};
3419        strata::kprof::kp(st, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
3420            sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
3421                sycl::range((size_t)n_tok * TILE * sizeof(float)), cgh);
3422            cgh.parallel_for<
3423                dpct_kernel_name<class gr_down_multi_kernel_7f5820, dpct_kernel_scalar<TILE>>>(
3424                sycl::nd_range<3>(sycl::range(1, 1, DOWN_BLOCKS * DOWN_SPLIT + 1) *
3425                                      sycl::range(1, 1, THREADS),
3426                                  sycl::range(1, 1, THREADS)),
3427                exp_props,
3428                [=](sycl::nd_item<3> item_ct1)
3429                    [[sycl::reqd_sub_group_size(32)]] {
3430                        gr_down_multi_kernel<TILE>(
3431                            m, dpct_local_acc_ct1
3432                                   .get_multi_ptr<sycl::access::decorated::no>()
3433                                   .get());
3434                    });
3435        });
3436    } else {
3437        for (int c0 = 0; c0 < n_tok; c0 += chunk_tok) {
3438            const int ct = n_tok - c0 < chunk_tok ? n_tok - c0 : chunk_tok;
3439            GrMulti c{};
3440            c.xn = xn_scratch + (size_t) c0 * D;
3441            c.T = ct;
3442            for (int k = 0; k < ct; ++k) c.a[k] = a[c0 + k];
3443            c.part = m.part;
3444            auto exp_props = sycl::ext::oneapi::experimental::properties{
3445                sycl::ext::oneapi::experimental::use_root_sync};
3446            strata::kprof::kp(st, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
3447                sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
3448                    sycl::range((size_t)ct * TILE * sizeof(float)), cgh);
3449                cgh.parallel_for<
3450                    dpct_kernel_name<class gr_down_multi_kernel_88cb86, dpct_kernel_scalar<TILE>>>(
3451                    sycl::nd_range<3>(sycl::range(1, 1, DOWN_BLOCKS * DOWN_SPLIT + 1) *
3452                                          sycl::range(1, 1, THREADS),
3453                                      sycl::range(1, 1, THREADS)),
3454                    exp_props,
3455                    [=](sycl::nd_item<3> item_ct1)
3456                        [[sycl::reqd_sub_group_size(32)]] {
3457                            gr_down_multi_kernel<TILE>(
3458                                c, dpct_local_acc_ct1
3459                                       .get_multi_ptr<sycl::access::decorated::no>()
3460                                       .get());
3461                        });
3462            });
3463        }
3464    }
3465    if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0 + 1, stream);
3466    const bool private_q8=b60_gr_q8_up32_enabled() && n_tok==1 && a[0].q8_mixed &&
3467        !a[0].q8_down && !a[0].q8_up && gf_enabled(st,m) && gf_phase("down") && !gf_phase("up") && gr_combo_silu_enabled();
3468    if(private_q8)launch_b60_gr_q8_up32_t1(st,m);
3469    else if(gf_enabled(st,m) && gf_phase("up")) gf_dispatch_up(st,m);
3470    else if(gf_enabled(st,m) && gr_combo_silu_enabled()) launch_gr_up_from_lo(st,m);
3471    else if(cached_norm){
3472        auto exp_props=sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};
3473        if(g_gr_cached_norm_mode==3){
3474            GrUpCompactReady u{};u.w_up=m.a[0].w_up;u.xn=m.xn;u.T=m.T;
3475            for(int k=0;k<m.T;++k){u.lo[k]=m.a[k].lo;u.mixed[k]=m.a[k].mixed;}
3476            st->parallel_for<dpct_kernel_name<class gr_up_compact_ready>>(
3477                sycl::nd_range<3>(sycl::range(1,1,UPM_BLOCKS)*sycl::range(1,1,THREADS),sycl::range(1,1,THREADS)),exp_props,
3478                [=](sycl::nd_item<3>)[[sycl::reqd_sub_group_size(32)]]{gr_up_compact_ready_kernel(u);});
3479        }else if(lo_once)st->parallel_for<dpct_kernel_name<class gr_up_cached_norm_lo>>(
3480            sycl::nd_range<3>(sycl::range(1,1,UPM_BLOCKS)*sycl::range(1,1,THREADS),sycl::range(1,1,THREADS)),exp_props,
3481            [=](sycl::nd_item<3>)[[sycl::reqd_sub_group_size(32)]]{gr_up_cached_norm_kernel<true>(m);});
3482        else st->parallel_for<dpct_kernel_name<class gr_up_cached_norm>>(
3483            sycl::nd_range<3>(sycl::range(1,1,UPM_BLOCKS)*sycl::range(1,1,THREADS),sycl::range(1,1,THREADS)),exp_props,
3484            [=](sycl::nd_item<3>)[[sycl::reqd_sub_group_size(32)]]{gr_up_cached_norm_kernel<false>(m);});
3485    }else if (lo_once) {
3486        launch_gr_up_prepared_lo(m, st);
3487    } else if (gr_more_groups(st)) {
3488
3489        if (gr_large_grf(st)) launch_gr_up_more<true>(st, m);
3490        else launch_gr_up_more<false>(st, m);
3491    } else {
3492        launch_gr_up_multi(st, m, gr_large_grf(st));   // STRATA_GR_UP_COLS (16 default, 8, 4): the same bits; Arc A-series: large GRF
3493    }
3494    /*
3495    DPCT1010: SYCL uses exceptions to report errors and does not use the
3496    error codes. The cudaGetLastError function call was replaced with 0. You
3497    need to rewrite this code.
3498    */
3499    const dpct::err0 e = 0;
3500    return private_q8; // only the private T1 branch writes the image; all other paths retain fallback
3501}
3502
3503// the bench only (AMD latency-hidden kernels): nothing to switch on the SYCL port
3504void fused_gr_set_fast(int) {}
3505
3506bool fused_gr_supported(int64_t n_embd, int64_t hc, int64_t hc_lr) {
3507    return n_embd == N && hc == HC && hc_lr == LR;
3508}
3509
3510void fused_gr_read(const FusedGrArgs& a, void* stream) {
3511    if (!a.R || !a.w_norm || !a.w_down || !a.w_up || !a.lo || !a.rs || !a.mixed ||
3512        (a.w_inject && !a.inject_out) || (a.apply && (!a.bo_prev || !a.inj_prev || !a.R_out)) ||
3513        (a.apply && a.inj_prev == a.inject_out)) {
3514        std::fprintf(stderr, "fused_gr_read: invalid arguments\n");
3515        std::exit(1);
3516    }
3517    dpct::queue_ptr st = strata::q_of(stream);
3518    // SYCL port: the multi-token read's sliced down kernel and per-(token, stream) norm sum in their own orders, so a
3519    // window's token would differ in its last bits from this kernel's. The header promises "every token's outputs
3520    // are bitwise fused_gr_read(a[t])" (gr_parity checks it): with those paths on, the single read IS the multi read
3521    // of one token (each token's sums run in the same order whatever the window size).
3522    if (kDownXnTooBig || gr_down_sliced() || gr_norm_split() || gr_down_direct()) {
3523        static std::mutex mu;
3524        static std::unordered_map<sycl::queue*, float*> xn;
3525        float* scratch;
3526        {
3527            std::lock_guard<std::mutex> lk(mu);
3528            float*& p = xn[st];
3529            if (!p) p = sycl::malloc_device<float>((size_t) D, *st);
3530            scratch = p;
3531        }
3532        fused_gr_read_multi(&a, 1, scratch, stream);
3533        return;
3534    }
3535    {
3536        auto exp_props = sycl::ext::oneapi::experimental::properties{
3537            sycl::ext::oneapi::experimental::use_root_sync};
3538
3539        strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class gr_down_kernel_a5fa71>>(
3540            sycl::nd_range<3>(sycl::range(1, 1, DOWN_BLOCKS + 1) *
3541                                  sycl::range(1, 1, THREADS),
3542                              sycl::range(1, 1, THREADS)),
3543            exp_props,
3544            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
3545                gr_down_kernel(a);
3546            });
3547    }
3548    {
3549        auto exp_props = sycl::ext::oneapi::experimental::properties{
3550            sycl::ext::oneapi::experimental::use_root_sync};
3551
3552        strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class gr_up_kernel_fe3258>>(
3553            sycl::nd_range<3>(sycl::range(1, 1, UP_BLOCKS) *
3554                                  sycl::range(1, 1, THREADS),
3555                              sycl::range(1, 1, THREADS)),
3556            exp_props,
3557            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
3558                gr_up_kernel(a);
3559            });
3560    }
3561    /*
3562    DPCT1010: SYCL uses exceptions to report errors and does not use the
3563    error codes. The cudaGetLastError function call was replaced with 0. You
3564    need to rewrite this code.
3565    */
3566    const dpct::err0 e = 0;
3567}
3568
3569
3570namespace {
3571
3572/// The plain read, split, staged and (for one token) the single-token read on random bf16 weights and random inputs,
3573/// 1..8 tokens, with and without the pending write; every output of split and staged compared with the plain read's
3574/// bit for bit (and the plain read's with the single-token read's).  `why[v]` gets the first difference of variant
3575/// v; false if the check itself could not run.
3576bool fused_gr_selftest(bool ok_variant[4], std::string why[4]) try {
3577    constexpr int TM = kFusedGrMaxT;
3578    constexpr int NV = 4;                             // sets: 0 = plain, 1 = split, 2 = staged, 3 = single-token
3579    std::mt19937 rng(20260930u);
3580    std::normal_distribution<float> nd(0.0f, 1.0f);
3581    std::vector<uint16_t> h_down((size_t) LR * D), h_up((size_t) D * LR), h_inj((size_t) HC * D);
3582    std::vector<float> h_norm(D), h_R((size_t) TM * D), h_bo((size_t) TM * N), h_ip((size_t) TM * HC);
3583    for (auto& w : h_down) w = bf16_from_f32(0.02f * nd(rng));
3584    for (auto& w : h_up) w = bf16_from_f32(0.05f * nd(rng));
3585    for (auto& w : h_inj) w = bf16_from_f32(0.02f * nd(rng));
3586    for (auto& w : h_norm) w = 1.0f + 0.1f * nd(rng);
3587    for (auto& x : h_R) x = nd(rng);
3588    for (auto& x : h_bo) x = 0.5f * nd(rng);
3589    for (auto& x : h_ip) x = 2.0f * nd(rng);
3590    for (int v = 0; v < 4; ++v) { ok_variant[v] = v == 1; why[v].clear(); }
3591
3592    const size_t n_set = (size_t) TM * (D + D + LR + HC + HC + N);   // R_out, xn, lo, rs, inject, mixed (floats)
3593    const size_t bytes = h_down.size() * 2 + h_up.size() * 2 + h_inj.size() * 2 +
3594                         (h_norm.size() + h_R.size() + h_bo.size() + h_ip.size() + NV * n_set) * 4 + 32 * 256;
3595    uint8_t* base = nullptr;
3596    if (DPCT_CHECK_ERROR(base = (uint8_t *)sycl::malloc_device(
3597                             bytes, dpct::get_in_order_queue())) != 0) {
3598        /*
3599        DPCT1026: The call to cudaGetLastError was removed because this
3600        functionality is redundant in SYCL.
3601        */
3602        why[0] =
3603            "no room for the check (" + std::to_string(bytes >> 20) + " MiB)";
3604        return false;
3605    }
3606    size_t off = 0;
3607    auto take = [&](size_t b) { void* p = base + off; off += (b + 255) / 256 * 256; return p; };
3608    uint16_t* d_down = (uint16_t*) take(h_down.size() * 2);
3609    uint16_t* d_up = (uint16_t*) take(h_up.size() * 2);
3610    uint16_t* d_inj = (uint16_t*) take(h_inj.size() * 2);
3611    float* d_norm = (float*) take(h_norm.size() * 4);
3612    float* d_R = (float*) take(h_R.size() * 4);
3613    float* d_bo = (float*) take(h_bo.size() * 4);
3614    float* d_ip = (float*) take(h_ip.size() * 4);
3615    struct Set { float *R_out, *xn, *lo, *rs, *inj, *mixed; } set[NV];
3616    for (Set& x : set) {
3617        x.R_out = (float*) take((size_t) TM * D * 4); x.xn = (float*) take((size_t) TM * D * 4);
3618        x.lo = (float*) take((size_t) TM * LR * 4); x.rs = (float*) take((size_t) TM * HC * 4);
3619        x.inj = (float*) take((size_t) TM * HC * 4); x.mixed = (float*) take((size_t) TM * N * 4);
3620    }
3621    dpct::queue_ptr st = &dpct::get_in_order_queue();
3622    /*
3623    DPCT1025: The SYCL queue is created ignoring the flag and priority
3624    options.
3625    */
3626    bool ok =
3627        off <= bytes &&
3628        DPCT_CHECK_ERROR(st = dpct::get_current_device().create_queue(true)) ==
3629            0 &&
3630        /*
3631        DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.
3632        While the origin API might be synchronous, it depends on the type of
3633        operand memory, so you may need to call wait() on event return by memcpy
3634        API to ensure synchronization behavior.
3635        */
3636        DPCT_CHECK_ERROR(
3637            st->memcpy(d_down, h_down.data(), h_down.size() * 2)) == 0 &&
3638        /*
3639        DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.
3640        While the origin API might be synchronous, it depends on the type of
3641        operand memory, so you may need to call wait() on event return by memcpy
3642        API to ensure synchronization behavior.
3643        */
3644        DPCT_CHECK_ERROR(st->memcpy(d_up, h_up.data(), h_up.size() * 2)) == 0 &&
3645        /*
3646        DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.
3647        While the origin API might be synchronous, it depends on the type of
3648        operand memory, so you may need to call wait() on event return by memcpy
3649        API to ensure synchronization behavior.
3650        */
3651        DPCT_CHECK_ERROR(st->memcpy(d_inj, h_inj.data(), h_inj.size() * 2)) ==
3652            0 &&
3653        /*
3654        DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.
3655        While the origin API might be synchronous, it depends on the type of
3656        operand memory, so you may need to call wait() on event return by memcpy
3657        API to ensure synchronization behavior.
3658        */
3659        DPCT_CHECK_ERROR(
3660            st->memcpy(d_norm, h_norm.data(), h_norm.size() * 4)) == 0 &&
3661        /*
3662        DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.
3663        While the origin API might be synchronous, it depends on the type of
3664        operand memory, so you may need to call wait() on event return by memcpy
3665        API to ensure synchronization behavior.
3666        */
3667        DPCT_CHECK_ERROR(st->memcpy(d_R, h_R.data(), h_R.size() * 4)) == 0 &&
3668        /*
3669        DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.
3670        While the origin API might be synchronous, it depends on the type of
3671        operand memory, so you may need to call wait() on event return by memcpy
3672        API to ensure synchronization behavior.
3673        */
3674        DPCT_CHECK_ERROR(st->memcpy(d_bo, h_bo.data(), h_bo.size() * 4)) == 0 &&
3675        /*
3676        DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.
3677        While the origin API might be synchronous, it depends on the type of
3678        operand memory, so you may need to call wait() on event return by memcpy
3679        API to ensure synchronization behavior.
3680        */
3681        DPCT_CHECK_ERROR(st->memcpy(d_ip, h_ip.data(), h_ip.size() * 4)) == 0;
3682    if (!ok) why[0] = "setting up the check failed";
3683    std::vector<float> h1, h2;
3684    // true when equal; false with the first difference in `w` (or a read-back failure in `ok`)
3685    auto same = [&](const float* d1, const float* d2, size_t n, const char* what, int T, int apply, std::string& w) {
3686        h1.resize(n);
3687        h2.resize(n);
3688        /*
3689        DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.
3690        While the origin API might be synchronous, it depends on the type of
3691        operand memory, so you may need to call wait() on event return by memcpy
3692        API to ensure synchronization behavior.
3693        */
3694        if (DPCT_CHECK_ERROR(st->memcpy(h1.data(), d1, n * 4)) != 0 ||
3695            /*
3696            DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy
3697            API. While the origin API might be synchronous, it depends on the
3698            type of operand memory, so you may need to call wait() on event
3699            return by memcpy API to ensure synchronization behavior.
3700            */
3701            DPCT_CHECK_ERROR(st->memcpy(h2.data(), d2, n * 4)) != 0 ||
3702            DPCT_CHECK_ERROR(st->wait()) != 0) {
3703            why[0] = "reading back the check failed";
3704            ok = false;
3705            return false;
3706        }
3707        for (size_t i = 0; i < n; ++i) {
3708            uint32_t u1, u2;
3709            std::memcpy(&u1, &h1[i], 4);
3710            std::memcpy(&u2, &h2[i], 4);
3711            if (u1 != u2) {
3712                char buf[192];
3713                std::snprintf(buf, sizeof buf, "%s differs for %d token(s)%s at %zu (%08x, not %08x)", what, T,
3714                              apply ? " with the pending write" : "", i, u2, u1);
3715                w = buf;
3716                return false;
3717            }
3718        }
3719        return true;
3720    };
3721    auto all_same = [&](const Set& s1, const Set& s2, int T, int apply, std::string& w) {
3722        return same(s1.lo, s2.lo, (size_t) T * LR, "lo", T, apply, w) &&
3723               same(s1.rs, s2.rs, (size_t) T * HC, "rs", T, apply, w) &&
3724               same(s1.inj, s2.inj, (size_t) T * HC, "inject", T, apply, w) &&
3725               same(s1.mixed, s2.mixed, (size_t) T * N, "mixed", T, apply, w) &&
3726               same(s1.R_out, s2.R_out, (size_t) T * D, "R", T, apply, w);
3727    };
3728    ok_variant[2] = ok_variant[3] = ok;
3729    bool single_ok = ok;
3730    for (int apply = 0; apply < 2 && ok; ++apply) {
3731        for (int T = 1; T <= TM && ok; ++T) {
3732            FusedGrArgs a[NV][TM];
3733            for (int v = 0; v < NV; ++v) {
3734                const size_t span = (size_t) ((uint8_t*) (set[v].mixed + (size_t) TM * N) - (uint8_t*) set[v].R_out);
3735                ok = ok &&
3736                     DPCT_CHECK_ERROR(st->memset(set[v].R_out, 0xFF, span)) ==
3737                         0; // the whole set
3738                for (int k = 0; k < T; ++k) {
3739                    FusedGrArgs& x = a[v][k];
3740                    x.R = d_R + (size_t) k * D; x.R_out = set[v].R_out + (size_t) k * D; x.apply = apply != 0;
3741                    x.bo_prev = d_bo + (size_t) k * N; x.inj_prev = d_ip + (size_t) k * HC;
3742                    x.w_norm = d_norm; x.w_down = d_down; x.w_up = d_up; x.w_inject = d_inj; x.eps = 1e-6f;
3743                    x.lo = set[v].lo + (size_t) k * LR; x.rs = set[v].rs + (size_t) k * HC;
3744                    x.inject_out = set[v].inj + (size_t) k * HC; x.mixed = set[v].mixed + (size_t) k * N;
3745                }
3746            }
3747            for (int v = 0; v < 3; ++v) {
3748                GrMulti m;
3749                for (int k = 0; k < T; ++k) m.a[k] = a[v][k];
3750                m.xn = set[v].xn;
3751                m.T = T;
3752                launch_multi(m, v + 1, st, nullptr, 0);
3753            }
3754            if (T == 1) fused_gr_read(a[3][0], st);
3755            /*
3756            DPCT1010: SYCL uses exceptions to report errors and does not
3757            use the error codes. The cudaGetLastError function call was replaced
3758            with 0. You need to rewrite this code.
3759            */
3760            if (0 != 0 || DPCT_CHECK_ERROR(st->wait()) != 0) {
3761                why[0] = "a kernel of the check failed";
3762                ok = false;
3763                break;
3764            }
3765            if (ok_variant[2] && !all_same(set[0], set[1], T, apply, why[2])) ok_variant[2] = false;
3766            if (ok && ok_variant[3] && !all_same(set[0], set[2], T, apply, why[3])) ok_variant[3] = false;
3767            if (ok && T == 1 && single_ok && !all_same(set[3], set[0], T, apply, why[1])) single_ok = false;
3768        }
3769    }
3770    if (!single_ok && ok) {                            // the plain read itself disagrees with the single-token read
3771        why[2] = why[3] = "the plain read differs from the single-token read: " + why[1];
3772        ok_variant[2] = ok_variant[3] = false;
3773    }
3774    if (st != &dpct::get_in_order_queue()) {
3775        st->wait();
3776        dpct::get_current_device().destroy_queue(st);
3777    }
3778    sycl::free(base, dpct::get_in_order_queue());
3779    /*
3780    DPCT1026: The call to cudaGetLastError was removed because this
3781    functionality is redundant in SYCL.
3782    */
3783    if (!ok) ok_variant[2] = ok_variant[3] = false;
3784    return ok;
3785}
3786catch (sycl::exception const &exc) {
3787  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
3788            << ", line:" << __LINE__ << std::endl;
3789  std::exit(1);
3790}
3791
3792}  // namespace
3793
3794int fused_gr_variant() {
3795    int dev = 0;
3796    dev = dpct::get_current_device_id();
3797    const int v = dev >= 0 && dev < 64 ? g_variant[dev].load() : 0;
3798    if (v > 0) return v;
3799    // not checked on this card: the plain read, unless STRATA_HC_SPLIT names a variant (a test such as gr_parity)
3800    const char* e = std::getenv("STRATA_HC_SPLIT");
3801    return e != nullptr && (e[0] == '1' || e[0] == '2') ? env_variant() : kHcPlain;
3802}
3803
3804void fused_gr_check() {
3805    int dev = 0;
3806    dev = dpct::get_current_device_id();
3807    if (dev < 0 || dev >= 64 || g_variant[dev].load() > 0) return;
3808    // SYCL port: the port's own read (sliced down / split norm, STRATA_GR_DOWN_SLICED etc.) does not use upstream's
3809    // variants, and their self-test crashes on the B70 (0.1.32 merge, under investigation): opt-in only.
3810    if (std::getenv("STRATA_HC_CHECK") == nullptr) {
3811        g_variant[dev].store(kHcPlain);
3812        return;
3813    }
3814    const int want = env_variant();
3815    if (want == kHcPlain) {
3816        g_variant[dev].store(kHcPlain);
3817        std::fprintf(stderr, "strata hc: CUDA%d: the hyper-connection read runs as the plain one (STRATA_HC_SPLIT=0)\n",
3818                     dev);
3819        return;
3820    }
3821    bool okv[4];
3822    std::string why[4];
3823    const bool ran = fused_gr_selftest(okv, why);
3824    int use = kHcPlain;
3825    if (want >= kHcStaged && okv[kHcStaged]) use = kHcStaged;
3826    else if (okv[kHcSplit]) use = kHcSplit;
3827    g_variant[dev].store(use);
3828    if (!ran)
3829        std::fprintf(stderr, "strata hc: CUDA%d: the check of split/staged could not run (%s)\n", dev, why[0].c_str());
3830    static const char* const name[4] = {"", "plain", "split", "staged"};
3831    for (int v = kHcStaged; v >= kHcSplit; --v)
3832        if (v <= want && !okv[v] && ran)
3833            std::fprintf(stderr, "strata hc: CUDA%d: the %s read differs from the plain read on this card - not used: "
3834                                 "%s\n", dev, name[v], why[v].c_str());
3835    static const char* const what[4] = {
3836        "", "the plain read (the norm per token, the down projection on 41 blocks)",
3837        "split (the norm per token and stream, then the plain read's down projection)",
3838        "staged (the norm per token and stream, the down projection's activations staged ahead by cp.async)"};
3839    std::fprintf(stderr, "strata hc: CUDA%d: the hyper-connection read runs as %s%s\n", dev, what[use],
3840                 use >= kHcSplit ? "; checked bit for bit against the plain read on this card (STRATA_HC_SPLIT=1 or 0 "
3841                                   "for the earlier ones)" : "");
3842}
3843
3844
3845}  // namespace strata::kernels