okami.mom/strata

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

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

main
9.5 KiB206 linesraw
1// Opt-in HIP smoke test for the rocBLAS solution table of the prompt path's FP16-out GEMMs (gfx103x); it needs
2// STRATA_ROCBLAS_TUNING (SKIP otherwise).  It checks that the table loads for this device and rocBLAS build, and that
3// Gemm's FP16 path (set_f16_io, the route the table serves) matches an FP32-out hipBLASEx reference on the table's
4// first two shapes, at their token bucket and at a smaller odd T that resolves to the same row.  Like the hipBLASLt
5// test it does not check that rocBLAS ran the table's solution: an id the library refuses falls back to the default
6// kernel and the test still passes; STRATA_ROCBLAS_VERBOSE=1 prints the "tuned_launches=... fallbacks=..." summary.
7#include <cuda_runtime.h>
8#include <hip/hip_fp16.h>
9#include <hipblas/hipblas.h>
10#include <rocblas/rocblas.h>
11
12#include "strata/prefill/gemm.hpp"
13#include "rocblas_tuning.hpp"
14
15#include <algorithm>
16#include <cmath>
17#include <cstdint>
18#include <cstdio>
19#include <cstdlib>
20#include <cstring>
21#include <filesystem>
22#include <random>
23#include <string>
24#include <vector>
25
26#define HIP_CHECK(call) do { \
27    const hipError_t status_ = (call); \
28    if (status_ != hipSuccess) { \
29        std::fprintf(stderr, "HIP failure at %s:%d: %s: %s\n", __FILE__, __LINE__, #call, hipGetErrorString(status_)); \
30        std::exit(2); \
31    } \
32} while (0)
33
34#define HIPBLAS_CHECK(call) do { \
35    const hipblasStatus_t status_ = (call); \
36    if (status_ != HIPBLAS_STATUS_SUCCESS) { \
37        std::fprintf(stderr, "hipBLAS failure at %s:%d: %s: %d\n", __FILE__, __LINE__, #call, (int) status_); \
38        std::exit(2); \
39    } \
40} while (0)
41
42namespace {
43
44struct DeviceBuffer {
45    void* p = nullptr;
46    explicit DeviceBuffer(size_t bytes) { if (bytes) HIP_CHECK(hipMalloc(&p, bytes)); }
47    ~DeviceBuffer() { if (p) (void) hipFree(p); }
48    DeviceBuffer(const DeviceBuffer&) = delete;
49    DeviceBuffer& operator=(const DeviceBuffer&) = delete;
50};
51
52uint16_t f16_bits(float value) {
53    const __half half = __float2half_rn(value);
54    uint16_t bits = 0;
55    std::memcpy(&bits, &half, sizeof(bits));
56    return bits;
57}
58
59// Y[T, N] (fp32, row stride ldy, at output_offset floats into the buffer) = X[T, K] . W[N, K]^T, Gemm's FP16 route
60// against hipBLASEx with FP32 out.  The FP16 route rounds its outputs to FP16 (that is the measured, accepted cost of
61// prompt_f16(), docs/AMD_HIP.md): the tolerance is a few FP16 ulps of the largest output.
62bool run_case(strata::prefill::Gemm& gemm, hipblasHandle_t blas, hipStream_t stream, int t, int n, int k, int ldy,
63              int output_offset, uint32_t seed) {
64    std::mt19937 rng(seed);
65    std::uniform_real_distribution<float> dist(-0.25f, 0.25f);
66    const size_t x_count = (size_t) t * k, w_count = (size_t) n * k;
67    std::vector<uint16_t> x(x_count), w(w_count);
68    for (auto& value : x) value = f16_bits(dist(rng));
69    for (auto& value : w) value = f16_bits(dist(rng));
70    const size_t output_count = (size_t) output_offset + (size_t) t * ldy + 8;
71    std::vector<float> initial(output_count, -777.25f);
72
73    DeviceBuffer dx(x_count * 2), dw(w_count * 2), dy(output_count * 4), dref(output_count * 4);
74    HIP_CHECK(hipMemcpyAsync(dx.p, x.data(), x_count * 2, hipMemcpyHostToDevice, stream));
75    HIP_CHECK(hipMemcpyAsync(dw.p, w.data(), w_count * 2, hipMemcpyHostToDevice, stream));
76    HIP_CHECK(hipMemcpyAsync(dy.p, initial.data(), output_count * 4, hipMemcpyHostToDevice, stream));
77    HIP_CHECK(hipMemcpyAsync(dref.p, initial.data(), output_count * 4, hipMemcpyHostToDevice, stream));
78    HIP_CHECK(hipStreamSynchronize(stream));
79
80    const float alpha = 1.0f, beta = 0.0f;
81    HIPBLAS_CHECK(hipblasGemmEx(blas, HIPBLAS_OP_T, HIPBLAS_OP_N, n, t, k, &alpha, dw.p, HIP_R_16F, k, dx.p, HIP_R_16F,
82                                k, &beta, (float*) dref.p + output_offset, HIP_R_32F, ldy, HIPBLAS_COMPUTE_32F,
83                                HIPBLAS_GEMM_DEFAULT));
84    gemm.f16((const uint16_t*) dx.p, (const uint16_t*) dw.p, (float*) dy.p + output_offset, t, n, k, ldy, beta);
85    HIP_CHECK(hipStreamSynchronize(stream));
86
87    std::vector<float> got(output_count), ref(output_count);
88    HIP_CHECK(hipMemcpy(got.data(), dy.p, output_count * 4, hipMemcpyDeviceToHost));
89    HIP_CHECK(hipMemcpy(ref.data(), dref.p, output_count * 4, hipMemcpyDeviceToHost));
90
91    std::vector<uint8_t> active(output_count, 0);
92    double diff2 = 0.0, ref2 = 0.0, max_abs = 0.0, max_ref = 0.0;
93    for (int row = 0; row < t; ++row) {
94        for (int col = 0; col < n; ++col) {
95            const size_t index = (size_t) output_offset + (size_t) row * ldy + col;
96            active[index] = 1;
97            if (!std::isfinite(got[index]) || !std::isfinite(ref[index])) {
98                std::fprintf(stderr, "non-finite output T=%d N=%d K=%d index=%zu\n", t, n, k, index);
99                return false;
100            }
101            const double delta = (double) got[index] - ref[index];
102            diff2 += delta * delta;
103            ref2 += (double) ref[index] * ref[index];
104            max_abs = std::max(max_abs, std::abs(delta));
105            max_ref = std::max(max_ref, (double) std::abs(ref[index]));
106        }
107    }
108    for (size_t i = 0; i < output_count; ++i) {
109        if (!active[i] && (got[i] != initial[i] || ref[i] != initial[i])) {
110            std::fprintf(stderr, "output touched padding/guard T=%d N=%d K=%d ldy=%d index=%zu got=%.9g\n", t, n, k, ldy,
111                         i, got[i]);
112            return false;
113        }
114    }
115    const double relative_l2 = std::sqrt(diff2 / std::max(ref2, 1e-300));
116    const double ulp = std::ldexp(1.0, (int) std::floor(std::log2(std::max(max_ref, 1e-30))) - 10);
117    const bool passed = relative_l2 <= 2e-3 && max_abs <= 4.0 * ulp;
118    std::printf("case T=%d N=%d K=%d ldy=%d output_offset=%d relative_l2=%.3g max_abs=%.3g (4 ulp = %.3g) %s\n", t, n, k,
119                ldy, output_offset, relative_l2, max_abs, 4.0 * ulp, passed ? "PASS" : "FAIL");
120    return passed;
121}
122
123}  // namespace
124
125int main() {
126    const char* tuning_path = std::getenv("STRATA_ROCBLAS_TUNING");
127    if (!tuning_path || !*tuning_path) {
128        std::fprintf(stderr, "SKIP: set STRATA_ROCBLAS_TUNING to a tuning table (or the tools/hip directory) for this GPU and rocBLAS build\n");
129        return 77;
130    }
131    if (!strata::prefill::prompt_f16()) {
132        std::fprintf(stderr, "SKIP: the FP16 prompt GEMMs (prompt_f16) are off on this device; the table serves that route only\n");
133        return 77;
134    }
135
136    int device = 0;
137    HIP_CHECK(hipGetDevice(&device));
138    hipDeviceProp_t properties{};
139    HIP_CHECK(hipGetDeviceProperties(&properties, device));
140    std::string arch(properties.gcnArchName);
141    if (const auto suffix = arch.find(':'); suffix != std::string::npos) arch.resize(suffix);
142    char version[128] = {0};
143    if (rocblas_get_version_string(version, sizeof version) != rocblas_status_success) {
144        std::fprintf(stderr, "rocblas_get_version_string failed\n");
145        return 2;
146    }
147    std::filesystem::path file(tuning_path);
148    std::error_code ec;
149    if (std::filesystem::is_directory(file, ec)) {   // the engine's rule: <arch>-rocblas-<version>.txt, trailing dots dropped
150        std::string tag(version);
151        while (!tag.empty() && tag.back() == '.') tag.pop_back();
152        file /= arch + "-rocblas-" + tag + ".txt";
153    }
154    strata::prefill::rocblas_tuning::Table table;
155    std::string error;
156    if (!table.load(file.string(), arch, version, error)) {
157        std::fprintf(stderr, "tuning table rejected: %s (%s)\n", error.c_str(), file.string().c_str());
158        return 1;
159    }
160    if (table.rows().empty()) {
161        std::fprintf(stderr, "tuning table has no rows\n");
162        return 1;
163    }
164
165    hipStream_t stream = nullptr;
166    HIP_CHECK(hipStreamCreateWithFlags(&stream, hipStreamNonBlocking));
167    bool ok = true;
168    int cases = 0;
169    {
170        std::string init_error;
171        strata::prefill::Gemm gemm;
172        if (!gemm.init((void*) stream, 0, init_error)) {
173            std::fprintf(stderr, "Gemm init failed: %s\n", init_error.c_str());
174            HIP_CHECK(hipStreamDestroy(stream));
175            return 2;
176        }
177        gemm.set_f16_io(true);
178        hipblasHandle_t blas = nullptr;
179        HIPBLAS_CHECK(hipblasCreate(&blas));
180        HIPBLAS_CHECK(hipblasSetStream(blas, stream));
181
182        // the table's first two distinct shapes: at their bucket (an exact row) and at a smaller odd T (the closest
183        // row, a non-tile-multiple tail), the second with the output inside a larger buffer
184        std::vector<const strata::prefill::rocblas_tuning::Row*> picked;
185        for (const auto& row : table.rows()) {
186            if (!row.tuned) continue;
187            bool seen = false;
188            for (const auto* p : picked) seen = seen || (p->n == row.n && p->k == row.k && p->ldy == row.ldy);
189            if (!seen) picked.push_back(&row);
190            if (picked.size() == 2) break;
191        }
192        uint32_t seed = 201;
193        for (const auto* row : picked) {
194            ok &= run_case(gemm, blas, stream, row->t_bucket, row->n, row->k, row->ldy, 0, seed++);
195            ok &= run_case(gemm, blas, stream, std::max(1, row->t_bucket - 37), row->n, row->k, row->ldy, 7, seed++);
196            cases += 2;
197        }
198        HIPBLAS_CHECK(hipblasDestroy(blas));
199    }
200    HIP_CHECK(hipStreamDestroy(stream));
201    std::printf("smoke test: %d cases on the first %zu shapes of the table's %zu rows; %s\n", cases,
202                std::min<size_t>(2, table.rows().size()), table.rows().size(),
203                ok ? "outputs match hipBLASEx within FP16 rounding (solution ids are not verified; see STRATA_ROCBLAS_VERBOSE)"
204                   : "FAILED");
205    return ok ? 0 : 1;
206}