okami.mom/strata

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

bsorensen110hip: address review of the gfx1201 table: current docs, smoke-test wordinga8d57b1f0

main
8.9 KiB197 linesraw
1// Opt-in HIP smoke test for the calibrated hipBLASLt prefill route; it needs STRATA_HIPBLASLT_TUNING (SKIP otherwise).
2// It checks that the table loads for this device and hipBLASLt version, that the two rows it uses exist (bf16
3// N=48 K=2560 ldy=96 and f16 N=512 K=2560 ldy=512, T bucket 4096), and that Gemm's output matches hipBLASEx on those
4// two rows. It does NOT check the other rows, and it does not check that hipBLASLt ran the table's solution: an id
5// the library rejects falls back to hipBLASEx and the test still passes. Set STRATA_HIPBLASLT_VERBOSE=1 to read the
6// "hipBLASLt summary launches=... fallbacks=..." line.
7#include <cuda_runtime.h>
8#include <hip/hip_bfloat16.h>
9#include <hip/hip_fp16.h>
10#include <hipblas/hipblas.h>
11#include <hipblaslt/hipblaslt.h>
12
13#include "strata/kernels/bf16_bits.hpp"
14#include "strata/prefill/gemm.hpp"
15#include "hipblaslt_tuning.hpp"
16
17#include <algorithm>
18#include <cmath>
19#include <cstdint>
20#include <cstdio>
21#include <cstdlib>
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
42struct DeviceBuffer {
43    void* p = nullptr;
44    explicit DeviceBuffer(size_t bytes) { if (bytes) HIP_CHECK(hipMalloc(&p, bytes)); }
45    ~DeviceBuffer() { if (p) (void) hipFree(p); }
46    DeviceBuffer(const DeviceBuffer&) = delete;
47    DeviceBuffer& operator=(const DeviceBuffer&) = delete;
48};
49
50uint16_t encode(float value, bool bf16) {
51    if (bf16) return strata::kernels::bf16_from_f32(value);
52    const __half half = __float2half_rn(value);
53    uint16_t bits = 0;
54    std::memcpy(&bits, &half, sizeof(bits));
55    return bits;
56}
57
58bool run_case(strata::prefill::Gemm& gemm, hipblasHandle_t blas, hipStream_t stream, bool bf16, int t, int n,
59              int k, int ldy, int output_offset, float beta, uint32_t seed) {
60    std::mt19937 rng(seed);
61    std::uniform_real_distribution<float> dist(-0.25f, 0.25f);
62    const size_t x_count = (size_t) t * k;
63    const size_t w_count = (size_t) n * k;
64    std::vector<uint16_t> x(x_count), w(w_count);
65    for (auto& value : x) value = encode(dist(rng), bf16);
66    for (auto& value : w) value = encode(dist(rng), bf16);
67
68    const size_t output_count = (size_t) output_offset + (size_t) t * ldy + 8;
69    std::vector<float> initial(output_count, -777.25f);
70    for (int row = 0; row < t; ++row) {
71        for (int col = 0; col < n; ++col) {
72            initial[(size_t) output_offset + (size_t) row * ldy + col] =
73                (float) ((row * 17 + col * 3) % 29 - 14) * 0.03125f;
74        }
75    }
76
77    DeviceBuffer dx(x_count * sizeof(uint16_t));
78    DeviceBuffer dw(w_count * sizeof(uint16_t));
79    DeviceBuffer dy(initial.size() * sizeof(float));
80    DeviceBuffer dref(initial.size() * sizeof(float));
81    HIP_CHECK(hipMemcpyAsync(dx.p, x.data(), x_count * sizeof(uint16_t), hipMemcpyHostToDevice, stream));
82    HIP_CHECK(hipMemcpyAsync(dw.p, w.data(), w_count * sizeof(uint16_t), hipMemcpyHostToDevice, stream));
83    HIP_CHECK(hipMemcpyAsync(dy.p, initial.data(), initial.size() * sizeof(float), hipMemcpyHostToDevice, stream));
84    HIP_CHECK(hipMemcpyAsync(dref.p, initial.data(), initial.size() * sizeof(float), hipMemcpyHostToDevice, stream));
85    HIP_CHECK(hipStreamSynchronize(stream));
86
87    const hipDataType type = bf16 ? HIP_R_16BF : HIP_R_16F;
88    const float alpha = 1.0f;
89    HIPBLAS_CHECK(hipblasGemmEx(blas, HIPBLAS_OP_T, HIPBLAS_OP_N, n, t, k, &alpha, dw.p, type, k, dx.p, type, k,
90                                &beta, (float*) dref.p + output_offset, HIP_R_32F, ldy, HIPBLAS_COMPUTE_32F,
91                                HIPBLAS_GEMM_DEFAULT));
92    if (bf16) {
93        gemm.bf16((const uint16_t*) dx.p, (const uint16_t*) dw.p, (float*) dy.p + output_offset, t, n, k, ldy,
94                  beta);
95    } else {
96        gemm.f16((const uint16_t*) dx.p, (const uint16_t*) dw.p, (float*) dy.p + output_offset, t, n, k, ldy,
97                 beta);
98    }
99    HIP_CHECK(hipStreamSynchronize(stream));
100
101    std::vector<float> got(initial.size()), ref(initial.size());
102    HIP_CHECK(hipMemcpy(got.data(), dy.p, got.size() * sizeof(float), hipMemcpyDeviceToHost));
103    HIP_CHECK(hipMemcpy(ref.data(), dref.p, ref.size() * sizeof(float), hipMemcpyDeviceToHost));
104
105    std::vector<uint8_t> active(initial.size(), 0);
106    double diff2 = 0.0, ref2 = 0.0, max_abs = 0.0;
107    for (int row = 0; row < t; ++row) {
108        for (int col = 0; col < n; ++col) {
109            const size_t index = (size_t) output_offset + (size_t) row * ldy + col;
110            active[index] = 1;
111            if (!std::isfinite(got[index]) || !std::isfinite(ref[index])) {
112                std::fprintf(stderr, "non-finite output dtype=%s T=%d N=%d K=%d beta=%.1f index=%zu\n",
113                             bf16 ? "bf16" : "f16", t, n, k, beta, index);
114                return false;
115            }
116            const double delta = (double) got[index] - ref[index];
117            diff2 += delta * delta;
118            ref2 += (double) ref[index] * ref[index];
119            max_abs = std::max(max_abs, std::abs(delta));
120        }
121    }
122    for (size_t i = 0; i < initial.size(); ++i) {
123        if (!active[i] && (got[i] != initial[i] || ref[i] != initial[i])) {
124            std::fprintf(stderr, "output touched padding/guard dtype=%s T=%d N=%d K=%d beta=%.1f index=%zu got=%.9g\n",
125                         bf16 ? "bf16" : "f16", t, n, k, beta, i, got[i]);
126            return false;
127        }
128    }
129    const double relative_l2 = std::sqrt(diff2 / std::max(ref2, 1e-300));
130    const bool passed = relative_l2 <= 1e-4 && max_abs <= 5e-3;
131    std::printf("case dtype=%s T=%d N=%d K=%d ldy=%d output_offset=%d beta=%.1f relative_l2=%.9g max_abs=%.9g %s\n",
132                bf16 ? "bf16" : "f16", t, n, k, ldy, output_offset, beta, relative_l2, max_abs,
133                passed ? "PASS" : "FAIL");
134    return passed;
135}
136
137int main() {
138    const char* tuning_path = std::getenv("STRATA_HIPBLASLT_TUNING");
139    if (!tuning_path || !*tuning_path) {
140        std::fprintf(stderr, "SKIP: set STRATA_HIPBLASLT_TUNING to a tuning table for this GPU and hipBLASLt version\n");
141        return 77;
142    }
143
144    int device = 0;
145    HIP_CHECK(hipGetDevice(&device));
146    hipDeviceProp_t properties{};
147    HIP_CHECK(hipGetDeviceProperties(&properties, device));
148    std::string arch(properties.gcnArchName);
149    const auto suffix = arch.find(':');
150    if (suffix != std::string::npos) arch.resize(suffix);
151    hipblasLtHandle_t lt = nullptr;
152    HIPBLAS_CHECK(hipblasLtCreate(&lt));
153    int version = 0;
154    HIPBLAS_CHECK(hipblasLtGetVersion(lt, &version));
155    HIPBLAS_CHECK(hipblasLtDestroy(lt));
156
157    strata::prefill::hipblaslt::TuningTable table;
158    std::string error;
159    if (!table.load(tuning_path, arch, version, error)) {
160        std::fprintf(stderr, "tuning table rejected: %s\n", error.c_str());
161        return 1;
162    }
163    if (!table.closest(strata::prefill::hipblaslt::InputType::bf16, 48, 2560, 96, 4096) ||
164        !table.closest(strata::prefill::hipblaslt::InputType::f16, 512, 2560, 512, 4096)) {
165        std::fprintf(stderr, "tuning table lacks the rows this smoke test uses (bf16 N=48 K=2560 ldy=96, f16 N=512 K=2560 ldy=512)\n");
166        return 1;
167    }
168
169    hipStream_t stream = nullptr;
170    HIP_CHECK(hipStreamCreateWithFlags(&stream, hipStreamNonBlocking));
171    bool ok = true;
172    {
173        std::string init_error;
174        strata::prefill::Gemm gemm;
175        if (!gemm.init((void*) stream, 0, init_error)) {
176            std::fprintf(stderr, "Gemm init failed: %s\n", init_error.c_str());
177            HIP_CHECK(hipStreamDestroy(stream));
178            return 2;
179        }
180        hipblasHandle_t blas = nullptr;
181        HIPBLAS_CHECK(hipblasCreate(&blas));
182        HIPBLAS_CHECK(hipblasSetStream(blas, stream));
183
184        // T=4096 is an exact calibrated bucket; T=37 resolves to the same T=4096 row (the closest bucket), validates the
185        // actual shape before launch, and tests a non-tile-multiple tail. So the four cases use two table rows.
186        ok &= run_case(gemm, blas, stream, true, 4096, 48, 2560, 96, 0, 0.0f, 101);
187        ok &= run_case(gemm, blas, stream, true, 37, 48, 2560, 96, 48, 1.0f, 102);
188        ok &= run_case(gemm, blas, stream, false, 4096, 512, 2560, 512, 0, 0.0f, 103);
189        ok &= run_case(gemm, blas, stream, false, 37, 512, 2560, 512, 7, 1.0f, 104);
190        HIPBLAS_CHECK(hipblasDestroy(blas));
191    }
192    HIP_CHECK(hipStreamDestroy(stream));
193    std::printf("smoke test: 4 cases on 2 of the table's %zu rows; %s\n", table.rows().size(),
194                ok ? "outputs match hipBLASEx (solution ids are not verified; see STRATA_HIPBLASLT_VERBOSE)"
195                   : "FAILED");
196    return ok ? 0 : 1;
197}