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
51.1 KiB1066 linesraw
1// src/prefill/gemm.cu - see include/strata/prefill/gemm.hpp.
2#define DPCT_PROFILING_ENABLED
3#include <sycl/sycl.hpp>
4#include "strata/kprof.hpp"
5#include <dpct/dpct.hpp>
6#include "strata/sycl_queue.hpp"
7#include "strata/prefill/gemm.hpp"
8#include "strata/workload_trace.hpp"
9#include "strata/kernels/dequant_bf16.hpp"
10#include <dpct/blas_utils.hpp>
11
12#if defined(STRATA_PREFILL_MMQ) && defined(__HIPCC__)
13#include "strata/prefill/moe_mmq.hpp"
14#endif
15
16#ifdef STRATA_USE_HIP
17#include "wmma_gemm.h"
18#endif
19
20#include <algorithm>
21#include <atomic>
22
23#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)
24// The HIP compatibility shim maps CUDA shuffle spellings to Strata helpers.
25// hipBLASLt's public headers declare native HIP shuffle functions, so keep
26// those declarations from being macro-expanded in this translation unit.
27#undef __shfl_xor_sync
28#undef __shfl_down_sync
29#undef __shfl_up_sync
30#undef __shfl_sync
31#undef __ballot_sync
32#endif
33
34#include <algorithm>
35#include <climits>
36#include <cstdio>
37#include <cstdlib>
38#include <cstring>
39#include <memory>
40#include <cmath>
41
42#include <dpct/lib_common_utils.hpp>
43
44#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)
45#include "hipblaslt_tuning.hpp"
46#include <hip/hip_runtime_api.h>
47#include <hipblaslt/hipblaslt.h>
48#include <hipblaslt/hipblaslt-ext.hpp>
49#include <map>
50#include <set>
51#include <tuple>
52#endif
53
54#if defined(__HIPCC__)
55#include <hip/hip_fp16.h>
56#endif
57
58namespace strata::prefill {
59namespace {
60#if defined(__HIPCC__)
61// Y's rows, written by an FP16-out GEMM as FP16 at the start of each FP32 row (ldc = 2 ldy halves), widened in place.
62// Float c overwrites halves 2c and 2c+1, so a row is walked from its end in blocks: a block's halves are read into
63// registers, the block syncs, then writes its floats - which only cover halves of blocks already read.
64// STRATA_DBG_NAN: the FP16 outputs that are not finite (an FP32-accumulated sum past 65504 becomes inf in FP16).
65__device__ unsigned long long g_f16_nonfinite = 0;
66__global__ void widen_rows_f16(float* __restrict__ Y, int64_t n, int64_t ldy, int count_nonfinite) {
67    float* y = Y + (int64_t) blockIdx.x * ldy;
68    const __half* h = reinterpret_cast<const __half*>(y);
69    const int64_t nb = (n + blockDim.x - 1) / blockDim.x;
70    for (int64_t b = nb - 1; b >= 0; --b) {
71        const int64_t c = b * blockDim.x + threadIdx.x;
72        const float v = c < n ? __half2float(h[c]) : 0.0f;
73        if (count_nonfinite && c < n && !isfinite(v)) atomicAdd(&g_f16_nonfinite, 1ull);
74        __syncthreads();
75        if (c < n) y[c] = v;
76        __syncthreads();
77    }
78}
79// BF16 weight rows -> FP16, saturated (bench/results/2026-10-04-rdna2-fp16-prompt: none leaves FP16's range)
80__global__ void bf16_to_f16_rows(const uint16_t* __restrict__ s, __half* __restrict__ d, int64_t n) {
81    for (int64_t i = blockIdx.x * (int64_t) blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) {
82        const float f = __uint_as_float((uint32_t) s[i] << 16);
83        d[i] = __float2half(isnan(f) ? f : fminf(fmaxf(f, -65504.0f), 65504.0f));   // as hf_sat: a NaN stays NaN
84    }
85}
86#endif
87
88void ck(int s, const char *what) {
89    if (s != 0) {
90        std::fprintf(stderr, "prefill gemm: %s: cuBLAS status %d\n", what, (int) s);
91        std::exit(1);
92    }
93}
94
95// #247/#325: on Windows (seen on gfx1201), hipBLAS can return success with the correct BF16/FP16 product for some
96// shapes (hc up once T >= 96, the router) and still leave hipErrorInvalidValue set, which the next kernel's error
97// check turns into an exit. The multiply has finished, so that one stale error is cleared after a GEMM that succeeded;
98// any other error still stops the engine. Windows only: on Linux a stale hipErrorInvalidValue is a real error from
99// an earlier call and keeps being reported. A no-op everywhere else (CUDA compiles none of it).
100#if defined(__HIPCC__) && defined(_WIN32)
101void absorb_hipblas_sticky(const char* what) {
102    const hipError_t sticky = hipGetLastError();
103    if (sticky == hipSuccess || sticky == hipErrorInvalidValue) return;
104    std::fprintf(stderr, "prefill gemm: %s left %s\n", what, hipGetErrorString(sticky));
105    std::exit(1);
106}
107#define STRATA_ABSORB_HIPBLAS_STICKY(what) absorb_hipblas_sticky(what)
108#else
109#define STRATA_ABSORB_HIPBLAS_STICKY(what) ((void) 0)
110#endif
111
112// A setup call whose failure the engine survives (the handle keeps its defaults), as before #240 - but said.
113void note(int s, const char *what) {
114    if (s != 0) std::fprintf(
115        stderr, "prefill gemm: %s: cuBLAS status %d (continuing)\n", what,
116        (int)s);
117}
118
119#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)
120struct HipLtCallKey {
121    strata::prefill::hipblaslt::InputType type;
122    int t;
123    int n;
124    int k;
125    int ldy;
126    uint32_t beta_bits;
127
128    bool operator<(const HipLtCallKey& other) const {
129        return std::tie(type, n, k, ldy, t, beta_bits) <
130               std::tie(other.type, other.n, other.k, other.ldy, other.t, other.beta_bits);
131    }
132};
133
134struct HipLtCachedAlgo {
135    bool supported = false;
136    hipblasLtMatmulAlgo_t algo{};
137    size_t workspace_bytes = 0;
138};
139
140struct HipLtState {
141    hipblasLtHandle_t handle = nullptr;
142    void* workspace = nullptr;
143    size_t workspace_bytes = 0;
144    strata::prefill::hipblaslt::TuningTable table;
145    std::map<HipLtCallKey, HipLtCachedAlgo> cache;
146    uint64_t lt_launches = 0;
147    uint64_t fallbacks = 0;
148    std::set<std::tuple<strata::prefill::hipblaslt::InputType, int, int, int, int>> fallback_shapes;
149
150    ~HipLtState() {
151        if (std::getenv("STRATA_HIPBLASLT_VERBOSE")) {
152            std::fprintf(stderr, "prefill gemm: hipBLASLt summary launches=%llu fallbacks=%llu unique_fallback_shapes=%zu\n",
153                         (unsigned long long) lt_launches, (unsigned long long) fallbacks, fallback_shapes.size());
154            for (const auto& shape : fallback_shapes) {
155                const auto type = std::get<0>(shape);
156                std::fprintf(stderr, "prefill gemm: fallback shape dtype=%s T=%d N=%d K=%d ldy=%d\n",
157                             type == strata::prefill::hipblaslt::InputType::bf16 ? "bf16" : "f16",
158                             std::get<1>(shape), std::get<2>(shape), std::get<3>(shape), std::get<4>(shape));
159            }
160        }
161        if (handle) hipblasLtDestroy(handle);
162    }
163};
164
165struct HipLtDescriptors {
166    hipblasLtMatmulDesc_t op = nullptr;
167    hipblasLtMatrixLayout_t a = nullptr;
168    hipblasLtMatrixLayout_t b = nullptr;
169    hipblasLtMatrixLayout_t c = nullptr;
170
171    ~HipLtDescriptors() {
172        if (op) hipblasLtMatmulDescDestroy(op);
173        if (a) hipblasLtMatrixLayoutDestroy(a);
174        if (b) hipblasLtMatrixLayoutDestroy(b);
175        if (c) hipblasLtMatrixLayoutDestroy(c);
176    }
177
178    bool init(hipDataType type, int t, int n, int k, int ldy, int ldb = 0) {
179        const hipblasOperation_t trans_a = HIPBLAS_OP_T;
180        const hipblasOperation_t trans_b = HIPBLAS_OP_N;
181        if (hipblasLtMatmulDescCreate(&op, HIPBLAS_COMPUTE_32F, HIP_R_32F) != HIPBLAS_STATUS_SUCCESS ||
182            hipblasLtMatmulDescSetAttribute(op, HIPBLASLT_MATMUL_DESC_TRANSA, &trans_a, sizeof(trans_a)) !=
183                HIPBLAS_STATUS_SUCCESS ||
184            hipblasLtMatmulDescSetAttribute(op, HIPBLASLT_MATMUL_DESC_TRANSB, &trans_b, sizeof(trans_b)) !=
185                HIPBLAS_STATUS_SUCCESS ||
186            hipblasLtMatrixLayoutCreate(&a, type, k, n, k) != HIPBLAS_STATUS_SUCCESS ||
187            hipblasLtMatrixLayoutCreate(&b, type, k, t, ldb > k ? ldb : k) != HIPBLAS_STATUS_SUCCESS ||
188            hipblasLtMatrixLayoutCreate(&c, HIP_R_32F, n, t, ldy) != HIPBLAS_STATUS_SUCCESS) {
189            return false;
190        }
191        return true;
192    }
193};
194
195std::unique_ptr<HipLtState> create_hipblaslt_state(void* workspace, size_t workspace_bytes) {
196    const char* path = std::getenv("STRATA_HIPBLASLT_TUNING");
197    if (!path || !*path) return nullptr;
198
199    auto state = std::make_unique<HipLtState>();
200    state->workspace = workspace;
201    state->workspace_bytes = workspace_bytes;
202    if (hipblasLtCreate(&state->handle) != HIPBLAS_STATUS_SUCCESS) {
203        std::fprintf(stderr, "prefill gemm: hipBLASLt handle creation failed; using hipBLASEx\n");
204        return nullptr;
205    }
206
207    int version = 0;
208    if (hipblasLtGetVersion(state->handle, &version) != HIPBLAS_STATUS_SUCCESS) {
209        std::fprintf(stderr, "prefill gemm: hipBLASLt version query failed; using hipBLASEx\n");
210        return nullptr;
211    }
212    int device = 0;
213    hipDeviceProp_t properties{};
214    if (hipGetDevice(&device) != hipSuccess || hipGetDeviceProperties(&properties, device) != hipSuccess) {
215        std::fprintf(stderr, "prefill gemm: HIP device query failed; using hipBLASEx\n");
216        return nullptr;
217    }
218    std::string arch(properties.gcnArchName);
219    const auto suffix = arch.find(':');
220    if (suffix != std::string::npos) arch.resize(suffix);
221
222    std::string error;
223    if (!state->table.load(path, arch, version, error)) {
224        std::fprintf(stderr, "prefill gemm: %s; using hipBLASEx\n", error.c_str());
225        return nullptr;
226    }
227    std::fprintf(stderr, "prefill gemm: hipBLASLt tuning enabled (%zu rows, %s, version %d)\n",
228                 state->table.rows().size(), arch.c_str(), version);
229    return state;
230}
231
232HipLtCachedAlgo resolve_hipblaslt_algo(HipLtState& state, strata::prefill::hipblaslt::InputType type, int t,
233                                       int n, int k, int ldy, float beta) {
234    uint32_t beta_bits = 0;
235    static_assert(sizeof(beta_bits) == sizeof(beta));
236    std::memcpy(&beta_bits, &beta, sizeof(beta));
237    const HipLtCallKey key{type, t, n, k, ldy, beta_bits};
238    const auto cached = state.cache.find(key);
239    if (cached != state.cache.end()) return cached->second;
240
241    HipLtCachedAlgo resolved;
242    const bool verbose = std::getenv("STRATA_HIPBLASLT_VERBOSE") != nullptr;
243    const auto* row = state.table.closest(type, n, k, ldy, t);
244    if (!row) {
245        if (verbose) {
246            std::fprintf(stderr, "prefill gemm: Lt fallback; no calibration for dtype=%s T=%d N=%d K=%d ldy=%d\n",
247                         type == strata::prefill::hipblaslt::InputType::bf16 ? "bf16" : "f16", t, n, k, ldy);
248        }
249        return state.cache.emplace(key, resolved).first->second;
250    }
251
252    HipLtDescriptors desc;
253    const hipDataType input_type = type == strata::prefill::hipblaslt::InputType::bf16 ? HIP_R_16BF : HIP_R_16F;
254    if (!desc.init(input_type, t, n, k, ldy)) {
255        return state.cache.emplace(key, resolved).first->second;
256    }
257
258    std::vector<int> solution_ids{row->solution_id};
259    std::vector<hipblasLtMatmulHeuristicResult_t> candidates;
260    if (hipblaslt_ext::getAlgosFromIndex(state.handle, solution_ids, candidates) != HIPBLAS_STATUS_SUCCESS ||
261        candidates.empty() || candidates.front().state != HIPBLAS_STATUS_SUCCESS ||
262        hipblaslt_ext::getIndexFromAlgo(candidates.front().algo) != row->solution_id) {
263        if (verbose) {
264            std::fprintf(stderr, "prefill gemm: Lt fallback; solution %d unavailable for T=%d N=%d K=%d ldy=%d\n",
265                         row->solution_id, t, n, k, ldy);
266        }
267        return state.cache.emplace(key, resolved).first->second;
268    }
269
270    const float alpha = 1.0f;
271    size_t required_workspace = 0;
272    auto algo = candidates.front().algo;
273    if (hipblaslt_ext::matmulIsAlgoSupported(state.handle, desc.op, &alpha, desc.a, desc.b, &beta, desc.c, desc.c,
274                                             algo, required_workspace) != HIPBLAS_STATUS_SUCCESS) {
275        if (verbose) {
276            std::fprintf(stderr, "prefill gemm: Lt fallback; solution %d rejects actual T=%d N=%d K=%d ldy=%d beta=%.9g\n",
277                         row->solution_id, t, n, k, ldy, beta);
278        }
279        return state.cache.emplace(key, resolved).first->second;
280    }
281
282    resolved.supported = true;
283    resolved.algo = algo;
284    resolved.workspace_bytes = required_workspace;
285    if (verbose) {
286        std::fprintf(stderr,
287                     "prefill gemm: Lt solution=%d dtype=%s T=%d N=%d K=%d ldy=%d beta=%.9g workspace=%zu\n",
288                     row->solution_id, type == strata::prefill::hipblaslt::InputType::bf16 ? "bf16" : "f16", t, n,
289                     k, ldy, beta, required_workspace);
290    }
291    return state.cache.emplace(key, resolved).first->second;
292}
293
294// the hipBLASLt solution index the tuning table gives this call (-1: none / unsupported)
295int hipblaslt_solution_for(void* opaque_state, strata::prefill::hipblaslt::InputType type, int64_t t, int64_t n, int64_t k,
296                           int64_t ldy, float beta) {
297    auto* state = static_cast<HipLtState*>(opaque_state);
298    if (!state || t <= 0 || n <= 0 || k <= 0 || t > INT_MAX || n > INT_MAX || k > INT_MAX || ldy > INT_MAX || ldy < n) return -1;
299    const auto resolved = resolve_hipblaslt_algo(*state, type, (int) t, (int) n, (int) k, (int) ldy, beta);
300    if (!resolved.supported || resolved.workspace_bytes > state->workspace_bytes) return -1;
301    auto algo = resolved.algo;
302    return hipblaslt_ext::getIndexFromAlgo(algo);
303}
304
305bool try_hipblaslt(void* opaque_state, strata::prefill::hipblaslt::InputType type, const uint16_t* x,
306                   const uint16_t* w, float* y, int64_t t, int64_t n, int64_t k, int64_t ldy, float beta,
307                   void* stream, int64_t ldx = 0) {
308    auto* state = static_cast<HipLtState*>(opaque_state);
309    if (!state || t <= 0 || n <= 0 || k <= 0 || t > INT_MAX || n > INT_MAX || k > INT_MAX || ldy > INT_MAX ||
310        ldy < n) {
311        return false;
312    }
313    const auto resolved = resolve_hipblaslt_algo(*state, type, (int) t, (int) n, (int) k, (int) ldy, beta);
314    if (!resolved.supported) {
315        ++state->fallbacks;
316        state->fallback_shapes.emplace(type, (int) t, (int) n, (int) k, (int) ldy);
317        return false;
318    }
319    if (resolved.workspace_bytes > state->workspace_bytes) {
320        ++state->fallbacks;
321        state->fallback_shapes.emplace(type, (int) t, (int) n, (int) k, (int) ldy);
322        if (std::getenv("STRATA_HIPBLASLT_VERBOSE")) {
323            std::fprintf(stderr, "prefill gemm: Lt fallback; solution needs %zu workspace bytes, have %zu\n",
324                         resolved.workspace_bytes, state->workspace_bytes);
325        }
326        return false;
327    }
328
329    HipLtDescriptors desc;
330    const hipDataType input_type = type == strata::prefill::hipblaslt::InputType::bf16 ? HIP_R_16BF : HIP_R_16F;
331    if (!desc.init(input_type, (int) t, (int) n, (int) k, (int) ldy, (int) ldx)) return false;
332    const float alpha = 1.0f;
333    const hipblasStatus_t status = hipblasLtMatmul(state->handle, desc.op, &alpha, w, desc.a, x, desc.b, &beta, y,
334                                                   desc.c, y, desc.c, &resolved.algo, state->workspace,
335                                                   state->workspace_bytes, (hipStream_t) stream);
336    if (status == HIPBLAS_STATUS_SUCCESS) {
337        ++state->lt_launches;
338        return true;
339    }
340
341    std::fprintf(stderr, "prefill gemm: hipBLASLt launch failed with status %d\n", (int) status);
342    if (beta != 0.0f) {
343        std::fprintf(stderr, "prefill gemm: refusing a fallback after hipBLASLt failed with nonzero beta\n");
344        std::exit(1);
345    }
346    auto* mutable_state = static_cast<HipLtState*>(opaque_state);
347    uint32_t beta_bits = 0;
348    std::memcpy(&beta_bits, &beta, sizeof(beta_bits));
349    auto cached = mutable_state->cache.find(HipLtCallKey{type, (int) t, (int) n, (int) k, (int) ldy, beta_bits});
350    if (cached != mutable_state->cache.end()) cached->second.supported = false;
351    ++mutable_state->fallbacks;
352    mutable_state->fallback_shapes.emplace(type, (int) t, (int) n, (int) k, (int) ldy);
353    return false;
354}
355#endif
356
357}  // namespace
358
359bool prompt_f16() {
360#if defined(__HIPCC__)
361    constexpr int kMaxDev = 64;
362    static std::atomic<int8_t> cached[kMaxDev] = {};   // 0 unknown, 1 off, 2 on
363    int dev = 0;
364    if (hipGetDevice(&dev) != hipSuccess || dev < 0 || dev >= kMaxDev) { (void) hipGetLastError(); return false; }
365    if (const int8_t c = cached[dev].load(std::memory_order_relaxed)) return c == 2;
366    // Opt-in (#835): only STRATA_HIP_PROMPT_F16=1 turns it on.  It changes the prompt path's numbers (an FP16 rounding of
367    // each 16-bit GEMM's output), so no card gets it unasked.  On gfx103x it is ~2x faster, so we say so once.
368    const char* e = std::getenv("STRATA_HIP_PROMPT_F16");
369    const bool on = e != nullptr && e[0] == '1';
370    hipDeviceProp_t p{};
371    if (hipGetDeviceProperties(&p, dev) != hipSuccess) { (void) hipGetLastError(); p.gcnArchName[0] = 0; }
372    if (on) std::fprintf(stderr, "strata prefill: HIP device %d%s%s - STRATA_HIP_PROMPT_F16=1: the prompt's 16-bit GEMMs run FP16 in and out "
373                                 "(rocBLAS is tuned only for that on gfx103x; not bit-identical to the default)%s",
374                         dev, p.gcnArchName[0] ? " " : "", p.gcnArchName, "\n");
375    else if (e == nullptr && std::strncmp(p.gcnArchName, "gfx103", 6) == 0)
376        std::fprintf(stderr, "strata prefill: HIP device %d %s - tip: STRATA_HIP_PROMPT_F16=1 reads long prompts about 2x faster here "
377                             "(FP16 prompt GEMMs, rocBLAS is tuned only for FP16 on gfx103x; the numbers differ slightly, see docs/AMD_HIP.md)%s",
378                     dev, p.gcnArchName, "\n");
379    cached[dev].store(on ? 2 : 1, std::memory_order_relaxed);
380    return on;
381#else
382    return false;
383#endif
384}
385
386Gemm::~Gemm() {
387#if defined(STRATA_PREFILL_MMQ) && defined(__HIPCC__)
388    delete static_cast<strata::prefill::mmq::Context*>(mmq_ctx_);
389    if (mmq_buf_) cudaFree(mmq_buf_);
390#endif
391#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)
392    delete static_cast<HipLtState*>(hipblaslt_state_);
393#endif
394    if (handle_) delete ((dpct::blas::descriptor_ptr)handle_);
395    if (tc_w_) sycl::free(tc_w_, dpct::get_in_order_queue());
396    if (tc_x_) sycl::free(tc_x_, dpct::get_in_order_queue());
397    if (!external_) {
398        if (scratch_) sycl::free(scratch_, dpct::get_in_order_queue());
399        if (workspace_) sycl::free(workspace_, dpct::get_in_order_queue());
400    }
401}
402
403bool Gemm::init_external(void *stream, uint16_t *scratch, int64_t scratch_elems,
404                         void *workspace, size_t ws_bytes,
405                         std::string &err) try {
406    dpct::blas::descriptor_ptr h = nullptr;
407    if (const int s = DPCT_CHECK_ERROR(h = new dpct::blas::descriptor());
408        s != 0) {
409        err = "prefill gemm: cublasCreate: cuBLAS status " + std::to_string((int) s);
410        return false;
411    }
412    handle_ = h;
413    stream_ = stream;
414    external_ = true;
415    note(DPCT_CHECK_ERROR(h->set_queue(strata::q_of(stream))),
416         "cublasSetStream");
417    workspace_ = workspace;
418    /*
419    DPCT1027: The call to cublasSetWorkspace was replaced with 0 because
420    this functionality is redundant in SYCL.
421    */
422    note(0, "cublasSetWorkspace");
423    note(DPCT_CHECK_ERROR(h->set_math_mode(dpct::blas::math_mode::mm_default)),
424         "cublasSetMathMode");
425    scratch_ = scratch;
426    scratch_elems_ = scratch_elems;
427#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)
428    hipblaslt_state_ = create_hipblaslt_state(workspace_, ws_bytes).release();
429#endif
430    return true;
431}
432catch (sycl::exception const &exc) {
433  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
434            << ", line:" << __LINE__ << std::endl;
435  std::exit(1);
436}
437
438void Gemm::rebind(uint16_t* scratch, int64_t scratch_elems, void* workspace, size_t ws_bytes) {
439    scratch_ = scratch;
440    scratch_elems_ = scratch_elems;
441    workspace_ = workspace;
442    /*
443    DPCT1026: The call to cublasSetWorkspace was removed because this
444    functionality is redundant in SYCL.
445    */
446#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)
447    if (hipblaslt_state_) {
448        auto* state = static_cast<HipLtState*>(hipblaslt_state_);
449        state->workspace = workspace_;
450        state->workspace_bytes = ws_bytes;
451    }
452#endif
453}
454
455bool Gemm::init(void *stream, int64_t scratch_elems, std::string &err) try {
456    // #240: every failure names the call and the real status, so "no VRAM" can be told from a broken install
457    dpct::blas::descriptor_ptr h = nullptr;
458    if (const int s = DPCT_CHECK_ERROR(h = new dpct::blas::descriptor());
459        s != 0) {
460        err = "prefill gemm: cublasCreate: cuBLAS status " + std::to_string((int) s);
461        return false;
462    }
463    handle_ = h;
464    stream_ = stream;
465    note(DPCT_CHECK_ERROR(h->set_queue(strata::q_of(stream))),
466         "cublasSetStream");
467    // A fixed workspace so the handle never allocates on the way (and graphs could capture it later).
468    const size_t ws = 32u << 20;
469    /*
470    DPCT1000: Error handling if-stmt was detected but could not be
471    rewritten.
472    */
473    if (const dpct::err0 e =
474            DPCT_CHECK_ERROR(workspace_ = (void *)sycl::malloc_device(
475                                 ws, dpct::get_in_order_queue()));
476        e != 0) {
477        /*
478        DPCT1009: SYCL reports errors using exceptions and does not use
479        error codes. Please replace the "get_error_string_dummy(...)" with a
480        real error-handling function.
481        */
482        /*
483        DPCT1001: The statement could not be removed.
484        */
485        err = std::string("prefill gemm: workspace of 32 MiB: ") +
486              dpct::get_error_string_dummy(e);
487        return false;
488    }
489    /*
490    DPCT1027: The call to cublasSetWorkspace was replaced with 0 because
491    this functionality is redundant in SYCL.
492    */
493    note(0, "cublasSetWorkspace");
494    note(DPCT_CHECK_ERROR(h->set_math_mode(dpct::blas::math_mode::mm_default)),
495         "cublasSetMathMode");
496#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)
497    hipblaslt_state_ = create_hipblaslt_state(workspace_, ws).release();
498#endif
499    if (scratch_elems > 0) {
500        /*
501        DPCT1000: Error handling if-stmt was detected but could not be
502        rewritten.
503        */
504        if (const dpct::err0 e = DPCT_CHECK_ERROR(
505                scratch_ = (uint16_t *)sycl::malloc_device(
506                    (size_t)scratch_elems * 2, dpct::get_in_order_queue()));
507            e != 0) {
508            /*
509            DPCT1001: The statement could not be removed.
510            */
511            err = "prefill gemm: dequant scratch of " +
512                  std::to_string(scratch_elems * 2 >> 20) + " MiB: " +
513                  /*
514                  DPCT1009: SYCL reports errors using exceptions and does
515                  not use error codes. Please replace the
516                  "get_error_string_dummy(...)" with a real error-handling
517                  function.
518                  */
519                  dpct::get_error_string_dummy(e);
520            return false;
521        }
522    }
523    scratch_elems_ = scratch_elems;
524    return true;
525}
526catch (sycl::exception const &exc) {
527  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
528            << ", line:" << __LINE__ << std::endl;
529  std::exit(1);
530}
531
532#if !defined(__HIPCC__)
533// ---- below sm_80: BF16 GEMMs without BF16 tensor cores (PR #655, #540, #395) ----------------------------------------
534// Turing and Volta have no BF16 tensor cores: cublasGemmEx on CUDA_R_16BF inputs falls back to a SIMT fp32 kernel
535// (magma_sgemmEx), a fifth of a 4K prompt on an RTX 2080 Ti (#655) and ~10% of a V100's prompt (#540).  BF16 -> FP16
536// is exact for every value inside FP16's normal range (the 7-bit mantissa fits in 10 bits); weights and normalized
537// activations sit there.  With the FP16 path, the weight is converted once per call and the activations in row
538// slices, into the instance's own buffers, and the product runs as the FP16 GEMM (fp32 accumulate) on the tensor
539// cores.  Finite values beyond FP16's range are clamped to +-65504 (#540) instead of becoming Inf.  A beta = 1
540// product (STRATA_PREFILL_BF16X2's remainder, ~2^-9 of the original, deep in FP16's subnormal band) keeps cuBLAS.
541//   Default: on for compute capability 7.0 - 7.4 (Volta: only the experimental STRATA_EXPERIMENTAL_SM60 build runs
542//   there), OFF for 7.5 (RTX 20 in the ready-made engine: the sums round differently, so it is opt-in until it has
543//   been gated).  STRATA_BF16_TC=1 / =0 turns it on / off on any 7.x card (=2, a test mode: on any card).
544// Pascal (6.x) has no tensor cores and cuBLAS has no BF16 GEMM for it (#395, measured NOT_SUPPORTED on a P40): both
545// operands are widened to fp32 by an exact shift and the product is cublasSgemm with the same fp32 accumulator.
546namespace {
547__dpct_inline__ void bf16_to_f16_kernel(const uint16_t *__restrict__ in,
548                                        sycl::half *__restrict__ out,
549                                        int64_t n) {
550    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
551    const int64_t i =
552        (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
553        item_ct1.get_local_id(2);
554    if (i < n) {
555        float f = sycl::bit_cast<float>((uint32_t)in[i] << 16);
556        if (f > 65504.0f && !sycl::isinf(f)) f = 65504.0f;
557        else if (f < -65504.0f && !sycl::isinf(f)) f = -65504.0f;
558        out[i] = sycl::vec<float, 1>(f)
559                     .convert<sycl::half, sycl::rounding_mode::rte>()[0];
560    }
561}
562void bf16_to_f16(const uint16_t *in, uint16_t *out, int64_t n,
563                 dpct::queue_ptr st) {
564    if (n <= 0) return;
565    {
566        auto exp_props = sycl::ext::oneapi::experimental::properties{
567            sycl::ext::oneapi::experimental::use_root_sync};
568        dpct::has_capability_or_fail(st->get_device(), {sycl::aspect::fp16});
569
570        strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class bf16_to_f16_kernel_a0031a>>(
571            sycl::nd_range<3>(sycl::range(1, 1, (unsigned)((n + 255) / 256)) *
572                                  sycl::range(1, 1, 256),
573                              sycl::range(1, 1, 256)),
574            exp_props, [=](sycl::nd_item<3> item_ct1) {
575                bf16_to_f16_kernel(in, reinterpret_cast<sycl::half *>(out), n);
576            });
577    }
578}
579#if defined(STRATA_EXPERIMENTAL_SM60)   // Pascal runs only the experimental build
580__global__ void bf16_to_f32_kernel(const uint16_t* __restrict__ in, float* __restrict__ out, int64_t n) {
581    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
582    if (i < n) out[i] = __uint_as_float((uint32_t) in[i] << 16);
583}
584void bf16_to_f32(const uint16_t* in, float* out, int64_t n, cudaStream_t st) {
585    if (n <= 0) return;
586    bf16_to_f32_kernel<<<(unsigned) ((n + 255) / 256), 256, 0, st>>>(in, out, n);
587}
588#endif
589// The current device's compute capability as 10 * major + minor, per device (a layer split can mix cards); 0: not
590// known, read as "not an old card" so a failed query keeps the cuBLAS BF16 call.
591int current_cc() try {
592    static std::atomic<int> cc[64] = {};
593    int dev = 0;
594    /*
595    DPCT1026: The call to cudaGetLastError was removed because this
596    functionality is redundant in SYCL.
597    */
598    if (DPCT_CHECK_ERROR(dev = dpct::get_current_device_id()) != 0 || dev < 0 ||
599        dev >= 64) {
600        ; return 0;
601    }
602    int v = cc[dev].load(std::memory_order_relaxed);
603    if (v == 0) {
604        int major = 0, minor = 0;
605        if (DPCT_CHECK_ERROR(
606                major = dpct::get_device(dev).get_major_version()) != 0 ||
607            DPCT_CHECK_ERROR(
608                minor = dpct::get_device(dev).get_minor_version()) != 0) {
609            /*
610            DPCT1026: The call to cudaGetLastError was removed because this
611            functionality is redundant in SYCL.
612            */
613            return 0;
614        }
615        v = 10 * major + minor;
616        cc[dev].store(v, std::memory_order_relaxed);
617    }
618    return v;
619}
620catch (sycl::exception const &exc) {
621  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
622            << ", line:" << __LINE__ << std::endl;
623  std::exit(1);
624}
625// 0: cuBLAS's BF16 GEMM, 1: through FP16 (tensor cores), 2: through FP32 (Pascal)
626int bf16_path() {
627    static const int forced = [] {
628        const char* v = std::getenv("STRATA_BF16_TC");
629        return v != nullptr && v[0] != '\0' ? std::atoi(v) : -1;
630    }();
631    const int cc = current_cc();
632    if (forced == 2 && cc > 0) return 1;   // a test mode: the FP16 path on any card (gemm_bf16_parity on sm_80+)
633    if (cc <= 0 || cc >= 80) return 0;
634    if (cc < 70) return 2;
635    if (forced >= 0) return forced != 0 ? 1 : 0;
636    return cc < 75 ? 1 : 0;
637}
638bool grow(uint16_t *&p, int64_t &have,
639          int64_t want) try { // `have`, `want`: 2-byte elements
640    if (have >= want) return true;
641    if (p) sycl::free(p, dpct::get_in_order_queue());
642    p = nullptr;
643    have = 0;
644    /*
645    DPCT1026: The call to cudaGetLastError was removed because this
646    functionality is redundant in SYCL.
647    */
648    if (DPCT_CHECK_ERROR(p = (uint16_t *)sycl::malloc_device(
649                             (size_t)want * 2, dpct::get_in_order_queue())) !=
650        0) {
651        ; p = nullptr; return false;
652    }
653    have = want;
654    return true;
655}
656catch (sycl::exception const &exc) {
657  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
658            << ", line:" << __LINE__ << std::endl;
659  std::exit(1);
660}
661constexpr int64_t kXSliceElems = 16ll << 20;   // 32 MiB of FP16 activations per slice (64 MiB as fp32)
662}  // namespace
663#endif
664bool Gemm::bf16_hcd_exact(const uint16_t* X, int64_t ldx, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K) {
665#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)
666    static std::atomic<bool> told{false};
667    if (!hipblaslt_state_ || N != 320 || K != 10240 || T < 1) {
668        if (N == 320 && K == 10240 && !told.exchange(true))
669            std::fprintf(stderr, "strata: STRATA_HCD_EXACT: no hipBLASLt tuning table is loaded, so the exact kernel has nothing to match: "
670                                 "the hyper-connection down projection stays on hipBLAS\n");
671        return false;
672    }
673    // The kernel copies hipBLASLt solution 1176 / 1177's summation order, which is only true of the library build the
674    // table was calibrated with: take it only when the table makes hipBLASLt pick one of those two for this T.
675    const int id = hipblaslt_solution_for(hipblaslt_state_, strata::prefill::hipblaslt::InputType::bf16, T, N, K, N, 0.0f);
676    if (id != 1176 && id != 1177) {
677        if (T >= 4096 && !told.exchange(true))   // (a short chunk may legitimately get another solution: not worth a line)
678            std::fprintf(stderr, "strata: STRATA_HCD_EXACT: the tuning table gives the hyper-connection down projection (N 320, K 10240) "
679                                 "solution %d at T %lld, not 1176 / 1177: hipBLASLt runs it (a changed table or library; "
680                                 "tools/hip/gfx1151-hipblaslt-100401.txt is the one measured)\n",
681                         id, (long long) T);
682        return false;
683    }
684    return strata_pf_hcdown_exact_bf16(X, ldx, W, Y, T, N, K, stream_);
685#else
686    (void) X; (void) ldx; (void) W; (void) Y; (void) T; (void) N; (void) K;
687    return false;
688#endif
689}
690
691
692// ---------------------------------------------------------------------------------------------------------------
693// CLEAN-6.0: oneMKL's bf16 GEMM is not repeatable on the Arc A750 for skinny shapes (measured: M=48,T=86,K=2560 and
694// M=4,T=86,K=10240 give a different result on every launch; T below ~128-160 at those M and K; M<=64 at T=1..8).  The
695// prompt path's ssm_alpha / ssm_beta (48 outputs) and hyper-connection inject (4 outputs) projections hit it in every
696// GDN layer, so the GDN state, and with it every token after a small near-tie, changed from run to run.  Gemm::bf16
697// runs outputs <= 64 on the fixed-order kernel below instead (repeatable, and 3-36x faster than oneMKL on the shapes tried, standalone).
698// STRATA_SYCL_BF16_DET=0 gives the oneMKL call back (A/B and diagnosis).
699// Deterministic bf16 x bf16 -> f32 skinny GEMM (CLEAN-6.0).  Y[t*ldy + n] (+)= sum_k W[n*K + k] * X[t*ldx + k]
700// Fixed accumulation order: lane l of a 16-lane sub-group takes the k pairs 2l, 2l+32, 2l+64, ... in order (two fp32
701// fused multiply-adds per pair), the 16 lane sums are then combined by the sub-group reduction (a fixed shuffle tree).
702// No atomics, no split-K, no dependence on scheduling: the same bits on every run.  oneMKL's GEMM for these shapes is
703// not repeatable on the Arc A750 (it accumulates the K split in an order that varies from launch to launch).
704// K must be even; W rows 4-byte aligned (any bf16 tensor from the pack is).
705namespace strata_bf16_det {
706constexpr int kLanes = 16, kSgPerWg = 4, kOut = 4;
707inline float bf16lo(uint32_t u) { return sycl::bit_cast<float>(u << 16); }
708inline float bf16hi(uint32_t u) { return sycl::bit_cast<float>(u & 0xFFFF0000u); }
709inline void gemm(sycl::queue& q, const uint16_t* X, int64_t ldx, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K,
710                 int64_t ldy, float beta) {
711    const int64_t nblk = (N + kOut - 1) / kOut;
712    const int64_t total_sg = T * nblk;
713    const int64_t wgs = (total_sg + kSgPerWg - 1) / kSgPerWg;
714    q.parallel_for(sycl::nd_range<1>(sycl::range<1>((size_t)(wgs * kSgPerWg * kLanes)), sycl::range<1>(kSgPerWg * kLanes)),
715                   [=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(16)]] {
716        const sycl::sub_group sg = it.get_sub_group();
717        const int64_t id = (int64_t) it.get_group(0) * kSgPerWg + (int64_t) sg.get_group_linear_id();
718        if (id >= total_sg) return;   // (whole sub-group: uniform)
719        const int64_t t = id / nblk, n0 = (id % nblk) * kOut;
720        const uint32_t* xr = reinterpret_cast<const uint32_t*>(X + t * ldx);
721        const uint32_t* wr[kOut];
722        float acc[kOut];
723        for (int o = 0; o < kOut; ++o) { wr[o] = reinterpret_cast<const uint32_t*>(W + (n0 + (o < N - n0 ? o : 0)) * K); acc[o] = 0.0f; }
724        const int lane = (int) sg.get_local_linear_id();
725        for (int64_t k2 = lane; k2 < K / 2; k2 += kLanes) {
726            const uint32_t xv = xr[k2];
727            const float x0 = bf16lo(xv), x1 = bf16hi(xv);
728            for (int o = 0; o < kOut; ++o) {
729                const uint32_t wv = wr[o][k2];
730                acc[o] = sycl::fma(bf16lo(wv), x0, acc[o]);
731                acc[o] = sycl::fma(bf16hi(wv), x1, acc[o]);
732            }
733        }
734        for (int o = 0; o < kOut; ++o) {
735            const float s = sycl::reduce_over_group(sg, acc[o], sycl::plus<float>());
736            if (lane == 0 && n0 + o < N) {
737                float* y = Y + t * ldy + n0 + o;
738                *y = beta == 0.0f ? s : sycl::fma(beta, *y, s);
739            }
740        }
741    });
742}
743}  // namespace strata_bf16_det
744
745namespace {
746// oneMKL's GEMM reads the last, partial tile of an operand from the wrong place when it lies more than 4 GiB into its
747// allocation (Arc A770, oneMKL 2026.1: a BF16 B placed past 4 GiB of a 10.5 GiB allocation gave its last 21 columns
748// wrong, and none below 4 GiB).  The prompt path borrows the top of the ~10 GiB expert cache for its buffers, so its
749// GEMMs met this and the prompt came out non-finite / garbage.  An operand past 4 GiB is copied into a scratch buffer
750// of the queue's own - a fresh allocation, so at offset 0 - and the GEMM runs on that.  Returns false, so the caller
751// runs the direct GEMM, when neither operand needs staging (the common, correct case).
752uint8_t* gemm_stage(size_t need, sycl::queue& q) {
753    static thread_local uint8_t* p = nullptr;
754    static thread_local size_t cap = 0;
755    if (need > cap) {
756        if (p != nullptr) {
757            q.wait();   // the queue is in-order but asynchronous: a previous staged GEMM may still read p
758            sycl::free(p, q);
759        }
760        p = (uint8_t*) sycl::malloc_device(need, q);
761        cap = p != nullptr ? need : 0;
762    }
763    return p;
764}
765inline bool staged_gemm(sycl::queue& q, void* handle, const uint16_t* W, int lda, const uint16_t* X, int ldb,
766                        dpct::library_data_t dt, int64_t N, int64_t T, int64_t K, float alpha, float beta,
767                        float* Y, int64_t ldy) {
768    // STRATA_SYCL_GEMM_NO_STAGE: the tests' negative control.  0.1.43: not on Battlemage either (the A770 oneMKL bug above did not
769    // show on a B70: 4K and 49K prompts, operands at 18 GiB into the cache arena, first-token logits byte-identical with and
770    // without staging; the 10 MB copy per expert was ~10% of a prompt).  STRATA_SYCL_GEMM_STAGE=1 stages there as before.
771    static const bool no_stage = std::getenv("STRATA_SYCL_GEMM_NO_STAGE") != nullptr ||
772        (strata::intel_gpu_gen(q.get_device()) == strata::IntelGpuGen::Battlemage && !(std::getenv("STRATA_SYCL_GEMM_STAGE") && std::getenv("STRATA_SYCL_GEMM_STAGE")[0] == '1'));
773    constexpr size_t k4G = 4ull << 30;
774    const size_t es = 2;
775    const size_t w_bytes = (size_t) lda * (size_t) N * es;   // W stored K x N, col-major (lda = K)
776    const size_t x_bytes = (size_t) ldb * (size_t) T * es;   // X stored ldb x T
777    const bool far_w = strata::device_offset_end(W, w_bytes) > k4G;
778    const bool far_x = strata::device_offset_end(X, x_bytes) > k4G;
779    if (no_stage || (!far_w && !far_x)) return false;
780    uint8_t* s = gemm_stage(w_bytes + x_bytes, q);
781    if (s == nullptr) {
782        std::fprintf(stderr, "strata: WARNING: a GEMM operand lies past 4 GiB and the %zu MiB staging buffer could not be "
783                             "allocated; the GEMM runs directly and may be wrong on this card\n",
784                     (w_bytes + x_bytes) >> 20);
785        return false;
786    }
787    uint8_t* sw = s;
788    uint8_t* sx = s + w_bytes;
789    if (far_w) q.memcpy(sw, W, w_bytes);
790    if (far_x) q.memcpy(sx, X, x_bytes);
791    const uint16_t* Wu = far_w ? (const uint16_t*) sw : W;
792    const uint16_t* Xu = far_x ? (const uint16_t*) sx : X;
793    ck(DPCT_CHECK_ERROR(dpct::blas::gemm(
794           (dpct::blas::descriptor_ptr) handle, oneapi::mkl::transpose::trans, oneapi::mkl::transpose::nontrans,
795           (int) N, (int) T, (int) K, &alpha, Wu, dt, lda, Xu, dt, ldb, &beta, Y,
796           dpct::library_data_t::real_float, (int) ldy, dpct::compute_type::f32)),
797       "cublasGemmEx (staged)");
798    return true;
799}
800}  // namespace
801
802// (#2091, CUDA Turing only) no FP16 activation image on this backend
803bool Gemm::bf16_converts_x() const { return false; }
804
805void Gemm::bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy,
806                float beta, int64_t ldx, bool /*x_f16*/) {
807    if (T <= 0 || N <= 0) return;
808    strata::kprof::Section kp_sec(strata::q_of(stream_), strata::kprof::enabled() ? "gemm bf16 N=" + std::to_string((long long) N) + " K=" + std::to_string((long long) K) : std::string());
809    if (ldy <= 0) ldy = N;
810    if (ldx <= K) ldx = 0;
811#ifdef STRATA_USE_HIP
812    // #313 (opt-in STRATA_WMMA_GEMM=1; STRATA_WMMA_BF16=0 excludes bf16): RDNA3 / RDNA3.5 WMMA dense GEMM, before
813    // hipBLASLt; it returns false for shapes it does not take (and off gfx11) and this falls through
814    static const bool wmma_on = [] { const char* v = std::getenv("STRATA_WMMA_GEMM"); return v && v[0] != 0 && v[0] != '0'; }();
815    static const bool bf16_on = [] { const char* v = std::getenv("STRATA_WMMA_BF16"); return !v || (v[0] != 0 && v[0] != '0'); }();
816    if (wmma_on && bf16_on && ldx == 0 && T >= 16 && (beta == 0.0f || beta == 1.0f) &&
817        strata_wmma_gemm_bf16(X, W, Y, T, N, K, ldy, beta, stream_)) {
818        return;
819    }
820#endif
821#if defined(__HIPCC__)
822    if (f16_io_) {   // X is the FP16 image (set_act_f16); W goes through the dequantization scratch as FP16
823        // the only accumulating BF16 product is the BF16X2 low part, which bf16x2_mode() turns off with this path
824        if (beta != 0.0f) { std::fprintf(stderr, "prefill gemm: an accumulating BF16 GEMM on the FP16 prompt path\n"); std::exit(1); }
825        const int64_t rows = std::min<int64_t>(N, scratch_elems_ / K);
826        if (rows <= 0) { std::fprintf(stderr, "prefill gemm: scratch too small for K=%lld\n", (long long) K); std::exit(1); }
827        for (int64_t r0 = 0; r0 < N; r0 += rows) {
828            const int64_t n = std::min(rows, N - r0);
829            bf16_to_f16_rows<<<1024, 256, 0, (cudaStream_t) stream_>>>(W + r0 * K, (__half*) scratch_, n * K);
830            f16_inplace(X, scratch_, Y + r0, T, n, K, ldy);
831        }
832        return;
833    }
834#endif
835    workload_trace::Scope trace("gemm.bf16_to_f32", stream_, T, N, K, ldx ? ldx : K, ldy);
836    const float alpha = 1.0f;
837    {   // CLEAN-6.0: the repeatable path for skinny outputs (see strata_bf16_det)
838        static const int det_mode = [] { const char* v = std::getenv("STRATA_SYCL_BF16_DET"); return v == nullptr || v[0] == 0 ? 1 : std::atoi(v); }();
839        const int64_t xs = ldx ? ldx : K;
840        if (det_mode != 0 && (K & 1) == 0 && (xs & 1) == 0 && N <= (det_mode == 2 ? (int64_t) 1 << 30 : (int64_t) 64) &&
841            (reinterpret_cast<uintptr_t>(X) & 3u) == 0 && (reinterpret_cast<uintptr_t>(W) & 3u) == 0) {
842            strata_bf16_det::gemm(*strata::q_of(stream_), X, xs, W, Y, T, N, K, ldy, beta);
843            return;
844        }
845    }
846#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)
847    if (try_hipblaslt(hipblaslt_state_, strata::prefill::hipblaslt::InputType::bf16, X, W, Y, T, N, K, ldy,
848                      beta, stream_, ldx)) {
849        STRATA_ABSORB_HIPBLAS_STICKY("hipBLASLt bf16");
850        return;
851    }
852#endif
853#if !defined(__HIPCC__)
854    if (const int path = K > 0 ? bf16_path() : 0; path == 1 && N > 1 && beta == 0.0f) {
855        // a single output row stays cuBLAS's GEMV, faster than the conversions; beta = 1: see above
856        const int64_t x_rows = std::max<int64_t>(1, std::min<int64_t>(T, kXSliceElems / K));
857        if (grow(tc_w_, tc_w_elems_, N * K) && grow(tc_x_, tc_x_elems_, x_rows * K)) {
858            bf16_to_f16(W, tc_w_, N * K, strata::q_of(stream_));
859            for (int64_t t0 = 0; t0 < T; t0 += x_rows) {
860                const int64_t n = std::min<int64_t>(x_rows, T - t0);
861                bf16_to_f16(X + t0 * K, tc_x_, n * K, strata::q_of(stream_));
862                f16(tc_x_, tc_w_, Y + t0 * ldy, n, N, K, ldy, beta);
863            }
864            return;
865        }
866    }
867#if defined(STRATA_EXPERIMENTAL_SM60)
868    else if (path == 2) {
869        // Pascal: fp32 copies (2 elements of the 2-byte buffers each).  Every tile is a disjoint block of Y, so each
870        // gets the caller's beta.
871        const int64_t x_rows = std::max<int64_t>(1, std::min<int64_t>(T, kXSliceElems / K));
872        if (grow(tc_w_, tc_w_elems_, 2 * N * K) && grow(tc_x_, tc_x_elems_, 2 * x_rows * K)) {
873            float* const wf = reinterpret_cast<float*>(tc_w_);
874            float* const xf = reinterpret_cast<float*>(tc_x_);
875            bf16_to_f32(W, wf, N * K, (cudaStream_t) stream_);
876            for (int64_t t0 = 0; t0 < T; t0 += x_rows) {
877                const int64_t n = std::min<int64_t>(x_rows, T - t0);
878                bf16_to_f32(X + t0 * K, xf, n * K, (cudaStream_t) stream_);
879                ck(cublasSgemm((cublasHandle_t) handle_, CUBLAS_OP_T, CUBLAS_OP_N, (int) N, (int) n, (int) K, &alpha,
880                               wf, (int) K, xf, (int) K, &beta, Y + t0 * ldy, (int) ldy),
881                   "cublasSgemm (bf16 on Pascal)");
882            }
883            return;
884        }
885    }
886#endif
887#endif
888    if (staged_gemm(*strata::q_of(stream_), handle_, W, (int) K, X, (int) (ldx ? ldx : K), dpct::library_data_t::real_bfloat16, N, T, K,
889                    alpha, beta, Y, ldy))
890        return;
891    // Column-major view: Y^T[N, T] = W[N, K] (stored K x N col-major, transposed) . X^T[K, T].
892    ck(DPCT_CHECK_ERROR(dpct::blas::gemm(
893           (dpct::blas::descriptor_ptr)handle_, oneapi::mkl::transpose::trans,
894           oneapi::mkl::transpose::nontrans, (int)N, (int)T, (int)K, &alpha, W,
895           dpct::library_data_t::real_bfloat16, (int)K, X,
896           dpct::library_data_t::real_bfloat16, (int)(ldx ? ldx : K), &beta, Y,
897           dpct::library_data_t::real_float, (int)ldy,
898           dpct::compute_type::f32)),
899       "cublasGemmEx");
900    STRATA_ABSORB_HIPBLAS_STICKY("cublasGemmEx");
901}
902
903void Gemm::f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy,
904               float beta) {
905    if (T <= 0 || N <= 0) return;
906    strata::kprof::Section kp_sec(strata::q_of(stream_), strata::kprof::enabled() ? "gemm f16 N=" + std::to_string((long long) N) + " K=" + std::to_string((long long) K) : std::string());
907    if (ldy <= 0) ldy = N;
908#ifdef STRATA_USE_HIP
909    // #313 (opt-in STRATA_WMMA_GEMM=1): RDNA3 / RDNA3.5 WMMA dense GEMM, before hipBLASLt (falls through when false)
910    static const bool wmma_on = [] { const char* v = std::getenv("STRATA_WMMA_GEMM"); return v && v[0] != 0 && v[0] != '0'; }();
911    static const bool pf_on = [] { const char* v = std::getenv("STRATA_PF_GEMM"); return v && v[0] == '1'; }();
912    static const int64_t pf_min_t = [] { const char* v = std::getenv("STRATA_PF_SWITCH_MIN_T"); return v ? (int64_t) std::atoll(v) : (int64_t) 0; }();
913    if (pf_on && T >= pf_min_t && strata_pf_gemm_f16(X, W, Y, T, N, K, ldy, beta, stream_)) return;   // S23: opt-in
914    if (wmma_on && T >= 16 && (beta == 0.0f || beta == 1.0f) &&
915        strata_wmma_gemm_f16(X, W, Y, T, N, K, ldy, beta, stream_)) {
916        return;
917    }
918#endif
919#if defined(__HIPCC__)
920    if (f16_io_ && beta == 0.0f) { f16_inplace(X, W, Y, T, N, K, ldy); return; }
921#endif
922    workload_trace::Scope trace("gemm.f16_to_f32", stream_, T, N, K, K, ldy);
923    const float alpha = 1.0f;
924#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)
925    if (try_hipblaslt(hipblaslt_state_, strata::prefill::hipblaslt::InputType::f16, X, W, Y, T, N, K, ldy,
926                      beta, stream_)) {
927        STRATA_ABSORB_HIPBLAS_STICKY("hipBLASLt f16");
928        return;
929    }
930#endif
931    if (staged_gemm(*strata::q_of(stream_), handle_, W, (int) K, X, (int) K, dpct::library_data_t::real_half, N, T, K, alpha, beta, Y, ldy))
932        return;
933    ck(DPCT_CHECK_ERROR(dpct::blas::gemm(
934           (dpct::blas::descriptor_ptr)handle_, oneapi::mkl::transpose::trans,
935           oneapi::mkl::transpose::nontrans, (int)N, (int)T, (int)K, &alpha, W,
936           dpct::library_data_t::real_half, (int)K, X,
937           dpct::library_data_t::real_half, (int)K, &beta, Y,
938           dpct::library_data_t::real_float, (int)ldy,
939           dpct::compute_type::f32)),
940       "cublasGemmEx f16");
941    STRATA_ABSORB_HIPBLAS_STICKY("cublasGemmEx f16");
942}
943
944#if defined(STRATA_PREFILL_MMQ) && defined(__HIPCC__)
945bool Gemm::native_mmq(const uint16_t* X, int type, const void* W, float* Y, int64_t T, int64_t N, int64_t K,
946                      int64_t ldy) {
947    namespace mmq = strata::prefill::mmq;
948    constexpr int64_t kRows = 1024, kMaxK = 8192;
949    static const bool enabled = [] {
950        const char* e = std::getenv("STRATA_DENSE_MMQ");
951        return e && e[0] == '1';
952    }();
953    if (!enabled || mmq_failed_ || !mmq::built() || !mmq::fits(type, N)) return false;
954    // K must be a multiple of 256: llama.cpp's MMQ loads the weights in 256-value K chunks, and the
955    // chunk past a partial row reads past the row (the next row's bytes - or, for the last weight
956    // row, bytes past the tensor, which no caller guarantees to be zeros). The MoE path is safe
957    // because its gather buffers carry a zeroed tail; a dense tensor is passed as-is, so a K that
958    // is not a full chunk multiple (e.g. the 640-value shared-expert down: 20 blocks of 32) stays on
959    // the dequantize + cuBLAS path.
960    if (K > kMaxK || K % 256 != 0) return false;
961    int64_t R = scratch_elems_ / (2 * K);   // FP32 activations for a chunk fit in the FP16 dequant scratch
962    if (R > kRows) R = kRows;
963    if (R > T) R = T;
964    if (R < 1) return false;
965    if (ldy <= 0) ldy = N;
966
967    const auto up = [](size_t v) { return (v + 255) & ~(size_t) 255; };
968    const size_t ident_off = up(mmq::q8_bytes(kRows, kMaxK));
969    const size_t bounds_off = ident_off + up((size_t) kRows * 4);
970    if (!mmq_buf_) {
971        if (cudaMalloc(&mmq_buf_, bounds_off + 256) != cudaSuccess) {
972            cudaGetLastError();
973            mmq_failed_ = true;
974            return false;
975        }
976        mmq_ctx_ = new mmq::Context();
977        mmq::iota((int32_t*) ((uint8_t*) mmq_buf_ + ident_off), kRows, stream_);
978        std::fprintf(stderr, "prefill gemm: dense MMQ on (STRATA_DENSE_MMQ=1)\n");
979    }
980    void* xq = mmq_buf_;
981    const int32_t* ident = (const int32_t*) ((uint8_t*) mmq_buf_ + ident_off);
982    int32_t* bounds = (int32_t*) ((uint8_t*) mmq_buf_ + bounds_off);
983    float* xf = (float*) scratch_;
984    auto* ctx = static_cast<mmq::Context*>(mmq_ctx_);
985
986    for (int64_t r0 = 0; r0 < T; r0 += R) {
987        const int64_t rows = (T - r0 < R) ? T - r0 : R;
988        mmq::f16_to_f32(X + r0 * K, xf, rows * K, stream_);
989        mmq::quantize(xf, nullptr, xq, type, K, K, rows, stream_);
990        mmq::set_bounds(bounds, (int32_t) rows, stream_);
991        mmq::Product p;
992        p.w = W;
993        p.type = type;
994        p.w_rows = N;
995        p.w_cols = K;
996        p.expert_bytes = mmq::matrix_bytes(type, N, K);
997        p.n = 1;
998        p.xq = xq;
999        p.bounds = bounds;
1000        p.ids = ident;
1001        p.total_rows = rows;
1002        p.max_rows = rows;
1003        p.dst = Y + r0 * ldy;
1004        p.ld_dst = ldy;
1005        ctx->run(p, stream_);
1006    }
1007    return true;
1008}
1009#endif
1010void Gemm::f16_inplace(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy) {
1011#if defined(__HIPCC__)
1012    const float one = 1.0f, zero = 0.0f;
1013    ck(cublasGemmEx((cublasHandle_t) handle_, CUBLAS_OP_T, CUBLAS_OP_N, (int) N, (int) T, (int) K, &one, W, CUDA_R_16F,
1014                    (int) K, X, CUDA_R_16F, (int) K, &zero, Y, CUDA_R_16F, (int) (2 * ldy), CUBLAS_COMPUTE_32F,
1015                    CUBLAS_GEMM_DEFAULT),
1016       "cublasGemmEx f16 out");
1017    static const bool dbg_nan = std::getenv("STRATA_DBG_NAN") != nullptr;
1018    widen_rows_f16<<<(unsigned) T, 256, 0, (cudaStream_t) stream_>>>(Y, N, ldy, dbg_nan ? 1 : 0);
1019    if (dbg_nan) {   // debug only: a sync per GEMM
1020        unsigned long long bad = 0, zero_count = 0;
1021        (void) hipStreamSynchronize((hipStream_t) stream_);
1022        if (hipMemcpyFromSymbol(&bad, HIP_SYMBOL(g_f16_nonfinite), sizeof bad) == hipSuccess && bad != 0) {
1023            std::fprintf(stderr, "strata prefill: STRATA_DBG_NAN: %llu non-finite FP16 GEMM outputs (T=%lld N=%lld K=%lld; FP16 ends at 65504)%s",
1024                         bad, (long long) T, (long long) N, (long long) K, "\n");
1025            (void) hipMemcpyToSymbol(HIP_SYMBOL(g_f16_nonfinite), &zero_count, sizeof zero_count);
1026        }
1027    }
1028#else
1029    (void) X; (void) W; (void) Y; (void) T; (void) N; (void) K; (void) ldy;
1030#endif
1031}
1032
1033void Gemm::native(const uint16_t* X, int ggml_type, const void* W_blocks, float* Y, int64_t T, int64_t N, int64_t K,
1034                  int64_t ldy, float beta, int64_t ldx) {
1035    if (T <= 0 || N <= 0) return;
1036    if (ldy <= 0) ldy = N;
1037    if (ldx <= 0) ldx = K;
1038    auto multiply = [&](int64_t n, float* out) {
1039        workload_trace::Scope trace("gemm.native_f16_to_f32", stream_, T, n, K, ldx, ldy, ggml_type);
1040        const float alpha = 1.0f;
1041        ck(DPCT_CHECK_ERROR(dpct::blas::gemm(
1042               (dpct::blas::descriptor_ptr)handle_, oneapi::mkl::transpose::trans,
1043               oneapi::mkl::transpose::nontrans, (int)n, (int)T, (int)K, &alpha, scratch_,
1044               dpct::library_data_t::real_half, (int)K, X,
1045               dpct::library_data_t::real_half, (int)ldx, &beta, out,
1046               dpct::library_data_t::real_float, (int)ldy,
1047               dpct::compute_type::f32)),
1048           "cublasGemmEx native");
1049    };
1050    if (N * K > scratch_elems_) {
1051        // Too large for the scratch at once: in row slices.
1052        const int64_t rows = scratch_elems_ / K;
1053        if (rows <= 0) { std::fprintf(stderr, "prefill gemm: scratch too small for K=%lld\n", (long long) K); std::exit(1); }
1054        if (ldy <= 0) ldy = N;
1055        for (int64_t r0 = 0; r0 < N; r0 += rows) {
1056            const int64_t n = (N - r0 < rows) ? N - r0 : rows;
1057            strata::kernels::dequant_f16(ggml_type, W_blocks, r0, n, K, scratch_, stream_);
1058            multiply(n, Y + r0);
1059        }
1060        return;
1061    }
1062    strata::kernels::dequant_f16(ggml_type, W_blocks, 0, N, K, scratch_, stream_);
1063    multiply(N, Y);
1064}
1065
1066}  // namespace strata::prefill