okami.mom/strata

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

Niko1221Merge branch 'f-split-int' into f-split-vision7c5e84612

main
16.3 KiB281 linesraw
1// tools/hip/tune_rocblas.cpp - a rocBLAS tuning table for the prompt path's FP16-out GEMMs (gfx103x, prompt_f16()).
2//
3// On RDNA2 the prompt path's dense products run as rocBLAS FP16 in -> FP16 out (docs/AMD_HIP.md, "RDNA2").  rocBLAS
4// picks its kernel from a table by shape, and for some shapes that pick is far from the best kernel the library has:
5// on an RX 6900 XT, N=10240 K=2560 (the GDN input projection) below T=1152 tokens runs at 5 TFLOPS where the best of
6// rocBLAS's own 237 solutions for the same shape runs at 32 (E270, 2026-10-05).  This tool enumerates the library's
7// solutions for each shape (rocblas_gemm_ex_get_solutions), times them, checks each against the default kernel's
8// output, and writes the rows where a solution beats the default by at least --min-gain (1.05 = 5%) as a table the
9// engine reads through STRATA_ROCBLAS_TUNING (src/prefill/rocblas_tuning.hpp; Gemm::f16_inplace).
10//
11// Solution indices are valid only for one GPU architecture and one rocBLAS build (its version string, tweak hash
12// included), so a table is calibrated on the card with the ROCm the engine runs with:
13//
14//   cmake --build build-hip --target tune_rocblas
15//   ./build-hip/tune_rocblas --tuning-out tools/hip/<arch>-rocblas-<version>.txt
16//
17// Defaults: the engine's 14 FP16 dense shapes at T = 256 ... 8192 (--tokens); --case T,N,K,ldy adds one shape.
18#define ROCBLAS_BETA_FEATURES_API
19#include <hip/hip_runtime.h>
20#include <hip/hip_fp16.h>
21#include <rocblas/rocblas.h>
22
23#include <algorithm>
24#include <cmath>
25#include <cstdint>
26#include <cstdio>
27#include <cstdlib>
28#include <cstring>
29#include <fstream>
30#include <functional>
31#include <limits>
32#include <random>
33#include <string>
34#include <vector>
35
36namespace {
37#define HIP_CHECK(call) do { const hipError_t e = (call); if (e != hipSuccess) { \
38    std::fprintf(stderr, "HIP %s:%d: %s: %s\n", __FILE__, __LINE__, #call, hipGetErrorString(e)); std::exit(2); } } while (0)
39#define RB_CHECK(call) do { const rocblas_status e = (call); if (e != rocblas_status_success) { \
40    std::fprintf(stderr, "rocBLAS %s:%d: %s: status=%d\n", __FILE__, __LINE__, #call, (int) e); std::exit(2); } } while (0)
41
42struct Buffer {
43    void* p = nullptr;
44    explicit Buffer(size_t bytes) { if (bytes) HIP_CHECK(hipMalloc(&p, bytes)); }
45    ~Buffer() { if (p) (void) hipFree(p); }
46    Buffer(const Buffer&) = delete;
47    Buffer& operator=(const Buffer&) = delete;
48};
49
50struct Shape { int t, n, k, ldy; };
51struct Options {
52    std::vector<Shape> shapes;
53    std::vector<int> tokens{256, 512, 768, 1024, 1536, 2048, 4096, 8192};
54    std::string tuning_out;
55    double min_gain = 1.05;
56    bool explicit_shapes = false;
57};
58struct Err { double rel_l2 = 0, max_abs = 0; bool finite = true, ok = true; size_t padding_writes = 0; };
59struct Row { Shape s; bool tuned; int solution; float default_ms, best_ms; };
60
61constexpr int WARMUPS = 2, REPS = 3, TOP = 8;
62constexpr uint16_t CANARY = 0x7BFF;   // the largest finite FP16 (65504): never a product of (-1, 1) inputs
63
64uint16_t f16_bits(float x) { const __half h = __float2half_rn(x); uint16_t b; std::memcpy(&b, &h, 2); return b; }
65float f16_value(uint16_t b) { __half h; std::memcpy(&h, &b, 2); return __half2float(h); }
66
67std::vector<std::string> csv(const std::string& s) {
68    std::vector<std::string> out; size_t b = 0;
69    for (;;) {
70        const size_t p = s.find(',', b);
71        out.push_back(s.substr(b, p == std::string::npos ? p : p - b));
72        if (p == std::string::npos) return out;
73        b = p + 1;
74    }
75}
76int positive(const std::string& s, const char* label) {
77    char* e = nullptr; const long v = std::strtol(s.c_str(), &e, 10);
78    if (s.empty() || !e || *e || v < 1 || v > std::numeric_limits<int>::max()) {
79        std::fprintf(stderr, "invalid %s: %s\n", label, s.c_str()); std::exit(2);
80    }
81    return (int) v;
82}
83void usage(const char* p) {
84    std::printf("Usage: %s [--case T,N,K,ldy]... [--tokens T1,T2,...] [--min-gain 1.05] [--tuning-out PATH]\n", p);
85    std::printf("Defaults: the engine's 14 FP16 dense shapes (ldy = N) at T = 256,512,768,1024,1536,2048,4096,8192.\n");
86}
87Options options(int argc, char** argv) {
88    Options o;
89    for (int i = 1; i < argc; ++i) {
90        const std::string a = argv[i];
91        auto next = [&]() -> std::string {
92            if (i + 1 >= argc) { std::fprintf(stderr, "missing option value\n"); std::exit(2); }
93            return argv[++i];
94        };
95        if (a == "-h" || a == "--help") { usage(argv[0]); std::exit(0); }
96        else if (a == "--case") {
97            const auto f = csv(next());
98            if (f.size() != 4) { std::fprintf(stderr, "--case expects T,N,K,ldy\n"); std::exit(2); }
99            const Shape s{positive(f[0], "T"), positive(f[1], "N"), positive(f[2], "K"), positive(f[3], "ldy")};
100            if (s.ldy < s.n) { std::fprintf(stderr, "ldy must be >= N\n"); std::exit(2); }
101            o.shapes.push_back(s); o.explicit_shapes = true;
102        } else if (a == "--tokens") {
103            o.tokens.clear();
104            for (const auto& x : csv(next())) o.tokens.push_back(positive(x, "token bucket"));
105        } else if (a == "--min-gain") { o.min_gain = std::atof(next().c_str()); if (o.min_gain < 1.0) o.min_gain = 1.0; }
106        else if (a == "--tuning-out") o.tuning_out = next();
107        else { std::fprintf(stderr, "unknown option: %s\n", a.c_str()); usage(argv[0]); std::exit(2); }
108    }
109    if (!o.explicit_shapes) {
110        // Qwen3.8-Flash-Next's dense FP16 products, prompt_f16() on (the hc read, GDN and QSA projections, the router
111        // and the shared expert), ldy = N for every one of them.  N K as the engine calls Gemm (ROCBLAS_LAYER=2).
112        const int nk[][2] = {{10240, 2560}, {12288, 2560}, {6144, 2560}, {2560, 6144}, {2560, 640}, {2560, 2560},
113                             {640, 2560}, {512, 2560}, {128, 2560}, {48, 2560}, {320, 10240}, {10240, 320},
114                             {4, 10240}, {1, 2560}};
115        for (const auto& p : nk) for (int t : o.tokens) o.shapes.push_back({t, p[0], p[1], p[0]});
116    }
117    return o;
118}
119
120float time_ms(hipStream_t stream, hipEvent_t a, hipEvent_t b, const std::function<rocblas_status()>& f, int reps,
121              bool& ok) {
122    HIP_CHECK(hipEventRecord(a, stream));
123    for (int i = 0; i < reps; ++i) if (f() != rocblas_status_success) { ok = false; return 0; }
124    HIP_CHECK(hipEventRecord(b, stream));
125    HIP_CHECK(hipEventSynchronize(b));
126    float ms = 0; HIP_CHECK(hipEventElapsedTime(&ms, a, b));
127    ok = true;
128    return ms / reps;
129}
130
131// The candidate's FP16 output against the default kernel's, over the N x T results; the rest of each 2*ldy-half column
132// (what the engine's widen_rows_f16 does not cover) must still hold the canary.
133Err compare(const std::vector<uint16_t>& ref, const std::vector<uint16_t>& got, const Shape& s) {
134    Err e; long double d2 = 0, r2 = 0; float max_ref = 0;
135    const size_t ldc = (size_t) s.ldy * 2;
136    for (int col = 0; col < s.t; ++col) {
137        for (int row = 0; row < s.n; ++row) {
138            const float r = f16_value(ref[col * ldc + row]), g = f16_value(got[col * ldc + row]);
139            if (!std::isfinite(r) || !std::isfinite(g)) { e.finite = false; continue; }
140            const double d = (double) g - r;
141            d2 += (long double) d * d; r2 += (long double) r * r;
142            e.max_abs = std::max(e.max_abs, std::abs(d)); max_ref = std::max(max_ref, std::abs(r));
143        }
144        for (size_t row = s.n; row < ldc; ++row) if (got[col * ldc + row] != CANARY) ++e.padding_writes;
145    }
146    e.rel_l2 = std::sqrt((double) (d2 / std::max(r2, 1e-300L)));
147    // the two kernels sum K products in different orders, then both round to FP16: a few last-bit differences
148    const float ulp = std::ldexp(1.0f, (int) std::floor(std::log2(std::max(max_ref, 1e-30f))) - 10);
149    e.ok = e.finite && e.padding_writes == 0 && e.rel_l2 <= 2e-3 && e.max_abs <= 4.0 * ulp;
150    return e;
151}
152}  // namespace
153
154int main(int argc, char** argv) {
155    const Options o = options(argc, argv);
156    rocblas_handle h; RB_CHECK(rocblas_create_handle(&h));
157    hipStream_t stream; HIP_CHECK(hipStreamCreateWithFlags(&stream, hipStreamNonBlocking));
158    RB_CHECK(rocblas_set_stream(h, stream));
159    char ver[128] = {0}; RB_CHECK(rocblas_get_version_string(ver, sizeof ver));
160    int device = 0; hipDeviceProp_t prop{};
161    HIP_CHECK(hipGetDevice(&device)); HIP_CHECK(hipGetDeviceProperties(&prop, device));
162    std::string arch(prop.gcnArchName); if (const auto c = arch.find(':'); c != std::string::npos) arch.resize(c);
163    std::printf("meta device_arch=%s rocblas_version=%s shapes=%zu min_gain=%.3f\n", arch.c_str(), ver, o.shapes.size(), o.min_gain);
164    hipEvent_t ea, eb; HIP_CHECK(hipEventCreate(&ea)); HIP_CHECK(hipEventCreate(&eb));
165
166    std::vector<Row> rows;
167    for (size_t ci = 0; ci < o.shapes.size(); ++ci) {
168        const Shape& s = o.shapes[ci];
169        const size_t na = (size_t) s.n * s.k, nb = (size_t) s.t * s.k, ldc = (size_t) s.ldy * 2, nc = ldc * s.t;
170        std::vector<uint16_t> ha(na), hb(nb), canary(nc, CANARY);
171        std::mt19937 rng(0x5A17C3u + (uint32_t) ci * 0x10001u);
172        std::uniform_real_distribution<float> dist(-1.0f, 1.0f);
173        for (auto& x : ha) x = f16_bits(dist(rng));
174        for (auto& x : hb) x = f16_bits(dist(rng));
175        Buffer da(na * 2), db(nb * 2), dc(nc * 2);
176        HIP_CHECK(hipMemcpy(da.p, ha.data(), na * 2, hipMemcpyHostToDevice));
177        HIP_CHECK(hipMemcpy(db.p, hb.data(), nb * 2, hipMemcpyHostToDevice));
178        const float alpha = 1.0f, beta = 0.0f;
179        // the engine's call (Gemm::f16_inplace): C[N x T] = W^T . X, FP16 out, ldc = 2 * ldy halves
180        auto gemm = [&](rocblas_gemm_algo algo, int32_t sol) {
181            return rocblas_gemm_ex(h, rocblas_operation_transpose, rocblas_operation_none, s.n, s.t, s.k, &alpha,
182                                   da.p, rocblas_datatype_f16_r, s.k, db.p, rocblas_datatype_f16_r, s.k, &beta, dc.p,
183                                   rocblas_datatype_f16_r, (int) ldc, dc.p, rocblas_datatype_f16_r, (int) ldc,
184                                   rocblas_datatype_f32_r, algo, sol, 0);
185        };
186        bool ok = true;
187        HIP_CHECK(hipMemcpy(dc.p, canary.data(), nc * 2, hipMemcpyHostToDevice));
188        for (int i = 0; i < WARMUPS; ++i) RB_CHECK(gemm(rocblas_gemm_algo_standard, 0));
189        const float default_ms = time_ms(stream, ea, eb, [&] { return gemm(rocblas_gemm_algo_standard, 0); }, REPS, ok);
190        HIP_CHECK(hipDeviceSynchronize());
191        std::vector<uint16_t> ref(nc);
192        HIP_CHECK(hipMemcpy(ref.data(), dc.p, nc * 2, hipMemcpyDeviceToHost));
193        const Err self = compare(ref, ref, s);
194        std::printf("case T=%d N=%d K=%d ldy=%d default_ms=%.4f default_padding_writes=%zu\n", s.t, s.n, s.k, s.ldy,
195                    default_ms, self.padding_writes);
196
197        rocblas_int count = 0;
198        auto solutions = [&](rocblas_int* list, rocblas_int* n) {
199            return rocblas_gemm_ex_get_solutions(h, rocblas_operation_transpose, rocblas_operation_none, s.n, s.t, s.k,
200                                                 &alpha, da.p, rocblas_datatype_f16_r, s.k, db.p, rocblas_datatype_f16_r,
201                                                 s.k, &beta, dc.p, rocblas_datatype_f16_r, (int) ldc, dc.p,
202                                                 rocblas_datatype_f16_r, (int) ldc, rocblas_datatype_f32_r,
203                                                 rocblas_gemm_algo_solution_index, 0, list, n);
204        };
205        if (solutions(nullptr, &count) != rocblas_status_success || count <= 0) {
206            std::printf("no_solutions T=%d N=%d K=%d ldy=%d\n", s.t, s.n, s.k, s.ldy);
207            continue;
208        }
209        std::vector<rocblas_int> ids(count);
210        RB_CHECK(solutions(ids.data(), &count));
211        // pass 1: one timed call each; pass 2: the TOP fastest get the full measurement and the output check
212        std::vector<std::pair<float, rocblas_int>> quick;
213        for (rocblas_int id : ids) {
214            if (gemm(rocblas_gemm_algo_solution_index, id) != rocblas_status_success) continue;
215            const float ms = time_ms(stream, ea, eb, [&] { return gemm(rocblas_gemm_algo_solution_index, id); }, 1, ok);
216            if (ok) quick.push_back({ms, id});
217        }
218        std::sort(quick.begin(), quick.end());
219        rocblas_int best = 0; float best_ms = std::numeric_limits<float>::infinity();
220        for (size_t i = 0; i < quick.size() && i < (size_t) TOP; ++i) {
221            const rocblas_int id = quick[i].second;
222            HIP_CHECK(hipMemcpy(dc.p, canary.data(), nc * 2, hipMemcpyHostToDevice));
223            for (int w = 0; w < WARMUPS; ++w) if (gemm(rocblas_gemm_algo_solution_index, id) != rocblas_status_success) { ok = false; break; }
224            if (!ok) continue;
225            const float ms = time_ms(stream, ea, eb, [&] { return gemm(rocblas_gemm_algo_solution_index, id); }, REPS, ok);
226            if (!ok) continue;
227            HIP_CHECK(hipDeviceSynchronize());
228            std::vector<uint16_t> got(nc);
229            HIP_CHECK(hipMemcpy(got.data(), dc.p, nc * 2, hipMemcpyDeviceToHost));
230            Err e = compare(ref, got, s);
231            // the engine applies a row to every T nearest its bucket, and a kernel can refuse a T it was not
232            // measured at (a tile or grid predicate): the solution must also run at odd, smaller token counts
233            bool accepts_neighbors = true;
234            for (int tn : {s.t - 1, s.t - 37, s.t - 63, s.t / 2 + 1}) {
235                if (tn < 1) continue;
236                const rocblas_status st = rocblas_gemm_ex(
237                    h, rocblas_operation_transpose, rocblas_operation_none, s.n, tn, s.k, &alpha, da.p,
238                    rocblas_datatype_f16_r, s.k, db.p, rocblas_datatype_f16_r, s.k, &beta, dc.p, rocblas_datatype_f16_r,
239                    (int) ldc, dc.p, rocblas_datatype_f16_r, (int) ldc, rocblas_datatype_f32_r,
240                    rocblas_gemm_algo_solution_index, id, 0);
241                if (st != rocblas_status_success) { accepts_neighbors = false; break; }
242            }
243            HIP_CHECK(hipDeviceSynchronize());
244            e.ok = e.ok && accepts_neighbors;
245            std::printf("  solution=%d ms=%.4f gain=%.2f relative_l2=%.3g max_abs=%.3g padding_writes=%zu %s%s\n", (int) id,
246                        ms, default_ms / ms, e.rel_l2, e.max_abs, e.padding_writes, e.ok ? "ok" : "REJECT",
247                        accepts_neighbors ? "" : " (refuses a smaller T)");
248            if (e.ok && ms < best_ms) { best = id; best_ms = ms; }
249        }
250        if (std::isfinite(best_ms) && default_ms / best_ms >= o.min_gain) {
251            std::printf("best T=%d N=%d K=%d ldy=%d solution=%d ms=%.4f default_ms=%.4f gain=%.2f\n", s.t, s.n, s.k, s.ldy,
252                        (int) best, best_ms, default_ms, default_ms / best_ms);
253            rows.push_back({s, true, (int) best, default_ms, best_ms});
254        } else {
255            // written too: the engine applies a row to the token counts nearest its bucket, and a `default` row keeps
256            // a neighbouring bucket's solution from reaching token counts where the default kernel measured best
257            std::printf("keep_default T=%d N=%d K=%d ldy=%d (%zu solutions; best %.4f ms vs default %.4f)\n", s.t, s.n, s.k,
258                        s.ldy, quick.size(), best_ms, default_ms);
259            rows.push_back({s, false, 0, default_ms, best_ms});
260        }
261    }
262
263    if (!o.tuning_out.empty()) {
264        std::ofstream f(o.tuning_out);
265        if (!f) { std::fprintf(stderr, "cannot write tuning output: %s\n", o.tuning_out.c_str()); return 2; }
266        f << "# rocBLAS solution indices for the prompt path's FP16-out GEMMs; valid for this architecture and rocBLAS build only\n";
267        f << "# rows: type N K ldy T solution   (type f16o: FP16 in, FP16 out, FP32 compute; Gemm::f16_inplace)\n";
268        f << "# solution: rocBLAS's solution index, or `default` where its own choice measured best at that bucket\n";
269        f << "STRATA_ROCBLAS_TUNING_V1 " << arch << " " << ver << "\n";
270        size_t tuned = 0;
271        for (const auto& r : rows) {
272            f << "f16o " << r.s.n << " " << r.s.k << " " << r.s.ldy << " " << r.s.t << " ";
273            if (r.tuned) { f << r.solution << "   # " << r.default_ms << " ms -> " << r.best_ms << " ms\n"; ++tuned; }
274            else f << "default   # " << r.default_ms << " ms\n";
275        }
276        std::printf("wrote %zu rows (%zu with a solution) to %s\n", rows.size(), tuned, o.tuning_out.c_str());
277    }
278    HIP_CHECK(hipEventDestroy(ea)); HIP_CHECK(hipEventDestroy(eb));
279    HIP_CHECK(hipStreamDestroy(stream)); RB_CHECK(rocblas_destroy_handle(h));
280    return 0;
281}