diff --git a/CMakeLists.txt b/CMakeLists.txt index 692484a807..f0d54bfb13 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -471,6 +471,7 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) src/kernels/cuda/elementwise.cu src/kernels/cuda/bf16_gemv.cu src/kernels/cuda/native_mmvq.cu + src/kernels/cuda/dense_tc.cu src/kernels/cuda/native_bf16.cu src/kernels/cuda/native_gr_norm.cu src/kernels/cuda/native_moe.cu @@ -1218,6 +1219,12 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_include_directories(mmvq_il_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(mmvq_il_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME mmvq_il_parity COMMAND mmvq_il_parity) + # BW-DENSE P2.1: the sm_120 INT8 tensor-core projections against a scalar reference of their arithmetic contract (skips on + # other cards); --bench times them against the path the engine takes today + add_executable(dense_tc_parity src/kernels/dense_tc_parity.cpp) + target_include_directories(dense_tc_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(dense_tc_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME dense_tc_parity COMMAND dense_tc_parity) # sm_89's opt-in tables (#3453, STRATA_MMVQ_IL_89=1): the table check only (no case matches MMVQ_IL_ONLY) add_test(NAME mmvq_il_parity_89table COMMAND mmvq_il_parity) set_tests_properties(mmvq_il_parity_89table PROPERTIES ENVIRONMENT "STRATA_MMVQ_IL_89=1;MMVQ_IL_ONLY=no-such-case") diff --git a/include/strata/kernels/dense_tc.hpp b/include/strata/kernels/dense_tc.hpp new file mode 100644 index 0000000000..b89fe84ae7 --- /dev/null +++ b/include/strata/kernels/dense_tc.hpp @@ -0,0 +1,56 @@ +#pragma once + +// Dense short-window INT8 tensor-core projections (BW-DENSE, P2.1). A separate translation unit +// (src/kernels/cuda/dense_tc.cu), CUDA sm_120 only; every other build and every ineligible call keeps native_mmvq / +// native_mmvq_il. All pointers are device pointers. +// +// Inputs are the plain q8_1 blocks native_quantize_q8_1 writes (36 bytes per 32 values, column j at +// x + j * n_in / 32 blocks) and the unmodified GGUF weight blocks, so no extra copy of either is made. +// Output column j is y + j * n_out (native_mmvq's layout). +// +// Arithmetic contract (docs: phaseA-tests/blackwell/decisions/E03.md): the integer dot products of each +// (row, 16- or 32-value sub-block, column) are exact int32 (mma.sync s8 x s8 -> s32); the scale products and the +// float accumulation have a fixed order that depends on the row, the block and (n_in, n_out) only, never on the +// column count, so a column's result does not depend on how many columns share the call. That order is not +// native_mmvq's (it multiplies and rounds per 4-value dp4a group), so the output is NOT bitwise native_mmvq's: this +// is a rounding-changing path, off unless dense_tc_enable(true) / STRATA_DENSE_TC=1. +#include + +namespace strata::kernels { + +// 0 = eligible. Otherwise a stable reason, checked before graph capture; the caller then keeps its existing path. +enum DenseTcStatus { + kDenseTcOk = 0, + kDenseTcOff = 1, // switch off (default) + kDenseTcArch = 2, // not an sm_120 card / build without sm_120 code + kDenseTcType = 3, // weight type without a tensor-core kernel + kDenseTcCols = 4, // ncols outside 1..8 + kDenseTcShape = 5, // n_in not a multiple of 256, n_out < 1, or an activation tile that does not fit + kDenseTcAlign = 6, // a pointer is not 4-byte aligned (weights: 2-byte aligned blocks are fine) + kDenseTcSmem = 7, // the card refuses the shared memory the tile needs + kDenseTcBuild = 8, // not built (HIP / SYCL / CPU / no sm_120 code) +}; +const char* dense_tc_reason(int status) noexcept; + +// Process switch. Default: STRATA_DENSE_TC (unset or 0 = off). +void dense_tc_enable(int on); // 1 on, 0 off, -1 back to the environment +bool dense_tc_enabled(); + +// Eligibility of one projection (no launch, no allocation). `weights`, `x_q8_1` and `y` may be null to skip the +// pointer checks (a plan made before the buffers exist). +int dense_tc_check(int ggml_type, int n_in, int n_out, int ncols, const void* weights, const void* x_q8_1, + const void* y) noexcept; + +// Launches the kernel on `stream` when dense_tc_check says kDenseTcOk and returns true; returns false (nothing +// launched) otherwise, and the caller calls native_mmvq / native_mmvq_il. +bool dense_tc(int ggml_type, const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, + void* stream); + +// Tests and benchmarks. +void dense_tc_tile(int row_tiles, int k_split); // 0, 0: the shape table (default) +int dense_tc_split_for(int ggml_type, int n_in, int n_out); // the k_split a launch of this shape uses (the rounding order's part) +int dense_tc_variant(int v); // -1 read, else set the kernel variant (experiments) +// Registers/spills/shared memory of the kernels in this build (cudaFuncGetAttributes), one line per instance, to stdout. +void dense_tc_print_resources(); + +} // namespace strata::kernels diff --git a/src/kernels/cuda/dense_tc.cu b/src/kernels/cuda/dense_tc.cu new file mode 100644 index 0000000000..af69eeaf5b --- /dev/null +++ b/src/kernels/cuda/dense_tc.cu @@ -0,0 +1,358 @@ +// src/kernels/cuda/dense_tc.cu - dense short-window INT8 tensor-core projections (BW-DENSE P2.1; sm_120 only). +// +// y[col][row] = sum over the row's blocks of a Q6_K (more formats follow) weight row times a q8_1 activation column, +// for 1..8 columns, as mma.sync.m16n8k16 s8 x s8 -> s32: one weight sub-block (16 values sharing one int8 scale) of +// 16 rows against 8 activation columns per instruction. The weights are decoded straight from the GGUF blocks into +// the instruction's A fragments; the activation columns are staged once per thread block in padded shared memory and +// read as the B fragments. +// +// Arithmetic (the contract in dense_tc.hpp): per (row, column), block b, activation block ab = 8b + a (a = 0..7): +// S = sc[2a] * D(2a) + sc[2a+1] * D(2a+1) D(.) the exact int32 sub-block dots, S exact in int32 +// inner = fma(d8[col][ab], float(S), inner) a ascending, inner starts at 0 for every block +// acc = fma(d_row[b], inner, acc) the blocks a warp owns, ascending +// and the k_split warps of a row tile are summed in warp order ((p0 + p1) + p2) + ... . Nothing in it depends on the +// column count. The weight values are the file's: (ql | qh << 4) - 32 exactly as dequantize_row_q6_K. +// +// Written from the mechanism only (m16n8k16 INT8 MMA fed by decoded quant blocks, q8_1 inputs, FP32 scaled +// accumulation); it shares no code with another engine. +#include "strata/kernels/dense_tc.hpp" + +#if !defined(__HIPCC__) + +#include "strata/kernels/native_mmvq.hpp" + +#include +#include + +#include +#include +#include +#include +#include + +namespace strata::kernels { +namespace { + +constexpr int kQ6Bytes = 210; +constexpr int kMaxCols = 8; +// Gate for the tensor-core body: the instruction and the tile live on sm_80+; the kernel is only ever launched on a +// 12.0 card, so older code objects in a multi-arch fat binary get an empty body (never launched). +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 1200 +#define STRATA_DTC_BODY 1 +#endif + +__device__ __forceinline__ int ldg_u16(const void* p) { + unsigned v; + asm volatile("ld.global.nc.u16 %0, [%1];" : "=r"(v) : "l"(p)); + return int(v); +} +// a 32-bit little-endian load from a 2-byte aligned address (Q6_K blocks are 210 bytes) +__device__ __forceinline__ int ldg_b2(const uint8_t* p) { return ldg_u16(p) | (ldg_u16(p + 2) << 16); } +__device__ __forceinline__ int ldg_s8(const void* p) { + int v; + asm volatile("ld.global.nc.s8 %0, [%1];" : "=r"(v) : "l"(p)); + return v; +} +// (x - 32) per byte for bytes of x in [0, 63]: x + 0x60 never carries out of its byte (0x60..0x9f), the xor undoes the 0x80 +__device__ __forceinline__ int sub32_bytes(int x) { return (x + 0x60606060) ^ 0x80808080; } + +__device__ __forceinline__ void mma_k16(int (&c)[4], int a0, int a1, int b0) { + asm volatile("mma.sync.aligned.m16n8k16.row.col.s32.s8.s8.s32 {%0,%1,%2,%3}, {%4,%5}, {%6}, {%7,%8,%9,%10};" + : "=r"(c[0]), "=r"(c[1]), "=r"(c[2]), "=r"(c[3]) + : "r"(a0), "r"(a1), "r"(b0), "r"(0), "r"(0), "r"(0), "r"(0)); +} + +struct Smem { // dynamic shared memory: the activation tile, then (reused after the last MMA) the k_split partials + static __host__ __device__ int pitch(int n_in) { return n_in + 16; } // bytes a column; +16 spreads the 8 columns over the banks + static __host__ __device__ size_t q_bytes(int n_in) { return size_t(kMaxCols) * size_t(pitch(n_in)); } + static __host__ __device__ size_t d_bytes(int n_in) { return size_t(n_in / 32) * kMaxCols * 4; } + static __host__ __device__ size_t total(int n_in, int rt, int ks) { + const size_t act = q_bytes(n_in) + d_bytes(n_in); + const size_t red = size_t(rt) * ks * 16 * 8 * 4; + return act > red ? act : red; + } +}; + +// RT row tiles (16 rows each) x KS k-split warps per thread block. Grid: ceil(ceil(n_out / 16) / RT). +template +__global__ void __launch_bounds__(32 * RT * KS) dense_tc_q6k_kernel(const uint8_t* __restrict__ w, const uint8_t* __restrict__ xq, + float* __restrict__ y, int n_in, int n_out, int T) { +#if defined(STRATA_DTC_BODY) + extern __shared__ __align__(16) uint8_t smem[]; + const int tid = int(threadIdx.x); + const int nb = n_in / 256, nab = n_in / 32; + const int pitch = Smem::pitch(n_in); + uint8_t* sq = smem; + float* sd = reinterpret_cast(smem + Smem::q_bytes(n_in)); // [ab][8] + // stage the activation columns: the int8 codes (4-byte aligned in the 36-byte blocks), and each block's d + { + const int per_col = n_in / 4; + for (int i = tid; i < T * per_col; i += 32 * RT * KS) { + const int col = i / per_col, k4 = i - col * per_col; + const int ab = k4 >> 3, p = k4 & 7; + const int v = *reinterpret_cast(xq + (size_t(col) * nab + ab) * 36 + 4 + 4 * p); + *reinterpret_cast(sq + size_t(col) * pitch + 4 * k4) = v; + } + for (int i = tid; i < nab * kMaxCols; i += 32 * RT * KS) { + const int ab = i >> 3, col = i & 7; + sd[i] = col < T ? __half2float(*reinterpret_cast(xq + (size_t(col) * nab + ab) * 36)) : 0.0f; + } + } + __syncthreads(); + + const int lane = tid & 31, warp = tid >> 5; + const int g = lane >> 2, t = lane & 3; + const int rt = warp / KS, ks = warp - rt * KS; + const int row_base = (int(blockIdx.x) * RT + rt) * 16; + const int r0 = min(row_base + g, n_out - 1), r1 = min(row_base + g + 8, n_out - 1); + const uint8_t* w0 = w + size_t(r0) * nb * kQ6Bytes; + const uint8_t* w1 = w + size_t(r1) * nb * kQ6Bytes; + const int gcol = g < T ? g : 0; // columns >= T: any valid column (their outputs are not stored) + const uint8_t* bq = sq + size_t(gcol) * pitch + 4 * t; + float acc[4] = {0.f, 0.f, 0.f, 0.f}; // (row g, cols 2t, 2t+1), (row g + 8, cols 2t, 2t+1) + + for (int b = ks; b < nb; b += KS) { + const uint8_t* p0 = w0 + size_t(b) * kQ6Bytes; + const uint8_t* p1 = w1 + size_t(b) * kQ6Bytes; + // the 16 int8 scales of both rows: sc?[sj] + int sc0[16], sc1[16]; +#pragma unroll + for (int j = 0; j < 16; ++j) { + sc0[j] = ldg_s8(p0 + 192 + j); + sc1[j] = ldg_s8(p1 + 192 + j); + } + const float dw0 = __half2float(__ushort_as_half((unsigned short) ldg_u16(p0 + 208))); + const float dw1 = __half2float(__ushort_as_half((unsigned short) ldg_u16(p1 + 208))); + float inner[4] = {0.f, 0.f, 0.f, 0.f}; +#pragma unroll + for (int h = 0; h < 2; ++h) { + // lh = 0/1: the 16-value half of the 32 a quadrant covers; this lane's 4 values are 4t..4t+3 of it + int qlA[2][2], qlB[2][2], qh[2][2]; // [row][lh] +#pragma unroll + for (int lh = 0; lh < 2; ++lh) { + const int off = 64 * h + 16 * lh + 4 * t; + qlA[0][lh] = ldg_b2(p0 + off); + qlB[0][lh] = ldg_b2(p0 + off + 32); + qh[0][lh] = ldg_b2(p0 + 128 + 32 * h + 16 * lh + 4 * t); + qlA[1][lh] = ldg_b2(p1 + off); + qlB[1][lh] = ldg_b2(p1 + off + 32); + qh[1][lh] = ldg_b2(p1 + 128 + 32 * h + 16 * lh + 4 * t); + } +#pragma unroll + for (int qd = 0; qd < 4; ++qd) { // quadrant: value offset 32 * qd inside the half + const int ab_l = 4 * h + qd; // activation block inside the weight block + int c[2][4]; +#pragma unroll + for (int lh = 0; lh < 2; ++lh) { + const int sj = 8 * h + 2 * qd + lh; + int a[2]; +#pragma unroll + for (int r = 0; r < 2; ++r) { + const int ql = (qd & 1) ? qlB[r][lh] : qlA[r][lh]; + const int lo = (qd >> 1) ? ((ql >> 4) & 0x0f0f0f0f) : (ql & 0x0f0f0f0f); + const int hi = ((qh[r][lh] >> (2 * qd)) & 0x03030303) << 4; + a[r] = sub32_bytes(lo | hi); + } + const int bv = *reinterpret_cast(bq + 32 * (8 * b + ab_l) + 16 * lh); + mma_k16(c[lh], a[0], a[1], bv); + } + const float2 d8 = *reinterpret_cast(sd + (8 * b + ab_l) * kMaxCols + 2 * t); + const int s2 = 8 * h + 2 * qd; + // S for (row g | row g + 8) x (col 2t | 2t + 1) + const int S0 = sc0[s2] * c[0][0] + sc0[s2 + 1] * c[1][0]; + const int S1 = sc0[s2] * c[0][1] + sc0[s2 + 1] * c[1][1]; + const int S2 = sc1[s2] * c[0][2] + sc1[s2 + 1] * c[1][2]; + const int S3 = sc1[s2] * c[0][3] + sc1[s2 + 1] * c[1][3]; + inner[0] = fmaf(d8.x, float(S0), inner[0]); + inner[1] = fmaf(d8.y, float(S1), inner[1]); + inner[2] = fmaf(d8.x, float(S2), inner[2]); + inner[3] = fmaf(d8.y, float(S3), inner[3]); + } + } + acc[0] = fmaf(dw0, inner[0], acc[0]); + acc[1] = fmaf(dw0, inner[1], acc[1]); + acc[2] = fmaf(dw1, inner[2], acc[2]); + acc[3] = fmaf(dw1, inner[3], acc[3]); + } + + // sum the k_split partials of each row tile in warp order, then store + __syncthreads(); // every warp is done with the activation tile + float* red = reinterpret_cast(smem); // [rt][ks][4][32] + if (KS > 1) { +#pragma unroll + for (int e = 0; e < 4; ++e) red[((rt * KS + ks) * 4 + e) * 32 + lane] = acc[e]; + __syncthreads(); + } + if (ks == 0) { + float v[4]; +#pragma unroll + for (int e = 0; e < 4; ++e) { + v[e] = acc[e]; + for (int k = 1; k < KS; ++k) v[e] += red[((rt * KS + k) * 4 + e) * 32 + lane]; + } + const int col0 = 2 * t; +#pragma unroll + for (int e = 0; e < 4; ++e) { + const int row = row_base + g + (e >> 1) * 8, col = col0 + (e & 1); + if (row < n_out && col < T) y[size_t(col) * n_out + row] = v[e]; + } + } +#endif +} + +// ---- host side ------------------------------------------------------------------------------------------------ +int g_enable = -1; // dense_tc_enable +int g_tile_rt = 0, g_tile_ks = 0; +int g_variant = 0; + +bool env_on() { + static const bool on = [] { const char* v = std::getenv("STRATA_DENSE_TC"); return v != nullptr && std::atoi(v) != 0; }(); + return on; +} + +int device_cc() { // 120 for a 12.0 card (emulation honoured), else 0 + static int cc[16] = {}; + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 16) return 0; + if (cc[dev] == 0) { + int ma = 0, mi = 0; + if (cudaDeviceGetAttribute(&ma, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess || + cudaDeviceGetAttribute(&mi, cudaDevAttrComputeCapabilityMinor, dev) != cudaSuccess) { + cudaGetLastError(); + return 0; + } + cc[dev] = (ma == 12 && mi == 0) ? 120 : -1; + } + return cc[dev] > 0 ? cc[dev] : 0; +} + +struct Pick { int rt, ks; }; +// The (row tiles, k_split) of a shape. The k_split decides the float summation order, so it is a function of the +// shape alone: never of the column count. +Pick pick(int type, int n_in, int n_out) { + (void) type; + if (g_tile_rt > 0 && g_tile_ks > 0) return {g_tile_rt, g_tile_ks}; + const int nb = n_in / 256; + const int tiles = (n_out + 15) / 16; + int ks = nb % 5 == 0 ? 5 : nb % 4 == 0 ? 4 : nb % 2 == 0 ? 2 : 1; + if (ks == 5 && tiles >= 640) ks = nb % 2 == 0 && nb >= 20 ? 2 : 1; + if (tiles >= 1024) ks = nb % 2 == 0 ? 2 : 1; + int rt = tiles >= 256 ? 2 : 1; + if (ks == 5 && rt > 2) rt = 2; + return {rt, ks}; +} + +template +bool launch_q6k(const uint8_t* w, const uint8_t* xq, float* y, int n_in, int n_out, int T, cudaStream_t s) { + const size_t smem = Smem::total(n_in, RT, KS); + static std::once_flag once; + static bool ok = true; + std::call_once(once, [&] { + ok = cudaFuncSetAttribute(dense_tc_q6k_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, int(99 * 1024)) == cudaSuccess; + if (!ok) cudaGetLastError(); + }); + if (!ok) return false; + const unsigned tiles = unsigned((n_out + 15) / 16); + const unsigned blocks = (tiles + RT - 1) / RT; + dense_tc_q6k_kernel<<>>(w, xq, y, n_in, n_out, T); + return true; +} + +bool dispatch_q6k(const uint8_t* w, const uint8_t* xq, float* y, int n_in, int n_out, int T, cudaStream_t s, Pick p) { +#define DTC_CASE(R, K) if (p.rt == R && p.ks == K) return launch_q6k(w, xq, y, n_in, n_out, T, s); + DTC_CASE(1, 1) DTC_CASE(1, 2) DTC_CASE(1, 4) DTC_CASE(1, 5) DTC_CASE(1, 10) + DTC_CASE(2, 1) DTC_CASE(2, 2) DTC_CASE(2, 4) DTC_CASE(2, 5) + DTC_CASE(4, 1) DTC_CASE(4, 2) +#undef DTC_CASE + return false; +} + +bool tile_known(Pick p) { + static const int ok[][2] = {{1, 1}, {1, 2}, {1, 4}, {1, 5}, {1, 10}, {2, 1}, {2, 2}, {2, 4}, {2, 5}, {4, 1}, {4, 2}}; + for (const auto& o : ok) if (o[0] == p.rt && o[1] == p.ks) return true; + return false; +} + +} // namespace + +const char* dense_tc_reason(int st) noexcept { + switch (st) { + case kDenseTcOk: return "ok"; + case kDenseTcOff: return "off"; + case kDenseTcArch: return "arch"; + case kDenseTcType: return "type"; + case kDenseTcCols: return "cols"; + case kDenseTcShape: return "shape"; + case kDenseTcAlign: return "align"; + case kDenseTcSmem: return "smem"; + case kDenseTcBuild: return "build"; + default: return "unknown"; + } +} + +void dense_tc_enable(int on) { g_enable = on; } +bool dense_tc_enabled() { return g_enable >= 0 ? g_enable != 0 : env_on(); } +void dense_tc_tile(int rt, int ks) { g_tile_rt = rt; g_tile_ks = ks; } +int dense_tc_variant(int v) { if (v >= 0) g_variant = v; return g_variant; } +int dense_tc_split_for(int type, int n_in, int n_out) { return pick(type, n_in, n_out).ks; } + +int dense_tc_check(int ggml_type, int n_in, int n_out, int ncols, const void* weights, const void* x_q8_1, const void* y) noexcept { + if (!dense_tc_enabled()) return kDenseTcOff; + if (device_cc() != 120) return kDenseTcArch; + if (ggml_type != 14) return kDenseTcType; + if (ncols < 1 || ncols > kMaxCols) return kDenseTcCols; + if (n_in <= 0 || n_in % 256 != 0 || n_out <= 0) return kDenseTcShape; + const Pick p = pick(ggml_type, n_in, n_out); + if (!tile_known(p)) return kDenseTcShape; + if (Smem::total(n_in, p.rt, p.ks) > size_t(99) * 1024) return kDenseTcShape; + if ((weights != nullptr && (reinterpret_cast(weights) & 1)) || + (x_q8_1 != nullptr && (reinterpret_cast(x_q8_1) & 3)) || (y != nullptr && (reinterpret_cast(y) & 3))) + return kDenseTcAlign; + return kDenseTcOk; +} + +bool dense_tc(int ggml_type, const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream) { + if (dense_tc_check(ggml_type, n_in, n_out, ncols, weights, x_q8_1, y) != kDenseTcOk) return false; + const Pick p = pick(ggml_type, n_in, n_out); + const bool ok = dispatch_q6k(static_cast(weights), static_cast(x_q8_1), y, n_in, n_out, ncols, + static_cast(stream), p); + return ok; +} + +void dense_tc_print_resources() { + cudaFuncAttributes a; + auto one = [&](const char* name, const void* f) { + if (cudaFuncGetAttributes(&a, f) == cudaSuccess) + std::printf("dense_tc %-24s regs %3d spill/local %4zu B static smem %zu B max threads %d binary sm_%d\n", name, a.numRegs, + a.localSizeBytes, a.sharedSizeBytes, a.maxThreadsPerBlock, a.binaryVersion); + else { + cudaGetLastError(); + std::printf("dense_tc %-24s (no attributes)\n", name); + } + }; + one("q6k rt1 ks1", reinterpret_cast(dense_tc_q6k_kernel<1, 1>)); + one("q6k rt1 ks2", reinterpret_cast(dense_tc_q6k_kernel<1, 2>)); + one("q6k rt1 ks4", reinterpret_cast(dense_tc_q6k_kernel<1, 4>)); + one("q6k rt1 ks5", reinterpret_cast(dense_tc_q6k_kernel<1, 5>)); + one("q6k rt2 ks2", reinterpret_cast(dense_tc_q6k_kernel<2, 2>)); + one("q6k rt2 ks4", reinterpret_cast(dense_tc_q6k_kernel<2, 4>)); + one("q6k rt4 ks1", reinterpret_cast(dense_tc_q6k_kernel<4, 1>)); +} + +} // namespace strata::kernels + +#else // HIP: no tensor-core path, every call keeps native_mmvq + +namespace strata::kernels { +const char* dense_tc_reason(int) noexcept { return "build"; } +void dense_tc_enable(int) {} +bool dense_tc_enabled() { return false; } +void dense_tc_tile(int, int) {} +int dense_tc_variant(int) { return 0; } +int dense_tc_split_for(int, int, int) { return 1; } +int dense_tc_check(int, int, int, int, const void*, const void*, const void*) noexcept { return kDenseTcBuild; } +bool dense_tc(int, const void*, const void*, float*, int, int, int, void*) { return false; } +void dense_tc_print_resources() {} +} // namespace strata::kernels + +#endif diff --git a/src/kernels/dense_tc_parity.cpp b/src/kernels/dense_tc_parity.cpp new file mode 100644 index 0000000000..194d755a36 --- /dev/null +++ b/src/kernels/dense_tc_parity.cpp @@ -0,0 +1,481 @@ +// src/kernels/dense_tc_parity.cpp - dense_tc (INT8 tensor-core projections, BW-DENSE P2.1) against +// (1) a host scalar reference written from the GGUF format and the arithmetic contract of dense_tc.hpp (bitwise), +// (2) a double-precision reference on the same q8_1 bytes (how far old and new each are from the true dot), +// (3) native_mmvq (the pre-existing dp4a path), reported as a difference, never as a parity claim, +// plus: T consistency (a column's bits do not depend on the column count), zero / extreme inputs, ineligible shapes +// and pointers, repeated CUDA-graph replay, two concurrent sessions, and with --bench the speed against the path the +// engine takes today (native_mmvq_il where its table says so, else native_mmvq). +// +// build/dense_tc_parity [--bench] [--only substr] [--tile rt,ks] [--rounds N] [--heavy] +#include "strata/kernels/dense_tc.hpp" +#include "strata/kernels/iq_kernels.hpp" +#include "strata/kernels/native_mmvq.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace strata::kernels; + +namespace { + +float h2f(uint16_t h) { // IEEE half -> float, subnormals included + const uint32_t s = (h >> 15) & 1, e = (h >> 10) & 31, m = h & 1023; + float v; + if (e == 0) v = std::ldexp(float(m), -24); + else if (e == 31) v = m ? NAN : INFINITY; + else v = std::ldexp(float(m + 1024), int(e) - 25); + return s ? -v : v; +} +bool ck(cudaError_t e, const char* what) { + if (e == cudaSuccess) return true; + std::printf("CUDA: %s: %s\n", what, cudaGetErrorString(e)); + return false; +} + +constexpr int kQ6 = 210; +struct Q6Row { // one decoded row of blocks (natural value order, as dequantize_row_q6_K) + std::vector q; // nb * 256 + std::vector sc; // nb * 16 + std::vector d; // nb +}; +void decode_q6_row(const uint8_t* row, int nb, Q6Row& o) { + o.q.assign(size_t(nb) * 256, 0); + o.sc.assign(size_t(nb) * 16, 0); + o.d.assign(nb, 0.f); + for (int b = 0; b < nb; ++b) { + const uint8_t* blk = row + size_t(b) * kQ6; + const uint8_t *ql = blk, *qh = blk + 128; + const int8_t* sc = reinterpret_cast(blk + 192); + uint16_t dh; + std::memcpy(&dh, blk + 208, 2); + o.d[b] = h2f(dh); + for (int i = 0; i < 16; ++i) o.sc[size_t(b) * 16 + i] = sc[i]; + int8_t* y = &o.q[size_t(b) * 256]; + for (int n = 0; n < 256; n += 128) { + for (int l = 0; l < 32; ++l) { + y[l + 0] = int8_t(((ql[l] & 0xF) | (((qh[l] >> 0) & 3) << 4)) - 32); + y[l + 32] = int8_t(((ql[l + 32] & 0xF) | (((qh[l] >> 2) & 3) << 4)) - 32); + y[l + 64] = int8_t(((ql[l] >> 4) | (((qh[l] >> 4) & 3) << 4)) - 32); + y[l + 96] = int8_t(((ql[l + 32] >> 4) | (((qh[l] >> 6) & 3) << 4)) - 32); + } + y += 128; + ql += 64; + qh += 32; + } + } +} + +// the contract's order for one (row, column); `ks` warps own blocks b = k, k + ks, ... +float contract_dot(const Q6Row& r, const uint8_t* xq_col, int nb, int ks) { + float part[16] = {}; + for (int k = 0; k < ks; ++k) { + float acc = 0.f; + for (int b = k; b < nb; b += ks) { + float inner = 0.f; + for (int a = 0; a < 8; ++a) { + const uint8_t* xb = xq_col + size_t(8 * b + a) * 36; + uint16_t dh; + std::memcpy(&dh, xb, 2); + const float d8 = h2f(dh); + const int8_t* u = reinterpret_cast(xb + 4); + int S = 0; + for (int half = 0; half < 2; ++half) { + int D = 0; + for (int j = 0; j < 16; ++j) D += int(r.q[size_t(b) * 256 + a * 32 + half * 16 + j]) * int(u[half * 16 + j]); + S += int(r.sc[size_t(b) * 16 + 2 * a + half]) * D; + } + inner = std::fmaf(d8, float(S), inner); + } + acc = std::fmaf(r.d[b], inner, acc); + } + part[k] = acc; + } + float v = part[0]; + for (int k = 1; k < ks; ++k) v += part[k]; + return v; +} +double exact_dot(const Q6Row& r, const uint8_t* xq_col, int nb) { + double tot = 0; + for (int b = 0; b < nb; ++b) { + double inner = 0; + for (int a = 0; a < 8; ++a) { + const uint8_t* xb = xq_col + size_t(8 * b + a) * 36; + uint16_t dh; + std::memcpy(&dh, xb, 2); + const double d8 = h2f(dh); + const int8_t* u = reinterpret_cast(xb + 4); + long long S = 0; + for (int half = 0; half < 2; ++half) { + long long D = 0; + for (int j = 0; j < 16; ++j) D += (long long) r.q[size_t(b) * 256 + a * 32 + half * 16 + j] * u[half * 16 + j]; + S += (long long) r.sc[size_t(b) * 16 + 2 * a + half] * D; + } + inner += d8 * double(S); + } + tot += double(r.d[b]) * inner; + } + return tot; +} + +struct Case { const char* name; int n_in, n_out; }; +const Case CASES[] = { + {"Q6_K 2560x10240", 2560, 10240}, {"Q6_K 2560x12288", 2560, 12288}, {"Q6_K 6144x2560", 6144, 2560}, + {"Q6_K 2560x6144", 2560, 6144}, {"Q6_K 2560x640", 2560, 640}, {"Q6_K 2560x512", 2560, 512}, + {"Q6_K odd rows 2560x2051", 2560, 2051}, {"Q6_K tail 256x37", 256, 37}, {"Q6_K 512x16", 512, 16}, + {"Q6_K head 2560x248320", 2560, 248320}, +}; + +enum WMode { W_RANDOM, W_MAXCODE, W_MINCODE, W_EXTREME, W_SUBNORMAL_D }; +enum XMode { X_NORMAL, X_ZERO, X_LARGE, X_SPIKE }; +const char* WN[] = {"random", "max-codes", "min-codes", "extremes", "subnormal-d"}; +const char* XN[] = {"normal", "zero", "large", "spike"}; + +void fill_weights(std::vector& w, size_t n_blocks, WMode m, std::mt19937& rng) { + for (size_t k = 0; k < n_blocks; ++k) { + uint8_t* b = &w[k * kQ6]; + for (int i = 0; i < 208; ++i) { + switch (m) { + case W_MAXCODE: b[i] = (i < 192) ? 0xFF : 0x7F; break; + case W_MINCODE: b[i] = (i < 192) ? 0x00 : 0x80; break; + case W_EXTREME: b[i] = (i < 192) ? ((rng() & 1) ? 0xFF : 0x00) : ((rng() & 1) ? 0x7F : 0x80); break; + default: b[i] = uint8_t(rng() & 0xff); break; + } + } + uint16_t d; + if (m == W_SUBNORMAL_D) d = uint16_t(1 + rng() % 1023); // positive subnormal halves + else { + const uint32_t r = rng(); + d = uint16_t(((r >> 31) << 15) | ((5u + (r >> 10) % 5u) << 10) | (r & 0x3ffu)); + } + std::memcpy(b + 208, &d, 2); + } +} +void fill_x(std::vector& x, int T, int n_in, XMode m, std::mt19937& rng) { + std::normal_distribution nd(0.f, 1.f); + for (int c = 0; c < T; ++c) + for (int i = 0; i < n_in; ++i) { + float v = nd(rng); + if (m == X_ZERO) v = 0.f; + else if (m == X_LARGE) v = (rng() & 1) ? 1000.f : -1000.f; + else if (m == X_SPIKE) v = (i % 64 == 3) ? 50.f * v : 0.01f * v; + x[size_t(c) * n_in + i] = v; + } +} + +struct Stats { double max_rel_new_vs_exact = 0, max_rel_old_vs_exact = 0, max_rel_new_vs_old = 0; }; + +int bad_total = 0; +#define EXPECT(cond, ...) do { if (!(cond)) { ++bad_total; std::printf("FAIL: "); std::printf(__VA_ARGS__); std::printf("\n"); } } while (0) + +// returns the number of failures +int run_case(const Case& c, WMode wm, XMode xm, bool heavy, cudaStream_t s) { + const int nb = c.n_in / 256; + const size_t wbytes = native_mmvq_weight_bytes(14, c.n_in, c.n_out); + std::mt19937 rng(1234u + unsigned(c.n_out) * 7u + unsigned(wm) * 101u + unsigned(xm) * 13u); + std::vector w(wbytes); + fill_weights(w, size_t(c.n_out) * nb, wm, rng); + uint8_t* dw = nullptr; + if (!ck(cudaMalloc(&dw, wbytes + 64), "malloc w") || !ck(cudaMemcpy(dw, w.data(), wbytes, cudaMemcpyHostToDevice), "copy w")) return 1; + + // rows to check on the host: all of them, or a sample for the big shapes + std::vector rows; + const int max_rows = heavy ? 100000000 : 600; + if (c.n_out <= max_rows) for (int r = 0; r < c.n_out; ++r) rows.push_back(r); + else { + for (int r = 0; r < 24; ++r) { rows.push_back(r); rows.push_back(c.n_out - 1 - r); } + for (int i = 0; i < 400; ++i) rows.push_back(int(rng() % unsigned(c.n_out))); + } + std::vector dec(rows.size()); + for (size_t i = 0; i < rows.size(); ++i) decode_q6_row(w.data() + size_t(rows[i]) * nb * kQ6, nb, dec[i]); + + const int ks = dense_tc_split_for(14, c.n_in, c.n_out); + int fails = 0; + std::vector> ycols_by_T; // for the T-consistency check: column 0..T-1 of the T=8 call + std::vector y8; + for (int T = 1; T <= 8; ++T) { + std::vector x(size_t(T) * c.n_in); + // the same first column for every T (embedding the token in a window): columns are generated per column index + { + std::mt19937 rx(777u + unsigned(xm)); + std::vector all(size_t(8) * c.n_in); + fill_x(all, 8, c.n_in, xm, rx); + std::copy(all.begin(), all.begin() + size_t(T) * c.n_in, x.begin()); + } + float* dx = nullptr; + void* xq = nullptr; + float *ynew = nullptr, *yold = nullptr; + const size_t ybytes = size_t(T) * c.n_out * 4; + if (!ck(cudaMalloc(&dx, x.size() * 4), "x") || !ck(cudaMalloc(&xq, native_q8_1_bytes(c.n_in, T) + 64), "xq") || + !ck(cudaMalloc(&ynew, ybytes), "ynew") || !ck(cudaMalloc(&yold, ybytes), "yold")) + return 1; + cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice); + quantize_q8_1_rows(dx, T, c.n_in, xq, s); + cudaMemsetAsync(ynew, 0xff, ybytes, s); // on the kernel's own stream: a legacy-stream memset does not order against a non-blocking stream + const bool launched = dense_tc(14, dw, xq, ynew, c.n_in, c.n_out, T, s); + EXPECT(launched, "%s T=%d: dense_tc did not launch (%s)", c.name, T, dense_tc_reason(dense_tc_check(14, c.n_in, c.n_out, T, dw, xq, ynew))); + native_mmvq(14, dw, xq, yold, c.n_in, c.n_out, T, s); + ck(cudaStreamSynchronize(s), "sync"); + ck(cudaGetLastError(), "launch"); + std::vector hn(size_t(T) * c.n_out), ho(hn.size()); + cudaMemcpy(hn.data(), ynew, ybytes, cudaMemcpyDeviceToHost); + cudaMemcpy(ho.data(), yold, ybytes, cudaMemcpyDeviceToHost); + std::vector hq(native_q8_1_bytes(c.n_in, T)); + cudaMemcpy(hq.data(), xq, hq.size(), cudaMemcpyDeviceToHost); + + long long bitdiff = 0, nonfinite = 0; + double maxrel_new = 0, maxrel_old = 0, maxrel_nv = 0, scale = 0; + // an output-scale for relative errors: the largest exact magnitude of the checked rows of this column + for (int col = 0; col < T; ++col) { + const uint8_t* xc = hq.data() + size_t(col) * (c.n_in / 32) * 36; + double colmax = 0; + std::vector ex(rows.size()); + for (size_t i = 0; i < rows.size(); ++i) { ex[i] = exact_dot(dec[i], xc, nb); colmax = std::max(colmax, std::fabs(ex[i])); } + scale = std::max(colmax, 1e-30); + for (size_t i = 0; i < rows.size(); ++i) { + const int r = rows[i]; + const float got = hn[size_t(col) * c.n_out + r]; + const float want = contract_dot(dec[i], xc, nb, ks); + uint32_t a, b; + std::memcpy(&a, &got, 4); + std::memcpy(&b, &want, 4); + if (a != b) ++bitdiff; + if (!std::isfinite(got)) ++nonfinite; + maxrel_new = std::max(maxrel_new, std::fabs(double(got) - ex[i]) / scale); + maxrel_old = std::max(maxrel_old, std::fabs(double(ho[size_t(col) * c.n_out + r]) - ex[i]) / scale); + maxrel_nv = std::max(maxrel_nv, std::fabs(double(got) - double(ho[size_t(col) * c.n_out + r])) / scale); + } + } + if (nonfinite) { // which columns / rows hold the non-finite values + for (int col = 0; col < T; ++col) { + long long nf = 0, first = -1; + for (int r = 0; r < c.n_out; ++r) if (!std::isfinite(hn[size_t(col) * c.n_out + r])) { if (first < 0) first = r; ++nf; } + if (nf) std::printf(" column %d: %lld of %d rows non-finite (first row %lld)\n", col, nf, c.n_out, first); + } + } + if (bitdiff || nonfinite) { + ++fails; + EXPECT(false, "%s [%s w, %s x] T=%d: %lld outputs differ from the contract reference, %lld non-finite", c.name, WN[wm], XN[xm], T, bitdiff, nonfinite); + } + // the error against the exact dot must be of the old path's size (both are fp32 sums of exact integer parts) + EXPECT(maxrel_new <= std::max(4.0 * maxrel_old, 2e-6), "%s [%s w, %s x] T=%d: new error %.3g vs old %.3g (of the column max)", c.name, WN[wm], XN[xm], T, maxrel_new, maxrel_old); + if (wm == W_RANDOM && xm == X_NORMAL && (T == 1 || T == 4 || T == 8)) + std::printf(" %-26s T=%d err vs exact (of column max): new %.2e old %.2e new vs old %.2e [k_split %d, %zu rows checked]\n", c.name, T, + maxrel_new, maxrel_old, maxrel_nv, ks, rows.size()); + // column-count independence: the T=8 call is the reference for every smaller T + if (T == 8) y8 = hn; + ycols_by_T.push_back(hn); + cudaFree(dx); cudaFree(xq); cudaFree(ynew); cudaFree(yold); + } + // each column's bits at every T equal its bits in the T=8 call (T=8 columns are the same data) + for (int T = 1; T <= 7; ++T) { + long long diff = 0; + for (int col = 0; col < T; ++col) + for (int r = 0; r < c.n_out; ++r) + if (std::memcmp(&ycols_by_T[T - 1][size_t(col) * c.n_out + r], &y8[size_t(col) * c.n_out + r], 4) != 0) { + if (diff < 4) std::printf(" T=%d col %d row %d: %.9g vs %.9g in the T=8 call\n", T, col, r, ycols_by_T[T - 1][size_t(col) * c.n_out + r], y8[size_t(col) * c.n_out + r]); + ++diff; + } + EXPECT(diff == 0, "%s [%s w, %s x]: T=%d differs from the same columns in T=8 in %lld outputs", c.name, WN[wm], XN[xm], T, diff); + if (diff) ++fails; + } + cudaFree(dw); + return fails; +} + +void check_ineligible() { + // pointers and shapes the kernel must refuse, with the stable reason + void *w = nullptr, *x = nullptr, *y = nullptr; + cudaMalloc(&w, 1 << 20); + cudaMalloc(&x, 1 << 20); + cudaMalloc(&y, 1 << 20); + auto chk = [&](const char* what, int got, int want) { EXPECT(got == want, "%s: reason %s, wanted %s", what, dense_tc_reason(got), dense_tc_reason(want)); }; + chk("ok", dense_tc_check(14, 2560, 640, 4, w, x, y), kDenseTcOk); + chk("ncols 0", dense_tc_check(14, 2560, 640, 0, w, x, y), kDenseTcCols); + chk("ncols 9", dense_tc_check(14, 2560, 640, 9, w, x, y), kDenseTcCols); + chk("n_in tail", dense_tc_check(14, 2560 + 32, 640, 4, w, x, y), kDenseTcShape); + chk("n_out 0", dense_tc_check(14, 2560, 0, 4, w, x, y), kDenseTcShape); + chk("type Q8_0", dense_tc_check(8, 2560, 640, 4, w, x, y), kDenseTcType); + chk("weights odd pointer", dense_tc_check(14, 2560, 640, 4, static_cast(w) + 1, x, y), kDenseTcAlign); + chk("activation pointer +2", dense_tc_check(14, 2560, 640, 4, w, static_cast(x) + 2, y), kDenseTcAlign); + chk("output pointer +2", dense_tc_check(14, 2560, 640, 4, w, x, static_cast(y) + 2), kDenseTcAlign); + chk("weights 2-byte aligned is fine", dense_tc_check(14, 2560, 640, 4, static_cast(w) + 2, x, y), kDenseTcOk); + EXPECT(!dense_tc(14, w, x, static_cast(y), 2560 + 32, 640, 4, nullptr), "a refused call must not launch"); + dense_tc_enable(0); + chk("switch off", dense_tc_check(14, 2560, 640, 4, w, x, y), kDenseTcOff); + dense_tc_enable(1); + cudaFree(w); cudaFree(x); cudaFree(y); +} + +// repeated graph replay and two concurrent sessions on distinct inputs +void check_graph_and_sessions() { + const int n_in = 2560, n_out = 6144, T = 5; + const size_t wbytes = native_mmvq_weight_bytes(14, n_in, n_out); + std::mt19937 rng(99); + std::vector w(wbytes); + fill_weights(w, size_t(n_out) * (n_in / 256), W_RANDOM, rng); + uint8_t* dw; + cudaMalloc(&dw, wbytes); + cudaMemcpy(dw, w.data(), wbytes, cudaMemcpyHostToDevice); + cudaStream_t s[2]; + cudaStreamCreateWithFlags(&s[0], cudaStreamNonBlocking); + cudaStreamCreateWithFlags(&s[1], cudaStreamNonBlocking); + float* dx[2]; + void* xq[2]; + float *ysolo[2], *yg[2]; + std::vector hsolo[2]; + for (int k = 0; k < 2; ++k) { + std::vector x(size_t(T) * n_in); + fill_x(x, T, n_in, X_NORMAL, rng); + cudaMalloc(&dx[k], x.size() * 4); + cudaMalloc(&xq[k], native_q8_1_bytes(n_in, T)); + cudaMalloc(&ysolo[k], size_t(T) * n_out * 4); + cudaMalloc(&yg[k], size_t(T) * n_out * 4); + cudaMemcpy(dx[k], x.data(), x.size() * 4, cudaMemcpyHostToDevice); + quantize_q8_1_rows(dx[k], T, n_in, xq[k], s[k]); + dense_tc(14, dw, xq[k], ysolo[k], n_in, n_out, T, s[k]); + cudaStreamSynchronize(s[k]); + hsolo[k].resize(size_t(T) * n_out); + cudaMemcpy(hsolo[k].data(), ysolo[k], hsolo[k].size() * 4, cudaMemcpyDeviceToHost); + } + cudaGraph_t g[2]; + cudaGraphExec_t ge[2]; + for (int k = 0; k < 2; ++k) { + cudaStreamBeginCapture(s[k], cudaStreamCaptureModeThreadLocal); + EXPECT(dense_tc(14, dw, xq[k], yg[k], n_in, n_out, T, s[k]), "launch under capture"); + cudaStreamEndCapture(s[k], &g[k]); + EXPECT(ck(cudaGraphInstantiate(&ge[k], g[k], 0), "instantiate"), "graph instantiate"); + } + long long diff = 0; + for (int rep = 0; rep < 200; ++rep) { // both sessions replay concurrently, distinct inputs + for (int k = 0; k < 2; ++k) cudaGraphLaunch(ge[k], s[k]); + if (rep % 20 == 19) { + for (int k = 0; k < 2; ++k) { + cudaStreamSynchronize(s[k]); + std::vector h(hsolo[k].size()); + cudaMemcpy(h.data(), yg[k], h.size() * 4, cudaMemcpyDeviceToHost); + diff += std::memcmp(h.data(), hsolo[k].data(), h.size() * 4) != 0; + cudaMemsetAsync(yg[k], 0xff, h.size() * 4, s[k]); + } + } + } + cudaDeviceSynchronize(); + EXPECT(diff == 0, "graph replay / two sessions: %lld replays differed from the solo launch", diff); + EXPECT(ck(cudaGetLastError(), "graph run"), "graph run error"); + std::printf(" graph replay x200, two concurrent sessions: %s\n", diff == 0 ? "identical to the solo launch" : "DIFFERENT"); +} + +// ---- bench --------------------------------------------------------------------------------------------------------- +template +double time_us(F fn, int reps, cudaStream_t s) { + cudaEvent_t e0, e1; + cudaEventCreate(&e0); + cudaEventCreate(&e1); + float ms = 0; + for (int rep = 0; rep < 2; ++rep) { + cudaEventRecord(e0, s); + for (int i = 0; i < reps; ++i) fn(i); + cudaEventRecord(e1, s); + cudaEventSynchronize(e1); + cudaEventElapsedTime(&ms, e0, e1); + } + cudaEventDestroy(e0); + cudaEventDestroy(e1); + return 1000.0 * ms / reps; +} + +void bench_case(const Case& c, int rounds, cudaStream_t s) { + const size_t wbytes = native_mmvq_weight_bytes(14, c.n_in, c.n_out); + const int copies = int(std::max(1, std::min(24, (size_t(256) << 20) / wbytes))); + std::mt19937 rng(5); + std::vector w(wbytes); + fill_weights(w, size_t(c.n_out) * (c.n_in / 256), W_RANDOM, rng); + std::vector dw(copies); + for (auto& p : dw) { cudaMalloc(&p, wbytes); cudaMemcpy(p, w.data(), wbytes, cudaMemcpyHostToDevice); } + for (int T = 1; T <= 8; ++T) { + std::vector x(size_t(T) * c.n_in); + fill_x(x, T, c.n_in, X_NORMAL, rng); + float* dx; + void *xq, *xil; + float *yn, *yo; + cudaMalloc(&dx, x.size() * 4); + cudaMalloc(&xq, native_q8_1_bytes(c.n_in, T)); + cudaMalloc(&xil, native_q8_1_il_bytes(c.n_in, T)); + cudaMalloc(&yn, size_t(T) * c.n_out * 4); + cudaMalloc(&yo, size_t(T) * c.n_out * 4); + cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice); + quantize_q8_1_rows(dx, T, c.n_in, xq, s); + if (T >= 2) native_q8_1_interleave(xq, xil, c.n_in, T, s); + const bool il = native_mmvq_il_supported(14, T, c.n_out); + auto old_call = [&](int i) { + if (il) native_mmvq_il(14, dw[i % copies], xq, xil, yo, c.n_in, c.n_out, T, s); + else native_mmvq(14, dw[i % copies], xq, yo, c.n_in, c.n_out, T, s); + }; + auto new_call = [&](int i) { dense_tc(14, dw[i % copies], xq, yn, c.n_in, c.n_out, T, s); }; + std::vector to, tn; + for (int r = 0; r < rounds; ++r) { // interleaved rounds + to.push_back(time_us(old_call, 100, s)); + tn.push_back(time_us(new_call, 100, s)); + } + std::sort(to.begin(), to.end()); + std::sort(tn.begin(), tn.end()); + const double mo = to[to.size() / 2], mn = tn[tn.size() / 2]; + std::printf("BENCH %-26s T=%d old(%s) %7.1f us %5.0f GB/s | dense_tc %7.1f us %5.0f GB/s | ratio %.3f\n", c.name, T, il ? "il " : "mmvq", mo, + wbytes / mo / 1e3, mn, wbytes / mn / 1e3, mn / mo); + cudaFree(dx); cudaFree(xq); cudaFree(xil); cudaFree(yn); cudaFree(yo); + } + for (auto p : dw) cudaFree(p); +} + +} // namespace + +int main(int argc, char** argv) { + bool bench = false, heavy = false; + int rounds = 5; + std::string only; + for (int i = 1; i < argc; ++i) { + if (!std::strcmp(argv[i], "--bench")) bench = true; + else if (!std::strcmp(argv[i], "--heavy")) heavy = true; + else if (!std::strcmp(argv[i], "--only") && i + 1 < argc) only = argv[++i]; + else if (!std::strcmp(argv[i], "--rounds") && i + 1 < argc) rounds = std::atoi(argv[++i]); + else if (!std::strcmp(argv[i], "--tile") && i + 1 < argc) { int a = 0, b = 0; std::sscanf(argv[++i], "%d,%d", &a, &b); dense_tc_tile(a, b); } + } + dense_tc_enable(1); + cudaStream_t s; + cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking); + if (dense_tc_check(14, 2560, 640, 4, nullptr, nullptr, nullptr) != kDenseTcOk) { + std::printf("dense_tc_parity: SKIP (%s: not a 12.0 card or not built)\n", dense_tc_reason(dense_tc_check(14, 2560, 640, 4, nullptr, nullptr, nullptr))); + return 0; + } + dense_tc_print_resources(); + if (bench) { + for (const Case& c : CASES) if (only.empty() || std::strstr(c.name, only.c_str())) bench_case(c, rounds, s); + return 0; + } + check_ineligible(); + for (const Case& c : CASES) { + if (!only.empty() && !std::strstr(c.name, only.c_str())) continue; + std::printf("%s\n", c.name); + const bool big = c.n_out > 100000; + for (int wm = 0; wm <= W_SUBNORMAL_D; ++wm) + for (int xm = 0; xm <= X_SPIKE; ++xm) { + if (big && (wm != W_RANDOM || xm != X_NORMAL) && !(wm == W_EXTREME && xm == X_LARGE)) continue; // the head: two modes (it is 521 MB) + run_case(c, WMode(wm), XMode(xm), heavy, s); + } + } + check_graph_and_sessions(); + if (bad_total) { + std::printf("dense_tc_parity: %d FAILURES\n", bad_total); + return 1; + } + std::printf("dense_tc_parity: OK\n"); + return 0; +}