okami.mom/strata

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

Niko1221Merge branch 'f-1402-w' into f-140253623e56f

main
20.9 KiB449 linesraw
1// tests/hip/prefill_wmma_gemm_parity.cpp - Numerical parity test for RDNA3 WMMA GEMM kernels.
2#include <cuda_runtime.h>
3#include <hip/hip_bfloat16.h>
4#include <hip/hip_fp16.h>
5
6#include "wmma_gemm.h"
7#include "strata/kernels/gfx_arch.hpp"
8
9#include <algorithm>
10#include <cmath>
11#include <cstdint>
12#include <cstdio>
13#include <cstdlib>
14#include <cstring>
15#include <limits>
16#include <random>
17#include <string>
18#include <vector>
19
20// ============================================================================
21// Exact Representability & Parity Rationale:
22//
23// Inputs (X, W, and initial Y for beta=1) are chosen from discrete binary fractions
24// k / 16.0f with integer k in [-8, 8].
25//
26// In IEEE 754 half-precision (fp16, 10-bit explicit mantissa) and bfloat16
27// (7-bit explicit mantissa), every such value k * 2^-4 requires at most 4 bits
28// of significand and is therefore EXACTLY representable without rounding.
29//
30// The product of any two such values is an exact integer multiple of 2^-8:
31//   (a * 2^-4) * (b * 2^-4) = (a * b) * 2^-8
32// with (a * b) in [-64, 64].
33//
34// For K <= 80, the sum of K products:
35//   sum_k (W[n, k] * X[t, k]) = (sum_k a_k * b_k) * 2^-8
36// has a maximum absolute magnitude of 80 * (0.5 * 0.5) = 20.0, and the integer
37// numerator cannot exceed 80 * 64 = 5120 (< 2^13).
38//
39// In IEEE 754 single-precision (fp32, 23-bit explicit mantissa, 24 bits total),
40// any integer multiple of 2^-8 up to 20.0 requires at most 13 bits of significand.
41// Because the RDNA3 hardware instructions (v_wmma_f32_16x16x16_f16_w32 and
42// v_wmma_f32_16x16x16_bf16_w32) accumulate in native FP32 registers, every
43// intermediate product and addition has ZERO truncation or rounding error.
44//
45// Furthermore, floating-point addition of exact binary fractions whose sum fits
46// within the mantissa is strictly associative and exact. Consequently, the GPU
47// WMMA pipeline and the CPU reference compute identical bitwise results, making
48// an exact assertion (max_abs == 0.0f) mathematically legitimate.
49// ============================================================================
50
51#define HIP_CHECK(call) do { \
52    const hipError_t status_ = (call); \
53    if (status_ != hipSuccess) { \
54        std::fprintf(stderr, "HIP failure at %s:%d: %s: %s\n", __FILE__, __LINE__, #call, hipGetErrorString(status_)); \
55        std::exit(2); \
56    } \
57} while (0)
58
59namespace {
60
61constexpr float kSentinel = -999.5f;
62
63struct DeviceBuffer {
64    void* p = nullptr;
65    explicit DeviceBuffer(size_t bytes) { if (bytes) HIP_CHECK(hipMalloc(&p, bytes)); }
66    ~DeviceBuffer() { if (p) (void) hipFree(p); }
67    DeviceBuffer(const DeviceBuffer&) = delete;
68    DeviceBuffer& operator=(const DeviceBuffer&) = delete;
69};
70
71uint16_t encode(float value, bool bf16) {
72    if (bf16) return hip_bfloat16(value).data;
73    const __half half = __float2half_rn(value);
74    return static_cast<__half_raw>(half).x;
75}
76
77float decode(uint16_t bits, bool bf16) {
78    if (bf16) {
79        const uint32_t u = static_cast<uint32_t>(bits) << 16;
80        float f = 0.0f;
81        std::memcpy(&f, &u, sizeof(f));
82        return f;
83    }
84    const __half_raw raw{bits};
85    return __half2float(__half(raw));
86}
87
88struct MismatchRecord {
89    const char* dtype = "";
90    int64_t T = 0, N = 0, K = 0, ldy = 0;
91    float beta = 0.0f;
92    int64_t row = 0, col = 0;
93    float got = 0.0f, ref = 0.0f;
94    double delta = 0.0;
95    bool is_padding = false;
96};
97
98// Independent host CPU reference computed in double precision.
99void gemm_reference(const uint16_t* X, const uint16_t* W, const float* initial_Y, float* ref_Y,
100                    int64_t T, int64_t N, int64_t K, int64_t ldy, float beta, bool is_bf16) {
101    std::vector<double> x_dec((size_t) T * K);
102    std::vector<double> w_dec((size_t) N * K);
103    for (size_t i = 0; i < x_dec.size(); ++i) x_dec[i] = decode(X[i], is_bf16);
104    for (size_t i = 0; i < w_dec.size(); ++i) w_dec[i] = decode(W[i], is_bf16);
105
106    for (int64_t t = 0; t < T; ++t) {
107        const double* x_row = x_dec.data() + t * K;
108        for (int64_t n = 0; n < N; ++n) {
109            const double* w_row = w_dec.data() + n * K;
110            double sum = 0.0;
111            for (int64_t k = 0; k < K; ++k) {
112                sum += x_row[k] * w_row[k];
113            }
114            const size_t out_idx = (size_t) t * ldy + n;
115            const double y_init = (beta == 0.0f) ? 0.0 : static_cast<double>(initial_Y[out_idx]);
116            ref_Y[out_idx] = static_cast<float>(beta * y_init + sum);
117        }
118    }
119}
120
121enum class CaseStatus {
122    Passed,
123    Skipped,
124    Failed
125};
126
127CaseStatus run_gemm_case(DeviceBuffer& dx, DeviceBuffer& dw, DeviceBuffer& dy,
128                         hipStream_t stream, bool is_bf16,
129                         int64_t T, int64_t N, int64_t K, int64_t ldy, float beta,
130                         uint32_t seed, double& out_max_abs,
131                         MismatchRecord* first_mismatch, size_t& failure_count) {
132    const char* dtype_str = is_bf16 ? "bf16" : "f16";
133    std::mt19937 rng(seed);
134    std::uniform_int_distribution<int> dist(-8, 8);
135
136    const size_t x_count = (size_t) T * K;
137    const size_t w_count = (size_t) N * K;
138    const size_t y_count = (size_t) T * ldy + 16;  // 16 guard floats past end of matrix
139
140    std::vector<uint16_t> x(x_count);
141    std::vector<uint16_t> w(w_count);
142    for (size_t i = 0; i < x_count; ++i) x[i] = encode(dist(rng) * 0.0625f, is_bf16);
143    for (size_t i = 0; i < w_count; ++i) w[i] = encode(dist(rng) * 0.0625f, is_bf16);
144
145    std::vector<float> initial_y(y_count, kSentinel);
146    for (int64_t t = 0; t < T; ++t) {
147        for (int64_t n = 0; n < N; ++n) {
148            if (beta == 0.0f) {
149                initial_y[(size_t) t * ldy + n] = -888.25f;
150            } else {
151                // beta == 1.0f: pre-fill with a known exact pattern to verify accumulation
152                initial_y[(size_t) t * ldy + n] = static_cast<float>((t * 5 + n * 3) % 17 - 8) * 0.0625f;
153            }
154        }
155    }
156
157    HIP_CHECK(hipMemcpyAsync(dx.p, x.data(), x_count * sizeof(uint16_t), hipMemcpyHostToDevice, stream));
158    HIP_CHECK(hipMemcpyAsync(dw.p, w.data(), w_count * sizeof(uint16_t), hipMemcpyHostToDevice, stream));
159    HIP_CHECK(hipMemcpyAsync(dy.p, initial_y.data(), y_count * sizeof(float), hipMemcpyHostToDevice, stream));
160
161    const bool launched = is_bf16 ? strata_wmma_gemm_bf16(static_cast<const uint16_t*>(dx.p),
162                                                           static_cast<const uint16_t*>(dw.p),
163                                                           static_cast<float*>(dy.p),
164                                                           T, N, K, ldy, beta, stream)
165                                  : strata_wmma_gemm_f16(static_cast<const uint16_t*>(dx.p),
166                                                          static_cast<const uint16_t*>(dw.p),
167                                                          static_cast<float*>(dy.p),
168                                                          T, N, K, ldy, beta, stream);
169
170    if (!launched) {
171        // Declined by kernel: caller falls back to hipBLAS. Test must SKIP rather than fail.
172        HIP_CHECK(hipStreamSynchronize(stream));
173        return CaseStatus::Skipped;
174    }
175
176    std::vector<float> got_y(y_count);
177    HIP_CHECK(hipMemcpyAsync(got_y.data(), dy.p, y_count * sizeof(float), hipMemcpyDeviceToHost, stream));
178    HIP_CHECK(hipStreamSynchronize(stream));
179
180    // 1. Verify padding columns and end guards are untouched.
181    for (int64_t t = 0; t < T; ++t) {
182        for (int64_t col = N; col < ldy; ++col) {
183            const size_t idx = (size_t) t * ldy + col;
184            if (got_y[idx] != kSentinel) {
185                failure_count++;
186                if (first_mismatch && first_mismatch->dtype[0] == '\0') {
187                    *first_mismatch = MismatchRecord{dtype_str, T, N, K, ldy, beta, t, col,
188                                                     got_y[idx], kSentinel,
189                                                     std::abs((double) got_y[idx] - (double) kSentinel), true};
190                }
191                std::fprintf(stderr, "FAIL: output touched padding column: dtype=%s T=%ld N=%ld K=%ld ldy=%ld beta=%.1f row=%ld col=%ld got=%.9g expected=%.9g\n",
192                             dtype_str, T, N, K, ldy, beta, t, col, got_y[idx], kSentinel);
193                return CaseStatus::Failed;
194            }
195        }
196    }
197    for (size_t g = (size_t) T * ldy; g < y_count; ++g) {
198        if (got_y[g] != kSentinel) {
199            failure_count++;
200            if (first_mismatch && first_mismatch->dtype[0] == '\0') {
201                *first_mismatch = MismatchRecord{dtype_str, T, N, K, ldy, beta, -1, (int64_t) g,
202                                                 got_y[g], kSentinel,
203                                                 std::abs((double) got_y[g] - (double) kSentinel), true};
204            }
205            std::fprintf(stderr, "FAIL: output touched end guard: dtype=%s T=%ld N=%ld K=%ld ldy=%ld beta=%.1f index=%zu got=%.9g expected=%.9g\n",
206                         dtype_str, T, N, K, ldy, beta, g, got_y[g], kSentinel);
207            return CaseStatus::Failed;
208        }
209    }
210
211    // 2. Compute reference on CPU and verify exact match.
212    std::vector<float> ref_y(y_count, kSentinel);
213    gemm_reference(x.data(), w.data(), initial_y.data(), ref_y.data(), T, N, K, ldy, beta, is_bf16);
214
215    double case_max_abs = 0.0;
216    for (int64_t t = 0; t < T; ++t) {
217        for (int64_t n = 0; n < N; ++n) {
218            const size_t idx = (size_t) t * ldy + n;
219            if (!std::isfinite(got_y[idx])) {
220                failure_count++;
221                if (first_mismatch && first_mismatch->dtype[0] == '\0') {
222                    *first_mismatch = MismatchRecord{dtype_str, T, N, K, ldy, beta, t, n,
223                                                     got_y[idx], ref_y[idx], 1e30, false};
224                }
225                std::fprintf(stderr, "FAIL: non-finite output: dtype=%s T=%ld N=%ld K=%ld ldy=%ld beta=%.1f at (%ld, %ld): got=%.9g\n",
226                             dtype_str, T, N, K, ldy, beta, t, n, got_y[idx]);
227                return CaseStatus::Failed;
228            }
229            const double delta = std::abs(static_cast<double>(got_y[idx]) - static_cast<double>(ref_y[idx]));
230            case_max_abs = std::max(case_max_abs, delta);
231            // The RDNA3 matrix core accumulates in fp32 but rounds toward zero rather than to nearest, while
232            // this reference sums in double and rounds to nearest, so a correct result may differ by one ULP
233            // (measured: every mismatch on this hardware is <= 1 ULP and toward zero).  Compare against a
234            // tolerance of 4 ULP - tight enough to stay diagnostic, since a wrong row, column, stride or tile
235            // boundary differs by O(value) rather than by 1e-7.  STRATA_WMMA_PARITY_EXACT=1 demands bit
236            // equality for anyone who wants to see the raw deltas.
237            static const bool exact = std::getenv("STRATA_WMMA_PARITY_EXACT") != nullptr;
238            const double tol = exact ? 0.0
239                                     : 4.0 * (double)std::numeric_limits<float>::epsilon() *
240                                           std::max(1.0, std::abs(static_cast<double>(ref_y[idx])));
241            if (delta > tol) {
242                failure_count++;
243                if (first_mismatch && first_mismatch->dtype[0] == '\0') {
244                    *first_mismatch = MismatchRecord{dtype_str, T, N, K, ldy, beta, t, n,
245                                                     got_y[idx], ref_y[idx], delta, false};
246                }
247                std::fprintf(stderr, "FAIL: mismatch: dtype=%s T=%ld N=%ld K=%ld ldy=%ld beta=%.1f at (%ld, %ld): got=%.9g ref=%.9g delta=%.9g\n",
248                             dtype_str, T, N, K, ldy, beta, t, n, got_y[idx], ref_y[idx], delta);
249                return CaseStatus::Failed;
250            }
251        }
252    }
253
254    out_max_abs = std::max(out_max_abs, case_max_abs);
255    return CaseStatus::Passed;
256}
257
258struct DeclinedShape {
259    int64_t T, N, K, ldy;
260    float beta;
261    const char* reason;
262};
263
264} // namespace
265
266int main() {
267    int device = 0;
268    HIP_CHECK(hipGetDevice(&device));
269    hipDeviceProp_t properties{};
270    HIP_CHECK(hipGetDeviceProperties(&properties, device));
271    std::printf("Device %d: %s (arch %s, warpSize %d)\n",
272                device, properties.name, properties.gcnArchName, properties.warpSize);
273    // No matrix cores (RDNA2 and older, gfx906): the kernel declines every shape, so the suite has nothing to compare
274    // and reports that as a skip (exit 77, SKIP_RETURN_CODE in CMake), as hip_prompt_attn_wmma does, not a failure.
275    if (!strata::kernels::gfx_arch_is_gfx11_wmma(properties.gcnArchName)) {
276        std::printf("WMMA GEMM parity SKIPPED: %s has no WMMA matrix cores (the kernel declines every shape here)\n",
277                    properties.gcnArchName);
278        return 77;
279    }
280
281    hipStream_t stream = nullptr;
282    HIP_CHECK(hipStreamCreateWithFlags(&stream, hipStreamNonBlocking));
283
284    // Allocate reusable device buffers sized for the maximum test dimensions:
285    // Max T = 127, Max N = 256, Max K = 80, Max ldy = 256 + 16.
286    constexpr size_t kMaxXBytes = 127 * 80 * sizeof(uint16_t);
287    constexpr size_t kMaxWBytes = 256 * 80 * sizeof(uint16_t);
288    constexpr size_t kMaxYBytes = (127 * (256 + 16) + 64) * sizeof(float);
289
290    DeviceBuffer dx(kMaxXBytes);
291    DeviceBuffer dw(kMaxWBytes);
292    DeviceBuffer dy(kMaxYBytes);
293
294    const std::vector<int64_t> k_t_values = {1, 15, 16, 17, 31, 32, 33, 63, 64, 65, 127};
295    const std::vector<int64_t> k_n_values = {16, 17, 32, 48, 64, 65, 127, 256};
296    const std::vector<int64_t> k_k_values = {16, 32, 48, 64, 80};
297
298    // Test matrix configurations for (beta, ldy):
299    // Covers beta=0 (overwrite) and beta=1 (accumulate), with ldy == N and ldy > N.
300    struct Config {
301        float beta;
302        int64_t ldy_offset;
303    };
304    const std::vector<Config> kConfigs = {
305        {0.0f, 0},  // beta=0, packed (ldy == N)
306        {1.0f, 3},  // beta=1, strided (ldy == N + 3), tests accumulation + padding
307        {0.0f, 7},  // beta=0, strided (ldy == N + 7), tests overwrite + padding
308        {1.0f, 0},  // beta=1, packed (ldy == N), tests accumulation in packed layout
309    };
310
311    const std::vector<DeclinedShape> kDeclinedShapes = {
312        // K not a multiple of 16
313        {1, 16, 15, 16, 0.0f, "K not multiple of 16 (K=15)"},
314        {15, 17, 24, 17, 0.0f, "K not multiple of 16 (K=24)"},
315        {32, 32, 35, 32, 1.0f, "K not multiple of 16 (K=35)"},
316        {64, 64, 47, 67, 1.0f, "K not multiple of 16 (K=47)"},
317        {127, 256, 79, 256, 0.0f, "K not multiple of 16 (K=79)"},
318        // ldy < N
319        {16, 32, 16, 16, 0.0f, "ldy < N (ldy=16, N=32)"},
320        {32, 48, 32, 40, 1.0f, "ldy < N (ldy=40, N=48)"},
321        // beta not 0 or 1
322        {16, 16, 16, 16, 0.5f, "beta not 0 or 1 (beta=0.5)"},
323        {32, 32, 32, 32, 2.0f, "beta not 0 or 1 (beta=2.0)"},
324        // Non-positive sizes
325        {0, 16, 16, 16, 0.0f, "T <= 0 (T=0)"},
326        {16, 0, 16, 16, 0.0f, "N <= 0 (N=0)"},
327        {16, 16, 0, 16, 0.0f, "K <= 0 (K=0)"},
328        {-1, 16, 16, 16, 0.0f, "T < 0 (T=-1)"},
329    };
330
331    size_t passed_count = 0;
332    size_t skipped_count = 0;
333    size_t failure_count = 0;
334    double global_max_abs = 0.0;
335    MismatchRecord first_mismatch{};
336    uint32_t case_seed = 0x574d4d41u;
337
338    const bool verbose = (std::getenv("STRATA_TEST_VERBOSE") != nullptr);
339
340    for (bool is_bf16 : {false, true}) {
341        const char* dtype_str = is_bf16 ? "bf16" : "f16";
342        std::printf("Testing strata_wmma_gemm_%s across %zu shapes (%zu execution configs)...\n",
343                    dtype_str, k_t_values.size() * k_n_values.size() * k_k_values.size(), kConfigs.size());
344
345        for (int64_t T : k_t_values) {
346            double t_max_abs = 0.0;
347            size_t t_passed = 0;
348            size_t t_skipped = 0;
349
350            for (int64_t N : k_n_values) {
351                for (int64_t K : k_k_values) {
352                    for (const auto& cfg : kConfigs) {
353                        const int64_t ldy = N + cfg.ldy_offset;
354                        double case_max_abs = 0.0;
355                        case_seed = case_seed * 1664525u + 1013904223u;
356
357                        const CaseStatus status = run_gemm_case(
358                            dx, dw, dy, stream, is_bf16, T, N, K, ldy, cfg.beta,
359                            case_seed, case_max_abs, &first_mismatch, failure_count);
360
361                        if (status == CaseStatus::Passed) {
362                            passed_count++;
363                            t_passed++;
364                            t_max_abs = std::max(t_max_abs, case_max_abs);
365                            global_max_abs = std::max(global_max_abs, case_max_abs);
366                            if (verbose) {
367                                std::printf("  case dtype=%s T=%3ld N=%3ld K=%2ld ldy=%3ld beta=%.1f max_abs=%.9g PASS\n",
368                                            dtype_str, T, N, K, ldy, cfg.beta, case_max_abs);
369                            }
370                        } else if (status == CaseStatus::Skipped) {
371                            skipped_count++;
372                            t_skipped++;
373                            if (verbose) {
374                                std::printf("  case dtype=%s T=%3ld N=%3ld K=%2ld ldy=%3ld beta=%.1f SKIP (declined)\n",
375                                            dtype_str, T, N, K, ldy, cfg.beta);
376                            }
377                        } else {
378                            // Failed: first_mismatch already recorded and reported to stderr
379                            if (verbose) {
380                                std::printf("  case dtype=%s T=%3ld N=%3ld K=%2ld ldy=%3ld beta=%.1f FAIL\n",
381                                            dtype_str, T, N, K, ldy, cfg.beta);
382                            }
383                        }
384                    }
385                }
386            }
387            std::printf("  dtype=%s T=%3ld: %zu passed, %zu skipped, max_abs=%.9g %s\n",
388                        dtype_str, T, t_passed, t_skipped, t_max_abs,
389                        (failure_count == 0) ? "PASS" : "FAIL");
390        }
391
392        // Test declined shapes: the kernel must return false and be skipped.
393        for (const auto& decl : kDeclinedShapes) {
394            const bool launched = is_bf16
395                ? strata_wmma_gemm_bf16(static_cast<const uint16_t*>(dx.p),
396                                        static_cast<const uint16_t*>(dw.p),
397                                        static_cast<float*>(dy.p),
398                                        decl.T, decl.N, decl.K, decl.ldy, decl.beta, stream)
399                : strata_wmma_gemm_f16(static_cast<const uint16_t*>(dx.p),
400                                       static_cast<const uint16_t*>(dw.p),
401                                       static_cast<float*>(dy.p),
402                                       decl.T, decl.N, decl.K, decl.ldy, decl.beta, stream);
403
404            if (launched) {
405                failure_count++;
406                std::fprintf(stderr, "FAIL: expected kernel to decline shape (%s) dtype=%s T=%ld N=%ld K=%ld ldy=%ld beta=%.1f but it returned true!\n",
407                             decl.reason, dtype_str, decl.T, decl.N, decl.K, decl.ldy, decl.beta);
408            } else {
409                skipped_count++;
410                if (verbose) {
411                    std::printf("  declined shape correctly rejected (%s): dtype=%s T=%ld N=%ld K=%ld ldy=%ld beta=%.1f SKIP\n",
412                                decl.reason, dtype_str, decl.T, decl.N, decl.K, decl.ldy, decl.beta);
413                }
414            }
415        }
416    }
417
418    HIP_CHECK(hipStreamDestroy(stream));
419
420    if (failure_count > 0) {
421        if (first_mismatch.dtype[0] != '\0') {
422            if (first_mismatch.is_padding) {
423                std::fprintf(stderr, "\nSUMMARY: First mismatch was padding/guard corruption:\n"
424                                     "  dtype=%s T=%ld N=%ld K=%ld ldy=%ld beta=%.1f at (%ld, %ld): got=%.9g expected=%.9g\n",
425                             first_mismatch.dtype, first_mismatch.T, first_mismatch.N, first_mismatch.K,
426                             first_mismatch.ldy, first_mismatch.beta, first_mismatch.row, first_mismatch.col,
427                             first_mismatch.got, first_mismatch.ref);
428            } else {
429                std::fprintf(stderr, "\nSUMMARY: First mismatch occurred at:\n"
430                                     "  dtype=%s T=%ld N=%ld K=%ld ldy=%ld beta=%.1f at (%ld, %ld): got=%.9g ref=%.9g delta=%.9g\n",
431                             first_mismatch.dtype, first_mismatch.T, first_mismatch.N, first_mismatch.K,
432                             first_mismatch.ldy, first_mismatch.beta, first_mismatch.row, first_mismatch.col,
433                             first_mismatch.got, first_mismatch.ref, first_mismatch.delta);
434            }
435        }
436        std::fprintf(stderr, "WMMA GEMM parity FAILED: %zu failures detected, max_abs=%.9g\n",
437                     failure_count, global_max_abs);
438        return 1;
439    }
440
441    if (passed_count == 0) {
442        std::fprintf(stderr, "WMMA GEMM parity FAILED: zero test cases passed (all were declined or skipped)\n");
443        return 1;
444    }
445
446    std::printf("\nWMMA GEMM parity OK: %zu test cases passed, %zu declined shapes skipped, max_abs=%.9g\n",
447                passed_count, skipped_count, global_max_abs);
448    return 0;
449}