okami.mom/strata

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

Niko1221Merge f-nvfp4 into f-144-rel66db34dc4

main
8.0 KiB156 linesraw
1// src/kernels/nvfp4_decode_bench.cpp - the decode path's grouped GPU experts (native_expert_grouped) timed on random
2// blobs of a format pair, as weight bytes per second against the card's DRAM bandwidth, plus a hash of the output so
3// a kernel change can be checked bit for bit.
4//
5//     nvfp4_decode_bench [gu_type d_type] [groups] [tokens per group] [iters]
6//
7// Defaults: 40 40 (NVFP4), 64 groups (distinct ~2.7 MB blobs: far past L2), 2 tokens each, 50 iterations.  UD-IQ4_XS's
8// experts: 21 20 (IQ3_S gate/up, IQ4_NL down).  Random bytes: the values are meaningless, the timing is not (the
9// kernels have no data-dependent branches but the NVFP4 scale decode), and the hash is stable for a given build.
10#include "strata/kernels/iq_kernels.hpp"
11
12#include <cuda_runtime.h>
13
14#include <cmath>
15#include <cstdint>
16#include <cstdio>
17#include <cstdlib>
18#include <cstring>
19#include <random>
20#include <vector>
21
22namespace k = strata::kernels;
23
24namespace {
25void ck(cudaError_t e, const char* what) {
26    if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); std::exit(1); }
27}
28}  // namespace
29
30int main(int argc, char** argv) {
31    {   // the UE4M3 decode built from bits (iq_kernels.cu) against the ldexpf form it replaced, all 256 bytes
32        int bad = 0;
33        for (int x = 0; x < 256; ++x) {
34            const int e = (x >> 3) & 0xF, m = x & 7;
35            const float old = (x == 0 || x == 0x7F) ? 0.0f
36                              : (e == 0 ? std::ldexp((float) m, -9) : std::ldexp(1.0f + (float) m / 8.0f, e - 7)) * 0.5f;
37            uint32_t bits = ((uint32_t) (e + 119) << 23) | ((uint32_t) m << 20);
38            float nw;
39            std::memcpy(&nw, &bits, 4);
40            if (x == 0 || x == 0x7F) nw = 0.0f;
41            else if (e == 0) nw = (float) m * 0.0009765625f;
42            bad += std::memcmp(&old, &nw, 4) != 0;
43        }
44        std::printf("ue4m3 decode: %d of 256 bytes differ from the ldexpf form\n", bad);
45        if (bad) return 1;
46    }
47    const int gu = argc > 2 ? std::atoi(argv[1]) : 40, dt = argc > 2 ? std::atoi(argv[2]) : 40;
48    const int G = argc > 3 ? std::atoi(argv[3]) : 64, TPG = argc > 4 ? std::atoi(argv[4]) : 2;
49    const int IT = argc > 5 ? std::atoi(argv[5]) : 50;
50    constexpr int64_t N = 2560, FF = 640;
51    if (!k::native_expert_supported(gu, dt, N, FF)) { std::fprintf(stderr, "types %d/%d not supported\n", gu, dt); return 2; }
52    const k::NativeExpertLayout L = k::native_expert_layout(gu, dt, N, FF);
53    const int E = G * TPG, T = 8;                      // entries; tokens of the window (activations)
54    std::mt19937 rng(20261012);
55    std::vector<uint8_t> blobs((size_t) G * L.bytes);
56    for (auto& b : blobs) b = (uint8_t) (rng() & 0xFF);
57    if (gu == 40 || dt == 40) {                        // NVFP4: UE4M3 scales in the checkpoint's range, sane tails
58        for (int g = 0; g < G; ++g) {
59            uint8_t* b = blobs.data() + (size_t) g * L.bytes;
60            auto fix = [&](size_t off, size_t bytes) {
61                for (size_t o = off; o + 36 <= off + bytes; o += 36)
62                    for (int s = 0; s < 4; ++s) b[o + s] = (uint8_t) (0x20 + rng() % 0x40);
63            };
64            if (gu == 40) fix(0, L.down_off);
65            if (dt == 40) fix(L.down_off, (size_t) N * L.d_row);
66            if (L.tail_off) {
67                const float t[4] = {8e-5f, 8e-5f, 1e-4f, 0.f};
68                std::memcpy(b + L.tail_off, t, sizeof t);
69            }
70        }
71    } else {                                           // the other formats: fp16 block scales kept finite (|d| < 2)
72        for (size_t i = 1; i < blobs.size(); i += 2) blobs[i] &= 0x3B;
73    }
74    // NVFP4_BENCH_FILE=<experts.bin or its head>: the blobs are read from it (the first G whole blobs, cycled when it
75    // holds fewer), real GPTQ / ModelOpt weights instead of random ones
76    if (const char* fp = std::getenv("NVFP4_BENCH_FILE")) {
77        FILE* f = std::fopen(fp, "rb");
78        if (!f) { std::fprintf(stderr, "cannot open %s\n", fp); return 2; }
79        int have = 0;
80        while (have < G && std::fread(blobs.data() + (size_t) have * L.bytes, 1, L.bytes, f) == L.bytes) ++have;
81        std::fclose(f);
82        if (have == 0) { std::fprintf(stderr, "%s holds no whole blob\n", fp); return 2; }
83        for (int g = have; g < G; ++g)
84            std::memcpy(blobs.data() + (size_t) g * L.bytes, blobs.data() + (size_t) (g % have) * L.bytes, L.bytes);
85        std::printf("blobs: %d real from %s (cycled to %d)\n", have, fp, G);
86    }
87    std::normal_distribution<float> nd(0.f, 1.f);
88    std::vector<float> x((size_t) T * N);
89    for (float& v : x) v = nd(rng);
90    std::vector<unsigned long long> ptr(G);
91    std::vector<int32_t> start(G + 1), dst(E), tok(E);
92    uint8_t* db;
93    ck(cudaMalloc(&db, blobs.size()), "blobs");
94    ck(cudaMemcpy(db, blobs.data(), blobs.size(), cudaMemcpyHostToDevice), "blobs");
95    for (int g = 0; g < G; ++g) {
96        ptr[g] = (unsigned long long) (db + (size_t) g * L.bytes);
97        start[g] = g * TPG;
98        for (int j = 0; j < TPG; ++j) { dst[g * TPG + j] = (g * TPG + j) % T + T * ((g * TPG + j) / T); tok[g * TPG + j] = (g + j) % T; }
99    }
100    start[G] = E;
101    for (int e = 0; e < E; ++e) dst[e] = e;            // one output row per entry (no summation races in the hash)
102    float *dx, *dout; void *dxq, *scr; unsigned long long* dptr; int32_t *dstart, *dng, *ddst, *dtok;
103    ck(cudaMalloc(&dx, x.size() * 4), "x");
104    ck(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x");
105    ck(cudaMalloc(&dxq, (size_t) T * N / 32 * 36), "xq");
106    ck(cudaMalloc(&dout, (size_t) E * N * 4), "out");
107    ck(cudaMalloc(&scr, k::native_expert_scratch_bytes(E, FF)), "scratch");
108    ck(cudaMalloc(&dptr, 8 * G), "p");
109    ck(cudaMemcpy(dptr, ptr.data(), 8 * G, cudaMemcpyHostToDevice), "p");
110    ck(cudaMalloc(&dstart, 4 * (G + 1)), "s");
111    ck(cudaMemcpy(dstart, start.data(), 4 * (G + 1), cudaMemcpyHostToDevice), "s");
112    ck(cudaMalloc(&dng, 4), "n");
113    ck(cudaMemcpy(dng, &G, 4, cudaMemcpyHostToDevice), "n");
114    ck(cudaMalloc(&ddst, 4 * E), "d");
115    ck(cudaMemcpy(ddst, dst.data(), 4 * E, cudaMemcpyHostToDevice), "d");
116    ck(cudaMalloc(&dtok, 4 * E), "t");
117    ck(cudaMemcpy(dtok, tok.data(), 4 * E, cudaMemcpyHostToDevice), "t");
118    k::quantize_q8_1_rows(dx, T, N, dxq, nullptr);
119    // NVFP4_BENCH_PHASE=1: gate/up + SwiGLU + quantize only, 2: down only (native_expert_set_mode), 0/unset: all
120    if (const char* ph = std::getenv("NVFP4_BENCH_PHASE")) k::native_expert_set_mode(-1, std::atoi(ph));
121    auto run = [&] { k::native_expert_grouped(L, dptr, dstart, dng, ddst, dtok, G, E, dxq, scr, dout, nullptr); };
122    run();
123    ck(cudaDeviceSynchronize(), "warm");
124    std::vector<float> out((size_t) E * N);
125    ck(cudaMemcpy(out.data(), dout, out.size() * 4, cudaMemcpyDeviceToHost), "out");
126    uint64_t h = 1469598103934665603ull;               // FNV-1a over the output bytes
127    for (const float& v : out) {
128        const auto* p = reinterpret_cast<const uint8_t*>(&v);
129        for (int i = 0; i < 4; ++i) h = (h ^ p[i]) * 1099511628211ull;
130    }
131    cudaEvent_t a, b;
132    cudaEventCreate(&a);
133    cudaEventCreate(&b);
134    float best = 1e30f, sum = 0.f;
135    for (int i = 0; i < IT; ++i) {
136        cudaEventRecord(a);
137        run();
138        cudaEventRecord(b);
139        cudaEventSynchronize(b);
140        float ms = 0.f;
141        cudaEventElapsedTime(&ms, a, b);
142        best = ms < best ? ms : best;
143        sum += ms;
144    }
145    ck(cudaGetLastError(), "run");
146    int dev = 0, bus = 0, clk = 0;
147    cudaGetDevice(&dev);
148    cudaDeviceGetAttribute(&bus, cudaDevAttrGlobalMemoryBusWidth, dev);
149    cudaDeviceGetAttribute(&clk, cudaDevAttrMemoryClockRate, dev);   // kHz
150    const double peak = 2.0 * clk * 1e3 * (bus / 8) / 1e9;            // GB/s, DDR
151    const double bytes = (double) G * (double) L.bytes;
152    std::printf("types %d/%d  blob %zu B  groups %d x %d tokens: best %.3f ms  mean %.3f ms  -> %.1f GB/s of weights "
153                "(%.0f%% of the %.0f GB/s DRAM peak)  out hash %016llx\n", gu, dt, L.bytes, G, TPG, best, sum / IT,
154                bytes / (best * 1e6), 100.0 * bytes / (best * 1e6) / peak, peak, (unsigned long long) h);
155    return 0;
156}