diff --git a/CMakeLists.txt b/CMakeLists.txt index f55befec..49a45ee1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -831,6 +831,11 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) 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) + # Pascal, opt-in STRATA_DENSE_F32=1: the dense projections' FP16 GEMMs as cublasSgemm on FP32 copies, bitwise vs + # the cuBLAS FP16 call over a sweep of chunk sizes (GPU, synthetic, no model; --full sweeps every size, --bench + # adds timings). Not a ctest: whether the two agree is a property of the cuBLAS build, which this checks. + add_executable(gemm_f32_parity src/prefill/gemm_f32_parity.cu) + target_link_libraries(gemm_f32_parity PRIVATE strata_prefill ) 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 935f1a9a..0740fd0d 100644 --- a/include/strata/prefill/gemm.hpp +++ b/include/strata/prefill/gemm.hpp @@ -89,6 +89,12 @@ private: void f16_inplace(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy); }; +/// Pascal, opt-in: Gemm::f16's large dense shapes as cublasSgemm on FP32 copies (gemm.cu; bitwise the FP16 call's +/// result at the sizes it takes with the cuBLAS it was measured on). 0 off, 1 on (any card), -1 the default +/// (STRATA_DENSE_F32=1 on compute capability 6.x, else off). For gemm_f32_parity; a no-op outside the experimental +/// CUDA 12 build. +void gemm_set_dense_f32(int mode); + /// HIP on gfx103x (RDNA2), for the current device: rocBLAS's tuned GEMMs there are FP16 in -> FP16 out only (FP16 or /// BF16 in -> FP32 out runs ~6x slower), so the prompt path's 16-bit GEMMs run in FP16 (Gemm::set_f16_io, /// set_act_f16). Cached per device (a layer split can mix cards). STRATA_HIP_PROMPT_F16=0/1 overrides. diff --git a/src/prefill/gemm.cu b/src/prefill/gemm.cu index 88ecb793..300da53b 100644 --- a/src/prefill/gemm.cu +++ b/src/prefill/gemm.cu @@ -539,8 +539,61 @@ bool grow(uint16_t*& p, int64_t& have, int64_t want) { // `have`, `want`: 2-by return true; } constexpr int64_t kXSliceElems = 16ll << 20; // 32 MiB of FP16 activations per slice (64 MiB as fp32) + +#if defined(STRATA_EXPERIMENTAL_SM60) +// ---- Pascal, opt-in (STRATA_DENSE_F32=1): the dense projections' FP16-operand GEMMs as cublasSgemm ---------------- +// Measured on a Tesla P40 (sm_61) with cuBLAS 12.4.5.8 (bench/results/2026-10-12-p40-sm61-kernels). For FP16 +// operands with FP32 sums cuBLAS has two Maxwell kernels there, maxwell_sgemm_fp16_64x64 and _32x128, and picks the +// slow one for most chunk sizes: the 10240 x 2560 qkv projection runs at 7.6 TFLOPS for T 7030-7040 and at 4.3 from +// T 7041 (49 -> 85 ms), and at 4.3-4.6 for two thirds of the T between 256 and 8192; the 12288-row query projection +// likewise. A 7K-token prompt reads in 16.3 or 19.5 s by its token count. cublasSgemm on FP32 copies +// (maxwell_sgemm_128x64) runs at 8.4-9.8 TFLOPS for every T from 512 (6.7+ from 256). The copies are exact +// (FP16 -> FP32), and for the shapes and sizes taken here the two kernels add every output's products in the same +// order: the result is bitwise the cuBLAS FP16 call's (gemm_f32_parity: 5,201 chunk sizes on a P40 with cuBLAS 12.4, a +// measurement of this library, not a guarantee of cuBLAS's; below the sizes taken here - T under +// ~144 at 6144+ rows, under ~408 at 2560 rows - cuBLAS switches one of them to another kernel family and the bits +// differ, so those keep the FP16 call). The weight goes through the BF16 path's conversion buffer (126 MiB for the +// largest, 21 MiB more than that path's own), the activations through its slices. +// Opt-in, and on Pascal (compute capability 6.x) only: the equality belongs to the cuBLAS build, so run +// gemm_f32_parity with yours before turning it on; newer cards have tensor cores for the FP16 call. +__global__ void f16_to_f32_kernel(const uint16_t* __restrict__ in, float* __restrict__ out, int64_t n) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) out[i] = __half2float(__ushort_as_half(in[i])); +} +void f16_to_f32(const uint16_t* in, float* out, int64_t n, cudaStream_t st) { + if (n <= 0) return; + f16_to_f32_kernel<<<(unsigned) ((n + 255) / 256), 256, 0, st>>>(in, out, n); +} +int g_dense_f32 = -1; // gemm_set_dense_f32 (the parity test: 0 / 1 on any card); -1 = STRATA_DENSE_F32 +bool dense_f32_on() { + static const bool env = [] { + const char* v = std::getenv("STRATA_DENSE_F32"); + return v != nullptr && std::atoi(v) != 0; + }(); + if (g_dense_f32 >= 0) return g_dense_f32 != 0; + if (!env) return false; + const int cc = current_cc(); + return cc >= 60 && cc < 70; +} +// The smallest T taken for a weight of N rows and K columns (0: never): the measured shapes only - the 2560-column +// qkv (10240 rows), query (12288) and gate (6144) projections and the 2560-row output projections (6144 and 4096 +// columns), each from a T where the FP32 route (its conversions included) is the faster one or within ~7% of the FP16 +// call (the gate projection below ~1300 tokens, the 4096-column output projection near 4096) and well above the T +// where the two stop agreeing bitwise. Every other shape (a row slice of a weight too) keeps the FP16 call. +int64_t dense_f32_min_t(int64_t N, int64_t K) { + if (K == 2560 && (N == 10240 || N == 12288)) return 256; + if (K == 2560 && N == 6144) return 512; + if (N == 2560 && (K == 6144 || K == 4096)) return 4096; + return 0; +} +#endif } // namespace #endif +#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60) +void gemm_set_dense_f32(int mode) { g_dense_f32 = mode; } +#else +void gemm_set_dense_f32(int) {} +#endif bool Gemm::bf16_hcd_exact(const uint16_t* X, int64_t ldx, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K) { #if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE) static std::atomic told{false}; @@ -698,6 +751,35 @@ void Gemm::f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_ return; } #endif +#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60) + // Pascal, STRATA_DENSE_F32=1: cublasSgemm on FP32 copies (dense_f32_on above: where it is bitwise the FP16 call) + if (const int64_t min_t = beta == 0.0f ? dense_f32_min_t(N, K) : 0; min_t > 0 && T >= min_t && dense_f32_on()) { + const int64_t n_sl = (T * K + kXSliceElems - 1) / kXSliceElems; // even slices of at most 64 MiB as fp32 + const int64_t x_rows = (T + n_sl - 1) / n_sl; + // grow() frees a buffer an earlier GEMM on this stream may still read + if (tc_w_elems_ < 2 * N * K || tc_x_elems_ < 2 * x_rows * K) cudaStreamSynchronize((cudaStream_t) stream_); + if (grow(tc_w_, tc_w_elems_, 2 * N * K) && grow(tc_x_, tc_x_elems_, 2 * x_rows * K)) { + static bool said = false; + if (!said) { + said = true; + std::fprintf(stderr, "prefill gemm: the dense projections' FP16 GEMMs run as cublasSgemm on FP32 copies " + "(STRATA_DENSE_F32=1; gemm_f32_parity checks the bits against this cuBLAS)\n"); + } + float* const wf = reinterpret_cast(tc_w_); + float* const xf = reinterpret_cast(tc_x_); + f16_to_f32(W, wf, N * K, (cudaStream_t) stream_); + for (int64_t t0 = 0; t0 < T; t0 += x_rows) { + const int64_t n = std::min(x_rows, T - t0); + f16_to_f32(X + t0 * K, xf, n * K, (cudaStream_t) stream_); + ck(cublasSgemm((cublasHandle_t) handle_, CUBLAS_OP_T, CUBLAS_OP_N, (int) N, (int) n, (int) K, &alpha, wf, (int) K, + xf, (int) K, &beta, Y + t0 * ldy, (int) ldy), + "cublasSgemm (FP16 operands, STRATA_DENSE_F32)"); + } + return; + } + cudaGetLastError(); // no room for the copies: the FP16 call below + } +#endif #if !defined(__HIPCC__) const auto f16_gemm = [&](cublasGemmAlgo_t algo) { return cublasGemmEx((cublasHandle_t) handle_, CUBLAS_OP_T, CUBLAS_OP_N, (int) N, (int) T, (int) K, &alpha, diff --git a/src/prefill/gemm_f32_parity.cu b/src/prefill/gemm_f32_parity.cu new file mode 100644 index 00000000..ee4eb87d --- /dev/null +++ b/src/prefill/gemm_f32_parity.cu @@ -0,0 +1,129 @@ +// src/prefill/gemm_f32_parity.cu - Pascal: Gemm::f16's opt-in FP32 route (cublasSgemm on FP32 copies of the FP16 +// operands, STRATA_DENSE_F32=1) against the cuBLAS FP16-operand call it replaces, bitwise, over the dense projections' +// shapes and a sweep of chunk sizes T (GPU, synthetic, no model). Whether the two agree is a property of the cuBLAS +// build (measured: 12.4.5.8 on a Tesla P40, 5,201 sizes): run this before setting STRATA_DENSE_F32=1. +// +// build/gemm_f32_parity [--quick | --full] [--bench] +// default: every 7th T from the route's first to 8192, every T of 7000-7100 and around the powers of two, 8192; +// --quick: every 251st T; --full: every T. --bench prints both times for a few T. Exit 0: every output bitwise +// equal (or the route is not built here: not the experimental CUDA 12 engine). +#include "strata/prefill/gemm.hpp" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { +__global__ void fill_f16(__half* p, int64_t n, unsigned seed, float scale) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; + unsigned x = (unsigned) i * 2654435761u + seed; + x ^= x >> 16; x *= 2246822519u; x ^= x >> 13; x *= 3266489917u; x ^= x >> 16; + p[i] = __float2half(((float) (x & 0xffff) / 32768.0f - 1.0f) * scale); +} +__global__ void count_diff(const unsigned* a, const unsigned* b, int64_t n, unsigned* out) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i < n && a[i] != b[i]) atomicAdd(out, 1u); +} +bool ok(cudaError_t e, const char* what) { + if (e != cudaSuccess) std::printf("FAIL: %s: %s\n", what, cudaGetErrorString(e)); + return e == cudaSuccess; +} +struct Shape { const char* what; int64_t N, K, t_min; }; +} // namespace + +int main(int argc, char** argv) { + setvbuf(stdout, nullptr, _IONBF, 0); + bool quick = false, full = false, bench = false; + for (int i = 1; i < argc; ++i) { + const std::string a = argv[i]; + quick |= a == "--quick"; full |= a == "--full"; bench |= a == "--bench"; + } + int dev = 0, maj = 0, min = 0; + cudaGetDevice(&dev); + cudaDeviceGetAttribute(&maj, cudaDevAttrComputeCapabilityMajor, dev); + cudaDeviceGetAttribute(&min, cudaDevAttrComputeCapabilityMinor, dev); + std::printf("gemm_f32_parity: compute capability %d.%d\n", maj, min); + cudaStream_t st = nullptr; + if (!ok(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; } + // the shapes the route takes and its first T for each (gemm.cu, dense_f32_min_t) + const Shape shapes[] = {{"gdn qkv", 10240, 2560, 256}, {"qsa query", 12288, 2560, 256}, {"gdn gate", 6144, 2560, 512}, + {"gdn out", 2560, 6144, 4096}, {"qsa out", 2560, 4096, 4096}}; + const int64_t TMAX = 8192; + unsigned* cnt = nullptr; + if (!ok(cudaMalloc((void**) &cnt, 4), "counter")) return 1; + cudaEvent_t e0, e1; + cudaEventCreate(&e0); + cudaEventCreate(&e1); + long long cases = 0, bad_cases = 0; + for (const Shape& s : shapes) { + const int64_t N = s.N, K = s.K; + uint16_t *W = nullptr, *X = nullptr; + float *Ya = nullptr, *Yb = nullptr; + if (!ok(cudaMalloc((void**) &W, (size_t) N * K * 2), "W") || !ok(cudaMalloc((void**) &X, (size_t) TMAX * K * 2), "X") || + !ok(cudaMalloc((void**) &Ya, (size_t) TMAX * N * 4), "Ya") || !ok(cudaMalloc((void**) &Yb, (size_t) TMAX * N * 4), "Yb")) return 1; + fill_f16<<<(unsigned) ((N * K + 255) / 256), 256, 0, st>>>((__half*) W, N * K, 1u + (unsigned) N, 0.05f); + fill_f16<<<(unsigned) ((TMAX * K + 255) / 256), 256, 0, st>>>((__half*) X, TMAX * K, 7u + (unsigned) K, 2.0f); + std::set ts; + const int64_t step = full ? 1 : quick ? 251 : 7; + for (int64_t t = s.t_min; t <= TMAX; t += step) ts.insert(t); + ts.insert(s.t_min); ts.insert(TMAX); + if (!quick) { + for (int64_t t = 7000; t <= 7100; ++t) if (t >= s.t_min) ts.insert(t); + for (int64_t p = 256; p <= TMAX; p *= 2) for (int64_t d = -3; d <= 3; ++d) if (p + d >= s.t_min && p + d <= TMAX) ts.insert(p + d); + for (int64_t t = 6540; t <= 6570; ++t) if (t >= s.t_min) ts.insert(t); // around the activation slices' first split (K 2560) + } + long long bad = 0, bad_outputs = 0; + int64_t first_bad = 0; + for (int64_t T : ts) { + strata::prefill::gemm_set_dense_f32(0); + gemm.f16(X, W, Ya, T, N, K); + strata::prefill::gemm_set_dense_f32(1); + gemm.f16(X, W, Yb, T, N, K); + cudaMemsetAsync(cnt, 0, 4, st); + count_diff<<<(unsigned) ((T * N + 255) / 256), 256, 0, st>>>((const unsigned*) Ya, (const unsigned*) Yb, T * N, cnt); + unsigned nd = 0; + cudaMemcpyAsync(&nd, cnt, 4, cudaMemcpyDeviceToHost, st); + if (!ok(cudaStreamSynchronize(st), "sync")) return 1; + ++cases; + if (nd) { if (!bad) first_bad = T; ++bad; bad_outputs += nd; } + } + std::printf("%-10s %5lld x %-5lld: %zu sizes from T %lld to %lld, %lld with different bits%s\n", s.what, (long long) N, (long long) K, ts.size(), + (long long) *ts.begin(), (long long) *ts.rbegin(), bad, bad ? "" : " (bitwise equal)"); + if (bad) std::printf("FAIL %s: first at T %lld, %lld outputs in all\n", s.what, (long long) first_bad, bad_outputs); + bad_cases += bad; + if (bench) { + for (int64_t T : {(int64_t) 560, (int64_t) 2048, (int64_t) 4096, (int64_t) 7040, (int64_t) 7041}) { + if (T < s.t_min) continue; + double ms[2] = {0, 0}; + for (int on = 0; on < 2; ++on) { + strata::prefill::gemm_set_dense_f32(on); + gemm.f16(X, W, Ya, T, N, K); + cudaEventRecord(e0, st); + for (int i = 0; i < 3; ++i) gemm.f16(X, W, Ya, T, N, K); + cudaEventRecord(e1, st); + cudaEventSynchronize(e1); + float t = 0; + cudaEventElapsedTime(&t, e0, e1); + ms[on] = t / 3; + } + std::printf("BENCH %-10s T %5lld | cuBLAS FP16 %7.2f ms | FP32 copies %7.2f ms (the conversions included) | %.2fx\n", s.what, (long long) T, ms[0], + ms[1], ms[0] / ms[1]); + } + } + cudaFree(W); cudaFree(X); cudaFree(Ya); cudaFree(Yb); + } + strata::prefill::gemm_set_dense_f32(-1); + std::printf("gemm_f32_parity: %lld sizes, %s\n", cases, bad_cases ? "FAILED" : "OK (bitwise)"); + return bad_cases ? 1 : 0; +}