okami.mom/strata

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

Niko1221Merge f-amd-f16 8d7f997d4 into f-p4-int (the Radeon 780M on Linux reads its 16-bit prompt GEMMs FP16 in and out by default; the hyper-connection up-mix kernel has an FP16 path)27cf035e5

main
79.8 KiB1523 linesraw
1// src/prefill/gemm.cu - see include/strata/prefill/gemm.hpp.
2#include "strata/prefill/gemm.hpp"
3#include "strata/kernels/dequant_bf16.hpp"
4#include "strata/core/arch_defaults.hpp"   // prompt_f16_resolve (inline)
5#if defined(STRATA_PREFILL_MMQ) && defined(__HIPCC__)
6#include "strata/prefill/mmq_ids_margin.hpp"
7#include "strata/prefill/moe_mmq.hpp"
8#endif
9
10#ifdef STRATA_USE_HIP
11#include "wmma_gemm.h"
12#endif
13
14#include <cublas_v2.h>
15#include <cuda_fp16.h>
16#include <cuda_runtime.h>
17
18#include <algorithm>
19#include <atomic>
20
21#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)
22// The HIP compatibility shim maps CUDA shuffle spellings to Strata helpers.
23// hipBLASLt's public headers declare native HIP shuffle functions, so keep
24// those declarations from being macro-expanded in this translation unit.
25#undef __shfl_xor_sync
26#undef __shfl_down_sync
27#undef __shfl_up_sync
28#undef __shfl_sync
29#undef __ballot_sync
30#endif
31
32#include <algorithm>
33#include <cctype>
34#include <initializer_list>
35#include <climits>
36#include <cstdio>
37#include <cstdlib>
38#include <cstring>
39#include <memory>
40
41#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)
42#include "hipblaslt_tuning.hpp"
43#if defined(_WIN32)
44#ifndef NOMINMAX
45#define NOMINMAX
46#endif
47#ifndef WIN32_LEAN_AND_MEAN
48#define WIN32_LEAN_AND_MEAN
49#endif
50#include <windows.h>
51#else
52#include <unistd.h>
53#endif
54#include <hip/hip_runtime_api.h>
55#include <hipblaslt/hipblaslt.h>
56#include <hipblaslt/hipblaslt-ext.hpp>
57#include <map>
58#include <set>
59#include <tuple>
60#endif
61#if defined(__HIPCC__) && defined(STRATA_ROCBLAS_AVAILABLE)
62#include "rocblas_tuning.hpp"
63#include "strata/core/amd_community.hpp"
64#include <hip/hip_runtime_api.h>
65#include <rocblas/rocblas.h>
66#include <filesystem>
67#include <map>
68#include <string>
69#include <system_error>
70#include <tuple>
71#endif
72
73#if defined(__HIPCC__)
74#include <hip/hip_fp16.h>
75#endif
76
77namespace strata::prefill {
78namespace {
79#if defined(__HIPCC__)
80// STRATA_F16_RANGE (gemm_set_f16_range): the largest |value| and the count beyond 65504 / non-finite, for the BF16
81// weights converted to FP16 (slot 0, bf16_to_f16_rows) and the FP16 GEMM outputs widened (slot 1, widen_rows_f16 -
82// an output rocBLAS wrote as FP16 is Inf there, not saturated).  As the activation counter in kernels.cu.
83__device__ int g_f16_range_on_g = 0;
84__device__ unsigned g_f16_range_max_g[2] = {0, 0};
85__device__ unsigned long long g_f16_range_over_g[2] = {0, 0};
86__device__ __forceinline__ void f16_range_note_g(int k, float f) {
87    const float a = fabsf(f);
88    const unsigned bits = __float_as_uint(a);
89    if (bits > g_f16_range_max_g[k]) atomicMax(&g_f16_range_max_g[k], bits);
90    if (a > 65504.0f || isnan(f)) atomicAdd(&g_f16_range_over_g[k], 1ull);
91}
92// 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.
93// 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
94// registers, the block syncs, then writes its floats - which only cover halves of blocks already read.
95// STRATA_DBG_NAN: the FP16 outputs that are not finite (an FP32-accumulated sum past 65504 becomes inf in FP16).
96__device__ unsigned long long g_f16_nonfinite = 0;
97__global__ void widen_rows_f16(float* __restrict__ Y, int64_t n, int64_t ldy, int count_nonfinite) {
98    float* y = Y + (int64_t) blockIdx.x * ldy;
99    const __half* h = reinterpret_cast<const __half*>(y);
100    const int64_t nb = (n + blockDim.x - 1) / blockDim.x;
101    for (int64_t b = nb - 1; b >= 0; --b) {
102        const int64_t c = b * blockDim.x + threadIdx.x;
103        const float v = c < n ? __half2float(h[c]) : 0.0f;
104        if (count_nonfinite && c < n && !isfinite(v)) atomicAdd(&g_f16_nonfinite, 1ull);
105        if (c < n && g_f16_range_on_g) f16_range_note_g(1, v);
106        __syncthreads();
107        if (c < n) y[c] = v;
108        __syncthreads();
109    }
110}
111// BF16 weight rows -> FP16, saturated (bench/results/2026-10-04-rdna2-fp16-prompt: none leaves FP16's range)
112__global__ void bf16_to_f16_rows(const uint16_t* __restrict__ s, __half* __restrict__ d, int64_t n) {
113    for (int64_t i = blockIdx.x * (int64_t) blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) {
114        const float f = __uint_as_float((uint32_t) s[i] << 16);
115        if (g_f16_range_on_g) f16_range_note_g(0, f);
116        d[i] = __float2half(isnan(f) ? f : fminf(fmaxf(f, -65504.0f), 65504.0f));   // as hf_sat: a NaN stays NaN
117    }
118}
119#endif
120}  // namespace
121
122void gemm_set_f16_range(bool on) {
123#if defined(__HIPCC__)
124    const int v = on ? 1 : 0;
125    if (cudaMemcpyToSymbol(g_f16_range_on_g, &v, sizeof v) != cudaSuccess) {
126        std::fprintf(stderr, "prefill gemm: setting the FP16 range check failed: %s\n", cudaGetErrorString(cudaGetLastError()));
127        std::exit(1);
128    }
129#else
130    (void) on;
131#endif
132}
133bool gemm_f16_range_read(float max_abs[2], unsigned long long over[2], bool reset) {
134#if defined(__HIPCC__)
135    unsigned bits[2] = {0, 0}; unsigned long long o[2] = {0, 0};
136    if (cudaMemcpyFromSymbol(bits, g_f16_range_max_g, sizeof bits) != cudaSuccess ||
137        cudaMemcpyFromSymbol(o, g_f16_range_over_g, sizeof o) != cudaSuccess) { cudaGetLastError(); return false; }
138    for (int k = 0; k < 2; ++k) { union { unsigned u; float f; } c; c.u = bits[k]; max_abs[k] = c.f; over[k] = o[k]; }
139    if (reset) {
140        const unsigned z[2] = {0, 0}; const unsigned long long zz[2] = {0, 0};
141        cudaMemcpyToSymbol(g_f16_range_max_g, z, sizeof z); cudaMemcpyToSymbol(g_f16_range_over_g, zz, sizeof zz);
142    }
143    return true;
144#else
145    (void) max_abs; (void) over; (void) reset;
146    return false;
147#endif
148}
149
150namespace {
151
152void ck(cublasStatus_t s, const char* what) {
153    if (s != CUBLAS_STATUS_SUCCESS) {
154        std::fprintf(stderr, "prefill gemm: %s: cuBLAS status %d\n", what, (int) s);
155        std::exit(1);
156    }
157}
158
159// #247/#325: on Windows (seen on gfx1201), hipBLAS can return success with the correct BF16/FP16 product for some
160// shapes (hc up once T >= 96, the router) and still leave hipErrorInvalidValue set, which the next kernel's error
161// check turns into an exit. The multiply has finished, so that one stale error is cleared after a GEMM that succeeded;
162// any other error still stops the engine. Windows only: on Linux a stale hipErrorInvalidValue is a real error from
163// an earlier call and keeps being reported. A no-op everywhere else (CUDA compiles none of it).
164#if defined(__HIPCC__) && defined(_WIN32)
165void absorb_hipblas_sticky(const char* what) {
166    const hipError_t sticky = hipGetLastError();
167    if (sticky == hipSuccess || sticky == hipErrorInvalidValue) return;
168    std::fprintf(stderr, "prefill gemm: %s left %s\n", what, hipGetErrorString(sticky));
169    std::exit(1);
170}
171#define STRATA_ABSORB_HIPBLAS_STICKY(what) absorb_hipblas_sticky(what)
172#else
173#define STRATA_ABSORB_HIPBLAS_STICKY(what) ((void) 0)
174#endif
175
176// A setup call whose failure the engine survives (the handle keeps its defaults), as before #240 - but said.
177void note(cublasStatus_t s, const char* what) {
178    if (s != CUBLAS_STATUS_SUCCESS) std::fprintf(stderr, "prefill gemm: %s: cuBLAS status %d (continuing)\n", what, (int) s);
179}
180
181#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)
182struct HipLtCallKey {
183    strata::prefill::hipblaslt::InputType type;
184    int t;
185    int n;
186    int k;
187    int ldy;
188    uint32_t beta_bits;
189
190    bool operator<(const HipLtCallKey& other) const {
191        return std::tie(type, n, k, ldy, t, beta_bits) <
192               std::tie(other.type, other.n, other.k, other.ldy, other.t, other.beta_bits);
193    }
194};
195
196struct HipLtCachedAlgo {
197    bool supported = false;
198    hipblasLtMatmulAlgo_t algo{};
199    size_t workspace_bytes = 0;
200};
201
202struct HipLtState {
203    hipblasLtHandle_t handle = nullptr;
204    void* workspace = nullptr;
205    size_t workspace_bytes = 0;
206    strata::prefill::hipblaslt::TuningTable table;
207    std::map<HipLtCallKey, HipLtCachedAlgo> cache;
208    uint64_t lt_launches = 0;
209    uint64_t fallbacks = 0;
210    std::set<std::tuple<strata::prefill::hipblaslt::InputType, int, int, int, int>> fallback_shapes;
211
212    ~HipLtState() {
213        if (std::getenv("STRATA_HIPBLASLT_VERBOSE")) {
214            std::fprintf(stderr, "prefill gemm: hipBLASLt summary launches=%llu fallbacks=%llu unique_fallback_shapes=%zu\n",
215                         (unsigned long long) lt_launches, (unsigned long long) fallbacks, fallback_shapes.size());
216            for (const auto& shape : fallback_shapes) {
217                const auto type = std::get<0>(shape);
218                std::fprintf(stderr, "prefill gemm: fallback shape dtype=%s T=%d N=%d K=%d ldy=%d\n",
219                             type == strata::prefill::hipblaslt::InputType::bf16 ? "bf16" : "f16",
220                             std::get<1>(shape), std::get<2>(shape), std::get<3>(shape), std::get<4>(shape));
221            }
222        }
223        if (handle) hipblasLtDestroy(handle);
224    }
225};
226
227struct HipLtDescriptors {
228    hipblasLtMatmulDesc_t op = nullptr;
229    hipblasLtMatrixLayout_t a = nullptr;
230    hipblasLtMatrixLayout_t b = nullptr;
231    hipblasLtMatrixLayout_t c = nullptr;
232
233    ~HipLtDescriptors() {
234        if (op) hipblasLtMatmulDescDestroy(op);
235        if (a) hipblasLtMatrixLayoutDestroy(a);
236        if (b) hipblasLtMatrixLayoutDestroy(b);
237        if (c) hipblasLtMatrixLayoutDestroy(c);
238    }
239
240    bool init(hipDataType type, int t, int n, int k, int ldy, int ldb = 0) {
241        const hipblasOperation_t trans_a = HIPBLAS_OP_T;
242        const hipblasOperation_t trans_b = HIPBLAS_OP_N;
243        if (hipblasLtMatmulDescCreate(&op, HIPBLAS_COMPUTE_32F, HIP_R_32F) != HIPBLAS_STATUS_SUCCESS ||
244            hipblasLtMatmulDescSetAttribute(op, HIPBLASLT_MATMUL_DESC_TRANSA, &trans_a, sizeof(trans_a)) !=
245                HIPBLAS_STATUS_SUCCESS ||
246            hipblasLtMatmulDescSetAttribute(op, HIPBLASLT_MATMUL_DESC_TRANSB, &trans_b, sizeof(trans_b)) !=
247                HIPBLAS_STATUS_SUCCESS ||
248            hipblasLtMatrixLayoutCreate(&a, type, k, n, k) != HIPBLAS_STATUS_SUCCESS ||
249            hipblasLtMatrixLayoutCreate(&b, type, k, t, ldb > k ? ldb : k) != HIPBLAS_STATUS_SUCCESS ||
250            hipblasLtMatrixLayoutCreate(&c, HIP_R_32F, n, t, ldy) != HIPBLAS_STATUS_SUCCESS) {
251            return false;
252        }
253        return true;
254    }
255};
256
257// The engine package's own tuning folder (<engine folder>/tuning), for a start that did not come through the launcher (a hand-made
258// config, a CLI run): without a table the prompt GEMMs fall back to plain hipBLAS and a Strix Halo reads prompts at half speed
259// (340 against 690 tok/s, IQ3_S 4K).  The launcher sets STRATA_HIPBLASLT_TUNING itself; this is the same table found by the engine.
260std::string own_tuning_dir() {
261#if defined(_WIN32)
262    char p[4096] = {};
263    const DWORD n = GetModuleFileNameA(nullptr, p, (DWORD) sizeof(p));
264    std::string s(p, n);
265    const size_t k = s.find_last_of("\\/");
266    return k == std::string::npos ? std::string() : s.substr(0, k + 1) + "tuning/";
267#else
268    char p[4096] = {};
269    const ssize_t n = readlink("/proc/self/exe", p, sizeof(p) - 1);
270    std::string s(p, n > 0 ? (size_t) n : 0);
271    const size_t k = s.find_last_of('/');
272    return k == std::string::npos ? std::string() : s.substr(0, k + 1) + "tuning/";
273#endif
274}
275
276std::unique_ptr<HipLtState> create_hipblaslt_state(void* workspace, size_t workspace_bytes) {
277    std::string path_own;
278    const char* path = std::getenv("STRATA_HIPBLASLT_TUNING");
279    bool from_package = false, table_forced = false;
280    if (!path || !*path) {
281        const char* sw = std::getenv("STRATA_HIPBLASLT_TABLE");     // the launcher's switch (strata_control/hipblaslt_tuning.py): off / on / auto
282        std::string low = sw != nullptr ? sw : "";                   // trimmed and lower case, as the launcher reads it
283        while (!low.empty() && std::isspace((unsigned char) low.back())) low.pop_back();
284        while (!low.empty() && std::isspace((unsigned char) low.front())) low.erase(low.begin());
285        for (char& ch : low) ch = (char) std::tolower((unsigned char) ch);
286        const auto word = [&](std::initializer_list<const char*> ws) {
287            for (const char* w : ws) if (low == w) return true;
288            return false;
289        };
290        if (word({"off", "0", "no", "false", "none", "disable", "disabled"})) return nullptr;   // never the packaged table
291        table_forced = word({"on", "1", "yes", "true", "force", "enable", "enabled"});          // any card that has a table beside the engine
292        from_package = true;                                          // the file is found below, once the card and the version are known
293    }
294
295    auto state = std::make_unique<HipLtState>();
296    state->workspace = workspace;
297    state->workspace_bytes = workspace_bytes;
298    if (hipblasLtCreate(&state->handle) != HIPBLAS_STATUS_SUCCESS) {
299        std::fprintf(stderr, "prefill gemm: hipBLASLt handle creation failed; using hipBLASEx\n");
300        return nullptr;
301    }
302
303    int version = 0;
304    if (hipblasLtGetVersion(state->handle, &version) != HIPBLAS_STATUS_SUCCESS) {
305        std::fprintf(stderr, "prefill gemm: hipBLASLt version query failed; using hipBLASEx\n");
306        return nullptr;
307    }
308    int device = 0;
309    hipDeviceProp_t properties{};
310    if (hipGetDevice(&device) != hipSuccess || hipGetDeviceProperties(&properties, device) != hipSuccess) {
311        std::fprintf(stderr, "prefill gemm: HIP device query failed; using hipBLASEx\n");
312        return nullptr;
313    }
314    std::string arch(properties.gcnArchName);
315    const auto suffix = arch.find(':');
316    if (suffix != std::string::npos) arch.resize(suffix);
317
318    if (from_package) {
319        // Unset or "auto": only Strix Halo (gfx1151) takes the packaged table by itself, the owner's decision of 2026-10-19 (the same
320        // rule as AUTO_ARCHS in strata_control/hipblaslt_tuning.py): on other cards the table changes the answers' last digits for ~1%
321        // (gfx1201), so they take it with STRATA_HIPBLASLT_TABLE=on only.
322        if (!table_forced && arch != "gfx1151") return nullptr;
323        const std::string dir = own_tuning_dir();
324        if (dir.empty()) return nullptr;
325        path_own = dir + arch + "-hipblaslt-" + std::to_string(version) + ".txt";
326        std::FILE* f = std::fopen(path_own.c_str(), "rb");
327        if (f == nullptr) return nullptr;       // no table for this card and hipBLASLt version beside the engine: plain hipBLAS as before
328        std::fclose(f);
329        path = path_own.c_str();
330    }
331    std::string error;
332    if (!state->table.load(path, arch, version, error)) {
333        std::fprintf(stderr, "prefill gemm: %s; using hipBLASEx\n", error.c_str());
334        return nullptr;
335    }
336    std::fprintf(stderr, "prefill gemm: hipBLASLt tuning enabled (%zu rows, %s, version %d)\n",
337                 state->table.rows().size(), arch.c_str(), version);
338    return state;
339}
340
341HipLtCachedAlgo resolve_hipblaslt_algo(HipLtState& state, strata::prefill::hipblaslt::InputType type, int t,
342                                       int n, int k, int ldy, float beta) {
343    uint32_t beta_bits = 0;
344    static_assert(sizeof(beta_bits) == sizeof(beta));
345    std::memcpy(&beta_bits, &beta, sizeof(beta));
346    const HipLtCallKey key{type, t, n, k, ldy, beta_bits};
347    const auto cached = state.cache.find(key);
348    if (cached != state.cache.end()) return cached->second;
349
350    HipLtCachedAlgo resolved;
351    const bool verbose = std::getenv("STRATA_HIPBLASLT_VERBOSE") != nullptr;
352    const auto* row = state.table.closest(type, n, k, ldy, t);
353    if (!row) {
354        if (verbose) {
355            std::fprintf(stderr, "prefill gemm: Lt fallback; no calibration for dtype=%s T=%d N=%d K=%d ldy=%d\n",
356                         type == strata::prefill::hipblaslt::InputType::bf16 ? "bf16" : "f16", t, n, k, ldy);
357        }
358        return state.cache.emplace(key, resolved).first->second;
359    }
360
361    HipLtDescriptors desc;
362    const hipDataType input_type = type == strata::prefill::hipblaslt::InputType::bf16 ? HIP_R_16BF : HIP_R_16F;
363    if (!desc.init(input_type, t, n, k, ldy)) {
364        return state.cache.emplace(key, resolved).first->second;
365    }
366
367    std::vector<int> solution_ids{row->solution_id};
368    std::vector<hipblasLtMatmulHeuristicResult_t> candidates;
369    if (hipblaslt_ext::getAlgosFromIndex(state.handle, solution_ids, candidates) != HIPBLAS_STATUS_SUCCESS ||
370        candidates.empty() || candidates.front().state != HIPBLAS_STATUS_SUCCESS ||
371        hipblaslt_ext::getIndexFromAlgo(candidates.front().algo) != row->solution_id) {
372        if (verbose) {
373            std::fprintf(stderr, "prefill gemm: Lt fallback; solution %d unavailable for T=%d N=%d K=%d ldy=%d\n",
374                         row->solution_id, t, n, k, ldy);
375        }
376        return state.cache.emplace(key, resolved).first->second;
377    }
378
379    const float alpha = 1.0f;
380    size_t required_workspace = 0;
381    auto algo = candidates.front().algo;
382    if (hipblaslt_ext::matmulIsAlgoSupported(state.handle, desc.op, &alpha, desc.a, desc.b, &beta, desc.c, desc.c,
383                                             algo, required_workspace) != HIPBLAS_STATUS_SUCCESS) {
384        if (verbose) {
385            std::fprintf(stderr, "prefill gemm: Lt fallback; solution %d rejects actual T=%d N=%d K=%d ldy=%d beta=%.9g\n",
386                         row->solution_id, t, n, k, ldy, beta);
387        }
388        return state.cache.emplace(key, resolved).first->second;
389    }
390
391    resolved.supported = true;
392    resolved.algo = algo;
393    resolved.workspace_bytes = required_workspace;
394    if (verbose) {
395        std::fprintf(stderr,
396                     "prefill gemm: Lt solution=%d dtype=%s T=%d N=%d K=%d ldy=%d beta=%.9g workspace=%zu\n",
397                     row->solution_id, type == strata::prefill::hipblaslt::InputType::bf16 ? "bf16" : "f16", t, n,
398                     k, ldy, beta, required_workspace);
399    }
400    return state.cache.emplace(key, resolved).first->second;
401}
402
403// the hipBLASLt solution index the tuning table gives this call (-1: none / unsupported)
404int hipblaslt_solution_for(void* opaque_state, strata::prefill::hipblaslt::InputType type, int64_t t, int64_t n, int64_t k,
405                           int64_t ldy, float beta) {
406    auto* state = static_cast<HipLtState*>(opaque_state);
407    if (!state || t <= 0 || n <= 0 || k <= 0 || t > INT_MAX || n > INT_MAX || k > INT_MAX || ldy > INT_MAX || ldy < n) return -1;
408    const auto resolved = resolve_hipblaslt_algo(*state, type, (int) t, (int) n, (int) k, (int) ldy, beta);
409    if (!resolved.supported || resolved.workspace_bytes > state->workspace_bytes) return -1;
410    auto algo = resolved.algo;
411    return hipblaslt_ext::getIndexFromAlgo(algo);
412}
413
414bool try_hipblaslt(void* opaque_state, strata::prefill::hipblaslt::InputType type, const uint16_t* x,
415                   const uint16_t* w, float* y, int64_t t, int64_t n, int64_t k, int64_t ldy, float beta,
416                   void* stream, int64_t ldx = 0) {
417    auto* state = static_cast<HipLtState*>(opaque_state);
418    if (!state || t <= 0 || n <= 0 || k <= 0 || t > INT_MAX || n > INT_MAX || k > INT_MAX || ldy > INT_MAX ||
419        ldy < n) {
420        return false;
421    }
422    const auto resolved = resolve_hipblaslt_algo(*state, type, (int) t, (int) n, (int) k, (int) ldy, beta);
423    if (!resolved.supported) {
424        ++state->fallbacks;
425        state->fallback_shapes.emplace(type, (int) t, (int) n, (int) k, (int) ldy);
426        return false;
427    }
428    if (resolved.workspace_bytes > state->workspace_bytes) {
429        ++state->fallbacks;
430        state->fallback_shapes.emplace(type, (int) t, (int) n, (int) k, (int) ldy);
431        if (std::getenv("STRATA_HIPBLASLT_VERBOSE")) {
432            std::fprintf(stderr, "prefill gemm: Lt fallback; solution needs %zu workspace bytes, have %zu\n",
433                         resolved.workspace_bytes, state->workspace_bytes);
434        }
435        return false;
436    }
437
438    HipLtDescriptors desc;
439    const hipDataType input_type = type == strata::prefill::hipblaslt::InputType::bf16 ? HIP_R_16BF : HIP_R_16F;
440    if (!desc.init(input_type, (int) t, (int) n, (int) k, (int) ldy, (int) ldx)) return false;
441    const float alpha = 1.0f;
442    const hipblasStatus_t status = hipblasLtMatmul(state->handle, desc.op, &alpha, w, desc.a, x, desc.b, &beta, y,
443                                                   desc.c, y, desc.c, &resolved.algo, state->workspace,
444                                                   state->workspace_bytes, (hipStream_t) stream);
445    if (status == HIPBLAS_STATUS_SUCCESS) {
446        ++state->lt_launches;
447        return true;
448    }
449
450    std::fprintf(stderr, "prefill gemm: hipBLASLt launch failed with status %d\n", (int) status);
451    if (beta != 0.0f) {
452        std::fprintf(stderr, "prefill gemm: refusing a fallback after hipBLASLt failed with nonzero beta\n");
453        std::exit(1);
454    }
455    auto* mutable_state = static_cast<HipLtState*>(opaque_state);
456    uint32_t beta_bits = 0;
457    std::memcpy(&beta_bits, &beta, sizeof(beta_bits));
458    auto cached = mutable_state->cache.find(HipLtCallKey{type, (int) t, (int) n, (int) k, (int) ldy, beta_bits});
459    if (cached != mutable_state->cache.end()) cached->second.supported = false;
460    ++mutable_state->fallbacks;
461    mutable_state->fallback_shapes.emplace(type, (int) t, (int) n, (int) k, (int) ldy);
462    return false;
463}
464#endif
465
466#if defined(__HIPCC__) && defined(STRATA_ROCBLAS_AVAILABLE)
467// The rocBLAS solution table of f16_inplace (STRATA_ROCBLAS_TUNING: a table file, or a directory holding
468// <arch>-rocblas-<version>.txt for this card and rocBLAS build; src/prefill/rocblas_tuning.hpp).  rocBLAS's own
469// pick for some shapes is up to 6x slower than the best kernel it holds for them (gfx1030: tools/hip/tune_rocblas.cpp).
470struct RocBlasState {
471    rocblas_handle handle = nullptr;
472    strata::prefill::rocblas_tuning::Table table;
473    struct Pick { bool tuned = false; int solution = 0; int refusals = 0; };
474    std::map<std::tuple<int, int, int, int>, Pick> cache;   // (T, N, K, ldy) -> the solution to run, or the default
475    uint64_t tuned_launches = 0;
476    uint64_t fallbacks = 0;
477
478    ~RocBlasState() {
479        if (std::getenv("STRATA_ROCBLAS_VERBOSE")) {
480            std::fprintf(stderr, "prefill gemm: rocBLAS tuning summary tuned_launches=%llu fallbacks=%llu\n",
481                         (unsigned long long) tuned_launches, (unsigned long long) fallbacks);
482        }
483        if (handle) rocblas_destroy_handle(handle);
484    }
485};
486
487std::unique_ptr<RocBlasState> create_rocblas_state(void* stream) {
488    const char* path = std::getenv("STRATA_ROCBLAS_TUNING");
489    if (!path || !*path) return nullptr;
490    auto state = std::make_unique<RocBlasState>();
491    if (rocblas_create_handle(&state->handle) != rocblas_status_success) {
492        std::fprintf(stderr, "prefill gemm: rocBLAS handle creation failed; its default kernels run\n");
493        return nullptr;
494    }
495    rocblas_set_stream(state->handle, (hipStream_t) stream);
496    char version[128] = {0};
497    if (rocblas_get_version_string(version, sizeof version) != rocblas_status_success) {
498        std::fprintf(stderr, "prefill gemm: rocBLAS version query failed; its default kernels run\n");
499        return nullptr;
500    }
501    int device = 0;
502    hipDeviceProp_t properties{};
503    if (hipGetDevice(&device) != hipSuccess || hipGetDeviceProperties(&properties, device) != hipSuccess) {
504        std::fprintf(stderr, "prefill gemm: HIP device query failed; rocBLAS's default kernels run\n");
505        return nullptr;
506    }
507    std::string arch(properties.gcnArchName);
508    if (const auto suffix = arch.find(':'); suffix != std::string::npos) arch.resize(suffix);
509    std::filesystem::path file(path);
510    std::error_code ec;
511    if (std::filesystem::is_directory(file, ec)) {
512        // the table of this card and this rocBLAS build (its version string, trailing dots dropped)
513        std::string tag(version);
514        while (!tag.empty() && tag.back() == '.') tag.pop_back();
515        file /= arch + "-rocblas-" + tag + ".txt";
516    }
517    // The community-made tables (strata/core/amd_community.hpp) load only with STRATA_AMD_COMMUNITY_TUNING on (the default).
518    if (!strata::amd_community::rocblas_table_allowed(arch, version)) {
519        std::fprintf(stderr, "prefill gemm: the rocBLAS table for %s / %s is community-made and STRATA_AMD_COMMUNITY_TUNING=0; "
520                             "rocBLAS's default kernels run\n", arch.c_str(), version);
521        return nullptr;
522    }
523    std::string error;
524    if (!state->table.load(file.string(), arch, version, error)) {
525        std::fprintf(stderr, "prefill gemm: %s (%s); rocBLAS's default kernels run\n", error.c_str(),
526                     file.string().c_str());
527        return nullptr;
528    }
529    // rocBLAS loads its kernel library on the first product through a handle; a solution-index call before that
530    // fails (rocblas_status_internal_error) although the index is valid.  One tiny default product opens it.
531    {
532        uint16_t* tiny = nullptr;
533        if (hipMalloc(&tiny, 4 * 64 * 64 * 2) == hipSuccess) {
534            const float one = 1.0f, zero = 0.0f;
535            (void) rocblas_gemm_ex(state->handle, rocblas_operation_transpose, rocblas_operation_none, 64, 64, 64, &one,
536                                   tiny, rocblas_datatype_f16_r, 64, tiny + 64 * 64, rocblas_datatype_f16_r, 64, &zero,
537                                   tiny + 2 * 64 * 64, rocblas_datatype_f16_r, 128, tiny + 2 * 64 * 64,
538                                   rocblas_datatype_f16_r, 128, rocblas_datatype_f32_r, rocblas_gemm_algo_standard, 0, 0);
539            (void) hipStreamSynchronize((hipStream_t) stream);
540            (void) hipFree(tiny);
541        }
542    }
543    size_t tuned_rows = 0;
544    for (const auto& row : state->table.rows()) tuned_rows += row.tuned ? 1 : 0;
545    std::fprintf(stderr, "prefill gemm: rocBLAS tuning enabled (%zu rows, %zu with a solution, %s, rocBLAS %s)\n",
546                 state->table.rows().size(), tuned_rows, arch.c_str(), version);
547    return state;
548}
549
550// Gemm::f16_inplace's product through the table's solution for its shape.  False when the shape has no row, or the
551// launch was refused (then the default kernel runs, and for that shape from now on).
552bool try_rocblas_f16o(void* opaque_state, const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N,
553                      int64_t K, int64_t ldy) {
554    auto* state = static_cast<RocBlasState*>(opaque_state);
555    if (!state || T <= 0 || N <= 0 || K <= 0 || T > INT_MAX || N > INT_MAX || K > INT_MAX || ldy > INT_MAX / 2) return false;
556    const auto key = std::make_tuple((int) T, (int) N, (int) K, (int) ldy);
557    auto it = state->cache.find(key);
558    if (it == state->cache.end()) {
559        RocBlasState::Pick pick;
560        if (const auto* row = state->table.closest((int) N, (int) K, (int) ldy, (int) T); row && row->tuned) {
561            pick.tuned = true;
562            pick.solution = row->solution;
563        }
564        if (std::getenv("STRATA_ROCBLAS_VERBOSE")) {
565            if (pick.tuned)
566                std::fprintf(stderr, "prefill gemm: rocBLAS solution %d for T=%lld N=%lld K=%lld ldy=%lld\n",
567                             pick.solution, (long long) T, (long long) N, (long long) K, (long long) ldy);
568            else
569                std::fprintf(stderr, "prefill gemm: rocBLAS default kernel; no row for T=%lld N=%lld K=%lld ldy=%lld\n",
570                             (long long) T, (long long) N, (long long) K, (long long) ldy);
571        }
572        it = state->cache.emplace(key, pick).first;
573    }
574    if (!it->second.tuned) return false;
575    const float one = 1.0f, zero = 0.0f;
576    const rocblas_status status = rocblas_gemm_ex(
577        state->handle, rocblas_operation_transpose, rocblas_operation_none, (int) N, (int) T, (int) K, &one, W,
578        rocblas_datatype_f16_r, (int) K, X, rocblas_datatype_f16_r, (int) K, &zero, Y, rocblas_datatype_f16_r,
579        (int) (2 * ldy), Y, rocblas_datatype_f16_r, (int) (2 * ldy), rocblas_datatype_f32_r,
580        rocblas_gemm_algo_solution_index, it->second.solution, 0);
581    if (status == rocblas_status_success) {
582        ++state->tuned_launches;
583        return true;
584    }
585    // A refusal writes nothing (the default kernel runs now).  The first one can be rocBLAS still setting up for the
586    // kernel (its device workspace: seen as invalid_value once, success after); a solution refused three times is
587    // dropped for this shape.
588    ++state->fallbacks;
589    if (++it->second.refusals >= 3) {
590        std::fprintf(stderr, "prefill gemm: rocBLAS solution %d refused (status %d) for T=%lld N=%lld K=%lld ldy=%lld "
591                             "three times; the default kernel runs for this shape\n", it->second.solution, (int) status,
592                     (long long) T, (long long) N, (long long) K, (long long) ldy);
593        it->second.tuned = false;
594    } else if (std::getenv("STRATA_ROCBLAS_VERBOSE")) {
595        std::fprintf(stderr, "prefill gemm: rocBLAS solution %d refused (status %d) for T=%lld N=%lld K=%lld ldy=%lld; "
596                             "the default kernel this time\n", it->second.solution, (int) status, (long long) T,
597                     (long long) N, (long long) K, (long long) ldy);
598    }
599    return false;
600}
601#endif
602
603}  // namespace
604
605bool prompt_f16() {
606#if defined(__HIPCC__)
607    constexpr int kMaxDev = 64;
608    static std::atomic<int8_t> cached[kMaxDev] = {};   // 0 unknown, 1 off, 2 on
609    int dev = 0;
610    if (hipGetDevice(&dev) != hipSuccess || dev < 0 || dev >= kMaxDev) { (void) hipGetLastError(); return false; }
611    if (const int8_t c = cached[dev].load(std::memory_order_relaxed)) return c == 2;
612    // Opt-in (#835): STRATA_HIP_PROMPT_F16=1 turns it on.  It changes the prompt path's numbers (an FP16 rounding of
613    // each 16-bit GEMM's output), so a card gets it unasked only where it was measured against the FP16 path's level: the Radeon 780M
614    // (gfx1103, integrated, Linux; strata::core::prompt_f16_resolve), where =0 is the way back.  On gfx103x it is ~2x faster, so we say so once.
615    const char* e = std::getenv("STRATA_HIP_PROMPT_F16");
616    hipDeviceProp_t p{};
617    if (hipGetDeviceProperties(&p, dev) != hipSuccess) { (void) hipGetLastError(); p.gcnArchName[0] = 0; p.integrated = 0; }
618#if defined(_WIN32)
619    constexpr bool kWin = true;
620#else
621    constexpr bool kWin = false;
622#endif
623    const bool on = strata::core::prompt_f16_resolve(e, p.gcnArchName, p.integrated != 0, kWin);
624    if (on && e != nullptr) 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 "
625                                 "(rocBLAS is tuned only for that on gfx103x; not bit-identical to the default)%s",
626                         dev, p.gcnArchName[0] ? " " : "", p.gcnArchName, "\n");
627    else if (e == nullptr && std::strncmp(p.gcnArchName, "gfx103", 6) == 0)
628        std::fprintf(stderr, "strata prefill: HIP device %d %s - tip: STRATA_HIP_PROMPT_F16=1 reads long prompts about 2x faster here "
629                             "(FP16 prompt GEMMs, rocBLAS is tuned only for FP16 on gfx103x; the numbers differ slightly, see docs/AMD_HIP.md)%s",
630                     dev, p.gcnArchName, "\n");
631    cached[dev].store(on ? 2 : 1, std::memory_order_relaxed);
632    return on;
633#else
634    return false;
635#endif
636}
637
638// A padded X (ldx > K) no kernel took: its rows copied to a contiguous FP16 buffer of stride K.  Grown, never shrunk
639// (one buffer per Gemm; a padded X only arrives from STRATA_PF_PAD's producers).  One 2-D copy: the same values, and
640// the ordinary paths below then read them exactly as if the producer had written them unpadded.
641const uint16_t* Gemm::unpad_x(const uint16_t* X, int64_t T, int64_t K, int64_t ldx) {
642    if (X == nullptr || T <= 0 || K <= 0 || ldx <= K) return nullptr;
643    const int64_t need = T * K;
644    if (need > unpadded_x_elems_) {
645        if (unpadded_x_ != nullptr) { cudaFree(unpadded_x_); unpadded_x_ = nullptr; unpadded_x_elems_ = 0; }
646        void* p = nullptr;
647        if (cudaMalloc(&p, (size_t) need * sizeof(uint16_t)) != cudaSuccess) { cudaGetLastError(); return nullptr; }
648        unpadded_x_ = (uint16_t*) p;
649        unpadded_x_elems_ = need;
650    }
651    if (cudaMemcpy2DAsync(unpadded_x_, (size_t) K * sizeof(uint16_t), X, (size_t) ldx * sizeof(uint16_t),
652                          (size_t) K * sizeof(uint16_t), (size_t) T, cudaMemcpyDeviceToDevice,
653                          (cudaStream_t) stream_) != cudaSuccess) {
654        cudaGetLastError();
655        return nullptr;
656    }
657    return unpadded_x_;
658}
659
660bool gemm_dequant_side() {
661#if defined(__HIPCC__)
662    return false;
663#else
664    static const bool on = [] { const char* v = std::getenv("STRATA_DEQUANT_SIDE"); return v && v[0] == '1'; }();
665    return on;
666#endif
667}
668
669Gemm::~Gemm() {
670    for (W16Entry& e : w16_) if (e.d) (void) cudaFree(e.d);
671    for (void* e : side_ready_)
672        if (e) (void) cudaEventDestroy((cudaEvent_t) e);
673    for (void* e : side_free_)
674        if (e) (void) cudaEventDestroy((cudaEvent_t) e);
675    if (side_stream_) (void) cudaStreamDestroy((cudaStream_t) side_stream_);
676#if defined(STRATA_PREFILL_MMQ) && defined(__HIPCC__)
677    delete static_cast<strata::prefill::mmq::Context*>(mmq_ctx_);
678    if (mmq_buf_) cudaFree(mmq_buf_);
679#endif
680#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)
681    delete static_cast<HipLtState*>(hipblaslt_state_);
682#endif
683#if defined(__HIPCC__) && defined(STRATA_ROCBLAS_AVAILABLE)
684    delete static_cast<RocBlasState*>(rocblas_state_);
685#endif
686    if (handle_) cublasDestroy((cublasHandle_t) handle_);
687    if (tc_w_) cudaFree(tc_w_);
688    if (tc_x_) cudaFree(tc_x_);
689    if (unpadded_x_) cudaFree(unpadded_x_);
690    if (!external_) {
691        if (scratch_) cudaFree(scratch_);
692        if (workspace_) cudaFree(workspace_);
693    }
694}
695
696bool Gemm::init_external(void* stream, uint16_t* scratch, int64_t scratch_elems, void* workspace, size_t ws_bytes,
697                         std::string& err) {
698    cublasHandle_t h = nullptr;
699    if (const cublasStatus_t s = cublasCreate(&h); s != CUBLAS_STATUS_SUCCESS) {
700        err = "prefill gemm: cublasCreate: cuBLAS status " + std::to_string((int) s);
701        return false;
702    }
703    handle_ = h;
704    stream_ = stream;
705    external_ = true;
706    note(cublasSetStream(h, (cudaStream_t) stream), "cublasSetStream");
707    workspace_ = workspace;
708    note(cublasSetWorkspace(h, workspace_, ws_bytes), "cublasSetWorkspace");
709    note(cublasSetMathMode(h, CUBLAS_DEFAULT_MATH), "cublasSetMathMode");
710    scratch_ = scratch;
711    scratch_elems_ = scratch_elems;
712#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)
713    hipblaslt_state_ = create_hipblaslt_state(workspace_, ws_bytes).release();
714#endif
715#if defined(__HIPCC__) && defined(STRATA_ROCBLAS_AVAILABLE)
716    rocblas_state_ = create_rocblas_state(stream).release();
717#endif
718    return true;
719}
720
721void Gemm::rebind(uint16_t* scratch, int64_t scratch_elems, void* workspace, size_t ws_bytes) {
722    scratch_ = scratch;
723    scratch_elems_ = scratch_elems;
724    workspace_ = workspace;
725    cublasSetWorkspace((cublasHandle_t) handle_, workspace_, ws_bytes);
726#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)
727    if (hipblaslt_state_) {
728        auto* state = static_cast<HipLtState*>(hipblaslt_state_);
729        state->workspace = workspace_;
730        state->workspace_bytes = ws_bytes;
731    }
732#endif
733}
734
735bool Gemm::set_dequant_side(uint16_t* scratch2, std::string& err) {
736    side_scratch_ = scratch2;
737    side_cur_ = 0;
738    if (scratch2 == nullptr) return true;
739    if (side_stream_ == nullptr) {   // once: the stream and the four events outlive every rebind
740        cudaStream_t s = nullptr;
741        if (const cudaError_t e = cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking); e != cudaSuccess) {
742            err = std::string("prefill gemm: dequant side stream: ") + cudaGetErrorString(e);
743            side_scratch_ = nullptr;
744            return false;
745        }
746        side_stream_ = s;
747        for (int i = 0; i < 2; ++i) {
748            cudaEvent_t r = nullptr, f = nullptr;
749            const bool made = cudaEventCreateWithFlags(&r, cudaEventDisableTiming) == cudaSuccess &&
750                              cudaEventCreateWithFlags(&f, cudaEventDisableTiming) == cudaSuccess;
751            side_ready_[i] = r;   // kept even on a failure: the destructor frees what was made
752            side_free_[i] = f;
753            if (!made) {
754                err = "prefill gemm: dequant side events";
755                side_scratch_ = nullptr;
756                return false;
757            }
758        }
759    }
760    // both scratches are free once what the compute stream holds now is done (a rebind follows a stream sync, so
761    // this is belt and braces; a wait on an event never recorded would pass anyway)
762    for (int i = 0; i < 2; ++i)
763        (void) cudaEventRecord((cudaEvent_t) side_free_[i], (cudaStream_t) stream_);
764    return true;
765}
766
767bool Gemm::init(void* stream, int64_t scratch_elems, std::string& err) {
768    // #240: every failure names the call and the real status, so "no VRAM" can be told from a broken install
769    cublasHandle_t h = nullptr;
770    if (const cublasStatus_t s = cublasCreate(&h); s != CUBLAS_STATUS_SUCCESS) {
771        err = "prefill gemm: cublasCreate: cuBLAS status " + std::to_string((int) s);
772        return false;
773    }
774    handle_ = h;
775    stream_ = stream;
776    note(cublasSetStream(h, (cudaStream_t) stream), "cublasSetStream");
777    // A fixed workspace so the handle never allocates on the way (and graphs could capture it later).
778    const size_t ws = 32u << 20;
779    if (const cudaError_t e = cudaMalloc(&workspace_, ws); e != cudaSuccess) {
780        err = std::string("prefill gemm: workspace of 32 MiB: ") + cudaGetErrorString(e);
781        return false;
782    }
783    note(cublasSetWorkspace(h, workspace_, ws), "cublasSetWorkspace");
784    note(cublasSetMathMode(h, CUBLAS_DEFAULT_MATH), "cublasSetMathMode");
785#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)
786    hipblaslt_state_ = create_hipblaslt_state(workspace_, ws).release();
787#endif
788#if defined(__HIPCC__) && defined(STRATA_ROCBLAS_AVAILABLE)
789    rocblas_state_ = create_rocblas_state(stream).release();
790#endif
791    if (scratch_elems > 0) {
792        if (const cudaError_t e = cudaMalloc((void**) &scratch_, (size_t) scratch_elems * 2); e != cudaSuccess) {
793            err = "prefill gemm: dequant scratch of " + std::to_string(scratch_elems * 2 >> 20) + " MiB: " +
794                  cudaGetErrorString(e);
795            return false;
796        }
797    }
798    scratch_elems_ = scratch_elems;
799    return true;
800}
801
802#if !defined(__HIPCC__)
803// ---- below sm_80: BF16 GEMMs without BF16 tensor cores (PR #655, #540, #395) ----------------------------------------
804// Turing and Volta have no BF16 tensor cores: cublasGemmEx on CUDA_R_16BF inputs falls back to a SIMT fp32 kernel
805// (magma_sgemmEx), a fifth of a 4K prompt on an RTX 2080 Ti (#655) and ~10% of a V100's prompt (#540).  BF16 -> FP16
806// is exact for every value inside FP16's normal range (the 7-bit mantissa fits in 10 bits); weights and normalized
807// activations sit there.  With the FP16 path, the weight is converted once per call and the activations in row
808// slices, into the instance's own buffers, and the product runs as the FP16 GEMM (fp32 accumulate) on the tensor
809// cores.  Finite values beyond FP16's range are clamped to +-65504 (#540) instead of becoming Inf.  A beta = 1
810// product (STRATA_PREFILL_BF16X2's remainder, ~2^-9 of the original, deep in FP16's subnormal band) keeps cuBLAS.
811//   Default: on for compute capability 7.0 - 7.4 (Volta: only the experimental STRATA_EXPERIMENTAL_SM60 build runs
812//   there), OFF for 7.5 (RTX 20 in the ready-made engine: the sums round differently, so it is opt-in until it has
813//   been gated).  STRATA_BF16_TC=1 / =0 turns it on / off on any 7.x card (=2, a test mode: on any card).
814// Pascal (6.x) has no tensor cores and cuBLAS has no BF16 GEMM for it (#395, measured NOT_SUPPORTED on a P40): both
815// operands are widened to fp32 by an exact shift and the product is cublasSgemm with the same fp32 accumulator.
816namespace {
817__global__ void bf16_to_f16_kernel(const uint16_t* __restrict__ in, __half* __restrict__ out, int64_t n) {
818    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
819    if (i < n) {
820        float f = __uint_as_float((uint32_t) in[i] << 16);
821        if (f > 65504.0f && !isinf(f)) f = 65504.0f;
822        else if (f < -65504.0f && !isinf(f)) f = -65504.0f;
823        out[i] = __float2half_rn(f);
824    }
825}
826void bf16_to_f16(const uint16_t* in, uint16_t* out, int64_t n, cudaStream_t st) {
827    if (n <= 0) return;
828    bf16_to_f16_kernel<<<(unsigned) ((n + 255) / 256), 256, 0, st>>>(in, reinterpret_cast<__half*>(out), n);
829}
830#if defined(STRATA_EXPERIMENTAL_SM60)   // Pascal runs only the experimental build
831__global__ void bf16_to_f32_kernel(const uint16_t* __restrict__ in, float* __restrict__ out, int64_t n) {
832    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
833    if (i < n) out[i] = __uint_as_float((uint32_t) in[i] << 16);
834}
835void bf16_to_f32(const uint16_t* in, float* out, int64_t n, cudaStream_t st) {
836    if (n <= 0) return;
837    bf16_to_f32_kernel<<<(unsigned) ((n + 255) / 256), 256, 0, st>>>(in, out, n);
838}
839#endif
840// The current device's compute capability as 10 * major + minor, per device (a layer split can mix cards); 0: not
841// known, read as "not an old card" so a failed query keeps the cuBLAS BF16 call.
842int current_cc() {
843    static std::atomic<int> cc[64] = {};
844    int dev = 0;
845    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return 0; }
846    int v = cc[dev].load(std::memory_order_relaxed);
847    if (v == 0) {
848        int major = 0, minor = 0;
849        if (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess ||
850            cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev) != cudaSuccess) {
851            cudaGetLastError();
852            return 0;
853        }
854        v = 10 * major + minor;
855        cc[dev].store(v, std::memory_order_relaxed);
856    }
857    return v;
858}
859// 0: cuBLAS's BF16 GEMM, 1: through FP16 (tensor cores), 2: through FP32 (Pascal)
860int bf16_path() {
861    static const int forced = [] {
862        const char* v = std::getenv("STRATA_BF16_TC");
863        return v != nullptr && v[0] != '\0' ? std::atoi(v) : -1;
864    }();
865    const int cc = current_cc();
866    if (forced == 2 && cc > 0) return 1;   // a test mode: the FP16 path on any card (gemm_bf16_parity on sm_80+)
867    if (cc <= 0 || cc >= 80) return 0;
868    if (cc < 70) return 2;
869    if (forced >= 0) return forced != 0 ? 1 : 0;
870    return cc < 75 ? 1 : 0;
871}
872bool grow(uint16_t*& p, int64_t& have, int64_t want) {   // `have`, `want`: 2-byte elements
873    if (have >= want) return true;
874    if (p) cudaFree(p);
875    p = nullptr;
876    have = 0;
877    if (cudaMalloc((void**) &p, (size_t) want * 2) != cudaSuccess) { cudaGetLastError(); p = nullptr; return false; }
878    have = want;
879    return true;
880}
881constexpr int64_t kXSliceElems = 16ll << 20;   // 32 MiB of FP16 activations per slice (64 MiB as fp32)
882
883#if defined(STRATA_EXPERIMENTAL_SM60)
884// ---- Pascal, opt-in (STRATA_DENSE_F32=1): the dense projections' FP16-operand GEMMs as cublasSgemm ----------------
885// Measured on a Tesla P40 (sm_61) with cuBLAS 12.4.5.8 (bench/results/2026-10-12-p40-sm61-kernels).  For FP16
886// operands with FP32 sums cuBLAS has two Maxwell kernels there, maxwell_sgemm_fp16_64x64 and _32x128, and picks the
887// slow one for most chunk sizes: the 10240 x 2560 qkv projection runs at 7.6 TFLOPS for T 7030-7040 and at 4.3 from
888// T 7041 (49 -> 85 ms), and at 4.3-4.6 for two thirds of the T between 256 and 8192; the 12288-row query projection
889// likewise.  A 7K-token prompt reads in 16.3 or 19.5 s by its token count.  cublasSgemm on FP32 copies
890// (maxwell_sgemm_128x64) runs at 8.4-9.8 TFLOPS for every T from 512 (6.7+ from 256).  The copies are exact
891// (FP16 -> FP32), and for the shapes and sizes taken here the two kernels add every output's products in the same
892// order: the result is bitwise the cuBLAS FP16 call's (gemm_f32_parity: 5,201 chunk sizes on a P40 with cuBLAS 12.4, a
893// measurement of this library, not a guarantee of cuBLAS's; below the sizes taken here - T under
894// ~144 at 6144+ rows, under ~408 at 2560 rows - cuBLAS switches one of them to another kernel family and the bits
895// differ, so those keep the FP16 call).  The weight goes through the BF16 path's conversion buffer (126 MiB for the
896// largest, 21 MiB more than that path's own), the activations through its slices.
897// Opt-in, and on Pascal (compute capability 6.x) only: the equality belongs to the cuBLAS build, so run
898// gemm_f32_parity with yours before turning it on; newer cards have tensor cores for the FP16 call.
899__global__ void f16_to_f32_kernel(const uint16_t* __restrict__ in, float* __restrict__ out, int64_t n) {
900    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
901    if (i < n) out[i] = __half2float(__ushort_as_half(in[i]));
902}
903void f16_to_f32(const uint16_t* in, float* out, int64_t n, cudaStream_t st) {
904    if (n <= 0) return;
905    f16_to_f32_kernel<<<(unsigned) ((n + 255) / 256), 256, 0, st>>>(in, out, n);
906}
907int g_dense_f32 = -1;   // gemm_set_dense_f32 (the parity test: 0 / 1 on any card); -1 = STRATA_DENSE_F32
908bool dense_f32_on() {
909    static const bool env = [] {
910        const char* v = std::getenv("STRATA_DENSE_F32");
911        return v != nullptr && std::atoi(v) != 0;
912    }();
913    if (g_dense_f32 >= 0) return g_dense_f32 != 0;
914    if (!env) return false;
915    const int cc = current_cc();
916    return cc >= 60 && cc < 70;
917}
918// The smallest T taken for a weight of N rows and K columns (0: never): the measured shapes only - the 2560-column
919// qkv (10240 rows), query (12288) and gate (6144) projections and the 2560-row output projections (6144 and 4096
920// columns), each from a T where the FP32 route (its conversions included) is the faster one or within ~7% of the FP16
921// call (the gate projection below ~1300 tokens, the 4096-column output projection near 4096) and well above the T
922// where the two stop agreeing bitwise.  Every other shape (a row slice of a weight too) keeps the FP16 call.
923int64_t dense_f32_min_t(int64_t N, int64_t K) {
924    if (K == 2560 && (N == 10240 || N == 12288)) return 256;
925    if (K == 2560 && N == 6144) return 512;
926    if (N == 2560 && (K == 6144 || K == 4096)) return 4096;
927    return 0;
928}
929#endif
930}  // namespace
931#endif
932#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60)
933void gemm_set_dense_f32(int mode) { g_dense_f32 = mode; }
934#else
935void gemm_set_dense_f32(int) {}
936#endif
937bool 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) {
938#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)
939    static std::atomic<bool> told{false};
940    if (!hipblaslt_state_ || N != 320 || K != 10240 || T < 1) {
941        if (N == 320 && K == 10240 && !told.exchange(true))
942            std::fprintf(stderr, "strata: STRATA_HCD_EXACT: no hipBLASLt tuning table is loaded, so the exact kernel has nothing to match: "
943                                 "the hyper-connection down projection stays on hipBLAS\n");
944        return false;
945    }
946    // The kernel copies hipBLASLt solution 1176 / 1177's summation order, which is only true of the library build the
947    // table was calibrated with: take it only when the table makes hipBLASLt pick one of those two for this T.
948    const int id = hipblaslt_solution_for(hipblaslt_state_, strata::prefill::hipblaslt::InputType::bf16, T, N, K, N, 0.0f);
949    if (id != 1176 && id != 1177) {
950        if (T >= 4096 && !told.exchange(true))   // (a short chunk may legitimately get another solution: not worth a line)
951            std::fprintf(stderr, "strata: STRATA_HCD_EXACT: the tuning table gives the hyper-connection down projection (N 320, K 10240) "
952                                 "solution %d at T %lld, not 1176 / 1177: hipBLASLt runs it (a changed table or library; "
953                                 "tools/hip/gfx1151-hipblaslt-100401.txt is the one measured)\n",
954                         id, (long long) T);
955        return false;
956    }
957    return strata_pf_hcdown_exact_bf16(X, ldx, W, Y, T, N, K, stream_);
958#else
959    (void) X; (void) ldx; (void) W; (void) Y; (void) T; (void) N; (void) K;
960    return false;
961#endif
962}
963
964#if defined(__HIPCC__)
965// ---- RDNA2 (gfx103x): the prompt path's GEMMs as FP32 SGEMMs ------------------------------------------------------
966// The GEMMs here take 16-bit inputs (FP16 or BF16) and write FP32 (rocBLAS's "HS" / "BS" types).  The rocBLAS the engine
967// ships has tuned gfx1030 kernels for FP16 -> FP16 ("HH"), int8 and FP32 -> FP32 ("SS") only: every 16-bit-input,
968// FP32-output GEMM runs a "fallback" kernel at ~5 TFLOPS.  Measured on an RX 6800 (ROCm 10.2.0a20260930) with the
969// engine's exact calls (opA = T, opB = N, fp32 compute): at the Coder's prompt shapes the FP16 GEMMs of one fresh
970// 12K-token prompt take 14.1 s, the same GEMMs as SGEMM on widened copies 4.7 s including the widening (e.g.
971// N 10240 x T 8192 x K 2560: 86.7 -> 27.7 ms); the BF16 hyper-connection GEMMs 10.9 -> 7.5 ms (N 320, K 10240).
972// Widening FP16 / BF16 to FP32 is exact and SGEMM accumulates in FP32 like the native call, so the products are the
973// same up to summation order.  The weight is widened once per call, the activations in slices of up to 128 MiB of
974// FP32 (an 8,192-token chunk at K = 2560 is one slice).  Small N (< 64: routers, gates) keeps the native call:
975// there the widening costs more than the GEMM gains.  If the FP32 buffers cannot be allocated, the native call runs.
976//   OPT-IN here: STRATA_RDNA2_SGEMM=1 turns it on for gfx103x devices (other cards keep the native call, also in a
977//   mixed layer split); =all turns it on for every AMD card (A/B arms, tests); unset or 0 is the native path.  The
978//   author ran it as the gfx103x default (RX 6800 343 -> 534 tok/s); it is not bit-identical to the native call.
979namespace {
980__global__ void rdna2_bf16_to_f32_kernel(const uint16_t* __restrict__ in, float* __restrict__ out, int64_t n) {
981    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
982    if (i < n) out[i] = __uint_as_float((uint32_t) in[i] << 16);
983}
984__global__ void rdna2_f16_to_f32_kernel(const __half* __restrict__ in, float* __restrict__ out, int64_t n) {
985    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
986    if (i < n) out[i] = __half2float(in[i]);
987}
988void rdna2_widen(const uint16_t* in, float* out, int64_t n, bool bf16, cudaStream_t st) {
989    if (n <= 0) return;
990    const unsigned blocks = (unsigned) ((n + 255) / 256);
991    if (bf16) rdna2_bf16_to_f32_kernel<<<blocks, 256, 0, st>>>(in, out, n);
992    else rdna2_f16_to_f32_kernel<<<blocks, 256, 0, st>>>(reinterpret_cast<const __half*>(in), out, n);
993}
994// whether this GEMM runs as an SGEMM (see above)
995bool rdna2_sgemm_on(int64_t N) {
996    static const int mode = [] {   // 0 off (unset), 1 gfx103x devices, 2 every AMD device
997        const char* v = std::getenv("STRATA_RDNA2_SGEMM");
998        if (v == nullptr || v[0] == '\0') return 0;
999        if (std::strcmp(v, "all") == 0) return 2;
1000        return std::atoi(v) > 0 ? 1 : 0;
1001    }();
1002    if (mode == 0 || N < 64) return false;
1003    if (mode == 2) return true;
1004    static std::atomic<int> arch[64] = {};   // per device: 0 not known, 1 gfx103x, 2 another architecture
1005    int dev = 0;
1006    if (hipGetDevice(&dev) != hipSuccess || dev < 0 || dev >= 64) { (void) hipGetLastError(); return false; }
1007    int v = arch[dev].load(std::memory_order_relaxed);
1008    if (v == 0) {
1009        hipDeviceProp_t prop{};
1010        if (hipGetDeviceProperties(&prop, dev) != hipSuccess) { (void) hipGetLastError(); return false; }
1011        v = std::strncmp(prop.gcnArchName, "gfx103", 6) == 0 ? 1 : 2;
1012        arch[dev].store(v, std::memory_order_relaxed);
1013    }
1014    return v == 1;
1015}
1016// `have`, `want`: FP32 elements (the buffers are the instance's 2-byte tc_ buffers, sized in 2-byte elements)
1017bool rdna2_grow(uint16_t*& p, int64_t& have_u16, int64_t want_f32) {
1018    const int64_t want = 2 * want_f32;
1019    if (have_u16 >= want) return true;
1020    if (p) cudaFree(p);
1021    p = nullptr;
1022    have_u16 = 0;
1023    if (cudaMalloc((void**) &p, (size_t) want * 2) != cudaSuccess) { (void) cudaGetLastError(); p = nullptr; return false; }
1024    have_u16 = want;
1025    return true;
1026}
1027constexpr int64_t kRdna2SliceF32 = 32ll << 20;   // 128 MiB of FP32 activations per slice
1028}  // namespace
1029
1030// Y^T[N, T] (+)= W[N, K] . X^T[K, T] as SGEMMs on FP32 copies; false: not this card / shape, or no buffers (the caller
1031// runs its native GEMM, nothing was written)
1032bool Gemm::rdna2_sgemm(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy,
1033                       float beta, bool bf16) {
1034    if (K <= 0 || !rdna2_sgemm_on(N)) return false;
1035    const int64_t rows = std::max<int64_t>(1, std::min<int64_t>(T, kRdna2SliceF32 / K));
1036    // growing frees a buffer an earlier GEMM on this stream may still read (as the sm_60 FP32 route does)
1037    if (tc_w_elems_ < 2 * N * K || tc_x_elems_ < 2 * rows * K) (void) hipStreamSynchronize((hipStream_t) stream_);
1038    if (!rdna2_grow(tc_w_, tc_w_elems_, N * K) || !rdna2_grow(tc_x_, tc_x_elems_, rows * K)) return false;
1039    float* const wf = reinterpret_cast<float*>(tc_w_);
1040    float* const xf = reinterpret_cast<float*>(tc_x_);
1041    const float alpha = 1.0f;
1042    rdna2_widen(W, wf, N * K, bf16, (cudaStream_t) stream_);
1043    for (int64_t t0 = 0; t0 < T; t0 += rows) {
1044        const int64_t n = std::min<int64_t>(rows, T - t0);
1045        rdna2_widen(X + t0 * K, xf, n * K, bf16, (cudaStream_t) stream_);
1046        // every slice is a disjoint block of Y, so each gets the caller's beta
1047        ck(hipblasSgemm((hipblasHandle_t) handle_, HIPBLAS_OP_T, HIPBLAS_OP_N, (int) N, (int) n, (int) K, &alpha, wf,
1048                        (int) K, xf, (int) K, &beta, Y + t0 * ldy, (int) ldy),
1049           "hipblasSgemm (RDNA2)");
1050    }
1051    return true;
1052}
1053#endif
1054
1055bool Gemm::bf16_converts_x() const {
1056#if defined(__HIPCC__) || defined(STRATA_EXPERIMENTAL_SM60)
1057    return false;
1058#else
1059    return bf16_path() == 1;
1060#endif
1061}
1062__global__ void f16_to_bf16_kernel(const __half* __restrict__ in, uint16_t* __restrict__ out, int64_t n) {
1063    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
1064    if (i < n) out[i] = (uint16_t) (__float_as_uint(__half2float(in[i])) >> 16);   // exact: the value was a BF16
1065}
1066void Gemm::bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy,
1067                float beta, int64_t ldx, bool x_f16) {
1068    if (T <= 0 || N <= 0) return;
1069    if (ldy <= 0) ldy = N;
1070    if (ldx <= K) ldx = 0;
1071#ifdef STRATA_USE_HIP
1072    // #313 (opt-in STRATA_WMMA_GEMM=1; STRATA_WMMA_BF16=0 excludes bf16): RDNA3 / RDNA3.5 WMMA dense GEMM, before
1073    // hipBLASLt; it returns false for shapes it does not take (and off gfx11) and this falls through
1074    static const bool wmma_on = [] { const char* v = std::getenv("STRATA_WMMA_GEMM"); return v && v[0] != 0 && v[0] != '0'; }();
1075    static const bool bf16_on = [] { const char* v = std::getenv("STRATA_WMMA_BF16"); return !v || (v[0] != 0 && v[0] != '0'); }();
1076    if (wmma_on && bf16_on && ldx == 0 && T >= 16 && (beta == 0.0f || beta == 1.0f) &&
1077        strata_wmma_gemm_bf16(X, W, Y, T, N, K, ldy, beta, stream_)) {
1078        return;
1079    }
1080#endif
1081#if defined(__HIPCC__)
1082    if (f16_io_) {   // X is the FP16 image (set_act_f16); W goes through the dequantization scratch as FP16
1083        // the only accumulating BF16 product is the BF16X2 low part, which bf16x2_mode() turns off with this path
1084        if (beta != 0.0f) { std::fprintf(stderr, "prefill gemm: an accumulating BF16 GEMM on the FP16 prompt path\n"); std::exit(1); }
1085        const int64_t rows = std::min<int64_t>(N, scratch_elems_ / K);
1086        if (rows <= 0) { std::fprintf(stderr, "prefill gemm: scratch too small for K=%lld\n", (long long) K); std::exit(1); }
1087        for (int64_t r0 = 0; r0 < N; r0 += rows) {
1088            const int64_t n = std::min(rows, N - r0);
1089            bf16_to_f16_rows<<<1024, 256, 0, (cudaStream_t) stream_>>>(W + r0 * K, (__half*) scratch_, n * K);
1090            f16_inplace(X, scratch_, Y + r0, T, n, K, ldy);
1091        }
1092        return;
1093    }
1094#endif
1095    const float alpha = 1.0f;
1096#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)
1097    if (try_hipblaslt(hipblaslt_state_, strata::prefill::hipblaslt::InputType::bf16, X, W, Y, T, N, K, ldy,
1098                      beta, stream_, ldx)) {
1099        STRATA_ABSORB_HIPBLAS_STICKY("hipBLASLt bf16");
1100        return;
1101    }
1102#endif
1103#if defined(__HIPCC__)
1104    // a padded X (STRATA_PF_PAD, ldx > K) keeps the native call: the widening copies contiguous rows
1105    if (ldx == 0 && rdna2_sgemm(X, W, Y, T, N, K, ldy, beta, true)) return;
1106#endif
1107#if !defined(__HIPCC__)
1108#if defined(STRATA_EXPERIMENTAL_SM60)
1109    constexpr bool kPascalPath = true;
1110#else
1111    constexpr bool kPascalPath = false;
1112#endif
1113    if (const int path = K > 0 ? bf16_path() : 0; (path == 1 && N > 1 && beta == 0.0f) || (path == 2 && kPascalPath)) {
1114        // FP16 (path 1) or FP32 (path 2, Pascal) copies of the weight and of X, converted in tiles.  Issue #1757: when
1115        // the buffers did not fit in the VRAM that was left (a stage of a layer split keeps ~100 MiB), this fell through
1116        // to the raw BF16 cuBLAS call, which a Pascal card answers with CUBLAS_STATUS_INTERNAL_ERROR (14).  Now the
1117        // weight is converted in tiles of N rows (the whole weight when it fits, as before) and X in slices; a card with
1118        // no room even for a tile says so.  A single output row stays cuBLAS's GEMV for path 1 (faster than the
1119        // conversions).  Every tile is a disjoint block of Y, so each gets the caller's beta.
1120        const int mult = path == 2 ? 2 : 1;   // 2-byte elements per converted value
1121        int64_t w_rows = N;
1122        int64_t x_rows = std::max<int64_t>(1, std::min<int64_t>(T, kXSliceElems / K));
1123        bool fit = false;
1124        for (;;) {
1125            if (grow(tc_w_, tc_w_elems_, mult * w_rows * K) && grow(tc_x_, tc_x_elems_, mult * x_rows * K)) { fit = true; break; }
1126            if (w_rows <= 64 && x_rows <= 64) break;
1127            w_rows = std::max<int64_t>(std::min<int64_t>(w_rows, 64), w_rows / 2);
1128            x_rows = std::max<int64_t>(std::min<int64_t>(x_rows, 64), x_rows / 2);
1129        }
1130        if (!fit && path == 2) {   // Pascal has no BF16 cuBLAS call to fall back to; Volta keeps its raw one below
1131            std::fprintf(stderr, "prefill gemm: no GPU memory left for the %s conversion buffers of a %lld x %lld BF16 weight "
1132                                 "(Pascal cards run the BF16 products through them); free VRAM on this card: raise "
1133                                 "--vram-reserve-mib, lower --max-context or --kv-resident, or give it fewer layers\n",
1134                         "FP32", (long long) N, (long long) K);
1135            std::exit(1);
1136        }
1137        if (fit) {
1138            for (int64_t n0 = 0; n0 < N; n0 += w_rows) {
1139                const int64_t nn = std::min<int64_t>(w_rows, N - n0);
1140                if (path == 2) {
1141#if defined(STRATA_EXPERIMENTAL_SM60)
1142                    float* const wf = reinterpret_cast<float*>(tc_w_);
1143                    float* const xf = reinterpret_cast<float*>(tc_x_);
1144                    bf16_to_f32(W + n0 * K, wf, nn * K, (cudaStream_t) stream_);
1145                    for (int64_t t0 = 0; t0 < T; t0 += x_rows) {
1146                        const int64_t n = std::min<int64_t>(x_rows, T - t0);
1147                        bf16_to_f32(X + t0 * K, xf, n * K, (cudaStream_t) stream_);
1148                        ck(cublasSgemm((cublasHandle_t) handle_, CUBLAS_OP_T, CUBLAS_OP_N, (int) nn, (int) n, (int) K, &alpha,
1149                                       wf, (int) K, xf, (int) K, &beta, Y + t0 * ldy + n0, (int) ldy),
1150                           "cublasSgemm (bf16 on Pascal)");
1151                    }
1152#endif
1153                } else {
1154                    bf16_to_f16(W + n0 * K, tc_w_, nn * K, (cudaStream_t) stream_);
1155                    for (int64_t t0 = 0; t0 < T; t0 += x_rows) {
1156                        const int64_t n = std::min<int64_t>(x_rows, T - t0);
1157                        if (x_f16) {   // already the converted values (the same slices: the same GEMMs)
1158                            f16(X + t0 * K, tc_w_, Y + t0 * ldy + n0, n, nn, K, ldy, beta);
1159                        } else {
1160                            bf16_to_f16(X + t0 * K, tc_x_, n * K, (cudaStream_t) stream_);
1161                            f16(tc_x_, tc_w_, Y + t0 * ldy + n0, n, nn, K, ldy, beta);
1162                        }
1163                    }
1164                }
1165            }
1166            return;
1167        }
1168    }
1169#endif
1170#if !defined(__HIPCC__)
1171    if (x_f16) {   // not the tensor-core path after all (one output row, or no room): X back to BF16, a slice at a time
1172        const int64_t x_rows = std::max<int64_t>(1, std::min<int64_t>(T, kXSliceElems / K));
1173        if (!grow(tc_x_, tc_x_elems_, x_rows * K)) {
1174            std::fprintf(stderr, "prefill gemm: no GPU memory for converting an FP16 image back to BF16\n");
1175            std::exit(1);
1176        }
1177        for (int64_t t0 = 0; t0 < T; t0 += x_rows) {
1178            const int64_t n = std::min<int64_t>(x_rows, T - t0);
1179            f16_to_bf16_kernel<<<(unsigned) ((n * K + 255) / 256), 256, 0, (cudaStream_t) stream_>>>(
1180                reinterpret_cast<const __half*>(X + t0 * K), tc_x_, n * K);
1181            bf16(tc_x_, W, Y + t0 * ldy, n, N, K, ldy, beta, 0, false);
1182        }
1183        return;
1184    }
1185#endif
1186    // Column-major view: Y^T[N, T] = W[N, K] (stored K x N col-major, transposed) . X^T[K, T].
1187    ck(cublasGemmEx((cublasHandle_t) handle_, CUBLAS_OP_T, CUBLAS_OP_N, (int) N, (int) T, (int) K, &alpha, W,
1188                    CUDA_R_16BF, (int) K, X, CUDA_R_16BF, (int) (ldx ? ldx : K), &beta, Y, CUDA_R_32F, (int) ldy,
1189                    CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT),
1190       "cublasGemmEx");
1191    STRATA_ABSORB_HIPBLAS_STICKY("cublasGemmEx");
1192}
1193
1194void Gemm::f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy,
1195               float beta) {
1196    if (T <= 0 || N <= 0) return;
1197    if (ldy <= 0) ldy = N;
1198#ifdef STRATA_USE_HIP
1199    // #313 (opt-in STRATA_WMMA_GEMM=1): RDNA3 / RDNA3.5 WMMA dense GEMM, before hipBLASLt (falls through when false)
1200    static const bool wmma_on = [] { const char* v = std::getenv("STRATA_WMMA_GEMM"); return v && v[0] != 0 && v[0] != '0'; }();
1201    static const bool pf_on = [] { const char* v = std::getenv("STRATA_PF_GEMM"); return v && v[0] == '1'; }();
1202    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; }();
1203    if (pf_on && T >= pf_min_t && strata_pf_gemm_f16(X, W, Y, T, N, K, ldy, beta, stream_)) return;   // S23: opt-in
1204    if (wmma_on && T >= 16 && (beta == 0.0f || beta == 1.0f) &&
1205        strata_wmma_gemm_f16(X, W, Y, T, N, K, ldy, beta, stream_)) {
1206        return;
1207    }
1208#endif
1209#if defined(__HIPCC__)
1210    if (f16_io_ && beta == 0.0f) { f16_inplace(X, W, Y, T, N, K, ldy); return; }
1211#endif
1212    const float alpha = 1.0f;
1213#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)
1214    if (try_hipblaslt(hipblaslt_state_, strata::prefill::hipblaslt::InputType::f16, X, W, Y, T, N, K, ldy,
1215                      beta, stream_)) {
1216        STRATA_ABSORB_HIPBLAS_STICKY("hipBLASLt f16");
1217        return;
1218    }
1219#endif
1220#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60)
1221    // Pascal, STRATA_DENSE_F32=1: cublasSgemm on FP32 copies (dense_f32_on above: where it is bitwise the FP16 call)
1222    if (const int64_t min_t = beta == 0.0f ? dense_f32_min_t(N, K) : 0; min_t > 0 && T >= min_t && dense_f32_on()) {
1223        const int64_t n_sl = (T * K + kXSliceElems - 1) / kXSliceElems;   // even slices of at most 64 MiB as fp32
1224        const int64_t x_rows = (T + n_sl - 1) / n_sl;
1225        // grow() frees a buffer an earlier GEMM on this stream may still read
1226        if (tc_w_elems_ < 2 * N * K || tc_x_elems_ < 2 * x_rows * K) cudaStreamSynchronize((cudaStream_t) stream_);
1227        if (grow(tc_w_, tc_w_elems_, 2 * N * K) && grow(tc_x_, tc_x_elems_, 2 * x_rows * K)) {
1228            static bool said = false;
1229            if (!said) {
1230                said = true;
1231                std::fprintf(stderr, "prefill gemm: the dense projections' FP16 GEMMs run as cublasSgemm on FP32 copies "
1232                                     "(STRATA_DENSE_F32=1; gemm_f32_parity checks the bits against this cuBLAS)\n");
1233            }
1234            float* const wf = reinterpret_cast<float*>(tc_w_);
1235            float* const xf = reinterpret_cast<float*>(tc_x_);
1236            f16_to_f32(W, wf, N * K, (cudaStream_t) stream_);
1237            for (int64_t t0 = 0; t0 < T; t0 += x_rows) {
1238                const int64_t n = std::min<int64_t>(x_rows, T - t0);
1239                f16_to_f32(X + t0 * K, xf, n * K, (cudaStream_t) stream_);
1240                ck(cublasSgemm((cublasHandle_t) handle_, CUBLAS_OP_T, CUBLAS_OP_N, (int) N, (int) n, (int) K, &alpha, wf, (int) K,
1241                               xf, (int) K, &beta, Y + t0 * ldy, (int) ldy),
1242                   "cublasSgemm (FP16 operands, STRATA_DENSE_F32)");
1243            }
1244            return;
1245        }
1246        cudaGetLastError();   // no room for the copies: the FP16 call below
1247    }
1248#endif
1249#if defined(__HIPCC__)
1250    if (rdna2_sgemm(X, W, Y, T, N, K, ldy, beta, false)) return;
1251#endif
1252#if !defined(__HIPCC__)
1253    const auto f16_gemm = [&](cublasGemmAlgo_t algo) {
1254        return cublasGemmEx((cublasHandle_t) handle_, CUBLAS_OP_T, CUBLAS_OP_N, (int) N, (int) T, (int) K, &alpha,
1255                            W, CUDA_R_16F, (int) K, X, CUDA_R_16F, (int) K, &beta, Y, CUDA_R_32F, (int) ldy,
1256                            CUBLAS_COMPUTE_32F, algo);
1257    };
1258    // Issue #1650: with a second CUDA device initialized in the process, cuBLAS 12 answers the default algorithm of a
1259    // few shapes - narrow ones, and the set moves with K - with CUBLAS_STATUS_INTERNAL_ERROR; a fixed algorithm keeps
1260    // a kernel that state does not break.  Only the shapes that fail are moved (the failing call itself is harmless);
1261    // the wide shapes, for which the fixed algorithms are markedly slower, stay on the default.
1262    const int64_t shape = ((int64_t) K << 32) | (uint32_t) N;
1263    cublasGemmAlgo_t algo = CUBLAS_GEMM_DEFAULT;
1264    for (int i = 0; i < f16_algo_n_; ++i)
1265        if (f16_algo_shape_[i] == shape) { algo = CUBLAS_GEMM_ALGO2; break; }
1266    cublasStatus_t st = f16_gemm(algo);
1267    if (st == CUBLAS_STATUS_INTERNAL_ERROR && algo == CUBLAS_GEMM_DEFAULT) {
1268        if (f16_algo_n_ < kF16AlgoSlots) f16_algo_shape_[f16_algo_n_++] = shape;
1269        st = f16_gemm(CUBLAS_GEMM_ALGO2);
1270    }
1271    ck(st, "cublasGemmEx f16");
1272#else
1273    ck(cublasGemmEx((cublasHandle_t) handle_, CUBLAS_OP_T, CUBLAS_OP_N, (int) N, (int) T, (int) K, &alpha, W,
1274                    CUDA_R_16F, (int) K, X, CUDA_R_16F, (int) K, &beta, Y, CUDA_R_32F, (int) ldy,
1275                    CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT),
1276       "cublasGemmEx f16");
1277#endif
1278    STRATA_ABSORB_HIPBLAS_STICKY("cublasGemmEx f16");
1279}
1280
1281#if defined(STRATA_PREFILL_MMQ) && defined(__HIPCC__)
1282bool Gemm::native_mmq(const uint16_t* X, int type, const void* W, float* Y, int64_t T, int64_t N, int64_t K,
1283                      int64_t ldy) {
1284    namespace mmq = strata::prefill::mmq;
1285    constexpr int64_t kRows = 1024, kMaxK = 8192;
1286    static const bool enabled = [] {
1287        const char* e = std::getenv("STRATA_DENSE_MMQ");
1288        return e && e[0] == '1';
1289    }();
1290    if (!enabled || mmq_failed_ || !mmq::built() || !mmq::fits(type, N)) return false;
1291    // K must be a multiple of 256: llama.cpp's MMQ loads the weights in 256-value K chunks, and the
1292    // chunk past a partial row reads past the row (the next row's bytes - or, for the last weight
1293    // row, bytes past the tensor, which no caller guarantees to be zeros). The MoE path is safe
1294    // because its gather buffers carry a zeroed tail; a dense tensor is passed as-is, so a K that
1295    // is not a full chunk multiple (e.g. the 640-value shared-expert down: 20 blocks of 32) stays on
1296    // the dequantize + cuBLAS path.
1297    if (K > kMaxK || K % 256 != 0) return false;
1298    int64_t R = scratch_elems_ / (2 * K);   // FP32 activations for a chunk fit in the FP16 dequant scratch
1299    if (R > kRows) R = kRows;
1300    if (R > T) R = T;
1301    if (R < 1) return false;
1302    if (ldy <= 0) ldy = N;
1303
1304    const auto up = [](size_t v) { return (v + 255) & ~(size_t) 255; };
1305    // The row table is read past its end by llama.cpp's MMQ (mul_mat_q: a whole J-column tile from the start of each tile, J up to 128; the stream-k fixup:
1306    // up to roundup(max_rows, J) from the expert's first row): kRows + the margin of mmq_ids_margin.hpp (max_rows <= kRows), the identity written over all of it.
1307    // Exact, with only the 256 bytes of the bounds after it, a tile of 112 columns on a full chunk read 384 bytes past the table, 128 past the allocation.
1308    const size_t ids_rows = (size_t) mmq::mmq_ids_table_rows((uint64_t) kRows, (uint64_t) kRows);
1309    const size_t ident_off = up(mmq::q8_bytes(kRows, kMaxK));
1310    const size_t bounds_off = ident_off + up(ids_rows * 4);
1311    if (!mmq_buf_) {
1312        if (cudaMalloc(&mmq_buf_, bounds_off + 256) != cudaSuccess) {
1313            cudaGetLastError();
1314            mmq_failed_ = true;
1315            return false;
1316        }
1317        mmq_ctx_ = new mmq::Context();
1318        mmq::iota((int32_t*) ((uint8_t*) mmq_buf_ + ident_off), (int64_t) ids_rows, stream_);
1319        std::fprintf(stderr, "prefill gemm: dense MMQ on (STRATA_DENSE_MMQ=1)\n");
1320    }
1321    void* xq = mmq_buf_;
1322    const int32_t* ident = (const int32_t*) ((uint8_t*) mmq_buf_ + ident_off);
1323    int32_t* bounds = (int32_t*) ((uint8_t*) mmq_buf_ + bounds_off);
1324    float* xf = (float*) scratch_;
1325    auto* ctx = static_cast<mmq::Context*>(mmq_ctx_);
1326
1327    for (int64_t r0 = 0; r0 < T; r0 += R) {
1328        const int64_t rows = (T - r0 < R) ? T - r0 : R;
1329        mmq::f16_to_f32(X + r0 * K, xf, rows * K, stream_);
1330        mmq::quantize(xf, nullptr, xq, type, K, K, rows, stream_);
1331        mmq::set_bounds(bounds, (int32_t) rows, stream_);
1332        mmq::Product p;
1333        p.w = W;
1334        p.type = type;
1335        p.w_rows = N;
1336        p.w_cols = K;
1337        p.expert_bytes = mmq::matrix_bytes(type, N, K);
1338        p.n = 1;
1339        p.xq = xq;
1340        p.bounds = bounds;
1341        p.ids = ident;
1342        p.total_rows = rows;
1343        p.max_rows = rows;
1344        p.dst = Y + r0 * ldy;
1345        p.ld_dst = ldy;
1346        ctx->run(p, stream_);
1347    }
1348    return true;
1349}
1350#endif
1351void 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) {
1352#if defined(__HIPCC__)
1353    const float one = 1.0f, zero = 0.0f;
1354    bool done = false;
1355#if defined(STRATA_ROCBLAS_AVAILABLE)
1356    done = try_rocblas_f16o(rocblas_state_, X, W, Y, T, N, K, ldy);   // the table's kernel for this shape, if any
1357#endif
1358    if (!done) {
1359        ck(cublasGemmEx((cublasHandle_t) handle_, CUBLAS_OP_T, CUBLAS_OP_N, (int) N, (int) T, (int) K, &one, W,
1360                        CUDA_R_16F, (int) K, X, CUDA_R_16F, (int) K, &zero, Y, CUDA_R_16F, (int) (2 * ldy),
1361                        CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT),
1362           "cublasGemmEx f16 out");
1363    }
1364    static const bool dbg_nan = std::getenv("STRATA_DBG_NAN") != nullptr;
1365    widen_rows_f16<<<(unsigned) T, 256, 0, (cudaStream_t) stream_>>>(Y, N, ldy, dbg_nan ? 1 : 0);
1366    if (dbg_nan) {   // debug only: a sync per GEMM
1367        unsigned long long bad = 0, zero_count = 0;
1368        (void) hipStreamSynchronize((hipStream_t) stream_);
1369        if (hipMemcpyFromSymbol(&bad, HIP_SYMBOL(g_f16_nonfinite), sizeof bad) == hipSuccess && bad != 0) {
1370            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",
1371                         bad, (long long) T, (long long) N, (long long) K, "\n");
1372            (void) hipMemcpyToSymbol(HIP_SYMBOL(g_f16_nonfinite), &zero_count, sizeof zero_count);
1373        }
1374    }
1375#else
1376    (void) X; (void) W; (void) Y; (void) T; (void) N; (void) K; (void) ldy;
1377#endif
1378}
1379
1380void Gemm::native(const uint16_t* X, int ggml_type, const void* W_blocks, float* Y, int64_t T, int64_t N, int64_t K,
1381                  int64_t ldy, float beta, int64_t ldx) {
1382#ifdef STRATA_USE_HIP
1383    // S23 (opt-in STRATA_PF_PAD=1, with STRATA_PF_GEMM=1 on chunks of STRATA_PF_SWITCH_MIN_T+ tokens): the weight
1384    // dequantized into the scratch with row stride K + 64 halves, so no 4 KB-multiple stride camps on the memory
1385    // channels (gemm_probe8: K 6144 19 -> 29 TFLOPS from W alone, 35 with X padded too).  Bitwise the same products.
1386    static const bool pad_on = [] { const char* v = std::getenv("STRATA_PF_PAD"); return v && v[0] == '1'; }();
1387    static const bool pf_on = [] { const char* v = std::getenv("STRATA_PF_GEMM"); return v && v[0] == '1'; }();
1388    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; }();
1389    // (strata_pf_padded_gemm_available(): the CURRENT device runs the padded gfx11 product.  On a gfx1151 + gfx1201 split the process-wide switch
1390    // is on for both stages; the gfx12 stage would dequantize the weight padded, find no product, and do it again unpadded below.)
1391    if (pad_on && pf_on && T >= pf_min_t && T >= 64 && N >= 512 && K % 32 == 0 && N * (K + 64) <= scratch_elems_ &&
1392        strata_pf_padded_gemm_available()) {
1393        const int64_t ldw = K + 64;
1394        if (strata::kernels::dequant_f16_ld(ggml_type, W_blocks, 0, N, K, ldw, scratch_, stream_) &&
1395            strata_pf_gemm_f16_ld(X, ldx > 0 ? ldx : K, scratch_, ldw, Y, T, N, K, ldy, beta, stream_)) {
1396            return;
1397        }
1398    }
1399#endif
1400    if (ldx > 0 && ldx != K) {
1401#ifdef STRATA_USE_HIP
1402        // X arrived padded but the weight cannot be (an i-quant without a strided dequant, or the scratch is too
1403        // small for N x (K + 64)): the weight unpadded, X read at its stride - the same products, the same bits
1404        const int64_t rows = scratch_elems_ / K;
1405        bool ok = rows > 0 && strata_pf_padded_gemm_available();
1406        if (ldy <= 0) ldy = N;
1407        for (int64_t r0 = 0; ok && r0 < N; r0 += rows) {
1408            const int64_t n = (N - r0 < rows) ? N - r0 : rows;
1409            strata::kernels::dequant_f16(ggml_type, W_blocks, r0, n, K, scratch_, stream_);
1410            ok = strata_pf_gemm_f16_ld(X, ldx, scratch_, K, Y + r0, T, n, K, ldy, beta, stream_);
1411        }
1412        if (ok) return;
1413#endif
1414        // Nothing took a padded X: the padded product is the gfx11 matrix cores' (STRATA_PF_PAD asks
1415        // strata_pf_padded_gemm_available() before padding now, so this is a stale producer or another card's
1416        // activation).  Copy the rows unpadded and run the ordinary paths - the same products, the same bits - rather
1417        // than ending the engine.
1418        const uint16_t* Xu = unpad_x(X, T, K, ldx);
1419        if (Xu != nullptr) {
1420            native(Xu, ggml_type, W_blocks, Y, T, N, K, ldy, beta, 0);
1421            return;
1422        }
1423        std::fprintf(stderr, "prefill gemm: a padded X (ldx %lld, K %lld) has no path on this card and could not be "
1424                             "copied unpadded (no device memory)\n", (long long) ldx, (long long) K);
1425        std::exit(1);
1426    }
1427#if defined(STRATA_PREFILL_MMQ) && defined(__HIPCC__)
1428    if (beta == 0.0f && (ldx == 0 || ldx == K) && native_mmq(X, ggml_type, W_blocks, Y, T, N, K, ldy)) return;
1429#endif
1430#ifndef STRATA_USE_HIP
1431    // The FP16 weight kept on the device after its first dequant.  NOT bit-exact against the uncached sliced form on every
1432    // card (see the default below): off unless STRATA_PF_W16_CACHE_MIB is set.  When on it is sized by the card, never by the user.  It takes only VRAM nobody else holds: a weight is
1433    // cached while the card keeps kW16AutoReserve free afterwards (the MTP prompt capture, the batch windows and a long
1434    // prompt's buffers are allocated later, out of that room; a replica with 309 MiB free ran out of memory at 14K tokens),
1435    // so a card whose expert cache fills it caches nothing and a card with room (all experts resident) caches what the
1436    // prompt path uses (~6 GB for Qwen3.8).  STRATA_PF_W16_CACHE_MIB=N is an explicit budget (2 GiB kept free, as before),
1437    // =0 turns it off.
1438    if (w16_budget_ < 0) {
1439        const char* v = std::getenv("STRATA_PF_W16_CACHE_MIB");
1440        if (v != nullptr && std::strcmp(v, "auto") == 0) {
1441            // STRATA_PF_W16_CACHE_MIB=auto (tester switch, round0212 item 7): the automatic sizing - weights are cached while the card
1442            // keeps kW16AutoReserve free afterwards, so a card whose expert cache fills it caches nothing.  Not bit-exact (see below),
1443            // so it is not the default until the owner says yes.
1444            w16_budget_ = 16ll << 30;
1445            w16_reserve_ = kW16AutoReserve;
1446        } else if (v != nullptr) {
1447            w16_budget_ = (int64_t) std::atoll(v) * (1ll << 20);
1448            w16_reserve_ = 2ll << 30;
1449        } else {
1450            // INT3 turned the default off (11-01) because gemm_dequant_side_parity failed with it on sm_86 / sm_120 / sm_121.  That test builds its Gemm
1451            // with a 10.5 M-element scratch, smaller than four of its weights, so uncached those take the sliced path (several GEMMs) and cached they
1452            // take one full-N GEMM: not the engine.  The engine's scratch is GEMM_SCRATCH = 32 M elements and every dense projection of Qwen3.8
1453            // (largest attn_q, 31.5 M) fits it, so cached and uncached are the same GEMM on the same FP16 values (gemm_w16_parity: the engine's scratch,
1454            // shapes and types, bitwise).  Round0212 item 7: on when the engine says so (set_w16_auto_default: Linux CUDA with batch slots), else off
1455            // as in v0.2.9.  It takes only VRAM beyond kW16AutoReserve, so a card whose expert cache fills it caches nothing.  =0 turns it off.
1456            w16_budget_ = w16_auto_default_().load() ? (16ll << 30) : 0;
1457            w16_reserve_ = kW16AutoReserve;
1458        }
1459    }
1460    if (w16_budget_ > 0 && !side_scratch_) {
1461        const int64_t bytes = N * K * 2;
1462        uint16_t* cw = nullptr;
1463        for (const W16Entry& e : w16_)
1464            if (e.p == W_blocks && e.type == ggml_type && e.n == N && e.k == K) { cw = e.d; break; }
1465        if (cw == nullptr && w16_used_ + bytes <= w16_budget_) {
1466            size_t fb = 0, tb = 0;
1467            if (cudaMemGetInfo(&fb, &tb) == cudaSuccess && fb > (size_t) bytes + (size_t) w16_reserve_ &&
1468                cudaMalloc((void**) &cw, (size_t) bytes) == cudaSuccess) {
1469                strata::kernels::dequant_f16(ggml_type, W_blocks, 0, N, K, cw, stream_);
1470                w16_.push_back({W_blocks, ggml_type, N, K, cw});
1471                w16_used_ += bytes;
1472            } else {
1473                (void) cudaGetLastError();
1474                cw = nullptr;
1475                if (w16_budget_ > 0 && !w16_logged_) {
1476                    w16_logged_ = true;
1477                    std::fprintf(stderr, "strata prefill: FP16 weight cache %lld MiB (the card keeps %lld MiB free; STRATA_PF_W16_CACHE_MIB=0 turns it off)\n",
1478                                 (long long) (w16_used_ >> 20), (long long) (w16_reserve_ >> 20));
1479                }
1480                w16_budget_ = w16_used_ > 0 ? w16_used_ : 0;   // out of room: stop trying
1481            }
1482        }
1483        if (cw != nullptr) {
1484            f16(X, cw, Y, T, N, K, ldy, beta);
1485            return;
1486        }
1487    }
1488#endif
1489    if (N * K > scratch_elems_) {
1490        // Too large for the scratch at once: in row slices.
1491        const int64_t rows = scratch_elems_ / K;
1492        if (rows <= 0) { std::fprintf(stderr, "prefill gemm: scratch too small for K=%lld\n", (long long) K); std::exit(1); }
1493        if (ldy <= 0) ldy = N;
1494        for (int64_t r0 = 0; r0 < N; r0 += rows) {
1495            const int64_t n = (N - r0 < rows) ? N - r0 : rows;
1496            strata::kernels::dequant_f16(ggml_type, W_blocks, r0, n, K, scratch_, stream_);
1497            f16(X, scratch_, Y + r0, T, n, K, ldy, beta);
1498        }
1499        // the side stream's next dequant into scratch_ waits for these slices' reads and writes of it
1500        if (side_scratch_) (void) cudaEventRecord((cudaEvent_t) side_free_[0], (cudaStream_t) stream_);
1501        return;
1502    }
1503    if (side_scratch_) {
1504        // STRATA_DEQUANT_SIDE: the dequant on the side stream, into the scratch the compute stream read last but one.
1505        // free[cur] -> dequant -> ready[cur] -> GEMM -> free[cur] orders the dequant after the GEMM that last read
1506        // this scratch and the GEMM after the dequant that filled it, so every read and write of a scratch is where
1507        // the serial form had it - the same kernels, the same bits - and the dequant runs while the kernels queued
1508        // ahead of this GEMM do.
1509        uint16_t* const s = side_cur_ == 0 ? scratch_ : side_scratch_;
1510        (void) cudaStreamWaitEvent((cudaStream_t) side_stream_, (cudaEvent_t) side_free_[side_cur_], 0);
1511        strata::kernels::dequant_f16(ggml_type, W_blocks, 0, N, K, s, side_stream_);
1512        (void) cudaEventRecord((cudaEvent_t) side_ready_[side_cur_], (cudaStream_t) side_stream_);
1513        (void) cudaStreamWaitEvent((cudaStream_t) stream_, (cudaEvent_t) side_ready_[side_cur_], 0);
1514        f16(X, s, Y, T, N, K, ldy, beta);
1515        (void) cudaEventRecord((cudaEvent_t) side_free_[side_cur_], (cudaStream_t) stream_);
1516        side_cur_ ^= 1;
1517        return;
1518    }
1519    strata::kernels::dequant_f16(ggml_type, W_blocks, 0, N, K, scratch_, stream_);
1520    f16(X, scratch_, Y, T, N, K, ldy, beta);
1521}
1522
1523}  // namespace strata::prefill