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++

sm_75: run the prompt path's BF16 products on the FP16 tensor cores

Rafa4dbc4c8b82b2
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 347d2ec7c..c25a6feb5 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -584,6 +584,11 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
add_executable(gdn_rec_parity src/prefill/gdn_rec_parity.cu)
target_link_libraries(gdn_rec_parity PRIVATE ${_strata_gpu_runtime_target})
add_test(NAME gdn_rec_parity COMMAND gdn_rec_parity)
+ # the prompt path's BF16 products against cuBLAS's own BF16 GEMM, within fp32 rounding (sm_75 runs them on the
+ # FP16 tensor cores; GPU, synthetic, no model; --bench adds timings)
+ add_executable(gemm_bf16_parity src/prefill/gemm_bf16_parity.cu)
+ target_link_libraries(gemm_bf16_parity PRIVATE strata_prefill )
+ add_test(NAME gemm_bf16_parity COMMAND gemm_bf16_parity)
endif()
# native_expert_grouped's group stride and fused SwiGLU + q8_1, bitwise vs the launches before them (GPU, synthetic,
# no model; --bench adds v1/new timings of a window's 48 calls in a graph)
diff --git a/include/strata/prefill/gemm.hpp b/include/strata/prefill/gemm.hpp
index c9ddc6f4d..b2cc9933b 100644
--- a/include/strata/prefill/gemm.hpp
+++ b/include/strata/prefill/gemm.hpp
@@ -26,6 +26,7 @@ public:
std::string& err);
/// Y[T, N] (fp32, row stride ldy) = X[T, K] (bf16, row-major) . W[N, K]^T (bf16, row-major). `beta` = 1 adds.
+ /// sm_75 (no BF16 tensor cores) converts both to FP16 and runs the FP16 tensor-core GEMM (STRATA_BF16_TC).
void bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy = 0,
float beta = 0.0f);
@@ -52,6 +53,11 @@ private:
void* workspace_ = nullptr;
bool external_ = false;
void* hipblaslt_state_ = nullptr;
+ // sm_75: FP16 copies of a BF16 product's weight and activation slice (Gemm::bf16, STRATA_BF16_TC)
+ uint16_t* tc_w_ = nullptr;
+ int64_t tc_w_elems_ = 0;
+ uint16_t* tc_x_ = nullptr;
+ int64_t tc_x_elems_ = 0;
};
diff --git a/src/prefill/gemm.cu b/src/prefill/gemm.cu
index bb6ef045b..dd8c9cd7d 100644
--- a/src/prefill/gemm.cu
+++ b/src/prefill/gemm.cu
@@ -3,8 +3,11 @@
#include "strata/kernels/dequant_bf16.hpp"
#include <cublas_v2.h>
+#include <cuda_fp16.h>
#include <cuda_runtime.h>
+#include <algorithm>
+
#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)
// The HIP compatibility shim maps CUDA shuffle spellings to Strata helpers.
// hipBLASLt's public headers declare native HIP shuffle functions, so keep
@@ -298,6 +301,8 @@ Gemm::~Gemm() {
delete static_cast<HipLtState*>(hipblaslt_state_);
#endif
if (handle_) cublasDestroy((cublasHandle_t) handle_);
+ if (tc_w_) cudaFree(tc_w_);
+ if (tc_x_) cudaFree(tc_x_);
if (!external_) {
if (scratch_) cudaFree(scratch_);
if (workspace_) cudaFree(workspace_);
@@ -372,6 +377,45 @@ bool Gemm::init(void* stream, int64_t scratch_elems, std::string& err) {
return true;
}
+// ---- sm_75: BF16 GEMMs through the FP16 tensor cores ---------------------------------------------------------------
+// Turing has no BF16 tensor cores: cublasGemmEx on CUDA_R_16BF inputs falls back to a SIMT fp32 kernel
+// (magma_sgemmEx) that ran at ~13 TFLOPS, a fifth of the 4K prompt. BF16 -> FP16 is exact for every value inside
+// FP16's range (the 7-bit mantissa fits in 10 bits); weights and normalized activations sit there. With
+// STRATA_BF16_TC (default on for sm_75), the weight is converted once per call and the activations in row slices,
+// into the instance's own scratch, and the product runs as the FP16 GEMM (fp32 accumulate) on the tensor cores.
+namespace {
+__global__ void bf16_to_f16_kernel(const uint16_t* __restrict__ in, __half* __restrict__ out, int64_t n) {
+ const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
+ if (i < n) out[i] = __float2half_rn(__uint_as_float((uint32_t) in[i] << 16));
+}
+void bf16_to_f16(const uint16_t* in, uint16_t* out, int64_t n, cudaStream_t st) {
+ if (n <= 0) return;
+ bf16_to_f16_kernel<<<(unsigned) ((n + 255) / 256), 256, 0, st>>>(in, reinterpret_cast<__half*>(out), n);
+}
+int bf16_tc_mode() {
+ static int mode = [] {
+ const char* v = std::getenv("STRATA_BF16_TC");
+ if (v != nullptr && v[0] != '\0') return std::atoi(v) != 0 ? 1 : 0;
+ int dev = 0, maj = 0, min = 0;
+ cudaGetDevice(&dev);
+ cudaDeviceGetAttribute(&maj, cudaDevAttrComputeCapabilityMajor, dev);
+ cudaDeviceGetAttribute(&min, cudaDevAttrComputeCapabilityMinor, dev);
+ return (maj == 7 && min == 5) ? 1 : 0;
+ }();
+ return mode;
+}
+bool grow(uint16_t*& p, int64_t& have, int64_t want) {
+ if (have >= want) return true;
+ if (p) cudaFree(p);
+ p = nullptr;
+ have = 0;
+ if (cudaMalloc((void**) &p, (size_t) want * 2) != cudaSuccess) { cudaGetLastError(); p = nullptr; return false; }
+ have = want;
+ return true;
+}
+constexpr int64_t kXSliceElems = 16ll << 20; // 32 MiB of FP16 activations per slice
+} // namespace
+
void Gemm::bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy,
float beta) {
if (T <= 0 || N <= 0) return;
@@ -383,6 +427,20 @@ void Gemm::bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64
STRATA_ABSORB_HIPBLAS_STICKY("hipBLASLt bf16");
return;
}
+#endif
+#if !defined(__HIPCC__)
+ if (bf16_tc_mode() && N > 1) { // a single output row stays cuBLAS's GEMV, faster than the conversions
+ const int64_t x_rows = std::max<int64_t>(1, std::min<int64_t>(T, kXSliceElems / K));
+ if (grow(tc_w_, tc_w_elems_, N * K) && grow(tc_x_, tc_x_elems_, x_rows * K)) {
+ bf16_to_f16(W, tc_w_, N * K, (cudaStream_t) stream_);
+ for (int64_t t0 = 0; t0 < T; t0 += x_rows) {
+ const int64_t n = std::min<int64_t>(x_rows, T - t0);
+ bf16_to_f16(X + t0 * K, tc_x_, n * K, (cudaStream_t) stream_);
+ f16(tc_x_, tc_w_, Y + t0 * ldy, n, N, K, ldy, beta);
+ }
+ return;
+ }
+ }
#endif
// Column-major view: Y^T[N, T] = W[N, K] (stored K x N col-major, transposed) . X^T[K, T].
ck(cublasGemmEx((cublasHandle_t) handle_, CUBLAS_OP_T, CUBLAS_OP_N, (int) N, (int) T, (int) K, &alpha, W,
diff --git a/src/prefill/gemm_bf16_parity.cu b/src/prefill/gemm_bf16_parity.cu
new file mode 100644
index 000000000..89bd8a25e
--- /dev/null
+++ b/src/prefill/gemm_bf16_parity.cu
@@ -0,0 +1,153 @@
+// src/prefill/gemm_bf16_parity.cu - Gemm::bf16 against cuBLAS's own BF16 product (GPU, synthetic, no model).
+//
+// On sm_75 (no BF16 tensor cores) Gemm::bf16 converts the weight and the activations to FP16 and runs the FP16
+// tensor-core GEMM (STRATA_BF16_TC, default on there); everywhere else it is the cuBLAS BF16 call itself. This
+// checks the result against cublasGemmEx on the same BF16 inputs, within fp32-accumulation rounding, over the prompt
+// path's shapes: the hyper-connection down / up projections, the router and indexer rows, the PLE value matrix, a T
+// large enough to slice the activations, beta = 1 accumulation (the bf16x2 low parts) and an output row stride wider
+// than N. --bench adds the time of each against the cuBLAS BF16 product.
+#include "strata/prefill/gemm.hpp"
+
+#include <cublas_v2.h>
+#include <cuda_runtime.h>
+
+#include <algorithm>
+#include <chrono>
+#include <cmath>
+#include <cstdint>
+#include <cstdio>
+#include <cstring>
+#include <random>
+#include <string>
+#include <vector>
+
+namespace {
+
+uint16_t to_bf16(float f) { // round to nearest even
+ uint32_t u;
+ std::memcpy(&u, &f, 4);
+ u += 0x7fffu + ((u >> 16) & 1u);
+ return (uint16_t) (u >> 16);
+}
+
+bool ok_or(cudaError_t e, const char* what) {
+ if (e != cudaSuccess) std::printf("FAIL: %s: %s\n", what, cudaGetErrorString(e));
+ return e == cudaSuccess;
+}
+
+struct Shape {
+ int64_t T, N, K, ldy;
+ const char* what;
+};
+
+} // namespace
+
+int main(int argc, char** argv) {
+ const bool bench = argc > 1 && std::string(argv[1]) == "--bench";
+ int dev = 0, maj = 0, min = 0;
+ cudaGetDevice(&dev);
+ cudaDeviceGetAttribute(&maj, cudaDevAttrComputeCapabilityMajor, dev);
+ cudaDeviceGetAttribute(&min, cudaDevAttrComputeCapabilityMinor, dev);
+ std::printf("gemm_bf16_parity: compute capability %d.%d\n", maj, min);
+
+ cudaStream_t st = nullptr;
+ if (!ok_or(cudaStreamCreate(&st), "stream")) return 1;
+ strata::prefill::Gemm gemm;
+ std::string err;
+ if (!gemm.init(st, 0, err)) { std::printf("FAIL: %s\n", err.c_str()); return 1; }
+ cublasHandle_t h = nullptr;
+ if (cublasCreate(&h) != CUBLAS_STATUS_SUCCESS) { std::printf("FAIL: cublasCreate\n"); return 1; }
+ cublasSetStream(h, st);
+
+ const Shape shapes[] = {
+ {4096, 320, 10240, 0, "hc down (activations sliced)"},
+ {4096, 10240, 320, 0, "hc up"},
+ {777, 2560, 2560, 0, "PLE value"},
+ {512, 512, 2560, 0, "router / indexer q"},
+ {300, 4, 10240, 0, "hc inject"},
+ {2048, 1, 2560, 0, "single row"},
+ {333, 128, 2560, 136, "row stride wider than N"},
+ };
+ std::mt19937 rng(1234);
+ std::normal_distribution<float> nd(0.0f, 1.0f);
+ int failures = 0;
+ for (const Shape& s : shapes) {
+ const int64_t ldy = s.ldy > 0 ? s.ldy : s.N;
+ std::vector<uint16_t> x((size_t) (s.T * s.K)), xlo(x.size()), w((size_t) (s.N * s.K));
+ for (size_t i = 0; i < x.size(); ++i) {
+ const float v = 3.0f * nd(rng); // activations: normalized, a few units
+ x[i] = to_bf16(v);
+ xlo[i] = to_bf16(1e-3f * nd(rng)); // a bf16x2 low part
+ }
+ for (auto& v : w) v = to_bf16(0.02f * nd(rng));
+ uint16_t *dx = nullptr, *dxlo = nullptr, *dw = nullptr;
+ float *dy = nullptr, *dr = nullptr;
+ const size_t ybytes = (size_t) (s.T * ldy) * 4;
+ bool ok = ok_or(cudaMalloc((void**) &dx, x.size() * 2), "x") && ok_or(cudaMalloc((void**) &dxlo, x.size() * 2), "xlo") &&
+ ok_or(cudaMalloc((void**) &dw, w.size() * 2), "w") && ok_or(cudaMalloc((void**) &dy, ybytes), "y") &&
+ ok_or(cudaMalloc((void**) &dr, ybytes), "ref");
+ if (!ok) return 1;
+ cudaMemcpy(dx, x.data(), x.size() * 2, cudaMemcpyHostToDevice);
+ cudaMemcpy(dxlo, xlo.data(), xlo.size() * 2, cudaMemcpyHostToDevice);
+ cudaMemcpy(dw, w.data(), w.size() * 2, cudaMemcpyHostToDevice);
+ cudaMemset(dy, 0, ybytes);
+ cudaMemset(dr, 0, ybytes);
+
+ // the product under test: X . W^T, then the low part added with beta = 1
+ gemm.bf16(dx, dw, dy, s.T, s.N, s.K, ldy);
+ gemm.bf16(dxlo, dw, dy, s.T, s.N, s.K, ldy, 1.0f);
+ // the reference: cuBLAS on the BF16 inputs, the same two calls
+ const float one = 1.0f, zero = 0.0f;
+ auto ref = [&](const uint16_t* X, float beta) {
+ return cublasGemmEx(h, CUBLAS_OP_T, CUBLAS_OP_N, (int) s.N, (int) s.T, (int) s.K, &one, dw, CUDA_R_16BF,
+ (int) s.K, X, CUDA_R_16BF, (int) s.K, &beta, dr, CUDA_R_32F, (int) ldy,
+ CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT);
+ };
+ if (ref(dx, zero) != CUBLAS_STATUS_SUCCESS || ref(dxlo, one) != CUBLAS_STATUS_SUCCESS) {
+ std::printf("FAIL: reference cublasGemmEx\n");
+ return 1;
+ }
+ if (!ok_or(cudaStreamSynchronize(st), "sync")) return 1;
+ std::vector<float> y((size_t) (s.T * ldy)), r(y.size());
+ cudaMemcpy(y.data(), dy, ybytes, cudaMemcpyDeviceToHost);
+ cudaMemcpy(r.data(), dr, ybytes, cudaMemcpyDeviceToHost);
+ double worst = 0.0, mag = 1e-30;
+ int bad = 0;
+ for (int64_t t = 0; t < s.T; ++t)
+ for (int64_t c = 0; c < s.N; ++c) {
+ const float a = y[(size_t) (t * ldy + c)], b = r[(size_t) (t * ldy + c)];
+ if (!std::isfinite(a)) ++bad;
+ worst = std::max(worst, (double) std::fabs(a - b));
+ mag = std::max(mag, (double) std::fabs(b));
+ }
+ // the untouched columns of a wider row stride stay as they were
+ for (int64_t t = 0; t < s.T && ldy > s.N; ++t)
+ for (int64_t c = s.N; c < ldy; ++c)
+ if (y[(size_t) (t * ldy + c)] != 0.0f) ++bad;
+ const bool pass = bad == 0 && worst <= 1e-4 * mag;
+ if (!pass) ++failures;
+ std::printf(" %-32s T %5lld N %5lld K %5lld ldy %5lld: worst |diff| %.3e of max |ref| %.3e (rel %.2e) %s\n",
+ s.what, (long long) s.T, (long long) s.N, (long long) s.K, (long long) ldy, worst, mag, worst / mag,
+ pass ? "pass" : "FAIL");
+
+ if (bench) {
+ auto time = [&](auto&& f) {
+ for (int i = 0; i < 3; ++i) f();
+ cudaStreamSynchronize(st);
+ const auto t0 = std::chrono::steady_clock::now();
+ for (int i = 0; i < 20; ++i) f();
+ cudaStreamSynchronize(st);
+ return std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count() / 20;
+ };
+ const double us_gemm = time([&] { gemm.bf16(dx, dw, dy, s.T, s.N, s.K, ldy); });
+ const double us_ref = time([&] { ref(dx, zero); });
+ std::printf(" bench: Gemm::bf16 %9.1f us cuBLAS BF16 %9.1f us (%.2fx)\n", us_gemm, us_ref,
+ us_ref / us_gemm);
+ }
+ cudaFree(dx); cudaFree(dxlo); cudaFree(dw); cudaFree(dy); cudaFree(dr);
+ }
+ cublasDestroy(h);
+ cudaStreamDestroy(st);
+ std::printf("gemm_bf16_parity: %d failures\n", failures);
+ return failures == 0 ? 0 : 1;
+}