okami.mom/strata

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

Guillaume PUTIERbf16: a NaN stays a quiet NaN in f32 -> bf16, as in ggmle2b0cbcde

main
26.5 KiB475 linesraw
1// src/kernels/elementwise_parity.cpp - P2.S5's test for the layer glue.
2//
3// The ops are small; the CONVENTIONS in them are not, and each one is a place where a plausible reading
4// gives a plausible number:
5//
6//   1. `softplus` HAS A LARGE-x BRANCH.  `log1p(exp(x))` overflows f32 at x > 88 and loses relative precision
7//      well before that; `ggml_compute_softplus_f32` returns `x` above 20.  A rival without the branch is
8//      asserted observable, because a gate that saturates to +inf makes `exp(gate)` inf and the whole
9//      recurrence NaN - which reads as a state bug and not as a missing branch.
10//   2. `ssm_a` IS NEGATIVE.  `gate = softplus(...) * ssm_a`, so `exp(gate) < 1` and the state DECAYS.  A
11//      fixture with a positive `ssm_a` would still produce finite output and the recurrence would blow up
12//      instead of decaying, so the sign is checked as a property and not assumed.
13//   3. `silu` IS COMPUTED IN DOUBLE then cast, because `ref/gdn.py`'s numpy does.  f32 `expf` differs in the
14//      last bits, and the test measures that rather than asserting it away.
15#include "strata/kernels/dequant_bf16.hpp"
16#include "strata/kernels/elementwise.hpp"
17#include "strata/kernels/f16_bits.hpp"
18
19#include <cuda_runtime.h>
20
21#include <cmath>
22#include <cstdio>
23#include <cstdlib>
24#include <cstring>
25#include <random>
26#include <string>
27#include <vector>
28
29namespace {
30
31void check(cudaError_t e, const char* what) {
32    if (e != cudaSuccess) {
33        std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e));
34        std::exit(1);
35    }
36}
37
38double rel_l1(const std::vector<float>& a, const std::vector<float>& b) {
39    double d = 0, m = 0;
40    for (size_t i = 0; i < a.size(); ++i) {
41        d += std::fabs((double) a[i] - (double) b[i]);
42        m += std::fabs((double) a[i]);
43    }
44    return d / (m > 1e-30 ? m : 1e-30);
45}
46
47}  // namespace
48
49int main(int argc, char** argv) {
50    bool selftest = false;
51    for (int i = 1; i < argc; ++i) {
52        if (std::string(argv[i]) == "--selftest") selftest = true;
53        else { std::fprintf(stderr, "usage: elementwise_parity [--selftest]\n"); return 2; }
54    }
55    int bad = 0;
56    const int64_t H_V = 48;
57
58    // ---- 1. gdn_gate, with the reference's own softplus
59    {
60        const int n = (int) H_V;
61        std::mt19937 rng(11);
62        std::normal_distribution<float> g(0.0f, 1.0f);
63        std::vector<float> alpha(n), dt(n), a(n), want(n);
64        for (int i = 0; i < n; ++i) {
65            // A MIXTURE THAT ACTUALLY CROSSES THE BRANCH.  The first version drew alpha from a normal with
66            // sigma 3, so the largest value was about 9 and `softplus` never took its `x > 20` path - the
67            // "branch is observable" check then reported **0.00% apart, 0 non-finite**, which is the fixture
68            // saying it cannot see the thing it was written to see.  Every third head is now large.
69            const bool large = (i % 3) == 0;
70            // Up to ~120, so the fixture spans WELL PAST f32's `exp` overflow at 88.  A fixture that stopped
71            // at 88 would show the branch as unobservable and would be right: `log1pf(expf(x))` equals `x` to
72            // f32 precision for the whole range 20..88, so ggml's threshold of 20 is CONSERVATIVE and the
73            // behaviour only actually changes where `expf` overflows.
74            alpha[i] = large ? (22.0f + 6.0f * (float) (i % 17)) : g(rng) * 3.0f;
75            dt[i] = g(rng) * 0.5f;
76            // NEGATIVE, as the artifact's `ssm_a = -exp(A_log)` is.  Checked below as a property.
77            a[i] = -(std::fabs(g(rng)) + 0.1f);
78            const double x = (double) alpha[i] + (double) dt[i];
79            const double sp = x > 20.0 ? x : std::log1p(std::exp(x));
80            want[(size_t) i] = (float) (sp * (double) a[i]);
81        }
82        // the fixture must EXERCISE the branch, or check 1 below measures nothing
83        {
84            int over = 0, past_overflow = 0;
85            for (int i = 0; i < n; ++i) {
86                const float x = alpha[(size_t) i] + dt[(size_t) i];
87                if (x > 20.0f) ++over;
88                if (x > 88.0f) ++past_overflow;
89            }
90            std::printf("  %-44s %s (%d above 20, %d above 88)\n", "the fixture crosses the branch",
91                        over ? "yes" : "*** NO ***", over, past_overflow);
92            if (!over) ++bad;
93        }
94        // the sign property, asserted rather than assumed
95        int positive = 0;
96        for (int i = 0; i < n; ++i) if (a[(size_t) i] >= 0.0f) ++positive;
97        std::printf("  %-44s %s (%d of %d non-negative)\n", "the fixture's ssm_a is negative",
98                    positive ? "*** NO ***" : "yes", positive, n);
99        if (positive) ++bad;
100
101        float *d_a = nullptr, *d_dt = nullptr, *d_sa = nullptr, *d_g = nullptr;
102        check(cudaMalloc(&d_a, n * 4), "a");
103        check(cudaMalloc(&d_dt, n * 4), "dt");
104        check(cudaMalloc(&d_sa, n * 4), "sa");
105        check(cudaMalloc(&d_g, n * 4), "g");
106        check(cudaMemcpy(d_a, alpha.data(), n * 4, cudaMemcpyHostToDevice), "ca");
107        check(cudaMemcpy(d_dt, dt.data(), n * 4, cudaMemcpyHostToDevice), "cd");
108        check(cudaMemcpy(d_sa, a.data(), n * 4, cudaMemcpyHostToDevice), "cs");
109        strata::kernels::gdn_gate(d_a, d_dt, d_sa, d_g, 1, H_V, nullptr);
110        std::vector<float> got((size_t) n);
111        check(cudaMemcpy(got.data(), d_g, n * 4, cudaMemcpyDeviceToHost), "cg");
112
113        const double rel = rel_l1(want, got);
114        std::printf("  %-44s rel %.3e\n", "gdn_gate vs the reference", rel);
115        // double softplus and double multiply on both sides, then one cast
116        if (!(rel <= 1e-6)) { std::printf("    *** over 1e-6 ***\n"); ++bad; }
117
118        // TRAP: no large-x branch.  `log1p(exp(x))` in f32, with no `x > 20` path.
119        //
120        // AND THE MEASUREMENT SAYS WHERE THE BRANCH ACTUALLY MATTERS.  The first version of this fixture
121        // spanned 20..88 and reported **0 heads differ**: `log1pf(expf(x))` agrees with `x` to f32 precision
122        // over that whole range, so ggml's threshold of 20 is CONSERVATIVE - the branch changes the answer only
123        // where `expf` OVERFLOWS, at about 88.  The check reports the smallest x at which the two readings
124        // part company, so the number is in the output rather than in this comment.
125        {
126            int wrong = 0, differing = 0;
127            float first_differ = -1.0f;
128            std::vector<float> rival((size_t) n);
129            for (int i = 0; i < n; ++i) {
130                const float x = alpha[(size_t) i] + dt[(size_t) i];
131                const float sp = std::log1p(std::exp(x));       // no branch, f32
132                rival[(size_t) i] = sp * a[(size_t) i];
133                if (!std::isfinite(sp)) ++wrong;
134                const float branched = x > 20.0f ? x : std::log1pf(std::exp(x));
135                if (sp != branched) {
136                    ++differing;
137                    if (first_differ < 0.0f || x < first_differ) first_differ = x;
138                }
139            }
140            const double r = rel_l1(want, rival);
141            const bool visible = r > 0.05 || wrong > 0;
142            std::printf("  %-44s %s (%.2f%% apart, %d non-finite, %d heads differ, first at x = %.1f)\n",
143                        "the softplus large-x branch is observable", visible ? "yes" : "*** NO ***",
144                        r * 100, wrong, differing, (double) first_differ);
145            if (!visible) ++bad;
146        }
147        // PROPERTY: exp(gate) < 1 for every element, which is what makes the state decay
148        {
149            int over = 0;
150            for (float v : got) if (!(std::exp(v) < 1.0f)) ++over;
151            std::printf("  %-44s %s (%d of %d not < 1)\n", "exp(gate) < 1 for every head",
152                        over ? "*** NO ***" : "yes", over, n);
153            if (over) ++bad;
154        }
155        cudaFree(d_a); cudaFree(d_dt); cudaFree(d_sa); cudaFree(d_g);
156    }
157
158    // ---- 2. silu, in double then cast
159    {
160        const int n = 4096;
161        std::mt19937 rng(22);
162        std::normal_distribution<float> g(0.0f, 3.0f);
163        std::vector<float> x((size_t) n), want((size_t) n);
164        for (int i = 0; i < n; ++i) {
165            x[(size_t) i] = g(rng);
166            const double v = (double) x[(size_t) i];
167            want[(size_t) i] = (float) (v / (1.0 + std::exp(-v)));
168        }
169        float* d_x = nullptr;
170        check(cudaMalloc(&d_x, n * 4), "sx");
171        check(cudaMemcpy(d_x, x.data(), n * 4, cudaMemcpyHostToDevice), "csx");
172        strata::kernels::silu_inplace(d_x, n, nullptr);
173        std::vector<float> got((size_t) n);
174        check(cudaMemcpy(got.data(), d_x, n * 4, cudaMemcpyDeviceToHost), "csg");
175        const double rel = rel_l1(want, got);
176        std::printf("\n  %-44s rel %.3e\n", "silu (double) vs the reference", rel);
177        if (!(rel <= 1e-7)) { std::printf("    *** over 1e-7 ***\n"); ++bad; }
178        cudaFree(d_x);
179    }
180
181    // ---- 3. scale and the f32->f16 bridge
182    {
183        const int n = 1024;
184        std::vector<float> x((size_t) n), want((size_t) n);
185        for (int i = 0; i < n; ++i) x[(size_t) i] = (float) (i - n / 2) * 0.013f;
186        const float s = 1.0f / std::sqrt(128.0f);
187        for (int i = 0; i < n; ++i) want[(size_t) i] = x[(size_t) i] * s;
188
189        float* d_x = nullptr;
190        uint16_t* d_h = nullptr;
191        check(cudaMalloc(&d_x, n * 4), "ex");
192        check(cudaMalloc(&d_h, n * 2), "eh");
193        check(cudaMemcpy(d_x, x.data(), n * 4, cudaMemcpyHostToDevice), "cex");
194        strata::kernels::scale_inplace(d_x, n, s, nullptr);
195        std::vector<float> got((size_t) n);
196        check(cudaMemcpy(got.data(), d_x, n * 4, cudaMemcpyDeviceToHost), "ceg");
197        int diff = 0;
198        for (int i = 0; i < n; ++i) if (got[(size_t) i] != want[(size_t) i]) ++diff;
199        std::printf("  %-44s %d of %d differ\n", "scale_inplace is exact", diff, n);
200        if (diff) ++bad;
201
202        strata::kernels::f32_to_f16_bulk(d_x, d_h, n, nullptr);
203        std::vector<uint16_t> h((size_t) n);
204        check(cudaMemcpy(h.data(), d_h, n * 2, cudaMemcpyDeviceToHost), "ceh");
205        int hbad = 0;
206        for (int i = 0; i < n; ++i)
207            if (h[(size_t) i] != strata::kernels::f16_from_f32(got[(size_t) i])) ++hbad;
208        std::printf("  %-44s %d of %d differ\n", "f32_to_f16_bulk uses the shared conversion", hbad, n);
209        if (hbad) ++bad;
210        cudaFree(d_x); cudaFree(d_h);
211    }
212
213    // ---- 4. rms_norm_weighted, and the TWO RIVAL READINGS it exists to be told apart from.
214    //
215    // This kernel's whole reason for being a separate entry point from `gdn_l2_norm` is that the two differ by
216    // one `/ cols`, and that a swap produces a well-scaled, plausible tensor.  So the test computes BOTH wrong
217    // readings and requires each to differ from the right one by more than the tolerance before it judges the
218    // kernel - the same discipline the shared-expert test uses for silu-on-gate.
219    {
220        const int64_t rows = 24, cols = 256;          // the real `attn_q`-norm shape
221        const float eps = 1e-6f;
222        std::vector<float> x((size_t) (rows * cols));
223        for (size_t i = 0; i < x.size(); ++i) x[i] = (float) std::sin((double) i * 0.017) * 1.7f + 0.4f;
224        std::vector<float> w((size_t) cols);
225        for (int64_t c = 0; c < cols; ++c) w[(size_t) c] = 0.5f + 0.002f * (float) (c % 97);
226
227        // the oracle: f64, mean, times w
228        auto ref = [&](bool use_sum, bool use_w) {
229            std::vector<double> y((size_t) (rows * cols));
230            for (int64_t r = 0; r < rows; ++r) {
231                double ss = 0;
232                for (int64_t c = 0; c < cols; ++c) {
233                    const double v = x[(size_t) (r * cols + c)];
234                    ss += v * v;
235                }
236                const double den = std::sqrt((use_sum ? ss : ss / (double) cols) + (double) eps);
237                for (int64_t c = 0; c < cols; ++c) {
238                    const double v = x[(size_t) (r * cols + c)];
239                    y[(size_t) (r * cols + c)] = (v / den) * (use_w ? (double) w[(size_t) c] : 1.0);
240                }
241            }
242            std::vector<float> out((size_t) (rows * cols));
243            for (size_t i = 0; i < out.size(); ++i) out[i] = (float) y[i];
244            return out;
245        };
246        const std::vector<float> want = ref(false, true);
247        const std::vector<float> rival_sum = ref(true, false);    // what gdn_l2_norm computes
248        const std::vector<float> rival_now = ref(false, false);   // the (1+w)-vs-w / no-weight confusion
249
250        auto rel = [&](const std::vector<float>& a, const std::vector<float>& b) {
251            double d = 0, m = 0;
252            for (size_t i = 0; i < a.size(); ++i) {
253                d += std::fabs((double) a[i] - (double) b[i]);
254                m += std::fabs((double) a[i]);
255            }
256            return d / (m > 1e-30 ? m : 1e-30);
257        };
258        const double r_sum = rel(want, rival_sum), r_now = rel(want, rival_now);
259        std::printf("  %-44s %.2f%% apart\n", "sum-vs-mean is observable", r_sum * 100);
260        std::printf("  %-44s %.2f%% apart\n", "with-w-vs-without-w is observable", r_now * 100);
261        // `sqrt(cols)` = 16 for the first and the weight's own spread for the second; a fixture that cannot
262        // separate them is not testing the kernel that was written.
263        if (!(r_sum > 0.5)) { std::printf("  *** the sum reading is NOT observable ***\n"); ++bad; }
264        if (!(r_now > 0.5)) { std::printf("  *** the no-weight reading is NOT observable ***\n"); ++bad; }
265
266        float* d_x = nullptr;
267        float* d_w = nullptr;
268        check(cudaMalloc(&d_x, x.size() * 4), "m rmsx");
269        check(cudaMalloc(&d_w, w.size() * 4), "m rmsw");
270        check(cudaMemcpy(d_x, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "c rmsx");
271        check(cudaMemcpy(d_w, w.data(), w.size() * 4, cudaMemcpyHostToDevice), "c rmsw");
272        strata::kernels::rms_norm_weighted(d_x, d_w, rows, cols, eps, nullptr);
273        std::vector<float> got((size_t) (rows * cols));
274        check(cudaMemcpy(got.data(), d_x, got.size() * 4, cudaMemcpyDeviceToHost), "c rmsg");
275
276        const double r_got = rel(want, got);
277        double worst = 0;
278        for (size_t i = 0; i < got.size(); ++i) {
279            const double m = std::fabs((double) want[i]);
280            const double e = std::fabs((double) got[i] - (double) want[i]) / (m > 1e-30 ? m : 1e-30);
281            if (e > worst) worst = e;
282        }
283        int nonfinite = 0;
284        for (float v : got) if (!std::isfinite(v)) ++nonfinite;
285        std::printf("  %-44s rel %.3e  worst %.3e  nonfinite %d\n", "rms_norm_weighted vs f64 oracle", r_got,
286                    worst, nonfinite);
287        if (nonfinite) ++bad;
288        // The kernel accumulates in f32 over 256 terms; 1e-6 is loose enough for that and far tighter than the
289        // 16x the rival readings are off by.
290        if (!(r_got < 1e-6)) { std::printf("  *** rms_norm_weighted is WRONG ***\n"); ++bad; }
291        // and a null `w` must be legal, because `ref/qsa.py` allows it.
292        //
293        // THE INPUT HAS TO BE RE-UPLOADED FIRST.  The kernel is IN PLACE, so `d_x` currently holds the
294        // NORMALISED tensor from the call above; running it again normalises a second time and every element
295        // differs.  That is exactly what the first version of this check reported - "6144 of 6144 differ" -
296        // and it is a fixture bug rather than a kernel bug: the oracle reads the ORIGINAL `x`, so the two
297        // sides were never looking at the same input.
298        const std::vector<float> want_null = ref(false, false);
299        check(cudaMemcpy(d_x, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "c rmsx2");
300        strata::kernels::rms_norm_weighted(d_x, nullptr, rows, cols, eps, nullptr);
301        check(cudaMemcpy(got.data(), d_x, got.size() * 4, cudaMemcpyDeviceToHost), "c rmsn");
302        int null_bad = 0;
303        for (size_t i = 0; i < got.size(); ++i)
304            if (std::fabs((double) got[i] - (double) want_null[i]) > 1e-6) ++null_bad;
305        std::printf("  %-44s %d of %zu differ\n", "a null weight is legal", null_bad, got.size());
306        if (null_bad) ++bad;
307        cudaFree(d_x);
308        cudaFree(d_w);
309    }
310
311    // Packed embedding rows: every code width, scale-group size, optional offset,
312    // row boundary and partial CUDA block. Compare bits with a scalar CPU decoder.
313    // Volatile materializes the multiply so this oracle cannot silently use FMA.
314    {
315        cudaStream_t stream;
316        check(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking), "embedding stream");
317        std::mt19937 rng(77);
318        std::uniform_real_distribution<float> values(-2.0f, 2.0f);
319        int mismatches = 0, guards = 0, fma_diff = 0, cases = 0;
320        for (const int bits : {2, 4, 8}) {
321            const int bias = bits == 2 ? -1 : bits == 4 ? -7 : -16;
322            const int per_byte = 8 / bits;
323            const unsigned mask = (1u << bits) - 1u;
324            for (const int group : {16, 32, 64}) {
325                for (const int n : {320, 2560}) {
326                    const int row_bytes = n / per_byte, row_groups = n / group;
327                    std::vector<uint8_t> codes((size_t) 3 * row_bytes, 0);
328                    std::vector<float> scales((size_t) 3 * row_groups), offsets(scales.size());
329                    std::vector<int> unpacked((size_t) 3 * n);
330                    for (size_t i = 0; i < unpacked.size(); ++i) {
331                        const unsigned code = (unsigned) (i * 13 + i / n * 7) & mask;
332                        unpacked[i] = (int) code;
333                        codes[i / per_byte] |= (uint8_t) (code << ((i % per_byte) * bits));
334                    }
335                    for (size_t i = 0; i < scales.size(); ++i) {
336                        scales[i] = values(rng);
337                        offsets[i] = values(rng);
338                    }
339                    scales[0] = -0.0f;
340                    offsets[0] = 0.0f;
341                    uint8_t* dc = nullptr;
342                    float *ds = nullptr, *dof = nullptr, *out = nullptr;
343                    check(cudaMalloc(&dc, codes.size()), "embedding codes");
344                    check(cudaMalloc(&ds, scales.size() * sizeof(float)), "embedding scales");
345                    check(cudaMalloc(&dof, offsets.size() * sizeof(float)), "embedding offsets");
346                    check(cudaMalloc(&out, ((size_t) n + 2) * sizeof(float)), "embedding output");
347                    check(cudaMemcpyAsync(dc, codes.data(), codes.size(), cudaMemcpyHostToDevice, stream), "embedding codes upload");
348                    check(cudaMemcpyAsync(ds, scales.data(), scales.size() * sizeof(float), cudaMemcpyHostToDevice, stream), "embedding scales upload");
349                    check(cudaMemcpyAsync(dof, offsets.data(), offsets.size() * sizeof(float), cudaMemcpyHostToDevice, stream), "embedding offsets upload");
350                    check(cudaStreamSynchronize(stream), "embedding upload sync");
351
352                    for (const bool with_offset : {false, true}) {
353                        for (int row = 0; row < 3; ++row) {
354                            std::vector<float> want((size_t) n), got((size_t) n + 2, -12345.0f);
355                            for (int i = 0; i < n; ++i) {
356                                const size_t gi = (size_t) row * row_groups + i / group;
357                                const float code = (float) (unpacked[(size_t) row * n + i] + bias);
358                                volatile float product = code * scales[gi];
359                                const float offset = with_offset ? offsets[gi] : 0.0f;
360                                want[(size_t) i] = product + offset;
361                                const float fused = std::fma(code, scales[gi], offset);
362                                if (std::memcmp(&fused, &want[(size_t) i], sizeof(float)) != 0) ++fma_diff;
363                            }
364                            check(cudaMemcpyAsync(out, got.data(), got.size() * sizeof(float), cudaMemcpyHostToDevice, stream), "embedding output guards");
365                            strata::kernels::embedding_gather(dc + (size_t) row * row_bytes,
366                                ds + (size_t) row * row_groups,
367                                with_offset ? dof + (size_t) row * row_groups : nullptr,
368                                n, bits, bias, group, out + 1, stream);
369                            check(cudaMemcpyAsync(got.data(), out, got.size() * sizeof(float), cudaMemcpyDeviceToHost, stream), "embedding result");
370                            check(cudaStreamSynchronize(stream), "embedding sync");
371                            for (int i = 0; i < n; ++i) {
372                                if (std::memcmp(&want[(size_t) i], &got[(size_t) i + 1], sizeof(float)) != 0) ++mismatches;
373                            }
374                            if (got.front() != -12345.0f || got.back() != -12345.0f) ++guards;
375                            ++cases;
376
377                            // Capturing the gather proves that it has no hidden synchronization.
378                            // A following scale also checks that it uses the caller's stream.
379                            if (row == 1) {
380                                cudaGraph_t graph;
381                                cudaGraphExec_t exec;
382                                check(cudaStreamBeginCapture(stream, cudaStreamCaptureModeThreadLocal), "embedding capture");
383                                strata::kernels::embedding_gather(dc + (size_t) row * row_bytes,
384                                    ds + (size_t) row * row_groups,
385                                    with_offset ? dof + (size_t) row * row_groups : nullptr,
386                                    n, bits, bias, group, out + 1, stream);
387                                strata::kernels::scale_inplace(out + 1, n, 2.0f, stream);
388                                check(cudaStreamEndCapture(stream, &graph), "embedding capture end");
389                                check(cudaGraphInstantiate(&exec, graph, 0), "embedding instantiate");
390                                check(cudaGraphLaunch(exec, stream), "embedding replay");
391                                check(cudaMemcpyAsync(got.data(), out, got.size() * sizeof(float), cudaMemcpyDeviceToHost, stream), "embedding graph result");
392                                check(cudaStreamSynchronize(stream), "embedding graph sync");
393                                for (int i = 0; i < n; ++i) {
394                                    const float expected = want[(size_t) i] * 2.0f;
395                                    if (std::memcmp(&expected, &got[(size_t) i + 1], sizeof(float)) != 0) ++mismatches;
396                                }
397                                if (got.front() != -12345.0f || got.back() != -12345.0f) ++guards;
398                                check(cudaGraphExecDestroy(exec), "embedding exec destroy");
399                                check(cudaGraphDestroy(graph), "embedding graph destroy");
400                            }
401                        }
402                    }
403                    cudaFree(dc); cudaFree(ds); cudaFree(dof); cudaFree(out);
404                }
405            }
406        }
407        check(cudaStreamDestroy(stream), "embedding stream destroy");
408        std::printf("  embedding gather: %d row cases, %d bit mismatches, %d guard failures, %d FMA differences\n",
409                    cases, mismatches, guards, fma_diff);
410        if (mismatches || guards || fma_diff == 0) ++bad;
411    }
412
413    // ---- THE f32 -> bf16 CONVERSIONS KEEP A NaN A NaN.  `f32_to_bf16_bulk` (the header's `bf16_from_f32`
414    // on the device) and the prompt path's dequantizer (its own `f2bf`) against ggml_compute_fp32_to_bf16's rule;
415    // before the fix 0x7FFFFFFF came back as -0 and 0x7F800001 as +inf.  `bf16_bits_test` covers every f32 on
416    // the host; this is the same header compiled by nvcc, plus the second copy in dequant_bf16.cu.
417    {
418        auto ggml_bf16 = [](uint32_t u) -> uint16_t {
419            if ((u & 0x7fffffffu) > 0x7f800000u) return (uint16_t) ((u >> 16) | 64);
420            return (uint16_t) ((u + (0x7fffu + ((u >> 16) & 1u))) >> 16);
421        };
422        std::vector<uint32_t> bits = {0x7FFFFFFFu, 0xFFFFFFFFu, 0x7F800001u, 0xFF800001u, 0x7FC00000u, 0x7FBFFFFFu,
423                                      0x7F800000u, 0xFF800000u, 0x7F7FFFFFu, 0x00000000u, 0x80000000u, 0x3F808000u,
424                                      0x3F818000u, 0x00008000u, 0x7F7F8000u};
425        std::mt19937 rng(13);
426        while (bits.size() < 4096) bits.push_back((uint32_t) rng());
427        const size_t n = bits.size();
428        float* dx = nullptr;
429        uint16_t* dy = nullptr;
430        check(cudaMalloc(&dx, n * 4), "bf16 x");
431        check(cudaMalloc(&dy, n * 2), "bf16 y");
432        check(cudaMemcpy(dx, bits.data(), n * 4, cudaMemcpyHostToDevice), "bf16 cx");
433        strata::kernels::f32_to_bf16_bulk(dx, dy, (int64_t) n, nullptr);
434        std::vector<uint16_t> got(n);
435        check(cudaMemcpy(got.data(), dy, n * 2, cudaMemcpyDeviceToHost), "bf16 cy");
436        int wrong = 0;
437        for (size_t i = 0; i < n; ++i) wrong += got[i] != ggml_bf16(bits[i]);
438
439        // A Q8_0 block (type 8) whose fp16 scale is a NaN: every dequantized value is NaN * q, a NaN, and it must
440        // still be one in BF16.  A second block with an ordinary scale checks the finite path did not move.
441        std::vector<uint8_t> blk(2 * 34, 0);
442        blk[0] = 0x00; blk[1] = 0x7E;                        // fp16 quiet NaN
443        blk[34] = 0x00; blk[35] = 0x3C;                      // fp16 1.0
444        for (int j = 0; j < 32; ++j) {
445            blk[(size_t) (2 + j)] = (uint8_t) (int8_t) (j - 16);
446            blk[(size_t) (36 + j)] = (uint8_t) (int8_t) (3 * j - 50);
447        }
448        uint8_t* db = nullptr;
449        uint16_t* dq = nullptr;
450        check(cudaMalloc(&db, blk.size()), "q8 blk");
451        check(cudaMalloc(&dq, 64 * 2), "q8 out");
452        check(cudaMemcpy(db, blk.data(), blk.size(), cudaMemcpyHostToDevice), "q8 cblk");
453        strata::kernels::dequant_bf16(8, db, 0, 2, 32, dq, nullptr);
454        check(cudaDeviceSynchronize(), "dequant_bf16");
455        std::vector<uint16_t> q(64);
456        check(cudaMemcpy(q.data(), dq, 64 * 2, cudaMemcpyDeviceToHost), "q8 cout");
457        int dq_wrong = 0;
458        for (int j = 0; j < 32; ++j) {
459            if (!((q[(size_t) j] & 0x7FFFu) > 0x7F80u)) ++dq_wrong;           // row 0: NaN scale -> NaN
460            const float v = (float) (3 * j - 50);                                // row 1: d = 1.0 -> the integer
461            uint32_t vb;
462            std::memcpy(&vb, &v, 4);
463            if (q[(size_t) (32 + j)] != ggml_bf16(vb)) ++dq_wrong;
464        }
465        std::printf("  f32 -> bf16 (NaN kept): bulk %d of %zu differ from ggml, dequant_bf16 %d of 64 wrong\n",
466                    wrong, n, dq_wrong);
467        if (wrong || dq_wrong) ++bad;
468        cudaFree(dx); cudaFree(dy); cudaFree(db); cudaFree(dq);
469    }
470
471    std::printf("\nelementwise: %d failures\n", bad);
472    if (bad) return 1;
473    if (selftest) std::printf("elementwise_parity OK\n");
474    return 0;
475}