Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

bf16: a NaN stays a quiet NaN in f32 -> bf16, as in ggml

Guillaume PUTIERe2b0cbcde9ad
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 22e4528a0..f33208645 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -579,6 +579,10 @@ if(STRATA_BUILD_TESTS)
add_executable(conv_cache_test src/program/conv_cache_test.cpp)
target_include_directories(conv_cache_test PRIVATE include)
add_test(NAME conv_cache_test COMMAND conv_cache_test)
+ # the f32 -> bf16 rounding against ggml's, NaN included, over every f32 bit pattern (header-only, CPU)
+ add_executable(bf16_bits_test src/kernels/bf16_bits_test.cpp)
+ target_include_directories(bf16_bits_test PRIVATE include)
+ add_test(NAME bf16_bits_test COMMAND bf16_bits_test)
endif()
add_library(strata_kernels_cpu STATIC src/kernels/cpu/expert.cpp src/kernels/cpu/pool.cpp
diff --git a/include/strata/kernels/bf16_bits.hpp b/include/strata/kernels/bf16_bits.hpp
index 5c37701fb..5c32532f6 100644
--- a/include/strata/kernels/bf16_bits.hpp
+++ b/include/strata/kernels/bf16_bits.hpp
@@ -28,6 +28,12 @@
namespace strata::kernels {
/// Round-to-nearest-even f32 -> bf16, returned as raw bits in the LOW half of the uint16.
+///
+/// **A NaN IS PASSED THROUGH, QUIETED, AS `ggml_compute_fp32_to_bf16` DOES.** The rounding add alone
+/// carries out of the mantissa for a NaN: 0x7FFFFFFF became 0x8000 (-0) and 0x7F800001 became 0x7F80 (+inf), so
+/// a NaN upstream was masked instead of propagated. The test is on the magnitude bits, the result keeps the
+/// sign and the top mantissa bits and sets the quiet bit (64 = bit 6 of the bf16). Every non-NaN input,
+/// infinities included, rounds exactly as before.
STRATA_BF16_HD inline uint16_t bf16_from_f32(float f) {
uint32_t i;
#if defined(__HIP_DEVICE_COMPILE__)
@@ -35,6 +41,7 @@ STRATA_BF16_HD inline uint16_t bf16_from_f32(float f) {
#else
std::memcpy(&i, &f, 4);
#endif
+ if ((i & 0x7FFFFFFFu) > 0x7F800000u) return (uint16_t) ((i >> 16) | 64u);
i = (i + ((i >> 16) & 1u) + 0x7FFFu) & 0xFFFF0000u;
return (uint16_t) (i >> 16);
}
diff --git a/src/kernels/bf16_bits_test.cpp b/src/kernels/bf16_bits_test.cpp
new file mode 100644
index 000000000..f996463f5
--- /dev/null
+++ b/src/kernels/bf16_bits_test.cpp
@@ -0,0 +1,80 @@
+// src/kernels/bf16_bits_test.cpp - `bf16_bits.hpp` against ggml's rule, over EVERY f32 bit pattern (CPU only).
+//
+// the rounding add `i + 0x7FFF + bit16` carries out of the mantissa for a NaN, so 0x7FFFFFFF came back as
+// -0 and 0x7F800001 as +inf - an upstream NaN was masked instead of propagated. `ggml_compute_fp32_to_bf16`
+// (ggml-impl.h at the pinned llama.cpp) tests the NaN first and returns `(i >> 16) | 64`. Three checks, all
+// exhaustive (2^32 inputs, a few seconds):
+//
+// 1. the header equals ggml's function, transcribed below, on every input;
+// 2. on every NON-NaN input it equals the previous rounding, so the change cannot move a finite value or an
+// infinity by a single bit;
+// 3. every NaN input gives a quiet NaN of the same sign.
+//
+// And the round trip over all 65,536 bf16 patterns: a non-NaN bf16 survives f32 and back unchanged.
+#include "strata/kernels/bf16_bits.hpp"
+
+#include <cstdint>
+#include <cstdio>
+#include <cstring>
+
+namespace {
+
+/// ggml_compute_fp32_to_bf16, ggml/src/ggml-impl.h (MIT, the ggml authors), on raw bits.
+uint16_t ggml_bf16(uint32_t u) {
+ if ((u & 0x7fffffffu) > 0x7f800000u) return (uint16_t) ((u >> 16) | 64);
+ return (uint16_t) ((u + (0x7fffu + ((u >> 16) & 1u))) >> 16);
+}
+
+/// The rule before this fix, kept only to prove the change is confined to NaN inputs.
+uint16_t previous_bf16(uint32_t u) {
+ u = (u + ((u >> 16) & 1u) + 0x7FFFu) & 0xFFFF0000u;
+ return (uint16_t) (u >> 16);
+}
+
+bool is_nan_bits(uint32_t u) { return (u & 0x7fffffffu) > 0x7f800000u; }
+
+} // namespace
+
+int main() {
+ unsigned long long vs_ggml = 0, vs_previous = 0, nan_lost = 0, nan_inputs = 0, previous_masked = 0;
+ uint32_t first_bad = 0;
+ bool have_bad = false;
+ for (uint64_t k = 0; k <= 0xFFFFFFFFull; ++k) {
+ const uint32_t u = (uint32_t) k;
+ float f;
+ std::memcpy(&f, &u, 4);
+ const uint16_t got = strata::kernels::bf16_from_f32(f);
+ if (got != ggml_bf16(u)) {
+ ++vs_ggml;
+ if (!have_bad) { first_bad = u; have_bad = true; }
+ }
+ if (is_nan_bits(u)) {
+ ++nan_inputs;
+ const uint32_t back = (uint32_t) got << 16;
+ // a quiet NaN (bit 22 of the f32) with the input's sign
+ if (!is_nan_bits(back) || (back & 0x00400000u) == 0 || (back >> 31) != (u >> 31)) ++nan_lost;
+ if (!is_nan_bits((uint32_t) previous_bf16(u) << 16)) ++previous_masked;
+ } else if (got != previous_bf16(u)) {
+ ++vs_previous;
+ if (!have_bad) { first_bad = u; have_bad = true; }
+ }
+ }
+ std::printf(" f32 -> bf16 over 2^32 inputs: %llu differ from ggml, %llu non-NaN differ from the previous rule\n",
+ vs_ggml, vs_previous);
+ std::printf(" NaN inputs: %llu, not a quiet same-sign NaN now: %llu (the previous rule masked %llu of them)\n",
+ nan_inputs, nan_lost, previous_masked);
+ if (have_bad) std::printf(" first mismatch at input 0x%08x\n", first_bad);
+
+ unsigned long long trip_bad = 0;
+ for (uint32_t h = 0; h <= 0xFFFFu; ++h) {
+ const float f = strata::kernels::f32_from_bf16((uint16_t) h);
+ const uint16_t back = strata::kernels::bf16_from_f32(f);
+ const bool nan = is_nan_bits(h << 16);
+ if (back != (nan ? (uint16_t) (h | 64u) : (uint16_t) h)) ++trip_bad;
+ }
+ std::printf(" bf16 -> f32 -> bf16 over 65536 patterns: %llu wrong\n", trip_bad);
+
+ const bool ok = vs_ggml == 0 && vs_previous == 0 && nan_lost == 0 && trip_bad == 0 && previous_masked > 0;
+ std::printf("\nbf16_bits_test %s\n", ok ? "OK" : "FAILED");
+ return ok ? 0 : 1;
+}
diff --git a/src/kernels/cuda/dequant_bf16.cu b/src/kernels/cuda/dequant_bf16.cu
index 849d5118f..faac2ab4b 100644
--- a/src/kernels/cuda/dequant_bf16.cu
+++ b/src/kernels/cuda/dequant_bf16.cu
@@ -19,6 +19,9 @@ __device__ __forceinline__ float h2f(const uint8_t* p) {
}
__device__ __forceinline__ uint16_t f2bf(float f) {
uint32_t u = __float_as_uint(f);
+ // a NaN (a NaN scale in the block) stays a quiet NaN, as in ggml_compute_fp32_to_bf16 and `bf16_from_f32`:
+ // the rounding add below would carry it into -0 or inf
+ if ((u & 0x7fffffffu) > 0x7f800000u) return (uint16_t) ((u >> 16) | 64u);
u += 0x7fffu + ((u >> 16) & 1u); // round to nearest even
return (uint16_t) (u >> 16);
}
diff --git a/src/kernels/elementwise_parity.cpp b/src/kernels/elementwise_parity.cpp
index 58a2c36d1..9a8fc3f3c 100644
--- a/src/kernels/elementwise_parity.cpp
+++ b/src/kernels/elementwise_parity.cpp
@@ -12,6 +12,7 @@
// instead of decaying, so the sign is checked as a property and not assumed.
// 3. `silu` IS COMPUTED IN DOUBLE then cast, because `ref/gdn.py`'s numpy does. f32 `expf` differs in the
// last bits, and the test measures that rather than asserting it away.
+#include "strata/kernels/dequant_bf16.hpp"
#include "strata/kernels/elementwise.hpp"
#include "strata/kernels/f16_bits.hpp"
@@ -409,6 +410,64 @@ int main(int argc, char** argv) {
if (mismatches || guards || fma_diff == 0) ++bad;
}
+ // ---- THE f32 -> bf16 CONVERSIONS KEEP A NaN A NaN. `f32_to_bf16_bulk` (the header's `bf16_from_f32`
+ // on the device) and the prompt path's dequantizer (its own `f2bf`) against ggml_compute_fp32_to_bf16's rule;
+ // before the fix 0x7FFFFFFF came back as -0 and 0x7F800001 as +inf. `bf16_bits_test` covers every f32 on
+ // the host; this is the same header compiled by nvcc, plus the second copy in dequant_bf16.cu.
+ {
+ auto ggml_bf16 = [](uint32_t u) -> uint16_t {
+ if ((u & 0x7fffffffu) > 0x7f800000u) return (uint16_t) ((u >> 16) | 64);
+ return (uint16_t) ((u + (0x7fffu + ((u >> 16) & 1u))) >> 16);
+ };
+ std::vector<uint32_t> bits = {0x7FFFFFFFu, 0xFFFFFFFFu, 0x7F800001u, 0xFF800001u, 0x7FC00000u, 0x7FBFFFFFu,
+ 0x7F800000u, 0xFF800000u, 0x7F7FFFFFu, 0x00000000u, 0x80000000u, 0x3F808000u,
+ 0x3F818000u, 0x00008000u, 0x7F7F8000u};
+ std::mt19937 rng(13);
+ while (bits.size() < 4096) bits.push_back((uint32_t) rng());
+ const size_t n = bits.size();
+ float* dx = nullptr;
+ uint16_t* dy = nullptr;
+ check(cudaMalloc(&dx, n * 4), "bf16 x");
+ check(cudaMalloc(&dy, n * 2), "bf16 y");
+ check(cudaMemcpy(dx, bits.data(), n * 4, cudaMemcpyHostToDevice), "bf16 cx");
+ strata::kernels::f32_to_bf16_bulk(dx, dy, (int64_t) n, nullptr);
+ std::vector<uint16_t> got(n);
+ check(cudaMemcpy(got.data(), dy, n * 2, cudaMemcpyDeviceToHost), "bf16 cy");
+ int wrong = 0;
+ for (size_t i = 0; i < n; ++i) wrong += got[i] != ggml_bf16(bits[i]);
+
+ // A Q8_0 block (type 8) whose fp16 scale is a NaN: every dequantized value is NaN * q, a NaN, and it must
+ // still be one in BF16. A second block with an ordinary scale checks the finite path did not move.
+ std::vector<uint8_t> blk(2 * 34, 0);
+ blk[0] = 0x00; blk[1] = 0x7E; // fp16 quiet NaN
+ blk[34] = 0x00; blk[35] = 0x3C; // fp16 1.0
+ for (int j = 0; j < 32; ++j) {
+ blk[(size_t) (2 + j)] = (uint8_t) (int8_t) (j - 16);
+ blk[(size_t) (36 + j)] = (uint8_t) (int8_t) (3 * j - 50);
+ }
+ uint8_t* db = nullptr;
+ uint16_t* dq = nullptr;
+ check(cudaMalloc(&db, blk.size()), "q8 blk");
+ check(cudaMalloc(&dq, 64 * 2), "q8 out");
+ check(cudaMemcpy(db, blk.data(), blk.size(), cudaMemcpyHostToDevice), "q8 cblk");
+ strata::kernels::dequant_bf16(8, db, 0, 2, 32, dq, nullptr);
+ check(cudaDeviceSynchronize(), "dequant_bf16");
+ std::vector<uint16_t> q(64);
+ check(cudaMemcpy(q.data(), dq, 64 * 2, cudaMemcpyDeviceToHost), "q8 cout");
+ int dq_wrong = 0;
+ for (int j = 0; j < 32; ++j) {
+ if (!((q[(size_t) j] & 0x7FFFu) > 0x7F80u)) ++dq_wrong; // row 0: NaN scale -> NaN
+ const float v = (float) (3 * j - 50); // row 1: d = 1.0 -> the integer
+ uint32_t vb;
+ std::memcpy(&vb, &v, 4);
+ if (q[(size_t) (32 + j)] != ggml_bf16(vb)) ++dq_wrong;
+ }
+ std::printf(" f32 -> bf16 (NaN kept): bulk %d of %zu differ from ggml, dequant_bf16 %d of 64 wrong\n",
+ wrong, n, dq_wrong);
+ if (wrong || dq_wrong) ++bad;
+ cudaFree(dx); cudaFree(dy); cudaFree(db); cudaFree(dq);
+ }
+
std::printf("\nelementwise: %d failures\n", bad);
if (bad) return 1;
if (selftest) std::printf("elementwise_parity OK\n");