// BF16/F16 prefill through the actual engine GEMM path against a CPU reference. #include #include #include #include "strata/prefill/gemm.hpp" #include #include #include #include #include #include #include #define CHECK(call) do { const auto e = (call); if (e != hipSuccess) { \ std::fprintf(stderr, "%s: %s\n", #call, hipGetErrorString(e)); std::exit(2); } } while (0) struct Buffer { void* p = nullptr; explicit Buffer(size_t bytes) { CHECK(hipMalloc(&p, bytes)); } ~Buffer() { if (p) (void) hipFree(p); } }; bool run(strata::prefill::Gemm& gemm, hipStream_t stream, bool bf16, int t, int n, int k, int ldy, float beta) { std::mt19937 rng(51012 + t + n); std::uniform_real_distribution dist(-0.25f, 0.25f); std::vector x((size_t)t*k), w((size_t)n*k); std::vector xf(x.size()), wf(w.size()); auto fill = [&](auto& bits, auto& values) { for (size_t i = 0; i < bits.size(); ++i) { if (bf16) { const hip_bfloat16 v(dist(rng)); bits[i] = v.data; const uint32_t wide = static_cast(v.data) << 16; std::memcpy(&values[i], &wide, 4); } else { const __half v = __float2half_rn(dist(rng)); std::memcpy(&bits[i], &v, 2); values[i] = __half2float(v); } } }; fill(x, xf); fill(w, wf); constexpr int offset = 5; std::vector initial(offset + (size_t)t*ldy + 8, -777.25f); for (int r = 0; r < t; ++r) for (int c = 0; c < n; ++c) initial[offset + (size_t)r*ldy + c] = (r+c)%17 * 0.03125f; Buffer dx(x.size()*2), dw(w.size()*2), dy(initial.size()*4); CHECK(hipMemcpyAsync(dx.p,x.data(),x.size()*2,hipMemcpyHostToDevice,stream)); CHECK(hipMemcpyAsync(dw.p,w.data(),w.size()*2,hipMemcpyHostToDevice,stream)); CHECK(hipMemcpyAsync(dy.p,initial.data(),initial.size()*4,hipMemcpyHostToDevice,stream)); if (bf16) gemm.bf16((const uint16_t*)dx.p,(const uint16_t*)dw.p,(float*)dy.p+offset,t,n,k,ldy,beta); else gemm.f16((const uint16_t*)dx.p,(const uint16_t*)dw.p,(float*)dy.p+offset,t,n,k,ldy,beta); CHECK(hipStreamSynchronize(stream)); std::vector got(initial.size()); CHECK(hipMemcpy(got.data(),dy.p,got.size()*4,hipMemcpyDeviceToHost)); std::vector active(got.size()); double diff2=0, ref2=0, maximum=0; bool ok=true; for (int r=0;r