okami.mom/strata

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

Niko1221Merge branch 'f-132-pr' into rel-0.1.32b0abdeb44

main
17.5 KiB305 linesraw
1// bench_tc_gemv.cu - ISOLATED benchmark: BF16 GEMV baseline vs Tensor Core (mma.m16n8k8, BF16->FP16) on sm_75.
2// Nothing in the engine changes. Shapes are the REAL Strata decode GEMVs (BF16 weights, n_in = n_embd = 2560):
3//   ssm_alpha / ssm_beta   [2560, 48]   project_bf16(split=true)  -> bf16_gemv_split(TPR=32) -> warp kernel
4//   indexer.k_proj         [2560, 128]  project_bf16(split=false) -> bf16_gemv -> warp kernel
5//   indexer.q_proj / ffn_gate_inp / mlp.gate [2560, 512]  warp / split(TPR=32) -> warp kernel
6//   ple_value              [2560, 2560] warp
7// Baseline = bf16_gemv_warp_kernel transcribed verbatim from src/kernels/cuda/bf16_gemv.cu (production).
8// TC variant = same maths; A = x broadcast down m16 (single-token GEMV), k-chunk = 8;
9//   (a) W preconverted bf16->fp16 once, x converted in-kernel (timed)   [tc_preconv]
10//   (b) fully inline: W read as bf16 and converted in-register           [tc_inline]
11// Numerics: fp64 host reference; max abs err for baseline and both TC variants; bf16->fp16 exactness scan.
12#include <cuda_runtime.h>
13#include <cuda_fp16.h>
14#include <cstdio>
15#include <cstdint>
16#include <cstring>
17#include <cstdlib>
18#include <cmath>
19#include <vector>
20#include <string>
21#include <functional>
22#include <algorithm>
23
24#define CHECK(e) do { cudaError_t err_ = (e); if (err_ != cudaSuccess) { \
25    fprintf(stderr, "CUDA %s:%d %s\n", __FILE__, __LINE__, cudaGetErrorString(err_)); exit(1); } } while (0)
26
27__device__ __forceinline__ float bf16_f32(uint16_t v) { return __int_as_float((int) ((unsigned) v << 16)); }
28static float bf16_f32_host(uint16_t v) { unsigned u = (unsigned) v << 16; float f; memcpy(&f, &u, 4); return f; }
29static uint16_t f32_bf16_host(float f) {
30    unsigned u, r; memcpy(&u, &f, 4);
31    r = ((u >> 16) ^ (u >> 15)) & 1; u += 0x7fff + r;
32    return (uint16_t) (u >> 16);
33}
34
35// ============ baseline: production warp kernel (verbatim semantics from bf16_gemv.cu) ============
36__global__ void gemv_warp(const uint16_t* __restrict__ x, const uint16_t* __restrict__ w,
37                          float* __restrict__ y, long long n_in, long long n_out) {
38    const long long o = (long long) blockIdx.x * (blockDim.x >> 5) + (threadIdx.x >> 5);
39    if (o >= n_out) return;
40    const int lane = threadIdx.x & 31;
41    const uint16_t* row = w + o * n_in;
42    float acc = 0.0f;
43    for (long long i = lane; i < n_in; i += 32)
44        acc += bf16_f32(x[i]) * bf16_f32(row[i]);
45    for (int off = 16; off > 0; off >>= 1) acc += __shfl_down_sync(0xFFFFFFFFu, acc, off);
46    if (lane == 0) y[o] = acc;
47}
48
49// ============ TC: A(x) broadcast, k-split over blocks, partial D row 0 -> scratch ============
50// A fragment (m16n8k8, .f16): lane l: a0 = A[m=l>>2][k=2(l&3)], a1 = A[m][k=2(l&3)+1],
51//                               a2/a3 = same cols at row m+8.  Broadcast => a2=a0, a3=a1.
52// B fragment (.f16, col-major): lane l: b0 = B[k=2(l&3)][n=(l>>2)], b1 = B[k=2(l&3)+1][n].
53//   B[k][n] = W[n][k], so lane l loads W[n][2(l&3)], W[n][2(l&3)+1] - coalesced within the row.
54// D fragment: c0/c1 = D[m=l>>2][cols 2(l&3), +1], c2/c3 = row m+8.  All m rows identical -> row 0.
55__global__ void tc_preconv(const uint16_t* __restrict__ x_b, const uint16_t* __restrict__ w_f,
56                           float* __restrict__ partials, long long n_in, long long n_out, int ks) {
57    const int tile = blockIdx.x, ks_i = blockIdx.y, lane = threadIdx.x & 31;
58    const long long n_base = (long long) tile * 8;
59    const long long k_per = n_in / (long long) ks;
60    const long long k0 = (long long) ks_i * k_per;
61    const int t2 = 2 * (lane & 3);
62    float c0 = 0.f, c1 = 0.f, c2 = 0.f, c3 = 0.f;
63    for (long long kk0 = k0; kk0 < k0 + k_per; kk0 += 8) {
64        // A (2 x f16x2): a0 = {A[m][2t], A[m+8][2t]}, a1 = {A[m][2t+1], A[m+8][2t+1]} (broadcast -> dup halves)
65        unsigned xh = (unsigned) x_b[kk0 + t2] | ((unsigned) x_b[kk0 + t2 + 1] << 16);
66        // fp16 conversion in-register: bf16 -> f32 -> f16 (exact within fp16 range)
67        __half2 ha = __floats2half2_rn(bf16_f32((uint16_t) (xh & 0xFFFF)), bf16_f32((uint16_t) (xh >> 16)));
68        __half2 hb = __floats2half2_rn(bf16_f32((uint16_t) (xh & 0xFFFF)), bf16_f32((uint16_t) (xh >> 16)));
69        unsigned a0 = *reinterpret_cast<unsigned*>(&ha);
70        unsigned a1 = *reinterpret_cast<unsigned*>(&hb);
71        // B is already fp16 here: load as __half2 directly (bf16 path must NOT convert twice)
72        __half2 wbh = *reinterpret_cast<const __half2*>(&w_f[(n_base + (lane >> 2)) * n_in + kk0 + t2]);
73        unsigned b0 = *reinterpret_cast<unsigned*>(&wbh);
74        asm volatile("mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5}, {%6}, {%0,%1,%2,%3};\n"
75                     : "+f"(c0), "+f"(c1), "+f"(c2), "+f"(c3)
76                     : "r"(a0), "r"(a1), "r"(b0));
77    }
78    if (lane < 4) { float* p = partials + (size_t) (tile * ks + ks_i) * 8; p[t2] = c0; p[t2 + 1] = c1; }
79}
80
81// same, but W stays bf16 and converts in-register (fully fair per-call cost)
82__global__ void tc_inline(const uint16_t* __restrict__ x_b, const uint16_t* __restrict__ w_b,
83                          float* __restrict__ partials, long long n_in, long long n_out, int ks) {
84    const int tile = blockIdx.x, ks_i = blockIdx.y, lane = threadIdx.x & 31;
85    const long long n_base = (long long) tile * 8;
86    const long long k_per = n_in / (long long) ks;
87    const long long k0 = (long long) ks_i * k_per;
88    const int t2 = 2 * (lane & 3);
89    float c0 = 0.f, c1 = 0.f, c2 = 0.f, c3 = 0.f;
90    for (long long kk0 = k0; kk0 < k0 + k_per; kk0 += 8) {
91        unsigned xh = (unsigned) x_b[kk0 + t2] | ((unsigned) x_b[kk0 + t2 + 1] << 16);
92        __half2 ha = __floats2half2_rn(bf16_f32((uint16_t) (xh & 0xFFFF)), bf16_f32((uint16_t) (xh >> 16)));
93        __half2 hb = __floats2half2_rn(bf16_f32((uint16_t) (xh & 0xFFFF)), bf16_f32((uint16_t) (xh >> 16)));
94        unsigned a0 = *reinterpret_cast<unsigned*>(&ha);
95        unsigned a1 = *reinterpret_cast<unsigned*>(&hb);
96        const uint16_t* wbv = w_b + (n_base + (lane >> 2)) * n_in + kk0 + t2;
97        __half2 wbh = __floats2half2_rn(bf16_f32(wbv[0]), bf16_f32(wbv[1]));
98        unsigned b0 = *reinterpret_cast<unsigned*>(&wbh);
99        asm volatile("mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5}, {%6}, {%0,%1,%2,%3};\n"
100                     : "+f"(c0), "+f"(c1), "+f"(c2), "+f"(c3)
101                     : "r"(a0), "r"(a1), "r"(b0));
102    }
103    if (lane < 4) { float* p = partials + (size_t) (tile * ks + ks_i) * 8; p[t2] = c0; p[t2 + 1] = c1; }
104}
105
106__global__ void tc_reduce(const float* __restrict__ partials, float* __restrict__ y, long long n_out, int ks) {
107    const long long o = blockIdx.x * blockDim.x + threadIdx.x;
108    if (o >= n_out) return;
109    float s = 0.f;
110    for (int q = 0; q < ks; ++q) s += partials[(size_t) ((o >> 3) * ks + q) * 8 + (o & 7)];
111    y[o] = s;
112}
113
114// variant with the OTHER candidate A layout: a0 = {A[gid][2t], A[gid+8][2t]} (same k-col, two rows),
115// a1 = same for col 2t+1. Broadcast => both halves of a0 hold x[2t], both halves of a1 hold x[2t+1].
116__global__ void tc_dupcol(const uint16_t* __restrict__ x_b, const uint16_t* __restrict__ w_b,
117                          float* __restrict__ partials, long long n_in, long long n_out, int ks) {
118    const int tile = blockIdx.x, ks_i = blockIdx.y, lane = threadIdx.x & 31;
119    const long long n_base = (long long) tile * 8;
120    const long long k_per = n_in / (long long) ks;
121    const long long k0 = (long long) ks_i * k_per;
122    const int t2 = 2 * (lane & 3);
123    float c0 = 0.f, c1 = 0.f, c2 = 0.f, c3 = 0.f;
124    for (long long kk0 = k0; kk0 < k0 + k_per; kk0 += 8) {
125        __half2 ha = __floats2half2_rn(bf16_f32(x_b[kk0 + t2]), bf16_f32(x_b[kk0 + t2]));
126        __half2 hb = __floats2half2_rn(bf16_f32(x_b[kk0 + t2 + 1]), bf16_f32(x_b[kk0 + t2 + 1]));
127        unsigned a0 = *reinterpret_cast<unsigned*>(&ha);
128        unsigned a1 = *reinterpret_cast<unsigned*>(&hb);
129        const uint16_t* wbv = w_b + (n_base + (lane >> 2)) * n_in + kk0 + t2;
130        __half2 wbh = __floats2half2_rn(bf16_f32(wbv[0]), bf16_f32(wbv[1]));
131        unsigned b0 = *reinterpret_cast<unsigned*>(&wbh);
132        asm volatile("mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5}, {%6}, {%0,%1,%2,%3};\n"
133                     : "+f"(c0), "+f"(c1), "+f"(c2), "+f"(c3)
134                     : "r"(a0), "r"(a1), "r"(b0));
135    }
136    if (lane < 4) { float* p = partials + (size_t) (tile * ks + ks_i) * 8; p[t2] = c0; p[t2 + 1] = c1; }
137}
138
139// FUSED, ks=1 only: with a single k-fragment the partial IS the answer -> write y directly, no reduce kernel,
140// no scratch. Fully inline bf16 W conversion (fairest per-call TC cost).
141__global__ void tc_fused(const uint16_t* __restrict__ x_b, const uint16_t* __restrict__ w_b,
142                         float* __restrict__ y, long long n_in, long long n_out) {
143    const int tile = blockIdx.x, lane = threadIdx.x & 31;
144    const long long n_base = (long long) tile * 8;
145    const int t2 = 2 * (lane & 3);
146    float c0 = 0.f, c1 = 0.f, c2 = 0.f, c3 = 0.f;
147    for (long long kk0 = 0; kk0 < n_in; kk0 += 8) {
148        __half2 ha = __floats2half2_rn(bf16_f32(x_b[kk0 + t2]), bf16_f32(x_b[kk0 + t2 + 1]));
149        __half2 hb = ha;   // broadcast: row gid+8 = row gid (single-token GEMV)
150        unsigned a0 = *reinterpret_cast<unsigned*>(&ha);
151        unsigned a1 = *reinterpret_cast<unsigned*>(&hb);
152        const uint16_t* wbv = w_b + (n_base + (lane >> 2)) * n_in + kk0 + t2;
153        __half2 wbh = __floats2half2_rn(bf16_f32(wbv[0]), bf16_f32(wbv[1]));
154        unsigned b0 = *reinterpret_cast<unsigned*>(&wbh);
155        asm volatile("mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5}, {%6}, {%0,%1,%2,%3};\n"
156                     : "+f"(c0), "+f"(c1), "+f"(c2), "+f"(c3)
157                     : "r"(a0), "r"(a1), "r"(b0));
158    }
159    if (lane < 4) { y[n_base + t2] = c0; y[n_base + t2 + 1] = c1; }
160}
161
162int main() {
163    CHECK(cudaSetDevice(0));
164    cudaDeviceProp prop; CHECK(cudaGetDeviceProperties(&prop, 0));
165    printf("device: %s, SMs %d, capability %d.%d\n", prop.name, prop.multiProcessorCount, prop.major, prop.minor);
166
167    struct Shape { const char* name; long long n_in, n_out; };
168    Shape shapes[] = {
169        {"ssm_alpha/beta [2560,48]", 2560, 48},
170        {"indexer.k_proj [2560,128]", 2560, 128},
171        {"q_proj/router [2560,512]", 2560, 512},
172        {"ple_value [2560,2560]", 2560, 2560},
173    };
174    auto rng = [](unsigned& s) { s = s * 1664525u + 1013904223u; return (float) ((s >> 8) & 0xFFFF) / 65535.0f - 0.5f; };
175    const int ITERS = 2000, WARM = 300;
176
177    printf("\n%-26s %13s | %s\n", "shape", "baseline us", "tc variants (pc = W preconverted, in = inline conversion, fused = no reduce), speedup vs baseline");
178    printf("%s\n", std::string(150, '-').c_str());
179
180    for (auto& sh : shapes) {
181        const long long n_in = sh.n_in, n_out = sh.n_out;
182        const size_t wn = (size_t) n_out * n_in;
183        std::vector<uint16_t> hw(wn), hx(n_in), hf(wn);
184        std::vector<float> hyb(n_out), hypc(n_out), hyin(n_out), hyfu(n_out);
185        std::vector<double> href(n_out);
186        unsigned seed = 991u + (unsigned) (n_out & 0xFFF);
187        for (size_t i = 0; i < wn; ++i) hw[i] = f32_bf16_host(rng(seed) * 0.3f);
188        for (long long i = 0; i < n_in; ++i) hx[i] = f32_bf16_host(rng(seed) * 3.0f);
189        for (long long o = 0; o < n_out; ++o) {
190            double s = 0.0;
191            for (long long i = 0; i < n_in; ++i) s += (double) bf16_f32_host(hx[i]) * (double) bf16_f32_host(hw[(size_t) o * n_in + i]);
192            href[o] = s;
193        }
194        // preconvert W to fp16 (bf16 -> fp16 is exact within fp16 range)
195        for (size_t i = 0; i < wn; ++i) { __half h = __float2half_rn(bf16_f32_host(hw[i])); memcpy(&hf[i], &h, 2); }
196
197        uint16_t *dx, *dw, *dwf; float *dy, *dyp;
198        CHECK(cudaMalloc(&dx, n_in * 2));
199        CHECK(cudaMalloc(&dw, wn * 2)); CHECK(cudaMalloc(&dwf, wn * 2));
200        CHECK(cudaMalloc(&dy, n_out * 4));
201        CHECK(cudaMalloc(&dyp, (size_t)(n_out / 8) * 65 * 8 * 4));
202        CHECK(cudaMemcpy(dx, hx.data(), n_in * 2, cudaMemcpyHostToDevice));
203        CHECK(cudaMemcpy(dw, hw.data(), wn * 2, cudaMemcpyHostToDevice));
204        CHECK(cudaMemcpy(dwf, hf.data(), wn * 2, cudaMemcpyHostToDevice));
205
206        // one-time W conversion cost (host->device, reported separately; the engine would fold this
207        // into the weight load exactly like Gemm::bf16 does for sm<80)
208        {
209            cudaEvent_t e0, e1; CHECK(cudaEventCreate(&e0)); CHECK(cudaEventCreate(&e1));
210            CHECK(cudaEventRecord(e0));
211            CHECK(cudaMemcpy(dwf, hf.data(), wn * 2, cudaMemcpyHostToDevice));
212            CHECK(cudaEventRecord(e1)); CHECK(cudaEventSynchronize(e1));
213            float ms = 0; CHECK(cudaEventElapsedTime(&ms, e0, e1));
214            printf("%-26s one-time W convert: %.2f ms (%.1f MB), tiles=%lld\n", sh.name, ms, wn * 2 / 1e6, n_out / 8);
215        }
216
217        int tiles = (int) (n_out / 8);
218        // valid ks must divide n_in so each k-chunk is a multiple of 8; sweep ALL of them, report the best
219        const int cands[11] = {1, 2, 4, 5, 8, 10, 16, 20, 32, 40, 64};
220
221        auto timeit = [&](const char* tag, const std::function<void()>& fn) -> double {
222            for (int i = 0; i < WARM; ++i) fn();
223            CHECK(cudaDeviceSynchronize());
224            double best = 1e30;
225            for (int rep = 0; rep < 3; ++rep) {
226                cudaEvent_t e0, e1; CHECK(cudaEventCreate(&e0)); CHECK(cudaEventCreate(&e1));
227                CHECK(cudaEventRecord(e0));
228                for (int i = 0; i < ITERS; ++i) fn();
229                CHECK(cudaEventRecord(e1)); CHECK(cudaEventSynchronize(e1));
230                float ms = 0; CHECK(cudaEventElapsedTime(&ms, e0, e1));
231                double us = ms * 1000.0 / ITERS;
232                if (us < best) best = us;
233            }
234            (void) tag; return best;
235        };
236
237        double t_base = timeit("base", [&]{ gemv_warp<<<(unsigned) ((n_out + 7) / 8), 256>>>(dx, dw, dy, n_in, n_out); });
238        gemv_warp<<<(unsigned) ((n_out + 7) / 8), 256>>>(dx, dw, dy, n_in, n_out);
239        CHECK(cudaMemcpy(hyb.data(), dy, n_out * 4, cudaMemcpyDeviceToHost));
240
241        // occupancy sweep over k-chunk count for the preconverted-W TC kernel
242        int best_ks = 1; double t_pc = 1e30;
243        for (int i = 0; i < 11; ++i) {
244            const int ksv = cands[i];
245            if (n_in % ksv != 0) continue;
246            dim3 g((unsigned) tiles, (unsigned) ksv);
247            double t = timeit("pcs", [&]{ tc_preconv<<<g, 32>>>(dx, dwf, dyp, n_in, n_out, ksv);
248                                          tc_reduce<<<(unsigned) ((n_out + 255) / 256), 256>>>(dyp, dy, n_out, ksv); });
249            if (t < t_pc) { t_pc = t; best_ks = ksv; }
250        }
251        dim3 gtc((unsigned) tiles, (unsigned) best_ks);
252        tc_preconv<<<gtc, 32>>>(dx, dwf, dyp, n_in, n_out, best_ks);
253        tc_reduce<<<(unsigned) ((n_out + 255) / 256), 256>>>(dyp, dy, n_out, best_ks);
254        CHECK(cudaMemcpy(hypc.data(), dy, n_out * 4, cudaMemcpyDeviceToHost));
255
256        double t_ti = timeit("tci", [&]{ tc_inline<<<gtc, 32>>>(dx, dw, dyp, n_in, n_out, best_ks);
257                                         tc_reduce<<<(unsigned) ((n_out + 255) / 256), 256>>>(dyp, dy, n_out, best_ks); });
258        tc_inline<<<gtc, 32>>>(dx, dw, dyp, n_in, n_out, best_ks);
259        tc_reduce<<<(unsigned) ((n_out + 255) / 256), 256>>>(dyp, dy, n_out, best_ks);
260        CHECK(cudaMemcpy(hyin.data(), dy, n_out * 4, cudaMemcpyDeviceToHost));
261
262        double t_fu = timeit("tcf", [&]{ tc_fused<<<(unsigned) tiles, 32>>>(dx, dw, dy, n_in, n_out); });
263        tc_fused<<<(unsigned) tiles, 32>>>(dx, dw, dy, n_in, n_out);
264        CHECK(cudaMemcpy(hyfu.data(), dy, n_out * 4, cudaMemcpyDeviceToHost));
265
266        double best_tc = t_pc; const char* best_var = "preconv";
267        if (t_ti < best_tc) { best_tc = t_ti; best_var = "inline"; }
268        if (t_fu < best_tc) { best_tc = t_fu; best_var = "fused"; }
269
270        double e_tc = 0, e_base = 0, sc = 0;
271        if (strcmp(best_var, "preconv") == 0) {
272            for (long long o = 0; o < n_out; ++o) { e_tc = std::max(e_tc, std::fabs((double) hypc[o] - href[o])); }
273        } else if (strcmp(best_var, "inline") == 0) {
274            for (long long o = 0; o < n_out; ++o) { e_tc = std::max(e_tc, std::fabs((double) hyin[o] - href[o])); }
275        } else {
276            for (long long o = 0; o < n_out; ++o) { e_tc = std::max(e_tc, std::fabs((double) hyfu[o] - href[o])); }
277        }
278        for (long long o = 0; o < n_out; ++o) {
279            e_base = std::max(e_base, std::fabs((double) hyb[o] - href[o]));
280            sc = std::max(sc, std::fabs(href[o]));
281        }
282        double gb_base = (double) (wn * 2) / t_base / 1e3;
283        double gb_tc = (double) (wn * 2) / best_tc / 1e3;
284        printf("%-26s %13.3f | pc %13.3f (ks=%d) | in %13.3f | fused %13.3f | BEST %s %7.3fx | maxerr tc %.2e base %.2e  (scale %.1f, BW base %.0f tc %.0f GB/s)\n",
285               sh.name, t_base, t_pc, best_ks, t_ti, t_fu, best_var, t_base / best_tc,
286               e_tc, e_base, sc, gb_base, gb_tc);
287
288        CHECK(cudaFree(dx)); CHECK(cudaFree(dw)); CHECK(cudaFree(dwf)); CHECK(cudaFree(dy)); CHECK(cudaFree(dyp));
289    }
290
291    {   // bf16 -> fp16 exactness scan
292        unsigned seed = 777u; double worst = 0; int bad = 0, n = 2000000;
293        for (int i = 0; i < n; ++i) {
294            float f = (rng(seed) * 2.0f - 1.0f) * 100.0f;
295            uint16_t b = f32_bf16_host(f);
296            __half h = __float2half_rn(bf16_f32_host(b));
297            if ((double) __half2float(h) != (double) bf16_f32_host(b)) {
298                bad++; worst = std::max(worst, std::fabs((double) __half2float(h) - (double) bf16_f32_host(b)));
299            }
300        }
301        printf("\nbf16->fp16 conversion exactness: %d / %d inexact, worst %.3g\n", bad, n, worst);
302    }
303    printf("BENCH_DONE\n");
304    return 0;
305}