okami.mom/strata

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

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

main
6.7 KiB130 linesraw
1// BF16/F16 prefill through the actual engine GEMM path against a CPU reference.
2//
3// Each shape runs twice: on the engine's GEMM as every card runs it (FP32 out), and with Gemm::set_f16_io(true), the
4// gfx103x prompt path's FP16-out GEMM widened in place in Y's own rows (bench/results/2026-10-04-rdna2-fp16-prompt).
5// The second mode is forced here on any HIP card, so the path is covered wherever the test runs.
6#include <hip/hip_runtime.h>
7#include <hip/hip_bfloat16.h>
8#include <hip/hip_fp16.h>
9#include "strata/prefill/gemm.hpp"
10#include <algorithm>
11#include <cmath>
12#include <cstdio>
13#include <cstdlib>
14#include <cstring>
15#include <random>
16#include <vector>
17
18#define CHECK(call) do { const auto e = (call); if (e != hipSuccess) { \
19    std::fprintf(stderr, "%s: %s\n", #call, hipGetErrorString(e)); std::exit(2); } } while (0)
20
21struct Buffer {
22    void* p = nullptr;
23    explicit Buffer(size_t bytes) { CHECK(hipMalloc(&p, bytes)); }
24    ~Buffer() { if (p) (void) hipFree(p); }
25};
26
27// `f16_io`: the Gemm was set_f16_io(true).  bf16() then takes X as the prompt path's FP16 image (W stays BF16), and
28// every GEMM with beta = 0 writes its result as FP16 before widening it: those are checked at FP16's rounding
29// (2^-11 relative per element, plus the FP32 accumulation) instead of the FP32-out tolerance.  beta = 1 keeps the
30// FP32-out GEMM on the f16() path, and bf16() refuses it there (the prompt path never accumulates a BF16 product).
31bool run(strata::prefill::Gemm& gemm, hipStream_t stream, bool bf16,
32         int t, int n, int k, int ldy, float beta, bool f16_io = false) {
33    std::mt19937 rng(51012 + t + n);
34    std::uniform_real_distribution<float> dist(-0.25f, 0.25f);
35    std::vector<uint16_t> x((size_t)t*k), w((size_t)n*k);
36    std::vector<float> xf(x.size()), wf(w.size());
37    auto fill = [&](auto& bits, auto& values, bool as_bf16) {
38        for (size_t i = 0; i < bits.size(); ++i) {
39            if (as_bf16) {
40                // the BF16 bits by hand (round to nearest even on the float's bits): hip_bfloat16(float) produced
41                // data 0 in this test's build (ROCm 10.0, not traced further), so both BF16 cases passed on all-zero
42                // inputs
43                const float f = dist(rng);
44                uint32_t u; std::memcpy(&u, &f, 4);
45                u += 0x7fffu + ((u >> 16) & 1u);
46                bits[i] = static_cast<uint16_t>(u >> 16);
47                const uint32_t wide = static_cast<uint32_t>(bits[i]) << 16;
48                std::memcpy(&values[i], &wide, 4);
49            } else {
50                const __half v = __float2half_rn(dist(rng));
51                std::memcpy(&bits[i], &v, 2);
52                values[i] = __half2float(v);
53            }
54        }
55    };
56    fill(x, xf, bf16 && !f16_io); fill(w, wf, bf16);
57    const bool f16_out = f16_io && (bf16 || beta == 0.0f);
58    constexpr int offset = 5;
59    std::vector<float> initial(offset + (size_t)t*ldy + 8, -777.25f);
60    for (int r = 0; r < t; ++r) for (int c = 0; c < n; ++c)
61        initial[offset + (size_t)r*ldy + c] = (r+c)%17 * 0.03125f;
62    Buffer dx(x.size()*2), dw(w.size()*2), dy(initial.size()*4);
63    CHECK(hipMemcpyAsync(dx.p,x.data(),x.size()*2,hipMemcpyHostToDevice,stream));
64    CHECK(hipMemcpyAsync(dw.p,w.data(),w.size()*2,hipMemcpyHostToDevice,stream));
65    CHECK(hipMemcpyAsync(dy.p,initial.data(),initial.size()*4,hipMemcpyHostToDevice,stream));
66    if (bf16) gemm.bf16((const uint16_t*)dx.p,(const uint16_t*)dw.p,(float*)dy.p+offset,t,n,k,ldy,beta);
67    else gemm.f16((const uint16_t*)dx.p,(const uint16_t*)dw.p,(float*)dy.p+offset,t,n,k,ldy,beta);
68    CHECK(hipStreamSynchronize(stream));
69    std::vector<float> got(initial.size());
70    CHECK(hipMemcpy(got.data(),dy.p,got.size()*4,hipMemcpyDeviceToHost));
71    std::vector<bool> active(got.size());
72    double diff2=0, ref2=0, maximum=0;
73    bool ok=true;
74    for (int r=0;r<t;++r) for (int c=0;c<n;++c) {
75        const size_t j=offset+(size_t)r*ldy+c;
76        active[j]=true;
77        double ref=beta*initial[j];
78        for (int i=0;i<k;++i) ref+=(double)xf[(size_t)r*k+i]*wf[(size_t)c*k+i];
79        const double d=(double)got[j]-ref;
80        ok=ok && std::isfinite(got[j]);
81        if (f16_out) ok=ok && std::abs(d) <= 6e-4*std::abs(ref) + 1e-4;
82        diff2+=d*d; ref2+=ref*ref; maximum=std::max(maximum,std::abs(d));
83    }
84    // the padding of every row (ldy > n) and the guards before and after Y: untouched by the GEMM and the widening
85    for (size_t j=0;j<got.size();++j) if (!active[j]) ok=ok && got[j]==initial[j];
86    const double rel=std::sqrt(diff2/std::max(ref2,1e-300));
87    ok=ok && (f16_out ? rel<1e-3 : (rel<1e-4 && maximum<5e-3));
88    std::printf("%s %s%s T=%d N=%d K=%d ldy=%d beta=%.1f rel_l2=%.3g max_abs=%.3g\n",
89                ok?"PASS":"FAIL",bf16?"BF16":"F16",f16_io?" (f16 io)":"",t,n,k,ldy,beta,rel,maximum);
90    return ok;
91}
92
93int main() {
94    setvbuf(stdout,nullptr,_IONBF,0);
95    hipStream_t stream;
96    CHECK(hipStreamCreateWithFlags(&stream,hipStreamNonBlocking));
97    bool ok=true;
98    {
99        strata::prefill::Gemm gemm;
100        std::string error;
101        if (!gemm.init(stream,0,error)) { std::fprintf(stderr,"%s\n",error.c_str()); return 2; }
102        ok=run(gemm,stream,true,16,96,2560,96,0) && ok;
103        ok=run(gemm,stream,true,17,48,2560,64,1) && ok;
104        ok=run(gemm,stream,false,32,640,2560,648,0) && ok;
105        ok=run(gemm,stream,false,64,2560,640,2560,1) && ok;
106        // RDNA2 (gfx103x) runs N >= 64 as an SGEMM on FP32 copies, the activations in slices of 32M floats
107        // (Gemm::rdna2_sgemm): at K = 10240 a slice is 3,276 rows, so these cross a slice boundary (padded ldy, beta 1).
108        // Other cards run them on the native path.
109        ok=run(gemm,stream,false,3300,64,10240,72,1) && ok;
110        ok=run(gemm,stream,true,3300,64,10240,64,0) && ok;
111    }
112    {
113        // The FP16-io mode.  The scratch holds 64 rows at K = 2560, so bf16()'s W conversion slices N = 96 in two
114        // (64 + 32 rows, the second written at Y + 64).  ldy > N and the odd N check widen_rows_f16's in-place
115        // walk (FP16 halves at the start of each FP32 row); T = 1 is a single block.
116        strata::prefill::Gemm gemm;
117        std::string error;
118        if (!gemm.init(stream,64*2560,error)) { std::fprintf(stderr,"%s\n",error.c_str()); return 2; }
119        gemm.set_f16_io(true);
120        ok=run(gemm,stream,true,16,96,2560,96,0,true) && ok;
121        ok=run(gemm,stream,true,17,48,2560,64,0,true) && ok;
122        ok=run(gemm,stream,false,32,640,2560,648,0,true) && ok;
123        ok=run(gemm,stream,false,64,2560,640,2560,0,true) && ok;
124        ok=run(gemm,stream,false,33,257,640,264,0,true) && ok;
125        ok=run(gemm,stream,false,1,96,2560,96,0,true) && ok;
126        ok=run(gemm,stream,false,17,48,2560,64,1,true) && ok;
127    }
128    CHECK(hipStreamDestroy(stream));
129    return ok?0:1;
130}