okami.mom/strata

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

Niko1221Merge f-amd-f16 8d7f997d4 into f-p4-int (the Radeon 780M on Linux reads its 16-bit prompt GEMMs FP16 in and out by default; the hyper-connection up-mix kernel has an FP16 path)27cf035e5

main
13.2 KiB291 linesraw
1// src/prefill/gr_upmix_parity.cu - the hyper-connection read's fused up projection + mix (gr_upmix, STRATA_HC_UPMIX=1)
2// against the default pair (Gemm::bf16 - cuBLAS - writing `gated`, then gr_mix_r), on synthetic inputs of the model's
3// shapes (N = 2560, 4 streams, K = 320).  Where cuBLAS's kernel sums K in the fused kernel's order the outputs are the
4// same bits (CUDA 13.3 on an RTX 5090 from 33 tokens - the prompt path's default there); elsewhere FP32 rounding: the
5// check bounds max |diff| / max |value| of `mixed`, counts the BF16 / FP16 images that differ, and measures both
6// against an FP64 reference on sampled tokens (the fused one must be as close to it as cuBLAS).
7//   gr_upmix_parity            the checks (T = 1 .. 32768)
8//   gr_upmix_parity --bench    and the timings of the pair and the fused kernel at T = 2048 / 8192 / 32768
9#include "strata/prefill/gemm.hpp"
10#include "strata/prefill/kernels.hpp"
11#include "strata/kernels/gfx_arch.hpp"
12
13#include <cuda_runtime.h>
14
15#include <algorithm>
16#include <cmath>
17#include <cstdint>
18#include <cstdio>
19#include <cstring>
20#include <random>
21#include <string>
22#include <vector>
23
24namespace {
25
26constexpr int N = 2560, HC = 4, D = N * HC, LR = 320;
27
28uint16_t to_bf16(float f) {
29    uint32_t u;
30    std::memcpy(&u, &f, 4);
31    u += 0x7fffu + ((u >> 16) & 1u);
32    return (uint16_t) (u >> 16);
33}
34float from_bf16(uint16_t h) {
35    const uint32_t u = (uint32_t) h << 16;
36    float f;
37    std::memcpy(&f, &u, 4);
38    return f;
39}
40// FP16 (IEEE binary16) from a float, round to nearest even; values beyond 65504 saturate (the engine's hf_sat)
41uint16_t to_f16(float f) {
42    f = std::fmin(std::fmax(f, -65504.0f), 65504.0f);
43    uint32_t u;
44    std::memcpy(&u, &f, 4);
45    const uint32_t sign = (u >> 16) & 0x8000u;
46    const int e = (int) ((u >> 23) & 0xffu) - 127;
47    uint32_t m = u & 0x7fffffu;
48    if (e < -25) return (uint16_t) sign;
49    if (e < -14) {   // subnormal
50        m |= 0x800000u;
51        const int sh = -e - 1;   // 14 .. 24
52        uint32_t r = m >> sh;
53        const uint32_t rem = m & ((1u << sh) - 1u), half = 1u << (sh - 1);
54        if (rem > half || (rem == half && (r & 1u))) ++r;
55        return (uint16_t) (sign | r);
56    }
57    uint32_t r = ((uint32_t) (e + 15) << 10) | (m >> 13);
58    const uint32_t rem = m & 0x1fffu;
59    if (rem > 0x1000u || (rem == 0x1000u && (r & 1u))) ++r;
60    return (uint16_t) (sign | r);
61}
62float from_f16(uint16_t h) {
63    const uint32_t e = (h >> 10) & 0x1fu, m = h & 0x3ffu;
64    float f = e == 0 ? std::ldexp((float) m, -24) : std::ldexp((float) (m | 0x400u), (int) e - 25);
65    return (h & 0x8000u) ? -f : f;
66}
67bool ck(cudaError_t e, const char* what) {
68    if (e != cudaSuccess) std::printf("FAIL: %s: %s\n", what, cudaGetErrorString(e));
69    return e == cudaSuccess;
70}
71template <typename T> T* dalloc(size_t n) {
72    T* p = nullptr;
73    if (!ck(cudaMalloc(&p, n * sizeof(T)), "cudaMalloc")) std::exit(2);
74    return p;
75}
76
77struct Inputs {
78    int64_t T;
79    bool f16;   // lo16 holds FP16 bits (the HIP FP16 prompt path); w_up stays BF16
80    std::vector<uint16_t> lo16, wu;
81    std::vector<float> R, rs, w;
82    uint16_t *d_lo16, *d_wu;
83    float *d_R, *d_rs, *d_w;
84    Inputs(int64_t t, uint32_t seed, bool as_f16 = false) : T(t), f16(as_f16) {
85        std::mt19937 g(seed);
86        std::normal_distribution<float> nd(0.0f, 1.0f);
87        lo16.resize((size_t) T * LR);
88        for (auto& x : lo16) x = f16 ? to_f16(nd(g) * 0.5f) : to_bf16(nd(g) * 0.5f);   // silu outputs: O(1) and below
89        wu.resize((size_t) D * LR);
90        for (auto& x : wu) x = to_bf16(nd(g) * 0.12f);              // gated ~ N(0, ~1): sigmoid in its live range
91        R.resize((size_t) T * D);
92        for (auto& x : R) x = nd(g) * 3.0f;
93        rs.resize((size_t) T * HC);
94        for (auto& x : rs) x = 0.2f + 0.3f * std::fabs(nd(g));
95        w.resize(D);
96        for (auto& x : w) x = 1.0f + 0.1f * nd(g);
97        d_lo16 = dalloc<uint16_t>(lo16.size());
98        d_wu = dalloc<uint16_t>(wu.size());
99        d_R = dalloc<float>(R.size());
100        d_rs = dalloc<float>(rs.size());
101        d_w = dalloc<float>(w.size());
102        cudaMemcpy(d_lo16, lo16.data(), lo16.size() * 2, cudaMemcpyHostToDevice);
103        cudaMemcpy(d_wu, wu.data(), wu.size() * 2, cudaMemcpyHostToDevice);
104        cudaMemcpy(d_R, R.data(), R.size() * 4, cudaMemcpyHostToDevice);
105        cudaMemcpy(d_rs, rs.data(), rs.size() * 4, cudaMemcpyHostToDevice);
106        cudaMemcpy(d_w, w.data(), w.size() * 4, cudaMemcpyHostToDevice);
107    }
108    ~Inputs() { cudaFree(d_lo16); cudaFree(d_wu); cudaFree(d_R); cudaFree(d_rs); cudaFree(d_w); }
109};
110
111struct Outputs {
112    float* mixed;
113    uint16_t *bf, *h;
114    explicit Outputs(int64_t T) {
115        mixed = dalloc<float>((size_t) T * N);
116        bf = dalloc<uint16_t>((size_t) T * N);
117        h = dalloc<uint16_t>((size_t) T * N);
118    }
119    ~Outputs() { cudaFree(mixed); cudaFree(bf); cudaFree(h); }
120};
121
122// mixed[t][d] in FP64 from the same BF16 inputs (the exact result both GPU paths round)
123double exact_mixed(const Inputs& in, int64_t t, int d) {
124    double s = 0.0;
125    for (int c = 0; c < HC; ++c) {
126        double g = 0.0;
127        const int j = c * N + d;
128        for (int k = 0; k < LR; ++k)
129            g += (double) (in.f16 ? from_f16(in.lo16[(size_t) t * LR + k]) : from_bf16(in.lo16[(size_t) t * LR + k])) *
130                 (double) from_bf16(in.wu[(size_t) j * LR + k]);
131        const double x = (double) in.R[(size_t) t * D + j] * in.rs[(size_t) t * HC + c] * in.w[j];
132        s += x / (1.0 + std::exp(-g));
133    }
134    return s / HC;
135}
136
137// f16 (HIP only): the FP16 prompt path, as Prefill::init sets it up (Gemm::set_f16_io + set_act_f16): lo16 holds FP16 bits, the pair's
138// GEMM writes FP16-rounded outputs, gr_upmix runs its FP16 matrix-core variant; the bound against the pair is the FP16 output rounding.
139int check(strata::prefill::Gemm& gm, cudaStream_t st, float* gated, int64_t T, uint32_t seed, bool f16 = false) {
140    if (f16) { gm.set_f16_io(true); strata::prefill::set_act_f16(true); }
141    struct Reset {
142        bool on;
143        strata::prefill::Gemm& g;
144        ~Reset() { if (on) { g.set_f16_io(false); strata::prefill::set_act_f16(false); } }
145    } reset{f16, gm};
146    Inputs in(T, seed, f16);
147    Outputs ref(T), got(T);
148    gm.bf16(in.d_lo16, in.d_wu, gated, T, D, LR);
149    strata::prefill::gr_mix_r(in.d_R, in.d_rs, in.d_w, gated, ref.mixed, ref.bf, T, st, ref.h);
150    if (!strata::prefill::gr_upmix(in.d_lo16, in.d_wu, in.d_R, in.d_rs, in.d_w, got.mixed, got.bf, got.h, T, st)) {
151        std::printf("FAIL T=%lld: gr_upmix refused (needs CUDA sm_80+)\n", (long long) T);
152        return 1;
153    }
154    if (!ck(cudaStreamSynchronize(st), "run")) return 1;
155    const size_t n = (size_t) T * N;
156    std::vector<float> a(n), b(n);
157    std::vector<uint16_t> abf(n), bbf(n), ah(n), bh(n);
158    cudaMemcpy(a.data(), ref.mixed, n * 4, cudaMemcpyDeviceToHost);
159    cudaMemcpy(b.data(), got.mixed, n * 4, cudaMemcpyDeviceToHost);
160    cudaMemcpy(abf.data(), ref.bf, n * 2, cudaMemcpyDeviceToHost);
161    cudaMemcpy(bbf.data(), got.bf, n * 2, cudaMemcpyDeviceToHost);
162    cudaMemcpy(ah.data(), ref.h, n * 2, cudaMemcpyDeviceToHost);
163    cudaMemcpy(bh.data(), got.h, n * 2, cudaMemcpyDeviceToHost);
164    double md = 0, mv = 0;
165    size_t bf_diff = 0, h_diff = 0, bit_diff = 0, nonfinite = 0;
166    for (size_t i = 0; i < n; ++i) {
167        if (!std::isfinite(b[i])) ++nonfinite;
168        md = std::max(md, (double) std::fabs(a[i] - b[i]));
169        mv = std::max(mv, (double) std::fabs(a[i]));
170        bf_diff += abf[i] != bbf[i];
171        h_diff += ah[i] != bh[i];
172        bit_diff += std::memcmp(&a[i], &b[i], 4) != 0;
173    }
174    // FP64 on sampled tokens: each path's max |error| / max |value|
175    std::mt19937 g(seed ^ 0x5a5a);
176    const int samples = (int) std::min<int64_t>(T, 24);
177    double ea = 0, eb = 0, ev = 0;
178    for (int i = 0; i < samples; ++i) {
179        const int64_t t = T <= 24 ? i : (int64_t) (g() % (uint32_t) T);
180        for (int d = 0; d < N; d += 37) {
181            const double x = exact_mixed(in, t, d);
182            ea = std::max(ea, std::fabs(a[(size_t) t * N + d] - x));
183            eb = std::max(eb, std::fabs(b[(size_t) t * N + d] - x));
184            ev = std::max(ev, std::fabs(x));
185        }
186    }
187    const double rel = md / std::max(mv, 1e-30);
188    const bool bad = nonfinite != 0 || rel > (f16 ? 2e-3 : 1e-5) || eb > 2.0 * ea + 1e-6 * ev;
189    std::printf("%s %sT=%-6lld %s mixed max |diff| / max |value| %.2e, BF16 / FP16 images differing %.4f%% / %.4f%%; "
190                "vs FP64 (sampled): cuBLAS + mix %.2e, fused %.2e\n", bad ? "FAIL" : "ok  ", f16 ? "FP16 io " : "", (long long) T,
191                bit_diff == 0 && bf_diff == 0 && h_diff == 0 ? "bitwise " : "        ", rel,
192                100.0 * (double) bf_diff / (double) n, 100.0 * (double) h_diff / (double) n, ea / ev, eb / ev);
193    return bad ? 1 : 0;
194}
195
196float median(std::vector<float> v) {
197    std::sort(v.begin(), v.end());
198    return v[v.size() / 2];
199}
200
201void bench(strata::prefill::Gemm& gm, cudaStream_t st, float* gated, int64_t T) {
202    Inputs in(T, 7);
203    Outputs o(T);
204    cudaEvent_t e0, e1;
205    cudaEventCreate(&e0);
206    cudaEventCreate(&e1);
207    std::vector<float> tp, tg, tm, tf;
208    for (int i = 0; i < 23; ++i) {
209        const bool fused_first = i & 1;   // alternate which runs first
210        for (int k = 0; k < 2; ++k) {
211            if ((k == 0) == fused_first) {
212                cudaEventRecord(e0, st);
213                strata::prefill::gr_upmix(in.d_lo16, in.d_wu, in.d_R, in.d_rs, in.d_w, o.mixed, o.bf, o.h, T, st);
214                cudaEventRecord(e1, st);
215                cudaEventSynchronize(e1);
216                float ms;
217                cudaEventElapsedTime(&ms, e0, e1);
218                if (i >= 3) tf.push_back(ms);
219            } else {
220                cudaEvent_t em;
221                cudaEventCreate(&em);
222                cudaEventRecord(e0, st);
223                gm.bf16(in.d_lo16, in.d_wu, gated, T, D, LR);
224                cudaEventRecord(em, st);
225                strata::prefill::gr_mix_r(in.d_R, in.d_rs, in.d_w, gated, o.mixed, o.bf, T, st, o.h);
226                cudaEventRecord(e1, st);
227                cudaEventSynchronize(e1);
228                float ms, msg;
229                cudaEventElapsedTime(&ms, e0, e1);
230                cudaEventElapsedTime(&msg, e0, em);
231                if (i >= 3) { tp.push_back(ms); tg.push_back(msg); tm.push_back(ms - msg); }
232                cudaEventDestroy(em);
233            }
234        }
235    }
236    const float p = median(tp), f = median(tf);
237    // the fused kernel's bytes: R and the outputs (FP32 + 3 x 16-bit), lo16 and w_up once
238    const double bytes = (double) T * D * 4 + (double) T * N * (4 + 6) + (double) T * LR * 2 + (double) D * LR * 2;
239    std::printf("  T=%-6lld default pair %.3f ms (up GEMM %.3f + gr_mix_r %.3f) | fused %.3f ms: %.2fx  "
240                "(fused: %.0f GB/s of its bytes, %.0f TFLOPS of its GEMM)\n", (long long) T, p, median(tg), median(tm),
241                f, p / f, bytes / f / 1e6, 2.0 * T * D * LR / f / 1e9);
242    cudaEventDestroy(e0);
243    cudaEventDestroy(e1);
244}
245
246}  // namespace
247
248int main(int argc, char** argv) {
249    {   // the fused read is sm_80+ (cp.async, BF16 mma): an older card has nothing to compare
250        int dev = 0, major = 0;
251        if (cudaGetDevice(&dev) != cudaSuccess || cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess) {
252            std::printf("gr_upmix_parity: no CUDA device, skipped\n");
253            return 77;
254        }
255#if defined(__HIPCC__)
256        cudaDeviceProp prop;   // HIP: the gfx11 matrix-core kernel (gr_upmix refuses every other architecture)
257        if (cudaGetDeviceProperties(&prop, dev) != cudaSuccess || !strata::kernels::gfx_arch_is_gfx11_wmma(prop.gcnArchName)) {
258            std::printf("gr_upmix_parity: not a gfx11 device, skipped\n");
259            return 77;
260        }
261#else
262        if (major < 8) { std::printf("gr_upmix_parity: sm_%d0, the fused read needs sm_80+: skipped\n", major); return 77; }
263#endif
264    }
265    bool do_bench = false;
266    int64_t Tmax = 32768;   // --max-t N: smaller sizes only (an iGPU that shares its memory: 2,048 tokens need about 0.4 GB)
267    for (int i = 1; i < argc; ++i) {
268        if (std::string(argv[i]) == "--bench") do_bench = true;
269        else if (std::string(argv[i]) == "--max-t" && i + 1 < argc) Tmax = std::atoll(argv[++i]);
270    }
271    cudaStream_t st = nullptr;
272    if (!ck(cudaStreamCreate(&st), "stream")) return 1;
273    strata::prefill::Gemm gm;
274    std::string err;
275    if (!gm.init(st, (int64_t) D * LR, err)) { std::printf("FAIL: %s\n", err.c_str()); return 1; }
276    float* gated = dalloc<float>((size_t) Tmax * D);
277    int fails = 0;
278    uint32_t seed = 101;
279    for (const int64_t T : {1, 7, 16, 31, 32, 33, 48, 63, 64, 65, 96, 126, 127, 128, 129, 600, 1000, 2048, 4099, 8192, 32768}) { if (T <= Tmax) fails += check(gm, st, gated, T, seed++); }
280#if defined(__HIPCC__)
281    // the FP16 prompt path (STRATA_HIP_PROMPT_F16=1): the up-mix reads FP16 images (it read them as BF16 before; the FP64 column is the arbiter)
282    for (const int64_t T : {33, 128, 600, 2048, 4099, 8192}) { if (T <= Tmax) fails += check(gm, st, gated, T, seed++, true); }
283#endif
284    if (do_bench) {
285        std::printf("--bench: the hyper-connection read's up projection + mix (medians of 20 alternating runs)\n");
286        for (const int64_t T : {2048, 8192, 32768}) { if (T <= Tmax) bench(gm, st, gated, T); }
287    }
288    cudaFree(gated);
289    std::printf("gr_upmix_parity: %d failures\n", fails);
290    return fails ? 1 : 0;
291}